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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c7896aabb412999e7a713769 | train | class | class ExpirationPolicy(proto.Message):
r"""A policy that specifies the conditions for resource
expiration (i.e., automatic resource deletion).
Attributes:
ttl (google.protobuf.duration_pb2.Duration):
Specifies the "time-to-live" duration for an associated
resource. The resou... | class ExpirationPolicy(proto.Message):
| r"""A policy that specifies the conditions for resource
expiration (i.e., automatic resource deletion).
Attributes:
ttl (google.protobuf.duration_pb2.Duration):
Specifies the "time-to-live" duration for an associated
resource. The resource expires if it is not active for a
... | honored on a best effort basis.
If this parameter is 0, a default value of 5 is used.
"""
dead_letter_topic = proto.Field(proto.STRING, number=1,)
max_delivery_attempts = proto.Field(proto.INT32, number=2,)
class ExpirationPolicy(proto.Message):
| 63 | 64 | 156 | 7 | 56 | huydinhle/python-pubsub | google/pubsub_v1/types/pubsub.py | Python | ExpirationPolicy | ExpirationPolicy | 674 | 689 | 674 | 674 | 7dd465960553aa2e94e2a7aa11232d0982f1c73f | bigcode/the-stack | train |
a484148102f2ab40d5988361 | train | class | class ModifyPushConfigRequest(proto.Message):
r"""Request for the ModifyPushConfig method.
Attributes:
subscription (str):
Required. The name of the subscription. Format is
``projects/{project}/subscriptions/{sub}``.
push_config (google.pubsub_v1.types.PushConfig):
... | class ModifyPushConfigRequest(proto.Message):
| r"""Request for the ModifyPushConfig method.
Attributes:
subscription (str):
Required. The name of the subscription. Format is
``projects/{project}/subscriptions/{sub}``.
push_config (google.pubsub_v1.types.PushConfig):
Required. The push configuration for fu... | ):
r"""Request for the DeleteSubscription method.
Attributes:
subscription (str):
Required. The subscription to delete. Format is
``projects/{project}/subscriptions/{sub}``.
"""
subscription = proto.Field(proto.STRING, number=1,)
class ModifyPushConfigRequest(proto.Mess... | 63 | 64 | 162 | 8 | 55 | huydinhle/python-pubsub | google/pubsub_v1/types/pubsub.py | Python | ModifyPushConfigRequest | ModifyPushConfigRequest | 895 | 913 | 895 | 895 | 61a473c020e22780ac90c6732394ef8c5bb8db06 | bigcode/the-stack | train |
8bb6f758527feba9d4bc7a44 | train | class | class ListTopicSubscriptionsResponse(proto.Message):
r"""Response for the ``ListTopicSubscriptions`` method.
Attributes:
subscriptions (Sequence[str]):
The names of subscriptions attached to the
topic specified in the request.
next_page_token (str):
If not em... | class ListTopicSubscriptionsResponse(proto.Message):
| r"""Response for the ``ListTopicSubscriptions`` method.
Attributes:
subscriptions (Sequence[str]):
The names of subscriptions attached to the
topic specified in the request.
next_page_token (str):
If not empty, indicates that there may be more subscriptions
... | and
that the system should return the next page of data.
"""
topic = proto.Field(proto.STRING, number=1,)
page_size = proto.Field(proto.INT32, number=2,)
page_token = proto.Field(proto.STRING, number=3,)
class ListTopicSubscriptionsResponse(proto.Message):
| 63 | 64 | 137 | 8 | 55 | huydinhle/python-pubsub | google/pubsub_v1/types/pubsub.py | Python | ListTopicSubscriptionsResponse | ListTopicSubscriptionsResponse | 351 | 369 | 351 | 351 | 543a1a6ddb170e86f8c2d39c42b384d44b81a5fb | bigcode/the-stack | train |
10e3ed1ff9ad9976e9de5e44 | train | class | class ReceivedMessage(proto.Message):
r"""A message and its corresponding acknowledgment ID.
Attributes:
ack_id (str):
This ID can be used to acknowledge the
received message.
message (google.pubsub_v1.types.PubsubMessage):
The message.
delivery_attem... | class ReceivedMessage(proto.Message):
| r"""A message and its corresponding acknowledgment ID.
Attributes:
ack_id (str):
This ID can be used to acknowledge the
received message.
message (google.pubsub_v1.types.PubsubMessage):
The message.
delivery_attempt (int):
The approximate ... | .Field(proto.STRING, number=1,)
audience = proto.Field(proto.STRING, number=2,)
push_endpoint = proto.Field(proto.STRING, number=1,)
attributes = proto.MapField(proto.STRING, proto.STRING, number=2,)
oidc_token = proto.Field(
proto.MESSAGE, number=3, oneof="authentication_method", message=O... | 86 | 86 | 288 | 6 | 80 | huydinhle/python-pubsub | google/pubsub_v1/types/pubsub.py | Python | ReceivedMessage | ReceivedMessage | 775 | 807 | 775 | 775 | 2b2adab0435650514ad570228102e6edace373c1 | bigcode/the-stack | train |
1599b222e493f554d30d009d | train | class | class Snapshot(proto.Message):
r"""A snapshot resource. Snapshots are used in
`Seek <https://cloud.google.com/pubsub/docs/replay-overview>`__
operations, which allow you to manage message acknowledgments in
bulk. That is, you can set the acknowledgment state of messages in
an existing subscription t... | class Snapshot(proto.Message):
| r"""A snapshot resource. Snapshots are used in
`Seek <https://cloud.google.com/pubsub/docs/replay-overview>`__
operations, which allow you to manage message acknowledgments in
bulk. That is, you can set the acknowledgment state of messages in
an existing subscription to the state captured by a snaps... | Request for the UpdateSnapshot method.
Attributes:
snapshot (google.pubsub_v1.types.Snapshot):
Required. The updated snapshot object.
update_mask (google.protobuf.field_mask_pb2.FieldMask):
Required. Indicates which fields in the
provided snapshot to update. Must... | 117 | 117 | 390 | 5 | 112 | huydinhle/python-pubsub | google/pubsub_v1/types/pubsub.py | Python | Snapshot | Snapshot | 1,183 | 1,218 | 1,183 | 1,183 | 639f13b8532e7e1a5c86c25709ab1c6e7a9d2645 | bigcode/the-stack | train |
9f76e8d43f66c8f7f3973ba3 | train | class | class ListTopicsRequest(proto.Message):
r"""Request for the ``ListTopics`` method.
Attributes:
project (str):
Required. The name of the project in which to list topics.
Format is ``projects/{project-id}``.
page_size (int):
Maximum number of topics to return.
... | class ListTopicsRequest(proto.Message):
| r"""Request for the ``ListTopics`` method.
Attributes:
project (str):
Required. The name of the project in which to list topics.
Format is ``projects/{project-id}``.
page_size (int):
Maximum number of topics to return.
page_token (str):
Th... | ]):
The server-assigned ID of each published
message, in the same order as the messages in
the request. IDs are guaranteed to be unique
within the topic.
"""
message_ids = proto.RepeatedField(proto.STRING, number=1,)
class ListTopicsRequest(proto.Message):
| 63 | 64 | 157 | 7 | 56 | huydinhle/python-pubsub | google/pubsub_v1/types/pubsub.py | Python | ListTopicsRequest | ListTopicsRequest | 287 | 305 | 287 | 287 | da2029d5bb4adef21e3bc39638225b940ee379b1 | bigcode/the-stack | train |
46373bea64ae99a74eb474a7 | train | class | class Subscription(proto.Message):
r"""A subscription resource.
Attributes:
name (str):
Required. The name of the subscription. It must have the
format
``"projects/{project}/subscriptions/{subscription}"``.
``{subscription}`` must start with a letter, and... | class Subscription(proto.Message):
| r"""A subscription resource.
Attributes:
name (str):
Required. The name of the subscription. It must have the
format
``"projects/{project}/subscriptions/{subscription}"``.
``{subscription}`` must start with a letter, and contain
only letters (... | .
next_page_token (str):
If not empty, indicates that there may be more snapshots
that match the request; this value should be passed in a new
``ListTopicSnapshotsRequest`` to get more snapshots.
"""
@property
def raw_page(self):
return self
snapshot... | 255 | 256 | 1,677 | 5 | 250 | huydinhle/python-pubsub | google/pubsub_v1/types/pubsub.py | Python | Subscription | Subscription | 445 | 593 | 445 | 445 | f5a9dea4dfa8bc8816e389e833c60bcc424ea2cd | bigcode/the-stack | train |
f1837212ee013fab03870511 | train | class | class ListTopicsResponse(proto.Message):
r"""Response for the ``ListTopics`` method.
Attributes:
topics (Sequence[google.pubsub_v1.types.Topic]):
The resulting topics.
next_page_token (str):
If not empty, indicates that there may be more topics that
match the... | class ListTopicsResponse(proto.Message):
| r"""Response for the ``ListTopics`` method.
Attributes:
topics (Sequence[google.pubsub_v1.types.Topic]):
The resulting topics.
next_page_token (str):
If not empty, indicates that there may be more topics that
match the request; this value should be passed in ... | , and that the system should return the
next page of data.
"""
project = proto.Field(proto.STRING, number=1,)
page_size = proto.Field(proto.INT32, number=2,)
page_token = proto.Field(proto.STRING, number=3,)
class ListTopicsResponse(proto.Message):
| 63 | 64 | 131 | 7 | 56 | huydinhle/python-pubsub | google/pubsub_v1/types/pubsub.py | Python | ListTopicsResponse | ListTopicsResponse | 308 | 325 | 308 | 308 | 9cc819f7efa3c6cc3813d8abb6988ddf05b6ca8a | bigcode/the-stack | train |
5d00cb59c33add025a7b6990 | train | class | class AcknowledgeRequest(proto.Message):
r"""Request for the Acknowledge method.
Attributes:
subscription (str):
Required. The subscription whose message is being
acknowledged. Format is
``projects/{project}/subscriptions/{sub}``.
ack_ids (Sequence[str]):
... | class AcknowledgeRequest(proto.Message):
| r"""Request for the Acknowledge method.
Attributes:
subscription (str):
Required. The subscription whose message is being
acknowledged. Format is
``projects/{project}/subscriptions/{sub}``.
ack_ids (Sequence[str]):
Required. The acknowledgment ID ... | is 600
seconds (10 minutes).
"""
subscription = proto.Field(proto.STRING, number=1,)
ack_ids = proto.RepeatedField(proto.STRING, number=4,)
ack_deadline_seconds = proto.Field(proto.INT32, number=3,)
class AcknowledgeRequest(proto.Message):
| 63 | 64 | 125 | 8 | 55 | huydinhle/python-pubsub | google/pubsub_v1/types/pubsub.py | Python | AcknowledgeRequest | AcknowledgeRequest | 989 | 1,004 | 989 | 989 | de57f814be699427a0d6e4bedcc7bfb3be649469 | bigcode/the-stack | train |
cf8e071424e2282d03bf34f5 | train | class | class ListSnapshotsRequest(proto.Message):
r"""Request for the ``ListSnapshots`` method.
Attributes:
project (str):
Required. The name of the project in which to list
snapshots. Format is ``projects/{project-id}``.
page_size (int):
Maximum number of snapshots... | class ListSnapshotsRequest(proto.Message):
| r"""Request for the ``ListSnapshots`` method.
Attributes:
project (str):
Required. The name of the project in which to list
snapshots. Format is ``projects/{project-id}``.
page_size (int):
Maximum number of snapshots to return.
page_token (str):
... | """Request for the GetSnapshot method.
Attributes:
snapshot (str):
Required. The name of the snapshot to get. Format is
``projects/{project}/snapshots/{snap}``.
"""
snapshot = proto.Field(proto.STRING, number=1,)
class ListSnapshotsRequest(proto.Message):
| 63 | 64 | 158 | 7 | 56 | huydinhle/python-pubsub | google/pubsub_v1/types/pubsub.py | Python | ListSnapshotsRequest | ListSnapshotsRequest | 1,233 | 1,251 | 1,233 | 1,233 | 193e4f5fb5d6ae2bfe026db90d8f67a0e03dd94a | bigcode/the-stack | train |
04b3b9b3ef3a8c7c702f91a7 | train | class | class UpdateSnapshotRequest(proto.Message):
r"""Request for the UpdateSnapshot method.
Attributes:
snapshot (google.pubsub_v1.types.Snapshot):
Required. The updated snapshot object.
update_mask (google.protobuf.field_mask_pb2.FieldMask):
Required. Indicates which fields ... | class UpdateSnapshotRequest(proto.Message):
| r"""Request for the UpdateSnapshot method.
Attributes:
snapshot (google.pubsub_v1.types.Snapshot):
Required. The updated snapshot object.
update_mask (google.protobuf.field_mask_pb2.FieldMask):
Required. Indicates which fields in the
provided snapshot to upda... | /pubsub/docs/labels">
Creating and managing labels</a>.
"""
name = proto.Field(proto.STRING, number=1,)
subscription = proto.Field(proto.STRING, number=2,)
labels = proto.MapField(proto.STRING, proto.STRING, number=3,)
class UpdateSnapshotRequest(proto.Message):
| 63 | 64 | 122 | 7 | 56 | huydinhle/python-pubsub | google/pubsub_v1/types/pubsub.py | Python | UpdateSnapshotRequest | UpdateSnapshotRequest | 1,165 | 1,180 | 1,165 | 1,165 | e5514aab472e974d53e2c6a4410d7ce8a915f282 | bigcode/the-stack | train |
f1580055cc66fc2bb1539731 | train | class | class ListSubscriptionsRequest(proto.Message):
r"""Request for the ``ListSubscriptions`` method.
Attributes:
project (str):
Required. The name of the project in which to list
subscriptions. Format is ``projects/{project-id}``.
page_size (int):
Maximum number ... | class ListSubscriptionsRequest(proto.Message):
| r"""Request for the ``ListSubscriptions`` method.
Attributes:
project (str):
Required. The name of the project in which to list
subscriptions. Format is ``projects/{project-id}``.
page_size (int):
Maximum number of subscriptions to return.
page_token ... | to update. Must be
specified and non-empty.
"""
subscription = proto.Field(proto.MESSAGE, number=1, message="Subscription",)
update_mask = proto.Field(
proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask,
)
class ListSubscriptionsRequest(proto.Message):
| 64 | 64 | 159 | 7 | 57 | huydinhle/python-pubsub | google/pubsub_v1/types/pubsub.py | Python | ListSubscriptionsRequest | ListSubscriptionsRequest | 840 | 858 | 840 | 840 | 8b83049ffa37a400c499537279c725b975ddb04c | bigcode/the-stack | train |
617c86c7ce29ab4d9436c525 | train | class | class DeleteSnapshotRequest(proto.Message):
r"""Request for the ``DeleteSnapshot`` method.
Attributes:
snapshot (str):
Required. The name of the snapshot to delete. Format is
``projects/{project}/snapshots/{snap}``.
"""
snapshot = proto.Field(proto.STRING, number=1,)
| class DeleteSnapshotRequest(proto.Message):
| r"""Request for the ``DeleteSnapshot`` method.
Attributes:
snapshot (str):
Required. The name of the snapshot to delete. Format is
``projects/{project}/snapshots/{snap}``.
"""
snapshot = proto.Field(proto.STRING, number=1,)
| ``ListSnapshotsRequest``.
"""
@property
def raw_page(self):
return self
snapshots = proto.RepeatedField(proto.MESSAGE, number=1, message="Snapshot",)
next_page_token = proto.Field(proto.STRING, number=2,)
class DeleteSnapshotRequest(proto.Message):
| 63 | 64 | 67 | 7 | 56 | huydinhle/python-pubsub | google/pubsub_v1/types/pubsub.py | Python | DeleteSnapshotRequest | DeleteSnapshotRequest | 1,274 | 1,283 | 1,274 | 1,274 | 9c0bc9e7087f5c9d21df072cc85ad15d94852a31 | bigcode/the-stack | train |
56ba675e52fa7728af51352e | train | class | class Topic(proto.Message):
r"""A topic resource.
Attributes:
name (str):
Required. The name of the topic. It must have the format
``"projects/{project}/topics/{topic}"``. ``{topic}`` must
start with a letter, and contain only letters
(``[A-Za-z]``), numb... | class Topic(proto.Message):
| r"""A topic resource.
Attributes:
name (str):
Required. The name of the topic. It must have the format
``"projects/{project}/topics/{topic}"``. ``{topic}`` must
start with a letter, and contain only letters
(``[A-Za-z]``), numbers (``[0-9]``), dashes (``-... | for
storage in one of the allowed regions. An empty
list means that no regions are allowed, and is
not a valid configuration.
"""
allowed_persistence_regions = proto.RepeatedField(proto.STRING, number=1,)
class SchemaSettings(proto.Message):
r"""Settings for validatin... | 194 | 195 | 652 | 5 | 189 | huydinhle/python-pubsub | google/pubsub_v1/types/pubsub.py | Python | Topic | Topic | 112 | 170 | 112 | 112 | 8620809b3cf5fc066e21230cc7216697bcd1d28f | bigcode/the-stack | train |
869efcb740d015767769925b | train | class | class ListSnapshotsResponse(proto.Message):
r"""Response for the ``ListSnapshots`` method.
Attributes:
snapshots (Sequence[google.pubsub_v1.types.Snapshot]):
The resulting snapshots.
next_page_token (str):
If not empty, indicates that there may be more snapshot that
... | class ListSnapshotsResponse(proto.Message):
| r"""Response for the ``ListSnapshots`` method.
Attributes:
snapshots (Sequence[google.pubsub_v1.types.Snapshot]):
The resulting snapshots.
next_page_token (str):
If not empty, indicates that there may be more snapshot that
match the request; this value should... | , and that the system should return
the next page of data.
"""
project = proto.Field(proto.STRING, number=1,)
page_size = proto.Field(proto.INT32, number=2,)
page_token = proto.Field(proto.STRING, number=3,)
class ListSnapshotsResponse(proto.Message):
| 63 | 64 | 132 | 7 | 56 | huydinhle/python-pubsub | google/pubsub_v1/types/pubsub.py | Python | ListSnapshotsResponse | ListSnapshotsResponse | 1,254 | 1,271 | 1,254 | 1,254 | aa5cb7363b067078f2d5e6f614109b4d9bf73a8f | bigcode/the-stack | train |
80f049317d28c5c8702b3a1d | train | class | class ModifyAckDeadlineRequest(proto.Message):
r"""Request for the ModifyAckDeadline method.
Attributes:
subscription (str):
Required. The name of the subscription. Format is
``projects/{project}/subscriptions/{sub}``.
ack_ids (Sequence[str]):
Required. List ... | class ModifyAckDeadlineRequest(proto.Message):
| r"""Request for the ModifyAckDeadline method.
Attributes:
subscription (str):
Required. The name of the subscription. Format is
``projects/{project}/subscriptions/{sub}``.
ack_ids (Sequence[str]):
Required. List of acknowledgment IDs.
ack_deadline_sec... | For JSON, the
response can be entirely empty. The Pub/Sub system may
return fewer than the ``maxMessages`` requested even if
there are more messages available in the backlog.
"""
received_messages = proto.RepeatedField(
proto.MESSAGE, number=1, message="ReceivedMess... | 75 | 75 | 250 | 8 | 67 | huydinhle/python-pubsub | google/pubsub_v1/types/pubsub.py | Python | ModifyAckDeadlineRequest | ModifyAckDeadlineRequest | 962 | 986 | 962 | 962 | a0a35fe14c255ab4434359f3a39d28cf8f97aed9 | bigcode/the-stack | train |
62b7575410a4c62a948610e5 | train | class | class PullRequest(proto.Message):
r"""Request for the ``Pull`` method.
Attributes:
subscription (str):
Required. The subscription from which messages should be
pulled. Format is
``projects/{project}/subscriptions/{sub}``.
return_immediately (bool):
... | class PullRequest(proto.Message):
| r"""Request for the ``Pull`` method.
Attributes:
subscription (str):
Required. The subscription from which messages should be
pulled. Format is
``projects/{project}/subscriptions/{sub}``.
return_immediately (bool):
Optional. If this field set to t... | the given subscription and
allow messages to be pulled and acknowledged - effectively
pausing the subscription if ``Pull`` or ``StreamingPull`` is
not called.
"""
subscription = proto.Field(proto.STRING, number=1,)
push_config = proto.Field(proto.MESSAGE, number=2, mess... | 75 | 75 | 253 | 6 | 69 | huydinhle/python-pubsub | google/pubsub_v1/types/pubsub.py | Python | PullRequest | PullRequest | 916 | 942 | 916 | 916 | 4d6da4b481db8cf4f8ded5e939663c99955232db | bigcode/the-stack | train |
ff13680bc207c902c601dea4 | train | class | class PushConfig(proto.Message):
r"""Configuration for a push delivery endpoint.
.. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields
Attributes:
push_endpoint (str):
A URL locating the endpoint to which messages should be
... | class PushConfig(proto.Message):
| r"""Configuration for a push delivery endpoint.
.. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields
Attributes:
push_endpoint (str):
A URL locating the endpoint to which messages should be
pushed. For example, a Webhook... |
ack_deadlines.
This field will be honored on a best effort basis.
If this parameter is 0, a default value of 5 is used.
"""
dead_letter_topic = proto.Field(proto.STRING, number=1,)
max_delivery_attempts = proto.Field(proto.INT32, number=2,)
class ExpirationPolicy(pr... | 230 | 231 | 772 | 6 | 224 | huydinhle/python-pubsub | google/pubsub_v1/types/pubsub.py | Python | PushConfig | PushConfig | 692 | 772 | 692 | 692 | a9ff4fcb0a7a5321870e38a46b7b4c76cdd0e3b8 | bigcode/the-stack | train |
067c84b0e060d9c02ef86789 | train | class | class TestParseProxyString(unittest.TestCase):
def test_none(self):
self.assertIsNone(parse_proxy_string(None))
def test_malformed_url(self):
with self.assertRaises(TelegramProxyError):
parse_proxy_string('foo')
def test_mtproxy(self):
s = parse_proxy_string('mtproxy://... | class TestParseProxyString(unittest.TestCase):
| def test_none(self):
self.assertIsNone(parse_proxy_string(None))
def test_malformed_url(self):
with self.assertRaises(TelegramProxyError):
parse_proxy_string('foo')
def test_mtproxy(self):
s = parse_proxy_string('mtproxy://secret@foo:123')
self.assertEqual(s, ('... | ):
return True
class TestPhoneMatch(unittest.TestCase):
def test_not_valid_phone(self):
with self.assertRaises(ValueError):
phone_match('foo')
def test_number(self):
number = '+34612345678'
self.assertEqual(phone_match(number), number)
class TestParseProxyString(un... | 69 | 69 | 231 | 9 | 60 | Khairulikhsn/XnUpload | tests/test_client.py | Python | TestParseProxyString | TestParseProxyString | 35 | 60 | 35 | 35 | eee62373bdfe6d64430fd738a7b8a4409fdedf50 | bigcode/the-stack | train |
9e43f25f240f2ae0cc69c936 | train | class | class TestClient(unittest.TestCase):
@patch('builtins.open', mock_open(read_data=json.dumps(CONFIG_DATA)))
@patch('xnup.client.TelegramClient.__init__')
def setUp(self, m1) -> None:
self.upload_file_path = os.path.abspath(os.path.join(directory, 'logo.png'))
self.client = Client('foo.json')
... | class TestClient(unittest.TestCase):
@patch('builtins.open', mock_open(read_data=json.dumps(CONFIG_DATA)))
@patch('xnup.client.TelegramClient.__init__')
| def setUp(self, m1) -> None:
self.upload_file_path = os.path.abspath(os.path.join(directory, 'logo.png'))
self.client = Client('foo.json')
self.client.send_file = Mock()
self.client.send_file.return_value.media.document.size = os.path.getsize(self.upload_file_path)
@patch('xnup.... | def test_unsupported_proxy_type(self):
with self.assertRaises(TelegramProxyError):
parse_proxy_string('foo://user:pass@foo:123')
def test_proxy(self):
self.assertEqual(
parse_proxy_string('http://user:pass@foo:123'),
(socks.HTTP, 'foo', 123, True, 'user', 'pa... | 121 | 121 | 404 | 38 | 83 | Khairulikhsn/XnUpload | tests/test_client.py | Python | TestClient | TestClient | 63 | 105 | 63 | 65 | 424384ecb57c738a7208004007b77792e3a35c60 | bigcode/the-stack | train |
4c977755562d315741c17e1c | train | class | class TestPhoneMatch(unittest.TestCase):
def test_not_valid_phone(self):
with self.assertRaises(ValueError):
phone_match('foo')
def test_number(self):
number = '+34612345678'
self.assertEqual(phone_match(number), number)
| class TestPhoneMatch(unittest.TestCase):
| def test_not_valid_phone(self):
with self.assertRaises(ValueError):
phone_match('foo')
def test_number(self):
number = '+34612345678'
self.assertEqual(phone_match(number), number)
| .abspath(os.path.dirname(__file__)), '../')
class AnyArg(object):
"""https://stackoverflow.com/questions/20428750/pythons-assert-called-with-is-there-a-wildcard-character"""
def __eq__(a, b):
return True
class TestPhoneMatch(unittest.TestCase):
| 64 | 64 | 55 | 8 | 55 | Khairulikhsn/XnUpload | tests/test_client.py | Python | TestPhoneMatch | TestPhoneMatch | 25 | 32 | 25 | 25 | 6fd610c3add9a9667416d6a7507c9236d5f401fa | bigcode/the-stack | train |
06aa71ae53f97a1849e3ea90 | train | class | class AnyArg(object):
"""https://stackoverflow.com/questions/20428750/pythons-assert-called-with-is-there-a-wildcard-character"""
def __eq__(a, b):
return True
| class AnyArg(object):
| """https://stackoverflow.com/questions/20428750/pythons-assert-called-with-is-there-a-wildcard-character"""
def __eq__(a, b):
return True
| TelegramUploadDataLoss, TelegramUploadNoSpaceError, TelegramProxyError, \
MissingFileError
from xnup.files import File
CONFIG_DATA = {'api_hash': '', 'api_id': ''}
directory = os.path.join(os.path.abspath(os.path.dirname(__file__)), '../')
class AnyArg(object):
| 64 | 64 | 46 | 5 | 59 | Khairulikhsn/XnUpload | tests/test_client.py | Python | AnyArg | AnyArg | 19 | 22 | 19 | 19 | 076a851dc6f22576482fc83ee36d380a5a4e6a5f | bigcode/the-stack | train |
d7df3595974770f263ac3c0b | train | class | class Blueprints:
def __init__(self, app=None):
self.app = app
if app:
self.init_app(app)
def init_app(self, app):
app.register_blueprint(auth_bp, url_prefix='/auth')
| class Blueprints:
| def __init__(self, app=None):
self.app = app
if app:
self.init_app(app)
def init_app(self, app):
app.register_blueprint(auth_bp, url_prefix='/auth')
| from app.auth.routes import auth_bp
class Blueprints:
| 12 | 64 | 51 | 4 | 7 | silwalumit/pustakalaya | app/blueprints.py | Python | Blueprints | Blueprints | 4 | 11 | 4 | 4 | 9c5b4bcf279b3d2b76edea2d96e3513b29dc77be | bigcode/the-stack | train |
d2f9ca36777ef32424212572 | train | function | def jac_getenv(name, default=None, type=None, prefix=None):
if prefix is None:
prefix = 'JAC_'
value = os.getenv((prefix + name).upper(), default)
if value is None:
return None
if type is None:
return value
elif type == 'bool':
return str2bool(value)
else:
... | def jac_getenv(name, default=None, type=None, prefix=None):
| if prefix is None:
prefix = 'JAC_'
value = os.getenv((prefix + name).upper(), default)
if value is None:
return None
if type is None:
return value
elif type == 'bool':
return str2bool(value)
else:
return type(value)
| # Distributed under terms of the MIT license.
import os
from jacinle.cli.keyboard import str2bool
from .cache import cached_result
__all__ = ['jac_getenv', 'jac_is_verbose', 'jac_is_debug']
def jac_getenv(name, default=None, type=None, prefix=None):
| 64 | 64 | 85 | 15 | 49 | ashutosh1919/neuro-symbolic-sudoku-solver | third_party/Jacinle/jacinle/utils/env.py | Python | jac_getenv | jac_getenv | 18 | 32 | 18 | 18 | 0cea1e769b605ae25b036616be172bf5c31e259e | bigcode/the-stack | train |
d3b72aafab4362c5d0427d7c | train | function | @cached_result
def jac_is_debug(default='n', prefix=None):
return jac_getenv('debug', default, type='bool', prefix=prefix)
| @cached_result
def jac_is_debug(default='n', prefix=None):
| return jac_getenv('debug', default, type='bool', prefix=prefix)
| ':
return str2bool(value)
else:
return type(value)
@cached_result
def jac_is_verbose(default='n', prefix=None):
return jac_getenv('verbose', default, type='bool', prefix=prefix)
@cached_result
def jac_is_debug(default='n', prefix=None):
| 64 | 64 | 33 | 15 | 49 | ashutosh1919/neuro-symbolic-sudoku-solver | third_party/Jacinle/jacinle/utils/env.py | Python | jac_is_debug | jac_is_debug | 40 | 42 | 40 | 41 | 5b33fa612daae59b31e12f417f79c52ad0d59391 | bigcode/the-stack | train |
4ea3d7d45d43714861f1972a | train | function | @cached_result
def jac_is_verbose(default='n', prefix=None):
return jac_getenv('verbose', default, type='bool', prefix=prefix)
| @cached_result
def jac_is_verbose(default='n', prefix=None):
| return jac_getenv('verbose', default, type='bool', prefix=prefix)
| + name).upper(), default)
if value is None:
return None
if type is None:
return value
elif type == 'bool':
return str2bool(value)
else:
return type(value)
@cached_result
def jac_is_verbose(default='n', prefix=None):
| 64 | 64 | 33 | 15 | 49 | ashutosh1919/neuro-symbolic-sudoku-solver | third_party/Jacinle/jacinle/utils/env.py | Python | jac_is_verbose | jac_is_verbose | 35 | 37 | 35 | 36 | 21c8ea66afc0fd374bc08a6c9c2e24d85471a1a9 | bigcode/the-stack | train |
350d7f7c73f0156c8cd3a225 | train | function | async def main(client, message, params):
files_failed = cfg.reload(debug=True)
if files_failed == 0:
embed = SuccessEmbed('Success', 'All files reloaded')
else:
embed = WarningEmbed('Reloading failed', f'Failed to reload {files_failed} file(s)')
roles = cfg.options["roles_stats"].values... | async def main(client, message, params):
| files_failed = cfg.reload(debug=True)
if files_failed == 0:
embed = SuccessEmbed('Success', 'All files reloaded')
else:
embed = WarningEmbed('Reloading failed', f'Failed to reload {files_failed} file(s)')
roles = cfg.options["roles_stats"].values()
# creates basic table structures ... | , WarningEmbed
from bt_utils.handle_sqlite import DatabaseHandler
SHL = Console('BundestagsBot Reload')
DB = DatabaseHandler()
settings = {
'name': 'reload',
'channels': ['team'],
'mod_cmd': True
}
async def main(client, message, params):
| 64 | 64 | 128 | 9 | 55 | zaanposni/umfrageBot | src/commands/reload.py | Python | main | main | 16 | 31 | 16 | 16 | 75eda653a3185142ce2ecc842d32fbe4f0f6d01e | bigcode/the-stack | train |
6d54f9e304555524750c5218 | train | class | class AppWindow(Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.init_window()
def init_window(self):
self.master.title('RSA Decryptor')
self.pack(fill=BOTH, expand=1)
self.encrypted_message_label = Label(self, tex... | class AppWindow(Frame):
| def __init__(self, master=None):
super().__init__(master)
self.master = master
self.init_window()
def init_window(self):
self.master.title('RSA Decryptor')
self.pack(fill=BOTH, expand=1)
self.encrypted_message_label = Label(self, text='Encrypted Message')
... | import tkinter
from tkinter import *
from rsa_decryption_125 import decryptor
class AppWindow(Frame):
| 22 | 204 | 681 | 5 | 16 | seanballais/rsa-decryption-125 | src/rsa_decryption_125/app.py | Python | AppWindow | AppWindow | 6 | 80 | 6 | 6 | f36fdccf4e0466ad8d6cc881397d0232e62ec89e | bigcode/the-stack | train |
440748337cdb3481410d5dcc | train | function | def main():
root = Tk()
root.geometry('430x350')
root.resizable(False, False)
app = AppWindow(root)
root.mainloop()
| def main():
| root = Tk()
root.geometry('430x350')
root.resizable(False, False)
app = AppWindow(root)
root.mainloop()
| self.encrypted_message_entrybox['state'] = 'normal'
self.n_entrybox['state'] = 'normal'
self.e_entrybox['state'] = 'normal'
self.decrypted_message_box['state'] = 'normal'
def app_exit(self):
exit()
def main():
| 63 | 64 | 35 | 3 | 60 | seanballais/rsa-decryption-125 | src/rsa_decryption_125/app.py | Python | main | main | 83 | 88 | 83 | 83 | 319017485cf0252325929148ba7788e5646ad14c | bigcode/the-stack | train |
b5286bb7be81c7b13d1e4a87 | train | class | class CollateFunc(object):
''' Collate function for AudioDataset
'''
def __init__(self, feat_dim, resample_rate, scale_factor):
self.feat_dim = feat_dim
self.resample_rate = resample_rate
self.scale_factor = scale_factor
pass
def __call__(self, batch):
tsb = time... | class CollateFunc(object):
| ''' Collate function for AudioDataset
'''
def __init__(self, feat_dim, resample_rate, scale_factor):
self.feat_dim = feat_dim
self.resample_rate = resample_rate
self.scale_factor = scale_factor
pass
def __call__(self, batch):
tsb = time.time()
mean_stat =... | #!/usr/bin/env python3
# encoding: utf-8
import sys
import argparse
import json
import codecs
import yaml
import time
import logging
import torch
import torchaudio
import torchaudio.compliance.kaldi as kaldi
from torch.utils.data import Dataset, DataLoader
torchaudio.set_audio_backend("sox_io")
LOG_FORMAT = "%(asc... | 124 | 149 | 499 | 6 | 118 | 8igfive/MyASR | tools/compute_cmvn_stats.py | Python | CollateFunc | CollateFunc | 24 | 74 | 24 | 24 | a3928bd4aa8295bbe138756e246d50ade64bce49 | bigcode/the-stack | train |
18421c006b787698cdb6021b | train | class | class AudioDataset(Dataset):
def __init__(self, data_file):
self.items = []
with codecs.open(data_file, 'r', encoding='utf-8') as f:
for line in f:
arr = line.strip().split()
self.items.append((arr[0], arr[1]))
def __len__(self):
return len(se... | class AudioDataset(Dataset):
| def __init__(self, data_file):
self.items = []
with codecs.open(data_file, 'r', encoding='utf-8') as f:
for line in f:
arr = line.strip().split()
self.items.append((arr[0], arr[1]))
def __len__(self):
return len(self.items)
def __getitem_... | number += mat.shape[0]
# logger.info('complete a item with {} seconds'.format(time.time() - tsi))
# logger.info('complete a batch with {} seconds'.format(time.time() - tsb))
return number, mean_stat, var_stat
class AudioDataset(Dataset):
| 64 | 64 | 95 | 6 | 57 | 8igfive/MyASR | tools/compute_cmvn_stats.py | Python | AudioDataset | AudioDataset | 77 | 89 | 77 | 77 | 17efb416d410b920594b88c829672561f1840292 | bigcode/the-stack | train |
69f73a29d28d6e30f997dcef | train | function | def get_model(args):
if args.first_layer_dense:
args.first_layer_type = "DenseConv"
print("=> Creating model '{}'".format(args.arch))
model = models.__dict__[args.arch]()
# applying sparsity to the network
if (args.conv_type != "DenseConv"):
if args.top_k < 0:
raise Val... | def get_model(args):
| if args.first_layer_dense:
args.first_layer_type = "DenseConv"
print("=> Creating model '{}'".format(args.arch))
model = models.__dict__[args.arch]()
# applying sparsity to the network
if (args.conv_type != "DenseConv"):
if args.top_k < 0:
raise ValueError("Need to set ... | model.load_state_dict(model_state_dict)
else:
print("=> no pretrained weights found at '{}'".format(args.pretrained))
def get_dataset(args):
print(f"=> Getting {args.set} dataset")
dataset = getattr(data, args.set)(args)
return dataset
def get_model(args):
| 64 | 64 | 129 | 5 | 58 | Lopez-Angel/hidden-fold-networks | main.py | Python | get_model | get_model | 312 | 330 | 312 | 312 | dcc71b79762a2f751df45ca91d888b4d6619a32b | bigcode/the-stack | train |
74df063e52744703f054516a | train | function | def resume(args, model, optimizer):
if os.path.isfile(args.resume):
print(f"=> Loading checkpoint '{args.resume}'")
checkpoint = torch.load(args.resume, map_location=f"cuda:{args.multigpu[0]}")
if args.start_epoch is None:
print(f"=> Setting new start epoch at {checkpoint['epoch... | def resume(args, model, optimizer):
| if os.path.isfile(args.resume):
print(f"=> Loading checkpoint '{args.resume}'")
checkpoint = torch.load(args.resume, map_location=f"cuda:{args.multigpu[0]}")
if args.start_epoch is None:
print(f"=> Setting new start epoch at {checkpoint['epoch']}")
args.start_epoch =... | = torch.nn.DataParallel(model, device_ids=args.multigpu).cuda(
args.multigpu[0]
)
if args.seed == None:
cudnn.benchmark = True
else:
cudnn.benchmark = False
return model
def resume(args, model, optimizer):
| 64 | 64 | 154 | 8 | 55 | Lopez-Angel/hidden-fold-networks | main.py | Python | resume | resume | 259 | 278 | 259 | 259 | c868b0b25711018a6b8db2aa69aeb047b9f56cba | bigcode/the-stack | train |
f9a7e0bb61fa6d0971c66d70 | train | function | def pretrained(args, model):
if os.path.isfile(args.pretrained):
print("=> loading pretrained weights from '{}'".format(args.pretrained))
pretrained = torch.load(
args.pretrained,
map_location=torch.device("cuda:{}".format(args.multigpu[0])),
)["state_dict"]
... | def pretrained(args, model):
| if os.path.isfile(args.pretrained):
print("=> loading pretrained weights from '{}'".format(args.pretrained))
pretrained = torch.load(
args.pretrained,
map_location=torch.device("cuda:{}".format(args.multigpu[0])),
)["state_dict"]
model_state_dict = model.stat... | _dict(checkpoint["state_dict"])
optimizer.load_state_dict(checkpoint["optimizer"])
print(f"=> Loaded checkpoint '{args.resume}' (epoch {checkpoint['epoch']})")
return best_acc1
else:
print(f"=> No checkpoint found at '{args.resume}'")
def pretrained(args, model):
| 64 | 64 | 186 | 6 | 58 | Lopez-Angel/hidden-fold-networks | main.py | Python | pretrained | pretrained | 281 | 302 | 281 | 281 | 61bd16159dd3c65f9183ce2858b7a25e294d2618 | bigcode/the-stack | train |
37deb86815f60f991b692ce1 | train | function | def write_result_to_csv(**kwargs):
results = pathlib.Path("runs") / "results.csv"
if not results.exists():
results.write_text(
"Date Finished, "
"Base Config, "
"Name, "
"Top K, "
"Best epoch, "
"Test Top 1, "
"Test Top... | def write_result_to_csv(**kwargs):
| results = pathlib.Path("runs") / "results.csv"
if not results.exists():
results.write_text(
"Date Finished, "
"Base Config, "
"Name, "
"Top K, "
"Best epoch, "
"Test Top 1, "
"Test Top 5, "
"Current Val Top ... | _dir / str(rep_count)
log_base_dir = run_base_dir / "logs"
ckpt_base_dir = run_base_dir / "checkpoints"
if not run_base_dir.exists():
os.makedirs(run_base_dir)
(run_base_dir / "settings.txt").write_text(str(args))
return run_base_dir, ckpt_base_dir, log_base_dir
def write_result_to_csv(*... | 85 | 85 | 285 | 8 | 76 | Lopez-Angel/hidden-fold-networks | main.py | Python | write_result_to_csv | write_result_to_csv | 407 | 446 | 407 | 407 | 51307b481c93aa0ceb8ebbcdf1815cc504835b6d | bigcode/the-stack | train |
9f8d46dba837069073b2ba8c | train | function | def get_dataset(args):
print(f"=> Getting {args.set} dataset")
dataset = getattr(data, args.set)(args)
return dataset
| def get_dataset(args):
| print(f"=> Getting {args.set} dataset")
dataset = getattr(data, args.set)(args)
return dataset
| ()
if (k in model_state_dict and v.size() == model_state_dict[k].size())
}
model_state_dict.update(pretrained)
model.load_state_dict(model_state_dict)
else:
print("=> no pretrained weights found at '{}'".format(args.pretrained))
def get_dataset(args):
| 64 | 64 | 31 | 5 | 59 | Lopez-Angel/hidden-fold-networks | main.py | Python | get_dataset | get_dataset | 305 | 309 | 305 | 305 | 494e58f8a4059d111f6caebf698f5885d3b86f73 | bigcode/the-stack | train |
33bd529c38269d425bd3e4e9 | train | function | def _run_dir_exists(run_base_dir):
log_base_dir = run_base_dir / "logs"
ckpt_base_dir = run_base_dir / "checkpoints"
return log_base_dir.exists() or ckpt_base_dir.exists()
| def _run_dir_exists(run_base_dir):
| log_base_dir = run_base_dir / "logs"
ckpt_base_dir = run_base_dir / "checkpoints"
return log_base_dir.exists() or ckpt_base_dir.exists()
| weight_decay=args.weight_decay,
nesterov=args.nesterov,
)
elif args.optimizer == "adam":
optimizer = torch.optim.Adam(
filter(lambda p: p.requires_grad, model.parameters()), lr=args.lr
)
return optimizer
def _run_dir_exists(run_base_dir):
| 64 | 64 | 49 | 9 | 54 | Lopez-Angel/hidden-fold-networks | main.py | Python | _run_dir_exists | _run_dir_exists | 366 | 370 | 366 | 366 | 74e6904d12c70ace6da64bd014bb62907f21505c | bigcode/the-stack | train |
4a7b70fedd46884364b011db | train | function | def get_trainer(args):
print(f"=> Using trainer from trainers.{args.trainer}")
trainer = importlib.import_module(f"trainers.{args.trainer}")
return trainer.train, trainer.validate, trainer.test, trainer.modifier
| def get_trainer(args):
| print(f"=> Using trainer from trainers.{args.trainer}")
trainer = importlib.import_module(f"trainers.{args.trainer}")
return trainer.train, trainer.validate, trainer.test, trainer.modifier
| ,
)
print(f"Best train acc.:\t{best_acc1:.2f}% valid, {best_train_acc1:.2f}% train @epoch {best_epoch}")
print(f"Test acc.:\t{test_acc1:.2f}%")
def get_trainer(args):
| 63 | 64 | 50 | 6 | 57 | Lopez-Angel/hidden-fold-networks | main.py | Python | get_trainer | get_trainer | 227 | 231 | 227 | 227 | 9a364cd048464a85abc32478580863133a0e0c55 | bigcode/the-stack | train |
2a809eb2134a97746405e87b | train | function | def main():
print(args)
if args.seed is not None:
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
torch.cuda.manual_seed(args.seed)
torch.cuda.m... | def main():
| print(args)
if args.seed is not None:
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
torch.cuda.manual_seed(args.seed)
torch.cuda.manual_seed_a... | .net_utils import (
set_model_top_k,
freeze_model_weights,
save_checkpoint,
get_lr,
LabelSmoothing,
)
from utils.schedulers import get_policy
from utils.profiling import estimate_params_size
from args import args
import importlib
import data
import models
def main():
| 64 | 64 | 88 | 3 | 60 | Lopez-Angel/hidden-fold-networks | main.py | Python | main | main | 46 | 59 | 46 | 46 | e183d69d616c3ddaf8bbec061710e87e80b88342 | bigcode/the-stack | train |
b991be02ba3d1555a5165c68 | train | function | def get_optimizer(args, model):
for n, v in model.named_parameters():
if v.requires_grad:
print("<DEBUG> gradient to", n)
if not v.requires_grad:
print("<DEBUG> no gradient to", n)
if args.optimizer == "sgd":
parameters = list(model.named_parameters())
b... | def get_optimizer(args, model):
| for n, v in model.named_parameters():
if v.requires_grad:
print("<DEBUG> gradient to", n)
if not v.requires_grad:
print("<DEBUG> no gradient to", n)
if args.optimizer == "sgd":
parameters = list(model.named_parameters())
bn_params = [v for n, v in parame... | if args.top_k < 0:
raise ValueError("Need to set a positive top k")
set_model_top_k(model, top_k=args.top_k)
# freezing the weights if we are only doing subnet training
if args.freeze_weights:
freeze_model_weights(model)
return model
def get_optimizer(args, model):
| 71 | 71 | 237 | 7 | 63 | Lopez-Angel/hidden-fold-networks | main.py | Python | get_optimizer | get_optimizer | 333 | 363 | 333 | 333 | 4c375b124963a540a9a9b2db7aa0af49f57a2405 | bigcode/the-stack | train |
f263ae2fb0777a4475b64e99 | train | function | def get_directories(args):
if args.config is None or args.name is None:
raise ValueError("Must have name and config")
config = pathlib.Path(args.config).stem
if args.log_dir is None:
run_base_dir = pathlib.Path(
f"runs/{config}/{args.name}/top_k={args.top_k}"
)
else:... | def get_directories(args):
| if args.config is None or args.name is None:
raise ValueError("Must have name and config")
config = pathlib.Path(args.config).stem
if args.log_dir is None:
run_base_dir = pathlib.Path(
f"runs/{config}/{args.name}/top_k={args.top_k}"
)
else:
run_base_dir = pat... | filter(lambda p: p.requires_grad, model.parameters()), lr=args.lr
)
return optimizer
def _run_dir_exists(run_base_dir):
log_base_dir = run_base_dir / "logs"
ckpt_base_dir = run_base_dir / "checkpoints"
return log_base_dir.exists() or ckpt_base_dir.exists()
def get_directories(arg... | 77 | 77 | 259 | 6 | 71 | Lopez-Angel/hidden-fold-networks | main.py | Python | get_directories | get_directories | 373 | 404 | 373 | 373 | e4997ab6d7b475169bf5739307cea229988e49c4 | bigcode/the-stack | train |
a42f1cbc10be152d51d27154 | train | function | def main_worker(args):
args.gpu = None
train, validate, test, modifier = get_trainer(args)
if args.gpu is not None:
print("Use GPU: {} for training".format(args.gpu))
# create model and optimizer
model = get_model(args)
model = set_gpu(args, model)
if args.pretrained:
pre... | def main_worker(args):
| args.gpu = None
train, validate, test, modifier = get_trainer(args)
if args.gpu is not None:
print("Use GPU: {} for training".format(args.gpu))
# create model and optimizer
model = get_model(args)
model = set_gpu(args, model)
if args.pretrained:
pretrained(args, model)
... | OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import pathlib
import random
import time
from torch.utils.tensorboard import SummaryWriter
import torch
import torch.nn as nn
import torch.nn.parallel
import ... | 256 | 256 | 1,348 | 5 | 251 | Lopez-Angel/hidden-fold-networks | main.py | Python | main_worker | main_worker | 62 | 224 | 62 | 62 | cc1f1d84fa34c7a3a4ba548831682328f7a8a041 | bigcode/the-stack | train |
1a32b24fe675e6137b9dde46 | train | function | def set_gpu(args, model):
assert torch.cuda.is_available(), "CPU-only experiments currently unsupported"
if args.gpu is not None:
torch.cuda.set_device(args.gpu)
model = model.cuda(args.gpu)
elif args.multigpu is None:
device = torch.device("cpu")
else:
# DataParallel wi... | def set_gpu(args, model):
| assert torch.cuda.is_available(), "CPU-only experiments currently unsupported"
if args.gpu is not None:
torch.cuda.set_device(args.gpu)
model = model.cuda(args.gpu)
elif args.multigpu is None:
device = torch.device("cpu")
else:
# DataParallel will divide and allocate bat... | 1:.2f}%")
def get_trainer(args):
print(f"=> Using trainer from trainers.{args.trainer}")
trainer = importlib.import_module(f"trainers.{args.trainer}")
return trainer.train, trainer.validate, trainer.test, trainer.modifier
def set_gpu(args, model):
| 64 | 64 | 181 | 7 | 56 | Lopez-Angel/hidden-fold-networks | main.py | Python | set_gpu | set_gpu | 234 | 256 | 234 | 234 | be9c7919aba6608c8a24a0a8861f815c7d8a2789 | bigcode/the-stack | train |
56dc8d7443fc7fe11ebb2b08 | train | class | class MainWindowError(Exception):
pass
| class MainWindowError(Exception):
| pass
| platform_specific
import dataset.experimental_data
import dataset.budgetary
from core import Core
from gui.progress import Worker, Cancelled
import gui
import gui.about
import gui.simulation
import gui.estimation
import gui.import_csv
log = logging.getLogger(__name__)
class MainWindowError(Exception):
| 64 | 64 | 9 | 6 | 58 | HaoZeke/prest | gui/gui/main_window.py | Python | MainWindowError | MainWindowError | 32 | 33 | 32 | 32 | 4b8cf28bb247b44183e8061614f23e644c034559 | bigcode/the-stack | train |
0a51fee3aaee773ed813c61c | train | class | class MainWindow(QMainWindow, uic.main_window.Ui_MainWindow, gui.ExceptionDialog):
def __init__(self):
# window setup
log.debug('creating GUI')
QMainWindow.__init__(self)
self.setupUi(self)
# icon
self.setWindowIcon(QIcon(platform_specific.get_embedded_file_path(
... | class MainWindow(QMainWindow, uic.main_window.Ui_MainWindow, gui.ExceptionDialog):
| def __init__(self):
# window setup
log.debug('creating GUI')
QMainWindow.__init__(self)
self.setupUi(self)
# icon
self.setWindowIcon(QIcon(platform_specific.get_embedded_file_path(
'images/prest.ico', # deployment
'gui/images/prest.ico', # ... | import sys
import logging
import functools
import os.path
from PyQt5.QtCore import Qt, pyqtSlot
from PyQt5.QtGui import QIcon, QKeySequence
from PyQt5.QtWidgets import QHeaderView, QMainWindow, QDialog, QMessageBox, \
QTableWidgetItem, QFileDialog, QTreeWidgetItem, QProgressDialog, QMenu, QAction, \
QStyle, QS... | 198 | 256 | 3,195 | 19 | 178 | HaoZeke/prest | gui/gui/main_window.py | Python | MainWindow | MainWindow | 35 | 483 | 35 | 35 | bc646feaa35ab52b51a4f8d30a7a70de8c55d128 | bigcode/the-stack | train |
132733883734da7120b827a1 | train | class | class Migration(migrations.Migration):
dependencies = [
('flashcard', '0007_auto_20191105_2034'),
]
operations = [
migrations.AlterField(
model_name='entry',
name='from_example',
field=models.TextField(blank=True, max_length=2000, null=True),
),
... | class Migration(migrations.Migration):
| dependencies = [
('flashcard', '0007_auto_20191105_2034'),
]
operations = [
migrations.AlterField(
model_name='entry',
name='from_example',
field=models.TextField(blank=True, max_length=2000, null=True),
),
]
| # Generated by Django 2.2.4 on 2019-11-20 16:27
from django.db import migrations, models
class Migration(migrations.Migration):
| 38 | 64 | 72 | 7 | 30 | Erfi/dorathewordexplorer | darvag/flashcard/migrations/0008_auto_20191120_1627.py | Python | Migration | Migration | 6 | 18 | 6 | 7 | 8c42f2ae0941023884af3e650501e81a1b0e04d2 | bigcode/the-stack | train |
52d2d88885a64f85b2c652ff | train | class | class TestHouseholder:
def test_householder(self):
vec = [5, 4, 3, 2, 1]
householder = Householder(vec)
householder_mat = householder.to_matrix()
vec_as_mat = Matrix.from_cols([vec])
product = householder_mat.multiply(vec_as_mat)
assert product.num_cols() == 1
... | class TestHouseholder:
| def test_householder(self):
vec = [5, 4, 3, 2, 1]
householder = Householder(vec)
householder_mat = householder.to_matrix()
vec_as_mat = Matrix.from_cols([vec])
product = householder_mat.multiply(vec_as_mat)
assert product.num_cols() == 1
assert product.get(0, ... | from pylinlin.householder import Householder
from pylinlin.matrix import Matrix
import pylinlin.matrix_utils as utils
import pytest
class TestHouseholder:
| 35 | 142 | 475 | 5 | 29 | owenl131/pylinlin | tests/test_householder.py | Python | TestHouseholder | TestHouseholder | 7 | 51 | 7 | 8 | fed61b9b700927beb94aa9b67858737ab5b5a4d1 | bigcode/the-stack | train |
c2c63f4f7389a56f9c3b368b | train | function | def main():
parser = LFCliBase.create_bare_argparse(
prog=__file__,
formatter_class=argparse.RawTextHelpFormatter,
description="""
""")
parser.add_argument('--action', help="command to execute when attenuator changes levels")
parser.add_argument('--action_every_channel', help="When T... | def main():
| parser = LFCliBase.create_bare_argparse(
prog=__file__,
formatter_class=argparse.RawTextHelpFormatter,
description="""
""")
parser.add_argument('--action', help="command to execute when attenuator changes levels")
parser.add_argument('--action_every_channel', help="When True, do an a... | channel=None,
value=None):
if not channel:
raise ValueError("do_cmd not given channel")
if not value:
raise ValueError("do_cmd not given value")
if not self.action:
raise ValueError("do_cmd lost self.action")
pprint.pprint([("channel",... | 81 | 81 | 273 | 3 | 78 | alexman69420/lanforge-scripts | py-scripts/sandbox/attenuator_mon.py | Python | main | main | 167 | 194 | 167 | 167 | e8379ecc14ab4eb4be142c24640db8dcaebb83da | bigcode/the-stack | train |
e07fe60c6e3b4aad12f22d96 | train | class | class AttenuatorMonitor(Realm):
def __init__(self,
host=None,
port=None,
action=None,
action_every_channel=False,
attenuator=None,
interval_sec: float = 1.0,
stop_file=None,
_deep_... | class AttenuatorMonitor(Realm):
| def __init__(self,
host=None,
port=None,
action=None,
action_every_channel=False,
attenuator=None,
interval_sec: float = 1.0,
stop_file=None,
_deep_clean=False,
_d... | #!/usr/bin/env python3
"""
NAME: attenuator_mon.py
PURPOSE: example of a monitoring loop that notices when attenator values change
EXAMPLE:
NOTES:
"""
import sys
if sys.version_info[0] != 3:
print("This script requires Python3")
exit()
sys.path.insert(1, "../../py-json")
import argparse
import importlib
... | 219 | 256 | 967 | 8 | 210 | alexman69420/lanforge-scripts | py-scripts/sandbox/attenuator_mon.py | Python | AttenuatorMonitor | AttenuatorMonitor | 39 | 165 | 39 | 39 | c90603a13ef703d3d4b6a33b394b43b142488b37 | bigcode/the-stack | train |
04cb63997f048595776a138b | train | function | def run():
app.run(host='0.0.0.0', port=8080)
| def run():
| app.run(host='0.0.0.0', port=8080)
| from flask import Flask
from threading import Thread
app = Flask('')
@app.route('/')
def home():
return "SERVER IS RUNNING !!"
def run():
| 33 | 64 | 21 | 3 | 30 | ibpme/IBPME-DiscordBot | keep_alive.py | Python | run | run | 12 | 13 | 12 | 12 | f9f52d1f6f144102fabcb68df894734176cd528c | bigcode/the-stack | train |
9e3c9733b52ecc5620b33802 | train | function | @app.route('/')
def home():
return "SERVER IS RUNNING !!"
| @app.route('/')
def home():
| return "SERVER IS RUNNING !!"
| from flask import Flask
from threading import Thread
app = Flask('')
@app.route('/')
def home():
| 20 | 64 | 15 | 6 | 15 | ibpme/IBPME-DiscordBot | keep_alive.py | Python | home | home | 7 | 9 | 7 | 8 | dbb1a5afb0bf380f6a30711599006567ee716e60 | bigcode/the-stack | train |
c324542a9c0c1521677a0533 | train | function | def keep_alive():
t = Thread(target=run)
t.start()
| def keep_alive():
| t = Thread(target=run)
t.start()
| from flask import Flask
from threading import Thread
app = Flask('')
@app.route('/')
def home():
return "SERVER IS RUNNING !!"
def run():
app.run(host='0.0.0.0', port=8080)
def keep_alive():
| 55 | 64 | 16 | 4 | 51 | ibpme/IBPME-DiscordBot | keep_alive.py | Python | keep_alive | keep_alive | 16 | 18 | 16 | 16 | 8f6c846cd24d4c7a8582b75ccd560c3a74f1c257 | bigcode/the-stack | train |
e2d43ae29b22fcad9bacb547 | train | function | @user_passes_test(lambda u: u.is_superuser)
def attempts(request, getnum=None):
if getnum == None:
getnum = 25
context = {}
context['getnum'] = getnum
context['attempts'] = Attempt.objects.order_by('-pk')[:getnum]
return render(request, "stats/attempts.html", context)
| @user_passes_test(lambda u: u.is_superuser)
def attempts(request, getnum=None):
| if getnum == None:
getnum = 25
context = {}
context['getnum'] = getnum
context['attempts'] = Attempt.objects.order_by('-pk')[:getnum]
return render(request, "stats/attempts.html", context)
| _staff=False)
model = UserProfile
template_name = 'stats/score_list.html'
ordering = ['-score', 'latest_correct_answer']
# attemps should only be visible to superusers
@user_passes_test(lambda u: u.is_superuser)
def attempts(request, getnum=None):
| 64 | 64 | 81 | 21 | 42 | kiloreven/challenge | stats/views.py | Python | attempts | attempts | 19 | 26 | 19 | 20 | 884c2a64c8f08572f95ab8336995ef3369cb13b7 | bigcode/the-stack | train |
2197f3b9be050489ff56c221 | train | class | class ScoreList(ListView):
# queryset = User.objects.filter(is_superuser=False).filter(is_staff=False)
model = UserProfile
template_name = 'stats/score_list.html'
ordering = ['-score', 'latest_correct_answer']
| class ScoreList(ListView):
# queryset = User.objects.filter(is_superuser=False).filter(is_staff=False)
| model = UserProfile
template_name = 'stats/score_list.html'
ordering = ['-score', 'latest_correct_answer']
| _passes_test
from django.shortcuts import render
from django.views.generic import ListView
from core.models import UserProfile
from levels.models import Score, Attempt
# score can be accessed by anyone
class ScoreList(ListView):
# queryset = User.objects.filter(is_superuser=False).filter(is_staff=False)
| 64 | 64 | 52 | 23 | 40 | kiloreven/challenge | stats/views.py | Python | ScoreList | ScoreList | 10 | 15 | 10 | 11 | d2b16ceed9dfc9cdf300f0ddc943c9e25fc0b4ce | bigcode/the-stack | train |
64fe5977c597613f2844e41b | train | class | class NGRAM(FieldType):
"""
Configured field that indexes text as N-grams. For example, with a field type
NGRAM(3,4), the value "hello" will be indexed as tokens
"hel", "hell", "ell", "ello", "llo".
"""
def __init__(self, minsize = 2, maxsize = 4, stored = False):
"""
... | class NGRAM(FieldType):
| """
Configured field that indexes text as N-grams. For example, with a field type
NGRAM(3,4), the value "hello" will be indexed as tokens
"hel", "hell", "ell", "ello", "llo".
"""
def __init__(self, minsize = 2, maxsize = 4, stored = False):
"""
:stored: Whether to st... | if phrase:
formatclass = Positions
else:
formatclass = Frequency
self.format = formatclass(analyzer = ana, field_boost = field_boost)
self.vector = vector
self.scorable = True
self.stored = stored
class NGRAM(FieldType):
| 64 | 64 | 211 | 6 | 57 | tallstreet/Whoosh-AppEngine | src/whoosh/fields.py | Python | NGRAM | NGRAM | 199 | 218 | 199 | 199 | 85b8734ba6668bd8b7f884d1afc47daa1f04f164 | bigcode/the-stack | train |
db57083606874acb38e0c308 | train | class | class Stored(Format):
"""A field that's stored but not indexed."""
analyzer = None
def __init__(self, **options):
self.options = options
def __repr__(self):
return "%s()" % self.__class__.__name__
| class Stored(Format):
| """A field that's stored but not indexed."""
analyzer = None
def __init__(self, **options):
self.options = options
def __repr__(self):
return "%s()" % self.__class__.__name__
| Interprets the given data as 'name', where 'name' is for example
"frequency" or "positions". This object must have a corresponding
.data_to_<name>() method.
"""
return self.interpreter(name)(data)
# Concrete field classes
class Stored(Format):
| 64 | 64 | 57 | 5 | 58 | tallstreet/Whoosh-AppEngine | src/whoosh/fields.py | Python | Stored | Stored | 488 | 497 | 488 | 488 | 752e111ef1d8ca293798d2d9ef08141061d3ebc2 | bigcode/the-stack | train |
34e7d75d996efbf06e675b8c | train | class | class Characters(Format):
"""Stores token position and character start and end information
for each posting.
"""
def word_datas(self, value, start_pos = 0, start_char = 0, **kwargs):
seen = defaultdict(list)
for t in unstopped(self.analyzer(value, positions = True, ... | class Characters(Format):
| """Stores token position and character start and end information
for each posting.
"""
def word_datas(self, value, start_pos = 0, start_char = 0, **kwargs):
seen = defaultdict(list)
for t in unstopped(self.analyzer(value, positions = True, chars = True,
... | _varint
freq = rv()
if freq > 10:
stream.read_ulong()
for _ in xrange(freq):
pos_base += rv()
pos_list.append(pos_base)
return pos_list
def read_weight(self, stream):
rv = stream.read_varint
... | 170 | 171 | 572 | 5 | 164 | tallstreet/Whoosh-AppEngine | src/whoosh/fields.py | Python | Characters | Characters | 685 | 767 | 685 | 685 | 54be0098492da5b75e4ddd6b6fd978215f502a88 | bigcode/the-stack | train |
b4284e3e433f57cb2fce4a1e | train | class | class DocBoosts(Frequency):
"""A Field that stores frequency and per-document boost information
for each posting.
"""
def word_datas(self, value, doc_boost = 1.0, **kwargs):
seen = defaultdict(int)
for t in unstopped(self.analyzer(value)):
seen[t.text] += 1
... | class DocBoosts(Frequency):
| """A Field that stores frequency and per-document boost information
for each posting.
"""
def word_datas(self, value, doc_boost = 1.0, **kwargs):
seen = defaultdict(int)
for t in unstopped(self.analyzer(value)):
seen[t.text] += 1
return ((w, fre... | _varint()
def read_weight(self, stream):
return stream.read_varint() * self.field_boost
def data_to_frequency(self, data):
return data
def data_to_weight(self, data):
return data * self.field_boost
class DocBoosts(Frequency):
| 63 | 64 | 202 | 7 | 55 | tallstreet/Whoosh-AppEngine | src/whoosh/fields.py | Python | DocBoosts | DocBoosts | 586 | 610 | 586 | 586 | 4bdd78631f8db3e202698de91e91cb60bdd44c53 | bigcode/the-stack | train |
388392b25481091f58c1841b | train | class | class STORED(FieldType):
"""
Configured field type for fields you want to store but not index.
"""
def __init__(self):
self.format = Stored()
self.stored = True
| class STORED(FieldType):
| """
Configured field type for fields you want to store but not index.
"""
def __init__(self):
self.format = Stored()
self.stored = True
| unique = False, expression = None):
expression = expression or re.compile(r"[^\r\n\t ,;]+")
analyzer = RegexAnalyzer(expression = expression)
self.format = Existence(analyzer = analyzer)
self.stored = stored
self.unique = unique
class STORED(FieldType):
| 64 | 64 | 46 | 6 | 57 | tallstreet/Whoosh-AppEngine | src/whoosh/fields.py | Python | STORED | STORED | 133 | 140 | 133 | 133 | 87bfa246f8e88c1625946e758c6b852c8a0576b3 | bigcode/the-stack | train |
b9eb613b2147a73efba562fc | train | class | class UnknownFieldError(Exception):
pass
| class UnknownFieldError(Exception):
| pass
|
"""
This module contains functions and classes related to fields.
"""
import re
from collections import defaultdict
from whoosh.analysis import unstopped, IDAnalyzer, RegexAnalyzer, KeywordAnalyzer, StandardAnalyzer, NgramAnalyzer
# Exceptions
class FieldConfigurationError(Exception):
pass
c... | 64 | 64 | 9 | 6 | 57 | tallstreet/Whoosh-AppEngine | src/whoosh/fields.py | Python | UnknownFieldError | UnknownFieldError | 32 | 33 | 32 | 32 | 2ace270693894a9b7eeebf2e85d5d37e4c70f905 | bigcode/the-stack | train |
aa9d77012d265d985bf022d3 | train | class | class PositionBoosts(Format):
"""A format that stores positions and per-position boost information
in each posting.
"""
def word_datas(self, value, start_pos = 0, **kwargs):
seen = defaultdict(iter)
for t in unstopped(self.analyzer(value, positions = True, boosts = True,
... | class PositionBoosts(Format):
| """A format that stores positions and per-position boost information
in each posting.
"""
def word_datas(self, value, start_pos = 0, **kwargs):
seen = defaultdict(iter)
for t in unstopped(self.analyzer(value, positions = True, boosts = True,
... | ()
return freq * self.field_boost
def data_to_frequency(self, data):
return len(data)
def data_to_weight(self, data):
return len(data) * self.field_boost
def data_to_positions(self, data):
return (pos for pos, _, _ in data)
def da... | 100 | 100 | 335 | 7 | 93 | tallstreet/Whoosh-AppEngine | src/whoosh/fields.py | Python | PositionBoosts | PositionBoosts | 770 | 813 | 770 | 770 | 8f08529fb66ff7de7d337dfea190206fcd3309f2 | bigcode/the-stack | train |
4a3f29b2bae920afc47ef66e | train | class | class Positions(Format):
"""A vector that stores position information in each posting, to
allow phrase searching and "near" queries.
"""
def word_datas(self, value, start_pos = 0, **kwargs):
seen = defaultdict(list)
for t in unstopped(self.analyzer(value, positions = True, st... | class Positions(Format):
| """A vector that stores position information in each posting, to
allow phrase searching and "near" queries.
"""
def word_datas(self, value, start_pos = 0, **kwargs):
seen = defaultdict(list)
for t in unstopped(self.analyzer(value, positions = True, start_pos = start_pos)):
... | , doc_boost)) for w, freq in seen.iteritems())
def write_postvalue(self, stream, data):
stream.write_varint(data[0])
stream.write_8bitfloat(data[1])
return data[0]
def read_postvalue(self, stream):
return (stream.read_varint(), stream.read_8bitfloat())
... | 129 | 129 | 430 | 5 | 123 | tallstreet/Whoosh-AppEngine | src/whoosh/fields.py | Python | Positions | Positions | 615 | 682 | 615 | 615 | 14dd5e2220c57b203542a7f838738b7d5572a3f6 | bigcode/the-stack | train |
a5188255186d66bf7cc0799c | train | class | class Schema(object):
"""
Represents the collection of fields in an index. Maps field names to
FieldType objects which define the behavior of each field.
Low-level parts of the index use field numbers instead of field names
for compactness. This class has several methods for converting be... | class Schema(object):
| """
Represents the collection of fields in an index. Maps field names to
FieldType objects which define the behavior of each field.
Low-level parts of the index use field numbers instead of field names
for compactness. This class has several methods for converting between
the field na... | .format = formatclass(analyzer = ana, field_boost = field_boost)
self.vector = vector
self.scorable = True
self.stored = stored
class NGRAM(FieldType):
"""
Configured field that indexes text as N-grams. For example, with a field type
NGRAM(3,4), the value "hello"... | 256 | 256 | 1,205 | 4 | 251 | tallstreet/Whoosh-AppEngine | src/whoosh/fields.py | Python | Schema | Schema | 223 | 396 | 223 | 223 | 54c2f4552ef7fd9534c0270870216ee011dc53d4 | bigcode/the-stack | train |
2906258388b162a7331e7a6f | train | class | class ID(FieldType):
"""
Configured field type that indexes the entire value of the field as one
token. This is useful for data you don't want to tokenize, such as the
path of a file.
"""
def __init__(self, stored = False, unique = False):
"""
:stored: Whether the v... | class ID(FieldType):
| """
Configured field type that indexes the entire value of the field as one
token. This is useful for data you don't want to tokenize, such as the
path of a file.
"""
def __init__(self, stored = False, unique = False):
"""
:stored: Whether the value of this field is ... | ),
(self.stored == other.stored),
(self.unique == other.unique)))
def clean(self):
if self.format and hasattr(self.format, "clean"):
self.format.clean()
if self.vector and hasattr(self.vector, "clean"):
self.vector.clean()
... | 64 | 64 | 110 | 5 | 59 | tallstreet/Whoosh-AppEngine | src/whoosh/fields.py | Python | ID | ID | 98 | 111 | 98 | 98 | e0123f4e389dcee6ad82c1ca4918258ac5f28365 | bigcode/the-stack | train |
b92f2ac14676c28a9525b8cf | train | class | class Frequency(Format):
"""Stores frequency information for each posting.
"""
def __init__(self, analyzer, field_boost = 1.0, boost_as_freq = False, **options):
"""
:analyzer: The analysis.Analyzer object to use to index this field.
See the analysis module for more i... | class Frequency(Format):
| """Stores frequency information for each posting.
"""
def __init__(self, analyzer, field_boost = 1.0, boost_as_freq = False, **options):
"""
:analyzer: The analysis.Analyzer object to use to index this field.
See the analysis module for more information. If this value
... | ()
for t in unstopped(self.analyzer(value)):
seen.add(t.text)
return ((w, 1, None) for w in seen)
def write_postvalue(self, stream, data):
return 0
def read_postvalue(self, stream):
return None
def data_to_frequency(self, data):... | 115 | 115 | 386 | 5 | 109 | tallstreet/Whoosh-AppEngine | src/whoosh/fields.py | Python | Frequency | Frequency | 535 | 583 | 535 | 535 | 538f1eaacf9d2b97821e8fbb093990b8bf8f42e0 | bigcode/the-stack | train |
ba259f5c90843183fd9ae531 | train | class | class Format(object):
"""Abstract base class representing a storage format for a field or vector.
Format objects are responsible for writing and reading the low-level
representation of a field. It controls what kind/level of information
to store about the indexed fields.
"""
def __in... | class Format(object):
| """Abstract base class representing a storage format for a field or vector.
Format objects are responsible for writing and reading the low-level
representation of a field. It controls what kind/level of information
to store about the indexed fields.
"""
def __init__(self, analyzer, fi... | type in self._by_number)
def vectored_fields(self):
"""Returns a list of field numbers corresponding to the fields that are
vectored.
"""
return [i for i, ftype in enumerate(self._by_number) if ftype.vector]
def scorable_fields(self):
"""Returns a list ... | 220 | 220 | 736 | 4 | 215 | tallstreet/Whoosh-AppEngine | src/whoosh/fields.py | Python | Format | Format | 401 | 483 | 401 | 401 | 140da4a35fb32a30b1ddfa691876b1e94d1e44f4 | bigcode/the-stack | train |
37e8a0c8a02ef14d309a98d3 | train | class | class CharacterBoosts(Format):
"""A format that stores positions, character start and end, and
per-position boost information in each posting.
"""
def word_datas(self, value, start_pos = 0, start_char = 0, **kwargs):
seen = defaultdict(iter)
for t in unstopped(self.analyzer(v... | class CharacterBoosts(Format):
| """A format that stores positions, character start and end, and
per-position boost information in each posting.
"""
def word_datas(self, value, start_pos = 0, start_char = 0, **kwargs):
seen = defaultdict(iter)
for t in unstopped(self.analyzer(value, positions = True, characte... | stream.read_varint()
pos_base = 0
pos_list = []
for _ in xrange(freq):
pos_base += stream.read_varint()
pos_list.append((pos_base, stream.read_8bitfloat()))
return (freq, pos_list)
def data_to_frequency(self, data):
return len(data)
... | 142 | 143 | 477 | 7 | 134 | tallstreet/Whoosh-AppEngine | src/whoosh/fields.py | Python | CharacterBoosts | CharacterBoosts | 816 | 877 | 816 | 816 | b1f157e0296d6aaa39b019cce7bed4fb51803cdd | bigcode/the-stack | train |
f39a11300d76d157fa4d5b4c | train | class | class FieldType(object):
"""
Represents a field configuration.
The FieldType object supports the following attributes:
- format (fields.Format): the storage format for the field's contents.
- vector (fields.Format): the storage format for the field's vectors
... | class FieldType(object):
| """
Represents a field configuration.
The FieldType object supports the following attributes:
- format (fields.Format): the storage format for the field's contents.
- vector (fields.Format): the storage format for the field's vectors
(forward index), or N... | www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under 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 permissio... | 152 | 152 | 508 | 5 | 146 | tallstreet/Whoosh-AppEngine | src/whoosh/fields.py | Python | FieldType | FieldType | 37 | 95 | 37 | 37 | a58e77f4c947b405cf1a25c95d202d6a82cfe87d | bigcode/the-stack | train |
9c40e0dc6cbf3d8e3ea08572 | train | class | class KEYWORD(FieldType):
"""
Configured field type for fields containing space-separated or comma-separated
keyword-like data (such as tags). The default is to not store positional information
(so phrase searching is not allowed in this field) and to not make the field scorable.
"""
... | class KEYWORD(FieldType):
| """
Configured field type for fields containing space-separated or comma-separated
keyword-like data (such as tags). The default is to not store positional information
(so phrase searching is not allowed in this field) and to not make the field scorable.
"""
def __init__(self, stored ... | self.stored = stored
self.unique = unique
class STORED(FieldType):
"""
Configured field type for fields you want to store but not index.
"""
def __init__(self):
self.format = Stored()
self.stored = True
class KEYWORD(FieldType):
| 65 | 65 | 219 | 6 | 58 | tallstreet/Whoosh-AppEngine | src/whoosh/fields.py | Python | KEYWORD | KEYWORD | 143 | 163 | 143 | 143 | d745a3d5c0dcf7440ca1402390c4dd7a360f4b16 | bigcode/the-stack | train |
18b23585c0690468dfa93d39 | train | class | class Existence(Format):
"""Only indexes whether a given term occurred in
a given document; it does not store frequencies or positions.
This is useful for fields that should be searchable but not
scorable, such as file path.
"""
def __init__(self, analyzer, field_boost = 1.0, **optio... | class Existence(Format):
| """Only indexes whether a given term occurred in
a given document; it does not store frequencies or positions.
This is useful for fields that should be searchable but not
scorable, such as file path.
"""
def __init__(self, analyzer, field_boost = 1.0, **options):
self.analyze... | Stored(Format):
"""A field that's stored but not indexed."""
analyzer = None
def __init__(self, **options):
self.options = options
def __repr__(self):
return "%s()" % self.__class__.__name__
class Existence(Format):
| 62 | 64 | 208 | 6 | 56 | tallstreet/Whoosh-AppEngine | src/whoosh/fields.py | Python | Existence | Existence | 500 | 529 | 500 | 500 | e8b6500509e724b0fcfafe64f74094215026198c | bigcode/the-stack | train |
194b80da59bdd67bf929d6fb | train | class | class FieldConfigurationError(Exception):
pass
| class FieldConfigurationError(Exception):
| pass
| # limitations under the License.
#===============================================================================
"""
This module contains functions and classes related to fields.
"""
import re
from collections import defaultdict
from whoosh.analysis import unstopped, IDAnalyzer, RegexAnalyzer, Keyword... | 64 | 64 | 9 | 6 | 57 | tallstreet/Whoosh-AppEngine | src/whoosh/fields.py | Python | FieldConfigurationError | FieldConfigurationError | 30 | 31 | 30 | 30 | c694c926ad2feffd0f0961467f07c2755fdb3fd8 | bigcode/the-stack | train |
2018aac27ed5648dfbdbcdf4 | train | class | class TEXT(FieldType):
"""
Configured field type for text fields (for example, the body text of an article). The
default is to store positional information to allow phrase searching. This field type
is always scorable.
"""
def __init__(self, analyzer = None, phrase = True, vector = N... | class TEXT(FieldType):
| """
Configured field type for text fields (for example, the body text of an article). The
default is to store positional information to allow phrase searching. This field type
is always scorable.
"""
def __init__(self, analyzer = None, phrase = True, vector = None,
s... | is treated as a space-separated field.
:scorable: Whether this field is scorable.
"""
ana = KeywordAnalyzer(lowercase = lowercase, commas = commas)
self.format = Frequency(analyzer = ana, field_boost = field_boost)
self.scorable = scorable
self.stored = s... | 81 | 81 | 271 | 5 | 75 | tallstreet/Whoosh-AppEngine | src/whoosh/fields.py | Python | TEXT | TEXT | 166 | 196 | 166 | 166 | b3e34dc60ea1f8cfdd086baef49e463aed70ec61 | bigcode/the-stack | train |
67796d4d60cfce28ad2f798f | train | class | class IDLIST(FieldType):
"""Configured field type for fields containing IDs separated by whitespace
and/or puntuation.
:stored: Whether the value of this field is stored with the document.
:unique: Whether the value of this field is unique per-document.
:expression: The regular expression... | class IDLIST(FieldType):
| """Configured field type for fields containing IDs separated by whitespace
and/or puntuation.
:stored: Whether the value of this field is stored with the document.
:unique: Whether the value of this field is unique per-document.
:expression: The regular expression object to use to extract ... | __init__(self, stored = False, unique = False):
"""
:stored: Whether the value of this field is stored with the document.
"""
self.format = Existence(analyzer = IDAnalyzer())
self.stored = stored
self.unique = unique
class IDLIST(FieldType):
| 64 | 64 | 168 | 6 | 57 | tallstreet/Whoosh-AppEngine | src/whoosh/fields.py | Python | IDLIST | IDLIST | 114 | 130 | 114 | 114 | 9f50f11231e602c089edcbebf3eb8887f864e0e6 | bigcode/the-stack | train |
da568f80c21f135bc31129b3 | train | class | class Migration(migrations.Migration):
dependencies = [
('bunchup', '0015_auto_20200531_2001'),
]
operations = [
migrations.AlterField(
model_name='activity',
name='finish_date',
field=models.DateTimeField(default=datetime.datetime(2020, 6, 1, 19, 52, 48... | class Migration(migrations.Migration):
| dependencies = [
('bunchup', '0015_auto_20200531_2001'),
]
operations = [
migrations.AlterField(
model_name='activity',
name='finish_date',
field=models.DateTimeField(default=datetime.datetime(2020, 6, 1, 19, 52, 48, 784772, tzinfo=utc)),
),
... | # Generated by Django 3.0.5 on 2020-05-31 19:52
import datetime
from django.db import migrations, models
import django.db.models.deletion
from django.utils.timezone import utc
class Migration(migrations.Migration):
| 56 | 64 | 140 | 7 | 48 | LloydTao/Hackathon-NASA-2020 | src/bunchup/migrations/0016_auto_20200531_2052.py | Python | Migration | Migration | 9 | 26 | 9 | 10 | 3a853945232cbbfa2de924c3108cac6dceeb127d | bigcode/the-stack | train |
003926ee7a81161a415dee27 | train | function | def test_build_index_path():
path = build_path_to_parameter(
DwdObservationDataset.CLIMATE_SUMMARY,
DwdObservationResolution.DAILY,
DwdObservationPeriod.HISTORICAL,
)
assert path == "daily/kl/historical/"
| def test_build_index_path():
| path = build_path_to_parameter(
DwdObservationDataset.CLIMATE_SUMMARY,
DwdObservationResolution.DAILY,
DwdObservationPeriod.HISTORICAL,
)
assert path == "daily/kl/historical/"
| import DwdColumns
from wetterdienst.provider.dwd.metadata.constants import DWDCDCBase
from wetterdienst.provider.dwd.observation import (
DwdObservationDataset,
DwdObservationPeriod,
DwdObservationResolution,
)
from wetterdienst.util.network import list_remote_files
def test_build_index_path():
| 64 | 64 | 55 | 6 | 57 | waltherg/wetterdienst | tests/provider/dwd/test_index.py | Python | test_build_index_path | test_build_index_path | 20 | 26 | 20 | 20 | 6da455bcce16b2595bce15fbba724f24c7a084c6 | bigcode/the-stack | train |
66e7777c4f9387ed3593a6db | train | function | @pytest.mark.remote
def test_list_files_of_climate_observations():
files_server = list_remote_files(
"https://opendata.dwd.de/climate_environment/CDC/observations_germany/climate/"
"annual/kl/recent",
recursive=False,
)
assert (
"https://opendata.dwd.de/climate_environment/C... | @pytest.mark.remote
def test_list_files_of_climate_observations():
| files_server = list_remote_files(
"https://opendata.dwd.de/climate_environment/CDC/observations_germany/climate/"
"annual/kl/recent",
recursive=False,
)
assert (
"https://opendata.dwd.de/climate_environment/CDC/observations_germany/climate/"
"annual/kl/recent/jahresw... | path = build_path_to_parameter(
DwdObservationDataset.CLIMATE_SUMMARY,
DwdObservationResolution.DAILY,
DwdObservationPeriod.HISTORICAL,
)
assert path == "daily/kl/historical/"
@pytest.mark.remote
def test_list_files_of_climate_observations():
| 63 | 64 | 112 | 15 | 48 | waltherg/wetterdienst | tests/provider/dwd/test_index.py | Python | test_list_files_of_climate_observations | test_list_files_of_climate_observations | 29 | 40 | 29 | 30 | e709ec23107310ce9c71fd34083c9ae53dd8e739 | bigcode/the-stack | train |
9ca5dd773a5825656109ab3a | train | function | def test_fileindex():
file_index = _create_file_index_for_dwd_server(
DwdObservationDataset.CLIMATE_SUMMARY,
DwdObservationResolution.DAILY,
DwdObservationPeriod.RECENT,
DWDCDCBase.CLIMATE_OBSERVATIONS,
)
assert "daily/kl/recent" in file_index.iloc[0][DwdColumns.FILENAME.va... | def test_fileindex():
| file_index = _create_file_index_for_dwd_server(
DwdObservationDataset.CLIMATE_SUMMARY,
DwdObservationResolution.DAILY,
DwdObservationPeriod.RECENT,
DWDCDCBase.CLIMATE_OBSERVATIONS,
)
assert "daily/kl/recent" in file_index.iloc[0][DwdColumns.FILENAME.value]
| ",
recursive=False,
)
assert (
"https://opendata.dwd.de/climate_environment/CDC/observations_germany/climate/"
"annual/kl/recent/jahreswerte_KL_01048_akt.zip" in files_server
)
def test_fileindex():
| 64 | 64 | 80 | 5 | 59 | waltherg/wetterdienst | tests/provider/dwd/test_index.py | Python | test_fileindex | test_fileindex | 43 | 52 | 43 | 44 | 388935d9a4c4344243fd7c4301c69aa314adda0e | bigcode/the-stack | train |
4a6ba47ca5d7e546bcd88933 | train | class | class OrderListener(object, metaclass=ABCMeta):
"""A callback class for an order."""
def on_execute(self, order: 'Order') -> None:
"""Callback for an order after execution.
Parameters
----------
order : `Order`
The executed order.
"""
pass
def o... | class OrderListener(object, metaclass=ABCMeta):
| """A callback class for an order."""
def on_execute(self, order: 'Order') -> None:
"""Callback for an order after execution.
Parameters
----------
order : `Order`
The executed order.
"""
pass
def on_cancel(self, order: 'Order') -> None:
... |
# distributed under 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
from abc import ABCMeta
class OrderListener(object, metaclass=ABCMeta):
| 65 | 65 | 219 | 11 | 53 | zeeshanalipanhwar/tensortrade | tensortrade/oms/orders/order_listener.py | Python | OrderListener | OrderListener | 19 | 62 | 19 | 19 | 207c4f347a0abd5b0b366f8f68ab7e6ed1ae79b7 | bigcode/the-stack | train |
9335171f7ea8862391dd410c | train | function | def _detect_nanopb(env):
'''Find the path to nanopb root directory.'''
if env.has_key('NANOPB'):
# Use nanopb dir given by user
return env['NANOPB']
p = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..'))
if os.path.isdir(p) and os.path.isfile(os.path.join(p, 'pb.... | def _detect_nanopb(env):
| '''Find the path to nanopb root directory.'''
if env.has_key('NANOPB'):
# Use nanopb dir given by user
return env['NANOPB']
p = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..'))
if os.path.isdir(p) and os.path.isfile(os.path.join(p, 'pb.h')):
# Assume we... | Cons.Action
import SCons.Builder
import SCons.Util
from SCons.Script import Dir, File
import os.path
import platform
class NanopbWarning(SCons.Warnings.Warning):
pass
SCons.Warnings.enableWarningClass(NanopbWarning)
def _detect_nanopb(env):
| 64 | 64 | 133 | 8 | 56 | edwardcoyne/nanopb | tests/site_scons/site_tools/nanopb.py | Python | _detect_nanopb | _detect_nanopb | 42 | 54 | 42 | 42 | faff8ea17caa62ccdaae0c884221e9638aefe29e | bigcode/the-stack | train |
7ff7758e1e1996e9ec8e8994 | train | class | class NanopbWarning(SCons.Warnings.Warning):
pass
| class NanopbWarning(SCons.Warnings.Warning):
| pass
| "--plugin=protoc-gen-nanopb=path/to/protoc-gen-nanopb")
'''
import SCons.Action
import SCons.Builder
import SCons.Util
from SCons.Script import Dir, File
import os.path
import platform
class NanopbWarning(SCons.Warnings.Warning):
| 64 | 64 | 14 | 11 | 52 | edwardcoyne/nanopb | tests/site_scons/site_tools/nanopb.py | Python | NanopbWarning | NanopbWarning | 38 | 39 | 38 | 38 | d643b3f8c62f9588eb27184e58c0b142e20e562a | bigcode/the-stack | train |
c9f0125ad8830fb46e0239aa | train | function | def _nanopb_proto_actions(source, target, env, for_signature):
esc = env['ESCAPE']
# Make protoc build inside the SConscript directory
prefix = os.path.dirname(str(source[-1]))
srcfile = esc(os.path.relpath(str(source[0]), prefix))
include_dirs = '-I.'
for d in env['PROTOCPATH']:
d = en... | def _nanopb_proto_actions(source, target, env, for_signature):
| esc = env['ESCAPE']
# Make protoc build inside the SConscript directory
prefix = os.path.dirname(str(source[-1]))
srcfile = esc(os.path.relpath(str(source[0]), prefix))
include_dirs = '-I.'
for d in env['PROTOCPATH']:
d = env.GetBuildPath(d)
if not os.path.isabs(d): d = os.path.... | ':
return e('--plugin=protoc-gen-nanopb=' + os.path.join(n, 'generator', 'protoc-gen-nanopb.bat'))
else:
return e('--plugin=protoc-gen-nanopb=' + os.path.join(n, 'generator', 'protoc-gen-nanopb'))
def _nanopb_proto_actions(source, target, env, for_signature):
| 86 | 86 | 289 | 16 | 70 | edwardcoyne/nanopb | tests/site_scons/site_tools/nanopb.py | Python | _nanopb_proto_actions | _nanopb_proto_actions | 128 | 150 | 128 | 128 | 947a86818544ca2934a6338c655ad8fbfd0ab065 | bigcode/the-stack | train |
caf60bb9e73d1066a95b1a2c | train | function | def _nanopb_proto_emitter(target, source, env):
basename = os.path.splitext(str(source[0]))[0]
source_extension = os.path.splitext(str(target[0]))[1]
header_extension = '.h' + source_extension[2:]
target.append(basename + '.pb' + header_extension)
# This is a bit of a hack. protoc include paths wor... | def _nanopb_proto_emitter(target, source, env):
| basename = os.path.splitext(str(source[0]))[0]
source_extension = os.path.splitext(str(target[0]))[1]
header_extension = '.h' + source_extension[2:]
target.append(basename + '.pb' + header_extension)
# This is a bit of a hack. protoc include paths work the sanest
# when the working directory is... | source_extension, header_extension)
return SCons.Action.CommandAction('$PROTOC $PROTOCFLAGS %s --nanopb_out=%s %s' % (include_dirs, nanopb_flags, srcfile),
chdir = prefix)
def _nanopb_proto_emitter(target, source, env):
| 64 | 64 | 169 | 14 | 50 | edwardcoyne/nanopb | tests/site_scons/site_tools/nanopb.py | Python | _nanopb_proto_emitter | _nanopb_proto_emitter | 152 | 167 | 152 | 152 | ca8eb3f8af05fd6d174c3dfdb0ea86ad5bbf86f8 | bigcode/the-stack | train |
a185a4ee9b4b08e6bdf607a2 | train | function | def generate(env):
'''Add Builder for nanopb protos.'''
env['NANOPB'] = _detect_nanopb(env)
env['PROTOC'] = _detect_protoc(env)
env['PROTOCFLAGS'] = _detect_protocflags(env)
env['PYTHON'] = _detect_python(env)
env['NANOPB_GENERATOR'] = _detect_nanopb_generator(env)
env.SetDefault(NANOPBFLAG... | def generate(env):
| '''Add Builder for nanopb protos.'''
env['NANOPB'] = _detect_nanopb(env)
env['PROTOC'] = _detect_protoc(env)
env['PROTOCFLAGS'] = _detect_protocflags(env)
env['PYTHON'] = _detect_python(env)
env['NANOPB_GENERATOR'] = _detect_nanopb_generator(env)
env.SetDefault(NANOPBFLAGS = '')
env.Se... | proto',
emitter = _nanopb_proto_emitter)
_nanopb_proto_cpp_builder = SCons.Builder.Builder(
generator = _nanopb_proto_actions,
suffix = '.pb.cpp',
src_suffix = '.proto',
emitter = _nanopb_proto_emitter)
def generate(env):
| 64 | 64 | 205 | 4 | 60 | edwardcoyne/nanopb | tests/site_scons/site_tools/nanopb.py | Python | generate | generate | 181 | 195 | 181 | 181 | 7039a596bcf40e13287ac19e6c886dcea6108381 | bigcode/the-stack | train |
1e3fba9afee65bc855b2523c | train | function | def _detect_protoc(env):
'''Find the path to the protoc compiler.'''
if env.has_key('PROTOC'):
# Use protoc defined by user
return env['PROTOC']
n = _detect_nanopb(env)
p1 = os.path.join(n, 'generator-bin', 'protoc' + env['PROGSUFFIX'])
if os.path.exists(p1):
# Use protoc bu... | def _detect_protoc(env):
| '''Find the path to the protoc compiler.'''
if env.has_key('PROTOC'):
# Use protoc defined by user
return env['PROTOC']
n = _detect_nanopb(env)
p1 = os.path.join(n, 'generator-bin', 'protoc' + env['PROGSUFFIX'])
if os.path.exists(p1):
# Use protoc bundled with binary package... | # Binary package
return env['ESCAPE'](generator_cmd)
else:
# Source package
return env['PYTHON'] + " " + env['ESCAPE'](os.path.join(env['NANOPB'], 'generator', 'nanopb_generator.py'))
def _detect_protoc(env):
| 68 | 68 | 229 | 7 | 61 | edwardcoyne/nanopb | tests/site_scons/site_tools/nanopb.py | Python | _detect_protoc | _detect_protoc | 81 | 107 | 81 | 81 | cfd8064ea95f14783b89625e30a02ce13c2ef213 | bigcode/the-stack | train |
77729108c8fc34d51042f8d0 | train | function | def _detect_nanopb_generator(env):
'''Return command for running nanopb_generator.py'''
generator_cmd = os.path.join(env['NANOPB'], 'generator-bin', 'nanopb_generator' + env['PROGSUFFIX'])
if os.path.exists(generator_cmd):
# Binary package
return env['ESCAPE'](generator_cmd)
else:
... | def _detect_nanopb_generator(env):
| '''Return command for running nanopb_generator.py'''
generator_cmd = os.path.join(env['NANOPB'], 'generator-bin', 'nanopb_generator' + env['PROGSUFFIX'])
if os.path.exists(generator_cmd):
# Binary package
return env['ESCAPE'](generator_cmd)
else:
# Source package
return e... | if p:
return env['ESCAPE'](p)
p = env.WhereIs('py.exe')
if p:
return env['ESCAPE'](p) + " -3"
return env['ESCAPE'](sys.executable)
def _detect_nanopb_generator(env):
| 64 | 64 | 121 | 9 | 55 | edwardcoyne/nanopb | tests/site_scons/site_tools/nanopb.py | Python | _detect_nanopb_generator | _detect_nanopb_generator | 71 | 79 | 71 | 71 | 0fdc81ec0c117f1e1a3c36a27bceb39feac0f6ba | bigcode/the-stack | train |
528f68fbb10ea7678cf47a38 | train | function | def exists(env):
return _detect_protoc(env) and _detect_protoc_opts(env)
| def exists(env):
| return _detect_protoc(env) and _detect_protoc_opts(env)
| $PROTOCFLAGS --nanopb_out=$NANOPBFLAGS:. $SOURCES')
env['BUILDERS']['NanopbProto'] = _nanopb_proto_builder
env['BUILDERS']['NanopbProtoCpp'] = _nanopb_proto_cpp_builder
def exists(env):
| 64 | 64 | 20 | 4 | 59 | edwardcoyne/nanopb | tests/site_scons/site_tools/nanopb.py | Python | exists | exists | 197 | 198 | 197 | 197 | 492496d8f2c9423214893b2f5123bdb85128824e | bigcode/the-stack | train |
2602901da66c7b2b459f5871 | train | function | def _detect_protocflags(env):
'''Find the options to use for protoc.'''
if env.has_key('PROTOCFLAGS'):
return env['PROTOCFLAGS']
p = _detect_protoc(env)
n = _detect_nanopb(env)
p1 = os.path.join(n, 'generator', 'protoc' + env['PROGSUFFIX'])
p2 = os.path.join(n, 'generator-bin', 'protoc'... | def _detect_protocflags(env):
| '''Find the options to use for protoc.'''
if env.has_key('PROTOCFLAGS'):
return env['PROTOCFLAGS']
p = _detect_protoc(env)
n = _detect_nanopb(env)
p1 = os.path.join(n, 'generator', 'protoc' + env['PROGSUFFIX'])
p2 = os.path.join(n, 'generator-bin', 'protoc' + env['PROGSUFFIX'])
if p... | env['ESCAPE'](p)
p = env.WhereIs('protoc')
if p:
# Use protoc from path
return env['ESCAPE'](p)
raise SCons.Errors.StopError(NanopbWarning,
"Could not find the protoc compiler")
def _detect_protocflags(env):
| 69 | 69 | 232 | 8 | 61 | edwardcoyne/nanopb | tests/site_scons/site_tools/nanopb.py | Python | _detect_protocflags | _detect_protocflags | 109 | 126 | 109 | 109 | 814a47111f45f77b1b3032868e70240861b8aae8 | bigcode/the-stack | train |
e3566304f3b211d961d4a4e7 | train | function | def _detect_python(env):
'''Find Python executable to use.'''
if env.has_key('PYTHON'):
return env['PYTHON']
p = env.WhereIs('python3')
if p:
return env['ESCAPE'](p)
p = env.WhereIs('py.exe')
if p:
return env['ESCAPE'](p) + " -3"
return env['ESCAPE'](sys.executable... | def _detect_python(env):
| '''Find Python executable to use.'''
if env.has_key('PYTHON'):
return env['PYTHON']
p = env.WhereIs('python3')
if p:
return env['ESCAPE'](p)
p = env.WhereIs('py.exe')
if p:
return env['ESCAPE'](p) + " -3"
return env['ESCAPE'](sys.executable)
| .isdir(p) and os.path.isfile(os.path.join(p, 'pb.h')):
# Assume we are running under tests/site_scons/site_tools
return p
raise SCons.Errors.StopError(NanopbWarning,
"Could not find the nanopb root directory")
def _detect_python(env):
| 64 | 64 | 96 | 6 | 58 | edwardcoyne/nanopb | tests/site_scons/site_tools/nanopb.py | Python | _detect_python | _detect_python | 56 | 69 | 56 | 56 | cebcc232f4b1e9c66a4b2242a8a9e0812ae80e12 | bigcode/the-stack | train |
5ec9cefbac1e3134f6af46a3 | train | function | def read_energy(spc_dct_i, pf_filesystems,
spc_model_dct_i, run_prefix,
read_ene=True, read_zpe=True, conf=None, saddle=False):
""" Get the energy for a species on a channel
"""
# Read the electronic energy and ZPVE
e_elec = None
if read_ene:
e_elec = electro... | def read_energy(spc_dct_i, pf_filesystems,
spc_model_dct_i, run_prefix,
read_ene=True, read_zpe=True, conf=None, saddle=False):
| """ Get the energy for a species on a channel
"""
# Read the electronic energy and ZPVE
e_elec = None
if read_ene:
e_elec = electronic_energy(
spc_dct_i, pf_filesystems, spc_model_dct_i, conf=conf)
ioprinter.debug_message('e_elec in models ene ', e_elec)
e_zpe = Non... | .amech_io import printer as ioprinter
from mechroutines.models import typ
from mechroutines.models import _vib as vib
# Functions to hand reading and formatting energies of single species
def read_energy(spc_dct_i, pf_filesystems,
spc_model_dct_i, run_prefix,
read_ene=True, read_zpe=Tr... | 84 | 84 | 282 | 41 | 42 | kevinmooreiii/mechdriver | mechroutines/models/ene.py | Python | read_energy | read_energy | 15 | 45 | 15 | 17 | 5793a25725d148c9e6f3feb0e4a2dc46af2af533 | bigcode/the-stack | train |
66d57748d828aacef96ac4f1 | train | function | def zero_point_energy(spc_dct_i,
pf_filesystems, spc_model_dct_i,
run_prefix, saddle=False):
""" compute the ZPE including torsional and anharmonic corrections
"""
ioprinter.info_message('- Calculating zero-point energy')
# Calculate ZPVE
is_atom = False... | def zero_point_energy(spc_dct_i,
pf_filesystems, spc_model_dct_i,
run_prefix, saddle=False):
| """ compute the ZPE including torsional and anharmonic corrections
"""
ioprinter.info_message('- Calculating zero-point energy')
# Calculate ZPVE
is_atom = False
if not saddle:
if typ.is_atom(spc_dct_i):
is_atom = True
if is_atom:
zpe = 0.0
else:
_, ... | ')
e_elec = None
break
else:
ioprinter.warning_message('No conformer to calculate the energy')
return e_elec
def zero_point_energy(spc_dct_i,
pf_filesystems, spc_model_dct_i,
run_prefix, saddle=False):
| 64 | 64 | 163 | 29 | 34 | kevinmooreiii/mechdriver | mechroutines/models/ene.py | Python | zero_point_energy | zero_point_energy | 98 | 118 | 98 | 100 | 851317aad3ddc04b19292269fab9b9ce43fb372f | bigcode/the-stack | train |
05ec2a17c437f2901fa217a2 | train | function | def rpath_ref_idx(ts_dct, scn_vals, coord_name, scn_prefix,
ene_info1, ene_info2):
""" Get the reference energy along a reaction path
"""
# Set up the filesystem
zma_fs = autofile.fs.zmatrix(scn_prefix)
zma_path = zma_fs[-1].path([0])
scn_fs = autofile.fs.scan(zma_path)
e... | def rpath_ref_idx(ts_dct, scn_vals, coord_name, scn_prefix,
ene_info1, ene_info2):
| """ Get the reference energy along a reaction path
"""
# Set up the filesystem
zma_fs = autofile.fs.zmatrix(scn_prefix)
zma_path = zma_fs[-1].path([0])
scn_fs = autofile.fs.scan(zma_path)
ene_info1 = ene_info1[1][0][1]
ene_info2 = ene_info2[0]
ioprinter.debug_message('mod_eneinf1',... |
if not saddle:
if typ.is_atom(spc_dct_i):
is_atom = True
if is_atom:
zpe = 0.0
else:
_, _, zpe, _ = vib.vib_analysis(
spc_dct_i, pf_filesystems, spc_model_dct_i,
run_prefix, zrxn=(None if not saddle else 'placeholder'))
return zpe
def rpath_r... | 121 | 121 | 406 | 29 | 91 | kevinmooreiii/mechdriver | mechroutines/models/ene.py | Python | rpath_ref_idx | rpath_ref_idx | 121 | 156 | 121 | 122 | 74929bd86cacff79062fbe9e524a61ea8e9d2d21 | bigcode/the-stack | train |
eadb91e29c008d606a71d8f2 | train | function | def electronic_energy(spc_dct_i, pf_filesystems, spc_model_dct_i, conf=None):
""" get high level energy at low level optimized geometry
"""
ioprinter.info_message('- Calculating electronic energy')
# spc_dct_i = spc_dct[spc_name]
rxn_info = spc_dct_i.get('rxn_info', None)
if rxn_info is not No... | def electronic_energy(spc_dct_i, pf_filesystems, spc_model_dct_i, conf=None):
| """ get high level energy at low level optimized geometry
"""
ioprinter.info_message('- Calculating electronic energy')
# spc_dct_i = spc_dct[spc_name]
rxn_info = spc_dct_i.get('rxn_info', None)
if rxn_info is not None:
spc_info = rinfo.ts_info(rxn_info)
else:
spc_info = si... | , saddle=saddle)
ioprinter.debug_message('zpe in models ene ', e_zpe)
# Return the total energy requested
ene = None
if read_ene and read_zpe:
if e_elec is not None and e_zpe is not None:
ene = e_elec + e_zpe
elif read_ene and not read_zpe:
ene = e_elec
elif read... | 135 | 135 | 451 | 23 | 111 | kevinmooreiii/mechdriver | mechroutines/models/ene.py | Python | electronic_energy | electronic_energy | 48 | 95 | 48 | 48 | ed80e3add5e91ffba460e15c6c359b8f87a75a96 | bigcode/the-stack | train |
4b55c9c08542529886630776 | train | function | def _params_converter(
params: Optional[Iterable[object]],
) -> Optional[Tuple[object, ...]]:
return tuple(params) if params is not None else None
| def _params_converter(
params: Optional[Iterable[object]],
) -> Optional[Tuple[object, ...]]:
| return tuple(params) if params is not None else None
| bool], ...],
Callable[[Any], Optional[object]],
]
]:
if ids is None:
return None
if callable(ids):
return ids
return tuple(ids)
def _params_converter(
params: Optional[Iterable[object]],
) -> Optional[Tuple[object, ...]]:
| 64 | 64 | 37 | 24 | 40 | sgaist/pytest | src/_pytest/fixtures.py | Python | _params_converter | _params_converter | 1,159 | 1,162 | 1,159 | 1,161 | ee4f8e19d17628043d7b6d6b44fef61de80009bf | bigcode/the-stack | train |
a2bef958bb934861b1e1cf0d | train | function | def yield_fixture(
fixture_function=None,
*args,
scope="function",
params=None,
autouse=False,
ids=None,
name=None,
):
"""(Return a) decorator to mark a yield-fixture factory function.
.. deprecated:: 3.0
Use :py:func:`pytest.fixture` directly instead.
"""
warnings.w... | def yield_fixture(
fixture_function=None,
*args,
scope="function",
params=None,
autouse=False,
ids=None,
name=None,
):
| """(Return a) decorator to mark a yield-fixture factory function.
.. deprecated:: 3.0
Use :py:func:`pytest.fixture` directly instead.
"""
warnings.warn(YIELD_FIXTURE, stacklevel=2)
return fixture(
fixture_function,
*args,
scope=scope,
params=params,
a... | name=name,
)
# Direct decoration.
if fixture_function:
return fixture_marker(fixture_function)
return fixture_marker
def yield_fixture(
fixture_function=None,
*args,
scope="function",
params=None,
autouse=False,
ids=None,
name=None,
):
| 64 | 64 | 128 | 36 | 27 | sgaist/pytest | src/_pytest/fixtures.py | Python | yield_fixture | yield_fixture | 1,345 | 1,368 | 1,345 | 1,353 | 4d0bc932620534b17e3a8c2cb727e7befeccddd1 | bigcode/the-stack | train |
acb18412e48633c2402c8c22 | train | class | class FixtureRequest:
"""A request for a fixture from a test or fixture function.
A request object gives access to the requesting test context and has
an optional ``param`` attribute in case the fixture is parametrized
indirectly.
"""
def __init__(self, pyfuncitem, *, _ispytest: bool = False) ... | class FixtureRequest:
| """A request for a fixture from a test or fixture function.
A request object gives access to the requesting test context and has
an optional ``param`` attribute in case the fixture is parametrized
indirectly.
"""
def __init__(self, pyfuncitem, *, _ispytest: bool = False) -> None:
check... | _closure, which means that the new closure will
always be a subset of the old one. The order is preserved.
This method is needed because direct parametrization may shadow some
of the fixtures that were included in the originally built dependency
tree. In this way the dependency tree can... | 256 | 256 | 2,969 | 4 | 252 | sgaist/pytest | src/_pytest/fixtures.py | Python | FixtureRequest | FixtureRequest | 435 | 765 | 435 | 435 | a5eec547687fb4d8713d6450e14f126a628798d2 | bigcode/the-stack | train |
9fc576a933cec4d0df91aa4c | train | class | @attr.s(frozen=True, auto_attribs=True)
class PseudoFixtureDef(Generic[FixtureValue]):
cached_result: "_FixtureCachedResult[FixtureValue]"
_scope: Scope
| @attr.s(frozen=True, auto_attribs=True)
class PseudoFixtureDef(Generic[FixtureValue]):
| cached_result: "_FixtureCachedResult[FixtureValue]"
_scope: Scope
| ],
Tuple[
None,
# Cache key.
object,
# Exc info if raised.
Tuple[Type[BaseException], BaseException, TracebackType],
],
]
@attr.s(frozen=True, auto_attribs=True)
class PseudoFixtureDef(Generic[FixtureValue]):
| 64 | 64 | 41 | 23 | 41 | sgaist/pytest | src/_pytest/fixtures.py | Python | PseudoFixtureDef | PseudoFixtureDef | 109 | 112 | 109 | 110 | b7749da2c58e7b935d0cb83aade841272d8e420b | bigcode/the-stack | train |
ae35367cb648a2b1cf1183a3 | train | function | def reorder_items(items: Sequence[nodes.Item]) -> List[nodes.Item]:
argkeys_cache: Dict[Scope, Dict[nodes.Item, Dict[_Key, None]]] = {}
items_by_argkey: Dict[Scope, Dict[_Key, Deque[nodes.Item]]] = {}
for scope in HIGH_SCOPES:
d: Dict[nodes.Item, Dict[_Key, None]] = {}
argkeys_cache[scope] =... | def reorder_items(items: Sequence[nodes.Item]) -> List[nodes.Item]:
| argkeys_cache: Dict[Scope, Dict[nodes.Item, Dict[_Key, None]]] = {}
items_by_argkey: Dict[Scope, Dict[_Key, Deque[nodes.Item]]] = {}
for scope in HIGH_SCOPES:
d: Dict[nodes.Item, Dict[_Key, None]] = {}
argkeys_cache[scope] = d
item_d: Dict[_Key, Deque[nodes.Item]] = defaultdict(deque... | Algorithm for sorting on a per-parametrized resource setup basis.
# It is called for Session scope first and performs sorting
# down to the lower scopes such as to minimize number of "high scope"
# setups and teardowns.
def reorder_items(items: Sequence[nodes.Item]) -> List[nodes.Item]:
| 64 | 64 | 213 | 16 | 48 | sgaist/pytest | src/_pytest/fixtures.py | Python | reorder_items | reorder_items | 281 | 298 | 281 | 281 | 75e06f5f3cd4eba8a023676393b84636e34dba35 | bigcode/the-stack | train |
496a8d90cc729fd7d1e26d0d | train | function | def pytest_sessionstart(session: "Session") -> None:
session._fixturemanager = FixtureManager(session)
| def pytest_sessionstart(session: "Session") -> None:
| session._fixturemanager = FixtureManager(session)
| ], BaseException, TracebackType],
],
]
@attr.s(frozen=True, auto_attribs=True)
class PseudoFixtureDef(Generic[FixtureValue]):
cached_result: "_FixtureCachedResult[FixtureValue]"
_scope: Scope
def pytest_sessionstart(session: "Session") -> None:
| 64 | 64 | 22 | 12 | 51 | sgaist/pytest | src/_pytest/fixtures.py | Python | pytest_sessionstart | pytest_sessionstart | 115 | 116 | 115 | 115 | 36717cc3eae546ecfc61bc070a2fe5649062a9f7 | bigcode/the-stack | train |
e1fc7b14f6f6142598808d67 | train | class | class FixtureManager:
"""pytest fixture definitions and information is stored and managed
from this class.
During collection fm.parsefactories() is called multiple times to parse
fixture function definitions into FixtureDef objects and internal
data structures.
During collection of test functi... | class FixtureManager:
| """pytest fixture definitions and information is stored and managed
from this class.
During collection fm.parsefactories() is called multiple times to parse
fixture function definitions into FixtureDef objects and internal
data structures.
During collection of test functions, metafunc-mechanic... | _function)
return fixture_marker
def yield_fixture(
fixture_function=None,
*args,
scope="function",
params=None,
autouse=False,
ids=None,
name=None,
):
"""(Return a) decorator to mark a yield-fixture factory function.
.. deprecated:: 3.0
Use :py:func:`pytest.fixture` ... | 256 | 256 | 2,587 | 4 | 252 | sgaist/pytest | src/_pytest/fixtures.py | Python | FixtureManager | FixtureManager | 1,395 | 1,693 | 1,395 | 1,395 | 74b4c8128c9982b0e95acacf81be17e067e3d7cc | bigcode/the-stack | train |
612a3daf825d6fa97f7a098d | train | function | def pytest_fixture_setup(
fixturedef: FixtureDef[FixtureValue], request: SubRequest
) -> FixtureValue:
"""Execution of fixture setup."""
kwargs = {}
for argname in fixturedef.argnames:
fixdef = request._get_active_fixturedef(argname)
assert fixdef.cached_result is not None
result... | def pytest_fixture_setup(
fixturedef: FixtureDef[FixtureValue], request: SubRequest
) -> FixtureValue:
| """Execution of fixture setup."""
kwargs = {}
for argname in fixturedef.argnames:
fixdef = request._get_active_fixturedef(argname)
assert fixdef.cached_result is not None
result, arg_cache_key, exc = fixdef.cached_result
request._check_scope(argname, request._scope, fixdef._s... | def.func)
if fixturefunc != fixturedef.func:
fixturefunc = fixturefunc.__get__(request.instance) # type: ignore[union-attr]
return fixturefunc
def pytest_fixture_setup(
fixturedef: FixtureDef[FixtureValue], request: SubRequest
) -> FixtureValue:
| 64 | 64 | 212 | 25 | 38 | sgaist/pytest | src/_pytest/fixtures.py | Python | pytest_fixture_setup | pytest_fixture_setup | 1,114 | 1,136 | 1,114 | 1,116 | 8b45edf3412c8dab3f3fc2f258d429e356c4e7d7 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.