id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
3259068 | <gh_stars>1-10
from setuptools import find_packages
from setuptools import setup
with open('README.rst') as f:
readme = f.read()
setup(
name='progeny',
version='0.2.0',
description='Simple but powerful management for complex class hierarchies',
long_description=readme,
url='https://github.com/... | StarcoderdataPython |
3274208 | # import the necessary packages
import cv2
from imutils.perspective import four_point_transform
import pytesseract
import argparse
import imutils
import re
import numpy as np
import io
from PIL import Image, ImageEnhance, ImageFilter
import datetime
from collections import namedtuple
import os
def ocr_co... | StarcoderdataPython |
1788249 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import requests
from django.conf import settings
from django.db import models
from django.core.exceptions import ValidationError
from solo.models import SingletonModel
from django_datajsonar.models import AbstractTask
class Query(models.Model):
"""... | StarcoderdataPython |
3317229 | <gh_stars>0
import unittest
from rolling_registry import RollingRegistry
#from my_sum import sum
class RollingRegistryTest(unittest.TestCase):
def test_empty_rolling_registry(self):
registry = RollingRegistry(3)
self.assertEqual(registry.last(), None)
self.assertEqual(registry.s... | StarcoderdataPython |
1650729 | from credential import Credential
class User:
"""
A class for user credentials
"""
users_list = []
user_credentials = []
def __init__(self, username, userpassword):
'''
Properties of the user
'''
self.username = username
self.userpassword = <PASSWORD>
... | StarcoderdataPython |
1734171 | <gh_stars>1-10
from . import json_serialiser
from . import time_util | StarcoderdataPython |
172176 | from os import path
import click
import contxt.schemas as schemas
from contxt.services.base_graph_service import BaseGraphService
from contxt.utils.contxt_environment import ContxtEnvironment
@click.command()
@click.option('--fresh-from-file', type=str, help='Overwrite/init from a specific environment file')
def ini... | StarcoderdataPython |
63947 | import pytest
def test_import_pipeline():
import kcwidrp.pipelines.kcwi_pipeline
| StarcoderdataPython |
4814454 | <reponame>DjLess/Dj-less-main<gh_stars>0
"""
Welcome to Dj less source code, here you will find everything that you need to understand the way dj less works
to this time,
this code was made only for data.csv provided from virtual serato's console. In the future our intention
it's to made this for all kind of his... | StarcoderdataPython |
3382513 | <filename>src/dipus/websetup.py<gh_stars>0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import argparse
import logging
from bottle import Bottle, route, run, request, response, abort
from bottle import Jinja2Template
from bottle import static_file
# increase POST request body size
import bottle... | StarcoderdataPython |
1670029 | import xpc.xpc as xpc
import rospy
import xplane_ros.msg as xplane_msgs
import rosplane_msgs.msg as rosplane_msgs
from geometry_msgs.msg import Twist
from geometry_msgs.msg import Pose, PoseStamped
from nav_msgs.msg import Odometry
from std_msgs.msg import Float32
from geometry_msgs.msg import Quaternion
from tf.tra... | StarcoderdataPython |
1763626 | <filename>grafeas/models/vulnerability_occurrences_summary_fixable_total_by_digest.py
# coding: utf-8
"""
grafeas.proto
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: v1beta1
Generated by: https://github.c... | StarcoderdataPython |
3344891 | import tensorflow as tf
from gcg.tf.layers.fullyconnectednn.fully_connected import FullyConnected
##################
### Operations ###
##################
def linear(args, output_size, dtype=tf.float32, scope=None, trainable=True):
with tf.variable_scope(scope or "linear"):
if isinstance(args, list) or ... | StarcoderdataPython |
51336 | <reponame>agolovkina/sdk-python<filename>ambra_sdk/service/entrypoints/generated/session.py
""" Session.
Do not edit this file by hand.
This is generated by parsing api.html service doc.
"""
from ambra_sdk.exceptions.service import AuthFailed
from ambra_sdk.exceptions.service import BadPassword
from ambra_sdk.exceptio... | StarcoderdataPython |
3259531 | import re
import subprocess
from ...exc import BleakError
def check_bluez_version(major: int, minor: int) -> bool:
"""
Checks the BlueZ version.
Returns:
``True`` if the BlueZ major version is equal to *major* and the minor
version is greater than or equal to *minor*, otherwise ``False``... | StarcoderdataPython |
173031 | import datetime
from mantabot import command
class Clear(command.Command):
""" Bot command that deletes messages """
name = 'clear'
errors = {
'usage': '{name} <number>|<text>|me\n'
'→ *<number>*: clear that many messages.\n'
'→ *<text>*: clear all messages since... | StarcoderdataPython |
3235285 | # _*_ coding:utf-8 _*_
import tensorflow as tf
class Network:
r"""网络结构,2个隐藏层,1个输出层,第一个隐藏层有500个神经元,第二层有100个,输出层10个,并附带检验方法
学习率0.01
激活函数:Relu
损失函数:交叉熵
优化器:AdagradOptimizer(改良型梯度下降)
"""
def __init__(self,datasize:int,labelsize:int)->None:
r"""构造网络计算图,输入参数为训练集数据大小和对应标签(独热码)大小
... | StarcoderdataPython |
1697788 | from sympy import symbols, sin, pi, latex
from ga import Ga
from printer import Format, xpdf
Format()
coords = (r, th, phi) = symbols('r,theta,phi', real=True)
sp3d = Ga('e_r e_th e_ph', g=[1, r**2, r**2*sin(th)**2], coords=coords, norm=True)
sph_uv = (u, v) = symbols('u,v', real=True)
sph_map = [1, u, v] # Coordina... | StarcoderdataPython |
1764441 | from jssp_ga import jssp_instance
class Schedule:
def __init__(self, schedule, jssp_instance):
self.schedule = schedule
self.decomposed_tasks = self.decompose_tasks(jssp_instance)
self.task_durations = {}
self.get_task_times()
def __getitem__(self, index):
return self.... | StarcoderdataPython |
1764110 | # Copyright 2021. ThingsBoard
#
# 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 ... | StarcoderdataPython |
3276737 | from dataclasses import asdict, dataclass
from logging import Logger
from torch.optim.adam import Adam # pylint: disable=no-name-in-module
from src.core.common.checkpoint import Checkpoint
from src.core.waveglow.hparams import HParams
from src.core.waveglow.model import WaveGlow
@dataclass
class CheckpointWaveglow... | StarcoderdataPython |
3261706 | #!/usr/bin/env python
# -*- coding: utf-8 -*-#
#-------------------------------------------------------------------------------
# Name: main
# Description: the entrance of procedure
# Author: <NAME>
# Date: 2021/08/06
#----------------------------------------------------------------------------... | StarcoderdataPython |
1775544 | '''
Created on 19 fvr. 2019
@author: <NAME>
'''
class Mention:
'''
classdocs
'''
def __init__(self, name, context, e_type, sentence_words):
'''
Constructor
'''
self.name= name
self.context= context
self.e_type= e_type
self.senten... | StarcoderdataPython |
195599 | #!/usr/bin/env python
# coding: utf-8
"""
Generate random data for your application
"""
import argparse, logging, importlib
from echolalia.generator import Generator
def add_args():
parser = argparse.ArgumentParser(
description='Generate random data for your application')
parser.add_argument('-w', '--writer'... | StarcoderdataPython |
3208192 | <reponame>Starrah/THU-SuperMoon
import os.path as osp
from itertools import product
from random import shuffle
import numpy as np
import openslide
from tqdm import tqdm
from scipy import ndimage
from skimage.filters import threshold_otsu
from skimage.morphology import dilation, star
BACKGROUND = 0
FOREGROUND = 1
de... | StarcoderdataPython |
3233976 | <gh_stars>100-1000
# Copyright 2017, <NAME>, All rights reserved.
class AppError(Exception):
"""
Exception indicating an error
"""
pass
class ServiceExit(AppError):
"""
Custom exception which is used to trigger the clean exit
of all running threads and the main program.
"""
pass
... | StarcoderdataPython |
1646535 | <reponame>SEQUOIIA/shipment-tracker
from sys import exit
class Provider:
def __init__(self):
self.name = ""
@staticmethod
def getProgress(shippingCode):
print("getProgress not implemented for provider yet.")
exit(1)
class ShipmentProgress:
def __init__(self):
self.stat... | StarcoderdataPython |
3270816 | <filename>Engine/ScanRing.py
def ScanRing(RingPositions, HOOK_OPTION):
NoHasRing = [0, 0]
if HOOK_OPTION == 0:
import pyautogui
NoHasRing = pyautogui.locateOnScreen('images/PlayerStats/NoRing.png', confidence=0.9, region=(
RingPositions[0], RingPositions[1], RingPositions[2], RingPo... | StarcoderdataPython |
4814635 | """Contains utilities for handling dimensions."""
import logging
import math
from copy import deepcopy
from typing import Any, List, Optional, Tuple, TypedDict, Union
import numpy as np # type: ignore[import]
import pandas as pd # type: ignore[import]
CatBin = Union[str, pd.Interval]
def analyze_data_type(data_... | StarcoderdataPython |
88147 | <gh_stars>0
# coding: utf-8
"""
Cloudbreak API
Cloudbreak is a powerful left surf that breaks over a coral reef, a mile off southwest the island of Tavarua, Fiji. Cloudbreak is a cloud agnostic Hadoop as a Service API. Abstracts the provisioning and ease management and monitoring of on-demand clusters. Sequen... | StarcoderdataPython |
1778776 | <reponame>p01arst0rm/twelete
__version__ = '1.1.0'
__author__ = 'polar'
__license__ = 'MIT'
from Twelete.main import twelete
| StarcoderdataPython |
3293975 | from django.contrib import admin
from .models import FirstAnswerReview,FirstQuestionReview
from .models import LateAnswerReview
# from .models import QuestionEdit
from .models import CloseQuestionVotes, ReviewQuestionReOpenVotes
from .models import ReviewCloseVotes,ReOpenQuestionVotes,QuestionEditVotes
from .models im... | StarcoderdataPython |
1657034 | <reponame>claresloggett/ponder-gittest
'''
Utilities for testing.
'''
import pandas as pd
def parse_test_df(f):
'''
Given a filehandle or filename for a CSV file,
return the dataframe, assuming our standard dtypes
for standard column names.
'''
df = pd.read_csv(f)
df['Boolean'] = df['Bool... | StarcoderdataPython |
3248886 | <gh_stars>0
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/02_tabular.preprocessing.ipynb (unless otherwise specified).
__all__ = ['EnvecoPreprocessor', 'process_one']
# Cell
from fastai.tabular.all import *
from fastai.data.all import *
from fastai.vision.data import get_grid
from ..data.las import *
from ..data.im... | StarcoderdataPython |
160486 | <filename>tests/0800_builder/06_build.py
import io
import importlib
import os
import shutil
import pytest
from optimus.setup_project import setup_project
from optimus.conf.loader import import_pages_module
from optimus.pages.builder import PageBuilder
from optimus.assets.registry import register_assets
def DummyFil... | StarcoderdataPython |
3215981 | import argparse
import os
from decouple import config
from rasa.core.nlg import TemplatedNaturalLanguageGenerator, NaturalLanguageGenerator
from rasa.utils.endpoints import EndpointConfig
from sanic import Sanic, response
from rasa.constants import ENV_SANIC_BACKLOG, DEFAULT_SANIC_WORKERS
import logging
from rasa.shar... | StarcoderdataPython |
3295373 | <filename>easy/Merge Sorted Array/solution.py
# Time complexity: O(m+n)
# Approach: Imputing values from end
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
if not n:
... | StarcoderdataPython |
1604201 | <gh_stars>0
import json
import os
from datetime import datetime
from requests_oauthlib import OAuth1Session
# Set up OAuth against Telldus Live API
telldus_oauth1_session = os.environ.get('TELLDUS_OAUTH1_SESSION')
telldus_client_secret = os.environ.get('TELLDUS_CLIENT_SECRET')
telldus_resource_owner_key = os.environ.g... | StarcoderdataPython |
1619027 | <gh_stars>0
# 管理技术的比较
"""
注意
def __getattribute__(self, name):
x = object.__getattribute__(self, 'other')
def __setattr__(self, name, value):
self.__dict__['other'] = value
def __setattr__(self, name, value):
object.__setattr__(self, 'other', value)
"""
# property描述符实现
class Powers:
def __init__(sel... | StarcoderdataPython |
196397 | """Predict with the most-common-label algorithm."""
import argparse
import logging
from pathlib import Path
import muspy
import numpy as np
import tqdm
from arranger.utils import (
load_config,
reconstruct_tracks,
save_sample_flat,
setup_loggers,
)
# Load configuration
CONFIG = load_config()
def pa... | StarcoderdataPython |
1659108 | #!/usr/bin/env python
"""Reliable executor for intermittently failing functions"""
import functools
import time
def reliably_execute(
partial_function: functools.partial,
*,
retry: int=3,
wait: int=5,
):
"""Helper function to reliably execute the provided partial function"""
re... | StarcoderdataPython |
1667305 | <filename>script/maeplot/utils.py<gh_stars>1-10
import os
import errno
import math
def msecToMin(msec):
return float(msec) / 60000.0
def usecToMin(usec):
return msecToMin(usec / 1000)
def coverageToPercent(cov):
return cov * 100
def sameFloat(a, b, eps):
return abs(a - b) <= eps;
def mkdirRec(direc... | StarcoderdataPython |
1749934 | <reponame>variable/todobackend
from django.contrib import admin
from .models import TODOItem
class TODOItemAmin(admin.ModelAdmin):
list_display = ['uuid', 'session_id', 'description', 'priority', 'created_at', 'completed_at']
admin.site.register(TODOItem, TODOItemAmin)
| StarcoderdataPython |
69531 | <reponame>stakira/ENUNU
#!/usr/bin/env python3
# Copyright (c) 2022 oatsu
"""
timelagとdurationをまとめて実行する。
MDN系のdurationが確率分布を持って生成されるため、フルラベルにしづらい。
そのため、timelagとdurationをファイル出力せずにtimingまで一気にやる。
"""
import hydra
import joblib
import numpy as np
import torch
from hydra.utils import to_absolute_path
from nnmnkwii.io impor... | StarcoderdataPython |
114266 | <gh_stars>0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def LF_flux(FL, FR, lmax, lmin, UR, UL, dt, dx):
ctilde = dx / dt
return 0.5 * (FL + FR) - 0.5 * ctilde * (UR - UL)
| StarcoderdataPython |
44445 |
from thaniya_server_sudo import SudoScriptRunner
from thaniya_server.usermgr import BackupUserManager
from thaniya_server.sysusers import SystemAccountManager
class IUploadSlotContext:
@property
def backupUserManager(self) -> BackupUserManager:
raise NotImplementedError()
#
@property
def sudoScriptRunne... | StarcoderdataPython |
3255827 | <reponame>kurli/chromium-crosswalk
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'variables': {
'chromium_code': 1,
},
'includes': [
'../native_client/build/untrusted.gypi',
'nacl/nac... | StarcoderdataPython |
3386823 | """
Helper functions for missing functionality in cupy.
"""
try:
import cupy as xp
from cupyx.scipy.special import erf, gammaln
CUPY_LOADED = True
except ImportError:
import numpy as xp
from scipy.special import erf, gammaln
CUPY_LOADED = False
def betaln(alpha, beta):
r"""
Logarith... | StarcoderdataPython |
189024 | """Controller holding and managing HUE resources of type `scene`."""
from typing import Optional, Type, Union
from ..models.feature import DimmingFeaturePut, RecallAction, RecallFeature
from ..models.resource import ResourceTypes
from ..models.room import Room
from ..models.scene import Scene, ScenePut
from ..models.z... | StarcoderdataPython |
3306735 | import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.express as px
import pandas as pd
import requests
import json
from app import app
base_url = 'https://api.pro.coinbase.com/products/{}/candles?granularity=86400'
def getBTCData(currency):
... | StarcoderdataPython |
1634231 | #!/usr/bin/env python
"""
inspiration.
* https://github.com/eightBEC/fastapi-ml-skeleton/tree/master/fastapi_skeleton
(APACHE 2.0)
* https://github.com/leosussan/fastapi-gino-arq-uvicorn
(PUBLIC DOMAIN)
"""
from fastapi import FastAPI
from fast_microservice.helpers import MiddlewareWrapper
from fast_microservice.ro... | StarcoderdataPython |
75198 | <reponame>GDGSNF/PXXTF<filename>core/postex.py
#!/usr/bin/python
import os, sys, subprocess, bs4,signal,requests
import core
from urllib.parse import quote
from socket import timeout
from urllib.request import urlopen
from urllib.request import Request
import readline, rlcompleter
from sys import argv
from subprocess ... | StarcoderdataPython |
110239 | <gh_stars>1-10
#!/usr/bin/env python
from application import router
if __name__ == '__main__':
router.app.run(host="0.0.0.0", port=8000, debug=True)
| StarcoderdataPython |
1679221 | <reponame>vanminhdev/kcsg
from queue import Queue
from threading import Timer
class ScanningMonitor:
scanning_interval = 5
local_interval = 5
changed_quantity = {
'old': 0,
'now': 0
}
max_size_queue = 3
last_times_v = Queue(max_size_queue)
@staticmethod
def check_chang... | StarcoderdataPython |
3306128 | <reponame>ISISComputingGroup/EPICS-DeviceEmulator
from collections import OrderedDict
from .states import DefaultState
from lewis.devices import StateMachineDevice
from random import random as rnd
class SimulatedTtiplp(StateMachineDevice):
def _initialize_data(self):
"""
Initialize all of the dev... | StarcoderdataPython |
165132 | # coding: utf-8
from django.contrib import admin
from django.utils.safestring import SafeString as _S
from django.utils.html import format_html
from ordered_model.admin import OrderedModelAdmin
from ordered_model.admin import OrderedTabularInline
from mptt.admin import MPTTModelAdmin
from mptt.forms import TreeNodeChoi... | StarcoderdataPython |
1746533 | from typing import TYPE_CHECKING, Any
from dis_snek.const import MISSING, Absent
from dis_snek.models.route import Route
from dis_snek.utils.serializer import dict_filter_missing
if TYPE_CHECKING:
from dis_snek.models.snowflake import Snowflake_Type
class ReactionRequests:
request: Any
async def create... | StarcoderdataPython |
1634944 | <reponame>Fireman730/python-eveng-api
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Description ...
"""
__author__ = "<NAME>"
__maintainer__ = "<NAME>"
__version__ = "1.0"
__email__ = "<EMAIL>"
__status__ = "Production"
__copyright__ = "Copyright 2019"
__license__ = "MIT"
#####################################... | StarcoderdataPython |
67087 | <filename>openproblems/api/load.py
from . import utils
def load_dataset(task_name, function_name, test):
"""Load a dataset for a task."""
fun = utils.get_function(task_name, "datasets", function_name)
return fun(test=test)
def main(args):
"""Run the ``load`` subcommand."""
adata = load_dataset(a... | StarcoderdataPython |
3210645 | <reponame>stas00/pytorch-lightning
# Copyright The PyTorch Lightning team.
#
# 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 requir... | StarcoderdataPython |
3395089 | <gh_stars>0
#!/usr/bin/env python3
def print_hello():
print("Hello!")
| StarcoderdataPython |
188742 | import json
import mimetypes
import os
from aws_xray_sdk.core import patch
import boto3
from boto3.dynamodb.conditions import Key
from botocore.client import Config
patch(["boto3"])
TABLE_NAME = os.getenv('TABLE_NAME')
NOT_FOUND = {
"isBase64Encoded": False,
"statusCode": 404,
"body": json.dumps({'messa... | StarcoderdataPython |
102330 | l, r = map(int, input().split())
mod = 10 ** 9 + 7
def f(x):
if x == 0:
return 0
res = 1
cnt = 2
f = 1
b_s = 2
e_s = 4
b_f = 3
e_f = 9
x -= 1
while x > 0:
if f:
res += cnt * (b_s + e_s) // 2
b_s = e_s + 2
e_s = e_s + 2 * (4 * ... | StarcoderdataPython |
3246984 | <filename>test/core/plugins/__init__.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author: <EMAIL>
# datetime: 2021/10/22 下午2:56
# project: DongTai-engine
| StarcoderdataPython |
3328712 | <gh_stars>1-10
#!/usr/bin/python2
#-*- coding:utf-8 -*-
#Samba 3.0.20 < 3.0.25rc3 - 'Username' map script' Command Execution
import os
import time
import socket
import platform
import sys
import threading
try:
from datetime import datetime
except ImportError:
print("[*] Module Datetime Not Found !")
try:
... | StarcoderdataPython |
3394094 | <reponame>njoanc/Instagram
from django.db import models
from django.contrib.auth.models import User
import datetime as dt
from django.db.models.signals import post_save
from django.dispatch import receiver
from tinymce.models import HTMLField
class Profile(models.Model):
user = models.OneToOneField(User,on_delete... | StarcoderdataPython |
168036 | <reponame>jaredhoberock/cuda_graphs_executor_prototypes
#!/usr/bin/env python3
import sys
import os
import subprocess
import numpy
endpoints = numpy.logspace(3, 8.66, 10)
sizes = []
start = 1
for end in endpoints:
points = numpy.linspace(start, end, 10, endpoint = False)
sizes.extend([int(pt) for pt in points])
... | StarcoderdataPython |
3245312 | class Solution:
def minimumDistance(self, word: str) -> int:
keyboard = [None] * 256
ncols = 6
word = [ord(ch) for ch in word]
for ch in string.ascii_uppercase:
idx = ord(ch) - ord('A')
r, c = idx // ncols, idx % ncols
keyboard[ord(ch)] = (r, c)
... | StarcoderdataPython |
3333956 | #######################################################
#
# Teams.py
# Python implementation of the Enumeration Teams
# Generated by Enterprise Architect
# Created on: 04-Nov-2020 4:43:17 PM
# Original author: natha
#
#######################################################
class Teams:
# default constructor d... | StarcoderdataPython |
53596 | import re
from arqtty_scrapper.page_types import Page_types
class Classifier:
def __init__(self, page_str):
self.page = page_str
def _is_404(self):
marker1 = 'Ой, ой, страничка потерялась'
marker2 = 'Спокойно! Логи записаны. Все будет исправлено.'
return re.search(marker1, se... | StarcoderdataPython |
1688374 | <filename>edge_tpu/video_object_detection.py<gh_stars>0
# Copyright 2019 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unl... | StarcoderdataPython |
15437 | # -*- coding: utf-8 -*-
"""
Created on Fri Aug 9 15:33:47 2019
@author: Bogoclu
"""
import typing
import multiprocessing as mp
import warnings
import numpy as np
from scipy import stats
from .space import FullSpace
from duqo.proba import DS, MC, SUSE, ISPUD, FORM
from duqo.doe.lhs import make_doe
def _check_obj_w... | StarcoderdataPython |
3260103 | <gh_stars>0
from django.utils.functional import cached_property
from waldur_core.structure.tests.fixtures import ProjectFixture
from . import factories
class AWSFixture(ProjectFixture):
@cached_property
def service(self):
return factories.AWSServiceFactory(customer=self.customer)
@cached_prope... | StarcoderdataPython |
3276276 | <reponame>altazur/PythonAutomationExamples
import pytest
def test_soap_calc_add(get_calculator, soap_version):
assert get_calculator.add(1,5, soap_version) == str(6)
| StarcoderdataPython |
1768980 | import logging
from urllib.parse import urlparse
logger = logging.getLogger(__name__)
def is_s3_url(url):
"""
Check if url is an s3, s3n, or s3a url
"""
try:
return urlparse(url).scheme in ["s3", "s3n", "s3a"]
except ValueError:
return False
def create_s3_bucket_if_not_exists(bu... | StarcoderdataPython |
1767752 | <reponame>scionrep/scioncc_new
__author__ = '<NAME> <<EMAIL>>'
from nose.plugins.attrib import attr
import time
import datetime
try:
import numpy as np
except ImportError:
np = None
from pyon.util.unit_test import PyonTestCase
from ion.util.ntp_time import NTP4Time
@attr('UNIT')
class NTP4TimeUnitTest(PyonT... | StarcoderdataPython |
120421 | <filename>data/retail-rfm.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#%%: import libraries
import pandas as pd
import numpy as np
import datetime as dt
import seaborn as sns
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
from sqlalchemy import create_engine
import matplotlib.pyplot as ... | StarcoderdataPython |
19477 | <filename>WD/Cwiczenia/rzymskie.py
rzymskie={'I':1,'II':2,'III':3,'IV':4,'V':5,'VI':6,'VII':7,'VIII':8}
print(rzymskie)
print('Jeden element slownika: \n')
print(rzymskie['I'])
| StarcoderdataPython |
2301 | <reponame>gribbg/x7-geom
"""
Simple file to validate that maketests is working. Call maketests via:
>>> from x7.shell import *; maketests('x7.sample.needs_tests')
"""
def needs_a_test(a, b):
return a+b
| StarcoderdataPython |
23352 | from go.apps.tests.view_helpers import AppViewsHelper
from go.base.tests.helpers import GoDjangoTestCase
class TestHttpApiViews(GoDjangoTestCase):
def setUp(self):
self.app_helper = self.add_helper(AppViewsHelper(u'http_api'))
self.client = self.app_helper.get_client()
def test_show_stopped(... | StarcoderdataPython |
150184 | """
Models for testing various aspects of the djang.contrib.admindocs app
"""
from django.db import models
class Company(models.Model):
name = models.CharField(max_length=200)
class Group(models.Model):
name = models.CharField(max_length=200)
class Family(models.Model):
last_name = models.CharField(m... | StarcoderdataPython |
9595 | """ docnado.py
A rapid documentation tool that will blow you away.
"""
import os
import re
import sys
import csv
import glob
import time
import signal
import shutil
import urllib
import base64
import hashlib
import argparse
import tempfile
import datetime
import threading
import traceback
import subprocess
import pl... | StarcoderdataPython |
85070 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 16 09:57:44 2017
@author: hao
"""
import numpy as np
import matplotlib.pyplot as plt
# In[]
# 4.1.1 The Normal Equation
X = 2 * np.random.rand(100, 1) # generate a 100*1 array
y = 4 + 3 * X + np.random.randn(100, 1)
X_b = np.c_[np.ones((100, 1)), X] # add x0 = 1 to eac... | StarcoderdataPython |
1633461 | #!/bin/python3
import sys
def to_arr(num):
arr = []
while num != 0:
arr.append(num % 10)
num = int(num / 10)
arr.reverse()
return arr
t = int(input().strip())
for a0 in range(t):
n = int(input().strip())
arr = to_arr(n)
num_div = 0
for i in range(0, len(arr)):
... | StarcoderdataPython |
3249601 | <filename>server/src/weblab/core/webclient/web/view_index.py
import traceback
from flask import render_template, request, flash, redirect, url_for, make_response
from weblab.core.login.exc import InvalidCredentialsError
from weblab.core.webclient.web.helpers import safe_redirect
from weblab.core.wl import weblab_api
f... | StarcoderdataPython |
3214169 | # SETUP
#
# Refs
# https://github.com/UKPLab/sentence-transformers
# https://towardsdatascience.com/nlp-extract-contextualized-word-embeddings-from-bert-keras-tf-67ef29f60a7b
# https://towardsdatascience.com/bert-for-dummies-step-by-step-tutorial-fb90890ffe03
# Standard includes
import csv
import pickle
import pandas ... | StarcoderdataPython |
3253171 | <gh_stars>0
# import urllib.request
import re
import os
import collections
import math
import sys
# import lxml
# from lxml import html
import requests
import time
from datetime import datetime
HTML_PREFIX = """\
<html>
<head>
<title>SIGGRAPH Word Clouds</title>
<meta name="author" content="<... | StarcoderdataPython |
69087 | <filename>tictactoe.py
#!/usr/bin/env python
# coding=utf-8
__author__ = 'Xevaquor'
__license__ = 'MIT'
from copy import deepcopy
import random
from minmax import MinmaxAgent
from common import Field
class RandomAgent(object):
def __init__(self, symbol=Field.Circle):
self.symbol = symbol
def make_m... | StarcoderdataPython |
3297201 | from evaluation.inception import InceptionScore
import re
import cv2
import numpy as np
import pandas as pd
import matplotlib
from sg2im.data import deprocess_batch, imagenet_deprocess
from sg2im.data.utils import decode_image
matplotlib.use('Agg')
from sg2im.meta_models import MetaGeneratorModel
import argparse, os
im... | StarcoderdataPython |
3335800 | """
reset database
"""
from patch_tracking.app import app
from patch_tracking.database import reset_database
def reset():
"""
reset database
"""
with app.app_context():
reset_database()
if __name__ == "__main__":
reset()
| StarcoderdataPython |
30179 | import itertools
import math
import pprint
import sys
import typing
import map_funcs
GOOGLE_EARTH_AIRPORT_IMAGES = {
'GoogleEarth_AirportCamera_C.jpg' : {
'path': 'video_images/GoogleEarth_AirportCamera_C.jpg',
'width': 4800,
'height': 3011,
# Originally measured on the 100m legend... | StarcoderdataPython |
89385 | <reponame>EricFelixLuther/quiz_app<gh_stars>0
from django.contrib import admin
from .models import Quiz_Set, Question
admin.site.register([Quiz_Set, Question])
| StarcoderdataPython |
1641861 | #!/usr/bin/python2.7
# -*- coding: utf-8 -*-
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
# 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
... | StarcoderdataPython |
28765 | """
Re-running de novo assembly, this time including reads that map to mobile elements.
"""
import os
import sys
# Setup Django environment.
sys.path.append(
os.path.join(os.path.dirname(os.path.realpath(__file__)), '../'))
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from Bio import SeqIO
from experim... | StarcoderdataPython |
1620580 | <gh_stars>10-100
# -*- coding: utf-8 -*-
"""
Test on 1d function
"""
import warnings
warnings.filterwarnings("ignore")
import pytest
import numpy as np
import matplotlib
matplotlib.use('agg')
from nextorch import plotting, bo, utils
from nextorch.parameter import Parameter
def simple_1d(X):
"""1D function y = (... | StarcoderdataPython |
3310782 | # -*- coding: utf-8 -*-
"""Utility functions for mirdata
Attributes:
NoteData (namedtuple): `intervals`, `notes`, `confidence`
F0Data (namedtuple): `times`, `frequencies`, `confidence`
LyricData (namedtuple): `start_times`, `end_times`, `lyrics`, `pronounciations`
SectionData (namedtuple): `start_t... | StarcoderdataPython |
3366179 | from django.db import models
class TreeQuerySet(models.query.QuerySet):
def get_descendants(self, *args, **kwargs):
return self.model.objects.get_queryset_descendants(self, *args, **kwargs)
get_descendants.queryset_only = True
def get_ancestors(self, *args, **kwargs):
return self.model.obj... | StarcoderdataPython |
1714423 | # encoding: utf-8
# 处理 var125-126
import pandas as pd
import re
# 区号
code_df = pd.read_csv("../../data/area_code.csv", encoding='gbk')
code_dict = {}
for i in range(0, len(code_df)):
code_dict.update({code_df['区号'][i]: code_df['城市'][i]})
# 省名
provinces = ('河北', '山西', '辽宁', '吉林', '江苏', '浙江', '安徽', '福建',
... | StarcoderdataPython |
3253477 | <filename>model_zoo/research/cv/dem/src/config.py<gh_stars>1-10
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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/license... | StarcoderdataPython |
3355354 | import torch.nn as nn
import ipdb
class Bottleneck(nn.Module):
expansion = 4
only_2D = False
def __init__(self, inplanes, planes, stride=1, downsample=None, dilation=1):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv3d(inplanes, planes, kernel_size=1, bias=False)
self.bn1... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.