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
3f793879f4d59b61d4bd6805
train
function
def bitwise_dot(s: str, t: str) -> str: length = len(s) res = 0 for i in range(length): res += int(s[i]) * int(t[i]) return str(res % 2)
def bitwise_dot(s: str, t: str) -> str:
length = len(s) res = 0 for i in range(length): res += int(s[i]) * int(t[i]) return str(res % 2)
(s: str, t: str) -> str: length = len(s) res = [] for i in range(length): res.append(str(int(s[i]) ^ int(t[i]))) return ''.join(res[::-1]) def bitwise_dot(s: str, t: str) -> str:
64
64
54
15
49
UCLA-SEAL/QDiff
benchmark/startQiskit_noisy3330.py
Python
bitwise_dot
bitwise_dot
24
29
24
24
078fbe078cfdf1766c9b9ac20f7a3207be47445c
bigcode/the-stack
train
1b3cfdac0abffc21977b909a
train
function
def make_circuit(n:int,f) -> QuantumCircuit: # circuit begin input_qubit = QuantumRegister(n,"qc") classical = ClassicalRegister(n, "qm") prog = QuantumCircuit(input_qubit, classical) prog.cx(input_qubit[0],input_qubit[3]) # number=13 prog.h(input_qubit[3]) # number=23 prog.cz(input_qubit[0]...
def make_circuit(n:int,f) -> QuantumCircuit: # circuit begin
input_qubit = QuantumRegister(n,"qc") classical = ClassicalRegister(n, "qm") prog = QuantumCircuit(input_qubit, classical) prog.cx(input_qubit[0],input_qubit[3]) # number=13 prog.h(input_qubit[3]) # number=23 prog.cz(input_qubit[0],input_qubit[3]) # number=24 prog.y(input_qubit[1]) # number=...
-toffoli-gate-using-only-single-qubit-and-cnot-gates # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate controls = QuantumRegister(n, "ofc") target = QuantumRegister(1, "oft") oracle = QuantumCircuit(controls, target, name="Of") for i in range(2 ** ...
203
203
679
17
185
UCLA-SEAL/QDiff
benchmark/startQiskit_noisy3330.py
Python
make_circuit
make_circuit
53
103
53
54
315dc9062027bd66188e79576dc8c5a10f98c477
bigcode/the-stack
train
92f4bfbd6d1341f386e8c66b
train
class
class rigolDP1116A(rigolDP1000): "Rigol DP1116A IVI DC power supply driver" def __init__(self, *args, **kwargs): self.__dict__.setdefault('_instrument_id', 'DP1116A') super(rigolDP1116A, self).__init__(*args, **kwargs) self._output_count = 1 self._...
class rigolDP1116A(rigolDP1000):
"Rigol DP1116A IVI DC power supply driver" def __init__(self, *args, **kwargs): self.__dict__.setdefault('_instrument_id', 'DP1116A') super(rigolDP1116A, self).__init__(*args, **kwargs) self._output_count = 1 self._output_spec = [ { ...
, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from .rigolDP1000 import * class rigolDP1116A(rigolDP1000):
64
64
190
13
51
edupo/python-ivi
ivi/rigol/rigolDP1116A.py
Python
rigolDP1116A
rigolDP1116A
29
52
29
29
f406c4c34a98c31b91dbb85887a027b25170fa00
bigcode/the-stack
train
7affe7683d92701daf330e0a
train
class
class Produto: qtde_produtos=0 produtos=[] def __init__(self, nome, preco, tipo, qtde): self.nome = nome self.preco = preco self.tipo = tipo self.qtde = qtde def save(self): Produto.qtde_produtos+=1 self.id = self.qtde_produtos Produto.produtos.append(self) def del...
class Produto:
qtde_produtos=0 produtos=[] def __init__(self, nome, preco, tipo, qtde): self.nome = nome self.preco = preco self.tipo = tipo self.qtde = qtde def save(self): Produto.qtde_produtos+=1 self.id = self.qtde_produtos Produto.produtos.append(self) def delete(): Prod...
class Produto:
3
64
102
3
0
VitoriaCamelo/PET
Nivelamento/projeto(v2).py
Python
Produto
Produto
1
18
1
1
3fd957faa7712a8bf49faf9a1db0b2d7956860c0
bigcode/the-stack
train
0e4a3f9ef01e7bb49021c246
train
function
def inserir(): qtd = int(input("digite qtde a inserir: ")) for i in range(qtd): nome = input("digite nome do produto: ") preco = float(input("digite preço do produto: ")) tipo = input("digite tipo do produto: ") qtde = int(input("digite qtde do produto: ")) produto = Produto(nome, preco, tipo, q...
def inserir():
qtd = int(input("digite qtde a inserir: ")) for i in range(qtd): nome = input("digite nome do produto: ") preco = float(input("digite preço do produto: ")) tipo = input("digite tipo do produto: ") qtde = int(input("digite qtde do produto: ")) produto = Produto(nome, preco, tipo, qtde) produt...
preco self.tipo = tipo self.qtde = qtde def save(self): Produto.qtde_produtos+=1 self.id = self.qtde_produtos Produto.produtos.append(self) def delete(): Produto.qtde_produtos-=1 def inserir():
63
64
118
3
59
VitoriaCamelo/PET
Nivelamento/projeto(v2).py
Python
inserir
inserir
20
32
20
20
0803c3509d8063e28a49e2e7c02bfe56e6996c52
bigcode/the-stack
train
1406b0a5a9e40b4b88c180f7
train
function
def pesquisar(): achou=0 qtde = Produto.qtde_produtos produtos = Produto.produtos nome_pesquisar=input("digite para pesquisar: ") for i in range(qtde): if produtos[i].nome==nome_pesquisar: achou=1 print("produto encontrado") print("nome do produto:", produtos[i].nome) print("preco ...
def pesquisar():
achou=0 qtde = Produto.qtde_produtos produtos = Produto.produtos nome_pesquisar=input("digite para pesquisar: ") for i in range(qtde): if produtos[i].nome==nome_pesquisar: achou=1 print("produto encontrado") print("nome do produto:", produtos[i].nome) print("preco do produto:", pro...
ite novo preço do produto: ")) produtos[i].tipo = input("digite novo tipo do produto: ") produtos[i].qtde= int(input("digite nova qtde do produto: ")) break if achou==0: print("produto não encontrado") def pesquisar():
63
64
141
3
60
VitoriaCamelo/PET
Nivelamento/projeto(v2).py
Python
pesquisar
pesquisar
52
67
52
52
fcea75a71cf1d465246feacbc4f6dd4fd71537e0
bigcode/the-stack
train
473f5111504906172e3f6a4d
train
function
def alterar(): achou=0 qtde = Produto.qtde_produtos produtos = Produto.produtos nome_alterar=input("digite para alterar: ") for i in range(qtde): if produtos[i].nome==nome_alterar: achou=1 print("produto encontrado") produtos[i].nome = input("digite novo nome do produto: ") produto...
def alterar():
achou=0 qtde = Produto.qtde_produtos produtos = Produto.produtos nome_alterar=input("digite para alterar: ") for i in range(qtde): if produtos[i].nome==nome_alterar: achou=1 print("produto encontrado") produtos[i].nome = input("digite novo nome do produto: ") produtos[i].preco = fl...
do produto: ") qtde = int(input("digite qtde do produto: ")) produto = Produto(nome, preco, tipo, qtde) produto.save() if qtd ==1: print("produto inserido") else: print("produtos inseridos") def alterar():
63
64
159
3
60
VitoriaCamelo/PET
Nivelamento/projeto(v2).py
Python
alterar
alterar
35
50
35
35
eb61cea73ee6093f2d5287daf354b7361db4095d
bigcode/the-stack
train
1fae1721ef146eb2803c08c0
train
function
def listar(): qtde = Produto.qtde_produtos for i in range(qtde): print("produto", i+1) print("nome do produto:", Produto.produtos[i].nome) print("preco do produto:", Produto.produtos[i].preco) print("tipo do produto:", Produto.produtos[i].tipo) print("qtde do produto:", Produto.produtos[i].qtde)...
def listar():
qtde = Produto.qtde_produtos for i in range(qtde): print("produto", i+1) print("nome do produto:", Produto.produtos[i].nome) print("preco do produto:", Produto.produtos[i].preco) print("tipo do produto:", Produto.produtos[i].tipo) print("qtde do produto:", Produto.produtos[i].qtde)
") for i in range(qtde): if produtos[i].nome==nome_remover: achou=1 del produtos[i] Produto.delete() print("produto removido") break if achou==0: print("produto não encontrado") def listar():
63
64
91
3
60
VitoriaCamelo/PET
Nivelamento/projeto(v2).py
Python
listar
listar
84
91
84
84
bb93315d3f798cdcb91d8d42afb8308a5bec793a
bigcode/the-stack
train
a777c86a9f2867590e97cc4e
train
function
def remover(): achou=0 qtde = Produto.qtde_produtos produtos = Produto.produtos nome_remover=input("digite para remover: ") for i in range(qtde): if produtos[i].nome==nome_remover: achou=1 del produtos[i] Produto.delete() print("produto removido") break if achou==0: pri...
def remover():
achou=0 qtde = Produto.qtde_produtos produtos = Produto.produtos nome_remover=input("digite para remover: ") for i in range(qtde): if produtos[i].nome==nome_remover: achou=1 del produtos[i] Produto.delete() print("produto removido") break if achou==0: print("produto não...
[i].nome) print("preco do produto:", produtos[i].preco) print("tipo do produto:", produtos[i].tipo) print("qtde do produto:", produtos[i].qtde) break if achou==0: print("produto não encontrado") def remover():
64
64
97
3
61
VitoriaCamelo/PET
Nivelamento/projeto(v2).py
Python
remover
remover
69
82
69
69
d9c1c6ec4369b1c558d6fbd7d902de2c572bc585
bigcode/the-stack
train
b9deaa4d6aec3a74f683b2b4
train
class
class CreateJSON(object): """This class will generate the JSON file needed by SIT.""" template = { "output_path": None, "import_config": { "ageclass_path": None, "classifiers_path": None, "disturbance_events_path": None, "disturbance_types_path": No...
class CreateJSON(object):
"""This class will generate the JSON file needed by SIT.""" template = { "output_path": None, "import_config": { "ageclass_path": None, "classifiers_path": None, "disturbance_events_path": None, "disturbance_types_path": None, "inventory_pat...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Written by Lucas Sinclair and Paul Rougieux. JRC biomass Project. Unit D1 Bioeconomy. """ # Built-in modules # import os # Third party modules # import simplejson as json # First party modules # from autopaths.auto_paths import AutoPaths #########################...
80
207
693
5
75
xapple/cbm_runner
cbmcfs3_runner/stdrd_import_tool/create_json.py
Python
CreateJSON
CreateJSON
21
94
21
21
e1f72d42cf7075f33ecd28f865fe751ce2135259
bigcode/the-stack
train
0f7e1b938ee542e400dfd1f4
train
class
class Quest (JQuest) : def __init__(self,id,name,descr): # first initialize the quest. The superclass defines variables, instantiates States, etc JQuest.__init__(self,id,name,descr) # Next, override necessary variables: self.NPC = [30191,31626,31588,31280,31644,31646,31647,31651,31654,31655,31658...
class Quest (JQuest) :
def __init__(self,id,name,descr): # first initialize the quest. The superclass defines variables, instantiates States, etc JQuest.__init__(self,id,name,descr) # Next, override necessary variables: self.NPC = [30191,31626,31588,31280,31644,31646,31647,31651,31654,31655,31658,31280] self.Items ...
# Made by Emperorc import sys from com.l2jfrozen.gameserver.model.quest import State from com.l2jfrozen.gameserver.model.quest import QuestState from quests.SagasSuperclass import Quest as JQuest qn = "85_SagaOfTheCardinal" qnu = 85 qna = "Saga of the Cardinal" class Quest (JQuest) :
78
161
538
7
71
DigitalCoin1/L2SPERO
datapack/data/scripts/quests/85_SagaOfTheCardinal/__init__.py
Python
Quest
Quest
11
34
11
12
05fe7093fcfaddaf1fccbd461d3657ec99825123
bigcode/the-stack
train
d78fcf80e36507f52574ae42
train
function
def make_circuit(n:int,f) -> QuantumCircuit: # circuit begin input_qubit = QuantumRegister(n,"qc") classical = ClassicalRegister(n, "qm") prog = QuantumCircuit(input_qubit, classical) prog.h(input_qubit[0]) # number=3 prog.h(input_qubit[1]) # number=4 prog.h(input_qubit[2]) # number=5 pr...
def make_circuit(n:int,f) -> QuantumCircuit: # circuit begin
input_qubit = QuantumRegister(n,"qc") classical = ClassicalRegister(n, "qm") prog = QuantumCircuit(input_qubit, classical) prog.h(input_qubit[0]) # number=3 prog.h(input_qubit[1]) # number=4 prog.h(input_qubit[2]) # number=5 prog.h(input_qubit[3]) # number=6 prog.h(input_qubit[0]) # numb...
transpile from pprint import pprint from qiskit.test.mock import FakeVigo from math import log2,floor, sqrt, pi import numpy as np import networkx as nx def build_oracle(n: int, f) -> QuantumCircuit: # implement the oracle O_f^\pm # NOTE: use U1 gate (P gate) with \lambda = 180 ==> CZ gate # or multi_cont...
256
256
932
17
238
UCLA-SEAL/QDiff
benchmark/startQiskit_Class1617.py
Python
make_circuit
make_circuit
41
115
41
42
5ed31817af76d0b45fc63c859a33c4b24e588d37
bigcode/the-stack
train
d84de2c19b2711917a082b72
train
function
def build_oracle(n: int, f) -> QuantumCircuit: # implement the oracle O_f^\pm # NOTE: use U1 gate (P gate) with \lambda = 180 ==> CZ gate # or multi_control_Z_gate (issue #127) controls = QuantumRegister(n, "ofc") oracle = QuantumCircuit(controls, name="Zf") for i in range(2 ** n): rep...
def build_oracle(n: int, f) -> QuantumCircuit: # implement the oracle O_f^\pm # NOTE: use U1 gate (P gate) with \lambda = 180 ==> CZ gate # or multi_control_Z_gate (issue #127)
controls = QuantumRegister(n, "ofc") oracle = QuantumCircuit(controls, name="Zf") for i in range(2 ** n): rep = np.binary_repr(i, n) if f(rep) == "1": for j in range(n): if rep[j] == "0": oracle.x(controls[j]) # oracle.h(controls[...
import networkx as nx def build_oracle(n: int, f) -> QuantumCircuit: # implement the oracle O_f^\pm # NOTE: use U1 gate (P gate) with \lambda = 180 ==> CZ gate # or multi_control_Z_gate (issue #127)
64
64
197
58
5
UCLA-SEAL/QDiff
benchmark/startQiskit_Class1617.py
Python
build_oracle
build_oracle
14
38
14
18
65ce9f82635737bf77eda8c5c06726774c01313a
bigcode/the-stack
train
c248f833733adf1f8ea69bb7
train
function
def main(): # load the file and convert it into a file-object response = request.urlopen(PATH_TO_EXCEL) file = BytesIO(response.read()) # pass into openpyxl and find when it was last modified wb = load_workbook(file, read_only=True, data_only=True) # we convert it to Central time because Texas ...
def main(): # load the file and convert it into a file-object
response = request.urlopen(PATH_TO_EXCEL) file = BytesIO(response.read()) # pass into openpyxl and find when it was last modified wb = load_workbook(file, read_only=True, data_only=True) # we convert it to Central time because Texas (sorry, El Paso) modified = wb.properties.modified.astimezone(...
import ZoneInfo from openpyxl import load_workbook PATH_TO_EXCEL = ( "https://www.dshs.texas.gov/immunize/covid19/COVID-19-Vaccine-Data-by-County.xls" ) CENTRAL_TZ = ZoneInfo("America/Chicago") LATEST_DISTRIBUTION_PATH = "distribution/latest.csv" LATEST_AGE_PATH = "ages/latest.csv" def main(): # load the fil...
100
100
335
16
84
rdmurphy/tx-covid-vaccine-data
distribution.py
Python
main
main
17
54
17
18
e42517ade0a0a7265ec11534bc13946dd801ab4b
bigcode/the-stack
train
cdb9bd52986d8027ba663668
train
class
class BuzzerTest(unittest.TestCase): def test_node_exist(self): nodes = rosnode.get_node_names() self.assertIn('/buzzer',nodes,"node does not exist")
class BuzzerTest(unittest.TestCase):
def test_node_exist(self): nodes = rosnode.get_node_names() self.assertIn('/buzzer',nodes,"node does not exist")
#!/usr/bin/env python import rospy, unittest, rostest import rosnode import time class BuzzerTest(unittest.TestCase):
29
64
38
8
20
chiba-RasPimouse/pimouse_ros
test/travis_test_buzzer.py
Python
BuzzerTest
BuzzerTest
6
9
6
6
0f29b01632ead48199381c9b4b3a5607af102eeb
bigcode/the-stack
train
3d951efbb460e2df28f7211c
train
function
def makedirs_ignore_exist(directory): try: os.makedirs(directory) except: exctype, oe = sys.exc_info()[:2] if not issubclass(exctype, OSError): raise if oe.errno != errno.EEXIST: raise
def makedirs_ignore_exist(directory):
try: os.makedirs(directory) except: exctype, oe = sys.exc_info()[:2] if not issubclass(exctype, OSError): raise if oe.errno != errno.EEXIST: raise
if fd.close(): raise RuntimeError("Unable to invoke condor_version") def test_version(self): self.assertEqual(htcondor.version(), self.lines[0]) def test_platform(self): self.assertEqual(htcondor.platform(), self.lines[1]) def makedirs_ignore_exist(directory):
64
64
60
8
56
final-israel/htcondor
src/condor_tests/python_bindings/htcondor_version_tests.py
Python
makedirs_ignore_exist
makedirs_ignore_exist
71
78
71
71
b5c92f5b8ed13741f04840d02a63554e0c531e7f
bigcode/the-stack
train
4e49bf75a1f3af099911af1d
train
class
class TestClassadExtensions(unittest.TestCase): def test_user_home(self): if platform.system() == 'Windows': self.assertEqual(classad.ExprTree('userHome("foo","bar")').eval(), classad.Value.Error) return import pwd pw = pwd.getpwuid(os.geteuid()) user = pw.pw...
class TestClassadExtensions(unittest.TestCase):
def test_user_home(self): if platform.system() == 'Windows': self.assertEqual(classad.ExprTree('userHome("foo","bar")').eval(), classad.Value.Error) return import pwd pw = pwd.getpwuid(os.geteuid()) user = pw.pw_name home = pw.pw_dir htcondor....
Up(self): os.environ["_condor_FOO"] = "BAR" htcondor.reload_config() def test_config(self): self.assertEqual(htcondor.param["FOO"], "BAR") def test_reconfig(self): htcondor.param["FOO"] = "BAZ" self.assertEqual(htcondor.param["FOO"], "BAZ") os.environ["_condor_F...
125
125
419
9
116
final-israel/htcondor
src/condor_tests/python_bindings/htcondor_version_tests.py
Python
TestClassadExtensions
TestClassadExtensions
26
51
26
27
36086be7181446ad0ee9d11bbdbf3008276abbaf
bigcode/the-stack
train
f9bd51d6888ebce08bf1847d
train
class
class TestConfig(unittest.TestCase): def setUp(self): os.environ["_condor_FOO"] = "BAR" htcondor.reload_config() def test_config(self): self.assertEqual(htcondor.param["FOO"], "BAR") def test_reconfig(self): htcondor.param["FOO"] = "BAZ" self.assertEqual(htcondor.p...
class TestConfig(unittest.TestCase):
def setUp(self): os.environ["_condor_FOO"] = "BAR" htcondor.reload_config() def test_config(self): self.assertEqual(htcondor.param["FOO"], "BAR") def test_reconfig(self): htcondor.param["FOO"] = "BAZ" self.assertEqual(htcondor.param["FOO"], "BAZ") os.environ...
#!/usr/bin/python import os import sys import errno import platform import unittest class TestConfig(unittest.TestCase):
27
64
126
7
19
final-israel/htcondor
src/condor_tests/python_bindings/htcondor_version_tests.py
Python
TestConfig
TestConfig
9
23
9
10
2f833c28abb48f89cbf06e844578aaeeaeca3c61
bigcode/the-stack
train
5293330f93fbb082d97bba93
train
class
class TestVersion(unittest.TestCase): def setUp(self): fd = os.popen("condor_version") self.lines = [] for line in fd.readlines(): self.lines.append(line.strip()) if fd.close(): raise RuntimeError("Unable to invoke condor_version") def test_version(self)...
class TestVersion(unittest.TestCase):
def setUp(self): fd = os.popen("condor_version") self.lines = [] for line in fd.readlines(): self.lines.append(line.strip()) if fd.close(): raise RuntimeError("Unable to invoke condor_version") def test_version(self): self.assertEqual(htcondor.ver...
userHome(1)').eval(), classad.Value.Error) htcondor.param['CLASSAD_ENABLE_USER_HOME'] = 'false' self.assertEqual(classad.ExprTree('userHome(%s)' % classad.quote(user)).eval(), classad.Value.Undefined) class TestVersion(unittest.TestCase):
64
64
100
7
57
final-israel/htcondor
src/condor_tests/python_bindings/htcondor_version_tests.py
Python
TestVersion
TestVersion
54
68
54
55
fa3c4816595811d41f5944c1c70f96021647f10f
bigcode/the-stack
train
158840e41616833824bda305
train
class
class DataManager: def __init__(self, end_point: str, username: str, password: str): self.end_point = end_point self.auth = HTTPBasicAuth(username, password) self.destination_data = {} def get_destination_data(self) -> dict: response = requests.get(url=self.end_point, auth=self....
class DataManager:
def __init__(self, end_point: str, username: str, password: str): self.end_point = end_point self.auth = HTTPBasicAuth(username, password) self.destination_data = {} def get_destination_data(self) -> dict: response = requests.get(url=self.end_point, auth=self.auth) data ...
# This class is responsible for talking to the Google Sheet. import requests from requests.auth import HTTPBasicAuth class DataManager:
27
64
169
4
22
steveanlorn/python_bootcamp_100_days
day_39/data_manager.py
Python
DataManager
DataManager
7
33
7
7
972e5c6528fd83775fe3fbbe9b90709ab6f3e0ff
bigcode/the-stack
train
07ad28dfbb5a6f3e3cc65c22
train
class
class LayerActivation(LayerAttribution): def __init__( self, forward_func: Callable, layer: Module, device_ids: Optional[List[int]] = None, ) -> None: r""" Args: forward_func (callable): The forward function of the model or any ...
class LayerActivation(LayerAttribution):
def __init__( self, forward_func: Callable, layer: Module, device_ids: Optional[List[int]] = None, ) -> None: r""" Args: forward_func (callable): The forward function of the model or any modification of it layer ...
#!/usr/bin/env python3 from typing import Callable, List, Optional, Tuple, Union, Any import torch from torch import Tensor from torch.nn import Module from ..._utils.attribution import LayerAttribution from ..._utils.common import _format_attributions from ..._utils.gradient import _forward_layer_eval class LayerAct...
77
256
970
8
68
ngduduong/captum
captum/attr/_core/layer/layer_activation.py
Python
LayerActivation
LayerActivation
13
118
13
13
4f4b770a7ab11c86d72cebe1246066fff802d78a
bigcode/the-stack
train
4117687ba87ac3a5b73061b0
train
class
class DjangoLanguageEnum(ChoicesEnum): ZH_HANS = "zh-hans" EN = "en"
class DjangoLanguageEnum(ChoicesEnum):
ZH_HANS = "zh-hans" EN = "en"
ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from backend.util.enum import ChoicesEnum class BKLanguageEnum(ChoicesEnum): ZH_CN = "zh-cn" EN = "en" class DjangoLanguageEnum(ChoicesEnum):
64
64
25
8
56
nannan00/bk-iam-saas
saas/backend/common/constants.py
Python
DjangoLanguageEnum
DjangoLanguageEnum
19
21
19
19
b262d2fada2a8a330b134485825b17aab54d0467
bigcode/the-stack
train
a33a4a849e0f39cd760159e4
train
class
class BKLanguageEnum(ChoicesEnum): ZH_CN = "zh-cn" EN = "en"
class BKLanguageEnum(ChoicesEnum):
ZH_CN = "zh-cn" EN = "en"
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. """ from backend.util.enum import ChoicesEnum class BKLanguageE...
64
64
23
8
55
nannan00/bk-iam-saas
saas/backend/common/constants.py
Python
BKLanguageEnum
BKLanguageEnum
14
16
14
14
d2d819bba8e95534705ae0c3815653e8e8376117
bigcode/the-stack
train
1bd5c664e7f28ce4c96d7bff
train
function
@tf.function def log_pos_pdf(sample, l, agg = None): log_prob = tfp.distributions.Poisson(rate=l).log_prob(sample) if(agg is None): return(log_prob) if(isinstance(agg, (np.ndarray, np.generic))): return(tf.reduce_mean(log_prob * agg[None, :log_prob.shape[-1]], axis = -1)) if(agg == '...
@tf.function def log_pos_pdf(sample, l, agg = None):
log_prob = tfp.distributions.Poisson(rate=l).log_prob(sample) if(agg is None): return(log_prob) if(isinstance(agg, (np.ndarray, np.generic))): return(tf.reduce_mean(log_prob * agg[None, :log_prob.shape[-1]], axis = -1)) if(agg == 'sum'): return(tf.reduce_sum(log_prob, axis = -1))...
return(tf.reduce_mean(KL, axis = -1)) if(agg == 'sum'): return(tf.reduce_sum(KL, axis = -1)) return(tf.reduce_mean(KL, axis = -1)) @tf.function def log_pos_pdf(sample, l, agg = None):
64
64
119
16
48
DoronHav/PyENVI
PyENVI/dists.py
Python
log_pos_pdf
log_pos_pdf
29
38
29
30
4740b3705d13ecca8c076ccf9a1c8ae21b20f17f
bigcode/the-stack
train
2f660a58b044547dd4d987fc
train
function
@tf.function def log_nb_pdf(sample, r, p, agg = None): log_prob = tfp.distributions.NegativeBinomial(total_count=r, logits=p).log_prob(sample) if(agg is None): return(log_prob) if(isinstance(agg, (np.ndarray, np.generic))): return(tf.reduce_mean(log_prob * agg[None, :log_prob.shape[-1]], axi...
@tf.function def log_nb_pdf(sample, r, p, agg = None):
log_prob = tfp.distributions.NegativeBinomial(total_count=r, logits=p).log_prob(sample) if(agg is None): return(log_prob) if(isinstance(agg, (np.ndarray, np.generic))): return(tf.reduce_mean(log_prob * agg[None, :log_prob.shape[-1]], axis = -1)) if(agg == 'sum'): return(tf.reduce...
:log_prob.shape[-1]], axis = -1)) if(agg == 'sum'): return(tf.reduce_sum(log_prob, axis = -1)) return(tf.reduce_mean(log_prob, axis = -1)) @tf.function def log_nb_pdf(sample, r, p, agg = None):
64
64
127
18
46
DoronHav/PyENVI
PyENVI/dists.py
Python
log_nb_pdf
log_nb_pdf
40
49
40
41
b79dc50c1d9429b24c397b0dffa0666000c5cde5
bigcode/the-stack
train
da5ca0265be19d3277514498
train
function
@tf.function def OTDistance(sample, mean, agg = None): sample = tf.reshape(sample, [sample.shape[0], -1]) mean = tf.reshape(mean, [mean.shape[0], -1]) log_prob = - tf.square(sample - mean) if(agg is None): return(log_prob) if(isinstance(agg, (np.ndarray, np.generic))): return(tf.r...
@tf.function def OTDistance(sample, mean, agg = None):
sample = tf.reshape(sample, [sample.shape[0], -1]) mean = tf.reshape(mean, [mean.shape[0], -1]) log_prob = - tf.square(sample - mean) if(agg is None): return(log_prob) if(isinstance(agg, (np.ndarray, np.generic))): return(tf.reduce_mean(log_prob, axis = -1)) if(agg == 'sum'): ...
[None, :log_prob.shape[-1]], axis = -1)) if(agg == 'sum'): return(tf.reduce_sum(log_prob, axis = -1)) return(tf.reduce_mean(log_prob, axis = -1)) @tf.function def OTDistance(sample, mean, agg = None):
64
64
132
15
49
DoronHav/PyENVI
PyENVI/dists.py
Python
OTDistance
OTDistance
66
77
66
67
34a7e00164349c75b6c651b130203b270b02bb9c
bigcode/the-stack
train
ecd420bc05c7ab37ad1e8618
train
function
@tf.function def NormalKL(mean, log_std, agg = None): KL = 0.5 * (tf.square(mean) + tf.square(tf.exp(log_std)) - 2 * log_std) if(agg is None): return(KL) if(isinstance(agg, (np.ndarray, np.generic))): return(tf.reduce_mean(KL, axis = -1)) if(agg == 'sum'): return(tf.reduc...
@tf.function def NormalKL(mean, log_std, agg = None):
KL = 0.5 * (tf.square(mean) + tf.square(tf.exp(log_std)) - 2 * log_std) if(agg is None): return(KL) if(isinstance(agg, (np.ndarray, np.generic))): return(tf.reduce_mean(KL, axis = -1)) if(agg == 'sum'): return(tf.reduce_sum(KL, axis = -1)) return(tf.reduce_mean(KL, axis ...
return(tf.reduce_mean(KL, axis = -1)) if(agg == 'sum'): return(tf.reduce_sum(KL, axis = -1)) return(tf.reduce_mean(KL, axis = -1)) @tf.function def NormalKL(mean, log_std, agg = None):
62
64
119
16
46
DoronHav/PyENVI
PyENVI/dists.py
Python
NormalKL
NormalKL
17
27
17
18
860165fbd01953039dd58f94f4e54e5ceec92859
bigcode/the-stack
train
cf3b5959c5239adb0294936a
train
function
@tf.function def log_normal_pdf(sample, mean, scale, agg = None): log_prob = tfp.distributions.Normal(loc = mean, scale = tf.exp(scale)).log_prob(sample) if(agg is None): return(log_prob) if(isinstance(agg, (np.ndarray, np.generic))): return(tf.reduce_mean(log_prob * agg[None, :log_prob....
@tf.function def log_normal_pdf(sample, mean, scale, agg = None):
log_prob = tfp.distributions.Normal(loc = mean, scale = tf.exp(scale)).log_prob(sample) if(agg is None): return(log_prob) if(isinstance(agg, (np.ndarray, np.generic))): return(tf.reduce_mean(log_prob * agg[None, :log_prob.shape[-1]], axis = -1)) if(agg == 'sum'): return(tf.reduce...
return(tf.reduce_mean(log_prob, axis = -1)) if(agg == 'sum'): return(tf.reduce_sum(log_prob, axis = -1)) return(tf.reduce_mean(log_prob, axis = -1)) @tf.function def log_normal_pdf(sample, mean, scale, agg = None):
64
64
126
18
46
DoronHav/PyENVI
PyENVI/dists.py
Python
log_normal_pdf
log_normal_pdf
79
88
79
80
7f5a0840c9cc7263a5dc43c21643ce7800fb024e
bigcode/the-stack
train
ef89519d970c9247818a308f
train
function
@tf.function def log_wish_pdf(sample, scale, agg = 'mean'): if(agg == 'mean'): return(tfp.distributions.WishartTriL(df = sample.shape[-1], scale_tril = scale, input_output_cholesky = True).log_prob(sample)/(sample.shape[-1] ** 2)) elif(agg == 'mean'): return(tfp.distributions.WishartTriL(df = sa...
@tf.function def log_wish_pdf(sample, scale, agg = 'mean'):
if(agg == 'mean'): return(tfp.distributions.WishartTriL(df = sample.shape[-1], scale_tril = scale, input_output_cholesky = True).log_prob(sample)/(sample.shape[-1] ** 2)) elif(agg == 'mean'): return(tfp.distributions.WishartTriL(df = sample.shape[-1], scale_tril = scale, input_output_cholesky = ...
= -1)) return(tf.reduce_mean(log_prob, axis = -1)) @tf.function def trace_log(Mat): return(tf.reduce_mean(tf.math.log(tf.linalg.diag_part(Mat)), axis = -1)) @tf.function def log_wish_pdf(sample, scale, agg = 'mean'):
64
64
115
18
46
DoronHav/PyENVI
PyENVI/dists.py
Python
log_wish_pdf
log_wish_pdf
94
99
94
95
f8f7f8f2db857de2cbd15f833cfb00d6234f99fa
bigcode/the-stack
train
5ac01737b18e196dc7f7829b
train
function
@tf.function def log_zinb_pdf(sample, r, p, d, agg = None): log_prob = tfp.distributions.Mixture( cat=tfp.distributions.Categorical(probs=tf.stack([d, 1-d], -1)), components=[tfp.distributions.Deterministic(loc = tf.zeros_like(d)), tfp.distributions.NegativeBinomial(total_count = r, logits = p)]).lo...
@tf.function def log_zinb_pdf(sample, r, p, d, agg = None):
log_prob = tfp.distributions.Mixture( cat=tfp.distributions.Categorical(probs=tf.stack([d, 1-d], -1)), components=[tfp.distributions.Deterministic(loc = tf.zeros_like(d)), tfp.distributions.NegativeBinomial(total_count = r, logits = p)]).log_prob(sample) if(agg is None): return(log...
[-1]], axis = -1)) if(agg == 'sum'): return(tf.reduce_sum(log_prob, axis = -1)) return(tf.reduce_mean(log_prob, axis = -1)) @tf.function def log_zinb_pdf(sample, r, p, d, agg = None):
64
64
181
22
42
DoronHav/PyENVI
PyENVI/dists.py
Python
log_zinb_pdf
log_zinb_pdf
51
64
51
52
ca1ba59b8058208bd5933af821783b05a2c9e024
bigcode/the-stack
train
74f105c5f480dda4273cd5b9
train
function
@tf.function def trace_log(Mat): return(tf.reduce_mean(tf.math.log(tf.linalg.diag_part(Mat)), axis = -1))
@tf.function def trace_log(Mat):
return(tf.reduce_mean(tf.math.log(tf.linalg.diag_part(Mat)), axis = -1))
.reduce_mean(log_prob * agg[None, :log_prob.shape[-1]], axis = -1)) if(agg == 'sum'): return(tf.reduce_sum(log_prob, axis = -1)) return(tf.reduce_mean(log_prob, axis = -1)) @tf.function def trace_log(Mat):
64
64
29
9
55
DoronHav/PyENVI
PyENVI/dists.py
Python
trace_log
trace_log
90
92
90
91
cb6f93103672be12d74bfb50d49e98b86951d39f
bigcode/the-stack
train
7f01d9f6aa4227926eaca862
train
function
@tf.function def LogNormalKL(mean, log_std, agg = None): KL = 0.5 * (tf.square(mean) + tf.square(tf.exp(log_std)) - 2 * log_std) if(agg is None): return(KL) if(isinstance(agg, (np.ndarray, np.generic))): return(tf.reduce_mean(KL, axis = -1)) if(agg == 'sum'): return(tf.reduce_sum...
@tf.function def LogNormalKL(mean, log_std, agg = None):
KL = 0.5 * (tf.square(mean) + tf.square(tf.exp(log_std)) - 2 * log_std) if(agg is None): return(KL) if(isinstance(agg, (np.ndarray, np.generic))): return(tf.reduce_mean(KL, axis = -1)) if(agg == 'sum'): return(tf.reduce_sum(KL, axis = -1)) return(tf.reduce_mean(KL, axis = -1)...
import tensorflow as tf import tensorflow_probability as tfp import numpy as np @tf.function def LogNormalKL(mean, log_std, agg = None):
34
64
119
17
16
DoronHav/PyENVI
PyENVI/dists.py
Python
LogNormalKL
LogNormalKL
5
14
5
6
3a5e770dd655109f81c1061318e72eba8867b04f
bigcode/the-stack
train
1c75ae376795e5ebbc3dfae2
train
class
class Config(object): # I need this to keep the name defined to load the config objects from model checkpoints. def __init__(self, to_log=True): pass
class Config(object): # I need this to keep the name defined to load the config objects from model checkpoints.
def __init__(self, to_log=True): pass
.captioning_epoch_loops import greedy_decoder from typing import Dict, List, Union import cv2 #元コードに存在しない import json #元コードに存在しない class Config(object): # I need this to keep the name defined to load the config objects from model checkpoints.
64
64
37
23
40
textcunma/DVC-fromRawVideo
single_video_prediction.py
Python
Config
Config
44
47
44
45
acc148987f486b69ccc9864b355619ddaf31f8ee
bigcode/the-stack
train
c86197dc97a5fb559b55e79e
train
class
class inference(): def __init__(self,videoname,number): """ :param videoname: 入力動画の名前(拡張子は不要) :param number: 1つの動画に対する最大イベント提案数 """ # 入力動画の尺を取得 cap = cv2.VideoCapture("../inputs/"+videoname+".mp4") #動画を取得 video_frame_count = cap.get(cv2.CAP_PROP_FRAM...
class inference():
def __init__(self,videoname,number): """ :param videoname: 入力動画の名前(拡張子は不要) :param number: 1つの動画に対する最大イベント提案数 """ # 入力動画の尺を取得 cap = cv2.VideoCapture("../inputs/"+videoname+".mp4") #動画を取得 video_frame_count = cap.get(cv2.CAP_PROP_FRAME_COUNT) #全フレーム数を...
import numpy as np import torch import os import sys os.chdir('./BMT/') # カレントディレクトリ変更 sys.path.append(".") #モジュール検索パスを追加 from datasets.captioning_dataset import ActivityNetCaptionsDataset from datasets.load_features import crop_a_segment, pad_segment from epoch_loops.captioning_epoch_loops import make_masks from m...
256
256
3,289
3
252
textcunma/DVC-fromRawVideo
single_video_prediction.py
Python
inference
inference
51
349
51
51
5d89a92cd7bc0f397a6794f5ba5c8370868b1839
bigcode/the-stack
train
9100005fe19531a64584814c
train
function
def pad_sents(sents, padding_token_index): """ Pad the sents(in word index form) into same length so they can form a matrix # 15447 >>> sents = [[1,2,3], [1,2], [1,2,3,4,5]] >>> pad_sents(sents, padding_token_index = -1) [[1, 2, 3, -1, -1], [1, 2, -1, -1, -1], [1, 2, 3, 4, 5]] ...
def pad_sents(sents, padding_token_index):
""" Pad the sents(in word index form) into same length so they can form a matrix # 15447 >>> sents = [[1,2,3], [1,2], [1,2,3,4,5]] >>> pad_sents(sents, padding_token_index = -1) [[1, 2, 3, -1, -1], [1, 2, -1, -1, -1], [1, 2, 3, 4, 5]] """ max_len_sent = max(sents, ...
(words, word2index) [0, 1, 2] """ return [word2index[w] for w in words if word2index.get(w) is not None # filter out those unknown ] def pad_sents(sents, padding_token_index):
63
64
205
11
52
Rohitmaan2012/Twitter_Sentiment_Analysis
sentiment.py
Python
pad_sents
pad_sents
26
43
26
26
2271a14179699e250807eac98bee08985e73f232
bigcode/the-stack
train
8d69ee311bfb8c0f818966ff
train
function
def sentiment_scores_of_sents(sents): """ Predict the sentiment positive scores for a bunch of sentences >>> sentiment_scores_of_sents([u'simultaneously heart breaking and very funny , the last kiss is really all about performances .', u'( u ) stupid .']) array([ 0.78528505, 0.0455901 ]) ...
def sentiment_scores_of_sents(sents):
""" Predict the sentiment positive scores for a bunch of sentences >>> sentiment_scores_of_sents([u'simultaneously heart breaking and very funny , the last kiss is really all about performances .', u'( u ) stupid .']) array([ 0.78528505, 0.0455901 ]) """ word_indices = [get_word_inde...
,,ebd_dm=48,,l2_regs=1e-06,1e-06,1e-06,0.0001,,dr=0.5,0.5,,nkerns=7,12.pkl") MODEL = DCNN(params) def sentiment_scores_of_sents(sents):
64
64
158
9
55
Rohitmaan2012/Twitter_Sentiment_Analysis
sentiment.py
Python
sentiment_scores_of_sents
sentiment_scores_of_sents
56
73
56
56
c23c0349811c3dc1f857f9f282822d9b63eff948
bigcode/the-stack
train
fd2404492671a547407b3eab
train
function
def sentiment_score(sent): """simple wrapper around the more general case""" return sentiment_scores_of_sents([sent])[0]
def sentiment_score(sent):
"""simple wrapper around the more general case""" return sentiment_scores_of_sents([sent])[0]
for sent in sents] x = np.asarray( pad_sents(word_indices, PADDING_INDEX), dtype = np.int32 ) scores = MODEL._p_y_given_x(x) return scores[:, 1] # return `positiveness` def sentiment_score(sent):
63
64
27
5
58
Rohitmaan2012/Twitter_Sentiment_Analysis
sentiment.py
Python
sentiment_score
sentiment_score
76
78
76
76
ef2500a11515378c76118c3e0520199108f123c3
bigcode/the-stack
train
dec13264e10270e18418c5c1
train
function
def get_word_index_array(words, word2index): u""" Transform the words into list of int(word index) Note: Unknown words are dropped >>> words = [u"I", u"love", u"you", u"RANDOM STUFF"] >>> word2index = {u"I": 0, u"love": 1, u"you": 2} >>> get_word_index_array(words, word2index) ...
def get_word_index_array(words, word2index):
u""" Transform the words into list of int(word index) Note: Unknown words are dropped >>> words = [u"I", u"love", u"you", u"RANDOM STUFF"] >>> word2index = {u"I": 0, u"love": 1, u"you": 2} >>> get_word_index_array(words, word2index) [0, 1, 2] """ return [word2inde...
""" Sentiment prediction module """ import nltk import numpy as np from cPickle import load def get_word_index_array(words, word2index):
33
64
142
11
21
Rohitmaan2012/Twitter_Sentiment_Analysis
sentiment.py
Python
get_word_index_array
get_word_index_array
9
23
9
9
05c0f7ed1897d092f8fb7814c888a369ec63666e
bigcode/the-stack
train
f74cd21759ec2968a23c8c82
train
function
def generate_launch_description(): ld = launch.LaunchDescription([ launch.actions.DeclareLaunchArgument( name='role_name', default_value='ego_vehicle' ), launch.actions.DeclareLaunchArgument( name='control_loop_rate', default_value='0.05' ...
def generate_launch_description():
ld = launch.LaunchDescription([ launch.actions.DeclareLaunchArgument( name='role_name', default_value='ego_vehicle' ), launch.actions.DeclareLaunchArgument( name='control_loop_rate', default_value='0.05' ), launch_ros.actions.No...
from pathlib import Path import launch import launch_ros.actions from ament_index_python.packages import get_package_share_directory def generate_launch_description():
31
64
169
5
25
umateusz/ros-bridge
carla_ackermann_control/launch/carla_ackermann_control.launch.py
Python
generate_launch_description
generate_launch_description
8
32
8
8
4ebf2425abbfaa1f002beffb20910c3e3bb61d43
bigcode/the-stack
train
4e5dfaa68a88ec0356acb8b5
train
class
class ValidationResult: """Metadata object representing the validation result of a single rule of an expectation result of a Feature Group.""" def __init__( self, status, message, value, features, rule, href=None, expand=None, items=None, ...
class ValidationResult:
"""Metadata object representing the validation result of a single rule of an expectation result of a Feature Group.""" def __init__( self, status, message, value, features, rule, href=None, expand=None, items=None, count=None, ...
# # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distr...
147
147
491
4
142
kouzant/feature-store-api
python/hsfs/validation_result.py
Python
ValidationResult
ValidationResult
23
109
23
23
ee1aed5a5cae72cb65c4a6e6063ff1de60ec1512
bigcode/the-stack
train
543efeef6ee3801bef9c4c14
train
class
class Solution(object): def minMutation(self, start, end, bank): """ :type start: str :type end: str :type bank: List[str] :rtype: int """ lookup = {} for b in bank: lookup[b] = False q = deque([(start, 0)]) while q: ...
class Solution(object):
def minMutation(self, start, end, bank): """ :type start: str :type end: str :type bank: List[str] :rtype: int """ lookup = {} for b in bank: lookup[b] = False q = deque([(start, 0)]) while q: cur, level = q.pop...
# Time: O(n * b), n is the length of gene string, b is size of bank # Space: O(b) from collections import deque class Solution(object):
38
64
187
4
33
Sourav692/FAANG-Interview-Preparation
Algo and DSA/LeetCode-Solutions-master/Python/minimum-genetic-mutation.py
Python
Solution
Solution
6
34
6
6
a6a90183e55169d7fbf2a47afc9e106e4e793080
bigcode/the-stack
train
054647d5f4a1ce845673902a
train
function
def plot_innerprod(current_data): return current_data.aux[2,:,:]
def plot_innerprod(current_data):
return current_data.aux[2,:,:]
plotdata.latex_figsperline = 2 # layout of plots plotdata.latex_framesperline = 1 # layout of plots plotdata.latex_makepdf = False # also run pdflatex? return plotdata def plot_innerprod(current_data):
64
64
17
7
56
rjleveque/adjoint
paper2_examples/acoustics_2d_ex3/setplot.py
Python
plot_innerprod
plot_innerprod
138
139
138
138
b78f9cd348854222797a6aec6b7055124579787b
bigcode/the-stack
train
58ce04f80da556019ccc5d00
train
function
def fixup(current_data): import pylab from pylab import plot size = 28 plot_rectangle(current_data) # Uncomment this line if you want to generate plots without a title for the paper #pylab.title(' ') pylab.xticks([-8, -4, 0, 4, 8], fontsize=size) pylab.yticks([0, 5, 10], fontsize=size) ...
def fixup(current_data):
import pylab from pylab import plot size = 28 plot_rectangle(current_data) # Uncomment this line if you want to generate plots without a title for the paper #pylab.title(' ') pylab.xticks([-8, -4, 0, 4, 8], fontsize=size) pylab.yticks([0, 5, 10], fontsize=size) plot([0., 0.], [-1000....
# Afteraxis functions: def addgauges(current_data): from clawpack.visclaw import gaugetools gaugetools.plot_gauge_locations(current_data.plotdata, \ gaugenos='all', format_string='ko', add_labels=True, fontsize=14) def fixup(current_data):
64
64
118
6
58
rjleveque/adjoint
paper2_examples/acoustics_2d_ex3/setplot.py
Python
fixup
fixup
148
157
148
148
f9e424e575eaa7c52fb53a0079fa19d658e766c9
bigcode/the-stack
train
c79b89db5e87fc17ccfc9334
train
function
def fixup_gauge(current_data): import pylab size = 34 pylab.title('Pressure at Gauge 0', fontsize=size) pylab.xticks([0.0, 1.5, 2.0, 2.5, 3.0], fontsize=size) pylab.yticks([-0.3, -0.1, 0.1, 0.3, 0.5], fontsize=size)
def fixup_gauge(current_data):
import pylab size = 34 pylab.title('Pressure at Gauge 0', fontsize=size) pylab.xticks([0.0, 1.5, 2.0, 2.5, 3.0], fontsize=size) pylab.yticks([-0.3, -0.1, 0.1, 0.3, 0.5], fontsize=size)
8, -4, 0, 4, 8], fontsize=size) pylab.yticks([0, 5, 10], fontsize=size) plot([0., 0.], [-1000., 1000.], 'k--') def fixup_gauge(current_data):
64
64
99
8
56
rjleveque/adjoint
paper2_examples/acoustics_2d_ex3/setplot.py
Python
fixup_gauge
fixup_gauge
168
173
168
168
22f5835b31c763f49210bd2676434f6b49dc608f
bigcode/the-stack
train
fdf97f2c02a5e7fd4a4935f7
train
function
def setplot(plotdata): #-------------------------- """ Specify what is to be plotted at each frame. Input: plotdata, an instance of clawpack.visclaw.data.ClawPlotData. Output: a modified version of plotdata. """ from clawpack.visclaw import colormaps plotdata.clearfigures() #...
def setplot(plotdata): #--------------------------
""" Specify what is to be plotted at each frame. Input: plotdata, an instance of clawpack.visclaw.data.ClawPlotData. Output: a modified version of plotdata. """ from clawpack.visclaw import colormaps plotdata.clearfigures() # clear any old figures,axes,items data plotdata.form...
""" Set up the plot figures, axes, and items to be done for each frame. This module is imported by the plotting routines and then the function setplot is called to set the plot parameters. """ #-------------------------- def setplot(plotdata): #--------------------------
58
256
1,383
10
48
rjleveque/adjoint
paper2_examples/acoustics_2d_ex3/setplot.py
Python
setplot
setplot
11
136
11
13
57072bfc3b9df883b6cb8d1e577d6ba90ab75fea
bigcode/the-stack
train
40bc95b2773670750fca2ba3
train
function
def plot_rectangle(current_data): from clawpack.visclaw.plottools import plotbox x1 = 0.68; x2 = 1.32; y1 = 5.26; y2 = 5.74 xy = [x1, x2, y1, y2] plotbox(xy, kwargs={'color': 'k', 'linewidth': 2})
def plot_rectangle(current_data):
from clawpack.visclaw.plottools import plotbox x1 = 0.68; x2 = 1.32; y1 = 5.26; y2 = 5.74 xy = [x1, x2, y1, y2] plotbox(xy, kwargs={'color': 'k', 'linewidth': 2})
0, 1.5, 2.0, 2.5, 3.0], fontsize=size) pylab.yticks([-0.3, -0.1, 0.1, 0.3, 0.5], fontsize=size) def plot_rectangle(current_data):
64
64
87
6
58
rjleveque/adjoint
paper2_examples/acoustics_2d_ex3/setplot.py
Python
plot_rectangle
plot_rectangle
175
179
175
175
74d3954a501952065d0befc25f0830ecc8e88acd
bigcode/the-stack
train
5f3af587f4e3dd27753bd01a
train
function
def addgauges(current_data): from clawpack.visclaw import gaugetools gaugetools.plot_gauge_locations(current_data.plotdata, \ gaugenos='all', format_string='ko', add_labels=True, fontsize=14)
def addgauges(current_data):
from clawpack.visclaw import gaugetools gaugetools.plot_gauge_locations(current_data.plotdata, \ gaugenos='all', format_string='ko', add_labels=True, fontsize=14)
atex_framesperline = 1 # layout of plots plotdata.latex_makepdf = False # also run pdflatex? return plotdata def plot_innerprod(current_data): return current_data.aux[2,:,:] # Afteraxis functions: def addgauges(current_data):
64
64
53
7
57
rjleveque/adjoint
paper2_examples/acoustics_2d_ex3/setplot.py
Python
addgauges
addgauges
143
146
143
143
914edb8e63a3a63369d4d1815dc55d98d8037159
bigcode/the-stack
train
5e2a7d8d8f4db39c516c238e
train
function
def fixup_innerprod(current_data): import pylab from pylab import plot size = 28 plot_rectangle(current_data) pylab.xticks([-8, -4, 0, 4, 8], fontsize=size) pylab.yticks([0, 5, 10], fontsize=size) plot([0., 0.], [-1000., 1000.], 'k--')
def fixup_innerprod(current_data):
import pylab from pylab import plot size = 28 plot_rectangle(current_data) pylab.xticks([-8, -4, 0, 4, 8], fontsize=size) pylab.yticks([0, 5, 10], fontsize=size) plot([0., 0.], [-1000., 1000.], 'k--')
8, -4, 0, 4, 8], fontsize=size) pylab.yticks([0, 5, 10], fontsize=size) plot([0., 0.], [-1000., 1000.], 'k--') def fixup_innerprod(current_data):
64
64
94
8
56
rjleveque/adjoint
paper2_examples/acoustics_2d_ex3/setplot.py
Python
fixup_innerprod
fixup_innerprod
159
166
159
159
5fb2c396853b000d2ad7c6b8fe1167abba4c1ef5
bigcode/the-stack
train
7b7f5dddb40cfaeb299eb6c6
train
function
def hints(env: PysmtEnv) -> FrozenSet[Hint]: assert isinstance(env, PysmtEnv) mgr = env.formula_manager pc = mgr.Symbol("pc", types.INT) x = mgr.Symbol("x", types.INT) y = mgr.Symbol("y", types.INT) symbs = frozenset([pc, x, y]) m_100 = mgr.Int(-100) m_1 = mgr.Int(-1) i_0 = mgr.Int...
def hints(env: PysmtEnv) -> FrozenSet[Hint]:
assert isinstance(env, PysmtEnv) mgr = env.formula_manager pc = mgr.Symbol("pc", types.INT) x = mgr.Symbol("x", types.INT) y = mgr.Symbol("y", types.INT) symbs = frozenset([pc, x, y]) m_100 = mgr.Int(-100) m_1 = mgr.Int(-1) i_0 = mgr.Int(0) i_1 = mgr.Int(1) i_2 = mgr.Int(2)...
= -1 cfg.append(mgr.Implies(pcend, x_pcend)) trans = [] same_x = mgr.Equals(x_x, x) same_y = mgr.Equals(x_y, y) same = mgr.And(same_x, same_y) # pc = 0 -> same trans.append(mgr.Implies(pcs[0], same)) # pc = 1 -> x' = x + y & same_y trans.append(mgr.Implies(pcs[1], ...
256
256
2,276
15
240
EnricoMagnago/F3
benchmarks/f3_wrong_hints/scaling_software_termination/18-2Nested_false-termination_16.py
Python
hints
hints
84
266
84
84
f0748b17bf8821e0b6ee8ade232a24f80a0754a3
bigcode/the-stack
train
13dbc31730746897f49bf772
train
function
def transition_system(env: PysmtEnv) -> Tuple[FrozenSet[FNode], FNode, FNode, FNode]: assert isinstance(env, PysmtEnv) mgr = env.formula_manager pc = mgr.Symbol("pc", types.INT) x = mgr.Symbol("x", types.INT) y = mgr.Symbol("y", types.INT) x_pc = sym...
def transition_system(env: PysmtEnv) -> Tuple[FrozenSet[FNode], FNode, FNode, FNode]:
assert isinstance(env, PysmtEnv) mgr = env.formula_manager pc = mgr.Symbol("pc", types.INT) x = mgr.Symbol("x", types.INT) y = mgr.Symbol("y", types.INT) x_pc = symb_to_next(mgr, pc) x_x = symb_to_next(mgr, x) x_y = symb_to_next(mgr, y) symbols = frozenset([pc, x, y]) m_1 = mgr...
from typing import Tuple, FrozenSet from pysmt.environment import Environment as PysmtEnv from pysmt.fnode import FNode import pysmt.typing as types from utils import symb_to_next from hint import Hint, Location def transition_system(env: PysmtEnv) -> Tuple[FrozenSet[FNode], FNode, FNode, ...
80
207
690
28
51
EnricoMagnago/F3
benchmarks/f3_wrong_hints/scaling_software_termination/18-2Nested_false-termination_16.py
Python
transition_system
transition_system
11
81
11
12
ee7d9122ed3dd418f18e1c09634da5f16f30d0d1
bigcode/the-stack
train
ebd055a1ccdb3b0b74608883
train
function
def generate_fiducial_alignment_directive( tilt_series_file: PathLike, pixel_size: float, fiducial_size: float, rotation_angle: float ) -> Dict[str, Any]: """Generate a fiducial-based alignment directive file for batchruntomo Parameters ---------- tilt_series_file : file...
def generate_fiducial_alignment_directive( tilt_series_file: PathLike, pixel_size: float, fiducial_size: float, rotation_angle: float ) -> Dict[str, Any]:
"""Generate a fiducial-based alignment directive file for batchruntomo Parameters ---------- tilt_series_file : file containing the tilt-series stack pixel_size : pixel size in the tilt-series (angstroms per pixel) fiducial_size : fiducial size (nanometers) rotation_angle : initial estimate...
, rotation_angle=nominal_rotation_angle ) run_batchruntomo( tilt_series_file=tilt_series_file, imod_directory=output_directory, directive=directive ) def generate_fiducial_alignment_directive( tilt_series_file: PathLike, pixel_size: float, fiducial_siz...
88
88
294
45
43
alisterburt/yet-another-imod-wrapper
yet_another_imod_wrapper/fiducials.py
Python
generate_fiducial_alignment_directive
generate_fiducial_alignment_directive
66
91
66
71
3d583caaed819b3017ee10d12271859ec0530b75
bigcode/the-stack
train
17351628bea817890bc6388e
train
function
def run_fiducial_based_alignment( tilt_series_file: Path, tilt_angles: List[float], pixel_size: float, fiducial_size: float, nominal_rotation_angle: float, output_directory: Path, ): """Run fiducial based alignment in IMOD on a single tilt-series. Parameters ...
def run_fiducial_based_alignment( tilt_series_file: Path, tilt_angles: List[float], pixel_size: float, fiducial_size: float, nominal_rotation_angle: float, output_directory: Path, ):
"""Run fiducial based alignment in IMOD on a single tilt-series. Parameters ---------- tilt_series_file: file containing tilt-series images. File must be compatible with the version of IMOD installed. tilt_angles: nominal stage tilt-angles from the microscope. pixel_size: nominal pixel ...
_ALIGNMENT, BATCHRUNTOMO_CONFIG_FIDUCIALS, REQUIRED_IMOD_VERSION from .utils import ( find_optimal_power_of_2_binning_factor, prepare_imod_directory, run_batchruntomo, imod_is_installed, get_imod_version ) console = Console(record=True) def run_fiducial_based_alignment( tilt_series_file: Pa...
120
120
403
52
68
alisterburt/yet-another-imod-wrapper
yet_another_imod_wrapper/fiducials.py
Python
run_fiducial_based_alignment
run_fiducial_based_alignment
19
63
19
26
d7fe1e397c40fa7ae6107c06ddc79cba2183e437
bigcode/the-stack
train
7b2bcf6c30dde8e5343aa9bd
train
class
class ConversationModelManagersTest(TestCase): @classmethod def setUpTestData(cls): cls.generic_superuser = Author.objects.create( username=settings.GENERIC_SUPERUSER_USERNAME, email="gsu", is_active=True ) cls.author_1 = Author.objects.create(username="a1", email="1", is_act...
class ConversationModelManagersTest(TestCase): @classmethod
def setUpTestData(cls): cls.generic_superuser = Author.objects.create( username=settings.GENERIC_SUPERUSER_USERNAME, email="gsu", is_active=True ) cls.author_1 = Author.objects.create(username="a1", email="1", is_active=True) cls.author_2 = Author.objects.create(username=...
.novice_eb) cls.entry_by_author_draft = Entry.objects.create(**cls.author_eb, is_draft=True) cls.entry_by_novice_draft = Entry.objects.create(**cls.novice_eb, is_draft=True) def test_objects(self): # Published AND Non-novice entries queryset = Entry.objects.all() self.asse...
256
256
1,261
12
244
ankitgc1/django-sozluk-master
dictionary/tests/test_model_managers.py
Python
ConversationModelManagersTest
ConversationModelManagersTest
50
143
50
51
97e0edaf90053a17fdd94a8317bab07033cee57b
bigcode/the-stack
train
f35ae04bad35109be6896ff9
train
class
class TopicModelManagersTest(TransactionTestCase): @classmethod def setUp(cls): cls.author = Author.objects.create(username="user666", email="666", is_novice=False) cls.novice = Author.objects.create(username="user333", email="333") cls.topic_1 = Topic.objects.create_topic("şeker çocuk"...
class TopicModelManagersTest(TransactionTestCase): @classmethod
def setUp(cls): cls.author = Author.objects.create(username="user666", email="666", is_novice=False) cls.novice = Author.objects.create(username="user333", email="333") cls.topic_1 = Topic.objects.create_topic("şeker çocuk", created_by=cls.author) # slug -> seker-cocuk cls.topic_2 ...
.count()) def test_with_user(self): # Self-conversation is not allowed self_convo = Conversation.objects.with_user(self.author_1, self.author_1) self.assertIsNone(self_convo) conversation_1_2 = Conversation.objects.with_user(self.author_1, self.author_2) self.assertEqual(co...
208
208
695
13
195
ankitgc1/django-sozluk-master
dictionary/tests/test_model_managers.py
Python
TopicModelManagersTest
TopicModelManagersTest
146
213
146
147
3dfdc5d28a3442f4d9e6043d5a3ababf678062a3
bigcode/the-stack
train
f440c1648f5dd1330f76a879
train
class
class EntryModelManagersTests(TestCase): @classmethod def setUpTestData(cls): cls.topic = Topic.objects.create_topic("topik") cls.author = Author.objects.create(username="author", email="0", is_novice=False) cls.novice = Author.objects.create(username="novice", email="1") cls.au...
class EntryModelManagersTests(TestCase): @classmethod
def setUpTestData(cls): cls.topic = Topic.objects.create_topic("topik") cls.author = Author.objects.create(username="author", email="0", is_novice=False) cls.novice = Author.objects.create(username="novice", email="1") cls.author_eb = {"topic": cls.topic, "author": cls.author} ...
from django.http import Http404 from django.test import TestCase, TransactionTestCase from dictionary.conf import settings from dictionary.models import Author, Entry, Conversation, Message, Topic class EntryModelManagersTests(TestCase): @classmethod
50
114
383
12
37
ankitgc1/django-sozluk-master
dictionary/tests/test_model_managers.py
Python
EntryModelManagersTests
EntryModelManagersTests
8
47
8
9
6912d4322ef7d7df15ccaea703771f1a56c2d060
bigcode/the-stack
train
b0ec113d091f768decd1a50f
train
class
@dataclass class OrderItem(OrderCommon): @dataclass class ItemInOrder(ModelBase): @dataclass class LangInOrderItem: item_name: str id: str url_name: str icon: str thumb: str sub_icon: Optional[str] quantity_for_set: Optional[int] ...
@dataclass class OrderItem(OrderCommon): @dataclass
class ItemInOrder(ModelBase): @dataclass class LangInOrderItem: item_name: str id: str url_name: str icon: str thumb: str sub_icon: Optional[str] quantity_for_set: Optional[int] mod_max_rank: Optional[int] # only for relics...
: int order_type: OrderType platform: Platform region: Optional[str] creation_date: Optional[datetime] closed_date: Optional[datetime] last_update: Optional[datetime] visible: bool @dataclass class OrderRow(OrderCommon): user: UserShort @dataclass class OrderItem(OrderCommon): @dat...
79
79
264
14
64
leonardodalinky/pywmapi
src/pywmapi/orders/models.py
Python
OrderItem
OrderItem
42
77
42
44
97cdefdbcb464193559cb884c4128fdef27d749c
bigcode/the-stack
train
d99083112ce5a1a863e1bde2
train
class
@dataclass class OrderCommon(ModelBase): id: str platinum: int quantity: int order_type: OrderType platform: Platform region: Optional[str] creation_date: Optional[datetime] closed_date: Optional[datetime] last_update: Optional[datetime] visible: bool
@dataclass class OrderCommon(ModelBase):
id: str platinum: int quantity: int order_type: OrderType platform: Platform region: Optional[str] creation_date: Optional[datetime] closed_date: Optional[datetime] last_update: Optional[datetime] visible: bool
..common import * __all__ = [ "OrderType", "OrderCommon", "OrderRow", "OrderItem", # "OrderFull", "OrderNewItemBase", "OrderNewItem", "OrderUpdateItem", ] @dataclass class OrderCommon(ModelBase):
64
64
71
9
55
leonardodalinky/pywmapi
src/pywmapi/orders/models.py
Python
OrderCommon
OrderCommon
23
34
23
24
6c885ccebc58f8b3fc3f8c42e0f8730a4d07c6ef
bigcode/the-stack
train
0f8c8a9e7df9d27f30f8a90d
train
class
@dataclass class OrderNewItem(OrderNewItemBase): """ Request class for ``orders.add_new_order`` and others. """ item_id: str order_type: OrderType
@dataclass class OrderNewItem(OrderNewItemBase):
""" Request class for ``orders.add_new_order`` and others. """ item_id: str order_type: OrderType
(OrderRow): # TODO def __init__(self): raise NotImplementedError() @dataclass class OrderNewItemBase(ModelBase): platinum: int quantity: int rank: Optional[int] visible: bool @dataclass class OrderNewItem(OrderNewItemBase):
64
64
42
12
51
leonardodalinky/pywmapi
src/pywmapi/orders/models.py
Python
OrderNewItem
OrderNewItem
95
102
95
96
53cf62faba71038b2769d65c9d78a0874578cfd6
bigcode/the-stack
train
d096d3ba979d93f4cade93bd
train
class
@dataclass class OrderNewItemBase(ModelBase): platinum: int quantity: int rank: Optional[int] visible: bool
@dataclass class OrderNewItemBase(ModelBase):
platinum: int quantity: int rank: Optional[int] visible: bool
Item] pl: Optional[LangInOrderItem] user: Optional[UserShort] item: ItemInOrder @dataclass class OrderFull(OrderRow): # TODO def __init__(self): raise NotImplementedError() @dataclass class OrderNewItemBase(ModelBase):
64
64
32
11
53
leonardodalinky/pywmapi
src/pywmapi/orders/models.py
Python
OrderNewItemBase
OrderNewItemBase
87
92
87
88
c0d0f04f6d401fa1d4a62af9b0215b724534e21f
bigcode/the-stack
train
94e36834a454a460d683fc06
train
class
@dataclass class OrderUpdateItem(OrderNewItemBase): """ Request class for ``orders.update_order`` """ pass
@dataclass class OrderUpdateItem(OrderNewItemBase):
""" Request class for ``orders.update_order`` """ pass
rank: Optional[int] visible: bool @dataclass class OrderNewItem(OrderNewItemBase): """ Request class for ``orders.add_new_order`` and others. """ item_id: str order_type: OrderType @dataclass class OrderUpdateItem(OrderNewItemBase):
64
64
29
12
51
leonardodalinky/pywmapi
src/pywmapi/orders/models.py
Python
OrderUpdateItem
OrderUpdateItem
105
111
105
106
1e822e13693c872d2baad313b89f19363814acd3
bigcode/the-stack
train
08585415537b68607a8c56de
train
class
@dataclass class OrderRow(OrderCommon): user: UserShort
@dataclass class OrderRow(OrderCommon):
user: UserShort
: int quantity: int order_type: OrderType platform: Platform region: Optional[str] creation_date: Optional[datetime] closed_date: Optional[datetime] last_update: Optional[datetime] visible: bool @dataclass class OrderRow(OrderCommon):
64
64
15
9
54
leonardodalinky/pywmapi
src/pywmapi/orders/models.py
Python
OrderRow
OrderRow
37
39
37
38
3756b0ac3e1096ccbaef742253273221b7259638
bigcode/the-stack
train
2c6e30efd96a023bcd2b3aab
train
class
@dataclass class OrderFull(OrderRow): # TODO def __init__(self): raise NotImplementedError()
@dataclass class OrderFull(OrderRow): # TODO
def __init__(self): raise NotImplementedError()
[LangInOrderItem] es: Optional[LangInOrderItem] it: Optional[LangInOrderItem] pl: Optional[LangInOrderItem] user: Optional[UserShort] item: ItemInOrder @dataclass class OrderFull(OrderRow): # TODO
64
64
26
13
50
leonardodalinky/pywmapi
src/pywmapi/orders/models.py
Python
OrderFull
OrderFull
80
84
80
82
10eec64148972e8f046e4f61c7e1cd2932d38560
bigcode/the-stack
train
bb6e86251631e4d73f3f55b7
train
function
def main(): os.chdir("..") def epochtime(x): string = parse(x) epoch = int(tm.mktime(string.timetuple())) return epoch def parseName(x): inst1 = x.find(">")+2 inst2 = x.find(">", inst1) building = x[inst1:inst2-1].lower() room = x[inst2+...
def main():
os.chdir("..") def epochtime(x): string = parse(x) epoch = int(tm.mktime(string.timetuple())) return epoch def parseName(x): inst1 = x.find(">")+2 inst2 = x.find(">", inst1) building = x[inst1:inst2-1].lower() room = x[inst2+6:] ...
import csv import time as tm import datetime from dateutil.parser import parse import models from linear_model import get_linear_coef import os from app import app import logging #useful for viewing the specific sql queries to debug if app.config['DEBUG']: logger = logging.getLogger('peewee') logger.setLevel(...
86
256
1,078
3
83
DonBlaine/OpenDoorData
application/original_data_entry.py
Python
main
main
18
166
18
18
fe0a9396d80a358257f81476a5123030b7ae6f09
bigcode/the-stack
train
72a34fd29da61d7464715346
train
class
class ContainerBenchmark(Benchmark): """ContainerBenchmark an extension of Benchmark to run benchmarks inside a container. """ @classmethod def image_name(cls, framework_def, label=None, **kwargs): if label is None: label = rget().project_info.branch di = framework_def....
class ContainerBenchmark(Benchmark):
"""ContainerBenchmark an extension of Benchmark to run benchmarks inside a container. """ @classmethod def image_name(cls, framework_def, label=None, **kwargs): if label is None: label = rget().project_info.branch di = framework_def.image author = di.author ...
""" **container** module is build on top of **benchmark** module to provide logic to create and run container images (e.g. docker, singularity) that are preconfigured with a given automl framework, and that can be used to run a benchmark anywhere. The image embeds a version of the automlbenchmark app so that tasks are ...
188
256
1,547
6
182
xiaowu0162/automlbenchmark
amlb/runners/container.py
Python
ContainerBenchmark
ContainerBenchmark
23
196
23
23
ef9a245ae6aee00d658774d60e0195475206b578
bigcode/the-stack
train
bcad76dbd9b40d3840c28cdc
train
class
class Bing(CommonEngine): """Bing Bing用の検索エンジン用Class. """ def __init__(self): # CommonEngineの処理を呼出し super().__init__() self.NAME = 'Bing' self.COLOR = Color.CYAN self.COLOR_NAME = self.COLOR + self.NAME + Color.END # リクエスト先のURLを指定 self.ENGINE_T...
class Bing(CommonEngine):
"""Bing Bing用の検索エンジン用Class. """ def __init__(self): # CommonEngineの処理を呼出し super().__init__() self.NAME = 'Bing' self.COLOR = Color.CYAN self.COLOR_NAME = self.COLOR + self.NAME + Color.END # リクエスト先のURLを指定 self.ENGINE_TOP_URL = 'https://www.bing...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # ======================================================= """engine_bing * Bing用の検索用Classを持つモジュール. """ import requests import datetime import json import asyncio import re from urllib import parse from bs4 import BeautifulSoup from .common import Color from .engin...
86
256
1,931
5
80
blacknon/pydork
pydork/engine_bing.py
Python
Bing
Bing
23
275
23
23
c8b257cb6cbfe64898676c26487688ed82f68c12
bigcode/the-stack
train
6e9d2247a8a5f2578f60b95b
train
function
def resolv_url(session: requests.Session, url: str): """resolv_url リダイレクト先のurlを取得する(Baiduで使用) Args: session (request.Session): リダイレクト先を取得する際に使用するSession url (str): リダイレクト先を取得するurl Returns: url (str): リダイレクト先のurl """ while True: try: # リダイレクト先のbodyを取得す...
def resolv_url(session: requests.Session, url: str):
"""resolv_url リダイレクト先のurlを取得する(Baiduで使用) Args: session (request.Session): リダイレクト先を取得する際に使用するSession url (str): リダイレクト先を取得するurl Returns: url (str): リダイレクト先のurl """ while True: try: # リダイレクト先のbodyを取得する res = session.get(url).text ex...
して処理 if url.netloc == 'www.bing.com' and url.path == '/ck/a': task = req(session, link) tasks.append(task) data = await asyncio.gather(*tasks) return data def resolv_url(session: requests.Session, url: str):
64
64
204
13
50
blacknon/pydork
pydork/engine_bing.py
Python
resolv_url
resolv_url
311
339
311
311
57173f912782f508788d413b1d34cb1d97a93695
bigcode/the-stack
train
79659c5f36b70c3610c1df41
train
function
async def resolv_links(loop: asyncio.AbstractEventLoop, session: requests.Session, links: list): """resolv_links リダイレクト先のurlをパラレルで取得する(Baiduで使用) Args: loop (asyncio.AbstractEventLoop): loop session (requests.Session): 使用するSession links (list): リダイレクト先を取得するurlのリスト Returns: ...
async def resolv_links(loop: asyncio.AbstractEventLoop, session: requests.Session, links: list):
"""resolv_links リダイレクト先のurlをパラレルで取得する(Baiduで使用) Args: loop (asyncio.AbstractEventLoop): loop session (requests.Session): 使用するSession links (list): リダイレクト先を取得するurlのリスト Returns: data (list): リダイレクト先を取得したurlのリスト """ async def req(session: requests.Session, url: s...
# リダイレクト先のurlに置き換え elinks = loop.run_until_complete( resolv_links(loop, session, elinks)) loop.close() return elinks, etitles, etexts async def resolv_links(loop: asyncio.AbstractEventLoop, session: requests.Session, links: list):
72
72
242
21
50
blacknon/pydork
pydork/engine_bing.py
Python
resolv_links
resolv_links
278
308
278
278
b520238472e05e6d5479f75d7fc8e0ee0a279bb0
bigcode/the-stack
train
d7c57ca29d5f712de601323e
train
function
def get_new_IP_address(): '''Generates a new IP address for the device.''' def lastMember(device): return int(device.device_ip.split('.')[3]) used_members = list(map(lastMember, Device.objects.all())) available_IPs = ([ a for a in range(settings.IP_RANGE_START, settings.IP_RANGE_END) ...
def get_new_IP_address():
'''Generates a new IP address for the device.''' def lastMember(device): return int(device.device_ip.split('.')[3]) used_members = list(map(lastMember, Device.objects.all())) available_IPs = ([ a for a in range(settings.IP_RANGE_START, settings.IP_RANGE_END) if a not in used_mem...
from django.conf import settings from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.core.urlresolvers import reverse from django.core.validators import RegexValidator from django.db import models def get_new_IP_address():
51
64
121
6
44
Atilla106/members.atilla.org
network/models/device.py
Python
get_new_IP_address
get_new_IP_address
9
23
9
9
1338471d55490e0a174986c9dd9725a893b0300a
bigcode/the-stack
train
733c489c76f3f658784f90e3
train
class
class Device(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) # Only accept a device name composed of alphanumeric characters, - and _ device_name = models.CharField( max_length=25, validators=[ RegexValidator( regex='^[-a-zA-Z0-9]{1,25}$'...
class Device(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE) # Only accept a device name composed of alphanumeric characters, - and _ device_name = models.CharField( max_length=25, validators=[ RegexValidator( regex='^[-a-zA-Z0-9]{1,25}$', message="Le...
from django.core.urlresolvers import reverse from django.core.validators import RegexValidator from django.db import models def get_new_IP_address(): '''Generates a new IP address for the device.''' def lastMember(device): return int(device.device_ip.split('.')[3]) used_members = list(map(lastMem...
149
149
499
5
144
Atilla106/members.atilla.org
network/models/device.py
Python
Device
Device
26
108
26
27
c718323189a731206f5e2ac3a8b764879526aec4
bigcode/the-stack
train
9177fa619e6b31b800eba6af
train
function
def put_file(team_id, user_id, url, file_data): """ Using put method to get data from given url Args: team_id (string): Slack team ID user_id (string): Slack User ID url (string): Jama API url file_data (dict): The file name and file data wants to be sent to the url Retur...
def put_file(team_id, user_id, url, file_data):
""" Using put method to get data from given url Args: team_id (string): Slack team ID user_id (string): Slack User ID url (string): Jama API url file_data (dict): The file name and file data wants to be sent to the url Returns: (dict): Data get from Jama (...
+ token } response = requests.get(url, headers=header_list) else: response = requests.get(url, auth=(os.environ["JAMA_USER"], os.environ["JAMA_PASS"])) return json.loads(response.text) def put_file(team_id, user_id, url, file_data):
64
64
194
14
50
taishengG/jama-slack-integration
src/jama/api_caller.py
Python
put_file
put_file
62
81
62
62
5fdc47517277e79add89217fc2e481398ead3e55
bigcode/the-stack
train
a21bd9b76b9af648467f90de
train
function
def post(team_id, user_id, url, payload): """ Using post method to get data from given Jama url Args: team_id (string): Slack team ID user_id (string): Slack User ID url (string): Jama API url payload (dict): The dictionary of payload wants to be sent to the url Returns: ...
def post(team_id, user_id, url, payload):
""" Using post method to get data from given Jama url Args: team_id (string): Slack team ID user_id (string): Slack User ID url (string): Jama API url payload (dict): The dictionary of payload wants to be sent to the url Returns: (dict): Data get from Jama ...
from jama import oauth import os import json import requests def is_using_oauth(): return "DB_HOST" in os.environ def post(team_id, user_id, url, payload):
42
64
212
12
29
taishengG/jama-slack-integration
src/jama/api_caller.py
Python
post
post
11
34
11
11
24dee447f18fbba404604039aeed2e31defefe30
bigcode/the-stack
train
ce0bb6c3177c001faaee745c
train
function
def is_using_oauth(): return "DB_HOST" in os.environ
def is_using_oauth():
return "DB_HOST" in os.environ
from jama import oauth import os import json import requests def is_using_oauth():
20
64
16
6
13
taishengG/jama-slack-integration
src/jama/api_caller.py
Python
is_using_oauth
is_using_oauth
7
8
7
7
51c10b960583deaf89d705e20e1759f2f5e0fc40
bigcode/the-stack
train
464d161d74b79f13dbebebeb
train
function
def get(team_id, user_id, url): """ Using get method to get data from given Jama url Args: team_id (string): Slack team ID user_id (string): Slack User ID url (string): Jama API url Returns: (dict): Data get from Jama (None): If fail to get Jama OAuth, return None...
def get(team_id, user_id, url):
""" Using get method to get data from given Jama url Args: team_id (string): Slack team ID user_id (string): Slack User ID url (string): Jama API url Returns: (dict): Data get from Jama (None): If fail to get Jama OAuth, return None """ if is_using_oauth()...
} response = requests.post(url, json=payload, headers=header_list) else: response = requests.post(url, json=payload, auth=(os.environ["JAMA_USER"], os.environ["JAMA_PASS"])) return json.loads(response.text) def get(team_id, user_id, url):
64
64
185
10
54
taishengG/jama-slack-integration
src/jama/api_caller.py
Python
get
get
37
59
37
37
9218c4ea86ffb1cc0479a0916b21fa0177f0bf0d
bigcode/the-stack
train
24bac67585e31dcdf1a98bca
train
function
def get_size(image): size_str = image["size"] i = size_str.find("x") size = (float(size_str[:i]),float(size_str[i+1:])) scale_str = image["scale"] j = scale_str.find("x") scale = int(scale_str[:j]) return (int(scale * float(size[0])), int(scale * float(size[1])))
def get_size(image):
size_str = image["size"] i = size_str.find("x") size = (float(size_str[:i]),float(size_str[i+1:])) scale_str = image["scale"] j = scale_str.find("x") scale = int(scale_str[:j]) return (int(scale * float(size[0])), int(scale * float(size[1])))
set", os.W_OK) == False: os.mkdir("AppIcon.appiconset") file = open("AppIcon.appiconset/Contents.json", mode="w") json.dump(json_data, file, indent=4, sort_keys=True, separators=(',', ':')) file.close() def get_size(image):
64
64
85
5
59
dorukgezici/iOSAppIconGenerator
iOSAppIconGenerator.py
Python
get_size
get_size
179
186
179
179
d930c063ac96ec9295bf5160b2d2444280ee9e80
bigcode/the-stack
train
76651827aa448cc9879cdf6d
train
class
class PolicyMetadataOperations(object): """PolicyMetadataOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. ...
class PolicyMetadataOperations(object):
"""PolicyMetadataOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.policyinsi...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
234
256
1,381
6
228
rsdoherty/azure-sdk-for-python
sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/operations/_policy_metadata_operations.py
Python
PolicyMetadataOperations
PolicyMetadataOperations
26
174
26
26
10ab943cc8b18c95645e096866985694c9d0c9b6
bigcode/the-stack
train
d90cd9da1493bc6bb6c2aa93
train
function
def basic_train_parser(): parser = argparse.ArgumentParser() parser.add_argument('--config', dest='config', type=str, default='config/session_paths.yaml') parser.add_argument('--reset_dir', dest='clear_dir', action='store_true', help="deletes everything under this config's folder.") ...
def basic_train_parser():
parser = argparse.ArgumentParser() parser.add_argument('--config', dest='config', type=str, default='config/session_paths.yaml') parser.add_argument('--reset_dir', dest='clear_dir', action='store_true', help="deletes everything under this config's folder.") parser.add_argument('-...
pus: tf.config.experimental.set_memory_growth(gpu, True) logical_gpus = tf.config.experimental.list_logical_devices('GPU') print(len(gpus), 'Physical GPUs,', len(logical_gpus), 'Logical GPUs') except Exception: traceback.print_exc() def basic_train_parser():
64
64
127
5
59
taylorlu/dulcet
utils/scripts_utils.py
Python
basic_train_parser
basic_train_parser
20
29
20
20
6018f48964f88747625870df57a2229bf61366c6
bigcode/the-stack
train
30a0cf6b8668ab878e4156f6
train
function
def dynamic_memory_allocation(): gpus = tf.config.experimental.list_physical_devices('GPU') if gpus: try: # Currently, memory growth needs to be the same across GPUs for gpu in gpus: tf.config.experimental.set_memory_growth(gpu, True) logical_gpus = tf...
def dynamic_memory_allocation():
gpus = tf.config.experimental.list_physical_devices('GPU') if gpus: try: # Currently, memory growth needs to be the same across GPUs for gpu in gpus: tf.config.experimental.set_memory_growth(gpu, True) logical_gpus = tf.config.experimental.list_logical...
import traceback import argparse import tensorflow as tf def dynamic_memory_allocation():
17
64
106
6
10
taylorlu/dulcet
utils/scripts_utils.py
Python
dynamic_memory_allocation
dynamic_memory_allocation
7
17
7
7
aafef138984fb74e21cc7a6f4f3f91594dfc14c9
bigcode/the-stack
train
963c12c7f790ec3765e53268
train
class
class DashboardESDocument(ElasticsearchDocument): """ Schema for the ES dashboard ES document """ def __init__(self, dashboard_group, # type: str dashboard_name, # type: str description, # type: Union[str, None] total_usage, # type:...
class DashboardESDocument(ElasticsearchDocument):
""" Schema for the ES dashboard ES document """ def __init__(self, dashboard_group, # type: str dashboard_name, # type: str description, # type: Union[str, None] total_usage, # type: int product='', # type: Optiona...
from typing import List, Optional # noqa: F401 from databuilder.models.elasticsearch_document import ElasticsearchDocument class DashboardESDocument(ElasticsearchDocument):
32
86
288
9
22
pemmasanikrishna/amundsendatabuilder
databuilder/models/dashboard_elasticsearch_document.py
Python
DashboardESDocument
DashboardESDocument
6
38
6
6
1a98b1dc324f695ef40d292e843f78580878d018
bigcode/the-stack
train
03fcac5948dbdf67d5c74012
train
function
def rotate_bound(image, angle): # grab the dimensions of the image and then determine the # center (h, w) = image.shape[:2] (cX, cY) = (w // 2, h // 2) # grab the rotation matrix (applying the negative of the # angle to rotate clockwise), then grab the sine and cosine # (i.e., the rotation c...
def rotate_bound(image, angle): # grab the dimensions of the image and then determine the # center
(h, w) = image.shape[:2] (cX, cY) = (w // 2, h // 2) # grab the rotation matrix (applying the negative of the # angle to rotate clockwise), then grab the sine and cosine # (i.e., the rotation components of the matrix) M = cv2.getRotationMatrix2D((cX, cY), -angle, 1.0) cos = np.abs(M[0, 0]) ...
import cv2 import numpy as np import os, shutil def rotate_bound(image, angle): # grab the dimensions of the image and then determine the # center
38
81
270
24
13
lybcodes/ocr
PPOCRLabel/test.py
Python
rotate_bound
rotate_bound
5
23
5
7
e1c842d2d5a5cd567549aee43fb7069a138be500
bigcode/the-stack
train
d508254af2d7fd7c8cf18b71
train
function
def rotate_imagine(raw_img_path, save_img_path, angle): now_file_path = raw_img_path for dirpath, dirnames, filenames in os.walk(now_file_path): for filename in filenames: file_path = now_file_path + filename img = cv2.imread(file_path) # img_rotate = rotate_bound(img...
def rotate_imagine(raw_img_path, save_img_path, angle):
now_file_path = raw_img_path for dirpath, dirnames, filenames in os.walk(now_file_path): for filename in filenames: file_path = now_file_path + filename img = cv2.imread(file_path) # img_rotate = rotate_bound(img, angle) save_file_path = save_img_path + 'r...
# perform the actual rotation and return the image return cv2.warpAffine(image, M, (nW, nH)) # 遍历某文件夹下所有文件名,包括子文件夹下的文件名 def rotate_imagine(raw_img_path, save_img_path, angle):
64
64
101
14
49
lybcodes/ocr
PPOCRLabel/test.py
Python
rotate_imagine
rotate_imagine
26
34
26
26
3e61edb4bcaaef25eecdaf1687eb47918f007f4b
bigcode/the-stack
train
291ab364817299432653fc9d
train
class
@unique class Field(Enum): """Enumeration, represent a non null field in a battle.""" _UNKNOWN = auto() ELECTRIC_TERRAIN = auto() GRASSY_TERRAIN = auto() GRAVITY = auto() HEAL_BLOCK = auto() MAGIC_ROOM = auto() MISTY_TERRAIN = auto() MUD_SPORT = auto() MUD_SPOT = auto() PSYC...
@unique class Field(Enum):
"""Enumeration, represent a non null field in a battle.""" _UNKNOWN = auto() ELECTRIC_TERRAIN = auto() GRASSY_TERRAIN = auto() GRAVITY = auto() HEAL_BLOCK = auto() MAGIC_ROOM = auto() MISTY_TERRAIN = auto() MUD_SPORT = auto() MUD_SPOT = auto() PSYCHIC_TERRAIN = auto() TR...
# -*- coding: utf-8 -*- """This module defines the Field class, which represents a battle field. """ # pyre-ignore-all-errors[45] from enum import Enum, unique, auto import logging @unique class Field(Enum):
51
114
383
7
43
BlackwellNick/poke-env
src/poke_env/environment/field.py
Python
Field
Field
10
61
10
11
e93ec2f4b553b1a29dd70221f05fa81e331bb813
bigcode/the-stack
train
327ce7251d95b8acab7979f1
train
class
class StackedInline(InlineModelAdmin): template = 'admin/edit_inline/stacked.html'
class StackedInline(InlineModelAdmin):
template = 'admin/edit_inline/stacked.html'
# to have the change permission for the related model in order to # be able to do anything with the intermediate model. return self.has_change_permission(request, obj) return super(InlineModelAdmin, self).has_delete_permission(request, obj) class StackedInline(InlineModelAdm...
64
64
21
9
55
ei-grad/django
django/contrib/admin/options.py
Python
StackedInline
StackedInline
1,893
1,894
1,893
1,893
cbc342767c6c151b70eefe0b31f353e0eb1fea73
bigcode/the-stack
train
113b5ab257728e3cd66b275a
train
class
class TabularInline(InlineModelAdmin): template = 'admin/edit_inline/tabular.html'
class TabularInline(InlineModelAdmin):
template = 'admin/edit_inline/tabular.html'
do anything with the intermediate model. return self.has_change_permission(request, obj) return super(InlineModelAdmin, self).has_delete_permission(request, obj) class StackedInline(InlineModelAdmin): template = 'admin/edit_inline/stacked.html' class TabularInline(InlineModelAdmin):
64
64
20
9
55
ei-grad/django
django/contrib/admin/options.py
Python
TabularInline
TabularInline
1,897
1,898
1,897
1,897
84a47671433f187bb4e7ad525ea32c546da24b1b
bigcode/the-stack
train
f996722d00df3b12c818017f
train
class
class IncorrectLookupParameters(Exception): pass
class IncorrectLookupParameters(Exception):
pass
at the module level. from django.contrib.contenttypes.models import ContentType return ContentType.objects.get_for_model(obj, for_concrete_model=False) def get_ul_class(radio_style): return 'radiolist' if radio_style == VERTICAL else 'radiolist inline' class IncorrectLookupParameters(Exception):
64
64
9
6
58
ei-grad/django
django/contrib/admin/options.py
Python
IncorrectLookupParameters
IncorrectLookupParameters
69
70
69
69
8a16b10380bee0f0a306796f2ad53bf2e79ca1ff
bigcode/the-stack
train
a86960cb0afbd3ef6e4aa334
train
class
@python_2_unicode_compatible class ModelAdmin(BaseModelAdmin): "Encapsulates all admin options and functionality for a given model." list_display = ('__str__',) list_display_links = () list_filter = () list_select_related = False list_per_page = 100 list_max_show_all = 200 list_editable...
@python_2_unicode_compatible class ModelAdmin(BaseModelAdmin):
"Encapsulates all admin options and functionality for a given model." list_display = ('__str__',) list_display_links = () list_filter = () list_select_related = False list_per_page = 100 list_max_show_all = 200 list_editable = () search_fields = () date_hierarchy = None save...
examine the `obj` parameter. Can be overridden by the user in subclasses. In such case it should return True if the given request has permission to delete the `obj` model instance. If `obj` is None, this should return True if the given request has permission to delete *any* obj...
256
256
10,474
15
241
ei-grad/django
django/contrib/admin/options.py
Python
ModelAdmin
ModelAdmin
483
1,715
483
484
54f66ba17cb07b317e8a5db703239740cb6d2529
bigcode/the-stack
train
4083f75d32398731c324e9f6
train
function
def get_content_type_for_model(obj): # Since this module gets imported in the application's root package, # it cannot import models from other applications at the module level. from django.contrib.contenttypes.models import ContentType return ContentType.objects.get_for_model(obj, for_concrete_model=Fal...
def get_content_type_for_model(obj): # Since this module gets imported in the application's root package, # it cannot import models from other applications at the module level.
from django.contrib.contenttypes.models import ContentType return ContentType.objects.get_for_model(obj, for_concrete_model=False)
IS_POPUP_VAR = '_popup' TO_FIELD_VAR = '_to_field' HORIZONTAL, VERTICAL = 1, 2 def get_content_type_for_model(obj): # Since this module gets imported in the application's root package, # it cannot import models from other applications at the module level.
64
64
62
35
28
ei-grad/django
django/contrib/admin/options.py
Python
get_content_type_for_model
get_content_type_for_model
58
62
58
60
51df9cf9b4043306cd5df6ae7f46cc95438b633a
bigcode/the-stack
train
454863601e3566a8bc96515e
train
class
class BaseModelAdmin(six.with_metaclass(forms.MediaDefiningClass)): """Functionality common to both ModelAdmin and InlineAdmin.""" raw_id_fields = () fields = None exclude = None fieldsets = None form = forms.ModelForm filter_vertical = () filter_horizontal = () radio_fields = {} ...
class BaseModelAdmin(six.with_metaclass(forms.MediaDefiningClass)):
"""Functionality common to both ModelAdmin and InlineAdmin.""" raw_id_fields = () fields = None exclude = None fieldsets = None form = forms.ModelForm filter_vertical = () filter_horizontal = () radio_fields = {} prepopulated_fields = {} formfield_overrides = {} readonly...
radiolist' if radio_style == VERTICAL else 'radiolist inline' class IncorrectLookupParameters(Exception): pass # Defaults for formfield_overrides. ModelAdmin subclasses can change this # by adding to ModelAdmin.formfield_overrides. FORMFIELD_FOR_DBFIELD_DEFAULTS = { models.DateTimeField: { 'form_cla...
256
256
3,339
15
241
ei-grad/django
django/contrib/admin/options.py
Python
BaseModelAdmin
BaseModelAdmin
95
480
95
95
c4a3ddd53e574853e989d3fee4db142a5c44ffec
bigcode/the-stack
train
4582b336b790a759e5a8a305
train
function
def get_ul_class(radio_style): return 'radiolist' if radio_style == VERTICAL else 'radiolist inline'
def get_ul_class(radio_style):
return 'radiolist' if radio_style == VERTICAL else 'radiolist inline'
(obj): # Since this module gets imported in the application's root package, # it cannot import models from other applications at the module level. from django.contrib.contenttypes.models import ContentType return ContentType.objects.get_for_model(obj, for_concrete_model=False) def get_ul_class(radio_sty...
64
64
26
8
56
ei-grad/django
django/contrib/admin/options.py
Python
get_ul_class
get_ul_class
65
66
65
65
2be5420e743dccc9aeb6cf13e27fb3d6c1a42c24
bigcode/the-stack
train
8227b26394dbd766901276f3
train
class
class InlineModelAdmin(BaseModelAdmin): """ Options for inline editing of ``model`` instances. Provide ``fk_name`` to specify the attribute name of the ``ForeignKey`` from ``model`` to its parent. This is required if ``model`` has more than one ``ForeignKey`` to its parent. """ model = None...
class InlineModelAdmin(BaseModelAdmin):
""" Options for inline editing of ``model`` instances. Provide ``fk_name`` to specify the attribute name of the ``ForeignKey`` from ``model`` to its parent. This is required if ``model`` has more than one ``ForeignKey`` to its parent. """ model = None fk_name = None formset = BaseIn...
admin/object_history.html" ], context) def _create_formsets(self, request, obj, change): "Helper function to generate formsets for add/change_view." formsets = [] inline_instances = [] prefixes = {} get_formsets_args = [request] if change: get_for...
256
256
1,565
8
247
ei-grad/django
django/contrib/admin/options.py
Python
InlineModelAdmin
InlineModelAdmin
1,718
1,890
1,718
1,718
97735480a58b38b66706fcab410e2e3714859075
bigcode/the-stack
train
b693f3e32b06828347349d0a
train
function
def qcengine_records(program): skip, msg = _check_qcenginerecords(return_data=True) if skip: pytest.skip(msg, allow_module_level=True) import qcenginerecords return qcenginerecords.get_info(program)
def qcengine_records(program):
skip, msg = _check_qcenginerecords(return_data=True) if skip: pytest.skip(msg, allow_module_level=True) import qcenginerecords return qcenginerecords.get_info(program)
msg = "Could not find QCEngineRecords in PYTHONPATH" if return_data: return skip, msg else: return pytest.mark.skipif(skip, reason=msg) using_qcenginerecords = _check_qcenginerecords() def qcengine_records(program):
64
64
56
6
58
jeffschriber/QCEngine
qcengine/testing.py
Python
qcengine_records
qcengine_records
43
51
43
44
9bcc040860566f866fb237ea12599117f070c24d
bigcode/the-stack
train
f9824118310408c29923a907
train
function
def _check_qcenginerecords(return_data=False): skip = True try: import qcenginerecords qcer_hash = qcenginerecords.__git_revision__[:7] if qcer_hash != QCENGINE_RECORDS_COMMIT[:7]: msg = f"Incorrect QCEngineRecord Git Revision, found {qcer_hash} need {QCENGINE_RECORDS_COMMI...
def _check_qcenginerecords(return_data=False):
skip = True try: import qcenginerecords qcer_hash = qcenginerecords.__git_revision__[:7] if qcer_hash != QCENGINE_RECORDS_COMMIT[:7]: msg = f"Incorrect QCEngineRecord Git Revision, found {qcer_hash} need {QCENGINE_RECORDS_COMMIT[:7]}." else: skip = False ...
import qcelemental as qcel from pkg_resources import parse_version from qcelemental.util import which, which_import import qcengine as qcng QCENGINE_RECORDS_COMMIT = "aa4a1b2" def _check_qcenginerecords(return_data=False):
64
64
155
13
51
jeffschriber/QCEngine
qcengine/testing.py
Python
_check_qcenginerecords
_check_qcenginerecords
18
37
18
19
cd3f0c36cf92ab6daa63c1713f82a6040e8cc0fb
bigcode/the-stack
train
d78aaffe56a88565e260f96b
train
function
@pytest.fixture(scope="function") def failure_engine(): unique_name = "testing_random_name" class FailEngine(qcng.programs.ProgramHarness): iter_modes: List[str] = [] ncalls: int = 0 start_distance: float = 5 equilibrium_distance: float = 4 _defaults = { "na...
@pytest.fixture(scope="function") def failure_engine():
unique_name = "testing_random_name" class FailEngine(qcng.programs.ProgramHarness): iter_modes: List[str] = [] ncalls: int = 0 start_distance: float = 5 equilibrium_distance: float = 4 _defaults = { "name": unique_name, "scratch": False, ...
s(return_data=True) if skip: pytest.skip(msg, allow_module_level=True) import qcenginerecords return qcenginerecords.get_info(program) def is_program_new_enough(program, version_feature_introduced): """Returns True if `program` registered in QCEngine, locatable in environment, has parsea...
156
156
520
10
146
jeffschriber/QCEngine
qcengine/testing.py
Python
failure_engine
failure_engine
67
138
67
68
45d67641d54bac073725dfedbb3e0da4da1ee787
bigcode/the-stack
train
0da4d4628e55074dc684243e
train
function
def is_program_new_enough(program, version_feature_introduced): """Returns True if `program` registered in QCEngine, locatable in environment, has parseable version, and that version in normalized form is equal to or later than `version_feature_introduced`. """ if program not in qcng.list_available...
def is_program_new_enough(program, version_feature_introduced):
"""Returns True if `program` registered in QCEngine, locatable in environment, has parseable version, and that version in normalized form is equal to or later than `version_feature_introduced`. """ if program not in qcng.list_available_programs(): return False candidate_version = qcng.g...
skip, msg = _check_qcenginerecords(return_data=True) if skip: pytest.skip(msg, allow_module_level=True) import qcenginerecords return qcenginerecords.get_info(program) def is_program_new_enough(program, version_feature_introduced):
64
64
108
14
50
jeffschriber/QCEngine
qcengine/testing.py
Python
is_program_new_enough
is_program_new_enough
54
64
54
54
67303ef8b951e310a0eb21f2f7859e213d9e28a3
bigcode/the-stack
train
989de4930fa25eb4dff6fb67
train
function
def using(program): if program not in _using_cache: import_message = f"Not detecting module {program}. Install package if necessary to enable tests." skip = pytest.mark.skipif(has_program(program) is False, reason=import_message) _using_cache[program] = skip return _using_cache[program...
def using(program):
if program not in _using_cache: import_message = f"Not detecting module {program}. Install package if necessary to enable tests." skip = pytest.mark.skipif(has_program(program) is False, reason=import_message) _using_cache[program] = skip return _using_cache[program]
(".openmm", package="simtk", return_bool=True) def has_program(name): if name in _programs: return _programs[name] else: raise KeyError(f"Program {name} not registered with QCEngine testing.") _using_cache = {} def using(program):
63
64
70
4
59
jeffschriber/QCEngine
qcengine/testing.py
Python
using
using
180
187
180
181
6ba21df74f61ffc95caf8fc013f2e5a4ab2bf270
bigcode/the-stack
train
12d400446396b30103aa2299
train
function
def has_program(name): if name in _programs: return _programs[name] else: raise KeyError(f"Program {name} not registered with QCEngine testing.")
def has_program(name):
if name in _programs: return _programs[name] else: raise KeyError(f"Program {name} not registered with QCEngine testing.")
turbomole": which("define", return_bool=True), "xtb": which_import("xtb", return_bool=True), } _programs["openmm"] = _programs["rdkit"] and which_import(".openmm", package="simtk", return_bool=True) def has_program(name):
64
64
41
5
59
jeffschriber/QCEngine
qcengine/testing.py
Python
has_program
has_program
170
174
170
170
65e8c48db0a24aa41d6714a2603b6e2e48cf68cd
bigcode/the-stack
train
78c923374b63abd740230f45
train
function
def atom_features(atom): return torch.Tensor(onek_encoding_unk(atom.GetSymbol(), ELEM_LIST) + onek_encoding_unk(atom.GetDegree(), [0,1,2,3,4,5]) + onek_encoding_unk(atom.GetFormalCharge(), [-1,-2,1,2,0]) + onek_encoding_unk(int(atom.GetChiralTag()), [0,1,2,3]) + [at...
def atom_features(atom):
return torch.Tensor(onek_encoding_unk(atom.GetSymbol(), ELEM_LIST) + onek_encoding_unk(atom.GetDegree(), [0,1,2,3,4,5]) + onek_encoding_unk(atom.GetFormalCharge(), [-1,-2,1,2,0]) + onek_encoding_unk(int(atom.GetChiralTag()), [0,1,2,3]) + [atom.GetIsAromatic()])
B = 6 def onek_encoding_unk(x, allowable_set): if x not in allowable_set: x = allowable_set[-1] return list(map(lambda s: x == s, allowable_set)) # changed to list for python 3.7 by Truman def atom_features(atom):
64
64
103
5
58
atfrank/SampleDock
sampledock/jtvae/mpn.py
Python
atom_features
atom_features
19
24
19
19
d594be9622527139b29183244fc74572155975b3
bigcode/the-stack
train
08791c237f707fd2426c1c71
train
function
def onek_encoding_unk(x, allowable_set): if x not in allowable_set: x = allowable_set[-1] return list(map(lambda s: x == s, allowable_set)) # changed to list for python 3.7 by Truman
def onek_encoding_unk(x, allowable_set):
if x not in allowable_set: x = allowable_set[-1] return list(map(lambda s: x == s, allowable_set)) # changed to list for python 3.7 by Truman
', 'H', 'Cu', 'Mn', 'unknown'] ATOM_FDIM = len(ELEM_LIST) + 6 + 5 + 4 + 1 BOND_FDIM = 5 + 6 MAX_NB = 6 def onek_encoding_unk(x, allowable_set):
64
64
54
11
52
atfrank/SampleDock
sampledock/jtvae/mpn.py
Python
onek_encoding_unk
onek_encoding_unk
14
17
14
14
a339e046809fde36f8ec9cd91ede13dc74118931
bigcode/the-stack
train
a05c6fa31d05c393de12d910
train
function
def bond_features(bond): bt = bond.GetBondType() stereo = int(bond.GetStereo()) fbond = [bt == Chem.rdchem.BondType.SINGLE, bt == Chem.rdchem.BondType.DOUBLE, bt == Chem.rdchem.BondType.TRIPLE, bt == Chem.rdchem.BondType.AROMATIC, bond.IsInRing()] fstereo = onek_encoding_unk(stereo, [0,1,2,3,4,5]) r...
def bond_features(bond):
bt = bond.GetBondType() stereo = int(bond.GetStereo()) fbond = [bt == Chem.rdchem.BondType.SINGLE, bt == Chem.rdchem.BondType.DOUBLE, bt == Chem.rdchem.BondType.TRIPLE, bt == Chem.rdchem.BondType.AROMATIC, bond.IsInRing()] fstereo = onek_encoding_unk(stereo, [0,1,2,3,4,5]) return torch.Tensor(fbond ...
]) + onek_encoding_unk(atom.GetFormalCharge(), [-1,-2,1,2,0]) + onek_encoding_unk(int(atom.GetChiralTag()), [0,1,2,3]) + [atom.GetIsAromatic()]) def bond_features(bond):
63
64
113
6
58
atfrank/SampleDock
sampledock/jtvae/mpn.py
Python
bond_features
bond_features
26
31
26
26
02ae4ebe51bf8a20f9097a55a49bcdcda7963a9e
bigcode/the-stack
train
a9868aabf6648ef6e461ca78
train
class
class MPN(nn.Module): def __init__(self, hidden_size, depth): super(MPN, self).__init__() self.hidden_size = hidden_size self.depth = depth self.W_i = nn.Linear(ATOM_FDIM + BOND_FDIM, hidden_size, bias=False) self.W_h = nn.Linear(hidden_size, hidden_size, bias=False) ...
class MPN(nn.Module):
def __init__(self, hidden_size, depth): super(MPN, self).__init__() self.hidden_size = hidden_size self.depth = depth self.W_i = nn.Linear(ATOM_FDIM + BOND_FDIM, hidden_size, bias=False) self.W_h = nn.Linear(hidden_size, hidden_size, bias=False) self.W_o = nn.Linear(...
allowable_set[-1] return list(map(lambda s: x == s, allowable_set)) # changed to list for python 3.7 by Truman def atom_features(atom): return torch.Tensor(onek_encoding_unk(atom.GetSymbol(), ELEM_LIST) + onek_encoding_unk(atom.GetDegree(), [0,1,2,3,4,5]) + onek_encoding_unk(atom.Get...
255
255
850
6
249
atfrank/SampleDock
sampledock/jtvae/mpn.py
Python
MPN
MPN
33
124
33
34
ad9b7bd1af2a3c92438a2e90aa7bb241e60a307e
bigcode/the-stack
train
628621be832c2edc36b58d7c
train
function
def kbtotx(kb): tx = "" t = "" i = 0 for n in kb: if n == 0: t += "◻️ " if n == 1: t += "❌ " if n == 2: t += "⭕️ " i += 1 if i == 3: tx += "\n"+t t = "" i = 0 return tx
def kbtotx(kb):
tx = "" t = "" i = 0 for n in kb: if n == 0: t += "◻️ " if n == 1: t += "❌ " if n == 2: t += "⭕️ " i += 1 if i == 3: tx += "\n"+t t = "" i = 0 return tx
time, random, re, json import importlib from uuid import uuid4 from pyrogram.types import ( InlineQueryResultArticle, InputTextMessageContent, InlineKeyboardMarkup, InlineKeyboardButton ) def updateMsgs(client, message,redis): pass def kbtotx(kb):
64
64
109
8
55
Tshakel/AEK1-files
xo.py
Python
kbtotx
kbtotx
21
38
21
22
c1ca38fd64e38f5a1a484e0d528ee3f613c0cdb8
bigcode/the-stack
train