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
fc888f53a7f132254d5740d2
train
class
class InvalidSignatureError(ValidationError): pass
class InvalidSignatureError(ValidationError):
pass
class DuplicateEntryError(NameError):pass class DataError(ValidationError): pass class UnknownDomainError(Exception): pass class MappingMismatchError(ValidationError): pass class InvalidStatusError(ValidationError): pass class MandatoryError(ValidationError): pass class InvalidSignatureError(ValidationError):
64
64
10
9
54
snehapatil1/frappe
frappe/exceptions.py
Python
InvalidSignatureError
InvalidSignatureError
66
66
66
66
53fa585431b94bcaa73c3534b1939159901c144c
bigcode/the-stack
train
0c2f3810ffc58ba169e07188
train
class
class SessionStopped(Exception): http_status_code = 503
class SessionStopped(Exception):
http_status_code = 503
_code = 401 class PermissionError(Exception): http_status_code = 403 class DoesNotExistError(ValidationError): http_status_code = 404 class NameError(Exception): http_status_code = 409 class OutgoingEmailError(Exception): http_status_code = 501 class SessionStopped(Exception):
64
64
12
5
58
snehapatil1/frappe
frappe/exceptions.py
Python
SessionStopped
SessionStopped
34
35
34
34
3922e5d22ab1aacccd78a069ce780b2b53ff4587
bigcode/the-stack
train
e1da2392d29949ab0c50c4ea
train
class
class ImplicitCommitError(ValidationError): pass
class ImplicitCommitError(ValidationError):
pass
pass class InvalidEmailAddressError(ValidationError): pass class TemplateNotFoundError(ValidationError): pass class UniqueValidationError(ValidationError): pass class AppNotInstalledError(ValidationError): pass class IncorrectSitePath(NotFound): pass class ImplicitCommitError(ValidationError):
64
64
11
10
53
snehapatil1/frappe
frappe/exceptions.py
Python
ImplicitCommitError
ImplicitCommitError
82
82
82
82
45a70738453a4c4ebcd09b3a54ab22e052c1c538
bigcode/the-stack
train
2e3e98baf4be533dd969d89c
train
class
class UniqueValidationError(ValidationError): pass
class UniqueValidationError(ValidationError):
pass
): pass class TimestampMismatchError(ValidationError): pass class EmptyTableError(ValidationError): pass class LinkExistsError(ValidationError): pass class InvalidEmailAddressError(ValidationError): pass class TemplateNotFoundError(ValidationError): pass class UniqueValidationError(ValidationError):
64
64
10
9
54
snehapatil1/frappe
frappe/exceptions.py
Python
UniqueValidationError
UniqueValidationError
79
79
79
79
62b500980acb42a5688117c3ab9515b45b925780
bigcode/the-stack
train
6d57ede146f3066ac1c1f410
train
class
class UnknownDomainError(Exception): pass
class UnknownDomainError(Exception):
pass
=None): if not msg: msg = "MariaDb is not properly configured" super(ImproperDBConfigurationError, self).__init__(msg) self.reason = reason class DuplicateEntryError(NameError):pass class DataError(ValidationError): pass class UnknownDomainError(Exception):
64
64
8
7
56
snehapatil1/frappe
frappe/exceptions.py
Python
UnknownDomainError
UnknownDomainError
62
62
62
62
ee5c2ff6594e2c48d8051e4e41ca857115d55819
bigcode/the-stack
train
5022286f1eebcddf19ad2837
train
class
class LinkValidationError(ValidationError): pass
class LinkValidationError(ValidationError):
pass
class InvalidSignatureError(ValidationError): pass class RateLimitExceededError(ValidationError): pass class CannotChangeConstantError(ValidationError): pass class CharacterLengthExceededError(ValidationError): pass class UpdateAfterSubmitError(ValidationError): pass class LinkValidationError(ValidationError):
64
64
10
9
54
snehapatil1/frappe
frappe/exceptions.py
Python
LinkValidationError
LinkValidationError
71
71
71
71
af6086b4fc88ea35720364220e3ceb97089f0516
bigcode/the-stack
train
5b9c1ae5f2a97cc700623e49
train
class
class InvalidStatusError(ValidationError): pass
class InvalidStatusError(ValidationError):
pass
(ImproperDBConfigurationError, self).__init__(msg) self.reason = reason class DuplicateEntryError(NameError):pass class DataError(ValidationError): pass class UnknownDomainError(Exception): pass class MappingMismatchError(ValidationError): pass class InvalidStatusError(ValidationError):
64
64
10
9
54
snehapatil1/frappe
frappe/exceptions.py
Python
InvalidStatusError
InvalidStatusError
64
64
64
64
d077e7bf07786b951da974f7e54cd49cd7dba53b
bigcode/the-stack
train
3984d5e088c798a32f41a3d8
train
class
class DoesNotExistError(ValidationError): http_status_code = 404
class DoesNotExistError(ValidationError):
http_status_code = 404
OperationalError as DatabaseOperationalError class ValidationError(Exception): http_status_code = 417 class AuthenticationError(Exception): http_status_code = 401 class SessionExpired(Exception): http_status_code = 401 class PermissionError(Exception): http_status_code = 403 class DoesNotExistError(ValidationE...
64
64
16
9
54
snehapatil1/frappe
frappe/exceptions.py
Python
DoesNotExistError
DoesNotExistError
25
26
25
25
58154aff43abac5392ef7eb024ce70da34a34065
bigcode/the-stack
train
90a6ec3446b7659a0acfc89d
train
class
class TemplateNotFoundError(ValidationError): pass
class TemplateNotFoundError(ValidationError):
pass
pass class DocstatusTransitionError(ValidationError): pass class TimestampMismatchError(ValidationError): pass class EmptyTableError(ValidationError): pass class LinkExistsError(ValidationError): pass class InvalidEmailAddressError(ValidationError): pass class TemplateNotFoundError(ValidationError):
64
64
11
10
53
snehapatil1/frappe
frappe/exceptions.py
Python
TemplateNotFoundError
TemplateNotFoundError
78
78
78
78
fdedc9928b1b81c4a36c0afd767c33c312682681
bigcode/the-stack
train
8efe46ce281e9d0367c53b78
train
class
class UpdateAfterSubmitError(ValidationError): pass
class UpdateAfterSubmitError(ValidationError):
pass
pass class MandatoryError(ValidationError): pass class InvalidSignatureError(ValidationError): pass class RateLimitExceededError(ValidationError): pass class CannotChangeConstantError(ValidationError): pass class CharacterLengthExceededError(ValidationError): pass class UpdateAfterSubmitError(ValidationError):
64
64
11
10
53
snehapatil1/frappe
frappe/exceptions.py
Python
UpdateAfterSubmitError
UpdateAfterSubmitError
70
70
70
70
0646adc67757d0c14bcac80533e89a5eb844fa02
bigcode/the-stack
train
40e35af4ed8585882d77b182
train
class
class RateLimitExceededError(ValidationError): pass
class RateLimitExceededError(ValidationError):
pass
Error(ValidationError): pass class UnknownDomainError(Exception): pass class MappingMismatchError(ValidationError): pass class InvalidStatusError(ValidationError): pass class MandatoryError(ValidationError): pass class InvalidSignatureError(ValidationError): pass class RateLimitExceededError(ValidationError):
64
64
11
10
53
snehapatil1/frappe
frappe/exceptions.py
Python
RateLimitExceededError
RateLimitExceededError
67
67
67
67
11637f0de5852763c4f7b0d6d6d4df82fe0f1b27
bigcode/the-stack
train
cf3c22bb5f39d12acba7a69c
train
class
class TimestampMismatchError(ValidationError): pass
class TimestampMismatchError(ValidationError):
pass
class CharacterLengthExceededError(ValidationError): pass class UpdateAfterSubmitError(ValidationError): pass class LinkValidationError(ValidationError): pass class CancelledLinkError(LinkValidationError): pass class DocstatusTransitionError(ValidationError): pass class TimestampMismatchError(ValidationError):
64
64
10
9
54
snehapatil1/frappe
frappe/exceptions.py
Python
TimestampMismatchError
TimestampMismatchError
74
74
74
74
1f8e787d865b88f7923fc3660418cccc3d3439ca
bigcode/the-stack
train
0b2feb27c52becad39233a1d
train
class
class SessionExpired(Exception): http_status_code = 401
class SessionExpired(Exception):
http_status_code = 401
import NotFound # imports - third-party imports from pymysql import ProgrammingError as SQLError, Error # from pymysql import OperationalError as DatabaseOperationalError class ValidationError(Exception): http_status_code = 417 class AuthenticationError(Exception): http_status_code = 401 class SessionExpired(Exce...
64
64
12
5
58
snehapatil1/frappe
frappe/exceptions.py
Python
SessionExpired
SessionExpired
19
20
19
19
19c117fda89b4db2cc51532b0e9532de45efefac
bigcode/the-stack
train
9f35504fb766993531d071a0
train
class
class DuplicateEntryError(NameError):pass
class DuplicateEntryError(NameError):
pass
are not properly configured """ def __init__(self, reason, msg=None): if not msg: msg = "MariaDb is not properly configured" super(ImproperDBConfigurationError, self).__init__(msg) self.reason = reason class DuplicateEntryError(NameError):
64
64
9
7
56
snehapatil1/frappe
frappe/exceptions.py
Python
DuplicateEntryError
DuplicateEntryError
60
60
60
60
1712b57bdcf576f09e910f983c75fa3ac2636e0a
bigcode/the-stack
train
721793e1c8a998ac34f8027c
train
class
class PermissionError(Exception): http_status_code = 403
class PermissionError(Exception):
http_status_code = 403
pymysql import ProgrammingError as SQLError, Error # from pymysql import OperationalError as DatabaseOperationalError class ValidationError(Exception): http_status_code = 417 class AuthenticationError(Exception): http_status_code = 401 class SessionExpired(Exception): http_status_code = 401 class PermissionError...
64
64
12
5
58
snehapatil1/frappe
frappe/exceptions.py
Python
PermissionError
PermissionError
22
23
22
22
c110e1f26cc9d19abc0033cb51bb3f014c10582c
bigcode/the-stack
train
daad5c90c14c1d70e5931846
train
class
class InvalidEmailAddressError(ValidationError): pass
class InvalidEmailAddressError(ValidationError):
pass
pass class CancelledLinkError(LinkValidationError): pass class DocstatusTransitionError(ValidationError): pass class TimestampMismatchError(ValidationError): pass class EmptyTableError(ValidationError): pass class LinkExistsError(ValidationError): pass class InvalidEmailAddressError(ValidationError):
64
64
11
10
53
snehapatil1/frappe
frappe/exceptions.py
Python
InvalidEmailAddressError
InvalidEmailAddressError
77
77
77
77
65a2e6a1e096c8eb87e4b2a23fac418c8e62341f
bigcode/the-stack
train
cd3912d5102b376f8e8a54bb
train
class
class UnsupportedMediaType(Exception): http_status_code = 415
class UnsupportedMediaType(Exception):
http_status_code = 415
= 403 class DoesNotExistError(ValidationError): http_status_code = 404 class NameError(Exception): http_status_code = 409 class OutgoingEmailError(Exception): http_status_code = 501 class SessionStopped(Exception): http_status_code = 503 class UnsupportedMediaType(Exception):
64
64
13
6
57
snehapatil1/frappe
frappe/exceptions.py
Python
UnsupportedMediaType
UnsupportedMediaType
37
38
37
37
404bad3cedd020e64cc54ebc7b7f9f034fb44f04
bigcode/the-stack
train
6008ff9f5bdd0f0feadd7df9
train
class
class CharacterLengthExceededError(ValidationError): pass
class CharacterLengthExceededError(ValidationError):
pass
): pass class InvalidStatusError(ValidationError): pass class MandatoryError(ValidationError): pass class InvalidSignatureError(ValidationError): pass class RateLimitExceededError(ValidationError): pass class CannotChangeConstantError(ValidationError): pass class CharacterLengthExceededError(ValidationError):
64
64
11
10
53
snehapatil1/frappe
frappe/exceptions.py
Python
CharacterLengthExceededError
CharacterLengthExceededError
69
69
69
69
04bf40d9244a113e1d80411b6b9d11174f889953
bigcode/the-stack
train
054dc840e68131fbc63bae9f
train
class
class CSRFTokenError(Exception): http_status_code = 400
class CSRFTokenError(Exception):
http_status_code = 400
(Exception): http_status_code = 501 class SessionStopped(Exception): http_status_code = 503 class UnsupportedMediaType(Exception): http_status_code = 415 class RequestToken(Exception): http_status_code = 200 class Redirect(Exception): http_status_code = 301 class CSRFTokenError(Exception):
64
64
14
7
56
snehapatil1/frappe
frappe/exceptions.py
Python
CSRFTokenError
CSRFTokenError
46
47
46
46
569f1721e4854d7c857cdbb311eb34874b356896
bigcode/the-stack
train
5ea345d2eb49303d53a42c17
train
class
class LinkExistsError(ValidationError): pass
class LinkExistsError(ValidationError):
pass
): pass class LinkValidationError(ValidationError): pass class CancelledLinkError(LinkValidationError): pass class DocstatusTransitionError(ValidationError): pass class TimestampMismatchError(ValidationError): pass class EmptyTableError(ValidationError): pass class LinkExistsError(ValidationError):
64
64
10
9
54
snehapatil1/frappe
frappe/exceptions.py
Python
LinkExistsError
LinkExistsError
76
76
76
76
5237231e8c5b13cd15eb1cd8fd787e041f7ebe26
bigcode/the-stack
train
b38da77066682076d53180ba
train
class
class ImproperDBConfigurationError(Error): """ Used when frappe detects that database or tables are not properly configured """ def __init__(self, reason, msg=None): if not msg: msg = "MariaDb is not properly configured" super(ImproperDBConfigurationError, self).__init__(msg) self.reason = reason
class ImproperDBConfigurationError(Error):
""" Used when frappe detects that database or tables are not properly configured """ def __init__(self, reason, msg=None): if not msg: msg = "MariaDb is not properly configured" super(ImproperDBConfigurationError, self).__init__(msg) self.reason = reason
_status_code = 503 class UnsupportedMediaType(Exception): http_status_code = 415 class RequestToken(Exception): http_status_code = 200 class Redirect(Exception): http_status_code = 301 class CSRFTokenError(Exception): http_status_code = 400 class ImproperDBConfigurationError(Error):
64
64
76
8
55
snehapatil1/frappe
frappe/exceptions.py
Python
ImproperDBConfigurationError
ImproperDBConfigurationError
49
58
49
49
1b836edd90947d85fa6502dbe67d068b150dce0e
bigcode/the-stack
train
4a92836f9bd63d4c5183a70a
train
class
class Redirect(Exception): http_status_code = 301
class Redirect(Exception):
http_status_code = 301
(Exception): http_status_code = 409 class OutgoingEmailError(Exception): http_status_code = 501 class SessionStopped(Exception): http_status_code = 503 class UnsupportedMediaType(Exception): http_status_code = 415 class RequestToken(Exception): http_status_code = 200 class Redirect(Exception):
64
64
11
4
59
snehapatil1/frappe
frappe/exceptions.py
Python
Redirect
Redirect
43
44
43
43
011227add4ec3629d6fa9cd41de7d41fe2311ab3
bigcode/the-stack
train
dbaeed4338c5162030dd827b
train
class
class RequestToken(Exception): http_status_code = 200
class RequestToken(Exception):
http_status_code = 200
): http_status_code = 404 class NameError(Exception): http_status_code = 409 class OutgoingEmailError(Exception): http_status_code = 501 class SessionStopped(Exception): http_status_code = 503 class UnsupportedMediaType(Exception): http_status_code = 415 class RequestToken(Exception):
64
64
12
5
58
snehapatil1/frappe
frappe/exceptions.py
Python
RequestToken
RequestToken
40
41
40
40
072784a0831667cd2731c721414c08c07d049821
bigcode/the-stack
train
6b45ddab57d6dfc1b94112b4
train
class
class AuthenticationError(Exception): http_status_code = 401
class AuthenticationError(Exception):
http_status_code = 401
put anything in this file except exceptions from werkzeug.exceptions import NotFound # imports - third-party imports from pymysql import ProgrammingError as SQLError, Error # from pymysql import OperationalError as DatabaseOperationalError class ValidationError(Exception): http_status_code = 417 class Authenticatio...
64
64
12
5
58
snehapatil1/frappe
frappe/exceptions.py
Python
AuthenticationError
AuthenticationError
16
17
16
16
d1a87604cbbd61098d2fcec83e426878d9206379
bigcode/the-stack
train
04419b50bd9b14f909e03d2b
train
class
class EmptyTableError(ValidationError): pass
class EmptyTableError(ValidationError):
pass
pass class UpdateAfterSubmitError(ValidationError): pass class LinkValidationError(ValidationError): pass class CancelledLinkError(LinkValidationError): pass class DocstatusTransitionError(ValidationError): pass class TimestampMismatchError(ValidationError): pass class EmptyTableError(ValidationError):
64
64
10
9
54
snehapatil1/frappe
frappe/exceptions.py
Python
EmptyTableError
EmptyTableError
75
75
75
75
a13b111b69f3f7c6e2d3f28d210fbf56ab09de6e
bigcode/the-stack
train
0f95ddb3d6be3a6ab55a826b
train
function
def display(image, layers="*", width=None, height=None): """Display :ref:`image<images>` inline in a Jupyter notebook. Parameters ---------- image: :class:`dict`, required :ref:`Image<images>` to be displayed. layers: :class:`str`, optional Names of the image layers to display. Use...
def display(image, layers="*", width=None, height=None):
"""Display :ref:`image<images>` inline in a Jupyter notebook. Parameters ---------- image: :class:`dict`, required :ref:`Image<images>` to be displayed. layers: :class:`str`, optional Names of the image layers to display. Use "*" (the default) to display all layers. width: :cla...
# Copyright 2020 Timothy M. Shead # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writi...
182
194
648
13
168
shead-custom-design/imagecat
imagecat/notebook.py
Python
display
display
27
105
27
27
ab0c688d01a14b8074dd8ef03a47ca11c76d727d
bigcode/the-stack
train
779fb40ad1c4fd184b9669cb
train
class
class PsdpRamWrite(Memory): def __init__(self, bus, clock, reset=None, size=1024, mem=None, *args, **kwargs): self.bus = bus self.clock = clock self.reset = reset self.log = logging.getLogger(f"cocotb.{bus._entity._name}.{bus._name}") self.log.info("Parallel Simple Dual Por...
class PsdpRamWrite(Memory):
def __init__(self, bus, clock, reset=None, size=1024, mem=None, *args, **kwargs): self.bus = bus self.clock = clock self.reset = reset self.log = logging.getLogger(f"cocotb.{bus._entity._name}.{bus._name}") self.log.info("Parallel Simple Dual Port RAM model (write)") ...
wr_cmd_valid", "wr_cmd_ready", "wr_done"] class PsdpRamReadBus(BaseBus): _signals = ["rd_cmd_addr", "rd_cmd_valid", "rd_cmd_ready", "rd_resp_data", "rd_resp_valid", "rd_resp_ready"] class PsdpRamBus: def __init__(self, write=None, read=None, **kwargs): self.write = write self.read = read ...
256
256
1,018
8
248
totuwei/corundum
fpga/lib/pcie/tb/dma_psdp_ram.py
Python
PsdpRamWrite
PsdpRamWrite
83
196
83
84
19fe40018e838219326ab967c55b87e3d8d92891
bigcode/the-stack
train
225d6701d07a8db7e5fe0312
train
class
class PsdpRamRead(Memory): def __init__(self, bus, clock, reset=None, size=1024, mem=None, *args, **kwargs): self.bus = bus self.clock = clock self.reset = reset self.log = logging.getLogger(f"cocotb.{bus._entity._name}.{bus._name}") self.log.info("Parallel Simple Dual Port...
class PsdpRamRead(Memory):
def __init__(self, bus, clock, reset=None, size=1024, mem=None, *args, **kwargs): self.bus = bus self.clock = clock self.reset = reset self.log = logging.getLogger(f"cocotb.{bus._entity._name}.{bus._name}") self.log.info("Parallel Simple Dual Port RAM model (read)") ...
_be = (cmd_be_sample >> self.seg_be_width*seg) & self.seg_be_mask addr = (seg_addr*self.seg_count+seg)*self.seg_byte_lanes self.mem.seek(addr % self.size) data = seg_data.to_bytes(self.seg_byte_lanes, 'little') for i in range(self.seg_b...
256
256
1,082
8
248
totuwei/corundum
fpga/lib/pcie/tb/dma_psdp_ram.py
Python
PsdpRamRead
PsdpRamRead
199
324
199
200
5dcdf264ff7d0a5bbb980a623960ef44232a2839
bigcode/the-stack
train
11aa28591cc5c77a0d96d02f
train
class
class PsdpRamBus: def __init__(self, write=None, read=None, **kwargs): self.write = write self.read = read @classmethod def from_entity(cls, entity, **kwargs): write = PsdpRamWriteBus.from_entity(entity, **kwargs) read = PsdpRamReadBus.from_entity(entity, **kwargs) r...
class PsdpRamBus:
def __init__(self, write=None, read=None, **kwargs): self.write = write self.read = read @classmethod def from_entity(cls, entity, **kwargs): write = PsdpRamWriteBus.from_entity(entity, **kwargs) read = PsdpRamReadBus.from_entity(entity, **kwargs) return cls(write, r...
wr_cmd_valid", "wr_cmd_ready", "wr_done"] class PsdpRamReadBus(BaseBus): _signals = ["rd_cmd_addr", "rd_cmd_valid", "rd_cmd_ready", "rd_resp_data", "rd_resp_valid", "rd_resp_ready"] class PsdpRamBus:
63
64
190
6
57
totuwei/corundum
fpga/lib/pcie/tb/dma_psdp_ram.py
Python
PsdpRamBus
PsdpRamBus
59
80
59
59
3f999f033a5e1dcf1b1e1f6fa55036f79c375704
bigcode/the-stack
train
42542bacfd1f991e944da107
train
class
class PsdpRamReadBus(BaseBus): _signals = ["rd_cmd_addr", "rd_cmd_valid", "rd_cmd_ready", "rd_resp_data", "rd_resp_valid", "rd_resp_ready"]
class PsdpRamReadBus(BaseBus):
_signals = ["rd_cmd_addr", "rd_cmd_valid", "rd_cmd_ready", "rd_resp_data", "rd_resp_valid", "rd_resp_ready"]
kwargs): return cls(entity, prefix, **kwargs) class PsdpRamWriteBus(BaseBus): _signals = ["wr_cmd_be", "wr_cmd_addr", "wr_cmd_data", "wr_cmd_valid", "wr_cmd_ready", "wr_done"] class PsdpRamReadBus(BaseBus):
63
64
43
9
54
totuwei/corundum
fpga/lib/pcie/tb/dma_psdp_ram.py
Python
PsdpRamReadBus
PsdpRamReadBus
55
56
55
55
984e17456d412d0d50f2ba4c1f2d6ffe362dd900
bigcode/the-stack
train
aa3f9c32712d67915555803f
train
class
class PsdpRam(Memory): def __init__(self, bus, clock, reset=None, size=1024, mem=None, *args, **kwargs): self.write_if = None self.read_if = None super().__init__(size, mem, *args, **kwargs) self.write_if = PsdpRamWrite(bus.write, clock, reset, mem=self.mem) self.read_if = ...
class PsdpRam(Memory):
def __init__(self, bus, clock, reset=None, size=1024, mem=None, *args, **kwargs): self.write_if = None self.read_if = None super().__init__(size, mem, *args, **kwargs) self.write_if = PsdpRamWrite(bus.write, clock, reset, mem=self.mem) self.read_if = PsdpRamRead(bus.read, c...
.value = cmd_ready self.bus.rd_resp_data.value = resp_data self.bus.rd_resp_valid.value = resp_valid async def _run_pause(self): for val in self._pause_generator: self.pause = val await RisingEdge(self.clock) class PsdpRam(Memory):
64
64
104
7
57
totuwei/corundum
fpga/lib/pcie/tb/dma_psdp_ram.py
Python
PsdpRam
PsdpRam
327
335
327
327
8f7f88624362f30cf67b84773ec5afb94502e243
bigcode/the-stack
train
cc00808dc3efe1d2a3ebd0d3
train
class
class PsdpRamWriteBus(BaseBus): _signals = ["wr_cmd_be", "wr_cmd_addr", "wr_cmd_data", "wr_cmd_valid", "wr_cmd_ready", "wr_done"]
class PsdpRamWriteBus(BaseBus):
_signals = ["wr_cmd_be", "wr_cmd_addr", "wr_cmd_data", "wr_cmd_valid", "wr_cmd_ready", "wr_done"]
als, **kwargs) @classmethod def from_entity(cls, entity, **kwargs): return cls(entity, **kwargs) @classmethod def from_prefix(cls, entity, prefix, **kwargs): return cls(entity, prefix, **kwargs) class PsdpRamWriteBus(BaseBus):
64
64
42
9
55
totuwei/corundum
fpga/lib/pcie/tb/dma_psdp_ram.py
Python
PsdpRamWriteBus
PsdpRamWriteBus
51
52
51
51
eb920bf28da15cc4bcc0469429d262048660bc93
bigcode/the-stack
train
00a25f797cf9f8ce851fe6da
train
class
class BaseBus(Bus): _signals = ["data"] _optional_signals = [] def __init__(self, entity=None, prefix=None, **kwargs): super().__init__(entity, prefix, self._signals, optional_signals=self._optional_signals, **kwargs) @classmethod def from_entity(cls, entity, **kwargs): return cls...
class BaseBus(Bus):
_signals = ["data"] _optional_signals = [] def __init__(self, entity=None, prefix=None, **kwargs): super().__init__(entity, prefix, self._signals, optional_signals=self._optional_signals, **kwargs) @classmethod def from_entity(cls, entity, **kwargs): return cls(entity, **kwargs) ...
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import logging import cocotb from cocotb.triggers import RisingEdge from cocotb_bus.bus import Bus from cocotbext.axi.memory import Memory class BaseBus(Bus):
64
64
111
6
57
totuwei/corundum
fpga/lib/pcie/tb/dma_psdp_ram.py
Python
BaseBus
BaseBus
34
48
34
35
de7eb2cd41e822d2ceff4bc4645c5065396f19f5
bigcode/the-stack
train
141cfb5fd66957f0fc56e058
train
function
def test_lr_find_with_bs_scale(tmpdir): """Test that lr_find runs with batch_size_scaling""" class BoringModelTune(BoringModel): def __init__(self, learning_rate=0.1, batch_size=2): super().__init__() self.save_hyperparameters() model = BoringModelTune() before_lr = mod...
def test_lr_find_with_bs_scale(tmpdir):
"""Test that lr_find runs with batch_size_scaling""" class BoringModelTune(BoringModel): def __init__(self, learning_rate=0.1, batch_size=2): super().__init__() self.save_hyperparameters() model = BoringModelTune() before_lr = model.hparams.learning_rate # logger f...
a lr BEFORE running lr find""" trainer = Trainer(default_root_dir=tmpdir, max_steps=2, auto_lr_find=True) with pytest.raises(MisconfigurationException, match="should have one of these fields"): trainer.tune(BoringModel()) def test_lr_find_with_bs_scale(tmpdir):
64
64
159
10
54
Tshimanga/pytorch-lightning
tests/tuner/test_lr_finder.py
Python
test_lr_find_with_bs_scale
test_lr_find_with_bs_scale
230
248
230
230
4d09b1dd8dd3630df222a34df29d386de4025a82
bigcode/the-stack
train
5ea22c4a800c732df6b7803c
train
function
def test_datamodule_parameter(tmpdir): """Test that the datamodule parameter works""" seed_everything(1) dm = ClassifDataModule() model = ClassificationModel() before_lr = model.lr # logger file to get meta trainer = Trainer(default_root_dir=tmpdir, max_epochs=2) lrfinder = trainer.tu...
def test_datamodule_parameter(tmpdir):
"""Test that the datamodule parameter works""" seed_everything(1) dm = ClassifDataModule() model = ClassificationModel() before_lr = model.lr # logger file to get meta trainer = Trainer(default_root_dir=tmpdir, max_epochs=2) lrfinder = trainer.tuner.lr_find(model, datamodule=dm) a...
trainer.tuner.lr_find(model, mode="linear") after_lr = lrfinder.suggestion() model.learning_rate = after_lr trainer.tune(model) assert before_lr != after_lr, "Learning rate was not altered after running learning rate finder" def test_datamodule_parameter(tmpdir):
64
64
127
9
55
Tshimanga/pytorch-lightning
tests/tuner/test_lr_finder.py
Python
test_datamodule_parameter
test_datamodule_parameter
155
170
155
155
28a20cd6f78db900ef5e26c60ea413ef684f7b8f
bigcode/the-stack
train
5eab766e7c8e48011b4ac321
train
function
@pytest.mark.parametrize("use_hparams", [False, True]) def test_trainer_arg_str(tmpdir, use_hparams): """Test that setting trainer arg to string works""" hparams = EvalModelTemplate.get_default_hparams() model = EvalModelTemplate(**hparams) model.my_fancy_lr = 1.0 # update with non-standard field m...
@pytest.mark.parametrize("use_hparams", [False, True]) def test_trainer_arg_str(tmpdir, use_hparams):
"""Test that setting trainer arg to string works""" hparams = EvalModelTemplate.get_default_hparams() model = EvalModelTemplate(**hparams) model.my_fancy_lr = 1.0 # update with non-standard field model.hparams["my_fancy_lr"] = 1.0 before_lr = model.my_fancy_lr if use_hparams: del mo...
after_lr = model.hparams.learning_rate else: after_lr = model.learning_rate assert before_lr != after_lr, "Learning rate was not altered after running learning rate finder" @pytest.mark.parametrize("use_hparams", [False, True]) def test_trainer_arg_str(tmpdir, use_hparams):
67
67
226
26
41
Tshimanga/pytorch-lightning
tests/tuner/test_lr_finder.py
Python
test_trainer_arg_str
test_trainer_arg_str
110
131
110
111
b011506bedb795db218d3ab9a26073aec0ecef9f
bigcode/the-stack
train
b7f27b2174f40c3609bd9421
train
function
def test_suggestion_parameters_work(tmpdir): """Test that default skipping does not alter results in basic case""" dm = ClassifDataModule() model = ClassificationModel() # logger file to get meta trainer = Trainer(default_root_dir=tmpdir, max_epochs=3) lrfinder = trainer.tuner.lr_find(model, ...
def test_suggestion_parameters_work(tmpdir):
"""Test that default skipping does not alter results in basic case""" dm = ClassifDataModule() model = ClassificationModel() # logger file to get meta trainer = Trainer(default_root_dir=tmpdir, max_epochs=3) lrfinder = trainer.tuner.lr_find(model, datamodule=dm) lr1 = lrfinder.suggestion(...
= trainer.tuner.lr_find(model, early_stop_threshold=None) assert lrfinder.suggestion() != 1e-3 assert len(lrfinder.results["lr"]) == 100 assert lrfinder._total_batch_idx == 199 def test_suggestion_parameters_work(tmpdir):
64
64
139
9
54
Tshimanga/pytorch-lightning
tests/tuner/test_lr_finder.py
Python
test_suggestion_parameters_work
test_suggestion_parameters_work
190
203
190
190
8dbcb57c014d054098ec9b325e45ec4b06310783
bigcode/the-stack
train
aada51ae756e9de4c68de66b
train
function
def test_model_reset_correctly(tmpdir): """Check that model weights are correctly reset after lr_find()""" model = EvalModelTemplate() # logger file to get meta trainer = Trainer(default_root_dir=tmpdir, max_epochs=1) before_state_dict = deepcopy(model.state_dict()) trainer.tuner.lr_find(mod...
def test_model_reset_correctly(tmpdir):
"""Check that model weights are correctly reset after lr_find()""" model = EvalModelTemplate() # logger file to get meta trainer = Trainer(default_root_dir=tmpdir, max_epochs=1) before_state_dict = deepcopy(model.state_dict()) trainer.tuner.lr_find(model, num_training=5) after_state_dic...
_optimizers = model.configure_optimizers__multiple_schedulers # logger file to get meta trainer = Trainer(default_root_dir=tmpdir, max_epochs=1) with pytest.raises(MisconfigurationException): trainer.tuner.lr_find(model) def test_model_reset_correctly(tmpdir):
64
64
143
9
55
Tshimanga/pytorch-lightning
tests/tuner/test_lr_finder.py
Python
test_model_reset_correctly
test_model_reset_correctly
41
60
41
41
6a038891c781806ff5552f8cf67387b64d5b5ecd
bigcode/the-stack
train
e5a1b3645414e597815791a5
train
function
@pytest.mark.parametrize("optimizer", ["Adam", "Adagrad"]) def test_call_to_trainer_method(tmpdir, optimizer): """Test that directly calling the trainer method works""" hparams = EvalModelTemplate.get_default_hparams() model = EvalModelTemplate(**hparams) if optimizer == "adagrad": model.config...
@pytest.mark.parametrize("optimizer", ["Adam", "Adagrad"]) def test_call_to_trainer_method(tmpdir, optimizer):
"""Test that directly calling the trainer method works""" hparams = EvalModelTemplate.get_default_hparams() model = EvalModelTemplate(**hparams) if optimizer == "adagrad": model.configure_optimizers = model.configure_optimizers__adagrad before_lr = hparams.get("learning_rate") # logger...
params.my_fancy_lr else: after_lr = model.my_fancy_lr assert before_lr != after_lr, "Learning rate was not altered after running learning rate finder" @pytest.mark.parametrize("optimizer", ["Adam", "Adagrad"]) def test_call_to_trainer_method(tmpdir, optimizer):
64
64
177
25
39
Tshimanga/pytorch-lightning
tests/tuner/test_lr_finder.py
Python
test_call_to_trainer_method
test_call_to_trainer_method
134
152
134
135
245a203c027ff364e967dc145dfa90ead8c517e9
bigcode/the-stack
train
3d3c6d0eb13464ad5b1f7809
train
function
def test_accumulation_and_early_stopping(tmpdir): """Test that early stopping of learning rate finder works, and that accumulation also works for this feature""" class TestModel(BoringModel): def __init__(self): super().__init__() self.lr = 1e-3 model = TestModel() trai...
def test_accumulation_and_early_stopping(tmpdir):
"""Test that early stopping of learning rate finder works, and that accumulation also works for this feature""" class TestModel(BoringModel): def __init__(self): super().__init__() self.lr = 1e-3 model = TestModel() trainer = Trainer(default_root_dir=tmpdir, accumulate_...
= trainer.tuner.lr_find(model, datamodule=dm) after_lr = lrfinder.suggestion() model.lr = after_lr assert before_lr != after_lr, "Learning rate was not altered after running learning rate finder" def test_accumulation_and_early_stopping(tmpdir):
64
64
146
13
51
Tshimanga/pytorch-lightning
tests/tuner/test_lr_finder.py
Python
test_accumulation_and_early_stopping
test_accumulation_and_early_stopping
173
187
173
173
200882cc170fa226fa35597e74fd96d60db0e25b
bigcode/the-stack
train
6bb1afcd3597c5494c6dc8f9
train
function
@pytest.mark.parametrize("use_hparams", [False, True]) def test_trainer_arg_bool(tmpdir, use_hparams): """Test that setting trainer arg to bool works""" hparams = EvalModelTemplate.get_default_hparams() model = EvalModelTemplate(**hparams) before_lr = hparams.get("learning_rate") if use_hparams: ...
@pytest.mark.parametrize("use_hparams", [False, True]) def test_trainer_arg_bool(tmpdir, use_hparams):
"""Test that setting trainer arg to bool works""" hparams = EvalModelTemplate.get_default_hparams() model = EvalModelTemplate(**hparams) before_lr = hparams.get("learning_rate") if use_hparams: del model.learning_rate model.configure_optimizers = model.configure_optimizers__lr_from_h...
, num_training=5) actual = {ca: getattr(trainer, ca) for ca in changed_attributes} assert actual == expected assert model.trainer == trainer @pytest.mark.parametrize("use_hparams", [False, True]) def test_trainer_arg_bool(tmpdir, use_hparams):
64
64
182
26
37
Tshimanga/pytorch-lightning
tests/tuner/test_lr_finder.py
Python
test_trainer_arg_bool
test_trainer_arg_bool
88
107
88
89
2fd71de177f483539157cbaa4b950a154d763a1b
bigcode/the-stack
train
b6dce607e013ffd7b348514f
train
function
def test_lr_finder_fails_fast_on_bad_config(tmpdir): """Test that tune fails if the model does not have a lr BEFORE running lr find""" trainer = Trainer(default_root_dir=tmpdir, max_steps=2, auto_lr_find=True) with pytest.raises(MisconfigurationException, match="should have one of these fields"): tr...
def test_lr_finder_fails_fast_on_bad_config(tmpdir):
"""Test that tune fails if the model does not have a lr BEFORE running lr find""" trainer = Trainer(default_root_dir=tmpdir, max_steps=2, auto_lr_find=True) with pytest.raises(MisconfigurationException, match="should have one of these fields"): trainer.tune(BoringModel())
.suggestion() lrfinder.results["loss"][-1] = float("nan") after_lr = lrfinder.suggestion() assert before_lr == after_lr, "Learning rate was altered because of non-finite loss values" def test_lr_finder_fails_fast_on_bad_config(tmpdir):
64
64
80
14
50
Tshimanga/pytorch-lightning
tests/tuner/test_lr_finder.py
Python
test_lr_finder_fails_fast_on_bad_config
test_lr_finder_fails_fast_on_bad_config
223
227
223
223
4a9cd07a2fb9deeb68cad0b1510af46fad27b7ff
bigcode/the-stack
train
58fb53c50e5c7f0cd61978e4
train
function
def test_error_on_more_than_1_optimizer(tmpdir): """Check that error is thrown when more than 1 optimizer is passed""" model = EvalModelTemplate() model.configure_optimizers = model.configure_optimizers__multiple_schedulers # logger file to get meta trainer = Trainer(default_root_dir=tmpdir, max_e...
def test_error_on_more_than_1_optimizer(tmpdir):
"""Check that error is thrown when more than 1 optimizer is passed""" model = EvalModelTemplate() model.configure_optimizers = model.configure_optimizers__multiple_schedulers # logger file to get meta trainer = Trainer(default_root_dir=tmpdir, max_epochs=1) with pytest.raises(Misconfiguration...
Trainer from pytorch_lightning.utilities.exceptions import MisconfigurationException from tests.base import EvalModelTemplate from tests.helpers import BoringModel from tests.helpers.datamodules import ClassifDataModule from tests.helpers.simple_models import ClassificationModel def test_error_on_more_than_1_optimizer...
64
64
93
12
51
Tshimanga/pytorch-lightning
tests/tuner/test_lr_finder.py
Python
test_error_on_more_than_1_optimizer
test_error_on_more_than_1_optimizer
28
38
28
28
ab0efd711c98ec5d6921320fda3ee9ac35502eaf
bigcode/the-stack
train
f923243ec765c20e6d857ed1
train
function
def test_lr_finder_ends_before_num_training(tmpdir): """Tests learning rate finder ends before `num_training` steps.""" class TestModel(BoringModel): def __init__(self, learning_rate=0.1): super().__init__() self.save_hyperparameters() def training_step_end(self, output...
def test_lr_finder_ends_before_num_training(tmpdir):
"""Tests learning rate finder ends before `num_training` steps.""" class TestModel(BoringModel): def __init__(self, learning_rate=0.1): super().__init__() self.save_hyperparameters() def training_step_end(self, outputs): assert self.global_step < num_trainin...
.tuner.lr_find(model, max_lr=lr_min, min_lr=lr_max, num_training=3) lr_candidates = lr_finder.results["lr"] assert all(lr_min <= lr <= lr_max for lr in lr_candidates) def test_lr_finder_ends_before_num_training(tmpdir):
64
64
121
13
51
Tshimanga/pytorch-lightning
tests/tuner/test_lr_finder.py
Python
test_lr_finder_ends_before_num_training
test_lr_finder_ends_before_num_training
269
284
269
269
a75a07a61a7469f5486e0a9bf06a97e56e521c8f
bigcode/the-stack
train
7d2badd4a930f573d77dbeeb
train
function
def test_suggestion_with_non_finite_values(tmpdir): """Test that non-finite values does not alter results""" hparams = EvalModelTemplate.get_default_hparams() model = EvalModelTemplate(**hparams) # logger file to get meta trainer = Trainer(default_root_dir=tmpdir, max_epochs=3) lrfinder = tra...
def test_suggestion_with_non_finite_values(tmpdir):
"""Test that non-finite values does not alter results""" hparams = EvalModelTemplate.get_default_hparams() model = EvalModelTemplate(**hparams) # logger file to get meta trainer = Trainer(default_root_dir=tmpdir, max_epochs=3) lrfinder = trainer.tuner.lr_find(model) before_lr = lrfinder.s...
uggestion(skip_begin=10) # default lr2 = lrfinder.suggestion(skip_begin=150) # way too high, should have an impact assert lr1 != lr2, "Skipping parameter did not influence learning rate" def test_suggestion_with_non_finite_values(tmpdir):
64
64
140
12
52
Tshimanga/pytorch-lightning
tests/tuner/test_lr_finder.py
Python
test_suggestion_with_non_finite_values
test_suggestion_with_non_finite_values
206
220
206
206
3991faa6de46dab651f867233e903657959d9c83
bigcode/the-stack
train
9b00f29a7ff6ce300025bf21
train
function
def test_lr_candidates_between_min_and_max(tmpdir): """Test that learning rate candidates are between min_lr and max_lr.""" class TestModel(BoringModel): def __init__(self, learning_rate=0.1): super().__init__() self.save_hyperparameters() model = TestModel() trainer = ...
def test_lr_candidates_between_min_and_max(tmpdir):
"""Test that learning rate candidates are between min_lr and max_lr.""" class TestModel(BoringModel): def __init__(self, learning_rate=0.1): super().__init__() self.save_hyperparameters() model = TestModel() trainer = Trainer(default_root_dir=tmpdir) lr_min = 1e-8 ...
auto_lr_find=True, auto_scale_batch_size=True) result = trainer.tune(model) bs = result["scale_batch_size"] lr = result["lr_find"].suggestion() assert lr != before_lr assert isinstance(bs, int) def test_lr_candidates_between_min_and_max(tmpdir):
64
64
153
11
53
Tshimanga/pytorch-lightning
tests/tuner/test_lr_finder.py
Python
test_lr_candidates_between_min_and_max
test_lr_candidates_between_min_and_max
251
266
251
251
cefde32424a9ffd673952d204bf0e7cee52e0ef7
bigcode/the-stack
train
50da1acb0612069835f3420a
train
function
def test_trainer_reset_correctly(tmpdir): """Check that all trainer parameters are reset correctly after lr_find()""" model = EvalModelTemplate() # logger file to get meta trainer = Trainer(default_root_dir=tmpdir, max_epochs=1) changed_attributes = [ "accumulate_grad_batches", "a...
def test_trainer_reset_correctly(tmpdir):
"""Check that all trainer parameters are reset correctly after lr_find()""" model = EvalModelTemplate() # logger file to get meta trainer = Trainer(default_root_dir=tmpdir, max_epochs=1) changed_attributes = [ "accumulate_grad_batches", "auto_lr_find", "callbacks", ...
in before_state_dict.keys(): assert torch.all( torch.eq(before_state_dict[key], after_state_dict[key]) ), "Model was not reset correctly after learning rate finder" assert not os.path.exists(tmpdir / "lr_find_temp_model.ckpt") def test_trainer_reset_correctly(tmpdir):
64
64
162
10
54
Tshimanga/pytorch-lightning
tests/tuner/test_lr_finder.py
Python
test_trainer_reset_correctly
test_trainer_reset_correctly
63
85
63
63
a906ef25ea5152f07a428ba6dfd96002adcf8954
bigcode/the-stack
train
23d35f8ca5e014889848f237
train
class
class ModelTests(TestCase): def test_create_user_with_email_successful(self): email = 'test@test.com' password = 'test1234' user = get_user_model().objects.create_user( email=email, password=password ) self.assertEqual(user.email, email) s...
class ModelTests(TestCase):
def test_create_user_with_email_successful(self): email = 'test@test.com' password = 'test1234' user = get_user_model().objects.create_user( email=email, password=password ) self.assertEqual(user.email, email) self.assertTrue(user.check_pas...
from django.test import TestCase from django.contrib.auth import get_user_model class ModelTests(TestCase):
22
64
199
6
15
jakemcannon/recipe-app-api
app/core/tests/test_models.py
Python
ModelTests
ModelTests
5
33
5
6
b2eba2cea376d8f2df3fdb92d3c6f14752f35516
bigcode/the-stack
train
56be4837309bdd6d274a1627
train
class
class AdminSiteTests(TestCase): def setUp(self): self.client = Client() self.admin_user = get_user_model().objects.create_superuser( email='admin@mb.com', password='password123' ) self.client.force_login(self.admin_user) self.user = get_user_model()....
class AdminSiteTests(TestCase):
def setUp(self): self.client = Client() self.admin_user = get_user_model().objects.create_superuser( email='admin@mb.com', password='password123' ) self.client.force_login(self.admin_user) self.user = get_user_model().objects.create_user( ...
from django.test import TestCase, Client from django.contrib.auth import get_user_model from django.urls import reverse class AdminSiteTests(TestCase):
31
76
256
7
23
rskumarmb/rest-python
app/core/tests/test_admin.py
Python
AdminSiteTests
AdminSiteTests
6
44
6
7
22b031fa11d3660be02cfb4cc8bfb0cfb7ecc255
bigcode/the-stack
train
fc2c5c545a5149fb49d8aedd
train
function
def execute(request): data = json.loads(request.body) sql= data["sql"] print("Execute: "+sql) print("Connection: "+str(connection)) cur = connection.cursor() cur.execute(sql) result= "" print("Row count: "+str(cur.rowcount)) try: if cur.rowcount > 0: ...
def execute(request):
data = json.loads(request.body) sql= data["sql"] print("Execute: "+sql) print("Connection: "+str(connection)) cur = connection.cursor() cur.execute(sql) result= "" print("Row count: "+str(cur.rowcount)) try: if cur.rowcount > 0: row = cur.fetchone...
from django.shortcuts import render from django.http import HttpResponse import json import psycopg2 datasource = "" # Create your views here. def index(request): return HttpResponse("Quartet") def execute(request):
48
64
164
4
44
digitalemil/quartett
python/quartetapp/views.py
Python
execute
execute
13
44
13
13
300b82750977b9c34876e36858153ac062bb9af4
bigcode/the-stack
train
35db784849f17608aa9cc3f8
train
function
def index(request): return HttpResponse("Quartet")
def index(request):
return HttpResponse("Quartet")
from django.shortcuts import render from django.http import HttpResponse import json import psycopg2 datasource = "" # Create your views here. def index(request):
36
64
12
4
32
digitalemil/quartett
python/quartetapp/views.py
Python
index
index
10
11
10
10
45d2cd81440bea44736dd11fa318f67e1a56af31
bigcode/the-stack
train
815c3420f4e2ea72094242b7
train
function
def datasource(request): print ("Raw Data: %s " %request.body ) data = json.loads(request.body) print("host="+data["ip"]+" port="+data["port"]+" dbname="+data["dbname"]+" user="+data["user"]+" password="+data["password"]) global connection connection = psycopg2.connect("host="+data["ip"]+" port="+...
def datasource(request):
print ("Raw Data: %s " %request.body ) data = json.loads(request.body) print("host="+data["ip"]+" port="+data["port"]+" dbname="+data["dbname"]+" user="+data["user"]+" password="+data["password"]) global connection connection = psycopg2.connect("host="+data["ip"]+" port="+data["port"]+" dbname="+d...
row = cur.fetchone() except (RuntimeError, TypeError, NameError, psycopg2.ProgrammingError): pass result= result+ cur.statusmessage print("Query returned: %s" % ( result )) cur.close() return HttpResponse(result) def datasource(request):
64
64
129
4
60
digitalemil/quartett
python/quartetapp/views.py
Python
datasource
datasource
46
55
46
46
8c787c20ef5d8285351a395f3a6f398fbf4d373c
bigcode/the-stack
train
d932170636892e648b86ae6d
train
function
def index(request): return render(request, 'index.html')
def index(request):
return render(request, 'index.html')
connection = psycopg2.connect("host="+data["ip"]+" port="+data["port"]+" dbname="+data["dbname"]+" user="+data["user"]+" password="+data["password"]) connection.set_session(autocommit=True) return HttpResponse("Datasource") def index(request):
64
64
13
4
60
digitalemil/quartett
python/quartetapp/views.py
Python
index
index
58
59
58
58
65bb9ba98fcd4c987cd78b3b5fe70897116396b0
bigcode/the-stack
train
b98f631757f9e63c7aea25dc
train
class
class Migration(migrations.Migration): dependencies = [ ("sites", "0002_alter_domain_unique"), ] operations = [ migrations.RunPython(create_site), ]
class Migration(migrations.Migration):
dependencies = [ ("sites", "0002_alter_domain_unique"), ] operations = [ migrations.RunPython(create_site), ]
muddy-cloud-30262.botics.co" site_params = { "name": "Muddy Cloud", } if custom_domain: site_params["domain"] = custom_domain Site.objects.update_or_create(defaults=site_params, id=1) class Migration(migrations.Migration):
64
64
38
7
57
crowdbotics-apps/muddy-cloud-30262
backend/home/migrations/0001_load_initial_data.py
Python
Migration
Migration
17
25
17
18
a00e759b1f365f6ee5c2b777b5b85c800f49887b
bigcode/the-stack
train
8c23c1bfb9e5bacb3aee4b7e
train
function
def create_site(apps, schema_editor): Site = apps.get_model("sites", "Site") custom_domain = "muddy-cloud-30262.botics.co" site_params = { "name": "Muddy Cloud", } if custom_domain: site_params["domain"] = custom_domain Site.objects.update_or_create(defaults=site_params, id=1)
def create_site(apps, schema_editor):
Site = apps.get_model("sites", "Site") custom_domain = "muddy-cloud-30262.botics.co" site_params = { "name": "Muddy Cloud", } if custom_domain: site_params["domain"] = custom_domain Site.objects.update_or_create(defaults=site_params, id=1)
from django.db import migrations def create_site(apps, schema_editor):
15
64
83
9
5
crowdbotics-apps/muddy-cloud-30262
backend/home/migrations/0001_load_initial_data.py
Python
create_site
create_site
4
14
4
4
666b606a87e317c38cb1eeb4a64d2b648fce2ef6
bigcode/the-stack
train
65f7c14ebe7272f6edeef269
train
class
class KeywordsGenerator(BaseEstimator, TransformerMixin): """Class to extract list of keywords from text. It is compatible with scikit-learn API (i.e. contains fit, transform methods). Parameters ---------- max_tfidf_features : int, optional Size of vocabulary for tfidf. Defau...
class KeywordsGenerator(BaseEstimator, TransformerMixin):
"""Class to extract list of keywords from text. It is compatible with scikit-learn API (i.e. contains fit, transform methods). Parameters ---------- max_tfidf_features : int, optional Size of vocabulary for tfidf. Default value, 10000. keywords : list, optional Ke...
import copy import numpy as np import pandas as pd import scipy.sparse as sp from collections import Counter from sklearn.base import BaseEstimator, TransformerMixin from sklearn.feature_extraction.text import TfidfVectorizer from melusine.utils.transformer_scheduler import TransformerScheduler from melusine import con...
104
256
1,907
9
95
DataFactory-Verlingue/melusine
melusine/summarizer/keywords_generator.py
Python
KeywordsGenerator
KeywordsGenerator
15
279
15
15
0f0cb6c7d7e07664e796c8a05ede04db0e5d641a
bigcode/the-stack
train
27e2381c272dff047d944545
train
function
def pic50(ic50, unit=None, digits=3): """Calculate pIC50 from IC50. Optionally, a unit for the input IC50 value may be given. Known units are: mM, uM, nM, pM""" if unit is not None: ic50 *= unit_factor(unit) return np.round(-math.log10(ic50), decimals=digits)
def pic50(ic50, unit=None, digits=3):
"""Calculate pIC50 from IC50. Optionally, a unit for the input IC50 value may be given. Known units are: mM, uM, nM, pM""" if unit is not None: ic50 *= unit_factor(unit) return np.round(-math.log10(ic50), decimals=digits)
. Raises ValueError for unknown unit.""" units = ["mm", "um", "nm", "pm"] pos = units.index(unit.lower()) + 1 factor = 10 ** -(pos * 3) return factor def pic50(ic50, unit=None, digits=3):
64
64
85
13
50
apahl/mol_frame
mol_frame/tools.py
Python
pic50
pic50
55
60
55
55
1b502a39447b1749209a5649d5ef52f70fb2f6bd
bigcode/the-stack
train
43095575df2aef5f93d34019
train
function
def unit_factor(unit): """Return the factor corresponding to the unit, e.g. 1E-9 for nM. Known units are: mM, uM, nM, pM. Raises ValueError for unknown unit.""" units = ["mm", "um", "nm", "pm"] pos = units.index(unit.lower()) + 1 factor = 10 ** -(pos * 3) return factor
def unit_factor(unit):
"""Return the factor corresponding to the unit, e.g. 1E-9 for nM. Known units are: mM, uM, nM, pM. Raises ValueError for unknown unit.""" units = ["mm", "um", "nm", "pm"] pos = units.index(unit.lower()) + 1 factor = 10 ** -(pos * 3) return factor
print("Configuration file {}.yaml not found.".format(conf)) print("`load_resources()` will not work.") print("Have a look at the *.yaml files in the `conf` folder") print("for templates and locations.") config = {} return config def unit_factor(unit):
64
64
94
5
58
apahl/mol_frame
mol_frame/tools.py
Python
unit_factor
unit_factor
46
52
46
46
3bfb34bfaa8e0f81cb20afbe4a1ec5b536f44535
bigcode/the-stack
train
da930dea9fd11ac4876cef82
train
function
def erg_sim(fp1, fp2): """Taken from iwatobipen's excellent blog: https://iwatobipen.wordpress.com/2016/01/16/ergfingerprint-in-rdkit/""" denominator = ( np.sum(np.dot(fp1, fp1)) + np.sum(np.dot(fp2, fp2)) - np.sum(np.dot(fp1, fp2)) ) numerator = np.sum(np.dot(fp1, fp2)) return numerator...
def erg_sim(fp1, fp2):
"""Taken from iwatobipen's excellent blog: https://iwatobipen.wordpress.com/2016/01/16/ergfingerprint-in-rdkit/""" denominator = ( np.sum(np.dot(fp1, fp1)) + np.sum(np.dot(fp2, fp2)) - np.sum(np.dot(fp1, fp2)) ) numerator = np.sum(np.dot(fp1, fp2)) return numerator / denominator
be given. Known units are: mM, uM, nM, pM""" ic50 = 10 ** (-pic50) if unit is not None: ic50 /= unit_factor(unit) return np.round(ic50, digits) def erg_sim(fp1, fp2):
64
64
105
9
55
apahl/mol_frame
mol_frame/tools.py
Python
erg_sim
erg_sim
72
79
72
72
3a71df343651a83b9f6c70d1af0d92ebe0c2c115
bigcode/the-stack
train
6d117e5ab434244551d47b9d
train
function
def ic50(pic50, unit=None, digits=3): """Calculate IC50 from pIC50. Optionally, a unit for the returned IC50 value may be given. Known units are: mM, uM, nM, pM""" ic50 = 10 ** (-pic50) if unit is not None: ic50 /= unit_factor(unit) return np.round(ic50, digits)
def ic50(pic50, unit=None, digits=3):
"""Calculate IC50 from pIC50. Optionally, a unit for the returned IC50 value may be given. Known units are: mM, uM, nM, pM""" ic50 = 10 ** (-pic50) if unit is not None: ic50 /= unit_factor(unit) return np.round(ic50, digits)
may be given. Known units are: mM, uM, nM, pM""" if unit is not None: ic50 *= unit_factor(unit) return np.round(-math.log10(ic50), decimals=digits) def ic50(pic50, unit=None, digits=3):
64
64
90
13
51
apahl/mol_frame
mol_frame/tools.py
Python
ic50
ic50
63
69
63
63
0a24a8ba79e8487529d4942eeedec23aaee852bb
bigcode/the-stack
train
c7a3d4a63c940cea69c7a1a6
train
function
def load_config(conf="config"): """Loads configuration from default location and returns config object. Known configuration files are `config.yaml` and `plates.yaml`. Raises error when the file could not be loaded.""" assert conf in ["config", "plates"] if "HOME" in os.environ: conf_fn ...
def load_config(conf="config"):
"""Loads configuration from default location and returns config object. Known configuration files are `config.yaml` and `plates.yaml`. Raises error when the file could not be loaded.""" assert conf in ["config", "plates"] if "HOME" in os.environ: conf_fn = op.join( os.enviro...
-*- """ ##### Tools ##### *Created on Mon, Jan 22 2018, 12:00 by A. Pahl* Helper Tools, e.g. for loading the configuration. """ import os import os.path as op import yaml import math import numpy as np def load_config(conf="config"):
69
69
233
7
61
apahl/mol_frame
mol_frame/tools.py
Python
load_config
load_config
21
43
21
21
f407a411ed19e19de048709504576354c3e20872
bigcode/the-stack
train
d8c67f1ad02bbc647dc42300
train
function
@pytest.mark.matplotlib def test_plot_corr_grid(close_figures): hie_data = randhie.load_pandas() corr_matrix = np.corrcoef(hie_data.data.values.T) plot_corr_grid([corr_matrix] * 2, xnames=hie_data.names) plot_corr_grid([corr_matrix] * 5, xnames=[], ynames=hie_data.names) plot_corr_grid([corr_matr...
@pytest.mark.matplotlib def test_plot_corr_grid(close_figures):
hie_data = randhie.load_pandas() corr_matrix = np.corrcoef(hie_data.data.values.T) plot_corr_grid([corr_matrix] * 2, xnames=hie_data.names) plot_corr_grid([corr_matrix] * 5, xnames=[], ynames=hie_data.names) plot_corr_grid([corr_matrix] * 3, normcolor=True, titles='', cmap='jet')
.T) plot_corr(corr_matrix, xnames=hie_data.names) plot_corr(corr_matrix, xnames=[], ynames=hie_data.names) plot_corr(corr_matrix, normcolor=True, title='', cmap='jet') @pytest.mark.matplotlib def test_plot_corr_grid(close_figures):
64
64
103
14
50
CCHiggins/statsmodels
statsmodels/graphics/tests/test_correlation.py
Python
test_plot_corr_grid
test_plot_corr_grid
20
29
20
21
d561719cc5c7b569581593370419b9a1368099d6
bigcode/the-stack
train
727920678499df1730f7c24e
train
function
@pytest.mark.matplotlib def test_plot_corr(close_figures): hie_data = randhie.load_pandas() corr_matrix = np.corrcoef(hie_data.data.values.T) plot_corr(corr_matrix, xnames=hie_data.names) plot_corr(corr_matrix, xnames=[], ynames=hie_data.names) plot_corr(corr_matrix, normcolor=True, title='', cma...
@pytest.mark.matplotlib def test_plot_corr(close_figures):
hie_data = randhie.load_pandas() corr_matrix = np.corrcoef(hie_data.data.values.T) plot_corr(corr_matrix, xnames=hie_data.names) plot_corr(corr_matrix, xnames=[], ynames=hie_data.names) plot_corr(corr_matrix, normcolor=True, title='', cmap='jet')
import numpy as np import pytest from statsmodels.datasets import randhie from statsmodels.graphics.correlation import plot_corr, plot_corr_grid @pytest.mark.matplotlib def test_plot_corr(close_figures):
44
64
87
13
30
CCHiggins/statsmodels
statsmodels/graphics/tests/test_correlation.py
Python
test_plot_corr
test_plot_corr
8
17
8
9
25b2312639091fdbb3a4f624a429b2b522ac17c2
bigcode/the-stack
train
54d5e6bf328ac54b9b9ca6dc
train
function
def evaluate_GAR(similarity_score, actual_label): if len(similarity_score) != len(actual_label): print("similarity score and actual labels do not match in size") return thresholds = np.linspace(1, 0, num=500) GARs = [] FMRs = [] thresholds_list = [] thresholds_false_images_dict...
def evaluate_GAR(similarity_score, actual_label):
if len(similarity_score) != len(actual_label): print("similarity score and actual labels do not match in size") return thresholds = np.linspace(1, 0, num=500) GARs = [] FMRs = [] thresholds_list = [] thresholds_false_images_dict = dict() for thresh in thresholds: fa...
[idx]: fnmr_fmr1000 = FRRs[idx] if fmr == 0: # FMR0 if fnmr_fmr0 > FRRs[idx]: fnmr_fmr0 = FRRs[idx] # Calculate EER eer = err(FARs, FRRs) return [fnmr_fmr0, fnmr_fmr100, fnmr_fmr1000, eer, thresholds, FARs, FRRs] def evaluate_GAR(similarity_score, actua...
111
111
371
11
100
sachith500/MaskedFaceRepresentation
utils/graph_util.py
Python
evaluate_GAR
evaluate_GAR
149
190
149
149
0df29f0d89c3cbf069bb10594964efb014274642
bigcode/the-stack
train
7aa640ac56251b9903827ce5
train
function
def get_similarity_scores(references, probes): if len(references) != len(probes): print("references and probes do not match in size") return distances = get_dist(references, probes) similarities = 1 / (1 + distances) return similarities
def get_similarity_scores(references, probes):
if len(references) != len(probes): print("references and probes do not match in size") return distances = get_dist(references, probes) similarities = 1 / (1 + distances) return similarities
ferences - probes, axis=1) def min_max_normalize(distance_matrix): temp = distance_matrix - np.min(distance_matrix) return temp / np.max(distance_matrix) # call with two arrays one containing the reference features and the other containing the corresponding probe features def get_similarity_scores(reference...
64
64
60
9
54
sachith500/MaskedFaceRepresentation
utils/graph_util.py
Python
get_similarity_scores
get_similarity_scores
31
38
31
31
b8e3c4cf2e926c09a858cda667d942e677a06a98
bigcode/the-stack
train
c3debbb388413a38cfd22155
train
function
def save_reference_and_probe(dataset_base_folder, image_1_path, image_2_path, reference_label, probel_label, match_status, sim, thresh, test_image_saving_folder): threshold_folder = f"{test_image_saving_folder}/{str(thresh)[:5]}" if not os.path.isdir(test_image_saving_folder): ...
def save_reference_and_probe(dataset_base_folder, image_1_path, image_2_path, reference_label, probel_label, match_status, sim, thresh, test_image_saving_folder):
threshold_folder = f"{test_image_saving_folder}/{str(thresh)[:5]}" if not os.path.isdir(test_image_saving_folder): os.mkdir(test_image_saving_folder) if not os.path.isdir(threshold_folder): os.mkdir(threshold_folder) status_color = (0, 0, 255) image_1 = cv2.imread(f"{dataset_base_f...
distance_matrix - np.min(distance_matrix) return temp / np.max(distance_matrix) # call with two arrays one containing the reference features and the other containing the corresponding probe features def get_similarity_scores(references, probes): if len(references) != len(probes): print("references an...
136
136
456
40
95
sachith500/MaskedFaceRepresentation
utils/graph_util.py
Python
save_reference_and_probe
save_reference_and_probe
41
81
41
42
0b3260b33deb4a8e696a5ff3dde9ade81181409c
bigcode/the-stack
train
e1d1f9d2f83cfe3b97fe6e73
train
function
def evaluate(similarity_score, actual_label): if len(similarity_score) != len(actual_label): print("similarity score and actual labels do not match in size") return thresholds = np.linspace(1, 0, num=500) FRRs = [] FARs = [] thresholds_list = [] thresholds_false_images_dict = d...
def evaluate(similarity_score, actual_label):
if len(similarity_score) != len(actual_label): print("similarity score and actual labels do not match in size") return thresholds = np.linspace(1, 0, num=500) FRRs = [] FARs = [] thresholds_list = [] thresholds_false_images_dict = dict() for thresh in thresholds: fa...
(image, match_status, (20, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.8, status_color, 1, cv2.LINE_AA) image = cv2.putText(image, f"reference {reference_label} probe : {probel_label} similarity : {sim} threshold : {thresh}", (20, 50), cv2.FONT_HERSHEY_SI...
171
171
570
9
161
sachith500/MaskedFaceRepresentation
utils/graph_util.py
Python
evaluate
evaluate
86
146
86
86
6b4cf433eae7447fd77753900be981e0ce5d14ad
bigcode/the-stack
train
d9b307b73f98fe4f91bbf678
train
function
def min_max_normalize(distance_matrix): temp = distance_matrix - np.min(distance_matrix) return temp / np.max(distance_matrix)
def min_max_normalize(distance_matrix):
temp = distance_matrix - np.min(distance_matrix) return temp / np.max(distance_matrix)
_abs_diff) err = (FARs[min_abs_diff_id] + FRRs[min_abs_diff_id]) / 2.0 return (err) def get_dist(references, probes): return np.linalg.norm(references - probes, axis=1) def min_max_normalize(distance_matrix):
64
64
28
8
56
sachith500/MaskedFaceRepresentation
utils/graph_util.py
Python
min_max_normalize
min_max_normalize
25
27
25
25
048ce970ccc624504be4f36989293d0545e1efc1
bigcode/the-stack
train
0b17abe013d8821bc8f1fc49
train
function
def err(FARs, FRRs): # find eer min_abs_diff = 5 min_abs_diff_id = -1 for i in range(0, FARs.__len__()): abs_diff = np.abs(FARs[i] - FRRs[i]) if abs_diff < min_abs_diff: min_abs_diff = abs_diff min_abs_diff_id = i # print(min_abs_diff_id, min_abs_diff) err...
def err(FARs, FRRs): # find eer
min_abs_diff = 5 min_abs_diff_id = -1 for i in range(0, FARs.__len__()): abs_diff = np.abs(FARs[i] - FRRs[i]) if abs_diff < min_abs_diff: min_abs_diff = abs_diff min_abs_diff_id = i # print(min_abs_diff_id, min_abs_diff) err = (FARs[min_abs_diff_id] + FRRs[min...
import os import cv2 import numpy as np def err(FARs, FRRs): # find eer
26
64
129
14
11
sachith500/MaskedFaceRepresentation
utils/graph_util.py
Python
err
err
7
18
7
8
b8ceba510e06f3df5dc52534d10414bbb7080759
bigcode/the-stack
train
405144d7876f486f122cfbce
train
function
def get_dist(references, probes): return np.linalg.norm(references - probes, axis=1)
def get_dist(references, probes):
return np.linalg.norm(references - probes, axis=1)
_diff = abs_diff min_abs_diff_id = i # print(min_abs_diff_id, min_abs_diff) err = (FARs[min_abs_diff_id] + FRRs[min_abs_diff_id]) / 2.0 return (err) def get_dist(references, probes):
64
64
22
8
56
sachith500/MaskedFaceRepresentation
utils/graph_util.py
Python
get_dist
get_dist
21
22
21
21
9fddf961c1ec71206d61afeec57a0081a1e6397a
bigcode/the-stack
train
8d3db7186fac9bc734683817
train
function
def evaluate_TP_FP_rates(similarity_score, actual_label): if len(similarity_score) != len(actual_label): print("similarity score and actual labels do not match in size") return thresholds = np.linspace(1, 0, num=500) TPRs = [] FPRs = [] thresholds_list = [] thresholds_false_imag...
def evaluate_TP_FP_rates(similarity_score, actual_label):
if len(similarity_score) != len(actual_label): print("similarity score and actual labels do not match in size") return thresholds = np.linspace(1, 0, num=500) TPRs = [] FPRs = [] thresholds_list = [] thresholds_false_images_dict = dict() for thresh in thresholds: fal...
_non_match + true_match) # divide by all correct samples FMR = false_match / (true_non_match + false_match) # divide by all wrong samples # when thresh == 0, FNMR = 0 # when thresh == 1, FMR = 0 GARs.append(GAR) FMRs.append(FMR) thresholds_list.append(thresh) retu...
113
113
377
13
100
sachith500/MaskedFaceRepresentation
utils/graph_util.py
Python
evaluate_TP_FP_rates
evaluate_TP_FP_rates
193
233
193
193
e8a022b7d06e011e420ae3fc81f20af5e05a6102
bigcode/the-stack
train
8e01d096981dca45d6680457
train
function
def voter_reaction_like_off_save_for_api( voter_device_id='', liked_item_we_vote_id=''): status = '' # Get voter_id from the voter_device_id so we can know who is doing the liking voter_id = fetch_voter_id_from_voter_device_link(voter_device_id) if not positive_value_exists(voter_id): ...
def voter_reaction_like_off_save_for_api( voter_device_id='', liked_item_we_vote_id=''):
status = '' # Get voter_id from the voter_device_id so we can know who is doing the liking voter_id = fetch_voter_id_from_voter_device_link(voter_device_id) if not positive_value_exists(voter_id): status += "VALID_VOTER_ID_MISSING " json_data = { 'status': ...
type_of_count': type_of_count, 'number_of_likes': number_of_likes, 'all_likes': all_likes, 'voter_network_likes': voter_network_likes, } return HttpResponse(json.dumps(json_data), content_type='application/json') def voter_reaction_like_off_save_for_api( v...
88
88
294
24
64
PrinceRios2000/WeVoteServer
reaction/controllers.py
Python
voter_reaction_like_off_save_for_api
voter_reaction_like_off_save_for_api
87
118
87
89
893e9bd28a93d3431b132d49b42ee20ccda12728
bigcode/the-stack
train
3cbcb14a1ae314d6a79f6d36
train
function
def reaction_like_status_retrieve_for_api(voter_device_id, liked_item_we_vote_id_list): # reactionLikeStatusRetrieve status = '' success = True reaction_like_list = [] # Get voter_id from the voter_device_id so we can know who is doing the liking voter_id = fetch_voter_id_from_voter_device_link(vot...
def reaction_like_status_retrieve_for_api(voter_device_id, liked_item_we_vote_id_list): # reactionLikeStatusRetrieve
status = '' success = True reaction_like_list = [] # Get voter_id from the voter_device_id so we can know who is doing the liking voter_id = fetch_voter_id_from_voter_device_link(voter_device_id) if not positive_value_exists(voter_id): status += "VALID_VOTER_ID_MISSING " json_dat...
_item_we_vote_id=liked_item_we_vote_id, activity_tidbit_we_vote_id=activity_tidbit_we_vote_id) status += results['status'] success = results['success'] reaction_like_id = results['reaction_like_id'] else: status += 'UNABLE_TO_SAVE_REACTION_LIKE-INSUFFICIENT_VARIABLES ' ...
168
168
561
27
141
PrinceRios2000/WeVoteServer
reaction/controllers.py
Python
reaction_like_status_retrieve_for_api
reaction_like_status_retrieve_for_api
179
227
179
179
9d927fd27d6df80116a8503bc50a4f8034307401
bigcode/the-stack
train
87e4bcf8e676b11cbbb99bfc
train
function
def reaction_like_count_for_api(voter_device_id, liked_item_we_vote_id, limit_to_voters_network=False): # Get voter_id from the voter_device_id so we can know who is doing the liking results = is_voter_device_id_valid(voter_device_id) if not results['success']: json_data = { 'status': ...
def reaction_like_count_for_api(voter_device_id, liked_item_we_vote_id, limit_to_voters_network=False): # Get voter_id from the voter_device_id so we can know who is doing the liking
results = is_voter_device_id_valid(voter_device_id) if not results['success']: json_data = { 'status': 'VALID_VOTER_DEVICE_ID_MISSING', 'success': False, 'voter_device_id': voter_device_id, 'liked_item_we_vote_id': liked_it...
# reaction/controllers.py # Brought to you by We Vote. Be good. # -*- coding: UTF-8 -*- from .models import ReactionLike, ReactionManager from django.db.models import Q from django.http import HttpResponse import json from voter.models import fetch_voter_id_from_voter_device_link, VoterManager import wevote_functions....
148
206
687
44
104
PrinceRios2000/WeVoteServer
reaction/controllers.py
Python
reaction_like_count_for_api
reaction_like_count_for_api
16
84
16
17
a528c106104b1741ff289c83c8c8270602fad01c
bigcode/the-stack
train
81a7da553d71ab9a6e30a10b
train
function
def voter_reaction_like_on_save_for_api( voter_device_id='', liked_item_we_vote_id='', activity_tidbit_we_vote_id=''): status = '' # Get voter_id from the voter_device_id so we can know who is doing the liking voter_id = fetch_voter_id_from_voter_device_link(voter_device_id) if n...
def voter_reaction_like_on_save_for_api( voter_device_id='', liked_item_we_vote_id='', activity_tidbit_we_vote_id=''):
status = '' # Get voter_id from the voter_device_id so we can know who is doing the liking voter_id = fetch_voter_id_from_voter_device_link(voter_device_id) if not positive_value_exists(voter_id): status += "VALID_VOTER_ID_MISSING " json_data = { 'status': ...
= reaction_like_manager.toggle_off_voter_reaction_like( voter_id=voter_id, liked_item_we_vote_id=liked_item_we_vote_id) status += results['status'] success = results['success'] else: status += 'UNABLE_TO_DELETE_REACTION_LIKE-INSUFFICIENT_VARIABLES ' success =...
158
158
528
33
125
PrinceRios2000/WeVoteServer
reaction/controllers.py
Python
voter_reaction_like_on_save_for_api
voter_reaction_like_on_save_for_api
121
176
121
124
7a4e514bc8be64daf402078ffd0b17978dc83d45
bigcode/the-stack
train
a15b88461b8943000ba84f9c
train
function
def get_SVHN(augment, dataroot, download): image_shape = (32, 32, 3) num_classes = 10 if augment: transformations = [transforms.RandomAffine(0, translate=(0.1, 0.1))] else: transformations = [] transformations.extend([transforms.ToTensor(), preprocess]) train_transform = transf...
def get_SVHN(augment, dataroot, download):
image_shape = (32, 32, 3) num_classes = 10 if augment: transformations = [transforms.RandomAffine(0, translate=(0.1, 0.1))] else: transformations = [] transformations.extend([transforms.ToTensor(), preprocess]) train_transform = transforms.Compose(transformations) test_tra...
test_dataset = datasets.CIFAR10( path, train=False, transform=test_transform, target_transform=one_hot_encode, download=download, ) return image_shape, num_classes, train_dataset, test_dataset def get_SVHN(augment, dataroot, download):
64
64
206
14
49
calebmcarr/Glow-PyTorch
datasets.py
Python
get_SVHN
get_SVHN
81
113
81
81
33feaf32d134ee0c3a92677bed53b1c26ff5b220
bigcode/the-stack
train
9523f6cf94f51e6b045ca5dc
train
function
def preprocess(x): # Follows: # https://github.com/tensorflow/tensor2tensor/blob/e48cf23c505565fd63378286d9722a1632f4bef7/tensor2tensor/models/research/glow.py#L78 x = x * 255 # undo ToTensor scaling to [0,1] n_bins = 2 ** n_bits if n_bits < 8: x = torch.floor(x / 2 ** (8 - n_bits)) x...
def preprocess(x): # Follows: # https://github.com/tensorflow/tensor2tensor/blob/e48cf23c505565fd63378286d9722a1632f4bef7/tensor2tensor/models/research/glow.py#L78
x = x * 255 # undo ToTensor scaling to [0,1] n_bins = 2 ** n_bits if n_bits < 8: x = torch.floor(x / 2 ** (8 - n_bits)) x = x / n_bins - 0.5 return x
n_bits = 8 def preprocess(x): # Follows: # https://github.com/tensorflow/tensor2tensor/blob/e48cf23c505565fd63378286d9722a1632f4bef7/tensor2tensor/models/research/glow.py#L78
64
64
128
58
5
calebmcarr/Glow-PyTorch
datasets.py
Python
preprocess
preprocess
11
22
11
14
ab0340c2efd35bdfadeaa201ded8b44da1cb1bd1
bigcode/the-stack
train
5e96782c8de37b04503fcff5
train
function
def postprocess(x): x = torch.clamp(x, -0.5, 0.5) x += 0.5 x = x * 2 ** n_bits return torch.clamp(x, 0, 255).byte()
def postprocess(x):
x = torch.clamp(x, -0.5, 0.5) x += 0.5 x = x * 2 ** n_bits return torch.clamp(x, 0, 255).byte()
Tensor scaling to [0,1] n_bins = 2 ** n_bits if n_bits < 8: x = torch.floor(x / 2 ** (8 - n_bits)) x = x / n_bins - 0.5 return x def postprocess(x):
64
64
57
5
58
calebmcarr/Glow-PyTorch
datasets.py
Python
postprocess
postprocess
25
29
25
25
916f4cafc3660fd426fd0302f490e780cb8e5927
bigcode/the-stack
train
51d17a9c39804d220df79850
train
function
def get_CIFAR10(augment, dataroot, download): image_shape = (32, 32, 3) num_classes = 10 if augment: transformations = [ transforms.RandomAffine(0, translate=(0.1, 0.1)), transforms.RandomHorizontalFlip(), ] else: transformations = [] transformations...
def get_CIFAR10(augment, dataroot, download):
image_shape = (32, 32, 3) num_classes = 10 if augment: transformations = [ transforms.RandomAffine(0, translate=(0.1, 0.1)), transforms.RandomHorizontalFlip(), ] else: transformations = [] transformations.extend([transforms.ToTensor(), preprocess]) ...
to one-hot encode Retn: one_hot_encoding - the OHE of this tensor """ num_classes = 10 one_hot_encoding = F.one_hot(torch.tensor(target),num_classes) return one_hot_encoding def get_CIFAR10(augment, dataroot, download):
65
65
217
15
49
calebmcarr/Glow-PyTorch
datasets.py
Python
get_CIFAR10
get_CIFAR10
43
78
43
43
e6857962eda628b766e1fd4344a861a534afc175
bigcode/the-stack
train
9eaa2a1e4b893807c045ba3a
train
function
def one_hot_encode(target): """ One hot encode with fixed 10 classes Args: target - the target labels to one-hot encode Retn: one_hot_encoding - the OHE of this tensor """ num_classes = 10 one_hot_encoding = F.one_hot(torch.tensor(target),num_classes) return one_hot_encoding
def one_hot_encode(target):
""" One hot encode with fixed 10 classes Args: target - the target labels to one-hot encode Retn: one_hot_encoding - the OHE of this tensor """ num_classes = 10 one_hot_encoding = F.one_hot(torch.tensor(target),num_classes) return one_hot_encoding
def postprocess(x): x = torch.clamp(x, -0.5, 0.5) x += 0.5 x = x * 2 ** n_bits return torch.clamp(x, 0, 255).byte() def one_hot_encode(target):
64
64
77
6
58
calebmcarr/Glow-PyTorch
datasets.py
Python
one_hot_encode
one_hot_encode
31
40
31
31
a9eea5f3be5c35e26b9a15d05847d622bed085e5
bigcode/the-stack
train
82b5ff2677cec680421ae944
train
class
class CollectiveAllReduceStrategyTestBase( multi_worker_test_base.MultiWorkerTestBase): collective_key_base = 0 def setUp(self): self._run_options = config_pb2.RunOptions() self._run_options.experimental.collective_graph_key = 6 self._sess_config = config_pb2.ConfigProto() # We use a differe...
class CollectiveAllReduceStrategyTestBase( multi_worker_test_base.MultiWorkerTestBase):
collective_key_base = 0 def setUp(self): self._run_options = config_pb2.RunOptions() self._run_options.experimental.collective_graph_key = 6 self._sess_config = config_pb2.ConfigProto() # We use a different key_base for each test so that collective keys won't be # reused. # TODO(yuefengz,...
permissions and # limitations under the License. # ============================================================================== """Tests for CollectiveAllReduceStrategy.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import paramete...
256
256
1,670
18
237
gsobala/tensorflow
tensorflow/contrib/distribute/python/collective_all_reduce_strategy_test.py
Python
CollectiveAllReduceStrategyTestBase
CollectiveAllReduceStrategyTestBase
48
238
48
50
317bf2ce2489e3bfba44313e244d26259d209369
bigcode/the-stack
train
876f6679a72bf14b8475f7ca
train
class
class DistributedCollectiveAllReduceStrategyTestWithChief( CollectiveAllReduceStrategyTestBase, parameterized.TestCase): @classmethod def setUpClass(cls): """Create a local cluster with 3 workers and 1 chief.""" cls._cluster_spec = multi_worker_test_base.create_in_process_cluster( num_workers=3...
class DistributedCollectiveAllReduceStrategyTestWithChief( CollectiveAllReduceStrategyTestBase, parameterized.TestCase): @classmethod
def setUpClass(cls): """Create a local cluster with 3 workers and 1 chief.""" cls._cluster_spec = multi_worker_test_base.create_in_process_cluster( num_workers=3, num_ps=0, has_chief=True) def setUp(self): super(DistributedCollectiveAllReduceStrategyTestWithChief, self).setUp() self._run_op...
( combinations.combine(mode=['graph'], num_gpus=[0, 1, 2], required_gpus=1)) def testComplexModel(self, num_gpus): if context.num_gpus() < num_gpus: return self._run_between_graph_clients( self._test_complex_model, self._cluster_spec, num_gpus=num_gpus) class DistributedCollectiveAllReduce...
107
107
359
28
79
gsobala/tensorflow
tensorflow/contrib/distribute/python/collective_all_reduce_strategy_test.py
Python
DistributedCollectiveAllReduceStrategyTestWithChief
DistributedCollectiveAllReduceStrategyTestWithChief
285
320
285
288
cd5ec131b6b03b5fd3ef3ecd181ec795fc6946d3
bigcode/the-stack
train
ed80b8896ce40e53cb46036e
train
class
class DistributedCollectiveAllReduceStrategyTest( CollectiveAllReduceStrategyTestBase, parameterized.TestCase): @classmethod def setUpClass(cls): """Create a local cluster with 3 workers.""" cls._cluster_spec = multi_worker_test_base.create_in_process_cluster( num_workers=3, num_ps=0) def te...
class DistributedCollectiveAllReduceStrategyTest( CollectiveAllReduceStrategyTestBase, parameterized.TestCase): @classmethod
def setUpClass(cls): """Create a local cluster with 3 workers.""" cls._cluster_spec = multi_worker_test_base.create_in_process_cluster( num_workers=3, num_ps=0) def test_num_replicas_in_sync(self): distribution = collective_all_reduce_strategy.CollectiveAllReduceStrategy( num_gpus_per_w...
=self._run_options) x_value, reduced_x_value = sess.run( [x, reduced_x], options=self._run_options) self.assertTrue( np.allclose(x_value, reduced_x_value, atol=1e-5), msg=('x_value = %r, reduced_x_value = %r' % (x_value, r...
123
123
410
26
97
gsobala/tensorflow
tensorflow/contrib/distribute/python/collective_all_reduce_strategy_test.py
Python
DistributedCollectiveAllReduceStrategyTest
DistributedCollectiveAllReduceStrategyTest
241
282
241
244
5928f92aa6c068698bf5a042d2f19e390ded8a2e
bigcode/the-stack
train
8bc71b55bd16681c6925a338
train
class
class LocalCollectiveAllReduceStrategy( CollectiveAllReduceStrategyTestBase, parameterized.TestCase): def testMinimizeLossGraph(self, num_gpus=2): # Collective ops doesn't support strategy with one device. if context.num_gpus() < num_gpus: return self._test_minimize_loss_graph(None, None, num_g...
class LocalCollectiveAllReduceStrategy( CollectiveAllReduceStrategyTestBase, parameterized.TestCase):
def testMinimizeLossGraph(self, num_gpus=2): # Collective ops doesn't support strategy with one device. if context.num_gpus() < num_gpus: return self._test_minimize_loss_graph(None, None, num_gpus) def testComplexModel(self, num_gpus=2): # Collective ops doesn't support strategy with one devi...
): if context.num_gpus() < num_gpus: return self._run_between_graph_clients( self._test_complex_model, self._cluster_spec, num_gpus=num_gpus) class LocalCollectiveAllReduceStrategy( CollectiveAllReduceStrategyTestBase, parameterized.TestCase):
64
64
131
21
43
gsobala/tensorflow
tensorflow/contrib/distribute/python/collective_all_reduce_strategy_test.py
Python
LocalCollectiveAllReduceStrategy
LocalCollectiveAllReduceStrategy
323
336
323
325
e27dccd2c71bc13d22772156137b32f580c3c85c
bigcode/the-stack
train
c49f16e1d68bf9dd8cdd0de2
train
function
def softmax(x): """Simple numpy softmax implementation """ # (n_samples, n_classes) if len(x.shape) == 2: row_max = np.max(x, axis=1) x -= row_max.reshape((x.shape[0], 1)) x = np.exp(x) row_sum = np.sum(x, axis=1) x /= row_sum.reshape((x.shape[0], 1)) # (n_samples, n_tasks, n_classes) el...
def softmax(x):
"""Simple numpy softmax implementation """ # (n_samples, n_classes) if len(x.shape) == 2: row_max = np.max(x, axis=1) x -= row_max.reshape((x.shape[0], 1)) x = np.exp(x) row_sum = np.sum(x, axis=1) x /= row_sum.reshape((x.shape[0], 1)) # (n_samples, n_tasks, n_classes) elif len(x.shape) ...
_ops from deepchem.models.tensorflow_models import utils as tf_utils from deepchem.trans import undo_transforms from deepchem.utils.save import log from deepchem.utils.evaluate import Evaluator from deepchem.data import pad_features from tensorflow.contrib.layers.python.layers import batch_norm def softmax(x):
64
64
182
5
58
n3011/deepchem
contrib/tensorflow_models/__init__.py
Python
softmax
softmax
29
46
29
29
babd2623bf847f622a22ce78305572816af1db09
bigcode/the-stack
train
3db232c2534ad915e7fbe208
train
class
class TensorflowClassifier(TensorflowGraphModel): """Classification model. Subclasses must set the following attributes: output: logits op(s) used for computing classification loss and predicted class probabilities for each task. """ def get_task_type(self): return "classification" def cost(s...
class TensorflowClassifier(TensorflowGraphModel):
"""Classification model. Subclasses must set the following attributes: output: logits op(s) used for computing classification loss and predicted class probabilities for each task. """ def get_task_type(self): return "classification" def cost(self, logits, labels, weights): """Calculate si...
.data.Dataset # Dataset object. # metric: deepchem.metrics.Metric # Evaluation metric # transformers: list # List of deepchem.transformers.Transformer # Returns # ------- # dict # Maps tasks to scores under metric. # """ # evaluator = Evaluator(self, dataset, transformers) # ...
256
256
1,148
10
246
n3011/deepchem
contrib/tensorflow_models/__init__.py
Python
TensorflowClassifier
TensorflowClassifier
615
764
615
615
fd4a6aaa777573bfdd47d4fc53e618a2ac9b1b4b
bigcode/the-stack
train
6d5201fd7ae2606e062a4ad7
train
class
class TensorflowGraphModel(Model): """Parent class for deepchem Tensorflow models. Classifier: n_classes Has the following attributes: placeholder_root: String placeholder prefix, used to create placeholder_scope. Generic base class for defining, training, and evaluating TensorflowGraphs. S...
class TensorflowGraphModel(Model):
"""Parent class for deepchem Tensorflow models. Classifier: n_classes Has the following attributes: placeholder_root: String placeholder prefix, used to create placeholder_scope. Generic base class for defining, training, and evaluating TensorflowGraphs. Subclasses must implement the follow...
= output self.labels = labels self.weights = weights self.loss = loss @staticmethod def get_placeholder_scope(graph, name_scopes): """Gets placeholder scope.""" placeholder_root = "placeholders" return TensorflowGraph.shared_name_scope(placeholder_root, graph, ...
256
256
4,004
7
248
n3011/deepchem
contrib/tensorflow_models/__init__.py
Python
TensorflowGraphModel
TensorflowGraphModel
97
612
97
97
b1fb4f313b9c5a87b84efd7e13f3576dc4ec708a
bigcode/the-stack
train
03ee408700431812bc6d79a7
train
class
class TensorflowGraph(object): """Simple class that holds information needed to run Tensorflow graph.""" def __init__(self, graph, session, name_scopes, output, labels, weights, loss): warnings.warn("TensorflowGraph is deprecated. " "Will be removed in DeepChem 1.4.", Deprecati...
class TensorflowGraph(object):
"""Simple class that holds information needed to run Tensorflow graph.""" def __init__(self, graph, session, name_scopes, output, labels, weights, loss): warnings.warn("TensorflowGraph is deprecated. " "Will be removed in DeepChem 1.4.", DeprecationWarning) self.graph = gra...
_sum.reshape((x.shape[0], 1)) # (n_samples, n_tasks, n_classes) elif len(x.shape) == 3: row_max = np.max(x, axis=2) x -= row_max.reshape(x.shape[:2] + (1,)) x = np.exp(x) row_sum = np.sum(x, axis=2) x /= row_sum.reshape(x.shape[:2] + (1,)) return x class TensorflowGraph(object):
104
104
347
6
97
n3011/deepchem
contrib/tensorflow_models/__init__.py
Python
TensorflowGraph
TensorflowGraph
49
94
49
49
603bfbe30ff4eed192e13caa07a5ce4adbabc6a4
bigcode/the-stack
train
b86bab0c0bf655f0892c1adc
train
class
class TensorflowRegressor(TensorflowGraphModel): """Regression model. Subclasses must set the following attributes: output: Op(s) used for computing regression loss and predicted regression outputs for each task. """ def get_task_type(self): return "regressor" def add_output_ops(self, graph, ...
class TensorflowRegressor(TensorflowGraphModel):
"""Regression model. Subclasses must set the following attributes: output: Op(s) used for computing regression loss and predicted regression outputs for each task. """ def get_task_type(self): return "regressor" def add_output_ops(self, graph, output): """No-op for regression models since...
are not both 3D or both 2D. """ if self.pad_batches: X = pad_features(self.batch_size, X) if not self._restored_model: self.restore() with self.eval_graph.graph.as_default(): # run eval data through the model n_tasks = self.n_tasks with self._get_shared_session(train=False...
255
255
852
11
244
n3011/deepchem
contrib/tensorflow_models/__init__.py
Python
TensorflowRegressor
TensorflowRegressor
767
880
767
767
c5a1d631e84095adeddbaed6028eda5325628db3
bigcode/the-stack
train
a592e6f3f9d9f7ccc169be93
train
class
class VRTbe(Plugin): @classmethod def can_handle_url(cls, url): return _url_re.match(url) def _get_live_stream(self, channel): channel = 'vualto_{0}'.format(channel) _live_json_re = re.compile(r'''"{0}":\s(\173[^\173\175]+\175)'''.format(channel)) res = http.get(API_LIVE) ...
class VRTbe(Plugin): @classmethod
def can_handle_url(cls, url): return _url_re.match(url) def _get_live_stream(self, channel): channel = 'vualto_{0}'.format(channel) _live_json_re = re.compile(r'''"{0}":\s(\173[^\173\175]+\175)'''.format(channel)) res = http.get(API_LIVE) match = _live_json_re.search(re...
/vrtnu/(?:kanalen/(?P<channel>[^/]+)|\S+)''') _json_re = re.compile(r'''(\173[^\173\175]+\175)''') API_LIVE = 'https://services.vrt.be/videoplayer/r/live.json' API_VOD = 'https://mediazone.vrt.be/api/v1/{0}/assets/{1}' _stream_schema = validate.Schema({ 'targetUrls': [ { 'type': validate.text,...
126
126
420
11
115
bobbybark/tantrumrepo
script.module.streamlink.base/resources/lib/streamlink/plugins/vrtbe.py
Python
VRTbe
VRTbe
26
82
26
27
cecd9bba63a8d7c3493f2b36383413707f212e9e
bigcode/the-stack
train
6afd28d75d4275594768e584
train
class
class Solution(object): def findCheapestPrice(self, n, flights, src, dst, K): """ :type n: int :type flights: List[List[int]] :type src: int :type dst: int :type K: int :rtype: int """ graph = collections.defaultdict(dict) for s, d, cos...
class Solution(object):
def findCheapestPrice(self, n, flights, src, dst, K): """ :type n: int :type flights: List[List[int]] :type src: int :type dst: int :type K: int :rtype: int """ graph = collections.defaultdict(dict) for s, d, cost in flights: ...
import sys, collections, heapq class Solution(object):
12
64
178
4
7
lzmaths/leetcode
leetcode_787_cheapest_flights_within_k_stops.py
Python
Solution
Solution
3
26
3
3
760dce192cd3c23a951257cbdeaf085c48d2b0a3
bigcode/the-stack
train
386cb1f8566d35bbc5024163
train
class
class SchedulingV1beta1Api(object): """NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. """ def __init__(self, api_client=None): if api_client is None: api_client = ApiClient() self.api_client = ...
class SchedulingV1beta1Api(object):
"""NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. """ def __init__(self, api_client=None): if api_client is None: api_client = ApiClient() self.api_client = api_client def create_priority_...
# coding: utf-8 """ Kubernetes No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: release-1.16 Generated by: https://openapi-generator.tech """ from __future__ import absolute_import import r...
143
256
15,707
9
134
pllsxyc/python
kubernetes/client/api/scheduling_v1beta1_api.py
Python
SchedulingV1beta1Api
SchedulingV1beta1Api
27
1,144
27
27
a4e2752fadc1a1ae3c0c96fb2823f0ef5ce8e2e2
bigcode/the-stack
train
ca5492600962ae5fa53d6e52
train
function
def get_strides(index, stride_vars): """Get the striding of given vars in an indexing expression. Parameters ---------- index : tvm.tir.PrimExpr The index expression where the stride vars are present. stride_vars : list of tvm.tir.Var The vars to determine the striding of. Retu...
def get_strides(index, stride_vars):
"""Get the striding of given vars in an indexing expression. Parameters ---------- index : tvm.tir.PrimExpr The index expression where the stride vars are present. stride_vars : list of tvm.tir.Var The vars to determine the striding of. Returns ------- strides : list of...
body after having collected the final attribute statement. """ attrs = {} while isinstance(stmt, tvm.tir.AttrStmt): # The pragma scheduler inserts "pragma_" before all the # attr names, this is annoying so we get rid of it attr = stmt.attr_key.replace("pragma_", "") attrs[a...
96
96
321
9
86
ccjoechou/tvm
python/tvm/relay/backend/contrib/ethosu/tir/utils.py
Python
get_strides
get_strides
71
108
71
71
e4e305fab91dd68a7d88cb4189f842b7632211bb
bigcode/the-stack
train
3f80f67b0546e76bc88abbf2
train
function
def get_op_attrs(stmt): """Iterate through nested attribute statements accumulating their values in an attribute dictionary. The "pragma_" prefix is removed as a convenience. Parameters ---------- stmt : tvm.tir.AttrStmt The outermost attribute statement to begin from. Returns ...
def get_op_attrs(stmt):
"""Iterate through nested attribute statements accumulating their values in an attribute dictionary. The "pragma_" prefix is removed as a convenience. Parameters ---------- stmt : tvm.tir.AttrStmt The outermost attribute statement to begin from. Returns ------- attrs : dic...
PU extern call if it exists""" supported_ops = ["ethosu_conv2d", "ethosu_depthwise_conv2d"] if tir_extern_call.args[0] in supported_ops: return tir_extern_call.args[44].buffer_var return None def get_op_attrs(stmt):
64
64
180
6
57
ccjoechou/tvm
python/tvm/relay/backend/contrib/ethosu/tir/utils.py
Python
get_op_attrs
get_op_attrs
41
68
41
41
0f44a46c3cb81f7578a81e21324da9f84b759323
bigcode/the-stack
train
3b6d58ac29039125b1e78bf9
train
function
def get_loads(stmt): """Get the Load statements. Parameters ---------- stmt : tvm.tir.Stmt The statement to get the Loads from. Returns ------- loads : list of tvm.tir.Load The Loads found. """ loads = [] def _visit(s): if isinstance(s, tvm.tir.Load): ...
def get_loads(stmt):
"""Get the Load statements. Parameters ---------- stmt : tvm.tir.Stmt The statement to get the Loads from. Returns ------- loads : list of tvm.tir.Load The Loads found. """ loads = [] def _visit(s): if isinstance(s, tvm.tir.Load): loads.app...
if layout == "NHCWB16": n = stmt h = n.body cb = h.body w = cb.body b = w.body return n, h, w, cb, b, b.body return None def get_loads(stmt):
64
64
107
6
57
ccjoechou/tvm
python/tvm/relay/backend/contrib/ethosu/tir/utils.py
Python
get_loads
get_loads
179
200
179
179
f696ca0f4af80871178e1beb95e4c0c5ab5e44e2
bigcode/the-stack
train
403aa9440ee8a5c2535ef30d
train
function
def get_stores(stmt): """Get the Store statements. Parameters ---------- stmt : tvm.tir.Stmt The statement to get the Stores from. Returns ------- stores : list of tvm.tir.Store The Stores found. """ stores = [] def _visit(s): if isinstance(s, tvm.tir....
def get_stores(stmt):
"""Get the Store statements. Parameters ---------- stmt : tvm.tir.Stmt The statement to get the Stores from. Returns ------- stores : list of tvm.tir.Store The Stores found. """ stores = [] def _visit(s): if isinstance(s, tvm.tir.Store): st...
.tir.Load The Loads found. """ loads = [] def _visit(s): if isinstance(s, tvm.tir.Load): loads.append(s) tvm.tir.stmt_functor.post_order_visit(stmt, _visit) return loads def get_stores(stmt):
64
64
107
6
57
ccjoechou/tvm
python/tvm/relay/backend/contrib/ethosu/tir/utils.py
Python
get_stores
get_stores
203
224
203
203
7497f4e1f92ac08733fddf321720e17c500d8f6e
bigcode/the-stack
train
51e31718d9aa415fcec098a4
train
function
def get_scale_bias_pointer(tir_extern_call): """Get the scale_bias pointer from a NPU extern call if it exists""" supported_ops = ["ethosu_conv2d", "ethosu_depthwise_conv2d"] if tir_extern_call.args[0] in supported_ops: return tir_extern_call.args[44].buffer_var return None
def get_scale_bias_pointer(tir_extern_call):
"""Get the scale_bias pointer from a NPU extern call if it exists""" supported_ops = ["ethosu_conv2d", "ethosu_depthwise_conv2d"] if tir_extern_call.args[0] in supported_ops: return tir_extern_call.args[44].buffer_var return None
"ethosu_depthwise_conv2d"] if tir_extern_call.args[0] in supported_ops: return tir_extern_call.args[41].buffer_var return None # TODO(@mbaret): Formalise this with a specification def get_scale_bias_pointer(tir_extern_call):
64
64
79
11
52
ccjoechou/tvm
python/tvm/relay/backend/contrib/ethosu/tir/utils.py
Python
get_scale_bias_pointer
get_scale_bias_pointer
33
38
33
33
a94509a586ef3db3cb315579b602436936c1215a
bigcode/the-stack
train
976f44b45537f81d8f124932
train
function
def get_outer_loops(stmt, layout): """Get the outer loops of an operator. Parameters ---------- stmt : tvm.tir.For The outermost loop. layout : str The output tensor layout (NHWC or NHCWB16). Returns ------- n : tvm.tir.For The batch loop. h : tvm.tir.For ...
def get_outer_loops(stmt, layout):
"""Get the outer loops of an operator. Parameters ---------- stmt : tvm.tir.For The outermost loop. layout : str The output tensor layout (NHWC or NHCWB16). Returns ------- n : tvm.tir.For The batch loop. h : tvm.tir.For The height loop. w : tvm....
dmap = {} def _visit(stmt): if isinstance(stmt, tvm.tir.Var): dmap[stmt] = arith.IntervalSet(0, 0) tvm.tir.stmt_functor.post_order_visit(index, _visit) base_address = int(arith.Analyzer().int_set(index, dmap).min_value) return base_address def get_outer_loops(stmt, layout):
90
90
300
9
80
ccjoechou/tvm
python/tvm/relay/backend/contrib/ethosu/tir/utils.py
Python
get_outer_loops
get_outer_loops
136
176
136
136
dc777e06c5ebfb5111688ef67eb74ab4a6a8ff7e
bigcode/the-stack
train
fb33913efe8c856c5007be2f
train
function
def get_base_address(index): """Determine the first (base) address accessed by an index expression. Parameters ---------- index : tvm.tir.PrimExpr The index expression to determine the base address of. Returns ------- base_address: The first address accessed by the index ex...
def get_base_address(index):
"""Determine the first (base) address accessed by an index expression. Parameters ---------- index : tvm.tir.PrimExpr The index expression to determine the base address of. Returns ------- base_address: The first address accessed by the index expression. """ dmap =...
.Analyzer().int_set(index, dmap).max_value) stride = int(max_value - min_value) i = stride_vars.index(var) strides[i] = stride dmap[var] = arith.IntervalSet(0, 0) return strides def get_base_address(index):
64
64
150
6
57
ccjoechou/tvm
python/tvm/relay/backend/contrib/ethosu/tir/utils.py
Python
get_base_address
get_base_address
111
133
111
111
cad81028d0019a925d362eb6ed7e0bf292a5ac97
bigcode/the-stack
train
36fa05e623ce1c10b384ef13
train
function
def get_weights_pointer(tir_extern_call): """Get the weights pointer from a NPU extern call if it exists""" supported_ops = ["ethosu_conv2d", "ethosu_depthwise_conv2d"] if tir_extern_call.args[0] in supported_ops: return tir_extern_call.args[41].buffer_var return None
def get_weights_pointer(tir_extern_call):
"""Get the weights pointer from a NPU extern call if it exists""" supported_ops = ["ethosu_conv2d", "ethosu_depthwise_conv2d"] if tir_extern_call.args[0] in supported_ops: return tir_extern_call.args[41].buffer_var return None
permissions and limitations # under the License. # pylint: disable=invalid-name """Helper utility functions used by the NPU TIR compiler""" import tvm from tvm import arith # TODO(@mbaret): Formalise this with a specification def get_weights_pointer(tir_extern_call):
64
64
77
10
53
ccjoechou/tvm
python/tvm/relay/backend/contrib/ethosu/tir/utils.py
Python
get_weights_pointer
get_weights_pointer
24
29
24
24
a829a829136bf5dc172283063c9796ae68feb193
bigcode/the-stack
train