id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
3371075 | """
This quiz will generate chord symbols for you to play.
It's designed for when you're with your instrument, to practice playing
different chords.
"""
import sys
from datetime import datetime as dt
from time import sleep
from src.chords import generate_random_chord
def countdown(seconds):
for i in range(second... | StarcoderdataPython |
3213137 | import numpy as np
import xarray as xr
grav = 9.81
cp = 1004
Lc = 2.5104e6
rho0 = 1.19
def metpy_wrapper(fun):
"""Given a metpy function return an xarray compatible version
"""
from metpy.units import units as u
def func(*args):
def f(*largs):
new_args = [u.Quantity(larg, arg.uni... | StarcoderdataPython |
3239453 |
import ast
from gemini.utils import *
from gemini.code_tree.code_node_leaf import CodeNodeLeaf
from ..transformer.import_module_transformer import ImportModuleTransformer
from .pass_base import PassBase
__all__ = [
'ImportModulePass',
]
class ImportModulePass(PassBase):
__slots__ = [
'_solvers',
... | StarcoderdataPython |
1704666 | <filename>Collect/SRTM/DEM.py
# -*- coding: utf-8 -*-
"""
Authors: <NAME>
Module: Collect/SRTM
"""
import os
from pyWAPOR.Collect.SRTM.DataAccess import DownloadData
import sys
def main(Dir, latlim, lonlim, Waitbar = 1):
"""
Downloads HydroSHED data from http://srtm.csi.cgiar.org/download
this data inclu... | StarcoderdataPython |
1649095 | # Python code for calculating communication efficiency of a network.
# The reference articles for the computed measure:
# <NAME>., and <NAME>. (2001). Efficient behavior of small-world networks. Physical Review Letters 87.
# <NAME>., and <NAME>. (2003). Economic small-world behavior in weighted networks. Eur Phys J B 3... | StarcoderdataPython |
47629 | # Generated by Django 3.0.11 on 2020-12-09 06:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('telephone_directory', '0002_auto_20201208_1801'),
]
operations = [
migrations.AddField(
model_name='contacts',
name... | StarcoderdataPython |
1621113 | <filename>scripts/VCF/QC/plot_variants_density.py<gh_stars>1-10
from VcfQC import VcfQC
import argparse
import os
#get command line arguments
parser = argparse.ArgumentParser(description='Script to get the variant density for a certain VCF file')
parser.add_argument('--bedtools_folder', type=str, required=True, hel... | StarcoderdataPython |
20215 | <gh_stars>0
from .utils import *
class Filter(object):####TODO add logging
def __init__(self, measure, cutting_rule):
"""
Basic univariate filter class with chosen(even custom) measure and cutting rule
:param measure:
Examples
--------
>>> f=Filter("PearsonCor... | StarcoderdataPython |
3324905 | <gh_stars>1-10
#!/usr/bin/env python
import rospy
from std_msgs.msg import Bool
from std_msgs.msg import Float32
from std_msgs.msg import Float64
speed = 0.3
steering_angle = 0.5
def servo_commands():
rospy.init_node('servo_commands', anonymous=True)
pub_vel_left_front_wheel = rospy.Publisher('/jetsoncar/fr... | StarcoderdataPython |
122548 | from django.apps import AppConfig
class MemberConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = 'apps.member'
verbose_name = '회원'
swagger_tag = dict(name='사용자 API 목록', description='')
def ready(self):
from . import signals
| StarcoderdataPython |
4824227 | # Licensed to the StackStorm, Inc ('StackStorm') 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, Version 2.0
# (the "License"); you may not use th... | StarcoderdataPython |
143652 | <reponame>moeyensj/atm
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import numpy as np
import pandas as pd
from ..config import Config
from ..constants import Constants
from ..helpers import __handleParameters
from .hg import calcHG
from .hg import calcQ
from .temperature import calcTss
from .blackbody import calcPl... | StarcoderdataPython |
1749413 | <filename>torrent_client/network/tracker_clients/__init__.py
from urllib.parse import urlparse
from torrent_client.models import DownloadInfo
from torrent_client.network.tracker_clients.base import *
from torrent_client.network.tracker_clients.http import *
from torrent_client.network.tracker_clients.udp import *
from... | StarcoderdataPython |
3271828 | #!/usr/bin/env python
from __future__ import division
import argparse
import numpy as np
import os
import GPy
import matplotlib.pyplot as plt
from fipy import *
from scipy.interpolate import griddata
from pdb import set_trace as keyboard
import time
import random
seed=19
os.environ['PYTHONHASHSEED'] = '0'
# Settin... | StarcoderdataPython |
94431 | <reponame>MesoSim/chase<gh_stars>0
#!/usr/bin/env python
"""
Main API Control
================
Using Flask-RESTful, this script hosts the resources for the full frontend API
"""
#########
# Setup #
#########
# Imports
from datetime import datetime, timedelta
import os
import pytz
from sqlite3 import dbapi2 as sql
im... | StarcoderdataPython |
1683624 | <reponame>mmaaz60/DCL<filename>models/Asoftmax_linear.py
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
from torch.nn import Parameter
import math
def myphi(x,m):
x = x * m
return 1-x**2/math.factorial(2)+x**4/math.factorial(4)-x**6/math.factorial(6) + \
... | StarcoderdataPython |
57288 | from .models import ToDoList
from rest_framework.generics import ListAPIView
from rest_framework import permissions
from api.serializers import ToDoSerializerList
from django.db import connection
from rest_framework.response import Response
class ToDoListView(ListAPIView):
permission_classes = (permissions.AllowA... | StarcoderdataPython |
33067 | # Escreva um programa que pergunte a quantidade de Km
# percorridos por um carro alugado e a quantidade de dias pelos
# quais ele foi alugado. Calcule o preço a pagar, sabendo que o carro
# custa R$60 por dia e R$0.15 por Km rodado.
km = float(input("Quantos km percorreu?: "))
dia = int(input("Quantos dias ele foi alu... | StarcoderdataPython |
4816039 | <filename>pythonv4/ScharfSandhiTest.py<gh_stars>1-10
"""
ScharfSandhiTest.py May 22, 2015
Jul 20, 2015
May 11, 2020. Revise for python3
"""
from scharfsandhi import ScharfSandhi
def simple_sandhioptions(code,sandhi):
if (code == 'C'):
sandhi.sandhioptions("C","N","S","")
elif (code == 'E'):
sandhi.sand... | StarcoderdataPython |
172368 | from .enums import *
from .structs import *
from .api import *
| StarcoderdataPython |
1656736 | <gh_stars>0
import os
import boto3
import json
import csv
s3 = boto3.resource('s3')
bucket = s3.Bucket('tracking-metrics')
# Iterates through all the objects, doing the pagination for you. Each obj
# is an ObjectSummary, so it doesn't contain the body. You'll need to call
# get to get the whole body.
with open('flor... | StarcoderdataPython |
97668 | #!/usr/bin/env python
#
# :History:
#
# 10 Aug 2018: Created.
#
# @author: <NAME> (UKATC)
#
"""
Script `cdp_correct_wildcard` corrects wildcard references within CDP metadata.
Prior to the CDP-7 release, MIRI CDPs would set a metadata keywords to 'ANY'
to indicate that the CDP was valid for any variant of that CDP (... | StarcoderdataPython |
46530 | <filename>paws/lib/python2.7/site-packages/requestbuilder-0.7.1-py2.7.egg/requestbuilder/mixins/formatting.py
# Copyright (c) 2012-2016 Hewlett Packard Enterprise Development LP
#
# Permission to use, copy, modify, and/or distribute this software for
# any purpose with or without fee is hereby granted, provided that th... | StarcoderdataPython |
3252473 | import threading
from modules.const import Const
from modules.lib.agent_utils import get_mac
from modules.lib.report_queue import ReportQueue
from modules.lib.reporter_manager import ReporterManager
from modules.things_cloud.device import ThingsCloudDevice
from modules.things_cloud.operation_handler import OperationDis... | StarcoderdataPython |
3320615 | <gh_stars>0
import cv2
import numpy as np
from keras.models import load_model
from img_processing import scale_and_centre
def predict(img_grid):
image = img_grid.copy()
image = cv2.resize(image, (28, 28))
image = image.astype('float32')
image = image.reshape(1, 28, 28, 1)
im... | StarcoderdataPython |
120016 | from datetime import datetime
import json
import os
import shutil
import sys
from django.contrib.auth.models import User
from django.core.management import call_command
from django.core.management.base import BaseCommand
from django.utils.dateparse import parse_datetime
from django.utils.timezone import utc
from djang... | StarcoderdataPython |
192302 | <reponame>tamahassam/farmer
from .plot_history import plot_history
from .history import * | StarcoderdataPython |
43470 | <filename>galleries/sql/queries/data_retriever.py<gh_stars>0
import abc
import numpy as np
from typing import List, Any, Dict, Optional
from galleries.annotations_filtering.filter import FilterStatement
class SqlDataRetriever:
@abc.abstractmethod
def get_indices(self, cursor, filters: List[List[FilterStatem... | StarcoderdataPython |
1685463 | <gh_stars>1-10
#!/usr/bin/env python3
# This script is used to publish Cargo to crates.io.
import os
import re
import subprocess
import time
import urllib.request
from urllib.error import HTTPError
TO_PUBLISH = [
'crates/cargo-platform',
'crates/crates-io',
'.',
]
def already_published(name, version):... | StarcoderdataPython |
4805466 | import sys as _sys
if _sys.version_info < (3,5):
raise RuntimeError('expectorant requires Python 3.5 or higher but the current vesion is: {}.{}'.format(_sys.version_info.major, _sys.version_info.minor))
from . import spec
from . import singletons
from .expector import * # all the matchers
from .runner import loa... | StarcoderdataPython |
1738971 | <filename>examples/Cluster-based_Input_Weight_Initialization_for_Echo_State_Networks.py<gh_stars>10-100
import time
import glob
import os
import numpy as np
import pandas as pd
from sklearn.base import clone
from sklearn.metrics import make_scorer
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from skl... | StarcoderdataPython |
3351102 | import unittest
from datetime import datetime
from botocore.stub import Stubber
from freezegun import freeze_time
from datahub.ingestion.api.common import PipelineContext
from datahub.ingestion.source.glue import GlueSource, GlueSourceConfig, get_column_type
from datahub.ingestion.source.metadata_common import Metada... | StarcoderdataPython |
6973 | <gh_stars>0
import logging
TRACE_LVL = int( (logging.DEBUG + logging.INFO) / 2 )
| StarcoderdataPython |
169353 | # -*- coding: utf-8 -*-
import django.contrib.admin.helpers
from ajaximage.utils import format_image
from django.contrib.admin.utils import display_for_field
from django.core.files.storage import default_storage
from django.db.models import Field
from django.db.models.fields.files import FileDescriptor, ImageFieldFile
... | StarcoderdataPython |
3232521 | # coding: utf-8
"""
Subscriptions
Subscriptions allow contacts to control what forms of communications they receive. Contacts can decide whether they want to receive communication pertaining to a specific topic, brand, or an entire HubSpot account. # noqa: E501
The version of the OpenAPI document: v3
... | StarcoderdataPython |
94032 | <reponame>zazaho/SimImg
''' The basic object that represents one file '''
import os
import hashlib
from datetime import datetime
from PIL import Image, ExifTags
from ..utils import pillowplus as PP
class FileObject():
' File object that contains all information relating to one file on disk '
def __init__(sel... | StarcoderdataPython |
1750208 | <filename>run/runPS_Recycle.py
import os
import numpy as np
import platform_paths as pp
EXE = 'stat_stokes'
EXE = 'peri_stokes'
i = 6
n = str(2**i+1)
woms = np.array([0.01, 0.05, 0.1, 0.5, 1., 5, 10., 50, 100., 225])
woms = 10**np.linspace(-2, 3, 5)
oms = woms
case_consts = ' --domain=2 --flow=5 --nx='+n+' --ny='+n... | StarcoderdataPython |
147783 | """Summary info about tickets."""
# :license: MIT, see LICENSE for more details.
import click
from SoftLayer.CLI.command import SLCommand as SLCommand
from SoftLayer.CLI import environment
from SoftLayer.CLI import formatting
@click.command(cls=SLCommand)
@environment.pass_env
def cli(env):
"""Summary info abou... | StarcoderdataPython |
1666183 | num1 = int(input('Digite o primeiro número: '))
num2 = int(input('Digite o segundo número: '))
if num1 > num2:
print('O primeiro valor é maior.')
elif num2 > num1:
print('O segundo valor é maior.')
else:
print('Os dois valores são iguais.')
'''elif num1 == num2:
print('Não existe valor maior, os dois n... | StarcoderdataPython |
4812909 | <gh_stars>0
"""Example using Advanced Array Filters with Statistics, Math and Logic"""
# Dependencies
import numpy as np
# Website analytics data:
# (row = day), (col = users, bounce, duration)
a = np.array([[815, 70, 115],
[767, 80, 50],
[912, 74, 77],
[554, 88, 70],
... | StarcoderdataPython |
152469 | #!/usr/bin/env python
"""Unique Crater Distribution Functions
Functions for extracting craters from model target predictions and filtering
out duplicates.
"""
from __future__ import absolute_import, division, print_function
from PIL import Image
import matplotlib
import cv2
import matplotlib.pyplot as plt
import numpy... | StarcoderdataPython |
3342669 | <reponame>marketredesign/pricecypher_python_api<filename>src/pricecypher/collections/scope_value_collection.py
from pricecypher.collections.base_collection import BaseCollection
from pricecypher.models import ScopeValue
class ScopeValueCollection(BaseCollection):
_type = ScopeValue
def __repr__(self):
... | StarcoderdataPython |
3218741 | import contextlib
import os
import threading
from textwrap import dedent
import unittest
import time
from test import support
from test.support import import_helper
_interpreters = import_helper.import_module('_xxsubinterpreters')
from test.support import interpreters
def _captured_script(script):
r, w = os.pipe... | StarcoderdataPython |
1713116 | <gh_stars>1-10
"""
Instagram插件: 有搜索接口可用
"""
import json
import traceback
import requests
from commonbaby.httpaccess.httpaccess import HttpAccess
from datacontract import IscoutTask
from idownclient.clientdatafeedback.scoutdatafeedback import NetworkProfile
from idownclient.scout.plugin.scoutplugbase import ScoutPlugB... | StarcoderdataPython |
3230008 | <gh_stars>100-1000
import torch
import torch.nn as nn
from torch.nn import init
def weights_init_cpm(m):
classname = m.__class__.__name__
# print(classname)
if classname.find('Conv') != -1:
m.weight.data.normal_(0, 0.01)
if m.bias is not None: m.bias.data.zero_()
elif classname.find('BatchNorm2d') != -... | StarcoderdataPython |
15794 | import napari
import time
from napari._qt.qthreading import thread_worker
import numpy as np
# create a viewer window
viewer = napari.Viewer()
# https://napari.org/guides/stable/threading.html
@thread_worker
def loop_run():
while True: # endless loop
print("Hello world", time.time())
time.sleep(0.... | StarcoderdataPython |
160260 | <reponame>zywkloo/Insomnia-Dungeon
import pygame
from helper_functions import *
##################################################################################################
class Item:
item_data = {}
for item in csv_loader('item.csv'):
item_data[item[0]] = {'function':item[1],'name': item[2],'sprite':item... | StarcoderdataPython |
3352546 |
#consider a string as follows
s = "Harry and Hermione along with Ron went to Hogwarts to learn magic and also win battle against Lord Voldemort"
#basic slicing format is s[startindex:stopindex:stepvalue(optional)] where stop index is not inclusive
# space is also considered as a charcater
print(s[0:7]) # print... | StarcoderdataPython |
3290129 | import argparse
import os
import sys
import pyfmt
DEFAULT_PATH = os.getenv("BASE_CODE_DIR", ".")
DEFAULT_LINE_LENGTH = int(os.getenv("MAX_LINE_LENGTH", "100"))
def main():
parser = argparse.ArgumentParser(prog="pyfmt")
parser.add_argument(
"path",
nargs="?",
default=DEFAULT_PATH,
... | StarcoderdataPython |
156782 | <filename>examples/python/partner_data.py<gh_stars>0
# For demonstration this will serve as the database of partners
# For real implementation this will come from a database.
# Both partnerId and key should be shared between services.
partners = {
'abcd123' : { # this is partner ssoId (abcd123)
'name'... | StarcoderdataPython |
3356625 | <gh_stars>1-10
#
# Copyright 2011-2013 Blender Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | StarcoderdataPython |
3344922 | # coding: utf-8
"""
Collection of builder functions
"""
from typing import Callable, Optional, Generator
import torch
from torch import nn
from torch.optim.lr_scheduler import _LRScheduler, ReduceLROnPlateau, \
StepLR, ExponentialLR
from torch.optim import Optimizer
from joeynmt.helpers import ConfigurationError
... | StarcoderdataPython |
1731686 | <filename>LuoguCodes/AT1476.py
from math import *
def isp(x):
if x <= 1: return False
if x == 2: return True
for i in range(2, int(x ** 0.5) + 1):
if x % i == 0: return False
return True
def sim(x):
return x % 2 != 0 and x % 3 != 0 and x % 5 != 0
n = int(raw_input())
print [';Not Prime';,... | StarcoderdataPython |
3259494 | <gh_stars>0
import pymysql
import pandas as pd
import joblib
from sklearn.metrics import mean_squared_error
import numpy as np
# Guname = AA,BB,CC..... factor: light_num,schoolnum.... value 1,2,3,10,20....
def return_graph_data(GuName,factor):
connection = pymysql.connect('localhost' ,'root','123123','dev')
... | StarcoderdataPython |
3211157 | from app.infrastructure.smtp import Mail, create_message
from app.pkgs.token import TokenFactory
from flask import render_template
class EmailService(object):
token_factory: TokenFactory
def __init__(self, mail: Mail, default_mail_sender: str, token: TokenFactory):
self.mail = mail
self.mail... | StarcoderdataPython |
165917 | import os
def prepare_videos(
videos, extension, start, duration, kinect_mask=True, width=1920, height=1080
):
video_start_secs = start % 60
video_start_mins = start // 60
print(f"Dumping frames and segmenting {len(videos)} input videos")
for i, video in enumerate(videos):
try:
... | StarcoderdataPython |
3322202 | """Module with main parts of NSGA-II algorithm.
Contains main loop"""
from nsga2.utils import NSGA2Utils
from nsga2.population import Population
class Evolution(object):
def __init__(self, problem, num_of_generations, num_of_individuals):
self.utils = NSGA2Utils(problem, num_of_individuals)
... | StarcoderdataPython |
3352795 | <reponame>Frikallo/YAKbot
import torch
import wandb
from argparse import ArgumentParser
import model
import sys
class dotdict(dict):
"""dot.notation access to dictionary attributes"""
__getattr__ = dict.get
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
def load_ckpt(args):
"""... | StarcoderdataPython |
3356806 | <reponame>no1xsyzy/bgmtinygrail
import queue
import threading
from bgmtinygrail.model_link.accounts import all_accounts
from bgmtinygrail.tinygrail.api import *
xsb_player = all_accounts['xsb_player']
NUM_F_WORKERS = 4
call = queue.Queue()
back = queue.Queue()
cid_set = []
def main():
for cid in range(1, 1000... | StarcoderdataPython |
3323339 |
from math import sqrt
def vdot(u, v):
assert len(u) == len(v)
tot = 0.0
if hasattr(u, "keys"):
for i in u:
tot += u[i] * v[i]
else:
for i in xrange(len(u)):
tot += u[i] * v[i]
return tot
def vproj(u, v):
return vmuls(v, vdot(u, v) / vmag(v)**2)
de... | StarcoderdataPython |
3368554 | <reponame>benhoyt/pythondotorg<filename>jobs/forms.py
from django import forms
from django.forms.widgets import CheckboxSelectMultiple
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from django_comments_xtd.conf import settings as comments_settings
from django_comments_xtd.for... | StarcoderdataPython |
94817 | <reponame>nyquist-h/premock<filename>reggaefile.py
from reggae import object_files, link, Build, user_vars, optional
san_opts = ""
if 'production' in user_vars:
san_opts = '-fsanitize=address'
includes = [".", "example/cpp/test", "example/src",
"example/deps", "example/cpp/mocks"]
common_flags = san_... | StarcoderdataPython |
46648 | <filename>paleomix/nodes/bedtools.py<gh_stars>0
#!/usr/bin/python
#
# Copyright (c) 2012 <NAME> <<EMAIL>>
#
# 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 with... | StarcoderdataPython |
1621705 | <filename>osx/devkit/plug-ins/scripted/pyVertexBufferGenerator.py<gh_stars>1-10
# Copyright 2015 Autodesk, Inc. All rights reserved.
#
# Use of this software is subject to the terms of the Autodesk
# license agreement provided at the time of installation or download,
# or which otherwise accompanies this software in e... | StarcoderdataPython |
1602044 | <filename>pac_maker.py
import sys
import shutil
import os
from typing import Iterable
pacjsminified = """\
al=JSON.parse('allowlist')
bl=JSON.parse('blocklist')
proxy="__PROXY__",direct="DIRECT;",proxy=="__PRO"+"XY__"&&(proxy=eval("__PRO"+"XY__")),hop=Object.hasOwnProperty;function FindProxyForURL(i,r){if(hop.call(al... | StarcoderdataPython |
1740727 | <filename>app/src/app_factory.py
from fastapi import FastAPI
from settings import settings # noqa
from logger import configure_logger
def app_factory():
configure_logger()
app = FastAPI(title="VideoStreamer",)
from api.api_v1.api import api_router
app.include_router(api_router)
return app
| StarcoderdataPython |
34581 | import cv2
import urllib
import numpy as np
import multiprocessing as mp
stream = 'http://192.168.53.114:8000/streamLow.mjpg'
stream2 = 'http://192.168.53.114:8001/streamLow.mjpg'
def procImg(str, wind, stop):
bytes = ''
stream = urllib.urlopen(str)
while not stop.is_set():
try:
bytes... | StarcoderdataPython |
3333763 | sentence_file_path = '/home/tim/Documents/NLP/electronics/electronics_large.csv'
sentence_remapped_file_path = '/home/tim/Documents/NLP/electronics/electronics_balanced_large.csv'
label_cnt = {}
def fiveToThreeClasses(label):
if label == '1' or label == '2':
return -1
elif label == '3':
retur... | StarcoderdataPython |
4836999 | from cleo.testers import CommandTester
from tests.helpers import get_package
def test_show_basic_with_installed_packages(app, poetry, installed):
command = app.find("show")
tester = CommandTester(command)
cachy_010 = get_package("cachy", "0.1.0")
cachy_010.description = "Cachy package"
pendulum... | StarcoderdataPython |
3305874 | <filename>utils.py
import copy
import os
import sys
from collections import Counter
import numpy as np
from PIL import Image
from tifffile import tifffile
from skimage.segmentation import slic
def openImage(img_path):
if "jpg" in img_path or "png" in img_path:
image = Image.open(img_path).convert('RGB')... | StarcoderdataPython |
1627059 | import os
import autofit as af
from test_autolens.integration import integration_util
from test_autolens.simulate.interferometer import simulate_util
from autofit.optimize.non_linear.mock_nlo import MockNLO
def run(
module,
test_name=None,
non_linear_class=af.MultiNest,
config_folder="config",
po... | StarcoderdataPython |
3227795 | <reponame>alekseydemidov/gcp_snap<filename>gcp_snap.py
#!/usr/bin/python3
#from __future__ import print_function
import argparse
from datetime import datetime,timedelta,timezone
import time
from google.oauth2 import service_account
import googleapiclient.discovery
def parse_args():
#Arguments parsing
parser = arg... | StarcoderdataPython |
1755829 | <gh_stars>0
import time
import json
class TTLeague:
def __init__(self, setCount=3):
self.setCount = setCount
def __str__(self):
return str(self.__dict__)
class Match:
def __init__(self, player1, player2):
# type: (Player, Player) -> None
self.timestamp = int(time.time() ... | StarcoderdataPython |
3378709 | <reponame>pmatigakis/vedette
from uuid import uuid4
from django.contrib.auth.models import User
from django.test import Client, TestCase
from django.urls import reverse
from events.tests.factories import EventFactory
class EventDetailsTests(TestCase):
def setUp(self):
super(EventDetailsTests, self).setU... | StarcoderdataPython |
36575 | import discord
import subprocess
import os, random, re, requests, json
import asyncio
from datetime import datetime
from discord.ext import commands
class Economy(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
print('[+] Trashmoney Code AC... | StarcoderdataPython |
187058 | from collections import defaultdict
from datetime import datetime, timedelta, time
from django.template.loader import render_to_string
from django.utils.translation import ugettext as _
from jsonobject.properties import DateTimeProperty
from corehq.apps.app_manager.models import ApplicationBase
from corehq.apps.users.... | StarcoderdataPython |
99271 | <reponame>vis7/django_pytest_fixture_tutorial
from django.test import TestCase
from django.contrib.auth.models import Group, User
# # simple test
def test_foo():
assert True
# accessing database
def test_should_create_user_with_username(db):
user = User.objects.create_user("Haki")
assert user.username == ... | StarcoderdataPython |
108498 | from setuptools import setup
setup(name='wiggum',
version='0.2',
description='utilities to detect simpson\'s paradox',
url='http://github.com/brownsarahm/DetectSimpsonParadox',
author='<NAME>, <NAME>, <NAME>',
author_email='<EMAIL>',
license='MIT',
packages=['wiggum', 'wiggum_... | StarcoderdataPython |
1657481 | <reponame>Tenchi2xh/DNAP
import scrapy
import time
class thinkgeek(scrapy.Spider):
name = __name__
start_urls = ["https://www.thinkgeek.com/collectibles/vinyl-records/"]
def parse(self, response):
scrape_time = time.time()
for div in response.css(".product"):
yield {
... | StarcoderdataPython |
1664618 | <reponame>praiseG/DABS-Django-Backend<gh_stars>1-10
from django.contrib import admin
from .models import Patient
# Register your models here.
class PatientModelAdmin(admin.ModelAdmin):
list_display = (
'name',
'email',
'mobile',
'age',
'disability',
'registered_by',... | StarcoderdataPython |
3240582 | <gh_stars>10-100
# cec2017.functions
# Author: <NAME>
# Combines simple, hybrid and composition functions (f1 - f30) into a single
# module
from .simple import *
from .hybrid import *
from .composition import *
all_functions = [
f1, f2, f3, f4, f5, f6, f7, f8, f9, f10,
f11, f12, f13, f14, f15, f16, f... | StarcoderdataPython |
4812273 | from setuptools import setup, find_packages
setup(
name="testbuilder",
version="0.2.32",
packages=find_packages(),
description="A python testing framework for frontend testing",
package_data = {
'': ['*.csv', '*.yaml'],
},
install_requires=[
"click==6.7",
"PyYAML==... | StarcoderdataPython |
78948 | <gh_stars>0
import requests
BASE = "http://127.0.0.1:5000/"
# putResponse = requests.put(BASE + "classify/", {'beacon1': 1, 'beacon2': 2, 'beacon3':3, 'location': 0})
# putResponse = requests.put(BASE + "classify/", {'beacon1': 2, 'beacon2': 2, 'beacon3':3, 'location': 0})
# putResponse = requests.put(BASE + "classif... | StarcoderdataPython |
158196 | # Checks mouse position on windows
import pyautogui as pa
import time
while True:
try:
pa.moveTo(2563, 171, duration=.25)
pa.click()
pa.moveRel(10, 0, duration=.25)
for i in range(12):
pa.moveRel(0, 50, duration=0.5)
time.sleep(3)
time.sleep(8)
except KeyboardInte... | StarcoderdataPython |
1765683 | <reponame>kgaughan/sterechrome_v2<filename>komorebi/html.py
"""
HTML parsing and serialisation support.
"""
import dataclasses
from html import escape
from html.parser import HTMLParser
import io
import logging
logger = logging.getLogger(__name__)
__all__ = [
"Element",
"escape",
"Parser",
]
# See: http... | StarcoderdataPython |
26435 | NAMES = [
'IL13stimulation',
'Rec',
'Rec_i',
'IL13_Rec',
'p_IL13_Rec',
'p_IL13_Rec_i',
'JAK2',
'pJAK2',
'SHP1',
'STAT5',
'pSTAT5',
'SOCS3mRNA',
'DecoyR',
'IL13_DecoyR',
'SOCS3',
'CD274mRNA',
]
for idx, name in enumerate(NAMES):
exec(
'{} = {:d... | StarcoderdataPython |
3354930 | """
This file handles question related HTTP request.
"""
from flask import request
from flask_restplus import Resource
from flask_jwt_extended import jwt_required
from flask_jwt_extended.exceptions import NoAuthorizationError,InvalidHeaderError,RevokedTokenError
from jwt import ExpiredSignatureError, InvalidTokenError... | StarcoderdataPython |
4802814 | import math
num = int(input("Digite um número: "))
print(f'O dobro de {num} é {num*2}')
print(f'O triplo de {num} é {num*3}')
print(f'A raiz quadrada de {num} é {math.sqrt(num):.2f}')
'''
Outras opções de raiz quadrada
pow(num,0.5)
num ** 0.5
''' | StarcoderdataPython |
99571 | <gh_stars>10-100
# coding: utf-8
# # R转Python
# ## 6.2 统计分析
# ### (1)数据读入
# In[7]:
# 导入Python做数据处理的模块pandas,并取别名为pd
# 导入numpy模块,并取别名为np
# 从pandas模块中导入DataFrame和Series类
import pandas as pd
import numpy as np
# In[10]:
#设置当前工作目录
#【注】“当前工作目录”的含义为文件和文件夹的读写路径
os.chdir('H:\PythonProjects')
print(os.getcwd())
... | StarcoderdataPython |
3344804 | from pprint import pprint
from configparser import ConfigParser
from powerbi.client import PowerBiClient
# Initialize the Parser.
config = ConfigParser()
# Read the file.
config.read('config/config.ini')
# Get the specified credentials.
client_id = config.get('power_bi_api', 'client_id')
redirect_uri = config.get('p... | StarcoderdataPython |
149456 | ###############################################
##<NAME>, 2021##
##Topo-Seq data analysis##
# Classify TCSs by localization in IGRs or if in TU than by strand orientation which is cleaved.
###############################################
#######
#Packages to be imported.
#######
import random as rd
import matplotlib... | StarcoderdataPython |
3202193 | <gh_stars>0
nombreFichero = "ejemplo1.txt";
fichero = open(nombreFichero,"w");
fichero.write("Este es un ejemplo de escritura\n");
fichero.write("Este es otro ejemplo de escritura\n");
fichero.write("\n");
for item in range(1,11):
fichero.write("%d\n" % item);
fichero.close();
fichero = open(nombreFichero,"r");
r... | StarcoderdataPython |
151063 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2018-03-09 14:01
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('submissions', '0003_auto_20170821_1735'),
]
operations = [
migrations.Alter... | StarcoderdataPython |
153995 | <reponame>yangjiahao106/LeetCode<gh_stars>1-10
#! python3
# __author__ = "YangJiaHao"
# date: 2018/3/2
class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
时间复杂度 O(m + n)
"""
if not matrix:
... | StarcoderdataPython |
1666478 | <reponame>filvarga/vpp-tests
#!/usr/bin/env python
from sys import stderr
from subprocess import Popen, PIPE
from os import walk, listdir
from os.path import join
from argparse import ArgumentParser
def check_output(args, stderr=None):
return Popen(args, stdout=PIPE, stderr=stderr).communicate()[0]
class Device... | StarcoderdataPython |
3295381 | <reponame>ruixuantan/FourParts
from fourparts.structures.notes.Notes import Notes
from fourparts.structures.Scales import Scales
class Key:
"""Represents all 24 keys.
Attributes
----------
key : str
As represented in KEYS
pitchcenter : str
One of the 12 notes in Notes.NOTES.
s... | StarcoderdataPython |
3363605 | <gh_stars>1-10
# import the pandas, os, sys, and pprint libraries
import pandas as pd
import os
import sys
import pprint
# import the respondent class
sys.path.append(os.getcwd() + "/helperfunctions")
import respondent as rp
import importlib
importlib.reload(rp)
pd.set_option('display.width', 150)
pd.set_option('displ... | StarcoderdataPython |
170908 | from . import invocation_support
from . import invocation_trace_support
| StarcoderdataPython |
127167 | na, nb = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a = set(a)
b = set(b)
t = len(a & b)
t2 = len(a.union(b))
print(t/t2)
| StarcoderdataPython |
1626573 | <filename>hikka/__init__.py
from flask_limiter.util import get_remote_address
from flask import Flask, render_template
# from hikka.modules import descriptors
# from hikka.modules import comments
# from hikka.modules import statuses
# from hikka.modules import episodes
from hikka.modules import account
from hikka.modul... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.