id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
9654711 | <filename>cogs/meta.py
import discord
import psutil
from discord.ext import commands
import textwrap
from utils.paginator import HelpPaginator
class Meta:
def __init__(self, bot):
self.bot = bot
bot.remove_command('help')
@staticmethod
async def __error(ctx, error):
"""Sends the E... | StarcoderdataPython |
1879054 | __version__ = '0.8.0'
def get_version():
return __version__
| StarcoderdataPython |
5181560 | <reponame>SiliconLabs/mltk
from re import L
import typer
from mltk import cli
@cli.root_cli.command('compile')
def compile_model_command(
model: str = typer.Argument(...,
help='''\b
One of the following:
- Name of MLTK model
- Path to trained model's archive (.mltk.zip)
- Path to MLTK model's python s... | StarcoderdataPython |
1805282 | <filename>modes/mission_control/code/mission_control.py
# Mission Control mode file for STTNG
import random
import inspect #329
from mpf.system.modes import Mode
class MissionControl(Mode):
def mode_init(self):
self.player = None
self.running_script = None
self.mission_lights = ['l_shi... | StarcoderdataPython |
11382999 | <filename>lib/sampleapiclient/masking/Masking.py<gh_stars>10-100
import json
from authenticationsdk.util.GlobalLabelParameters import *
# This method reads the items to be masked and accordingly masks the response from the server
def masking(r):
try:
j = json.loads(r)
maskdata = json.dumps(
... | StarcoderdataPython |
11347532 | <reponame>Borda/kaggle_iMet-collection<gh_stars>1-10
import os
import pytest
import torch
from PIL import Image
from torch import tensor
from kaggle_imet.data import IMetDataset, IMetDM
_PATH_HERE = os.path.dirname(__file__)
_TEST_IMAGE_NAMES = (
'1cc66a822733a3c3a1ce66fe4be60a6f',
'09fe6ff247881b37779bcb386... | StarcoderdataPython |
51029 | def array_count9(nums):
count = 0
# Standard loop to look at each value
for num in nums:
if num == 9:
count = count + 1
return count
| StarcoderdataPython |
6581231 | <reponame>8Avalon8/pisces_af<filename>tasks/mainstory15.py
# -*- coding: utf-8 -*-
task = Task("MainStory15",desc = u"自动主线15级后",pretask = ["MainStory"])
#task.addSetupActionSet("RefreshGame",tag="pre1",desc="RefreshGame")
tasksuit.addTask(task)
step = Step("step0.5",u"Login")
task.addStep(step)
#step.addActionSet("Inpu... | StarcoderdataPython |
183797 | <filename>bin/iamonds/hexiamonds-4x12-stacked-hexagons.py
#!/usr/bin/env python
# $Id$
"""51 solutions"""
import puzzler
from puzzler.puzzles.hexiamonds import Hexiamonds4x12StackedHexagons
puzzler.run(Hexiamonds4x12StackedHexagons)
| StarcoderdataPython |
6533890 | <filename>tests/browser/pages/external/govuk_article_page.py
# -*- coding: utf-8 -*-
"""GOV.UK - Generic article page."""
from selenium.webdriver.remote.webdriver import WebDriver
from directory_tests_shared import URLs
from directory_tests_shared.enums import PageType, Service
from directory_tests_shared.utils import... | StarcoderdataPython |
258147 |
import cv2
import numpy as np
import matplotlib.pyplot as plt
import os
import tqdm
from scipy import interpolate
from mouse_detection.tracker import EuclideanDistTracker
def savitzky_golay(y, window_size, order, deriv=0, rate=1):
r"""Smooth (and optionally differentiate) data with a Savitzky-Golay filter.
... | StarcoderdataPython |
1927977 | import functools
from dataclasses import dataclass
def singleton(cls):
instances = []
@functools.wraps
def wrapper(*args, **kwargs):
if not instances:
instances.append(cls(*args, **kwargs))
return instances[0]
return wrapper
@singleton
@dataclass
class Person:
name:... | StarcoderdataPython |
3201709 | import tweepy
import logging
import time
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger()
def follow_followers(api):
logger.info("Retrieving and following followers")
for follower in tweepy.Cursor(api.followers).items():
if not follower.following:
logger.info(f"Followin... | StarcoderdataPython |
3379056 | <filename>app.py
# This is a PyThon Flask app to listen for PR updates in the GitHub
# PyTorch repository. Webhooks PRs that satisfy the conditions set
# below trigger an Azure Pipelines run for running PyTorch custom
# tests on the PR's appropriate artifact(s).
import os
import sys
import requests
import json
from fl... | StarcoderdataPython |
239920 | <reponame>sturzl/guet
from unittest import TestCase
from unittest.mock import Mock
from guet.commands.command_factory import CommandFactoryMethod
from guet.commands.strategies.print_strategy import PrintCommandStrategy
from guet.commands.decorators.version_decorator import VersionDecorator
from guet.settings.settings ... | StarcoderdataPython |
1745389 | #
# import json
#
#
# def get_task_name_from_id(task_id):
# """
# Translate the task id (e.g. 'T0') into abbreviated text (e.g. 'features')
#
# Args:
# task_id (str): task id of Galaxy Zoo question e.g. 'T0'
#
# Returns:
# (str) abbreviated text name of Galaxy Zoo question e.g. 'features... | StarcoderdataPython |
5185295 | #!/usr/bin/env python3
from pathlib import Path
# import argparse
import ast
from graphviz import Digraph
# import jupytext
import os
# import fire
# opt = argparse.ArgumentParser("Function grapher")
# opt.add_argument("-d", "--dir", help="Enter directory")
# opt.add_argument(
# "-f", type=bool, help="Generate fo... | StarcoderdataPython |
11310332 | # Enable type hinting for static methods
from __future__ import annotations
from typing import Optional, Annotated, Any
from dataclasses import dataclass
from requests import Response
@dataclass
class RoundData:
roundID: int
job: Optional[str]
timestamp: Annotated[str, "ISO 8601, YYYY-MM-DDThh:mm:ss.ffffZ... | StarcoderdataPython |
1898331 | from sqlalchemy.exc import SQLAlchemyError, IntegrityError
from convergence.utils import exceptions
from convergence.utils import logger
from convergence.data.repo import Store
from convergence.data.models import User
class UserStore(Store):
def __init__(self, session=None):
super().__init__(session)
... | StarcoderdataPython |
301496 | <filename>orangecontrib/OasysWiser/widgets/optical_elements/ow_plane_mirror.py
import numpy
from syned.widget.widget_decorator import WidgetDecorator
from syned.beamline.shape import Plane
from wiselib2 import Optics
from wofrywise2.beamline.optical_elements.wise_plane_mirror import WisePlaneMirror
from orangecontr... | StarcoderdataPython |
11297096 | <filename>withpty.py
#!/usr/bin/python
import pty, sys; pty.spawn(sys.argv[1:])
| StarcoderdataPython |
9769608 | """Trainer for OCR CTC model."""
import paddle.fluid as fluid
from utility import add_arguments, print_arguments, to_lodtensor, get_feeder_data
from crnn_ctc_model import ctc_train_net
import ctc_reader
import argparse
import functools
import sys
import time
import os
import numpy as np
parser = argparse.ArgumentParse... | StarcoderdataPython |
9731558 | <filename>src/graph_transpiler/webdnn/backend/code_generator/command_buffer.py
from typing import List, Tuple
from webdnn.backend.code_generator.injectors.buffer_injector import BufferInjector
from webdnn.util import flags
class CommandBuffer:
def __init__(self, buffer_injector: BufferInjector):
self.cod... | StarcoderdataPython |
3436597 | <filename>tests/client/test_builds.py
import json
import pytest
import requests_mock
from fl33t.exceptions import InvalidBuildIdError
from fl33t.models import Build
def test_get_build(fl33t_client):
build_id = 'mnbv'
train_id = 'vbnm'
build_response = {
'build': {
'build_id': build_... | StarcoderdataPython |
133002 | #!/usr/bin/env python
"""
Export a history to an archive file using attribute files.
usage: %prog history_attrs dataset_attrs job_attrs out_file
-G, --gzip: gzip archive file
"""
from __future__ import print_function
import optparse
import os
import shutil
import sys
from galaxy.model.store import tar_export_dir... | StarcoderdataPython |
5043784 | <reponame>srinivasdabbeeru/cisco_python<gh_stars>0
#!/usr/bin/python3
import netmiko
#multi-vendor library
#Device IPs I am connecting to today
#192.168.90.146
#192.168.90.147
#192.168.90.148
device1 = {
'username' : 'root',
'password' : '<PASSWORD>',
'device_type' : 'cisco_ios',
'host' : '192.1... | StarcoderdataPython |
5197373 | # coding=utf-8
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from future.utils import raise_
from future.utils import raise_with_traceback
from future.utils import raise_from
from future.utils import iteritems
import os
import logging
import psutil
from... | StarcoderdataPython |
3200787 | <reponame>dailishan/pachong
# coding:utf-8
# 下载豆瓣爱情的电影封面
import requests
import json
# 下载图片
def download(url, title):
dir = './' + title + '.jpg'
try:
pic = requests.get(url)
fp = open(dir, 'wb')
fp.write(pic.content)
fp.close()
print(title)
except requests.exception... | StarcoderdataPython |
201491 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import json
sys.path.insert(0, os.path.abspath('..'))
from helpers import unittest
from pycaustic import Scraper
from pycaustic.errors import InvalidInstructionError
FILE_PATH = os.path.abspath(__file__)
class TestSetup(object):
def setUp(self)... | StarcoderdataPython |
3416399 | <filename>module1a/10.py
import sys
# allows import of project files (idk how else to do this)
sys.path.insert(1, '..')
from utils.webassign import array_from_shitstring
from stats import median
from utils.helpers import round_to_nearest_interval
actual_pressure = array_from_shitstring(
"128.6 137.8 148.4 1... | StarcoderdataPython |
6462369 | """ Resolves OpenSSL issues in some servers:
https://lukasa.co.uk/2013/01/Choosing_SSL_Version_In_Requests/
https://github.com/kennethreitz/requests/pull/799
"""
from distutils.version import StrictVersion
from requests.adapters import HTTPAdapter
try:
import requests.packages.urllib3 as urllib3
except ... | StarcoderdataPython |
3291612 | class ConnectionError(Exception): pass
| StarcoderdataPython |
1698652 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import time
import datetime
print(time.time())
print(time.localtime())
print(time.strftime('%Y-%m-%d %H:%M:%S'))
print(time.strftime('%Y%m%d'))
print(datetime.datetime.now())
new_time = datetime.timedelta(minutes=10)
print(datetime.datetime.now() + new_time)
one_day = da... | StarcoderdataPython |
3563489 | <gh_stars>1-10
import datetime
import dateutil.parser
import json
import os
import subprocess
from prometheus_client import Gauge
class FileBackup():
def parse(self, dict):
self._name = dict['name']
self._time = dateutil.parser.isoparse(dict['time'])
return self
def getName(self):
... | StarcoderdataPython |
9782384 | <filename>train_Cycle_Gan.py
#!/usr/bin/python3
import argparse
import itertools
import os
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
from torch.autograd import Variable
import torch.nn as nn
import torch
from mymodels import Generator_resnet
from mymodels import Discriminator... | StarcoderdataPython |
283832 | <filename>parser/fase2/team14/Entorno/Simbolo.py
from Entorno.TipoSimbolo import TipoSimbolo
class Simbolo:
def __init__(self, tipo="", nombre="", valor=None, linea=0):
self.tipo = tipo
self.nombre = nombre
self.valor = valor
self.linea = linea
self.atributos = {}
s... | StarcoderdataPython |
5479 | <reponame>Jeans212/codility-dev-training
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
'''
Rotate an array A to the right by a given number of steps K.
Covert the array to a deque
Apply the rotate() method the rotate the deque in positive K steps
Convert... | StarcoderdataPython |
3410902 | <reponame>AshKelly/PyAutoLens
import os
from autofit import conf
from autofit.optimize import non_linear as nl
from autofit.mapper import prior
from autolens.data import ccd
from autolens.model.galaxy import galaxy, galaxy_model as gm
from autolens.pipeline import phase as ph
from autolens.pipeline import pipeline as ... | StarcoderdataPython |
4942716 | import functools
import os
import os.path as osp
from collections import OrderedDict
from math import cos, pi
import torch
from torch import distributed as dist
from .dist import get_dist_info, master_only
class AverageMeter(object):
"""Computes and stores the average and current value."""
def __init__(sel... | StarcoderdataPython |
75845 | <reponame>seberg/scipy
import numpy as np
from numpy import array, poly1d
from scipy.interpolate import interp1d
from scipy.special import beta
# The following code was used to generate the Pade coefficients for the
# Tukey Lambda variance function. Version 0.17 of mpmath was used.
#-------------------------------... | StarcoderdataPython |
1720117 | <reponame>arensdj/data-structures-and-algorithms
from tree import BinarySearchTree
def test_preorder_traversal():
tree = BinarySearchTree()
tree.add(25)
tree.add(15)
tree.add(35)
tree.add(8)
tree.add(19)
tree.add(30)
tree.add(45)
expected = [25, 15, 8, 19, 35, 30, 45]
result =... | StarcoderdataPython |
11299017 | from torch.utils.data import Dataset
class ChunkDataset(Dataset):
"""
Class implementing chunk-based loading.
"""
def __init__(self, cfg, mode='train'):
super(ChunkDataset, self).__init__()
self.cfg = cfg
self.mode = mode
self.chunk_idx = 0 # Next chunk index to load
... | StarcoderdataPython |
9780580 | <filename>yadi/datalog2sql/ast2sql/ast2sqlconverter.py
from .safety_checker import *
from .preprocessor import *
from .sql_generator import *
from ...sql_engine.db_state_tracker import DBStateTracker
from ...interpreter.syntax_highlighter import SyntaxHighlight
class Ast2SqlConverter:
def __init__(self, db_state_t... | StarcoderdataPython |
5176986 | # Generated by Django 3.0.8 on 2020-08-11 07:11
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='MlModel',
fields=[
('id', models.AutoField(... | StarcoderdataPython |
9674952 | <filename>climber/__init__.py
__version__ = '0.1.4'
import requests
import re
import json
from bs4 import BeautifulSoup
# TODO: def see_also() => makes a whole set of related thhings to the topic
# chosen
# TODO:
# def chossy() => parse disambiguation pages can be called
# when the page reached durign climb or
# ... | StarcoderdataPython |
8165589 | import numpy as np
import json
from sklearn import svm
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.linear_model import SGDClassifier
import time
import sys
train_file = sys.argv[1]
test_file = sys.ar... | StarcoderdataPython |
12820432 | def make_example_image_1():
from playfair.compare import add_comparisons_to_axes, Comparison, stars
from matplotlib import pyplot as plt
import numpy as np
# Generate some data
d1 = np.linspace(1, 2, 55)
d2 = np.linspace(2, 2.5, 34)
# Create a comparison marker between populations at the p... | StarcoderdataPython |
6685141 | import os
def list_dir():
'''Print out working directory path, as well as the subdirectories
and files.
'''
print("You are here: " + os.getcwd() + "\n")
for root, dirs, files in os.walk("."):
level = root.replace(".", '').count(os.sep)
indent = ' ' * 4 * (level)
print('{}{}... | StarcoderdataPython |
12831226 | <filename>hmmer_reader/_click.py<gh_stars>1-10
import click
def command(either=None):
if either is None:
either = []
class CommandOptionsTogether(click.Command):
def invoke(self, ctx):
eit = [list(t) for t in either]
for opts in eit:
if sum([ctx.params... | StarcoderdataPython |
3298154 | <reponame>ktaranov/HPI<gh_stars>1-10
from pathlib import Path
from my.core.common import get_files
import pytest # type: ignore
def test_single_file():
"""
Regular file path is just returned as is.
"""
"Exception if it doesn't exist"
with pytest.raises(Exception):
get_files("/tmp/hpi_te... | StarcoderdataPython |
9714197 | from setuptools import setup
with open('requirements.txt') as f:
requirements = f.read().splitlines()
setup(
name='InstagramAPI',
version='1.0.2',
description='Unofficial instagram API, give you access to ALL instagram features (like, follow, upload photo and video and etc)! Write on python.',
url... | StarcoderdataPython |
261733 | """ Xbox 360 controller support for Python
11/9/13 - <NAME>
This class module supports reading a connected Xbox controller under Python 2 and 3.
You'll need to first install xboxdrv:
sudo apt-get install xboxdrv
See http://pingus.seul.org/~grumbel/xboxdrv/ for details on xboxdrv
Example usage:
import xbox... | StarcoderdataPython |
5053322 | #!/usr/bin/env python3
# Update the ValidatingWebhookConfiguration with the contents of the Service CA.
from kubernetes import client, config
import os
import argparse
import copy
import base64
parser = argparse.ArgumentParser(description="Options to Program")
parser.add_argument('-a', default="managed.openshift.io/... | StarcoderdataPython |
9753786 | <reponame>Indigo-Uliv/indigo-cli<gh_stars>0
"""
Indigo Command Line Interface -- multiple put.
Copyright 2015 Archive Analytics Solutions
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://ww... | StarcoderdataPython |
11293783 | <reponame>lawi21/escriptorium<gh_stars>1-10
# Generated by Django 2.2.23 on 2021-06-11 08:34
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0049_auto_20210526_1517'),
]
operations = [
migrations... | StarcoderdataPython |
3344804 | from pprint import pprint
from configparser import ConfigParser
from powerbi.client import PowerBiClient
# Initialize the Parser.
config = ConfigParser()
# Read the file.
config.read('config/config.ini')
# Get the specified credentials.
client_id = config.get('power_bi_api', 'client_id')
redirect_uri = config.get('p... | StarcoderdataPython |
12807504 | #!/usr/bin/env python3
from zencad import *
from globals import *
class Room(zencad.assemble.unit):
motor_hole = cylinder(r=5.5, h=T) - halfspace().rotateX(deg(90)).moveY(5)
def __init__(self):
super().__init__()
self.t = T
self.roof_r = ROOF_R
self.border_t = BORDER_T
self.add(self.model())
def model(... | StarcoderdataPython |
9625816 | <gh_stars>10-100
# JN 2015-05-08 adding docstrings to this old, useful code
"""
Simple signal filtering for spike extraction
"""
from __future__ import absolute_import, division
import numpy as np
from scipy.signal import ellip, filtfilt
# pylint: disable=invalid-name, unbalanced-tuple-unpacking, E1101
DETECT_LOW ... | StarcoderdataPython |
8087674 | <reponame>kevin-ci/janeric2
from django.test import TestCase, RequestFactory
from django_libs.tests.mixins import ViewTestMixin
from products.forms import ProductForm, ProductFamilyForm
from products.models import Category, Product_Family, Product
from .factories import (
CategoryFactory,
Product_FamilyFactor... | StarcoderdataPython |
5070922 | from config import get_config
from geoserver.catalog import Catalog
geoserver = Catalog(
get_config('geoserver.restUrl'),
get_config('geoserver.user'),
get_config('geoserver.password'),
)
# create workspace if not exists, a workspace is mandatory to work with geoserver
workspace_name = get_config('geose... | StarcoderdataPython |
6524398 | from scenes.leve1.main_scene import MainScene
# class ScenesManager:
# def __init__(self, wind):
# self.win = wind
# self.scenes = [MainScene(wind)]
# self.current_scene = self.scenes[0]
#
# def draw(self):
# self.current_scene.action()
# self.current_scene.draw()
#
# ... | StarcoderdataPython |
4984027 |
class SqlaJsonTranscoder(object):
"""
encodes/decodes a type of object to a "flat" json form, which matches
the form needed by SQL tables supported by SQLAlchemy. In particular
the form of insert().values(flat_data) in insertion queries and the
form returned by query results that then needs to be t... | StarcoderdataPython |
6528460 | # AUTOGENERATED! DO NOT EDIT! File to edit: 08_contrastive_loss.ipynb (unless otherwise specified).
__all__ = ['TripletLoss', 'ContrastiveLoss', 'CosineContrastiveLoss', 'batched_labels', 'XentOldContrastiveLoss',
'XentLoss', 'XentContrastiveLoss', 'XentContrastiveLoss2', 'BatchContrastiveLoss']
# Cell
fro... | StarcoderdataPython |
9601041 | # -*- coding: UTF-8 -*-
################################################################################
#
# Copyright (c) 2020 Baidu, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"
# you may not use this file except in compliance with the License.
# You may obtain a copy... | StarcoderdataPython |
5079548 | <reponame>anton-sidelnikov/openstacksdk<gh_stars>0
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | StarcoderdataPython |
6605984 | <reponame>andrewp-as-is/django-postgres-drop-index.py
from django.core.management.base import BaseCommand
from django_postgres_drop_index.utils import drop_schema_indexes
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('schemaname', nargs='+')
def handle(self, *args,... | StarcoderdataPython |
8185969 | import data_fetcher
import os
from skimage import io
# You need to implement a function that defines how the data is prepared,
# this function will be called in the data thread, and a arg will be passed when it's called,
# so even if you don't need any args, keep an args variable for the function,
# if you hav... | StarcoderdataPython |
1632167 | """
Issue:
NOTE using Python 2.4, this results in an exe about 4Mb in size.
NOTE using Python 2.6, this results in an exe about 5.5Mb in size.
E:\Python24\python.exe p2_setup.py py2exe
c:\python24\python p2_setup.py py2exe
setup.py py2exe
Quick-N-Dirty create win32 binaries and zip file script.
Zero erro... | StarcoderdataPython |
3241214 | <reponame>hashnfv/hashnfv-functest<filename>functest/tests/unit/openstack/tempest/test_conf_utils.py<gh_stars>0
#!/usr/bin/env python
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is ... | StarcoderdataPython |
321471 | import argparse
import sys
import time
from itertools import izip
from string import ascii_uppercase
import numpy as np
from .volume import Volume
from .structure import Ligand, Structure
from .transformer import Transformer
from .solvers import QPSolver, MIQPSolver
from .validator import Validator
def parse_args()... | StarcoderdataPython |
11311137 | <gh_stars>0
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.OUT)
GPIO.output(11, True)
print "ON"
time.sleep(10)
GPIO.output(11, False)
print "OFF"
| StarcoderdataPython |
168072 | """
This problem was asked by Stripe.
Given an array of integers, find the first missing positive integer in linear time and constant space. In other words,
find the lowest positive integer that does not exist in the array. The array can contain duplicates and
negative numbers as well.
For example, the input [3, 4,... | StarcoderdataPython |
11278192 | <gh_stars>0
__author__ = 'bengt'
BOARD, WHITE, BLACK, MOVE = 'BOARD', 'WHITE', 'BLACK', 'MOVE'
WIDTH, HEIGHT = 8, 8
NORTH = -HEIGHT
NORTHEAST = -HEIGHT + 1
EAST = 1
SOUTHEAST = HEIGHT + 1
SOUTH = HEIGHT
SOUTHWEST = HEIGHT - 1
WEST = - 1
NORTHWEST = -HEIGHT - 1
DIRECTIONS = (NORTH, NORTHEAST, EAST, SOUTHEAST, SOUTH, S... | StarcoderdataPython |
299463 | ##
# Contains TranscriptomeIndexListView, TranscriptomeIndexDetailView, and needed serializer
##
from django.utils.decorators import method_decorator
from rest_framework import filters, generics, serializers
from django_filters.rest_framework import DjangoFilterBackend
from drf_yasg import openapi
from drf_yasg.utils... | StarcoderdataPython |
3481183 | <filename>leetcodeOct2020/oct1.py
# You have a RecentCounter class which counts the number of recent requests within a certain time frame.
# Implement the RecentCounter class:
# RecentCounter() Initializes the counter with zero recent requests.
# int ping(int t) Adds a new request at time t, where t represents some t... | StarcoderdataPython |
1925681 | <reponame>meyerweb/wpt
def main(request, response):
status = request.GET.first(b'status')
response.status = (status, b"");
if b'tao_value' in request.GET:
response.headers.set(b'timing-allow-origin', request.GET.first(b'tao_value'))
| StarcoderdataPython |
9624204 | <filename>day07/00/solution.py
import util
def test():
#test_vals =
assert run(util.TEST_VALS) == 'tknk'
def run(in_val):
tree = util.parse_to_tree(in_val)
return(tree.getroot().get(util.NAME))
| StarcoderdataPython |
1894491 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import tensorflow.contrib.slim as slim
from backbones import utils
resnet_arg_scope = utils.resnet_arg_scope
@slim.add_arg_scope
def bottleneck(inputs, depth, depth_bottleneck, strid... | StarcoderdataPython |
11361412 | <filename>TMbidimensional.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 13 14:56:30 2019
@author: fernando
"""
#Use esta Máquina de Turing responsablemente (y bajo su propio riesgo)
import copy
def ConstruccTM():
TM = []
numInstrucc = int(input("Elija la cantidad de instrucciones ... | StarcoderdataPython |
5113597 | <reponame>Rahuum/glooey<filename>tests/drawing/demo_outline.py
#!/usr/bin/env python3
import pyglet
import glooey
import run_demos
from vecrec import Vector, Rect
window = pyglet.window.Window()
batch = pyglet.graphics.Batch()
full = Rect.from_pyglet_window(window)
left = Rect(full.left, full.bottom, full.width/2, f... | StarcoderdataPython |
101264 | <reponame>superseeker13/Sain
import time
import copy
import socket
import sys
import traceback
import color_hex
import remoteAPI
PreRead = 0
PostRead = 1
PreWrite = 2
PostWrite = 3
PreExecute = 4
PostExecute = 5
_Activate = 1
_Deactivate = 3
_Stop = 5
_Access = 9
_Controllers = 11
_Frame = 13
_Scanline = 15
... | StarcoderdataPython |
3236171 | <reponame>rs992214/keanu
## This is a generated file. DO NOT EDIT.
from typing import Collection, Optional
from py4j.java_gateway import java_import
from keanu.context import KeanuContext
from .base import Vertex, Double, Integer, Boolean, vertex_constructor_param_types
from keanu.vertex.label import _VertexLabel
from... | StarcoderdataPython |
3381616 | <gh_stars>0
import os
import sys
import itertools
if sys.platform == "linux" or sys.platform == "linux2":
os.system("clear")
elif sys.platform == "win32":
os.system("cls")
strings = []
user_repeats = ""
user_wdlist = "<PASSWORD>"
def strings_control():
global strings
strings = ... | StarcoderdataPython |
9766384 | <gh_stars>0
import argparse
import numpy as np
from scipy import ndimage
import h5py
class Clefts:
def __init__(self, test, truth):
test_clefts = test
truth_clefts = truth
self.resolution=(40.0, 8.0, 8.0)
#self.truth_clefts_invalid = (truth_clefts == 0)
self.test_clefts_... | StarcoderdataPython |
6581022 | #!/usr/bin/python3
import os
from db_manager.database import managed_connection
import db_manager.dimManuscript
import db_manager.dimManuscriptVersion
import db_manager.dimManuscriptVersionHistory
import db_manager.dimCountry
import db_manager.dimPerson
import logging
logging.basicConfig(level=logging.INFO,
... | StarcoderdataPython |
276142 | #!/usr/bin/env python
# coding: utf-8
# In given array find the duplicate odd number .
#
# Note: There is only one duplicate odd number
#
# <b> Ex [1,4,6,3,1] should return 1 </b>
# In[3]:
def dup_odd_num(num):
count=0
for i in range(len(num)):
if num[i] % 2 != 0:
count+=1
if c... | StarcoderdataPython |
1940597 | from tensorflow.test import TestCase
from groco.groups import wallpaper_group_dict
import tensorflow as tf
from groco.utils import test_equivariance
class TestWallpaperGroup(TestCase):
def test_inverse_comp(self):
"""
The composition attribute gives the composition of an inverse with another group... | StarcoderdataPython |
12848300 | <filename>meiduo_mall/apps/orders/views.py
import json
from datetime import datetime
from decimal import Decimal
from django import http
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render
# Create your views here.
from django.views import View
from django_redis import get_r... | StarcoderdataPython |
1783464 | <reponame>MithunNallana/Time-Scaled-Collision-Cone
from tscc.model.updatestate import updatestate
def computecoefficients(stateObst, stateRobo, radiusObst, radiusRobo, deltaT):
''' Compute collision cone constraint coefficients '''
clearanceR = 0.0
R = radiusObst + radiusRobo + clearanceR
# unrolling... | StarcoderdataPython |
6500854 | """
@brief Wrapper interface for pyLikelihood.Composite2 to provide
more natural symantics for use in python alongside other analysis classes.
@author <NAME> <<EMAIL>>
"""
#
# $Header: /nfs/slac/g/glast/ground/cvs/ScienceTools-scons/pyLikelihood/python/Composite2.py,v 1.5 2010/07/10 17:01:49 jchiang Exp $
#
import py... | StarcoderdataPython |
6656891 | #
# Copyright 2014-2016 CloudVelox Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
#
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | StarcoderdataPython |
4827453 | <filename>setup.py
#!/usr/bin/python3
import setuptools
import os
import suid_sudo
#with open("README.md", "r") as fh:
# long_description = fh.read()
with open("VERSION", "r") as fh:
version = fh.readline().strip()
setuptools.setup(
# setup_requires=['setuptools_scm'],
# use_scm_version=True,
name="... | StarcoderdataPython |
6567351 | from .middlewares import AutoExtractMiddleware # noqa: F401
| StarcoderdataPython |
1859782 | <reponame>Fluke667/catcher<filename>catcher/steps/http.py
import json
from typing import Union
import requests
from requests import request
from catcher.steps.step import Step, update_variables
from catcher.utils.file_utils import read_file
from catcher.utils.logger import debug
from catcher.utils.misc import fill_te... | StarcoderdataPython |
3584955 | # The MIT License (MIT)
# Copyright (c) 2018 by the xcube development team and contributors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation... | StarcoderdataPython |
6443990 | import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *
''' IMPORTS '''
from typing import Dict, List, Tuple, Any
from netaddr import IPAddress
import urllib3
# Disable insecure warnings
urllib3.disable_warnings()
''' CONSTANTS '''
INTEGRATION_NAME = 'Public DNS Feed'
c... | StarcoderdataPython |
1984730 | """ This function calculates similarity scores with different methods
It calculates similarity scores with :
- difflib library to find matching sequences.
- Jaccard Similarity
- words counting,
- overlapping words
"""
import difflib
from utils import remove_numbers, remove_stop_words, lemmatize
def difflib_overlap... | StarcoderdataPython |
148839 | <reponame>wharvey31/project-diploid-assembly<filename>scripts/utilities/version_checker.py<gh_stars>0
#!/usr/bin/env python
import os
import sys
import argparse
import re
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--outfile', '-o', type=str, dest='outfile')
parser.add_argument('... | StarcoderdataPython |
1668130 | <reponame>djconly85/PPA2_0_code
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 9 13:13:38 2020
@author: dconly
https://www.reportlab.com/documentation/tutorial/#json-to-pdf-invoice-tutorial
"""
| StarcoderdataPython |
1928792 | <filename>indico/modules/events/contributions/forms.py
# This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from datetime import timedelta
from flask import r... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.