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
974575f899f0e779d27696a0
train
class
@final class RequiredBaseClassViolation(ASTViolation): """ Forbids to write classes without base classes. Reasoning: We just need to decide how to do it. We need a single and unified rule about base classes. We have decided to stick to the explicit base class notation. Solution...
@final class RequiredBaseClassViolation(ASTViolation):
""" Forbids to write classes without base classes. Reasoning: We just need to decide how to do it. We need a single and unified rule about base classes. We have decided to stick to the explicit base class notation. Solution: Add a base class. Example:: # C...
+ 2) 'Hey {user}! How are you?'.format(user='sobolevn') .. versionadded:: 0.1.0 """ error_template = 'Found `f` string' code = 305 @final class RequiredBaseClassViolation(ASTViolation):
64
64
151
11
52
ulturt/wemake-python-styleguide
wemake_python_styleguide/violations/consistency.py
Python
RequiredBaseClassViolation
RequiredBaseClassViolation
339
368
339
340
f8a780f490241f6ad4d4d376e4fb08ff92eac17b
bigcode/the-stack
train
f57a9b766a6023bcc6adee87
train
class
@final class UselessCompareViolation(ASTViolation): """ Forbids to have compares between the same variable. Reasoning: When the same variables are compared it is typically an indication of a mistake, since the Boolean value of the compare will always be the same. Solution: ...
@final class UselessCompareViolation(ASTViolation):
""" Forbids to have compares between the same variable. Reasoning: When the same variables are compared it is typically an indication of a mistake, since the Boolean value of the compare will always be the same. Solution: Remove the same variable compare and any associa...
ord not in line not in square: .. versionadded:: 0.3.0 .. versionchanged:: 0.10.0 """ error_template = 'Found multiple `in` compares' code = 311 @final class UselessCompareViolation(ASTViolation):
64
64
151
12
51
ulturt/wemake-python-styleguide
wemake_python_styleguide/violations/consistency.py
Python
UselessCompareViolation
UselessCompareViolation
532
562
532
533
d9fe4ebf27fb00ac9da385ec53587a9a6a906ab1
bigcode/the-stack
train
b8bbb3266822676577fc9771
train
class
@final class ImplicitRawStringViolation(TokenizeViolation): r""" Forbids to use ``\\`` escape sequences inside regular strings. Reasoning: It is hard to read escape sequencse inside regular strings, because they use ``\\`` double backslash for a single character escape. Solution: ...
@final class ImplicitRawStringViolation(TokenizeViolation):
r""" Forbids to use ``\\`` escape sequences inside regular strings. Reasoning: It is hard to read escape sequencse inside regular strings, because they use ``\\`` double backslash for a single character escape. Solution: Use raw strings ``r''`` to rewrite the escape seq...
0xABCDEF # Wrong: number = 0xabcdef .. versionadded:: 0.12.0 """ error_template = 'Found wrong hex number case: {0}' code = 341 @final class ImplicitRawStringViolation(TokenizeViolation):
64
64
153
13
50
ulturt/wemake-python-styleguide
wemake_python_styleguide/violations/consistency.py
Python
ImplicitRawStringViolation
ImplicitRawStringViolation
1,617
1,643
1,617
1,618
bb3b9f8a9a33624cba2e4eb0dee452ca3ba876b6
bigcode/the-stack
train
7da6ce8e00521a46d9584a8c
train
class
@final class LocalFolderImportViolation(ASTViolation): """ Forbids to have imports relative to the current folder. Reasoning: We should pick one style and stick to it. We have decided to use the explicit one. Solution: Refactor your imports to use the absolute path. Exampl...
@final class LocalFolderImportViolation(ASTViolation):
""" Forbids to have imports relative to the current folder. Reasoning: We should pick one style and stick to it. We have decided to use the explicit one. Solution: Refactor your imports to use the absolute path. Example:: # Correct: from my_package.version...
mentedAssignPatternViolation .. autoclass:: UnnecessaryLiteralsViolation .. autoclass:: MultilineLoopViolation """ from typing_extensions import final from wemake_python_styleguide.violations.base import ( ASTViolation, TokenizeViolation, ) @final class LocalFolderImportViolation(ASTViolation):
64
64
132
11
53
ulturt/wemake-python-styleguide
wemake_python_styleguide/violations/consistency.py
Python
LocalFolderImportViolation
LocalFolderImportViolation
149
175
149
150
6eb58118caeedb948774e1fb4c11e96353f90159
bigcode/the-stack
train
2cdcb79cc9aa615275d21757
train
class
@final class NumberWithMeaninglessZeroViolation(TokenizeViolation): """ Forbids to use meaningless zeros. We discorauge using meaningless zeros in float, binary, octal, hex, and exponential numbers. Reasoning: There are ~infinite ways to write these numbers by adding meaningless le...
@final class NumberWithMeaninglessZeroViolation(TokenizeViolation):
""" Forbids to use meaningless zeros. We discorauge using meaningless zeros in float, binary, octal, hex, and exponential numbers. Reasoning: There are ~infinite ways to write these numbers by adding meaningless leading zeros to the number itself. ``0b1`` is the same as ``0...
can go deeper in case we are interested. Solution: Reorder methods inside your class to match our format. .. versionadded:: 0.12.0 """ error_template = 'Found incorrect order of methods in a class' code = 338 @final class NumberWithMeaninglessZeroViolation(TokenizeViolation):
72
72
241
14
57
ulturt/wemake-python-styleguide
wemake_python_styleguide/violations/consistency.py
Python
NumberWithMeaninglessZeroViolation
NumberWithMeaninglessZeroViolation
1,525
1,557
1,525
1,526
fe91b69193ccbc100e157c3dbce28141b2672197
bigcode/the-stack
train
4525df3f9559fcd13f46d9d8
train
class
class SubscriptionType(Named, Notable): '''Type of subscription'''
class SubscriptionType(Named, Notable):
'''Type of subscription'''
# NOTE: takes precedence over generic type if it occurs if self.notes: match = re.search(self.re_nonstandard_notation, self.notes) if match: return self.nonstandard_notation[match.group(0)] return self.event_type class SubscriptionType(Named, Notable):
64
64
15
9
54
making-books-ren-today/test_eval_3_shxco
mep/accounts/models.py
Python
SubscriptionType
SubscriptionType
356
357
356
356
e70d828a4f012c7f93b132295cd3195fee2ca7be
bigcode/the-stack
train
13b19b1647c62b495e5dac11
train
class
class Subscription(Event, CurrencyMixin): '''Records subscription events in the MEP database''' duration = models.PositiveIntegerField( 'Days', blank=True, null=True, help_text='Subscription duration in days. ' + 'Automatically calculated from start and end date.') volumes ...
class Subscription(Event, CurrencyMixin):
'''Records subscription events in the MEP database''' duration = models.PositiveIntegerField( 'Days', blank=True, null=True, help_text='Subscription duration in days. ' + 'Automatically calculated from start and end date.') volumes = models.DecimalField( blank=True,...
if match: return self.nonstandard_notation[match.group(0)] return self.event_type class SubscriptionType(Named, Notable): '''Type of subscription''' class CurrencyMixin(models.Model): '''Mixin for currency field with currency symbol display''' USD = 'USD' FRF = '...
256
256
1,191
7
249
making-books-ren-today/test_eval_3_shxco
mep/accounts/models.py
Python
Subscription
Subscription
394
517
394
394
b2e1267af5d0dc4e015ea28ba9fe6151c4ed8621
bigcode/the-stack
train
de8ed26523f3497768d4da45
train
class
class Reimbursement(Event, CurrencyMixin): '''Reimbursement event; extends :class:`Event`''' refund = models.DecimalField(max_digits=8, decimal_places=2, null=True, blank=True) def date(self): '''alias of :attr:`start_date` for display, since reimbersument i...
class Reimbursement(Event, CurrencyMixin):
'''Reimbursement event; extends :class:`Event`''' refund = models.DecimalField(max_digits=8, decimal_places=2, null=True, blank=True) def date(self): '''alias of :attr:`start_date` for display, since reimbersument is a single-day event''' return self...
'''alias of :attr:`date_range` for display; since reimbersument is a single-day event will always be a single partial date.''' return self.date_range date.admin_order_field = 'start_date' def save(self, *args, **kwargs): # override save to always set start = end, end will be dis...
120
120
402
8
112
making-books-ren-today/test_eval_3_shxco
mep/accounts/models.py
Python
Reimbursement
Reimbursement
567
609
567
567
44d9e11a47194712aeb8a4abee07d38aea49d73a
bigcode/the-stack
train
51027e6161e5d9e296b66898
train
class
class CurrencyMixin(models.Model): '''Mixin for currency field with currency symbol display''' USD = 'USD' FRF = 'FRF' GBP = 'GBP' # NOTE: Preliminary currency set for now CURRENCY_CHOICES = ( ('', '----'), (USD, 'US Dollar'), (FRF, 'French Franc'), (GBP, 'Britis...
class CurrencyMixin(models.Model):
'''Mixin for currency field with currency symbol display''' USD = 'USD' FRF = 'FRF' GBP = 'GBP' # NOTE: Preliminary currency set for now CURRENCY_CHOICES = ( ('', '----'), (USD, 'US Dollar'), (FRF, 'French Franc'), (GBP, 'British Pound') ) symbols = { ...
if self.notes: match = re.search(self.re_nonstandard_notation, self.notes) if match: return self.nonstandard_notation[match.group(0)] return self.event_type class SubscriptionType(Named, Notable): '''Type of subscription''' class CurrencyMixin(models.Model):
63
64
210
6
57
making-books-ren-today/test_eval_3_shxco
mep/accounts/models.py
Python
CurrencyMixin
CurrencyMixin
360
391
360
360
f9d71d624ecab0028a1a578cc30fe7a28cd1d24c
bigcode/the-stack
train
854676db67007a1f1c372e9e
train
class
class Purchase(CurrencyMixin, Event): '''Inherited table indicating purchase events; extends :class:`Event`''' price = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) footnotes = GenericRelation(Footnote, related_query_name='purchases') def dat...
class Purchase(CurrencyMixin, Event):
'''Inherited table indicating purchase events; extends :class:`Event`''' price = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) footnotes = GenericRelation(Footnote, related_query_name='purchases') def date(self): '''alias of :attr:`da...
# if end date is set and item status is not, automatically set # status to returned if self.end_date and not self.item_status: self.item_status = self.ITEM_RETURNED super(Borrow, self).save(*args, **kwargs) class Purchase(CurrencyMixin, Event):
64
64
180
8
56
making-books-ren-today/test_eval_3_shxco
mep/accounts/models.py
Python
Purchase
Purchase
547
564
547
547
e97cb9767dc1181ee8b7600660d704b7838a109f
bigcode/the-stack
train
1121a0ecafd9b1dd2a3a8d8a
train
class
class EventQuerySet(models.QuerySet): '''Custom :class:`~django.db.models.Queryset` for :class:`Event` with filter methods for generic events and each event subtype.''' def generic(self): '''Generic events only (excludes subscriptions, reimbursements, borrows, and purchases).''' ret...
class EventQuerySet(models.QuerySet):
'''Custom :class:`~django.db.models.Queryset` for :class:`Event` with filter methods for generic events and each event subtype.''' def generic(self): '''Generic events only (excludes subscriptions, reimbursements, borrows, and purchases).''' return self.filter(subscription__isnull=T...
otherwise just location return str(self.location) def clean(self): '''Validate to require one and only one of :class:`Account` or :class:`~mep.people.models.Person`''' if not self.account and not self.person: raise ValidationError('Address must be associated with an acc...
102
102
342
8
94
making-books-ren-today/test_eval_3_shxco
mep/accounts/models.py
Python
EventQuerySet
EventQuerySet
236
280
236
236
fa5263a4a6b253dae9fb62c61a86ba2880ffd6da
bigcode/the-stack
train
778a9a303c6997d099fa98c1
train
class
class Borrow(Event): '''Inherited table indicating borrow events''' #: :class:`~mep.books.models.Work` that was borrowed; #: optional to account for unclear titles ITEM_RETURNED = 'R' ITEM_BOUGHT = 'B' ITEM_MISSING = 'M' STATUS_CHOICES = ( ('', 'Unknown'), (ITEM_RETURNED, 'Re...
class Borrow(Event):
'''Inherited table indicating borrow events''' #: :class:`~mep.books.models.Work` that was borrowed; #: optional to account for unclear titles ITEM_RETURNED = 'R' ITEM_BOUGHT = 'B' ITEM_MISSING = 'M' STATUS_CHOICES = ( ('', 'Unknown'), (ITEM_RETURNED, 'Returned'), (IT...
== 0: weeks = self.duration / 7 return '%d week%s' % (weeks, pluralize(weeks)) # otherwise, combine months & days return ', '.join(parts) readable_duration.short_description = 'Duration' readable_duration.admin_order_field = 'duration' class Borrow(Event):
68
68
227
4
64
making-books-ren-today/test_eval_3_shxco
mep/accounts/models.py
Python
Borrow
Borrow
520
544
520
520
f201d97ba19975513fdc699e1f180a3d77dd8ef5
bigcode/the-stack
train
208a35db5c0224d387f055b2
train
class
class Event(Notable, PartialDateMixin): '''Base table for events in the Shakespeare and Co. Lending Library''' account = models.ForeignKey(Account, on_delete=models.CASCADE) start_date = models.DateField(blank=True, null=True) end_date = models.DateField(blank=True, null=True) work = models.ForeignK...
class Event(Notable, PartialDateMixin):
'''Base table for events in the Shakespeare and Co. Lending Library''' account = models.ForeignKey(Account, on_delete=models.CASCADE) start_date = models.DateField(blank=True, null=True) end_date = models.DateField(blank=True, null=True) work = models.ForeignKey( Work, null=True, blank=True,...
type('reimbursement') def borrows(self): '''Events with associated borrow event only''' return self._subtype('borrow') def purchases(self): '''Events with associated purchase event only''' return self._subtype('purchase') def membership_activities(self): '''Subscri...
182
182
608
9
173
making-books-ren-today/test_eval_3_shxco
mep/accounts/models.py
Python
Event
Event
283
353
283
283
d87f81a9da4609b419b80cdf588cf75cc318217e
bigcode/the-stack
train
5fe9f2c0c80f581f25571df9
train
class
class Address(Notable, PartialDateMixin): '''Address associated with an :class:`Account` or a :class:`~mep.people.models.Person`. Used to associate locations with people and accounts, with optional start and end dates and a care/of person.''' location = models.ForeignKey(Location, on_delete=models....
class Address(Notable, PartialDateMixin):
'''Address associated with an :class:`Account` or a :class:`~mep.people.models.Person`. Used to associate locations with people and accounts, with optional start and end dates and a care/of person.''' location = models.ForeignKey(Location, on_delete=models.CASCADE) account = models.ForeignKey( ...
the manifest) event_cards = Canvas.objects.exclude(manifest=self.card.manifest) \ .filter( models.Q(footnote__events__account__pk=self.pk) | models.Q(footnote__borrows__account__pk=self.pk) | models.Q(footnote__purchases__account__pk=self.pk)) \ ...
143
143
477
9
134
making-books-ren-today/test_eval_3_shxco
mep/accounts/models.py
Python
Address
Address
186
233
186
186
076fb809b33977cbead6d2b2695203106ab94bd6
bigcode/the-stack
train
9100aa1b00529dbb7be5c015
train
class
class Account(models.Model, EventSetMixin): '''Central model for all account and related information, M2M explicity to :class:`people.Person`''' persons = models.ManyToManyField(Person, blank=True, verbose_name='Account holder(s)') # convenience access to associated locations, although # we...
class Account(models.Model, EventSetMixin):
'''Central model for all account and related information, M2M explicity to :class:`people.Person`''' persons = models.ManyToManyField(Person, blank=True, verbose_name='Account holder(s)') # convenience access to associated locations, although # we will probably use Address for most things ...
# -*- coding: utf-8 -*- import re from cached_property import cached_property from dateutil.relativedelta import relativedelta from django.contrib.contenttypes.fields import GenericRelation from django.core.exceptions import ObjectDoesNotExist from django.core.validators import ValidationError from django.db import mo...
165
256
1,366
9
155
making-books-ren-today/test_eval_3_shxco
mep/accounts/models.py
Python
Account
Account
22
183
22
22
a09c4b7455e7338c81bb043d9b55b79edb734292
bigcode/the-stack
train
64506aa33bfb1edc302a8d75
train
function
@needs_py39 def test_post_upload_file(tmp_path, app: FastAPI): path = tmp_path / "test.txt" path.write_bytes(b"<file content>") path2 = tmp_path / "test2.txt" path2.write_bytes(b"<file content2>") client = TestClient(app) with path.open("rb") as file, path2.open("rb") as file2: response...
@needs_py39 def test_post_upload_file(tmp_path, app: FastAPI):
path = tmp_path / "test.txt" path.write_bytes(b"<file content>") path2 = tmp_path / "test2.txt" path2.write_bytes(b"<file content2>") client = TestClient(app) with path.open("rb") as file, path2.open("rb") as file2: response = client.post( "/uploadfiles/", files=...
)), ("files", ("test2.txt", file2)), ), ) assert response.status_code == 200, response.text assert response.json() == {"file_sizes": [14, 15]} @needs_py39 def test_post_upload_file(tmp_path, app: FastAPI):
63
64
160
18
45
ssensalo/fastapi
tests/test_tutorial/test_request_files/test_tutorial002_py39.py
Python
test_post_upload_file
test_post_upload_file
210
227
210
211
db5a803e57cbc0fbd011ec5e2e63d3670ee11a8d
bigcode/the-stack
train
94d45d12e5caea3d071e4b33
train
function
@needs_py39 def test_post_files(tmp_path, app: FastAPI): path = tmp_path / "test.txt" path.write_bytes(b"<file content>") path2 = tmp_path / "test2.txt" path2.write_bytes(b"<file content2>") client = TestClient(app) with path.open("rb") as file, path2.open("rb") as file2: response = cli...
@needs_py39 def test_post_files(tmp_path, app: FastAPI):
path = tmp_path / "test.txt" path.write_bytes(b"<file content>") path2 = tmp_path / "test2.txt" path2.write_bytes(b"<file content2>") client = TestClient(app) with path.open("rb") as file, path2.open("rb") as file2: response = client.post( "/files/", files=( ...
def test_post_body_json(client: TestClient): response = client.post("/files/", json={"file": "Foo"}) assert response.status_code == 422, response.text assert response.json() == file_required @needs_py39 def test_post_files(tmp_path, app: FastAPI):
64
64
155
17
46
ssensalo/fastapi
tests/test_tutorial/test_request_files/test_tutorial002_py39.py
Python
test_post_files
test_post_files
190
207
190
191
e148bf0588f763514286d605961e5e7e94e9d1bf
bigcode/the-stack
train
16ddcf08d3a722e3e7440469
train
function
@needs_py39 def test_post_body_json(client: TestClient): response = client.post("/files/", json={"file": "Foo"}) assert response.status_code == 422, response.text assert response.json() == file_required
@needs_py39 def test_post_body_json(client: TestClient):
response = client.post("/files/", json={"file": "Foo"}) assert response.status_code == 422, response.text assert response.json() == file_required
} ] } @needs_py39 def test_post_form_no_body(client: TestClient): response = client.post("/files/") assert response.status_code == 422, response.text assert response.json() == file_required @needs_py39 def test_post_body_json(client: TestClient):
64
64
51
15
48
ssensalo/fastapi
tests/test_tutorial/test_request_files/test_tutorial002_py39.py
Python
test_post_body_json
test_post_body_json
183
187
183
184
0f1d5d6da5441c8295f21185f0009d00e6ce386b
bigcode/the-stack
train
35c08a8fed07d0c18856e865
train
function
@needs_py39 def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == openapi_schema
@needs_py39 def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == openapi_schema
app") def get_app(): from docs_src.request_files.tutorial002_py39 import app return app @pytest.fixture(name="client") def get_client(app: FastAPI): client = TestClient(app) return client @needs_py39 def test_openapi_schema(client: TestClient):
64
64
47
15
48
ssensalo/fastapi
tests/test_tutorial/test_request_files/test_tutorial002_py39.py
Python
test_openapi_schema
test_openapi_schema
158
162
158
159
eea82443acdcc21c99fb6512bfbd896e5688b207
bigcode/the-stack
train
2f664cffa20eac9dcf8a85e9
train
function
@pytest.fixture(name="app") def get_app(): from docs_src.request_files.tutorial002_py39 import app return app
@pytest.fixture(name="app") def get_app():
from docs_src.request_files.tutorial002_py39 import app return app
object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, } }, } @pyte...
64
64
28
10
54
ssensalo/fastapi
tests/test_tutorial/test_request_files/test_tutorial002_py39.py
Python
get_app
get_app
144
148
144
145
e9e0284fa5670a6e7d0ccb2a2a7e3b47180891e4
bigcode/the-stack
train
6e6392574f90371a820ca7cb
train
function
@needs_py39 def test_get_root(app: FastAPI): client = TestClient(app) response = client.get("/") assert response.status_code == 200, response.text assert b"<form" in response.content
@needs_py39 def test_get_root(app: FastAPI):
client = TestClient(app) response = client.get("/") assert response.status_code == 200, response.text assert b"<form" in response.content
file)), ("files", ("test2.txt", file2)), ), ) assert response.status_code == 200, response.text assert response.json() == {"filenames": ["test.txt", "test2.txt"]} @needs_py39 def test_get_root(app: FastAPI):
63
64
49
14
50
ssensalo/fastapi
tests/test_tutorial/test_request_files/test_tutorial002_py39.py
Python
test_get_root
test_get_root
230
235
230
231
42580f80242967ae596a7ba1acbb01788f703db6
bigcode/the-stack
train
dfca1c29ef5f8c67ea687c3f
train
function
@needs_py39 def test_post_form_no_body(client: TestClient): response = client.post("/files/") assert response.status_code == 422, response.text assert response.json() == file_required
@needs_py39 def test_post_form_no_body(client: TestClient):
response = client.post("/files/") assert response.status_code == 422, response.text assert response.json() == file_required
openapi_schema file_required = { "detail": [ { "loc": ["body", "files"], "msg": "field required", "type": "value_error.missing", } ] } @needs_py39 def test_post_form_no_body(client: TestClient):
64
64
45
16
48
ssensalo/fastapi
tests/test_tutorial/test_request_files/test_tutorial002_py39.py
Python
test_post_form_no_body
test_post_form_no_body
176
180
176
177
6f1b709f56ee5e397244918f730e9960e5af929d
bigcode/the-stack
train
bc9edb3924f36a13422dd6bc
train
function
@pytest.fixture(name="client") def get_client(app: FastAPI): client = TestClient(app) return client
@pytest.fixture(name="client") def get_client(app: FastAPI):
client = TestClient(app) return client
ref": "#/components/schemas/ValidationError"}, } }, }, } }, } @pytest.fixture(name="app") def get_app(): from docs_src.request_files.tutorial002_py39 import app return app @pytest.fixture(name="client") def get_client(app: FastAPI):
64
64
25
14
49
ssensalo/fastapi
tests/test_tutorial/test_request_files/test_tutorial002_py39.py
Python
get_client
get_client
151
155
151
153
5b7a5fb1cab8119411ffb0882a5b98596c3258e4
bigcode/the-stack
train
8de809d64f71674d62d9dc59
train
function
def _round_values(values, decimal_precision=True): """Round a value to the decimal precision in the MassConfiguration. Warnings -------- This method is intended for internal use only. """ if decimal_precision: values = apply_decimal_precision(values, MASSCONFIGURATION.decimal_precision...
def _round_values(values, decimal_precision=True):
"""Round a value to the decimal precision in the MassConfiguration. Warnings -------- This method is intended for internal use only. """ if decimal_precision: values = apply_decimal_precision(values, MASSCONFIGURATION.decimal_precision) return values
or '(t0, tf, numpoints)'" ) if steps is not None: steps = int(steps) time_input = ((t0, tf, numpoints, None, None), {"steps": steps}) return time_input def _round_values(values, decimal_precision=True):
64
64
67
10
53
z-haiman/MASSpy
src/mass/simulation/simulation.py
Python
_round_values
_round_values
1,648
1,659
1,648
1,648
10e3c5ee2c86977a67f8aee01ed040731030c146
bigcode/the-stack
train
0aa5d0f48f8b8683461eab06
train
function
def _load_model_into_roadrunner(mass_model, rr=None, verbose=False, **kwargs): """Create a RoadRunner instance for the given model. Warnings -------- This method is intended for internal use only. """ # Convert SBML model to string doc = _model_to_sbml(mass_model, f_replace={}, **kwargs) ...
def _load_model_into_roadrunner(mass_model, rr=None, verbose=False, **kwargs):
"""Create a RoadRunner instance for the given model. Warnings -------- This method is intended for internal use only. """ # Convert SBML model to string doc = _model_to_sbml(mass_model, f_replace={}, **kwargs) sbml_str = writeSBMLToString(doc) # Validate that model can load into Ro...
, "superfluous": True, "elemental": True, } ) raise MassSimulationError(msg) # Log warning if numerical consistency issues exist in the model if not consistency_check: msg = "MassModel has numerical consistency issues, use wit...
129
129
430
21
108
z-haiman/MASSpy
src/mass/simulation/simulation.py
Python
_load_model_into_roadrunner
_load_model_into_roadrunner
1,537
1,592
1,537
1,537
60e6aa9c3a946ea0c0ad48d530405cc220ce6554
bigcode/the-stack
train
9aa60d3e143d45a4ae59bcf0
train
function
def _assess_model_quality_for_simulation(mass_model, verbose, report): """Assess the model quality to ensure it can be simulated. Warnings -------- This method is intended for internal use only. """ # Check if model can simulate or has numerical consistency issues simulate_check, consisten...
def _assess_model_quality_for_simulation(mass_model, verbose, report):
"""Assess the model quality to ensure it can be simulated. Warnings -------- This method is intended for internal use only. """ # Check if model can simulate or has numerical consistency issues simulate_check, consistency_check = is_simulatable(mass_model) if not simulate_check: ...
) self.update_model_simulation_values(model) else: # Otherwise add to simulation values self._simulation_values.add(_get_sim_values_from_model(model)) _log_msg( LOGGER, logging.INFO, verbose, "Successfully loaded MassM...
83
83
278
17
66
z-haiman/MASSpy
src/mass/simulation/simulation.py
Python
_assess_model_quality_for_simulation
_assess_model_quality_for_simulation
1,493
1,534
1,493
1,493
c09ba26c84cf3d0104c1579f7478c79895f97b41
bigcode/the-stack
train
2c26f3261848af0090a221b0
train
function
def _get_sim_values_from_model(mass_model): """Return the initial conditions and parameter values in a DictWithID. Warnings -------- This method is intended for internal use only. """ init_conds = mass_model.initial_conditions parameters = mass_model._get_all_parameters() values = { ...
def _get_sim_values_from_model(mass_model):
"""Return the initial conditions and parameter values in a DictWithID. Warnings -------- This method is intended for internal use only. """ init_conds = mass_model.initial_conditions parameters = mass_model._get_all_parameters() values = { "init_conds": DictWithID( ...
rr = roadrunner.RoadRunner(sbml_str) _log_msg( LOGGER, logging.INFO, verbose, "Successfully loaded MassModel '%s' into RoadRunner.", str(mass_model), ) return rr def _get_sim_values_from_model(mass_model):
64
64
170
11
52
z-haiman/MASSpy
src/mass/simulation/simulation.py
Python
_get_sim_values_from_model
_get_sim_values_from_model
1,595
1,617
1,595
1,595
99c00a977ae7d050b585b22be534d48c5cc37083
bigcode/the-stack
train
8b1f5b78aec6043f4f5dfb8c
train
function
def _make_conc(metabolite_str): """Add the concentration brackets from a metabolite identifier. Warnings -------- This method is intended for internal use only. """ return "[" + metabolite_str + "]"
def _make_conc(metabolite_str):
"""Add the concentration brackets from a metabolite identifier. Warnings -------- This method is intended for internal use only. """ return "[" + metabolite_str + "]"
_conc(metabolite_str): """Strip the concentration brackets from a metabolite identifier. Warnings -------- This method is intended for internal use only. """ return metabolite_str.lstrip("[").rstrip("]") def _make_conc(metabolite_str):
63
64
52
11
53
z-haiman/MASSpy
src/mass/simulation/simulation.py
Python
_make_conc
_make_conc
1,673
1,681
1,673
1,673
1d8f477356f4f21b74bd397cab55650a9feb14bf
bigcode/the-stack
train
3ff6b8928e13316c7b4c0027
train
function
def _format_time_input(time, steps=None, verbose=False): """Format the time input and return it as a tuple for the RoadRunner. Warnings -------- This method is intended for internal use only. """ _log_msg(LOGGER, logging.INFO, verbose, "Getting time points") if len(time) == 2: t0, ...
def _format_time_input(time, steps=None, verbose=False):
"""Format the time input and return it as a tuple for the RoadRunner. Warnings -------- This method is intended for internal use only. """ _log_msg(LOGGER, logging.INFO, verbose, "Getting time points") if len(time) == 2: t0, tf = time numpoints = None elif len(time) == ...
ID( id=mass_model.id + "_parameters", data_dict={param: value for param, value in iteritems(parameters)}, ), } return DictWithID(id=mass_model.id + "_values", data_dict=values) def _format_time_input(time, steps=None, verbose=False):
64
64
203
13
51
z-haiman/MASSpy
src/mass/simulation/simulation.py
Python
_format_time_input
_format_time_input
1,620
1,645
1,620
1,620
b15672fa20f6f7a7af9d4c92d27eb699be90ccb4
bigcode/the-stack
train
0bc3a42b1b5cc3f96d5d220a
train
function
def _make_init_cond(metabolite_str): """Format metabolite identifier to match initial condition accesors. Warnings -------- This method is intended for internal use only. """ return "init(" + metabolite_str + ")"
def _make_init_cond(metabolite_str):
"""Format metabolite identifier to match initial condition accesors. Warnings -------- This method is intended for internal use only. """ return "init(" + metabolite_str + ")"
) def _make_conc(metabolite_str): """Add the concentration brackets from a metabolite identifier. Warnings -------- This method is intended for internal use only. """ return "[" + metabolite_str + "]" def _make_init_cond(metabolite_str):
64
64
55
11
53
z-haiman/MASSpy
src/mass/simulation/simulation.py
Python
_make_init_cond
_make_init_cond
1,684
1,692
1,684
1,684
342a76673b4f4f9b21a7fb036bc3093e5dc49106
bigcode/the-stack
train
7a624c80bd358f8a75db2828
train
class
class Simulation(Object): """Class for managing setup and result handling of simulations. The :class:`Simulation` class is designed to address all aspects related to the simulation of :class:`~.MassModel` objects, including setting the solver and solver options, perturbation of concentrations and param...
class Simulation(Object):
"""Class for managing setup and result handling of simulations. The :class:`Simulation` class is designed to address all aspects related to the simulation of :class:`~.MassModel` objects, including setting the solver and solver options, perturbation of concentrations and parameters, simulation of a...
ml import _model_to_sbml from mass.util.dict_with_id import DictWithID from mass.util.qcqa import is_simulatable, qcqa_model from mass.util.util import ( _check_kwargs, _log_msg, _make_logger, apply_decimal_precision, ensure_iterable, ) # Set the logger MASSCONFIGURATION = MassConfiguration() # If...
256
256
10,059
4
252
z-haiman/MASSpy
src/mass/simulation/simulation.py
Python
Simulation
Simulation
135
1,490
135
135
860fdfa95be1b2bcd2d951a68a379aa351ad840a
bigcode/the-stack
train
1a034ddea409dea65dafd188
train
function
def _make_ss_flux(reaction_str): """Format reaction identifier to match steady state flux parameter. Warnings -------- This method is intended for internal use only. """ return "v_" + reaction_str
def _make_ss_flux(reaction_str):
"""Format reaction identifier to match steady state flux parameter. Warnings -------- This method is intended for internal use only. """ return "v_" + reaction_str
def _make_init_cond(metabolite_str): """Format metabolite identifier to match initial condition accesors. Warnings -------- This method is intended for internal use only. """ return "init(" + metabolite_str + ")" def _make_ss_flux(reaction_str):
64
64
49
9
54
z-haiman/MASSpy
src/mass/simulation/simulation.py
Python
_make_ss_flux
_make_ss_flux
1,695
1,703
1,695
1,695
179bf62b36a9643c2b0af4ffacd3e50a676c6a51
bigcode/the-stack
train
24a9022acee1d1b9caabf727
train
function
def _strip_conc(metabolite_str): """Strip the concentration brackets from a metabolite identifier. Warnings -------- This method is intended for internal use only. """ return metabolite_str.lstrip("[").rstrip("]")
def _strip_conc(metabolite_str):
"""Strip the concentration brackets from a metabolite identifier. Warnings -------- This method is intended for internal use only. """ return metabolite_str.lstrip("[").rstrip("]")
value to the decimal precision in the MassConfiguration. Warnings -------- This method is intended for internal use only. """ if decimal_precision: values = apply_decimal_precision(values, MASSCONFIGURATION.decimal_precision) return values def _strip_conc(metabolite_str):
64
64
55
11
52
z-haiman/MASSpy
src/mass/simulation/simulation.py
Python
_strip_conc
_strip_conc
1,662
1,670
1,662
1,662
161157169f669e9681ba5212baaf1abb8f68d792
bigcode/the-stack
train
2fc86adcb82dcd8ea0c69976
train
class
class Migration(migrations.Migration): dependencies = [ ('Servico', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='servico', options={'ordering': ('-nome_servico',), 'verbose_name': 'serviço', 'verbose_name_plural': 'serviços'}, ), ...
class Migration(migrations.Migration):
dependencies = [ ('Servico', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='servico', options={'ordering': ('-nome_servico',), 'verbose_name': 'serviço', 'verbose_name_plural': 'serviços'}, ), migrations.RemoveField( ...
# Generated by Django 2.2.7 on 2019-11-10 03:24 from django.db import migrations, models class Migration(migrations.Migration):
38
64
136
7
30
linikerunk/laundr-it
LaundrIT-Project/Servico/migrations/0002_auto_20191110_0024.py
Python
Migration
Migration
6
27
6
7
903945e7dc3d2d365ba462aa7d9ca61f8e1bd85f
bigcode/the-stack
train
705ae7adc8625c4b61896da2
train
class
class Insert_t(unittest.TestCase): @DaoConfig("DBSWriter") def __init__(self, methodName='runTest'): super(Insert_t, self).__init__(methodName) data_location = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'test_data.pkl') self.data_provider = create_dbs_data_provider(data_typ...
class Insert_t(unittest.TestCase): @DaoConfig("DBSWriter")
def __init__(self, methodName='runTest'): super(Insert_t, self).__init__(methodName) data_location = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'test_data.pkl') self.data_provider = create_dbs_data_provider(data_type='transient', data_location=data_location) self.data =...
DataTier.Insert unittests """ import os import unittest from dbsserver_t.utils.DaoConfig import DaoConfig from dbsserver_t.utils.DBSDataProvider import create_dbs_data_provider from dbs.dao.Oracle.DataTier.Insert import Insert as DataTierInsert from dbs.dao.Oracle.SequenceManager import SequenceManager as SequenceMan...
90
90
303
16
73
vkuznet/DBS
Server/Python/tests/dbsserver_t/unittests/dao_t/Oracle_t/DataTier_t/Insert_t.py
Python
Insert_t
Insert_t
13
46
13
14
c5b8286e3aeb6b4a34a903ed740147d3a1c8e68b
bigcode/the-stack
train
a5e1acfa5eda221efd91fef4
train
class
class NexusSink(FileSink): """This is a sink for writing NeXus HDF5 files from a template. The template is a dictionary representing the structure of the NeXus file. Special elements in this dictionary are responsible for writing the various NeXus elements. The actual writing work is done in the NexusS...
class NexusSink(FileSink):
"""This is a sink for writing NeXus HDF5 files from a template. The template is a dictionary representing the structure of the NeXus file. Special elements in this dictionary are responsible for writing the various NeXus elements. The actual writing work is done in the NexusSinkHandler. This class ...
linkpath = self.find_scan_link(h5obj, self.template) if linkpath is not None: self.make_scan_links(h5obj, self.template, linkpath) try: self.h5file.close() self.h5file = None self._inited = False except Exceptio...
108
108
362
6
102
ebadkamil/nicos
nicos_mlz/toftof/devices/datasinks/nexussink.py
Python
NexusSink
NexusSink
236
283
236
236
c67edecbc41efe18520e252062563db518da4db9
bigcode/the-stack
train
7bd94e6ecd9bd0b0fe0ae043
train
class
class NexusSinkHandler(DataSinkHandler): _inited = False h5file = None def __init__(self, sink, dataset, detector): self.startdataset = None DataSinkHandler.__init__(self, sink, dataset, detector) def prepare(self): if self.startdataset is None: self.startdataset =...
class NexusSinkHandler(DataSinkHandler):
_inited = False h5file = None def __init__(self, sink, dataset, detector): self.startdataset = None DataSinkHandler.__init__(self, sink, dataset, detector) def prepare(self): if self.startdataset is None: self.startdataset = self.dataset self.h5file = No...
, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation...
256
256
1,734
8
247
ebadkamil/nicos
nicos_mlz/toftof/devices/datasinks/nexussink.py
Python
NexusSinkHandler
NexusSinkHandler
42
233
42
43
3df94ebf210203d2e661dc72d33d9c11c93bd4fe
bigcode/the-stack
train
3be140f1785719134e2ccc86
train
class
class FacialExpressionModel(object): EMOTIONS_LIST = ["Angry", "Disgust", "Fear", "Happy", "Neutral", "Sad", "Surprise"] def __init__(self, model_json_file, model_weights_file): # load model from JSON file with open(model_json_file...
class FacialExpressionModel(object):
EMOTIONS_LIST = ["Angry", "Disgust", "Fear", "Happy", "Neutral", "Sad", "Surprise"] def __init__(self, model_json_file, model_weights_file): # load model from JSON file with open(model_json_file, "r") as json_file: loade...
from keras.models import model_from_json import numpy as np class FacialExpressionModel(object):
19
64
161
6
12
HarshitRuwali/Facial-Expression-Recognition
model.py
Python
FacialExpressionModel
FacialExpressionModel
4
23
4
5
558cdf70f88e8748d1006beced60fae1cdb815b7
bigcode/the-stack
train
69d38710a83fac1cca1c6a12
train
function
def systematic_performance_bias( # type: ignore metrics_list: List[Number], threshold: Number = 0.8) -> bool: """ Checks for a systematic bias in provided predictive performance values. Please see the documentation of :func:`fatf.accountability.models.measures. systematic_performance_bias_grid...
def systematic_performance_bias( # type: ignore metrics_list: List[Number], threshold: Number = 0.8) -> bool:
""" Checks for a systematic bias in provided predictive performance values. Please see the documentation of :func:`fatf.accountability.models.measures. systematic_performance_bias_grid` function for a description of input parameters, errors and exceptions. .. note:: This function expect...
.uk> # Rafael Poyiadzi <rp13102@bristol.ac.uk> # License: new BSD from numbers import Number from typing import List import numpy as np __all__ = ['systematic_performance_bias', 'systematic_performance_bias_grid'] def systematic_performance_bias( # type: ignore metrics_list: List[Number], threshold:...
91
91
305
32
59
RafaelPo/fat-forensics
fatf/accountability/models/measures.py
Python
systematic_performance_bias
systematic_performance_bias
16
47
16
17
07dd891db8156e8e0dc40fc1154855ec239c9461
bigcode/the-stack
train
2ebcf3cc5b482818398e0c47
train
function
def systematic_performance_bias_grid( # type: ignore metrics_list: List[Number], threshold: Number = 0.8) -> np.ndarray: """ Checks for pairwise systematic bias in group-wise predictive performance. If a disparity in performance is found to be above the specified ``threshold`` a given pair sub...
def systematic_performance_bias_grid( # type: ignore metrics_list: List[Number], threshold: Number = 0.8) -> np.ndarray:
""" Checks for pairwise systematic bias in group-wise predictive performance. If a disparity in performance is found to be above the specified ``threshold`` a given pair sub-population performance metrics is considered biased. .. note:: This function expects a list of predictive perform...
.utils.models.metric_tools.performance_per_subgroup_indexed` or :func:`fatf.utils.models.metric_tools.confusion_matrix_per_subgroup`/ :func:`fatf.utils.models.metric_tools. confusion_matrix_per_subgroup_indexed` in conjunction with :func:`fatf.utils.models.metric_tools.apply_metric_fu...
197
197
659
34
162
RafaelPo/fat-forensics
fatf/accountability/models/measures.py
Python
systematic_performance_bias_grid
systematic_performance_bias_grid
50
123
50
51
a524ade23f152f7f99ac5152d64540913294ab0e
bigcode/the-stack
train
06a1b9a7426e003be226780f
train
function
def video(obj): """ Matches the given input againts the available video type matchers. Args: obj: path to file, bytes or bytearray. Returns: Type instance if matches. Otherwise None. Raises: TypeError: if obj is not a supported type. """ return match(obj, video...
def video(obj):
""" Matches the given input againts the available video type matchers. Args: obj: path to file, bytes or bytearray. Returns: Type instance if matches. Otherwise None. Raises: TypeError: if obj is not a supported type. """ return match(obj, video_matchers)
font type matchers. Args: obj: path to file, bytes or bytearray. Returns: Type instance if matches. Otherwise None. Raises: TypeError: if obj is not a supported type. """ return match(obj, font_matchers) def video(obj):
64
64
75
4
60
fzzylogic/filetype.py
filetype/match.py
Python
video
video
73
87
73
73
7ad987a32a9d8c1037338cabd47e4db44d0c5df9
bigcode/the-stack
train
f88d2da0ccbc8af2a49064e8
train
function
def document(obj): """ Matches the given input againts the available document type matchers. Args: obj: path to file, bytes or bytearray. Returns: Type instance if matches. Otherwise None. Raises: TypeError: if obj is not a supported type. """ return match(obj,...
def document(obj):
""" Matches the given input againts the available document type matchers. Args: obj: path to file, bytes or bytearray. Returns: Type instance if matches. Otherwise None. Raises: TypeError: if obj is not a supported type. """ return match(obj, document_matchers)...
application type matchers. Args: obj: path to file, bytes or bytearray. Returns: Type instance if matches. Otherwise None. Raises: TypeError: if obj is not a supported type. """ return match(obj, application_matchers) def document(obj):
63
64
75
4
59
fzzylogic/filetype.py
filetype/match.py
Python
document
document
141
155
141
141
40c99bba01115a41f0e3a5c61f1f3a00ac4b9236
bigcode/the-stack
train
bcb6fc384fa32373d22e01f8
train
function
def match(obj, matchers=TYPES): """ Matches the given input againts the available file type matchers. Args: obj: path to file, bytes or bytearray. Returns: Type instance if type matches. Otherwise None. Raises: TypeError: if obj is not a supported type. """ buf...
def match(obj, matchers=TYPES):
""" Matches the given input againts the available file type matchers. Args: obj: path to file, bytes or bytearray. Returns: Type instance if type matches. Otherwise None. Raises: TypeError: if obj is not a supported type. """ buf = get_bytes(obj) for match...
ers from .types import DOCUMENT as document_matchers from .types import FONT as font_matchers from .types import IMAGE as image_matchers from .types import VIDEO as video_matchers from .types import TYPES from .utils import get_bytes def match(obj, matchers=TYPES):
64
64
100
9
54
fzzylogic/filetype.py
filetype/match.py
Python
match
match
16
36
16
16
725ee38d8881067c67581668da96b8dc651ce642
bigcode/the-stack
train
eca44bfec39d8cbc66e3170f
train
function
def image(obj): """ Matches the given input againts the available image type matchers. Args: obj: path to file, bytes or bytearray. Returns: Type instance if matches. Otherwise None. Raises: TypeError: if obj is not a supported type. """ return match(obj, image...
def image(obj):
""" Matches the given input againts the available image type matchers. Args: obj: path to file, bytes or bytearray. Returns: Type instance if matches. Otherwise None. Raises: TypeError: if obj is not a supported type. """ return match(obj, image_matchers)
array. Returns: Type instance if type matches. Otherwise None. Raises: TypeError: if obj is not a supported type. """ buf = get_bytes(obj) for matcher in matchers: if matcher.match(buf): return matcher return None def image(obj):
64
64
75
4
59
fzzylogic/filetype.py
filetype/match.py
Python
image
image
39
53
39
39
b2504acad4a04e454a8180e902c9e0e6f49373f5
bigcode/the-stack
train
dfcb0018129711b6339b7542
train
function
def application(obj): """ Matches the given input againts the available application type matchers. Args: obj: path to file, bytes or bytearray. Returns: Type instance if matches. Otherwise None. Raises: TypeError: if obj is not a supported type. """ return matc...
def application(obj):
""" Matches the given input againts the available application type matchers. Args: obj: path to file, bytes or bytearray. Returns: Type instance if matches. Otherwise None. Raises: TypeError: if obj is not a supported type. """ return match(obj, application_mat...
archive type matchers. Args: obj: path to file, bytes or bytearray. Returns: Type instance if matches. Otherwise None. Raises: TypeError: if obj is not a supported type. """ return match(obj, archive_matchers) def application(obj):
64
64
75
4
60
fzzylogic/filetype.py
filetype/match.py
Python
application
application
124
138
124
124
6f7f535c43394a1b4634a2f4bb217f23130d90b3
bigcode/the-stack
train
62ef871c9130c90db295be79
train
function
def font(obj): """ Matches the given input againts the available font type matchers. Args: obj: path to file, bytes or bytearray. Returns: Type instance if matches. Otherwise None. Raises: TypeError: if obj is not a supported type. """ return match(obj, font_ma...
def font(obj):
""" Matches the given input againts the available font type matchers. Args: obj: path to file, bytes or bytearray. Returns: Type instance if matches. Otherwise None. Raises: TypeError: if obj is not a supported type. """ return match(obj, font_matchers)
image type matchers. Args: obj: path to file, bytes or bytearray. Returns: Type instance if matches. Otherwise None. Raises: TypeError: if obj is not a supported type. """ return match(obj, image_matchers) def font(obj):
64
64
75
4
60
fzzylogic/filetype.py
filetype/match.py
Python
font
font
56
70
56
56
b757abfbb9065b1689aa8d8ab3c57b90318288a6
bigcode/the-stack
train
fbdd46b19428db2c765ff79b
train
function
def audio(obj): """ Matches the given input againts the available autio type matchers. Args: obj: path to file, bytes or bytearray. Returns: Type instance if matches. Otherwise None. Raises: TypeError: if obj is not a supported type. """ return match(obj, audio...
def audio(obj):
""" Matches the given input againts the available autio type matchers. Args: obj: path to file, bytes or bytearray. Returns: Type instance if matches. Otherwise None. Raises: TypeError: if obj is not a supported type. """ return match(obj, audio_matchers)
video type matchers. Args: obj: path to file, bytes or bytearray. Returns: Type instance if matches. Otherwise None. Raises: TypeError: if obj is not a supported type. """ return match(obj, video_matchers) def audio(obj):
64
64
76
4
60
fzzylogic/filetype.py
filetype/match.py
Python
audio
audio
90
104
90
90
e6d7b3cc0ada4afa207d88b3052811e1475e214b
bigcode/the-stack
train
e5e7d715b8bed37018de13d6
train
function
def archive(obj): """ Matches the given input againts the available archive type matchers. Args: obj: path to file, bytes or bytearray. Returns: Type instance if matches. Otherwise None. Raises: TypeError: if obj is not a supported type. """ return match(obj, a...
def archive(obj):
""" Matches the given input againts the available archive type matchers. Args: obj: path to file, bytes or bytearray. Returns: Type instance if matches. Otherwise None. Raises: TypeError: if obj is not a supported type. """ return match(obj, archive_matchers)
autio type matchers. Args: obj: path to file, bytes or bytearray. Returns: Type instance if matches. Otherwise None. Raises: TypeError: if obj is not a supported type. """ return match(obj, audio_matchers) def archive(obj):
64
64
75
4
60
fzzylogic/filetype.py
filetype/match.py
Python
archive
archive
107
121
107
107
634b1bad0bc80e6ca4fb4840de7b58e56cf7123b
bigcode/the-stack
train
2b53cc13516ebb28bced7ceb
train
function
def create_number_character_table(start_num=0, end_num=1024): '''For each number looped through, the function determines the Unicode character that corresponds to that number (unless that character cannot be printed--see comments below); appends both the number and its corresponding character to a tuple...
def create_number_character_table(start_num=0, end_num=1024):
'''For each number looped through, the function determines the Unicode character that corresponds to that number (unless that character cannot be printed--see comments below); appends both the number and its corresponding character to a tuple; and stores that tuple in a list. The function then retur...
creates a table of i, chr(i) pairs for all instances of # chr(i) that could be successfully encoded. # # It's fun to look through the output (which I needed to open in Libre Calc, as # most characters did not render correctly in Excel using its default settings) # and see all the different types of characters that ex...
199
199
664
16
182
kburchfiel/number-character_table_builder
num_char_table.py
Python
create_number_character_table
create_number_character_table
23
74
23
23
621abe53101838d738e1d36eb1e2b2dbc0173e99
bigcode/the-stack
train
4a0fc7a56b09becd6637fa21
train
class
class Migration(migrations.Migration): dependencies = [ ('gameapp', '0008_visitors'), ] operations = [ migrations.AlterField( model_name='visitors', name='ipAddress', field=models.TextField(), ), ]
class Migration(migrations.Migration):
dependencies = [ ('gameapp', '0008_visitors'), ] operations = [ migrations.AlterField( model_name='visitors', name='ipAddress', field=models.TextField(), ), ]
# Generated by Django 3.0.3 on 2020-04-28 17:00 from django.db import migrations, models class Migration(migrations.Migration):
38
64
56
7
30
Rahul0700/Roras-gamehub
gameproject/gameapp/migrations/0009_auto_20200428_2230.py
Python
Migration
Migration
6
18
6
7
fd6e4c797e9dda6e6d69ad8a1380bd96ae4de176
bigcode/the-stack
train
cc2f45c8067facbe942b7bbe
train
class
class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='City', fields=[ ('id', models.AutoField(auto_created=True, primary_k...
class Migration(migrations.Migration):
initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='City', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='...
# Generated by Django 3.0.8 on 2020-07-06 20:41 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):
51
64
123
7
43
mesc08/django-weather-app
main/weather/migrations/0001_initial.py
Python
Migration
Migration
8
28
8
9
faeb041b4d53cfe5a6cfdb61d04caa44dfc5ac86
bigcode/the-stack
train
e84be44660e892b95bbdde57
train
function
def process(index,total,value): value=str(value) print("Processing",index,"/",total,value, flush=True) retrycount=0 while True: # create two files to hold the output and errors, respectively with open("/tmp/"+value+'.out','w+') as fout: with open("/tmp/"+value+'.err','w+') as...
def process(index,total,value):
value=str(value) print("Processing",index,"/",total,value, flush=True) retrycount=0 while True: # create two files to hold the output and errors, respectively with open("/tmp/"+value+'.out','w+') as fout: with open("/tmp/"+value+'.err','w+') as ferr: cmd="prin...
#!/usr/bin/env python from joblib import Parallel, delayed import time import os import subprocess import sys def process(index,total,value):
32
162
542
6
25
thinkahead/faas-fn
pi_invoke_function.py
Python
process
process
9
58
9
9
4c2bcc4aab0e4349a6039be956f9aa6ff61650ef
bigcode/the-stack
train
080c292c9f804116b0fcba36
train
class
class Event(object): """Represents an event or fragment of an event to be written by this modular input to Splunk. To write an input to a stream, call the ``write_to`` function, passing in a stream. """ def __init__(self, data=None, stanza=None, time=None, host=None, index=None, source=None, ...
class Event(object):
"""Represents an event or fragment of an event to be written by this modular input to Splunk. To write an input to a stream, call the ``write_to`` function, passing in a stream. """ def __init__(self, data=None, stanza=None, time=None, host=None, index=None, source=None, sourcetype=Non...
# Copyright 2011-2015 Splunk, Inc. # # 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 agreed to in wri...
170
238
795
4
165
CyberGRX/api-connector-splunk
bin/api_connector_splunk/splunklib/modularinput/event.py
Python
Event
Event
20
107
20
20
7c64d52725f55c06917c511074e4d8eddbd7f445
bigcode/the-stack
train
6e4cab9a928ce794d1213e89
train
function
def getMayaMainWindow(): mayaPtr = omui.MQtUtil.mainWindow() return wrapInstance(long(mayaPtr), QtWidgets.QWidget)
def getMayaMainWindow():
mayaPtr = omui.MQtUtil.mainWindow() return wrapInstance(long(mayaPtr), QtWidgets.QWidget)
if develop: reload(core) reload(mainView) try: proxyTextureUI.close() except: pass proxyTextureUI = Controller(envVar) proxyTextureUI.show(dockable = dockable) # wrapper to get mayas main window def getMayaMainWindow():
64
64
33
7
56
Viele/Masters-Project-Pipeline-Tools
proxyTexture/controller.py
Python
getMayaMainWindow
getMayaMainWindow
45
47
45
45
5a9d39534e4dffe3a7d11164a10158eef5e76c2e
bigcode/the-stack
train
24f08e137a9d0c2773270430
train
function
def open(develop = False, dockable = False, envVar = ""): if develop: reload(core) reload(mainView) try: proxyTextureUI.close() except: pass proxyTextureUI = Controller(envVar) proxyTextureUI.show(dockable = dockable)
def open(develop = False, dockable = False, envVar = ""):
if develop: reload(core) reload(mainView) try: proxyTextureUI.close() except: pass proxyTextureUI = Controller(envVar) proxyTextureUI.show(dockable = dockable)
'_Glossiness'] for f in pm.ls(type='file'): for t in types: if t in f.fileTextureName.get(): f.colorSpace.set('Raw') proxyTextureUI = None def open(develop = False, dockable = False, envVar = ""):
64
64
66
17
46
Viele/Masters-Project-Pipeline-Tools
proxyTexture/controller.py
Python
open
open
30
42
30
31
9cffa84e3ad2abae75b20a8f43301632bded9c18
bigcode/the-stack
train
172360b2d5f734b23a471410
train
function
def fixColorSpace(): types = ['_ior', '_Normal', '_Glossiness'] for f in pm.ls(type='file'): for t in types: if t in f.fileTextureName.get(): f.colorSpace.set('Raw')
def fixColorSpace():
types = ['_ior', '_Normal', '_Glossiness'] for f in pm.ls(type='file'): for t in types: if t in f.fileTextureName.get(): f.colorSpace.set('Raw')
proxyTexture.controller as proxyTextureCtrl proxyTextureCtrl.open() ''' # because maya is changing the colorspace when updating the file path # some of them are wrong. run this to fix # of course you need to set the suffixes depending on how your naming scheme works def fixColorSpace():
64
64
55
5
58
Viele/Masters-Project-Pipeline-Tools
proxyTexture/controller.py
Python
fixColorSpace
fixColorSpace
20
26
20
20
40fbfc41762af9a0b538947ba2626a0bc2ec4508
bigcode/the-stack
train
87fc07dc7a06e6edbf12df15
train
class
class Controller(MayaQWidgetDockableMixin, QtWidgets.QMainWindow, mainView.Ui_proxyTextureWindow): def __init__(self, envVar, parent = getMayaMainWindow()): super(Controller, self).__init__(parent) self.envVar = envVar self.setupUi(self) self.core = core.Core() ...
class Controller(MayaQWidgetDockableMixin, QtWidgets.QMainWindow, mainView.Ui_proxyTextureWindow):
def __init__(self, envVar, parent = getMayaMainWindow()): super(Controller, self).__init__(parent) self.envVar = envVar self.setupUi(self) self.core = core.Core() self.setAttribute(QtCore.Qt.WA_DeleteOnClose) self.createConnections() def createC...
wrapper to get mayas main window def getMayaMainWindow(): mayaPtr = omui.MQtUtil.mainWindow() return wrapInstance(long(mayaPtr), QtWidgets.QWidget) class Controller(MayaQWidgetDockableMixin, QtWidgets.QMainWindow, mainView.Ui_proxyTextureWindow):
64
64
140
23
41
Viele/Masters-Project-Pipeline-Tools
proxyTexture/controller.py
Python
Controller
Controller
50
70
50
51
780b4f6a551df1d2f219fd66bdba26c88ad29463
bigcode/the-stack
train
2f4f6df5e4a9be6fe2878118
train
function
def monkey_patch(): _Rendezvous.__await__ = __await__
def monkey_patch():
_Rendezvous.__await__ = __await__
the License is distributed on an "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 asyncio import sys from grpc._channel import _Rendezvous def monkey_patch():
64
64
16
4
59
windies21/loopchain
loopchain/tools/grpc_helper/grpc_patcher.py
Python
monkey_patch
monkey_patch
21
22
21
21
4103e2bf8972d4f65060a702a300d723a896b4de
bigcode/the-stack
train
ec8e2cad38f91e585b90b1df
train
function
def __await__(self: _Rendezvous): def _callback(): try: future.set_result(self.result()) except StopIteration as e: print(f"await _callback(StopIteration): {e!r}", sys.stderr) # instead StopIteration to Exception future.set_exception(Exception(f"await ...
def __await__(self: _Rendezvous):
def _callback(): try: future.set_result(self.result()) except StopIteration as e: print(f"await _callback(StopIteration): {e!r}", sys.stderr) # instead StopIteration to Exception future.set_exception(Exception(f"await _callback(StopIteration): {e!r}"))...
implied. # See the License for the specific language governing permissions and # limitations under the License. import asyncio import sys from grpc._channel import _Rendezvous def monkey_patch(): _Rendezvous.__await__ = __await__ def __await__(self: _Rendezvous):
63
64
154
11
52
windies21/loopchain
loopchain/tools/grpc_helper/grpc_patcher.py
Python
__await__
__await__
25
43
25
25
9db7e67b3409470f4f42c68dafa27a1a6541d9f2
bigcode/the-stack
train
e236e8b340d209f1441b3e0e
train
function
def upload(project_id, filepath): api_token = os.environ['POEDITOR_API_TOKEN'] with open(filepath, 'rb') as f: data = { 'id': project_id, 'api_token': api_token, 'updating': 'terms_translations', 'language': 'en', 'overwrite': 1, } ...
def upload(project_id, filepath):
api_token = os.environ['POEDITOR_API_TOKEN'] with open(filepath, 'rb') as f: data = { 'id': project_id, 'api_token': api_token, 'updating': 'terms_translations', 'language': 'en', 'overwrite': 1, } files = {'file': f} r...
import requests import argparse import os def upload(project_id, filepath):
16
64
192
7
8
resmio/TastyTomato
scripts/translationupload.py
Python
upload
upload
6
30
6
6
1bd87eb586f4658b6fbd4b93c4ac52cac3441662
bigcode/the-stack
train
dce67f94710cc2bb620fe129
train
class
class RoomManager: rooms = list() selection = Signal(message=None) abort = Signal(message=None) clock = Signal(uid=None, room=None) connected = asyncio.Event() timer = None def __init__(self, loop=None): if not loop: self.loop = asyncio.get_event_loop() else: ...
class RoomManager:
rooms = list() selection = Signal(message=None) abort = Signal(message=None) clock = Signal(uid=None, room=None) connected = asyncio.Event() timer = None def __init__(self, loop=None): if not loop: self.loop = asyncio.get_event_loop() else: self.loop ...
browser.wait() await self.stop.send() class GraylogManager: handler = None async def update(self, message, **kwargs): if self.handler in logger.handlers: logger.removeHandler(self.handler) if "graylog" not in message: return graylog = message.get(...
106
106
354
4
102
medunigraz/outpost.attendance.browser
src/outpost/attendance/browser.py
Python
RoomManager
RoomManager
81
126
81
82
90a190f654d5b89e926742cc93d15b88eb80619e
bigcode/the-stack
train
b1a46bb0cae3355353f208dd
train
function
@click.command() @click.option("--terminal") @click.option("--api") @click.option("--username") @click.option("--password") @click.option("--http-host", default="localhost") @click.option("--http-port", default=6788) @click.option("--ws-host", default="localhost") @click.option("--ws-port", default=6789) @click.option(...
@click.command() @click.option("--terminal") @click.option("--api") @click.option("--username") @click.option("--password") @click.option("--http-host", default="localhost") @click.option("--http-port", default=6788) @click.option("--ws-host", default="localhost") @click.option("--ws-port", default=6789) @click.option(...
loop = asyncio.get_event_loop() screensaver = ScreenSaver() GPIO.setmode(GPIO.BOARD) GPIO.setup(sounddetection, GPIO.IN) GPIO.add_event_detect( sounddetection, GPIO.RISING, lambda _: asyncio.run_coroutine_threadsafe(screensaver.disable(), loop), bouncetime=1000, )...
.code, _("Network error"))} logger.debug("Sending webservice progress signal {c}".format(c=cardid)) await self.progress.send(message=data) @click.command() @click.option("--terminal") @click.option("--api") @click.option("--username") @click.option("--password") @click.option("--http-host", default="loc...
136
136
454
103
33
medunigraz/outpost.attendance.browser
src/outpost/attendance/browser.py
Python
cli
cli
318
376
318
330
6a710f45a54c45f5d13368ded632c8adb32b59b1
bigcode/the-stack
train
2dd98148c762f86fd79de9c7
train
class
class Webservice: session = None config_task = None headers = {"Content-Type": "application/json"} connected = asyncio.Event() ready = Signal(message=None) unready = Signal(message=None) progress = Signal(message=None) configured = Signal(message=None) def __init__(self, base_url, ...
class Webservice:
session = None config_task = None headers = {"Content-Type": "application/json"} connected = asyncio.Event() ready = Signal(message=None) unready = Signal(message=None) progress = Signal(message=None) configured = Signal(message=None) def __init__(self, base_url, terminal, username,...
, self.read) if uid and not self.cache.equals(uid): if timer: timer.cancel() timer = None logger.info("Scanned UID: {u}".format(u=uid)) self.cache.set(uid) timer = self.loop.ca...
256
256
957
4
252
medunigraz/outpost.attendance.browser
src/outpost/attendance/browser.py
Python
Webservice
Webservice
205
315
205
206
7a55dec3a9faa7d0af2b3bae7a16a2ddf8f6b208
bigcode/the-stack
train
5afbf09b928eeafcb242fe4d
train
class
class Browser: start = Signal() stop = Signal() def __init__(self, url): self.url = url async def run(self): while True: browser = await asyncio.create_subprocess_exec( "/usr/bin/chromium-browser", "--app={url}".format(url=self.url), ...
class Browser:
start = Signal() stop = Signal() def __init__(self, url): self.url = url async def run(self): while True: browser = await asyncio.create_subprocess_exec( "/usr/bin/chromium-browser", "--app={url}".format(url=self.url), "--star...
= Signal() async def disable(self, **kwargs): logger.debug("Activating display") proc = await asyncio.create_subprocess_exec( "/usr/bin/xset", "dpms", "force", "on" ) await self.disabled.send() return await proc.wait() class Browser:
64
64
118
3
61
medunigraz/outpost.attendance.browser
src/outpost/attendance/browser.py
Python
Browser
Browser
42
62
42
42
98419d78debe2d04c8032c679887f96d28c4e041
bigcode/the-stack
train
bc98d8418b06c6cbb1f82691
train
class
class GraylogManager: handler = None async def update(self, message, **kwargs): if self.handler in logger.handlers: logger.removeHandler(self.handler) if "graylog" not in message: return graylog = message.get("graylog") self.handler = graypy.GELFUDPHandl...
class GraylogManager:
handler = None async def update(self, message, **kwargs): if self.handler in logger.handlers: logger.removeHandler(self.handler) if "graylog" not in message: return graylog = message.get("graylog") self.handler = graypy.GELFUDPHandler( graylog...
app={url}".format(url=self.url), "--start-fullscreen", "--kiosk", "--incognito", "--disable-pinch", "--overscroll-history-navigation=0", ) await self.start.send() await browser.wait() await se...
64
64
93
5
59
medunigraz/outpost.attendance.browser
src/outpost/attendance/browser.py
Python
GraylogManager
GraylogManager
65
78
65
66
2710d58f1b92ac04e793f77cf6c134a07ee5de9e
bigcode/the-stack
train
a6a16420b68550bc1a3bed2d
train
class
class UIDCache: uid = None def set(self, uid): self.uid = uid def equals(self, uid): return self.uid == uid def reset(self): self.uid = None
class UIDCache:
uid = None def set(self, uid): self.uid = uid def equals(self, uid): return self.uid == uid def reset(self): self.uid = None
") return await self.clock.send(uid=uid, room=room) def timeout(self): abort = partial( self.abort.send, message={"type": "rooms", "uid": None, "rooms": tuple()} ) asyncio.ensure_future(abort(), loop=self.loop) class UIDCache:
64
64
47
4
60
medunigraz/outpost.attendance.browser
src/outpost/attendance/browser.py
Python
UIDCache
UIDCache
129
140
129
130
ef59fd5788669a8ae8e572b5bb0e1d67409a50ee
bigcode/the-stack
train
9a41d1b55c01569cba4a716d
train
class
class CardReader: scanned = Signal(uid=None) def __init__(self, reader, loop=None): if not loop: self.loop = asyncio.get_event_loop() else: self.loop = loop self.reader = reader self.cache = UIDCache() def read(self): self.reader.wait_for_ta...
class CardReader:
scanned = Signal(uid=None) def __init__(self, reader, loop=None): if not loop: self.loop = asyncio.get_event_loop() else: self.loop = loop self.reader = reader self.cache = UIDCache() def read(self): self.reader.wait_for_tag() (error,...
tuple()} ) asyncio.ensure_future(abort(), loop=self.loop) class UIDCache: uid = None def set(self, uid): self.uid = uid def equals(self, uid): return self.uid == uid def reset(self): self.uid = None class CardReader:
66
66
222
4
61
medunigraz/outpost.attendance.browser
src/outpost/attendance/browser.py
Python
CardReader
CardReader
143
175
143
144
fb4e2a8db4d50d87a1ec2fc3c8ed85b7baeee13e
bigcode/the-stack
train
2806b4b91769c8a3be13a864
train
class
class Websocket: clients = set() incoming = Signal(message=None) connected = Signal(client=None) async def connector(self, websocket, path): self.clients.add(websocket) try: greeting = json.dumps({"type": "ready", "service": "websocket"}) await websocket.send(gr...
class Websocket:
clients = set() incoming = Signal(message=None) connected = Signal(client=None) async def connector(self, websocket, path): self.clients.add(websocket) try: greeting = json.dumps({"type": "ready", "service": "websocket"}) await websocket.send(greeting) ...
if timer: timer.cancel() timer = None logger.info("Scanned UID: {u}".format(u=uid)) self.cache.set(uid) timer = self.loop.call_later(10, self.cache.reset) await self.scanned.send(uid=tuple(ui...
64
64
177
4
60
medunigraz/outpost.attendance.browser
src/outpost/attendance/browser.py
Python
Websocket
Websocket
178
202
178
179
c10190698b8022480733d27321c5adfe7f65f591
bigcode/the-stack
train
bc831e0091aa4fa8d3f135f2
train
function
def main(): cli(auto_envvar_prefix="ATTENDANCE")
def main():
cli(auto_envvar_prefix="ATTENDANCE")
= asyncio.gather( rooms.run(), loop.create_server(app.make_handler(), http_host, http_port), webservice.connect(), cardreader.run(), websockets.serve(websocket.connector, ws_host, ws_port), browser.run(), ) loop.run_until_complete(tasks) def main():
64
64
14
3
61
medunigraz/outpost.attendance.browser
src/outpost/attendance/browser.py
Python
main
main
379
380
379
379
9257049f740a7fdba7ab30419eb2e678697530ec
bigcode/the-stack
train
fd5dc262fcf206224a12aaff
train
class
class ScreenSaver: enabled = Signal() disabled = Signal() async def disable(self, **kwargs): logger.debug("Activating display") proc = await asyncio.create_subprocess_exec( "/usr/bin/xset", "dpms", "force", "on" ) await self.disabled.send() return await ...
class ScreenSaver:
enabled = Signal() disabled = Signal() async def disable(self, **kwargs): logger.debug("Activating display") proc = await asyncio.create_subprocess_exec( "/usr/bin/xset", "dpms", "force", "on" ) await self.disabled.send() return await proc.wait()
= logging.getLogger(__name__) logger.setLevel(logging.DEBUG) logging.basicConfig(level=logging.DEBUG) sounddetection = 12 cardkey = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF] class ScreenSaver:
64
64
72
4
60
medunigraz/outpost.attendance.browser
src/outpost/attendance/browser.py
Python
ScreenSaver
ScreenSaver
28
39
28
29
b58a05606a87e4c2a91160d16cab94e1a32ca18c
bigcode/the-stack
train
65bccfe9ce44f39764d56d3c
train
class
class CiderD: """ Main Class to compute the CIDEr metric """ def __init__(self, n=4, sigma=6.0, df="corpus"): # set cider to sum over 1 to 4-grams self._n = n # set the standard deviation parameter for gaussian penalty self._sigma = sigma # set which where to com...
class CiderD:
""" Main Class to compute the CIDEr metric """ def __init__(self, n=4, sigma=6.0, df="corpus"): # set cider to sum over 1 to 4-grams self._n = n # set the standard deviation parameter for gaussian penalty self._sigma = sigma # set which where to compute document ...
-Based Image Description Evaluation) Metric # by Vedantam, Zitnick, and Parikh (http://arxiv.org/abs/1411.5726) # # Creation Date: Sun Feb 8 14:16:54 2015 # # Authors: Ramakrishna Vedantam <vrama91@vt.edu> and Tsung-Yi Lin <tl483@cornell.edu> from ciderD_scorer_token4 import CiderScorer import pdb class...
109
109
366
5
103
WuJie1010/Fine-Grained-Image-Captioning
cider/pyciderevalcap/ciderD/ciderD_token.py
Python
CiderD
CiderD
13
54
13
13
cf04481cc20adda00562e6204593f64ac2cd3757
bigcode/the-stack
train
6e6ebb0f27ca66236487b7c1
train
function
def _group_or_org_autocomplete( context: Context, data_dict: DataDict, is_org: bool) -> list[dict[str, str]]: q = data_dict['q'] limit = data_dict.get('limit', 20) model = context['model'] query = model.Group.search_by_name_or_title(q, group_type=None, ...
def _group_or_org_autocomplete( context: Context, data_dict: DataDict, is_org: bool) -> list[dict[str, str]]:
q = data_dict['q'] limit = data_dict.get('limit', 20) model = context['model'] query = model.Group.search_by_name_or_title(q, group_type=None, is_org=is_org, limit=limit) group_list: list[dict[str, Any]] = [] for group in query.all(): res...
', 'name', 'fullname']: result_dict[k] = getattr(user, k) user_list.append(result_dict) return user_list def _group_or_org_autocomplete( context: Context, data_dict: DataDict, is_org: bool) -> list[dict[str, str]]:
64
64
148
34
29
salsadigitalauorg/ckan
ckan/logic/action/get.py
Python
_group_or_org_autocomplete
_group_or_org_autocomplete
1,648
1,666
1,648
1,651
7834b4c676e67713902508ceb579d9486025d0d5
bigcode/the-stack
train
75fca301700c48af52c132da
train
function
def resource_show( context: Context, data_dict: DataDict) -> ActionResult.ResourceShow: '''Return the metadata of a resource. :param id: the id of the resource :type id: string :param include_tracking: add tracking information to dataset and resources (default: ``False``) :t...
def resource_show( context: Context, data_dict: DataDict) -> ActionResult.ResourceShow:
'''Return the metadata of a resource. :param id: the id of the resource :type id: string :param include_tracking: add tracking information to dataset and resources (default: ``False``) :type include_tracking: bool :rtype: dictionary ''' model = context['model'] id = _get_o...
package_dict, _errors = lib_plugins.plugin_validate( package_plugin, context, package_dict, schema, 'package_show') for item in plugins.PluginImplementations(plugins.IPackageController): item.after_dataset_show(context, package_dict) return package_dict def resource_sh...
78
78
260
22
55
salsadigitalauorg/ckan
ckan/logic/action/get.py
Python
resource_show
resource_show
1,075
1,112
1,075
1,077
5d378137e85b2a1278276c12b2d2f8a7c91fb888
bigcode/the-stack
train
7ac12fcb2e73cda5ec5b7979
train
function
def help_show(context: Context, data_dict: DataDict) -> ActionResult.HelpShow: '''Return the help string for a particular API action. :param name: Action function name (eg `user_create`, `package_search`) :type name: string :returns: The help string for the action function, or None if the function ...
def help_show(context: Context, data_dict: DataDict) -> ActionResult.HelpShow:
'''Return the help string for a particular API action. :param name: Action function name (eg `user_create`, `package_search`) :type name: string :returns: The help string for the action function, or None if the function does not have a docstring. :rtype: string :raises: :class:`c...
== 'group': roles_list = [role for role in roles_list if role['value'] != 'editor'] _check_access('member_roles_list', context, data_dict) return roles_list def help_show(context: Context, data_dict: DataDict) -> ActionResult.HelpShow:
64
64
171
19
44
salsadigitalauorg/ckan
ckan/logic/action/get.py
Python
help_show
help_show
3,059
3,081
3,059
3,059
83f697eed367b8ee2455d12ae6f00336ffc05188
bigcode/the-stack
train
7e9901a5f83fb6beed259241
train
function
def organization_list_for_user(context: Context, data_dict: DataDict) -> ActionResult.OrganizationListForUser: '''Return the organizations that the user has a given permission for. Specifically it returns the list of organizations that the currently authorized user has a give...
def organization_list_for_user(context: Context, data_dict: DataDict) -> ActionResult.OrganizationListForUser:
'''Return the organizations that the user has a given permission for. Specifically it returns the list of organizations that the currently authorized user has a given permission (for example: "manage_group") against. By default this returns the list of organizations that the currently authoriz...
: q: Any = model.Session.query(model.Member.group_id) \ .filter(model.Member.table_name == 'user') \ .filter( # type_ignore_reason: incomplete SQLAlchemy types model.Member.capacity.in_(roles) # type: ignore ).filter(model.Member.table_id == u...
256
256
1,023
24
231
salsadigitalauorg/ckan
ckan/logic/action/get.py
Python
organization_list_for_user
organization_list_for_user
631
746
631
632
1737a5ea4ebd8bfc7fa7af6b2cc82bb7dbe0667f
bigcode/the-stack
train
cd220de40f272d142ca7d2e4
train
function
def _tag_search( context: Context, data_dict: DataDict) -> tuple[list[model.Tag], int]: model = context['model'] terms = data_dict.get('query') or data_dict.get('q') or [] if isinstance(terms, str): terms = [terms] terms = [t.strip() for t in terms if t.strip()] if 'fields' in data...
def _tag_search( context: Context, data_dict: DataDict) -> tuple[list[model.Tag], int]:
model = context['model'] terms = data_dict.get('query') or data_dict.get('q') or [] if isinstance(terms, str): terms = [terms] terms = [t.strip() for t in terms if t.strip()] if 'fields' in data_dict: log.warning('"fields" parameter is deprecated. ' 'Use the "q...
) \ and isinstance(result[0], model.DomainObject): # This is the case for order_by rank due to the add_column. results.append(result[0]) else: results.append(result) # If run in the context of a search query, then don't dictize the results. if not con...
126
126
421
25
101
salsadigitalauorg/ckan
ckan/logic/action/get.py
Python
_tag_search
_tag_search
2,180
2,230
2,180
2,181
3ae24d996c404b7359e1b59c1c44827f938bce32
bigcode/the-stack
train
e7881d477e546cada640309b
train
function
def group_follower_list( context: Context, data_dict: DataDict) -> ActionResult.GroupFollowerList: '''Return the list of users that are following the given group. :param id: the id or name of the group :type id: string :rtype: list of dictionaries ''' _check_access('group_foll...
def group_follower_list( context: Context, data_dict: DataDict) -> ActionResult.GroupFollowerList:
'''Return the list of users that are following the given group. :param id: the id or name of the group :type id: string :rtype: list of dictionaries ''' _check_access('group_follower_list', context, data_dict) return _follower_list( context, data_dict, ckan.logic.schema.de...
_list', context, data_dict) return _follower_list( context, data_dict, ckan.logic.schema.default_follow_dataset_schema(), context['model'].UserFollowingDataset) def group_follower_list( context: Context, data_dict: DataDict) -> ActionResult.GroupFollowerList:
64
64
116
25
39
salsadigitalauorg/ckan
ckan/logic/action/get.py
Python
group_follower_list
group_follower_list
2,618
2,633
2,618
2,620
3a4ca369d5be4ac2cb6ca0432c5df70f0d90f401
bigcode/the-stack
train
ba8b153bb915a0419e19dc9b
train
function
def organization_autocomplete(context: Context, data_dict: DataDict) -> ActionResult.OrganizationAutocomplete: ''' Return a list of organization names that contain a string. :param q: the string to search for :type q: string :param limit: the maximum number of organiza...
def organization_autocomplete(context: Context, data_dict: DataDict) -> ActionResult.OrganizationAutocomplete:
''' Return a list of organization names that contain a string. :param q: the string to search for :type q: string :param limit: the maximum number of organizations to return (optional, default: ``20``) :type limit: int :rtype: a list of organization dictionaries each with keys ``'n...
'``, and ``'id'`` ''' _check_access('group_autocomplete', context, data_dict) return _group_or_org_autocomplete(context, data_dict, is_org=False) def organization_autocomplete(context: Context, data_dict: DataDict) -> ActionResult.OrganizationAutocomplete:
64
64
147
21
43
salsadigitalauorg/ckan
ckan/logic/action/get.py
Python
organization_autocomplete
organization_autocomplete
1,689
1,706
1,689
1,690
e265ac0155eef2227dc4cc1ca48497d8a79f4b34
bigcode/the-stack
train
0458c54964051abc01915483
train
function
def organization_list(context: Context, data_dict: DataDict) -> ActionResult.OrganizationList: '''Return a list of the names of the site's organizations. :param type: the type of organization to list (optional, default: ``'organization'``), See docs for :py:class:`~ckan.pl...
def organization_list(context: Context, data_dict: DataDict) -> ActionResult.OrganizationList:
'''Return a list of the names of the site's organizations. :param type: the type of organization to list (optional, default: ``'organization'``), See docs for :py:class:`~ckan.plugins.interfaces.IGroupForm` :type type: string :param order_by: the field to sort the list by, must be ``'na...
type include_dataset_count: bool :param include_extras: if all_fields, include the group extra fields (optional, default: ``False``) :type include_extras: bool :param include_tags: if all_fields, include the group tags (optional, default: ``False``) :type include_tags: bool :param in...
200
200
668
20
180
salsadigitalauorg/ckan
ckan/logic/action/get.py
Python
organization_list
organization_list
502
560
502
503
29d50551a6e38af1d4746903402adca65dd7d6d0
bigcode/the-stack
train
861a82981a29db135218e8b0
train
function
def api_token_list( context: Context, data_dict: DataDict) -> ActionResult.ApiTokenList: '''Return list of all available API Tokens for current user. :returns: collection of all API Tokens :rtype: list .. versionadded:: 2.9 ''' id_or_name = _get_or_bust(data_dict, u'user') _check_a...
def api_token_list( context: Context, data_dict: DataDict) -> ActionResult.ApiTokenList:
'''Return list of all available API Tokens for current user. :returns: collection of all API Tokens :rtype: list .. versionadded:: 2.9 ''' id_or_name = _get_or_bust(data_dict, u'user') _check_access(u'api_token_list', context, data_dict) user = model.User.get(id_or_name) if user is...
) id = _get_or_bust(data_dict, u'id') try: return jobs.dictize_job(jobs.job_from_id(id)) except KeyError: raise NotFound def api_token_list( context: Context, data_dict: DataDict) -> ActionResult.ApiTokenList:
64
64
151
23
40
salsadigitalauorg/ckan
ckan/logic/action/get.py
Python
api_token_list
api_token_list
3,176
3,191
3,176
3,177
95daef4a15e1108d425a5c1eea7db8c109449985
bigcode/the-stack
train
d397e4beaa764f76d5f20ad8
train
function
def group_list_authz(context: Context, data_dict: DataDict) -> ActionResult.GroupListAuthz: '''Return the list of groups that the user is authorized to edit. :param available_only: remove the existing groups in the package (optional, default: ``False``) :type available_only: bool...
def group_list_authz(context: Context, data_dict: DataDict) -> ActionResult.GroupListAuthz:
'''Return the list of groups that the user is authorized to edit. :param available_only: remove the existing groups in the package (optional, default: ``False``) :type available_only: bool :param am_member: if ``True`` return only the groups the logged-in user is a member of, otherwise ret...
:param include_groups: if all_fields, include the organizations the organizations are in (optional, default: ``False``) :type include_groups: bool :param include_users: if all_fields, include the organization users (optional, default: ``False``). :type include_users: bool :...
159
159
531
24
135
salsadigitalauorg/ckan
ckan/logic/action/get.py
Python
group_list_authz
group_list_authz
563
628
563
564
5fc0fceb11c7e5233e02cec8cfe12c2b29ff91a2
bigcode/the-stack
train
c675f8eaa9a2b5cfdf4b5009
train
function
def _am_following( context: Context, data_dict: DataDict, default_schema: Schema, FollowerClass: Type["ModelFollowingModel[Any, Any]"]): schema = context.get('schema', default_schema) data_dict, errors = _validate(data_dict, schema, context) if errors: raise ValidationError(errors) ...
def _am_following( context: Context, data_dict: DataDict, default_schema: Schema, FollowerClass: Type["ModelFollowingModel[Any, Any]"]):
schema = context.get('schema', default_schema) data_dict, errors = _validate(data_dict, schema, context) if errors: raise ValidationError(errors) if 'user' not in context: raise NotAuthorized model = context['model'] userobj = model.User.get(context['user']) if not userobj...
( context, data_dict, ckan.logic.schema.default_follow_group_schema(), context['model'].UserFollowingGroup) def _am_following( context: Context, data_dict: DataDict, default_schema: Schema, FollowerClass: Type["ModelFollowingModel[Any, Any]"]):
64
64
146
38
26
salsadigitalauorg/ckan
ckan/logic/action/get.py
Python
_am_following
_am_following
2,653
2,672
2,653
2,655
74dd14390f119df380f3751ba8cde88e8ff3ca57
bigcode/the-stack
train
3dabcb7b039077782460b0da
train
function
def user_list( context: Context, data_dict: DataDict ) -> ActionResult.UserList: '''Return a list of the site's user accounts. :param q: filter the users returned to those whose names contain a string (optional) :type q: string :param email: filter the users returned to those whose email ...
def user_list( context: Context, data_dict: DataDict ) -> ActionResult.UserList:
'''Return a list of the site's user accounts. :param q: filter the users returned to those whose names contain a string (optional) :type q: string :param email: filter the users returned to those whose email match a string (optional) (you must be a sysadmin to use this filter) :type ema...
to this vocabulary will be returned (optional) :type vocabulary_id: string :param all_fields: return full tag dictionaries instead of just names (optional, default: ``False``) :type all_fields: bool :rtype: list of dictionaries ''' model = context['model'] vocab_id_or_name = data...
256
256
865
22
233
salsadigitalauorg/ckan
ckan/logic/action/get.py
Python
user_list
user_list
814
921
814
816
7319e46167889ab515ce69f7ffc5462fd8f9f483
bigcode/the-stack
train
54efb0fc02a614831c68b763
train
function
def organization_show(context: Context, data_dict: DataDict) -> ActionResult.OrganizationShow: '''Return the details of a organization. :param id: the id or name of the organization :type id: string :param include_datasets: include a truncated list of the org's datasets (optional, default: ``F...
def organization_show(context: Context, data_dict: DataDict) -> ActionResult.OrganizationShow:
'''Return the details of a organization. :param id: the id or name of the organization :type id: string :param include_datasets: include a truncated list of the org's datasets (optional, default: ``False``) :type include_datasets: bool :param include_dataset_count: include the full pac...
True``) :type include_tags: bool :param include_followers: include the group's number of followers (optional, default: ``True``) :type include_followers: bool :rtype: dictionary .. note:: Only its first 1000 datasets are returned ''' return _group_or_org_show(context, data_dict) ...
97
97
325
19
78
salsadigitalauorg/ckan
ckan/logic/action/get.py
Python
organization_show
organization_show
1,287
1,320
1,287
1,287
eb683e1626563b9e421463a12cf317cfd4679857
bigcode/the-stack
train
a0530abf6041e369006fc2ab
train
function
def dataset_followee_count( context: Context, data_dict: DataDict) -> ActionResult.DatasetFolloweeCount: '''Return the number of datasets that are followed by the given user. :param id: the id of the user :type id: string :rtype: int ''' return _followee_count( context...
def dataset_followee_count( context: Context, data_dict: DataDict) -> ActionResult.DatasetFolloweeCount:
'''Return the number of datasets that are followed by the given user. :param id: the id of the user :type id: string :rtype: int ''' return _followee_count( context, data_dict, context['model'].UserFollowingDataset)
:type id: string :rtype: int ''' return _followee_count( context, data_dict, context['model'].UserFollowingUser) def dataset_followee_count( context: Context, data_dict: DataDict) -> ActionResult.DatasetFolloweeCount:
64
64
89
26
38
salsadigitalauorg/ckan
ckan/logic/action/get.py
Python
dataset_followee_count
dataset_followee_count
2,781
2,794
2,781
2,783
348ef7457a9b33d8391eabf18e5618d65b9d798b
bigcode/the-stack
train
4756db02fd36dc704d730c9a
train
function
def tag_autocomplete(context: Context, data_dict: DataDict) -> ActionResult.TagAutocomplete: '''Return a list of tag names that contain a given string. By default only free tags (tags that don't belong to any vocabulary) are searched. If the ``vocabulary_id`` argument is given then only tags belonging ...
def tag_autocomplete(context: Context, data_dict: DataDict) -> ActionResult.TagAutocomplete:
'''Return a list of tag names that contain a given string. By default only free tags (tags that don't belong to any vocabulary) are searched. If the ``vocabulary_id`` argument is given then only tags belonging to that vocabulary will be searched instead. :param query: the string to search for ...
string, a list of dictionaries. :rtype: dictionary ''' tags, count = _tag_search(context, data_dict) return {'count': count, 'results': [_table_dictize(tag, context) for tag in tags]} def tag_autocomplete(context: Context, data_dict: DataDict) -> ActionResult.TagAutocomplete:
74
75
250
20
54
salsadigitalauorg/ckan
ckan/logic/action/get.py
Python
tag_autocomplete
tag_autocomplete
2,270
2,298
2,270
2,270
6c9ccb0548134b6780f1419fc1ec48e60dc329ba
bigcode/the-stack
train
4e6ee53b004b4d84fb97975d
train
function
def job_show(context: Context, data_dict: DataDict) -> ActionResult.JobShow: '''Show details for a background job. :param string id: The ID of the background job. :returns: Details about the background job. :rtype: dict .. versionadded:: 2.7 ''' _check_access(u'job_show', context, data_di...
def job_show(context: Context, data_dict: DataDict) -> ActionResult.JobShow:
'''Show details for a background job. :param string id: The ID of the background job. :returns: Details about the background job. :rtype: dict .. versionadded:: 2.7 ''' _check_access(u'job_show', context, data_dict) id = _get_or_bust(data_dict, u'id') try: return jobs.dict...
queues] else: queues = jobs.get_all_queues() for queue in queues: for job in queue.jobs: dictized_jobs.append(jobs.dictize_job(job)) return dictized_jobs def job_show(context: Context, data_dict: DataDict) -> ActionResult.JobShow:
64
64
123
19
44
salsadigitalauorg/ckan
ckan/logic/action/get.py
Python
job_show
job_show
3,158
3,173
3,158
3,158
29673731ffa5f57ef54b4625cd523808bea13c9f
bigcode/the-stack
train
525c083dda9aea2d3396c51d
train
function
def organization_follower_list( context: Context, data_dict: DataDict) -> ActionResult.OrganizationFollowerList: '''Return the list of users that are following the given organization. :param id: the id or name of the organization :type id: string :rtype: list of dictionaries ''' ...
def organization_follower_list( context: Context, data_dict: DataDict) -> ActionResult.OrganizationFollowerList:
'''Return the list of users that are following the given organization. :param id: the id or name of the organization :type id: string :rtype: list of dictionaries ''' _check_access('organization_follower_list', context, data_dict) return _follower_list( context, data_dict, ...
_list', context, data_dict) return _follower_list( context, data_dict, ckan.logic.schema.default_follow_group_schema(), context['model'].UserFollowingGroup) def organization_follower_list( context: Context, data_dict: DataDict) -> ActionResult.OrganizationFollowerList:
64
64
116
25
39
salsadigitalauorg/ckan
ckan/logic/action/get.py
Python
organization_follower_list
organization_follower_list
2,636
2,651
2,636
2,638
e27e589e83600936f45fab29f56adf53643eab5d
bigcode/the-stack
train
66561d4675d5eec1967a1e67
train
function
def user_follower_list( context: Context, data_dict: DataDict) -> ActionResult.UserFollowerList: '''Return the list of users that are following the given user. :param id: the id or name of the user :type id: string :rtype: list of dictionaries ''' _check_access('user_follower_...
def user_follower_list( context: Context, data_dict: DataDict) -> ActionResult.UserFollowerList:
'''Return the list of users that are following the given user. :param id: the id or name of the user :type id: string :rtype: list of dictionaries ''' _check_access('user_follower_list', context, data_dict) return _follower_list( context, data_dict, ckan.logic.schema.defau...
] users = [user for user in users if user is not None] # Dictize the list of User objects. return model_dictize.user_list_dictize(users, context) def user_follower_list( context: Context, data_dict: DataDict) -> ActionResult.UserFollowerList:
64
64
116
25
39
salsadigitalauorg/ckan
ckan/logic/action/get.py
Python
user_follower_list
user_follower_list
2,582
2,597
2,582
2,584
6ce87b56893a58a293973fff42c608470adac40c
bigcode/the-stack
train
e567e4808b992af793836813
train
function
def member_roles_list( context: Context, data_dict: DataDict) -> ActionResult.MemberRolesList: '''Return the possible roles for members of groups and organizations. :param group_type: the group type, either ``"group"`` or ``"organization"`` (optional, default ``"organization"``) :type group...
def member_roles_list( context: Context, data_dict: DataDict) -> ActionResult.MemberRolesList:
'''Return the possible roles for members of groups and organizations. :param group_type: the group type, either ``"group"`` or ``"organization"`` (optional, default ``"organization"``) :type group_type: string :returns: a list of dictionaries each with two keys: ``"text"`` (the display ...
sorts.append((field, order)) if total and len(sorts) > total: raise ValidationError( 'Too many sort criteria provided only %s allowed' % total) return sorts def member_roles_list( context: Context, data_dict: DataDict) -> ActionResult.MemberRolesList:
66
66
221
23
42
salsadigitalauorg/ckan
ckan/logic/action/get.py
Python
member_roles_list
member_roles_list
3,036
3,056
3,036
3,037
74cc7e0d949b1eb7075b823d708274a2d9115764
bigcode/the-stack
train
82dfa2cb44cbd85b950ef14f
train
function
def package_collaborator_list_for_user( context: Context, data_dict: DataDict) -> ActionResult.PackageCollaboratorListForUser: '''Return a list of all package the user is a collaborator in Note: This action requires the collaborators feature to be enabled with the :ref:`ckan.auth.allow_dataset_coll...
def package_collaborator_list_for_user( context: Context, data_dict: DataDict) -> ActionResult.PackageCollaboratorListForUser:
'''Return a list of all package the user is a collaborator in Note: This action requires the collaborators feature to be enabled with the :ref:`ckan.auth.allow_dataset_collaborators` configuration option. :param id: the id or name of the user :type id: string :param capacity: (optional) If pro...
and capacity not in allowed_capacities: raise ValidationError( {'message': _('Capacity must be one of "{}"').format(', '.join( allowed_capacities))}) q = model.Session.query(model.PackageMember).\ filter(model.PackageMember.package_id == package.id) if capacity: ...
127
127
424
30
97
salsadigitalauorg/ckan
ckan/logic/action/get.py
Python
package_collaborator_list_for_user
package_collaborator_list_for_user
261
317
261
262
1577517b24eac7e36808f0c764605298d0a5b818
bigcode/the-stack
train
f73ad7b07117cc39f3ead011
train
function
@logic.validate(ckan.logic.schema.default_autocomplete_schema) def format_autocomplete(context: Context, data_dict: DataDict) -> ActionResult.FormatAutocomplete: '''Return a list of resource formats whose names contain a string. :param q: the string to search for :type q: string :param limit: the maxim...
@logic.validate(ckan.logic.schema.default_autocomplete_schema) def format_autocomplete(context: Context, data_dict: DataDict) -> ActionResult.FormatAutocomplete:
'''Return a list of resource formats whose names contain a string. :param q: the string to search for :type q: string :param limit: the maximum number of resource formats to return (optional, default: ``5``) :type limit: int :rtype: list of strings ''' model = context['model']...
= { 'name': package['name'], 'title': package['title'], 'match_field': match_field, 'match_displayed': match_displayed} pkg_list.append(result_dict) return pkg_list @logic.validate(ckan.logic.schema.default_autocomplete_schema) def format_autocomplete(contex...
81
81
270
33
47
salsadigitalauorg/ckan
ckan/logic/action/get.py
Python
format_autocomplete
format_autocomplete
1,568
1,603
1,568
1,569
04e0a79e275efc0b53f9888e21e932334aa22348
bigcode/the-stack
train
2774f7283a9ac5d55b170ab6
train
function
def group_show(context: Context, data_dict: DataDict) -> ActionResult.GroupShow: '''Return the details of a group. :param id: the id or name of the group :type id: string :param include_datasets: include a truncated list of the group's datasets (optional, default: ``False``) :type include_...
def group_show(context: Context, data_dict: DataDict) -> ActionResult.GroupShow:
'''Return the details of a group. :param id: the id or name of the group :type id: string :param include_datasets: include a truncated list of the group's datasets (optional, default: ``False``) :type include_datasets: bool :param include_dataset_count: include the full package_count ...
['id']}) else: group_dict['num_followers'] = 0 if not schema: schema = ckan.logic.schema.default_show_group_schema() group_dict, _errors = lib_plugins.plugin_validate( group_plugin, context, group_dict, schema, 'organization_show' if is_org else 'group_show') return grou...
96
96
321
19
76
salsadigitalauorg/ckan
ckan/logic/action/get.py
Python
group_show
group_show
1,251
1,284
1,251
1,251
5069a68e52521eceeba2f19732820f7195f55f23
bigcode/the-stack
train
4e660d5f6827f9bc4e79e5ff
train
function
def resource_view_list(context: Context, data_dict: DataDict) -> ActionResult.ResourceViewList: ''' Return the list of resource views for a particular resource. :param id: the id of the resource :type id: string :rtype: list of dictionaries. ''' model = context['mode...
def resource_view_list(context: Context, data_dict: DataDict) -> ActionResult.ResourceViewList:
''' Return the list of resource views for a particular resource. :param id: the id of the resource :type id: string :rtype: list of dictionaries. ''' model = context['model'] id = _get_or_bust(data_dict, 'id') resource = model.Resource.get(id) if not resource: raise Not...
: raise NotFound context['resource'] = resource _check_access('resource_view_show', context, data_dict) return model_dictize.resource_view_dictize(resource_view, context) def resource_view_list(context: Context, data_dict: DataDict) -> ActionResult.ResourceViewList:
64
64
207
22
42
salsadigitalauorg/ckan
ckan/logic/action/get.py
Python
resource_view_list
resource_view_list
1,142
1,166
1,142
1,143
798192c9eac956e2ae1556778f285127988b56a0
bigcode/the-stack
train
4d90f1a04ebf7a71b4958a86
train
function
def package_collaborator_list(context: Context, data_dict: DataDict) -> ActionResult.PackageCollaboratorList: '''Return the list of all collaborators for a given package. Currently you must be an Admin on the package owner organization to manage collaborators. Note: This ...
def package_collaborator_list(context: Context, data_dict: DataDict) -> ActionResult.PackageCollaboratorList:
'''Return the list of all collaborators for a given package. Currently you must be an Admin on the package owner organization to manage collaborators. Note: This action requires the collaborators feature to be enabled with the :ref:`ckan.auth.allow_dataset_collaborators` configuration option. ...
if obj_type: q = q.filter(model.Member.table_name == obj_type) if capacity: q = q.filter(model.Member.capacity == capacity) trans = authz.roles_trans() def translated_capacity(capacity: str): try: return trans[capacity] except KeyError: return ca...
116
117
392
25
91
salsadigitalauorg/ckan
ckan/logic/action/get.py
Python
package_collaborator_list
package_collaborator_list
206
258
206
207
d04daa508c18ee1063c130389c3824ced67f7636
bigcode/the-stack
train
2f4f842d6611b14a0c743d81
train
function
@logic.validate(ckan.logic.schema.default_follow_user_schema) def followee_list( context: Context, data_dict: DataDict) -> ActionResult.FolloweeList: '''Return the list of objects that are followed by the given user. Returns all objects, of any type, that the given user is following (e.g. followed ...
@logic.validate(ckan.logic.schema.default_follow_user_schema) def followee_list( context: Context, data_dict: DataDict) -> ActionResult.FolloweeList:
'''Return the list of objects that are followed by the given user. Returns all objects, of any type, that the given user is following (e.g. followed users, followed datasets, followed groups.. ). :param id: the id of the user :type id: string :param q: a query string to limit results by, only...
eeCount: '''Return the number of datasets that are followed by the given user. :param id: the id of the user :type id: string :rtype: int ''' return _followee_count( context, data_dict, context['model'].UserFollowingDataset) def group_followee_count( context: Context...
192
192
643
37
155
salsadigitalauorg/ckan
ckan/logic/action/get.py
Python
followee_list
followee_list
2,813
2,876
2,813
2,815
c5e9253a9323790f697fe333d09a56346e379c14
bigcode/the-stack
train
fdf7bff4c39d26390f7f20e0
train
function
def user_followee_list( context: Context, data_dict: DataDict) -> ActionResult.UserFolloweeList: '''Return the list of users that are followed by the given user. :param id: the id of the user :type id: string :rtype: list of dictionaries ''' _check_access('user_followee_list',...
def user_followee_list( context: Context, data_dict: DataDict) -> ActionResult.UserFolloweeList:
'''Return the list of users that are followed by the given user. :param id: the id of the user :type id: string :rtype: list of dictionaries ''' _check_access('user_followee_list', context, data_dict) if not context.get('skip_validation'): schema = context.get('schema') or ( ...
ee_dicts: if followee_dict['display_name'].strip().lower().startswith(q): matching_followee_dicts.append(followee_dict) followee_dicts = matching_followee_dicts return followee_dicts def user_followee_list( context: Context, data_dict: DataDict) -> ActionResult.U...
77
77
258
26
50
salsadigitalauorg/ckan
ckan/logic/action/get.py
Python
user_followee_list
user_followee_list
2,879
2,909
2,879
2,881
a1c8e64f4321fa8a62b3e322fa20c59446b127fa
bigcode/the-stack
train
e6de46d9ed314ccf52f1bd5a
train
function
def am_following_user(context: Context, data_dict: DataDict) -> ActionResult.AmFollowingUser: '''Return ``True`` if you're following the given user, ``False`` if not. :param id: the id or name of the user :type id: string :rtype: bool ''' return _am_following( co...
def am_following_user(context: Context, data_dict: DataDict) -> ActionResult.AmFollowingUser:
'''Return ``True`` if you're following the given user, ``False`` if not. :param id: the id or name of the user :type id: string :rtype: bool ''' return _am_following( context, data_dict, ckan.logic.schema.default_follow_user_schema(), context['model'].UserFollowingUser...
if not userobj: raise NotAuthorized object_id: Optional[str] = data_dict.get('id') return FollowerClass.is_following(userobj.id, object_id) def am_following_user(context: Context, data_dict: DataDict) -> ActionResult.AmFollowingUser:
64
64
103
24
40
salsadigitalauorg/ckan
ckan/logic/action/get.py
Python
am_following_user
am_following_user
2,675
2,688
2,675
2,676
4d4c252a162ba94eddda4726dba2efb01bbe4773
bigcode/the-stack
train
69533fce1a6e5e377e6b3292
train
function
def _follower_count( context: Context, data_dict: DataDict, default_schema: Schema, ModelClass: Type["ModelFollowingModel[Any, Any]"]): schema = context.get('schema', default_schema) data_dict, errors = _validate(data_dict, schema, context) if errors: raise ValidationError(errors) ...
def _follower_count( context: Context, data_dict: DataDict, default_schema: Schema, ModelClass: Type["ModelFollowingModel[Any, Any]"]):
schema = context.get('schema', default_schema) data_dict, errors = _validate(data_dict, schema, context) if errors: raise ValidationError(errors) return ModelClass.follower_count(data_dict['id'])
"') % vocab_id) vocabulary_dict = model_dictize.vocabulary_dictize(vocabulary, context) return vocabulary_dict def _follower_count( context: Context, data_dict: DataDict, default_schema: Schema, ModelClass: Type["ModelFollowingModel[Any, Any]"]):
64
64
85
37
26
salsadigitalauorg/ckan
ckan/logic/action/get.py
Python
_follower_count
_follower_count
2,486
2,493
2,486
2,488
104a9c7f2020d3026c99aae50bcfcc1e897d2165
bigcode/the-stack
train
65899e595b7b4f9fc755e5e2
train
function
@logic.validate(ckan.logic.schema.default_autocomplete_schema) def user_autocomplete(context: Context, data_dict: DataDict) -> ActionResult.UserAutocomplete: '''Return a list of user names that contain a string. :param q: the string to search for :type q: string :param limit: the maximum number of user...
@logic.validate(ckan.logic.schema.default_autocomplete_schema) def user_autocomplete(context: Context, data_dict: DataDict) -> ActionResult.UserAutocomplete:
'''Return a list of user names that contain a string. :param q: the string to search for :type q: string :param limit: the maximum number of user names to return (optional, default: ``20``) :type limit: int :rtype: a list of user dictionaries each with keys ``'name'``, ``'fulln...
types .filter(model.Resource.format.ilike(like_q)) # type: ignore .group_by(model.Resource.format) .order_by(text('total DESC')) .limit(limit)) return [resource.format.lower() for resource in query] @logic.validate(ckan.logic.schema.default_autocomplete_schema) def user_autocomple...
87
87
292
33
54
salsadigitalauorg/ckan
ckan/logic/action/get.py
Python
user_autocomplete
user_autocomplete
1,606
1,645
1,606
1,607
e49f22da8cf1a1212eb327ec487c1cf98d50a71d
bigcode/the-stack
train