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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
20f9af2e5280e3e20296570c | train | class | class LSTMCell(RNNCellBase):
r"""A long short-term memory (LSTM) cell.
.. math::
\begin{array}{ll}
i = \sigma(W_{ii} x + b_{ii} + W_{hi} h + b_{hi}) \\
f = \sigma(W_{if} x + b_{if} + W_{hf} h + b_{hf}) \\
g = \tanh(W_{ig} x + b_{ig} + W_{hg} h + b_{hg}) \\
o = \sigma(W_... | class LSTMCell(RNNCellBase):
| r"""A long short-term memory (LSTM) cell.
.. math::
\begin{array}{ll}
i = \sigma(W_{ii} x + b_{ii} + W_{hi} h + b_{hi}) \\
f = \sigma(W_{if} x + b_{if} + W_{hf} h + b_{hf}) \\
g = \tanh(W_{ig} x + b_{ig} + W_{hg} h + b_{hg}) \\
o = \sigma(W_{io} x + b_{io} + W_{ho} h + ... | = torch.randn(3, 20)
>>> output = []
>>> for i in range(6):
hx = rnn(input[i], hx)
output.append(hx)
"""
def __init__(self, input_size, hidden_size, bias=True, nonlinearity="tanh"):
super(RNNCell, self).__init__(input_size, hidden_size, bias, num_chunks=... | 255 | 256 | 854 | 9 | 246 | YoNyeoSeok/Cityname_Classification-RNN- | rnn.py | Python | LSTMCell | LSTMCell | 662 | 737 | 662 | 662 | cf831e932ead871de0452be5f21626e19e6a0e32 | bigcode/the-stack | train |
25c03b82b10b9b5c2032f629 | train | class | class RNN(RNNBase):
r"""Applies a multi-layer Elman RNN with :math:`tanh` or :math:`ReLU` non-linearity to an
input sequence.
For each element in the input sequence, each layer computes the following
function:
.. math::
h_t = \text{tanh}(w_{ih} x_t + b_{ih} + w_{hh} h_{(t-1)} + b_{hh})
... | class RNN(RNNBase):
| r"""Applies a multi-layer Elman RNN with :math:`tanh` or :math:`ReLU` non-linearity to an
input sequence.
For each element in the input sequence, each layer computes the following
function:
.. math::
h_t = \text{tanh}(w_{ih} x_t + b_{ih} + w_{hh} h_{(t-1)} + b_{hh})
where :math:`h_t`... | ):
super(RNNBase, self).__setstate__(d)
if 'all_weights' in d:
self._all_weights = d['all_weights']
if isinstance(self._all_weights[0][0], str):
return
num_layers = self.num_layers
num_directions = 2 if self.bidirectional else 1
self._all_weights =... | 256 | 256 | 1,223 | 7 | 249 | YoNyeoSeok/Cityname_Classification-RNN- | rnn.py | Python | RNN | RNN | 232 | 330 | 232 | 232 | f8be4ed3c8c182e1e48c040f6c7dec72d0fc0b1f | bigcode/the-stack | train |
76fa99009e16834933094e43 | train | class | class RNNBase(Module):
def __init__(self, mode, input_size, hidden_size,
num_layers=1, bias=True, batch_first=False,
dropout=0, bidirectional=False):
super(RNNBase, self).__init__()
self.mode = mode
self.input_size = input_size
self.hidden_size = hi... | class RNNBase(Module):
| def __init__(self, mode, input_size, hidden_size,
num_layers=1, bias=True, batch_first=False,
dropout=0, bidirectional=False):
super(RNNBase, self).__init__()
self.mode = mode
self.input_size = input_size
self.hidden_size = hidden_size
self.n... | import math
import torch
import warnings
import itertools
import numbers
from torch.nn.modules.module import Module
from torch.nn.parameter import Parameter
from torch.nn.utils.rnn import PackedSequence
from torch.nn import init
_VF = torch._C._VariableFunctions
_rnn_impls = {
'LSTM': _VF.lstm,
'GRU': _VF.gru... | 117 | 256 | 1,956 | 6 | 111 | YoNyeoSeok/Cityname_Classification-RNN- | rnn.py | Python | RNNBase | RNNBase | 21 | 229 | 21 | 22 | d4a2383442799d62412b8efeb3e6d3117242cf69 | bigcode/the-stack | train |
f52b4cd9fa3864b102484e64 | train | function | def rot_puzzle_type(puzzle_type):
return ROT_PUZZLE_TYPE[puzzle_type]
| def rot_puzzle_type(puzzle_type):
| return ROT_PUZZLE_TYPE[puzzle_type]
| _puzzle_type',
]
class PuzzleType(enum.IntEnum):
BR = 0
UL = 1
ROT_PUZZLE_TYPE = {
PuzzleType.BR: PuzzleType.UL,
PuzzleType.UL: PuzzleType.BR,
}
def rot_puzzle_type(puzzle_type):
| 64 | 64 | 21 | 9 | 55 | simone-campagna/fifteen | src/fifteen/puzzle_type.py | Python | rot_puzzle_type | rot_puzzle_type | 20 | 21 | 20 | 20 | 58577e3b937e44042d66aaf09947feab7cdebd6d | bigcode/the-stack | train |
f8217f4ca20716b250b8c8db | train | class | class PuzzleType(enum.IntEnum):
BR = 0
UL = 1
| class PuzzleType(enum.IntEnum):
| BR = 0
UL = 1
| import enum
__all__ = [
'PuzzleType',
'rot_puzzle_type',
]
class PuzzleType(enum.IntEnum):
| 28 | 64 | 19 | 7 | 21 | simone-campagna/fifteen | src/fifteen/puzzle_type.py | Python | PuzzleType | PuzzleType | 9 | 11 | 9 | 9 | a879eedf5a4adb8d9be939a606f26858f5e3a092 | bigcode/the-stack | train |
d9dd4f564987e0229ee73107 | train | class | class AllPages(webapp2.RequestHandler):
def get(self, path):
lang = self.request.get("hl", "en")
text = None
file_path = os.path.join(os.path.dirname(__file__), "build", "_langs", lang, path)
if os.path.isfile(file_path):
text = render("wrapper.tpl", {"content": file_path,... | class AllPages(webapp2.RequestHandler):
| def get(self, path):
lang = self.request.get("hl", "en")
text = None
file_path = os.path.join(os.path.dirname(__file__), "build", "_langs", lang, path)
if os.path.isfile(file_path):
text = render("wrapper.tpl", {"content": file_path, "lang": lang})
file_path = os.... | # Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
im... | 136 | 136 | 454 | 9 | 127 | cwdoh/WebFundamentals | appengine/main.py | Python | AllPages | AllPages | 32 | 69 | 32 | 32 | 33d703957db504894b2f33f617013cd71061d4f4 | bigcode/the-stack | train |
a67c9d4e84d2109004874bb1 | train | class | class HomePage(webapp2.RequestHandler):
def get(self):
self.redirect("/web/", permanent=True)
| class HomePage(webapp2.RequestHandler):
| def get(self):
self.redirect("/web/", permanent=True)
| specific language governing permissions and
# limitations under the License.
#
import webapp2
import json
import logging
from datetime import datetime, timedelta
from urlparse import urljoin
import os
import re
from google.appengine.ext.webapp.template import render
class HomePage(webapp2.RequestHandler):
| 64 | 64 | 23 | 9 | 54 | cwdoh/WebFundamentals | appengine/main.py | Python | HomePage | HomePage | 28 | 30 | 28 | 28 | 78a10b46a844c24dae627c577037577fa33cf257 | bigcode/the-stack | train |
32976b2b961dde4295615dd9 | train | class | class TestSyncExecutor:
def test_sync_is_depcrecated(self):
with pytest.warns(UserWarning) as w:
e = SynchronousExecutor()
assert "deprecated" in str(w[0].message)
assert "LocalDaskExecutor" in str(w[0].message)
assert isinstance(e, LocalDaskExecutor)
assert e.sc... | class TestSyncExecutor:
| def test_sync_is_depcrecated(self):
with pytest.warns(UserWarning) as w:
e = SynchronousExecutor()
assert "deprecated" in str(w[0].message)
assert "LocalDaskExecutor" in str(w[0].message)
assert isinstance(e, LocalDaskExecutor)
assert e.scheduler == "synchronous"... | ()
post = cloudpickle.loads(cloudpickle.dumps(e))
assert isinstance(post, Executor)
def test_is_pickleable_after_start(self):
e = Executor()
with e.start():
post = cloudpickle.loads(cloudpickle.dumps(e))
assert isinstance(post, Executor)
class TestSyncExecuto... | 64 | 64 | 82 | 5 | 59 | mattalhonte/prefect | tests/engine/executors/test_executors.py | Python | TestSyncExecutor | TestSyncExecutor | 53 | 61 | 53 | 53 | e4388d2d18c8ff136f54b4434c3c2d7124e9506d | bigcode/the-stack | train |
4ce9137cdf057865b1166669 | train | class | class TestLocalExecutor:
def test_submit(self):
"""LocalExecutor directly executes the function"""
assert LocalExecutor().submit(lambda: 1) == 1
assert LocalExecutor().submit(lambda x: x, 1) == 1
assert LocalExecutor().submit(lambda x: x, x=1) == 1
assert LocalExecutor().subm... | class TestLocalExecutor:
| def test_submit(self):
"""LocalExecutor directly executes the function"""
assert LocalExecutor().submit(lambda: 1) == 1
assert LocalExecutor().submit(lambda x: x, 1) == 1
assert LocalExecutor().submit(lambda x: x, x=1) == 1
assert LocalExecutor().submit(lambda: prefect) is pr... | , 2], [1, 3]))
assert res == [2, 5]
def test_map_fails_with_processes_executor(self):
def map_fn(x, y):
return x + y
e = LocalDaskExecutor(scheduler="processes")
with pytest.raises(RuntimeError):
with e.start():
res = e.wait(e.map(map_fn, [1,... | 98 | 99 | 331 | 5 | 93 | mattalhonte/prefect | tests/engine/executors/test_executors.py | Python | TestLocalExecutor | TestLocalExecutor | 152 | 192 | 152 | 152 | 5c983131fc894cc869e23d2cb90f845b510f4114 | bigcode/the-stack | train |
04388ac009204f5bc944d328 | train | function | def test_dask_processes_executor_handles_timeouts(mproc):
slow_fn = lambda: time.sleep(2)
with mproc.start():
with pytest.raises(TimeoutError, match="Execution timed out"):
mproc.wait(mproc.submit(mproc.timeout_handler, slow_fn, timeout=1))
| def test_dask_processes_executor_handles_timeouts(mproc):
| slow_fn = lambda: time.sleep(2)
with mproc.start():
with pytest.raises(TimeoutError, match="Execution timed out"):
mproc.wait(mproc.submit(mproc.timeout_handler, slow_fn, timeout=1))
| _executor_has_compatible_timeout_handler(executor):
slow_fn = lambda: time.sleep(3)
with executor.start():
with pytest.raises(TimeoutError):
executor.wait(executor.submit(executor.timeout_handler, slow_fn, timeout=1))
def test_dask_processes_executor_handles_timeouts(mproc):
| 64 | 64 | 63 | 13 | 51 | mattalhonte/prefect | tests/engine/executors/test_executors.py | Python | test_dask_processes_executor_handles_timeouts | test_dask_processes_executor_handles_timeouts | 215 | 219 | 215 | 215 | cef06a7591846da28674bcbe2297ab7fea204f2f | bigcode/the-stack | train |
4c45527d1101173f40b9aa50 | train | class | class TestBaseExecutor:
def test_submit_raises_notimplemented(self):
with pytest.raises(NotImplementedError):
Executor().submit(lambda: 1)
def test_map_raises_notimplemented(self):
with pytest.raises(NotImplementedError):
Executor().map(lambda: 1)
def test_wait_rais... | class TestBaseExecutor:
| def test_submit_raises_notimplemented(self):
with pytest.raises(NotImplementedError):
Executor().submit(lambda: 1)
def test_map_raises_notimplemented(self):
with pytest.raises(NotImplementedError):
Executor().map(lambda: 1)
def test_wait_raises_notimplemented(self):... |
import time
from unittest.mock import MagicMock
import cloudpickle
import dask
import distributed
import pytest
import prefect
from prefect.engine.executors import (
DaskExecutor,
Executor,
LocalDaskExecutor,
LocalExecutor,
SynchronousExecutor,
)
class TestBaseExecutor:
| 64 | 64 | 177 | 5 | 59 | mattalhonte/prefect | tests/engine/executors/test_executors.py | Python | TestBaseExecutor | TestBaseExecutor | 24 | 50 | 24 | 24 | c245eff5ca8d1c97e17548207a79402446634577 | bigcode/the-stack | train |
ce8b347ace745d3d5a1bb2bb | train | class | class TestLocalDaskExecutor:
def test_scheduler_defaults_to_threads(self):
e = LocalDaskExecutor()
assert e.scheduler == "threads"
def test_responds_to_kwargs(self):
e = LocalDaskExecutor(scheduler="threads")
assert e.scheduler == "threads"
def test_start_yields_cfg(self):
... | class TestLocalDaskExecutor:
| def test_scheduler_defaults_to_threads(self):
e = LocalDaskExecutor()
assert e.scheduler == "threads"
def test_responds_to_kwargs(self):
e = LocalDaskExecutor(scheduler="threads")
assert e.scheduler == "threads"
def test_start_yields_cfg(self):
with LocalDaskExecuto... | Executor().map(lambda: 1)
def test_wait_raises_notimplemented(self):
with pytest.raises(NotImplementedError):
Executor().wait([1])
def test_start_doesnt_do_anything(self):
with Executor().start():
assert True
def test_is_pickleable(self):
e = Executor()
... | 215 | 215 | 719 | 7 | 208 | mattalhonte/prefect | tests/engine/executors/test_executors.py | Python | TestLocalDaskExecutor | TestLocalDaskExecutor | 64 | 149 | 64 | 64 | af4eeffd96e680d41fe2cb131ce882c4c0a3a07e | bigcode/the-stack | train |
5b4933c94b9f32428b9465f5 | train | class | class TestDaskExecutor:
@pytest.fixture(scope="class")
def executors(self):
return {
"processes": DaskExecutor(local_processes=True),
"threads": DaskExecutor(local_processes=False),
}
@pytest.mark.parametrize("executor", ["mproc", "mthread"], indirect=True)
def t... | class TestDaskExecutor:
@pytest.fixture(scope="class")
| def executors(self):
return {
"processes": DaskExecutor(local_processes=True),
"threads": DaskExecutor(local_processes=False),
}
@pytest.mark.parametrize("executor", ["mproc", "mthread"], indirect=True)
def test_submit_and_wait(self, executor):
to_compute = {... | was called")
e = LocalExecutor()
with e.start():
res = e.wait(e.map(map_fn))
assert res == []
@pytest.mark.parametrize("executor", ["mproc", "mthread", "sync"], indirect=True)
def test_submit_does_not_assume_pure_functions(executor):
def random_fun():
return random.ra... | 256 | 256 | 1,347 | 14 | 242 | mattalhonte/prefect | tests/engine/executors/test_executors.py | Python | TestDaskExecutor | TestDaskExecutor | 222 | 366 | 222 | 223 | 773419f98c7cc23dfe6d1f5731934780933de6dc | bigcode/the-stack | train |
95787f9b13bc57eb5f57e983 | train | function | @pytest.mark.parametrize("executor", ["mproc", "mthread", "sync"], indirect=True)
def test_submit_does_not_assume_pure_functions(executor):
def random_fun():
return random.random()
with executor.start():
one = executor.wait(executor.submit(random_fun))
two = executor.wait(executor.submi... | @pytest.mark.parametrize("executor", ["mproc", "mthread", "sync"], indirect=True)
def test_submit_does_not_assume_pure_functions(executor):
| def random_fun():
return random.random()
with executor.start():
one = executor.wait(executor.submit(random_fun))
two = executor.wait(executor.submit(random_fun))
assert one != two
| was called")
e = LocalExecutor()
with e.start():
res = e.wait(e.map(map_fn))
assert res == []
@pytest.mark.parametrize("executor", ["mproc", "mthread", "sync"], indirect=True)
def test_submit_does_not_assume_pure_functions(executor):
| 63 | 64 | 77 | 34 | 29 | mattalhonte/prefect | tests/engine/executors/test_executors.py | Python | test_submit_does_not_assume_pure_functions | test_submit_does_not_assume_pure_functions | 195 | 204 | 195 | 196 | 8e2364f1ed7c1e5ab8b1502a70cc072d15a9c233 | bigcode/the-stack | train |
fa2319d1a3429f01b6e14e09 | train | function | @pytest.mark.parametrize("executor", ["local", "mthread", "sync"], indirect=True)
def test_executor_has_compatible_timeout_handler(executor):
slow_fn = lambda: time.sleep(3)
with executor.start():
with pytest.raises(TimeoutError):
executor.wait(executor.submit(executor.timeout_handler, slow_... | @pytest.mark.parametrize("executor", ["local", "mthread", "sync"], indirect=True)
def test_executor_has_compatible_timeout_handler(executor):
| slow_fn = lambda: time.sleep(3)
with executor.start():
with pytest.raises(TimeoutError):
executor.wait(executor.submit(executor.timeout_handler, slow_fn, timeout=1))
| ()
with executor.start():
one = executor.wait(executor.submit(random_fun))
two = executor.wait(executor.submit(random_fun))
assert one != two
@pytest.mark.parametrize("executor", ["local", "mthread", "sync"], indirect=True)
def test_executor_has_compatible_timeout_handler(executor):
| 64 | 64 | 72 | 30 | 33 | mattalhonte/prefect | tests/engine/executors/test_executors.py | Python | test_executor_has_compatible_timeout_handler | test_executor_has_compatible_timeout_handler | 207 | 212 | 207 | 208 | ffc914958d6eaa38a9840b41a61616fd7ca9aea2 | bigcode/the-stack | train |
ae1047e206c937bf1e8757c7 | train | function | def bench_platform_test():
"""
This is textbook premature optimization, but I was curious
Results:
Timed best=477.768 ns, mean=709.491 ± 128.4 ns for == win32
Timed best=585.802 ns, mean=864.347 ± 191.0 ns for startswith(win32)
Timed best=494.998 ns, mean=771.782 ± 135.9 ns for == l... | def bench_platform_test():
| """
This is textbook premature optimization, but I was curious
Results:
Timed best=477.768 ns, mean=709.491 ± 128.4 ns for == win32
Timed best=585.802 ns, mean=864.347 ± 191.0 ns for startswith(win32)
Timed best=494.998 ns, mean=771.782 ± 135.9 ns for == linux
Timed best=592... | def bench_platform_test():
| 5 | 76 | 254 | 5 | 0 | SamuelLabrador/ubelt | dev/bench_misc.py | Python | bench_platform_test | bench_platform_test | 2 | 30 | 2 | 2 | afcba9ae3fc0ffd57a8e56747efef8d34100b7ff | bigcode/the-stack | train |
b781100175bed92b32ccfa86 | train | function | def train_q_learning(mode,
episodes,
max_episode_len,
epsilon,
gamma,
lr):
n_S = 2048
n_A = 3
if mode == 'raw':
n_S = 2
w = np.zeros((n_S, n_A))
b = 0
returns = []... | def train_q_learning(mode,
episodes,
max_episode_len,
epsilon,
gamma,
lr):
| n_S = 2048
n_A = 3
if mode == 'raw':
n_S = 2
w = np.zeros((n_S, n_A))
b = 0
returns = []
car = MountainCar(mode)
for i in range(episodes):
s = get_state(mode, car.reset())
R = 0.
g = 1.
for t in range(max_episode_len):
... | from environment import MountainCar
def get_state(mode, state):
if mode == 'raw':
s = np.zeros((2, 1))
else:
s = np.zeros((2048, 1))
for k in state:
s[k] = state[k]
return s
def get_q(s, w, b):
return w.T @ s + b
def train_q_learning(mode,
... | 105 | 105 | 351 | 23 | 81 | punit-bhatt/cmu-10601-intro-to-ml | assignments/solutions/hw8/handout/python/q_learning.py | Python | train_q_learning | train_q_learning | 23 | 84 | 23 | 29 | 248477efe6342e28f21c74cf39cda7b8222bb46d | bigcode/the-stack | train |
5a2119b8573eaebaec6c9163 | train | function | def moving_average(a, n=3) :
ret = np.cumsum(a, dtype=float)
ret[n:] = ret[n:] - ret[:-n]
return ret[n - 1:] / n
| def moving_average(a, n=3) :
| ret = np.cumsum(a, dtype=float)
ret[n:] = ret[n:] - ret[:-n]
return ret[n - 1:] / n
| len(array.shape) < 2
out_str = '\n'.join(array.astype('U'))
with open(filepath, 'w') as f:
f.write(out_str)
print('Array written to {0} successfully!'.format(filepath))
def moving_average(a, n=3) :
| 64 | 64 | 45 | 10 | 54 | punit-bhatt/cmu-10601-intro-to-ml | assignments/solutions/hw8/handout/python/q_learning.py | Python | moving_average | moving_average | 103 | 106 | 103 | 103 | 51e64f128f917c382bd4efe2500f9a3c5a13dfd1 | bigcode/the-stack | train |
d23c79fb842251fe272167ae | train | function | def write_array_to_file(filepath, array):
"""Write a numpy matrix to a file.
Args:
filepath (str): File path.
array (ndarray): Numpy 1D array.
"""
assert len(array.shape) < 2
out_str = '\n'.join(array.astype('U'))
with open(filepath, 'w') as f:
f.write(ou... | def write_array_to_file(filepath, array):
| """Write a numpy matrix to a file.
Args:
filepath (str): File path.
array (ndarray): Numpy 1D array.
"""
assert len(array.shape) < 2
out_str = '\n'.join(array.astype('U'))
with open(filepath, 'w') as f:
f.write(out_str)
print('Array written to {0} s... | w[:, a] = w[:, a] - lr * td * s.flatten()
b = b - lr * td
s = s_
if done:
break
returns.append(R)
return np.array(returns), w, b
def write_array_to_file(filepath, array):
| 64 | 64 | 102 | 9 | 54 | punit-bhatt/cmu-10601-intro-to-ml | assignments/solutions/hw8/handout/python/q_learning.py | Python | write_array_to_file | write_array_to_file | 86 | 101 | 86 | 86 | fbc4bec7e1f1a361e738ad7dc50d96759c44ae22 | bigcode/the-stack | train |
7ab249df273a26ce24fc7b5d | train | function | def get_state(mode, state):
if mode == 'raw':
s = np.zeros((2, 1))
else:
s = np.zeros((2048, 1))
for k in state:
s[k] = state[k]
return s
| def get_state(mode, state):
| if mode == 'raw':
s = np.zeros((2, 1))
else:
s = np.zeros((2048, 1))
for k in state:
s[k] = state[k]
return s
| import matplotlib.pyplot as plt
import numpy as np
import sys
from environment import MountainCar
def get_state(mode, state):
| 27 | 64 | 58 | 7 | 19 | punit-bhatt/cmu-10601-intro-to-ml | assignments/solutions/hw8/handout/python/q_learning.py | Python | get_state | get_state | 7 | 17 | 7 | 8 | 6696067770def8fd7cce321e393fadc97f2bd7fe | bigcode/the-stack | train |
1370cee80c2198b9f1b75396 | train | function | def get_q(s, w, b):
return w.T @ s + b
| def get_q(s, w, b):
| return w.T @ s + b
| (mode, state):
if mode == 'raw':
s = np.zeros((2, 1))
else:
s = np.zeros((2048, 1))
for k in state:
s[k] = state[k]
return s
def get_q(s, w, b):
| 64 | 64 | 18 | 9 | 54 | punit-bhatt/cmu-10601-intro-to-ml | assignments/solutions/hw8/handout/python/q_learning.py | Python | get_q | get_q | 19 | 21 | 19 | 20 | a53c9f48f5a4fe0763d1e7cf8d80c75e9207faef | bigcode/the-stack | train |
05048f10de6faf9943f9fb41 | train | function | @se
def info_print(
msg, num_of_new_lines=0, num_of_tabs=0,
color=INFO_COLOR, info_label="INFO : ",
timestamp=True, exception=None
):
"""VOID : Print out an info message with a nice format"""
# info print
label_print(msg, num_of_new_lines=num_of_new_lines,
num_of_tabs=num_of_tabs... | @se
def info_print(
msg, num_of_new_lines=0, num_of_tabs=0,
color=INFO_COLOR, info_label="INFO : ",
timestamp=True, exception=None
):
| """VOID : Print out an info message with a nice format"""
# info print
label_print(msg, num_of_new_lines=num_of_new_lines,
num_of_tabs=num_of_tabs, color=color,
label=info_label, timestamp=timestamp,
exception=exception)
| _of_tabs, color=color,
label=warning_label, timestamp=timestamp,
exception=exception)
@se
def info_print(
msg, num_of_new_lines=0, num_of_tabs=0,
color=INFO_COLOR, info_label="INFO : ",
timestamp=True, exception=None
):
| 64 | 64 | 102 | 43 | 21 | lollococce/golog | golog/log.py | Python | info_print | info_print | 184 | 195 | 184 | 189 | c756153c9fbcfea9dfc3d81f03c94ae1666974c8 | bigcode/the-stack | train |
268ac21ac4861e648583f04e | train | function | @nocrash_return
def ask_input_login(
pre_msg="", color=None,
username_label="USERNAME",
password_label="PASSWORD",
pin_label=None,
show_debug=False
):
"""RETURN : dict - ask a user the login and save it"""
print_color("\n" + pre_msg + " LOGIN:\n", color=color, show_debug=show_debug)
user... | @nocrash_return
def ask_input_login(
pre_msg="", color=None,
username_label="USERNAME",
password_label="PASSWORD",
pin_label=None,
show_debug=False
):
| """RETURN : dict - ask a user the login and save it"""
print_color("\n" + pre_msg + " LOGIN:\n", color=color, show_debug=show_debug)
username = input_color("\t{}: ".format(str(username_label)), color=color, show_debug=show_debug)
try:
password = getpass.getpass(col("\t{}: ".format(str(password... | t{}: ".format(str(password)), color))
except Exception:
password = getpass.getpass("\t{}: ".format(str(password_label)))
return password
@nocrash_return
def ask_input_login(
pre_msg="", color=None,
username_label="USERNAME",
password_label="PASSWORD",
pin_label=None,
show_debug=Fal... | 77 | 77 | 258 | 40 | 36 | lollococce/golog | golog/log.py | Python | ask_input_login | ask_input_login | 526 | 551 | 526 | 533 | c69882a353e921e4b4118617ffaac222df3f5639 | bigcode/the-stack | train |
33581fe5b8835a8e537fcec4 | train | function | @se
def print_red(msg, show_debug=True):
"""VOID : print a text with 'print' but colored red"""
try:
print(col(str(msg), color=RED))
except Exception as e:
if show_debug:
warning_print("Probably cannot recognize color", exception=e)
print(str(msg))
| @se
def print_red(msg, show_debug=True):
| """VOID : print a text with 'print' but colored red"""
try:
print(col(str(msg), color=RED))
except Exception as e:
if show_debug:
warning_print("Probably cannot recognize color", exception=e)
print(str(msg))
| print a text with 'print' but colored blue"""
try:
print(col(str(msg), color=BLUE))
except Exception as e:
if show_debug:
warning_print("Probably cannot recognize color", exception=e)
print(str(msg))
@se
def print_red(msg, show_debug=True):
| 64 | 64 | 68 | 12 | 52 | lollococce/golog | golog/log.py | Python | print_red | print_red | 358 | 366 | 358 | 359 | 424a2c6d034f5cf760bb1e5fa4b5bed90af3a0c3 | bigcode/the-stack | train |
9db22a9d1a61e723f7031348 | train | function | @nocrash_return
def ask_input_int(
msg, to_bool=False, color=None,
security_stop=1000, show_debug=True
):
"""
RETURN : Ask an int to the user and return it as int (or bool)
Parameters
----------
msg : string
An info string message for the user before the input
to_bool (optional)... | @nocrash_return
def ask_input_int(
msg, to_bool=False, color=None,
security_stop=1000, show_debug=True
):
| """
RETURN : Ask an int to the user and return it as int (or bool)
Parameters
----------
msg : string
An info string message for the user before the input
to_bool (optional) : bool
Cast the int to bool?
color (optional) : string
The string or const var for termcolor
... | ash_return
def input_color(
msg, color, parse_none=False,
show_debug=True
):
"""RETURN : ask a user input but with colored msg and return it"""
try:
user_input = input(col(msg, color))
except Exception as e:
user_input = input(msg)
if show_debug:
warning_print("Er... | 141 | 141 | 472 | 32 | 108 | lollococce/golog | golog/log.py | Python | ask_input_int | ask_input_int | 450 | 510 | 450 | 454 | 8ba08b8677086452f05653ec7b0bb3b596fec713 | bigcode/the-stack | train |
29f02252cd9e12619a892bf8 | train | function | @se
def print_blue(msg, show_debug=True):
"""VOID : print a text with 'print' but colored blue"""
try:
print(col(str(msg), color=BLUE))
except Exception as e:
if show_debug:
warning_print("Probably cannot recognize color", exception=e)
print(str(msg))
| @se
def print_blue(msg, show_debug=True):
| """VOID : print a text with 'print' but colored blue"""
try:
print(col(str(msg), color=BLUE))
except Exception as e:
if show_debug:
warning_print("Probably cannot recognize color", exception=e)
print(str(msg))
| text with 'print' but colored magenta"""
try:
print(col(str(msg), color=MAGENTA))
except Exception as e:
if show_debug:
warning_print("Probably cannot recognize color", exception=e)
print(str(msg))
@se
def print_blue(msg, show_debug=True):
| 64 | 64 | 68 | 12 | 52 | lollococce/golog | golog/log.py | Python | print_blue | print_blue | 347 | 355 | 347 | 348 | cac78a6f14679253011d244b4206067317eb88f3 | bigcode/the-stack | train |
8a5d227dbfc0aae34ccea06e | train | function | @se
def list_print(
list_to_print, intro_label="Printing the list:",
color=WHITE, show_length=True, show_debug=True
):
"""VOID : Print out a list of values with a nice format"""
# list print
try:
if show_length:
label_print('\n' + intro_label + ' [length : {}]'.format(len(list_to... | @se
def list_print(
list_to_print, intro_label="Printing the list:",
color=WHITE, show_length=True, show_debug=True
):
| """VOID : Print out a list of values with a nice format"""
# list print
try:
if show_length:
label_print('\n' + intro_label + ' [length : {}]'.format(len(list_to_print)) + '\n', label="", color=color)
else:
label_print('\n' + intro_label + '\n', label="", color=color)... | as e:
if show_debug:
warning_print("Cannot get dict in nice format, printing standard", exception=e)
return dict_to_format
@se
def list_print(
list_to_print, intro_label="Printing the list:",
color=WHITE, show_length=True, show_debug=True
):
| 64 | 64 | 169 | 33 | 30 | lollococce/golog | golog/log.py | Python | list_print | list_print | 286 | 304 | 286 | 290 | 125bcb5393590140eeef53afa410d58d0a882de9 | bigcode/the-stack | train |
28ea6c60b7a9f2be1b0685a0 | train | function | @se
def print_green(msg, show_debug=True):
"""VOID : print a text with 'print' but colored green"""
try:
print(col(str(msg), color=GREEN))
except Exception as e:
if show_debug:
warning_print("Probably cannot recognize color", exception=e)
print(str(msg))
| @se
def print_green(msg, show_debug=True):
| """VOID : print a text with 'print' but colored green"""
try:
print(col(str(msg), color=GREEN))
except Exception as e:
if show_debug:
warning_print("Probably cannot recognize color", exception=e)
print(str(msg))
| a text with 'print' but colored yellow"""
try:
print(col(str(msg), color=YELLOW))
except Exception as e:
if show_debug:
warning_print("Probably cannot recognize color", exception=e)
print(str(msg))
@se
def print_green(msg, show_debug=True):
| 64 | 64 | 68 | 12 | 52 | lollococce/golog | golog/log.py | Python | print_green | print_green | 380 | 388 | 380 | 381 | 33d22faf65453ef16cbe92644d93593c1cfcf8a2 | bigcode/the-stack | train |
0a962aefac90be89eef0fd08 | train | function | @nocrash_return
def ask_password(
password_label=None,
color=None
):
"""RETURN : The password string"""
if password_label is None:
password_label = " PASSWORD : "
try:
password = getpass.getpass(col("\t{}: ".format(str(password)), color))
except Exception:
password = get... | @nocrash_return
def ask_password(
password_label=None,
color=None
):
| """RETURN : The password string"""
if password_label is None:
password_label = " PASSWORD : "
try:
password = getpass.getpass(col("\t{}: ".format(str(password)), color))
except Exception:
password = getpass.getpass("\t{}: ".format(str(password_label)))
return password
| again!
if security_stop > 0:
return ask_input_int(msg=msg, to_bool=to_bool,
color=color, security_stop=security_stop - 1)
else:
return None
@nocrash_return
def ask_password(
password_label=None,
color=None
):
| 64 | 64 | 91 | 19 | 44 | lollococce/golog | golog/log.py | Python | ask_password | ask_password | 512 | 524 | 512 | 516 | 494d0ac296494604e31362b8ed0b967cd907b571 | bigcode/the-stack | train |
7e7245e68339c0d6820b14e7 | train | function | @se
def print_color(msg, color, show_debug=True):
"""VOID : print a text with 'print' but colored"""
try:
print(col(str(msg), color))
except Exception as e:
if show_debug:
warning_print("Probably cannot recognize color", exception=e)
print(str(msg))
| @se
def print_color(msg, color, show_debug=True):
| """VOID : print a text with 'print' but colored"""
try:
print(col(str(msg), color))
except Exception as e:
if show_debug:
warning_print("Probably cannot recognize color", exception=e)
print(str(msg))
| - {} : {}".format(str(key), str(value)))
new_line()
except Exception as e:
if show_debug:
warning_print("Cannot print dict in nice format, printing standard", exception=e)
print(dict_to_print)
@se
def print_color(msg, color, show_debug=True):
| 64 | 64 | 67 | 14 | 50 | lollococce/golog | golog/log.py | Python | print_color | print_color | 325 | 333 | 325 | 326 | e3126e1460f3e3bc967249a46cbaa772c5becf04 | bigcode/the-stack | train |
1f3236588207d9c22bcbf29a | train | function | @se
def error_print(
msg, num_of_new_lines=0, num_of_tabs=0,
color=ERROR_COLOR, error_label="* * * ERROR * * * : ",
timestamp=True, exception=None
):
"""VOID : Print out an error message with a nice format"""
# error print
label_print(msg, num_of_new_lines=num_of_new_lines,
num_o... | @se
def error_print(
msg, num_of_new_lines=0, num_of_tabs=0,
color=ERROR_COLOR, error_label="* * * ERROR * * * : ",
timestamp=True, exception=None
):
| """VOID : Print out an error message with a nice format"""
# error print
label_print(msg, num_of_new_lines=num_of_new_lines,
num_of_tabs=num_of_tabs, color=color,
label=error_label, timestamp=timestamp,
exception=exception)
| label=output_label, timestamp=timestamp,
exception=exception)
@se
def error_print(
msg, num_of_new_lines=0, num_of_tabs=0,
color=ERROR_COLOR, error_label="* * * ERROR * * * : ",
timestamp=True, exception=None
):
| 64 | 64 | 108 | 49 | 15 | lollococce/golog | golog/log.py | Python | error_print | error_print | 156 | 167 | 156 | 161 | 481ec8bcbf146e312bb9911895b69c5e9366a15d | bigcode/the-stack | train |
b652a597d50bfa5d2fa52aac | train | function | @se
def print_yellow(msg, show_debug=True):
"""VOID : print a text with 'print' but colored yellow"""
try:
print(col(str(msg), color=YELLOW))
except Exception as e:
if show_debug:
warning_print("Probably cannot recognize color", exception=e)
print(str(msg))
| @se
def print_yellow(msg, show_debug=True):
| """VOID : print a text with 'print' but colored yellow"""
try:
print(col(str(msg), color=YELLOW))
except Exception as e:
if show_debug:
warning_print("Probably cannot recognize color", exception=e)
print(str(msg))
| a text with 'print' but colored red"""
try:
print(col(str(msg), color=RED))
except Exception as e:
if show_debug:
warning_print("Probably cannot recognize color", exception=e)
print(str(msg))
@se
def print_yellow(msg, show_debug=True):
| 64 | 64 | 70 | 13 | 51 | lollococce/golog | golog/log.py | Python | print_yellow | print_yellow | 369 | 377 | 369 | 370 | e795bb348fc5d8bc16b04a639bd2b18f9d8105b6 | bigcode/the-stack | train |
7f10fd46ba917af966bd2f29 | train | function | @se
def print_magenta(msg, show_debug=True):
"""VOID : print a text with 'print' but colored magenta"""
try:
print(col(str(msg), color=MAGENTA))
except Exception as e:
if show_debug:
warning_print("Probably cannot recognize color", exception=e)
print(str(msg))
| @se
def print_magenta(msg, show_debug=True):
| """VOID : print a text with 'print' but colored magenta"""
try:
print(col(str(msg), color=MAGENTA))
except Exception as e:
if show_debug:
warning_print("Probably cannot recognize color", exception=e)
print(str(msg))
| VOID : print a text with 'print' but colored"""
try:
print(col(str(msg), color))
except Exception as e:
if show_debug:
warning_print("Probably cannot recognize color", exception=e)
print(str(msg))
@se
def print_magenta(msg, show_debug=True):
| 64 | 64 | 71 | 13 | 51 | lollococce/golog | golog/log.py | Python | print_magenta | print_magenta | 336 | 344 | 336 | 337 | 89f36d48e83e5dc27bab8665668b3b6b0c1761b1 | bigcode/the-stack | train |
c7693323559e7c60c744606b | train | function | @se
def dict_print(
dict_to_print, intro_label="Printing the dict:",
color=WHITE, show_debug=True
):
"""VOID : Print out a dict of keys and values with a nice format"""
# dict print
try:
label_print('\n' + intro_label + '\n', label="", color=color)
for key, value in dict_to_print.ite... | @se
def dict_print(
dict_to_print, intro_label="Printing the dict:",
color=WHITE, show_debug=True
):
| """VOID : Print out a dict of keys and values with a nice format"""
# dict print
try:
label_print('\n' + intro_label + '\n', label="", color=color)
for key, value in dict_to_print.items():
print(" - {} : {}".format(str(key), str(value)))
new_line()
except Exception a... | ()
except Exception as e:
if show_debug:
warning_print("Cannot print list in nice format, printing standard", exception=e)
print(list_to_print)
@se
def dict_print(
dict_to_print, intro_label="Printing the dict:",
color=WHITE, show_debug=True
):
| 64 | 64 | 136 | 29 | 35 | lollococce/golog | golog/log.py | Python | dict_print | dict_print | 307 | 322 | 307 | 311 | a5f367712ba8b0a5f03c1315b8c323ac728ef1f1 | bigcode/the-stack | train |
9c5a24a354261e5989efe2cd | train | function | @se
def success_print(
msg, num_of_new_lines=0, num_of_tabs=0,
color=SUCCESS_COLOR, success_label="SUCCESS : ",
timestamp=True, exception=None
):
"""VOID : Print out a success message with a nice format"""
# success print
label_print(msg, num_of_new_lines=num_of_new_lines,
num_of... | @se
def success_print(
msg, num_of_new_lines=0, num_of_tabs=0,
color=SUCCESS_COLOR, success_label="SUCCESS : ",
timestamp=True, exception=None
):
| """VOID : Print out a success message with a nice format"""
# success print
label_print(msg, num_of_new_lines=num_of_new_lines,
num_of_tabs=num_of_tabs, color=color,
label=success_label, timestamp=timestamp,
exception=exception)
| _of_tabs, color=color,
label=info_label, timestamp=timestamp,
exception=exception)
@se
def success_print(
msg, num_of_new_lines=0, num_of_tabs=0,
color=SUCCESS_COLOR, success_label="SUCCESS : ",
timestamp=True, exception=None
):
| 64 | 64 | 102 | 43 | 21 | lollococce/golog | golog/log.py | Python | success_print | success_print | 198 | 209 | 198 | 203 | b5004fa77eb4f56e458bc7f7062fa0dba7909635 | bigcode/the-stack | train |
0305c9d07376a7e519a9e339 | train | function | def list_format(
list_to_format,
intro_label="Printing the list:",
color=WHITE, show_debug=True
):
"""RETURN : Format a list with a nice format"""
# dict print
try:
list_str = label_format('\n' + intro_label + ' [length : {}]'.format(len(list_to_format)) + '\n', label="")
for ele... | def list_format(
list_to_format,
intro_label="Printing the list:",
color=WHITE, show_debug=True
):
| """RETURN : Format a list with a nice format"""
# dict print
try:
list_str = label_format('\n' + intro_label + ' [length : {}]'.format(len(list_to_format)) + '\n', label="")
for element in list_to_format:
list_str += " - {}\n".format(element)
return list_str
except E... | """
label_format(msg, num_of_new_lines=num_of_new_lines,
num_of_tabs=num_of_tabs,
label=label, timestamp=timestamp,
exception=exception)
def list_format(
list_to_format,
intro_label="Printing the list:",
color=WHITE, show_debug=True
):
| 64 | 64 | 139 | 27 | 37 | lollococce/golog | golog/log.py | Python | list_format | list_format | 251 | 266 | 251 | 255 | 58a09c41b690dbeaa6a93aa4e3dde457269248d2 | bigcode/the-stack | train |
b9dcb4120f465d958028720d | train | function | @nocrash_return
def error_format(
msg, num_of_new_lines=0, num_of_tabs=0,
label="* * * ERROR * * *: ", timestamp=True,
exception=None
):
"""RETURN : Return a string formatted in a LABEL way"""
label_format(msg, num_of_new_lines=num_of_new_lines,
num_of_tabs=num_of_tabs,
... | @nocrash_return
def error_format(
msg, num_of_new_lines=0, num_of_tabs=0,
label="* * * ERROR * * *: ", timestamp=True,
exception=None
):
| """RETURN : Return a string formatted in a LABEL way"""
label_format(msg, num_of_new_lines=num_of_new_lines,
num_of_tabs=num_of_tabs,
label=label, timestamp=timestamp,
exception=exception)
| , color=color,
label=success_label, timestamp=timestamp,
exception=exception)
@nocrash_return
def error_format(
msg, num_of_new_lines=0, num_of_tabs=0,
label="* * * ERROR * * *: ", timestamp=True,
exception=None
):
| 64 | 64 | 94 | 45 | 19 | lollococce/golog | golog/log.py | Python | error_format | error_format | 212 | 222 | 212 | 217 | 2dec6b96d1b07eb8c6832957c1125fa09f988916 | bigcode/the-stack | train |
649c7abb366cf8592a04dba1 | train | function | @se
def new_line():
"""VOID : Print out new line"""
print('\n')
| @se
def new_line():
| """VOID : Print out new line"""
print('\n')
| :
print("\n\n* * * * * * * * * * * * * * * * * *")
print("* WELCOME *")
print("* * * * * * * * * * * * * * * * * *\n")
@se
def new_line():
| 64 | 64 | 21 | 7 | 57 | lollococce/golog | golog/log.py | Python | new_line | new_line | 417 | 420 | 417 | 418 | c9849bd30c66ab9838aa29800910e6cbe578b268 | bigcode/the-stack | train |
09923082eaae78f95dfcdf34 | train | function | @se
def warning_print(
msg, num_of_new_lines=0, num_of_tabs=0,
color=WARNING_COLOR, warning_label="* WARNING * : ",
timestamp=True, exception=None
):
"""VOID : Print out a warning message with a nice format"""
# warning print
label_print(msg, num_of_new_lines=num_of_new_lines,
nu... | @se
def warning_print(
msg, num_of_new_lines=0, num_of_tabs=0,
color=WARNING_COLOR, warning_label="* WARNING * : ",
timestamp=True, exception=None
):
| """VOID : Print out a warning message with a nice format"""
# warning print
label_print(msg, num_of_new_lines=num_of_new_lines,
num_of_tabs=num_of_tabs, color=color,
label=warning_label, timestamp=timestamp,
exception=exception)
| , color=color,
label=error_label, timestamp=timestamp,
exception=exception)
@se
def warning_print(
msg, num_of_new_lines=0, num_of_tabs=0,
color=WARNING_COLOR, warning_label="* WARNING * : ",
timestamp=True, exception=None
):
| 64 | 64 | 104 | 45 | 19 | lollococce/golog | golog/log.py | Python | warning_print | warning_print | 170 | 181 | 170 | 175 | b970af7f95b63d88c34740006f7b0c43c80a6135 | bigcode/the-stack | train |
cce542da9e9ff74ca1f19a8b | train | function | @nocrash_return
def label_format(
msg, num_of_new_lines=0, num_of_tabs=0,
label="LABEL: ", timestamp=True,
exception=None
):
"""RETURN : Return a string formatted in a LABEL way"""
# number of new lines before text
if timestamp:
label = '[' + str(datetime.now()) + '] ' + label
if nu... | @nocrash_return
def label_format(
msg, num_of_new_lines=0, num_of_tabs=0,
label="LABEL: ", timestamp=True,
exception=None
):
| """RETURN : Return a string formatted in a LABEL way"""
# number of new lines before text
if timestamp:
label = '[' + str(datetime.now()) + '] ' + label
if num_of_new_lines > 0:
for _ in range(num_of_new_lines):
print("\n")
if num_of_tabs > 0:
for _ in range(num_... | # + + + + + Settings + + + + +
# + + + + + Functions + + + + +
@nocrash_return
def label_format(
msg, num_of_new_lines=0, num_of_tabs=0,
label="LABEL: ", timestamp=True,
exception=None
):
| 64 | 64 | 196 | 39 | 25 | lollococce/golog | golog/log.py | Python | label_format | label_format | 73 | 99 | 73 | 78 | 29c563f03470ad6f166ce84fd1e5098268eafdbb | bigcode/the-stack | train |
bcfcb89be44160b0eb5a84d9 | train | function | @se
def welcome(color=WHITE, num_of_new_lines=0, num_of_tabs=0):
"""VOID : Print out a welcome message with a nice format"""
# number of new lines before text
if num_of_new_lines > 0:
for _ in range(num_of_new_lines):
print("\n")
if num_of_tabs > 0:
for _ in range(num_of_tabs... | @se
def welcome(color=WHITE, num_of_new_lines=0, num_of_tabs=0):
| """VOID : Print out a welcome message with a nice format"""
# number of new lines before text
if num_of_new_lines > 0:
for _ in range(num_of_new_lines):
print("\n")
if num_of_tabs > 0:
for _ in range(num_of_tabs):
print("\t")
# print welcome message
if col... | def print_green(msg, show_debug=True):
"""VOID : print a text with 'print' but colored green"""
try:
print(col(str(msg), color=GREEN))
except Exception as e:
if show_debug:
warning_print("Probably cannot recognize color", exception=e)
print(str(msg))
@se
def welcome(color... | 87 | 87 | 292 | 22 | 65 | lollococce/golog | golog/log.py | Python | welcome | welcome | 391 | 414 | 391 | 392 | 71a839e788498025f9bb977d9d81a3bdba7934d4 | bigcode/the-stack | train |
47d49fb3807fe1586896604d | train | function | @nocrash_return
def input_color(
msg, color, parse_none=False,
show_debug=True
):
"""RETURN : ask a user input but with colored msg and return it"""
try:
user_input = input(col(msg, color))
except Exception as e:
user_input = input(msg)
if show_debug:
warning_prin... | @nocrash_return
def input_color(
msg, color, parse_none=False,
show_debug=True
):
| """RETURN : ask a user input but with colored msg and return it"""
try:
user_input = input(col(msg, color))
except Exception as e:
user_input = input(msg)
if show_debug:
warning_print("Error, probably cannot recognize color", exception=e)
if parse_none:
if use... | new lines"""
for _ in range(n):
new_line()
# + + + + + PRINT + + + + +
# + + + + + USER INPUT + + + + +
@nocrash_return
def input_color(
msg, color, parse_none=False,
show_debug=True
):
| 64 | 64 | 111 | 24 | 40 | lollococce/golog | golog/log.py | Python | input_color | input_color | 432 | 447 | 432 | 436 | fd872f8aa5efd1556fa0a05261ee53ed52f73c92 | bigcode/the-stack | train |
8d91839d909c0d2373f6e1a8 | train | function | def dict_format(
dict_to_format, intro_label="Printing the dict:",
color=WHITE, show_debug=True
):
"""RETURN : Format a dict of keys and values with a nice format"""
# dict print
try:
dict_str = label_format('\n' + intro_label + '\n', label="")
for key, value in dict_to_format.items(... | def dict_format(
dict_to_format, intro_label="Printing the dict:",
color=WHITE, show_debug=True
):
| """RETURN : Format a dict of keys and values with a nice format"""
# dict print
try:
dict_str = label_format('\n' + intro_label + '\n', label="")
for key, value in dict_to_format.items():
dict_str += " - {} : {}\n".format(str(key), str(value))
return dict_str
except ... | return list_str
except Exception as e:
if show_debug:
warning_print("Cannot get list in nice format, printing standard", exception=e)
return list_to_format
def dict_format(
dict_to_format, intro_label="Printing the dict:",
color=WHITE, show_debug=True
):
| 64 | 64 | 137 | 26 | 37 | lollococce/golog | golog/log.py | Python | dict_format | dict_format | 269 | 283 | 269 | 272 | d1f71bf0b34c81f364f520b5c71177fa77a53fd9 | bigcode/the-stack | train |
a5c72e3bcbe10e2527c60f54 | train | function | @se
def new_lines(n):
"""VOID : Print out n new lines"""
for _ in range(n):
new_line()
| @se
def new_lines(n):
| """VOID : Print out n new lines"""
for _ in range(n):
new_line()
| * *")
print("* WELCOME *")
print("* * * * * * * * * * * * * * * * * *\n")
@se
def new_line():
"""VOID : Print out new line"""
print('\n')
@se
def new_lines(n):
| 64 | 64 | 29 | 8 | 56 | lollococce/golog | golog/log.py | Python | new_lines | new_lines | 423 | 427 | 423 | 424 | a8058e03bb3c25846394e0699993592d8e2d8e3c | bigcode/the-stack | train |
ac972f97887ed495c3b93b13 | train | function | @nocrash_return
def warning_format(
msg, num_of_new_lines=0, num_of_tabs=0,
label="* WARNING *: ", timestamp=True,
exception=None
):
"""RETURN : Return a string formatted in a LABEL way"""
label_format(msg, num_of_new_lines=num_of_new_lines,
num_of_tabs=num_of_tabs,
... | @nocrash_return
def warning_format(
msg, num_of_new_lines=0, num_of_tabs=0,
label="* WARNING *: ", timestamp=True,
exception=None
):
| """RETURN : Return a string formatted in a LABEL way"""
label_format(msg, num_of_new_lines=num_of_new_lines,
num_of_tabs=num_of_tabs,
label=label, timestamp=timestamp,
exception=exception)
| ,
num_of_tabs=num_of_tabs,
label=label, timestamp=timestamp,
exception=exception)
@nocrash_return
def warning_format(
msg, num_of_new_lines=0, num_of_tabs=0,
label="* WARNING *: ", timestamp=True,
exception=None
):
| 64 | 64 | 90 | 41 | 23 | lollococce/golog | golog/log.py | Python | warning_format | warning_format | 225 | 235 | 225 | 230 | c74b820fad45103f1c0b88e417a0d0142c70e8ee | bigcode/the-stack | train |
cce5bf720c01bf0b350ed05f | train | function | @nocrash_return
def success_format(
msg, num_of_new_lines=0, num_of_tabs=0,
label="SUCCESS: ", timestamp=True,
exception=None
):
"""RETURN : Return a string formatted in a LABEL way"""
label_format(msg, num_of_new_lines=num_of_new_lines,
num_of_tabs=num_of_tabs,
lab... | @nocrash_return
def success_format(
msg, num_of_new_lines=0, num_of_tabs=0,
label="SUCCESS: ", timestamp=True,
exception=None
):
| """RETURN : Return a string formatted in a LABEL way"""
label_format(msg, num_of_new_lines=num_of_new_lines,
num_of_tabs=num_of_tabs,
label=label, timestamp=timestamp,
exception=exception)
| _new_lines,
num_of_tabs=num_of_tabs,
label=label, timestamp=timestamp,
exception=exception)
@nocrash_return
def success_format(
msg, num_of_new_lines=0, num_of_tabs=0,
label="SUCCESS: ", timestamp=True,
exception=None
):
| 64 | 64 | 88 | 39 | 25 | lollococce/golog | golog/log.py | Python | success_format | success_format | 238 | 248 | 238 | 243 | a31fd665bf4afaee71351c8a1db325830db72f1c | bigcode/the-stack | train |
046a43c64a51b749cd3a0462 | train | function | @se
def label_print(
msg, num_of_new_lines=0, num_of_tabs=0,
color=None, label="LABEL: ", timestamp=True,
exception=None
):
"""VOID : Print out a labeled message with a nice format"""
# number of new lines before text
if timestamp:
label = '[' + str(datetime.now()) + '] ' + label
if... | @se
def label_print(
msg, num_of_new_lines=0, num_of_tabs=0,
color=None, label="LABEL: ", timestamp=True,
exception=None
):
| """VOID : Print out a labeled message with a nice format"""
# number of new lines before text
if timestamp:
label = '[' + str(datetime.now()) + '] ' + label
if num_of_new_lines > 0:
for _ in range(num_of_new_lines):
print("\n")
if num_of_tabs > 0:
for _ in range(... | -> {}".format(str(exception), str(traceback.format_exc()))
# return
if msg is None:
return None
else:
return label + msg
@se
def label_print(
msg, num_of_new_lines=0, num_of_tabs=0,
color=None, label="LABEL: ", timestamp=True,
exception=None
):
| 75 | 75 | 253 | 40 | 34 | lollococce/golog | golog/log.py | Python | label_print | label_print | 102 | 139 | 102 | 107 | 2d654433192bbf6439b01cbe41f6ec9ecdb74973 | bigcode/the-stack | train |
b883514f117f553f43ece976 | train | function | @se
def output_print(
msg, num_of_new_lines=0, num_of_tabs=0,
color=INFO_COLOR, output_label=" >> ",
timestamp=True, exception=None
):
"""VOID : Print out an output message with a nice format"""
# output print
label_print(msg, num_of_new_lines=num_of_new_lines,
num_of_tabs=num_of... | @se
def output_print(
msg, num_of_new_lines=0, num_of_tabs=0,
color=INFO_COLOR, output_label=" >> ",
timestamp=True, exception=None
):
| """VOID : Print out an output message with a nice format"""
# output print
label_print(msg, num_of_new_lines=num_of_new_lines,
num_of_tabs=num_of_tabs, color=color,
label=output_label, timestamp=timestamp,
exception=exception)
| as e:
if msg is None:
print(None)
else:
print(label + msg)
@se
def output_print(
msg, num_of_new_lines=0, num_of_tabs=0,
color=INFO_COLOR, output_label=" >> ",
timestamp=True, exception=None
):
| 64 | 64 | 101 | 42 | 22 | lollococce/golog | golog/log.py | Python | output_print | output_print | 142 | 153 | 142 | 147 | 3b076a851657ccd203ddc738247539bcde2bc747 | bigcode/the-stack | train |
6bc975a508a6d33bbcb317c8 | train | class | class Migration(migrations.Migration):
dependencies = [
('front_data', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Configuration',
fields=[
('description', models.TextField(blank=True, null=True)),
('key', models.C... | class Migration(migrations.Migration):
| dependencies = [
('front_data', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Configuration',
fields=[
('description', models.TextField(blank=True, null=True)),
('key', models.CharField(max_length=255, primary_key=Tru... | # Generated by Django 3.2.9 on 2021-11-06 06:08
from django.db import migrations, models
class Migration(migrations.Migration):
| 38 | 64 | 106 | 7 | 30 | mahbd/django-front-data | front_data/migrations/0002_configuration.py | Python | Migration | Migration | 6 | 24 | 6 | 7 | 04da963d08ad0101478a9ea3b255ad123c886870 | bigcode/the-stack | train |
375c1a45e900bf645191ac2f | train | function | def test_homogenous_input(input_gridsize=128, output_gridsize=64):
"""
Tests that passing a homogenous input grid will produce a homogenous
output.
The test will fail if the output grid is not homogenously filled with
values of 1.0.
We also run a suite of unit tests (see `unit_tests` function)... | def test_homogenous_input(input_gridsize=128, output_gridsize=64):
| """
Tests that passing a homogenous input grid will produce a homogenous
output.
The test will fail if the output grid is not homogenously filled with
values of 1.0.
We also run a suite of unit tests (see `unit_tests` function) that will
return a RuntimeError if they're not passed.
Pa... | the expected datatype.
for (i, j, k) in itertools.product(range(expected_gridsize),
range(expected_gridsize),
range(expected_gridsize)):
if not type(grid[i,j,k]) == expected_datatype:
print("The input data format was... | 136 | 136 | 456 | 20 | 115 | qyx268/testing_tutorial | tests/tests.py | Python | test_homogenous_input | test_homogenous_input | 72 | 126 | 72 | 72 | eaa039da5d9cdc3ebe2556161d51fc63a8e676b8 | bigcode/the-stack | train |
9d0bd979a0b81e77cace7309 | train | function | def unit_tests(grid, expected_gridsize, expected_datatype=np.float64):
"""
Tests some fundamental properties of the grids output by `downsample`.
Parameters
----------
grid : `~numpy.ndarray`
The 3D downsampled array created by `downsample`.
expected_gridsize : int, optional
... | def unit_tests(grid, expected_gridsize, expected_datatype=np.float64):
| """
Tests some fundamental properties of the grids output by `downsample`.
Parameters
----------
grid : `~numpy.ndarray`
The 3D downsampled array created by `downsample`.
expected_gridsize : int, optional
The expected 1D size of output grid. Default : 128 and 64.
Re... | itertools
try: # Python2
from urllib import urlretrieve
except ImportError: #Python3
from urllib.request import urlretrieve
import subprocess
# Get the directorys where we launched this script from and where the
# downsample script is located.
test_dir = os.path.dirname(os.path.realpath(__file__))
script_dir... | 110 | 110 | 368 | 17 | 92 | qyx268/testing_tutorial | tests/tests.py | Python | unit_tests | unit_tests | 24 | 69 | 24 | 24 | ee38db53653420854afe67cfe7c625f8ece2d98a | bigcode/the-stack | train |
cfaf0e8e9c735468587608e2 | train | function | def run_tests():
"""
Wrapper to run all the tests.
Parameters
----------
None.
Returns
----------
None.
"""
print("=================================")
print("Running tests")
print("=================================")
print("")
print("Testing a homogenous gri... | def run_tests():
| """
Wrapper to run all the tests.
Parameters
----------
None.
Returns
----------
None.
"""
print("=================================")
print("Running tests")
print("=================================")
print("")
print("Testing a homogenous grid input")
tes... | format(seed,
known_grid_name))
print("These were cells {0} with difference {1}".format(w,
known_grid-output_grid[w]))
raise RuntimeError
# Now run some unit tests that check some properties.
unit_tests(output_grid, output_gridsize)
def run_tests():
| 64 | 64 | 159 | 4 | 60 | qyx268/testing_tutorial | tests/tests.py | Python | run_tests | run_tests | 277 | 312 | 277 | 277 | 4a012cb95c5814e1da3eb8921df1ae3c2fbf3b4f | bigcode/the-stack | train |
4b5fa8ec6c0bd3c4c0d0d353 | train | function | def test_random(input_gridsize=128, output_gridsize=64,
seed=12, save_output=False):
"""
Generates an input grid of random numbers. This is then checked against a
saved output grid generated using the same seed.
Parameters
----------
input_gridsize, output_gridsize : int, opt... | def test_random(input_gridsize=128, output_gridsize=64,
seed=12, save_output=False):
| """
Generates an input grid of random numbers. This is then checked against a
saved output grid generated using the same seed.
Parameters
----------
input_gridsize, output_gridsize : int, optional
1D size of the input/output grids. Default : 128 and 64.
..note::
... | .downsample_grid(input_grid, output_gridsize)
# Find any instances where the output grid is not 1.
w = np.where((output_grid <= 1.0-1e-6) & (output_grid >= 1.0+1e-6))[0]
# Raise errors.
if len(w) > 0:
print("We tested an input grid with every {0} cell containing a value "
"o... | 204 | 204 | 680 | 27 | 177 | qyx268/testing_tutorial | tests/tests.py | Python | test_random | test_random | 195 | 274 | 195 | 196 | a5b7ca796662d5139c8a8dd3ceadf8c3c375d6d9 | bigcode/the-stack | train |
2b43f6a269253c3cc0be30d4 | train | function | def test_multiple_input(input_gridsize=128, output_gridsize=64):
"""
Tests that passing an input grid where every input_gridsize/output_gridsize
cell is filled will a value of (input_gridsize/output_gridsize)^3 produces
a grid that is homogenously filled with values of 1.0.
The test will fail if t... | def test_multiple_input(input_gridsize=128, output_gridsize=64):
| """
Tests that passing an input grid where every input_gridsize/output_gridsize
cell is filled will a value of (input_gridsize/output_gridsize)^3 produces
a grid that is homogenously filled with values of 1.0.
The test will fail if the output grid is not homogenously filled with
values of 1.0.... | # Find any instances where the output grid is not 1.
w = np.where((output_grid <= 1.0-1e-6) & (output_grid >= 1.0+1e-6))[0]
# Raise error.
if len(w) > 0:
print("We tested a homogenous input grid with every cell containing a "
"value of 1.0. We expected the output grid to contain valu... | 172 | 172 | 576 | 18 | 154 | qyx268/testing_tutorial | tests/tests.py | Python | test_multiple_input | test_multiple_input | 129 | 192 | 129 | 129 | 46a14be8a560f975faf994d3df19476e8581fa0c | bigcode/the-stack | train |
59ed2484b3d4b434e7cc1ca5 | train | class | class Particle2DipoleSGD(Optimizer):
"""
Stochastic gradient descent optimization for Particle2 Dipole layers
"""
def __init__(self, alpha=0.01, beta=0.0, n_epochs=1, mini_batch_size=1, verbosity=2, weight_update="sd",
cost_freq=2, gamma=0.9, alpha_decay=1.0, n_threads=1, chunk_size=1)... | class Particle2DipoleSGD(Optimizer):
| """
Stochastic gradient descent optimization for Particle2 Dipole layers
"""
def __init__(self, alpha=0.01, beta=0.0, n_epochs=1, mini_batch_size=1, verbosity=2, weight_update="sd",
cost_freq=2, gamma=0.9, alpha_decay=1.0, n_threads=1, chunk_size=1):
"""
:param alpha: l... | from .optimizer import Optimizer
import numpy as np
import time
from multiprocessing import Pool
class Particle2DipoleSGD(Optimizer):
| 30 | 256 | 6,027 | 10 | 19 | awlange/brainsparks | src/calrissian/optimizers/particle2_dipole_sgd.py | Python | Particle2DipoleSGD | Particle2DipoleSGD | 9 | 445 | 9 | 9 | 887501070cb578d55ee5529a3f6d505d9d6a1ebd | bigcode/the-stack | train |
456666535c2330a9cd6fddc8 | train | class | class V1alpha1Info(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
... | class V1alpha1Info(object):
| """NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The... | # coding: utf-8
"""
Consolidate Services
Description of all APIs # noqa: E501
The version of the OpenAPI document: version not set
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from argocd_client.configuration import Configuration
class V1alpha... | 82 | 243 | 811 | 8 | 73 | thepabloaguilar/argocd-client | argocd_client/models/v1alpha1_info.py | Python | V1alpha1Info | V1alpha1Info | 21 | 146 | 21 | 21 | 6f6f9b22c6c373e5e8d28a911f2f1660157f2c97 | bigcode/the-stack | train |
05986c9c67b0255b5f279b37 | train | class | class TestDeque(RaleighTestCase):
def test_simple(self):
oid = self.createObject(RaleighDeque.TYPE)
deque = RaleighDeque(self.client, oid)
deque.push_front('A')
deque.push_front('B')
deque.push_back('C')
deque.push_back('D')
deque.push_front('E')
deque.push_back('F')
# E B A C D F... | class TestDeque(RaleighTestCase):
| def test_simple(self):
oid = self.createObject(RaleighDeque.TYPE)
deque = RaleighDeque(self.client, oid)
deque.push_front('A')
deque.push_front('B')
deque.push_back('C')
deque.push_back('D')
deque.push_front('E')
deque.push_back('F')
# E B A C D F
data = deque.pop_front()
... | 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 writing, software
# distributed under the License is distributed on an "AS IS" BASIS,... | 152 | 152 | 509 | 8 | 143 | matteobertozzi/RaleighSL | src/raleigh-client/pyraleigh/tests/test_deque.py | Python | TestDeque | TestDeque | 20 | 77 | 20 | 20 | 94f55ce39e89ccbc2afcbf329383c84618236c57 | bigcode/the-stack | train |
4eaeae2f837a391da5add6eb | train | function | def delete_about_page(event, context):
about_page_id = int(event['about_page_id'])
id_param = {'name' : 'about_page_id', 'value' : {'longValue' : about_page_id}}
delete_sql = "DELETE FROM about_page WHERE about_page_id = :about_page_id"
params = [id_param]
try:
query(delete_sql, params)
... | def delete_about_page(event, context):
| about_page_id = int(event['about_page_id'])
id_param = {'name' : 'about_page_id', 'value' : {'longValue' : about_page_id}}
delete_sql = "DELETE FROM about_page WHERE about_page_id = :about_page_id"
params = [id_param]
try:
query(delete_sql, params)
except Exception as e:
raise La... | from package.query_db import query
from package.lambda_exception import LambdaException
def delete_about_page(event, context):
| 23 | 64 | 122 | 8 | 14 | charvi-a/320-S20-Track1 | lambdas/delete_about_page.py | Python | delete_about_page | delete_about_page | 4 | 15 | 4 | 4 | c1dbdab64690801fa7f22535d78adfaf3f325564 | bigcode/the-stack | train |
278acac818f2724d54f1e6ac | train | function | def conv(x):
return x.replace(',', '.').encode()
| def conv(x):
| return x.replace(',', '.').encode()
| go
import pandas as pd
import numpy as np
from Exp_Main.models import OCA
from Exp_Sub.models import LSP
from plotly.subplots import make_subplots
from Analysis.Osz_Drop import *
from Lab_Misc import Load_Data
from Lab_Misc import General
def conv(x):
| 64 | 64 | 13 | 4 | 59 | SimonSchubotz/Electronic-Laboratory-Notebook | Lab_Dash/dash_plot.py | Python | conv | conv | 21 | 22 | 21 | 21 | 4511dacc672f84d9fe8d433d100b985be1aa6a87 | bigcode/the-stack | train |
4b8fb5c91b8224de88cd274f | train | function | @app.expanded_callback(
Output(component_id='example-graph', component_property='figure'),
[Input(component_id='target_id', component_property='value'),
Input('my-dropdown1', 'value')]
)
def update_figure(target_id, Graph_select, *args,**kwargs):
GenFig = Gen_fig(target_id)
if Graph_select ==... | @app.expanded_callback(
Output(component_id='example-graph', component_property='figure'),
[Input(component_id='target_id', component_property='value'),
Input('my-dropdown1', 'value')]
)
def update_figure(target_id, Graph_select, *args,**kwargs):
| GenFig = Gen_fig(target_id)
if Graph_select == 'CA/Time':
fig = GenFig.CA_Time()
elif Graph_select == 'CA/BD':
fig = GenFig.CA_BD()
elif Graph_select == 'CA/Run_no':
fig = GenFig.CA_RunNo()
elif Graph_select == 'CA/CL_Pos':
fig = GenFig.CA_CLPos()
elif Graph_sele... | )
])
@app.expanded_callback(
Output(component_id='example-graph', component_property='figure'),
[Input(component_id='target_id', component_property='value'),
Input('my-dropdown1', 'value')]
)
def update_figure(target_id, Graph_select, *args,**kwargs):
| 64 | 64 | 192 | 62 | 2 | SimonSchubotz/Electronic-Laboratory-Notebook | Lab_Dash/dash_plot.py | Python | update_figure | update_figure | 484 | 506 | 484 | 490 | cd7d3766900b977d4eff2b65b764d6246894f4fe | bigcode/the-stack | train |
b660fc20b9ab2f79a26f7257 | train | class | class Gen_fig():
drop_name = ['Drop 1', 'Drop 2', 'Drop 3', 'Drop 4', 'Drop 5', 'Drop 6', 'Drop 7', 'Drop 8', 'Drop 9', 'Drop 10', 'Drop 11', 'Drop 12', 'Drop 13', 'Drop 14', 'Drop 15',]
colours = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf', '#1f... | class Gen_fig():
| drop_name = ['Drop 1', 'Drop 2', 'Drop 3', 'Drop 4', 'Drop 5', 'Drop 6', 'Drop 7', 'Drop 8', 'Drop 9', 'Drop 10', 'Drop 11', 'Drop 12', 'Drop 13', 'Drop 14', 'Drop 15',]
colours = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf', '#1f77b4', '#ff7f0e',... | import json
import glob, os
import dash
import datetime
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.express as px
from django_plotly_dash import DjangoDash
import plotly.graph_objects as go
import pandas as pd
import numpy as np
from E... | 137 | 256 | 4,835 | 4 | 133 | SimonSchubotz/Electronic-Laboratory-Notebook | Lab_Dash/dash_plot.py | Python | Gen_fig | Gen_fig | 24 | 444 | 24 | 24 | cf459e7313b01bced0eea7ebc5a3bfc6ac71d79b | bigcode/the-stack | train |
e1b3e0c72786bd270c17be4d | train | function | def get():
"""Locate the ca_certs.txt file.
The httplib2 library will look for local ca_certs_locater module to override
the default location for the ca_certs.txt file. We override it here to first
try loading via resources, falling back to the traditional method if
that fails.
Returns:
The file locat... | def get():
| """Locate the ca_certs.txt file.
The httplib2 library will look for local ca_certs_locater module to override
the default location for the ca_certs.txt file. We override it here to first
try loading via resources, falling back to the traditional method if
that fails.
Returns:
The file location returne... | """Custom locater for CA_CERTS files."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
def get():
| 39 | 64 | 153 | 3 | 35 | bopopescu/Social-Lite | google-cloud-sdk/platform/bq/third_party/httplib2/python2/ca_certs_locater.py | Python | get | get | 11 | 28 | 11 | 11 | 4958d9ebe7fba19cb9fd7dc90e9a938aed3b2183 | bigcode/the-stack | train |
0897d79e6eec91ca0f0e8db8 | train | function | def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'woodash.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on you... | def main():
| os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'woodash.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH... | #!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
| 26 | 64 | 93 | 3 | 22 | tiagocordeiro/woodash | manage.py | Python | main | main | 7 | 17 | 7 | 7 | 72abefef72e0a7ccd52a887be168a280ae949dac | bigcode/the-stack | train |
60bc1019273bdf4526be127a | train | function | def Corner2Center(boxes):
return np.concatenate([
(boxes[..., :2] + boxes[..., 2:]) / 2,
boxes[..., 2:] - boxes[..., :2]
], len(boxes.shape) - 1)
| def Corner2Center(boxes):
| return np.concatenate([
(boxes[..., :2] + boxes[..., 2:]) / 2,
boxes[..., 2:] - boxes[..., :2]
], len(boxes.shape) - 1)
| ) - 1)
def Center2Corner(locations):
return np.concatenate([locations[..., :2] - locations[..., 2:] / 2,
locations[..., :2] + locations[..., 2:] / 2], len(locations.shape) - 1)
def Corner2Center(boxes):
| 64 | 64 | 53 | 7 | 57 | explain116/labelImg | libs/detector/ssd/postprocess/utils/box.py | Python | Corner2Center | Corner2Center | 41 | 45 | 41 | 41 | 3eebcb02a342d2f97cd411441198676bb8deff80 | bigcode/the-stack | train |
97b15a893ff13da6a0be607c | train | function | def Center2Corner(locations):
return np.concatenate([locations[..., :2] - locations[..., 2:] / 2,
locations[..., :2] + locations[..., 2:] / 2], len(locations.shape) - 1)
| def Center2Corner(locations):
| return np.concatenate([locations[..., :2] - locations[..., 2:] / 2,
locations[..., :2] + locations[..., 2:] / 2], len(locations.shape) - 1)
| locations[..., :2] * center_variance * priors[..., 2:] + priors[..., :2],
np.exp(locations[..., 2:] * size_variance) * priors[..., 2:]
], axis=len(locations.shape) - 1)
def Center2Corner(locations):
| 64 | 64 | 52 | 7 | 57 | explain116/labelImg | libs/detector/ssd/postprocess/utils/box.py | Python | Center2Corner | Center2Corner | 36 | 38 | 36 | 36 | 323345c19597d4e0bae317f8986d874dcfd1e215 | bigcode/the-stack | train |
5318aae7d86089f52084d64a | train | function | def Locations2Boxes(locations, priors, center_variance, size_variance):
"""Convert regressional location results of SSD into boxes in the form of (center_x, center_y, h, w).
The conversion:
$$predicted\_center * center_variance = \frac {real\_center - prior\_center} {prior\_hw}$$
$$exp(predicte... | def Locations2Boxes(locations, priors, center_variance, size_variance):
| """Convert regressional location results of SSD into boxes in the form of (center_x, center_y, h, w).
The conversion:
$$predicted\_center * center_variance = \frac {real\_center - prior\_center} {prior\_hw}$$
$$exp(predicted\_hw * size_variance) = \frac {real\_hw} {prior\_hw}$$
We do it in ... | #!/usr/bin/python3 python
# encoding: utf-8
'''
@author: 孙昊
@contact: smartadpole@163.com
@file: box.py
@time: 2021/2/23 上午10:26
@desc:
'''
import numpy as np
def Locations2Boxes(locations, priors, center_variance, size_variance):
| 81 | 103 | 344 | 18 | 62 | explain116/labelImg | libs/detector/ssd/postprocess/utils/box.py | Python | Locations2Boxes | Locations2Boxes | 12 | 34 | 12 | 12 | bef46d0956aacd3eda3611c8752f1689a7e75538 | bigcode/the-stack | train |
62a395637aab19feab0c0606 | train | class | class ObjectNameParser:
@staticmethod
def teradata_parse_object_name(statement, start_key, end_key):
object_name = None
if statement.find(start_key) != -1:
object_name = statement[statement.find(start_key) + len(start_key):statement.find(end_key)].strip()
return object_... | class ObjectNameParser:
@staticmethod
| def teradata_parse_object_name(statement, start_key, end_key):
object_name = None
if statement.find(start_key) != -1:
object_name = statement[statement.find(start_key) + len(start_key):statement.find(end_key)].strip()
return object_name
return object_name
@stat... | class ObjectNameParser:
@staticmethod
| 9 | 64 | 146 | 9 | 0 | patrickdehoon/dataspot-docker | dataspot-bokeh/dataspot/parsers/object_name_parser.py | Python | ObjectNameParser | ObjectNameParser | 3 | 24 | 3 | 5 | 58f7577b83977d4c9c0108c483c64b524790f7c9 | bigcode/the-stack | train |
c0c26f002ad9f9291c2e298c | train | function | def test_vanilla():
for task in [252, 9971]:
X_train, y_train, X_test, y_test, cat = load_task(task)
autoML = AutoML(time_budget=60,
time_limit_for_evaluation=30,
memory_limit=3024,
seed=1,
scoring_func=... | def test_vanilla():
| for task in [252, 9971]:
X_train, y_train, X_test, y_test, cat = load_task(task)
autoML = AutoML(time_budget=60,
time_limit_for_evaluation=30,
memory_limit=3024,
seed=1,
scoring_func="balanced_accuracy",... | from examples.update_metadata_util import load_task, classification_tasks
from mosaic_ml.automl import AutoML
def test_vanilla():
| 28 | 64 | 131 | 6 | 21 | herilalaina/mosaic_ml | tests/test_vanilla.py | Python | test_vanilla | test_vanilla | 5 | 20 | 5 | 5 | c20cc2257fd6a5cb45dbc0787fe2781a847d7693 | bigcode/the-stack | train |
df6e4a63abb469ccf6a42070 | train | class | class SkewedChi2Sampler(BaseEstimator, TransformerMixin):
"""Approximates feature map of the "skewed chi-squared" kernel by Monte
Carlo approximation of its Fourier transform.
Read more in the :ref:`User Guide <skewed_chi_kernel_approx>`.
Parameters
----------
skewedness : float
"skewe... | class SkewedChi2Sampler(BaseEstimator, TransformerMixin):
| """Approximates feature map of the "skewed chi-squared" kernel by Monte
Carlo approximation of its Fourier transform.
Read more in the :ref:`User Guide <skewed_chi_kernel_approx>`.
Parameters
----------
skewedness : float
"skewedness" parameter of the kernel. Needs to be cross-validate... | .normal(
size=(n_features, self.n_components)))
self.random_offset_ = random_state.uniform(0, 2 * np.pi,
size=self.n_components)
return self
def transform(self, X, y=None):
"""Apply the approximate feature map to X.
Pa... | 211 | 211 | 705 | 13 | 197 | Con-Mi/lambda-packs | Sklearn_scipy_numpy/source/sklearn/kernel_approximation.py | Python | SkewedChi2Sampler | SkewedChi2Sampler | 112 | 203 | 112 | 112 | a019ec479c41028905df37a91b7fb96490395538 | bigcode/the-stack | train |
ca9656020a99555194f260d1 | train | class | class Nystroem(BaseEstimator, TransformerMixin):
"""Approximate a kernel map using a subset of the training data.
Constructs an approximate feature map for an arbitrary kernel
using a subset of the data as basis.
Read more in the :ref:`User Guide <nystroem_kernel_approx>`.
Parameters
--------... | class Nystroem(BaseEstimator, TransformerMixin):
| """Approximate a kernel map using a subset of the training data.
Constructs an approximate feature map for an arbitrary kernel
using a subset of the data as basis.
Read more in the :ref:`User Guide <nystroem_kernel_approx>`.
Parameters
----------
kernel : string or callable, default="rbf"... | X.indices.copy()
indptr = X.indptr.copy()
data_step = np.sqrt(X.data * self.sample_interval_)
X_step = sp.csr_matrix((data_step, indices, indptr),
shape=X.shape, dtype=X.dtype, copy=False)
X_new = [X_step]
log_step_nz = self.sample_interval_ * np... | 256 | 256 | 1,186 | 11 | 245 | Con-Mi/lambda-packs | Sklearn_scipy_numpy/source/sklearn/kernel_approximation.py | Python | Nystroem | Nystroem | 361 | 521 | 361 | 361 | 0c75dc5e9b289841264c712385c08237f44c6118 | bigcode/the-stack | train |
a80b6dd2318278eb4687f18e | train | class | class RBFSampler(BaseEstimator, TransformerMixin):
"""Approximates feature map of an RBF kernel by Monte Carlo approximation
of its Fourier transform.
It implements a variant of Random Kitchen Sinks.[1]
Read more in the :ref:`User Guide <rbf_kernel_approx>`.
Parameters
----------
gamma : ... | class RBFSampler(BaseEstimator, TransformerMixin):
| """Approximates feature map of an RBF kernel by Monte Carlo approximation
of its Fourier transform.
It implements a variant of Random Kitchen Sinks.[1]
Read more in the :ref:`User Guide <rbf_kernel_approx>`.
Parameters
----------
gamma : float
Parameter of RBF kernel: exp(-gamma *... | """
The :mod:`sklearn.kernel_approximation` module implements several
approximate kernel feature maps base on Fourier transforms.
"""
# Author: Andreas Mueller <amueller@ais.uni-bonn.de>
#
# License: BSD 3 clause
import warnings
import numpy as np
import scipy.sparse as sp
from scipy.linalg import svd
from .base im... | 144 | 188 | 629 | 10 | 133 | Con-Mi/lambda-packs | Sklearn_scipy_numpy/source/sklearn/kernel_approximation.py | Python | RBFSampler | RBFSampler | 24 | 109 | 24 | 24 | 899dd1dbbe78900da889fb0e80be9bceb8fdcfd3 | bigcode/the-stack | train |
2feb010a38a6f1b58ed811ec | train | class | class AdditiveChi2Sampler(BaseEstimator, TransformerMixin):
"""Approximate feature map for additive chi2 kernel.
Uses sampling the fourier transform of the kernel characteristic
at regular intervals.
Since the kernel that is to be approximated is additive, the components of
the input vectors can b... | class AdditiveChi2Sampler(BaseEstimator, TransformerMixin):
| """Approximate feature map for additive chi2 kernel.
Uses sampling the fourier transform of the kernel characteristic
at regular intervals.
Since the kernel that is to be approximated is additive, the components of
the input vectors can be treated separately. Each entry in the original
space ... | .log(np.tan(np.pi / 2. * uniform)))
self.random_offset_ = random_state.uniform(0, 2 * np.pi,
size=self.n_components)
return self
def transform(self, X, y=None):
"""Apply the approximate feature map to X.
Parameters
--------... | 256 | 256 | 1,309 | 12 | 243 | Con-Mi/lambda-packs | Sklearn_scipy_numpy/source/sklearn/kernel_approximation.py | Python | AdditiveChi2Sampler | AdditiveChi2Sampler | 206 | 358 | 206 | 206 | 9dd9d89ea55b2f4bb47fae2dcd7ab9750eb7daf6 | bigcode/the-stack | train |
36c64995421c80e2bee9b083 | train | function | def jun_dataframe_plot(df, fn, save='None', keywords=[]):
if ( isinstance(df, pd.core.frame.DataFrame) ):
# clean before any plot
mpl.pyplot.figure()
# make dict from keywords even if empty!
kwargs = dict(keywords)
# get the fun from seaborn directly since we want a dynamic c... | def jun_dataframe_plot(df, fn, save='None', keywords=[]):
| if ( isinstance(df, pd.core.frame.DataFrame) ):
# clean before any plot
mpl.pyplot.figure()
# make dict from keywords even if empty!
kwargs = dict(keywords)
# get the fun from seaborn directly since we want a dynamic call
fun = getattr(sns, fn)
plot = fun(**kw... | import scipy as sp
import numpy as np
import matplotlib as mpl
import pandas as pd
import sklearn as skl
mpl.use('Agg')
import seaborn as sns
# common helper for dataframe plot using seaborn,
# trying to return a file instead a raw opaque item
def jun_dataframe_plot(df, fn, save='None', keywords=[]):
| 73 | 73 | 244 | 15 | 57 | prateek-rtk/jun | priv/jun_seaborn.py | Python | jun_dataframe_plot | jun_dataframe_plot | 15 | 39 | 15 | 15 | 2c728acafd67fc86f5d3e39dea81c6714aff2c13 | bigcode/the-stack | train |
7fcb7bead1852f3235d8e1e7 | train | function | @coroutine
def printer():
while True:
line = yield
print(line)
| @coroutine
def printer():
| while True:
line = yield
print(line)
| )
# A filter
@coroutine
def grep(pattern, target):
while True:
line = yield # Receive a line
if pattern in line:
target.send(line) # Send to next stage
# A sink. A coroutine that receives data
@coroutine
def printer():
| 64 | 64 | 20 | 7 | 56 | vyahello/python-generators-cheetsheet | materials/broadcast.py | Python | printer | printer | 30 | 34 | 30 | 31 | 9d3f01b370497d5cda28d1b9c465c3e6ab7b2131 | bigcode/the-stack | train |
f56ca89e4020d23509a53bf6 | train | function | def follow(thefile, target):
thefile.seek(0, 2) # Go to end of a file
while True:
line = thefile.readline()
if not line:
time.sleep(0.1)
continue
target.send(line)
| def follow(thefile, target):
| thefile.seek(0, 2) # Go to end of a file
while True:
line = thefile.readline()
if not line:
time.sleep(0.1)
continue
target.send(line)
| """
An example of broadcasting a data stream onto multiple coroutine targets.
"""
import time
from materials.decorator import coroutine
# A data source. This is not a coroutine, but it sends data into one target
def follow(thefile, target):
| 50 | 64 | 58 | 7 | 42 | vyahello/python-generators-cheetsheet | materials/broadcast.py | Python | follow | follow | 10 | 17 | 10 | 10 | 66de4dcca38e350ee507a50b8ca1f5606039ad01 | bigcode/the-stack | train |
71696cf4219f6d8d65edca65 | train | function | @coroutine
def broadcast(targets):
while True:
item = yield
for target in targets:
target.send(item)
| @coroutine
def broadcast(targets):
| while True:
item = yield
for target in targets:
target.send(item)
| if pattern in line:
target.send(line) # Send to next stage
# A sink. A coroutine that receives data
@coroutine
def printer():
while True:
line = yield
print(line)
# Broadcast a stream onto multiple targets
@coroutine
def broadcast(targets):
| 64 | 64 | 29 | 9 | 54 | vyahello/python-generators-cheetsheet | materials/broadcast.py | Python | broadcast | broadcast | 38 | 43 | 38 | 39 | c4c2d0c2eef4b95b830a9f9738686e547feffa83 | bigcode/the-stack | train |
4e36835ac47892646c81454f | train | function | @coroutine
def grep(pattern, target):
while True:
line = yield # Receive a line
if pattern in line:
target.send(line) # Send to next stage
| @coroutine
def grep(pattern, target):
| while True:
line = yield # Receive a line
if pattern in line:
target.send(line) # Send to next stage
| thefile.seek(0, 2) # Go to end of a file
while True:
line = thefile.readline()
if not line:
time.sleep(0.1)
continue
target.send(line)
# A filter
@coroutine
def grep(pattern, target):
| 64 | 64 | 42 | 10 | 53 | vyahello/python-generators-cheetsheet | materials/broadcast.py | Python | grep | grep | 21 | 26 | 21 | 22 | da4f6b3281ffaf625d5cbac972890ddb4c6b08d2 | bigcode/the-stack | train |
aa94eb237b61a7368fc769e9 | train | class | class SubscriptionClientConfiguration(Configuration):
"""Configuration for SubscriptionClient.
Note that all parameters used to create this instance are saved as instance
attributes.
:param credential: Credential needed for the client to connect to Azure.
:type credential: ~azure.core.credentials_... | class SubscriptionClientConfiguration(Configuration):
| """Configuration for SubscriptionClient.
Note that all parameters used to create this instance are saved as instance
attributes.
:param credential: Credential needed for the client to connect to Azure.
:type credential: ~azure.core.credentials_async.AsyncTokenCredential
"""
def __init__(
... | root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import Any, TYPE_CHECKING
from azure.core.configuration... | 123 | 123 | 413 | 6 | 116 | xolve/azure-sdk-for-python | sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/v2018_06_01/aio/_configuration.py | Python | SubscriptionClientConfiguration | SubscriptionClientConfiguration | 22 | 61 | 22 | 22 | 6197371cfad223f3216afa2cfd3d1297fbb43caa | bigcode/the-stack | train |
715b483a96148cd370f60c33 | train | function | def index(request):
return render(request,'blog/base.html')
| def index(request):
| return render(request,'blog/base.html')
| from django.shortcuts import render
from .models import BlogPost
def index(request):
| 17 | 64 | 13 | 4 | 12 | Ellena45/template-python-django | blog/views.py | Python | index | index | 5 | 6 | 5 | 5 | 3ef32ae990b9113feb927aa736be2e775e36620c | bigcode/the-stack | train |
3976585a7cb5def693a321fb | train | function | def timeline_view(request):
posts = BlogPost.objects.filter(user=request.user)
return render(request,'blog/timeline.html', {'posts':posts}) | def timeline_view(request):
| posts = BlogPost.objects.filter(user=request.user)
return render(request,'blog/timeline.html', {'posts':posts}) | from django.shortcuts import render
from .models import BlogPost
def index(request):
return render(request,'blog/base.html')
def timeline_view(request):
| 31 | 64 | 31 | 5 | 26 | Ellena45/template-python-django | blog/views.py | Python | timeline_view | timeline_view | 8 | 10 | 8 | 8 | e24bbaba2495c9ad2beeb248864a1ca1263074d6 | bigcode/the-stack | train |
7d72de59322e8b02628be5c8 | train | function | def export(result, name, reporting_start_datetime_local, reporting_end_datetime_local, period_type):
####################################################################################################################
# Step 1: Validate the report data
#######################################################... | def export(result, name, reporting_start_datetime_local, reporting_end_datetime_local, period_type):
####################################################################################################################
# Step 1: Validate the report data
#######################################################... | if result is None:
return None
####################################################################################################################
# Step 2: Generate excel file from the report data
################################################################################################... | # Step 2: Generate excelexporters file
# Step 3: Encode the excelexporters file to Base64
####################################################################################################################
def export(result, name, reporting_start_datetime_local, reporting_end_datetime_local, period_type):
########... | 69 | 70 | 235 | 38 | 31 | 823914102/myems-api | excelexporters/metersubmetersbalance.py | Python | export | export | 21 | 54 | 21 | 24 | a0b329d5a031dfc66bd01e092ab55982f1c89e3f | bigcode/the-stack | train |
a57a95b472f775d0fbf1c6d4 | train | function | def generate_excel(report, name, reporting_start_datetime_local, reporting_end_datetime_local, period_type):
wb = Workbook()
ws = wb.active
# Row height
ws.row_dimensions[1].height = 118
for i in range(2, 2000 + 1):
ws.row_dimensions[i].height = 30
# Col width
ws.column_dimensions[... | def generate_excel(report, name, reporting_start_datetime_local, reporting_end_datetime_local, period_type):
| wb = Workbook()
ws = wb.active
# Row height
ws.row_dimensions[1].height = 118
for i in range(2, 2000 + 1):
ws.row_dimensions[i].height = 30
# Col width
ws.column_dimensions['A'].width = 1.5
for i in range(ord('B'), ord('I')):
ws.column_dimensions[chr(i)].width = 15.0
... |
def export(result, name, reporting_start_datetime_local, reporting_end_datetime_local, period_type):
####################################################################################################################
# Step 1: Validate the report data
#####################################################... | 256 | 256 | 2,322 | 20 | 235 | 823914102/myems-api | excelexporters/metersubmetersbalance.py | Python | generate_excel | generate_excel | 57 | 289 | 57 | 57 | c51e17de260722175c3966b286ac94e1bd4a8722 | bigcode/the-stack | train |
c43bac2a44d789daecd1b8eb | train | function | def n_primes(n):
"""List of the n-first prime numbers.
Parameters
----------
n : int
Number of prime numbers wanted.
Returns
-------
primes : list(int)
List of primes.
"""
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59,
61, 67... | def n_primes(n):
| """List of the n-first prime numbers.
Parameters
----------
n : int
Number of prime numbers wanted.
Returns
-------
primes : list(int)
List of primes.
"""
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59,
61, 67, 71, 73, 79, 83,... | (int)
Primes in ``2 <= p < n``.
References
----------
[1] `StackOverflow <https://stackoverflow.com/questions/2068372>`_.
"""
sieve = np.ones(n // 3 + (n % 6 == 2), dtype=bool)
for i in range(1, int(n ** 0.5) // 3 + 1):
if sieve[i]:
k = 3 * i + 1 | 1
siev... | 189 | 190 | 634 | 6 | 183 | EkremBayar/bayar | venv/Lib/site-packages/statsmodels/tools/sequences.py | Python | n_primes | n_primes | 84 | 119 | 84 | 84 | 5faec21577062e19b31741877d5c8ec72836138a | bigcode/the-stack | train |
4fc996ac15249a05259a4062 | train | function | def van_der_corput(n_sample, base=2, start_index=0):
"""Van der Corput sequence.
Pseudo-random number generator based on a b-adic expansion.
Parameters
----------
n_sample : int
Number of element of the sequence.
base : int
Base of the sequence.
start_index : int
In... | def van_der_corput(n_sample, base=2, start_index=0):
| """Van der Corput sequence.
Pseudo-random number generator based on a b-adic expansion.
Parameters
----------
n_sample : int
Number of element of the sequence.
base : int
Base of the sequence.
start_index : int
Index to start the sequence from.
Returns
----... |
while 'Not enought primes':
primes = primes_from_2_to(big_number)[:n]
if len(primes) == n:
break
big_number += 1000
return primes
def van_der_corput(n_sample, base=2, start_index=0):
| 64 | 64 | 188 | 17 | 46 | EkremBayar/bayar | venv/Lib/site-packages/statsmodels/tools/sequences.py | Python | van_der_corput | van_der_corput | 122 | 151 | 122 | 122 | 395321865cecd84eba2d2345f3ad616f0aa00d1b | bigcode/the-stack | train |
283db5ebf552d809abf76515 | train | function | def halton(dim, n_sample, bounds=None, start_index=0):
"""Halton sequence.
Pseudo-random number generator that generalize the Van der Corput sequence
for multiple dimensions. Halton sequence use base-two Van der Corput
sequence for the first dimension, base-three for its second and base-n for
its n... | def halton(dim, n_sample, bounds=None, start_index=0):
| """Halton sequence.
Pseudo-random number generator that generalize the Van der Corput sequence
for multiple dimensions. Halton sequence use base-two Van der Corput
sequence for the first dimension, base-three for its second and base-n for
its n-dimension.
Parameters
----------
dim : in... | base : int
Base of the sequence.
start_index : int
Index to start the sequence from.
Returns
-------
sequence : list (n_samples,)
Sequence of Van der Corput.
"""
sequence = []
for i in range(start_index, start_index + n_sample):
n_th_number, denom = 0., 1.
... | 144 | 144 | 480 | 16 | 127 | EkremBayar/bayar | venv/Lib/site-packages/statsmodels/tools/sequences.py | Python | halton | halton | 154 | 212 | 154 | 154 | 93b832fdb5c4bd98915526c82e0abaaa58bbc012 | bigcode/the-stack | train |
158a7f7cae8a3d3f2da0401f | train | function | def discrepancy(sample, bounds=None):
"""Discrepancy.
Compute the centered discrepancy on a given sample.
It is a measure of the uniformity of the points in the parameter space.
The lower the value is, the better the coverage of the parameter space is.
Parameters
----------
sample : array_... | def discrepancy(sample, bounds=None):
| """Discrepancy.
Compute the centered discrepancy on a given sample.
It is a measure of the uniformity of the points in the parameter space.
The lower the value is, the better the coverage of the parameter space is.
Parameters
----------
sample : array_like (n_samples, k_vars)
The s... | """Low discrepancy sequence tools."""
import numpy as np
def discrepancy(sample, bounds=None):
| 18 | 136 | 455 | 7 | 10 | EkremBayar/bayar | venv/Lib/site-packages/statsmodels/tools/sequences.py | Python | discrepancy | discrepancy | 5 | 55 | 5 | 5 | 2661bad16b505ba54d2fb4cac02edb50af68211c | bigcode/the-stack | train |
3e8c1bf53bdf0f3b0a7a1704 | train | function | def primes_from_2_to(n):
"""Prime numbers from 2 to *n*.
Parameters
----------
n : int
Sup bound with ``n >= 6``.
Returns
-------
primes : list(int)
Primes in ``2 <= p < n``.
References
----------
[1] `StackOverflow <https://stackoverflow.com/questions/2068372>... | def primes_from_2_to(n):
| """Prime numbers from 2 to *n*.
Parameters
----------
n : int
Sup bound with ``n >= 6``.
Returns
-------
primes : list(int)
Primes in ``2 <= p < n``.
References
----------
[1] `StackOverflow <https://stackoverflow.com/questions/2068372>`_.
"""
sieve = n... | s0))
disc2 = prod_arr.sum()
c2 = ((13.0 / 12.0) ** dim - 2.0 / n_sample * disc1 +
1.0 / (n_sample ** 2) * disc2)
return c2
def primes_from_2_to(n):
| 69 | 69 | 232 | 8 | 60 | EkremBayar/bayar | venv/Lib/site-packages/statsmodels/tools/sequences.py | Python | primes_from_2_to | primes_from_2_to | 58 | 81 | 58 | 58 | eae462f87d344d7b03826406b6b5a6192d5ddf4b | bigcode/the-stack | train |
fc7f886fddc5f069655896a0 | train | class | class ProviderInterface:
"""This interface provides methods to be implemented for each ISP"""
def get_stream_info(self, channel_id: int) -> dict:
"""
Get stream information (MPD address, Widewine key) for the specified id.
Required keys: path, mime_type, manifest_type, drm, lice... | class ProviderInterface:
| """This interface provides methods to be implemented for each ISP"""
def get_stream_info(self, channel_id: int) -> dict:
"""
Get stream information (MPD address, Widewine key) for the specified id.
Required keys: path, mime_type, manifest_type, drm, license_type, license_key
... | # -*- coding: utf-8 -*-
"""PROVIDER INTERFACE"""
class ProviderInterface:
| 18 | 64 | 190 | 4 | 14 | wail-fajr-rd/plugin.video.orange.fr | resources/lib/providers/provider_interface.py | Python | ProviderInterface | ProviderInterface | 4 | 24 | 4 | 4 | 7f01e2c77f7cd87292d8eca08434629da0ea6145 | bigcode/the-stack | train |
1e30c6e843f82ab6a87e3a30 | train | class | class test_misc(unittest.TestCase):
def setUp(self):
self.app = app_or_default()
def test_State(self):
state = self.app.events.State()
self.assertDictEqual(dict(state.workers), {})
| class test_misc(unittest.TestCase):
| def setUp(self):
self.app = app_or_default()
def test_State(self):
state = self.app.events.State()
self.assertDictEqual(dict(state.workers), {})
| (ev)
it = r.itercapture(limit=4, wakeup=True)
it.next() # skip consumer (see itercapture)
list(it)
self.assertEqual(events_received[0], 4)
finally:
channel.close()
connection.close()
class test_misc(unittest.TestCase):
| 64 | 64 | 46 | 7 | 57 | aleszoulek/celery | celery/tests/test_events.py | Python | test_misc | test_misc | 179 | 186 | 179 | 180 | 565e9b7619f1a6ae3240f7e3a3aaf2de81cb7fc6 | bigcode/the-stack | train |
d57332e59ec382659a6b7537 | train | class | class MockProducer(object):
raise_on_publish = False
def __init__(self, *args, **kwargs):
self.sent = []
def publish(self, msg, *args, **kwargs):
if self.raise_on_publish:
raise KeyError()
self.sent.append(msg)
def close(self):
pass
def has_event(self,... | class MockProducer(object):
| raise_on_publish = False
def __init__(self, *args, **kwargs):
self.sent = []
def publish(self, msg, *args, **kwargs):
if self.raise_on_publish:
raise KeyError()
self.sent.append(msg)
def close(self):
pass
def has_event(self, kind):
for event in... | import socket
from celery import events
from celery.app import app_or_default
from celery.tests.utils import unittest
class MockProducer(object):
| 28 | 64 | 101 | 5 | 22 | aleszoulek/celery | celery/tests/test_events.py | Python | MockProducer | MockProducer | 8 | 26 | 8 | 8 | 9fcde49d3af49f8547e18d5c28d54e7a9e05493d | bigcode/the-stack | train |
ca2b4422aa5223a72aea2356 | train | class | class TestEventReceiver(unittest.TestCase):
def setUp(self):
self.app = app_or_default()
def test_process(self):
message = {"type": "world-war"}
got_event = [False]
def my_handler(event):
got_event[0] = True
r = events.EventReceiver(object(),
... | class TestEventReceiver(unittest.TestCase):
| def setUp(self):
self.app = app_or_default()
def test_process(self):
message = {"type": "world-war"}
got_event = [False]
def my_handler(event):
got_event[0] = True
r = events.EventReceiver(object(),
handlers={"world-war": ... | channel)
self.assertTrue(dispatcher.enabled)
self.assertTrue(dispatcher.publisher.channel)
self.assertEqual(dispatcher.publisher.serializer,
self.app.conf.CELERY_EVENT_SERIALIZER)
created_channel = dispatcher.publisher.channel
disp... | 151 | 151 | 504 | 8 | 143 | aleszoulek/celery | celery/tests/test_events.py | Python | TestEventReceiver | TestEventReceiver | 98 | 176 | 98 | 99 | 319f69dfe68ae46b5af0570111ff466e13680a71 | bigcode/the-stack | train |
4f70924f061a2241eb0d358e | train | class | class TestEventDispatcher(unittest.TestCase):
def setUp(self):
self.app = app_or_default()
def test_send(self):
producer = MockProducer()
eventer = self.app.events.Dispatcher(object(), enabled=False)
eventer.publisher = producer
eventer.enabled = True
eventer.se... | class TestEventDispatcher(unittest.TestCase):
| def setUp(self):
self.app = app_or_default()
def test_send(self):
producer = MockProducer()
eventer = self.app.events.Dispatcher(object(), enabled=False)
eventer.publisher = producer
eventer.enabled = True
eventer.send("World War II", ended=True)
self.ass... | ):
self.sent = []
def publish(self, msg, *args, **kwargs):
if self.raise_on_publish:
raise KeyError()
self.sent.append(msg)
def close(self):
pass
def has_event(self, kind):
for event in self.sent:
if event["type"] == kind:
re... | 129 | 130 | 434 | 8 | 121 | aleszoulek/celery | celery/tests/test_events.py | Python | TestEventDispatcher | TestEventDispatcher | 37 | 95 | 37 | 38 | 11ea16a00bc295caec317b32fbb5453950dd7d27 | bigcode/the-stack | train |
766d8f344f372c80f40e9496 | train | class | class TestEvent(unittest.TestCase):
def test_constructor(self):
event = events.Event("world war II")
self.assertEqual(event["type"], "world war II")
self.assertTrue(event["timestamp"])
| class TestEvent(unittest.TestCase):
| def test_constructor(self):
event = events.Event("world war II")
self.assertEqual(event["type"], "world war II")
self.assertTrue(event["timestamp"])
| if self.raise_on_publish:
raise KeyError()
self.sent.append(msg)
def close(self):
pass
def has_event(self, kind):
for event in self.sent:
if event["type"] == kind:
return event
return False
class TestEvent(unittest.TestCase):
| 64 | 64 | 44 | 7 | 56 | aleszoulek/celery | celery/tests/test_events.py | Python | TestEvent | TestEvent | 29 | 34 | 29 | 30 | 0a6754bec026d13df6b9938b36b35e68aaf1c38d | bigcode/the-stack | train |
fbab31df8c5285f01c44ec40 | train | class | class HLS:
def __init__(self, file_path: str, destination_type: str):
self.path = file_path
| class HLS:
| def __init__(self, file_path: str, destination_type: str):
self.path = file_path
| import ffmpeg_streaming
from ffmpeg_streaming import Representation, Formats, CloudManager
import tempfile
class HLS:
| 26 | 64 | 28 | 4 | 21 | includeamin/ffmpeg-cloud | classes/ffmpeg/hls.py | Python | HLS | HLS | 6 | 8 | 6 | 6 | 6479b4b45868e303f312ce02bdb3837cc97a8b58 | bigcode/the-stack | train |
ec10470888efbe822548ebe9 | train | class | class Entity(object):
"""Entity object that identifies some resource/item/other.
:ivar kind: **immutable** type/kind that identifies this
entity (typically unique to a library/application)
:type kind: string
:ivar Entity.name: **immutable** name that can be used to uniquely
... | class Entity(object):
| """Entity object that identifies some resource/item/other.
:ivar kind: **immutable** type/kind that identifies this
entity (typically unique to a library/application)
:type kind: string
:ivar Entity.name: **immutable** name that can be used to uniquely
identify this enti... | agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
class Entity(object):
| 64 | 64 | 189 | 4 | 60 | JonasMie/taskflow | taskflow/types/entity.py | Python | Entity | Entity | 18 | 43 | 18 | 18 | e1c956b2d52902f22cc3ffeda8ad41219650b080 | bigcode/the-stack | train |
099c74263dbbf5d8b7a11764 | train | function | def process_sources_results(sources_list):
'''
function that processes the sources results and transform them into a list of objects
'''
sources_results = []
for source_item in sources_list:
id = source_item.get('id')
name = source_item.get('name')
description = source_item... | def process_sources_results(sources_list):
| '''
function that processes the sources results and transform them into a list of objects
'''
sources_results = []
for source_item in sources_list:
id = source_item.get('id')
name = source_item.get('name')
description = source_item.get('description')
url = source_ite... | url:
get_articles_data = url.read()
get_articles_response = json.loads(get_articles_data)
if get_articles_response['articles']:
articles_list = get_articles_response['articles']
articles_results = process_articles_results(articles_list)
return articles_results
def p... | 64 | 64 | 136 | 9 | 54 | lavylipesh/News-Highlight | app/requests.py | Python | process_sources_results | process_sources_results | 43 | 60 | 43 | 43 | fd460f9bfe6596736718027614a38b010f122ee3 | bigcode/the-stack | train |
010cc5c1afe9d96b574e7375 | train | function | def get_sources(category):
'''
function that gets the json response to our url requests
'''
get_sources_url = base_url.format(category,api_key)
with urllib.request.urlopen(get_sources_url) as url:
get_sources_data = url.read()
get_sources_response = json.loads(get_sources_data)
... | def get_sources(category):
| '''
function that gets the json response to our url requests
'''
get_sources_url = base_url.format(category,api_key)
with urllib.request.urlopen(get_sources_url) as url:
get_sources_data = url.read()
get_sources_response = json.loads(get_sources_data)
sources_results = None
... | import os
# getting api key
api_key = None
# getting base url
base_url = None
def configure_request(app):
global api_key,base_url
api_key = app.config['NEWS_API_KEY']
base_url = app.config['NEWS_API_BASE_URL']
def get_sources(category):
| 64 | 64 | 105 | 5 | 59 | lavylipesh/News-Highlight | app/requests.py | Python | get_sources | get_sources | 16 | 29 | 16 | 16 | 045061316ef98bf94ac6eae2f678399d976c8ce7 | bigcode/the-stack | train |
9aa51d8651f95155bf4d019c | train | function | def configure_request(app):
global api_key,base_url
api_key = app.config['NEWS_API_KEY']
base_url = app.config['NEWS_API_BASE_URL']
| def configure_request(app):
| global api_key,base_url
api_key = app.config['NEWS_API_KEY']
base_url = app.config['NEWS_API_BASE_URL']
| from app import main
import urllib.request,json
from .models import Sources,Articles
import os
# getting api key
api_key = None
# getting base url
base_url = None
def configure_request(app):
| 46 | 64 | 36 | 5 | 40 | lavylipesh/News-Highlight | app/requests.py | Python | configure_request | configure_request | 11 | 14 | 11 | 11 | 70fb0fc8c0a1243b8711a38403ef0a874d8cd1ba | bigcode/the-stack | train |
3ee018bd85bac532d15b2292 | train | function | def get_articles(id):
'''
function that gets the json response to our url requests
'''
get_articles_url = 'https://newsapi.org/v2/everything?sources={}&apiKey={}'.format(id,api_key)
with urllib.request.urlopen(get_articles_url) as url:
get_articles_data = url.read()
get_articles_resp... | def get_articles(id):
| '''
function that gets the json response to our url requests
'''
get_articles_url = 'https://newsapi.org/v2/everything?sources={}&apiKey={}'.format(id,api_key)
with urllib.request.urlopen(get_articles_url) as url:
get_articles_data = url.read()
get_articles_response = json.loads(get_... | get_sources_data = url.read()
get_sources_response = json.loads(get_sources_data)
sources_results = None
if get_sources_response['sources']:
sources_list = get_sources_response['sources']
sources_results = process_sources_results(sources_list)
return sources_... | 64 | 64 | 116 | 5 | 58 | lavylipesh/News-Highlight | app/requests.py | Python | get_articles | get_articles | 30 | 42 | 30 | 30 | 1c6a0212db093a08ae5415434977f21f5d714708 | bigcode/the-stack | train |
47dff6fc1d4e96c6ed2509a5 | train | function | def process_articles_results(articles_list):
'''
function that processess the article result and transform them into a list of objects
'''
articles_results = []
for article_item in articles_list:
id = article_item.get('id')
author = article_item.get('author')
title = article... | def process_articles_results(articles_list):
| '''
function that processess the article result and transform them into a list of objects
'''
articles_results = []
for article_item in articles_list:
id = article_item.get('id')
author = article_item.get('author')
title = article_item.get('title')
description = arti... | language = source_item.get('language')
country = source_item.get('country')
category = source_item.get('category')
source_object = Sources(id,name,description,url,category,language,country)
sources_results.append(source_object)
return sources_results
def process_articles_r... | 64 | 64 | 155 | 8 | 55 | lavylipesh/News-Highlight | app/requests.py | Python | process_articles_results | process_articles_results | 61 | 79 | 61 | 61 | 857e9603016dc11e86bdb711f19d60f827c1b593 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.