body stringlengths 26 98.2k | body_hash int64 -9,222,864,604,528,158,000 9,221,803,474B | docstring stringlengths 1 16.8k | path stringlengths 5 230 | name stringlengths 1 96 | repository_name stringlengths 7 89 | lang stringclasses 1
value | body_without_docstring stringlengths 20 98.2k |
|---|---|---|---|---|---|---|---|
def test_keywordarg_passes_through_classicalnode(self, qubit_device_2_wires, tol):
"Tests that qnodes' keyword arguments pass through classical nodes."
def circuit(w, x=None):
qml.RX(w, wires=[0])
qml.RX(x, wires=[1])
return (qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1)))
cir... | -8,997,125,060,598,245,000 | Tests that qnodes' keyword arguments pass through classical nodes. | artifacts/old_dataset_versions/minimal_commits/pennylane/pennylane#385/after/test_tf.py | test_keywordarg_passes_through_classicalnode | MattePalte/Bugs-Quantum-Computing-Platforms | python | def test_keywordarg_passes_through_classicalnode(self, qubit_device_2_wires, tol):
def circuit(w, x=None):
qml.RX(w, wires=[0])
qml.RX(x, wires=[1])
return (qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1)))
circuit = qml.QNode(circuit, qubit_device_2_wires).to_tf()
def cla... |
def test_keywordarg_gradient(self, qubit_device_2_wires, tol):
"Tests that qnodes' keyword arguments work with gradients"
def circuit(x, y, input_state=np.array([0, 0])):
qml.BasisState(input_state, wires=[0, 1])
qml.RX(x, wires=[0])
qml.RY(y, wires=[0])
return qml.expval(qml.Pa... | 8,919,149,541,014,781,000 | Tests that qnodes' keyword arguments work with gradients | artifacts/old_dataset_versions/minimal_commits/pennylane/pennylane#385/after/test_tf.py | test_keywordarg_gradient | MattePalte/Bugs-Quantum-Computing-Platforms | python | def test_keywordarg_gradient(self, qubit_device_2_wires, tol):
def circuit(x, y, input_state=np.array([0, 0])):
qml.BasisState(input_state, wires=[0, 1])
qml.RX(x, wires=[0])
qml.RY(y, wires=[0])
return qml.expval(qml.PauliZ(0))
circuit = qml.QNode(circuit, qubit_device_2_w... |
def test_qnode_evaluation_agrees(self, qubit_device_2_wires, tol):
'Tests that simple example is consistent.'
@qml.qnode(qubit_device_2_wires, interface='autograd')
def circuit(phi, theta):
qml.RX(phi[0], wires=0)
qml.RY(phi[1], wires=1)
qml.CNOT(wires=[0, 1])
qml.PhaseShift... | 4,092,149,334,003,494,000 | Tests that simple example is consistent. | artifacts/old_dataset_versions/minimal_commits/pennylane/pennylane#385/after/test_tf.py | test_qnode_evaluation_agrees | MattePalte/Bugs-Quantum-Computing-Platforms | python | def test_qnode_evaluation_agrees(self, qubit_device_2_wires, tol):
@qml.qnode(qubit_device_2_wires, interface='autograd')
def circuit(phi, theta):
qml.RX(phi[0], wires=0)
qml.RY(phi[1], wires=1)
qml.CNOT(wires=[0, 1])
qml.PhaseShift(theta[0], wires=0)
return qml.exp... |
def test_qnode_gradient_agrees(self, qubit_device_2_wires, tol):
'Tests that simple gradient example is consistent.'
@qml.qnode(qubit_device_2_wires, interface='autograd')
def circuit(phi, theta):
qml.RX(phi[0], wires=0)
qml.RY(phi[1], wires=1)
qml.CNOT(wires=[0, 1])
qml.Pha... | -1,064,862,785,118,787,500 | Tests that simple gradient example is consistent. | artifacts/old_dataset_versions/minimal_commits/pennylane/pennylane#385/after/test_tf.py | test_qnode_gradient_agrees | MattePalte/Bugs-Quantum-Computing-Platforms | python | def test_qnode_gradient_agrees(self, qubit_device_2_wires, tol):
@qml.qnode(qubit_device_2_wires, interface='autograd')
def circuit(phi, theta):
qml.RX(phi[0], wires=0)
qml.RY(phi[1], wires=1)
qml.CNOT(wires=[0, 1])
qml.PhaseShift(theta[0], wires=0)
return qml.expva... |
@pytest.fixture
def qnodes(self):
'Two QNodes to be used for the gradient tests'
dev = qml.device('default.qubit', wires=2)
@qml.qnode(dev, interface='tf')
def f(x):
qml.RX(x, wires=0)
return qml.expval(qml.PauliZ(0))
@qml.qnode(dev, interface='tf')
def g(y):
qml.RY(y, ... | -7,397,888,158,913,202,000 | Two QNodes to be used for the gradient tests | artifacts/old_dataset_versions/minimal_commits/pennylane/pennylane#385/after/test_tf.py | qnodes | MattePalte/Bugs-Quantum-Computing-Platforms | python | @pytest.fixture
def qnodes(self):
dev = qml.device('default.qubit', wires=2)
@qml.qnode(dev, interface='tf')
def f(x):
qml.RX(x, wires=0)
return qml.expval(qml.PauliZ(0))
@qml.qnode(dev, interface='tf')
def g(y):
qml.RY(y, wires=0)
return qml.expval(qml.PauliX(... |
@pytest.mark.parametrize('x, y', gradient_test_data)
def test_addition_qnodes_gradient(self, qnodes, x, y):
'Test the gradient of addition of two QNode circuits'
(f, g) = qnodes
def add(a, b):
return (a + b)
xt = Variable(x)
yt = Variable(y)
with tf.GradientTape() as tape:
tape.... | -4,094,283,874,855,288,300 | Test the gradient of addition of two QNode circuits | artifacts/old_dataset_versions/minimal_commits/pennylane/pennylane#385/after/test_tf.py | test_addition_qnodes_gradient | MattePalte/Bugs-Quantum-Computing-Platforms | python | @pytest.mark.parametrize('x, y', gradient_test_data)
def test_addition_qnodes_gradient(self, qnodes, x, y):
(f, g) = qnodes
def add(a, b):
return (a + b)
xt = Variable(x)
yt = Variable(y)
with tf.GradientTape() as tape:
tape.watch([xt, yt])
a = f(xt)
b = g(yt)
... |
@pytest.mark.parametrize('x, y', gradient_test_data)
def test_subtraction_qnodes_gradient(self, qnodes, x, y):
'Test the gradient of subtraction of two QNode circuits'
(f, g) = qnodes
def subtract(a, b):
return (a - b)
xt = Variable(x)
yt = Variable(y)
with tf.GradientTape() as tape:
... | 2,051,418,203,866,679,300 | Test the gradient of subtraction of two QNode circuits | artifacts/old_dataset_versions/minimal_commits/pennylane/pennylane#385/after/test_tf.py | test_subtraction_qnodes_gradient | MattePalte/Bugs-Quantum-Computing-Platforms | python | @pytest.mark.parametrize('x, y', gradient_test_data)
def test_subtraction_qnodes_gradient(self, qnodes, x, y):
(f, g) = qnodes
def subtract(a, b):
return (a - b)
xt = Variable(x)
yt = Variable(y)
with tf.GradientTape() as tape:
tape.watch([xt, yt])
a = f(xt)
b =... |
@pytest.mark.parametrize('x, y', gradient_test_data)
def test_multiplication_qnodes_gradient(self, qnodes, x, y):
'Test the gradient of multiplication of two QNode circuits'
(f, g) = qnodes
def mult(a, b):
return (a * b)
xt = Variable(x)
yt = Variable(y)
with tf.GradientTape() as tape:
... | -5,933,840,820,186,481,000 | Test the gradient of multiplication of two QNode circuits | artifacts/old_dataset_versions/minimal_commits/pennylane/pennylane#385/after/test_tf.py | test_multiplication_qnodes_gradient | MattePalte/Bugs-Quantum-Computing-Platforms | python | @pytest.mark.parametrize('x, y', gradient_test_data)
def test_multiplication_qnodes_gradient(self, qnodes, x, y):
(f, g) = qnodes
def mult(a, b):
return (a * b)
xt = Variable(x)
yt = Variable(y)
with tf.GradientTape() as tape:
tape.watch([xt, yt])
a = f(xt)
b = ... |
@pytest.mark.parametrize('x, y', gradient_test_data)
def test_division_qnodes_gradient(self, qnodes, x, y, tol):
'Test the gradient of division of two QNode circuits'
(f, g) = qnodes
def div(a, b):
return (a / b)
xt = Variable(x)
yt = Variable(y)
with tf.GradientTape() as tape:
... | -7,874,686,265,030,168,000 | Test the gradient of division of two QNode circuits | artifacts/old_dataset_versions/minimal_commits/pennylane/pennylane#385/after/test_tf.py | test_division_qnodes_gradient | MattePalte/Bugs-Quantum-Computing-Platforms | python | @pytest.mark.parametrize('x, y', gradient_test_data)
def test_division_qnodes_gradient(self, qnodes, x, y, tol):
(f, g) = qnodes
def div(a, b):
return (a / b)
xt = Variable(x)
yt = Variable(y)
with tf.GradientTape() as tape:
tape.watch([xt, yt])
a = f(xt)
b = g(... |
@pytest.mark.parametrize('x, y', gradient_test_data)
def test_composition_qnodes_gradient(self, qnodes, x, y):
'Test the gradient of composition of two QNode circuits'
(f, g) = qnodes
xt = Variable(x)
yt = Variable(y)
with tf.GradientTape() as tape:
tape.watch([xt])
y = f(xt)
... | 5,884,952,253,218,689,000 | Test the gradient of composition of two QNode circuits | artifacts/old_dataset_versions/minimal_commits/pennylane/pennylane#385/after/test_tf.py | test_composition_qnodes_gradient | MattePalte/Bugs-Quantum-Computing-Platforms | python | @pytest.mark.parametrize('x, y', gradient_test_data)
def test_composition_qnodes_gradient(self, qnodes, x, y):
(f, g) = qnodes
xt = Variable(x)
yt = Variable(y)
with tf.GradientTape() as tape:
tape.watch([xt])
y = f(xt)
grad1 = tape.gradient(y, xt)
with tf.GradientTape()... |
def tearDown(self):
'\n Clean up all the event sources left behind by either directly by\n test methods or indirectly via some distrib API.\n '
dl = [defer.Deferred(), defer.Deferred()]
if ((self.f1 is not None) and (self.f1.proto is not None)):
self.f1.proto.notifyOnDisconnect(... | 3,693,195,591,005,340,700 | Clean up all the event sources left behind by either directly by
test methods or indirectly via some distrib API. | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py | tearDown | 12123ads/learn_python3_spider | python | def tearDown(self):
'\n Clean up all the event sources left behind by either directly by\n test methods or indirectly via some distrib API.\n '
dl = [defer.Deferred(), defer.Deferred()]
if ((self.f1 is not None) and (self.f1.proto is not None)):
self.f1.proto.notifyOnDisconnect(... |
def _setupDistribServer(self, child):
'\n Set up a resource on a distrib site using L{ResourcePublisher}.\n\n @param child: The resource to publish using distrib.\n\n @return: A tuple consisting of the host and port on which to contact\n the created site.\n '
distribRoot =... | -8,420,973,455,920,807,000 | Set up a resource on a distrib site using L{ResourcePublisher}.
@param child: The resource to publish using distrib.
@return: A tuple consisting of the host and port on which to contact
the created site. | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py | _setupDistribServer | 12123ads/learn_python3_spider | python | def _setupDistribServer(self, child):
'\n Set up a resource on a distrib site using L{ResourcePublisher}.\n\n @param child: The resource to publish using distrib.\n\n @return: A tuple consisting of the host and port on which to contact\n the created site.\n '
distribRoot =... |
def _requestTest(self, child, **kwargs):
'\n Set up a resource on a distrib site using L{ResourcePublisher} and\n then retrieve it from a L{ResourceSubscription} via an HTTP client.\n\n @param child: The resource to publish using distrib.\n @param **kwargs: Extra keyword arguments to pas... | 8,997,882,814,128,054,000 | Set up a resource on a distrib site using L{ResourcePublisher} and
then retrieve it from a L{ResourceSubscription} via an HTTP client.
@param child: The resource to publish using distrib.
@param **kwargs: Extra keyword arguments to pass to L{Agent.request} when
requesting the resource.
@return: A L{Deferred} whic... | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py | _requestTest | 12123ads/learn_python3_spider | python | def _requestTest(self, child, **kwargs):
'\n Set up a resource on a distrib site using L{ResourcePublisher} and\n then retrieve it from a L{ResourceSubscription} via an HTTP client.\n\n @param child: The resource to publish using distrib.\n @param **kwargs: Extra keyword arguments to pas... |
def _requestAgentTest(self, child, **kwargs):
'\n Set up a resource on a distrib site using L{ResourcePublisher} and\n then retrieve it from a L{ResourceSubscription} via an HTTP client.\n\n @param child: The resource to publish using distrib.\n @param **kwargs: Extra keyword arguments t... | -3,814,017,065,179,760,000 | Set up a resource on a distrib site using L{ResourcePublisher} and
then retrieve it from a L{ResourceSubscription} via an HTTP client.
@param child: The resource to publish using distrib.
@param **kwargs: Extra keyword arguments to pass to L{Agent.request} when
requesting the resource.
@return: A L{Deferred} whic... | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py | _requestAgentTest | 12123ads/learn_python3_spider | python | def _requestAgentTest(self, child, **kwargs):
'\n Set up a resource on a distrib site using L{ResourcePublisher} and\n then retrieve it from a L{ResourceSubscription} via an HTTP client.\n\n @param child: The resource to publish using distrib.\n @param **kwargs: Extra keyword arguments t... |
def test_requestHeaders(self):
"\n The request headers are available on the request object passed to a\n distributed resource's C{render} method.\n "
requestHeaders = {}
logObserver = proto_helpers.EventLoggingObserver()
globalLogPublisher.addObserver(logObserver)
req = [None]
... | 6,032,571,273,442,479,000 | The request headers are available on the request object passed to a
distributed resource's C{render} method. | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py | test_requestHeaders | 12123ads/learn_python3_spider | python | def test_requestHeaders(self):
"\n The request headers are available on the request object passed to a\n distributed resource's C{render} method.\n "
requestHeaders = {}
logObserver = proto_helpers.EventLoggingObserver()
globalLogPublisher.addObserver(logObserver)
req = [None]
... |
def test_requestResponseCode(self):
"\n The response code can be set by the request object passed to a\n distributed resource's C{render} method.\n "
class SetResponseCode(resource.Resource):
def render(self, request):
request.setResponseCode(200)
return ''... | 1,863,444,923,536,960,300 | The response code can be set by the request object passed to a
distributed resource's C{render} method. | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py | test_requestResponseCode | 12123ads/learn_python3_spider | python | def test_requestResponseCode(self):
"\n The response code can be set by the request object passed to a\n distributed resource's C{render} method.\n "
class SetResponseCode(resource.Resource):
def render(self, request):
request.setResponseCode(200)
return
... |
def test_requestResponseCodeMessage(self):
"\n The response code and message can be set by the request object passed to\n a distributed resource's C{render} method.\n "
class SetResponseCode(resource.Resource):
def render(self, request):
request.setResponseCode(200, b'... | 2,802,432,140,346,846,700 | The response code and message can be set by the request object passed to
a distributed resource's C{render} method. | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py | test_requestResponseCodeMessage | 12123ads/learn_python3_spider | python | def test_requestResponseCodeMessage(self):
"\n The response code and message can be set by the request object passed to\n a distributed resource's C{render} method.\n "
class SetResponseCode(resource.Resource):
def render(self, request):
request.setResponseCode(200, b'... |
def test_largeWrite(self):
'\n If a string longer than the Banana size limit is passed to the\n L{distrib.Request} passed to the remote resource, it is broken into\n smaller strings to be transported over the PB connection.\n '
class LargeWrite(resource.Resource):
def rende... | -5,210,885,590,019,892,000 | If a string longer than the Banana size limit is passed to the
L{distrib.Request} passed to the remote resource, it is broken into
smaller strings to be transported over the PB connection. | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py | test_largeWrite | 12123ads/learn_python3_spider | python | def test_largeWrite(self):
'\n If a string longer than the Banana size limit is passed to the\n L{distrib.Request} passed to the remote resource, it is broken into\n smaller strings to be transported over the PB connection.\n '
class LargeWrite(resource.Resource):
def rende... |
def test_largeReturn(self):
'\n Like L{test_largeWrite}, but for the case where C{render} returns a\n long string rather than explicitly passing it to L{Request.write}.\n '
class LargeReturn(resource.Resource):
def render(self, request):
return ((b'x' * SIZE_LIMIT) + b... | -9,676,789,066,152,152 | Like L{test_largeWrite}, but for the case where C{render} returns a
long string rather than explicitly passing it to L{Request.write}. | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py | test_largeReturn | 12123ads/learn_python3_spider | python | def test_largeReturn(self):
'\n Like L{test_largeWrite}, but for the case where C{render} returns a\n long string rather than explicitly passing it to L{Request.write}.\n '
class LargeReturn(resource.Resource):
def render(self, request):
return ((b'x' * SIZE_LIMIT) + b... |
def test_connectionLost(self):
'\n If there is an error issuing the request to the remote publisher, an\n error response is returned.\n '
self.f1 = serverFactory = PBServerFactory(pb.Root())
self.port1 = serverPort = reactor.listenTCP(0, serverFactory)
self.sub = subscription = dist... | -6,647,387,831,302,386,000 | If there is an error issuing the request to the remote publisher, an
error response is returned. | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py | test_connectionLost | 12123ads/learn_python3_spider | python | def test_connectionLost(self):
'\n If there is an error issuing the request to the remote publisher, an\n error response is returned.\n '
self.f1 = serverFactory = PBServerFactory(pb.Root())
self.port1 = serverPort = reactor.listenTCP(0, serverFactory)
self.sub = subscription = dist... |
def test_logFailed(self):
'\n When a request fails, the string form of the failure is logged.\n '
logObserver = proto_helpers.EventLoggingObserver.createWithCleanup(self, globalLogPublisher)
f = failure.Failure(ArbitraryError())
request = DummyRequest([b''])
issue = distrib.Issue(reque... | 117,272,590,343,925,780 | When a request fails, the string form of the failure is logged. | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py | test_logFailed | 12123ads/learn_python3_spider | python | def test_logFailed(self):
'\n \n '
logObserver = proto_helpers.EventLoggingObserver.createWithCleanup(self, globalLogPublisher)
f = failure.Failure(ArbitraryError())
request = DummyRequest([b])
issue = distrib.Issue(request)
issue.failed(f)
self.assertEquals(1, len(logObserver)... |
def test_requestFail(self):
"\n When L{twisted.web.distrib.Request}'s fail is called, the failure\n is logged.\n "
logObserver = proto_helpers.EventLoggingObserver.createWithCleanup(self, globalLogPublisher)
err = ArbitraryError()
f = failure.Failure(err)
req = distrib.Request(D... | 4,460,541,986,423,108,000 | When L{twisted.web.distrib.Request}'s fail is called, the failure
is logged. | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py | test_requestFail | 12123ads/learn_python3_spider | python | def test_requestFail(self):
"\n When L{twisted.web.distrib.Request}'s fail is called, the failure\n is logged.\n "
logObserver = proto_helpers.EventLoggingObserver.createWithCleanup(self, globalLogPublisher)
err = ArbitraryError()
f = failure.Failure(err)
req = distrib.Request(D... |
def test_interface(self):
'\n L{UserDirectory} instances provide L{resource.IResource}.\n '
self.assertTrue(verifyObject(resource.IResource, self.directory)) | 2,984,908,371,918,376,400 | L{UserDirectory} instances provide L{resource.IResource}. | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py | test_interface | 12123ads/learn_python3_spider | python | def test_interface(self):
'\n \n '
self.assertTrue(verifyObject(resource.IResource, self.directory)) |
def _404Test(self, name):
'\n Verify that requesting the C{name} child of C{self.directory} results\n in a 404 response.\n '
request = DummyRequest([name])
result = self.directory.getChild(name, request)
d = _render(result, request)
def cbRendered(ignored):
self.assertE... | -7,691,561,648,553,702,000 | Verify that requesting the C{name} child of C{self.directory} results
in a 404 response. | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py | _404Test | 12123ads/learn_python3_spider | python | def _404Test(self, name):
'\n Verify that requesting the C{name} child of C{self.directory} results\n in a 404 response.\n '
request = DummyRequest([name])
result = self.directory.getChild(name, request)
d = _render(result, request)
def cbRendered(ignored):
self.assertE... |
def test_getInvalidUser(self):
'\n L{UserDirectory.getChild} returns a resource which renders a 404\n response when passed a string which does not correspond to any known\n user.\n '
return self._404Test('carol') | 524,398,963,170,523,840 | L{UserDirectory.getChild} returns a resource which renders a 404
response when passed a string which does not correspond to any known
user. | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py | test_getInvalidUser | 12123ads/learn_python3_spider | python | def test_getInvalidUser(self):
'\n L{UserDirectory.getChild} returns a resource which renders a 404\n response when passed a string which does not correspond to any known\n user.\n '
return self._404Test('carol') |
def test_getUserWithoutResource(self):
'\n L{UserDirectory.getChild} returns a resource which renders a 404\n response when passed a string which corresponds to a known user who has\n neither a user directory nor a user distrib socket.\n '
return self._404Test('alice') | 2,095,579,798,873,494,500 | L{UserDirectory.getChild} returns a resource which renders a 404
response when passed a string which corresponds to a known user who has
neither a user directory nor a user distrib socket. | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py | test_getUserWithoutResource | 12123ads/learn_python3_spider | python | def test_getUserWithoutResource(self):
'\n L{UserDirectory.getChild} returns a resource which renders a 404\n response when passed a string which corresponds to a known user who has\n neither a user directory nor a user distrib socket.\n '
return self._404Test('alice') |
def test_getPublicHTMLChild(self):
'\n L{UserDirectory.getChild} returns a L{static.File} instance when passed\n the name of a user with a home directory containing a I{public_html}\n directory.\n '
home = filepath.FilePath(self.bob[(- 2)])
public_html = home.child('public_html')... | 8,963,394,596,767,200,000 | L{UserDirectory.getChild} returns a L{static.File} instance when passed
the name of a user with a home directory containing a I{public_html}
directory. | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py | test_getPublicHTMLChild | 12123ads/learn_python3_spider | python | def test_getPublicHTMLChild(self):
'\n L{UserDirectory.getChild} returns a L{static.File} instance when passed\n the name of a user with a home directory containing a I{public_html}\n directory.\n '
home = filepath.FilePath(self.bob[(- 2)])
public_html = home.child('public_html')... |
def test_getDistribChild(self):
'\n L{UserDirectory.getChild} returns a L{ResourceSubscription} instance\n when passed the name of a user suffixed with C{".twistd"} who has a\n home directory containing a I{.twistd-web-pb} socket.\n '
home = filepath.FilePath(self.bob[(- 2)])
hom... | 2,114,948,889,774,105,000 | L{UserDirectory.getChild} returns a L{ResourceSubscription} instance
when passed the name of a user suffixed with C{".twistd"} who has a
home directory containing a I{.twistd-web-pb} socket. | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py | test_getDistribChild | 12123ads/learn_python3_spider | python | def test_getDistribChild(self):
'\n L{UserDirectory.getChild} returns a L{ResourceSubscription} instance\n when passed the name of a user suffixed with C{".twistd"} who has a\n home directory containing a I{.twistd-web-pb} socket.\n '
home = filepath.FilePath(self.bob[(- 2)])
hom... |
def test_invalidMethod(self):
'\n L{UserDirectory.render} raises L{UnsupportedMethod} in response to a\n non-I{GET} request.\n '
request = DummyRequest([''])
request.method = 'POST'
self.assertRaises(server.UnsupportedMethod, self.directory.render, request) | 6,040,538,577,880,428,000 | L{UserDirectory.render} raises L{UnsupportedMethod} in response to a
non-I{GET} request. | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py | test_invalidMethod | 12123ads/learn_python3_spider | python | def test_invalidMethod(self):
'\n L{UserDirectory.render} raises L{UnsupportedMethod} in response to a\n non-I{GET} request.\n '
request = DummyRequest([])
request.method = 'POST'
self.assertRaises(server.UnsupportedMethod, self.directory.render, request) |
def test_render(self):
'\n L{UserDirectory} renders a list of links to available user content\n in response to a I{GET} request.\n '
public_html = filepath.FilePath(self.alice[(- 2)]).child('public_html')
public_html.makedirs()
web = filepath.FilePath(self.bob[(- 2)])
web.makedi... | -8,024,123,066,555,492,000 | L{UserDirectory} renders a list of links to available user content
in response to a I{GET} request. | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py | test_render | 12123ads/learn_python3_spider | python | def test_render(self):
'\n L{UserDirectory} renders a list of links to available user content\n in response to a I{GET} request.\n '
public_html = filepath.FilePath(self.alice[(- 2)]).child('public_html')
public_html.makedirs()
web = filepath.FilePath(self.bob[(- 2)])
web.makedi... |
def test_passwordDatabase(self):
'\n If L{UserDirectory} is instantiated with no arguments, it uses the\n L{pwd} module as its password database.\n '
directory = distrib.UserDirectory()
self.assertIdentical(directory._pwd, pwd) | -2,410,661,611,890,471,400 | If L{UserDirectory} is instantiated with no arguments, it uses the
L{pwd} module as its password database. | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py | test_passwordDatabase | 12123ads/learn_python3_spider | python | def test_passwordDatabase(self):
'\n If L{UserDirectory} is instantiated with no arguments, it uses the\n L{pwd} module as its password database.\n '
directory = distrib.UserDirectory()
self.assertIdentical(directory._pwd, pwd) |
def on_train_begin(self, **kwargs):
'Call watch method to log model topology, gradients & weights'
super().on_train_begin()
if (not WandbCallback._watch_called):
WandbCallback._watch_called = True
wandb.watch(self.learn.model, log=self.log) | 8,583,803,843,895,094,000 | Call watch method to log model topology, gradients & weights | wandb/fastai/__init__.py | on_train_begin | MPGek/client | python | def on_train_begin(self, **kwargs):
super().on_train_begin()
if (not WandbCallback._watch_called):
WandbCallback._watch_called = True
wandb.watch(self.learn.model, log=self.log) |
def on_epoch_end(self, epoch, smooth_loss, last_metrics, **kwargs):
'Logs training loss, validation loss and custom metrics & log prediction samples & save model'
if self.save_model:
current = self.get_monitor_value()
if ((current is not None) and self.operator(current, self.best)):
... | -2,929,695,461,219,322,000 | Logs training loss, validation loss and custom metrics & log prediction samples & save model | wandb/fastai/__init__.py | on_epoch_end | MPGek/client | python | def on_epoch_end(self, epoch, smooth_loss, last_metrics, **kwargs):
if self.save_model:
current = self.get_monitor_value()
if ((current is not None) and self.operator(current, self.best)):
print('Better model found at epoch {} with {} value: {}.'.format(epoch, self.monitor, current)... |
def on_train_end(self, **kwargs):
'Load the best model.'
if self.save_model:
if self.model_path.is_file():
with self.model_path.open('rb') as model_file:
self.learn.load(model_file, purge=False)
print('Loaded best saved model from {}'.format(self.model_path)) | -5,013,564,440,215,056,000 | Load the best model. | wandb/fastai/__init__.py | on_train_end | MPGek/client | python | def on_train_end(self, **kwargs):
if self.save_model:
if self.model_path.is_file():
with self.model_path.open('rb') as model_file:
self.learn.load(model_file, purge=False)
print('Loaded best saved model from {}'.format(self.model_path)) |
def _wandb_log_predictions(self):
'Log prediction samples'
pred_log = []
for (x, y) in self.validation_data:
try:
pred = self.learn.predict(x)
except:
raise FastaiError('Unable to run "predict" method from Learner to log prediction samples.')
if (not pred[1].s... | -7,904,175,559,029,698,000 | Log prediction samples | wandb/fastai/__init__.py | _wandb_log_predictions | MPGek/client | python | def _wandb_log_predictions(self):
pred_log = []
for (x, y) in self.validation_data:
try:
pred = self.learn.predict(x)
except:
raise FastaiError('Unable to run "predict" method from Learner to log prediction samples.')
if (not pred[1].shape):
pred_... |
def find_in_path(name, path):
'Find a file in a search path'
for dir in path.split(os.pathsep):
binpath = pjoin(dir, name)
if os.path.exists(binpath):
return os.path.abspath(binpath)
return None | -4,401,254,251,811,251,000 | Find a file in a search path | swig_muesli/muesli/da/setup_da.py | find_in_path | NinaHerrmann/muesli2py | python | def find_in_path(name, path):
for dir in path.split(os.pathsep):
binpath = pjoin(dir, name)
if os.path.exists(binpath):
return os.path.abspath(binpath)
return None |
def length_normalize(matrix):
'Length normalize the matrix\n\n Args:\n matrix (np.ndarray): Input matrix that needs to be normalized\n\n Returns:\n Normalized matrix\n '
norms = np.sqrt(np.sum((matrix ** 2), axis=1))
norms[(norms == 0)] = 1
return (matrix / norms[:, np.newaxis]) | -9,094,982,554,804,503,000 | Length normalize the matrix
Args:
matrix (np.ndarray): Input matrix that needs to be normalized
Returns:
Normalized matrix | reco_utils/recommender/geoimc/geoimc_utils.py | length_normalize | 154King154/recommenders | python | def length_normalize(matrix):
'Length normalize the matrix\n\n Args:\n matrix (np.ndarray): Input matrix that needs to be normalized\n\n Returns:\n Normalized matrix\n '
norms = np.sqrt(np.sum((matrix ** 2), axis=1))
norms[(norms == 0)] = 1
return (matrix / norms[:, np.newaxis]) |
def mean_center(matrix):
'Performs mean centering across axis 0\n\n Args:\n matrix (np.ndarray): Input matrix that needs to be mean centered\n '
avg = np.mean(matrix, axis=0)
matrix -= avg | 313,667,976,247,406,600 | Performs mean centering across axis 0
Args:
matrix (np.ndarray): Input matrix that needs to be mean centered | reco_utils/recommender/geoimc/geoimc_utils.py | mean_center | 154King154/recommenders | python | def mean_center(matrix):
'Performs mean centering across axis 0\n\n Args:\n matrix (np.ndarray): Input matrix that needs to be mean centered\n '
avg = np.mean(matrix, axis=0)
matrix -= avg |
def reduce_dims(matrix, target_dim):
'Reduce dimensionality of the data using PCA.\n\n Args:\n matrix (np.ndarray): Matrix of the form (n_sampes, n_features)\n target_dim (uint): Dimension to which n_features should be reduced to.\n\n '
model = PCA(n_components=target_dim)
model.fit(matr... | 8,133,367,132,709,024,000 | Reduce dimensionality of the data using PCA.
Args:
matrix (np.ndarray): Matrix of the form (n_sampes, n_features)
target_dim (uint): Dimension to which n_features should be reduced to. | reco_utils/recommender/geoimc/geoimc_utils.py | reduce_dims | 154King154/recommenders | python | def reduce_dims(matrix, target_dim):
'Reduce dimensionality of the data using PCA.\n\n Args:\n matrix (np.ndarray): Matrix of the form (n_sampes, n_features)\n target_dim (uint): Dimension to which n_features should be reduced to.\n\n '
model = PCA(n_components=target_dim)
model.fit(matr... |
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
'\n #最长连续公共子串\n l1=len(text1)\n l2=len(text2)\n\n if l1==0 or l2==0:\n return 0\n dp = [[0 for i in range(l2)] for i in range(l1)]\n res = 0\n if text1[0]==text2[0]:\n dp[0][0]=1... | -8,524,905,220,200,732,000 | #最长连续公共子串
l1=len(text1)
l2=len(text2)
if l1==0 or l2==0:
return 0
dp = [[0 for i in range(l2)] for i in range(l1)]
res = 0
if text1[0]==text2[0]:
dp[0][0]=1
res=1
for i in range(1,l2):
if text2[i]==text1[0]:
dp[0][i]=1
res=1
for i in range(1,l1):
if text1[i]==text2[0]:
dp[i]... | DP/Leetcode1143.py | longestCommonSubsequence | Rylie-W/LeetRecord | python | def longestCommonSubsequence(self, text1: str, text2: str) -> int:
'\n #最长连续公共子串\n l1=len(text1)\n l2=len(text2)\n\n if l1==0 or l2==0:\n return 0\n dp = [[0 for i in range(l2)] for i in range(l1)]\n res = 0\n if text1[0]==text2[0]:\n dp[0][0]=1... |
def initialize_weights(model):
'\n Initializes the weights of a model in place.\n\n :param model: An nn.Module.\n '
for param in model.parameters():
if (param.dim() > 1):
nn.init.xavier_normal_(param) | -4,855,580,883,977,360,000 | Initializes the weights of a model in place.
:param model: An nn.Module. | Repeat/CoMPT/utils_node.py | initialize_weights | jcchan23/SAIL | python | def initialize_weights(model):
'\n Initializes the weights of a model in place.\n\n :param model: An nn.Module.\n '
for param in model.parameters():
if (param.dim() > 1):
nn.init.xavier_normal_(param) |
def __init__(self, optimizer, warmup_epochs, total_epochs, steps_per_epoch, init_lr, max_lr, final_lr):
'\n Initializes the learning rate scheduler.\n\n :param optimizer: A PyTorch optimizer.\n :param warmup_epochs: The number of epochs during which to linearly increase the learning rate.\n ... | 8,412,762,859,212,071,000 | Initializes the learning rate scheduler.
:param optimizer: A PyTorch optimizer.
:param warmup_epochs: The number of epochs during which to linearly increase the learning rate.
:param total_epochs: The total number of epochs.
:param steps_per_epoch: The number of steps (batches) per epoch.
:param init_lr: The initial l... | Repeat/CoMPT/utils_node.py | __init__ | jcchan23/SAIL | python | def __init__(self, optimizer, warmup_epochs, total_epochs, steps_per_epoch, init_lr, max_lr, final_lr):
'\n Initializes the learning rate scheduler.\n\n :param optimizer: A PyTorch optimizer.\n :param warmup_epochs: The number of epochs during which to linearly increase the learning rate.\n ... |
def get_lr(self):
'Gets a list of the current learning rates.'
return list(self.lr) | -3,543,556,912,278,854,700 | Gets a list of the current learning rates. | Repeat/CoMPT/utils_node.py | get_lr | jcchan23/SAIL | python | def get_lr(self):
return list(self.lr) |
def step(self, current_step: int=None):
'\n Updates the learning rate by taking a step.\n\n :param current_step: Optionally specify what step to set the learning rate to.\n If None, current_step = self.current_step + 1.\n '
if (current_step is not None):
self.current_step = c... | -2,704,965,584,552,467,000 | Updates the learning rate by taking a step.
:param current_step: Optionally specify what step to set the learning rate to.
If None, current_step = self.current_step + 1. | Repeat/CoMPT/utils_node.py | step | jcchan23/SAIL | python | def step(self, current_step: int=None):
'\n Updates the learning rate by taking a step.\n\n :param current_step: Optionally specify what step to set the learning rate to.\n If None, current_step = self.current_step + 1.\n '
if (current_step is not None):
self.current_step = c... |
def setUp(self):
'Get all the PROTO files to be tested.'
self.version = None
with open(((((os.environ['WEBOTS_HOME'] + os.sep) + 'resources') + os.sep) + 'version.txt')) as file:
content = file.read()
self.version = content.splitlines()[0].strip().split()[0]
self.files = []
for (root... | -3,331,968,831,251,895,300 | Get all the PROTO files to be tested. | tests/sources/test_header_version.py | setUp | junjihashimoto/webots | python | def setUp(self):
self.version = None
with open(((((os.environ['WEBOTS_HOME'] + os.sep) + 'resources') + os.sep) + 'version.txt')) as file:
content = file.read()
self.version = content.splitlines()[0].strip().split()[0]
self.files = []
for (rootPath, dirNames, fileNames) in os.walk(o... |
def test_header_version(self):
'Test that the PROTO and world files have the correct header.'
for currentFile in self.files:
fileToTest = currentFile[0]
with open(fileToTest) as file:
content = file.read()
if (content == ''):
continue
line = co... | -272,396,101,947,376,400 | Test that the PROTO and world files have the correct header. | tests/sources/test_header_version.py | test_header_version | junjihashimoto/webots | python | def test_header_version(self):
for currentFile in self.files:
fileToTest = currentFile[0]
with open(fileToTest) as file:
content = file.read()
if (content == ):
continue
line = content.splitlines()[0].strip()
self.assertTrue(line.s... |
def float_with_error(x):
'\n some value in cif accompanies error like "1.234(5)\n '
if ('?' in x):
return 0
pos = x.find('(')
if (pos >= 0):
x = x[:pos]
return float(x) | -7,629,848,625,370,556,000 | some value in cif accompanies error like "1.234(5) | cif_tools.py | float_with_error | cwaitt/zse | python | def float_with_error(x):
'\n \n '
if ('?' in x):
return 0
pos = x.find('(')
if (pos >= 0):
x = x[:pos]
return float(x) |
def get_indices(cif):
'\n This is a tool that will read a CIF file and return the unique T-sites,\n their multiplicities, and an example atom index.\n\n It also does the same for the unique O-sites in the framework.\n\n This tool only works on CIFs that are formatted the same way as the IZA\n Structu... | -8,522,372,167,062,766,000 | This is a tool that will read a CIF file and return the unique T-sites,
their multiplicities, and an example atom index.
It also does the same for the unique O-sites in the framework.
This tool only works on CIFs that are formatted the same way as the IZA
Structure Database CIFs. | cif_tools.py | get_indices | cwaitt/zse | python | def get_indices(cif):
'\n This is a tool that will read a CIF file and return the unique T-sites,\n their multiplicities, and an example atom index.\n\n It also does the same for the unique O-sites in the framework.\n\n This tool only works on CIFs that are formatted the same way as the IZA\n Structu... |
@classmethod
def from_service_account_file(cls, filename, *args, **kwargs):
'Creates an instance of this client using the provided credentials\n file.\n\n Args:\n filename (str): The path to the service account private key json\n file.\n args: Additional arguments ... | 8,165,111,019,497,557,000 | Creates an instance of this client using the provided credentials
file.
Args:
filename (str): The path to the service account private key json
file.
args: Additional arguments to pass to the constructor.
kwargs: Additional arguments to pass to the constructor.
Returns:
TextToSpeechClient: The ... | texttospeech/google/cloud/texttospeech_v1beta1/gapic/text_to_speech_client.py | from_service_account_file | Abd-Elrazek/google-cloud-python | python | @classmethod
def from_service_account_file(cls, filename, *args, **kwargs):
'Creates an instance of this client using the provided credentials\n file.\n\n Args:\n filename (str): The path to the service account private key json\n file.\n args: Additional arguments ... |
def __init__(self, transport=None, channel=None, credentials=None, client_config=None, client_info=None):
"Constructor.\n\n Args:\n transport (Union[~.TextToSpeechGrpcTransport,\n Callable[[~.Credentials, type], ~.TextToSpeechGrpcTransport]): A transport\n instanc... | -6,464,139,821,673,658,000 | Constructor.
Args:
transport (Union[~.TextToSpeechGrpcTransport,
Callable[[~.Credentials, type], ~.TextToSpeechGrpcTransport]): A transport
instance, responsible for actually making the API calls.
The default transport uses the gRPC protocol.
This argument may also be a callable... | texttospeech/google/cloud/texttospeech_v1beta1/gapic/text_to_speech_client.py | __init__ | Abd-Elrazek/google-cloud-python | python | def __init__(self, transport=None, channel=None, credentials=None, client_config=None, client_info=None):
"Constructor.\n\n Args:\n transport (Union[~.TextToSpeechGrpcTransport,\n Callable[[~.Credentials, type], ~.TextToSpeechGrpcTransport]): A transport\n instanc... |
def list_voices(self, language_code=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None):
'\n Returns a list of ``Voice`` supported for synthesis.\n\n Example:\n >>> from google.cloud import texttospeech_v1beta1\n >>... | 3,337,317,461,552,284,700 | Returns a list of ``Voice`` supported for synthesis.
Example:
>>> from google.cloud import texttospeech_v1beta1
>>>
>>> client = texttospeech_v1beta1.TextToSpeechClient()
>>>
>>> response = client.list_voices()
Args:
language_code (str): Optional (but recommended)
`BCP-47 <https://www.... | texttospeech/google/cloud/texttospeech_v1beta1/gapic/text_to_speech_client.py | list_voices | Abd-Elrazek/google-cloud-python | python | def list_voices(self, language_code=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None):
'\n Returns a list of ``Voice`` supported for synthesis.\n\n Example:\n >>> from google.cloud import texttospeech_v1beta1\n >>... |
def synthesize_speech(self, input_, voice, audio_config, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None):
'\n Synthesizes speech synchronously: receive results after all text input\n has been processed.\n\n Example:\n >>>... | -245,552,770,767,781,020 | Synthesizes speech synchronously: receive results after all text input
has been processed.
Example:
>>> from google.cloud import texttospeech_v1beta1
>>>
>>> client = texttospeech_v1beta1.TextToSpeechClient()
>>>
>>> # TODO: Initialize `input_`:
>>> input_ = {}
>>>
>>> # TODO: Initializ... | texttospeech/google/cloud/texttospeech_v1beta1/gapic/text_to_speech_client.py | synthesize_speech | Abd-Elrazek/google-cloud-python | python | def synthesize_speech(self, input_, voice, audio_config, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None):
'\n Synthesizes speech synchronously: receive results after all text input\n has been processed.\n\n Example:\n >>>... |
@noPosargs
@permittedKwargs({})
def symbols_have_underscore_prefix_method(self, args, kwargs):
'\n Check if the compiler prefixes _ (underscore) to global C symbols\n See: https://en.wikipedia.org/wiki/Name_mangling#C\n '
return self.compiler.symbols_have_underscore_prefix(self.environment) | 362,288,032,390,152,640 | Check if the compiler prefixes _ (underscore) to global C symbols
See: https://en.wikipedia.org/wiki/Name_mangling#C | mesonbuild/interpreter.py | symbols_have_underscore_prefix_method | tolnaisz/meson | python | @noPosargs
@permittedKwargs({})
def symbols_have_underscore_prefix_method(self, args, kwargs):
'\n Check if the compiler prefixes _ (underscore) to global C symbols\n See: https://en.wikipedia.org/wiki/Name_mangling#C\n '
return self.compiler.symbols_have_underscore_prefix(self.environment) |
@noPosargs
@permittedKwargs({})
def unittest_args_method(self, args, kwargs):
'\n This function is deprecated and should not be used.\n It can be removed in a future version of Meson.\n '
if (not hasattr(self.compiler, 'get_feature_args')):
raise InterpreterException('This {} compil... | -1,227,826,540,872,375,300 | This function is deprecated and should not be used.
It can be removed in a future version of Meson. | mesonbuild/interpreter.py | unittest_args_method | tolnaisz/meson | python | @noPosargs
@permittedKwargs({})
def unittest_args_method(self, args, kwargs):
'\n This function is deprecated and should not be used.\n It can be removed in a future version of Meson.\n '
if (not hasattr(self.compiler, 'get_feature_args')):
raise InterpreterException('This {} compil... |
def _handle_featurenew_dependencies(self, name):
'Do a feature check on dependencies used by this subproject'
if (name == 'mpi'):
FeatureNew('MPI Dependency', '0.42.0').use(self.subproject)
elif (name == 'pcap'):
FeatureNew('Pcap Dependency', '0.42.0').use(self.subproject)
elif (name == ... | -4,183,288,055,773,951,000 | Do a feature check on dependencies used by this subproject | mesonbuild/interpreter.py | _handle_featurenew_dependencies | tolnaisz/meson | python | def _handle_featurenew_dependencies(self, name):
if (name == 'mpi'):
FeatureNew('MPI Dependency', '0.42.0').use(self.subproject)
elif (name == 'pcap'):
FeatureNew('Pcap Dependency', '0.42.0').use(self.subproject)
elif (name == 'vulkan'):
FeatureNew('Vulkan Dependency', '0.42.0')... |
def _func_custom_target_impl(self, node, args, kwargs):
'Implementation-only, without FeatureNew checks, for internal use'
name = args[0]
kwargs['install_mode'] = self._get_kwarg_install_mode(kwargs)
if ('input' in kwargs):
try:
kwargs['input'] = self.source_strings_to_files(extract_... | -1,760,694,228,567,836,000 | Implementation-only, without FeatureNew checks, for internal use | mesonbuild/interpreter.py | _func_custom_target_impl | tolnaisz/meson | python | def _func_custom_target_impl(self, node, args, kwargs):
name = args[0]
kwargs['install_mode'] = self._get_kwarg_install_mode(kwargs)
if ('input' in kwargs):
try:
kwargs['input'] = self.source_strings_to_files(extract_as_list(kwargs, 'input'))
except mesonlib.MesonException:
... |
def keras_convert_hdf5_model_to_tf_saved_model(model_path: InputPath('KerasModelHdf5'), converted_model_path: OutputPath('TensorflowSavedModel')):
'Converts Keras HDF5 model to Tensorflow SavedModel format.\n\n Args:\n model_path: Keras model in HDF5 format.\n converted_model_path: Keras model in T... | 6,726,971,064,905,890,000 | Converts Keras HDF5 model to Tensorflow SavedModel format.
Args:
model_path: Keras model in HDF5 format.
converted_model_path: Keras model in Tensorflow SavedModel format.
Annotations:
author: Alexey Volkov <example@example.com> | components/_converters/KerasModelHdf5/to_TensorflowSavedModel/component.py | keras_convert_hdf5_model_to_tf_saved_model | 9rince/kfp | python | def keras_convert_hdf5_model_to_tf_saved_model(model_path: InputPath('KerasModelHdf5'), converted_model_path: OutputPath('TensorflowSavedModel')):
'Converts Keras HDF5 model to Tensorflow SavedModel format.\n\n Args:\n model_path: Keras model in HDF5 format.\n converted_model_path: Keras model in T... |
def __init__(self, Token, URL, get_all_field=False):
'\n Create a project using PyCap\n :param Token:\n :param URL:\n :return:\n '
self.project = Project(URL, Token)
fields_keyid = ['patientID', 'cf_p_cnnpatientui']
self.data = self.get_fields(fields_keyid)
if get_... | 8,593,968,137,652,244,000 | Create a project using PyCap
:param Token:
:param URL:
:return: | query_CNFUN.py | __init__ | CNBP/RCAPI | python | def __init__(self, Token, URL, get_all_field=False):
'\n Create a project using PyCap\n :param Token:\n :param URL:\n :return:\n '
self.project = Project(URL, Token)
fields_keyid = ['patientID', 'cf_p_cnnpatientui']
self.data = self.get_fields(fields_keyid)
if get_... |
def filter_with_CNNPatientUI(self, CNNPatientUI: (str or List[str])):
'\n Check the list, only retain the relevant records with matching PatientID are retained.\n :param dataset: CNBPIDs & record ID correspondence list.\n :param CNNPatientUI:\n :return:\n '
list_filtered = Non... | 2,923,195,438,025,086,500 | Check the list, only retain the relevant records with matching PatientID are retained.
:param dataset: CNBPIDs & record ID correspondence list.
:param CNNPatientUI:
:return: | query_CNFUN.py | filter_with_CNNPatientUI | CNBP/RCAPI | python | def filter_with_CNNPatientUI(self, CNNPatientUI: (str or List[str])):
'\n Check the list, only retain the relevant records with matching PatientID are retained.\n :param dataset: CNBPIDs & record ID correspondence list.\n :param CNNPatientUI:\n :return:\n '
list_filtered = Non... |
def get_PatientID_with_CNNPatientUI(self, CNNPatientUI: (str or List[str])):
'\n PatientID has 1:1 correspondence with CNNPatientUI which is the same as PatientUI from CNN Baby table.\n :return:\n '
if (type(CNNPatientUI) is str):
CNNPatientUI = [CNNPatientUI]
list_filtered_dict... | 6,397,022,490,869,362,000 | PatientID has 1:1 correspondence with CNNPatientUI which is the same as PatientUI from CNN Baby table.
:return: | query_CNFUN.py | get_PatientID_with_CNNPatientUI | CNBP/RCAPI | python | def get_PatientID_with_CNNPatientUI(self, CNNPatientUI: (str or List[str])):
'\n PatientID has 1:1 correspondence with CNNPatientUI which is the same as PatientUI from CNN Baby table.\n :return:\n '
if (type(CNNPatientUI) is str):
CNNPatientUI = [CNNPatientUI]
list_filtered_dict... |
def get_records_CNFUN(self, PatientID: (str or List[str])):
'\n Retrieve the cases based on their INDEX which is the\n :param cases:\n :return:\n '
if (type(PatientID) is str):
PatientID = [PatientID]
cases_data = self.project.export_records(records=PatientID)
return ... | -8,302,587,750,901,383,000 | Retrieve the cases based on their INDEX which is the
:param cases:
:return: | query_CNFUN.py | get_records_CNFUN | CNBP/RCAPI | python | def get_records_CNFUN(self, PatientID: (str or List[str])):
'\n Retrieve the cases based on their INDEX which is the\n :param cases:\n :return:\n '
if (type(PatientID) is str):
PatientID = [PatientID]
cases_data = self.project.export_records(records=PatientID)
return ... |
def __init__(self, id=None, name=None, created_at=None, updated_at=None):
'\n Role - a model defined in Swagger\n\n :param dict swaggerTypes: The key is attribute name\n and the value is attribute type.\n :param dict attributeMap: The key is attribute name\n ... | -3,533,986,126,233,254,000 | Role - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition. | esp_sdk/models/role.py | __init__ | EvidentSecurity/esp-sdk-python | python | def __init__(self, id=None, name=None, created_at=None, updated_at=None):
'\n Role - a model defined in Swagger\n\n :param dict swaggerTypes: The key is attribute name\n and the value is attribute type.\n :param dict attributeMap: The key is attribute name\n ... |
@property
def id(self):
'\n Gets the id of this Role.\n Unique ID\n\n :return: The id of this Role.\n :rtype: int\n '
return self._id | -4,175,835,661,677,043,700 | Gets the id of this Role.
Unique ID
:return: The id of this Role.
:rtype: int | esp_sdk/models/role.py | id | EvidentSecurity/esp-sdk-python | python | @property
def id(self):
'\n Gets the id of this Role.\n Unique ID\n\n :return: The id of this Role.\n :rtype: int\n '
return self._id |
@id.setter
def id(self, id):
'\n Sets the id of this Role.\n Unique ID\n\n :param id: The id of this Role.\n :type: int\n '
self._id = id | -3,053,184,595,672,948,000 | Sets the id of this Role.
Unique ID
:param id: The id of this Role.
:type: int | esp_sdk/models/role.py | id | EvidentSecurity/esp-sdk-python | python | @id.setter
def id(self, id):
'\n Sets the id of this Role.\n Unique ID\n\n :param id: The id of this Role.\n :type: int\n '
self._id = id |
@property
def name(self):
'\n Gets the name of this Role.\n The name of the role\n\n :return: The name of this Role.\n :rtype: str\n '
return self._name | -3,958,561,292,520,585,000 | Gets the name of this Role.
The name of the role
:return: The name of this Role.
:rtype: str | esp_sdk/models/role.py | name | EvidentSecurity/esp-sdk-python | python | @property
def name(self):
'\n Gets the name of this Role.\n The name of the role\n\n :return: The name of this Role.\n :rtype: str\n '
return self._name |
@name.setter
def name(self, name):
'\n Sets the name of this Role.\n The name of the role\n\n :param name: The name of this Role.\n :type: str\n '
self._name = name | 8,241,518,132,240,190,000 | Sets the name of this Role.
The name of the role
:param name: The name of this Role.
:type: str | esp_sdk/models/role.py | name | EvidentSecurity/esp-sdk-python | python | @name.setter
def name(self, name):
'\n Sets the name of this Role.\n The name of the role\n\n :param name: The name of this Role.\n :type: str\n '
self._name = name |
@property
def created_at(self):
'\n Gets the created_at of this Role.\n ISO 8601 timestamp when the resource was created\n\n :return: The created_at of this Role.\n :rtype: datetime\n '
return self._created_at | 5,446,404,519,584,327,000 | Gets the created_at of this Role.
ISO 8601 timestamp when the resource was created
:return: The created_at of this Role.
:rtype: datetime | esp_sdk/models/role.py | created_at | EvidentSecurity/esp-sdk-python | python | @property
def created_at(self):
'\n Gets the created_at of this Role.\n ISO 8601 timestamp when the resource was created\n\n :return: The created_at of this Role.\n :rtype: datetime\n '
return self._created_at |
@created_at.setter
def created_at(self, created_at):
'\n Sets the created_at of this Role.\n ISO 8601 timestamp when the resource was created\n\n :param created_at: The created_at of this Role.\n :type: datetime\n '
self._created_at = created_at | 7,548,933,885,825,973,000 | Sets the created_at of this Role.
ISO 8601 timestamp when the resource was created
:param created_at: The created_at of this Role.
:type: datetime | esp_sdk/models/role.py | created_at | EvidentSecurity/esp-sdk-python | python | @created_at.setter
def created_at(self, created_at):
'\n Sets the created_at of this Role.\n ISO 8601 timestamp when the resource was created\n\n :param created_at: The created_at of this Role.\n :type: datetime\n '
self._created_at = created_at |
@property
def updated_at(self):
'\n Gets the updated_at of this Role.\n ISO 8601 timestamp when the resource was updated\n\n :return: The updated_at of this Role.\n :rtype: datetime\n '
return self._updated_at | 107,710,952,778,185,120 | Gets the updated_at of this Role.
ISO 8601 timestamp when the resource was updated
:return: The updated_at of this Role.
:rtype: datetime | esp_sdk/models/role.py | updated_at | EvidentSecurity/esp-sdk-python | python | @property
def updated_at(self):
'\n Gets the updated_at of this Role.\n ISO 8601 timestamp when the resource was updated\n\n :return: The updated_at of this Role.\n :rtype: datetime\n '
return self._updated_at |
@updated_at.setter
def updated_at(self, updated_at):
'\n Sets the updated_at of this Role.\n ISO 8601 timestamp when the resource was updated\n\n :param updated_at: The updated_at of this Role.\n :type: datetime\n '
self._updated_at = updated_at | 2,238,393,510,890,466,300 | Sets the updated_at of this Role.
ISO 8601 timestamp when the resource was updated
:param updated_at: The updated_at of this Role.
:type: datetime | esp_sdk/models/role.py | updated_at | EvidentSecurity/esp-sdk-python | python | @updated_at.setter
def updated_at(self, updated_at):
'\n Sets the updated_at of this Role.\n ISO 8601 timestamp when the resource was updated\n\n :param updated_at: The updated_at of this Role.\n :type: datetime\n '
self._updated_at = updated_at |
def to_dict(self):
'\n Returns the model properties as a dict\n '
result = {}
for (attr, _) in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map((lambda x: (x.to_dict() if hasattr(x, 'to_dict') else x)), v... | 2,191,974,537,531,847,000 | Returns the model properties as a dict | esp_sdk/models/role.py | to_dict | EvidentSecurity/esp-sdk-python | python | def to_dict(self):
'\n \n '
result = {}
for (attr, _) in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map((lambda x: (x.to_dict() if hasattr(x, 'to_dict') else x)), value))
elif hasattr(value, 'to... |
def to_str(self):
'\n Returns the string representation of the model\n '
return pformat(self.to_dict()) | -3,531,024,894,346,511,000 | Returns the string representation of the model | esp_sdk/models/role.py | to_str | EvidentSecurity/esp-sdk-python | python | def to_str(self):
'\n \n '
return pformat(self.to_dict()) |
def __repr__(self):
'\n For `print` and `pprint`\n '
return self.to_str() | 5,853,962,500,611,353,000 | For `print` and `pprint` | esp_sdk/models/role.py | __repr__ | EvidentSecurity/esp-sdk-python | python | def __repr__(self):
'\n \n '
return self.to_str() |
def __eq__(self, other):
'\n Returns true if both objects are equal\n '
if (not isinstance(other, Role)):
return False
return (self.__dict__ == other.__dict__) | -4,678,687,099,986,198,000 | Returns true if both objects are equal | esp_sdk/models/role.py | __eq__ | EvidentSecurity/esp-sdk-python | python | def __eq__(self, other):
'\n \n '
if (not isinstance(other, Role)):
return False
return (self.__dict__ == other.__dict__) |
def __ne__(self, other):
'\n Returns true if both objects are not equal\n '
return (not (self == other)) | 3,600,423,175,817,510,400 | Returns true if both objects are not equal | esp_sdk/models/role.py | __ne__ | EvidentSecurity/esp-sdk-python | python | def __ne__(self, other):
'\n \n '
return (not (self == other)) |
def testDashboard(self):
'Test Dashboard'
pass | 6,571,422,790,749,848,000 | Test Dashboard | test/test_dashboard.py | testDashboard | PowerOlive/python-client | python | def testDashboard(self):
pass |
def get_gif():
'Return gif.'
gif = BytesIO(b'GIF87a\x01\x00\x01\x00\x80\x01\x00\x00\x00\x00ccc,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;')
gif.name = 'image.gif'
return gif | 2,126,571,613,711,030,800 | Return gif. | modoboa_webmail/tests/test_views.py | get_gif | modoboa/modoboa-webmail | python | def get_gif():
gif = BytesIO(b'GIF87a\x01\x00\x01\x00\x80\x01\x00\x00\x00\x00ccc,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;')
gif.name = 'image.gif'
return gif |
@classmethod
def setUpTestData(cls):
'Create some users.'
super(WebmailTestCase, cls).setUpTestData()
admin_factories.populate_database()
cls.user = core_models.User.objects.get(username='example@example.com') | 5,195,052,972,593,634,000 | Create some users. | modoboa_webmail/tests/test_views.py | setUpTestData | modoboa/modoboa-webmail | python | @classmethod
def setUpTestData(cls):
super(WebmailTestCase, cls).setUpTestData()
admin_factories.populate_database()
cls.user = core_models.User.objects.get(username='example@example.com') |
def setUp(self):
'Connect with a simpler user.'
patcher = mock.patch('imaplib.IMAP4')
self.mock_imap4 = patcher.start()
self.mock_imap4.return_value = IMAP4Mock()
self.addCleanup(patcher.stop)
self.set_global_parameter('imap_port', 1435)
self.workdir = tempfile.mkdtemp()
os.mkdir('{}/web... | 8,880,333,680,631,719,000 | Connect with a simpler user. | modoboa_webmail/tests/test_views.py | setUp | modoboa/modoboa-webmail | python | def setUp(self):
patcher = mock.patch('imaplib.IMAP4')
self.mock_imap4 = patcher.start()
self.mock_imap4.return_value = IMAP4Mock()
self.addCleanup(patcher.stop)
self.set_global_parameter('imap_port', 1435)
self.workdir = tempfile.mkdtemp()
os.mkdir('{}/webmail'.format(self.workdir))
... |
def tearDown(self):
'Cleanup.'
shutil.rmtree(self.workdir) | 6,105,586,400,696,134,000 | Cleanup. | modoboa_webmail/tests/test_views.py | tearDown | modoboa/modoboa-webmail | python | def tearDown(self):
shutil.rmtree(self.workdir) |
def test_listmailbox(self):
'Check listmailbox action.'
url = reverse('modoboa_webmail:index')
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
response = self.client.get('{}?action=listmailbox'.format(url), HTTP_X_REQUESTED_WITH='XMLHttpRequest')
self.assertEqual(resp... | -4,219,483,767,522,329,600 | Check listmailbox action. | modoboa_webmail/tests/test_views.py | test_listmailbox | modoboa/modoboa-webmail | python | def test_listmailbox(self):
url = reverse('modoboa_webmail:index')
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
response = self.client.get('{}?action=listmailbox'.format(url), HTTP_X_REQUESTED_WITH='XMLHttpRequest')
self.assertEqual(response.status_code, 200)
... |
def test_attachments(self):
'Check attachments.'
url = reverse('modoboa_webmail:index')
response = self.client.get('{}?action=compose'.format(url))
self.assertEqual(response.status_code, 200)
self.assertIn('compose_mail', self.client.session)
url = reverse('modoboa_webmail:attachment_list')
... | 621,653,214,064,495,600 | Check attachments. | modoboa_webmail/tests/test_views.py | test_attachments | modoboa/modoboa-webmail | python | def test_attachments(self):
url = reverse('modoboa_webmail:index')
response = self.client.get('{}?action=compose'.format(url))
self.assertEqual(response.status_code, 200)
self.assertIn('compose_mail', self.client.session)
url = reverse('modoboa_webmail:attachment_list')
response = self.clie... |
def test_delattachment_errors(self):
'Check error cases.'
url = reverse('modoboa_webmail:index')
response = self.client.get('{}?action=compose'.format(url))
self.assertEqual(response.status_code, 200)
self.assertIn('compose_mail', self.client.session)
url = reverse('modoboa_webmail:attachment_de... | -4,068,887,393,520,834,600 | Check error cases. | modoboa_webmail/tests/test_views.py | test_delattachment_errors | modoboa/modoboa-webmail | python | def test_delattachment_errors(self):
url = reverse('modoboa_webmail:index')
response = self.client.get('{}?action=compose'.format(url))
self.assertEqual(response.status_code, 200)
self.assertIn('compose_mail', self.client.session)
url = reverse('modoboa_webmail:attachment_delete')
with self... |
def test_send_mail(self):
'Check compose form.'
url = '{}?action=compose'.format(reverse('modoboa_webmail:index'))
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
response = self.client.post(url, {'from_': self.user.email, 'to': 'example@example.com', 'subject': 'test', '... | -1,387,542,173,281,891,300 | Check compose form. | modoboa_webmail/tests/test_views.py | test_send_mail | modoboa/modoboa-webmail | python | def test_send_mail(self):
url = '{}?action=compose'.format(reverse('modoboa_webmail:index'))
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
response = self.client.post(url, {'from_': self.user.email, 'to': 'example@example.com', 'subject': 'test', 'body': 'Test'})
s... |
def test_signature(self):
'Check signature in different formats.'
signature = 'Antoine Nguyen'
self.user.parameters.set_value('signature', signature)
self.user.save()
response = self.client.get(reverse('modoboa_webmail:index'))
self.assertEqual(response.status_code, 200)
url = '{}?action=com... | 848,823,360,628,905,700 | Check signature in different formats. | modoboa_webmail/tests/test_views.py | test_signature | modoboa/modoboa-webmail | python | def test_signature(self):
signature = 'Antoine Nguyen'
self.user.parameters.set_value('signature', signature)
self.user.save()
response = self.client.get(reverse('modoboa_webmail:index'))
self.assertEqual(response.status_code, 200)
url = '{}?action=compose'.format(reverse('modoboa_webmail:i... |
def test_custom_js_in_preferences(self):
'Check that custom js is included.'
url = reverse('core:user_index')
response = self.client.get(url)
self.assertContains(response, 'function toggleSignatureEditor()') | 8,341,938,609,019,007,000 | Check that custom js is included. | modoboa_webmail/tests/test_views.py | test_custom_js_in_preferences | modoboa/modoboa-webmail | python | def test_custom_js_in_preferences(self):
url = reverse('core:user_index')
response = self.client.get(url)
self.assertContains(response, 'function toggleSignatureEditor()') |
def test_send_mail_errors(self):
'Check error cases.'
url = '{}?action=compose'.format(reverse('modoboa_webmail:index'))
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
response = self.ajax_post(url, {'to': '', 'subject': 'test', 'body': 'Test'}, 400)
self.assertEqual... | -4,056,351,638,885,951,500 | Check error cases. | modoboa_webmail/tests/test_views.py | test_send_mail_errors | modoboa/modoboa-webmail | python | def test_send_mail_errors(self):
url = '{}?action=compose'.format(reverse('modoboa_webmail:index'))
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
response = self.ajax_post(url, {'to': , 'subject': 'test', 'body': 'Test'}, 400)
self.assertEqual(len(mail.outbox), 0) |
def test_new_folder(self):
'Test folder creation.'
url = reverse('modoboa_webmail:folder_add')
response = self.client.get(url)
self.assertContains(response, 'Create a new folder')
response = self.ajax_post(url, {'name': 'Test'})
self.assertIn('newmb', response) | 5,715,399,611,297,225,000 | Test folder creation. | modoboa_webmail/tests/test_views.py | test_new_folder | modoboa/modoboa-webmail | python | def test_new_folder(self):
url = reverse('modoboa_webmail:folder_add')
response = self.client.get(url)
self.assertContains(response, 'Create a new folder')
response = self.ajax_post(url, {'name': 'Test'})
self.assertIn('newmb', response) |
def test_edit_folder(self):
'Test folder edition.'
url = reverse('modoboa_webmail:folder_change')
response = self.client.get(url)
self.assertContains(response, 'Invalid request')
url = '{}?name=Test'.format(url)
response = self.client.get(url)
self.assertContains(response, 'Edit folder')
... | -7,015,717,075,723,713,000 | Test folder edition. | modoboa_webmail/tests/test_views.py | test_edit_folder | modoboa/modoboa-webmail | python | def test_edit_folder(self):
url = reverse('modoboa_webmail:folder_change')
response = self.client.get(url)
self.assertContains(response, 'Invalid request')
url = '{}?name=Test'.format(url)
response = self.client.get(url)
self.assertContains(response, 'Edit folder')
session = self.client... |
def test_delete_folder(self):
'Test folder removal.'
url = reverse('modoboa_webmail:folder_delete')
self.ajax_get(url, status=400)
url = '{}?name=Test'.format(url)
session = self.client.session
session['webmail_navparams'] = {'inbox': 'Test'}
session.save()
self.ajax_get(url) | -7,600,897,677,307,676,000 | Test folder removal. | modoboa_webmail/tests/test_views.py | test_delete_folder | modoboa/modoboa-webmail | python | def test_delete_folder(self):
url = reverse('modoboa_webmail:folder_delete')
self.ajax_get(url, status=400)
url = '{}?name=Test'.format(url)
session = self.client.session
session['webmail_navparams'] = {'inbox': 'Test'}
session.save()
self.ajax_get(url) |
def test_reply_to_email(self):
'Test reply form.'
url = '{}?action=reply&mbox=INBOX&mailid=46931'.format(reverse('modoboa_webmail:index'))
session = self.client.session
session['lastaction'] = 'compose'
session.save()
response = self.ajax_get(url)
self.assertIn('id="id_origmsgid"', response[... | 8,669,863,298,764,621,000 | Test reply form. | modoboa_webmail/tests/test_views.py | test_reply_to_email | modoboa/modoboa-webmail | python | def test_reply_to_email(self):
url = '{}?action=reply&mbox=INBOX&mailid=46931'.format(reverse('modoboa_webmail:index'))
session = self.client.session
session['lastaction'] = 'compose'
session.save()
response = self.ajax_get(url)
self.assertIn('id="id_origmsgid"', response['listing'])
re... |
def test_forward_email(self):
'Test forward form.'
url = '{}?action=forward&mbox=INBOX&mailid=46932'.format(reverse('modoboa_webmail:index'))
session = self.client.session
session['lastaction'] = 'compose'
session.save()
with self.settings(MEDIA_ROOT=self.workdir):
response = self.client... | 4,625,502,241,085,917,000 | Test forward form. | modoboa_webmail/tests/test_views.py | test_forward_email | modoboa/modoboa-webmail | python | def test_forward_email(self):
url = '{}?action=forward&mbox=INBOX&mailid=46932'.format(reverse('modoboa_webmail:index'))
session = self.client.session
session['lastaction'] = 'compose'
session.save()
with self.settings(MEDIA_ROOT=self.workdir):
response = self.client.get(url, HTTP_X_REQ... |
def test_getmailcontent_empty_mail(self):
'Try to display an empty email.'
url = '{}?action=reply&mbox=INBOX&mailid=33'.format(reverse('modoboa_webmail:mailcontent_get'))
response = self.client.get(url)
self.assertEqual(response.status_code, 200) | -5,638,293,346,663,087,000 | Try to display an empty email. | modoboa_webmail/tests/test_views.py | test_getmailcontent_empty_mail | modoboa/modoboa-webmail | python | def test_getmailcontent_empty_mail(self):
url = '{}?action=reply&mbox=INBOX&mailid=33'.format(reverse('modoboa_webmail:mailcontent_get'))
response = self.client.get(url)
self.assertEqual(response.status_code, 200) |
def test_getmailsource(self):
"Try to display a message's source."
url = '{}?mbox=INBOX&mailid=133872'.format(reverse('modoboa_webmail:mailsource_get'))
response = self.client.get(url)
self.assertContains(response, 'Message-ID') | 4,267,383,935,041,959,000 | Try to display a message's source. | modoboa_webmail/tests/test_views.py | test_getmailsource | modoboa/modoboa-webmail | python | def test_getmailsource(self):
url = '{}?mbox=INBOX&mailid=133872'.format(reverse('modoboa_webmail:mailsource_get'))
response = self.client.get(url)
self.assertContains(response, 'Message-ID') |
def get_args():
' Get script argument '
parser = argparse.ArgumentParser(description='Show current weather on polybar')
parser.add_argument('log', nargs='?', help='Logging for debugging or not')
parser.add_argument('-u', '--unit', default='metric', nargs='?', help='unit: metric or imperial. Default: met... | 4,760,475,130,287,260,000 | Get script argument | .config/polybar/weather/weather.py | get_args | NearHuscarl/dotfiles | python | def get_args():
' '
parser = argparse.ArgumentParser(description='Show current weather on polybar')
parser.add_argument('log', nargs='?', help='Logging for debugging or not')
parser.add_argument('-u', '--unit', default='metric', nargs='?', help='unit: metric or imperial. Default: metric')
return pa... |
def set_up_logging():
' Set some logging parameter '
if importlib.util.find_spec('requests'):
logging.getLogger('requests').setLevel(logging.WARNING)
logging.getLogger('urllib3').setLevel(logging.WARNING)
logging.basicConfig(format='[%(levelname)s] %(message)s', level=logging.DEBUG) | 7,073,323,484,583,997,000 | Set some logging parameter | .config/polybar/weather/weather.py | set_up_logging | NearHuscarl/dotfiles | python | def set_up_logging():
' '
if importlib.util.find_spec('requests'):
logging.getLogger('requests').setLevel(logging.WARNING)
logging.getLogger('urllib3').setLevel(logging.WARNING)
logging.basicConfig(format='[%(levelname)s] %(message)s', level=logging.DEBUG) |
def get_day_or_night():
" return 'day' or 'night' based on current hour "
hour = int(datetime.datetime.now().strftime('%H'))
if ((hour >= 18) or (hour <= 5)):
return 'night'
return 'day' | 9,053,619,928,646,817,000 | return 'day' or 'night' based on current hour | .config/polybar/weather/weather.py | get_day_or_night | NearHuscarl/dotfiles | python | def get_day_or_night():
" "
hour = int(datetime.datetime.now().strftime('%H'))
if ((hour >= 18) or (hour <= 5)):
return 'night'
return 'day' |
def get_weather_icon(weather_id):
' Get weather icon based on weather condition '
day_night_status = get_day_or_night()
weather = {'thunderstorm': (200 <= weather_id <= 232), 'rain': (300 <= weather_id <= 531), 'snow': (600 <= weather_id <= 622), 'atmosphere': (701 <= weather_id <= 781), 'squall': (weather_... | -2,874,299,759,056,601,600 | Get weather icon based on weather condition | .config/polybar/weather/weather.py | get_weather_icon | NearHuscarl/dotfiles | python | def get_weather_icon(weather_id):
' '
day_night_status = get_day_or_night()
weather = {'thunderstorm': (200 <= weather_id <= 232), 'rain': (300 <= weather_id <= 531), 'snow': (600 <= weather_id <= 622), 'atmosphere': (701 <= weather_id <= 781), 'squall': (weather_id == 771), 'tornado': ((weather_id == 781)... |
def get_thermo_icon(temp_value, temp_unit):
' Get thermometer icon based on temperature '
if (temp_unit == 'F'):
temp_value = convert_temp_unit(temp_unit, 'C')
if (temp_value <= (- 15)):
return '\uf2cb'
elif ((- 15) < temp_value <= 0):
return '\uf2ca'
elif (0 < temp_value <= ... | -6,282,912,500,564,119,000 | Get thermometer icon based on temperature | .config/polybar/weather/weather.py | get_thermo_icon | NearHuscarl/dotfiles | python | def get_thermo_icon(temp_value, temp_unit):
' '
if (temp_unit == 'F'):
temp_value = convert_temp_unit(temp_unit, 'C')
if (temp_value <= (- 15)):
return '\uf2cb'
elif ((- 15) < temp_value <= 0):
return '\uf2ca'
elif (0 < temp_value <= 15):
return '\uf2c9'
elif (15... |
def convert_temp_unit(temp_value, temp_unit):
' Convert current temp_value to temp_unit '
if (temp_unit == 'C'):
return round(((temp_value - 32) / 1.8))
elif (temp_unit == 'F'):
return round(((temp_value * 1.8) + 32)) | -1,498,469,046,806,664,200 | Convert current temp_value to temp_unit | .config/polybar/weather/weather.py | convert_temp_unit | NearHuscarl/dotfiles | python | def convert_temp_unit(temp_value, temp_unit):
' '
if (temp_unit == 'C'):
return round(((temp_value - 32) / 1.8))
elif (temp_unit == 'F'):
return round(((temp_value * 1.8) + 32)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.