id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
3357230 | <filename>wormil/migrations/0003_auto_20220513_0208.py
# Generated by Django 3.2.12 on 2022-05-13 02:08
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wormil', '0002_alter_specimen_description'),
]
operations = [
migrations.AddField(
... | StarcoderdataPython |
1704728 | <reponame>ElgaSalvadore/watools
# -*- coding: utf-8 -*-
"""
Authors: <NAME> and <NAME>
UNESCO-IHE 2016
Contact: <EMAIL>
<EMAIL>
Repository: https://github.com/wateraccounting/watools
Module: Collect/CHIRPS
Description:
This module downloads daily and monthly CHIRPS 2.0 data from
ftp://chg-ftpout.geo... | StarcoderdataPython |
3338858 | <reponame>Stanford-PERTS/neptune
"""Project: A team from some organization participating in a program."""
from collections import OrderedDict
from google.appengine.api import memcache, taskqueue
from google.appengine.ext import ndb
import json
import logging
from gae_models import DatastoreModel, CachedPropertiesMode... | StarcoderdataPython |
3259865 | from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
from typing import Callable
from functools import wraps
def plotaxes():
glClear(GL_COLOR_BUFFER_BIT)
glColor3f(1.0,1.0,1.0)
glBegin(GL_LINES)
glVertex2f(0,-100)
glVertex2f(0,100)
glEnd()
glBegin(GL_LINES)
glVerte... | StarcoderdataPython |
96720 | from djitellopy import Tello
import time
tello = Tello()
tello.connect()
user_input = ' '
while user_input != 'x':
user_input = input()
if user_input == 't':
print("takeoff")
tello.takeoff()
if user_input == 'l':
print("land")
tello.land()
... | StarcoderdataPython |
72138 | import logging
class LogHelper():
handler = None
@staticmethod
def setup():
FORMAT = '[%(levelname)s] %(asctime)s - %(name)s - %(message)s'
LogHelper.handler = logging.StreamHandler()
LogHelper.handler.setLevel(logging.DEBUG)
LogHelper.handler.setFormatter(logging.Formatter(F... | StarcoderdataPython |
176240 | <gh_stars>0
## This table will store the daily company earnings
## Of every branch inside the company.
from tools.DataBase.Connect import conection
__maintainer__ = '<NAME>'
__email__ = '<EMAIL>'
__date__ = '1/23/2019'
from sqlalchemy import Column, BIGINT, MetaData, Table
from sqlalchemy.dialects.mysql.base import N... | StarcoderdataPython |
1733625 | # -----------------------------------------------------------------------------
# Common config file for bridge,py, test_bridge.py, etc.
# -----------------------------------------------------------------------------
# For challenges 1 & 2:
Z_SPIN_PERIOD_SECS = 75
Z_SPIN_COMMS_WINDOW_SECS = 15
DO_ORBITAL_BLA... | StarcoderdataPython |
1672722 | # This script tests the Terminal class on computers which are running
# a Linux operating system
from terminal import Terminal
testTerminal = Terminal("test-terminal", "/bin/bash")
terminalOutput = testTerminal.executeCommand("ls")
print(
"The command '" + terminalOutput['executedCommand']
+ "' was executed i... | StarcoderdataPython |
1696366 | <filename>sea5kg_cpplint/__pkginfo__.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2020 <NAME> <<EMAIL>>
# pylint: disable=redefined-builtin,invalid-name
"""sea5kg_cpplint packaging information"""
# For an official release, use dev_version = None
numversion = (0, 0, 2)
version = ".".join(str(num... | StarcoderdataPython |
16616 | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
import log... | StarcoderdataPython |
28856 | <filename>api/model.py<gh_stars>0
from torchvision import models
import json
import numpy as np
import torch
from collections import OrderedDict
from operator import itemgetter
import os
def return_top_5(processed_image):
# inception = models.inception_v3(pretrained=True)
inception = models.inception_v3()
... | StarcoderdataPython |
3331358 | # Generated by Django 2.0.1 on 2018-01-09 18:57
from django.db import migrations, models
import django.db.models.deletion
import djstripe.fields
class Migration(migrations.Migration):
dependencies = [
('djstripe', '0015_auto_20180109_0245'),
]
operations = [
migrations.CreateModel(
... | StarcoderdataPython |
4820005 | <gh_stars>1-10
import re
import copy
from urlparse import urlparse, ParseResult
from util import *
import datetime
class Value(object):
@property
def is_graph(self):
return False
@property
def is_literal(self):
return False
@property
def is_node(self):
return False
@property
def is_resource(self):
... | StarcoderdataPython |
1640897 | <filename>age-dist-german-parliament-population.py
# coding: utf-8
data = np.genfromtxt('data/bundestag-WP18.csv', delimiter=',', skip_header=1)
df = pd.read_csv('data/bundestag-WP18.csv', sep=',')
plt.ion()
df.plot()
plt.hist(data[:,1])
plt.hist(data[:,1])
get_ipython().magic(u'pinfo plt.hist')
plt.hist(data[:,1], r... | StarcoderdataPython |
1607696 | from __future__ import unicode_literals
from django.core.management.base import BaseCommand
from core.import_secondary import import_secondary_schools
class Command(BaseCommand):
help = "Import secondary schools from .csv file"
def handle(self, *args, **options):
import_secondary_schools... | StarcoderdataPython |
3362062 | <reponame>ThomasBollmeier/komparse<filename>src/komparse/translators.py
from .ast import Ast
class TokenType(object):
def __init__(self, token_type, id=""):
self._token_type = token_type
self._id = id
def translate(self, grammar, token_stream):
if not token_stream.has_next():
... | StarcoderdataPython |
1758901 | from typing import Union
from .field import Field
import requests
class Attachment:
def __init__(self, text: str, fallback: str = None, color: Union[str, int] = None, pretext: str = None,
author_name: str = None, author_link: str = None, author_icon: str = None,
fields: Union[Fiel... | StarcoderdataPython |
3378052 | <gh_stars>0
'''
Generates the location data for the data.gov.uk alpha.
'''
import argparse
import json
import traceback
import csv
from pprint import pprint
import requests
import requests_cache
from running_stats import Stats
stats_types = Stats()
stats = Stats()
args = None
max_pk = None
one_day = 60 * 60 * 24
r... | StarcoderdataPython |
3342957 | <gh_stars>0
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2016 kirmani <<EMAIL>>
#
# Distributed under terms of the MIT license.
"""
Timed Petri net for resource controller.
"""
from floor_listener import FloorListener
from ros_cadence.srv import *
from petri_net import *
import ros... | StarcoderdataPython |
103236 | <filename>binding.gyp
{
"variables": {
"GTK_Root%": "c:\\gtk",
"conditions": [
[ "OS == 'mac'", {
"pkg_env": "PKG_CONFIG_PATH=/opt/X11/lib/pkgconfig"
}, {
"pkg_env": ""
}]
]
},
"targets": [
{
"target_name": "rsvg",
"sources": [
"src/Rsvg.cc",
"src/Enums.cc",
"src/Autocrop.c... | StarcoderdataPython |
3363505 | <gh_stars>0
import re
def hyperop(exp: str) -> int:
"""
This function facilitates higher order repetitive operations (hyperoperations) such as tetration.\n
'exp' should be a string of the form: an integer a, followed by one or more *'s, followed by an integer b. Whitespace around args is ignored.\n
... | StarcoderdataPython |
1704486 | <filename>group/migrations/0001_initial.py
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-08-15 01:42
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import taggit.managers
clas... | StarcoderdataPython |
116080 | import numpy as np
import matplotlib.pyplot as plot
time = np.arange(0, 10, 0.1);
amplitude =np.sin(time)
plot.plot(time, amplitude)
plot.title('Sign Wave 1')
plot.xlabel('Time')
plot.ylabel('Amplitude = sin(time)')
plot.grid(True, which='both')
plot.axhline(y=0, color='k')
plot.show()
| StarcoderdataPython |
3244504 | <reponame>jethornton/7i97<filename>7i97/src/lib7i97/pcinfo.py
"""
Usage extcmd.job(self, cmd="something", args="",
dest=self.QPlainTextEdit, clean="file to delete when done")
To pipe the output of cmd1 to cmd2 use the following
Usage extcmd.pipe_job(self, cmd1="something", arg1="", cmd2="pipe to",
arg2, "", dest=self.... | StarcoderdataPython |
4811773 | <gh_stars>0
#!/usr/bin/env python
#
# Cork - Authentication module for tyyhe Bottle web framework
# Copyright (C) 2013 <NAME> and others, see AUTHORS file.
#
# This package is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free So... | StarcoderdataPython |
1602119 | import math
import numpy as _np
import numba as _numba
import contextlib
@contextlib.contextmanager
def corrfunction(shape, z, qmax, xcenter=None, ycenter=None):
"""
CPU based radial Autocorrelation with q correction
parameters:
shape (tuple) of inputs in pixels
z (scalar) distance of detector in... | StarcoderdataPython |
1767271 | """Problem 29 of https://projecteuler.net"""
def problem_29():
"""Solution to problem 29."""
powers = [a ** b for a in range(2, 101) for b in range(2, 101)]
answer = len(set(powers))
return answer
| StarcoderdataPython |
4815259 | from node import Node
class NodeNetwork(object):
''' Handles a collection of nodes in a grid. '''
def __init__(self, d1=5, d2=9):
''' Initialize stuff like the node grid. '''
# TODO?: Consider using numpy arrays
self.node_grid = [[None for b in range(0,d2)] for a in range(0,d1)]
... | StarcoderdataPython |
1713925 | from setuptools import setup
setup(
name='HospitalDBWeb',
version='1.0',
packages=[''],
url='https://github.com/nairachiclana/HospitalDBWeb',
license='MIT',
author='joseroma & nairachiclana',
description='Trabajo de la asignatura de Estandares de datos abiertos e integración de datos.'
)
| StarcoderdataPython |
3252300 | <filename>tcpPC.py
# -*- coding: utf-8 -*-
"""
Created on Mon May 14 16:18:14 2018
@author: fahad
@contributor: <NAME>
"""
import socket
import sys
import time
import tty, termios
#-------------Initialization-----------------------------------
def tcpPC():
# this is the tcp client to connect w... | StarcoderdataPython |
1602096 | <filename>src/data/make_first_raw_dataset.py
from src.utils.utils import get_file_path
import json
from pickle import dump
def import_dataset(dataset_name):
reviews_list = list()
with open(get_file_path("raw\\" + dataset_name + ".json"), encoding="utf8") as json_file:
for line in json_file:
... | StarcoderdataPython |
67999 | import time
import numpy as np
from kid_readout.interactive import *
from kid_readout.measurement import acquire
from kid_readout.roach import r2heterodyne, attenuator, hardware_tools
logger.setLevel(logging.DEBUG)
setup = hardware.Hardware()
ri = hardware_tools.r2h14_with_mk2(initialize=True, use_config=False)
r... | StarcoderdataPython |
3332997 | import redis
def connect_db():
"""Crear conexion a la base de datos."""
conexion = redis.StrictRedis(host='db-rentals',port=6379,db=0, decode_responses=True)
if(conexion.ping()):
print("Conectado al servidor de redis")
else:
print("Error")
return conexion | StarcoderdataPython |
3270064 | #!/user/bin/env python
# -*- coding: utf-8 -*-
"""
------------------------------------
@Project : nightwalker
@Time : 2020/10/13 14:01
@Auth : chineseluo
@Email : <EMAIL>
@File : cli.py
@IDE : PyCharm
------------------------------------
"""
import os
import sys
import pytest
import argparse
from night... | StarcoderdataPython |
1640544 | <reponame>victor-gp/tfg-H16b
import yaml
from os.path import relpath, commonprefix
def parse_job_config(args):
job_config_file = args.job_config
validate(job_config_file)
with open(job_config_file) as f:
job_config = yaml.safe_load(f)
if args.job_type is not None:
job_config['job_type... | StarcoderdataPython |
162993 | <reponame>sqall01/LSMS<filename>scripts/monitor_ssh_authorized_keys.py
#!/usr/bin/env python3
# written by sqall
# twitter: https://twitter.com/sqall01
# blog: https://h4des.org
# github: https://github.com/sqall01
#
# Licensed under the MIT License.
"""
Short summary:
Monitor ~/.ssh/authorized_keys for changes to de... | StarcoderdataPython |
1627872 | <reponame>killapop/hypha
import re
from datetime import timedelta
from bs4 import BeautifulSoup
from django.contrib.auth.models import AnonymousUser
from django.core.exceptions import PermissionDenied
from django.http import Http404
from django.test import RequestFactory, TestCase, override_settings
from django.urls i... | StarcoderdataPython |
148294 | import requests
import os
import sys
def remove_nonpicture_files(arr, file, extensions):
for extension in extensions:
if file.endswith("." + extension):
return
arr.remove(file)
return
print("Running " + sys.argv[0] + " with " + str(len(sys.argv)) + " args...")
if not(len(sys.argv) == 4... | StarcoderdataPython |
3332380 | <filename>ApproachV3/src/spam_metric/multinomial_bayes.py
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn import metrics
import pandas as pd
import pickle
import re
import string
import time
tabl... | StarcoderdataPython |
3312731 | import numpy as np
from tensorflow import keras
from sklearn.model_selection import train_test_split
import os
from numpy import save, load
from sklearn.preprocessing import StandardScaler
root_logdir = os.path.join(os.curdir, "rna_logs")
FILENAME = 'menus.csv'
etapa = '-400relu-300relu'
def get_run_logd... | StarcoderdataPython |
3222803 | from flask import Flask, render_template, request, redirect,send_file
from werkzeug.utils import secure_filename
from functions import split,transform
import io
import os
import pdfrw
from reportlab.pdfgen import canvas
from reportlab.lib.units import cm,mm
# 12 questions adjustments
diff = -0.45*mm#(74.7/2-9.37)*mm
d... | StarcoderdataPython |
113119 | <reponame>Timh37/SeasonalDSLC_NWES<gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 21 16:11:35 2019
Applies change in seasonal anomalies of wind-velocity change from CMIP6 model to ERA5 boundary conditions to ROMS model.
@author: thermans
"""
import numpy as np
import cmocean
import ... | StarcoderdataPython |
111467 | <reponame>MBHuman/NSD_TechSearch
from flask import Flask, render_template, request, send_file
import pickle
from lib.ut.robot import Robot
app = Flask(__name__)
results = []
@app.route('/', methods=['POST', 'GET'])
def index():
error = None
if request.method == 'POST':
search_field = request.form.g... | StarcoderdataPython |
4842136 | # ЗАДАНИЕ ПЕРИОДА ОБНОВЛЕНИЯ ПОКАЗАНИЙ ДАТЧИКОВ:
# Подключаем библиотеку для работы с датчиком температуры и влажности I2C-flash (Sensor Humidity and Temperature).
from pyiArduinoI2Csht import *
from time import sleep
# Объявляем объект sht для работы с функциями и методами библиотеки pyiArduinoI2Csht.
# Если при объ... | StarcoderdataPython |
3260222 | <reponame>bitech-bit/projet<filename>projet.py
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def Afficher(self):
print("L'abscisse est :{}".format(self.x))
print("L'ordonnee est :{}".format(self.y))
class cercle(Point):
def __init__(self, x, y, ... | StarcoderdataPython |
3399006 | <filename>tools/convertCANData.py
# Tool to read in image times and the CANData.csv file and out the interpolated value for each
# car parameter at the time of the image.
import pandas as pd
import numpy as np
import struct
import os
import argparse
def convertToBytes(x):
if len(x) == 1:
x = "0" + x
... | StarcoderdataPython |
3285924 | <filename>sudoku/tests/test_tl.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019-10-20 13:10
# @Author : sean10
# @Site :
# @File : test_tl.py
# @Software: PyCharm
"""
test tui li sudoku from sudokufans.org
"""
import requests
import pytesseract
from PIL import Image
from bs4 import Beautifu... | StarcoderdataPython |
3298635 | from functools import partial
import sqlalchemy as sa
RequiredColumn = partial(sa.Column, nullable=False)
metadata = sa.MetaData()
company = sa.Table(
'companies', metadata,
sa.Column('id', sa.types.Integer, primary_key=True),
RequiredColumn('name', sa.types.String),
RequiredColumn('phone', sa.types.S... | StarcoderdataPython |
4837679 | <filename>wechat_django/tests/test_site_admin.py<gh_stars>100-1000
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from .base import WeChatTestCase
class AdminSiteTestCase(WeChatTestCase):
def test_admin_view(self):
"""测试admin view"""
# 测试request能正确拿到appid
pass
# ... | StarcoderdataPython |
1617510 | """
Lidar
"""
# requies glob to be installed: "pip3 install glob2"
# requires rplidar to be installed: "pip3 install rplidar"
import time
import math
import pickle
import serial
import numpy as np
from donkeycar.utils import norm_deg, dist, deg2rad, arr_to_img
from PIL import Image, ImageDraw
class RPLidar(object):
... | StarcoderdataPython |
3329834 | # coding: utf-8
import glob
import sys
import os
import csv
filedir = sys.argv[2]
outfilename = sys.argv[1]
dup_check = dict()
with open(outfilename, 'wt', encoding='utf-8') as f:
filelist = glob.glob( os.path.join(filedir,"*.csv"))
csv_writer = csv.writer(f, delimiter=',')
for filename in filelist:
try:
... | StarcoderdataPython |
104241 | <gh_stars>0
from keybender import config
from keybender.knox import KnoX
from keybender.listener import Listener
from keybender.event import Event, EventLoop
from keybender.rctl import SocketMgr, SocketSender
import sys
import os
import argparse
import socket
import traceback
"""
argument parser
open named pipe for co... | StarcoderdataPython |
3386453 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import numpy as np
from ax.metrics.noisy_function import NoisyFunctionMetric
from ax.utils.common.typeutils import chec... | StarcoderdataPython |
2861 | import unittest
from http import HTTPStatus
from unittest import TestCase
import bcrypt
from flask.ctx import AppContext
from flask.testing import FlaskClient
from app import create_app
from models.theme import Theme, SubTheme
from models.users import Users
class TestSubTemes(TestCase):
"""
Unittest for the... | StarcoderdataPython |
3252087 | <reponame>mikacuy/point2cyl
import numpy as np
import torch.nn as nn
import torch
from torch.autograd import grad
import torch.nn.functional as F
from general import *
def gradient(inputs, outputs):
d_points = torch.ones_like(outputs, requires_grad=False, device=outputs.device)
points_grad = grad(
outp... | StarcoderdataPython |
1625403 | '''
Various types of "assist", i.e. different methods for shared control
between neural control and machine control. Only applies in cases where
some knowledge of the task goals is available.
'''
import numpy as np
from riglib.stereo_opengl import ik
from riglib.bmi import feedback_controllers
import pickle
from ut... | StarcoderdataPython |
137138 | #!/usr/bin/env python3
file = open('file_example.txt', 'r')
contents = file.read()
file.close()
print(contents)
with open('file_example.txt', 'r') as file:
contents = file.read()
print(contents)
import os
print(os.getcwd())
os.chdir('/Users/denov/Downloads/python-book/')
print(os.getcwd())
os.chdir('/Users/de... | StarcoderdataPython |
1724312 | import inspect
import nest_asyncio
from async_eval import async_eval, asyncio_patch
from . import code
def generate_main_script() -> str:
return "\n".join(
inspect.getsource(m)
for m in (
nest_asyncio,
asyncio_patch,
async_eval,
code,
)
... | StarcoderdataPython |
1608769 | #!/usr/bin/python
#csv upload to gsheet
import logging
import json
import gspread
import time
import re
from oauth2client.client import SignedJwtAssertionCredentials
from Naked.toolshed.shell import muterun_rb
logging.basicConfig(filename='/var/log/gspread.log',format='%(asctime)s %(levelname)s:%(message)s',level=lo... | StarcoderdataPython |
1644216 | # Copyright 2021 The Kubeflow 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | StarcoderdataPython |
106994 | <gh_stars>0
"""Collection of Functions to convert API responses into python objects
and vice versa.
"""
from contextlib import contextmanager
from functools import wraps
from inspect import signature
import json
import re
import pandas as pd
def _dataframe_to_json(payload_df):
payload_df.index.name = 'timestamp... | StarcoderdataPython |
38127 | <filename>idact/detail/deployment_sync/nodes/get_nodes_deployment_definition.py
from idact.detail.deployment_sync.deployment_definition import \
DeploymentDefinition
from idact.detail.deployment_sync.nodes.get_expiration_date_from_nodes \
import get_expiration_date_from_nodes
from idact.detail.nodes.nodes_impl ... | StarcoderdataPython |
1722354 | # This file is auto-generated, don't edit it. Thanks.
from Tea.model import TeaModel
class SegmentAnimalRequest(TeaModel):
def __init__(self, image_url=None):
self.image_url = image_url
def validate(self):
self.validate_required(self.image_url, 'image_url')
def to_map(self):
resu... | StarcoderdataPython |
191035 | import tensorflow as tf
import numpy as np
from utils import get_shape
try:
from tensorflow.contrib.rnn import LSTMStateTuple
except ImportError:
LSTMStateTuple = tf.nn.rnn_cell.LSTMStateTuple
def bidirectional_rnn(cell_fw, cell_bw, inputs, input_lengths,
initial_state_fw=None, initial_sta... | StarcoderdataPython |
1676824 | import collections
import pytest
import itertools
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import cross_val_score
from sklearn.linear_model import LogisticRegression
from sklearn.utils import estimator_checks
from skorecard.bucketers impo... | StarcoderdataPython |
3352149 | from jproperties import Properties
def test_repeated():
p = Properties()
p.load(b"key:value\nkey=the value\nkey = value1\nkey : value2\nkey value3\nkey\tvalue4")
assert p.properties == {"key": "value4"}
def test_repeated_with_meta():
p = Properties()
p.load(b"""
key = value1
#: m... | StarcoderdataPython |
3240447 | <reponame>hitachi-rd-yokohama-sato/deep_saucer
# -*- coding: utf-8 -*-
#******************************************************************************************
# Copyright (c) 2019
# School of Electronics and Computer Science, University of Southampton and Hitachi, Ltd.
# All rights reserved. This program and the ac... | StarcoderdataPython |
1631966 | <filename>hyde/environment.py
from hyde.errors import BaseError
class RuntimeError(BaseError):
pass
class Environment:
def __init__(self, enclosing = None):
self.values = {}
self.enclosing = enclosing
def assign(self, name, value):
if name.lexeme in self.values:
s... | StarcoderdataPython |
1793972 | <filename>pygfx/objects/_base.py
import random
import weakref
import threading
import numpy as np
from ._events import EventTarget
from ..linalg import Vector3, Matrix4, Quaternion
from ..linalg.utils import transform_aabb, aabb_to_sphere
from ..resources import Resource, Buffer
from ..utils import array_from_shadert... | StarcoderdataPython |
147478 | import soundset
# create random score for C3~C5note == 130.8~523.3hz
#-> score object
s1 = soundset.score.random(length=32,tempo=120,beat=16,chord=3,pitch=3,register=25,random_state=None)
# create score piano roll
#-> 2-dim binaly numpy array, size of (length, 128)
roll = s1.to_roll(ignore_out_of_range=False)
assert... | StarcoderdataPython |
147003 | import os
import pusher
import hashlib
from dotenv import load_dotenv
from flask import Blueprint, request
from flask_login import login_required, current_user
from models import Session
project_folder = os.path.dirname(os.path.abspath(__file__))
load_dotenv(os.path.join(project_folder, os.pardir, 'app-env'))
pus... | StarcoderdataPython |
3258974 | import math
import torch.nn as nn
from torch.optim import Adam
from gym import spaces
from common.distributions import *
from common.util import Flatten
def atari(env, **kwargs):
in_dim = env.observation_space.shape
policy_dim = env.action_space.n
network = CNN(in_dim, policy_dim)
optimizer = Adam(n... | StarcoderdataPython |
1697358 | import ujson
import usocket
import _thread
import time
import ussl
DEBUG=1
class VAR:
class auth:
list={}
surl="identitytoolkit.googleapis.com"
class rtdb:
url=None
secret=None
ruleurl=None
apikey=None
socklist={}
authct=None
class rtdb:
def put(PATH, DATA, DUMP=None, bg=True, id=0, c... | StarcoderdataPython |
190369 | import mongoengine
from marvinbot.utils import localized_date
class ChatLink(mongoengine.Document):
source_chat_id = mongoengine.LongField(required=True, null=False)
target_chat_id = mongoengine.LongField(null=True)
first_name = mongoengine.StringField()
user_id = mongoengine.LongField(required=True,... | StarcoderdataPython |
38400 | from vivid.core import BaseBlock, network_hash
def test_network_hash():
a = BaseBlock('a')
b = BaseBlock('b')
assert network_hash(a) != network_hash(b)
assert network_hash(a) == network_hash(a)
c = BaseBlock('c', parent=[a, b])
hash1 = network_hash(c)
a._parent = [BaseBlock('z')]
hash... | StarcoderdataPython |
4832675 | <gh_stars>0
class Solution:
def XXX(self, n: int) -> List[str]:
res=[]
def backtrace(s: str,left: int,right: int):
if left==n and right==n:
res.append(s)
if left<n:backtrace(s+"(",left+1,right)
if right<left:backtrace(s+")",left,right+1)
b... | StarcoderdataPython |
1702259 | <filename>dgen/commands/model/templates/model.py
class [[ name ]](models.Model):
class Meta:
verbose_name = _('[[ name ]]')
verbose_name_plural = _('[[ name ]]s')
ordering = ['id']
[% for field in fields %][[ field ]][% endfor %]
def __str__(self):
return f'[[ name ]]{self.i... | StarcoderdataPython |
1453 | from bs4 import BeautifulSoup
import requests
from urllib.request import urlretrieve
ROOT = 'http://pdaotao.duytan.edu.vn'
def get_url_sub(sub, id_, page):
all_td_tag = []
for i in range(1, page+1):
print('http://pdaotao.duytan.edu.vn/EXAM_LIST/?page={}&lang=VN'.format(i))
r = requests.get('ht... | StarcoderdataPython |
3340084 | from __future__ import unicode_literals
from django.db import models
from django.conf import settings
from decimal import Decimal
from django.utils.translation import pgettext_lazy
from django.utils.timezone import now
from datetime import datetime
from django.contrib.auth.models import (AbstractBaseUser, BaseUserMana... | StarcoderdataPython |
1756772 | <reponame>restful-open-annotation/eve-restoa
#!/usr/bin/env python
"""RESTful Open Annotation server based on Eve.
The RESTful Open Annotation API is primarily implemented using two
ways of modifying the Eve default API:
1. global configuration of keys in settings.py to use OA names,
e.g. "annotatedAt" instead of t... | StarcoderdataPython |
8344 | <filename>dragontail/content/models/basicpage.py<gh_stars>0
# encoding: utf-8
from django.db import models
from wagtail.wagtailcore.models import Page
from wagtail.wagtailcore.fields import StreamField
from wagtail.wagtailcore import blocks
from wagtail.wagtailadmin.edit_handlers import FieldPanel, StreamFieldPanel... | StarcoderdataPython |
48007 | # -*- coding: utf-8 -*-
# (The MIT License)
#
# Copyright (c) 2013-2021 Kura
#
# 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
# ... | StarcoderdataPython |
73684 | <filename>manager/projects/models/snapshots.py
import os
from typing import Optional
import shortuuid
from django.db import models
from django.http import HttpRequest
from django.utils import timezone
from jobs.models import Job, JobMethod
from manager.storage import StorageUsageMixin, snapshots_storage
from projects... | StarcoderdataPython |
4808593 | from random import randint
from sympy import Eq, solve, symbols
from homogeneous import *
def point_on_conic(conic_z_roots, x0, y0):
f, x, y = symbols('f, x, y')
return multiplied(x0, y0, conic_z_roots[randint(0, 1)].subs(x, x0).subs(y, y0))
def main():
a, b, c, d, e, f, x, y, z = symbols('a, b, c, d, e, ... | StarcoderdataPython |
3278377 | """Peak control."""
import logging
from datetime import timedelta
import homeassistant.helpers.config_validation as cv
import voluptuous as vol
from homeassistant.const import (
EVENT_HOMEASSISTANT_START,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_OFF,
)
from homeassistant.core import callback
from homea... | StarcoderdataPython |
1764882 | <filename>pystratis/api/interop/responsemodels/transactionresponsemodel.py
from pydantic import Field
from pystratis.api import Model
from pystratis.core import DestinationChain
from pystratis.core.types import Money, hexstr
class TransactionResponseModel(Model):
"""A pydantic model of a multisig transaction resp... | StarcoderdataPython |
1763573 | <reponame>usgin/nrrc-repository
from django.http import HttpResponseNotAllowed, HttpResponseForbidden
from django.contrib.auth.decorators import login_required
from metadatadb.proxy import proxyRequest, can_edit, hide_unpublished
def oneFile(req, resourceId, fileName):
allowed = [ 'GET', 'DELETE' ]
if req.meth... | StarcoderdataPython |
3340287 | import numpy as np
tinycycle = np.array([[0, 1, 0],
[1, 0, 1],
[0, 1, 0]], dtype=bool)
tinyline = np.array([0, 1, 1, 1, 0], dtype=bool)
skeleton0 = np.array([[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],... | StarcoderdataPython |
67795 | <filename>All Stars Pattern/Hill Pattern.py
"""
Hill Pattern
"""
print("")
n = 5
# Method 1
print("Method 1")
for a in range(n):
for b in range(a, n):
print(" ", end="")
for c in range(a + 1):
print(" * ", end="")
for d in range(a):
print(" * ", end="")
... | StarcoderdataPython |
1629438 | <gh_stars>10-100
#!/usr/bin/env python3
import json
import logging
import sys
import time
import click
import requests
from requests import Response
from bubuku.features.remote_exec import RemoteCommandExecutorCheck
from bubuku.utils import get_opt_broker_id, prepare_configs, is_cluster_healthy, get_max_bytes_in
from... | StarcoderdataPython |
3505 | greeting = """
--------------- BEGIN SESSION ---------------
You have connected to a chat server. Welcome!
:: About
Chat is a small piece of server software
written by <NAME> to allow people to
talk to eachother from any computer as long
as it has an internet connection. (Even an
arduino!). Check out the project at:... | StarcoderdataPython |
1678286 | <filename>pyleecan/Methods/Geometry/PolarArc/discretize.py<gh_stars>10-100
# -*-- coding: utf-8 -*
def discretize(self, nb_point):
"""Returns the discretize version of the PolarArc
Parameters
----------
nb_point : int
number of points wanted per line
Returns
-------
point_list : li... | StarcoderdataPython |
3256900 | <filename>tg_bot/longpool.py
from config import *
from astro_bot_vars import *
from db_functions import *
from sending_functions import *
import telebot
from keyboards import *
bot = telebot.TeleBot(main_token)
print('Лонгпул запущен...')
@bot.message_handler(func = lambda message: message.text.lower() in ["/subscri... | StarcoderdataPython |
59290 | import logging
from dotenv import load_dotenv
import sqlalchemy
import urllib
import pyodbc
import os
ROOT = os.path.dirname(os.path.abspath(__name__))
load_dotenv(os.path.join(ROOT, '.env'))
LOG = logging.getLogger('luigi-interface')
RPT_SERVER = os.environ['SERVER_A']
SCG_SERVER = os.environ['SERVER_B']
RPT_DB =... | StarcoderdataPython |
3273744 | <reponame>GustavoMendel/curso-python<filename>mundo-1/ex029.py
velocidade = int(input('Digite a sua velocidade: '))
if velocidade > 80:
multa = (velocidade - 80) * 7
print('PARE! Você está acima do limite permitido!')
print('Você está a {}Km/h, ultrapassou {}Km/h do limite!'.format(velocidade, velocidade -... | StarcoderdataPython |
30017 | # A python svg graph plotting library and creating interactive charts !
# PyPi: https://pypi.org/project/pygal/
# Docs: http://www.pygal.org/en/stable/index.html
# Chart types: http://www.pygal.org/en/stable/documentation/types/index.html
# Maps: http://www.pygal.org/en/stable/documentation/types/maps/pygal_maps_wor... | StarcoderdataPython |
103299 | <reponame>magical-eda/UT-AnLay
#
# @file util.py
# @author <NAME>
# @date July 2019
# @brief generate coordinate channel embeddings
#
import numpy as np
# Coordinate channel embeddings
def cordinate_img(img):
# img shape (dim, dim, chan)
new_img_x = np.zeros((img.shape))
new_img_y = np.zeros((img.shape))... | StarcoderdataPython |
54073 | # Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from torchvision.models import resnet50, resnet101, resnext101_32x8d
import torch
import torch.nn as nn
import random
import numpy as np
clas... | StarcoderdataPython |
89252 | #!/usr/bin/python3
import os
import os.path
import sys
from bottle import abort, redirect, request, route, run, static_file, template
SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
STATIC_DIR = '{}/static'.format(SCRIPT_DIR)
NAVIGATION_SIZE = 7
PREFETCH_SIZE = 5
ROW_COUNT = 5
LARGE_GALLERY_SIZE = 100
de... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.