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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
666841ba5c30d7fb2f4ec4f5 | train | function | @question_proc('open', 'open-textfield')
def question_open(request, question, runinfo, errors):
key = "question_%s" % question.number
value = question.getcheckdict().get('default', '')
answers = []
if key in request.POST:
value = request.POST[key]
else:
if question.number not in erro... | @question_proc('open', 'open-textfield')
def question_open(request, question, runinfo, errors):
| key = "question_%s" % question.number
value = question.getcheckdict().get('default', '')
answers = []
if key in request.POST:
value = request.POST[key]
else:
if question.number not in errors:
try:
answers = Answer.objects.get(subject=runinfo.subject, runid... | know': hasdontknow,
'comment': cmt,
'jstriggers': jstriggers,
'template': 'questionnaire/choice-yesnocomment.html',
}
@question_proc('open', 'open-textfield')
def question_open(request, question, runinfo, errors):
| 64 | 64 | 196 | 23 | 41 | affan2/ed-questionnaire | questionnaire/qprocessors/simple.py | Python | question_open | question_open | 73 | 95 | 73 | 74 | 589c75adcb65155b7820e13f7247a0f94671951e | bigcode/the-stack | train |
5c94373819e820048671516d | train | function | @answer_proc('comment')
def process_comment(question, answer):
pass
| @answer_proc('comment')
def process_comment(question, answer):
| pass
| Choice [radio]')
add_type('choice-yesnocomment', 'Yes/No Choice with optional comment [radio, input]')
add_type('choice-yesnodontknow', 'Yes/No/Don\'t know Choice [radio]')
@answer_proc('comment')
def process_comment(question, answer):
| 63 | 64 | 16 | 13 | 51 | affan2/ed-questionnaire | questionnaire/qprocessors/simple.py | Python | process_comment | process_comment | 143 | 145 | 143 | 144 | 89e8e7c18031634e84a676fadac2271223404a5c | bigcode/the-stack | train |
0d68603b6061123d0fe82c92 | train | function | @answer_proc('open', 'open-textfield', 'choice-yesno', 'choice-yesnocomment', 'choice-yesnodontknow')
def process_simple(question, ansdict):
checkdict = question.getcheckdict()
ans = ansdict['ANSWER'] or ''
qtype = question.get_type()
validation = checkdict.get('validation', '')
if qtype.startswith(... | @answer_proc('open', 'open-textfield', 'choice-yesno', 'choice-yesnocomment', 'choice-yesnodontknow')
def process_simple(question, ansdict):
| checkdict = question.getcheckdict()
ans = ansdict['ANSWER'] or ''
qtype = question.get_type()
validation = checkdict.get('validation', '')
if qtype.startswith('choice-yesno'):
if ans not in ('yes', 'no', 'dontknow'):
raise AnswerException(_(u'You must select an option'))
... | Returned:
answers = Answer.objects.filter(subject=runinfo.subject, runid=runinfo.runid, question=question).order_by('-id')[0]
if answers and answers.split_answer():
value = answers.split_answer()[0]
return {
'required': question.getcheckdict().get('required', False),
... | 117 | 117 | 393 | 41 | 76 | affan2/ed-questionnaire | questionnaire/qprocessors/simple.py | Python | process_simple | process_simple | 98 | 133 | 98 | 99 | 15efd3d7d6a10ba0ad27e6637a435175a231011f | bigcode/the-stack | train |
6501d7d808a5172150a89c07 | train | function | def ResetState():
state.load = {'r1': NIL, 'r2': NIL}
state.doorStatus = {'d1': 'closed', 'd2': 'closed'}
state.loc = {'r1': 1, 'r2': 4}
state.pos = {'o1': 1, 'o2': 2}
state.done = {0: False}
state.doorType = {'d1': UNK, 'd2': UNK}
| def ResetState():
| state.load = {'r1': NIL, 'r2': NIL}
state.doorStatus = {'d1': 'closed', 'd2': 'closed'}
state.loc = {'r1': 1, 'r2': 4}
state.pos = {'o1': 1, 'o2': 2}
state.done = {0: False}
state.doorType = {'d1': UNK, 'd2': UNK}
| 4): 'd1', (2, 3): 'd2'}
rv.ROBOTS = ['r1', 'r2']
rv.DOORS = ['d1', 'd2']
rv.DOORTYPES = {'d1': 'ordinary', 'd2': 'spring'}
def ResetState():
| 64 | 64 | 105 | 4 | 60 | patras91/rae_release | domains/nav/problems/auto/problem18_SD.py | Python | ResetState | ResetState | 38 | 44 | 38 | 38 | 0bd3da998bfb8c14ece382864037e93ea63d3207 | bigcode/the-stack | train |
9bb752e2e3f724614841dc18 | train | function | def result():
with django_block("header") as header:
with div(_class="row top-right-div"):
with column(12):
top_left_div()
top_right_div()
return (
"{% extends 'base_base.html' %}\n",
"{% load i18n %}\n",
header,
)
| def result():
| with django_block("header") as header:
with div(_class="row top-right-div"):
with column(12):
top_left_div()
top_right_div()
return (
"{% extends 'base_base.html' %}\n",
"{% load i18n %}\n",
header,
)
| Shared Goals")
with a(href="{% url 'about' %}"):
text("| About")
with a(href="{% url 'tos' %}"):
text("| Terms")
with a(href="{% url 'feedback' %}"):
text("| Give feedback")
def result():
| 64 | 64 | 72 | 3 | 61 | mnieber/shared-goal | django/main/templates/base_html.py | Python | result | result | 94 | 105 | 94 | 94 | 0d1b50859c50613e882cec629d5e3bdb01f85119 | bigcode/the-stack | train |
71763be5e9af466fa1e892e0 | train | function | @div(_class="btn-group")
def goal_buttons():
url_new_goal = \
"location.href='{% url 'new-goal' %}';"
url_join_goal = \
"location.href='{% url 'join-goal' request.goal.slug %}';"
with django_if("not request.goal"):
with button(_class="btn btn-success", onclick=url_new_goal):
... | @div(_class="btn-group")
def goal_buttons():
| url_new_goal = \
"location.href='{% url 'new-goal' %}';"
url_join_goal = \
"location.href='{% url 'join-goal' request.goal.slug %}';"
with django_if("not request.goal"):
with button(_class="btn btn-success", onclick=url_new_goal):
text("New Goal")
with django_if("r... | request.global_user"
):
with button(_class="btn btn-info", onclick=url_update_suggestion):
text("Edit Suggestion")
with button(_class="btn btn-success", onclick=url_new_suggestion):
text("New Suggestion")
@div(_class="btn-group")
def goal_buttons():
| 64 | 64 | 122 | 12 | 52 | mnieber/shared-goal | django/main/templates/base_html.py | Python | goal_buttons | goal_buttons | 46 | 60 | 46 | 47 | 09afe810bb77f2cd6df4a865648bbeb559d2b370 | bigcode/the-stack | train |
c5b9e0d5a46c7e139d4c00b7 | train | function | @div(_class="btn-group")
def suggestion_buttons():
url_update_suggestion = (
"location.href='{% url 'update-suggestion' request.goal.slug "
"suggestion.slug %}';"
)
url_new_suggestion = \
"location.href='{% url 'new-suggestion' request.goal.slug %}';"
with django_if(
"su... | @div(_class="btn-group")
def suggestion_buttons():
| url_update_suggestion = (
"location.href='{% url 'update-suggestion' request.goal.slug "
"suggestion.slug %}';"
)
url_new_suggestion = \
"location.href='{% url 'new-suggestion' request.goal.slug %}';"
with django_if(
"suggestion and suggestion.owner == request.global_use... | a(href="{% url 'auth_logout' %}"):
text("{% trans 'Log out' %}")
with a(href="{% url 'auth_password_change' %}"):
text("{% trans 'Change password' %}")
@div(_class="btn-group")
def suggestion_buttons():
| 63 | 64 | 137 | 12 | 51 | mnieber/shared-goal | django/main/templates/base_html.py | Python | suggestion_buttons | suggestion_buttons | 27 | 43 | 27 | 28 | d0b0910a608ca401b0b41241aa26f891e2d7524c | bigcode/the-stack | train |
d1b2de0f5d95667c36d3f2e0 | train | function | @span
def top_left_div():
with a(href="{% url 'home' %}"):
text("Shared Goals")
with a(href="{% url 'about' %}"):
text("| About")
with a(href="{% url 'tos' %}"):
text("| Terms")
with a(href="{% url 'feedback' %}"):
text("| Give feedback")
| @span
def top_left_div():
| with a(href="{% url 'home' %}"):
text("Shared Goals")
with a(href="{% url 'about' %}"):
text("| About")
with a(href="{% url 'tos' %}"):
text("| Terms")
with a(href="{% url 'feedback' %}"):
text("| Give feedback")
| .member"):
suggestion_buttons()
with django_if("request.global_user"):
goal_buttons()
top_right_menu()
with django_else():
with a(href="{% url 'auth_login' %}"):
text("{% trans 'Log in' %}")
@span
def top_left_div():
| 63 | 64 | 86 | 8 | 55 | mnieber/shared-goal | django/main/templates/base_html.py | Python | top_left_div | top_left_div | 79 | 91 | 79 | 80 | 66d7d89359bfb5de47ff0fbca23936c4ce44cd5f | bigcode/the-stack | train |
16eb8b0b0b65df56391ef232 | train | function | @div(_class="pull-right")
def top_right_div():
with django_if("user.is_authenticated"):
with django_if("request.member"):
suggestion_buttons()
with django_if("request.global_user"):
goal_buttons()
top_right_menu()
with django_else():
with a(href... | @div(_class="pull-right")
def top_right_div():
| with django_if("user.is_authenticated"):
with django_if("request.member"):
suggestion_buttons()
with django_if("request.global_user"):
goal_buttons()
top_right_menu()
with django_else():
with a(href="{% url 'auth_login' %}"):
tex... | (_class="btn btn-success", onclick=url_new_goal):
text("New Goal")
with django_if("request.goal and not request.member"):
with button(_class="btn btn-success", onclick=url_join_goal):
text("Join Goal")
@div(_class="pull-right")
def top_right_div():
| 64 | 64 | 84 | 13 | 51 | mnieber/shared-goal | django/main/templates/base_html.py | Python | top_right_div | top_right_div | 63 | 76 | 63 | 64 | 7a87219d1996f71a5c5729041ad7cc4b7660d213 | bigcode/the-stack | train |
8173f1f03ab55d17dc24ebda | train | function | @div(_class="dropdown clearfix pull-right")
def top_right_menu():
with a(
_class="btn dropdown-toggle",
data_toggle="dropdown",
href="#"
):
text("{{ user.first_name }}")
span(_class="caret")
with ul(_class="dropdown-menu"):
with li():
with a(href="{% ... | @div(_class="dropdown clearfix pull-right")
def top_right_menu():
| with a(
_class="btn dropdown-toggle",
data_toggle="dropdown",
href="#"
):
text("{{ user.first_name }}")
span(_class="caret")
with ul(_class="dropdown-menu"):
with li():
with a(href="{% url 'auth_logout' %}"):
text("{% trans 'Log out' %... | from dominate.tags import *
from dominate.util import text
from django_dominate.django_tags import *
from goal.templates.dominate_tags import *
@div(_class="dropdown clearfix pull-right")
def top_right_menu():
| 43 | 64 | 121 | 15 | 28 | mnieber/shared-goal | django/main/templates/base_html.py | Python | top_right_menu | top_right_menu | 9 | 24 | 9 | 10 | 232881bbf4dd60758afd8ab01d797916e3348191 | bigcode/the-stack | train |
111a67cb473f3045ae34bcf7 | train | class | class FluxSched(AutotoolsPackage):
""" A scheduler for flux-core (pre-alpha) """
homepage = "https://github.com/flux-framework/flux-sched"
url = "https://github.com/flux-framework/flux-sched/releases/download/v0.5.0/flux-sched-0.5.0.tar.gz"
git = "https://github.com/flux-framework/flux-sched.... | class FluxSched(AutotoolsPackage):
| """ A scheduler for flux-core (pre-alpha) """
homepage = "https://github.com/flux-framework/flux-sched"
url = "https://github.com/flux-framework/flux-sched/releases/download/v0.5.0/flux-sched-0.5.0.tar.gz"
git = "https://github.com/flux-framework/flux-sched.git"
tags = ['radiuss', 'e4... | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import os
from spack import *
class FluxSched(AutotoolsPackage):
| 66 | 256 | 2,190 | 9 | 57 | BenWibking/spack | var/spack/repos/builtin/packages/flux-sched/package.py | Python | FluxSched | FluxSched | 11 | 157 | 11 | 11 | 4c5dd4ce2fa7d19993005410e3fa9325ba23f40d | bigcode/the-stack | train |
842c95dde9cff75a75b13d41 | train | function | def get_network(name, num_classes=21):
"""Get a network by name."""
if name.split('_')[0] == 'VGGnet':
if name.split('_')[1] == 'test':
return VGGnet_test(num_classes)
elif name.split('_')[1] == 'train':
return VGGnet_train()
elif name.split('_')[1] == 'testold':
... | def get_network(name, num_classes=21):
| """Get a network by name."""
if name.split('_')[0] == 'VGGnet':
if name.split('_')[1] == 'test':
return VGGnet_test(num_classes)
elif name.split('_')[1] == 'train':
return VGGnet_train()
elif name.split('_')[1] == 'testold':
return VGGnet_testold()
... | _testold
from .VGGnet_train import VGGnet_train
from .Resnet50_test import Resnet50_test
from .Resnet50_train import Resnet50_train
from .Resnet101_test import Resnet101_test
from .Resnet101_train import Resnet101_train
from .PVAnet_train import PVAnet_train
from .PVAnet_test import PVAnet_test
def get_network(name, nu... | 97 | 97 | 324 | 10 | 86 | aivsol/aivsol-TFFRCNN | lib/networks/factory.py | Python | get_network | get_network | 23 | 56 | 23 | 23 | db286ff6372e2b8299e10699952d4c8ce873d628 | bigcode/the-stack | train |
d911cbc6d54b34ecd51b6bea | train | function | def list_networks():
"""List all registered imdbs."""
return __sets.keys()
| def list_networks():
| """List all registered imdbs."""
return __sets.keys()
| 'test':
return PVAnet_test()
elif name.split('_')[1] == 'train':
return PVAnet_train()
else:
raise KeyError('Unknown dataset: {}'.format(name))
else:
raise KeyError('Unknown dataset: {}'.format(name))
def list_networks():
| 64 | 64 | 19 | 5 | 59 | aivsol/aivsol-TFFRCNN | lib/networks/factory.py | Python | list_networks | list_networks | 58 | 60 | 58 | 58 | 0ec9d68a083640ff173f2e7863e0e8014de947e1 | bigcode/the-stack | train |
68e189c8ee65cab4edf2f483 | train | class | class ZeroMQInterface:
def queue_device(
self,
worker_ipc: str,
worker_port: int,
host: str,
port: int,
):
"""
A queue_device maintains a queue to distribute the requests among the workers.
Remember the queue device is blocking.
Parameter... | class ZeroMQInterface:
| def queue_device(
self,
worker_ipc: str,
worker_port: int,
host: str,
port: int,
):
"""
A queue_device maintains a queue to distribute the requests among the workers.
Remember the queue device is blocking.
Parameters
----------
... | from typing import Callable
import zmq
import logging
import os
"""
If we want to replace the client-server patter with other implementation like Simple Pirate pattern,
implement the ZeroMQInterface class and replace the ZeroMQ with the new implementation instance.
"""
class ZeroMQInterface:
| 57 | 109 | 365 | 5 | 52 | hipacloud/zero | zero/zero_mq.py | Python | ZeroMQInterface | ZeroMQInterface | 12 | 67 | 12 | 12 | 3d2ac7d719540b7227b68f6133b55a9cf6437ff9 | bigcode/the-stack | train |
6205a5f9fd46e28154b07ad1 | train | class | class ZeroMQPythonDevice(ZeroMQInterface):
def queue_device(
self,
host: str,
port: int,
worker_ipc: str,
worker_port: int,
):
try:
ctx = zmq.Context.instance()
gateway = ctx.socket(zmq.ROUTER)
gateway.bind(f"tcp://{host}:{port}... | class ZeroMQPythonDevice(ZeroMQInterface):
| def queue_device(
self,
host: str,
port: int,
worker_ipc: str,
worker_port: int,
):
try:
ctx = zmq.Context.instance()
gateway = ctx.socket(zmq.ROUTER)
gateway.bind(f"tcp://{host}:{port}")
logging.info(f"Starting serv... | _port.
worker_port: int
It is used if ipc is not supported by os.
worker_id: int
The id of the worker.
process_message: Callable
The function that will process the message.
It takes the rpc method name and msg in parameters as bytes and should retu... | 105 | 105 | 351 | 10 | 95 | hipacloud/zero | zero/zero_mq.py | Python | ZeroMQPythonDevice | ZeroMQPythonDevice | 70 | 123 | 70 | 70 | e8b381caef2054c2554915097036db562799630a | bigcode/the-stack | train |
74c4300aeb3d0db2e5e828d0 | train | class | class EccCPU_SIM():
reg = [0,0,0,0]
ram = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
pc = 0
flags = 0
rom = ""
step = False
code = []
symbols = {}
instr_limit = 1024
flag_bits = {'zero': 1, 'neg': 2, 'carry': 4,
'>u': 8, '<u': 16, '=': 32,
'>s': 64, '... | class EccCPU_SIM():
| reg = [0,0,0,0]
ram = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
pc = 0
flags = 0
rom = ""
step = False
code = []
symbols = {}
instr_limit = 1024
flag_bits = {'zero': 1, 'neg': 2, 'carry': 4,
'>u': 8, '<u': 16, '=': 32,
'>s': 64, '<s': 128}
def r... | #!/usr/bin/env python
class EccCPU_SIM():
| 12 | 256 | 1,846 | 6 | 5 | nobodywasishere/EccCPU | ecccpu/ecccpu_sim.py | Python | EccCPU_SIM | EccCPU_SIM | 3 | 163 | 3 | 3 | a4246c8b3b05a71e70b6ef5c93b6e4f4c479302c | bigcode/the-stack | train |
b7a9307f8c90ea94db421448 | train | class | class Initialization(object):
r"""
State space initialization
Parameters
----------
k_states : int
exact_diffuse_initialization : bool, optional
Whether or not to use exact diffuse initialization; only has an effect
if some states are initialized as diffuse. Default is True.
... | class Initialization(object):
| r"""
State space initialization
Parameters
----------
k_states : int
exact_diffuse_initialization : bool, optional
Whether or not to use exact diffuse initialization; only has an effect
if some states are initialized as diffuse. Default is True.
approximate_diffuse_variance ... | """
State Space Representation - Initialization
Author: Chad Fulton
License: Simplified-BSD
"""
import warnings
import numpy as np
from . import tools
class Initialization(object):
| 37 | 256 | 5,587 | 4 | 32 | KshitizSharmaV/Quant_Platform_Python | lib/python3.6/site-packages/statsmodels/tsa/statespace/initialization.py | Python | Initialization | Initialization | 14 | 613 | 14 | 14 | 9c0d979210979225d8b574f31060845b6b94918c | bigcode/the-stack | train |
867b3f76c14d60d67784fe8f | train | class | class Metric(Enum):
TRAINING_ACCURACY = 'Training Accuracy'
VALIDATION_ACCURACY = 'Validation Accuracy'
TESTING_ACCURACY = 'Testing Accuracy'
VALIDATION_WEIGHTED_F1 = 'Validation Weighted F1 Score'
TESTING_WEIGHTED_F1 = 'Testing Weighted F1 Score'
VALIDATION_WEIGHTED_PRECISION = 'Validation Wei... | class Metric(Enum):
| TRAINING_ACCURACY = 'Training Accuracy'
VALIDATION_ACCURACY = 'Validation Accuracy'
TESTING_ACCURACY = 'Testing Accuracy'
VALIDATION_WEIGHTED_F1 = 'Validation Weighted F1 Score'
TESTING_WEIGHTED_F1 = 'Testing Weighted F1 Score'
VALIDATION_WEIGHTED_PRECISION = 'Validation Weighted Precision'
... | from enum import Enum
from typing import Optional
import numpy as np
import sklearn.metrics as sk_metrics
from framework.trackers import Numeric, Aggregator
class Metric(Enum):
| 36 | 112 | 374 | 4 | 31 | Wattpad/gatas | framework/trackers/metrics.py | Python | Metric | Metric | 10 | 44 | 10 | 10 | 2fa84fc93776af0012258b94b0e719d37642f681 | bigcode/the-stack | train |
5473ac7fe16875f668071ec7 | train | class | class MetricFunctions:
@staticmethod
def accuracy(targets: np.ndarray, predictions: np.ndarray) -> Numeric:
return sk_metrics.accuracy_score(targets, predictions)
@staticmethod
def precision(targets: np.ndarray, predictions: np.ndarray, average: Optional[str] = 'weighted') -> Numeric:
r... | class MetricFunctions:
@staticmethod
| def accuracy(targets: np.ndarray, predictions: np.ndarray) -> Numeric:
return sk_metrics.accuracy_score(targets, predictions)
@staticmethod
def precision(targets: np.ndarray, predictions: np.ndarray, average: Optional[str] = 'weighted') -> Numeric:
return sk_metrics.precision_score(targets,... | Micro Recall'
TESTING_MICRO_RECALL = 'Testing Micro Recall'
TRAINING_MACRO_F1 = 'Training Macro F1 Score'
VALIDATION_MACRO_F1 = 'Validation Macro F1 Score'
TESTING_MACRO_F1 = 'Testing Macro F1 Score'
VALIDATION_MACRO_PRECISION = 'Validation Macro Precision'
TESTING_MACRO_PRECISION = 'Testing M... | 182 | 182 | 608 | 8 | 174 | Wattpad/gatas | framework/trackers/metrics.py | Python | MetricFunctions | MetricFunctions | 47 | 114 | 47 | 48 | 417153a1fc3844487b01e9ed50f4fa03317af2b2 | bigcode/the-stack | train |
c2d5302912e3707f0cac4493 | train | class | class Correlator(ampcor.protocol, family="ampcor.correlators"):
"""
The protocol for all AMPCOR correlator implementations
"""
# requirements
@ampcor.provides
def estimate(self, plexus, reference, target):
"""
Estimate the offset field between a pair of raster images
""... | class Correlator(ampcor.protocol, family="ampcor.correlators"):
| """
The protocol for all AMPCOR correlator implementations
"""
# requirements
@ampcor.provides
def estimate(self, plexus, reference, target):
"""
Estimate the offset field between a pair of raster images
"""
# hooks
@classmethod
def pyre_default(cls, **kwd... | vázis <michael.aivazis@para-sim.com>
# parasim
# (c) 1998-2019 all rights reserved
#
# framework
import ampcor
# declaration
class Correlator(ampcor.protocol, family="ampcor.correlators"):
| 64 | 64 | 129 | 17 | 46 | isce-framework/ampcor | pkg/ampcor/correlators/Correlator.py | Python | Correlator | Correlator | 15 | 38 | 15 | 15 | 1b2615a1972b7188cd91744538593d8518e8684b | bigcode/the-stack | train |
2972d603dd6f92035ef10406 | train | class | class InstanryConfig(AppConfig):
name = 'instanry'
| class InstanryConfig(AppConfig):
| name = 'instanry'
| from django.apps import AppConfig
class InstanryConfig(AppConfig):
| 15 | 64 | 16 | 8 | 6 | hope-mbuthye38/instaclonery | instanry/apps.py | Python | InstanryConfig | InstanryConfig | 4 | 5 | 4 | 4 | dd42c7585cd558924e772613c58e4c873cbec55a | bigcode/the-stack | train |
c7c23c57be80f4dbf854b6ce | train | class | class TestEvaluation(unittest.TestCase):
def test_init_should_init(self):
ev = mls.sl.models.Evaluation()
self.assertIsInstance(ev, mls.sl.models.Evaluation)
def test_to_dict_should_converted(self):
ev = mls.sl.models.Evaluation()
expected = {'type': 'Evaluation'}
resul... | class TestEvaluation(unittest.TestCase):
| def test_init_should_init(self):
ev = mls.sl.models.Evaluation()
self.assertIsInstance(ev, mls.sl.models.Evaluation)
def test_to_dict_should_converted(self):
ev = mls.sl.models.Evaluation()
expected = {'type': 'Evaluation'}
result = ev.to_dict()
self.assertDictEq... | import unittest
import mlsurvey as mls
class TestEvaluation(unittest.TestCase):
| 18 | 64 | 135 | 7 | 10 | jlaumonier/mlsurvey | test/test_sl/test_model/test_evaluation.py | Python | TestEvaluation | TestEvaluation | 6 | 22 | 6 | 7 | 3635c7bb13f1e99d8b5ba4fb861c94b36b1bf695 | bigcode/the-stack | train |
91e3d746149fd4348f19ab15 | train | class | class Browser_Get_Code(Browser):
def __init__(
self,
binary_location,
chrome_driver,
use_tabs=False,
personal_information=dict(),
):
super().__init__(binary_location, chrome_driver, use_tabs)
self.check_button_xpath = "/html/body/app-root/div/app-pag... | class Browser_Get_Code(Browser):
| def __init__(
self,
binary_location,
chrome_driver,
use_tabs=False,
personal_information=dict(),
):
super().__init__(binary_location, chrome_driver, use_tabs)
self.check_button_xpath = "/html/body/app-root/div/app-page-its-login/div/div/div[2]/app-its-log... | .driver.find_element_by_xpath(self.cookie_xpath)
logging.info(" ACTION: Acknowledge cookies.")
cookie_button.click()
time.sleep(1)
logging.info(" ACTION: Reload desired website")
self._open_url(url)
logging.info(" ... | 256 | 256 | 997 | 8 | 247 | andreasdoerr/impf_termin_tester | impf_termin_tester/browser.py | Python | Browser_Get_Code | Browser_Get_Code | 238 | 331 | 238 | 239 | ba71f09059c84fbeeea1a31dfc0e9cec399eb0dd | bigcode/the-stack | train |
015681c9f2f8d069ad823db9 | train | class | class Browser:
Result = namedtuple("Result", ["source", "screenshot", "time", "url"])
def __init__(self, binary_location, chrome_driver, use_tabs=True):
# Path to chrome executable and chrome driver executable
self.binary_location = binary_location
self.chrome_driver = chrome_driver
... | class Browser:
| Result = namedtuple("Result", ["source", "screenshot", "time", "url"])
def __init__(self, binary_location, chrome_driver, use_tabs=True):
# Path to chrome executable and chrome driver executable
self.binary_location = binary_location
self.chrome_driver = chrome_driver
self.tabs... | import time
import logging
from collections import namedtuple, defaultdict
from datetime import datetime
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
class Browser:
| 53 | 256 | 1,859 | 3 | 49 | andreasdoerr/impf_termin_tester | impf_termin_tester/browser.py | Python | Browser | Browser | 12 | 235 | 12 | 13 | 8960676663c19380460e3c1dd234c3384345ce74 | bigcode/the-stack | train |
8338b63c9997511db13dc48a | train | class | class FormPesquisa(forms.Form):
monitoramento = forms.ModelChoiceField(
widget = forms.Select(
attrs = {'class': 'form-control'}
),
queryset = Monitoramento.objects.order_by('ponto_monitoramento', 'data_monitoramento').all(),
empty_label = "Selecione uma data de monitoramento"
)
entorno = forms.ModelCh... | class FormPesquisa(forms.Form):
| monitoramento = forms.ModelChoiceField(
widget = forms.Select(
attrs = {'class': 'form-control'}
),
queryset = Monitoramento.objects.order_by('ponto_monitoramento', 'data_monitoramento').all(),
empty_label = "Selecione uma data de monitoramento"
)
entorno = forms.ModelChoiceField(
widget = forms.Selec... | #coding: utf-8
from apptcc.models import Entorno, Monitoramento
from django import forms
class FormPesquisa(forms.Form):
| 30 | 64 | 129 | 6 | 23 | fndomariano/prototipo-rbc | apptcc/forms/pesquisa.py | Python | FormPesquisa | FormPesquisa | 6 | 22 | 6 | 7 | 08962c8893b935cb0e973321afb94c5750fd4887 | bigcode/the-stack | train |
dcf49f14e7e124a162e74597 | train | class | @mock.patch(MODULE + '.storage')
@mock.patch('kfp_component.google.dataflow._common_ops.display')
@mock.patch(MODULE + '.KfpExecutionContext')
@mock.patch(MODULE + '.DataflowClient')
class LaunchFlexTemplateTest(unittest.TestCase):
def test_launch_flex_template_succeed(
self, mock_client, mock_context, moc... | @mock.patch(MODULE + '.storage')
@mock.patch('kfp_component.google.dataflow._common_ops.display')
@mock.patch(MODULE + '.KfpExecutionContext')
@mock.patch(MODULE + '.DataflowClient')
class LaunchFlexTemplateTest(unittest.TestCase):
| def test_launch_flex_template_succeed(
self, mock_client, mock_context, mock_display, mock_storage
):
mock_context().__enter__().context_id.return_value = 'context-1'
mock_storage.Client().bucket().blob().exists.return_value = False
mock_client().launch_flex_template.return_value... | import unittest
import mock
from kfp_component.google.dataflow import launch_flex_template
MODULE = 'kfp_component.google.dataflow._launch_flex_template'
@mock.patch(MODULE + '.storage')
@mock.patch('kfp_component.google.dataflow._common_ops.display')
@mock.patch(MODULE + '.KfpExecutionContext')
@mock.patch(MODULE + ... | 90 | 236 | 789 | 56 | 34 | Strasser-Pablo/pipelines | components/gcp/container/component_sdk/python/tests/google/dataflow/test__launch_flex_template.py | Python | LaunchFlexTemplateTest | LaunchFlexTemplateTest | 9 | 107 | 9 | 14 | b0101f3dbd30e695465a0e194539f3df3e87c09c | bigcode/the-stack | train |
9efdb50ddfacf319d6d49df4 | train | function | def _run_pickle_model(model_dir, model_name):
sklearn_model, data = _train_sample_model()
model_file = os.path.join(model_dir, model_name)
pickle.dump(sklearn_model, open(model_file, 'wb'))
model = SKLearnModel("model", model_dir)
model.load()
request = data[0:1].tolist()
response = model.pr... | def _run_pickle_model(model_dir, model_name):
| sklearn_model, data = _train_sample_model()
model_file = os.path.join(model_dir, model_name)
pickle.dump(sklearn_model, open(model_file, 'wb'))
model = SKLearnModel("model", model_dir)
model.load()
request = data[0:1].tolist()
response = model.predict({"instances": request})
assert respo... | ")
def _train_sample_model():
iris = datasets.load_iris()
X, y = iris.data, iris.target
sklearn_model = svm.SVC(gamma='scale')
sklearn_model.fit(X, y)
return sklearn_model, X
def _run_pickle_model(model_dir, model_name):
| 64 | 64 | 98 | 11 | 52 | animesh-agarwal/kfserving | python/sklearnserver/sklearnserver/test_model.py | Python | _run_pickle_model | _run_pickle_model | 39 | 47 | 39 | 39 | a51e09ad746f93058e5563db5a132bc02eaaf7fa | bigcode/the-stack | train |
c99d7214bf0fb92f33836281 | train | function | def _train_sample_model():
iris = datasets.load_iris()
X, y = iris.data, iris.target
sklearn_model = svm.SVC(gamma='scale')
sklearn_model.fit(X, y)
return sklearn_model, X
| def _train_sample_model():
| iris = datasets.load_iris()
X, y = iris.data, iris.target
sklearn_model = svm.SVC(gamma='scale')
sklearn_model.fit(X, y)
return sklearn_model, X
| = [[os.path.join(_MODEL_DIR, "pkl", "model"), "model.pkl"],
[os.path.join(_MODEL_DIR, "pickle", "model"), "model.pickle"]]
MULTI_DIR = os.path.join(_MODEL_DIR, "multi", "model")
def _train_sample_model():
| 64 | 64 | 52 | 6 | 58 | animesh-agarwal/kfserving | python/sklearnserver/sklearnserver/test_model.py | Python | _train_sample_model | _train_sample_model | 31 | 36 | 31 | 31 | 6cfae5fc754343c2d483bcf8f67421583d884eca | bigcode/the-stack | train |
ebc028bb8d56d5c6bcb4e65e | train | function | def test_model_joblib():
sklearn_model, data = _train_sample_model()
model_file = os.path.join(JOBLIB_FILE[0], JOBLIB_FILE[1])
joblib.dump(value=sklearn_model, filename=model_file)
model = SKLearnModel("model", JOBLIB_FILE[0])
model.load()
request = data[0:1].tolist()
response = model.predic... | def test_model_joblib():
| sklearn_model, data = _train_sample_model()
model_file = os.path.join(JOBLIB_FILE[0], JOBLIB_FILE[1])
joblib.dump(value=sklearn_model, filename=model_file)
model = SKLearnModel("model", JOBLIB_FILE[0])
model.load()
request = data[0:1].tolist()
response = model.predict({"instances": request})... | arn_model, open(model_file, 'wb'))
model = SKLearnModel("model", model_dir)
model.load()
request = data[0:1].tolist()
response = model.predict({"instances": request})
assert response["predictions"] == [0]
def test_model_joblib():
| 64 | 64 | 102 | 6 | 58 | animesh-agarwal/kfserving | python/sklearnserver/sklearnserver/test_model.py | Python | test_model_joblib | test_model_joblib | 50 | 58 | 50 | 50 | b90c1247a3113c7255636b8ac164b77d013fade4 | bigcode/the-stack | train |
025616569ffb98bb941dc1d8 | train | function | def test_dir_with_no_model():
model = SKLearnModel("model", _MODEL_DIR)
with pytest.raises(RuntimeError) as e:
model.load()
assert 'Missing Model File' in str(e.value)
| def test_dir_with_no_model():
| model = SKLearnModel("model", _MODEL_DIR)
with pytest.raises(RuntimeError) as e:
model.load()
assert 'Missing Model File' in str(e.value)
| 0:1].tolist()
response = model.predict({"instances": request})
assert response["predictions"] == [0]
def test_model_pickle():
for pickle_file in PICKLE_FILES:
_run_pickle_model(pickle_file[0], pickle_file[1])
def test_dir_with_no_model():
| 64 | 64 | 46 | 7 | 57 | animesh-agarwal/kfserving | python/sklearnserver/sklearnserver/test_model.py | Python | test_dir_with_no_model | test_dir_with_no_model | 66 | 70 | 66 | 66 | e31a958642bb1bc2df87e91fe8d2495feabe6a7b | bigcode/the-stack | train |
a6f432c1ef3cdd1491bd3127 | train | function | def test_model_pickle():
for pickle_file in PICKLE_FILES:
_run_pickle_model(pickle_file[0], pickle_file[1])
| def test_model_pickle():
| for pickle_file in PICKLE_FILES:
_run_pickle_model(pickle_file[0], pickle_file[1])
| sklearn_model, filename=model_file)
model = SKLearnModel("model", JOBLIB_FILE[0])
model.load()
request = data[0:1].tolist()
response = model.predict({"instances": request})
assert response["predictions"] == [0]
def test_model_pickle():
| 64 | 64 | 30 | 5 | 59 | animesh-agarwal/kfserving | python/sklearnserver/sklearnserver/test_model.py | Python | test_model_pickle | test_model_pickle | 61 | 63 | 61 | 61 | 53cab41e80ec0295654091ddeb27130fec917951 | bigcode/the-stack | train |
1d030bbcfe7c8d74928513d8 | train | function | def test_dir_with_two_models():
model = SKLearnModel("model", MULTI_DIR)
with pytest.raises(RuntimeError) as e:
model.load()
assert 'More than one model file is detected' in str(e.value)
| def test_dir_with_two_models():
| model = SKLearnModel("model", MULTI_DIR)
with pytest.raises(RuntimeError) as e:
model.load()
assert 'More than one model file is detected' in str(e.value)
| (pickle_file[0], pickle_file[1])
def test_dir_with_no_model():
model = SKLearnModel("model", _MODEL_DIR)
with pytest.raises(RuntimeError) as e:
model.load()
assert 'Missing Model File' in str(e.value)
def test_dir_with_two_models():
| 64 | 64 | 50 | 7 | 57 | animesh-agarwal/kfserving | python/sklearnserver/sklearnserver/test_model.py | Python | test_dir_with_two_models | test_dir_with_two_models | 73 | 77 | 73 | 73 | 8c4c3ea05a052c7e415dfcbf9a31d1f9ade75d6c | bigcode/the-stack | train |
ad31005e8f92d4850335da86 | train | class | class Migration(migrations.Migration):
initial = True
dependencies = [
('events', '0002_auto_20200219_1614'),
]
operations = [
migrations.CreateModel(
name='Certificate',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, seri... | class Migration(migrations.Migration):
| initial = True
dependencies = [
('events', '0002_auto_20200219_1614'),
]
operations = [
migrations.CreateModel(
name='Certificate',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
... | # Generated by Django 2.2 on 2021-02-12 07:07
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
| 46 | 64 | 156 | 7 | 38 | Robotix-NITRR/RobotixWeb2021 | certificate/migrations/0001_initial.py | Python | Migration | Migration | 8 | 27 | 8 | 9 | 301c730149306318eee73272bdf5a093d0ffb01c | bigcode/the-stack | train |
c37eea195d75bd88ca869ab0 | train | function | @app.route('/<int:personID>')
@app.route('/<int:personID>/')
def redirection_person_days(personID):
return redirect('/' + str(personID) + '/' + '31')
| @app.route('/<int:personID>')
@app.route('/<int:personID>/')
def redirection_person_days(personID):
| return redirect('/' + str(personID) + '/' + '31')
| Flask
#------------------------------------------------------------------------------------------
app = Flask(__name__)
@app.route('/')
def index():
return render_template('login.html', enumerate=enumerate, list=list, persons=persons)
@app.route('/<int:personID>')
@app.route('/<int:personID>/')
def redirection_pe... | 64 | 64 | 42 | 27 | 37 | meggiman/BS440 | plugins/BS440webapp/BS440flask.py | Python | redirection_person_days | redirection_person_days | 59 | 64 | 59 | 63 | 323907b1e76889974b5d1046ddadd72aabb124e2 | bigcode/the-stack | train |
4c5aecf968104032df1821f7 | train | function | @app.route('/<int:personID>/<int:days>')
@app.route('/<int:personID>/<int:days>/')
def person(personID, days):
def updatePlot():
os.system('python BS440plot.py -p ' + str(personID) + ' -w ' + str(days))
personsection = 'Person' + str(personID)
if config.has_section(personsection):
person = config.get(personse... | @app.route('/<int:personID>/<int:days>')
@app.route('/<int:personID>/<int:days>/')
def person(personID, days):
| def updatePlot():
os.system('python BS440plot.py -p ' + str(personID) + ' -w ' + str(days))
personsection = 'Person' + str(personID)
if config.has_section(personsection):
person = config.get(personsection, 'username')
else:
return redirect('/')
plotTemplate = 'plot-' + str(personID) + '-' + str(days) + '.... | )
@app.route('/<int:personID>')
@app.route('/<int:personID>/')
def redirection_person_days(personID):
return redirect('/' + str(personID) + '/' + '31')
@app.route('/<int:personID>/<int:days>')
@app.route('/<int:personID>/<int:days>/')
def person(personID, days):
| 77 | 77 | 259 | 34 | 43 | meggiman/BS440 | plugins/BS440webapp/BS440flask.py | Python | person | person | 67 | 101 | 67 | 71 | ff49cecb1637abb71841628c015222d1c984fcb7 | bigcode/the-stack | train |
1eca7fd1e54d6085d1de9be6 | train | function | @app.route('/')
def index():
return render_template('login.html', enumerate=enumerate, list=list, persons=persons)
| @app.route('/')
def index():
| return render_template('login.html', enumerate=enumerate, list=list, persons=persons)
| ():
if config.has_option(section_name, 'username'):
persons.append(config.get(section_name, 'username'))
personsdata.append(persons)
if personsdata == []:
sys.exit(127)
#------------------------------------------------------------------------------------------
# Flask
#-----------------------------------------... | 64 | 64 | 26 | 7 | 57 | meggiman/BS440 | plugins/BS440webapp/BS440flask.py | Python | index | index | 52 | 56 | 52 | 55 | bcbe8da8bcf7808e1df1b37bcdbe2ac6b317d85b | bigcode/the-stack | train |
68c4a9a283b60d56d12c9fc1 | train | function | def AbelianGroup(*cyclic_orders):
"""
Returns the direct product of cyclic groups with the given orders.
According to the structure theorem for finite abelian groups ([1]),
every finite abelian group can be written as the direct product of
finitely many cyclic groups.
Examples
========
... | def AbelianGroup(*cyclic_orders):
| """
Returns the direct product of cyclic groups with the given orders.
According to the structure theorem for finite abelian groups ([1]),
every finite abelian group can be written as the direct product of
finitely many cyclic groups.
Examples
========
>>> Permutation.print_cyclic = T... | from .group_constructs import DirectProduct
from .perm_groups import PermutationGroup
from .permutations import Permutation
_af_new = Permutation._af_new
def AbelianGroup(*cyclic_orders):
| 45 | 78 | 263 | 9 | 35 | rajkk1/diofant | diofant/combinatorics/named_groups.py | Python | AbelianGroup | AbelianGroup | 9 | 51 | 9 | 9 | 6095215c6fec8521400ccaf03b743e270be0ac3c | bigcode/the-stack | train |
6e11e731bc930ebd29347185 | train | function | def RubikGroup(n):
"""Return a group of Rubik's cube generators.
>>> RubikGroup(2).is_group
True
"""
from .generators import rubik
if n <= 1:
raise ValueError('Invalid cube . n has to be greater than 1')
return PermutationGroup(rubik(n))
| def RubikGroup(n):
| """Return a group of Rubik's cube generators.
>>> RubikGroup(2).is_group
True
"""
from .generators import rubik
if n <= 1:
raise ValueError('Invalid cube . n has to be greater than 1')
return PermutationGroup(rubik(n))
| False
if n < 5:
G._is_solvable = True
else:
G._is_solvable = False
G._degree = n
G._is_transitive = True
G._is_sym = True
return G
def RubikGroup(n):
| 64 | 64 | 77 | 6 | 57 | rajkk1/diofant | diofant/combinatorics/named_groups.py | Python | RubikGroup | RubikGroup | 290 | 300 | 290 | 290 | 19c2bdb941ddf4318cc62f3145670c840ada9cf6 | bigcode/the-stack | train |
1596cc9586425bb3153962bb | train | function | def DihedralGroup(n):
r"""
Generates the dihedral group `D_n` as a permutation group.
The dihedral group `D_n` is the group of symmetries of the regular
``n``-gon. The generators taken are the ``n``-cycle ``a = (0 1 2 ... n-1)``
(a rotation of the ``n``-gon) and ``b = (0 n-1)(1 n-2)...``
(a ref... | def DihedralGroup(n):
| r"""
Generates the dihedral group `D_n` as a permutation group.
The dihedral group `D_n` is the group of symmetries of the regular
``n``-gon. The generators taken are the ``n``-cycle ``a = (0 1 2 ... n-1)``
(a rotation of the ``n``-gon) and ``b = (0 n-1)(1 n-2)...``
(a reflection of the ``n``-g... | 0], [2, 3, 4, 5, 0, 1],
[3, 4, 5, 0, 1, 2], [4, 5, 0, 1, 2, 3], [5, 0, 1, 2, 3, 4]]
See Also
========
SymmetricGroup, DihedralGroup, AlternatingGroup
"""
a = list(range(1, n))
a.append(0)
gen = _af_new(a)
G = PermutationGroup([gen])
G._is_abelian = True
G._is_nilpotent = ... | 193 | 193 | 644 | 6 | 186 | rajkk1/diofant | diofant/combinatorics/named_groups.py | Python | DihedralGroup | DihedralGroup | 164 | 224 | 164 | 164 | ab2edccd0be779fd3530a7afbbbb2b4e5f5bb67b | bigcode/the-stack | train |
ddb51fabf1583c34d75b3dd3 | train | function | def SymmetricGroup(n):
"""
Generates the symmetric group on ``n`` elements as a permutation group.
The generators taken are the ``n``-cycle
``(0 1 2 ... n-1)`` and the transposition ``(0 1)`` (in cycle notation).
(See [1]). After the group is generated, some of its basic properties
are set.
... | def SymmetricGroup(n):
| """
Generates the symmetric group on ``n`` elements as a permutation group.
The generators taken are the ``n``-cycle
``(0 1 2 ... n-1)`` and the transposition ``(0 1)`` (in cycle notation).
(See [1]). After the group is generated, some of its basic properties
are set.
Examples
========... | Group([Permutation([1, 0, 3, 2]),
Permutation([2, 3, 0, 1]), Permutation([3, 2, 1, 0])])
a = list(range(1, n))
a.append(0)
gen1 = _af_new(a)
a = list(range(n))
a.reverse()
gen2 = _af_new(a)
G = PermutationGroup([gen1, gen2])
# if n is a power of 2, group... | 210 | 210 | 701 | 6 | 203 | rajkk1/diofant | diofant/combinatorics/named_groups.py | Python | SymmetricGroup | SymmetricGroup | 227 | 287 | 227 | 227 | 20a7fd64fc774b43e7b9f8cf321393bc339ea776 | bigcode/the-stack | train |
43418126929736615b7498ff | train | function | def AlternatingGroup(n):
"""
Generates the alternating group on ``n`` elements as a permutation group.
For ``n > 2``, the generators taken are ``(0 1 2), (0 1 2 ... n-1)`` for
``n`` odd
and ``(0 1 2), (1 2 ... n-1)`` for ``n`` even (See [1], p.31, ex.6.9.).
After the group is generated, some of... | def AlternatingGroup(n):
| """
Generates the alternating group on ``n`` elements as a permutation group.
For ``n > 2``, the generators taken are ``(0 1 2), (0 1 2 ... n-1)`` for
``n`` odd
and ``(0 1 2), (1 2 ... n-1)`` for ``n`` even (See [1], p.31, ex.6.9.).
After the group is generated, some of its basic properties are... | 4, 5, 6)])
>>> _.is_group
True
See Also
========
diofant.combinatorics.group_constructs.DirectProduct
References
==========
* https://groupprops.subwiki.org/wiki/Structure_theorem_for_finitely_generated_abelian_groups
"""
groups = []
degree = 0
order = 1
for siz... | 156 | 156 | 521 | 6 | 149 | rajkk1/diofant | diofant/combinatorics/named_groups.py | Python | AlternatingGroup | AlternatingGroup | 54 | 121 | 54 | 54 | 7fc5b303aeeb2361b10385049c9f7f7d75dd4d92 | bigcode/the-stack | train |
c0c19b10372ea60fcc9f5431 | train | function | def CyclicGroup(n):
"""
Generates the cyclic group of order ``n`` as a permutation group.
The generator taken is the ``n``-cycle ``(0 1 2 ... n-1)``
(in cycle notation). After the group is generated, some of its basic
properties are set.
Examples
========
>>> G = CyclicGroup(6)
>>... | def CyclicGroup(n):
| """
Generates the cyclic group of order ``n`` as a permutation group.
The generator taken is the ``n``-cycle ``(0 1 2 ... n-1)``
(in cycle notation). After the group is generated, some of its basic
properties are set.
Examples
========
>>> G = CyclicGroup(6)
>>> G.is_group
Tru... | is_abelian = True
G._is_nilpotent = True
else:
G._is_abelian = False
G._is_nilpotent = False
if n < 5:
G._is_solvable = True
else:
G._is_solvable = False
G._degree = n
G._is_transitive = True
G._is_alt = True
return G
def CyclicGroup(n):
| 102 | 102 | 341 | 6 | 95 | rajkk1/diofant | diofant/combinatorics/named_groups.py | Python | CyclicGroup | CyclicGroup | 124 | 161 | 124 | 124 | 2c233d14cb642e3c5b5b10818ba06dc79abf2070 | bigcode/the-stack | train |
1232b96dc381a9ec64336cb1 | train | class | class Rods(namedtuple('Rods', ('start', 'end', 'tmp')), Sequence, Validatable, Serializable):
"""
A collection of 3 Rod's that form the Tower.
:param Rod start:
The rod containing the disks at their start position.
:param Rod end:
The rod containing the disks at their end position.
... | class Rods(namedtuple('Rods', ('start', 'end', 'tmp')), Sequence, Validatable, Serializable):
| """
A collection of 3 Rod's that form the Tower.
:param Rod start:
The rod containing the disks at their start position.
:param Rod end:
The rod containing the disks at their end position.
:param Rod tmp:
The intermediary rod.
:param int height:
The height of the... | #!/usr/bin/env python
# -*- coding: latin-1 -*-
#
# @module towers.core.rods
# @version 0.1
# @copyright (c) 2017-present Francis Horsman.
import copy
import json
from collections import Sequence, namedtuple
import six
from .disk import Disk
from .errors import InvalidRod, InvalidRodHeight
from .rod import Rod
from ... | 134 | 256 | 1,124 | 25 | 109 | sys-git/towers | towers/core/rods.py | Python | Rods | Rods | 23 | 222 | 23 | 23 | 8abcd17f9bfa5b1e6ab951aba512798e740ace89 | bigcode/the-stack | train |
0823fd42e85159f4a624bc62 | train | class | class sensorapi(object):
def __init__(self):
self.sensor_count = int()
self.controller_count = int()
self.sensor = {"temp":"","ldr":""}
self.controller = {"ac_controller":""}
self.clocation = sys.argv[1]
def setSensorCount(self, count):
self.sensor_count = c... | class sensorapi(object):
| def __init__(self):
self.sensor_count = int()
self.controller_count = int()
self.sensor = {"temp":"","ldr":""}
self.controller = {"ac_controller":""}
self.clocation = sys.argv[1]
def setSensorCount(self, count):
self.sensor_count = count
def setControlle... | import sys
from commAPI import obj
import json
class sensorapi(object):
| 17 | 81 | 271 | 5 | 11 | ronitray95/ias_hackathon1 | hackathon2/pawan/API.py | Python | sensorapi | sensorapi | 5 | 45 | 5 | 6 | ada5a2f2aa32439900ec5647b349d8bf736175d3 | bigcode/the-stack | train |
7a4cca1e0893414744eb7b85 | train | function | def get_mesh(mesh_owner: Optional[str] = None,
name: Optional[str] = None,
tags: Optional[Mapping[str, str]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetMeshResult:
"""
The App Mesh Mesh data source allows details of an App Mesh Mesh to be retrieved... | def get_mesh(mesh_owner: Optional[str] = None,
name: Optional[str] = None,
tags: Optional[Mapping[str, str]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetMeshResult:
| """
The App Mesh Mesh data source allows details of an App Mesh Mesh to be retrieved by its name and optionally the mesh_owner.
## Example Usage
```python
import pulumi
import pulumi_aws as aws
simple = aws.appmesh.get_mesh(name="simpleapp")
```
```python
import pulumi
im... | False:
yield self
return GetMeshResult(
arn=self.arn,
created_date=self.created_date,
id=self.id,
last_updated_date=self.last_updated_date,
mesh_owner=self.mesh_owner,
name=self.name,
resource_owner=self.resource_ow... | 123 | 123 | 413 | 54 | 69 | alexbowers/pulumi-aws | sdk/python/pulumi_aws/appmesh/get_mesh.py | Python | get_mesh | get_mesh | 136 | 185 | 136 | 139 | a0cfdd5db49d8e88c992b31a8904af3627fe4036 | bigcode/the-stack | train |
2ccc85daad29f10c738ff764 | train | class | class AwaitableGetMeshResult(GetMeshResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return GetMeshResult(
arn=self.arn,
created_date=self.created_date,
id=self.id,
last_updated_date=self.last_upd... | class AwaitableGetMeshResult(GetMeshResult):
# pylint: disable=using-constant-test
| def __await__(self):
if False:
yield self
return GetMeshResult(
arn=self.arn,
created_date=self.created_date,
id=self.id,
last_updated_date=self.last_updated_date,
mesh_owner=self.mesh_owner,
name=self.name,
... | ")
@property
@pulumi.getter
def tags(self) -> Mapping[str, str]:
"""
A map of tags.
"""
return pulumi.get(self, "tags")
class AwaitableGetMeshResult(GetMeshResult):
# pylint: disable=using-constant-test
| 64 | 64 | 99 | 21 | 43 | alexbowers/pulumi-aws | sdk/python/pulumi_aws/appmesh/get_mesh.py | Python | AwaitableGetMeshResult | AwaitableGetMeshResult | 119 | 133 | 119 | 120 | 993afd219d7a1aecf1e3b2e79e331fb27babafeb | bigcode/the-stack | train |
a62e674aa6d42e6d258a5f9e | train | class | @pulumi.output_type
class GetMeshResult:
"""
A collection of values returned by getMesh.
"""
def __init__(__self__, arn=None, created_date=None, id=None, last_updated_date=None, mesh_owner=None, name=None, resource_owner=None, specs=None, tags=None):
if arn and not isinstance(arn, str):
... | @pulumi.output_type
class GetMeshResult:
| """
A collection of values returned by getMesh.
"""
def __init__(__self__, arn=None, created_date=None, id=None, last_updated_date=None, mesh_owner=None, name=None, resource_owner=None, specs=None, tags=None):
if arn and not isinstance(arn, str):
raise TypeError("Expected argument 'a... | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... | 120 | 243 | 812 | 11 | 109 | alexbowers/pulumi-aws | sdk/python/pulumi_aws/appmesh/get_mesh.py | Python | GetMeshResult | GetMeshResult | 18 | 116 | 18 | 19 | 48a77079333a8bd9c53dc8010e28c349e1811b0e | bigcode/the-stack | train |
4e931088a50d080bef941356 | train | function | def _as_graph_element(obj):
"""Retrieves Graph element."""
graph = ops.get_default_graph()
if not isinstance(obj, six.string_types):
if not hasattr(obj, "graph") or obj.graph != graph:
raise ValueError("Passed %s should have graph attribute that is equal "
"to current graph %s." %... | def _as_graph_element(obj):
| """Retrieves Graph element."""
graph = ops.get_default_graph()
if not isinstance(obj, six.string_types):
if not hasattr(obj, "graph") or obj.graph != graph:
raise ValueError("Passed %s should have graph attribute that is equal "
"to current graph %s." % (obj, graph))
return ob... | step, save_path)
with gfile.Open(save_path, "w") as f:
trace = timeline.Timeline(step_stats)
f.write(
trace.generate_chrome_trace_format(
show_dataflow=self._show_dataflow, show_memory=self._show_memory))
def _as_graph_element(obj):
| 64 | 64 | 193 | 7 | 57 | PaulWang1905/tensorflow | tensorflow/python/training/basic_session_run_hooks.py | Python | _as_graph_element | _as_graph_element | 1,073 | 1,094 | 1,073 | 1,073 | d1d604ea1bd47a6f38f363db1c605b033d388c67 | bigcode/the-stack | train |
266e97cc8ec3ca565c8fb47c | train | class | class _HookTimer(object):
"""Base timer for determining when Hooks should trigger.
Should not be instantiated directly.
"""
def __init__(self):
pass
def reset(self):
"""Resets the timer."""
pass
def should_trigger_for_step(self, step):
"""Return true if the timer should trigger for the s... | class _HookTimer(object):
| """Base timer for determining when Hooks should trigger.
Should not be instantiated directly.
"""
def __init__(self):
pass
def reset(self):
"""Resets the timer."""
pass
def should_trigger_for_step(self, step):
"""Return true if the timer should trigger for the specified step."""
rais... | _hook
from tensorflow.python.training import training_util
from tensorflow.python.training.session_run_hook import SessionRunArgs
from tensorflow.python.training.summary_io import SummaryWriterCache
from tensorflow.python.util.tf_export import tf_export
_HOOKS = "hooks"
_STEPS_PER_RUN_VAR = "steps_per_run"
class _Hook... | 67 | 67 | 224 | 6 | 61 | PaulWang1905/tensorflow | tensorflow/python/training/basic_session_run_hooks.py | Python | _HookTimer | _HookTimer | 54 | 87 | 54 | 54 | d60a773d642a68ad72525e0a913b68cc7d782597 | bigcode/the-stack | train |
64ba715dc1b59642be56b027 | train | class | @tf_export(v1=["train.FeedFnHook"])
class FeedFnHook(session_run_hook.SessionRunHook):
"""Runs `feed_fn` and sets the `feed_dict` accordingly."""
def __init__(self, feed_fn):
"""Initializes a `FeedFnHook`.
Args:
feed_fn: function that takes no arguments and returns `dict` of `Tensor`
to feed... | @tf_export(v1=["train.FeedFnHook"])
class FeedFnHook(session_run_hook.SessionRunHook):
| """Runs `feed_fn` and sets the `feed_dict` accordingly."""
def __init__(self, feed_fn):
"""Initializes a `FeedFnHook`.
Args:
feed_fn: function that takes no arguments and returns `dict` of `Tensor`
to feed.
"""
self.feed_fn = feed_fn
def before_run(self, run_context): # pylint: d... | the `value_op`, executed by `FinalOpsHook`, triggers "
"another data reading, which ends OutOfRangeError/StopIteration. "
"Please fix that.")
raise e
@tf_export(v1=["train.FeedFnHook"])
class FeedFnHook(session_run_hook.SessionRunHook):
| 64 | 64 | 133 | 23 | 40 | PaulWang1905/tensorflow | tensorflow/python/training/basic_session_run_hooks.py | Python | FeedFnHook | FeedFnHook | 970 | 985 | 970 | 971 | 1a927a7330ab90518b27396df1bad54b45f848ba | bigcode/the-stack | train |
131fec3ee667e889d6d2ec43 | train | class | @tf_export(v1=["train.CheckpointSaverHook"])
class CheckpointSaverHook(session_run_hook.SessionRunHook):
"""Saves checkpoints every N steps or seconds."""
def __init__(self,
checkpoint_dir,
save_secs=None,
save_steps=None,
saver=None,
check... | @tf_export(v1=["train.CheckpointSaverHook"])
class CheckpointSaverHook(session_run_hook.SessionRunHook):
| """Saves checkpoints every N steps or seconds."""
def __init__(self,
checkpoint_dir,
save_secs=None,
save_steps=None,
saver=None,
checkpoint_basename="model.ckpt",
scaffold=None,
listeners=None):
"""Initial... | 1.train.MonitoredTrainingSession(chief_only_hooks=[saver_hook]):
...
```
A `CheckpointSaverListener` may simply take some action after every
checkpoint save. It is also possible for the listener to use its own schedule
to act less frequently, e.g. based on global_step_value. In this case,
implementors sh... | 256 | 256 | 1,243 | 24 | 231 | PaulWang1905/tensorflow | tensorflow/python/training/basic_session_run_hooks.py | Python | CheckpointSaverHook | CheckpointSaverHook | 512 | 646 | 512 | 513 | 527d8df0074da59e368f4253bc59d505f015d787 | bigcode/the-stack | train |
d05d0fd8b2352ed09270cdf3 | train | function | def get_or_create_steps_per_run_variable():
"""Gets or creates the steps_per_run variable.
In Estimator, the user provided computation, the model_fn, is wrapped
inside a tf.while_loop for peak performance. The iterations of the loop are
specified by this variable, which adjusts its value on the CPU after each
... | def get_or_create_steps_per_run_variable():
| """Gets or creates the steps_per_run variable.
In Estimator, the user provided computation, the model_fn, is wrapped
inside a tf.while_loop for peak performance. The iterations of the loop are
specified by this variable, which adjusts its value on the CPU after each
device program execution and before the ne... | not None:
logging.info("%s (%.3f sec)", ", ".join(stats), elapsed_secs)
else:
logging.info("%s", ", ".join(stats))
np.set_printoptions(**original)
def after_run(self, run_context, run_values):
_ = run_context
if self._should_trigger:
self._log_tensors(run_values.results)
... | 131 | 131 | 437 | 9 | 122 | PaulWang1905/tensorflow | tensorflow/python/training/basic_session_run_hooks.py | Python | get_or_create_steps_per_run_variable | get_or_create_steps_per_run_variable | 278 | 322 | 278 | 278 | 56140a9117a5eada6a015a5cf83079773ae7ddd0 | bigcode/the-stack | train |
f3f96dd67d0dabb5432ed428 | train | class | class _MultiStepStopAtStepHook(session_run_hook.SessionRunHook):
"""Hook that requests stop at a specified step."""
def __init__(self, num_steps=None, last_step=None, steps_per_run=1):
"""Initializes a `MultiStepStopAtStepHook`.
This hook requests stop after either a number of steps have been
executed... | class _MultiStepStopAtStepHook(session_run_hook.SessionRunHook):
| """Hook that requests stop at a specified step."""
def __init__(self, num_steps=None, last_step=None, steps_per_run=1):
"""Initializes a `MultiStepStopAtStepHook`.
This hook requests stop after either a number of steps have been
executed or a last step has been reached. Only one of the two options can... | If multi steps_per_run variables were found.
"""
graph = ops.get_default_graph()
collection_name = "{}_{}".format(_HOOKS, _STEPS_PER_RUN_VAR)
steps_per_run_vars = graph.get_collection(collection_name)
if len(steps_per_run_vars) == 1:
return steps_per_run_vars[0]
elif len(steps_per_run_vars) > 1:
ra... | 189 | 189 | 632 | 15 | 174 | PaulWang1905/tensorflow | tensorflow/python/training/basic_session_run_hooks.py | Python | _MultiStepStopAtStepHook | _MultiStepStopAtStepHook | 325 | 386 | 325 | 325 | 3c957f7204862284f2be810de3199e092dbf770a | bigcode/the-stack | train |
774857b5a072987bd730802b | train | class | class NeverTriggerTimer(_HookTimer):
"""Timer that never triggers."""
def should_trigger_for_step(self, step):
_ = step
return False
def update_last_triggered_step(self, step):
_ = step
return (None, None)
def last_triggered_step(self):
return None
| class NeverTriggerTimer(_HookTimer):
| """Timer that never triggers."""
def should_trigger_for_step(self, step):
_ = step
return False
def update_last_triggered_step(self, step):
_ = step
return (None, None)
def last_triggered_step(self):
return None
| step - self._last_triggered_step
self._last_triggered_time = current_time
self._last_triggered_step = step
return (elapsed_secs, elapsed_steps)
def last_triggered_step(self):
return self._last_triggered_step
class NeverTriggerTimer(_HookTimer):
| 64 | 64 | 69 | 8 | 55 | PaulWang1905/tensorflow | tensorflow/python/training/basic_session_run_hooks.py | Python | NeverTriggerTimer | NeverTriggerTimer | 158 | 170 | 158 | 158 | 315143174db4f94affe0a6c26dafd91413df4e7c | bigcode/the-stack | train |
cc485ce61b2a79bc854e9251 | train | class | @tf_export(v1=["train.ProfilerHook"])
class ProfilerHook(session_run_hook.SessionRunHook):
"""Captures CPU/GPU profiling information every N steps or seconds.
This produces files called "timeline-<step>.json", which are in Chrome
Trace format.
For more information see:
https://github.com/catapult-project/ca... | @tf_export(v1=["train.ProfilerHook"])
class ProfilerHook(session_run_hook.SessionRunHook):
| """Captures CPU/GPU profiling information every N steps or seconds.
This produces files called "timeline-<step>.json", which are in Chrome
Trace format.
For more information see:
https://github.com/catapult-project/catapult/blob/master/tracing/README.md
"""
def __init__(self,
save_steps=... | ` to get the metric values. "
"The `value_op` here should have dependency back to variables "
"reading only, rather than reading another batch from input. "
"Otherwise, the `value_op`, executed by `FinalOpsHook`, triggers "
"another data reading, which ends OutOfRangeErro... | 237 | 237 | 791 | 22 | 215 | PaulWang1905/tensorflow | tensorflow/python/training/basic_session_run_hooks.py | Python | ProfilerHook | ProfilerHook | 988 | 1,070 | 988 | 989 | 7ca9bcc945ebdfbd56dc92840a54be0e76ed9ebc | bigcode/the-stack | train |
dd219c30da3cd3b106f526bf | train | class | @tf_export(v1=["train.CheckpointSaverListener"])
class CheckpointSaverListener(object):
"""Interface for listeners that take action before or after checkpoint save.
`CheckpointSaverListener` triggers only in steps when `CheckpointSaverHook` is
triggered, and provides callbacks at the following points:
- befor... | @tf_export(v1=["train.CheckpointSaverListener"])
class CheckpointSaverListener(object):
| """Interface for listeners that take action before or after checkpoint save.
`CheckpointSaverListener` triggers only in steps when `CheckpointSaverHook` is
triggered, and provides callbacks at the following points:
- before using the session
- before each call to `Saver.save()`
- after each call to `Sav... | argument
return SessionRunArgs(self._global_step_tensor)
def after_run(self, run_context, run_values):
global_step = run_values.results + 1
if global_step >= self._last_step:
# Check latest global step to ensure that the targeted last step is
# reached. global_step read tensor is the value of... | 153 | 153 | 510 | 19 | 134 | PaulWang1905/tensorflow | tensorflow/python/training/basic_session_run_hooks.py | Python | CheckpointSaverListener | CheckpointSaverListener | 445 | 509 | 445 | 446 | 344c8597c32a47cec6512646c6b3d6ddabdb7b82 | bigcode/the-stack | train |
352e17b9fc5578804de7a635 | train | class | @tf_export(v1=["train.LoggingTensorHook"])
class LoggingTensorHook(session_run_hook.SessionRunHook):
"""Prints the given tensors every N local steps, every N seconds, or at end.
The tensors will be printed to the log, with `INFO` severity. If you are not
seeing the logs, you might want to add the following line ... | @tf_export(v1=["train.LoggingTensorHook"])
class LoggingTensorHook(session_run_hook.SessionRunHook):
| """Prints the given tensors every N local steps, every N seconds, or at end.
The tensors will be printed to the log, with `INFO` severity. If you are not
seeing the logs, you might want to add the following line after your imports:
```python
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO)
... | _triggered_time + self._every_secs:
return True
if self._every_steps is not None:
if step >= self._last_triggered_step + self._every_steps:
return True
return False
def update_last_triggered_step(self, step):
current_time = time.time()
if self._last_triggered_time is None:
... | 256 | 256 | 934 | 22 | 233 | PaulWang1905/tensorflow | tensorflow/python/training/basic_session_run_hooks.py | Python | LoggingTensorHook | LoggingTensorHook | 173 | 275 | 173 | 174 | 1ed40e71e9902c810c27af63b8264c8fb9f12c34 | bigcode/the-stack | train |
6da6fa547c74cd105c1eb0f9 | train | class | @tf_export(v1=["train.FinalOpsHook"])
class FinalOpsHook(session_run_hook.SessionRunHook):
"""A hook which evaluates `Tensors` at the end of a session."""
def __init__(self, final_ops, final_ops_feed_dict=None):
"""Initializes `FinalOpHook` with ops to run at the end of the session.
Args:
final_ops:... | @tf_export(v1=["train.FinalOpsHook"])
class FinalOpsHook(session_run_hook.SessionRunHook):
| """A hook which evaluates `Tensors` at the end of a session."""
def __init__(self, final_ops, final_ops_feed_dict=None):
"""Initializes `FinalOpHook` with ops to run at the end of the session.
Args:
final_ops: A single `Tensor`, a list of `Tensors` or a dictionary of names
to `Tensors`.
... | last_logged_step = 0
while True:
current_step = run_context.session.run(self._global_step_tensor)
if current_step >= self._wait_until_step:
self._worker_is_started = True
return None
if current_step - last_logged_step > 1000:
logging.info(
"Waiting for global s... | 134 | 134 | 449 | 22 | 112 | PaulWang1905/tensorflow | tensorflow/python/training/basic_session_run_hooks.py | Python | FinalOpsHook | FinalOpsHook | 926 | 967 | 926 | 927 | a7443cb8e034d1c817229436a84fc2a2e79b49ce | bigcode/the-stack | train |
f14d1d31af2e2beca8476eaf | train | class | @tf_export(v1=["train.StepCounterHook"])
class StepCounterHook(session_run_hook.SessionRunHook):
"""Hook that counts steps per second."""
def __init__(self,
every_n_steps=100,
every_n_secs=None,
output_dir=None,
summary_writer=None):
if (every_n_step... | @tf_export(v1=["train.StepCounterHook"])
class StepCounterHook(session_run_hook.SessionRunHook):
| """Hook that counts steps per second."""
def __init__(self,
every_n_steps=100,
every_n_secs=None,
output_dir=None,
summary_writer=None):
if (every_n_steps is None) == (every_n_secs is None):
raise ValueError(
"exactly one of every_n_s... | .info(
"A CheckpointSaverListener requested that training be stopped. "
"listener: {}".format(l))
should_stop = True
return should_stop
def _get_saver(self):
if self._saver is not None:
return self._saver
elif self._scaffold is not None:
return self._scaffold.s... | 239 | 239 | 797 | 22 | 217 | PaulWang1905/tensorflow | tensorflow/python/training/basic_session_run_hooks.py | Python | StepCounterHook | StepCounterHook | 649 | 726 | 649 | 650 | ad69d33392ddf874260fb600ab15385b572895ea | bigcode/the-stack | train |
d02f66e219cf6b851acdd82f | train | class | @tf_export(v1=["train.NanTensorHook"])
class NanTensorHook(session_run_hook.SessionRunHook):
"""Monitors the loss tensor and stops training if loss is NaN.
Can either fail with exception or just stop training.
"""
def __init__(self, loss_tensor, fail_on_nan_loss=True):
"""Initializes a `NanTensorHook`.
... | @tf_export(v1=["train.NanTensorHook"])
class NanTensorHook(session_run_hook.SessionRunHook):
| """Monitors the loss tensor and stops training if loss is NaN.
Can either fail with exception or just stop training.
"""
def __init__(self, loss_tensor, fail_on_nan_loss=True):
"""Initializes a `NanTensorHook`.
Args:
loss_tensor: `Tensor`, the loss tensor.
fail_on_nan_loss: `bool`, whethe... | _step)
self._last_global_step = stale_global_step
@tf_export(v1=["train.NanLossDuringTrainingError"])
class NanLossDuringTrainingError(RuntimeError):
def __str__(self):
return "NaN loss during training."
@tf_export(v1=["train.NanTensorHook"])
class NanTensorHook(session_run_hook.SessionRunHook):
| 75 | 75 | 253 | 23 | 52 | PaulWang1905/tensorflow | tensorflow/python/training/basic_session_run_hooks.py | Python | NanTensorHook | NanTensorHook | 736 | 765 | 736 | 737 | 646909f77736ad958c65ed834d9c61e4e8a6583a | bigcode/the-stack | train |
9123cd42522dd859d896bb93 | train | class | @tf_export(v1=["train.SummarySaverHook"])
class SummarySaverHook(session_run_hook.SessionRunHook):
"""Saves summaries every N steps."""
def __init__(self,
save_steps=None,
save_secs=None,
output_dir=None,
summary_writer=None,
scaffold=None,... | @tf_export(v1=["train.SummarySaverHook"])
class SummarySaverHook(session_run_hook.SessionRunHook):
| """Saves summaries every N steps."""
def __init__(self,
save_steps=None,
save_secs=None,
output_dir=None,
summary_writer=None,
scaffold=None,
summary_op=None):
"""Initializes a `SummarySaverHook`.
Args:
save_st... | RunHook):
"""Monitors the loss tensor and stops training if loss is NaN.
Can either fail with exception or just stop training.
"""
def __init__(self, loss_tensor, fail_on_nan_loss=True):
"""Initializes a `NanTensorHook`.
Args:
loss_tensor: `Tensor`, the loss tensor.
fail_on_nan_loss: `boo... | 256 | 256 | 937 | 23 | 233 | PaulWang1905/tensorflow | tensorflow/python/training/basic_session_run_hooks.py | Python | SummarySaverHook | SummarySaverHook | 768 | 874 | 768 | 769 | 1de792d039d00fcee1476a7b75ac4a044fe00f60 | bigcode/the-stack | train |
8ce37b30899523495a05f810 | train | class | @tf_export(v1=["train.StopAtStepHook"])
class StopAtStepHook(session_run_hook.SessionRunHook):
"""Hook that requests stop at a specified step."""
def __init__(self, num_steps=None, last_step=None):
"""Initializes a `StopAtStepHook`.
This hook requests stop after either a number of steps have been
exec... | @tf_export(v1=["train.StopAtStepHook"])
class StopAtStepHook(session_run_hook.SessionRunHook):
| """Hook that requests stop at a specified step."""
def __init__(self, num_steps=None, last_step=None):
"""Initializes a `StopAtStepHook`.
This hook requests stop after either a number of steps have been
executed or a last step has been reached. Only one of the two options can be
specified.
if... | ):
global_step = session.run(self._global_step_tensor)
if self._last_step is None:
self._last_step = global_step + self._num_steps
self._update_steps_per_run_variable(global_step, session)
def after_run(self, run_context, run_values):
# Global step cannot be retrieved via SessionRunArgs and bef... | 158 | 158 | 528 | 24 | 134 | PaulWang1905/tensorflow | tensorflow/python/training/basic_session_run_hooks.py | Python | StopAtStepHook | StopAtStepHook | 389 | 442 | 389 | 390 | 6e20071b615692bc91a9e995ee2ed330a35791c3 | bigcode/the-stack | train |
2e7092ced794529573b8abe4 | train | class | @tf_export(v1=["train.SecondOrStepTimer"])
class SecondOrStepTimer(_HookTimer):
"""Timer that triggers at most once every N seconds or once every N steps.
This symbol is also exported to v2 in tf.estimator namespace. See
https://github.com/tensorflow/estimator/blob/master/tensorflow_estimator/python/estimator/ho... | @tf_export(v1=["train.SecondOrStepTimer"])
class SecondOrStepTimer(_HookTimer):
| """Timer that triggers at most once every N seconds or once every N steps.
This symbol is also exported to v2 in tf.estimator namespace. See
https://github.com/tensorflow/estimator/blob/master/tensorflow_estimator/python/estimator/hooks/basic_session_run_hooks.py
"""
def __init__(self, every_secs=None, ever... | _step(self, step):
"""Update the last triggered time and step number.
Args:
step: The current step.
Returns:
A pair `(elapsed_time, elapsed_steps)`, where `elapsed_time` is the number
of seconds between the current trigger and the last one (a float), and
`elapsed_steps` is the numb... | 158 | 158 | 528 | 21 | 136 | PaulWang1905/tensorflow | tensorflow/python/training/basic_session_run_hooks.py | Python | SecondOrStepTimer | SecondOrStepTimer | 90 | 155 | 90 | 91 | d18c0e7217f090a55d5b529b898efce2aff38245 | bigcode/the-stack | train |
084f615406dfe9446ffa97f4 | train | class | @tf_export(v1=["train.GlobalStepWaiterHook"])
class GlobalStepWaiterHook(session_run_hook.SessionRunHook):
"""Delays execution until global step reaches `wait_until_step`.
This hook delays execution until global step reaches to `wait_until_step`. It
is used to gradually start workers in distributed settings. One... | @tf_export(v1=["train.GlobalStepWaiterHook"])
class GlobalStepWaiterHook(session_run_hook.SessionRunHook):
| """Delays execution until global step reaches `wait_until_step`.
This hook delays execution until global step reaches to `wait_until_step`. It
is used to gradually start workers in distributed settings. One example usage
would be setting `wait_until_step=int(K*log(task_id+1))` assuming that
task_id=0 is the ... | ._scaffold.
Returns:
Returns a list of summary `Tensor`.
"""
summary_op = None
if self._summary_op is not None:
summary_op = self._summary_op
elif self._scaffold.summary_op is not None:
summary_op = self._scaffold.summary_op
if summary_op is None:
return None
if no... | 123 | 123 | 411 | 26 | 96 | PaulWang1905/tensorflow | tensorflow/python/training/basic_session_run_hooks.py | Python | GlobalStepWaiterHook | GlobalStepWaiterHook | 877 | 923 | 877 | 878 | e61f90d1b4c2003d0c679103f4b8ee01946c3c88 | bigcode/the-stack | train |
8a5d4c1718a0c04506207ffa | train | class | @tf_export(v1=["train.NanLossDuringTrainingError"])
class NanLossDuringTrainingError(RuntimeError):
def __str__(self):
return "NaN loss during training."
| @tf_export(v1=["train.NanLossDuringTrainingError"])
class NanLossDuringTrainingError(RuntimeError):
| def __str__(self):
return "NaN loss during training."
| _global_step() to Optimizer.apply_gradients or "
"Optimizer.minimize.", 5, stale_global_step, self._last_global_step)
self._last_global_step = stale_global_step
@tf_export(v1=["train.NanLossDuringTrainingError"])
class NanLossDuringTrainingError(RuntimeError):
| 64 | 64 | 39 | 23 | 40 | PaulWang1905/tensorflow | tensorflow/python/training/basic_session_run_hooks.py | Python | NanLossDuringTrainingError | NanLossDuringTrainingError | 729 | 733 | 729 | 731 | bbd367a1c3cf8f4271b19e86842ac4e3821e9a9d | bigcode/the-stack | train |
67e53d379a02abfbbfd226f0 | train | function | def main():
args = get_args()
set_up_logging(args.verbose)
proof_root = pathlib.Path(__file__).resolve().parent
litani = get_litani_path(proof_root)
run_cmd(["./prepare.py"], check=True, cwd=str(proof_root))
if not args.no_standalone:
run_cmd(
[str(litani), "init", "--proje... | def main():
| args = get_args()
set_up_logging(args.verbose)
proof_root = pathlib.Path(__file__).resolve().parent
litani = get_litani_path(proof_root)
run_cmd(["./prepare.py"], check=True, cwd=str(proof_root))
if not args.no_standalone:
run_cmd(
[str(litani), "init", "--project", args.pr... | )
return True
def configure_proof_dirs(proof_dirs, proof_root, counter, litani):
for proof_dir in proof_dirs:
print_counter(counter)
success = add_proof_jobs(proof_dir, proof_root, litani)
counter["pass" if success else "fail"].append(proof_dir)
counter["complete"] += 1
def ... | 80 | 80 | 268 | 3 | 76 | FedyaExtreme/amazon-freertos | tools/cbmc/proofs/run-cbmc-proofs.py | Python | main | main | 272 | 308 | 272 | 272 | c9326ed5a3b1fd1c351646861d3f022a9ea9ac62 | bigcode/the-stack | train |
0d81252b5c0cdea1b44402bf | train | function | def get_args():
pars = argparse.ArgumentParser(
description=DESCRIPTION, epilog=EPILOG,
formatter_class=argparse.RawDescriptionHelpFormatter)
for arg in [{
"flags": ["-j", "--parallel-jobs"],
"type": int,
"metavar": "N",
"help": "run at most N proo... | def get_args():
| pars = argparse.ArgumentParser(
description=DESCRIPTION, epilog=EPILOG,
formatter_class=argparse.RawDescriptionHelpFormatter)
for arg in [{
"flags": ["-j", "--parallel-jobs"],
"type": int,
"metavar": "N",
"help": "run at most N proof jobs in parall... | when you want to add additional proof jobs, not
just the CBMC ones. In that case, you would run `litani init`
yourself; then run `run-cbmc-proofs --no-standalone`; add any
additional jobs that you want to execute with `litani add-job`; and
finally run `litani run-build`.
"""
def get_args():
| 79 | 79 | 265 | 4 | 75 | FedyaExtreme/amazon-freertos | tools/cbmc/proofs/run-cbmc-proofs.py | Python | get_args | get_args | 60 | 90 | 60 | 60 | ff0c862127deac64280f35f37d212252f760dc2b | bigcode/the-stack | train |
211e6c7fd043e98ca7fe7996 | train | function | def add_proof_jobs(proof_directory, proof_root, litani):
proof_directory = pathlib.Path(proof_directory)
harnesses = [
f for f in os.listdir(proof_directory) if f.endswith("_harness.c")]
if not len(harnesses) == 1:
logging.error(
"Found %d harnesses in directory '%s'", len(harnes... | def add_proof_jobs(proof_directory, proof_root, litani):
| proof_directory = pathlib.Path(proof_directory)
harnesses = [
f for f in os.listdir(proof_directory) if f.endswith("_harness.c")]
if not len(harnesses) == 1:
logging.error(
"Found %d harnesses in directory '%s'", len(harnesses),
proof_directory)
return False
... | "The following proofs were not found: %s",
", ".join(proofs_remaining))
sys.exit(1)
def run_cmd(cmd, **args):
if "shell" in args and args["shell"]:
if not isinstance(cmd, str):
raise UserWarning("Command must be a string if shell=True")
str_cmd = cmd
... | 240 | 240 | 801 | 15 | 225 | FedyaExtreme/amazon-freertos | tools/cbmc/proofs/run-cbmc-proofs.py | Python | add_proof_jobs | add_proof_jobs | 163 | 259 | 163 | 163 | 3844d14b62a8238c052137a4b80b0a9867319008 | bigcode/the-stack | train |
5952de77e93c74abbe9d237b | train | function | def print_counter(counter):
print(
"\rConfiguring CBMC proofs: "
"{complete:{width}} / {total:{width}}".format(
**counter), end="", file=sys.stderr)
| def print_counter(counter):
| print(
"\rConfiguring CBMC proofs: "
"{complete:{width}} / {total:{width}}".format(
**counter), end="", file=sys.stderr)
| flags, **arg)
return pars.parse_args()
def set_up_logging(verbose):
if verbose:
level = logging.DEBUG
else:
level = logging.WARNING
logging.basicConfig(
format="run-cbmc-proofs: %(message)s", level=level)
def print_counter(counter):
| 64 | 64 | 43 | 5 | 59 | FedyaExtreme/amazon-freertos | tools/cbmc/proofs/run-cbmc-proofs.py | Python | print_counter | print_counter | 102 | 106 | 102 | 102 | 495ab8df81364c0c70fdc411b8b3e030e5a05185 | bigcode/the-stack | train |
0136568c33b4bbe183cd6212 | train | function | def set_up_logging(verbose):
if verbose:
level = logging.DEBUG
else:
level = logging.WARNING
logging.basicConfig(
format="run-cbmc-proofs: %(message)s", level=level)
| def set_up_logging(verbose):
| if verbose:
level = logging.DEBUG
else:
level = logging.WARNING
logging.basicConfig(
format="run-cbmc-proofs: %(message)s", level=level)
| %(default)s",
}, {
"flags": ["--verbose"],
"action": "store_true",
"help": "verbose output",
}]:
flags = arg.pop("flags")
pars.add_argument(*flags, **arg)
return pars.parse_args()
def set_up_logging(verbose):
| 64 | 64 | 48 | 6 | 58 | FedyaExtreme/amazon-freertos | tools/cbmc/proofs/run-cbmc-proofs.py | Python | set_up_logging | set_up_logging | 93 | 99 | 93 | 93 | aafd461159dce5f898ecec8a637b85549438776b | bigcode/the-stack | train |
5e4af5f767eb1843a5a83ae9 | train | function | def run_cmd(cmd, **args):
if "shell" in args and args["shell"]:
if not isinstance(cmd, str):
raise UserWarning("Command must be a string if shell=True")
str_cmd = cmd
else:
if not isinstance(cmd, list):
raise UserWarning("Command passed to run_cmd must be a list")... | def run_cmd(cmd, **args):
| if "shell" in args and args["shell"]:
if not isinstance(cmd, str):
raise UserWarning("Command must be a string if shell=True")
str_cmd = cmd
else:
if not isinstance(cmd, list):
raise UserWarning("Command passed to run_cmd must be a list")
str_cmd = " ".joi... | _name)
if "cbmc-batch.yaml" in fyles:
yield pathlib.Path(root)
if proofs_remaining:
logging.error(
"The following proofs were not found: %s",
", ".join(proofs_remaining))
sys.exit(1)
def run_cmd(cmd, **args):
| 64 | 64 | 128 | 8 | 56 | FedyaExtreme/amazon-freertos | tools/cbmc/proofs/run-cbmc-proofs.py | Python | run_cmd | run_cmd | 131 | 148 | 131 | 131 | 191d41451ef52e673ebbdfb548d285730ab01c18 | bigcode/the-stack | train |
f5afe89dceeed92b336ee78c | train | function | def get_litani_path(proof_root):
return proof_root.parent.parent / "litani" / "litani"
| def get_litani_path(proof_root):
| return proof_root.parent.parent / "litani" / "litani"
| s", str_cmd)
return proc
def run_build(litani, jobs):
cmd = [str(litani), "run-build"]
if jobs:
cmd.extend(["-j", str(jobs)])
run_cmd(cmd, check=True)
def get_litani_path(proof_root):
| 64 | 64 | 26 | 10 | 54 | FedyaExtreme/amazon-freertos | tools/cbmc/proofs/run-cbmc-proofs.py | Python | get_litani_path | get_litani_path | 159 | 160 | 159 | 159 | b274fab3b2bfcbd2c82e55be801e4a63143e3974 | bigcode/the-stack | train |
1489849540dfe93fa9d81951 | train | function | def get_proof_dirs(proof_root, proof_list):
if proof_list is not None:
proofs_remaining = list(proof_list)
else:
proofs_remaining = []
for root, _, fyles in os.walk(proof_root):
proof_name = str(pathlib.Path(root).name)
if proof_list and proof_name not in proof_list:
... | def get_proof_dirs(proof_root, proof_list):
| if proof_list is not None:
proofs_remaining = list(proof_list)
else:
proofs_remaining = []
for root, _, fyles in os.walk(proof_root):
proof_name = str(pathlib.Path(root).name)
if proof_list and proof_name not in proof_list:
continue
if proof_list and proo... | : %(message)s", level=level)
def print_counter(counter):
print(
"\rConfiguring CBMC proofs: "
"{complete:{width}} / {total:{width}}".format(
**counter), end="", file=sys.stderr)
def get_proof_dirs(proof_root, proof_list):
| 64 | 64 | 151 | 12 | 52 | FedyaExtreme/amazon-freertos | tools/cbmc/proofs/run-cbmc-proofs.py | Python | get_proof_dirs | get_proof_dirs | 109 | 128 | 109 | 109 | 271a11a69842575e2aeaa6db286dc1fb64c8a09f | bigcode/the-stack | train |
175e96c0957dff96fc85f8f0 | train | function | def run_build(litani, jobs):
cmd = [str(litani), "run-build"]
if jobs:
cmd.extend(["-j", str(jobs)])
run_cmd(cmd, check=True)
| def run_build(litani, jobs):
| cmd = [str(litani), "run-build"]
if jobs:
cmd.extend(["-j", str(jobs)])
run_cmd(cmd, check=True)
| ")
str_cmd = " ".join(cmd)
logging.info("Command: %s", str_cmd)
proc = subprocess.run(cmd, **args)
if proc.returncode:
logging.error("Command failed: %s", str_cmd)
return proc
def run_build(litani, jobs):
| 64 | 64 | 45 | 9 | 54 | FedyaExtreme/amazon-freertos | tools/cbmc/proofs/run-cbmc-proofs.py | Python | run_build | run_build | 151 | 156 | 151 | 151 | 13571a12b5513a85d301bb82cb401a9cc90440ae | bigcode/the-stack | train |
b43c57370b90c60c0476c7f4 | train | function | def configure_proof_dirs(proof_dirs, proof_root, counter, litani):
for proof_dir in proof_dirs:
print_counter(counter)
success = add_proof_jobs(proof_dir, proof_root, litani)
counter["pass" if success else "fail"].append(proof_dir)
counter["complete"] += 1
| def configure_proof_dirs(proof_dirs, proof_root, counter, litani):
| for proof_dir in proof_dirs:
print_counter(counter)
success = add_proof_jobs(proof_dir, proof_root, litani)
counter["pass" if success else "fail"].append(proof_dir)
counter["complete"] += 1
| ", "report",
"--cwd", str(proof_directory),
"--tags", "stats-group:report generation",
"--description", ("%s: generating report" % proof_name),
], check=True)
return True
def configure_proof_dirs(proof_dirs, proof_root, counter, litani):
| 64 | 64 | 72 | 17 | 46 | FedyaExtreme/amazon-freertos | tools/cbmc/proofs/run-cbmc-proofs.py | Python | configure_proof_dirs | configure_proof_dirs | 262 | 269 | 262 | 262 | bbfe92e6d5f935a65ff592f74abb7586b2c95e97 | bigcode/the-stack | train |
bf98805474ed6f47318552bf | train | function | def adjust_markdown_html(content):
soup = bs4.BeautifulSoup(
content,
features='html.parser'
)
for a in soup.find_all('a'):
a_class = a.attrs.get('class')
a_href = a.attrs.get('href')
if a_class and 'headerlink' in a_class:
a.string = '\xa0'
if a_... | def adjust_markdown_html(content):
| soup = bs4.BeautifulSoup(
content,
features='html.parser'
)
for a in soup.find_all('a'):
a_class = a.attrs.get('class')
a_href = a.attrs.get('href')
if a_class and 'headerlink' in a_class:
a.string = '\xa0'
if a_href and a_href.startswith('http'):... | = True
iframe_src = iframe.attrs['src']
for domain in allowed_domains:
if iframe_src.startswith(domain):
illegal_domain = False
break
if illegal_domain:
raise RuntimeError(f'iframe from illegal domain: {iframe_src}')
wrapper = soup.new_tag('div')
wrapper.attr... | 197 | 197 | 659 | 7 | 190 | sonvt1710/ClickHouse | docs/tools/website.py | Python | adjust_markdown_html | adjust_markdown_html | 44 | 123 | 44 | 44 | 523a3c07cd73b2a301024df98bd79374e903b732 | bigcode/the-stack | train |
0f662de1fb0a2de158a359b4 | train | function | def get_js_in(args):
return [
f"'{args.website_dir}/js/jquery.js'",
f"'{args.website_dir}/js/popper.js'",
f"'{args.website_dir}/js/bootstrap.js'",
f"'{args.website_dir}/js/sentry.js'",
f"'{args.website_dir}/js/base.js'",
f"'{args.website_dir}/js/index.js'",
f"... | def get_js_in(args):
| return [
f"'{args.website_dir}/js/jquery.js'",
f"'{args.website_dir}/js/popper.js'",
f"'{args.website_dir}/js/bootstrap.js'",
f"'{args.website_dir}/js/sentry.js'",
f"'{args.website_dir}/js/base.js'",
f"'{args.website_dir}/js/index.js'",
f"'{args.website_dir}/j... | _dir}/css/base.css'",
f"'{args.website_dir}/css/blog.css'",
f"'{args.website_dir}/css/docs.css'",
f"'{args.website_dir}/css/highlight.css'",
f"'{args.website_dir}/css/main.css'"
]
def get_js_in(args):
| 63 | 64 | 121 | 6 | 57 | sonvt1710/ClickHouse | docs/tools/website.py | Python | get_js_in | get_js_in | 200 | 211 | 200 | 200 | a50aae1fabe81eee3ebc69b9bdd1c69330d84b5a | bigcode/the-stack | train |
dc07c4979130b71cbc43b5e6 | train | function | def handle_iframe(iframe, soup):
allowed_domains = ['https://www.youtube.com/', 'https://datalens.yandex/']
illegal_domain = True
iframe_src = iframe.attrs['src']
for domain in allowed_domains:
if iframe_src.startswith(domain):
illegal_domain = False
break
if illegal_... | def handle_iframe(iframe, soup):
| allowed_domains = ['https://www.youtube.com/', 'https://datalens.yandex/']
illegal_domain = True
iframe_src = iframe.attrs['src']
for domain in allowed_domains:
if iframe_src.startswith(domain):
illegal_domain = False
break
if illegal_domain:
raise RuntimeErro... | import concurrent.futures
import hashlib
import json
import logging
import os
import shutil
import subprocess
import sys
import bs4
import closure
import cssmin
import htmlmin
import jsmin
import util
def handle_iframe(iframe, soup):
| 57 | 66 | 223 | 9 | 47 | sonvt1710/ClickHouse | docs/tools/website.py | Python | handle_iframe | handle_iframe | 19 | 41 | 19 | 19 | 6d98453087be0d155f6eaa49e7c30f088558eb7b | bigcode/the-stack | train |
2dc1ba32514697ef3c7b8fde | train | function | def minify_file(path, css_digest, js_digest):
if not (
path.endswith('.html') or
path.endswith('.css')
):
return
logging.info('Minifying %s', path)
with open(path, 'rb') as f:
content = f.read().decode('utf-8')
if path.endswith('.html'):
content = minify_html... | def minify_file(path, css_digest, js_digest):
| if not (
path.endswith('.html') or
path.endswith('.css')
):
return
logging.info('Minifying %s', path)
with open(path, 'rb') as f:
content = f.read().decode('utf-8')
if path.endswith('.html'):
content = minify_html(content)
content = content.replace('b... | f"'{args.website_dir}/js/index.js'",
f"'{args.website_dir}/js/docsearch.js'",
f"'{args.website_dir}/js/docs.js'",
f"'{args.website_dir}/js/main.js'"
]
def minify_file(path, css_digest, js_digest):
| 63 | 64 | 197 | 12 | 51 | sonvt1710/ClickHouse | docs/tools/website.py | Python | minify_file | minify_file | 214 | 235 | 214 | 214 | 477e48e4b253b3e522b0950aee507d40da49b63d | bigcode/the-stack | train |
8fcbc12a4d9f3348ab2a31dc | train | function | def build_website(args):
logging.info('Building website')
env = util.init_jinja2_env(args)
shutil.copytree(
args.website_dir,
args.output_dir,
ignore=shutil.ignore_patterns(
'*.md',
'*.sh',
'*.css',
'*.json',
'js/*.js',
... | def build_website(args):
| logging.info('Building website')
env = util.init_jinja2_env(args)
shutil.copytree(
args.website_dir,
args.output_dir,
ignore=shutil.ignore_patterns(
'*.md',
'*.sh',
'*.css',
'*.json',
'js/*.js',
'build',
... | div_class) or ('warning' in div_class):
mode = 'alert-warning'
elif 'important' in div_class:
mode = 'alert-danger'
elif 'tip' in div_class:
mode = 'alert-info'
else:
mode = 'alert-secondary'
div.attrs['clas... | 111 | 111 | 372 | 6 | 105 | sonvt1710/ClickHouse | docs/tools/website.py | Python | build_website | build_website | 130 | 185 | 130 | 130 | 5b0894ca490dd98fdac9ea679fa7b8fb1bd15dd0 | bigcode/the-stack | train |
21c937c274d485fca5e72950 | train | function | def process_benchmark_results(args):
benchmark_root = os.path.join(args.website_dir, 'benchmark')
required_keys = {
'dbms': ['result'],
'hardware': ['result', 'system', 'system_full', 'kind']
}
for benchmark_kind in ['dbms', 'hardware']:
results = []
results_root = os.pat... | def process_benchmark_results(args):
| benchmark_root = os.path.join(args.website_dir, 'benchmark')
required_keys = {
'dbms': ['result'],
'hardware': ['result', 'system', 'system_full', 'kind']
}
for benchmark_kind in ['dbms', 'hardware']:
results = []
results_root = os.path.join(benchmark_root, benchmark_kind... | _dir):
for filename in filenames:
path = os.path.join(root, filename)
futures.append(executor.submit(minify_file, path, css_digest, js_digest))
for future in futures:
exc = future.exception()
if exc:
... | 70 | 70 | 234 | 7 | 63 | sonvt1710/ClickHouse | docs/tools/website.py | Python | process_benchmark_results | process_benchmark_results | 306 | 327 | 306 | 306 | 04fbfd038a78d1f0c0e25b89c2f61a53dde1511d | bigcode/the-stack | train |
5300480baba16a9c06c472a4 | train | function | def get_css_in(args):
return [
f"'{args.website_dir}/css/bootstrap.css'",
f"'{args.website_dir}/css/docsearch.css'",
f"'{args.website_dir}/css/base.css'",
f"'{args.website_dir}/css/blog.css'",
f"'{args.website_dir}/css/docs.css'",
f"'{args.website_dir}/css/highlight.c... | def get_css_in(args):
| return [
f"'{args.website_dir}/css/bootstrap.css'",
f"'{args.website_dir}/css/docsearch.css'",
f"'{args.website_dir}/css/base.css'",
f"'{args.website_dir}/css/blog.css'",
f"'{args.website_dir}/css/docs.css'",
f"'{args.website_dir}/css/highlight.css'",
f"'{args... | , 'rb') as f:
content = f.read().decode('utf-8')
template = env.from_string(content)
content = template.render(args.__dict__)
with open(path, 'wb') as f:
f.write(content.encode('utf-8'))
def get_css_in(args):
| 63 | 64 | 97 | 6 | 57 | sonvt1710/ClickHouse | docs/tools/website.py | Python | get_css_in | get_css_in | 188 | 197 | 188 | 188 | 256f36383ed6c4c6bae034e4f17826a4b56cc82e | bigcode/the-stack | train |
c095280cf47b64b240c88220 | train | function | def minify_website(args):
css_in = ' '.join(get_css_in(args))
css_out = f'{args.output_dir}/docs/css/base.css'
os.makedirs(f'{args.output_dir}/docs/css')
if args.minify and False: # TODO: return closure
command = f"purifycss -w '*algolia*' --min {css_in} '{args.output_dir}/*.html' " \
... | def minify_website(args):
| css_in = ' '.join(get_css_in(args))
css_out = f'{args.output_dir}/docs/css/base.css'
os.makedirs(f'{args.output_dir}/docs/css')
if args.minify and False: # TODO: return closure
command = f"purifycss -w '*algolia*' --min {css_in} '{args.output_dir}/*.html' " \
f"'{args.output_dir}/d... | path.endswith('.css')
):
return
logging.info('Minifying %s', path)
with open(path, 'rb') as f:
content = f.read().decode('utf-8')
if path.endswith('.html'):
content = minify_html(content)
content = content.replace('base.css?css_digest', f'base.css?{css_digest}')
... | 179 | 180 | 601 | 7 | 172 | sonvt1710/ClickHouse | docs/tools/website.py | Python | minify_website | minify_website | 238 | 303 | 238 | 238 | 49cb00e015b297383e8eaa17164b62850d09e7d1 | bigcode/the-stack | train |
231774884728b969fa5751be | train | function | def minify_html(content):
return htmlmin.minify(content)
| def minify_html(content):
| return htmlmin.minify(content)
| '
elif 'tip' in div_class:
mode = 'alert-info'
else:
mode = 'alert-secondary'
div.attrs['class'] = div_class + ['alert', 'pb-0', 'mb-4', mode]
return str(soup)
def minify_html(content):
| 64 | 64 | 14 | 6 | 58 | sonvt1710/ClickHouse | docs/tools/website.py | Python | minify_html | minify_html | 126 | 127 | 126 | 126 | 562fa85fa4a58ab7e72691e364f6aea914cbae59 | bigcode/the-stack | train |
efc9cd96e27620035506e36e | train | class | class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Designation',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
... | class Migration(migrations.Migration):
| initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Designation',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=... | # Generated by Django 3.0.2 on 2020-01-28 12:31
from django.db import migrations, models
class Migration(migrations.Migration):
| 38 | 64 | 91 | 7 | 30 | ShwethaRGowda/FADB | administration/migrations/0001_initial.py | Python | Migration | Migration | 6 | 22 | 6 | 7 | 4f5ab5aaf377324d0e1e8735ea36ca0d87806fdf | bigcode/the-stack | train |
b964e21d7ddc121d7491e3c6 | train | class | class Model(Node, W.PsModel):
pass
| class Model(Node, W.PsModel):
| pass
| W.PsInstanceList):
pass
class InstanceListEntry(Object3D, W.PsInstanceListEntry):
pass
class Joint(Node, W.PsJoint):
pass
class Loader3D(Node, W.PsLoader3D):
pass
class Model(Node, W.PsModel):
| 64 | 64 | 12 | 9 | 54 | likianta/declare-qtquick | declare_qtquick/widgets/api/qtquick3d/__list__.py | Python | Model | Model | 94 | 95 | 94 | 94 | 1fd2d5595c5f7aae07d0b8f162c4cbe1de8388b5 | bigcode/the-stack | train |
e692c5ca17866fcd1ac8f399 | train | class | class DefaultMaterial(Material, W.PsDefaultMaterial):
pass
| class DefaultMaterial(Material, W.PsDefaultMaterial):
| pass
| Buffer(C, W.PsBuffer):
pass
class BufferInput(Command, W.PsBufferInput):
pass
class CustomCamera(Camera, W.PsCustomCamera):
pass
class CustomMaterial(Material, W.PsCustomMaterial):
pass
class DefaultMaterial(Material, W.PsDefaultMaterial):
| 64 | 64 | 14 | 11 | 52 | likianta/declare-qtquick | declare_qtquick/widgets/api/qtquick3d/__list__.py | Python | DefaultMaterial | DefaultMaterial | 58 | 59 | 58 | 58 | e924d32a9a1af37417662b03d902f6433b4fd1cf | bigcode/the-stack | train |
13d08c65ca7fd48891fcf6e1 | train | class | class FrustumCamera(PerspectiveCamera, W.PsFrustumCamera):
pass
| class FrustumCamera(PerspectiveCamera, W.PsFrustumCamera):
| pass
| ):
pass
class DefaultMaterial(Material, W.PsDefaultMaterial):
pass
class DirectionalLight(Light, W.PsDirectionalLight):
pass
class Effect(Object3D, W.PsEffect):
pass
class FrustumCamera(PerspectiveCamera, W.PsFrustumCamera):
| 64 | 64 | 19 | 16 | 47 | likianta/declare-qtquick | declare_qtquick/widgets/api/qtquick3d/__list__.py | Python | FrustumCamera | FrustumCamera | 70 | 71 | 70 | 70 | d332856b8a957d7d637ff71aa107dbd510a50c33 | bigcode/the-stack | train |
deb8be818b91ee6b9df64b5e | train | class | class Repeater3D(Node, W.PsRepeater3D):
pass
| class Repeater3D(Node, W.PsRepeater3D):
| pass
| ):
pass
class PrincipledMaterial(Material, W.PsPrincipledMaterial):
pass
class QuaternionAnimation(PropertyAnimation, W.PsQuaternionAnimation):
pass
class RenderStats(C, W.PsRenderStats):
pass
class Repeater3D(Node, W.PsRepeater3D):
| 64 | 64 | 18 | 15 | 48 | likianta/declare-qtquick | declare_qtquick/widgets/api/qtquick3d/__list__.py | Python | Repeater3D | Repeater3D | 130 | 131 | 130 | 130 | 5ef8725337287167dc6ebfc7c487fd242c462480 | bigcode/the-stack | train |
1c93f6bbefd4fbed1cdbfa22 | train | class | class PickResult(C, W.PsPickResult):
pass
| class PickResult(C, W.PsPickResult):
| pass
| Model(Node, W.PsModel):
pass
class MorphTarget(C, W.PsMorphTarget):
pass
class OrthographicCamera(Camera, W.PsOrthographicCamera):
pass
class Pass(C, W.PsPass):
pass
class PickResult(C, W.PsPickResult):
| 64 | 64 | 14 | 11 | 52 | likianta/declare-qtquick | declare_qtquick/widgets/api/qtquick3d/__list__.py | Python | PickResult | PickResult | 110 | 111 | 110 | 110 | 994e788383157ddd54b908092b0b1d72cac76a23 | bigcode/the-stack | train |
3ea64d69bc5b35279330661f | train | class | class OrthographicCamera(Camera, W.PsOrthographicCamera):
pass
| class OrthographicCamera(Camera, W.PsOrthographicCamera):
| pass
| , W.PsJoint):
pass
class Loader3D(Node, W.PsLoader3D):
pass
class Model(Node, W.PsModel):
pass
class MorphTarget(C, W.PsMorphTarget):
pass
class OrthographicCamera(Camera, W.PsOrthographicCamera):
| 64 | 64 | 16 | 13 | 50 | likianta/declare-qtquick | declare_qtquick/widgets/api/qtquick3d/__list__.py | Python | OrthographicCamera | OrthographicCamera | 102 | 103 | 102 | 102 | c4e0adfffba2eba626b8b677bf5cce1f813f672a | bigcode/the-stack | train |
930ff064e9d880d359ac6082 | train | class | class Command(C, W.PsCommand):
pass
| class Command(C, W.PsCommand):
| pass
| pass
class Node(Object3D, W.PsNode):
pass
class Camera(Node, W.PsCamera):
pass
class Light(Node, W.PsLight):
pass
class Material(Object3D, W.PsMaterial):
pass
class Command(C, W.PsCommand):
| 64 | 64 | 12 | 9 | 54 | likianta/declare-qtquick | declare_qtquick/widgets/api/qtquick3d/__list__.py | Python | Command | Command | 26 | 27 | 26 | 26 | 852c54fd14c6d145abae766f699f94ab39d9a88c | bigcode/the-stack | train |
7dee9c8cd0ac2db3b8f4ea75 | train | class | class SceneEnvironment(Object3D, W.PsSceneEnvironment):
pass
| class SceneEnvironment(Object3D, W.PsSceneEnvironment):
| pass
| ):
pass
class QuaternionAnimation(PropertyAnimation, W.PsQuaternionAnimation):
pass
class RenderStats(C, W.PsRenderStats):
pass
class Repeater3D(Node, W.PsRepeater3D):
pass
class SceneEnvironment(Object3D, W.PsSceneEnvironment):
| 64 | 64 | 16 | 13 | 50 | likianta/declare-qtquick | declare_qtquick/widgets/api/qtquick3d/__list__.py | Python | SceneEnvironment | SceneEnvironment | 134 | 135 | 134 | 134 | 2a852daa8b98ee4046cec6c925b37e8e76306317 | bigcode/the-stack | train |
10af6261064fcc40db04db05 | train | class | class Buffer(C, W.PsBuffer):
pass
| class Buffer(C, W.PsBuffer):
| pass
|
class Command(C, W.PsCommand):
pass
class Instancing(Object3D, W.PsInstancing):
pass
class PerspectiveCamera(Camera, W.PsPerspectiveCamera):
pass
class Bounds(C, W.PsBounds):
pass
class Buffer(C, W.PsBuffer):
| 64 | 64 | 12 | 9 | 54 | likianta/declare-qtquick | declare_qtquick/widgets/api/qtquick3d/__list__.py | Python | Buffer | Buffer | 42 | 43 | 42 | 42 | 5608ebd84c204a344b06308f57481687765c98b1 | bigcode/the-stack | train |
af634e7a46a6e76fa8c6bd90 | train | class | class Texture(Object3D, W.PsTexture):
pass
| class Texture(Object3D, W.PsTexture):
| pass
| UniformValue(Command, W.PsSetUniformValue):
pass
class Shader(C, W.PsShader):
pass
class Skeleton(Node, W.PsSkeleton):
pass
class SpotLight(Light, W.PsSpotLight):
pass
class Texture(Object3D, W.PsTexture):
| 64 | 64 | 14 | 11 | 52 | likianta/declare-qtquick | declare_qtquick/widgets/api/qtquick3d/__list__.py | Python | Texture | Texture | 154 | 155 | 154 | 154 | 14bc8670dd755ea4dd182dc3f2ca4d9534caec98 | bigcode/the-stack | train |
3a4af49f8bb06e99c3d3ae52 | train | class | class BufferInput(Command, W.PsBufferInput):
pass
| class BufferInput(Command, W.PsBufferInput):
| pass
| Instancing(Object3D, W.PsInstancing):
pass
class PerspectiveCamera(Camera, W.PsPerspectiveCamera):
pass
class Bounds(C, W.PsBounds):
pass
class Buffer(C, W.PsBuffer):
pass
class BufferInput(Command, W.PsBufferInput):
| 64 | 64 | 14 | 11 | 52 | likianta/declare-qtquick | declare_qtquick/widgets/api/qtquick3d/__list__.py | Python | BufferInput | BufferInput | 46 | 47 | 46 | 46 | 8b05ccea74289ff15565786f10b480302a2e73ad | bigcode/the-stack | train |
cdda33c9ca9f191c2a39eb6a | train | class | class DirectionalLight(Light, W.PsDirectionalLight):
pass
| class DirectionalLight(Light, W.PsDirectionalLight):
| pass
| W.PsBufferInput):
pass
class CustomCamera(Camera, W.PsCustomCamera):
pass
class CustomMaterial(Material, W.PsCustomMaterial):
pass
class DefaultMaterial(Material, W.PsDefaultMaterial):
pass
class DirectionalLight(Light, W.PsDirectionalLight):
| 64 | 64 | 16 | 13 | 50 | likianta/declare-qtquick | declare_qtquick/widgets/api/qtquick3d/__list__.py | Python | DirectionalLight | DirectionalLight | 62 | 63 | 62 | 62 | b6359c1dcda0160a10b58bbf7fee7c661786756c | bigcode/the-stack | train |
246896b7276b78c275144c39 | train | class | class Effect(Object3D, W.PsEffect):
pass
| class Effect(Object3D, W.PsEffect):
| pass
| W.PsCustomCamera):
pass
class CustomMaterial(Material, W.PsCustomMaterial):
pass
class DefaultMaterial(Material, W.PsDefaultMaterial):
pass
class DirectionalLight(Light, W.PsDirectionalLight):
pass
class Effect(Object3D, W.PsEffect):
| 64 | 64 | 14 | 11 | 52 | likianta/declare-qtquick | declare_qtquick/widgets/api/qtquick3d/__list__.py | Python | Effect | Effect | 66 | 67 | 66 | 66 | 41ede4093136e62c6131d367479090db77451b09 | bigcode/the-stack | train |
410677054a7953424cf6d62d | train | class | class SetUniformValue(Command, W.PsSetUniformValue):
pass
| class SetUniformValue(Command, W.PsSetUniformValue):
| pass
| pass
class RenderStats(C, W.PsRenderStats):
pass
class Repeater3D(Node, W.PsRepeater3D):
pass
class SceneEnvironment(Object3D, W.PsSceneEnvironment):
pass
class SetUniformValue(Command, W.PsSetUniformValue):
| 64 | 64 | 16 | 13 | 50 | likianta/declare-qtquick | declare_qtquick/widgets/api/qtquick3d/__list__.py | Python | SetUniformValue | SetUniformValue | 138 | 139 | 138 | 138 | 604061fe3bcd7933e376736d4ba156cf6d275f5c | bigcode/the-stack | train |
a2f1b8dcbc529a0693136281 | train | class | class Object3D(QtObject, W.PsObject3D):
pass
| class Object3D(QtObject, W.PsObject3D):
| pass
| from .__base__ import *
from ..qtqml import QtObject
from ..qtquick import PropertyAnimation
class Object3D(QtObject, W.PsObject3D):
| 37 | 64 | 17 | 14 | 22 | likianta/declare-qtquick | declare_qtquick/widgets/api/qtquick3d/__list__.py | Python | Object3D | Object3D | 6 | 7 | 6 | 6 | 97391676c090b07632a0e5f4c9dfbd29037ad879 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.