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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3bafb7ec63371e1814246121 | train | function | @hooks.register('register_log_actions')
def register_core_log_actions(actions):
actions.register_action('wagtail.create', _('Create'), _('Created'))
actions.register_action('wagtail.edit', _('Save draft'), _('Draft saved'))
actions.register_action('wagtail.delete', _('Delete'), _('Deleted'))
actions.reg... | @hooks.register('register_log_actions')
def register_core_log_actions(actions):
| actions.register_action('wagtail.create', _('Create'), _('Created'))
actions.register_action('wagtail.edit', _('Save draft'), _('Draft saved'))
actions.register_action('wagtail.delete', _('Delete'), _('Deleted'))
actions.register_action('wagtail.publish', _('Publish'), _('Published'))
actions.regist... | register_collection_permissions():
return Permission.objects.filter(
content_type__app_label='wagtailcore',
codename__in=['add_collection', 'change_collection', 'delete_collection']
)
@hooks.register('register_permissions')
def register_workflow_permissions():
return Permission.objects.fi... | 256 | 256 | 2,136 | 15 | 241 | shreyashsrivastava/wagtail | wagtail/core/wagtail_hooks.py | Python | register_core_log_actions | register_core_log_actions | 99 | 330 | 99 | 100 | d08594d5b14ad7b2b0b9449a7a9ba0a26ebe6d65 | bigcode/the-stack | train |
dbb57156a634d0622247dd30 | train | function | @hooks.register('register_permissions')
def register_task_permissions():
return Permission.objects.filter(
content_type__app_label='wagtailcore',
codename__in=['add_task', 'change_task', 'delete_task']
)
| @hooks.register('register_permissions')
def register_task_permissions():
| return Permission.objects.filter(
content_type__app_label='wagtailcore',
codename__in=['add_task', 'change_task', 'delete_task']
)
| hooks.register('register_permissions')
def register_workflow_permissions():
return Permission.objects.filter(
content_type__app_label='wagtailcore',
codename__in=['add_workflow', 'change_workflow', 'delete_workflow']
)
@hooks.register('register_permissions')
def register_task_permissions():
| 64 | 64 | 49 | 12 | 52 | shreyashsrivastava/wagtail | wagtail/core/wagtail_hooks.py | Python | register_task_permissions | register_task_permissions | 75 | 80 | 75 | 76 | 76e82b198f7eace464a4b5469f63e85abfe06f5c | bigcode/the-stack | train |
d294af41ffa4cc9a78a879ad | train | function | @hooks.register('before_serve_page')
def check_view_restrictions(page, request, serve_args, serve_kwargs):
"""
Check whether there are any view restrictions on this page which are
not fulfilled by the given request object. If there are, return an
HttpResponse that will notify the user of that restrictio... | @hooks.register('before_serve_page')
def check_view_restrictions(page, request, serve_args, serve_kwargs):
| """
Check whether there are any view restrictions on this page which are
not fulfilled by the given request object. If there are, return an
HttpResponse that will notify the user of that restriction (and possibly
include a password / login form that will allow them to proceed). If
there are no s... | import PageLinkHandler
def require_wagtail_login(next):
login_url = getattr(settings, 'WAGTAIL_FRONTEND_LOGIN_URL', reverse('wagtailcore_login'))
return redirect_to_login(next, login_url)
@hooks.register('before_serve_page')
def check_view_restrictions(page, request, serve_args, serve_kwargs):
| 72 | 72 | 240 | 25 | 47 | shreyashsrivastava/wagtail | wagtail/core/wagtail_hooks.py | Python | check_view_restrictions | check_view_restrictions | 19 | 38 | 19 | 20 | 40045d19713ba7c0e5e7be5905d6940f017cae51 | bigcode/the-stack | train |
91d24b3f3c17218d182ee60e | train | class | class Contents(models.Model):
lesson=models.ForeignKey(Lesson,on_delete=models.DO_NOTHING)
content=models.ForeignKey(Content,on_delete=models.DO_NOTHING)
owner = models.ForeignKey(User, on_delete=models.DO_NOTHING)
place = models.IntegerField(default=0)
is_active = models.BooleanField(default=True)
... | class Contents(models.Model):
| lesson=models.ForeignKey(Lesson,on_delete=models.DO_NOTHING)
content=models.ForeignKey(Content,on_delete=models.DO_NOTHING)
owner = models.ForeignKey(User, on_delete=models.DO_NOTHING)
place = models.IntegerField(default=0)
is_active = models.BooleanField(default=True)
def is_authorized(self, ... | = models.DateTimeField(auto_now_add=True, editable=True)
is_active = models.BooleanField(default=True)
def __str__(self):
return self.title
def is_authorized(self, user):
if self.owner == user:
return True
return False
class Contents(models.Model):
| 64 | 64 | 90 | 5 | 58 | kasimbozdag/SWE_573 | API/lesson/models.py | Python | Contents | Contents | 31 | 42 | 31 | 31 | 6e26be43b079466cbeda93699817882999e03c40 | bigcode/the-stack | train |
ab9e605996714dbf6016cb5b | train | class | class Lesson(models.Model):
title = models.CharField(max_length=127)
description = models.ForeignKey(Content, on_delete=models.CASCADE)
course = models.ForeignKey(Course, on_delete=models.DO_NOTHING)
place = models.IntegerField(default=0)
owner = models.ForeignKey(User, on_delete=models.DO_NOTHING)
... | class Lesson(models.Model):
| title = models.CharField(max_length=127)
description = models.ForeignKey(Content, on_delete=models.CASCADE)
course = models.ForeignKey(Course, on_delete=models.DO_NOTHING)
place = models.IntegerField(default=0)
owner = models.ForeignKey(User, on_delete=models.DO_NOTHING)
created_at = models.Date... | from django.db import models
# Create your models here.
from content.models import Content
from django.contrib.auth.models import User
from django.db import models
# Create your models here.
from course.models import Course
class Lesson(models.Model):
| 49 | 64 | 150 | 5 | 43 | kasimbozdag/SWE_573 | API/lesson/models.py | Python | Lesson | Lesson | 13 | 29 | 13 | 13 | 1e4cbeca9c3af4bbbb9764104d93e348ad151a1e | bigcode/the-stack | train |
b3cc33f7509da6342446a99b | train | function | def solution(allowed: str, words: list) -> int:
answer = 0
for word in words:
for index, letter in enumerate(word):
if letter in allowed:
if index == len(word) - 1:
answer += 1
else:
break
return answer
| def solution(allowed: str, words: list) -> int:
| answer = 0
for word in words:
for index, letter in enumerate(word):
if letter in allowed:
if index == len(word) - 1:
answer += 1
else:
break
return answer
| istent-strings
"""
# define an input for testing purposes
allowed = "cad"
words = ["cc", "acd", "b", "ba", "bac", "bad", "ac", "d"]
# actual code to submit
def solution(allowed: str, words: list) -> int:
| 64 | 64 | 68 | 14 | 49 | Pavocracy/Coding-Challenges | SOLVED/count-the-number-of-consistent-strings.py | Python | solution | solution | 10 | 21 | 10 | 10 | 5f79963f96da3caf46f924f4a5d79d169701223f | bigcode/the-stack | train |
7cf74920619ddd97928fd04a | train | class | class OperatorFamily(DbSchemaObject):
"""An operator family"""
objtype = "OPERATOR FAMILY"
keylist = ['schema', 'name', 'index_method']
def extern_key(self):
"""Return the key to be used in external maps for the operator family
:return: string
"""
return '%s %s using ... | class OperatorFamily(DbSchemaObject):
| """An operator family"""
objtype = "OPERATOR FAMILY"
keylist = ['schema', 'name', 'index_method']
def extern_key(self):
"""Return the key to be used in external maps for the operator family
:return: string
"""
return '%s %s using %s' % (self.objtype.lower(), self.name... | -8 -*-
"""
pyrseas.operfamily
~~~~~~~~~~~~~~~~~~
This module defines two classes: OperatorFamily derived from
DbSchemaObject and OperatorFamilyDict derived from DbObjectDict.
"""
from pyrseas.dbobject import DbObjectDict, DbSchemaObject
class OperatorFamily(DbSchemaObject):
| 64 | 64 | 210 | 7 | 56 | andreypopp/Pyrseas | pyrseas/dbobject/operfamily.py | Python | OperatorFamily | OperatorFamily | 12 | 44 | 12 | 12 | 9ee806328b440886ac845892d79bc0da19c90a6b | bigcode/the-stack | train |
3b15176137d7e67c128adb22 | train | class | class OperatorFamilyDict(DbObjectDict):
"The collection of operator families in a database"
cls = OperatorFamily
query = \
"""SELECT nspname AS schema, opfname AS name,
amname AS index_method,
obj_description(o.oid, 'pg_opfamily') AS description
FROM p... | class OperatorFamilyDict(DbObjectDict):
| "The collection of operator families in a database"
cls = OperatorFamily
query = \
"""SELECT nspname AS schema, opfname AS name,
amname AS index_method,
obj_description(o.oid, 'pg_opfamily') AS description
FROM pg_opfamily o
JOIN pg_am ... | from DbObjectDict.
"""
from pyrseas.dbobject import DbObjectDict, DbSchemaObject
class OperatorFamily(DbSchemaObject):
"""An operator family"""
objtype = "OPERATOR FAMILY"
keylist = ['schema', 'name', 'index_method']
def extern_key(self):
"""Return the key to be used in external maps for t... | 239 | 239 | 798 | 8 | 230 | andreypopp/Pyrseas | pyrseas/dbobject/operfamily.py | Python | OperatorFamilyDict | OperatorFamilyDict | 47 | 130 | 47 | 47 | 8b3bc01b3e322aa4fa86cb4746d5063c1f08ce27 | bigcode/the-stack | train |
b4897b9b3744258a38d99e23 | train | class | class GenerateReport():
def __init__(self, search=False, classifiers=['LR','XG']):
self.models = {
'LR': LogisticRegression(solver="saga", n_jobs=cpu_count()),
'RF': RandomForestClassifier(n_jobs=cpu_count()),
'XG': XGBClassifier(n_jobs=cpu_count()),
'LG': LGB... | class GenerateReport():
| def __init__(self, search=False, classifiers=['LR','XG']):
self.models = {
'LR': LogisticRegression(solver="saga", n_jobs=cpu_count()),
'RF': RandomForestClassifier(n_jobs=cpu_count()),
'XG': XGBClassifier(n_jobs=cpu_count()),
'LG': LGBMClassifier(n_jobs=cpu_c... | import base64
import io
import os
import warnings
from functools import partial
from multiprocessing import cpu_count
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from hyperopt import STATUS_OK, Trials, fmin, hp, space_eval, tpe
from lightgbm import LGBMClassifier
from sklearn import tree
fro... | 155 | 256 | 1,819 | 4 | 151 | TalkingData/MultiLayerStacking | mlstacking/report.py | Python | GenerateReport | GenerateReport | 24 | 163 | 24 | 24 | 721a8d1d333c2759ea60310cb931a65dccef5709 | bigcode/the-stack | train |
c0ed68e9325ba3457bb0bbfd | train | function | def sigmoid_function(signal):
# Prevent overflow.
signal = np.clip(signal, -500, 500)
# Calculate activation signal
return expit(signal)
| def sigmoid_function(signal):
# Prevent overflow.
| signal = np.clip(signal, -500, 500)
# Calculate activation signal
return expit(signal)
| , keepdims=False):
squared_norm = np.sum(np.square(s), axis=axis, keepdims=keepdims)
return np.sqrt(squared_norm + epsilon)
expit = lambda x: 1.0 / (1 + np.exp(-x))
def sigmoid_function(signal):
# Prevent overflow.
| 64 | 64 | 35 | 10 | 54 | cbu-novatec/CapsNet-Visualization | render.py | Python | sigmoid_function | sigmoid_function | 93 | 97 | 93 | 94 | 4407ac011c525bdf64f3edb6e82c2ba6d18b4158 | bigcode/the-stack | train |
7e95ac712437f3121d849e8b | train | function | def safe_norm(s, axis=-1, epsilon=1e-9, keepdims=False):
squared_norm = np.sum(np.square(s), axis=axis, keepdims=keepdims)
return np.sqrt(squared_norm + epsilon)
| def safe_norm(s, axis=-1, epsilon=1e-9, keepdims=False):
| squared_norm = np.sum(np.square(s), axis=axis, keepdims=keepdims)
return np.sqrt(squared_norm + epsilon)
| )
safe_norm = np.sqrt(squared_norm + epsilon)
squash_factor = squared_norm / (1. + squared_norm)
unit_vector = s / safe_norm
return squash_factor * unit_vector
def safe_norm(s, axis=-1, epsilon=1e-9, keepdims=False):
| 64 | 64 | 50 | 20 | 43 | cbu-novatec/CapsNet-Visualization | render.py | Python | safe_norm | safe_norm | 87 | 89 | 87 | 87 | 5be6af13e3c0e9ad58d37d3ee88eedfa39a73738 | bigcode/the-stack | train |
94e239d88209678d6ac0e807 | train | function | def ReLU_function(signal):
# Return the activation signal
return np.maximum(0, signal)
| def ReLU_function(signal):
# Return the activation signal
| return np.maximum(0, signal)
| lambda x: 1.0 / (1 + np.exp(-x))
def sigmoid_function(signal):
# Prevent overflow.
signal = np.clip(signal, -500, 500)
# Calculate activation signal
return expit(signal)
def ReLU_function(signal):
# Return the activation signal
| 64 | 64 | 22 | 13 | 51 | cbu-novatec/CapsNet-Visualization | render.py | Python | ReLU_function | ReLU_function | 100 | 102 | 100 | 101 | 7771f57f6543a032fafc393c697245ae0fdd3d6e | bigcode/the-stack | train |
f50ddc2cbc755891ee4bb453 | train | function | def squash(s, axis=-1, epsilon=1e-9):
squared_norm = np.sum(np.square(s), axis=axis, keepdims=True)
safe_norm = np.sqrt(squared_norm + epsilon)
squash_factor = squared_norm / (1. + squared_norm)
unit_vector = s / safe_norm
return squash_factor * unit_vector
| def squash(s, axis=-1, epsilon=1e-9):
| squared_norm = np.sum(np.square(s), axis=axis, keepdims=True)
safe_norm = np.sqrt(squared_norm + epsilon)
squash_factor = squared_norm / (1. + squared_norm)
unit_vector = s / safe_norm
return squash_factor * unit_vector
| _CONNECTED1_BIAS)
fully_connected2_bias = np.load(PATH_TO_WEIGHTS_FULLY_CONNECTED2_BIAS)
fully_connected3_bias = np.load(PATH_TO_WEIGHTS_FULLY_CONNECTED3_BIAS)
################################################################################
# Helper Functions
###########################################################... | 64 | 64 | 76 | 15 | 48 | cbu-novatec/CapsNet-Visualization | render.py | Python | squash | squash | 79 | 84 | 79 | 79 | 5152b1f2e4275173d2b8c08f2da4e4775b2f2030 | bigcode/the-stack | train |
2b76353e7268e2bcf0a1613e | train | function | def wigner_D(l, alpha, beta, gamma):
r"""Wigner D matrix representation of :math:`SO(3)`.
It satisfies the following properties:
* :math:`D(\text{identity rotation}) = \text{identity matrix}`
* :math:`D(R_1 \circ R_2) = D(R_1) \circ D(R_2)`
* :math:`D(R^{-1}) = D(R)^{-1} = D(R)^T`
* :math:`D(\... | def wigner_D(l, alpha, beta, gamma):
| r"""Wigner D matrix representation of :math:`SO(3)`.
It satisfies the following properties:
* :math:`D(\text{identity rotation}) = \text{identity matrix}`
* :math:`D(R_1 \circ R_2) = D(R_1) \circ D(R_2)`
* :math:`D(R^{-1}) = D(R)^{-1} = D(R)^T`
* :math:`D(\text{rotation around Y axis})` has so... | zeros((*shape, 2 * l + 1, 2 * l + 1))
inds = torch.arange(0, 2 * l + 1, 1, device=device)
reversed_inds = torch.arange(2 * l, -1, -1, device=device)
frequencies = torch.arange(l, -l - 1, -1, dtype=dtype, device=device)
M[..., inds, reversed_inds] = torch.sin(frequencies * angle[..., None])
M[..., in... | 136 | 136 | 455 | 12 | 123 | claycurry34/e3nn | e3nn/o3/_wigner.py | Python | wigner_D | wigner_D | 37 | 79 | 37 | 37 | 795ee2fe23dec8c9a1fa7c43158f890835e81981 | bigcode/the-stack | train |
fce32e261adf010b02fee0cb | train | function | def _generate_wigner_3j(l1, l2, l3, dtype=None, device=None): # pragma: no cover
r"""Computes the 3-j symbol
"""
# these three propositions are equivalent
assert abs(l2 - l3) <= l1 <= l2 + l3
assert abs(l3 - l1) <= l2 <= l3 + l1
assert abs(l1 - l2) <= l3 <= l1 + l2
n = (2 * l1 + 1) * (2 * ... | def _generate_wigner_3j(l1, l2, l3, dtype=None, device=None): # pragma: no cover
| r"""Computes the 3-j symbol
"""
# these three propositions are equivalent
assert abs(l2 - l3) <= l1 <= l2 + l3
assert abs(l3 - l1) <= l2 <= l3 + l1
assert abs(l1 - l2) <= l3 <= l1 + l2
n = (2 * l1 + 1) * (2 * l2 + 1) * (2 * l3 + 1) # dimension of the 3-j symbol
def _DxDxD(a, b, c):
... | flat_src[_W3j_indices[(l3, l1, l2)]].reshape(2 * l3 + 1, 2 * l1 + 1, 2 * l2 + 1).transpose(0, 2).transpose(0, 1)
except KeyError:
raise NotImplementedError(f'Wigner 3j symbols maximum l implemented is {max(_W3j_indices.keys())[0]}, send us an email to ask for more')
dtype, device = explicit_default_ty... | 205 | 205 | 686 | 30 | 175 | claycurry34/e3nn | e3nn/o3/_wigner.py | Python | _generate_wigner_3j | _generate_wigner_3j | 144 | 193 | 144 | 144 | 825e5d9c2314d17d3bd157098e47b75f05658b90 | bigcode/the-stack | train |
7fdecd23da78c9084988ce27 | train | function | def _z_rot_mat(angle, l):
r"""
Create the matrix representation of a z-axis rotation by the given angle,
in the irrep l of dimension 2 * l + 1, in the basis of real centered
spherical harmonics (RC basis in rep_bases.py).
Note: this function is easy to use, but inefficient: only the entries
on ... | def _z_rot_mat(angle, l):
| r"""
Create the matrix representation of a z-axis rotation by the given angle,
in the irrep l of dimension 2 * l + 1, in the basis of real centered
spherical harmonics (RC basis in rep_bases.py).
Note: this function is easy to use, but inefficient: only the entries
on the diagonal and anti-diag... | 2l+1)
# _W3j_flat is a flatten version of W3j symbols
# _W3j_indices is a dict from (l1, l2, l3) -> slice(i, j) to index the flat tensor
# only l1 <= l2 <= l3 are stored
def _z_rot_mat(angle, l):
| 75 | 75 | 250 | 9 | 65 | claycurry34/e3nn | e3nn/o3/_wigner.py | Python | _z_rot_mat | _z_rot_mat | 17 | 34 | 17 | 17 | 352967b1f994949de9601b1f78757b588e473fcc | bigcode/the-stack | train |
1fcc3e30debf50d5bdeed34b | train | function | def wigner_3j(l1, l2, l3, flat_src=_W3j_flat, dtype=None, device=None):
r"""Wigner 3j symbols :math:`C_{lmn}`.
It satisfies the following two properties:
.. math::
C_{lmn} = C_{ijk} D_{il}(g) D_{jm}(g) D_{kn}(g) \qquad \forall g \in SO(3)
where :math:`D` are given by `wigner_D`.
... | def wigner_3j(l1, l2, l3, flat_src=_W3j_flat, dtype=None, device=None):
| r"""Wigner 3j symbols :math:`C_{lmn}`.
It satisfies the following two properties:
.. math::
C_{lmn} = C_{ijk} D_{il}(g) D_{jm}(g) D_{kn}(g) \qquad \forall g \in SO(3)
where :math:`D` are given by `wigner_D`.
.. math::
C_{ijk} C_{ijk} = 1
Parameters
... | of shape :math:`(...)`
Rotation :math:`\beta` around X axis, applied second.
gamma : `torch.Tensor`
tensor of shape :math:`(...)`
Rotation :math:`\gamma` around Y axis, applied first.
Returns
-------
`torch.Tensor`
tensor :math:`D^l(\alpha, \beta, \gamma)` of shape :ma... | 256 | 256 | 881 | 29 | 226 | claycurry34/e3nn | e3nn/o3/_wigner.py | Python | wigner_3j | wigner_3j | 82 | 141 | 82 | 82 | b97d6bc2b026604fa87f2ebc33f189af7adf4d3a | bigcode/the-stack | train |
60156f045124b891075e8ab3 | train | class | class ResolveGeneratedPathRefs(NodeTransformer):
"""
Converts any instances of ctree.nodes.GeneratedPathRef into strings
containing the absolute path of the target file.
"""
def __init__(self, compilation_dir):
self.compilation_dir = compilation_dir
self.count = 0
def visit_Gen... | class ResolveGeneratedPathRefs(NodeTransformer):
| """
Converts any instances of ctree.nodes.GeneratedPathRef into strings
containing the absolute path of the target file.
"""
def __init__(self, compilation_dir):
self.compilation_dir = compilation_dir
self.count = 0
def visit_GeneratedPathRef(self, node):
self.count += ... | (node, UnaryOp):
node.arg = self.visit(node.arg)
return node
argument = self.visit(node.operand)
op = self.PY_OP_TO_CTREE_OP.get(type(node.op), type(node.op))()
return UnaryOp(op, argument)
class ResolveGeneratedPathRefs(NodeTransformer):
| 64 | 64 | 97 | 8 | 56 | alphaFred/Sejits4Fpgas | sejits4fpgas/src/vhdl_ctree/transformations.py | Python | ResolveGeneratedPathRefs | ResolveGeneratedPathRefs | 402 | 415 | 402 | 402 | 91a668b86c9a2be1c71730c58a34aa72416584ab | bigcode/the-stack | train |
039f127caf7e6f88737b9d59 | train | class | class PyBasicConversions(NodeTransformer):
"""
Convert constructs with obvious C analogues.
"""
def __init__(self, names_dict={}, constants_dict={}):
self.names_dict = names_dict
self.constants_dict = constants_dict
PY_OP_TO_CTREE_OP = {
ast.Add: Op.Add,
ast.Mod: Op.... | class PyBasicConversions(NodeTransformer):
| """
Convert constructs with obvious C analogues.
"""
def __init__(self, names_dict={}, constants_dict={}):
self.names_dict = names_dict
self.constants_dict = constants_dict
PY_OP_TO_CTREE_OP = {
ast.Add: Op.Add,
ast.Mod: Op.Mod,
ast.Mult: Op.Mul,
ast.... | c.nodes import Constant, String, SymbolRef, BinaryOp, TernaryOp, \
Return, While, MultiNode, UnaryOp
from .c.nodes import If, CFile, FunctionCall, FunctionDecl, For, Assign, \
ArrayRef, Cast
from .nodes import CtreeNode
from .c.nodes import Lt, Gt, AddAssign
from .c.nodes import Break, Continue, Pass, Array, Li... | 256 | 256 | 2,850 | 7 | 248 | alphaFred/Sejits4Fpgas | sejits4fpgas/src/vhdl_ctree/transformations.py | Python | PyBasicConversions | PyBasicConversions | 52 | 399 | 52 | 52 | 259ba7ee3838f1afdf675e7affdbb7767180068d | bigcode/the-stack | train |
8a9bec5385d6e84dd7a6ecee | train | class | class PyCtxScrubber(NodeTransformer):
"""
Removes pesky ctx attributes from Python ast.Name nodes,
yielding much cleaner python asts.
"""
def visit_Name(self, node):
node.ctx = None
return node
| class PyCtxScrubber(NodeTransformer):
| """
Removes pesky ctx attributes from Python ast.Name nodes,
yielding much cleaner python asts.
"""
def visit_Name(self, node):
node.ctx = None
return node
| else:
from itertools import zip_longest as izip_longest
def get_type(node):
if hasattr(node, 'get_type'):
return type(node.get_type())
elif hasattr(node, 'type'):
return type(node.type)
return c_void_p
class PyCtxScrubber(NodeTransformer):
| 64 | 64 | 49 | 8 | 55 | alphaFred/Sejits4Fpgas | sejits4fpgas/src/vhdl_ctree/transformations.py | Python | PyCtxScrubber | PyCtxScrubber | 41 | 49 | 41 | 41 | 23e51d059e1b77e501019864838c171048db2811 | bigcode/the-stack | train |
27f24abd367e920064aa0a4c | train | class | class Lifter(NodeTransformer):
"""
To aid in adding new includes or parameters during tree
traversals, users can store them with arbitrary child nodes and call this
transformation to move them to the correct position.
"""
def __init__(self, lift_params=True, lift_includes=True):
self.lif... | class Lifter(NodeTransformer):
| """
To aid in adding new includes or parameters during tree
traversals, users can store them with arbitrary child nodes and call this
transformation to move them to the correct position.
"""
def __init__(self, lift_params=True, lift_includes=True):
self.lift_params = lift_params
... | """
def __init__(self, compilation_dir):
self.compilation_dir = compilation_dir
self.count = 0
def visit_GeneratedPathRef(self, node):
self.count += 1
return String(os.path.join(self.compilation_dir,
node.target.get_filename()))
class Lifter(... | 68 | 69 | 232 | 6 | 62 | alphaFred/Sejits4Fpgas | sejits4fpgas/src/vhdl_ctree/transformations.py | Python | Lifter | Lifter | 418 | 445 | 418 | 418 | da80137db21b4c0f2c65cbb67fbb72c33ebb1750 | bigcode/the-stack | train |
0711fb2c7ebd917c2e422a5d | train | function | def get_type(node):
if hasattr(node, 'get_type'):
return type(node.get_type())
elif hasattr(node, 'type'):
return type(node.type)
return c_void_p
| def get_type(node):
| if hasattr(node, 'get_type'):
return type(node.get_type())
elif hasattr(node, 'type'):
return type(node.type)
return c_void_p
| Op
from .visitors import NodeTransformer
from .types import get_common_ctype
# conditional imports
if sys.version_info < (3, 0):
from itertools import izip_longest
else:
from itertools import zip_longest as izip_longest
def get_type(node):
| 64 | 64 | 41 | 5 | 58 | alphaFred/Sejits4Fpgas | sejits4fpgas/src/vhdl_ctree/transformations.py | Python | get_type | get_type | 33 | 38 | 33 | 33 | 219449c4c2f3d96130e4ad60303cb9b2df1fc105 | bigcode/the-stack | train |
dd03bfe3185f3bf010ca1087 | train | class | @interface.volumedriver
class XIVDS8KDriver(san.SanDriver,
driver.ManageableVD,
driver.ExtendVD,
driver.SnapshotVD,
driver.MigrateVD,
driver.ConsistencyGroupVD,
driver.CloneableImageVD,
... | @interface.volumedriver
class XIVDS8KDriver(san.SanDriver,
driver.ManageableVD,
driver.ExtendVD,
driver.SnapshotVD,
driver.MigrateVD,
driver.ConsistencyGroupVD,
driver.CloneableImageVD,
... | """Unified IBM XIV and DS8K volume driver."""
def __init__(self, *args, **kwargs):
"""Initialize the driver."""
super(XIVDS8KDriver, self).__init__(*args, **kwargs)
self.configuration.append_config_values(xiv_ds8k_opts)
proxy = importutils.import_class(self.configuration.xiv_... | xiv_ds8k_opts = [
cfg.StrOpt(
'xiv_ds8k_proxy',
default='xiv_ds8k_openstack.nova_proxy.XIVDS8KNovaProxy',
help='Proxy driver that connects to the IBM Storage Array'),
cfg.StrOpt(
'xiv_ds8k_connection_type',
default='iscsi',
choices=['fibre_channel', 'iscsi'],
... | 256 | 256 | 1,762 | 61 | 195 | bswartz/cinder | cinder/volume/drivers/ibm/xiv_ds8k.py | Python | XIVDS8KDriver | XIVDS8KDriver | 62 | 287 | 62 | 70 | b259aa73dfe66c7e9b398feff13adab940e20fc3 | bigcode/the-stack | train |
68cdbddc24fa41b60b7df254 | train | function | def slope_intercept_simple_linear_regression(x, y):
# compute the sum of input and output
sum = x + y
# compute the product of the output and the input and its sum
product = x * y
sum_of_product = product.sum()
# compute the squared value of the input and its sum
x_squared = x... | def slope_intercept_simple_linear_regression(x, y):
# compute the sum of input and output
| sum = x + y
# compute the product of the output and the input and its sum
product = x * y
sum_of_product = product.sum()
# compute the squared value of the input and its sum
x_squared = x * x
sum_x_squared = x_squared.sum()
# use the formula for the slope
numerator = s... | # simple linear regression f(x)
# x is the input and y is the output
def slope_intercept_simple_linear_regression(x, y):
# compute the sum of input and output
| 41 | 64 | 185 | 23 | 17 | futureseadev/hgwxx7 | helpers/slr_1.py | Python | slope_intercept_simple_linear_regression | slope_intercept_simple_linear_regression | 4 | 26 | 4 | 6 | 99dfee165cd589189951e4c41502c88d930e722a | bigcode/the-stack | train |
a5bc463a4605469c444dc69d | train | class | class TestOnchangeProductId(TransactionCase):
"""Test that when an included tax is mapped by a fiscal position, the included tax must be
subtracted to the price of the product.
"""
def setUp(self):
super(TestOnchangeProductId, self).setUp()
self.fiscal_position_model = self.env['account... | class TestOnchangeProductId(TransactionCase):
| """Test that when an included tax is mapped by a fiscal position, the included tax must be
subtracted to the price of the product.
"""
def setUp(self):
super(TestOnchangeProductId, self).setUp()
self.fiscal_position_model = self.env['account.fiscal.position']
self.fiscal_positio... | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tests import Form
from odoo.tests.common import TransactionCase
class TestOnchangeProductId(TransactionCase):
| 49 | 256 | 2,681 | 9 | 39 | jjiege/odoo | addons/sale/tests/test_onchange.py | Python | TestOnchangeProductId | TestOnchangeProductId | 8 | 271 | 8 | 8 | f7a94cd25a8c4a45938a5e0788f2a6470d201f31 | bigcode/the-stack | train |
81b821df5a7efcd7f951612b | train | class | class CopyFormPage(TemplateWriter):
extension = '_copy_form.html'
include_extension = '_copy_form_block.html'
def generate(self, context):
# Copy Form Page
return f"""{{% extends "base.html" %}}
{{% block head_title %}}{context.model.verbose_name}{{% endblock %}}
{{% block content %}}
<H1>{... | class CopyFormPage(TemplateWriter):
| extension = '_copy_form.html'
include_extension = '_copy_form_block.html'
def generate(self, context):
# Copy Form Page
return f"""{{% extends "base.html" %}}
{{% block head_title %}}{context.model.verbose_name}{{% endblock %}}
{{% block content %}}
<H1>{context.model.verbose_name}</H1>
{{%... | >
<form action="{{% url '{context.model_code_name}_copy' {context.model_code_name}.id %}}" method="post">
{{% csrf_token %}}
{{{{ form }}}}
<input type="submit" value="Submit">
</form>"""
class CopyFormPage(TemplateWriter):
| 64 | 64 | 115 | 8 | 56 | mozumder/django-mozumder | mozumder/management/writers/templates.py | Python | CopyFormPage | CopyFormPage | 150 | 162 | 150 | 150 | c69eb0781c4945a011bc1b047f340f897f207c90 | bigcode/the-stack | train |
f5b83be2e39db6064b5bc39c | train | class | class TemplateWriter(Writer):
sub_directory = 'templates'
def get_filename(self, context):
# Subclass this as needed. This function defines the file name.
return f"{context['model_code_name']}{self.extension}"
def get_filepath(self, context):
# Subclass this as needed. This function... | class TemplateWriter(Writer):
| sub_directory = 'templates'
def get_filename(self, context):
# Subclass this as needed. This function defines the file name.
return f"{context['model_code_name']}{self.extension}"
def get_filepath(self, context):
# Subclass this as needed. This function defines the file path.
... | import os
from .base import Writer
from ...models.development import *
from ..utilities.name_case import *
class TemplateWriter(Writer):
| 29 | 64 | 96 | 6 | 23 | mozumder/django-mozumder | mozumder/management/writers/templates.py | Python | TemplateWriter | TemplateWriter | 6 | 14 | 6 | 6 | 2bd179eb7248cd88871e3acd67be36fa29a36847 | bigcode/the-stack | train |
4c41d306c2ac3d79e3c74342 | train | class | class DeleteFormBlock(TemplateWriter):
extension = '_delete_form_block.html'
def generate(self, context):
# Delete Form Block
return f"""<div>Model Delete Form</div>
<form action="{{% url \'{context.model_code_name}_delete\' {context.model_code_name}.id %}}" method="post">
{{% csrf_toke... | class DeleteFormBlock(TemplateWriter):
| extension = '_delete_form_block.html'
def generate(self, context):
# Delete Form Block
return f"""<div>Model Delete Form</div>
<form action="{{% url \'{context.model_code_name}_delete\' {context.model_code_name}.id %}}" method="post">
{{% csrf_token %}}
{{{{ form }}}}
<input typ... | {context.model.verbose_name}{{% endblock %}}
{{% block content %}}
<H1>{context.model.verbose_name}</H1>
{{% include "{context.app.name}/{context.model_code_name}{self.include_extension}" %}}
{{% endblock content %}}
"""
class DeleteFormBlock(TemplateWriter):
| 64 | 64 | 100 | 8 | 56 | mozumder/django-mozumder | mozumder/management/writers/templates.py | Python | DeleteFormBlock | DeleteFormBlock | 164 | 174 | 164 | 164 | 51e7d927619ee70056c6c390c195e065bf1329fd | bigcode/the-stack | train |
121e74c4d64ad98fe2f5187f | train | class | class ModelDetailPage(TemplateWriter):
extension = '_detail.html'
def generate(self, context):
# Model Detail Page
return f"""{{% extends "base.html" %}}
{{% block head_title %}}{context.model.verbose_name}{{% endblock %}}
{{% block content %}}
<H1>{ context.model.verbose_name }</H1>
{{% includ... | class ModelDetailPage(TemplateWriter):
| extension = '_detail.html'
def generate(self, context):
# Model Detail Page
return f"""{{% extends "base.html" %}}
{{% block head_title %}}{context.model.verbose_name}{{% endblock %}}
{{% block content %}}
<H1>{ context.model.verbose_name }</H1>
{{% include "{context.app.name}/{context.model_co... | ,show_in_detail_view=True)
for field in fields:
field_ul += f"<li>{{{{{context.model_code_name}.{field.name}}}}}</li>"
return f'<div>Model Detail</div>\n<ul>{field_ul}</ul>'
class ModelDetailPage(TemplateWriter):
| 63 | 64 | 104 | 8 | 55 | mozumder/django-mozumder | mozumder/management/writers/templates.py | Python | ModelDetailPage | ModelDetailPage | 66 | 77 | 66 | 66 | f6129c211b5ab92aa589782267075fd3119bdb15 | bigcode/the-stack | train |
9b4ae813fb3a72d0dff8217f | train | class | class CreateFormPage(TemplateWriter):
extension = '_create_form.html'
include_extension = '_create_form_block.html'
def generate(self, context):
# Create Form Page
return f"""{{% extends "base.html" %}}
{{% block head_title %}}{context.model.verbose_name}{{% endblock %}}
{{% block content %... | class CreateFormPage(TemplateWriter):
| extension = '_create_form.html'
include_extension = '_create_form_block.html'
def generate(self, context):
# Create Form Page
return f"""{{% extends "base.html" %}}
{{% block head_title %}}{context.model.verbose_name}{{% endblock %}}
{{% block content %}}
<H1>{context.model.verbose_name}</H... | div>Model Create Form</div>
<form action="{{% url '{context.model_code_name}_create' %}}" method="post">
{{% csrf_token %}}
{{{{ form }}}}
<input type="submit" value="Submit">
</form>"""
class CreateFormPage(TemplateWriter):
| 64 | 64 | 115 | 8 | 56 | mozumder/django-mozumder | mozumder/management/writers/templates.py | Python | CreateFormPage | CreateFormPage | 98 | 110 | 98 | 98 | a14786f3aa3355574250ac7e04186b15072f3387 | bigcode/the-stack | train |
ea50e2e2ddb67a2fa09d0db3 | train | class | class DeleteFormPage(TemplateWriter):
extension = '_delete_form.html'
include_extension = '_delete_form_block.html'
def generate(self, context):
return f"""{{% extends "base.html" %}}
{{% block head_title %}}{context.model.verbose_name}{{% endblock %}}
{{% block content %}}
<H1>{context.model.v... | class DeleteFormPage(TemplateWriter):
| extension = '_delete_form.html'
include_extension = '_delete_form_block.html'
def generate(self, context):
return f"""{{% extends "base.html" %}}
{{% block head_title %}}{context.model.verbose_name}{{% endblock %}}
{{% block content %}}
<H1>{context.model.verbose_name}</H1>
{{% include "{contex... | <form action="{{% url \'{context.model_code_name}_delete\' {context.model_code_name}.id %}}" method="post">
{{% csrf_token %}}
{{{{ form }}}}
<input type="submit" value="Submit">
</form>"""
class DeleteFormPage(TemplateWriter):
| 64 | 64 | 110 | 8 | 56 | mozumder/django-mozumder | mozumder/management/writers/templates.py | Python | DeleteFormPage | DeleteFormPage | 176 | 187 | 176 | 176 | d70f3c032576534258c2fcffe41200ab6ca98415 | bigcode/the-stack | train |
83b70c35e72ca3c48496cdee | train | class | class UpdateModelsListBlock(TemplateWriter):
extension = '_update_list_block.html'
def generate(self, context):
# Add model to app's models list HTML
return f"""<li><a href="{{% url '{context.model_code_name}_list' %}}">{context.model.verbose_name}</a> <a href="{{% url '{context.model_code_name... | class UpdateModelsListBlock(TemplateWriter):
| extension = '_update_list_block.html'
def generate(self, context):
# Add model to app's models list HTML
return f"""<li><a href="{{% url '{context.model_code_name}_list' %}}">{context.model.verbose_name}</a> <a href="{{% url '{context.model_code_name}_create' %}}">Add</a></li>"""
| context.model.verbose_name}{{% endblock %}}
{{% block content %}}
<H1>{ context.model.verbose_name }</H1>
{{% include "{context.app.name}/{context.model_code_name}_detail_block.html" %}}
{{% endblock content %}}
"""
class UpdateModelsListBlock(TemplateWriter):
| 64 | 64 | 90 | 9 | 55 | mozumder/django-mozumder | mozumder/management/writers/templates.py | Python | UpdateModelsListBlock | UpdateModelsListBlock | 79 | 84 | 79 | 79 | a9b6e6ac264f65c5bf759e0d8ade33cbf580a5fd | bigcode/the-stack | train |
fea2165e23db00fd73a294e7 | train | class | class ModelDetailBlock(TemplateWriter):
extension = '_detail_block.html'
def generate(self, context):
# Model Detail Block
field_ul = ''
fields = TrackedField.objects.filter(owner=context.model,show_in_detail_view=True)
for field in fields:
field_ul += f"<li>{{{{{con... | class ModelDetailBlock(TemplateWriter):
| extension = '_detail_block.html'
def generate(self, context):
# Model Detail Block
field_ul = ''
fields = TrackedField.objects.filter(owner=context.model,show_in_detail_view=True)
for field in fields:
field_ul += f"<li>{{{{{context.model_code_name}.{field.name}}}}}</... | .model.verbose_name_plural}{{% endblock %}}
{{% block content %}}
<H1>{ context.model.verbose_name_plural }</H1>
{{% include "{context.app.name}/{context.model_code_name}_list_block.html" %}}
{{% endblock content %}}
"""
class ModelDetailBlock(TemplateWriter):
| 64 | 64 | 100 | 8 | 56 | mozumder/django-mozumder | mozumder/management/writers/templates.py | Python | ModelDetailBlock | ModelDetailBlock | 54 | 64 | 54 | 54 | 5fa8be100aa17cd299a8987953ca4673fc362bc8 | bigcode/the-stack | train |
9d8098be96cde7fe3821876e | train | class | class ModelListBlock(TemplateWriter):
extension = '_list_block.html'
def generate(self, context):
# Model List Block
header_row = ''
row = ''
list_fields = TrackedField.objects.filter(owner=context.model,show_in_list_view=True)
header_row += f'<th>ID</th>'
row +=... | class ModelListBlock(TemplateWriter):
| extension = '_list_block.html'
def generate(self, context):
# Model List Block
header_row = ''
row = ''
list_fields = TrackedField.objects.filter(owner=context.model,show_in_list_view=True)
header_row += f'<th>ID</th>'
row += f"""<td><a href="{{% url '{context.mo... | Writer):
sub_directory = 'templates'
def get_filename(self, context):
# Subclass this as needed. This function defines the file name.
return f"{context['model_code_name']}{self.extension}"
def get_filepath(self, context):
# Subclass this as needed. This function defines the file pat... | 100 | 100 | 336 | 8 | 92 | mozumder/django-mozumder | mozumder/management/writers/templates.py | Python | ModelListBlock | ModelListBlock | 16 | 39 | 16 | 16 | d4d14b64bd344d06918374f30efc40aae4d54580 | bigcode/the-stack | train |
4b2f9609cfd34a4f2b5d2252 | train | class | class ModelListPage(TemplateWriter):
extension = '_list.html'
def generate(self, context):
# Model List Page
return f"""{{% extends "base.html" %}}
{{% block head_title %}}{context.model.verbose_name_plural}{{% endblock %}}
{{% block content %}}
<H1>{ context.model.verbose_name_plural }</H1>
{{... | class ModelListPage(TemplateWriter):
| extension = '_list.html'
def generate(self, context):
# Model List Page
return f"""{{% extends "base.html" %}}
{{% block head_title %}}{context.model.verbose_name_plural}{{% endblock %}}
{{% block content %}}
<H1>{ context.model.verbose_name_plural }</H1>
{{% include "{context.app.name}/{contex... | _code_name}_delete' instance.id %}}">Delete</a></td>"""
return f"""<table>
<tr>{header_row}</tr>
{{% for instance in object_list %}}
<tr>{ row }</tr>
{{% endfor %}}
</table>"""
class ModelListPage(TemplateWriter):
| 64 | 64 | 106 | 8 | 56 | mozumder/django-mozumder | mozumder/management/writers/templates.py | Python | ModelListPage | ModelListPage | 41 | 52 | 41 | 41 | 75b9f931d1551631071543c54cfe0116e5cafc29 | bigcode/the-stack | train |
caba61762c2ad4d8f36b7af2 | train | class | class CreateFormBlock(TemplateWriter):
extension = '_create_form_block.html'
def generate(self, context):
# Create Form Block
return f"""<div>Model Create Form</div>
<form action="{{% url '{context.model_code_name}_create' %}}" method="post">
{{% csrf_token %}}
{{{{ form }}}}
<input... | class CreateFormBlock(TemplateWriter):
| extension = '_create_form_block.html'
def generate(self, context):
# Create Form Block
return f"""<div>Model Create Form</div>
<form action="{{% url '{context.model_code_name}_create' %}}" method="post">
{{% csrf_token %}}
{{{{ form }}}}
<input type="submit" value="Submit">
</form>"... | HTML
return f"""<li><a href="{{% url '{context.model_code_name}_list' %}}">{context.model.verbose_name}</a> <a href="{{% url '{context.model_code_name}_create' %}}">Add</a></li>"""
class CreateFormBlock(TemplateWriter):
| 64 | 64 | 91 | 8 | 56 | mozumder/django-mozumder | mozumder/management/writers/templates.py | Python | CreateFormBlock | CreateFormBlock | 86 | 96 | 86 | 86 | 92671232c08fc0986dc2a29a41a43f8561c90671 | bigcode/the-stack | train |
49cb6d3f76ce14e6f079d50f | train | class | class CopyFormBlock(TemplateWriter):
extension = '_copy_form_block.html'
def generate(self, context):
# Copy Form Block
return f"""<div>Model Copy Form</div>
<form action="{{% url '{context.model_code_name}_copy' {context.model_code_name}.id %}}" method="post">
{{% csrf_token %}}
{{{{ f... | class CopyFormBlock(TemplateWriter):
| extension = '_copy_form_block.html'
def generate(self, context):
# Copy Form Block
return f"""<div>Model Copy Form</div>
<form action="{{% url '{context.model_code_name}_copy' {context.model_code_name}.id %}}" method="post">
{{% csrf_token %}}
{{{{ form }}}}
<input type="submit" val... | context.model.verbose_name}{{% endblock %}}
{{% block content %}}
<H1>{context.model.verbose_name}</H1>
{{% include "{context.app.name}/{context.model_code_name}_update_form_block.html" %}}
{{% endblock content %}}
"""
class CopyFormBlock(TemplateWriter):
| 64 | 64 | 98 | 8 | 56 | mozumder/django-mozumder | mozumder/management/writers/templates.py | Python | CopyFormBlock | CopyFormBlock | 138 | 148 | 138 | 138 | fef789a4060a6bf329935bfa13e34433347539eb | bigcode/the-stack | train |
9adaaaf37e1565e1c782e484 | train | class | class ModelsBlock(TemplateWriter):
filename = 'models'
extension = '.html'
def get_filename(self, context):
# Subclass this as needed. This function defines the file name.
return f"{self.filename}{self.extension}"
def generate(self, context):
# Models Block
models = Trac... | class ModelsBlock(TemplateWriter):
| filename = 'models'
extension = '.html'
def get_filename(self, context):
# Subclass this as needed. This function defines the file name.
return f"{self.filename}{self.extension}"
def generate(self, context):
# Models Block
models = TrackedModel.objects.filter(owner=conte... | }}{context.model.verbose_name}{{% endblock %}}
{{% block content %}}
<H1>{context.model.verbose_name}</H1>
{{% include "{context.app.name}/{context.model_code_name}{self.include_extension}" %}}
{{% endblock content %}}
"""
class ModelsBlock(TemplateWriter):
| 64 | 64 | 154 | 7 | 57 | mozumder/django-mozumder | mozumder/management/writers/templates.py | Python | ModelsBlock | ModelsBlock | 190 | 204 | 190 | 190 | 47fd51a252dfd73f028f69d2dd4fc350609300d8 | bigcode/the-stack | train |
7f329516f09f0ce0cb09cb11 | train | class | class UpdateFormBlock(TemplateWriter):
extension = '_update_form_block.html'
def generate(self, context):
# Update Form Block
return f"""<div>Model Update Form</div>
<form action="{{% url '{context.model_code_name}_update' {context.model_code_name}.id %}}" method="post">
{{% csrf_token %}}
... | class UpdateFormBlock(TemplateWriter):
| extension = '_update_form_block.html'
def generate(self, context):
# Update Form Block
return f"""<div>Model Update Form</div>
<form action="{{% url '{context.model_code_name}_update' {context.model_code_name}.id %}}" method="post">
{{% csrf_token %}}
{{{{ form }}}}
<input type="sub... | {context.model.verbose_name}{{% endblock %}}
{{% block content %}}
<H1>{context.model.verbose_name}</H1>
{{% include "{context.app.name}/{context.model_code_name}{self.include_extension}" %}}
{{% endblock content %}}
"""
class UpdateFormBlock(TemplateWriter):
| 64 | 64 | 98 | 8 | 56 | mozumder/django-mozumder | mozumder/management/writers/templates.py | Python | UpdateFormBlock | UpdateFormBlock | 112 | 122 | 112 | 112 | e150d102a890c2842a65535fb324ddc2019f9f38 | bigcode/the-stack | train |
c10ff8a088936a6c27fafcb1 | train | class | class UpdateFormPage(TemplateWriter):
extension = '_update_form.html'
include_extension = '_update_form_block.html'
def generate(self, context):
# Update Form Page
return f"""{{% extends "base.html" %}}
{{% block head_title %}}{context.model.verbose_name}{{% endblock %}}
{{% block content %... | class UpdateFormPage(TemplateWriter):
| extension = '_update_form.html'
include_extension = '_update_form_block.html'
def generate(self, context):
# Update Form Page
return f"""{{% extends "base.html" %}}
{{% block head_title %}}{context.model.verbose_name}{{% endblock %}}
{{% block content %}}
<H1>{context.model.verbose_name}</H... | >
<form action="{{% url '{context.model_code_name}_update' {context.model_code_name}.id %}}" method="post">
{{% csrf_token %}}
{{{{ form }}}}
<input type="submit" value="Submit">
</form>"""
class UpdateFormPage(TemplateWriter):
| 64 | 64 | 116 | 8 | 56 | mozumder/django-mozumder | mozumder/management/writers/templates.py | Python | UpdateFormPage | UpdateFormPage | 124 | 136 | 124 | 124 | bb01fb50ba4145b708d294fff5b7ad074a3c561c | bigcode/the-stack | train |
b8ec9f3eda75a344ee2c8f79 | train | class | class ReshapedDataset(tud.Dataset):
def __init__(self, X, y):
self.X = X.astype(np.float32).reshape((1, X.shape[0], X.shape[1]))
self.y = y.astype(np.float32).reshape((-1))
print("Reshaped data:")
print(self.X.shape, self.y.shape)
def __len__(self):
return len(self.X)
... | class ReshapedDataset(tud.Dataset):
| def __init__(self, X, y):
self.X = X.astype(np.float32).reshape((1, X.shape[0], X.shape[1]))
self.y = y.astype(np.float32).reshape((-1))
print("Reshaped data:")
print(self.X.shape, self.y.shape)
def __len__(self):
return len(self.X)
def __getitem__(self, idx):
... | _h)
cv2.imshow("combined", img_c)
cv2.waitKey(0) # press enter to close the window
cv2.destroyAllWindows()
X = img_o / 255.0
y = img_c / 255.0
class ReshapedDataset(tud.Dataset):
| 64 | 64 | 107 | 9 | 54 | SCGTall/CX6364ArtificalIntelligence | HW5/HW5_Chaoran_Li_code/question3.py | Python | ReshapedDataset | ReshapedDataset | 81 | 92 | 81 | 81 | 311b2845e99e37ea0fe8ce8915187d1171fc0ed9 | bigcode/the-stack | train |
f563ca750e741993384f3222 | train | function | def manual_edge_detect(_img, _kernel):
r_offset = _kernel.shape[0] // 2
c_offset = _kernel.shape[1] // 2
outp = np.zeros(_img.shape, np.uint8)
for r in range(_img.shape[0]):
for c in range(_img.shape[1]):
sum = 0
for i in range(_kernel.shape[0]):
for j in ... | def manual_edge_detect(_img, _kernel):
| r_offset = _kernel.shape[0] // 2
c_offset = _kernel.shape[1] // 2
outp = np.zeros(_img.shape, np.uint8)
for r in range(_img.shape[0]):
for c in range(_img.shape[1]):
sum = 0
for i in range(_kernel.shape[0]):
for j in range(_kernel.shape[1]):
... | , -1]],
[[1, 0, -1],
[2, 0, -2],
[1, 0, -1]]
]) # horizontal, vertical
print("Kernels:")
for k in kernels:
print(k)
def manual_edge_detect(_img, _kernel):
| 65 | 65 | 218 | 10 | 55 | SCGTall/CX6364ArtificalIntelligence | HW5/HW5_Chaoran_Li_code/question3.py | Python | manual_edge_detect | manual_edge_detect | 33 | 51 | 33 | 33 | 9eeafad99e37cb98de5a4f75b23319b6d4576c7a | bigcode/the-stack | train |
4cd76c9a6b42020e301986ef | train | class | class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.conv1 = nn.Conv2d(1, 2, 3, padding=1)
self.conv1.weight.data = torch.Tensor([[kernels[0].tolist()], [kernels[1].tolist()]])
self.act1 = nn.ReLU()
self.pool1 = nn.MaxPool2d(3, 1, padding=1)
def... | class Model(nn.Module):
| def __init__(self):
super(Model, self).__init__()
self.conv1 = nn.Conv2d(1, 2, 3, padding=1)
self.conv1.weight.data = torch.Tensor([[kernels[0].tolist()], [kernels[1].tolist()]])
self.act1 = nn.ReLU()
self.pool1 = nn.MaxPool2d(3, 1, padding=1)
def image_func(self, _X, _n... | (np.float32).reshape((1, X.shape[0], X.shape[1]))
self.y = y.astype(np.float32).reshape((-1))
print("Reshaped data:")
print(self.X.shape, self.y.shape)
def __len__(self):
return len(self.X)
def __getitem__(self, idx):
return [self.X, self.y]
ds = ReshapedDataset(X, y)... | 103 | 103 | 346 | 5 | 98 | SCGTall/CX6364ArtificalIntelligence | HW5/HW5_Chaoran_Li_code/question3.py | Python | Model | Model | 99 | 127 | 99 | 99 | bd6fb2bf3c6e0f4977ba6681e151c200b1d1c783 | bigcode/the-stack | train |
422c027aede6a915afdb2003 | train | class | @init_model_state_from_kwargs
class ServiceSummary(object):
"""
A specific OCI service supported by resource limits.
"""
def __init__(self, **kwargs):
"""
Initializes a new ServiceSummary object with values from keyword arguments.
The following keyword arguments are supported (c... | @init_model_state_from_kwargs
class ServiceSummary(object):
| """
A specific OCI service supported by resource limits.
"""
def __init__(self, **kwargs):
"""
Initializes a new ServiceSummary object with values from keyword arguments.
The following keyword arguments are supported (corresponding to the getters/setters of this class):
... | 8
# Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either l... | 140 | 140 | 469 | 12 | 127 | Manny27nyc/oci-python-sdk | src/oci/limits/models/service_summary.py | Python | ServiceSummary | ServiceSummary | 10 | 101 | 10 | 11 | 9000584dcd2079d46f922107597698901f7f4df4 | bigcode/the-stack | train |
38ceb073cb50b0e3372f8dab | train | function | def main():
parser = OptionParser(usage="usage: %prog [options] results_file1 results_file2 ...")
parser.add_option("-t", "--top", action="store", type="int", dest="top", help="number of top terms and documents to write (default=20)", default=20)
parser.add_option("-o","--outdir", action="store", type="string", des... | def main():
| parser = OptionParser(usage="usage: %prog [options] results_file1 results_file2 ...")
parser.add_option("-t", "--top", action="store", type="int", dest="top", help="number of top terms and documents to write (default=20)", default=20)
parser.add_option("-o","--outdir", action="store", type="string", dest="dir_out",... | #!/usr/bin/env python
"""
Export topic modeling results generated by NMF, to a comma-delimited file.
"""
import os.path
import logging as log
from optparse import OptionParser
import unsupervised.nmf, unsupervised.rankings
# --------------------------------------------------------------
def main():
| 59 | 199 | 666 | 3 | 56 | jmparelman/dynamic-nmf | export-csv.py | Python | main | main | 12 | 63 | 12 | 12 | ae96172ab340ed357c85e2d92e491887fd421eea | bigcode/the-stack | train |
f94ce2acc37123a0e28747ad | train | class | class TeacherLoginTestCase(BaseTestCase):
def setUp(self):
super(TeacherLoginTestCase, self).setUp()
self.login = LoginPage(self.driver)
self.login.goto_page()
self.login.login_as_teacher(email_teacher, password_teacher)
| class TeacherLoginTestCase(BaseTestCase):
| def setUp(self):
super(TeacherLoginTestCase, self).setUp()
self.login = LoginPage(self.driver)
self.login.goto_page()
self.login.login_as_teacher(email_teacher, password_teacher)
| (executable_path="../browsers/geckodriver")
# self.driver = webdriver.Chrome(executable_path=CHROME_EXECUTABLE_PATH)
self.wait = WebDriverWait(self.driver, EXPLICIT_TIMEOUT)
def tearDown(self):
self.driver.quit()
class TeacherLoginTestCase(BaseTestCase):
| 64 | 64 | 55 | 9 | 55 | SQAPractical/AssesmentControlePython | ASK/fixtures/base.py | Python | TeacherLoginTestCase | TeacherLoginTestCase | 24 | 29 | 24 | 24 | 9fdb058d25de048f3bc642a2e555abf98237fd6c | bigcode/the-stack | train |
4b3c7f0d8ad6daecda2b2740 | train | class | class BaseTestCase(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome(executable_path="../browsers/chromedriver")
# self.driver = webdriver.Firefox(executable_path="../browsers/geckodriver")
# self.driver = webdriver.Chrome(executable_path=CHROME_EXECUTABLE_PATH)
s... | class BaseTestCase(unittest.TestCase):
| def setUp(self):
self.driver = webdriver.Chrome(executable_path="../browsers/chromedriver")
# self.driver = webdriver.Firefox(executable_path="../browsers/geckodriver")
# self.driver = webdriver.Chrome(executable_path=CHROME_EXECUTABLE_PATH)
self.wait = WebDriverWait(self.driver, E... | import unittest
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from direct_commands.commands_with_api import *
from fixtures.params import *
from pages.login_page import LoginPage
from parameters.parameters import *
class BaseTestCase(unittest.TestCase):
| 52 | 64 | 95 | 8 | 44 | SQAPractical/AssesmentControlePython | ASK/fixtures/base.py | Python | BaseTestCase | BaseTestCase | 11 | 21 | 11 | 11 | 65f39032dd7dea0abd8a9711132120fab0867ce9 | bigcode/the-stack | train |
8dd9a81f5aba3a739d1a04a2 | train | class | class Wiki40b(tfds.core.BeamBasedBuilder):
"""Wiki40B: A Clean Wikipedia Dataset for Mutlilingual Language Modeling."""
BUILDER_CONFIGS = [
Wiki40bConfig( # pylint:disable=g-complex-comprehension
version=_VERSION,
language=lang,
) for lang in WIKIPEDIA_LANGUAGES
]
def _info(se... | class Wiki40b(tfds.core.BeamBasedBuilder):
| """Wiki40B: A Clean Wikipedia Dataset for Mutlilingual Language Modeling."""
BUILDER_CONFIGS = [
Wiki40bConfig( # pylint:disable=g-complex-comprehension
version=_VERSION,
language=lang,
) for lang in WIKIPEDIA_LANGUAGES
]
def _info(self):
return tfds.core.DatasetInfo(
... | ", "ms", "no", "ro", "sk",
"sl", "sr", "sv", "tl", "uk", "vi"]
class Wiki40bConfig(tfds.core.BuilderConfig):
"""BuilderConfig for Wiki40B."""
def __init__(self, *, language=None, **kwargs):
"""BuilderConfig for Wiki40B.
Args:
language: string, the language code for the Wiki40B dataset to use.
... | 173 | 173 | 578 | 12 | 161 | CrimsonRadiator/datasets | tensorflow_datasets/text/wiki40b.py | Python | Wiki40b | Wiki40b | 83 | 162 | 83 | 83 | 3bbe481da616c5244f5ae7d7e77833e7378df18e | bigcode/the-stack | train |
bf9abda8bd0b3003c0425ffe | train | class | class Wiki40bConfig(tfds.core.BuilderConfig):
"""BuilderConfig for Wiki40B."""
def __init__(self, *, language=None, **kwargs):
"""BuilderConfig for Wiki40B.
Args:
language: string, the language code for the Wiki40B dataset to use.
**kwargs: keyword arguments forwarded to super.
"""
sup... | class Wiki40bConfig(tfds.core.BuilderConfig):
| """BuilderConfig for Wiki40B."""
def __init__(self, *, language=None, **kwargs):
"""BuilderConfig for Wiki40B.
Args:
language: string, the language code for the Wiki40B dataset to use.
**kwargs: keyword arguments forwarded to super.
"""
super(Wiki40bConfig, self).__init__(
name... | "he", "hi", "hr", "hu", "id", "lt", "lv", "ms", "no", "ro", "sk",
"sl", "sr", "sv", "tl", "uk", "vi"]
class Wiki40bConfig(tfds.core.BuilderConfig):
| 63 | 64 | 115 | 11 | 52 | CrimsonRadiator/datasets | tensorflow_datasets/text/wiki40b.py | Python | Wiki40bConfig | Wiki40bConfig | 63 | 77 | 63 | 63 | 6827a7da4f8e78dacdf535fad5911647a9f6609e | bigcode/the-stack | train |
7fadc90b688974bb77ac90b3 | train | class | class IntelAnalyzer(Analyzer):
"""Intel-based program analyzer."""
def __init__(self, logger, num_bits, is_elf):
"""Create the Intel Analyzer instance.
Args:
logger (logger): logger instance
num_bits (int): bitness of the CPU (32 bits by default)
is_elf (boo... | class IntelAnalyzer(Analyzer):
| """Intel-based program analyzer."""
def __init__(self, logger, num_bits, is_elf):
"""Create the Intel Analyzer instance.
Args:
logger (logger): logger instance
num_bits (int): bitness of the CPU (32 bits by default)
is_elf (bool): True iff analyzing an ELF b... | .function import FunctionClassifier
from utils.strings import StringIdentifier
from utils.local_constants import LocalsIdentifier
from utils.fptr import FptrIdentifier
from utils.switch_table import SwitchIdentifier
###############################
# Architecture Configurations #
#####... | 242 | 242 | 807 | 6 | 236 | CrackerCat/Karta | src/thumbs_up/analyzers/intel.py | Python | IntelAnalyzer | IntelAnalyzer | 27 | 134 | 27 | 27 | 0377b6a04f4c296fb9fdcde01810ed0fb3c56b83 | bigcode/the-stack | train |
0b0bf9e996459d8e68560de7 | train | function | def setup(bot: commands.Bot):
cog = Mod(bot)
bot.loop.create_task(cog.set_warn_error())
bot.add_cog(cog)
| def setup(bot: commands.Bot):
| cog = Mod(bot)
bot.loop.create_task(cog.set_warn_error())
bot.add_cog(cog)
| );
"""
)
await db.commit()
return await self.bot.invoke(ctx)
await ctx.bot.errhdl_g(ctx, error)
cls.warn.error(warn_error)
cls.rmwn.error(warn_error)
cls.chkwrn.error(warn_error)
def setup(bot: co... | 64 | 64 | 32 | 7 | 57 | windowsboy111/merlin-py | src/cogs/mod.py | Python | setup | setup | 286 | 289 | 286 | 286 | f11346f571ef0c68756ceaf2c24ffa1a11cff2e3 | bigcode/the-stack | train |
afcd66f5e288f157547f374e | train | class | class Mod(commands.Cog):
description = "Commands for moderation."
def __init__(self, bot):
self.bot = bot
@commands.group(name='role', aliases=['roles'], help='Get your role rolling automatically. Possible sub-commands: assign, remove, create, delete')
@chk_sudo()
@commands.guild_only()
... | class Mod(commands.Cog):
| description = "Commands for moderation."
def __init__(self, bot):
self.bot = bot
@commands.group(name='role', aliases=['roles'], help='Get your role rolling automatically. Possible sub-commands: assign, remove, create, delete')
@chk_sudo()
@commands.guild_only()
async def role(self, ct... | """Moderation stuff."""
import json
import random
import asyncio
from datetime import datetime
import discord
from discord.utils import get
from discord.ext import commands
import aiosqlite
import pyTableMaker
from ext.excepts import NoMutedRole
from ext.const import WARNFILE, SETFILE, STRFILE, chk_sudo
muted = dict()
... | 107 | 256 | 3,135 | 6 | 101 | windowsboy111/merlin-py | src/cogs/mod.py | Python | Mod | Mod | 18 | 284 | 18 | 18 | a91b6541c7130192a99929a66bb4d2720a1b004f | bigcode/the-stack | train |
e8eab892a90c33830b559e7e | train | class | class MempoolCoinbaseTest(DRiyalTestFramework):
def set_test_params(self):
self.num_nodes = 2
self.extra_args = [
[
'-whitelist=noban@127.0.0.1', # immediate tx relay
],
[]
]
def run_test(self):
wallet = MiniWallet(self.nodes[... | class MempoolCoinbaseTest(DRiyalTestFramework):
| def set_test_params(self):
self.num_nodes = 2
self.extra_args = [
[
'-whitelist=noban@127.0.0.1', # immediate tx relay
],
[]
]
def run_test(self):
wallet = MiniWallet(self.nodes[0])
# Start with a 200 block chain
... | #!/usr/bin/env python3
# Copyright (c) 2014-2021 The DRiyal Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test mempool re-org scenarios.
Test re-org scenarios with a mempool that contains transactions
that spe... | 133 | 256 | 1,332 | 14 | 118 | driyal/driyal | test/functional/mempool_reorg.py | Python | MempoolCoinbaseTest | MempoolCoinbaseTest | 15 | 109 | 15 | 15 | 01853f731cb0a567e98d088db895306afb8a86ad | bigcode/the-stack | train |
28dc530b19fc46ba39af5e47 | train | function | def test_hexagonal():
hexagonal_lattice =[[10.0, 0.0, 0.0],
[-5.0, 8.660254, 0.0],
[ 0.0, 0.0, 10.0]]
coords = [[0.0, 0.0, 0.0]]
# recipro_lat_abc = (0.85, 1.09, 1.31)
structure = Structure(lattice=hexagonal_lattice,
spec... | def test_hexagonal():
| hexagonal_lattice =[[10.0, 0.0, 0.0],
[-5.0, 8.660254, 0.0],
[ 0.0, 0.0, 10.0]]
coords = [[0.0, 0.0, 0.0]]
# recipro_lat_abc = (0.85, 1.09, 1.31)
structure = Structure(lattice=hexagonal_lattice,
species=["H"], coords=coor... | = StructureKpointsGenerator(primitive_structure,
task=Task.structure_opt,
kpt_density=5)
expected_generator.generate_input()
assert generator.num_kpts == expected_generator.num_kpts
assert generator.kpoin... | 64 | 64 | 176 | 5 | 58 | kumagai-group/vise | vise/tests/input_set/test_structure_kpoints_generator.py | Python | test_hexagonal | test_hexagonal | 188 | 200 | 188 | 188 | 424128ea548b660750fce4047fa96ff61ecd9447 | bigcode/the-stack | train |
ad086742a908394c272253a9 | train | function | def test_constructor_kpt_mode(sc_structure):
generator = StructureKpointsGenerator(sc_structure,
task=Task.cluster_opt)
assert generator._kpt_mode is KpointsMode.uniform
| def test_constructor_kpt_mode(sc_structure):
| generator = StructureKpointsGenerator(sc_structure,
task=Task.cluster_opt)
assert generator._kpt_mode is KpointsMode.uniform
| _kpt_factor == 3
def test_constructor_only_even_num_kpts(sc_structure):
generator = StructureKpointsGenerator(sc_structure,
only_even_num_kpts=True,
task=Task.cluster_opt)
assert generator._only_even_num_kpts is False
def test... | 64 | 64 | 39 | 9 | 54 | kumagai-group/vise | vise/tests/input_set/test_structure_kpoints_generator.py | Python | test_constructor_kpt_mode | test_constructor_kpt_mode | 28 | 31 | 28 | 28 | 9958c62800d9d80718106a8b7768705dfefcdcc6 | bigcode/the-stack | train |
70847f5019f853fda5d9fec7 | train | function | def test_constructor_kpt_shift_dos(sc_structure):
generator = StructureKpointsGenerator(sc_structure,
task=Task.dos)
assert generator._gamma_centered is True
| def test_constructor_kpt_shift_dos(sc_structure):
| generator = StructureKpointsGenerator(sc_structure,
task=Task.dos)
assert generator._gamma_centered is True
| _opt)
assert generator._kpt_mode is KpointsMode.uniform
def test_constructor_kpt_shift_structure_opt(sc_structure):
generator = StructureKpointsGenerator(sc_structure,
task=Task.structure_opt)
assert generator._gamma_centered is None
def test_constructor_kpt_shift... | 64 | 64 | 38 | 11 | 52 | kumagai-group/vise | vise/tests/input_set/test_structure_kpoints_generator.py | Python | test_constructor_kpt_shift_dos | test_constructor_kpt_shift_dos | 40 | 43 | 40 | 40 | 9efda0eb459f74282e8691817a821f9585338e9e | bigcode/the-stack | train |
06557043aa421e1f7be3568a | train | function | def test_mc_structure_band(mc_structure):
generator = StructureKpointsGenerator(mc_structure, task=Task.band)
generator.generate_input()
actual = generator.structure.lattice.matrix
expected = [[ 6., 3., 0.],
[-6., 3., 0.],
[-4., 0., 7.]]
np.testing.assert_array_almost... | def test_mc_structure_band(mc_structure):
| generator = StructureKpointsGenerator(mc_structure, task=Task.band)
generator.generate_input()
actual = generator.structure.lattice.matrix
expected = [[ 6., 3., 0.],
[-6., 3., 0.],
[-4., 0., 7.]]
np.testing.assert_array_almost_equal(actual, expected)
| = generator.structure.lattice.matrix
expected = [[ 6.,-3., 0.],
[ 6., 3., 0.],
[-4., 0., 7.]]
np.testing.assert_array_almost_equal(actual, expected)
def test_mc_structure_band(mc_structure):
| 64 | 64 | 85 | 8 | 56 | kumagai-group/vise | vise/tests/input_set/test_structure_kpoints_generator.py | Python | test_mc_structure_band | test_mc_structure_band | 72 | 79 | 72 | 72 | 5152a6b9dc4077cdc7171fc81b430c30457f7934 | bigcode/the-stack | train |
e07adfcb489597a61916082c | train | function | def test_conventional_input(tmpdir):
structure = Structure(Lattice.cubic(3.183372), species=["H"] * 2,
coords=[[0] * 3, [0.5] * 3])
generator = StructureKpointsGenerator(initial_structure=structure,
task=Task.structure_opt,
... | def test_conventional_input(tmpdir):
| structure = Structure(Lattice.cubic(3.183372), species=["H"] * 2,
coords=[[0] * 3, [0.5] * 3])
generator = StructureKpointsGenerator(initial_structure=structure,
task=Task.structure_opt,
kpt_density=2.5... | =coords)
generator = StructureKpointsGenerator(structure,
task=Task.structure_opt,
kpt_density=5)
generator.generate_input()
assert generator.kpoints.kpts_shift == [0.0, 0.0, 0.5]
def test_conventional_input(tmpdir):
| 64 | 64 | 178 | 8 | 56 | kumagai-group/vise | vise/tests/input_set/test_structure_kpoints_generator.py | Python | test_conventional_input | test_conventional_input | 203 | 217 | 203 | 203 | 2b13e38802334b4282cc6ab7d43a59fcc877ca73 | bigcode/the-stack | train |
9bee00330c43ee335b0ee999 | train | function | def test_kpt_factor(sc_structure):
generator = StructureKpointsGenerator(sc_structure,
task=Task.structure_opt,
kpt_density=2.,
num_kpt_factor=2)
generator.generate_input()
num_kpt_l... | def test_kpt_factor(sc_structure):
| generator = StructureKpointsGenerator(sc_structure,
task=Task.structure_opt,
kpt_density=2.,
num_kpt_factor=2)
generator.generate_input()
num_kpt_list = generator.kpoints.kpts[0]
... | task=Task.structure_opt,
kpt_density=2.,
only_even_num_kpts=True)
generator.generate_input()
num_kpt_list = generator.kpoints.kpts[0]
assert num_kpt_list == [14, 14, 14]
def test_kpt_factor(sc_structure):
| 64 | 64 | 75 | 8 | 56 | kumagai-group/vise | vise/tests/input_set/test_structure_kpoints_generator.py | Python | test_kpt_factor | test_kpt_factor | 135 | 142 | 135 | 135 | d48887c2c6931db1decf54dbe5b0c286bc227957 | bigcode/the-stack | train |
8d16ade14f84c1ea5209b618 | train | function | def test_oi_ti_bravais():
structure = Structure(Lattice.orthorhombic(20, 8, 6),
species=["H"]*2,
coords=[[0.0]*3, [0.5]*3])
generator = StructureKpointsGenerator(structure,
task=Task.structure_opt,
... | def test_oi_ti_bravais():
| structure = Structure(Lattice.orthorhombic(20, 8, 6),
species=["H"]*2,
coords=[[0.0]*3, [0.5]*3])
generator = StructureKpointsGenerator(structure,
task=Task.structure_opt,
kpt_... | 0.5, 0.5] are set.
generator.generate_input()
assert generator.kpoints.num_kpts == 44
assert generator.kpoints.kpts[0] == [0.125, 0.125, 0.125]
def test_oi_ti_bravais():
| 64 | 64 | 158 | 9 | 55 | kumagai-group/vise | vise/tests/input_set/test_structure_kpoints_generator.py | Python | test_oi_ti_bravais | test_oi_ti_bravais | 168 | 185 | 168 | 168 | af0b299e7484b907790167afcea992675e28f5b2 | bigcode/the-stack | train |
fcd7d121df0a854d09002fb1 | train | function | def test_only_even_num_kpts(sc_structure):
generator = StructureKpointsGenerator(sc_structure,
task=Task.structure_opt,
kpt_density=2.)
generator.generate_input()
num_kpt_list = generator.kpoints.kpts[0]
assert num_kpt_l... | def test_only_even_num_kpts(sc_structure):
| generator = StructureKpointsGenerator(sc_structure,
task=Task.structure_opt,
kpt_density=2.)
generator.generate_input()
num_kpt_list = generator.kpoints.kpts[0]
assert num_kpt_list == [13, 13, 13]
generator = Struct... | ure,
task=Task.structure_opt,
kpt_mode=KpointsMode.uniform,
gamma_centered=True)
generator.generate_input()
assert generator.kpoints.kpts_shift == [0.0, 0.0, 0.0]
def test_only_even_num_... | 64 | 64 | 136 | 10 | 54 | kumagai-group/vise | vise/tests/input_set/test_structure_kpoints_generator.py | Python | test_only_even_num_kpts | test_only_even_num_kpts | 118 | 132 | 118 | 118 | 9a7ed25c7f3f3bb387a4a4e961ab2d43f318eed0 | bigcode/the-stack | train |
30b3b4f8b085a094eb63b5e0 | train | function | def test_mc_structure_dos_uniform(mc_structure):
generator = StructureKpointsGenerator(mc_structure, task=Task.dos,
kpt_mode=KpointsMode.uniform)
generator.generate_input()
actual = generator.structure.lattice.matrix
expected = [[ 6., 3., 0.],
[ ... | def test_mc_structure_dos_uniform(mc_structure):
| generator = StructureKpointsGenerator(mc_structure, task=Task.dos,
kpt_mode=KpointsMode.uniform)
generator.generate_input()
actual = generator.structure.lattice.matrix
expected = [[ 6., 3., 0.],
[ 6.,-3., 0.],
[-4., 0., 7.]]
n... | generator.structure.lattice.matrix
expected = [[ 6., 3., 0.],
[-6., 3., 0.],
[-4., 0., 7.]]
np.testing.assert_array_almost_equal(actual, expected)
def test_mc_structure_dos_uniform(mc_structure):
| 64 | 64 | 99 | 10 | 54 | kumagai-group/vise | vise/tests/input_set/test_structure_kpoints_generator.py | Python | test_mc_structure_dos_uniform | test_mc_structure_dos_uniform | 82 | 90 | 82 | 82 | 88800f38f573ccb4362f5343e66f3e6997e74c69 | bigcode/the-stack | train |
946c68719fbf71c8a48de1cd | train | function | def test_constructor_symmetrizer(sc_structure, mocker):
mock = mocker.patch(
"vise.input_set.structure_kpoints_generator.StructureSymmetrizer")
StructureKpointsGenerator(sc_structure,
task=Task.dos,
symprec=10.0,
a... | def test_constructor_symmetrizer(sc_structure, mocker):
| mock = mocker.patch(
"vise.input_set.structure_kpoints_generator.StructureSymmetrizer")
StructureKpointsGenerator(sc_structure,
task=Task.dos,
symprec=10.0,
angle_tolerance=20.0,
band_... | Task.structure_opt)
assert generator._gamma_centered is None
def test_constructor_kpt_shift_dos(sc_structure):
generator = StructureKpointsGenerator(sc_structure,
task=Task.dos)
assert generator._gamma_centered is True
def test_constructor_symmetrizer(sc_structure... | 64 | 64 | 123 | 12 | 51 | kumagai-group/vise | vise/tests/input_set/test_structure_kpoints_generator.py | Python | test_constructor_symmetrizer | test_constructor_symmetrizer | 46 | 57 | 46 | 46 | 9c5a47f1b5b9a76063f7d38368112724ea9e5cf2 | bigcode/the-stack | train |
73098bab8532b620807daa0c | train | function | def test_cluster_opt_kpoints(sc_structure):
generator = StructureKpointsGenerator(sc_structure,
task=Task.cluster_opt,
kpt_density=2.)
generator.generate_input()
num_kpt_list = generator.kpoints.kpts[0]
assert num_kpt_li... | def test_cluster_opt_kpoints(sc_structure):
| generator = StructureKpointsGenerator(sc_structure,
task=Task.cluster_opt,
kpt_density=2.)
generator.generate_input()
num_kpt_list = generator.kpoints.kpts[0]
assert num_kpt_list == [1, 1, 1]
kpt_shift = generator.kp... | =Task.structure_opt,
kpt_density=2.,
num_kpt_factor=2)
generator.generate_input()
num_kpt_list = generator.kpoints.kpts[0]
assert num_kpt_list == [26, 26, 26]
def test_cluster_opt_kpoints(sc_structure):
| 64 | 64 | 95 | 9 | 55 | kumagai-group/vise | vise/tests/input_set/test_structure_kpoints_generator.py | Python | test_cluster_opt_kpoints | test_cluster_opt_kpoints | 145 | 153 | 145 | 145 | 53f950030935f8bef0eea6c5b10de664673e5186 | bigcode/the-stack | train |
87825affd25bb0ebd80095ae | train | function | def test_constructor_num_kpt_multiplication_factor(sc_structure):
generator = StructureKpointsGenerator(sc_structure,
task=Task.dielectric_function)
assert generator._num_kpt_factor == 3
| def test_constructor_num_kpt_multiplication_factor(sc_structure):
| generator = StructureKpointsGenerator(sc_structure,
task=Task.dielectric_function)
assert generator._num_kpt_factor == 3
| Structure
from vise.input_set.kpoints_mode import KpointsMode
from vise.input_set.structure_kpoints_generator import \
StructureKpointsGenerator
from vise.input_set.task import Task
from vise.util.structure_symmetrizer import StructureSymmetrizer
def test_constructor_num_kpt_multiplication_factor(sc_structure):
| 64 | 64 | 44 | 13 | 50 | kumagai-group/vise | vise/tests/input_set/test_structure_kpoints_generator.py | Python | test_constructor_num_kpt_multiplication_factor | test_constructor_num_kpt_multiplication_factor | 15 | 18 | 15 | 15 | f2203e6965ea99fe56b4f530f2032ab0be11a5e9 | bigcode/the-stack | train |
36f6e0549cf2f19c6af4707f | train | function | def test_mc_structure_primitive(mc_structure):
generator = StructureKpointsGenerator(mc_structure, task=Task.structure_opt)
generator.generate_input()
actual = generator.structure.lattice.matrix
expected = [[ 6.,-3., 0.],
[ 6., 3., 0.],
[-4., 0., 7.]]
np.testing.asser... | def test_mc_structure_primitive(mc_structure):
| generator = StructureKpointsGenerator(mc_structure, task=Task.structure_opt)
generator.generate_input()
actual = generator.structure.lattice.matrix
expected = [[ 6.,-3., 0.],
[ 6., 3., 0.],
[-4., 0., 7.]]
np.testing.assert_array_almost_equal(actual, expected)
| is_magnetization=True)
mock.assert_called_once_with(
structure=sc_structure, symprec=10.0, angle_tolerance=20.0,
band_mesh_distance=30.0, time_reversal=False)
# Structure related unittests.
def test_mc_structure_primitive(mc_structure):
| 64 | 64 | 88 | 9 | 55 | kumagai-group/vise | vise/tests/input_set/test_structure_kpoints_generator.py | Python | test_mc_structure_primitive | test_mc_structure_primitive | 62 | 69 | 62 | 62 | e30bf7bd84265a1bebcf63920139abcc04cf207e | bigcode/the-stack | train |
a8e251eb2540c243ee7f6b05 | train | function | def test_constructor_kpt_shift_structure_opt(sc_structure):
generator = StructureKpointsGenerator(sc_structure,
task=Task.structure_opt)
assert generator._gamma_centered is None
| def test_constructor_kpt_shift_structure_opt(sc_structure):
| generator = StructureKpointsGenerator(sc_structure,
task=Task.structure_opt)
assert generator._gamma_centered is None
| _opt)
assert generator._only_even_num_kpts is False
def test_constructor_kpt_mode(sc_structure):
generator = StructureKpointsGenerator(sc_structure,
task=Task.cluster_opt)
assert generator._kpt_mode is KpointsMode.uniform
def test_constructor_kpt_shift_structure_o... | 64 | 64 | 38 | 11 | 52 | kumagai-group/vise | vise/tests/input_set/test_structure_kpoints_generator.py | Python | test_constructor_kpt_shift_structure_opt | test_constructor_kpt_shift_structure_opt | 34 | 37 | 34 | 34 | ea3ec3c6747fc2528b70d8e853fa2344d00e52a5 | bigcode/the-stack | train |
968fb2ac0c973b94507c6f88 | train | function | def test_constructor_only_even_num_kpts(sc_structure):
generator = StructureKpointsGenerator(sc_structure,
only_even_num_kpts=True,
task=Task.cluster_opt)
assert generator._only_even_num_kpts is False
| def test_constructor_only_even_num_kpts(sc_structure):
| generator = StructureKpointsGenerator(sc_structure,
only_even_num_kpts=True,
task=Task.cluster_opt)
assert generator._only_even_num_kpts is False
| _symmetrizer import StructureSymmetrizer
def test_constructor_num_kpt_multiplication_factor(sc_structure):
generator = StructureKpointsGenerator(sc_structure,
task=Task.dielectric_function)
assert generator._num_kpt_factor == 3
def test_constructor_only_even_num_kpts(... | 64 | 64 | 48 | 11 | 52 | kumagai-group/vise | vise/tests/input_set/test_structure_kpoints_generator.py | Python | test_constructor_only_even_num_kpts | test_constructor_only_even_num_kpts | 21 | 25 | 21 | 21 | e0bd660d8b9e15dbc481a08d1cb61abb161163c0 | bigcode/the-stack | train |
ff7a25dc463a1f34b7f845a3 | train | function | def test_band_path(sc_structure):
generator = StructureKpointsGenerator(sc_structure,
task=Task.band,
kpt_density=0.5,
band_ref_dist=0.5)
# reciprocal length = 2 * pi / 1 = 6.28
# so... | def test_band_path(sc_structure):
| generator = StructureKpointsGenerator(sc_structure,
task=Task.band,
kpt_density=0.5,
band_ref_dist=0.5)
# reciprocal length = 2 * pi / 1 = 6.28
# so num_kpt_list = [12, 12, 12] and k... | num_kpt_list = generator.kpoints.kpts[0]
assert num_kpt_list == [1, 1, 1]
kpt_shift = generator.kpoints.kpts_shift
assert kpt_shift == [0, 0, 0]
def test_band_path(sc_structure):
| 64 | 64 | 142 | 7 | 57 | kumagai-group/vise | vise/tests/input_set/test_structure_kpoints_generator.py | Python | test_band_path | test_band_path | 156 | 165 | 156 | 156 | 07af868484ba0a46fbd52986ab94a376d548b919 | bigcode/the-stack | train |
c3986e3c28cfe6e16d127e67 | train | function | def test_manual_kpts():
lattice =[[10.0, 0.0, 0.0],
[ 0.0, 8.0, 0.0],
[-2.0, 0.0, 8.0]]
coords = [[0.0, 0.0, 0.0]]
# lattice angles are (90.0, 104.0362434679265, 90.0)
# so only kpoint shift along b-direction must be 0.5.
structure = Structure(lattice=lattice, species=["H... | def test_manual_kpts():
| lattice =[[10.0, 0.0, 0.0],
[ 0.0, 8.0, 0.0],
[-2.0, 0.0, 8.0]]
coords = [[0.0, 0.0, 0.0]]
# lattice angles are (90.0, 104.0362434679265, 90.0)
# so only kpoint shift along b-direction must be 0.5.
structure = Structure(lattice=lattice, species=["H"], coords=coords)
g... | =KpointsMode.uniform)
generator.generate_input()
actual = generator.structure.lattice.matrix
expected = [[ 6., 3., 0.],
[ 6.,-3., 0.],
[-4., 0., 7.]]
np.testing.assert_array_almost_equal(actual, expected)
# KPOINTS related unittests.
def test_manual_kpts():
| 84 | 84 | 280 | 6 | 78 | kumagai-group/vise | vise/tests/input_set/test_structure_kpoints_generator.py | Python | test_manual_kpts | test_manual_kpts | 95 | 115 | 95 | 95 | a05de7b9851571d2220ef7cefa05d481a550cff3 | bigcode/the-stack | train |
acd6e5bd6fce25ee67feb1bf | train | class | class PeekIterTest(BaseIteratorsTest):
def test_init_with_sentinel(self):
a = iter(['1', '2', 'DONE'])
sentinel = 'DONE'
self.assertRaises(TypeError, peek_iter, a, sentinel)
def get_next():
return next(a)
it = peek_iter(get_next, sentinel)
self.assertEqua... | class PeekIterTest(BaseIteratorsTest):
| def test_init_with_sentinel(self):
a = iter(['1', '2', 'DONE'])
sentinel = 'DONE'
self.assertRaises(TypeError, peek_iter, a, sentinel)
def get_next():
return next(a)
it = peek_iter(get_next, sentinel)
self.assertEqual(it.sentinel, sentinel)
self.a... | Case):
def assertEqualTwice(self, expected, func, *args):
self.assertEqual(expected, func(*args))
self.assertEqual(expected, func(*args))
def assertFalseTwice(self, func, *args):
self.assertFalse(func(*args))
self.assertFalse(func(*args))
def assertNext(self, it, expected, ... | 256 | 256 | 2,339 | 9 | 247 | m-chaturvedi/sphinx | tests/test_ext_napoleon_iterators.py | Python | PeekIterTest | PeekIterTest | 48 | 303 | 48 | 48 | 9f34c9630fefab1f56c4c4c56c3bdd95fdbf924a | bigcode/the-stack | train |
6dfeed679cdf50ce0682a1df | train | class | class ModifyIterTest(BaseIteratorsTest):
def test_init_with_sentinel_args(self):
a = iter(['1', '2', '3', 'DONE'])
sentinel = 'DONE'
def get_next():
return next(a)
it = modify_iter(get_next, sentinel, int)
expected = [1, 2, 3]
self.assertEqual(expected, [... | class ModifyIterTest(BaseIteratorsTest):
| def test_init_with_sentinel_args(self):
a = iter(['1', '2', '3', 'DONE'])
sentinel = 'DONE'
def get_next():
return next(a)
it = modify_iter(get_next, sentinel, int)
expected = [1, 2, 3]
self.assertEqual(expected, [i for i in it])
def test_init_with_s... | a = ['1']
it = peek_iter(a)
self.assertTrueTwice(it.has_next)
self.assertEqualTwice([], it.peek, 0)
self.assertTrueTwice(it.has_next)
self.assertEqualTwice([], it.peek, 0)
a = ['1', '2']
it = peek_iter(a)
self.assertTrueTwice(it.has_next)
self.as... | 129 | 129 | 430 | 9 | 120 | m-chaturvedi/sphinx | tests/test_ext_napoleon_iterators.py | Python | ModifyIterTest | ModifyIterTest | 306 | 346 | 306 | 306 | 29b59a557b8b2e838f127f52df0928c9c2c8129d | bigcode/the-stack | train |
7928063c785397d59230bee9 | train | class | class BaseIteratorsTest(TestCase):
def assertEqualTwice(self, expected, func, *args):
self.assertEqual(expected, func(*args))
self.assertEqual(expected, func(*args))
def assertFalseTwice(self, func, *args):
self.assertFalse(func(*args))
self.assertFalse(func(*args))
def ass... | class BaseIteratorsTest(TestCase):
| def assertEqualTwice(self, expected, func, *args):
self.assertEqual(expected, func(*args))
self.assertEqual(expected, func(*args))
def assertFalseTwice(self, func, *args):
self.assertFalse(func(*args))
self.assertFalse(func(*args))
def assertNext(self, it, expected, is_last... | mod:`sphinx.ext.napoleon.iterators` module.
:copyright: Copyright 2007-2020 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from unittest import TestCase
from sphinx.ext.napoleon.iterators import peek_iter, modify_iter
class BaseIteratorsTest(TestCase):
| 75 | 75 | 253 | 8 | 66 | m-chaturvedi/sphinx | tests/test_ext_napoleon_iterators.py | Python | BaseIteratorsTest | BaseIteratorsTest | 17 | 45 | 17 | 17 | d4823718af207455fced817af4cc23708e14473d | bigcode/the-stack | train |
7f8900988549559bcf2bfafe | train | function | def spreadsheet(service, id):
"""Fetch and return spreadsheet meta data with Google sheets API."""
request = service.spreadsheets().get(spreadsheetId=id)
try:
response = request.execute()
except apiclient.errors.HttpError as e:
if e.resp.status == 404:
raise KeyError(id)
... | def spreadsheet(service, id):
| """Fetch and return spreadsheet meta data with Google sheets API."""
request = service.spreadsheets().get(spreadsheetId=id)
try:
response = request.execute()
except apiclient.errors.HttpError as e:
if e.resp.status == 404:
raise KeyError(id)
else: # pragma: no cover
... | request = service.files().list(**params)
response = request.execute()
for f in response['files']:
yield f['id'], f['name']
try:
params['pageToken'] = response['nextPageToken']
except KeyError:
return
def spreadsheet(service, id):
| 64 | 64 | 87 | 6 | 57 | xflr6/gsheets | gsheets/backend.py | Python | spreadsheet | spreadsheet | 64 | 74 | 64 | 64 | 15a6ef9a3b86793b6fd9de4bac869c57ded66aca | bigcode/the-stack | train |
08abae589a5b5030e5ad7109 | train | function | def values(service, id, ranges):
"""Fetch and return spreadsheet cell values with Google sheets API."""
params = {'majorDimension': 'ROWS',
'valueRenderOption': 'UNFORMATTED_VALUE',
'dateTimeRenderOption': 'FORMATTED_STRING',
'spreadsheetId': id,
'ranges':... | def values(service, id, ranges):
| """Fetch and return spreadsheet cell values with Google sheets API."""
params = {'majorDimension': 'ROWS',
'valueRenderOption': 'UNFORMATTED_VALUE',
'dateTimeRenderOption': 'FORMATTED_STRING',
'spreadsheetId': id,
'ranges': ranges}
request = service.sp... | Id=id)
try:
response = request.execute()
except apiclient.errors.HttpError as e:
if e.resp.status == 404:
raise KeyError(id)
else: # pragma: no cover
raise
return response
def values(service, id, ranges):
| 64 | 64 | 99 | 8 | 55 | xflr6/gsheets | gsheets/backend.py | Python | values | values | 77 | 86 | 77 | 77 | 9d313e5e8998c7656ea8afc7fec4eda90430a618 | bigcode/the-stack | train |
0c3b2323badbc4e087dc28a1 | train | function | def quote(worksheet_name: str) -> str:
"""Return ``worksheet_name``, single-quote if needed.
>>> quote('spam')
'spam'
>>> quote('spam spam')
'spam spam'
>>> quote('DKC3')
"'DKC3'"
"""
if IS_ALPHANUMERIC_A1(worksheet_name):
# https://developers.google.com/sheets/api/guides/... | def quote(worksheet_name: str) -> str:
| """Return ``worksheet_name``, single-quote if needed.
>>> quote('spam')
'spam'
>>> quote('spam spam')
'spam spam'
>>> quote('DKC3')
"'DKC3'"
"""
if IS_ALPHANUMERIC_A1(worksheet_name):
# https://developers.google.com/sheets/api/guides/concepts#expandable-1
return f"... | dateTimeRenderOption': 'FORMATTED_STRING',
'spreadsheetId': id,
'ranges': ranges}
request = service.spreadsheets().values().batchGet(**params)
response = request.execute()
return response['valueRanges']
def quote(worksheet_name: str) -> str:
| 64 | 64 | 112 | 11 | 53 | xflr6/gsheets | gsheets/backend.py | Python | quote | quote | 89 | 104 | 89 | 89 | 0217caa337213afa61ed7bbf3eb32d76041be899 | bigcode/the-stack | train |
5830f0b4f0e8abdd663ac5af | train | function | def iterfiles(service, *, name=None, mimeType=SHEET, order=FILEORDER): # noqa: N803
"""Fetch and yield ``(id, name)`` pairs for Google drive files."""
params = {'orderBy': order, 'pageToken': None}
q = []
if name is not None:
q.append(f"name='{name}'")
if mimeType is not None:
q.app... | def iterfiles(service, *, name=None, mimeType=SHEET, order=FILEORDER): # noqa: N803
| """Fetch and yield ``(id, name)`` pairs for Google drive files."""
params = {'orderBy': order, 'pageToken': None}
q = []
if name is not None:
q.append(f"name='{name}'")
if mimeType is not None:
q.append(f"mimeType='{mimeType}'")
if q:
params['q'] = ' and '.join(q)
wh... | o2c_version == '4' or o2c_version.startswith('4.'):
kwargs['cache_discovery'] = False
return apiclient.discovery.build(**kwargs)
def iterfiles(service, *, name=None, mimeType=SHEET, order=FILEORDER): # noqa: N803
| 64 | 64 | 177 | 26 | 38 | xflr6/gsheets | gsheets/backend.py | Python | iterfiles | iterfiles | 42 | 61 | 42 | 42 | c4d171d0c42cc7a39fea3148336daf8538b1fc15 | bigcode/the-stack | train |
5705a7689a95da4f96bdc1e7 | train | function | def build_service(name=None, **kwargs):
"""Return a service endpoint for interacting with a Google API."""
if name is not None:
for kw, value in SERVICES[name].items():
kwargs.setdefault(kw, value)
if 'cache_discovery' not in kwargs:
try:
from oauth2client import __ve... | def build_service(name=None, **kwargs):
| """Return a service endpoint for interacting with a Google API."""
if name is not None:
for kw, value in SERVICES[name].items():
kwargs.setdefault(kw, value)
if 'cache_discovery' not in kwargs:
try:
from oauth2client import __version__ as o2c_version
except Im... | = 'folder,name,createdTime'
IS_ALPHANUMERIC_A1 = re.compile(r'[a-zA-Z]{1,3}' # last column 'ZZZ' (18_278)
r'\d{1,}').fullmatch
def build_service(name=None, **kwargs):
| 64 | 64 | 160 | 9 | 54 | xflr6/gsheets | gsheets/backend.py | Python | build_service | build_service | 24 | 39 | 24 | 24 | 27f34075682690089417ee23bcdbf429ab77c011 | bigcode/the-stack | train |
82e1c6d9ae695f6a7731b3ab | train | function | def check_parameters(parameters):
"""
Check if any yaml file parameter is null
:param parameters: necessary parameters to create the NS
:return:
"""
for k, v in parameters.items():
if v is None:
return False
return {k: parameters[k] for k in set(keys) & set(parameters.key... | def check_parameters(parameters):
| """
Check if any yaml file parameter is null
:param parameters: necessary parameters to create the NS
:return:
"""
for k, v in parameters.items():
if v is None:
return False
return {k: parameters[k] for k in set(keys) & set(parameters.keys())}
| def check_content(parameters):
"""
Check if yaml file has all the necessary parameters
:param parameters: necessary parameters to create the NS
:return: False if the user forgot any parameter
"""
if not set(keys) <= set(parameters):
return False
def check_parameters(parameters):
| 64 | 64 | 74 | 5 | 58 | oocran/oocran | oocran/django/alerts/orchestrator.py | Python | check_parameters | check_parameters | 34 | 43 | 34 | 34 | 5df7803abc6b47646a0a537de04b4877f6bd71b2 | bigcode/the-stack | train |
a1a385b53c3aa35b43c2b2e6 | train | function | def read_yaml(file):
"""
Read the yaml file parameters
:param file:
:return:
"""
doc = yaml.load(file)
list = []
try:
for rrh, parameters in doc.items():
if check_content(parameters) is not False and check_parameters(parameters) is not False:
list.app... | def read_yaml(file):
| """
Read the yaml file parameters
:param file:
:return:
"""
doc = yaml.load(file)
list = []
try:
for rrh, parameters in doc.items():
if check_content(parameters) is not False and check_parameters(parameters) is not False:
list.append(check_parameters(... | null
:param parameters: necessary parameters to create the NS
:return:
"""
for k, v in parameters.items():
if v is None:
return False
return {k: parameters[k] for k in set(keys) & set(parameters.keys())}
def read_yaml(file):
| 64 | 64 | 91 | 5 | 59 | oocran/oocran | oocran/django/alerts/orchestrator.py | Python | read_yaml | read_yaml | 46 | 63 | 46 | 46 | 229cf37536816913e5ae40b564aa26892d1ccead | bigcode/the-stack | train |
f0a93df4828349b10a0b77c8 | train | function | def check_content(parameters):
"""
Check if yaml file has all the necessary parameters
:param parameters: necessary parameters to create the NS
:return: False if the user forgot any parameter
"""
if not set(keys) <= set(parameters):
return False
| def check_content(parameters):
| """
Check if yaml file has all the necessary parameters
:param parameters: necessary parameters to create the NS
:return: False if the user forgot any parameter
"""
if not set(keys) <= set(parameters):
return False
| permissions and
limitations under the License.
"""
import yaml
from math import radians, cos, sin, asin, sqrt
keys = ["ip", "name", "latitude", "longitude", "pt", "neighbor", "bw","first_band","second_band","third_band"]
def check_content(parameters):
| 63 | 64 | 59 | 5 | 58 | oocran/oocran | oocran/django/alerts/orchestrator.py | Python | check_content | check_content | 24 | 31 | 24 | 24 | 362f3d9f49ba16c0a5b73ffd13b9e7c08fb3c16d | bigcode/the-stack | train |
b4644a56c2df254983d4d7cb | train | class | class Lof(BaseDetector):
def __init__(self):
super().__init__()
self.__clf = None
def train(self, X_train, params):
self.__clf = LocalOutlierFactor(n_neighbors=params['n_neighbors'], novelty=True,
contamination='auto').fit(X_train)
def score... | class Lof(BaseDetector):
| def __init__(self):
super().__init__()
self.__clf = None
def train(self, X_train, params):
self.__clf = LocalOutlierFactor(n_neighbors=params['n_neighbors'], novelty=True,
contamination='auto').fit(X_train)
def score_samples(self):
re... | from sklearn.neighbors import LocalOutlierFactor
import numpy as np
from models.detectors.base import BaseDetector
class Lof(BaseDetector):
| 30 | 64 | 162 | 6 | 23 | myrtakis/MxM | PredictiveOutlierExplanationBenchmark/src/models/detectors/Lof.py | Python | Lof | Lof | 6 | 32 | 6 | 7 | 6d989c1eeb73754de5ae081da699fcd3b94c0bea | bigcode/the-stack | train |
021d566affb7fb98d6a106c1 | train | function | def check_lambda_code_bucket_exists(args, bucket):
# Check that there is an appropriatly named code bucket
# for each region we will deploy to.
# to-do check that it's in the region it's name implies.
try:
args.s3.meta.client.head_bucket(Bucket=bucket)
shlog.normal("prerequisite bucket {} e... | def check_lambda_code_bucket_exists(args, bucket):
# Check that there is an appropriatly named code bucket
# for each region we will deploy to.
# to-do check that it's in the region it's name implies.
| try:
args.s3.meta.client.head_bucket(Bucket=bucket)
shlog.normal("prerequisite bucket {} exists".format(bucket))
return True
except botocore.exceptions.ClientError as e:
# If a client error is thrown, then check that it was a 404 error.
# If it was a 404 error, then the b... | #######################
CODE_BUCKET_TEMPLATE="scimma-processes-{}"
def check_lambda_code_bucket_exists(args, bucket):
# Check that there is an appropriatly named code bucket
# for each region we will deploy to.
# to-do check that it's in the region it's name implies.
| 64 | 64 | 198 | 48 | 16 | loftwah/security-scripts | security_scripts/rdk/rdk_manage.py | Python | check_lambda_code_bucket_exists | check_lambda_code_bucket_exists | 78 | 95 | 78 | 81 | 1b29e319e4d289f7d78f9b011c803c2d462140cb | bigcode/the-stack | train |
405495165ce35c12947ac57f | train | function | def parallelize (args, width, cmdlists):
# Run each command in a command list in a seperate process.
#
# cmdlists is a list of tuples -- (commands, context)
# number of processes active at once is contrained to width`
# just tell user
if args.dry_run:
for cmd, ctx in cmdlists:
... | def parallelize (args, width, cmdlists):
# Run each command in a command list in a seperate process.
#
# cmdlists is a list of tuples -- (commands, context)
# number of processes active at once is contrained to width`
# just tell user
| if args.dry_run:
for cmd, ctx in cmdlists:
shlog.normal ("would have executed: \n {}".format(cmd))
return
#ececute and display results.
with Pool(width) as p:
for status, stdout, stderr, cmd, ctx in p.map(do, cmdlists):
shlog.normal ('*************')
... | ctx
def parallelize (args, width, cmdlists):
# Run each command in a command list in a seperate process.
#
# cmdlists is a list of tuples -- (commands, context)
# number of processes active at once is contrained to width`
# just tell user
| 64 | 64 | 199 | 62 | 1 | loftwah/security-scripts | security_scripts/rdk/rdk_manage.py | Python | parallelize | parallelize | 44 | 64 | 44 | 50 | f2f5a07940d65f9c5c0119536e3ca2272d822498 | bigcode/the-stack | train |
f2d112c85289cc35190f39c3 | train | function | def do(cmdlist):
# run command, capture and return results.
#
# cmdlist is a two-element list.
# - shell command
# - Context -- short string.
cmd = cmdlist[0]
ctx = cmdlist[1]
result = subprocess.run(cmd,
capture_output=True,
... | def do(cmdlist):
# run command, capture and return results.
#
# cmdlist is a two-element list.
# - shell command
# - Context -- short string.
| cmd = cmdlist[0]
ctx = cmdlist[1]
result = subprocess.run(cmd,
capture_output=True,
shell=True,
timeout=600,
text=True)
return result.returncode, result.stdout.split("\n"), result.stderr.split... | import subprocess
from multiprocessing import Pool
########################
#
# Parallel Utilities
#
#######################
def do(cmdlist):
# run command, capture and return results.
#
# cmdlist is a two-element list.
# - shell command
# - Context -- short string.
| 63 | 64 | 107 | 43 | 20 | loftwah/security-scripts | security_scripts/rdk/rdk_manage.py | Python | do | do | 27 | 41 | 27 | 33 | aa4326ca0880c6056121287054bb312a4c9ad561 | bigcode/the-stack | train |
f8f4416ffb7fa25c15258cbf | train | function | def main(args):
"perform (or dry run) the indicated rdk command"
#########################################################################
# Check pre-condition -- check them all before quitting to have mercy and
# allow parallel debug
###############################################################... | def main(args):
| "perform (or dry run) the indicated rdk command"
#########################################################################
# Check pre-condition -- check them all before quitting to have mercy and
# allow parallel debug
#########################################################################
... | '])
if error_code == 403:
shlog.error("cannot access pre-requisite bucket {}".format(bucket))
return False
elif error_code == 404:
shlog.error("pre-requisite bucket {} does not exist".format(bucket))
return False
########################
#
# Drive... | 75 | 75 | 253 | 4 | 71 | loftwah/security-scripts | security_scripts/rdk/rdk_manage.py | Python | main | main | 103 | 129 | 103 | 103 | b80e0d14e76d8429937113f95931d74fb35ac5f1 | bigcode/the-stack | train |
80980091791562ec84e94254 | train | class | class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'MapAndAddress'
db.create_table('yandex_maps_mapandaddress', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('address', self.gf('django.db.models.fields.CharField')(... | class Migration(SchemaMigration):
| def forwards(self, orm):
# Adding model 'MapAndAddress'
db.create_table('yandex_maps_mapandaddress', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('address', self.gf('django.db.models.fields.CharField')(db_index=True, max_length=255, blan... | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
| 36 | 94 | 315 | 6 | 29 | 66ru/yandex-maps | yandex_maps/migrations/0001_initial.py | Python | Migration | Migration | 7 | 37 | 7 | 8 | 42c1fed346a74114827b21e3993142d3e486e071 | bigcode/the-stack | train |
d6f318cbfaaae40dbcdfc5c8 | train | function | def naming_image(city_name):
image = Image.open('{}.jpg'.format(city_name))
# Creating a image object.
font_type = ImageFont.load_default()
# This function truetype takes two arguments, 1. Font type 2. Font size
image_draw = ImageDraw.Draw(image)
# This function is used to conv... | def naming_image(city_name):
| image = Image.open('{}.jpg'.format(city_name))
# Creating a image object.
font_type = ImageFont.load_default()
# This function truetype takes two arguments, 1. Font type 2. Font size
image_draw = ImageDraw.Draw(image)
# This function is used to convert the image in editable form... | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 20 17:28:22 2021
@author: tushar
"""
from PIL import Image, ImageDraw, ImageFont
#PIL = Python imaging library.
def naming_image(city_name):
| 57 | 64 | 143 | 6 | 51 | tusharpandey1539/Image_naming | image_naming.py | Python | naming_image | naming_image | 10 | 25 | 10 | 10 | e3fd63829104b084dcf2b5f4b84e4cd08bd1b29b | bigcode/the-stack | train |
79c68829a3de010d45c6e663 | train | class | class Migration(migrations.Migration):
dependencies = [
('upload', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='photo',
name='publish',
field=models.BooleanField(default=False),
),
]
| class Migration(migrations.Migration):
| dependencies = [
('upload', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='photo',
name='publish',
field=models.BooleanField(default=False),
),
]
| # Generated by Django 2.1.5 on 2019-01-15 21:35
from django.db import migrations, models
class Migration(migrations.Migration):
| 38 | 64 | 54 | 7 | 30 | chmbrs/WeddingUpload | upload/migrations/0002_auto_20190115_2135.py | Python | Migration | Migration | 6 | 18 | 6 | 7 | 4c0b061ad52e563d29368a3f7bb8491804c605be | bigcode/the-stack | train |
949ad803ec37737c35f96104 | train | class | class LSTM_Attn_Classifier(nn.Module):
def __init__(self, inp_size, hidden_size, n_classes, return_attn_weights=False, attn_type='dot'):
super(LSTM_Attn_Classifier, self).__init__()
self.return_attn_weights = return_attn_weights
self.lstm = nn.LSTM(inp_size, hidden_size, batch_first=True)
... | class LSTM_Attn_Classifier(nn.Module):
| def __init__(self, inp_size, hidden_size, n_classes, return_attn_weights=False, attn_type='dot'):
super(LSTM_Attn_Classifier, self).__init__()
self.return_attn_weights = return_attn_weights
self.lstm = nn.LSTM(inp_size, hidden_size, batch_first=True)
self.attn_type = attn_type
... | hidden_size, batch_first=True)
self.classifier = nn.Linear(hidden_size, n_classes)
def forward(self, x):
lstm_out, (hidden, _) = self.lstm(x.transpose(1,2))
lstm_out = lstm_out[:, -1, :]
out = self.classifier(lstm_out)
return out
class LSTM_Attn_Classifier(nn.Module):
| 84 | 84 | 282 | 10 | 73 | shangeth/wavencoder | wavencoder/models/lstm_classifier.py | Python | LSTM_Attn_Classifier | LSTM_Attn_Classifier | 18 | 47 | 18 | 18 | c308d861926a1931d3a75f889d7a0d2d10f9a2af | bigcode/the-stack | train |
5669a8c49566644128541ac9 | train | class | class LSTM_Classifier(nn.Module):
def __init__(self, inp_size, hidden_size, n_classes):
super(LSTM_Classifier, self).__init__()
self.lstm = nn.LSTM(inp_size, hidden_size, batch_first=True)
self.classifier = nn.Linear(hidden_size, n_classes)
def forward(self, x):
lstm_out, (hidde... | class LSTM_Classifier(nn.Module):
| def __init__(self, inp_size, hidden_size, n_classes):
super(LSTM_Classifier, self).__init__()
self.lstm = nn.LSTM(inp_size, hidden_size, batch_first=True)
self.classifier = nn.Linear(hidden_size, n_classes)
def forward(self, x):
lstm_out, (hidden, _) = self.lstm(x.transpose(1,2)... | import torch
import torch.nn as nn
import torch.nn.functional as F
from wavencoder.layers import DotAttention, SoftAttention
class LSTM_Classifier(nn.Module):
| 35 | 64 | 120 | 8 | 26 | shangeth/wavencoder | wavencoder/models/lstm_classifier.py | Python | LSTM_Classifier | LSTM_Classifier | 6 | 16 | 6 | 6 | 15192ab2268e62bf47c5c5002672d89ca61d289f | bigcode/the-stack | train |
76b491f483d8a3f811cee604 | train | function | @pytest.mark.unit
def test_density_mass(instance):
"""Test calculation of cell."""
result = instance.calculate(
input_n_molecules=1,
input_n_atoms=1,
input_mass=input_mass,
density=Q_(density, "g/ml"),
mass=Q_(n_atoms * mass, "g"),
)
assert abs(result["size"].magn... | @pytest.mark.unit
def test_density_mass(instance):
| """Test calculation of cell."""
result = instance.calculate(
input_n_molecules=1,
input_n_atoms=1,
input_mass=input_mass,
density=Q_(density, "g/ml"),
mass=Q_(n_atoms * mass, "g"),
)
assert abs(result["size"].magnitude - 10.0) < 0.000001
| =input_mass,
density=Q_(density, "g/ml"),
n_moles=Q_(n_atoms / n_A, "mol"),
)
assert abs(result["size"].magnitude - 10.0) < 0.000001
@pytest.mark.unit
def test_density_mass(instance):
| 64 | 64 | 92 | 10 | 53 | molssi-seamm/packmol_step | tests/test_calculate.py | Python | test_density_mass | test_density_mass | 148 | 158 | 148 | 149 | 98b632392e7932578b47fc2af43e4b33fe1a7139 | bigcode/the-stack | train |
915e79fe9a910266858d4c83 | train | function | @pytest.mark.unit
def test_cell_mass(instance):
"""Test calculation of cell."""
result = instance.calculate(
input_n_molecules=1,
input_n_atoms=1,
input_mass=input_mass,
size=Q_(10, "Å"),
mass=Q_(n_atoms * mass, "g"),
)
assert abs(result["density"].magnitude - den... | @pytest.mark.unit
def test_cell_mass(instance):
| """Test calculation of cell."""
result = instance.calculate(
input_n_molecules=1,
input_n_atoms=1,
input_mass=input_mass,
size=Q_(10, "Å"),
mass=Q_(n_atoms * mass, "g"),
)
assert abs(result["density"].magnitude - density) < 0.000001
| ,
input_mass=input_mass,
size=Q_(10, "Å"),
n_moles=Q_(n_atoms / n_A, "mol"),
)
assert abs(result["density"].magnitude - density) < 0.000001
@pytest.mark.unit
def test_cell_mass(instance):
| 64 | 64 | 88 | 10 | 53 | molssi-seamm/packmol_step | tests/test_calculate.py | Python | test_cell_mass | test_cell_mass | 83 | 93 | 83 | 84 | d6adf1798f01f50a2c41a73701c4d4917c6c33dd | bigcode/the-stack | train |
0209cd0fe23db1de293412fd | train | function | @pytest.mark.unit
def test_volume_nmolecules(instance):
"""Test calculation of cell."""
result = instance.calculate(
input_n_molecules=1,
input_n_atoms=1,
input_mass=input_mass,
volume=Q_(1000, "Å**3"),
n_molecules=100,
)
assert abs(result["density"].magnitude - d... | @pytest.mark.unit
def test_volume_nmolecules(instance):
| """Test calculation of cell."""
result = instance.calculate(
input_n_molecules=1,
input_n_atoms=1,
input_mass=input_mass,
volume=Q_(1000, "Å**3"),
n_molecules=100,
)
assert abs(result["density"].magnitude - density) < 0.000001
| =1,
input_mass=input_mass,
size=Q_(10, "Å"),
mass=Q_(n_atoms * mass, "g"),
)
assert abs(result["density"].magnitude - density) < 0.000001
@pytest.mark.unit
def test_volume_nmolecules(instance):
| 64 | 64 | 86 | 11 | 52 | molssi-seamm/packmol_step | tests/test_calculate.py | Python | test_volume_nmolecules | test_volume_nmolecules | 96 | 106 | 96 | 97 | 5e8e3bd6ac15ee71de647c021eb5296f31da7302 | bigcode/the-stack | train |
4747d4e17d59439915dd1acf | train | function | @pytest.mark.unit
def test_cell_nmolecules(instance):
"""Test calculation of cell."""
result = instance.calculate(
input_n_molecules=1,
input_n_atoms=1,
input_mass=input_mass,
size=Q_(10, "Å"),
n_molecules=100,
)
assert abs(result["density"].magnitude - density) <... | @pytest.mark.unit
def test_cell_nmolecules(instance):
| """Test calculation of cell."""
result = instance.calculate(
input_n_molecules=1,
input_n_atoms=1,
input_mass=input_mass,
size=Q_(10, "Å"),
n_molecules=100,
)
assert abs(result["density"].magnitude - density) < 0.000001
| _volume = 22.710954641485 # L
rho_stp = m_Ar / molar_volume
@pytest.fixture
def instance():
instance = packmol_step.Packmol()
instance._id = (1,)
return instance
@pytest.mark.unit
def test_cell_nmolecules(instance):
| 64 | 64 | 83 | 11 | 52 | molssi-seamm/packmol_step | tests/test_calculate.py | Python | test_cell_nmolecules | test_cell_nmolecules | 31 | 41 | 31 | 32 | e49bb85f8c12f60c9d04a65b58efffbba7ec0926 | bigcode/the-stack | train |
776de5d95a78248e2fe1528c | train | function | @pytest.mark.unit
def test_ideal_gas(instance):
"""Test calculation of cell."""
result = instance.calculate(
input_n_molecules=1,
input_n_atoms=1,
input_mass=input_mass,
pressure=Q_(1, "bar"),
temperature=Q_(273.15, "K"),
n_molecules=n_A,
)
assert abs(resu... | @pytest.mark.unit
def test_ideal_gas(instance):
| """Test calculation of cell."""
result = instance.calculate(
input_n_molecules=1,
input_n_atoms=1,
input_mass=input_mass,
pressure=Q_(1, "bar"),
temperature=Q_(273.15, "K"),
n_molecules=n_A,
)
assert abs(result["density"].to("g/L").magnitude - rho_stp) < 0... | _mass=input_mass,
density=Q_(density, "g/ml"),
mass=Q_(n_atoms * mass, "g"),
)
assert abs(result["size"].magnitude - 10.0) < 0.000001
@pytest.mark.unit
def test_ideal_gas(instance):
| 64 | 64 | 103 | 12 | 51 | molssi-seamm/packmol_step | tests/test_calculate.py | Python | test_ideal_gas | test_ideal_gas | 161 | 172 | 161 | 162 | 2ecae01a2c063b20734561871e688dd18c8ab46b | bigcode/the-stack | train |
d69b3a5c3522ed3ea0c7f62b | train | function | @pytest.mark.unit
def test_cell_density(instance):
"""Test calculation of cell."""
result = instance.calculate(
input_n_molecules=1,
input_n_atoms=1,
input_mass=input_mass,
size=Q_(10, "Å"),
density=Q_(density, "g/ml"),
)
assert result["n_atoms"] == 100
| @pytest.mark.unit
def test_cell_density(instance):
| """Test calculation of cell."""
result = instance.calculate(
input_n_molecules=1,
input_n_atoms=1,
input_mass=input_mass,
size=Q_(10, "Å"),
density=Q_(density, "g/ml"),
)
assert result["n_atoms"] == 100
| olecules=1,
input_n_atoms=1,
input_mass=input_mass,
size=Q_(10, "Å"),
n_atoms=100,
)
assert abs(result["density"].magnitude - density) < 0.000001
@pytest.mark.unit
def test_cell_density(instance):
| 64 | 64 | 78 | 10 | 53 | molssi-seamm/packmol_step | tests/test_calculate.py | Python | test_cell_density | test_cell_density | 57 | 67 | 57 | 58 | 1178a4bc312b4a4bf74989edd28ba280be6435df | bigcode/the-stack | train |
4ae03b0047a89d2ec0db49d9 | train | function | @pytest.mark.unit
def test_density_natoms(instance):
"""Test calculation of cell."""
result = instance.calculate(
input_n_molecules=1,
input_n_atoms=1,
input_mass=input_mass,
density=Q_(density, "g/ml"),
n_atoms=100,
)
assert abs(result["size"].magnitude - 10.0) <... | @pytest.mark.unit
def test_density_natoms(instance):
| """Test calculation of cell."""
result = instance.calculate(
input_n_molecules=1,
input_n_atoms=1,
input_mass=input_mass,
density=Q_(density, "g/ml"),
n_atoms=100,
)
assert abs(result["size"].magnitude - 10.0) < 0.000001
| _n_atoms=1,
input_mass=input_mass,
density=Q_(density, "g/ml"),
n_molecules=100,
)
assert abs(result["size"].magnitude - 10.0) < 0.000001
@pytest.mark.unit
def test_density_natoms(instance):
| 64 | 64 | 86 | 11 | 52 | molssi-seamm/packmol_step | tests/test_calculate.py | Python | test_density_natoms | test_density_natoms | 122 | 132 | 122 | 123 | 8a86eb9291b11b2927ae4457218bb2bd9bebed60 | bigcode/the-stack | train |
82333abe24c7fa9dead67f19 | train | function | @pytest.mark.unit
def test_density_nmoles(instance):
"""Test calculation of cell."""
result = instance.calculate(
input_n_molecules=1,
input_n_atoms=1,
input_mass=input_mass,
density=Q_(density, "g/ml"),
n_moles=Q_(n_atoms / n_A, "mol"),
)
assert abs(result["size"... | @pytest.mark.unit
def test_density_nmoles(instance):
| """Test calculation of cell."""
result = instance.calculate(
input_n_molecules=1,
input_n_atoms=1,
input_mass=input_mass,
density=Q_(density, "g/ml"),
n_moles=Q_(n_atoms / n_A, "mol"),
)
assert abs(result["size"].magnitude - 10.0) < 0.000001
| input_n_atoms=1,
input_mass=input_mass,
density=Q_(density, "g/ml"),
n_atoms=100,
)
assert abs(result["size"].magnitude - 10.0) < 0.000001
@pytest.mark.unit
def test_density_nmoles(instance):
| 64 | 64 | 96 | 11 | 52 | molssi-seamm/packmol_step | tests/test_calculate.py | Python | test_density_nmoles | test_density_nmoles | 135 | 145 | 135 | 136 | c75a1e1ba0934e958d086d7bc195a5f6bd1e5e15 | bigcode/the-stack | train |
ccc795da17d550bb5b1e23fb | train | function | @pytest.mark.unit
def test_cell_natoms(instance):
"""Test calculation of cell."""
result = instance.calculate(
input_n_molecules=1,
input_n_atoms=1,
input_mass=input_mass,
size=Q_(10, "Å"),
n_atoms=100,
)
assert abs(result["density"].magnitude - density) < 0.00000... | @pytest.mark.unit
def test_cell_natoms(instance):
| """Test calculation of cell."""
result = instance.calculate(
input_n_molecules=1,
input_n_atoms=1,
input_mass=input_mass,
size=Q_(10, "Å"),
n_atoms=100,
)
assert abs(result["density"].magnitude - density) < 0.000001
| 1,
input_n_atoms=1,
input_mass=input_mass,
size=Q_(10, "Å"),
n_molecules=100,
)
assert abs(result["density"].magnitude - density) < 0.000001
@pytest.mark.unit
def test_cell_natoms(instance):
| 64 | 64 | 82 | 11 | 52 | molssi-seamm/packmol_step | tests/test_calculate.py | Python | test_cell_natoms | test_cell_natoms | 44 | 54 | 44 | 45 | a325c20c953d8ff0a4c4aa5c3f1a9297c765ee8a | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.