id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
5010610 | from typing import Any, Awaitable, Callable
from xpresso.openapi.models import SecurityScheme
class SecurityBase:
model: SecurityScheme
scheme_name: str
__call__: Callable[..., Awaitable[Any]]
| StarcoderdataPython |
3263398 | <filename>visualize.py
import matplotlib.pyplot as plt
import pickle
history = pickle.load(open("history.p", "rb"))
print(history)
# Plot the training and validation loss for each epoch
plt.plot(history['loss'])
plt.plot(history['val_loss'])
plt.title('model mean squared error loss')
plt.ylabel('mean squared error ... | StarcoderdataPython |
8036317 | """Tests for zookeeper_remove_locks.py"""
import unittest
import os
import logging
from mock import patch, Mock
from lib.ingest.zookeeper_remove_locks import ZookeeperLocks
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
class ZookeeperLocksFunctionsTest(unittest.TestCase):
"""Tests."""
def setUp(sel... | StarcoderdataPython |
3522152 | import random
a1 = str(input('Primeiro aluno: '))
a2 = str(input('Segundo aluno: '))
a3 = str(input('Terceiro aluno: '))
a4 = str(input('Quarto aluno: '))
lista = [a1, a2, a3, a4]
aa = random.sample(lista, 4)
print(f'O aluno escolhido é {aa}') | StarcoderdataPython |
6657991 | <reponame>haradashinya/cloud_logger<filename>cloud_logger/__init__.py
import datetime
import logging
import os
import time
import uuid
import json
import boto3
from io import StringIO
class CloudLoggerObject:
def __init__(self, format, name, **kwargs):
self.name = name
self.format = format
... | StarcoderdataPython |
3326922 | # test fbchat api
import sys
from unittest.mock import patch
from pathlib import Path
import pytest
from postr import fbchat_api
from postr import config
sys.path.insert(0, '../postr')
my_file = Path('../postr_config.ini')
if not my_file.is_file():
pytest.skip('If there is no config_file, then all these tests wi... | StarcoderdataPython |
1754601 | <filename>test/test_converter_v3.py<gh_stars>0
import io
from lxml import objectify
import pathlib
import pytest
import tempfile
from hpxml_version_translator.converter import (
convert_hpxml3_to_4,
convert_hpxml_to_version,
)
from hpxml_version_translator import exceptions as exc
hpxml_dir = pathlib.Path(__... | StarcoderdataPython |
3515253 | from rest_framework import serializers
from .models import DynatraceConfiguration
class DynatraceConfigurationSerializer(serializers.ModelSerializer):
class Meta:
model = DynatraceConfiguration
fields = ("id", "base_url", "api_key", "entity_selector")
| StarcoderdataPython |
8162055 | import torch
from torch import nn
import torchvision.models as models
import os
from config import DATA_PATH
import pickle
import bcolz
model_names = sorted(name for name in models.__dict__
if name.islower() and not name.startswith("__")
and callable(models.__dict__[name]))
class Identity(nn.Module):
"""... | StarcoderdataPython |
399612 | <filename>demos/org.python3.11.0/static/org.python3.11.0.py<gh_stars>1-10
# suspicious or too slow
# test.test_fileio.PyAutoFileTests.testReadintoByteArray
# test.test_mimetypes.MimetypesCliTestCase.test_invalid_option
# test.test_getpath.MockGetPathTests.test_registry_win32 ?????? picke error on module obj
SLOW=""... | StarcoderdataPython |
5197801 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
from bs4 import BeautifulSoup
'''
功能:基于http的可目录浏览网站文件的递归下载
'''
#baseurl="http://10.166.7.151/docs/powerui2"
baseurl="http://10.166.7.151/docs/jquery-easyui-1.4.2"
def getpginfo(url,path):
headers = {'Accept': 'text/html,applic... | StarcoderdataPython |
8042388 | # Copyright 2016-2022 The <NAME> Lab at the California Institute of
# Technology (Caltech), with support from the Paul Allen Family Foundation,
# Google, & National Institutes of Health (NIH) under Grant U24CA224309-01.
# All rights reserved.
#
# Licensed under a modified Apache License, Version 2.0 (the "License");
# ... | StarcoderdataPython |
5095543 | import numpy as np
import torch
from torch import Tensor
def rand_bbox(size, lam):
W = size[2]
H = size[3]
cut_rat = np.sqrt(1. - lam)
cut_w = np.int(W * cut_rat)
cut_h = np.int(H * cut_rat)
# uniform
cx = np.random.randint(W)
cy = np.random.randint(H)
bbx1 = np.clip(cx - cut_w //... | StarcoderdataPython |
6667384 | <gh_stars>100-1000
#!/usr/bin/env python3
"""
Simple script to convert .org url lines to .md urls
+ [[http://www.h4labs.com][h4labs]]
to
+ [h4labs](http://www.h4labs.com)
If the line doesn't match, simply print the line.
bin/org_url2md.py haskell.md
"""
import os
import sys
import re
prog = re.compile(r"\+ \[\[(.... | StarcoderdataPython |
353626 | from connection import client
class My_mongo():
"""
My mongodb manager that i made to learn how to interract with mongodb using pymongo.
Currently supports creating collection,showing collections, inserting single/multi elements
finding/deleting/showing elements.
"""
def __init__(self, db_nam... | StarcoderdataPython |
1639580 | <filename>alldigitalradio/hardware/qmtech_wukong.py<gh_stars>0
from alldigitalradio.io.xilinx_gtp import XilinxGTPSerdes
from nmigen.build import Resource, Pins, Attrs
def load():
from boards.qmtech_wukong import Platform as wukong
wukong.resources += [
Resource("clk_n", 0, Pins("AB13", dir="i")),
... | StarcoderdataPython |
5199016 | <reponame>Pallagani-Praveen/CodeSignal
# Question Link : https://app.codesignal.com/challenge/LNukgzSzfY88RzNjF
# Level : Easy
# Solution is right below:-
def boxBlur(image):
def helper(image,i,j):
r_one = image[i-1][j-1]+image[i-1][j]+image[i-1][j+1]
r_two = image[i][j-1]+image[i][j]+image[i][j+1]... | StarcoderdataPython |
6626153 | import argparse
import random
from datetime import timedelta
from operator import getitem
from os import listdir, makedirs, remove
from os.path import join, exists, getsize
import h5py
import librosa
import numpy as np
import pandas as pd
import soundfile as sf
from python_speech_features import mfcc
from scipy.io imp... | StarcoderdataPython |
11213103 | # webcam.py
import cv2
import time
import ipdb
from object_detection.object_detection import ObjDet
from pose_estimation.pose_estimation import Pose
from activity_recognition.activity_recognition import ActRec
from distance import get_shoulder_dist_from_pe, get_obj_obj_dist
class TimeMeter():
''' Handle time meas... | StarcoderdataPython |
9764836 | #!/usr/bin/env python
# Density_Sampling/Density_Sampling.py
# Author: <NAME> for the GC Yuan Lab
# Affiliation: Harvard University
# Contact: <EMAIL>, <EMAIL>
"""For a data-set comprising a mixture of rare and common populations,
density sampling gives equal weights to selected representatives
of those distinct p... | StarcoderdataPython |
3569636 | #!/usr/bin/env python3
import argparse
import cfg_sample
import csv
import random
def main(args):
data = list(import_proverb_dataset(args.dataset))
print(f"tags: {args.tags}")
print(f"Datalen {len(data)}. Example: {data[0]}")
print(data[0:20])
def gen_hint_combos(tags, chance):
hint_promp... | StarcoderdataPython |
9705609 | from nlptools.preprocessing import *
# Use doQuoteNormalization to normalize all quotation to ASCII ' and " chars:'
t = "« Hello World » I’m ``Mick´´"
print(preprocess(t, doQuoteNormalization=True))
# Remove the html and unescape the html:
t = "Hello <span>World</span>! ><"
print(preprocess(t, removeHtml=True, ... | StarcoderdataPython |
4972788 | import os
import fnmatch
def getFileList(path_to_folder):
matches = []
for root, dirnames, filenames in os.walk(path_to_folder):
for filename in fnmatch.filter(filenames, '*.*'):
matches.append(os.path.join(root, filename))
return matches | StarcoderdataPython |
4999496 | from fastapi.exceptions import HTTPException
from fastapi import APIRouter, status, Body, Depends
from fastapi.encoders import jsonable_encoder
from fastapi.security import HTTPBasicCredentials
from app.models.common import *
from app.models.user import *
from app.database.crud.user import *
from app.database.crud.br... | StarcoderdataPython |
4921588 | <reponame>tageerBOY/discord_py<filename>plugins/Example1/program.py
#Plugin1
#me
#v1.0.0
@bot.command()
async def test(ctx):
print('test')
#Plugin1 | StarcoderdataPython |
6489779 | """
Listas Aninhadas
- Algumas linguagens de programação possuem uma estrutura de dados chamadas de arrays:
- Unidimensionais (Arrays/Vetores);
- Multidimensionais (Matrizes);
Em Python nós temos as Listas
numeros = [1, 'b', 3.234, True, 5]
print(listas)
print(type(listas))
# Exemplos
listas =... | StarcoderdataPython |
5130612 | from psireporter.worker import Report
import platform, calendar
from datetime import datetime
class PsistatsReport(Report):
def __new__(cls, **kwargs):
return tuple.__new__(cls, (
kwargs.get('id', platform.node()),
kwargs.get('message', None),
kwargs.get('sender', None),... | StarcoderdataPython |
9665543 | <filename>pyluos/__init__.py
import logging
from .device import Device
from .services import *
nh = logging.NullHandler()
logging.getLogger(__name__).addHandler(nh)
| StarcoderdataPython |
170021 | <filename>services/web/api/db_threads.py
import os
import uuid
from common.dbinstance import DbInstance
from common.s3client import S3Client
def select_threads(board_id, limit, offset):
# prepare result
result = {
'status': 404,
'data': []
}
# fetch rows from db
with DbInstance().get_instance().curs... | StarcoderdataPython |
11213744 | <filename>setup.py
from setuptools import setup, find_packages
setup(
name='gym_trainer',
packages=find_packages('gym_trainer'),
author='<NAME>',
version='0.1.0',
install_requires=[
'gym==0.10.9', 'matplotlib==3.0.2', 'chainer==5.1.0', 'cupy==5.1.0', 'torch==1.0.0', 'torchvision==0.2.1',
... | StarcoderdataPython |
1836411 | <gh_stars>0
from django.apps import AppConfig
class RelationshipsConfig(AppConfig):
name = 'relationships'
| StarcoderdataPython |
6547818 | import urllib.request
import string
import random
import project
from os import path
import json
from PIL import Image
def get_schedule_path() -> str:
return f"{project.get_dir()}/scheduled.json"
def load() -> dict:
file = get_schedule_path()
if path.exists(file):
with open(file, 'r') as fp:
... | StarcoderdataPython |
11327013 | <gh_stars>1-10
import os
import unittest
from conans.model.ref import ConanFileReference
from conans.paths import EXPORT_SOURCES_DIR_OLD
from conans.test.utils.test_files import temp_folder
from conans.test.utils.tools import TestClient, TestServer
from conans.util.files import tar_extract
class DoNotKeepOldExportSo... | StarcoderdataPython |
3202205 | <filename>template_server_serializer.py
import discord
def getPermissionJson(name, value):
return {
"permissionName": name,
"allow": value
}
def getCategoryJson(category):
return {
"name": category.name,
"type": str(category.type),
"nsfw": category.is_nsfw(),
... | StarcoderdataPython |
373353 | #!/usr/bin/env python
"""
Repro
-----
This is a module about repro
"""
from sdk.foo import foo
def handler(event, context):
"""Make a request and print it"""
resp = foo()
print(resp)
if __name__ == '__main__':
handler('a', 'b') | StarcoderdataPython |
103415 | <filename>testing/test_xml.py
import py
from testing.test_interpreter import BaseTestInterpreter
py.test.skip("xml module unavailable")
class TestXML(BaseTestInterpreter):
def test_basic_parse(self):
output = self.run("""
$parser = xml_parser_create();
$x = "";
function callback(... | StarcoderdataPython |
3225844 | import numpy as np
I = 100
J = 2
beta_0 = -1
beta_1 = 1
sigma_u = 0.5
sigma_eps = 1
iteration = 30
initial = [0, 0, 5, 5]
result = []
def xE(E_t):
return sum(sum(value_x * np.array([E_t, E_t]).T))
def eps_right(E_t, beta0, beta1):
return (sum(sum((value_y - beta0-beta1*value_x)**2)) + J * sum(E_t**2) - 2*sum... | StarcoderdataPython |
1709898 | <filename>src/cdev/project_templates/quick_start/src/hello_world/resources.py<gh_stars>1-10
# Generated as part of Quick Start project template
from cdev.resources.simple.api import Api
from cdev.resources.simple.xlambda import simple_function_annotation
from cdev import Project as cdev_project
myProject = cdev_proj... | StarcoderdataPython |
360865 | # Generated by Django 3.2.2 on 2021-05-13 18:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('game', '0016_game_torrent_file_size'),
]
operations = [
migrations.AlterField(
model_name='game',
name='torrent_file... | StarcoderdataPython |
3310799 | <filename>exashellcore.py
from platform import platform
import time
import os
import requests
import platform
import subprocess
import psutil
from pystyle import Write, Colors
VERSION = "1.1"
req = requests.get("https://api.github.com/repos/xYanis/ExaShell/releases/latest").json()
lastestVersion = req['tag_name']
i... | StarcoderdataPython |
9614037 | <filename>bench.py
import numpy as np
import time
import cv2
import click
import glob
from imutils.video import FPS
from Events import *
from utils import *
net_path = path.join('data', 'frozen.pb')
predictor_path = path.join('data', 'shape_predictor_68_face_landmarks.dat')
@click.command()
@click.option('--debug'... | StarcoderdataPython |
9753411 | <reponame>RobDoesData/btccagr-calc
import matplotlib.pyplot as plt
import os
import pandas as pd
import json
from datetime import date, timedelta
def cagr_calc(start,end,ticker):
"""
start - type:date - start date for CAGR Calc
end - type:date - end date for CAGR Calc
ticker - type:str - asset to ca... | StarcoderdataPython |
5030319 |
import os
from app.networks import get_ip
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
APPLICATION_DIR = os.path.dirname(os.path.realpath(__file__))
STATIC_DIR = os.path.join(APPLICATION_DIR, 'static')
IMAGES_DIR = os.path.join(APPLICATION_DIR, 'images')
SECRET_KEY = os... | StarcoderdataPython |
152057 | <reponame>cloudmesh/pbs<gh_stars>1-10
from cloudmesh_base.locations import config_file
from cloudmesh_base.ConfigDict import ConfigDict
from cloudmesh_base.logger import LOGGER
log = LOGGER(__file__)
class cmd3_check:
@staticmethod
def yaml(plugin):
"""
This function reads in the cloudmesh ... | StarcoderdataPython |
1915227 | import glob
import re
from collections import defaultdict
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from matplotlib.axes import Axes
from matplotlib.lines import Line2D
matplotlib.style.use("bmh")
tab20 = matplotlib.cm.get_cmap("tab20")
poss = np.li... | StarcoderdataPython |
11252792 | # Copyright (c) 2016, 2018 <NAME> <<EMAIL>>
try:
import pkg_resources
except ImportError:
pkg_resources = None
def is_namespace(modname):
return pkg_resources is not None and modname in pkg_resources._namespace_packages
| StarcoderdataPython |
3507029 | <gh_stars>10-100
import numpy as np
from simple_convnet import convnet as cn
from scipy.optimize import approx_fprime
def _check_gradients(layer_args, input_shape):
rand = np.random.RandomState(0)
net = cn.SoftmaxNet(layer_args=layer_args, input_shape=input_shape, rand_state=rand)
x = rand.randn(*(10,)+ne... | StarcoderdataPython |
5029292 | # -*- coding: utf-8 -*-
import sys
import unittest
from glob import glob
sys.path.append('../loc_measure')
from loc_measure import LocMeasure
class TestExtension(unittest.TestCase):
def setUp(self):
cfg_file = '../loc_measure/config.json'
self.loc_measure = LocMeasure(cfg_file)
def run_test(... | StarcoderdataPython |
1902374 | <filename>mxdc/widgets/plotter.py
import numpy
from gi.repository import Gtk
from matplotlib import cm, transforms
from matplotlib.backends.backend_gtk3 import NavigationToolbar2GTK3
from matplotlib.backends.backend_gtk3cairo import FigureCanvasGTK3Cairo as FigureCanvas
from matplotlib.colors import Normalize
from mat... | StarcoderdataPython |
201597 | <reponame>CMLivingston/pants<gh_stars>0
# coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
import os
import sys
from builtins import str
fro... | StarcoderdataPython |
6417124 | <filename>server/mysite/studygroups/apps.py
from django.apps import AppConfig
class StudygroupsConfig(AppConfig):
name = 'studygroups'
| StarcoderdataPython |
3281692 | # https://leetcode.com/problems/contains-duplicate/
from typing import List
class Solution:
def containsDuplicateSet(self, nums: List[int]) -> bool:
"""
Set approach
Time complexity: O(n)
Space complexity: O(n)
"""
seen = set()
for n in nums:
... | StarcoderdataPython |
5014664 | <reponame>Norwa9/missing_modalities<gh_stars>0
import torch
import torch.nn as nn
import torch.nn.functional as F
class LSTMEncoder(nn.Module):
''' one directional LSTM encoder
'''
def __init__(self, input_size, hidden_size, embd_method='last'):
super(LSTMEncoder, self).__init__()
self.inp... | StarcoderdataPython |
11261342 | <gh_stars>0
from arm.logicnode.arm_nodes import *
class PickObjectNode(ArmLogicTreeNode):
"""Use to pick the rigid body in a location using the screen
coordinates (only x/y values are used)."""
bl_idname = 'LNPickObjectNode'
bl_label = 'Pick Rigid Body'
arm_version = 1
def init(self, context):... | StarcoderdataPython |
1792891 | # Copyright 2014 CloudFounders NV
#
# 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 agreed to in writ... | StarcoderdataPython |
6564091 | # Copyright (c) 2013, <NAME> and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.utils import flt, getdate, cstr
from frappe import _
import ast
import datetime
def execute(filters=None):
columns, data = [], []
columns = [
{
"fi... | StarcoderdataPython |
11310583 | <filename>cloudrunner_server/api/__init__.py
VERSION = '0.9'
| StarcoderdataPython |
3259577 | import json
import logging
import os
import re
from backup_initialize.lookup import Lookup
logger = logging.getLogger(__name__)
class InvalidJsonBackupsConfigurationArray(Exception):
# Custom exception raised when the backups configuration json array was not found
def __init__(self):
Exception.__ini... | StarcoderdataPython |
132360 | <reponame>VWS-Python/vws-python-mock
"""
Validators for the project state.
"""
from typing import Dict, Set
from mock_vws._database_matchers import get_database_matching_client_keys
from mock_vws._query_validators.exceptions import InactiveProject
from mock_vws.database import VuforiaDatabase
from mock_vws.states imp... | StarcoderdataPython |
4837260 | from sgan.models.transformer.decoder import Decoder
from sgan.models.transformer.multihead_attention import MultiHeadAttention
from sgan.models.transformer.positional_encoding import PositionalEncoding
from sgan.models.transformer.pointerwise_feedforward import PointerwiseFeedforward
from sgan.models.transformer.encode... | StarcoderdataPython |
220425 | <reponame>AustralianSynchrotron/bluesky-queueserver
# flake8: noqa
from typing import List, Optional, Dict, Any
from bluesky.plans import (
count,
list_scan,
rel_list_scan,
list_grid_scan,
rel_list_grid_scan,
log_scan,
rel_log_scan,
adaptive_scan,
rel_adaptive_scan,
tune_centroi... | StarcoderdataPython |
3392995 | # Create your forms here.
from django import forms
class CreateForm(forms.Form):
domain_id = forms.CharField(required=True, widget=forms.HiddenInput)
group_name = forms.CharField(required=True)
description = forms.CharField(
required=True,
widget=forms.Textarea
)
group_owner = form... | StarcoderdataPython |
3563814 | def fibonacci():
n1 = 0
n2 = 1
while True:
yield n1
n1, n2 = n2, n1 + n2
generator = fibonacci()
for i in range(8):
print(next(generator))
| StarcoderdataPython |
354722 | <reponame>disktnk/chainer-compiler<filename>ch2o/tests/node/Roi.py
# coding: utf-8
import argparse
import pickle
import sys
import os
import chainer
import chainer.functions as F
from chainer.backends import cuda
class ROIPool2D(chainer.Chain):
def __init__(self, fn, outsize, spatial_scale):
super(ROIPo... | StarcoderdataPython |
1687896 | <filename>filey/__init__.py
from .handles import *
from .shell import *
from .walking import *
from .persistence import *
from .shortcuts import *
if __name__ == "__main__":
pass | StarcoderdataPython |
4991665 | <filename>Crawler/server.py
from flask import Flask
from flask_restful import Api, Resource
from query import main, statistics_by_id
app = Flask(__name__)
api = Api(app)
class Query(Resource):
def get(self, query):
videos = main(query)
response = app.response_class(
response=videos,
... | StarcoderdataPython |
3569373 | # coding: utf-8
"""
TileDB Storage Platform API
TileDB Storage Platform REST API # noqa: E501
The version of the OpenAPI document: 2.2.19
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import unittest
import tiledb.cloud.rest_api
from tiledb.cloud.rest_ap... | StarcoderdataPython |
4961164 | <filename>code/classifier/lstm_1000.py<gh_stars>1-10
import csv
import datetime
import json
import os
import time
import pickle
import gc
from os.path import expanduser, exists
from pprint import pprint
from zipfile import ZipFile
import numpy as np
from sklearn.metrics import f1_score
from sklearn.model_selection im... | StarcoderdataPython |
11343020 | import torch
import os
import warnings
class EMA:
# Found this useful (thanks alexis-jacq):
# https://discuss.pytorch.org/t/how-to-apply-exponential-moving-average-decay-for-variables/10856/3
def __init__(
self, gamma=0.99, save=True, save_frequency=5, save_filename="ema_weights.pth"
):
... | StarcoderdataPython |
5110399 | from pathlib import Path
from setuptools import setup
from setuptools import find_packages
PROJECT = "redex"
PROJECT_DIR = f"src/{PROJECT}"
REPOSITORY = f"manifest/{PROJECT}"
README = (Path(__file__).parent / "README.md").read_text()
# Setup project version.
__version__ = None
with open(f"{PROJECT_DIR}/version.py") a... | StarcoderdataPython |
1678164 | if __name__ == '__main__':
from kervi.application import Application
APP = Application()
#Important GPIO must be imported after application creation
from kervi.hal import GPIO
from kervi.dashboards import Dashboard, DashboardPanel
Dashboard(
"app",
"App",
[
D... | StarcoderdataPython |
3277639 | <gh_stars>0
import sys
import numpy as np
from keras import optimizers
from keras.callbacks import ReduceLROnPlateau, EarlyStopping
# use non standard flow_from_directory
from utils.image_preprocessing_v2 import ImageDataGenerator
# it outputs y_batch that contains onehot targets and logits
# logits came from xception... | StarcoderdataPython |
189896 | # Copyright (c) Facebook, Inc. and its affiliates.
#
# 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 ... | StarcoderdataPython |
3239452 | from __future__ import unicode_literals
import sure # noqa
import moto.server as server
from moto import mock_mediastore
"""
Test the different server responses
"""
@mock_mediastore
def test_mediastore_lists_containers():
backend = server.create_backend_app("mediastore")
test_client = backend.test_client(... | StarcoderdataPython |
3413223 | <filename>test/unit/test_cache.py
from unittest import TestCase
from dbt.adapters.cache import RelationsCache
from dbt.adapters.default.relation import DefaultRelation
from multiprocessing.dummy import Pool as ThreadPool
import dbt.exceptions
import random
import time
def make_relation(schema, identifier):
retur... | StarcoderdataPython |
8164980 | <reponame>worko1/python_learn
import yaml
from pprint import pprint
y_filename = raw_input('Enter filaname:')
# y_filename='yaml_file.yml'
def read_yaml(input_file):
with open(input_file ,"r") as f:
return (yaml.load(f))
pprint(read_yaml(y_filename)) | StarcoderdataPython |
3513864 | from enum import Enum
from typing import List, Dict
from kbc_pul.experiments_utils.color_utils import matplotlib_color_name_to_hex
class GroupNameEnum(Enum):
total = "$\left|\mathbf{R}\\right|$"
filter = '$S_{q}$'
other = '$S_{\\neg q}$'
@staticmethod
def get_groups_as_ordered_strings() -> List[... | StarcoderdataPython |
6556711 | import json
import re
from tornado.httputil import format_timestamp
from tornado.web import RequestHandler
from engine.common.settings import load_settings
from engine.tornado_messages import FlashMessageMixin
from engine.user.user_manager import UserManager
user_manager = UserManager(load_settings('settings.yaml')... | StarcoderdataPython |
8057313 | <filename>tensortrade/data/stream/transform.py
# Copyright 2019 The TensorTrade Authors.
#
# 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 |
9663859 | <reponame>jakev/dtf<gh_stars>10-100
# Android Device Testing Framework ("dtf")
# Copyright 2013-2017 <NAME> (@jake_valletta)
#
# 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.apa... | StarcoderdataPython |
9706251 | <gh_stars>1-10
def fizzbuzz(n):
return ["FizzBuzz" if (i%3==0 and i%5==0) else "Fizz" if i%3==0 else "Buzz" if i%5==0 else i for i in range(1,n+1)]
| StarcoderdataPython |
6602900 | <filename>pactman/mock/mock_urlopen.py
import io
import logging
import urllib3.connectionpool
import urllib3.poolmanager
from urllib3.response import HTTPResponse
from .pact_request_handler import PactRequestHandler
_providers = {}
log = logging.getLogger(__name__)
class MockConnectionPool(urllib3.connectionpool... | StarcoderdataPython |
5016219 | from direct.interval.IntervalGlobal import *
from direct.gui.DirectGui import *
from direct.fsm.FSM import FSM
from panda3d.core import *
import sys, os, time, random
from Level import Level
from Camera import CameraControls
from Timer import Timer
class FNAFBase(FSM):
def __init__(self, withinTTH=False):
... | StarcoderdataPython |
9610008 | <gh_stars>1-10
from urllib.request import urlopen
from urllib.error import HTTPError
from io import BytesIO
from subprocess import call
import threading
import multiprocessing
import signal
import sys
from uuid import uuid4
from pickle import loads, dumps
import logging
import logging.config
from redis import Redis
f... | StarcoderdataPython |
3454779 | <reponame>vzhong/silg<filename>silg/envs/touchdown/__init__.py
from silg.envs.touchdown import gym_wrapper | StarcoderdataPython |
6423001 | <filename>dirigible/featured_sheet/models.py<gh_stars>100-1000
# Copyright (c) 2011 Resolver Systems Ltd, PythonAnywhere LLP
# See LICENSE.md
#
from django.db import models
from sheet.models import Sheet
class FeaturedSheet(models.Model):
sheet = models.ForeignKey(Sheet)
description = models.TextField()
... | StarcoderdataPython |
6562656 | import numpy as np
import torch
def compute_histogram(gamma, m3, b_y):
activations = np.zeros((10, m3))
for i in range(10):
n_ci = float(torch.sum(b_y==i))
if n_ci>0:
gamma_i = gamma[b_y[b_y==i],:,:,:]
activations[i,:] = count_activations(gamma_i, 1e-4)
return activa... | StarcoderdataPython |
245120 |
import proton.graphicscomponent
from proton.scenemanager import SceneManager
from proton.scene import *
from proton.protonsingleton import *
import proton.motioncomponent as mc
class GameObject(object):
def __init__(self, name):
"""
Initializes the gameobject.
:param name: gameobject name... | StarcoderdataPython |
9761334 | <filename>store2mongo.py<gh_stars>1-10
"""
Store json data to mongodb
"""
from pymongo import MongoClient
import json
import os
import argparse
def connect(args):
"""
:param args:
:return:
:rtype pymongo.collection.Collection
"""
conn = MongoClient(host=args.host, port=args.port)
return ... | StarcoderdataPython |
5096335 | from logging import getLogger
logger = getLogger("jobs.utils")
TIMEOUT_CALLS = 60
class Subway():
"""Simple code that allows extending things by .attr.ing them"""
def __init__(self, _url, _session, version):
self._url = _url.rstrip('/')
self._session = _session
def __repr__(self):
return f"<Subway... | StarcoderdataPython |
9730488 | # -*- coding: utf-8 -*-
from django import conf
from django.db import models, IntegrityError
import schools.models
class Session(models.Model):
"""SIS session from poldnev.ru"""
poldnev_id = models.CharField(
primary_key=True,
max_length=50,
help_text='Id смены на poldnev.ru. Заполня... | StarcoderdataPython |
113088 | """
After an apology from the opponent (they play C while it plays D, only happens when they play D first), if the opponent
immediately plays D, it plays another C instead of punishing in order to encourage the opponent to get back to CC-chain
(i.e. olive branch). If it plays D again, go full D.
Difference between tft... | StarcoderdataPython |
9699136 | <reponame>valentingol/PANNsTensorflow
import argparse
import os
import sys
from lib.options import Options
# Running 'pytest <this file> <options>' causes the parser
# to get <this file> and <options> as arguments (unexpected).
# The following line solves the problem.
sys.argv = ['pytest']
def test_init():
opt =... | StarcoderdataPython |
11398784 | <gh_stars>0
import pytest
from instascrape import Profile
@pytest.fixture(scope='module')
def profile() -> Profile:
profile_url = "https://www.instagram.com/chris_greening/"
profile_obj = Profile(profile_url)
profile_obj.load()
return profile_obj
def test_from_username(profile):
expected_profile_... | StarcoderdataPython |
322183 | #coding:utf-8
###########################################################
# SpCoTMHPi: Spatial Concept-based Path-Planning Program for SIGVerse
# Path-Planning Program by A star algorithm (ver. approximate inference)
# Path Selection: minimum cost (- log-likelihood) in a path trajectory
# <NAME> 2022/02/07
# Spacial T... | StarcoderdataPython |
5164497 | from jig.commands.base import BaseCommand
from jig.commands.hints import AFTER_INIT
from jig.gitutils.hooking import hook
from jig.plugins import initializer
try:
import argparse
except ImportError: # pragma: no cover
from backports import argparse
_parser = argparse.ArgumentParser(
description='Initial... | StarcoderdataPython |
11331005 | from io import StringIO
import pytest
from snowfakery.data_generator import generate
from snowfakery.data_gen_exceptions import DataGenError
class TestFaker:
def test_top_field_unknown(self):
yaml = """
- bobject: OBJ
fields:
first_name:
fake:
... | StarcoderdataPython |
1626122 | from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import sqlite3
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
DB = SQLAlchemy(app)
# Create user class
class User(DB.Model):
'''Instantiate user class'''
id = DB.Column(DB.Integer, primary_key=True)
name = ... | StarcoderdataPython |
4955169 | """
This testsuite contains the initial test cases for testing the
f5 converter tool along with its options / parameters
"""
import json
import logging
import os
import subprocess
import sys
import pytest
import yaml
from avi.migrationtools.avi_migration_utils import get_count, set_update_count
from avi.migrationtools.... | StarcoderdataPython |
1765201 | <gh_stars>1-10
import pygal
import pandas as pd
from pygal.style import Style
from pygal.style import DefaultStyle
def line_chart_24h(df):
temperature_list = df["Temperature"].tolist()
humidity_list = df["Humidity"].tolist()
x_labels = []
for time in df.Timestamp:
m = time[11:16]
x_la... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.