id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
1684991 | <filename>makeTrainingDS.py
#!/usr/bin/env python3
import argparse
import os
import pickle as pkl
import gzip
from camaptools.Dataset import TrainingDataset
from camaptools.EnhancedFutures import EnhancedProcessPoolExecutor, EnhancedMPIPoolExecutor
def write_to_disk(dat, ds_name):
if not os.path.exists('output/... | StarcoderdataPython |
3356008 | import sys
from glados.es.ws2es.denormalization import DenormalizationHandler
class DrugDenormalizationHandler(DenormalizationHandler):
RESOURCE = DenormalizationHandler.AVAILABLE_RESOURCES.DRUG
def __init__(self):
super().__init__()
self.compound_dict = {}
def handle_doc(self, es_doc: ... | StarcoderdataPython |
85958 | <filename>tests/previs/test_track.py
# -*- coding: utf-8 -*-
import unittest
from anima.edit import Track, Clip, File
class TrackTestCase(unittest.TestCase):
"""tests the anima.previs.Track class
"""
def test_to_xml_method_is_working_properly(self):
"""testing if the to xml method is working pro... | StarcoderdataPython |
1727135 | /home/runner/.cache/pip/pool/7e/65/ee/200d991e43cd86a0907aab8ec16d798d074658390e3c0e8a43423cd2cf | StarcoderdataPython |
4813514 | <gh_stars>0
class Solution(object):
def findNumberIn2DArray(self, matrix, target):
if matrix in ([], [ [] ]):
# Quick rejection for empty matrix
return False
h, w = len(matrix), len(matrix[0])
# start search from top-right corner
y, x = 0, w-1
# ke... | StarcoderdataPython |
38498 | <gh_stars>10-100
from .parallel import DataParallelModel, DataParallelCriterion
__all__ = ["DataParallelModel", "DataParallelCriterion"] | StarcoderdataPython |
3305878 | <filename>python/IECoreMaya/Collapsible.py<gh_stars>100-1000
##########################################################################
#
# Copyright (c) 2011, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided t... | StarcoderdataPython |
38594 | #
# voice-skill-sdk
#
# (C) 2020, Deutsche Telekom AG
#
# Deutsche Telekom AG and all other contributors /
# copyright owners license this file to you under the MIT
# License (the "License"); you may not use this file
# except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensou... | StarcoderdataPython |
1799231 | <filename>enterprise_manage/apps/score_center/score_center/adminx.py
import xadmin
from enterprise_manage.apps.score_center.models import *
class ScoreProjectAdmin(object):
list_display = ['id', 'name']
list_editable = ['id', 'name']
xadmin.site.register(ScoreProject, ScoreProjectAdmin)
class ScoreOptionA... | StarcoderdataPython |
18539 | <filename>code/Elipsoide_Clark_FAT.py<gh_stars>1-10
from __future__ import division
import numpy as np
from scipy import linalg
from matplotlib import pyplot as plt
from fatiando.gravmag import sphere
from fatiando import mesher, gridder, utils
from fatiando.vis import mpl
import scipy.special
import scipy.interpolat... | StarcoderdataPython |
179448 | from channels.generic.websockets import JsonWebsocketConsumer
from .schema import schema
class ArtificialRequestContext(object):
def __init__(self, user):
self.user = user
def get_context(self):
return {
'request': self
}
def get_channel_group_name_for_user(user_id):
... | StarcoderdataPython |
196751 | import random
#Create a Agent class to give agents attributes and behaviours
class Agent():
def __init__ (self, environment, agents, y, x):
#Randomise the starting location of an agent
self.y=random.randint(0,99)
""""Randomly assign the value of coordinate Y to an agen... | StarcoderdataPython |
1743817 | from .redis_box import RedisBox
from .redis_mapping import RedisMapping
from .redis_mutable_mapping import RedisMutableMapping
| StarcoderdataPython |
31482 | <reponame>rheimon1/Calculadora
def media_suicida (mediaProvas, mediaTrabalhos):
if mediaProvas >= 5 and mediaTrabalhos >= 5:
return mediaProvas * 0.6 + mediaTrabalhos * 0.4
return min(mediaProvas, mediaTrabalhos)
notasProva = []
notasTrabalho = []
quantidadeProva = int(input("Quantidade de provas: ")... | StarcoderdataPython |
52263 | import deck_of_cards
from deck_of_cards import CountingSystemHiLo, DeckOfCards
import random
from time import sleep
from dataclasses import dataclass
import rich
from rich.console import Console
from rich.panel import Panel
from rich.markdown import Markdown
from rich.text import Text
from rich.layout import Layout
fro... | StarcoderdataPython |
93480 | <filename>16.12.1/mdt/mdtcfg.py
#!/usr/bin/env python3
#
# Copyright (c) 2019, Cisco and/or its affiliates
# All rights reserved.
#__maintainer__ = '<NAME>'
#__email__ = '<EMAIL>'
#__date__ = 'Aug 2019'
#__version__ = 1.0
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitt... | StarcoderdataPython |
1677550 | """Run a vasp workflow from json input."""
import argparse
from aiida import load_dbenv
load_dbenv()
def get_parser():
"""Create a cmdline parser for the tool"""
parser = argparse.ArgumentParser(description=('Run a vasp workflow reading parameters ' 'from a json file'))
parser.add_argument(
'--st... | StarcoderdataPython |
4802170 | from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bootstrap import Bootstrap
import config
from prices.site import site
bootstrap = Bootstrap()
db = SQLAlchemy()
def create_app():
app = Flask(__name__)
load_config(app)
bootstrap.init_app(app)
app.register_blueprint(site)
d... | StarcoderdataPython |
6167 | <reponame>godormad/PySyft
# stdlib
import importlib
import sys
from typing import Any
from typing import Any as TypeAny
from typing import Dict as TypeDict
from typing import Optional
# third party
from packaging import version
# syft relative
from ..ast.globals import Globals
from ..lib.python import create_python_a... | StarcoderdataPython |
145095 | import copy
import pickle
import random
import os
import torch
import torch.nn.functional as F
import torch.distributed as dist
import numpy as np
from torch.autograd import Variable
from gym.spaces import Discrete, Box
import ped_env
import rl
from rl.utils.miscellaneous import str_key
def set_dict(target_dict, v... | StarcoderdataPython |
161868 | <reponame>dumpmemory/zulip
from unittest import mock
from django.utils.timezone import now as timezone_now
from zerver.lib.test_classes import ZulipTestCase
from zerver.lib.test_helpers import queries_captured
from zerver.models import Client, UserActivity, UserProfile, flush_per_request_caches
class ActivityTest(Z... | StarcoderdataPython |
199673 | <filename>integration_tests/src/main/python/conftest.py
# Copyright (c) 2020, <NAME>.
#
# 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
#
# Un... | StarcoderdataPython |
3210726 | import pygame
import sys
import time
import random
import src
class Square(pygame.sprite.Sprite):
def __init__(self, x, y, screen_height, screen_width, image):
'''
Initalizes Square attributes
args:
x:(int) a number, x coordinate on screen
y:(int) a number, y... | StarcoderdataPython |
160087 | """Return text streams to EDAM data.
Keep parsing and such to minimum to maintain maximum backward compatibility.
"""
from importlib.resources import open_text
from typing import TextIO
def tabular_stream() -> TextIO:
"""Yield EDAM data in TSV format as a Python UTF-8 encoded text stream."""
return open_text... | StarcoderdataPython |
109511 | <filename>pdf2text.py<gh_stars>1-10
from pdf2image import convert_from_bytes
from datetime import datetime
from io import BytesIO
from PIL import Image
import numpy as np
import pytesseract
import subprocess
import cv2
import os
from pytesseract.pytesseract import TesseractNotFoundError
class PDF2Text:
def __init... | StarcoderdataPython |
1682179 | <gh_stars>0
from typing import Callable, Optional, Tuple
from typish import get_args
from jsons._load_impl import load
from jsons.exceptions import DeserializationError
def default_dict_deserializer(
obj: dict,
cls: type,
*,
key_transformer: Optional[Callable[[str], str]] = None,
... | StarcoderdataPython |
3337272 | from abc import ABC, abstractmethod
from typing import List, Tuple
from uuid import UUID
class GrantsCrypto(ABC):
@abstractmethod
def to_token(self, person_id: UUID, grants : List[str]) -> str:
pass
@abstractmethod
def to_user_id_with_grants(self, token: str) -> Tuple[UUID, List[str]]:
... | StarcoderdataPython |
3381469 | import uuid
from django.contrib.auth.models import User
from django.http import HttpRequest
from permissions import permissions_response
from wiki.models.permissionpage import PermissionPage
from wiki.models.permissionsection import PermissionSection
from wiki.models.wikipage import WikiPage
from wiki.models.wikisect... | StarcoderdataPython |
3270894 | # -*- coding: utf-8 -*-
import difflib
############################################
### HELPER/UTIL FUNCTIONS FOR DATAFRAMES ###
############################################
def get_unique_vals(data, col="type"):
"""
returns unique values of a column
call to (e.g.) data.type.unique()
... | StarcoderdataPython |
105339 | # # from selenium import webdriver
# # import time
# # from selenium.webdriver.chrome.options import Options
# #
# # chrome_options = Options()
# # # chrome_options.add_argument('--headless')
# # # chrome_options.add_argument('--disable-gpu')
# #
# # path = r'/usr/bin/chromedriver'
# # driver = webdriver.Chrome(chrome_... | StarcoderdataPython |
99794 | # (C) 2021 GoodData Corporation
import pytest
from gooddata_pandas import DataFrameFactory, GoodPandas
@pytest.fixture
def gdf(test_config) -> DataFrameFactory:
gdpd = GoodPandas(host=test_config["host"], token=test_config["token"])
return gdpd.data_frames(test_config["workspace"])
| StarcoderdataPython |
3284052 | <reponame>marcosalcazar/django-simple-accounting<filename>accounting/migrations/0002_auto_create_mandatory_accounts.py
# -*- coding: utf-8 -*-
import json
from django.db import migrations
INITIAL = """
[
{
"fields": {
"rght": 2,
"code": "1",
"mandatory": true,
"name": "Asset",
... | StarcoderdataPython |
3375067 | """Test the helpers."""
import pytest
from sqlfluff.core.parser.helpers import trim_non_code_segments, iter_indices
@pytest.mark.parametrize(
"token_list,pre_len,mid_len,post_len",
[
(["bar", ".", "bar"], 0, 3, 0),
(("bar", ".", "bar"), 0, 3, 0),
([], 0, 0, 0),
([" ", "\n", ... | StarcoderdataPython |
3372690 | <filename>pystacia/api/jnatypes.py<gh_stars>1-10
from sys import exc_info
import ctypes
from java.lang import UnsatisfiedLinkError # @UnresolvedImport
from com.sun.jna import NativeLibrary, Pointer # @UnresolvedImport
from pystacia.util import memoized
class c_void_p(object):
_wrap = True
_unwrap = True
... | StarcoderdataPython |
157256 | <filename>saleor/core/db/schema.py<gh_stars>0
def set_search_path(sender, **kwargs):
conn = kwargs.get('connection')
if conn is not None:
cursor = conn.cursor()
cursor.execute("SET search_path=saleor")
| StarcoderdataPython |
48757 | <gh_stars>1-10
from django.db import models
# Create your models here.
class given_image(models.Model):
image_given=models.ImageField(max_length=64)
class image_name(models.Model):
name_of_image=models.CharField(max_length=64)
def __str__(self):
return self.name_of_image
... | StarcoderdataPython |
123237 | from master.workflow.netconf.workflow_netconf import WorkFlowNetConf
from common.utils import *
from master import models
from django.core import serializers as serial
import json
class WorkFlowNetConfCNN(WorkFlowNetConf):
"""
"""
def __init__(self, key = None):
"""
init key variable
... | StarcoderdataPython |
1714790 | try:
import usocket as socket
except:
import socket
import uselect as select
from helpers import dbg
import gc
class Poller:
# A simple utility class to wait for incoming data to be
# read on a socket.
def __init__(self):
if "poll" in dir(select):
self.use_poll = True
... | StarcoderdataPython |
3257053 | <filename>src/byrne/__init__.py
from .dynamodb import DynamoDb
from .table import Table
from .table_view import TableView
__all__ = [
"DynamoDb",
"Table",
"TableView"
]
| StarcoderdataPython |
72755 | <filename>openfecli/cli.py
# This code is part of OpenFE and is licensed under the MIT license.
# For details, see https://github.com/OpenFreeEnergy/openfe
import pathlib
import click
from plugcli.cli import CLI, CONTEXT_SETTINGS
from plugcli.plugin_management import FilePluginLoader
import openfecli
from .plugins ... | StarcoderdataPython |
4839803 | # ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distrib... | StarcoderdataPython |
3257064 | <filename>setup.py<gh_stars>1-10
'''
Build script for Tapo PluG API
'''
from setuptools import setup
from codecs import open
from os import path
import tapo_plug
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
long_description = f.re... | StarcoderdataPython |
56487 | from django.contrib.auth import authenticate
from rest_framework import viewsets
from rest_framework.authtoken.models import Token
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.status ... | StarcoderdataPython |
139328 | """Link user to organisation
Revision ID: 4d8b254d7e7e
Revises: 016571f41a20
Create Date: 2020-01-22 17:42:42.968199
"""
# revision identifiers, used by Alembic.
revision = '4d8b254d7e7e'
down_revision = '016571f41a20'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.ext.declarative import declarative... | StarcoderdataPython |
1664780 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
from datagenerator.segment import SegmentIdentifyEvent, SegmentTrackEvent, SegmentSender
from datagenerator.amplitude import AmplitudeIdentifyEvent, AmplitudeTrackEvent, AmplitudeSender
from datagenerator.file import ... | StarcoderdataPython |
1638812 | # All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
import shlex
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, us... | StarcoderdataPython |
4801981 | <reponame>SiliconLabs/gecko_sdk
from pyradioconfig.calculator_model_framework.interfaces.itarget import ITarget
from os.path import join
class Target_Sim_Sol(ITarget):
_targetName = "Sim"
_description = "Supports the wired FPGA and other targets of sim PHYs"
_store_config_output = True
_cfg_location =... | StarcoderdataPython |
1705392 | from django.shortcuts import render
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from common import base_admin
from .utils import table_filter
def index(request):
#print(base_admin.enabled_admins)
return render(request, 'common/index.html', {'table_list': base_admin.enabled_admins}... | StarcoderdataPython |
3252734 | <gh_stars>0
from setuptools import setup
from setuptools import Extension
from Cython.Build import cythonize
setup(
name='beam-collatz',
ext_modules=cythonize([
Extension(
'*',
['collatz.pyx'],
libraries=['gmp', 'gmpxx'],
language='c++',
)
]),... | StarcoderdataPython |
3207656 | <reponame>vishalbelsare/operalib
"""
:mod:`operalib.kernel_maps` implement some Operator-Valued Kernel
maps associated to the operator-valued kernel models defined in
:mod:`operalib.kernels`.
"""
# Author: <NAME> <<EMAIL>> with help from
# the scikit-learn community.
# License: MIT
from scipy.sparse.linalg imp... | StarcoderdataPython |
100890 | <filename>objectModel/Python/cdm/persistence/syms/manifest_databases_persistence.py
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
import dateutil.parser
from cdm.enums import CdmObjectType
from cdm.objectmodel... | StarcoderdataPython |
3358169 | from yapsy.PluginManager import PluginManager
import logging
import os.path
import sys
log = logging.getLogger(__name__)
class PluginManager2(PluginManager):
def loadPluginByName(self, name, callback=None):
"""
"""
if not hasattr(self, '_candidates'):
raise ValueError("locatePl... | StarcoderdataPython |
1641570 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import re
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
os.system('python setup.py bdist_wheel upload')
sys.exit()
#... | StarcoderdataPython |
1667127 | <reponame>all-of-us/raw-data-repository<gh_stars>10-100
"""genomic_gc_manifest_workflow
Revision ID: f5520e9dde27
Revises: <PASSWORD>
Create Date: 2020-02-12 15:52:30.417779
"""
from alembic import op
import sqlalchemy as sa
import model.utils
from sqlalchemy.dialects import mysql
from rdr_service.participant_enums ... | StarcoderdataPython |
3222848 | """
Generate argument list for benchmark random forest
"""
from sklearn.model_selection import ParameterGrid
from util import write_config_file
import argparse
parser = argparse.ArgumentParser(description="Generate configuration file for bench_rf")
parser.add_argument('tool', help="configuration for which tool", choi... | StarcoderdataPython |
3201394 | """
FILTERED ELEMENT COLLECTOR
"""
__author__ = '<NAME> - <EMAIL>'
__twitter__ = '@solamour'
__version__ = '1.0.0'
# Importing Reference Modules
import clr # CLR ( Common Language Runtime Module )
clr.AddReference("RevitServices") # Adding the RevitServices.dll special Dynamo module to deal
# with Revit
... | StarcoderdataPython |
136737 | from django.apps import AppConfig
class ChannelsConfig(AppConfig):
name = 'channels'
def ready(self):
import channels.signals
| StarcoderdataPython |
193530 | from sklearn.linear_model import SGDClassifier
sgd = SGDClassifier(loss='modified_huber',shuffle=True,random_state=101)
sgd.fit(XA,yA)
yP = sgd.predict(XB) | StarcoderdataPython |
1749953 | """
题目:和为s的连续正数序列
输入一个正数s 打印出所有和为s的连续正数序列(至少含两个数) 例如 输入15 由于1+2+...+8=15 哟所打印3个连续序列1~5 4~6 7~8
"""
class Solution(object):
def FindequenceSumSS(self, s):
if s <= 0:
return
small, middle, big = 1, (s + 1)//2, 2
curSum = small + big
while big <= middle:
if ... | StarcoderdataPython |
1672771 | """Define mention classifier class."""
import logging
from pathlib import Path
from negbio.pipeline import parse, ptb2ud, negdetect
from negbio.neg import semgraph, propagator, neg_detector
from negbio import ngrex
from tqdm import tqdm
from constants import *
class ModifiedDetector(neg_detector.Detector):
"""Ch... | StarcoderdataPython |
112434 | <filename>addons/crnd_wsd/tests/test_mail.py
import logging
from odoo.tests import (
HOST,
PORT,
)
from odoo.tools.misc import mute_logger
from odoo.addons.generic_request.tests.common import disable_mail_auto_delete
from .phantom_common import TestPhantomTour
_logger = logging.getLogger(__name__)
class Test... | StarcoderdataPython |
188453 | <filename>BeaverBotFinal.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'BeaverBot.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
from APIRequest import APIRequest
import os
from sub... | StarcoderdataPython |
1737739 | <reponame>bsnacks000/deo
import io
import os
import sys
from shutil import rmtree
from setuptools import find_packages, setup, Command
# Package meta-data.
NAME = 'deo'
DESCRIPTION = 'another jsonrpc2-http implementation'
URL = 'https://github.com/bsnacks000/deo'
EMAIL = '<EMAIL>'
AUTHOR = 'bsnacks000'
REQUIRES_PYTHO... | StarcoderdataPython |
4838853 | <filename>preview/factory.py
"""Provides an application factory for the submission preview service."""
from flask import Flask, Response, jsonify
from werkzeug.exceptions import HTTPException, Forbidden, Unauthorized, \
BadRequest, MethodNotAllowed, InternalServerError, NotFound, \
ServiceUnavailable
from arx... | StarcoderdataPython |
70758 | <filename>assignment/sets/max_min_set.py
s = set(map(int, input().split()))
print(s)
print("max is: ",max(s))
print("min is: ",min(s))
| StarcoderdataPython |
3208626 | import os
import sys
import json
from .codecs import *
from collections import OrderedDict
class BaseEmoji:
def __init__(self):
self.emoji_file = '{}/data/emojis.json'.format(os.path.dirname(__file__))
self.all_emojis = self.load_emojis(self.emoji_file)
def load_emojis(self, file):
w... | StarcoderdataPython |
159715 | <filename>dotenv/__init__.py
# encoding=UTF-8
from __future__ import with_statement
__version__ = '0.0.5'
class Dotenv(dict):
def __init__(self, file_path):
self.file_path = file_path
super(Dotenv, self).__init__(**self.__create_dict())
def __create_dict(self):
with open(self.file_... | StarcoderdataPython |
3261118 | <filename>modules/scrape_emails_and_social_media.py<gh_stars>1-10
#!/usr/bin/env python3
"""
Scrapes urls from file for email addresses and social media
does not add new urls to the queue from urls found while scraping
"""
from bs4 import BeautifulSoup
from modules.errors import insert
from modules.file_io import io
fr... | StarcoderdataPython |
31081 | # (C) Datadog, Inc. 2018-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import os
from datadog_checks.utils.common import get_docker_hostname
HERE = os.path.dirname(os.path.abspath(__file__))
# Networking
HOST = get_docker_hostname()
GITLAB_TEST_PASSWORD = "<PASSWORD>"
GI... | StarcoderdataPython |
1746531 | <reponame>mister-bailey/solvent
import os
from glob import glob
from configparser import ConfigParser
from collections.abc import Sequence
def save_dir(save_prefix):
return str(os.path.split(save_prefix)[0])
def is_seq(x):
return isinstance(x, Sequence) and not isinstance(x, str)
def glob_most_recent(path):
... | StarcoderdataPython |
106310 | <filename>keycloak_admin_aio/__init__.py
"""This package provides a asynchronous Keycloak Admin API wrapper."""
from ._keycloak_admin_aio import KeycloakAdmin
from .types import *
__all__ = ["KeycloakAdmin"]
| StarcoderdataPython |
3215807 | <filename>gnomad/resources/config.py<gh_stars>10-100
"""Configuration for loading resources."""
from enum import Enum
from typing import Union
class GnomadPublicResourceSource(Enum):
"""Sources for public gnomAD resources."""
GNOMAD = "gnomAD"
GOOGLE_CLOUD_PUBLIC_DATASETS = "Google Cloud Public Datasets... | StarcoderdataPython |
3350478 | import os
import sys
import configparser
from pathlib import Path
import xml.etree.ElementTree as ET
from xml.dom import minidom
from time import sleep
import datetime
from http.server import BaseHTTPRequestHandler, HTTPServer
import ssl
dirname, filename = os.path.split(os.path.abspath(__file__))
posts_received = 0
p... | StarcoderdataPython |
1619727 | <reponame>pulumi/pulumi-pagerduty<gh_stars>1-10
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Op... | StarcoderdataPython |
15040 | <gh_stars>0
from rest_framework.test import APIRequestFactory
from rest_framework import status
from django.test import TestCase
from django.urls import reverse
from ..models import User
from ..serializer import UserSerializer
from ..views import UserViewSet
import ipapi
class UsersApiRootTestCase(TestCase):
def... | StarcoderdataPython |
1748712 | <filename>bin/sa_haveibeenpwned/aob_py3/jsl/_compat/__init__.py<gh_stars>1-10
# coding: utf-8
"""
Compatibility utils for Python 2 & 3.
"""
import sys
IS_PY3 = sys.version_info[0] == 3
string_types = (str, ) if IS_PY3 else (basestring, )
text_type = str if IS_PY3 else unicode
_identity = lambda x: x
if... | StarcoderdataPython |
3301187 | <gh_stars>1-10
# dp.py
import csv
import attr
import numpy as np
from collections import defaultdict
class BudgetDepletedError(Exception):
pass
@attr.s
class Rating:
"""Movie rating."""
user = attr.ib()
movie = attr.ib()
date = attr.ib()
stars = attr.ib()
# Unsure what Rating this? It is a ... | StarcoderdataPython |
191387 | from enum import Enum
class Exceptions(Enum):
InvalidSyntax = 100
AlreadyDefined = 101
NotImplementedException = 102
NotDefinedException = 103
GeneralException = 104
DivideByZeroException = 105
InvalidValue = 106
InvalidTypeException = 107
class Types(Enum):
Boolean = 0
Integer = 1
Float = 2
List = 3
... | StarcoderdataPython |
1621571 | <gh_stars>10-100
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ..... | StarcoderdataPython |
1624344 | """
Geocoding.
Look up and reverse look up addresses.
"""
import requests
from kochira import config
from kochira.service import Service, background, Config, coroutine
from kochira.userdata import UserData
service = Service(__name__, __doc__)
@service.config
class Config(Config):
api_key = config.Field(doc="G... | StarcoderdataPython |
174849 | """Constants for the CPU Speed integration."""
import logging
from typing import Final
from homeassistant.const import Platform
DOMAIN: Final = "cpuspeed"
PLATFORMS = [Platform.SENSOR]
LOGGER = logging.getLogger(__package__)
| StarcoderdataPython |
1602956 | <filename>tools/setup.py
"""Setup py distutils"""
# pylint: skip-file
from distutils.core import setup
from Cython.Build import cythonize
setup(name='montecarlo_cython',
ext_modules=cythonize("montecarlo_cython.pyx"))
| StarcoderdataPython |
1681089 | # -*- coding: utf-8 -*-
import tensorflow as tf
import numpy as np
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.training import moving_averages
#
# 用于最中执行batch normalization的函数
# tf.nn.batch_normalization(
# x,
# mean,
# variance,
# offset,
# scale,
# ... | StarcoderdataPython |
3352525 | <gh_stars>10-100
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"PySimpleSOAP"
import client
import server
import simplexml
import transport | StarcoderdataPython |
153511 | #!/usr/bin/env python3
from termcolor import colored, cprint
import threading
import requests
import argparse
import signal
import time
import sys
import os
import re
logo = """
___ _____ _ _ __
| _ \___ ____ __ ___ _ _ _____|_ _| |_ (_)___ / _|
| / -_(_-| '_ / _ | ' \(_-/... | StarcoderdataPython |
3385484 | <filename>qs_oauth.py
#!/usr/bin/env python3
from ecdsa import SigningKey, NIST384p
import base64
import importlib
import urllib
import requests
import sys
import os
import os.path
import socket
import time
import timeit
import getopt
from tempfile import mkstemp
try:
from BaseHTTPServer import HTTPServer
from... | StarcoderdataPython |
1721648 | from flake8_multiline_containers import MultilineContainers
import pytest
@pytest.fixture
def linter():
m = MultilineContainers()
m.errors = []
return m
@pytest.fixture
def dummy_file_path():
return 'tests/dummy'
| StarcoderdataPython |
1643095 | <reponame>grovyle/schema-gen-greendao
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# main.py
#
# Copyright 2015 <NAME> <<EMAIL>>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either ... | StarcoderdataPython |
1644268 | <reponame>iai-group/arXivDigest
# -*- coding: utf-8 -*-
__author__ = '<NAME> and <NAME>'
__copyright__ = 'Copyright 2020, The arXivDigest project'
from datetime import date
from datetime import datetime
from functools import wraps
from uuid import UUID
from flask import g
from flask import jsonify
from flask import m... | StarcoderdataPython |
3269810 | <filename>cdk/2-api-gateway-cognito-auth.py
from aws_cdk import core
from aws_cdk import aws_apigateway
from aws_cdk import aws_lambda
class InfrastructureStack(core.Stack):
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
super().__init__(scope, id, **kwargs)
# Create... | StarcoderdataPython |
3310896 | <gh_stars>0
class ObservingConditionsDevice:
def __init__(self):
self.__connected = False
self.__client_transaction_id = 0
self.__client_id = 0
self.__description = "Observing Conditions Alpaca Device"
self.__driver_info = ""
self.__driver_version = 1.0
self... | StarcoderdataPython |
169173 | <gh_stars>0
from django.contrib import admin
from django.urls import path
from .views import home, result
urlpatterns = [
path('', home, name='home'),
path('result/', result, name='result')
] | StarcoderdataPython |
4802725 | import fault
import magma
from hwtypes import BitVector, Bit
from fault.value import AnyValue, UnknownValue, HiZ
from fault.real_type import RealType, RealKind
from fault.array import Array
from fault.select_path import SelectPath
from hwtypes.adt import Enum
def make_value(type_, value):
if issubclass(type_, Rea... | StarcoderdataPython |
3046 | #!/usr/bin/env python
"""Test checkpoint-like periodic snapshots.
We test that there are that many folders and that the currentStep changes.
"""
import mirheo as mir
u = mir.Mirheo(nranks=(1, 1, 1), domain=(4, 6, 8), debug_level=3,
log_filename='log', no_splash=True,
checkpoint_every=1... | StarcoderdataPython |
1665534 | from pyautogui import *
import pyautogui
import time
import keyboard
import random
import win32api, win32con
## This code is just an autoclicker
try:
while keyboard.is_pressed('q') == False:
while keyboard.is_pressed('e') == True:
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDO... | StarcoderdataPython |
1759904 | from django.forms import *
from django.utils.translation import gettext_lazy as _
from .models import FSJUser
from .forms import *
| StarcoderdataPython |
1700538 | #!/usr/bin/python3
# TextStreaming by digits version 0.6 2019.7
import textwrap
from os import system
from sys import stdout, platform
from time import sleep
### Calling Text.clear() ### (clear screen)
'''
Clears Terminal Screen
Shorthand for os.system('clear'/'cls')
'''
### Calling Text.count_chars() #... | StarcoderdataPython |
1732553 | <reponame>nunenuh/modelzoo.pytorch
import torch
import torch.nn as nn
__all__ = ['SimpleNet', 'MultilayerNet']
class SimpleNet(nn.Module):
def __init__(self, num_in_feat, num_hid_feat, num_out_feat):
super(SimpleNet, self).__init__()
self.input_layer = nn.Linear(num_in_feat, num_hid_feat)
... | StarcoderdataPython |
134019 | <reponame>athento/pystanbol
from rdflib.namespace import RDF, RDFS, DCTERMS
from rdflib.namespace import Namespace
from rdflib.namespace import split_uri
class Entity:
def __init__(self, reference, site, graph):
self.__reference = reference
self.__site = site
self.__graph = graph
@cl... | StarcoderdataPython |
144799 | <gh_stars>0
########################################
# Automatically generated, do not edit.
########################################
from pyvisdk.thirdparty import Enum
VirtualMachineUsbInfoFamily = Enum(
'audio',
'bluetooth',
'communication',
'hid',
'hid_bootable',
'hub',
'imaging',
... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.