id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
1841274 | <filename>metricreporter.py
import requests
import json
import socket
from time import time
from pprint import pprint
class MetricsReporter(object):
PATH = "/ws/v1/timeline/metrics"
HEADERS = {"Content-Type": "application/json"}
def __init__(self, url_base, metricname, appid):
self.url_base = url... | StarcoderdataPython |
3496798 | # -*- coding: utf-8 -*-
## Used Imports
import os
import io
import zipfile
import random
import numpy as np
import streamlit as st
import clip
import gc
# import psutil ## show info (cpu, memeory)
from io import BytesIO
from PIL import Image
from zipfile import ZipFile
from pathlib import Path, Pure... | StarcoderdataPython |
8085832 | __version__ = '19.6'
| StarcoderdataPython |
11323899 | <gh_stars>0
from HappyDogs.lib.decorators import render
from HappyDogs.lib.utils import get_request_data
from django.views.decorators.http import require_http_methods
from models import BoardingVisit, Dog
from datetime import date
from django.db.models import Avg, Max, Min
from utils import weeks_beetwen
from utils imp... | StarcoderdataPython |
11320049 | """
Image Finder
"""
import os
from pathlib import Path
from typing import Union
from ImageCopy.image_file import ImageFile
class ImageFinder:
"""
Utility to find all images in any given directory
"""
@staticmethod
def get_images_dict(directory: Union[str, Path], target_dir: Union[str, Path], fi... | StarcoderdataPython |
3398762 | <reponame>followwwind/flask-web<filename>routes/hello.py
# -*- encoding:utf-8 -*-
"""
@author:wind
@time:2021/3/23 20:37
@desc:
"""
from config import app
@app.route('/hello')
def hello_world():
return 'Hello World!'
| StarcoderdataPython |
3442857 | <gh_stars>100-1000
from unittest import TestCase
from SingleNumber import SingleNumber
class TestSingleNumber(TestCase):
def test_singleNumber(self):
sn = SingleNumber()
self.assertTrue(sn.singleNumber(None) == 0)
self.assertTrue(sn.singleNumber([1]) == 1)
self.assertTrue(sn.sin... | StarcoderdataPython |
5127554 | <gh_stars>1-10
from django.apps import AppConfig
class DjangoSessionJwtConfig(AppConfig):
name = 'django_session_jwt'
| StarcoderdataPython |
1981153 | from textwrap import dedent, indent
from typing import Union, List
class MultiLineFormatter:
"""
\\* operator -> add de-dented text (+ \\\\n), if operand is a list -> add \\\\n-joined elements
% operator -> add de-dented text (+ \\\\n), if operand is a list -> add ,-joined elements
/ operator -> inc... | StarcoderdataPython |
8045176 | <reponame>dannyjeck-matroid/solaris
from . import bin, data, eval, nets, raster, tile, utils, vector
__version__ = "0.1.3"
| StarcoderdataPython |
3579372 | <gh_stars>1-10
# Copyright [2017] [<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
#
# Unless required by applicable law or agreed t... | StarcoderdataPython |
393475 | <filename>tvsched/application/models/auth.py
from dataclasses import dataclass
import uuid
from tvsched.entities.auth import Role
@dataclass(frozen=True)
class UserAdd:
"""Data for register user with USER role."""
username: str
password: str
@dataclass(frozen=True)
class UserWithRoleAdd:
"""Data f... | StarcoderdataPython |
5088317 | <filename>utils/model_utils.py
import torch,os
import torch.nn as nn
from reformer_pytorch_LD.reformer_pytorch import ReformerLM
from reformer_pytorch_LD.reformer_pytorch_kmeans import ReformerKmeansLM
def init_weight(args,weight):
if args.init == 'uniform':
nn.init.uniform_(weight, -args.init_range, args... | StarcoderdataPython |
6490530 | '''
Usage: openPortfolio [-dpwish] [COUNTER] ...
Arguments:
COUNTER Optional counters
Options:
-p,--portfolio Select portfolio from config.json
-w,--watchlist Select watchlist from config.json
-i,--i3 Open in i3investor.com
-s,--sb Open in my.stockbit.co... | StarcoderdataPython |
1707104 | <gh_stars>0
from main import generate
import argparse
parser = argparse.ArgumentParser(description='ETERNALCRYSTAL - Generate code names on the fly.')
parser.add_argument('-w', metavar='--wordlist', type=str, nargs='?',help='path to wordlist')
parser.add_argument('-v', '--version', action='version', version='v0.0.1-al... | StarcoderdataPython |
1991953 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import getpass
import io
import logging
import os
import platform
import requests
import string
import sys
import tkinter as tk
import tkinter.filedialog as fd
import tkinter.messagebox as messagebox
from datetime import timedelta
from PIL import Image, ImageTk
from budd... | StarcoderdataPython |
8042871 | <reponame>dmitsf/GOT
''' FADDIS clustering implementation in Python
'''
import numpy as np
import numpy.linalg as LA
ZERO_BOUND = 10 ** (-9)
MIN_CLUSTER_CONTRIBUTION = 5 * 10 ** (-3)
EPSILON = 5 * 10 ** (-2)
# Maximum number of clusters
MAX_NUM_CLUSTERS = 15
def ensure_np_matrix(A):
if not isinstance(A, np.mat... | StarcoderdataPython |
3554157 | #open a file without knowing what encoding the file is taken
#
import codecs
encode = ["utf8", "gbk", "gb2312"]
filename = ""
content = ""
for code in encode:
f = codecs.open(filename, "r", encoding = code)
try:
content = f.readlines()
except:
f.close()
continue
f.close()
... | StarcoderdataPython |
6700616 | <reponame>lby314xx/MLP-coursework
import torch
import torch.nn as nn
import torch.nn.init as init
from functools import reduce
class Net(nn.Module):
def __init__(self, blocks, rate):
super(Net, self).__init__()
self.convt_I1 = nn.ConvTranspose2d(1, 1, kernel_size=int(4*rate//2), stride=rate, paddi... | StarcoderdataPython |
3593604 | '''
Og é um homem das cavernas com vários filhos e filhas, e ele quer contar todos eles. Og conta seus filhos com sua mão esquerda e suas filhas com sua mão direita.
Entretanto, Og não é inteligente, e não sabe somar os dois números. Assim, ele pediu para você escrever um programa que realize a soma.
Entrada
A entrad... | StarcoderdataPython |
4888844 | # Script : areas_of_triangles
# Description : This program asks the user for the length and width
# of two rectangles and then tell the user which rectangle
# has the greater area, or if the areas are the same using the formula
# Area = Length * Breadth
# Programmer : <NAME>
#... | StarcoderdataPython |
6458215 | <reponame>insad-video/marsha
"""Structure of Video related models API responses with Django Rest Framework serializers."""
from datetime import timedelta
from urllib.parse import quote_plus
from django.conf import settings
from django.urls import reverse
from django.utils import timezone
from django.utils.text import ... | StarcoderdataPython |
354437 | <filename>indico/modules/users/legacy.py
# This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from flask_multipass import IdentityInfo
from indico.legacy.comm... | StarcoderdataPython |
6648133 | import argparse
import os
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
from dataset.dataset import AVDataset
from models.basic_model import AVClassifier
from utils.utils import setup_seed, we... | StarcoderdataPython |
4825802 | <gh_stars>0
#!/usr/bin/env python
############################################################################
# Copyright (c) 2015 Saint Petersburg State University
# All Rights Reserved
# See file LICENSE for details.
############################################################################
import os
import sys
... | StarcoderdataPython |
8137861 | from sklearn.ensemble import RandomForestClassifier
from sklearn import metrics
import tensorflow as tf
from tensorflow.keras import Model
from functions import *
import os
import numpy as np
new_path = "D:\\Data\\archive\\numpy"
train_y_number = new_path+"\\train_y_number.npy"
test_y_number = new_path+"\\test_y_numb... | StarcoderdataPython |
1842456 | <reponame>ryutaro-0907/simple-health
"""Define routers for Record."""
from typing import List
from fastapi import APIRouter, Depends, status, HTTPException
from fastapi.responses import JSONResponse
from sqlalchemy.orm import Session
from ..use_cases import record_services
from ..entities.user import UserId
from ..e... | StarcoderdataPython |
3573709 | <gh_stars>1-10
import uuid
from django.db import models
class BaseAsset(models.Model):
id = models.UUIDField(
primary_key=True, null=False, editable=False, default=uuid.uuid4
)
identifier = models.CharField(max_length=255, null=False, blank=False)
class Meta:
abstract = True
class ... | StarcoderdataPython |
6541570 | <filename>odes.py
import numpy as np
from collections.abc import Iterable
from collections import deque
from functools import wraps
from typing import NamedTuple, Callable, Dict, Any, Tuple
from math import ceil
from itertools import count
class IvpSolution(NamedTuple):
length: int
ts: np.array
ys: np.a... | StarcoderdataPython |
208034 | <gh_stars>1-10
import contextlib
import os
import shutil
import pytest
from transform.msigdb.transform import transform
@pytest.fixture
def input_xml(request):
return os.path.join(request.fspath.dirname, 'source/msigdb/msigdb_v6.2.xml')
def validate(helpers, emitter_directory, input_xml):
""" run xform and ... | StarcoderdataPython |
8018984 | from tkinter import *
from tkinter import ttk
from tkinter import messagebox
from PIL import ImageTk, Image
import sqlite3
class userwindow:
sqlite_var = 0 #variable to establish connection btw python and sqlite3
theCursor = 0 #variable to store the indexing cursor
curItem=0 #variable to store curre... | StarcoderdataPython |
4827147 | <filename>tests/python/profiling/test_nvtx.py
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License... | StarcoderdataPython |
1784593 | <filename>alipay/aop/api/domain/AuthFieldSceneDTO.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AuthFieldSceneDTO(object):
def __init__(self):
self._scene_code = None
self._scene_desc = None
@property
def scene_co... | StarcoderdataPython |
4824589 | import os
import shutil
from util import file_util
from util.frontend.normalize_lab_for_merlin import normalize_label_files
MerlinDir = "merlin"
frontend = os.path.join(MerlinDir, "misc", "scripts", "frontend")
ESTDIR = os.path.join(MerlinDir, "tools", "speech_tools")
FESTDIR = os.path.join(MerlinDir, "tools", "festi... | StarcoderdataPython |
3456577 | <reponame>avs123/Farmers-Portal<filename>home/views.py
from django.shortcuts import render, get_object_or_404, redirect
from django.http import HttpResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.contrib import messages
from django.db.models import Count
from django.db import con... | StarcoderdataPython |
3381804 | <gh_stars>0
import pymia.deeplearning.model as mdl
import torch.optim as optim
import torch.nn as nn
import mialab.configuration.config as cfg
class TorchMRFModel(mdl.TorchModel):
def inference(self, x) -> object:
return self.network(x)
def loss_function(self, prediction, label=None, **kwargs):
... | StarcoderdataPython |
4800951 | # -*- coding: utf-8 -*-
'''
torstack.storage.sync_memcache
sync memcache storage definition.
:copyright: (c) 2018 by longniao <<EMAIL>>
:license: MIT, see LICENSE for more details.
'''
import memcache
class SyncMemcahhe(object):
def __init__(self, configs=[], expire=1800, debug=False):
if not configs:
... | StarcoderdataPython |
176147 | # ========== (c) <NAME> 3/8/21 ==========
import pandas as pd
import numpy as np
import scipy.stats
desired_width = 320
pd.set_option('display.max_columns', 20)
pd.set_option('display.width', desired_width)
# ==========================
# For datasets 1-3
# ==========================
df = pd.read_csv("data-vid/examp... | StarcoderdataPython |
9644500 | import numpy as np
import pandas as pd
import scipy.spatial.distance as ssd
from sklearn.utils import check_array
import logging
from time import time
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - ... | StarcoderdataPython |
1958073 | #!/usr/bin/env python3
import argparse
import random
import os
import pickle
from sklearn.model_selection import train_test_split
from tensorflow.keras.optimizers import Adam, RMSprop
from tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping
from tensorflow.keras.utils import to_categorical
from generator... | StarcoderdataPython |
11291510 | #!/usr/bin/env python
import cv2
import numpy as np
import matplotlib.pyplot as plt
img = cv2.imread('img-desktop-kv-background.jpg')
blurred_img = cv2.blur(img, ksize=(4, 4))
edges = cv2.Canny(image=blurred_img, threshold1=20, threshold2=60)
plt.imshow(edges)
plt.show()
| StarcoderdataPython |
298753 | <reponame>exekias/beats-kubernetes-demo<filename>app/questions/views.py
from django.views.generic.edit import CreateView
from django.urls import reverse_lazy
from django.core.exceptions import ValidationError
from django.shortcuts import render, redirect
from django.contrib import messages
from django.db.models import ... | StarcoderdataPython |
280035 | <filename>cleanup.py
import boto3
import json
import sys
# Prototype to remove s3 records and dynamodb records for images that have been removed from ECR.
# Right now, the list_repos.py has to be run under 10011 credentials to build the list of all repos,
# then this script runs under 10021 credentials to remove s3 re... | StarcoderdataPython |
6436405 | <filename>compiler/cpsconvert.py
from . import ast as A
from . import parse as P
from . import string2ast as S2A
from . import symbol as S
def cpsConvert(ast):
def cps(ast, contAst):
if A.isLit(ast):
ret = A.makeApp([contAst, ast])
return ret
if A.isRef(ast):
r... | StarcoderdataPython |
6621252 | <reponame>qq1418381215/caat<gh_stars>10-100
import torch
from torch.autograd import Function
from torch.nn import Module
from .warp_rnnt import *
from .rnnt import rnnt_loss,RNNTLoss
from .delay_transducer import delay_transducer_loss, DelayTLoss
__all__ = ['rnnt_loss', 'RNNTLoss','delay_transducer_loss', 'DelayTLos... | StarcoderdataPython |
107917 | #!/usr/bin/python
# -*- coding: iso-8859-1 -*-
from collections import namedtuple
from math import sqrt
import random
Cluster = namedtuple('Cluster', ('points', 'center', 'n'))
def calculate_center(points):
vals = [0,0]
if len(points) < 1:
return vals
plen = 0
for p in points:
plen += ... | StarcoderdataPython |
9610437 | <reponame>iashraful/pnp-graphql<filename>pnp_graphql/exceptions.py
from pnp_graphql import status_code
from django.utils.translation import ugettext_lazy as _
class APIBaseException(Exception):
status = status_code.HTTP_500_INTERNAL_SERVER_ERROR
message = _('Internal Server Error.')
error_key = 'error'
... | StarcoderdataPython |
8029468 | <reponame>facebookresearch/uimnet<filename>scripts/run_prediction.py
#!/usr/bin/env python3
#
# # Copyright (c) 2021 Facebook, inc. and its affiliates. All Rights Reserved
#
#
"""
Evaluate in-domain metrics on the sweep directory
"""
import argparse
import os
import submitit
import pickle
import concurrent.futures
impo... | StarcoderdataPython |
5011817 | <reponame>tschijnmo/FFOMP<gh_stars>0
"""
Models for molecular mechanics
==============================
In this package, models are provided to model some molecular and material
properties based on some force fields.
Most often force fields are going to model the energy and atomic forces based
on the atomic coordinate... | StarcoderdataPython |
8187784 | <reponame>elfosardo/coursera-dsa<filename>algorithms-on-graphs/Decomposition of Graphs 1/connected_components.py
# Uses python3
import sys
def number_of_components(adj):
visited = [False for x in range(len(adj))]
components = 0
def DFS(x):
visited[x] = True
for w in adj[x]:
i... | StarcoderdataPython |
6453882 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import numpy as np
import plotly as pxe
import plotly.express as px
country = pd.read_csv(r'C:\Users\Master\Desktop\Jupyter\country_vaccinations.csv')
country.describe()
# In[2]:
country
# In[3]:
np.unique(country['country'],return_counts= T... | StarcoderdataPython |
3418544 | from setuptools import setup, find_packages
setup(
name='testspace-python',
version='',
packages=find_packages(include=['testspace', 'testspace.*']),
url='',
license="MIT license",
author="<NAME>",
author_email='<EMAIL>',
description="Module for interacting with Testspace Server",
i... | StarcoderdataPython |
11297106 | <gh_stars>10-100
#!/usr/bin/env python
# coding=utf-8
"""
@function:
@version: 1.0
@author: <NAME>
@license: Apache Licence
@file: anna_writer.py
@time: 2017/7/4 下午2:27
"""
import time
import numpy as np
import tensorflow as tf
# 读取训练数据
file_path = './data/anna.txt'
with open(file_path) as f:
text = f.read()
# p... | StarcoderdataPython |
93514 | <gh_stars>10-100
from numpy import zeros, matrix, array, random
from middleware import CodeRedLib
from time import time
from math import floor
def experiment(n, k, samples):
profiles = zeros((6, k))
G = random.randint(0,2, size=(k, n), dtype="bool")
red = CodeRedLib(G)
for s in range(samples):
... | StarcoderdataPython |
3437295 | import numpy as np
from numpy import ndarray
from dataclasses import dataclass
from scipy.spatial.transform import Rotation
from config import DEBUG
from cross_matrix import get_cross_matrix
@dataclass
class RotationQuaterion:
"""Class representing a rotation quaternion (norm = 1). Has some useful
methods f... | StarcoderdataPython |
1685304 | <filename>examples/thermoelectric_fridge.py<gh_stars>0
#!/usr/bin/env python
"""
Create a thermoelectric fridge controller to control motor and peltier from a 12 folt source.
"""
from simple_skidl_parts.analog.power import *
from simple_skidl_parts.analog.vdiv import *
from simple_skidl_parts.units.linear import *
fr... | StarcoderdataPython |
3407700 | <reponame>KelOdgSmile/ml-cvnets<filename>utils/common_utils.py
#
# For licensing see accompanying LICENSE file.
# Copyright (C) 2020 Apple Inc. All Rights Reserved.
#
import random
import torch
import numpy as np
from utils import logger
import os
from utils.ddp_utils import is_master
from cvnets.layers import norm_la... | StarcoderdataPython |
1675911 | """
Copyright (c) 2016-2020 <NAME> http://www.keithsterling.com
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, m... | StarcoderdataPython |
3556824 | import json
from http import HTTPStatus
USERS = {
'railgun': {
'name': '<NAME>',
'age': 14,
'city': 'Gakuen-toshi',
'country': 'Japan'
},
'imagine-breaker': {
'name': '<NAME>',
'age': 15,
'city': 'Gakuen-toshi',
'country': 'Japan'
},
'... | StarcoderdataPython |
3245566 | <filename>python/AULAS/aula016.py
# lanche = ('Hambúrguer', 'Suco', 'Pizza', 'Pudim')
# for comida in lanche:
# print(lanche)
# for cont in range(0, len(lanche)):
# print(f'{cont + 1}° eu vou comer {lanche[cont]}')
# for pos, cont in enumerate(lanche):
# print(f'{pos + 1}° eu vou comer {cont}')
# print(... | StarcoderdataPython |
8039470 | <reponame>1696012928/RoomAI
#!/bin/python
#coding:utf-8
import roomai.common
import copy
import logging
import random
import sys
from functools import cmp_to_key
from roomai.fivecardstud import FiveCardStudPokerCard
from roomai.fivecardstud import FiveCardStudPublicState
from roomai.fivecardstud import FiveCard... | StarcoderdataPython |
336223 | <gh_stars>0
from collections import OrderedDict
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from mkt.api.base import CORSMixin
from mkt.constants.features import APP_FEATURES, FeatureProfile
class AppFeaturesList(CORSMixin, APIView):
au... | StarcoderdataPython |
3277777 | <reponame>DeliciousLlama/MCturtle
from mcpi.minecraft import Minecraft #Importing MCPI, which is necessary for MCpen
import time #Yet another import (not that important)
from MCpen.mcturtle import MCTurtle, direction #Imports imports imports. (This one is important because it actually import the MCpen library)
#Please ... | StarcoderdataPython |
11330936 | # -*- coding: UTF-8 -*-
from __future__ import print_function, division, absolute_import
from io import StringIO
from numba.annotate.annotate import (Source, Annotation, Intermediate, Program,
A_type, render_text, Renderer)
# _______________________________________________________... | StarcoderdataPython |
6406056 | from django.db import models
from django.contrib.auth.models import User
class Cryptographer(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
points = models.PositiveIntegerField(default=0)
def __str__(self):
return str(self.user)
| StarcoderdataPython |
263947 | <reponame>scopatz/leyline
"""Tools for handling events in the documents."""
from leyline.ast import indent
from leyline.context_visitor import ContextVisitor
class EventsVisitor(ContextVisitor):
def __init__(self, *, initial_event=None, **kwargs):
super().__init__(**kwargs)
self.events = []
... | StarcoderdataPython |
6620248 | from keras_peleenet import peleenet_model
from PIL import Image
import numpy as np
import torchvision.transforms as transforms
def softmax(x):
return np.exp(x)/np.sum(np.exp(x),axis=0)
model = peleenet_model(input_shape=(224, 224, 3))
model.load_weights('peleenet_keras_weights.h5')
file_name = 'synset_words.tx... | StarcoderdataPython |
5112664 | # Generated by Django 3.0.7 on 2021-06-25 17:45
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Redmine_issues',
fields=[
('id', models.Aut... | StarcoderdataPython |
3435605 | import argparse
import pickle
import vgg
import torch
import torch.optim as optim
from torch.utils import data
from HDF5Dataset import HDF5Dataset
import sys
# define the command line parser.
parser = argparse.ArgumentParser(description="""Script to train the GalaxyZoo VGG network on the
... | StarcoderdataPython |
1656325 | from django.contrib.auth import get_user_model
from django.test import SimpleTestCase, TestCase
from django.urls import resolve, reverse
from .views import AboutPageView, HomePageView
class HomePageTests(SimpleTestCase):
def test_home_page_status_code(self):
response = self.client.get("/")
self.a... | StarcoderdataPython |
3556465 | import sys
from typing import Dict, Optional
import click
from cognite.client.exceptions import CogniteAPIError, CogniteNotFoundError
from cognite.transformations_cli.clients import get_client
from cognite.transformations_cli.commands.utils import (
exit_with_cognite_api_error,
get_transformation,
is_id_e... | StarcoderdataPython |
4866800 | BOOST_VERSION = "1.70.0"
def new_boost_library(name, deps = []):
boost_library(name, deps)
boost_build_rule(name)
def boost_library(name, deps = []):
native.cc_library(
name = name,
srcs =
select({
"osx": [
"libboost_{}.a".format(name),
... | StarcoderdataPython |
11377386 | #
# This file is part of pretix (Community Edition).
#
# Copyright (C) 2014-2020 <NAME> and contributors
# Copyright (C) 2020-2021 rami.io GmbH and contributors
#
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General
# Public License as published by the Free... | StarcoderdataPython |
361202 | import aioprocessing
from dataclasses import dataclass
from decimal import Decimal
import os
from pathlib import Path
from typing import Optional, Any, Dict, AsyncIterable, List
from hummingbot.core.event.events import TradeType
from hummingbot.core.utils import detect_available_port
_default_paths: Optional["Gatewa... | StarcoderdataPython |
5031274 | <gh_stars>1-10
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from torch import nn
from configs.constants import Constants
class ConvolutionTransposeBlock(nn.Module):
def __init__(self, width, height, in_channels, out_channels, stride, padding, output_padding, batch_on, relu_on):
super().__init__()
... | StarcoderdataPython |
3287751 | <filename>src/Services/Phonebook/Root.py
from flask.views import MethodView
from flask import jsonify
from Helpers.EndpointList import EndpointList
class Root(MethodView):
def get(self, serviceName):
return jsonify(Endpoints=self.getEndpoints(serviceName))
def getEndpoints(self, serviceName):
... | StarcoderdataPython |
1625163 | #!/usr/bin/env python
#'''
#<NAME>
#'''
import argparse, urllib, os
def parse_downloadFiles_args():
parser = argparse.ArgumentParser(description="Take in a file where the first column holds the url of a file to be downloaded, will overwrite current files if they exist")
parser.add_argument('-f', '--file', type... | StarcoderdataPython |
62639 | <reponame>scionrep/scioncc_new<filename>src/ion/data/persist/test/test_hdf5_persist.py
#!/usr/bin/env python
__author__ = '<NAME>'
from nose.plugins.attrib import attr
import gevent
import yaml
import os
import random
from pyon.util.int_test import IonIntegrationTestCase
from pyon.public import BadRequest, NotFound,... | StarcoderdataPython |
189854 | from lms.lmstests.sandbox.config import celery as celery_config
from lms.lmstests.sandbox.linters import tasks as flake8_tasks
celery_app = celery_config.app
__all__ = ('flake8_tasks', 'celery_app')
| StarcoderdataPython |
4869423 | from GUI import GUI
from HAL import HAL
import math
import numpy as np
# Enter sequential code!
threshold_angle = 0.01
threshold_distance = 0.25
threshold = 0.01
kp = 1.0
while True:
# Enter iterative code!
# creating Objects
currentTarget = GUI.map.getNextTarget()
laser_data = HAL.getLaserData ()
... | StarcoderdataPython |
1791333 | <reponame>sdch10/Storm-time-TEC
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 18 11:02:28 2019
### STORM STUDY FOR SMALLER SPATIO-TEMPORAL AVERAGING ####
@author: sdch10
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
import matplotlib.mlab as mlab
from matpl... | StarcoderdataPython |
354938 | import tkinter as tk
import tkinter.font as tkf
import re
from PIL import ImageTk, Image
from src.utils import *
class StatusPage(tk.Frame):
STAT_LIST = [('공격력', '공격력', '공격력 증가'),
('마력', '마력', '마력 증가'),
('HP 증가', 'HP', 'HP 증가'),
('치명타 확률 증가', '치명타 확률', '... | StarcoderdataPython |
1897467 | <gh_stars>0
# Define a function `plus()`
def plus(a,b):
return a + b
# Create a `Summation` class
class Summation(object):
def sum(self, a, b):
self.contents = a + b
return self.contents
| StarcoderdataPython |
11257391 | <filename>maddpg_implementation/experiments/test.py
import argparse
import numpy as np
import tensorflow as tf
import time
import pickle
import os
import matplotlib.pyplot as plt
import maddpg_implementation.maddpg.common.tf_util as U
from maddpg_implementation.maddpg.trainer.maddpg import MADDPGAgentTrainer
import ten... | StarcoderdataPython |
4821604 | import numpy as np
import warnings
def anisodiff(img,niter=1,kappa=50,gamma=0.1,step=(1.,1.),option=1,ploton=False):
"""
Anisotropic diffusion.
Usage:
imgout = anisodiff(im, niter, kappa, gamma, option)
Arguments:
img - input image
niter - number of iterations
kappa - conduction coefficient 20-100... | StarcoderdataPython |
12806201 | from pathlib import Path
# Project Directories
MODULE_ROOT = Path(__file__).resolve().parent
ROOT = MODULE_ROOT.parent.parent
print(ROOT)
| StarcoderdataPython |
3308574 | <filename>UoSM/lab8.py
# Lab 8 (Online Lab)
# 30 November 2020
# © <NAME>
# Code available on Github https://github.com/yonghuatang/soton1/tree/master/FEEG1001
# Python version 3.8
import numpy as np
import scipy
import matplotlib.pyplot as plt
def trapez(f, a, b, n):
h = (b - a) / n
x_data = np.linspace(a, b... | StarcoderdataPython |
8102885 | import unittest
from conans.test.utils.tools import TestClient
from conans.model.ref import ConanFileReference
import os
class NoCopySourceTest(unittest.TestCase):
def test_basic(self):
conanfile = '''
from conans import ConanFile
from conans.util.files import save, load
import os
class ConanFileToolsTe... | StarcoderdataPython |
3328958 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from setuptools import setup
from setuptools.command.test import test as TestCommand
import pyptouch
class Tox(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True... | StarcoderdataPython |
6408070 | <gh_stars>1-10
print(len('foo')) # print, len | StarcoderdataPython |
5145992 | # my_note/__init__.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
# Importamos as configuracaoes
from config import app_environments
from .admin import admin as admin_blueprint
from .auth import auth as auth_blueprint
from .home import home as home_blueprint
# I... | StarcoderdataPython |
11321482 | <filename>apps/api/bitacoras/url.py
from rest_framework.routers import DefaultRouter
from apps.api.bitacoras.views import BitacoraViewSet
router_bitacoras = DefaultRouter()
router_bitacoras.register(prefix='bitacoras', basename='bitacoras', viewset=BitacoraViewSet)
| StarcoderdataPython |
1869059 | import unittest
import sys
import os
import datetime
try:
from unittest import mock
except:
import mock
import voltverine.plugins
class TestTime(unittest.TestCase):
def test_no_time_provided(self):
voltverine_plugin = voltverine.plugins.Time()
(action, info) = voltverine_plugin.analyze()... | StarcoderdataPython |
346110 | # TODO: Turn this into a generator?
def get_tiles(image, tile_size):
"""Splits an image into multiple tiles of a certain size"""
tile_images = []
x = 0
y = 0
while y < image.height:
im_tile = image.crop((x, y, x+tile_size, y+tile_size))
tile_images.append(im_tile)
if x < i... | StarcoderdataPython |
6420353 | import os
from io import StringIO
import hvplot.pandas # noqa
import pandas as pd # noqa
import panel as pn
import param
import pendulum
from astropy.coordinates import SkyCoord
from astropy.utils.data import download_file
from bokeh.models import (ColumnDataSource, DataTable, TableColumn, NumberFormatter, DateForma... | StarcoderdataPython |
1972652 | <reponame>sungyubkim/cifar_training_jax<gh_stars>0
from typing import Any
from functools import partial
from absl import app, flags
import jax
import jax.numpy as jnp
from jax.flatten_util import ravel_pytree
import flax
from flax import linen as nn
from flax.training import train_state, checkpoints
from flax.jax_utils... | StarcoderdataPython |
8009191 | from nextcord.ext import commands
from nextcord.ext.commands import errors
class Errors(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_command_error(self, ctx, err):
if isinstance(err, errors.MissingRequiredArgument) or isinstance(err, errors.... | StarcoderdataPython |
11354735 | <reponame>atsgen/tf-test
from common.k8s.base import BaseK8sTest
from k8s.network_policy import NetworkPolicyFixture
from tcutils.wrappers import preposttest_wrapper
from test import BaseTestCase
from k8s.namespace import NamespaceFixture
from k8s.pod import PodFixture
from tcutils.util import get_random_name, get_ra... | StarcoderdataPython |
69076 | import numpy as np
class user:
def __init__(self):
self.planned_channel = -1
self.transmission_success = False
print('user creation success')
def choose_channel(self, method, num_channels):
if method == 'uniform':
self.planned_channel = np.random.randint(0, num_chan... | StarcoderdataPython |
8020385 | from django.apps import AppConfig
class TgadmincoreConfig(AppConfig):
name = 'tgadmincore'
| StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.