id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
1848915 | """
Classes for Repo providers
Subclass the base class, ``RepoProvider``, to support different version
control services and providers.
"""
from datetime import timedelta
import json
import os
import time
from prometheus_client import Gauge
from tornado import gen
from tornado.httpclient import AsyncHTTPClient, HTTP... | StarcoderdataPython |
1731652 | <reponame>JosephChataignon/pyclustering
"""!
@brief Templates for tests of Local Excitatory Global Inhibitory Oscillatory Network (LEGION).
@authors <NAME> (<EMAIL>)
@date 2014-2020
@copyright BSD-3-Clause
"""
from pyclustering.nnet.legion import legion_network;
from pyclustering.nnet import conn_type;... | StarcoderdataPython |
6409494 | <reponame>UACoreFacilitiesIT/UA-Clarity-LIMS-Tools
"""Tools that interact with Clarity's REST database."""
import os
import re
import argparse
from dataclasses import dataclass, field, astuple
from collections import namedtuple
import requests
from bs4 import BeautifulSoup, Tag
from jinja2 import Template
from ua_clari... | StarcoderdataPython |
3373408 | """
Utility functions for gathering data from Google Datastore Query
objects.
"""
def has_filter(query, col_and_operator):
"""
query: A Cloud Datastore Query object
col_and_operator: tuple of column name and operator
"""
for col, operator, value in query.filters:
if (col, o... | StarcoderdataPython |
4815923 | def f(x):
loops = 0
if x<100:
loops = x*5
else:
if x<200:
loops = x*10
else:
if x<300:
loops = x*15
else:
loops = x*20
for i in xrange(loops):
t=0 | StarcoderdataPython |
5044522 | #!/usr/bin/env python3
"""Star Wars API HTTP response parsing"""
# pprint helps make things like dictionaries more human-readable
from pprint import pprint
# requests is used to send HTTP requests (get it?)
import requests
URL= "https://swapi.dev/api/people/1"
def main():
"""getting at the JSON attached to this... | StarcoderdataPython |
11391827 | # Generated by Django 3.1.1 on 2020-10-28 16:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ramaelectric', '0023_auto_20201028_1138'),
]
operations = [
migrations.AlterModelOptions(
name='items',
options={'ge... | StarcoderdataPython |
12823275 | """Convert epidemic forecasts into JSON files for online viewing."""
import datetime
import errno
import h5py
import json
import logging
import numpy as np
import os.path
import pypfilt.summary
from . import settings
fs_fmt = "%Y-%m-%d %H:%M:%S"
d_fmt = "%Y-%m-%d"
def dtime(dstr):
"""Convert datetime strings ... | StarcoderdataPython |
8126516 | <gh_stars>0
from beautifuldict.baseconfig import Baseconfig
from decouple import config
from pkg_resources import resource_filename
params = {
'path': {
'input': resource_filename(__name__, 'data/input/'),
'output': resource_filename(__name__, 'data/output/')
},
'value_labels': {
... | StarcoderdataPython |
12853923 | <filename>losses.py
import tensorflow as tf
from tensorflow.keras import backend
#DEPRECATED
# An implementation of wasserstein used for a naive implementation of WGAN
# calculate wasserstein loss
def wasserstein_loss(y_true, y_pred):
return backend.mean(y_true * y_pred)
# Define the loss functions for the discrimi... | StarcoderdataPython |
5097832 | <reponame>marteinn/wagtail-text-analysis
from django.db import models
from django.utils.translation import ugettext_lazy as _
from wagtail.core.models import Page
from wagtail.admin.edit_handlers import FieldPanel
from wagtailtextanalysis.text_analysis import (
TextAnalysis,
KeyPhrasesField,
SentimentField... | StarcoderdataPython |
6620895 | import sys
def helloWorld(args, params):
to = 'World'
if params['variables']['to'] != '':
to = params['variables']['to']
text = 'Hello, {}'.format(to)
if params['toggle']['excited']:
text += '!'
print(text)
commands = {
'hello': {
'function': helloWorld,
'comm... | StarcoderdataPython |
3366201 | from .generic_arch import *
from .lm32 import * | StarcoderdataPython |
1794922 | import pandas as pd
from sklearn.model_selection import StratifiedKFold
if __name__ == '__main__':
df = pd.read_csv('input/train.csv')
# Creating the dummy column
df['kfold'] = -1
# Shuffle the data and reseting the indices
df = df.sample(frac=1).reset_index(drop=True)
# Creating the KFolds
... | StarcoderdataPython |
12850405 | """Modelo de pacientes"""
# Django
from django.db import models
# Utilidades
from apis.utils.models import ModelUtil
class Memberships(ModelUtil):
"""Modelo de pacientes
Un paciente puede tener un grupo familiar asociado,
si el paciente crea el grupo sera el titular de la familia,
los miembros del ... | StarcoderdataPython |
3352850 | import re
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers, exceptions
class CreateEmergencycodeSerializer(serializers.Serializer):
description = serializers.CharField(required=True)
activation_delay = serializers.IntegerField(required=True)
emergency_auth... | StarcoderdataPython |
4924822 | # _*_ coding: utf-8 _*_
__author__ = 'LelandYan'
__date__ = '2019/5/16 19:32'
import numpy as np
import cv2
import matplotlib.pyplot as plt
import copy
from pylab import mpl
import skimage
# 防止中文乱码
mpl.rcParams['font.sans-serif'] = ['SimHei']
class processing_image:
def __init__(self, filename="./raw_data/1.jpg",... | StarcoderdataPython |
150191 | from typing import Callable
from typing import Tuple
from astrolib.base_objects import Matrix
from astrolib.base_objects import TimeSpan
def integrate(t_0: TimeSpan, X_0: Matrix, h: TimeSpan, dynamics_func: Callable[[TimeSpan, Matrix],Matrix]) -> Tuple[TimeSpan, Matrix, TimeSpan]:
""" Function utilizes a first-o... | StarcoderdataPython |
3278479 | <reponame>kurisufriend/modular-discord-bot-fw<gh_stars>0
"""
the "hello world" (if you will) of the plugin system.
there are only two required parts:
* 'hooks': a list of dispatch events to run() on
* run(event, ctx, bot): the function to run on-event, where event is the trigger,
ctx is the 'd'(data) key of the res... | StarcoderdataPython |
6419803 | <filename>azure/functions/__init__.py
from ._abc import HttpRequest, TimerRequest, InputStream, Context, Out # NoQA
from ._http import HttpResponse # NoQA
from ._queue import QueueMessage # NoQA
| StarcoderdataPython |
3268922 | from django.db import models
class User(models.Model):
first_name = models.CharField(max_length=200)
last_name = models.CharField(max_length=200)
age = models.PositiveSmallIntegerField(range(5, 100))
class Event(models.Model):
event_name = models.CharField(max_length=200)
creator_id = models.For... | StarcoderdataPython |
323194 | <filename>advanced_modules/lv2_os_app_history_analyzer.py
# -*- coding: utf-8 -*-
"""module for LV2."""
import os, sys
from datetime import datetime
from advanced_modules import manager
from advanced_modules import interface
from advanced_modules import logger
from dfvfs.lib import definitions as dfvfs_definitions
c... | StarcoderdataPython |
1998227 | <filename>Outdated/RNN_draft.py
from keras.models import Model
from keras.layers import Input, LSTM, Dense
import numpy as np
# vectorize data
input_text = []
output_text = []
input_character = set()
output_character = set()
def make_dictionary (fname):
content = []
with open(fname, 'r') as f:
content... | StarcoderdataPython |
3293220 | <reponame>ShengyuH/PredateOverlap
import time
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0.0
self.sq_sum = 0.0
self.count = 0
... | StarcoderdataPython |
3530102 | import sqlite3
import subprocess
# Get the restore point
res_pt = raw_input("Enter the restore point date\n")
# Restoring
script = "cd backups & sqlite3 Restored_DB.db < "+ res_pt + ".bak"
restore = subprocess.Popen(script, shell = True)
restore.wait()
print("Database Restored successfully")
restore.kill() | StarcoderdataPython |
1788357 | <gh_stars>10-100
import random
from context_creator import ContextCreator
# returns a random TARGET context for the wordset and parameters supplied to the constructor
class RandomContextCreator(ContextCreator):
def __init__(self, word_list, num_contexts=5000, length_bounds=[6,12], tagset=set([0])):
self.w... | StarcoderdataPython |
8006395 | <filename>Fundamentals/Exercises/Basic_Syntax_Lab/5_patterns.py
char = '*'
num = int(input())
for i in range(num):
print(char*(i+1))
for i in reversed(range(num-1)):
print(char*(i+1)) | StarcoderdataPython |
11322838 | <reponame>CAVED123/reinvent-randomized
import random
import math
import numpy as np
import scipy.stats as sps
import torch
import torch.utils.data as tud
import torch.nn.utils as tnnu
import models.dataset as md
import models.vocabulary as mv
import utils.chem as uc
import utils.tensorboard as utb
class Action:
... | StarcoderdataPython |
94310 | <reponame>mojaie/kiwiii-server<filename>kiwiii/test/parser/test_helper.py
#
# (C) 2014-2017 <NAME>
# Licensed under the MIT License (MIT)
# http://opensource.org/licenses/MIT
#
import os
import unittest
from kiwiii.parser import helper
TEST_FILE = os.path.join(
os.path.dirname(__file__),
"../../../resources/... | StarcoderdataPython |
5094885 | <reponame>AustralianDisabilityLimited/MultiversePlatform<filename>client/Scripts/SceneQuery.py<gh_stars>10-100
#
# The Multiverse Platform is made available under the MIT License.
#
# Copyright (c) 2012 The Multiverse Foundation
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of ... | StarcoderdataPython |
3414177 | <gh_stars>0
from functools import reduce
from typing import List
from bscscan.enums.actions_enum import ActionsEnum as actions
from bscscan.enums.fields_enum import FieldsEnum as fields
from bscscan.enums.modules_enum import ModulesEnum as modules
from bscscan.enums.tags_enum import TagsEnum as tags
class Accounts:
... | StarcoderdataPython |
11358863 | <reponame>miguelgrinberg/circular-dependencies-webcast<filename>myapp/api.py
from flask import url_for, jsonify, request, Blueprint
from myapp import db
from myapp.models.user import User
from myapp.models.message import Message
api = Blueprint('api', __name__)
@api.route('/users', methods=['POST'])
def new_user():
... | StarcoderdataPython |
1849202 | import json
import networkx as nwx
from networkx.readwrite import json_graph
global G
G=nwx.DiGraph()
global dummy
def edges():
print list(G.edges_iter(data='weight', default=-999))
def newGraph():
global G
G=nwx.DiGraph()
def addedge(s,t,w):
global G
G.add_edge(s,t,weight=w)
def savejson():
... | StarcoderdataPython |
1638543 | # -*- coding: utf-8 -*-
import json
from fastapi import APIRouter, File, HTTPException, UploadFile
from loguru import logger
from xmltodict import parse as xml_parse
from xmltodict import unparse as xml_unparse
router = APIRouter()
@router.post("/xml-json", status_code=201)
async def convert_xml(
myfile: Upload... | StarcoderdataPython |
3463020 | <filename>instagramy/core/requests.py<gh_stars>10-100
""" Wrapper for urllib.request """
import random
from typing import Any
from urllib.request import Request, urlopen
from .user_agent import user_agents
def get(url: str, sessionid=None) -> Any:
"""
Function send the HTTP requests to Instagram and
Log... | StarcoderdataPython |
132000 | # Copyright 2014 Kylincloud
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... | StarcoderdataPython |
387912 | from pinout import core, config
from pinout.components.layout import Group
class Swatch(Group):
"""Graphical icon for display in LegendEntry"""
def __init__(self, width=None, height=None, **kwargs):
super().__init__(**kwargs)
self.update_config(config.legend["entry"]["swatch"])
width ... | StarcoderdataPython |
1979352 | import numpy as np
def run(df, docs):
for doc in docs:
doc.start("t23 - Ano", df)
df['failed_last_year'] = 0
max_grade = df['ano'].max()
df['failed_last_year'][df['ano'] == max_grade] = 1
for doc in docs:
doc.end(df)
return df
| StarcoderdataPython |
9682483 | <reponame>xaviml/z2m_ikea_controller
from typing import TYPE_CHECKING, Any, Dict, Optional, Set
from appdaemon.plugins.hass.hassapi import Hass
from cx_const import DefaultActionsMapping
from cx_core.integration import EventData, Integration
if TYPE_CHECKING:
from cx_core.controller import Controller
class Home... | StarcoderdataPython |
296981 | import numpy as np
import pytest
from hashlib import md5
from pathlib import Path
from xml.etree import ElementTree as ET
from readimc import IMCMcdFile
class TestIMCMCDFile:
damond_mcd_file_path = Path("data/Damond2019/20170814_G_SE.mcd")
@classmethod
def setup_class(cls):
if cls.damond_mcd_fi... | StarcoderdataPython |
4972512 | <gh_stars>0
#######################################
############### Imports ###############
#######################################
from kafka import KafkaProducer
from kafka import KafkaConsumer
#import re
#import os, errno
from time import time
from datetime import timedelta
from atexit import register
import sys
f... | StarcoderdataPython |
270149 | <gh_stars>0
__all__ = ["decoder"]
def decoder(x: list) -> int:
x = int(str("0b" + "".join(reversed(list(map(str, x))))), 2)
return x | StarcoderdataPython |
11209242 | <reponame>brutzl/pymbs
import threading
import time
class PyMbsThread(threading.Thread):
def __init__(self, function, realTime=False):
threading.Thread.__init__(self)
self.execute = False
self.function = function
self.realTime = realTime
self.scaling = 1
# Start-Ti... | StarcoderdataPython |
9719777 | from dotenv import load_dotenv
import discord
from discord.ext import commands
from discord.ext.commands import has_permissions
import asyncio
import random
import os
load_dotenv()
# intents = discord.Intents.default()
# intents.members = True
# client = discord.Client(intents=intents)
intents = discord.Intents(messa... | StarcoderdataPython |
8111395 | <gh_stars>0
# -*- coding: utf-8 -*-
"""
面包多Pay签名算法实现
Doc: https://doc.mbd.pub/api/qian-ming-suan-fa
"""
from hashlib import md5
def sign(attributes: dict, payjs_key: str) -> str:
attributes_new = {k: attributes[k] for k in sorted(attributes.keys())}
sign_str = "&".join(
[f"{key}={attribut... | StarcoderdataPython |
3571315 | <gh_stars>1-10
class Emoji:
def __init__(self):
self.id = None
self.code = None
self.code_point = None
self.name = None
self.short_name = None
self.has_tone = False
self.tone = 0
self.emoji_order = None
self.keywords = set()
self.catego... | StarcoderdataPython |
3275180 | from metaflow.api import step, FlowSpec
# Note that the explicit `FlowSpec` inheritance here is optional (it will be added by the `Flow` metaclass if omitted).
# Including it helps IntelliJ to analyze/syntax-highlight member accesses downstream.
#
# Some functionality, like referencing `self.input` in a join step, get... | StarcoderdataPython |
1972334 | <filename>dalib/adaptation/__init__.py
from . import proto
__all__ = ["proto"]
| StarcoderdataPython |
3211537 | <reponame>olgam4/design3
import cv2
from vision.domain.iCamera import ICamera
from vision.domain.iCameraFactory import ICameraFactory
from vision.infrastructure.fallbackCamera import FallbackCamera
from vision.infrastructure.openCvCamera import OpenCvCamera
class OpenCvCameraFactory(ICameraFactory):
def __init__... | StarcoderdataPython |
1671547 | import os
from musicscore.musictree.treescoretimewise import TreeScoreTimewise
from musurgia.unittest import TestCase
from musurgia.fractaltree.fractalmusic import FractalMusic
from musurgia.fractaltree.fractalmusicsquare import Square
path = str(os.path.abspath(__file__).split('.')[0])
def set_tempo(square):
... | StarcoderdataPython |
4936076 | # -*- coding: utf-8 -*-
""" A visualization widget for Orange3.
This is a visualization widget for Orange3, that displays a joint distribution of two
variables from a dataset. The Widget is a two-dimensional kernel-density estimate graph
using Gaussian kernels. The Kernel density estimation (KDE) is a met... | StarcoderdataPython |
5038498 | <gh_stars>0
#!/usr/bin/env python3
"""Build transition matrix estimators"""
import csv
import os
import random
import sys
from typing import Callable, List, Tuple
import lightgbm as lgb
import numpy as np
from scipy.special import softmax
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection ... | StarcoderdataPython |
3446886 | <filename>Protheus_WebApp/Modules/SIGAGTP/GTPA115BTestCase.py
from tir import Webapp
from datetime import datetime
DataSystem = datetime.today().strftime('%d/%m/%Y')
import unittest
import time
class GTPA115B(unittest.TestCase):
@classmethod
def setUpClass(inst):
inst.oHelper = Webapp()
#Parametros de ini... | StarcoderdataPython |
11281366 | """
Azure Training admin
"""
from django.contrib import admin
from .models import Project, Task, Train
# Register your models here.
admin.site.register(Project)
admin.site.register(Task)
admin.site.register(Train)
| StarcoderdataPython |
11361510 | <gh_stars>1-10
from __future__ import print_function
import six
import sys
import os
import traceback
from Technical.SaveLog import SaveLog
if six.PY3:
unicode = str
sys.stdout = SaveLog()
print(os.path.basename(__file__))
__author__ = 'BS-DEV-QT-VFOURRIER'
__documentation__ = ''
| StarcoderdataPython |
6631631 | import ssa
import numpy as np
import matplotlib.pyplot as plt
def run():
reactants = np.array([[2, 0], [0, 1]])
products = np.array([[0, 1], [2, 0]])
volume = 1e-15
use_na = True
k_det = np.array([5e5, 0.2])
k1 = ssa.util.k_det_to_k_stoch(
k_det, reactants=reactants, volume=volume, u... | StarcoderdataPython |
5013813 | # Moduł definiujący endpointy API
from flask_restful import Resource
from flask_jwt_extended import create_access_token
from flask import jsonify, request
import json as jsonlib
from marshmallow import ValidationError
import datetime
from .validators import VUser, VUserPatch, VEmail, VJson, VUserLogin
from app impor... | StarcoderdataPython |
12858500 | <reponame>Odder/PyraminXolver
from collections import deque
import pickle
from . import Pyraminx, PYRAMINX_CASE_PATH
from multiprocessing import Pool, cpu_count
def setup():
graph = create_graph()
with open(PYRAMINX_CASE_PATH, 'wb') as f:
pickle.dump(graph, f, pickle.HIGHEST_PROTOCOL)
def create_gr... | StarcoderdataPython |
4901677 | # Generated by Django 3.0.6 on 2020-06-09 10:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('schedule', '0007_auto_20200609_1550'),
]
operations = [
migrations.AlterField(
model_name='routine',
name='eigth_per... | StarcoderdataPython |
1736931 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [("pollingstations", "0003_residentialaddress")]
operations = [
migrations.AlterField(
model_name="residentialaddress",
... | StarcoderdataPython |
5093245 | #!/usr/bin/env pytest
# -*- coding: utf-8 -*-
###############################################################################
# $Id: ogr_sxf.py 26513 2013-10-02 11:59:50Z bishop $
#
# Project: GDAL/OGR Test Suite
# Purpose: Test OGR SXF driver functionality.
# Author: <NAME> <<EMAIL>>
#
############################... | StarcoderdataPython |
1990309 | <reponame>SymmetricChaos/FiniteFields<gh_stars>1-10
# Find the shortest chain of additions, starting from 1, which give n.
# This is a simple branch and bound style algorithm which starts by trying
# the greedy method and prunes branches that are worse than what it has found
# before.
def addition_chain_recur(N,L=[1]... | StarcoderdataPython |
11207918 | <reponame>felipesch92/cursoFiap
lista_estatica = ['teste', 30]
lista_dinamica = [input('Nome do usuário'), bool(input('Está logado? '))]
print(lista_dinamica)
| StarcoderdataPython |
193089 | <filename>nipype/interfaces/semtools/brains/tests/test_auto_SimilarityIndex.py
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from ..segmentation import SimilarityIndex
def test_SimilarityIndex_inputs():
input_map = dict(
ANNContinuousVolume=dict(
argstr='--ANNContinuousVolume %s',
... | StarcoderdataPython |
9675539 | import os
import sys
py_dll_path = os.path.join(sys.exec_prefix, 'Library', 'bin')
os.add_dll_directory(py_dll_path)
import numpy as np
import cv2
from PIL import Image, ImageDraw
from matplotlib import cm
from scipy import ndimage
import torch
import torchvision
from torchvision.models.detection.faster_rcnn... | StarcoderdataPython |
12841735 | <gh_stars>1-10
import uuid
def set_created_by_if_empty(model, user):
"""
This function is called by our save function because django
throws exceptions on object access if something doesn't exist.
You cannot dereference a related field if it doesn't exist.
Meaning you have to do a try except block.
... | StarcoderdataPython |
366573 | <gh_stars>0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
import kambi.query
import kambi.stores
import multiprocessing
class Metric(object):
def __init__(self, metric_id, query, sumologic_client, statuspageio_client,
interval=30, span=900000, prune=True, backfill=False,
... | StarcoderdataPython |
11292525 | <filename>emnist/__init__.py
"""
# EMNIST
This package is a convenience wrapper around the EMNIST data set. Documentation on this data set, as well as manually
downloadable files, can be found [here](https://www.nist.gov/itl/iad/image-group/emnist-dataset).
"""
import gzip
import html
import logging
import os
import ... | StarcoderdataPython |
190016 | <filename>src/vigorish/cli/menu_items/change_env_var_setting.py<gh_stars>1-10
"""Menu that allows the user to view and modify environment variables."""
import subprocess
from sys import exit
from bullet import colors, Input
from getch import pause
from vigorish.cli.components import print_message, yes_no_cancel_promp... | StarcoderdataPython |
5061050 | <filename>env/lib/python3.6/site-packages/nibabel/streamlines/tests/test_tractogram_file.py<gh_stars>1-10
""" Test tractogramFile base class
"""
from ..tractogram import Tractogram
from ..tractogram_file import TractogramFile
from nose.tools import assert_raises, assert_equal
def test_subclassing_tractogram_file():... | StarcoderdataPython |
177723 | from .factory import create_cli
| StarcoderdataPython |
11337935 | <filename>gffpal/scripts/trnascan2gff.py
import sys
import argparse
from typing import Tuple, List, Dict
from typing import Sequence, Mapping
from gffpal.gff import GFF
from gffpal.gff import GFF3Record
from gffpal.gff import Strand, Phase
from gffpal.attributes import GFF3Attributes
from gffpal.parsers.trnascan impo... | StarcoderdataPython |
6476937 | <filename>Euler100/challenge6.py
# Sum square difference
# The squares of the first n natural numbers and the square of the sum.
def sumSquareDifference(n):
sumSq = sum(range(1, n+1))**2
sqSum = sum(i**2 for i in range(1, n+1))
return sumSq - sqSum
| StarcoderdataPython |
5088623 | <filename>tests/test_sharknado/test_sniffing/test_single.py
# Copyright 2020 <NAME> and collaborators.
# This program is distributed under the MIT license.
from __future__ import annotations
import abc
import time
from typing import (Iterable, Union, Optional, Tuple, Any, Iterator, Type,
Sequence,... | StarcoderdataPython |
8180015 | """
Subsample a fasta file to generate a number of sequences.
We iterate the file twice to count the number of sequences.
"""
import os
import sys
import argparse
from roblib import stream_fasta, message
from random import shuffle
def get_sequence_ids(inputfile, verbose=False):
"""
count the sequences in the... | StarcoderdataPython |
12847856 | <reponame>schmouk/PythonOpenSourceProject<gh_stars>0
"""
Copyright (c) 2020 <NAME>
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 |
245591 | from gtts import gTTS
import os,time
def save_sound(message):
speech = gTTS(message)
speech.save("audio.mp3")
| StarcoderdataPython |
3334880 | <filename>math2d_spline.py
# math2d_spline.py
import math
from math2d_vector import Vector
class Spline(object):
def __init__(self):
self.point_list = []
def Deserialize(self, json_data):
self.point_list = [Vector().Deserialize(point_data) for point_data in json_data]
return self
... | StarcoderdataPython |
1788614 | <reponame>AlexCWolff/Portfolio<gh_stars>0
from flask import render_template, redirect, url_for
from fpflask import FunctionalFlask
from effect.do import do, do_return
from effect import Effect, Func, base_dispatcher
counter = 0
def increment_counter(num):
global counter
counter += num
def get_counter(): retu... | StarcoderdataPython |
11315850 | from .metrics import accuracy
| StarcoderdataPython |
25624 | <reponame>hgohel/Python-for-Everyday-Life
# -*- coding: utf-8 -*-
# !/usr/bin/env python3
if __name__ == '__main__':
import money
# crafting money
euro = money.Money(1.0, 'EUR')
five_euros = money.Money(5.0, 'EUR')
ten_euros = money.Money(10.0, 'EUR')
dollar = money.Money(1.0, 'USD')
# mo... | StarcoderdataPython |
11207606 | #pythran export allpairs_distances_loops(int)
#runas allpairs_distances_loops(100)
#bench allpairs_distances_loops(100)
import numpy as np
def dists(X,Y):
result = np.zeros( (X.shape[0], Y.shape[0]), X.dtype)
for i in xrange(X.shape[0]):
for j in xrange(Y.shape[0]):
result[i,j] = np.sum( (X[i,:] - Y[j,:]... | StarcoderdataPython |
11295651 | <filename>ht/embeds.py<gh_stars>0
import discord, asyncio, random
from discord.ext import commands
from enum import Enum
from . import utils
DEFAULT = 0x444850
class Theme(Enum):
ERROR = (0xdd3333, "4/4e/OOjs_UI_icon_error-destructive.svg/200px-OOjs_UI_icon_error-destructive.svg.png", "An error has been encountered"... | StarcoderdataPython |
5055954 | <filename>class work/JacobLedbetter_11,23,15_pdf 6-10/pong.py
#Pong
#<NAME>
#12/4/13
#--------------------Notes--------------------------------------------------------
#In computer graphics, a sprite is a two-dimensional image or animation that is
# integrated into a larger scene.
#--------Import Libraries-------------... | StarcoderdataPython |
6549669 | import numpy as np
import metrics
import datasets
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import KFold
from hypothesis import TreeHypothesis
from consistency import MCConsistentTree
from hypothesis_search import MCHypothesisSearch
... | StarcoderdataPython |
3316178 | import os
import os.path as op
import json
# import logging
import base64
import yaml
import errno
import io
import math
from PIL import Image, ImageDraw
from maskrcnn_benchmark.structures.bounding_box import BoxList
from .box_label_loader import LabelLoader
def load_linelist_file(linelist_file):
... | StarcoderdataPython |
3350645 | <filename>SalishSeaTools/salishsea_tools/stormtools.py
# Copyright 2013-2021 The Salish Sea MEOPAR contributors
# and The University of British Columbia
# 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 Li... | StarcoderdataPython |
3305166 | <gh_stars>0
# Buscando os links da pagina pela tag <a>
import requests
from bs4 import BeautifulSoup
pagina = requests.get('http://www.uninove.br')
pagebs = BeautifulSoup(pagina.text, 'html.parser')
# encontra todos os links
uninove = pagebs.find_all('a')
for i in uninove:
print(i.prettify())
input('Tecle ENTER... | StarcoderdataPython |
1637447 | """
Copyright 2019 <NAME>.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distribut... | StarcoderdataPython |
145256 | <gh_stars>1-10
import pytest, random
from string import ascii_lowercase
from random import seed, choice, randrange
from src.search import SearchBM, SearchKMP
@pytest.mark.parametrize("search", [SearchBM, SearchKMP])
def test_empty_pattern_0(search):
s = search("")
assert s.search("Hello, world!") == 0
@py... | StarcoderdataPython |
6556954 | import os
for i in range(101):
cmd = "/Users/ahakim/research/gkeyll-project/gkeyllall/gkeyll/scripts/gkeplot.py -p s2-5m-2d-rt_q_%d.h5 -c 0 -t 'N_e t=%g' --dont-show --save -o s2-5m-2d-rt_numElc_%05d" % (i, 5*i, i)
print cmd
os.system(cmd)
| StarcoderdataPython |
1888158 | <reponame>coderdojo-banbridge/astro-pi-examples<filename>sense hat/buttons/pygame_test.py
#!/usr/bin/python
from sense_hat import SenseHat
import os
import time
import pygame # See http://www.pygame.org/docs
from pygame.locals import *
print("Press Escape to quit")
time.sleep(1)
pygame.init()
pygame.display.set_mod... | StarcoderdataPython |
11249056 | <gh_stars>0
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: wxnacy(<EMAIL>)
"""
for github
"""
import requests
from .exceptions import GitException
class Git(object):
domain = None
proxy = None
proxies = {}
def __init__(self, *args, **kwargs):
for k, v in kwargs.items():
s... | StarcoderdataPython |
8068645 | import pickle
import time
from sklearn.metrics import f1_score, mean_absolute_error
import lightgbm as lgb
import cv2
import numpy as np
import pandas as pd
if __name__ == '__main__':
csvpath = r"datasets/datasets.csv"
csvdf = pd.read_csv(csvpath, header=0)
alldataX = csvdf[["calctype","col","row","con... | StarcoderdataPython |
1677260 | <reponame>ForrestPi/AnomalyDetection
import os
import torch
from torch.nn import functional as F
from dataset import return_MVTecAD_loader
from network import VAE,loss_function
import matplotlib.pyplot as plt
def train(model,train_loader,device,optimizer,epoch):
model.train()
train_loss = 0
for batch_idx, ... | StarcoderdataPython |
1728320 | <reponame>vahndi/quant-survey
from itertools import product
from pandas import DataFrame
from probability.distributions import BetaBinomial, BetaBinomialConjugate
from tqdm import tqdm
from typing import List, Tuple
from survey import Survey
from survey.attributes import SingleCategoryAttribute
from survey.custom_type... | StarcoderdataPython |
1822817 | <gh_stars>10-100
#!/usr/bin/env python
#############################################################################
##
## Copyright (C) 2004-2005 Trolltech AS. All rights reserved.
##
## This file is part of the example classes of the Qt Toolkit.
##
## This file may be used under the terms of the GNU General Public
#... | StarcoderdataPython |
9606222 | <gh_stars>10-100
from sqlalchemy.orm import Session
from fastapi import Depends
from app.schemas import tenant as schemas
from app.models.tenant import Tenant, TenantAccount
from app.controllers.billing import stripe
from app.controllers.account import create_account
def get_tenant(db_session: Session, id: int):
... | StarcoderdataPython |
12822646 | <gh_stars>0
# Copyright 2015 - Mirantis, Inc.
# Copyright 2015 - StackStorm, Inc.
# Copyright 2016 - Nokia Networks.
#
# 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:/... | StarcoderdataPython |
292765 | # Generated by Django 2.0.2 on 2018-06-26 09:55
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('linker', '0017_auto_20180625_2237'),
]
operations = [
migrations.RemoveField(
model_name='analy... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.