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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bb3df689acb26b6bb768fbfb | train | class | class Documentation(DjangoDocElement):
def __str__(self):
return "\n\n\n".join(str(part) for part in self.parts)
def get_part(self, part_slug):
return self.parts_by_slug.get(part_slug)
def get_chapter(self, part_slug, chapter_slug):
part = self.parts_by_slug.get(part_slug)
... | class Documentation(DjangoDocElement):
| def __str__(self):
return "\n\n\n".join(str(part) for part in self.parts)
def get_part(self, part_slug):
return self.parts_by_slug.get(part_slug)
def get_chapter(self, part_slug, chapter_slug):
part = self.parts_by_slug.get(part_slug)
if part:
return part.chapte... | skip cls in docstring extraction."""
return cls.__name__.endswith("Box") or (hasattr(cls, "no_doc") and cls.no_doc)
def skip_module_doc(module, modules_seen):
return (
module.__doc__ is None
or module in modules_seen
or hasattr(module, "no_doc")
and module.no_doc
)
class... | 256 | 256 | 875 | 7 | 249 | shirok1/mathics-django | mathics_django/doc/django_doc.py | Python | Documentation | Documentation | 99 | 230 | 99 | 99 | 079f924facdb42da5708da1d687b5e33f5144862 | bigcode/the-stack | train |
6711dddc3fc03be6e894f6df | train | function | def skip_doc(cls):
"""Returns True if we should skip cls in docstring extraction."""
return cls.__name__.endswith("Box") or (hasattr(cls, "no_doc") and cls.no_doc)
| def skip_doc(cls):
| """Returns True if we should skip cls in docstring extraction."""
return cls.__name__.endswith("Box") or (hasattr(cls, "no_doc") and cls.no_doc)
| _doc_html_data_path(should_be_readable=True)
with open(doc_data_path, "rb") as doc_data_file:
doc_data = pickle.load(doc_data_file)
except IOError:
print(f"Trouble reading Doc file {doc_data_path}")
doc_data = {}
def skip_doc(cls):
| 63 | 64 | 45 | 5 | 58 | shirok1/mathics-django | mathics_django/doc/django_doc.py | Python | skip_doc | skip_doc | 58 | 60 | 58 | 58 | d27db50dd7e0c146cebfd0508d85653999e4c1e5 | bigcode/the-stack | train |
791f491bf7dc7163c6a27cb9 | train | class | class DjangoDocPart(DjangoDocElement):
def __init__(self, doc, title, is_reference=False):
self.doc = doc
self.title = title
self.slug = slugify(title)
self.chapters = []
self.chapters_by_slug = {}
self.is_reference = is_reference
self.is_appendix = False
... | class DjangoDocPart(DjangoDocElement):
| def __init__(self, doc, title, is_reference=False):
self.doc = doc
self.title = title
self.slug = slugify(title)
self.chapters = []
self.chapters_by_slug = {}
self.is_reference = is_reference
self.is_appendix = False
doc.parts_by_slug[self.slug] = self... | = {self.title} =\n\n{sections}"
def get_collection(self):
"""Return a list of chapters in the part of this chapter."""
return self.part.chapters
def get_uri(self) -> str:
return f"/{self.part.slug}/{self.slug}/"
class DjangoDocPart(DjangoDocElement):
| 70 | 70 | 234 | 9 | 61 | shirok1/mathics-django | mathics_django/doc/django_doc.py | Python | DjangoDocPart | DjangoDocPart | 684 | 715 | 684 | 684 | 828862e6c9feea76042db9f06a0102d468be07b9 | bigcode/the-stack | train |
ea8ba67cb1f3b404af4ed093 | train | class | class DjangoDocElement(object):
def href(self, ajax=False):
if ajax:
return "javascript:loadDoc('%s')" % self.get_uri()
else:
return "/doc%s" % self.get_uri()
def get_prev(self):
return self.get_prev_next()[0]
def get_next(self):
return self.get_prev... | class DjangoDocElement(object):
| def href(self, ajax=False):
if ajax:
return "javascript:loadDoc('%s')" % self.get_uri()
else:
return "/doc%s" % self.get_uri()
def get_prev(self):
return self.get_prev_next()[0]
def get_next(self):
return self.get_prev_next()[1]
def get_collecti... | (hasattr(cls, "no_doc") and cls.no_doc)
def skip_module_doc(module, modules_seen):
return (
module.__doc__ is None
or module in modules_seen
or hasattr(module, "no_doc")
and module.no_doc
)
class DjangoDocElement(object):
| 64 | 64 | 172 | 6 | 58 | shirok1/mathics-django | mathics_django/doc/django_doc.py | Python | DjangoDocElement | DjangoDocElement | 72 | 96 | 72 | 72 | 475783117548d67c0cca1c196ca49363751f38ea | bigcode/the-stack | train |
e26efef9d8a45b709c699450 | train | class | class MathicsMainDocumentation(Documentation):
def __init__(self):
self.doc_dir = settings.DOC_DIR
self.parts = []
self.parts_by_slug = {}
self.pymathics_doc_loaded = False
self.title = "Overview"
files = listdir(self.doc_dir)
files.sort()
appendix = [... | class MathicsMainDocumentation(Documentation):
| def __init__(self):
self.doc_dir = settings.DOC_DIR
self.parts = []
self.parts_by_slug = {}
self.pymathics_doc_loaded = False
self.title = "Overview"
files = listdir(self.doc_dir)
files.sort()
appendix = []
for file in files:
part_... | exact:
return -4 if name == query else -3
if name.startswith(query):
return -2
if query in name:
return -1
lower_name = name.lower()
if lower_name.startswith(query):
return 0
if lower_name in qu... | 256 | 256 | 1,788 | 8 | 247 | shirok1/mathics-django | mathics_django/doc/django_doc.py | Python | MathicsMainDocumentation | MathicsMainDocumentation | 233 | 506 | 233 | 233 | b629cea905452693889a3f6638f3f81080e24f28 | bigcode/the-stack | train |
929c61ff2512875911d74f45 | train | class | class DjangoDocSubsection(DjangoDocElement):
"""An object for a Django Documented Subsection.
A Subsection is part of a Section.
"""
def __init__(
self,
chapter,
section,
title,
text,
operator=None,
installed=True,
in_guide=False,
... | class DjangoDocSubsection(DjangoDocElement):
| """An object for a Django Documented Subsection.
A Subsection is part of a Section.
"""
def __init__(
self,
chapter,
section,
title,
text,
operator=None,
installed=True,
in_guide=False,
summary_text="",
):
"""
I... | self.installed = installed
self.slug = slugify(title)
self.section = submodule
self.slug = slugify(title)
self.subsections = []
self.subsections_by_slug = {}
self.title = title
# FIXME: Sections never are operators. Subsections can have
# operators thoug... | 202 | 203 | 679 | 10 | 192 | shirok1/mathics-django | mathics_django/doc/django_doc.py | Python | DjangoDocSubsection | DjangoDocSubsection | 817 | 910 | 817 | 817 | bdf39e06c771ad9558f2b4e0724c2ac83b207f9a | bigcode/the-stack | train |
ef09b1258658f7974d57e6cf | train | class | class DjangoDocTests(DocTests):
def __init__(self):
self.tests = []
self.text = ""
def html(self, counters=None):
if len(self.tests) == 0:
return "\n"
return '<ul class="tests">%s</ul>' % (
"\n".join(
"<li>%s</li>" % test.html() for test i... | class DjangoDocTests(DocTests):
| def __init__(self):
self.tests = []
self.text = ""
def html(self, counters=None):
if len(self.tests) == 0:
return "\n"
return '<ul class="tests">%s</ul>' % (
"\n".join(
"<li>%s</li>" % test.html() for test in self.tests if not test.private... | r["result"]: # is not None and result['result'].strip():
result += f'<li class="result">{r["result"]}</li>'
result += "</ul>"
result += "</ul>"
result += "</div>"
return result
class DjangoDocTests(DocTests):
| 64 | 64 | 111 | 8 | 55 | shirok1/mathics-django | mathics_django/doc/django_doc.py | Python | DjangoDocTests | DjangoDocTests | 951 | 966 | 951 | 951 | 1ccab70176d24476fec72fac6346481b127daa43 | bigcode/the-stack | train |
bba14f76249ae6556edcf39d | train | class | class PyMathicsDocumentation(Documentation):
def __init__(self, module=None):
self.title = "Overview"
self.parts = []
self.parts_by_slug = {}
self.doc_dir = None
self.doc_data_file = None
self.symbols = {}
if module is None:
return
import ... | class PyMathicsDocumentation(Documentation):
| def __init__(self, module=None):
self.title = "Overview"
self.parts = []
self.parts_by_slug = {}
self.doc_dir = None
self.doc_data_file = None
self.symbols = {}
if module is None:
return
import importlib
# Load the module and veri... | from mathics.settings import default_pymathics_modules
pymathicspart = None
# Look the "Pymathics Modules" part, and if it does not exist, create it.
for part in self.parts:
if part.title == "Pymathics Modules":
pymathicspart = part
if pymathicspart is None:... | 247 | 247 | 826 | 8 | 238 | shirok1/mathics-django | mathics_django/doc/django_doc.py | Python | PyMathicsDocumentation | PyMathicsDocumentation | 509 | 611 | 509 | 509 | 270232f54718f838ef0b39614b58c02e24c9ef57 | bigcode/the-stack | train |
15ba1f2b7debc51e962570b9 | train | class | class CurrentComponentsSinglePING(CurrentComponents):
"""
This lass contains methods of computing the current components for the network of a single PING network.
:param connectivity: information about connectivity between neurons in the oscillatory network.
:type connectivity: Connectivity
:param... | class CurrentComponentsSinglePING(CurrentComponents):
| """
This lass contains methods of computing the current components for the network of a single PING network.
:param connectivity: information about connectivity between neurons in the oscillatory network.
:type connectivity: Connectivity
:param params_synaptic: contains synaptic parameters.
:t... | from src.params.ParamsSynaptic import *
from src.izhikevich_simulation.CurrentComponents import *
from src.izhikevich_simulation.Connectivity import *
import numpy as np
class CurrentComponentsSinglePING(CurrentComponents):
| 47 | 240 | 801 | 8 | 38 | thatmariia/grid-ping | src/izhikevich_simulation/CurrentComponentsSinglePING.py | Python | CurrentComponentsSinglePING | CurrentComponentsSinglePING | 9 | 102 | 9 | 9 | 8a3f82aade4a06164dfb457d4a422560d78ce2d4 | bigcode/the-stack | train |
64addd479463abd4e3e13c5a | train | class | class QualificationCourseEnricher:
"""Handles enriching courses with Qualification data"""
def __init__(self):
blob_helper = BlobHelper()
storage_container_name = os.environ["AzureStorageQualificationsContainerName"]
storage_blob_name = os.environ["AzureStorageQualificationsBlobName"]
... | class QualificationCourseEnricher:
| """Handles enriching courses with Qualification data"""
def __init__(self):
blob_helper = BlobHelper()
storage_container_name = os.environ["AzureStorageQualificationsContainerName"]
storage_blob_name = os.environ["AzureStorageQualificationsBlobName"]
csv_string = blob_helper.g... | import os
import logging
import csv
from SharedCode.blob_helper import BlobHelper
from SharedCode import exceptions
class QualificationCourseEnricher:
| 32 | 117 | 390 | 7 | 24 | office-for-students/beta-data-pipelines | EtlPipeline/qualification_enricher.py | Python | QualificationCourseEnricher | QualificationCourseEnricher | 9 | 62 | 9 | 9 | 139d02a26a09d429622230e49da068e66a588c6a | bigcode/the-stack | train |
2517e5cd43fed75fa847b2fe | train | function | def load_from_gzip_file(gzip_filename):
with gzip.GzipFile(gzip_filename, 'r') as fin: # 4. gzip
json_bytes = fin.read() # 3. bytes (i.e. UTF-8)
json_str = json_bytes.decode('utf-8') # 2. string (i.e. JSON)
return json.loads(json_str) # 1. data
| def load_from_gzip_file(gzip_filename):
| with gzip.GzipFile(gzip_filename, 'r') as fin: # 4. gzip
json_bytes = fin.read() # 3. bytes (i.e. UTF-8)
json_str = json_bytes.decode('utf-8') # 2. string (i.e. JSON)
return json.loads(json_str) # 1. data
| = json_str.encode('utf-8') # 3. bytes (i.e. UTF-8)
with gzip.GzipFile(gzip_filename, 'w') as f_out: # 4. gzip
f_out.write(json_bytes)
def load_from_gzip_file(gzip_filename):
| 64 | 64 | 92 | 10 | 54 | xalperte/tfm-uoc-crawling-system | src/notebooks/json_utils.py | Python | load_from_gzip_file | load_from_gzip_file | 19 | 24 | 19 | 19 | 07b222acd018e4e6215bc4aae997fa9f617730c2 | bigcode/the-stack | train |
0cb7eac72eafb45a5be6cf25 | train | function | def write_to_gzip_file(gzip_filename, data):
json_str = json.dumps(data) + "\n" # 2. string (i.e. JSON)
json_bytes = json_str.encode('utf-8') # 3. bytes (i.e. UTF-8)
with gzip.GzipFile(gzip_filename, 'w') as f_out: # 4. gzip
f_out.write(json_bytes)
| def write_to_gzip_file(gzip_filename, data):
| json_str = json.dumps(data) + "\n" # 2. string (i.e. JSON)
json_bytes = json_str.encode('utf-8') # 3. bytes (i.e. UTF-8)
with gzip.GzipFile(gzip_filename, 'w') as f_out: # 4. gzip
f_out.write(json_bytes)
| -8 -*
# Copyright (c) 2019 BuildGroup Data Services Inc.
# All rights reserved.
# This software is proprietary and confidential and may not under
# any circumstances be used, copied, or distributed.
import gzip
import json
def write_to_gzip_file(gzip_filename, data):
| 64 | 64 | 93 | 12 | 51 | xalperte/tfm-uoc-crawling-system | src/notebooks/json_utils.py | Python | write_to_gzip_file | write_to_gzip_file | 10 | 16 | 10 | 11 | 46e5909d5971496328f82a9dcf04245181ca16c7 | bigcode/the-stack | train |
e5e6c0e7d9ff87cda5193cb2 | train | class | class LoggingBaseCommand(BaseCommand):
"""
Extends BaseCommand with a logger whose level is
set from the `--verbosity` option.
Verbosity to log level mapping:
0: error
1: warning (default)
2: info
3: debug
"""
def __init__(self, log_name=None, mapping=None, *args, **kwargs):
... | class LoggingBaseCommand(BaseCommand):
| """
Extends BaseCommand with a logger whose level is
set from the `--verbosity` option.
Verbosity to log level mapping:
0: error
1: warning (default)
2: info
3: debug
"""
def __init__(self, log_name=None, mapping=None, *args, **kwargs):
BaseCommand.__init__(self, *args,... | """
BaseCommand extension adding logger.
"""
import logging
from django.core.management import BaseCommand
from oauth2_client.compat import HelpTextFormatter
class LoggingBaseCommand(BaseCommand):
| 36 | 81 | 273 | 7 | 28 | Livit/Labster.OAuth2Client | oauth2_client/utils/django/base_cmd.py | Python | LoggingBaseCommand | LoggingBaseCommand | 11 | 43 | 11 | 11 | e8fe23100a10c7f07a601158eec5696b1f11922d | bigcode/the-stack | train |
7f7f6bec119334d0c311dddc | train | function | def parts_mode(dataset_name, parts_num):
if dataset_name == 'coco':
k = lambda name: coco_keypoints_id[name]
parts_names = coco_keypoints_id
elif dataset_name == 'mpii':
k = lambda name: mpii_keypoints_id[name]
parts_names = mpii_keypoints_id
else:
print("wrong datase... | def parts_mode(dataset_name, parts_num):
| if dataset_name == 'coco':
k = lambda name: coco_keypoints_id[name]
parts_names = coco_keypoints_id
elif dataset_name == 'mpii':
k = lambda name: mpii_keypoints_id[name]
parts_names = mpii_keypoints_id
else:
print("wrong dataset name")
raise ValueError
pa... | = 15
coco_keypoints_id = {}
coco_keypoints_id['nose'] = 0
coco_keypoints_id['l_eye'] = 1
coco_keypoints_id['r_eye'] = 2
coco_keypoints_id['l_ear'] = 3
coco_keypoints_id['r_ear'] = 4
coco_keypoints_id['l_shoulder'] = 5
coco_keypoints_id['r_shoulder'] = 6
coco_keypoints_id['l_elbow'] = 7
coco_keypoints_id['r_elbow'] = ... | 256 | 256 | 1,027 | 9 | 246 | zhangrj91/DarkPose | src/network_factory/body_parts.py | Python | parts_mode | parts_mode | 56 | 131 | 56 | 56 | a1eb6caed749b5d95a30344346889f9e61aa0ac1 | bigcode/the-stack | train |
59e500052c0139b4a100c0fc | train | class | class Migration(migrations.Migration):
dependencies = [
('setting', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='setting',
options={'ordering': ('key',), 'verbose_name': 'Parameter', 'verbose_name_plural': 'Parameters'},
),
]
| class Migration(migrations.Migration):
| dependencies = [
('setting', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='setting',
options={'ordering': ('key',), 'verbose_name': 'Parameter', 'verbose_name_plural': 'Parameters'},
),
]
| # Generated by Django 2.1 on 2019-03-13 21:22
from django.db import migrations
class Migration(migrations.Migration):
| 34 | 64 | 65 | 7 | 26 | mucahitnezir/django-starter | setting/migrations/0002_auto_20190314_0022.py | Python | Migration | Migration | 6 | 17 | 6 | 7 | 0a2dfae299ac0598b6c872f8e863e05c65a44b8a | bigcode/the-stack | train |
462a9853486a41626e5eea68 | train | function | def main():
""" The main() function. """
print("STARTING ENVIRONMENT TEST")
seed = 0
max_timesteps = 4e6
if ARGS.DebugRack:
on_rack = True
else:
on_rack = False
if ARGS.DebugPath:
draw_foot_path = True
else:
draw_foot_path = False
if ARGS.Height... | def main():
| """ The main() function. """
print("STARTING ENVIRONMENT TEST")
seed = 0
max_timesteps = 4e6
if ARGS.DebugRack:
on_rack = True
else:
on_rack = False
if ARGS.DebugPath:
draw_foot_path = True
else:
draw_foot_path = False
if ARGS.HeightField:
... | .pyplot as plt
import copy
import sys
import time
import os
import argparse
sys.path.append('../')
from gym_env import GymEnv
from gui_param_control import GuiParamControl
from kinematics import Kinematics
from bezier_gait import BezierGait
from env_randomizer import EnvRandomizer
# ARGUMENTS
parser = argparse.Argum... | 256 | 256 | 969 | 3 | 253 | reubenstr/zuko | quad_ws/src/quad_simulation/quad_simulation/src/env_tester.py | Python | main | main | 52 | 179 | 52 | 52 | 54edfc53aef7ef5c1719ab91bf191a66eac7c582 | bigcode/the-stack | train |
50352e51ae3e611b949aed06 | train | class | class NetWrapper(nn.Module):
def __init__(self, cfg):
super(NetWrapper, self).__init__()
self.model_name = cfg.MODEL.NAME
model_list = {
"resnet50": ResNet50Protein,
"resnet34_maxavg": ResNet34MaxAvgProtein,
"resnet34_maxavg_no_dropout": ResNet34MaxAvgNoDr... | class NetWrapper(nn.Module):
| def __init__(self, cfg):
super(NetWrapper, self).__init__()
self.model_name = cfg.MODEL.NAME
model_list = {
"resnet50": ResNet50Protein,
"resnet34_maxavg": ResNet34MaxAvgProtein,
"resnet34_maxavg_no_dropout": ResNet34MaxAvgNoDropout,
"resnet34_... | # Copyright (c) xiaoxuan : https://github.com/shawnau/kaggle-HPA
# modified by sailfish009
from torch import nn
from .base import *
class NetWrapper(nn.Module):
| 46 | 120 | 401 | 6 | 40 | sailfish009/mydl | custom/protein/network.py | Python | NetWrapper | NetWrapper | 8 | 46 | 8 | 8 | 2e292234c787d594d5c96a3086293f9fea77bacd | bigcode/the-stack | train |
d79fcc63169074ba28c044d3 | train | class | class TeamRegister(forms.ModelForm):
team_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Team name'}), max_length=50, required=True, help_text="Enter team name")
college_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Colle... | class TeamRegister(forms.ModelForm):
| team_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Team name'}), max_length=50, required=True, help_text="Enter team name")
college_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'College name', 'readonly':'readonly'}), ma... | from django import forms;
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.db import models
from django.forms import fields
from teams.models.team import Team
from bootstrap_modal_forms.forms import BSModalModelForm
from django.shortcuts import get_object_or_404... | 68 | 68 | 227 | 7 | 60 | JasbirCodeSpace/CTF | teams/forms/team.py | Python | TeamRegister | TeamRegister | 10 | 28 | 10 | 10 | 372acc7dde8753edc322a1e415a5a0a866362b4b | bigcode/the-stack | train |
60612c490ba712715d45bf94 | train | class | class TeamJoin(forms.Form):
team_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Team name'}), max_length=50, required=True, help_text="Enter team name")
password = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control', 'placeholder':'Team password'... | class TeamJoin(forms.Form):
| team_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Team name'}), max_length=50, required=True, help_text="Enter team name")
password = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control', 'placeholder':'Team password'}), max_length=50, required=... | ['team_name']
if Team.objects.filter(team_name = team_name).exists():
raise forms.ValidationError("Team with this name already exist")
return team_name
def clean(self):
cleaned_data = super(TeamRegister, self).clean()
return cleaned_data
class TeamJoin(forms.For... | 64 | 64 | 188 | 6 | 57 | JasbirCodeSpace/CTF | teams/forms/team.py | Python | TeamJoin | TeamJoin | 30 | 48 | 30 | 30 | c10910ffbc3fe61b1697cbd1b786dd4f607ddb78 | bigcode/the-stack | train |
0cab3ce94d88728256e3d4e7 | train | class | class TeamCaptainForm(forms.Form):
team_captain = forms.ModelChoiceField(queryset=User.objects.all(),widget=forms.Select(attrs={'class':'form-control'}),empty_label=None)
def __init__(self, *args, **kwargs):
team_id = kwargs.pop('team_id', None)
super(TeamCaptainForm, self).__init__(*args, ... | class TeamCaptainForm(forms.Form):
| team_captain = forms.ModelChoiceField(queryset=User.objects.all(),widget=forms.Select(attrs={'class':'form-control'}),empty_label=None)
def __init__(self, *args, **kwargs):
team_id = kwargs.pop('team_id', None)
super(TeamCaptainForm, self).__init__(*args, **kwargs)
if team_id:
... | ):
# team_name = self.cleaned_data['team_name']
# print(self)
# if Team.objects.filter(team_name = team_name).exists():
# raise forms.ValidationError("Team with this name already exist")
# return team_name
class TeamCaptainForm(forms.Form):
| 64 | 64 | 141 | 7 | 56 | JasbirCodeSpace/CTF | teams/forms/team.py | Python | TeamCaptainForm | TeamCaptainForm | 66 | 76 | 66 | 66 | 9b8b87c0e94fbe1a572b36c153f46654be10e1d1 | bigcode/the-stack | train |
d7e35b0e9461227d9a2a63a7 | train | class | class TeamUpdateForm(forms.ModelForm):
team_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Team name'}), max_length=50, required=True, help_text="Enter team name")
password = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Team pa... | class TeamUpdateForm(forms.ModelForm):
| team_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Team name'}), max_length=50, required=True, help_text="Enter team name")
password = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Team password'}), max_length=50, required=True... | _name, password = password)
if not team:
raise forms.ValidationError("Invalid team name or password")
if team.first().users.all().count()>=5:
raise forms.ValidationError("Maximum 5 members allowed per team.")
return cleaned_data
class TeamUpdateForm(forms.ModelForm):... | 64 | 64 | 106 | 8 | 55 | JasbirCodeSpace/CTF | teams/forms/team.py | Python | TeamUpdateForm | TeamUpdateForm | 51 | 57 | 51 | 51 | 6381402b6145ebc7a0ac07a3aa34dc962a93617d | bigcode/the-stack | train |
05bf9c4a3b79dc6880411094 | train | class | class NoProgram(object):
def toXML(self, writer, ttFont):
pass
def getBytecode(self):
return ''
| class NoProgram(object):
| def toXML(self, writer, ttFont):
pass
def getBytecode(self):
return ''
| ].box
if lbox is not None:
box = (min(box[0], lbox[0]), min(box[1], lbox[1]), max(box[2], lbox[2]), max(box[3], lbox[3]))
return box
class NoProgram(object):
| 64 | 64 | 29 | 5 | 58 | roboDocs/RoboChrome | RoboChrome.roboFontExt/lib/colorfont/__init__.py | Python | NoProgram | NoProgram | 898 | 903 | 898 | 898 | fb2c4a10f240ceef78e168e00873fa97f739c05a | bigcode/the-stack | train |
a55d8e74492ef333b8e320a4 | train | class | class ColorFont(object):
def __init__(self, rfont=None):
"""Initialize a ColorFont and read color data from a RFont.
rfont: The RFont object to load the color data from"""
self.libkey = "com.fontfont.colorfont"
# default values
self._auto_layer_regex_default = r"\.alt[0-... | class ColorFont(object):
| def __init__(self, rfont=None):
"""Initialize a ColorFont and read color data from a RFont.
rfont: The RFont object to load the color data from"""
self.libkey = "com.fontfont.colorfont"
# default values
self._auto_layer_regex_default = r"\.alt[0-9]{3}$"
self._bit... | _, Color
from fontTools.ttLib.tables.C_O_L_R_ import table_C_O_L_R_, LayerRecord
from fontTools.ttLib.tables._s_b_i_x import table__s_b_i_x
from fontTools.ttLib.tables.sbixStrike import Strike
from fontTools.ttLib.tables.sbixGlyph import Glyph as sbixGlyph
from fontTools.ttLib.tables.S_V_G_ import table_S_V_G_
import ... | 256 | 256 | 6,081 | 5 | 250 | roboDocs/RoboChrome | RoboChrome.roboFontExt/lib/colorfont/__init__.py | Python | ColorFont | ColorFont | 38 | 670 | 38 | 38 | a55cc8b6f3f0e1c7619a960e8830aca68830c5ad | bigcode/the-stack | train |
4c93a07f0ffe56fdc9f08a91 | train | function | def test():
# make PDF for color glyph
_font = ColorFont(CurrentFont())
_font.read_from_rfont()
# _font._export_sbix(r"/Users/jenskutilek/Documents/Color Fonts MS/Dingbats2SamplerOT.ttf", 0, [20, 40, 72, 96, 128, 160, 256, 512], "png")
# _font.rasterize(0, [16])
# _font.export_png("six", "/Users... | def test():
# make PDF for color glyph
| _font = ColorFont(CurrentFont())
_font.read_from_rfont()
# _font._export_sbix(r"/Users/jenskutilek/Documents/Color Fonts MS/Dingbats2SamplerOT.ttf", 0, [20, 40, 72, 96, 128, 160, 256, 512], "png")
# _font.rasterize(0, [16])
# _font.export_png("six", "/Users/jenskutilek/Desktop/six.png", 0, 1000)
... | (box[2], lbox[2]), max(box[3], lbox[3]))
return box
class NoProgram(object):
def toXML(self, writer, ttFont):
pass
def getBytecode(self):
return ''
def test():
# make PDF for color glyph
| 63 | 64 | 184 | 11 | 52 | roboDocs/RoboChrome | RoboChrome.roboFontExt/lib/colorfont/__init__.py | Python | test | test | 906 | 919 | 906 | 907 | a9d806f09f250d5a25daa4ca441c043b1d0f8bfd | bigcode/the-stack | train |
82a3d8ea104c3566fbc82b24 | train | class | class ColorGlyph(object):
def __init__(self, parent, basename=""):
"""Each ColorGlyph consists of a base glyph and some layer glyphs
which are assigned to colors via palette indices.
parent: the ColorFont instance
basename: name of the base glyph"""
self.font = pare... | class ColorGlyph(object):
| def __init__(self, parent, basename=""):
"""Each ColorGlyph consists of a base glyph and some layer glyphs
which are assigned to colors via palette indices.
parent: the ColorFont instance
basename: name of the base glyph"""
self.font = parent
self.basename =... | _regex)
regex = compile(layer_regex)
# print("Looking for layer glyphs with regex", layer_regex)
has_layers = False
for layername in self.rfont.glyphOrder:
if regex.search(layername):
# print(" found")
if not basegl... | 256 | 256 | 2,182 | 5 | 251 | roboDocs/RoboChrome | RoboChrome.roboFontExt/lib/colorfont/__init__.py | Python | ColorGlyph | ColorGlyph | 673 | 895 | 673 | 673 | 6244e7c3d6ea33fe390c5cb1b71bab77bc774746 | bigcode/the-stack | train |
cca33175fd14cb04ac6862c1 | train | function | def select_py(
condition, pairs_path, output, output_rest, send_comments_to, chrom_subset,
startup_code, type_cast,
**kwargs
):
instream = (_fileio.auto_open(pairs_path, mode='r',
nproc=kwargs.get('nproc_in'),
command=kwargs.get('... | def select_py(
condition, pairs_path, output, output_rest, send_comments_to, chrom_subset,
startup_code, type_cast,
**kwargs
):
| instream = (_fileio.auto_open(pairs_path, mode='r',
nproc=kwargs.get('nproc_in'),
command=kwargs.get('cmd_in', None))
if pairs_path else sys.stdin)
outstream = (_fileio.auto_open(output, mode='w',
... | e.g. regex_match(chrom1, 'chr\d')
\b
Examples:
pairtools select '(pair_type=="UU") or (pair_type=="UR") or (pair_type=="RU")'
pairtools select 'chrom1==chrom2'
pairtools select 'COLS[1]==COLS[3]'
pairtools select '(chrom1==chrom2) and (abs(pos1 - pos2) < 1e6)'
pairtools select '(chrom1=... | 233 | 234 | 783 | 36 | 197 | agalitsyna/pairtools | pairtools/pairtools_select.py | Python | select_py | select_py | 123 | 217 | 123 | 128 | 83454899db0c0a0016e741eaf070e82854992a4a | bigcode/the-stack | train |
05293529dfc9b0758c6bd87f | train | function | @cli.command()
@click.argument(
'condition',
type=str
)
@click.argument(
'pairs_path',
type=str,
required=False)
@click.option(
'-o', "--output",
type=str,
default="",
help='output file.'
' If the path ends with .gz or .lz4, the output is pbgzip-/lz4c-compressed.'
... | @cli.command()
@click.argument(
'condition',
type=str
)
@click.argument(
'pairs_path',
type=str,
required=False)
@click.option(
'-o', "--output",
type=str,
default="",
help='output file.'
' If the path ends with .gz or .lz4, the output is pbgzip-/lz4c-compressed.'
... | '''Select pairs according to some condition.
CONDITION : A Python expression; if it returns True, select the read pair.
Any column declared in the #columns line of the pairs header can be
accessed by its name. If the header lacks the #columns line, the columns
are assumed to follow the .pairs/.pai... | @cli.command()
@click.argument(
'condition',
type=str
)
@click.argument(
'pairs_path',
type=str,
required=False)
@click.option(
'-o', "--output",
type=str,
default="",
help='output file.'
' If the path ends with .gz or .lz4, the output is pbgzip-/lz4c-compressed.'
... | 494 | 256 | 989 | 494 | 0 | agalitsyna/pairtools | pairtools/pairtools_select.py | Python | select | select | 9 | 121 | 9 | 79 | 16f775d6916eaa1ac4f2b1bbb7b89f0e06fdd900 | bigcode/the-stack | train |
e1f782ea57d1ed632a10ca78 | train | class | class ProductStructureElementModel:
def __init__(self, data):
self.children = []
self.type = None
self.elementId = data['elementId']
self.type = data['type']
self.name = data['name']
self.additionalData = data['additionalData']
for element in data['c... | class ProductStructureElementModel:
| def __init__(self, data):
self.children = []
self.type = None
self.elementId = data['elementId']
self.type = data['type']
self.name = data['name']
self.additionalData = data['additionalData']
for element in data['children']:
self.children... | from typing import List
from enum import Enum
class ProductStructureTypeEnum(Enum):
CHARACTERISTIC = "CHARACTERISTIC",
FEATURE = "FEATURE",
CLUSTER = "CLUSTER",
VARIABLE = "VARIABLE",
class ProductStructureElementModel:
| 52 | 64 | 191 | 6 | 46 | 13hannes11/bachelor_thesis_m.recommend | src/model/product_structure_model.py | Python | ProductStructureElementModel | ProductStructureElementModel | 11 | 35 | 11 | 11 | a276d2bf0971efe582f65cc5566cb9c8fe152138 | bigcode/the-stack | train |
d20d17153ed2bc369b258e94 | train | class | class ProductStructureTypeEnum(Enum):
CHARACTERISTIC = "CHARACTERISTIC",
FEATURE = "FEATURE",
CLUSTER = "CLUSTER",
VARIABLE = "VARIABLE",
| class ProductStructureTypeEnum(Enum):
| CHARACTERISTIC = "CHARACTERISTIC",
FEATURE = "FEATURE",
CLUSTER = "CLUSTER",
VARIABLE = "VARIABLE",
| from typing import List
from enum import Enum
class ProductStructureTypeEnum(Enum):
| 17 | 64 | 36 | 7 | 9 | 13hannes11/bachelor_thesis_m.recommend | src/model/product_structure_model.py | Python | ProductStructureTypeEnum | ProductStructureTypeEnum | 4 | 8 | 4 | 4 | cfb705823de9dda0888a3a4aef5124bacdf3a25d | bigcode/the-stack | train |
eb409ddc21e8e45ca62de916 | train | class | class ProductStructureModel:
list_of_features = []
list_of_characteristics = []
def __init__(self, data):
self.productStructure : List[ProductStructureElementModel] = []
for element in data['ProductStructure']:
child = ProductStructureElementModel(element)
self... | class ProductStructureModel:
| list_of_features = []
list_of_characteristics = []
def __init__(self, data):
self.productStructure : List[ProductStructureElementModel] = []
for element in data['ProductStructure']:
child = ProductStructureElementModel(element)
self.productStructure.append(child... | if ProductStructureTypeEnum[self.type] == type:
tmp_list.append(self)
return tmp_list
def get_children_characteristics(self):
tmp_list = self.get_list_of_all(ProductStructureTypeEnum.CHARACTERISTIC)
if self in tmp_list:
tmp_list.remove(self)
r... | 72 | 72 | 243 | 5 | 66 | 13hannes11/bachelor_thesis_m.recommend | src/model/product_structure_model.py | Python | ProductStructureModel | ProductStructureModel | 38 | 67 | 38 | 38 | ea3ed456081cb0b3e0c2af28e5c72662cc606f18 | bigcode/the-stack | train |
86a0ee45cd31584f24ed5273 | train | function | def undo_image_transformation(img, w, h):
"""
Takes a transformed image tensor and returns a numpy ndarray that is untransformed.
Arguments w and h are the original height and width of the image.
"""
img_numpy = img.permute(1, 2, 0).cpu().numpy()
img_numpy = img_numpy[:, :, (2, 1, 0)] # To BRG
... | def undo_image_transformation(img, w, h):
| """
Takes a transformed image tensor and returns a numpy ndarray that is untransformed.
Arguments w and h are the original height and width of the image.
"""
img_numpy = img.permute(1, 2, 0).cpu().numpy()
img_numpy = img_numpy[:, :, (2, 1, 0)] # To BRG
if cfg.backbone.transform.normalize:
... | align_corners=False)
mask = mask.gt(0.5).float()
full_masks[jdx, y1:y2, x1:x2] = mask
masks = full_masks
return classes, scores, boxes, masks
def undo_image_transformation(img, w, h):
| 63 | 64 | 212 | 11 | 51 | chenjianqu/is_slam | src/is_slam/yolact/layers/output_utils.py | Python | undo_image_transformation | undo_image_transformation | 131 | 147 | 131 | 131 | f67830bdb5070b110923b19ba98c7bda4efd9efd | bigcode/the-stack | train |
ccb2343cf77e743bbc3d0e3b | train | function | def postprocess(det_output, w, h, batch_idx=0, interpolation_mode='bilinear',
visualize_lincomb=False, crop_masks=True, score_threshold=0):
"""
Postprocesses the output of Yolact on testing mode into a format that makes sense,
accounting for all the possible configuration settings.
Args... | def postprocess(det_output, w, h, batch_idx=0, interpolation_mode='bilinear',
visualize_lincomb=False, crop_masks=True, score_threshold=0):
| """
Postprocesses the output of Yolact on testing mode into a format that makes sense,
accounting for all the possible configuration settings.
Args:
- det_output: The lost of dicts that Detect outputs.
- w: The real with of the image.
- h: The real height of the image.
-... | """ Contains functions used to sanitize and prepare the output of Yolact. """
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import cv2
from data import cfg, mask_type, MEANS, STD, activation_func
from utils.augmentations import Resize
from utils import timer
from .box_utils im... | 120 | 256 | 1,021 | 36 | 83 | chenjianqu/is_slam | src/is_slam/yolact/layers/output_utils.py | Python | postprocess | postprocess | 18 | 125 | 18 | 19 | 732ff47d9bad093a8beb1818c1621121ef1beb31 | bigcode/the-stack | train |
82edd2eb03f934d897a6d5ef | train | function | def display_lincomb(proto_data, masks):
out_masks = torch.matmul(proto_data, masks.t())
# out_masks = cfg.mask_proto_mask_activation(out_masks)
for kdx in range(1):
jdx = kdx + 0
import matplotlib.pyplot as plt
coeffs = masks[jdx, :].cpu().numpy()
idx = np.argsort(-np.abs(co... | def display_lincomb(proto_data, masks):
| out_masks = torch.matmul(proto_data, masks.t())
# out_masks = cfg.mask_proto_mask_activation(out_masks)
for kdx in range(1):
jdx = kdx + 0
import matplotlib.pyplot as plt
coeffs = masks[jdx, :].cpu().numpy()
idx = np.argsort(-np.abs(coeffs))
# plt.bar(list(range(idx.... | 0)] # To BRG
if cfg.backbone.transform.normalize:
img_numpy = (img_numpy * np.array(STD) + np.array(MEANS)) / 255.0
elif cfg.backbone.transform.subtract_means:
img_numpy = (img_numpy / 255.0 + np.array(MEANS) / 255.0).astype(np.float32)
img_numpy = img_numpy[:, :, (2, 1, 0)] # To R... | 139 | 139 | 464 | 9 | 130 | chenjianqu/is_slam | src/is_slam/yolact/layers/output_utils.py | Python | display_lincomb | display_lincomb | 150 | 191 | 150 | 150 | a323455ee5e09c903f4d060a1258fb0f57cbfde8 | bigcode/the-stack | train |
62daabe397a39400520735d9 | train | function | def test_xy_to_gpd():
pts_df = pts[[sites_col_name, 'geometry']].copy()
pts_df['x'] = pts_df.geometry.x
pts_df['y'] = pts_df.geometry.y
pts_df.drop('geometry', axis=1, inplace=True)
pts3 = vector.xy_to_gpd(sites_col_name, 'x', 'y', pts_df)
assert (len(pts3) == 2) & isinstance(pts3, gpd.GeoData... | def test_xy_to_gpd():
| pts_df = pts[[sites_col_name, 'geometry']].copy()
pts_df['x'] = pts_df.geometry.x
pts_df['y'] = pts_df.geometry.y
pts_df.drop('geometry', axis=1, inplace=True)
pts3 = vector.xy_to_gpd(sites_col_name, 'x', 'y', pts_df)
assert (len(pts3) == 2) & isinstance(pts3, gpd.GeoDataFrame)
| poly2 = vector.pts_poly_join(sites_shp_path, catch_shp_path, poly_col_name)
assert (len(pts2) == 2) & (len(poly2) == 1) & isinstance(pts2, gpd.GeoDataFrame)
def test_xy_to_gpd():
| 64 | 64 | 108 | 7 | 57 | claruspeter/gistools | gistools/tests/test_vector.py | Python | test_xy_to_gpd | test_xy_to_gpd | 51 | 59 | 51 | 51 | a9e98fbd98adfbaff62a051cc71a1d7ff3c64c7e | bigcode/the-stack | train |
a87ee9318641525f8aaa4b54 | train | function | def test_pts_poly_join():
pts2, poly2 = vector.pts_poly_join(sites_shp_path, catch_shp_path, poly_col_name)
assert (len(pts2) == 2) & (len(poly2) == 1) & isinstance(pts2, gpd.GeoDataFrame)
| def test_pts_poly_join():
| pts2, poly2 = vector.pts_poly_join(sites_shp_path, catch_shp_path, poly_col_name)
assert (len(pts2) == 2) & (len(poly2) == 1) & isinstance(pts2, gpd.GeoDataFrame)
| roid
def test_sel_sites_poly():
pts1 = vector.sel_sites_poly(sites_shp_path, rec_catch_shp_path, buffer_dis=10)
assert (len(pts1) == 2) & isinstance(pts1, gpd.GeoDataFrame)
def test_pts_poly_join():
| 64 | 64 | 67 | 6 | 58 | claruspeter/gistools | gistools/tests/test_vector.py | Python | test_pts_poly_join | test_pts_poly_join | 46 | 49 | 46 | 46 | 9c722e43f48ec135ecf31c7c398652dc483c859d | bigcode/the-stack | train |
ad93328c752ca91db53cdbb0 | train | function | def test_sel_sites_poly():
pts1 = vector.sel_sites_poly(sites_shp_path, rec_catch_shp_path, buffer_dis=10)
assert (len(pts1) == 2) & isinstance(pts1, gpd.GeoDataFrame)
| def test_sel_sites_poly():
| pts1 = vector.sel_sites_poly(sites_shp_path, rec_catch_shp_path, buffer_dis=10)
assert (len(pts1) == 2) & isinstance(pts1, gpd.GeoDataFrame)
| ites_shp_path)
pts['geometry'] = pts.geometry.simplify(1)
rec_streams1 = util.load_geo_data(rec_streams_shp_path)
rec_pts1 = rec_streams1.copy()
rec_pts1['geometry'] = rec_streams1.centroid
def test_sel_sites_poly():
| 64 | 64 | 56 | 6 | 57 | claruspeter/gistools | gistools/tests/test_vector.py | Python | test_sel_sites_poly | test_sel_sites_poly | 41 | 44 | 41 | 41 | 5819f0b443f5d0f537b8c9835f776586f6e60d8f | bigcode/the-stack | train |
9494139a7d5d6402bb923ddb | train | function | def test_kd_nearest():
line2 = vector.kd_nearest(pts, rec_pts1, line_site_col)
assert (len(line2) == 2) & isinstance(line2, gpd.GeoDataFrame) & line2[line_site_col].notnull().all()
| def test_kd_nearest():
| line2 = vector.kd_nearest(pts, rec_pts1, line_site_col)
assert (len(line2) == 2) & isinstance(line2, gpd.GeoDataFrame) & line2[line_site_col].notnull().all()
| = vector.closest_line_to_pts(sites_shp_path, rec_streams_shp_path, line_site_col)
assert (len(line1) == 2) & isinstance(line1, gpd.GeoDataFrame) & line1[line_site_col].notnull().all()
def test_kd_nearest():
| 64 | 64 | 61 | 7 | 57 | claruspeter/gistools | gistools/tests/test_vector.py | Python | test_kd_nearest | test_kd_nearest | 67 | 70 | 67 | 67 | 25be957a9149b05309e3b007b4d0e8b2a87056bf | bigcode/the-stack | train |
fbc8e771a09a2b69f656de12 | train | function | def test_closest_line_to_pts():
line1 = vector.closest_line_to_pts(sites_shp_path, rec_streams_shp_path, line_site_col)
assert (len(line1) == 2) & isinstance(line1, gpd.GeoDataFrame) & line1[line_site_col].notnull().all()
| def test_closest_line_to_pts():
| line1 = vector.closest_line_to_pts(sites_shp_path, rec_streams_shp_path, line_site_col)
assert (len(line1) == 2) & isinstance(line1, gpd.GeoDataFrame) & line1[line_site_col].notnull().all()
| geometry', axis=1, inplace=True)
pts3 = vector.xy_to_gpd(sites_col_name, 'x', 'y', pts_df)
assert (len(pts3) == 2) & isinstance(pts3, gpd.GeoDataFrame)
def test_closest_line_to_pts():
| 64 | 64 | 68 | 8 | 56 | claruspeter/gistools | gistools/tests/test_vector.py | Python | test_closest_line_to_pts | test_closest_line_to_pts | 61 | 64 | 61 | 61 | 4196432f527cd241f4f725d51c8331b6f17d94d0 | bigcode/the-stack | train |
32e5a13737ce8cbedf3c1c83 | train | class | class GradeSheetError(Exception):
"""A general-purpose exception thrown by the Assignment class.
"""
pass
| class GradeSheetError(Exception):
| """A general-purpose exception thrown by the Assignment class.
"""
pass
| import git
import glob
import logging
import os
from .config import AssignmentConfig
logger = logging.getLogger(__name__)
class GradeSheetError(Exception):
| 33 | 64 | 23 | 6 | 27 | redkyn/grader | redkyn-grader/grader/models/gradesheet.py | Python | GradeSheetError | GradeSheetError | 11 | 14 | 11 | 11 | b24af6fe57fb8ffc134cf74c69339c378c4a764d | bigcode/the-stack | train |
1115f670c0593aafcd8e4bf8 | train | class | class GradeSheet(object):
"""A gradesheet for an assignment. Gradesheets are git
repositories. They have the following attributes...
A configuration file
Assignment-specific configuration information (refer to
:class:`AssignmentConfig`)
A Dockerfile
Used to build a docker image... | class GradeSheet(object):
| """A gradesheet for an assignment. Gradesheets are git
repositories. They have the following attributes...
A configuration file
Assignment-specific configuration information (refer to
:class:`AssignmentConfig`)
A Dockerfile
Used to build a docker image. That image will be used ... | import git
import glob
import logging
import os
from .config import AssignmentConfig
logger = logging.getLogger(__name__)
class GradeSheetError(Exception):
"""A general-purpose exception thrown by the Assignment class.
"""
pass
class GradeSheet(object):
| 55 | 229 | 764 | 5 | 49 | redkyn/grader | redkyn-grader/grader/models/gradesheet.py | Python | GradeSheet | GradeSheet | 17 | 127 | 17 | 17 | f63e08237271ca07d436829f07f5b45a736b20da | bigcode/the-stack | train |
a217d9f19f944caff406293c | train | function | def P(num):
num += 1
num = str(num)
l = len(num)
if l % 2:
mir = num[:int(l/2)] + num[l//2::-1]
else:
mir = num[:int(l/2)] + num[l//2-1::-1]
if int(mir) < int(num):
if l % 2:
return mir[:l//2] + str(int(mir[l//2])+1) + mir[l//2+1:]
else:
... | def P(num):
| num += 1
num = str(num)
l = len(num)
if l % 2:
mir = num[:int(l/2)] + num[l//2::-1]
else:
mir = num[:int(l/2)] + num[l//2-1::-1]
if int(mir) < int(num):
if l % 2:
return mir[:l//2] + str(int(mir[l//2])+1) + mir[l//2+1:]
else:
return mir[:... | : What is P( 7100 )
Thanks to ashashwat for suggesting this problem at /r/dailyprogrammer_ideas! (problem originally from here) If you have
a problem that you think would be good for this subreddit, why not head over there and suggest it?
"""
def P(num):
| 64 | 64 | 157 | 4 | 60 | DayGitH/Python-Challenges | DailyProgrammer/20120528B.py | Python | P | P | 17 | 32 | 17 | 17 | 9a9861a717b5933e493a8eb68aaabb4ad1b428c2 | bigcode/the-stack | train |
8553198a2e552c4f3c7e05cd | train | function | def main():
print(808, P(808))
print(999, P(999))
print(2133, P(2133))
print(3 ** 39, P(3 ** 39))
print('')
print(7**100)
print(P(7**100))
| def main():
| print(808, P(808))
print(999, P(999))
print(2133, P(2133))
print(3 ** 39, P(3 ** 39))
print('')
print(7**100)
print(P(7**100))
| str(int(mir[l//2])+1) + mir[l//2+1:]
else:
return mir[:l//2-1] + str(int(mir[l//2-1:l//2+1])+11) + mir[l//2+1:]
return mir
def main():
| 64 | 64 | 66 | 3 | 60 | DayGitH/Python-Challenges | DailyProgrammer/20120528B.py | Python | main | main | 34 | 42 | 34 | 34 | a545c3184ce483023ad8508b1e22b52cfe8bd1a1 | bigcode/the-stack | train |
5d3def6581da615b02ebd4b8 | train | class | class App(QtWidgets.QMainWindow, design.Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
pg.setConfigOptions(antialias=True)
self.graphicsView.plot()
def update_graphics(self):
self.graphicsView.clear()
a1 = self.verticalSlider_1.value()... | class App(QtWidgets.QMainWindow, design.Ui_MainWindow):
| def __init__(self):
super().__init__()
self.setupUi(self)
pg.setConfigOptions(antialias=True)
self.graphicsView.plot()
def update_graphics(self):
self.graphicsView.clear()
a1 = self.verticalSlider_1.value()
a2 = self.verticalSlider_2.value()
a3 = ... | from PyQt5 import QtWidgets, QtCore
from design import design
import numpy as np
import pyqtgraph as pg
class App(QtWidgets.QMainWindow, design.Ui_MainWindow):
| 41 | 91 | 304 | 13 | 27 | Egor-Iudin/fourier | main.py | Python | App | App | 7 | 32 | 7 | 8 | 21f0c7a8a2bb5fde7e3bf8078c57d4ab84013aae | bigcode/the-stack | train |
8cda3504d2dbb0e8356f4efb | train | class | @DATASETS.register_module()
class CustomVideoDataset(Dataset):
"""Custom dataset for out video semantic segmentation. An example of file structure
is as followed.
.. code-block:: none
├── data
│ ├── my_dataset
│ │ ├── img_dir
│ │ │ ├── train
│ │ │ ... | @DATASETS.register_module()
class CustomVideoDataset(Dataset):
| """Custom dataset for out video semantic segmentation. An example of file structure
is as followed.
.. code-block:: none
├── data
│ ├── my_dataset
│ │ ├── img_dir
│ │ │ ├── train
│ │ │ │ ├── xxx{img_suffix}
│ │ │ │ ├── yyy{img_suf... | import os.path as osp
import random
from functools import reduce
import numpy as np
from terminaltables import AsciiTable
from torch.utils.data import Dataset
import mmcv
from mmcv.utils import print_log
from mmseg.core import eval_metrics
from mmseg.utils import get_root_logger
from .builder import DATASETS
from .pi... | 107 | 256 | 4,133 | 13 | 94 | labdeeman7/TRDP_temporal_stability_semantic_segmentation | mmseg/datasets/custom_video.py | Python | CustomVideoDataset | CustomVideoDataset | 18 | 487 | 18 | 19 | 5486a9c6c2672b0746db7101e63e3a3231c25be6 | bigcode/the-stack | train |
8eb2b74e11a05ff1fd1eac2f | train | function | def check_ltl(menv: msat_env, enc: LTLEncoder) -> (Iterable, msat_term,
msat_term, msat_term):
assert menv
assert isinstance(menv, msat_env)
assert enc
assert isinstance(enc, LTLEncoder)
real_type = msat_get_rational_type(menv)
int_type = msat_g... | def check_ltl(menv: msat_env, enc: LTLEncoder) -> (Iterable, msat_term,
msat_term, msat_term):
| assert menv
assert isinstance(menv, msat_env)
assert enc
assert isinstance(enc, LTLEncoder)
real_type = msat_get_rational_type(menv)
int_type = msat_get_integer_type(menv)
bool_type = msat_get_bool_type(menv)
delta, x_delta = decl_consts(menv, delta_name, real_type)
v1, x_v1 = decl_... | _make_geq(menv: msat_env, arg0: msat_term, arg1: msat_term):
return msat_make_leq(menv, arg1, arg0)
def msat_make_gt(menv: msat_env, arg0: msat_term, arg1: msat_term):
leq = msat_make_leq(menv, arg0, arg1)
return msat_make_not(menv, leq)
def msat_make_impl(menv: msat_env, arg0: msat_term, arg1: msat_ter... | 253 | 253 | 846 | 33 | 220 | EnricoMagnago/F3 | benchmarks/ltl_timed_automata/lynch/f3/lynch_protocol_0019.py | Python | check_ltl | check_ltl | 60 | 131 | 60 | 61 | 6f1fd977642472a6dd4698fe07d68618b4053d6e | bigcode/the-stack | train |
0a118b83c4098396796f6fc7 | train | function | def diverging_symbs(menv: msat_env) -> frozenset:
real_type = msat_get_rational_type(menv)
delta = msat_declare_function(menv, delta_name, real_type)
delta = msat_make_constant(menv, delta)
return frozenset([delta])
| def diverging_symbs(menv: msat_env) -> frozenset:
| real_type = msat_get_rational_type(menv)
delta = msat_declare_function(menv, delta_name, real_type)
delta = msat_make_constant(menv, delta)
return frozenset([delta])
| _env, arg0: msat_term, arg1: msat_term):
n_arg0 = msat_make_not(menv, arg0)
return msat_make_or(menv, n_arg0, arg1)
def diverging_symbs(menv: msat_env) -> frozenset:
| 64 | 64 | 67 | 17 | 47 | EnricoMagnago/F3 | benchmarks/ltl_timed_automata/lynch/f3/lynch_protocol_0019.py | Python | diverging_symbs | diverging_symbs | 53 | 57 | 53 | 53 | 52aee152609891824a5119dca9434b688ce1f7d3 | bigcode/the-stack | train |
1800561fcbf6d4cb0770bf77 | train | function | def msat_make_minus(menv: msat_env, arg0: msat_term, arg1: msat_term):
m_one = msat_make_number(menv, "-1")
arg1 = msat_make_times(menv, arg1, m_one)
return msat_make_plus(menv, arg0, arg1)
| def msat_make_minus(menv: msat_env, arg0: msat_term, arg1: msat_term):
| m_one = msat_make_number(menv, "-1")
arg1 = msat_make_times(menv, arg1, m_one)
return msat_make_plus(menv, arg0, arg1)
| _s = msat_declare_function(menv, name_next(name), c_type)
x_s = msat_make_constant(menv, x_s)
return s, x_s
def msat_make_minus(menv: msat_env, arg0: msat_term, arg1: msat_term):
| 64 | 64 | 72 | 26 | 37 | EnricoMagnago/F3 | benchmarks/ltl_timed_automata/lynch/f3/lynch_protocol_0019.py | Python | msat_make_minus | msat_make_minus | 28 | 31 | 28 | 28 | c38225f1e9673b3cae169f25af1413608ccd44e7 | bigcode/the-stack | train |
8bc3cd7d089fd5af3106beae | train | function | def msat_make_gt(menv: msat_env, arg0: msat_term, arg1: msat_term):
leq = msat_make_leq(menv, arg0, arg1)
return msat_make_not(menv, leq)
| def msat_make_gt(menv: msat_env, arg0: msat_term, arg1: msat_term):
| leq = msat_make_leq(menv, arg0, arg1)
return msat_make_not(menv, leq)
| q(menv: msat_env, arg0: msat_term, arg1: msat_term):
return msat_make_leq(menv, arg1, arg0)
def msat_make_gt(menv: msat_env, arg0: msat_term, arg1: msat_term):
| 64 | 64 | 56 | 26 | 38 | EnricoMagnago/F3 | benchmarks/ltl_timed_automata/lynch/f3/lynch_protocol_0019.py | Python | msat_make_gt | msat_make_gt | 43 | 45 | 43 | 43 | 6ebfbc8ba8c3ffb3ba712af6009f476ff9bc91f6 | bigcode/the-stack | train |
1f706b461967f742d328b825 | train | function | def decl_consts(menv: msat_env, name: str, c_type):
assert not name.startswith("_"), name
s = msat_declare_function(menv, name, c_type)
s = msat_make_constant(menv, s)
x_s = msat_declare_function(menv, name_next(name), c_type)
x_s = msat_make_constant(menv, x_s)
return s, x_s
| def decl_consts(menv: msat_env, name: str, c_type):
| assert not name.startswith("_"), name
s = msat_declare_function(menv, name, c_type)
s = msat_make_constant(menv, s)
x_s = msat_declare_function(menv, name_next(name), c_type)
x_s = msat_make_constant(menv, x_s)
return s, x_s
| import msat_make_number, msat_make_plus, msat_make_times
from ltl.ltl import TermMap, LTLEncoder
from utils import name_next
num_procs = 19
delta_name = "delta"
def decl_consts(menv: msat_env, name: str, c_type):
| 64 | 64 | 94 | 17 | 47 | EnricoMagnago/F3 | benchmarks/ltl_timed_automata/lynch/f3/lynch_protocol_0019.py | Python | decl_consts | decl_consts | 19 | 25 | 19 | 19 | 66e15d0e17f1d69d1c89ef9443ffced8e3b6c9aa | bigcode/the-stack | train |
e3cffa2b22929c4756f1f6d9 | train | function | def msat_make_geq(menv: msat_env, arg0: msat_term, arg1: msat_term):
return msat_make_leq(menv, arg1, arg0)
| def msat_make_geq(menv: msat_env, arg0: msat_term, arg1: msat_term):
| return msat_make_leq(menv, arg1, arg0)
| arg1: msat_term):
geq = msat_make_geq(menv, arg0, arg1)
return msat_make_not(menv, geq)
def msat_make_geq(menv: msat_env, arg0: msat_term, arg1: msat_term):
| 64 | 64 | 43 | 27 | 37 | EnricoMagnago/F3 | benchmarks/ltl_timed_automata/lynch/f3/lynch_protocol_0019.py | Python | msat_make_geq | msat_make_geq | 39 | 40 | 39 | 39 | b508b807d803a8843eb678982d7c937a8b671e86 | bigcode/the-stack | train |
baa4c14d1f895b9525accc72 | train | class | class Module:
"""Synchronous component"""
def __init__(self, name: str, menv: msat_env, enc: LTLEncoder,
*args, **kwargs):
self.name = name
self.menv = menv
self.enc = enc
self.symb2next = {}
true = msat_make_true(menv)
self.init = true
se... | class Module:
| """Synchronous component"""
def __init__(self, name: str, menv: msat_env, enc: LTLEncoder,
*args, **kwargs):
self.name = name
self.menv = menv
self.enc = enc
self.symb2next = {}
true = msat_make_true(menv)
self.init = true
self.trans = tru... | utter, p.evt_stutter)
trans = msat_make_and(menv, trans,
msat_make_impl(menv, d_eq_0,
msat_make_not(menv, all_stutter)))
# (G F v1 = 1) -> (G F p0.CS7)
ltl = msat_make_impl(
menv,
enc.make_G(enc.make_F(msat_make_equal(menv, ... | 131 | 131 | 437 | 3 | 127 | EnricoMagnago/F3 | benchmarks/ltl_timed_automata/lynch/f3/lynch_protocol_0019.py | Python | Module | Module | 134 | 176 | 134 | 134 | a509f6a2989ad356ef16e53ba4490ca09d27fa49 | bigcode/the-stack | train |
11719f56d91e35f0c919dc74 | train | class | class P(Module):
"""Process module"""
def __init__(self, name: str, menv: msat_env, enc: LTLEncoder,
pid, v1, x_v1, v2, x_v2, T, delta):
super().__init__(name, menv, enc)
# int_type = msat_get_integer_type(menv)
real_type = msat_get_rational_type(menv)
bool_type... | class P(Module):
| """Process module"""
def __init__(self, name: str, menv: msat_env, enc: LTLEncoder,
pid, v1, x_v1, v2, x_v2, T, delta):
super().__init__(name, menv, enc)
# int_type = msat_get_integer_type(menv)
real_type = msat_get_rational_type(menv)
bool_type = msat_get_bool_... | c_name = "{}{}".format(v_name, idx)
b_vars.append(tuple(self._symb(c_name, bool_type)))
vals = []
x_vals = []
for enum_val in range(enum_size):
bit_val = format(enum_val, '0{}b'.format(num_bits))
assert len(bit_val) == num_bits
assert all(c in {'0... | 256 | 256 | 3,180 | 4 | 251 | EnricoMagnago/F3 | benchmarks/ltl_timed_automata/lynch/f3/lynch_protocol_0019.py | Python | P | P | 179 | 410 | 179 | 179 | a7fb8353e4ac7f6966980487cc8c3974b3f96216 | bigcode/the-stack | train |
8d8cad0e48c2b80f3fa86384 | train | function | def msat_make_impl(menv: msat_env, arg0: msat_term, arg1: msat_term):
n_arg0 = msat_make_not(menv, arg0)
return msat_make_or(menv, n_arg0, arg1)
| def msat_make_impl(menv: msat_env, arg0: msat_term, arg1: msat_term):
| n_arg0 = msat_make_not(menv, arg0)
return msat_make_or(menv, n_arg0, arg1)
| , arg1: msat_term):
leq = msat_make_leq(menv, arg0, arg1)
return msat_make_not(menv, leq)
def msat_make_impl(menv: msat_env, arg0: msat_term, arg1: msat_term):
| 64 | 64 | 57 | 26 | 38 | EnricoMagnago/F3 | benchmarks/ltl_timed_automata/lynch/f3/lynch_protocol_0019.py | Python | msat_make_impl | msat_make_impl | 48 | 50 | 48 | 48 | 6517b33753958b928ace2c9a49a92b8749eb6875 | bigcode/the-stack | train |
9c972403306a028f712f6b55 | train | function | def msat_make_lt(menv: msat_env, arg0: msat_term, arg1: msat_term):
geq = msat_make_geq(menv, arg0, arg1)
return msat_make_not(menv, geq)
| def msat_make_lt(menv: msat_env, arg0: msat_term, arg1: msat_term):
| geq = msat_make_geq(menv, arg0, arg1)
return msat_make_not(menv, geq)
| (menv, "-1")
arg1 = msat_make_times(menv, arg1, m_one)
return msat_make_plus(menv, arg0, arg1)
def msat_make_lt(menv: msat_env, arg0: msat_term, arg1: msat_term):
| 64 | 64 | 56 | 26 | 38 | EnricoMagnago/F3 | benchmarks/ltl_timed_automata/lynch/f3/lynch_protocol_0019.py | Python | msat_make_lt | msat_make_lt | 34 | 36 | 34 | 34 | f682ff02b643620fb47f1bac9d203fab49c9977a | bigcode/the-stack | train |
56e952ba835fe5202a4d8127 | train | class | class CreateFileReport(CreateReport):
filename = None
def __init__(self, filename, *args, **kwargs):
super(CreateFileReport, self).__init__(*args, **kwargs)
self.filename = filename or self.filename
if not self.filename:
raise NotConfigured("You must define a template output... | class CreateFileReport(CreateReport):
| filename = None
def __init__(self, filename, *args, **kwargs):
super(CreateFileReport, self).__init__(*args, **kwargs)
self.filename = filename or self.filename
if not self.filename:
raise NotConfigured("You must define a template output file.")
@classmethod
def fro... | from __future__ import absolute_import
from spidermon.exceptions import NotConfigured
from . import CreateReport
class CreateFileReport(CreateReport):
| 31 | 64 | 159 | 7 | 23 | heylouiz/spidermon | spidermon/contrib/actions/reports/files.py | Python | CreateFileReport | CreateFileReport | 7 | 26 | 7 | 7 | 25b031bafdcb55b948f796791451713fc8ace8d6 | bigcode/the-stack | train |
c136ba040afacc00a40082ae | train | class | class BaseMotorController(MotController):
"""Base motor controller features for all CTRE CAN motor controllers."""
ControlMode = ControlMode
FeedbackDevice = FeedbackDevice
LimitSwitchNormal = LimitSwitchNormal
LimitSwitchSource = LimitSwitchSource
NeutralMode = NeutralMode
ParamEnum = ... | class BaseMotorController(MotController):
| """Base motor controller features for all CTRE CAN motor controllers."""
ControlMode = ControlMode
FeedbackDevice = FeedbackDevice
LimitSwitchNormal = LimitSwitchNormal
LimitSwitchSource = LimitSwitchSource
NeutralMode = NeutralMode
ParamEnum = ParamEnum
RemoteLimitSwitchSource = Re... | FOR A
# PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL
# CROSS THE ROAD ELECTRONICS BE LIABLE FOR ANY INCIDENTAL, SPECIAL,
# INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF
# PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS
# BY THIRD PARTIES (INCLUDING BUT ... | 255 | 256 | 1,816 | 8 | 247 | stmobo/robotpy-ctre | ctre/basemotorcontroller.py | Python | BaseMotorController | BaseMotorController | 48 | 261 | 48 | 48 | 0502939f74c7082c5de991ce7e5a8fd0ec2eabfd | bigcode/the-stack | train |
fc7e70b70845645ab567e8e3 | train | function | def random_colors(N, bright=True):
"""
生成随机RGB颜色
:param N: 颜色数量
:param bright:
:return:
"""
brightness = 1.0 if bright else 0.7
hsv = [(i / N, 1, brightness) for i in range(N)]
colors = list(map(lambda c: colorsys.hsv_to_rgb(*c), hsv))
random.shuffle(colors)
return colors
| def random_colors(N, bright=True):
| """
生成随机RGB颜色
:param N: 颜色数量
:param bright:
:return:
"""
brightness = 1.0 if bright else 0.7
hsv = [(i / N, 1, brightness) for i in range(N)]
colors = list(map(lambda c: colorsys.hsv_to_rgb(*c), hsv))
random.shuffle(colors)
return colors
| utf-8 -*-
"""
Created on 2019/4/14 下午7:55
@author: mick.yi
可视化工具类
"""
import matplotlib.pyplot as plt
from matplotlib import patches
import colorsys
import random
import numpy as np
def random_colors(N, bright=True):
| 64 | 64 | 99 | 8 | 55 | embracesource-cv-com/keras-east | east/utils/visualize.py | Python | random_colors | random_colors | 17 | 28 | 17 | 17 | 2abdbbfed5fd00346897903990e2e75798776dea | bigcode/the-stack | train |
d14ae52dec309ceb3018b135 | train | function | def display_polygons(image, polygons, scores=None, figsize=(16, 16), ax=None, colors=None):
"""
可视化多边形
:param image: [H,W,3]
:param polygons: [n,4,(x,y)]
:param scores:
:param figsize:
:param ax:
:param colors:
:return:
"""
auto_show = False
if ax is None:
_, ax =... | def display_polygons(image, polygons, scores=None, figsize=(16, 16), ax=None, colors=None):
| """
可视化多边形
:param image: [H,W,3]
:param polygons: [n,4,(x,y)]
:param scores:
:param figsize:
:param ax:
:param colors:
:return:
"""
auto_show = False
if ax is None:
_, ax = plt.subplots(1, figsize=figsize)
auto_show = True
if colors is None:
co... | brightness = 1.0 if bright else 0.7
hsv = [(i / N, 1, brightness) for i in range(N)]
colors = list(map(lambda c: colorsys.hsv_to_rgb(*c), hsv))
random.shuffle(colors)
return colors
def display_polygons(image, polygons, scores=None, figsize=(16, 16), ax=None, colors=None):
| 86 | 86 | 287 | 24 | 61 | embracesource-cv-com/keras-east | east/utils/visualize.py | Python | display_polygons | display_polygons | 31 | 64 | 31 | 31 | 9c9fa0d3a7a2f6a0d7f26446847fd5b5b9f3499c | bigcode/the-stack | train |
be5983a8c15c1b60789a4028 | train | class | class ListProtectedInstancesProjectTagsRequest:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
... | class ListProtectedInstancesProjectTagsRequest:
| """
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
openapi_types = {
... | # coding: utf-8
import re
import six
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class ListProtectedInstancesProjectTagsRequest:
| 36 | 134 | 449 | 8 | 27 | huaweicloud/huaweicloud-sdk-python-v3 | huaweicloud-sdk-sdrs/huaweicloudsdksdrs/v1/model/list_protected_instances_project_tags_request.py | Python | ListProtectedInstancesProjectTagsRequest | ListProtectedInstancesProjectTagsRequest | 11 | 85 | 11 | 13 | 54596e9d0b6fbadcf4e37a6c56d1a4a2da11ee9a | bigcode/the-stack | train |
b01ecc8e6977521235bdd1a4 | train | class | class DataCrawler():
def __init__(
self,
db: DataBase
):
self.db = db
self.data = self.load_data()
self.t = 0
def load_data(
self,
) -> None:
"""Load local data set.
"""
upbit_csv = os.path.abspath(os.path.join(
os.pa... | class DataCrawler():
| def __init__(
self,
db: DataBase
):
self.db = db
self.data = self.load_data()
self.t = 0
def load_data(
self,
) -> None:
"""Load local data set.
"""
upbit_csv = os.path.abspath(os.path.join(
os.path.dirname(__file__),... | """
Cinyoung Hur, cinyoung.hur@gmail.com
James Park, laplacian.k@gmail.com
seoulai.com
2018
"""
import pandas as pd
import os
from seoulai_gym.envs.market.database import DataBase
class DataCrawler():
| 59 | 95 | 317 | 4 | 54 | seoulai/laplacian | laplacian/envs/crawler.py | Python | DataCrawler | DataCrawler | 13 | 65 | 13 | 13 | 630f472d4fdef8559fd88f586330f545db595587 | bigcode/the-stack | train |
cfc9495c71cf726f404d41a6 | train | class | class DeviceEndpoint(RestEndpoint):
"""REST end-point for querying and managing devices"""
ENDPOINT_PATH = "/api/devices/{device_id}"
async def get(self, device_id) -> web.Response:
device = self._ledfx.devices.get(device_id)
if device is None:
response = {"not found": 404}
... | class DeviceEndpoint(RestEndpoint):
| """REST end-point for querying and managing devices"""
ENDPOINT_PATH = "/api/devices/{device_id}"
async def get(self, device_id) -> web.Response:
device = self._ledfx.devices.get(device_id)
if device is None:
response = {"not found": 404}
return web.json_response(da... | import logging
from aiohttp import web
from ledfx.api import RestEndpoint
from ledfx.config import save_config
_LOGGER = logging.getLogger(__name__)
class DeviceEndpoint(RestEndpoint):
| 42 | 168 | 563 | 6 | 36 | broccoliboy/LedFx | ledfx/api/device.py | Python | DeviceEndpoint | DeviceEndpoint | 11 | 90 | 11 | 11 | 90431e7445c1315667cb018ab543fa0b1fc8ab11 | bigcode/the-stack | train |
403c5c1c472ac9f495b22469 | train | function | def _get_deleted_expire_index(table):
members = sorted(['deleted', 'expire'])
for idx in table.indexes:
if sorted(idx.columns.keys()) == members:
return idx
| def _get_deleted_expire_index(table):
| members = sorted(['deleted', 'expire'])
for idx in table.indexes:
if sorted(idx.columns.keys()) == members:
return idx
| the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_log import log as logging
from sqlalchemy import Index, MetaData, Table
from nova.i18n import _LI
LOG = logging.getLogger(__name__)
def _get_deleted_expire_index(table):
| 64 | 64 | 41 | 9 | 55 | bopopescu/nova-17 | nova/db/sqlalchemy/migrate_repo/versions/248_add_expire_reservations_index.py | Python | _get_deleted_expire_index | _get_deleted_expire_index | 23 | 27 | 23 | 23 | 238659a588db0aeda2b098fefb4e35896a33ae98 | bigcode/the-stack | train |
194d4b9d459317b7a79068f3 | train | function | def downgrade(migrate_engine):
meta = MetaData()
meta.bind = migrate_engine
reservations = Table('reservations', meta, autoload=True)
index = _get_deleted_expire_index(reservations)
if index:
index.drop(migrate_engine)
else:
LOG.info(_LI('Skipped removing reservations_deleted_e... | def downgrade(migrate_engine):
| meta = MetaData()
meta.bind = migrate_engine
reservations = Table('reservations', meta, autoload=True)
index = _get_deleted_expire_index(reservations)
if index:
index.drop(migrate_engine)
else:
LOG.info(_LI('Skipped removing reservations_deleted_expire_idx '
... | index already exists.'))
return
# Based on expire_reservations query
# from: nova/db/sqlalchemy/api.py
index = Index('reservations_deleted_expire_idx',
reservations.c.deleted, reservations.c.expire)
index.create(migrate_engine)
def downgrade(migrate_engine):
| 64 | 64 | 83 | 6 | 58 | bopopescu/nova-17 | nova/db/sqlalchemy/migrate_repo/versions/248_add_expire_reservations_index.py | Python | downgrade | downgrade | 48 | 59 | 48 | 48 | 3bc89200cf0cdd779270377a01870043094d026e | bigcode/the-stack | train |
b9ef716b3224c4f61e7e4ef9 | train | function | def upgrade(migrate_engine):
meta = MetaData()
meta.bind = migrate_engine
reservations = Table('reservations', meta, autoload=True)
if _get_deleted_expire_index(reservations):
LOG.info(_LI('Skipped adding reservations_deleted_expire_idx '
'because an equivalent index alread... | def upgrade(migrate_engine):
| meta = MetaData()
meta.bind = migrate_engine
reservations = Table('reservations', meta, autoload=True)
if _get_deleted_expire_index(reservations):
LOG.info(_LI('Skipped adding reservations_deleted_expire_idx '
'because an equivalent index already exists.'))
return
... | from nova.i18n import _LI
LOG = logging.getLogger(__name__)
def _get_deleted_expire_index(table):
members = sorted(['deleted', 'expire'])
for idx in table.indexes:
if sorted(idx.columns.keys()) == members:
return idx
def upgrade(migrate_engine):
| 64 | 64 | 122 | 6 | 57 | bopopescu/nova-17 | nova/db/sqlalchemy/migrate_repo/versions/248_add_expire_reservations_index.py | Python | upgrade | upgrade | 30 | 45 | 30 | 30 | ef3f7a7d37c9131c8ea6764cd06f83f255ae9731 | bigcode/the-stack | train |
3507876818968199abd8ae8e | train | function | def batch_run_sample(bam_fname, target_bed, antitarget_bed, ref_fname,
output_dir, male_reference, plot_scatter, plot_diagram,
rscript_path, by_count, skip_low, seq_method,
segment_method, processes, do_cluster):
"""Run the pipeline on one BAM file."""
... | def batch_run_sample(bam_fname, target_bed, antitarget_bed, ref_fname,
output_dir, male_reference, plot_scatter, plot_diagram,
rscript_path, by_count, skip_low, seq_method,
segment_method, processes, do_cluster):
| """Run the pipeline on one BAM file."""
# ENH - return probes, segments (cnarr, segarr)
logging.info("Running the CNVkit pipeline on %s ...", bam_fname)
sample_id = core.fbase(bam_fname)
sample_pfx = os.path.join(output_dir, sample_id)
raw_tgt = coverage.do_coverage(target_bed, bam_fname, by_co... | , antitarget_fnames,
fasta, male_reference, None,
do_gc=True,
do_edge=(method == "hybrid"),
do_rmask=True,
do_clust... | 226 | 226 | 756 | 59 | 166 | sridhar0605/cnvkit | cnvlib/batch.py | Python | batch_run_sample | batch_run_sample | 162 | 225 | 162 | 165 | 6088257c5747861cd7c003efb2da6a46787a0344 | bigcode/the-stack | train |
f8ed58d2ca10b26b8c94287c | train | function | def batch_write_coverage(bed_fname, bam_fname, out_fname, by_count, processes):
"""Run coverage on one sample, write to file."""
cnarr = coverage.do_coverage(bed_fname, bam_fname, by_count, 0, processes)
tabio.write(cnarr, out_fname)
return out_fname
| def batch_write_coverage(bed_fname, bam_fname, out_fname, by_count, processes):
| """Run coverage on one sample, write to file."""
cnarr = coverage.do_coverage(bed_fname, bam_fname, by_count, 0, processes)
tabio.write(cnarr, out_fname)
return out_fname
| = os.path.join(output_dir, "reference.cnn")
core.ensure_path(output_reference)
tabio.write(ref_arr, output_reference)
return output_reference, target_bed, antitarget_bed
def batch_write_coverage(bed_fname, bam_fname, out_fname, by_count, processes):
| 64 | 64 | 71 | 20 | 43 | sridhar0605/cnvkit | cnvlib/batch.py | Python | batch_write_coverage | batch_write_coverage | 155 | 159 | 155 | 155 | 73cb2d90de5265311c6ae1826fa039c418525704 | bigcode/the-stack | train |
34bba4595eaf302cded8597f | train | function | def batch_make_reference(normal_bams, target_bed, antitarget_bed,
male_reference, fasta, annotate, short_names,
target_avg_size, access_bed, antitarget_avg_size,
antitarget_min_size, output_reference, output_dir,
process... | def batch_make_reference(normal_bams, target_bed, antitarget_bed,
male_reference, fasta, annotate, short_names,
target_avg_size, access_bed, antitarget_avg_size,
antitarget_min_size, output_reference, output_dir,
process... | """Build the CN reference from normal samples, targets and antitargets."""
if method in ("wgs", "amplicon"):
if antitarget_bed:
raise ValueError("%r protocol: antitargets should not be "
"given/specified." % method)
if access_bed and target_bed and access... | """The 'batch' command."""
import logging
import os
from matplotlib import pyplot
from skgenome import tabio, GenomicArray as GA
from . import (access, antitarget, autobin, bintest, call, core, coverage,
diagram, fix, parallel, reference, scatter, segmentation,
segmetrics, target)
from .... | 151 | 256 | 1,416 | 68 | 82 | sridhar0605/cnvkit | cnvlib/batch.py | Python | batch_make_reference | batch_make_reference | 14 | 152 | 14 | 18 | 15751e76934dadbba9703e6946c3421e95b5d3db | bigcode/the-stack | train |
1b4803af67cd437c53da2b67 | train | function | def find_current_file(db):
#todo find "last file"
return "data/" + db + ".db"
| def find_current_file(db):
#todo find "last file"
| return "data/" + db + ".db"
| import sys
import os
def get_file_size_limit_bytes():
return 100
def find_current_file(db):
#todo find "last file"
| 32 | 64 | 25 | 14 | 17 | deniskovalenko/python-storage-engine | write.py | Python | find_current_file | find_current_file | 7 | 9 | 7 | 8 | a9240a296255860afddc9ed850c09be4794398f7 | bigcode/the-stack | train |
2ba3f68163f5634f53692ffd | train | function | def get_file_size_limit_bytes():
return 100
| def get_file_size_limit_bytes():
| return 100
| import sys
import os
def get_file_size_limit_bytes():
| 13 | 64 | 12 | 7 | 5 | deniskovalenko/python-storage-engine | write.py | Python | get_file_size_limit_bytes | get_file_size_limit_bytes | 4 | 5 | 4 | 4 | 3d6b243c098c94e590b7d8b68a38c3015ae1dc41 | bigcode/the-stack | train |
1633aaa52159ab7548ed58f9 | train | function | def main():
db = sys.argv[1]
key = sys.argv[2]
value = sys.argv[3]
current_file = find_current_file(db)
write_to_file(current_file, key, value)
current_file_size = os.path.getsize(current_file)
if current_file_size > get_file_size_limit_bytes():
#todo create another file, mark ... | def main():
| db = sys.argv[1]
key = sys.argv[2]
value = sys.argv[3]
current_file = find_current_file(db)
write_to_file(current_file, key, value)
current_file_size = os.path.getsize(current_file)
if current_file_size > get_file_size_limit_bytes():
#todo create another file, mark current file... | os.path.exists(directory):
os.makedirs(directory)
try:
os.makedirs(directory)
except FileExistsError:
# directory already exists
pass
file = open(file_path, "a+")
file.write(key + "," + value + "\n")
file.close()
def main():
| 63 | 64 | 97 | 3 | 60 | deniskovalenko/python-storage-engine | write.py | Python | main | main | 25 | 36 | 25 | 25 | 09a213b3feb720062f3fbc73fddce381833a1d37 | bigcode/the-stack | train |
bd5bd3f43c8cc0e16ce0facb | train | function | def write_to_file(file_path, key, value):
directory = os.path.dirname(file_path)
if not os.path.exists(directory):
os.makedirs(directory)
try:
os.makedirs(directory)
except FileExistsError:
# directory already exists
pass
file = open(file_path, "a+")
file.write(ke... | def write_to_file(file_path, key, value):
| directory = os.path.dirname(file_path)
if not os.path.exists(directory):
os.makedirs(directory)
try:
os.makedirs(directory)
except FileExistsError:
# directory already exists
pass
file = open(file_path, "a+")
file.write(key + "," + value + "\n")
file.close()
| import sys
import os
def get_file_size_limit_bytes():
return 100
def find_current_file(db):
#todo find "last file"
return "data/" + db + ".db"
def write_to_file(file_path, key, value):
| 54 | 64 | 83 | 11 | 43 | deniskovalenko/python-storage-engine | write.py | Python | write_to_file | write_to_file | 11 | 22 | 11 | 11 | 3f854639be4eab85e789d48e339247b856578c12 | bigcode/the-stack | train |
4f11449035eb1182cf398788 | train | function | def handle(socket):
global clients
client = Client(socket)
clients.append(client)
| def handle(socket):
| global clients
client = Client(socket)
clients.append(client)
| extend(v, l):
out = str(v)
while len(out) < l:
out = "0" + out
return out
# This handles a new client.
# We need to hand them to an object
# so that we can read and write from it
def handle(socket):
| 64 | 64 | 19 | 4 | 59 | ChrisFadden/PartyTowers | webrouter.py | Python | handle | handle | 148 | 151 | 148 | 148 | 6b11c33694ca4f6e8511be6dfcd2046d1386614f | bigcode/the-stack | train |
84312fe0b236ee0a5ca4a119 | train | function | def extend(v, l):
out = str(v)
while len(out) < l:
out = "0" + out
return out
| def extend(v, l):
| out = str(v)
while len(out) < l:
out = "0" + out
return out
| Code == code:
return host
return None
def newHostCode():
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
code = ''.join(chars[int(random.random()*26)] for _ in range(4))
if findHost(code):
return newHostCode()
return code
def extend(v, l):
| 64 | 64 | 33 | 6 | 57 | ChrisFadden/PartyTowers | webrouter.py | Python | extend | extend | 139 | 143 | 139 | 139 | 38203f870d1a7ceecf06dcdc37eae2b6b2077b61 | bigcode/the-stack | train |
2c8c95d96a8b5e57092fe03e | train | class | class Host:
def __init__(self, socket, hostCode):
self.socket = socket
self.hostCode = hostCode
self.players = {}
self.pID = 0
self.socket.send("999" + str(self.hostCode))
self.writingTo = 0
self.data = ""
def getNextpID(self):
self.pID += ... | class Host:
| def __init__(self, socket, hostCode):
self.socket = socket
self.hostCode = hostCode
self.players = {}
self.pID = 0
self.socket.send("999" + str(self.hostCode))
self.writingTo = 0
self.data = ""
def getNextpID(self):
self.pID += 1
return ... | self
self.needsConfirmation = False
self.sID = extend(self.pID, 2)
self.socket.send("999" + self.sID)
self.host.socket.send("998" + self.sID)
def becomeHost(self):
host = Host(self.socket, newHostCode())
clients.remove(self)
hosts.append(host)
def disco... | 104 | 104 | 347 | 4 | 99 | ChrisFadden/PartyTowers | webrouter.py | Python | Host | Host | 71 | 124 | 71 | 72 | dff4a0b22054841f76392e7cb0138b062841c93c | bigcode/the-stack | train |
f54a68b0df5ccb347d9f55bc | train | function | def newHostCode():
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
code = ''.join(chars[int(random.random()*26)] for _ in range(4))
if findHost(code):
return newHostCode()
return code
| def newHostCode():
| chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
code = ''.join(chars[int(random.random()*26)] for _ in range(4))
if findHost(code):
return newHostCode()
return code
| .writingTo = 0
def disconnect(self):
print("Lost host.")
hosts.remove(self)
self.socket = None
return
def findHost(code):
for host in hosts:
if host.hostCode == code:
return host
return None
def newHostCode():
| 64 | 64 | 46 | 5 | 58 | ChrisFadden/PartyTowers | webrouter.py | Python | newHostCode | newHostCode | 132 | 137 | 132 | 132 | aa88a2188a6204c952070715ce02143024f198f4 | bigcode/the-stack | train |
ec08b40d36850ad830b609a5 | train | function | def setupMessages():
return
| def setupMessages():
| return
| # This file runs the websockets.
import string, cgi, time
import sys
sys.path.insert(0, 'PyWebPlug')
from wsserver import *
from time import sleep
def setupMessages():
| 44 | 64 | 7 | 4 | 39 | ChrisFadden/PartyTowers | webrouter.py | Python | setupMessages | setupMessages | 10 | 11 | 10 | 10 | 244f61f25b4c159cffb2ef14eb218fa55ebc14d8 | bigcode/the-stack | train |
3108bb674eba9a183c6ba3e7 | train | class | class Client:
def __init__(self, socket):
self.socket = socket
self.needsConfirmation = True
def handle(self):
if (self.socket):
try:
data = self.socket.readRaw()
except:
self.socket = None
if len(data) == 0:
... | class Client:
| def __init__(self, socket):
self.socket = socket
self.needsConfirmation = True
def handle(self):
if (self.socket):
try:
data = self.socket.readRaw()
except:
self.socket = None
if len(data) == 0:
return
... | # This file runs the websockets.
import string, cgi, time
import sys
sys.path.insert(0, 'PyWebPlug')
from wsserver import *
from time import sleep
def setupMessages():
return
class Client:
| 50 | 104 | 349 | 3 | 46 | ChrisFadden/PartyTowers | webrouter.py | Python | Client | Client | 14 | 69 | 14 | 15 | ea9b365acdf27ca535ddb72ae5e47900eb6e51e4 | bigcode/the-stack | train |
47a268b193205ff0e17981e4 | train | function | def main():
global gameStarted
global stage
try:
setupMessages()
server = startServer()
while True:
newClient = handleNetwork()
if newClient:
handle(newClient)
for client in clients:
client.handle()
for h... | def main():
| global gameStarted
global stage
try:
setupMessages()
server = startServer()
while True:
newClient = handleNetwork()
if newClient:
handle(newClient)
for client in clients:
client.handle()
for host in hosts... | :
out = "0" + out
return out
# This handles a new client.
# We need to hand them to an object
# so that we can read and write from it
def handle(socket):
global clients
client = Client(socket)
clients.append(client)
def main():
| 64 | 64 | 90 | 3 | 61 | ChrisFadden/PartyTowers | webrouter.py | Python | main | main | 153 | 170 | 153 | 153 | 7d4149dcc9849de7de978c11a4835b3d73c65aaa | bigcode/the-stack | train |
53d3d5c90ce5bc29dc9b4e7f | train | function | def findHost(code):
for host in hosts:
if host.hostCode == code:
return host
return None
| def findHost(code):
| for host in hosts:
if host.hostCode == code:
return host
return None
| tried to send a messaged to non-existant player", pID)
self.data = self.data[ind+2:]
self.writingTo = 0
def disconnect(self):
print("Lost host.")
hosts.remove(self)
self.socket = None
return
def findHost(code):
| 64 | 64 | 27 | 5 | 58 | ChrisFadden/PartyTowers | webrouter.py | Python | findHost | findHost | 126 | 130 | 126 | 126 | bbb66d6cd86862d62dc109d478ea456ea9e305aa | bigcode/the-stack | train |
ba18825a97618d2891263738 | train | function | def normal_gen_code():
numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
code = sample(numbers, 20)
return ''.join(code)
| def normal_gen_code():
| numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
code = sample(numbers, 20)
return ''.join(code)
| import qrcode
from PIL import Image
from random import sample
import os
def normal_gen_code():
| 22 | 64 | 84 | 5 | 16 | nawafalqari/LinksBase | tests/qrcode_test.py | Python | normal_gen_code | normal_gen_code | 6 | 10 | 6 | 6 | ca12c5ed97ce9a3d6471dc88cef725fae4deecbb | bigcode/the-stack | train |
aac44eb5857f5a5a3a41562e | train | function | def has_digit(text):
return digit_re.match(text)
| def has_digit(text):
| return digit_re.match(text)
| import re
from dataPipelines.gc_scrapy.gc_scrapy.items import DocItem
from dataPipelines.gc_scrapy.gc_scrapy.GCSpider import GCSpider
digit_re = re.compile('\d')
def has_digit(text):
| 48 | 64 | 12 | 5 | 43 | dod-advana/gamechanger-crawlers | dataPipelines/gc_scrapy/gc_scrapy/spiders/milpersman_spider.py | Python | has_digit | has_digit | 9 | 10 | 9 | 9 | 726a87a239330bbf6e829318d117a76684b84b65 | bigcode/the-stack | train |
6a47a5b1dbb6fb80e1a76314 | train | class | class MilpersmanSpider(GCSpider):
name = 'milpersman_crawler'
start_urls = ['https://www.mynavyhr.navy.mil/References/MILPERSMAN/']
doc_type = "MILPERSMAN"
cac_login_required = False
def parse(self, response):
anchors = [
a for a in
response.css('li[title="MILPERSM... | class MilpersmanSpider(GCSpider):
| name = 'milpersman_crawler'
start_urls = ['https://www.mynavyhr.navy.mil/References/MILPERSMAN/']
doc_type = "MILPERSMAN"
cac_login_required = False
def parse(self, response):
anchors = [
a for a in
response.css('li[title="MILPERSMAN"] ul li a') if has_digit(a.css(... | import re
from dataPipelines.gc_scrapy.gc_scrapy.items import DocItem
from dataPipelines.gc_scrapy.gc_scrapy.GCSpider import GCSpider
digit_re = re.compile('\d')
def has_digit(text):
return digit_re.match(text)
class MilpersmanSpider(GCSpider):
| 64 | 215 | 719 | 9 | 55 | dod-advana/gamechanger-crawlers | dataPipelines/gc_scrapy/gc_scrapy/spiders/milpersman_spider.py | Python | MilpersmanSpider | MilpersmanSpider | 13 | 109 | 13 | 13 | 09d0c5759b1d357397d7928e53badf71dcecbea4 | bigcode/the-stack | train |
e97d3bb0b1666f135887f7e3 | train | function | def hex_switchEndian(s):
""" Switches the endianness of a hex string (in pairs of hex chars) """
pairList = [s[i:i+2].encode() for i in range(0, len(s), 2)]
return b''.join(pairList[::-1]).decode()
| def hex_switchEndian(s):
| """ Switches the endianness of a hex string (in pairs of hex chars) """
pairList = [s[i:i+2].encode() for i in range(0, len(s), 2)]
return b''.join(pairList[::-1]).decode()
| : # Python 3
import http.client as httplib
except ImportError: # Python 2
import httplib
import json
import re
import base64
import sys
import os
import os.path
settings = {}
##### Switch endian-ness #####
def hex_switchEndian(s):
| 64 | 64 | 63 | 6 | 57 | HuntCoinDeveloper/huntcoin | contrib/linearize/linearize-hashes.py | Python | hex_switchEndian | hex_switchEndian | 25 | 28 | 25 | 25 | 06fe94ecea69d999173eeac03747f220d716a545 | bigcode/the-stack | train |
68a2bd802bea03728cd6e6fb | train | function | def get_block_hashes(settings, max_blocks_per_call=10000):
rpc = HuntcoinRPC(settings['host'], settings['port'],
settings['rpcuser'], settings['rpcpassword'])
height = settings['min_height']
while height < settings['max_height']+1:
num_blocks = min(settings['max_height']+1-height, max_blocks_per_call)
batch... | def get_block_hashes(settings, max_blocks_per_call=10000):
| rpc = HuntcoinRPC(settings['host'], settings['port'],
settings['rpcuser'], settings['rpcpassword'])
height = settings['min_height']
while height < settings['max_height']+1:
num_blocks = min(settings['max_height']+1-height, max_blocks_per_call)
batch = []
for x in range(num_blocks):
batch.append(rpc.bui... | }
if params is None:
obj['params'] = []
else:
obj['params'] = params
return obj
@staticmethod
def response_is_error(resp_obj):
return 'error' in resp_obj and resp_obj['error'] is not None
def get_block_hashes(settings, max_blocks_per_call=10000):
| 73 | 73 | 245 | 15 | 57 | HuntCoinDeveloper/huntcoin | contrib/linearize/linearize-hashes.py | Python | get_block_hashes | get_block_hashes | 71 | 96 | 71 | 71 | ef6b3095b82525d1482c33df818f5c448137b590 | bigcode/the-stack | train |
d6296d27ccb406f7144abbd8 | train | function | def get_rpc_cookie():
# Open the cookie file
with open(os.path.join(os.path.expanduser(settings['datadir']), '.cookie'), 'r') as f:
combined = f.readline()
combined_split = combined.split(":")
settings['rpcuser'] = combined_split[0]
settings['rpcpassword'] = combined_split[1]
| def get_rpc_cookie():
# Open the cookie file
| with open(os.path.join(os.path.expanduser(settings['datadir']), '.cookie'), 'r') as f:
combined = f.readline()
combined_split = combined.split(":")
settings['rpcuser'] = combined_split[0]
settings['rpcpassword'] = combined_split[1]
| '] == x) # assume replies are in-sequence
if settings['rev_hash_bytes'] == 'true':
resp_obj['result'] = hex_switchEndian(resp_obj['result'])
print(resp_obj['result'])
height += num_blocks
def get_rpc_cookie():
# Open the cookie file
| 64 | 64 | 75 | 12 | 51 | HuntCoinDeveloper/huntcoin | contrib/linearize/linearize-hashes.py | Python | get_rpc_cookie | get_rpc_cookie | 98 | 104 | 98 | 99 | ad9132d7f62544549eafea59007b20b99958fa19 | bigcode/the-stack | train |
594871dcf9e6d99483cbf076 | train | class | class HuntcoinRPC:
def __init__(self, host, port, username, password):
authpair = "%s:%s" % (username, password)
authpair = authpair.encode('utf-8')
self.authhdr = b"Basic " + base64.b64encode(authpair)
self.conn = httplib.HTTPConnection(host, port=port, timeout=30)
def execute(self, obj):
try:
self.con... | class HuntcoinRPC:
| def __init__(self, host, port, username, password):
authpair = "%s:%s" % (username, password)
authpair = authpair.encode('utf-8')
self.authhdr = b"Basic " + base64.b64encode(authpair)
self.conn = httplib.HTTPConnection(host, port=port, timeout=30)
def execute(self, obj):
try:
self.conn.request('POST', '... |
import base64
import sys
import os
import os.path
settings = {}
##### Switch endian-ness #####
def hex_switchEndian(s):
""" Switches the endianness of a hex string (in pairs of hex chars) """
pairList = [s[i:i+2].encode() for i in range(0, len(s), 2)]
return b''.join(pairList[::-1]).decode()
class HuntcoinRPC:
| 93 | 93 | 311 | 5 | 88 | HuntCoinDeveloper/huntcoin | contrib/linearize/linearize-hashes.py | Python | HuntcoinRPC | HuntcoinRPC | 30 | 69 | 30 | 30 | 489618077e9f8a3bf63f9f1779a53482d34e4b20 | bigcode/the-stack | train |
ddfef98e6848ef3a70b13314 | train | class | class WikiTableService:
def get_table_column_numbers(self, table: wtp.Table) -> int:
"""
Returns the number of columns in a table
Keyword arguments:
table -- The table which the number of columns is
being searched
Returns:
table_column_numbers -- Th... | class WikiTableService:
| def get_table_column_numbers(self, table: wtp.Table) -> int:
"""
Returns the number of columns in a table
Keyword arguments:
table -- The table which the number of columns is
being searched
Returns:
table_column_numbers -- The number of columns in t... | import re
import wikitextparser as wtp
from server.services.wiki.wiki_section_service import WikiSectionService
class WikiTableService:
| 31 | 256 | 1,316 | 5 | 25 | hotosm/oeg-reporter | server/services/wiki/wiki_table_service.py | Python | WikiTableService | WikiTableService | 8 | 185 | 8 | 8 | 65247520425f7c9efb7f82f216dd895504c6afb2 | bigcode/the-stack | train |
da4bb56389e41b5f71093785 | train | class | class FloatRange(_NumberRangeBase, FloatParamType):
"""Restrict a :data:`click.FLOAT` value to a range of accepted
values. See :ref:`ranges`.
If ``min`` or ``max`` are not passed, any value is accepted in that
direction. If ``min_open`` or ``max_open`` are enabled, the
corresponding boundary is not... | class FloatRange(_NumberRangeBase, FloatParamType):
| """Restrict a :data:`click.FLOAT` value to a range of accepted
values. See :ref:`ranges`.
If ``min`` or ``max`` are not passed, any value is accepted in that
direction. If ``min_open`` or ``max_open`` are enabled, the
corresponding boundary is not included in the range.
If ``clamp`` is enabled... | Added the ``min_open`` and ``max_open`` parameters.
"""
name = "integer range"
def _clamp(self, bound, dir, open):
if not open:
return bound
return bound + dir
class FloatParamType(_NumberParamTypeBase):
name = "float"
_number_class = float
def __repr__(self):
... | 97 | 97 | 326 | 12 | 85 | click-contrib/asyncclick | src/click/types.py | Python | FloatRange | FloatRange | 468 | 501 | 468 | 468 | f840fafd28cd90225ee00a187da571cb1e8ae2bd | bigcode/the-stack | train |
c861ace22a5bae39a603be8e | train | class | class Choice(ParamType):
"""The choice type allows a value to be checked against a fixed set
of supported values. All of these values have to be strings.
You should only pass a list or tuple of choices. Other iterables
(like generators) may lead to surprising results.
The resulting value will alwa... | class Choice(ParamType):
| """The choice type allows a value to be checked against a fixed set
of supported values. All of these values have to be strings.
You should only pass a list or tuple of choices. Other iterables
(like generators) may lead to surprising results.
The resulting value will always be one of the original... | except ValueError:
try:
value = str(value)
except UnicodeError:
value = value.decode("utf-8", "replace")
self.fail(value, param, ctx)
class UnprocessedParamType(ParamType):
name = "text"
def convert(self, value, param, ctx):
return... | 229 | 229 | 766 | 6 | 223 | click-contrib/asyncclick | src/click/types.py | Python | Choice | Choice | 190 | 284 | 190 | 190 | bfa34967277b7346ecbc72a4f637e03e17251819 | bigcode/the-stack | train |
f6f2b9828a9c3c0ad4e560bc | train | class | class FloatParamType(_NumberParamTypeBase):
name = "float"
_number_class = float
def __repr__(self):
return "FLOAT"
| class FloatParamType(_NumberParamTypeBase):
| name = "float"
_number_class = float
def __repr__(self):
return "FLOAT"
| .0
Added the ``min_open`` and ``max_open`` parameters.
"""
name = "integer range"
def _clamp(self, bound, dir, open):
if not open:
return bound
return bound + dir
class FloatParamType(_NumberParamTypeBase):
| 64 | 64 | 35 | 10 | 53 | click-contrib/asyncclick | src/click/types.py | Python | FloatParamType | FloatParamType | 460 | 465 | 460 | 460 | 82bd09b3142ddf7fa33f0908dfe0099892e82122 | bigcode/the-stack | train |
f6a8bcdd3da57da72c2c1d88 | train | class | class Tuple(CompositeParamType):
"""The default behavior of Click is to apply a type on a value directly.
This works well in most cases, except for when `nargs` is set to a fixed
count and different types should be used for different items. In this
case the :class:`Tuple` type can be used. This type c... | class Tuple(CompositeParamType):
| """The default behavior of Click is to apply a type on a value directly.
This works well in most cases, except for when `nargs` is set to a fixed
count and different types should be used for different items. In this
case the :class:`Tuple` type can be used. This type can only be used
if `nargs` is... | Invocation context for this command.
:param param: The parameter that is requesting completion.
:param incomplete: Value being completed. May be empty.
.. versionadded:: 8.0
"""
from asyncclick.shell_completion import CompletionItem
type = "dir" if self.dir_okay and no... | 95 | 96 | 322 | 7 | 88 | click-contrib/asyncclick | src/click/types.py | Python | Tuple | Tuple | 792 | 828 | 792 | 792 | a494615f995133e3cd506025f07c8591191d7325 | bigcode/the-stack | train |
aa9c1c5b111668b6b3e4cc15 | train | class | class UUIDParameterType(ParamType):
name = "uuid"
def convert(self, value, param, ctx):
import uuid
if isinstance(value, uuid.UUID):
return value
value = value.strip()
try:
return uuid.UUID(value)
except ValueError:
self.fail(f"{val... | class UUIDParameterType(ParamType):
| name = "uuid"
def convert(self, value, param, ctx):
import uuid
if isinstance(value, uuid.UUID):
return value
value = value.strip()
try:
return uuid.UUID(value)
except ValueError:
self.fail(f"{value!r} is not a valid UUID.", param, ... | norm in {"0", "false", "f", "no", "n", "off"}:
return False
self.fail(f"{value!r} is not a valid boolean.", param, ctx)
def __repr__(self):
return "BOOL"
class UUIDParameterType(ParamType):
| 64 | 64 | 92 | 8 | 56 | click-contrib/asyncclick | src/click/types.py | Python | UUIDParameterType | UUIDParameterType | 525 | 542 | 525 | 525 | 35092b7a2e9978ffd1a80714e95fe5285b880207 | bigcode/the-stack | train |
db78d05f94f817371b4eb37d | train | class | class DateTime(ParamType):
"""The DateTime type converts date strings into `datetime` objects.
The format strings which are checked are configurable, but default to some
common (non-timezone aware) ISO 8601 formats.
When specifying *DateTime* formats, you should only pass a list or a tuple.
Other ... | class DateTime(ParamType):
| """The DateTime type converts date strings into `datetime` objects.
The format strings which are checked are configurable, but default to some
common (non-timezone aware) ISO 8601 formats.
When specifying *DateTime* formats, you should only pass a list or a tuple.
Other iterables, like generators,... | that start with the incomplete value.
:param ctx: Invocation context for this command.
:param param: The parameter that is requesting completion.
:param incomplete: Value being completed. May be empty.
.. versionadded:: 8.0
"""
from asyncclick.shell_completion import C... | 146 | 146 | 489 | 7 | 139 | click-contrib/asyncclick | src/click/types.py | Python | DateTime | DateTime | 287 | 344 | 287 | 287 | f0ace4dffa166134460a426fe3b5ec201427cf89 | bigcode/the-stack | train |
91654ff0f25622a941357985 | train | class | class CompositeParamType(ParamType):
is_composite = True
@property
def arity(self):
raise NotImplementedError()
| class CompositeParamType(ParamType):
| is_composite = True
@property
def arity(self):
raise NotImplementedError()
| ions as well.
:param ctx: Invocation context for this command.
:param param: The parameter that is requesting completion.
:param incomplete: Value being completed. May be empty.
.. versionadded:: 8.0
"""
return []
class CompositeParamType(ParamType):
| 63 | 64 | 31 | 8 | 55 | click-contrib/asyncclick | src/click/types.py | Python | CompositeParamType | CompositeParamType | 126 | 131 | 126 | 126 | 0623922da3f36c3375cf1ef46bc6008f72e9e3a1 | bigcode/the-stack | train |
bbce9e1f752ad76ce02b421b | train | class | class BoolParamType(ParamType):
name = "boolean"
def convert(self, value, param, ctx):
if value in {False, True}:
return bool(value)
norm = value.strip().lower()
if norm in {"1", "true", "t", "yes", "y", "on"}:
return True
if norm in {"0", "false", "f"... | class BoolParamType(ParamType):
| name = "boolean"
def convert(self, value, param, ctx):
if value in {False, True}:
return bool(value)
norm = value.strip().lower()
if norm in {"1", "true", "t", "yes", "y", "on"}:
return True
if norm in {"0", "false", "f", "no", "n", "off"}:
... | math.nextafter here, but clamping an
# open float range doesn't seem to be particularly useful. It's
# left up to the user to write a callback to do it if needed.
raise RuntimeError("Clamping is not supported for open bounds.")
class BoolParamType(ParamType):
| 63 | 64 | 133 | 8 | 55 | click-contrib/asyncclick | src/click/types.py | Python | BoolParamType | BoolParamType | 504 | 522 | 504 | 504 | d066d291b2c1ba1dd9c63e3d3006ca9817d288f3 | bigcode/the-stack | train |
df4407c1dc3ffbf3ba134e76 | train | class | class _NumberParamTypeBase(ParamType):
_number_class = None
def convert(self, value, param, ctx):
try:
return self._number_class(value)
except ValueError:
self.fail(f"{value!r} is not a valid {self.name}.", param, ctx)
| class _NumberParamTypeBase(ParamType):
| _number_class = None
def convert(self, value, param, ctx):
try:
return self._number_class(value)
except ValueError:
self.fail(f"{value!r} is not a valid {self.name}.", param, ctx)
| (repr(f) for f in self.formats)
self.fail(
f"{value!r} does not match the format{plural} {formats_str}.", param, ctx
)
def __repr__(self):
return "DateTime"
class _NumberParamTypeBase(ParamType):
| 64 | 64 | 66 | 10 | 54 | click-contrib/asyncclick | src/click/types.py | Python | _NumberParamTypeBase | _NumberParamTypeBase | 347 | 354 | 347 | 347 | db2ea2bc33b90af6247963f58d15fa9b508c4e14 | bigcode/the-stack | train |
8cd96fe00abab21ff2825521 | train | class | class FuncParamType(ParamType):
def __init__(self, func):
self.name = func.__name__
self.func = func
async def to_info_dict(self):
info_dict = await super().to_info_dict()
info_dict["func"] = self.func
return info_dict
def convert(self, value, param, ctx):
t... | class FuncParamType(ParamType):
| def __init__(self, func):
self.name = func.__name__
self.func = func
async def to_info_dict(self):
info_dict = await super().to_info_dict()
info_dict["func"] = self.func
return info_dict
def convert(self, value, param, ctx):
try:
return self.func... | : Value being completed. May be empty.
.. versionadded:: 8.0
"""
return []
class CompositeParamType(ParamType):
is_composite = True
@property
def arity(self):
raise NotImplementedError()
class FuncParamType(ParamType):
| 64 | 64 | 126 | 8 | 56 | click-contrib/asyncclick | src/click/types.py | Python | FuncParamType | FuncParamType | 134 | 153 | 134 | 134 | b1f4d520743c45b3ef22b5922b051a50df2c0711 | bigcode/the-stack | train |
bb268d6869b764f01225b99a | train | class | class IntParamType(_NumberParamTypeBase):
name = "integer"
_number_class = int
def __repr__(self):
return "INT"
| class IntParamType(_NumberParamTypeBase):
| name = "integer"
_number_class = int
def __repr__(self):
return "INT"
| .min}{lop}x{rop}{self.max}"
def __repr__(self):
clamp = " clamped" if self.clamp else ""
return f"<{type(self).__name__} {self._describe_range()}{clamp}>"
class IntParamType(_NumberParamTypeBase):
| 63 | 64 | 35 | 10 | 53 | click-contrib/asyncclick | src/click/types.py | Python | IntParamType | IntParamType | 428 | 433 | 428 | 428 | a1d73391c78d5ae2be6db53ddbf3b8dd471f2fe1 | bigcode/the-stack | train |
833068d1fa6a8f69aadb5130 | train | class | class StringParamType(ParamType):
name = "text"
def convert(self, value, param, ctx):
if isinstance(value, bytes):
enc = _get_argv_encoding()
try:
value = value.decode(enc)
except UnicodeError:
fs_enc = get_filesystem_encoding()
... | class StringParamType(ParamType):
| name = "text"
def convert(self, value, param, ctx):
if isinstance(value, bytes):
enc = _get_argv_encoding()
try:
value = value.decode(enc)
except UnicodeError:
fs_enc = get_filesystem_encoding()
if fs_enc != enc:
... | replace")
self.fail(value, param, ctx)
class UnprocessedParamType(ParamType):
name = "text"
def convert(self, value, param, ctx):
return value
def __repr__(self):
return "UNPROCESSED"
class StringParamType(ParamType):
| 64 | 64 | 138 | 8 | 56 | click-contrib/asyncclick | src/click/types.py | Python | StringParamType | StringParamType | 166 | 187 | 166 | 166 | 8322064d849caa8928dbfbcd1bb6f21464770e27 | bigcode/the-stack | train |
e32d8ea663178187c4811210 | train | class | class IntRange(_NumberRangeBase, IntParamType):
"""Restrict an :data:`click.INT` value to a range of accepted
values. See :ref:`ranges`.
If ``min`` or ``max`` are not passed, any value is accepted in that
direction. If ``min_open`` or ``max_open`` are enabled, the
corresponding boundary is not incl... | class IntRange(_NumberRangeBase, IntParamType):
| """Restrict an :data:`click.INT` value to a range of accepted
values. See :ref:`ranges`.
If ``min`` or ``max`` are not passed, any value is accepted in that
direction. If ``min_open`` or ``max_open`` are enabled, the
corresponding boundary is not included in the range.
If ``clamp`` is enabled,... | (self).__name__} {self._describe_range()}{clamp}>"
class IntParamType(_NumberParamTypeBase):
name = "integer"
_number_class = int
def __repr__(self):
return "INT"
class IntRange(_NumberRangeBase, IntParamType):
| 64 | 64 | 174 | 12 | 52 | click-contrib/asyncclick | src/click/types.py | Python | IntRange | IntRange | 436 | 457 | 436 | 436 | b6867ab79596345ee2c832a65ecb72b4797da5da | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.