id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
4825969 | # -*- coding:utf-8 -*-
# author:Anson
from __future__ import unicode_literals
import sqlalchemy
from sqlalchemy import Table, Column, Integer, String
from sqlalchemy.sql import text
import settings
class Db(object):
def __init__(self, connection='default'):
conn = settings.MYSQL_DATABASES... | StarcoderdataPython |
4839177 | <filename>pandapipes/plotting/geo.py
# Copyright (c) 2020 by Fraunhofer Institute for Energy Economics
# and Energy System Technology (IEE), Kassel. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
from pandapower.plotting.geo import _node_geometr... | StarcoderdataPython |
1729578 | <reponame>n5iln/railmops
'''
Help: provides some basic help facilities
Model Operations Processing System. Copyright <NAME> 2009-2010. Licenced under the EUPL.
You may not use this work except in compliance with the Licence. You may obtain a copy of the
Licence at http://ec.europa.eu/idabc/eupl or as attached... | StarcoderdataPython |
195061 | #! /usr/bin/env python3
## import modules
from Bio import SeqIO
from tqdm import tqdm
import collections
import subprocess as sp
import os
## functions: taxonomy assignment
def tax2dict(acc2tax, taxid, name, accession_dict):
acc_taxid_info = {}
print(f'reading {acc2tax} into memory')
with tqdm(total = os.... | StarcoderdataPython |
162251 | <gh_stars>0
#%%
'''
https://stackoverflow.com/questions/11443302/compiling-numpy-with-openblas-integration
'''
import numpy as np
from time import time
#%% Let's take the randomness out of random numbers (for reproducibility)
np.random.seed(0)
size = 8192
A, B = np.random.random((size, size)), np.random.random((size,... | StarcoderdataPython |
140521 | from django.db import models
from django.utils import timezone
class Books(models.Model):
Name = models.CharField(max_length=100)
Page_Number = models.CharField(max_length=200)
Genre = models.CharField(max_length=50)
pub_date = models.Field(default=timezone.now)
| StarcoderdataPython |
154846 | import os
import copy
import logging
import time
import numpy as np
np.seterr(divide='ignore', invalid='ignore')
from prune import prune
logging_path = os.path.join(os.getcwd(), "text_log.log")
logging.basicConfig(level=logging.INFO,
format="%(levelname)s - %(asctime)s - %(msg)s",
datefmt="%Y-%m-%d %H:%M:%S... | StarcoderdataPython |
3291145 | <reponame>bethunebtj/BigDL<gh_stars>1-10
from bigdl.nn.layer import *
from optparse import OptionParser
from bigdl.nn.criterion import *
from bigdl.nn.initialization_method import *
from bigdl.optim.optimizer import *
from bigdl.transform.vision.image import *
from math import ceil
def t(input_t):
if type(input_t... | StarcoderdataPython |
1720809 | import asyncio
async def hello():
print('Hello Task!')
coroutine = hello()
asyncio.get_event_loop().run_until_complete(coroutine)
| StarcoderdataPython |
29893 | from mixcoatl.admin.billing_code import BillingCode
from mixcoatl.geography.region import Region
from mixcoatl.admin.group import Group
from mixcoatl.admin.user import User
def get_servers(servers, **kwargs):
""" Returns a list of servers
Arguments:
:param servers: a list of servers that needs to be filt... | StarcoderdataPython |
4843012 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
import cloudinary.models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
... | StarcoderdataPython |
1663192 | """
CostCenters v3
"""
from typing import List, Dict
from ..api_base import ApiBase
class CostCenters(ApiBase):
"""Class for CostCenters APIs."""
POST_COST_CENTERS = '/v3/cost_centers'
GET_COST_CENTERS = '/v3/cost_centers'
def get(self, limit: int = None, offset: int = None, **kwargs) -> Dict:
... | StarcoderdataPython |
1672619 | import os
import datetime
import yaml
from api.util.dbconnect import db_instance
from api.providers.configuration import ConfigurationProviderInterfaceV0
from api.util import api_cfg
class ConfigurationProviderException(Exception):
pass
class ConfigurationProvider(ConfigurationProviderInterfaceV0):
def __... | StarcoderdataPython |
3313218 | # Copyright 2017 Catalyst IT Limited
#
# 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 |
1671063 | <reponame>zealoussnow/chromium
# Copyright 2021 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.
"""
Validates the media_metric.
"""
from cli_tools.tbmv3.validators import simple_validator
def CompareHistograms(test_ctx):... | StarcoderdataPython |
3226930 | <gh_stars>0
import datetime as dt
from ravenpy.models import GR4JCN
from ravenpy.utilities.testdata import get_local_testdata
"""
Test to perform a hindcast using Caspar data on THREDDS.
Currently only runs GEPS, eventually will run GEPS, GDPS, REPS and RDPS.
To do so will need to add the actual data from Caspar, cur... | StarcoderdataPython |
4839313 | import difflib
import re
from typing import Optional, Union
from discord.utils import escape_markdown
def wrap_in_code(value: str, *, block: Optional[Union[bool, str]] = None):
value = value.replace("`", "\u200b`\u200b")
value = value.replace("\u200b\u200b", "\u200b")
if block is None:
return "`... | StarcoderdataPython |
140807 | import logging
import ray
from ray.rllib.optimizers.policy_optimizer import PolicyOptimizer
from ray.rllib.utils.annotations import override
from ray.rllib.utils.timer import TimerStat
logger = logging.getLogger(__name__)
class TorchDistributedDataParallelOptimizer(PolicyOptimizer):
"""EXPERIMENTAL: torch distr... | StarcoderdataPython |
4809185 | <filename>test/testp4svn_actions.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''Test cases of perforce to svn replication
'''
import os
import unittest
import tempfile
from testcommon import get_p4d_from_docker
from testcommon_p4svn import replicate_P4SvnReplicate, verify_replication
from lib.buildlogger impor... | StarcoderdataPython |
33029 | from . import configure, core, draw, io, interp, retrieve, qc
__all__ = ["configure", "core", "draw", "io", "interp", "qc", "retrieve"]
| StarcoderdataPython |
4840456 | #!/usr/bin/env python
import rospy
import pymesh
import rospkg
import os
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def extract_centroid_normal_list(mesh_filepath):
mesh = pymesh.load_mesh(mesh_filepath)
mesh.enable_connectivity() # enables connectivity on me... | StarcoderdataPython |
3298301 | # coding=utf-8
"""
``fish_data`` 包含的是一些与数据信息相关的函数,比如银行卡、身份证信息的生成和校验。
在我们进行一些开发测试、功能测试、自动化测试、压力测试等场景下,都需要模拟身份证、银行卡等信息。
fish_data 中的函数就是用在这样的场景。注意,这些函数不会生成真实的身份证和银行卡号。
"""
# 2018.12.9 v1.1.3 created by <NAME>
# 2019.1.13 edit by <NAME>, #202 优化 class CardBin(), class IdCard()
import re
import sqlite3
import os
from ... | StarcoderdataPython |
29198 | <filename>main/views.py
from django.shortcuts import get_object_or_404, render
from django.http import Http404
from .models import MainMetadata
from cal.models import Event
from classes.models import ClassInstance
from cal.models import Event
from datetime import date, timedelta
# Create your views here.
def about(r... | StarcoderdataPython |
1616020 | <reponame>CURG/rpcz
#!/usr/bin/env python
from rpcz import compiler
from os import listdir
from os.path import isfile, join
# compiler.generate_proto('../common/search.proto', '.')
# compiler.generate_proto(
# '../common/search.proto', '.',
# with_plugin='python_rpcz', suffix='_rpcz.py',
# plu... | StarcoderdataPython |
3338183 | import itertools
from datetime import timedelta
from unittest.mock import Mock
from pfun import schedule, success
two_seconds = timedelta(seconds=2)
def test_spaced():
deltas = schedule.spaced(two_seconds).run(None)
assert list(itertools.islice(deltas, 3)) == [two_seconds] * 3
def test_exponential():
... | StarcoderdataPython |
3306195 | # -*- coding: utf-8 -*-
from numpy import *
import pyximport ; pyximport.install()
from munkres_step4 import step1_cython, step2_cython, step3_cython
from munkres_step4 import step4_cython, step5_cython, step6_cython
from munkres_step4 import compute_cost
class Munkres2:
starred = array([])
primed = array(... | StarcoderdataPython |
167319 | <reponame>KartikKannapur/HackerRank
#Problem 20:
#n! means n × (n − 1) × ... × 3 × 2 × 1
#For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
#and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
#Find the sum of the digits in the number 100!
import sympy as sp
def main(num):
val = sp... | StarcoderdataPython |
4802195 | from locust import HttpUser, between, task, tag
class ESGFUser(HttpUser):
host = "http://esgf3.dkrz.de"
wait_time = between(5, 15)
@task
def catalog(self):
query = "/thredds/catalog/catalog.html"
with self.client.get(query, catch_response=True, name="catalog") as response:
... | StarcoderdataPython |
156704 | # from url_encoding import make_url
# full url encoding
import urllib
try: # Python2 and python3 comatible code
from urllib.parse import urlparse
except ImportError:
from urlparse import urlparse
def make_url(string):
'''Encode every char in percentage format'''
return "".join("%{0:0>2}".format(form... | StarcoderdataPython |
156618 | <filename>python/python/linked_list/linked.py
class Node:
"""
this is the constructor.
"""
def __init__ (self, val = None, next = None):
self.val = val
self.next = next
class LinkedList:
"""
stores reference to head node, and interacts with nodes, but is not a node.
"""
... | StarcoderdataPython |
4830836 | <reponame>khramtsova/federated<filename>tensorflow_federated/python/learning/federated_evaluation.py
# Lint as: python3
# Copyright 2019, The TensorFlow Federated 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 obt... | StarcoderdataPython |
1770318 | import json
from collections import namedtuple
from pathlib import Path
import torch
from torch.utils.data import Dataset
from PIL import Image
annotations = namedtuple('Annotations',['image_id','sentences'])
class Flickr8k(Dataset):
""" for flickr 8k dataset."""
def __init__(self, img_dir, ann_file, vocab,... | StarcoderdataPython |
51884 | class Parser:
def __init__(self, *args, **kwargs):
import argparse
self.parser = argparse.ArgumentParser(
description='Request Ray-Triangle computations to the PYNQ-Z1 renderer.')
client_info = 'client: runs on any machine that accesses the PYNQ-Z1 renderer'
server_inf... | StarcoderdataPython |
144795 | <filename>ubcs_auxiliary/other.py<gh_stars>0
"""
advance Sleep functions
author: <NAME>
data: 2017 - Nov 17 2018
functions:
psleep - precision sleep takes
intsleep with inputs t, dt and interupt as a function.
The precision sleep class.
functiob:
psleep - sleep specified amount of time with sub milisecond precision
t... | StarcoderdataPython |
3360634 | from .base import Piece, Color, PieceRepresentation
import numpy as np
class Pawn(Piece):
def __init__(self, color, *args, **kwargs):
"""Initialise bishop, sets color of piece."""
# Initialise bishop with correct symbol
super().__init__(
color,
symbol = PieceReprese... | StarcoderdataPython |
3238580 | <filename>boa3_test/test_sc/class_test/UserClassAccessInstanceVariableOnMethod.py<gh_stars>10-100
from boa3.builtin import public
class Example:
def __init__(self):
self.val1 = 1
self.val2 = 4
def get_val1(self) -> int:
return self.val1
def get_val2(self) -> int:
return s... | StarcoderdataPython |
1637142 | <filename>core/platform/taskqueue/gae_taskqueue_services.py
# coding: utf-8
#
# Copyright 2014 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# ... | StarcoderdataPython |
47715 | <filename>flowsa/NOAA_FisheryLandings.py
# write_NOAA_fisheries_from_csv.py (scripts)
# !/usr/bin/env python3
# coding=utf-8
# <EMAIL>
"""
This script is run on it's own, not through flowbyactivity.py, as data pulled from csv in flowsa.
NOAA fisheries data obtained from: https://foss.nmfs.noaa.gov/apexfoss/f?p=215:20... | StarcoderdataPython |
90841 | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | StarcoderdataPython |
1775418 | # Generated by Django 2.1.7 on 2019-06-05 12:37
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("user", "0022_auto_20190604_1550"),
]
operations = [
migrations.RemoveField(
model_name="user",
name="user_settings",
... | StarcoderdataPython |
1740170 | import os
from setuptools import find_packages, setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='pifttt',
version='0.0.1',
author='<NAME>',
author_email='<EMAIL>',
description='A Python package to simplify sending requests to IFTTT webho... | StarcoderdataPython |
82285 | #!/usr/bin/env python3
import math
class UnitVectors:
"""List of unit vectors"""
def __init__(self, vectors):
self.vectors = vectors
def __getitem__(self, k):
return self.vectors[k % len(self.vectors)]
@staticmethod
def Create(count=8):
step = 360.0 / count
unit_v... | StarcoderdataPython |
3379391 | #!/usr/bin/env python3
"""
Pixel Art Fx
:copyright: 2015 <NAME>.
:license: Apache 2.0.
"""
from setuptools import setup
DESCRIPTION = 'Pixel Art effects'
setup(name='pafx',
version='0.1.0',
description=DESCRIPTION,
author='<NAME>',
author_email='<EMAIL>',
license='Apacke 2.0',
pl... | StarcoderdataPython |
1738792 | from raiden.exceptions import HashLengthNot32
from raiden.utils import sha3, split_in_pairs
# the layers grow from the leaves to the root
LEAVES = 0
MERKLEROOT = -1
def hash_pair(first, second):
""" Computes the keccak hash of the elements ordered topologically.
Since a merkle proof will not include all the... | StarcoderdataPython |
3237850 | <filename>brute-csrf.py<gh_stars>0
import sys,re, requests, random
if len(sys.argv) != 4:
print ('Example python brute-csrf.py http://10.10.10.10/admin/login user wordlist')
sys.exit()
HOST = sys.argv[1]
USER = sys.argv[2]
WORDLIST = sys.argv[3]
PROXY = { 'http':'//127.0.0.1:8080' }
def init_session():
#... | StarcoderdataPython |
133454 | import numpy as np
import pandas as pd
import statsmodels.api as sm
from statsmodels.imputation.bayes_mi import BayesGaussMI, MI
from numpy.testing import assert_allclose
def test_pat():
x = np.asarray([[1, np.nan, 3], [np.nan, 2, np.nan], [3, np.nan, 0],
[np.nan, 1, np.nan], [3, 2, 1]])
... | StarcoderdataPython |
168011 | <reponame>prattl/teamfinder-web
from django.core.management.base import BaseCommand, CommandError
from django.template.loader import render_to_string
from common.models import EmailTag
from tf_auth.models import TFUser
class Command(BaseCommand):
def handle(self, *args, **options):
for user in TFUser.obj... | StarcoderdataPython |
3246655 | <filename>src/combinatory_input/hid.py
import fcntl
import os
import io
import threading
from struct import unpack
from combinatory_processing import source_poll
from .low_level import ImpulseBuffer
INITIAL_VALUES = {
'axis': 0,
'flag': False
}
class StateRegister:
def __init__(self, input_type):
... | StarcoderdataPython |
102763 | from __future__ import absolute_import, division, print_function
import codecs
try:
from collections import OrderedDict
except ImportError:
from ordereddict import OrderedDict
import copy
import os
import os.path as path
import sys
import toml
import nfldb
import nflfan.provider as provider
import nflfan.sco... | StarcoderdataPython |
148760 | import unittest
import json
from PingMePy import PingMeClient
__author__ = 'TheGreatCO'
class PingMeTests(unittest.TestCase):
client = PingMeClient("<EMAIL>", "c954a569-3905-4e51-9590-714be9fafe62",
"http://ec2-52-27-76-79.us-west-2.compute.amazonaws.com:8080")
def get... | StarcoderdataPython |
96585 | <gh_stars>1-10
# agol_operator.py - logic for all AGOL airflow operators
import logging
import os
import json
import hashlib
from datetime import datetime
from pathlib import Path
import requests
from airflow.models.baseoperator import BaseOperator
from airflow.utils.decorators import apply_defaults
# init some vars... | StarcoderdataPython |
127976 | <gh_stars>1-10
# -*- coding: utf-8 -*-
"""
mathdeck.check
~~~~~~~~~~~~~~
This module checks if a user submitted answer is equal to an
answer defined in a problem file.
:copyright: (c) 2014-2016 by <NAME>.
:license: Apache 2.0, see ../LICENSE for more details.
"""
import os
import sys
from mathdeck import load, sett... | StarcoderdataPython |
114543 | import jenkins
import pandas as pd
from kpireport.datasource import Datasource
import logging
LOG = logging.getLogger(__name__)
class JenkinsDatasource(Datasource):
"""Provides accessors for listing all jobs and builds from a Jenkins host.
The Jenkins Datasource exposes an RPC-like interface to fetch all ... | StarcoderdataPython |
1661001 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file './modules/dialogPassword.ui'
#
# Created by: PyQt4 UI code generator 4.12.1
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
de... | StarcoderdataPython |
123991 | '''
The MIT License (MIT)
Copyright (c) 2015 <NAME> - https://github.com/janglapuk/SPB-OpenCV-Recognizer
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 lim... | StarcoderdataPython |
184876 | #!/usr/local/bin/python
import datetime, MySQLdb, os
class db:
def __init__(self, cgibin='../cgi-bin'):
dbd = eval(open(cgibin + '/.dbconnect').read())
self.db = MySQLdb.connect(user=dbd['user'], passwd=dbd['passwd'], db=dbd['db'])
self.cgibin = cgibin
# user functions
def login(self, name, passwd):... | StarcoderdataPython |
1600598 | import os
def getPackages(dir, includePrivates=False):
names = os.listdir(dir)
for name in names:
if name[0] == '_' and not includePrivates:
continue
name_parts = os.path.basename(name).split('.')
if len(name_parts) > 1 and name_parts[1] != 'py':
continue
... | StarcoderdataPython |
1670051 | from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import render
from django.db.models import Q
from iRiffSync.models import iRiffItem
from iRiffSync.iRiffClient import iRiffClient
def index(request):
return render(request, 'searchUI/index.html', {})
def search(request):
... | StarcoderdataPython |
99168 | # This script creates a callable class which runs a single Perceptron
# The perceptron is able to solve the logical OR, the logical AND, but not
# The logical XOR problem. The only library used is numpy.
#
# Code from <NAME>, Machine Learning An Algorithmic Perspective, 2nd edition
# https://seat.massey.ac.nz/pers... | StarcoderdataPython |
3365324 | BBBB BBBBBBBBBBBBBBBBBB
BB BBBBBBBBBBBBBBB
BBBB
XXXX XXXXXXXXX XXXXXXXXXXXXXXXXXBB BBBBBBBBBBBB XXXXXBBBBBBB BBBBBBBBBBBBBBBBB XXXXXXXXBBBBBBB BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB BBBBBBB BBBBBBBBBBBBBBBBB BBBBBXX
BBB BBBBB BB BBBBBBBBBBBB
XX XXXXXXXXXXXX XXXXXXXXXXXXXXXXXXX
... | StarcoderdataPython |
3317099 | <reponame>gitjot/python-for-lccs
# Event: LCCS Python Fundamental Skills Workshop
# Date: May 2018
# Author: <NAME>, PDST
# eMail: <EMAIL>
# Purpose: A loop to draw a square
from turtle import *
# Draw a square using a loop
for count in range(4):
forward(100)
left(90)
| StarcoderdataPython |
1647446 | <reponame>ars-1/Modular<gh_stars>0
from django.urls import path
from Guardian import views
urlpatterns = [
path('signup/', views.SignUp, name='signup'),
path('login/',views.Login, name='login'),
path('logout/',views.Logout,name='logout'),
] | StarcoderdataPython |
1602891 | import os
import numpy as np
import visualize as artist
import matplotlib.pyplot as plt
from matplotlib import rcParams
rcParams['text.usetex'] = True
def jaccard_index(abstract,topic):
abstract = set(abstract)
topic = set(topic)
return len(abstract & topic)/float(len(abstract | topic))
def parse(data):
ans ... | StarcoderdataPython |
117568 | <reponame>ryanjsfx2424/ComputationalFluidDynamicNFTs
import time; start = time.time()
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.font_manager
csfont = {"fontname":"Adobe Garamond Pro"}
TMI = 12
TMA = 14
TIT = 18
LAB = 16
with open("rootroopnft.txt", "r") as fid:
line = fid.read()
# end wit... | StarcoderdataPython |
3336067 | <reponame>ehasting/psybot
import sqlite3
import json
import ast
import os
import sys
import libs.Loggiz as Loggiz
import libs.SerializableDict as SerializableDict
'''
Copyright (c) 2016, <NAME>
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided t... | StarcoderdataPython |
1671652 | #RESOLUÇÃO DO PROFESSOR/LEONARDO:
from time import sleep
import random
print('''Escolha uma opção:
[ 0 ] - PEDRA
[ 1 ] - PAPEL
[ 2 ] - TESOURA ''')
print('-=-'*30)
jog = int(input('Qual é a sua jogada? '))
if jog<0 or jog>2:
print('COMANDO INVÁLIDO, TENTE NOVAMENTE')
exit()
sleep(0.5)
print('PEDRA...')
sleep(1... | StarcoderdataPython |
1615770 | <reponame>ypspy/audit_activity_classification
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 25 23:32:14 2021
@author: yoonseok
"""
from ckonlpy.tag import Twitter
from collections import defaultdict
import os
import pandas as pd
import numpy as np
import re
from tqdm import tqdm
import math
import pickle
from skle... | StarcoderdataPython |
1637039 | import os
import sys
import unittest
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
from common.data.joker import user
from common.model.chrome import Chrome
from common.model.log4p import log
from pages import *
class AuthorizeTest(unittest.TestCase):
def setUp(self):
self.driver = Chrome... | StarcoderdataPython |
150501 | <reponame>AprilXiaoyanLiu/whitenoise-system
from enum import Enum
import numpy as np
class Mechanism(Enum):
gaussian = 1
laplace = 2
geometric = 3
class AdditiveNoiseMechanism:
"""
Adds noise to an exact aggregated quantity.
"""
def __init__(
self, epsilon, *ignore, delta=0.0, sen... | StarcoderdataPython |
4833325 | <reponame>rafalpotempa/image-similarity
import numpy as np
from metrics_engine import MetricsEngine
def test_load_metrics():
# given
engine = MetricsEngine()
expected_metrics_names = ['psnr_metric', 'rmse_metric']
# when
engine.load_metrics('../plugins')
# then
assert len(engine.metrics_list) == 2
metrics_na... | StarcoderdataPython |
1625481 | <reponame>Oliver-Yan-2019/algorithm<filename>Others/CustomerRange/__init__.py
from Others.SequenceABC import Sequence
class CustomerRange(Sequence):
def __init__(self, start, stop=None, step=1):
"""
构造函数, 初始化自定义Range实例
:param start: 起始索引
:param stop: 结束索引
:param step: 步长
... | StarcoderdataPython |
3386009 | # -*- coding: utf-8 -*-
from __future__ import with_statement
import collections
import glob
import json
import os
import os.path
import re
import shutil
import subprocess
import sys
import tempfile
import unittest
import warnings
from six import PY3, StringIO, b, text_type
from werkzeug.test import Client
from werkz... | StarcoderdataPython |
1634889 | <gh_stars>100-1000
import numpy as np
import densmap
from densmap.load_trial import load_trial
try:
import matplotlib.pyplot as plt
import matplotlib.cm as cm
mpl = True
except:
mpl = False
data = load_trial()
print(data.shape)
# densMAP run
print('Running densMAP')
emb, ro, re = densmap.densMAP(verb... | StarcoderdataPython |
135079 |
for index in range(1,101):
# if index % 15 == 0:
# print("fifteen")
if index % 3 == 0 and index % 5 == 0 :
print("fifteen")
elif index % 3 == 0:
print("three")
elif index % 5 == 0:
print("five")
else:
print(index)
| StarcoderdataPython |
4842198 | <reponame>matthewlchambers/flowsa
# USDA_ACUP.py (flowsa)
# !/usr/bin/env python3
# coding=utf-8
"""
Functions to import and parse USDA Chemical Use Survey
"""
import json
import pandas as pd
from flowsa.location import US_FIPS, abbrev_us_state
from flowsa.common import WITHDRAWN_KEYWORD, log
from flowsa.flowbyfunctio... | StarcoderdataPython |
1630807 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import os.path
import stat
import subprocess
import sys
from . import options, util
from .branch import Branch
from .checkout import Checkout
HOOKSCRIPT = """
#!/usr/bin/env bash
set -e; set -o pipefail;
export PATH=$PATH:{path_suffix}
logging_wrapper pypaas g... | StarcoderdataPython |
1733016 | <filename>test_array_slicing.py
import unittest
import numpy as np
from numpy.testing import assert_array_equal
class TestArraySlicing(unittest.TestCase):
def test_slicing_1d(self):
vector = np.arange(10)
assert_array_equal(vector[2:5], np.array([2, 3, 4]))
def test_slicing_1d_with_step(self)... | StarcoderdataPython |
1736561 | <gh_stars>0
import torch
from torch.autograd import Variable
import numpy as np
from train import params
from util import utils
import torch.optim as optim
def train(training_mode, feature_extractor, class_classifier, domain_classifier, class_criterion, domain_criterion,
source_dataloader, target_dataload... | StarcoderdataPython |
1632405 | <reponame>obrmmk/multiese-1<filename>new_corpus/_matplotlib_marker.py
import matplotlib.pyplot as plt
データ列 = [1, 2, 3]
データ列2 = [2, 3, 4]
__X__ = '.'
marker = __X__
'''
@X('.';'o';'^';'v';'<';'>';'x';'X';'s';'D';'*')
@Y(ポイント;丸;[[|上]三角|▲|△];[下三角|▽|▼];左三角;右三角;[バツ|クロス];大バツ;四角;[ダイアモンド|菱形];星)
@alt(マーカー|印)
<オプション>マーカーを__Y... | StarcoderdataPython |
1700195 | <filename>tracker.py
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Polynomial fit values from the previous frame
# Make sure to grab the actual values from the previous step in your project!
left_fit = np.array([2.13935315e-04, -3.77507980e-01, 4.76902175e+02])
right_fit = np.array([4.17622148e-04, ... | StarcoderdataPython |
3385286 | <filename>devices/master/splthread.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import threading
from abc import ABCMeta, abstractmethod
class SplThread(metaclass=ABCMeta):
'''Partly abstract class to implement threading & message handling
'''
def __init__(self, msg_handler, child):
s... | StarcoderdataPython |
1748501 | <reponame>SolarSPELL-Main/DLMS
# Generated by Django 2.1.3 on 2020-02-12 19:36
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('content_management', '0038_auto_20200124_1342'),
]
operations = [
migrations.RemoveField(
model_n... | StarcoderdataPython |
1633620 | <filename>app/request_parsers/hostname.py
import re
from request_parsers import errors
from request_parsers import json
_HOSTNAME_PATTERN = re.compile(r'^[-0-9a-z]{1,63}$')
def parse_hostname(request):
"""
Parses the hostname property from the request.
Checks whether the hostname is valid according to t... | StarcoderdataPython |
3226721 | import numpy
from matplotlib import pyplot
import itertools
import click
@click.command()
@click.option("--length", "-l", default=50, help="Length of the system.")
@click.option("--jex", default=1.0, help="Exchange constant.")
def main(length, jex):
N = length * length
sites = []
spins = []
sites = l... | StarcoderdataPython |
1761113 | import functools
import operator
from pathlib import Path
input_file_name = Path(__file__).with_suffix('.txt').name
with open(Path('2020/inputs') / input_file_name) as f:
data = f.readlines()
# def write():
# with open(Path('2020/inputs') / input_file_name, 'w') as f:
# for line in data:
# ... | StarcoderdataPython |
3234409 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__title__ = 'pyloghandlers'
__description__ = 'A python log handler packages with supported Multi-process'
__version__ = '0.0.3'
__url__ = 'https://github.com/ugvibib/pyloghandlers'
__author__ = 'ugvibib'
__author_email__ = '<EMAIL>'
__license__ = 'Apache License Version ... | StarcoderdataPython |
1732791 | import pandas as pd
from sklearn.model_selection import StratifiedShuffleSplit, ShuffleSplit
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_extraction.text import CountVectorizer
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from sklearn.metrics i... | StarcoderdataPython |
4835868 | from flask_restful import Resource
import requests
pomber_covid_stats = requests.get('https://pomber.github.io/covid19/timeseries.json')
coronastatistics_url = 'http://api.coronastatistics.live'
class Stats(Resource):
def get(self):
return {'status': 'success', 'data': pomber_covid_stats.json()}, 200
... | StarcoderdataPython |
138188 | import base64
from _hashlib import HASH
from dataclasses import dataclass
from hashlib import md5
from io import DEFAULT_BUFFER_SIZE
from typing import IO, Callable
@dataclass()
class Hash(object):
_h: HASH
def digest(self) -> bytes:
return self._h.digest()
def hexdigest(self) -> str:
re... | StarcoderdataPython |
1678326 | <filename>source/heartbeats/soundwav_util.py
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from scipy.io import wavfile
import os
def convert_to_spectrogram(wav_file, class_label):
rate, data = get_wave_info(wav_file)
nfft = 256 # Length of the windowing segments
fs = 256 # Sa... | StarcoderdataPython |
199684 | from dataclasses import dataclass
from collections import defaultdict
from functools import lru_cache
from typing import Dict, List
import json
import warnings
from scipy.spatial import distance as spd
from torch.distributions.categorical import Categorical
from tqdm import tqdm
import joblib
import langdetect
import ... | StarcoderdataPython |
1736533 | from datetime import timedelta as td
from django.conf import settings
from django.core.signing import base64_hmac
from django.utils.timezone import now
from hc.api.models import Check
from hc.test import BaseTestCase
class BadgeTestCase(BaseTestCase):
def setUp(self):
super(BadgeTestCase, self).setUp()... | StarcoderdataPython |
116515 | from snovault import (
upgrade_step,
)
@upgrade_step('workflow_run_awsem', '1', '2')
@upgrade_step('workflow_run_sbg', '1', '2')
@upgrade_step('workflow_run', '1', '2')
def workflow_run_1_2(value, system):
'''Change input_files.format_if_extra to FileFormat'''
formats = system['registry']['collections']['... | StarcoderdataPython |
182707 | <reponame>pierpaolofiore/A001026<filename>04-Cloud_Computing-Managing_Data-Environmental_Data/NetCDF2Cloud/slice.py<gh_stars>0
from netCDF4 import Dataset
from os import mkdir, path, remove, makedirs
import numpy as np
from time import perf_counter
import json
from sys import exit
import sys
if not sys.warnoptions:... | StarcoderdataPython |
3209541 | # coding: utf-8
r"""
>>> from django.contrib.comments.models import Comment
>>> from django.contrib.auth.models import User
>>> u = User.objects.create_user('commenttestuser', '<EMAIL>', '<PASSWORD>pw')
>>> c = Comment(user=u, comment=u'\xe2')
>>> c
<Comment: commenttestuser: â...>
>>> print c
commenttestuser: â...
""... | StarcoderdataPython |
1773577 | #Fibonacci up to n
def user_input(min, max):
digits = 0
while ( min > digits or digits > max):
digits = input("Enter number, n, between {} and {} to generate fibonacci up to n: ".format(min, max))
try:
digits = int(digits)
except:
digits = 0
return digits
... | StarcoderdataPython |
3323684 | <reponame>williamliee/crptobotwill<gh_stars>1000+
""" RSI Indicator
"""
import math
import pandas
from talib import abstract
from analyzers.utils import IndicatorUtils
class RSI(IndicatorUtils):
def analyze(self, historical_data, period_count=14,
signal=['rsi'], hot_thresh=None, cold_thresh=Non... | StarcoderdataPython |
1738896 | from elapsedTimerPy import elapsedTimer
timer = elapsedTimer.Timer()
timer.set_start()
tmp1 = [i for i in range(10000)]
timer.add_point("point1")
tmp2 = [i for i in range(10000)]
timer.set_end()
timer.print()
| StarcoderdataPython |
1737085 | <reponame>volfpeter/markyp-bootstrap4
"""
CSS class names for coloring.
See https://getbootstrap.com/docs/4.0/utilities/colors/ for more information.
"""
__all__ = ("bg", "text")
class __Background(object):
"""
CSS class names for background coloring.
"""
__slots__ = ()
@property
def prim... | StarcoderdataPython |
3343719 | from tqdm import tqdm
import os
import shutil
import numpy as np
import pandas as pd
from models import *
from metrics import *
import time
import datetime
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
from torch.autograd import Variable
import torch.uti... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.