id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
11309401 | """
Created on 11 Jan 2021
@author: <NAME> (<EMAIL>)
"""
from scs_core.aws.greengrass.aws_group import AWSGroup
# --------------------------------------------------------------------------------------------------------------------
class AWSGroupDeployer(object):
"""
classdocs
"""
BUILDING = "... | StarcoderdataPython |
5013800 | import statistics
def custom_mean(arr):
if len(arr) < 1:
return 0
else:
return statistics.mean(arr)
def custom_var(arr):
if len(arr) < 2:
return 0
else:
return statistics.variance(arr)
class FinderAccount:
def __init__(self, balance, identifier):
self.ba... | StarcoderdataPython |
6671226 | <reponame>rnburn/authz-service
from flask import Flask, request
app = Flask(__name__)
@app.route('/service')
def hello():
print(request.headers)
return 'Hello, Hello'
if __name__ == "__main__":
app.run(host='0.0.0.0', port=8080, debug=False)
| StarcoderdataPython |
11303343 | <gh_stars>0
import numpy as np
import gym
from gym import wrappers
import tensorflow as tf
import json, sys, os
from os import path
import random
from collections import deque
#####################################################################################################
## Algorithm
# Deep Q-Networks (DQN)
# A... | StarcoderdataPython |
4837353 | <filename>aioquant/utils/web.py
# -*- coding:utf-8 -*-
"""
Web module.
Author: HuangTao
Date: 2018/08/26
Email: <EMAIL>
"""
import json
import aiohttp
from urllib.parse import urlparse
from aioquant.utils import logger
from aioquant.configure import config
from aioquant.tasks import LoopRunTask, SingleTask
from... | StarcoderdataPython |
3311799 | <reponame>Cameron-D/gift-registry
# Generated by Django 3.2 on 2021-05-08 11:31
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('registry', '0009_rename_og_desciption_item_og_description'),
]
operations = [
migrations.RenameField(
mo... | StarcoderdataPython |
4839273 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Distances in a grid
# <NAME> et <NAME> - 2014-2015
from collections import deque
# snip{
def dist_grid(grid, source, target=None):
"""Distances in a grid by BFS
:param grid: matrix with 4-neighborhood
:param (int,int) source: pair of row, column indices
... | StarcoderdataPython |
9647511 | <filename>scripts/python/barraProgresoTerminal.py
# -*- coding: utf-8 -*-
from tqdm import tqdm # Requiere instalar la librería -> pip install tqdm
from time import sleep
tareasQueRealizar = 100;
for i in tqdm(range(tareasQueRealizar)):
sleep(0.2)
| StarcoderdataPython |
375078 | <filename>tkbuilder/widgets/widget_wrappers/radiobutton.py<gh_stars>0
from tkinter import ttk
from tkbuilder.widgets.widget_utils.widget_events import WidgetEvents
import tkinter
class RadioButton(tkinter.Radiobutton, WidgetEvents):
def __init__(self, master=None, **kw):
ttk.Radiobutton.__init__(self, mas... | StarcoderdataPython |
3533090 | <reponame>Bernardoviski/Sincroniza<gh_stars>0
# Sincroniza Web App - Por <NAME> | Desenvolvido como requisito para a Mostra Cientifica
import socket
import threading
from utils import *
from urllib.parse import unquote
from python_parser import pythonfier
content_dir = "web/"
class WebServer(object):
def __init... | StarcoderdataPython |
1820866 | GOTO_URL = "https://ilias-app2.let.ethz.ch/goto.php?target=fold_"
LOGIN_URL = "https://ilias-app2.let.ethz.ch/shib_login.php"
IDP_DATA = {
"user_idp": "https://aai-logon.ethz.ch/idp/shibboleth",
"Select": "Auswählen",
}
| StarcoderdataPython |
119188 | <reponame>michaeldavie/pyinsteon<gh_stars>10-100
"""Get Device Info command handler."""
from ...address import Address
from ...topics import ENTER_UNLINKING_MODE
from .direct_command import DirectCommandHandlerBase
class EnterUnlinkingModeCommand(DirectCommandHandlerBase):
"""Place a device in linking mode comman... | StarcoderdataPython |
11389524 | # -*- coding: utf-8 -*-
#
# This file is part of Sequana software
#
# Copyright (c) 2016-2020 - Sequana Development Team
#
# File author(s):
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
#
# Distributed under the terms of the 3-clause BSD license.
# The full license is in the LICENSE file, distributed with this ... | StarcoderdataPython |
8099798 | from aws_mock.lib import get_aws_mock_db, aws_response
from aws_mock.predefined import MASTER_REGION_NAME, MASTER_REGION_IMAGE
@aws_response
def describe_images(region_name: str) -> dict:
if region_name == MASTER_REGION_NAME:
return {"items": [MASTER_REGION_IMAGE]}
return {"items": list(get_aws_mock_d... | StarcoderdataPython |
3524696 | <reponame>iamwillbar/home-assistant-deako<filename>components/deako/__init__.py
"""The Deako component."""
| StarcoderdataPython |
3258065 | <gh_stars>0
from pynamodb.models import Model
from pynamodb.attributes import UnicodeAttribute, BooleanAttribute
import os
class ProductNotificationTable(Model):
""" DynamoDB table storing information about whether
notification for an in-stock product has already
been sent out.
"""
class ... | StarcoderdataPython |
1631843 | <reponame>danielballan/amostra<filename>amostra/test/test_basic.py
import pytest
from amostra.testing import _baseSM, TESTING_CONFIG
from amostra.client.commands import SampleReference
from io import StringIO
import json
import yaml
class TestBasicSampleRef(_baseSM):
db_class = SampleReference
args = ()
k... | StarcoderdataPython |
12819289 | <gh_stars>1-10
"""CODING GUIDELINES:
- Add docstrings following the pattern chosen by the community.
- Add comments explaining step by step how your method works and the purpose of it.
- If possible, add examples showing how to call them properly.
- Remember to add the parameters and return types.
- Add unit tests / i... | StarcoderdataPython |
8148407 | <filename>{{cookiecutter.project_slug}}/backend/app/app/tests/api/api_v1/user/test_user.py<gh_stars>10-100
# Standard library packages
import random
# Installed packages
import requests
# App code
from app.tests.utils.utils import random_lower_string, get_server_api
from app.tests.utils.user import user_authenticatio... | StarcoderdataPython |
3231192 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 4 22:04:22 2019
@author: sercangul
"""
class Difference:
def __init__(self, a):
self.__elements = a
def computeDifference(self):
t = self.__elements
k = []
j = 1
while j<len(t):
i = 0
... | StarcoderdataPython |
78336 | <reponame>jacksonhzx95/Joint_segmentation_denoise_for_scoliosis
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmseg.core import add_prefix
from mmseg.ops import resize
from .. import builder
from ..builder import SEGMENTORS
from .base import BaseSegmentor
@SEGMENTORS.register_module()
class... | StarcoderdataPython |
3520496 | import numpy as np
from src.pre_processing.core.mesh.functions.verify_flow_region import FlowFieldRegion
from src.constants import SMALL_NUMBER
# Generate the points of the layer
def generate_layer_points_func(airfoil: np.ndarray, circle: np.ndarray, multiplier: float, height: float, region: FlowFieldRegion) -> np.nd... | StarcoderdataPython |
9653906 | L = [1, 2] # Make a 2-item list
L.append(L) # Append L as a single item to itself
print(L) # Print L: a cyclic/circular object | StarcoderdataPython |
8134291 | import pathlib
from taichi.core import ti_core as _ti_core
from taichi.lang.impl import default_cfg
from taichi.lang.kernel_arguments import ext_arr, template
from taichi.lang.kernel_impl import kernel
from taichi.lang.ops import get_addr
from .utils import *
class Gui:
def __init__(self, gui) -> None:
... | StarcoderdataPython |
1801065 | from manga_py.crypt import MangaRockComCrypt
from manga_py.fs import rename, unlink, basename
from manga_py.provider import Provider
from .helpers.std import Std
# api example:
"""
curl 'https://api.mangarockhd.com/query/web401/manga_detail?country=Japan' --compressed --data '{"oids":{"mrs-serie-100226981":0},"section... | StarcoderdataPython |
8118900 | <reponame>ejconlon/pushpluck
from contextlib import contextmanager
from dataclasses import dataclass
from pushpluck import constants
from pushpluck.base import Resettable
from pushpluck.color import Color
from pushpluck.push import PushInterface, ButtonCC, ButtonIllum, ButtonColor, TimeDivCC
from pushpluck.pos import P... | StarcoderdataPython |
362389 | <gh_stars>0
"""
Class :py:class:`FWViewHist` is a widget with interactive axes
==============================================================
FWViewHist <- FWView <- QGraphicsView <- QWidget
Usage ::
Create FWViewHist object within pyqt QApplication
--------------------------------------------------
imp... | StarcoderdataPython |
9690814 | <reponame>beesandbombs/coldtype<gh_stars>1-10
from coldtype.test import *
@test()
def empty(r):
pass | StarcoderdataPython |
156129 | <gh_stars>10-100
import tensorflow as tf
__all__ = ['AutomatedTrainingMonitor']
class AutomatedTrainingMonitor:
def __init__(self, input_var, output_var, training_input, training_output,
train, cost, sess, training_steps=100,
validation_input=None, validation_output=None,
... | StarcoderdataPython |
5139646 | from __future__ import print_function
import subprocess
import sys
includes = subprocess.check_output(['python', '-m', 'pybind11', '--includes'])
includes_str = includes.decode()
# offset = 0
# while (i := includes_str.find('-I')) != -1:
# path = includes_str[0:i]
# includes_str = includes_str[i+2:]
# if len(pa... | StarcoderdataPython |
4939694 | <gh_stars>0
from __future__ import annotations
import copy
import scipy.sparse
import astropy
from astropy import units as qu
from typing import Callable
from metadata import *
class SamplingMethod:
def __init__(self, srate: astropy.units.quantity.Quantity=30e3*qu.Hz):
self.srate = srate.to('Hz')
d... | StarcoderdataPython |
11340177 | <reponame>marcoag/rmf_demos
# Copyright 2021 Open Source Robotics Foundation, Inc.
#
# 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
#
# Unle... | StarcoderdataPython |
9703233 | <filename>Globals.py<gh_stars>0
'''
This module contains a bunch of data that needs to be globally accessible all
across AutoNifty. That mostly means the config settings and stuff directly
related to or derived from them.
'''
import time
import datetime
import ConfigParser
import os
# These defaults largely come fro... | StarcoderdataPython |
8077953 |
class UnitNames(object):
"""
Unit Names is a namepace to hold units
"""
__slots__ = ()
bits = "bits"
kbits = "K" + bits
mbits = "M" + bits
gbits = "G" + bits
bytes = "Bytes"
kbytes = "KBytes"
mbytes = "MBytes"
gbytes = "GBytes"
# end UnitNames
IDENTITY = 1
ONE = 1.0
KI... | StarcoderdataPython |
3219844 | from python_qt_binding import QtGui
class BaseWidget(QtGui.QWidget):
def __init__(self, topic_name, publisher, parent=None):
super(BaseWidget, self).__init__(parent=None)
self._topic_name = topic_name
self._publisher = publisher
def get_text(self):
return ''
def get_rang... | StarcoderdataPython |
6552063 | <reponame>AlexRovan/Python_training
from model.group import Group
import random
import allure
def test_edit_group_by_index(app,db,json_groups,check_ui):
with allure.step('Add group, if no groups now'):
group = json_groups
if app.group.count() == 0:
app.group.create(group)
with allur... | StarcoderdataPython |
3373703 | <filename>setup.py
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name='clippercard',
version='0.2.0',
author='<NAME>',
author_email='<EMAIL>',
packages=['clippercard'],
package_dir = {'clippercard':'clippercard'},
entry_points = {
... | StarcoderdataPython |
8006407 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
import string
import os
import json
from contextlib import contextmanager
try:
import serial
except ImportError:
raise CncLibraryException("pyserial needs to be installed!")
from .version import VERSION
__version__ = VERSION
class CncLibrary(object):
... | StarcoderdataPython |
188975 | # -*- coding: utf-8 -*-
"""lhs_opt.py: Module to generate design matrix from an optimized
Latin Hypercube design
"""
import numpy as np
from . import lhs
__author__ = "<NAME>"
def create_ese(n: int, d: int, seed: int, max_outer: int,
obj_function: str="w2_discrepancy",
threshold_init: f... | StarcoderdataPython |
5155243 | import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class ObserverFolder(FileSystemEventHandler):
def on_modified(self, event):
print('File Modified')
def on_created(self, event):
print('File Created')
def on_moved(self, event):
... | StarcoderdataPython |
3299579 | <gh_stars>10-100
# GENERATED BY KOMAND SDK - DO NOT EDIT
import insightconnect_plugin_runtime
import json
class Component:
DESCRIPTION = "Quarantine (isolate) endpoint an endpoint"
class Input:
AGENT = "agent"
QUARANTINE_STATE = "quarantine_state"
WHITELIST = "whitelist"
class Output:
SUCC... | StarcoderdataPython |
4932299 | import datetime
import os
import airflow
from data_pipelines.actions.aws import AppDataBaseToS3, S3ToDatawarehouse
from data_pipelines.airflow.operator import ActionOperator
table_list = ["customers", "transactions", "transaction_details"]
dag = airflow.DAG(
dag_id="pipeline.appdb_to_datawarehouse",
star... | StarcoderdataPython |
1672653 | <filename>secrets.template.py
##
## SP API Developer Settings
##
# This is the first part of the LWA credentials from the developer console
# and is specific to the application you set up. This looks something like
# "amzn1.application-oa2-client.<hex id>"
client_id = None
# This is the hidden part of the LWA credent... | StarcoderdataPython |
11354510 | <filename>celltraj/__init__.py
"""Top-level package for CellTraj."""
__author__ = """<NAME>"""
__email__ = '<EMAIL>'
__version__ = '0.1.0'
| StarcoderdataPython |
6425606 | <reponame>RobertPastor/flight-profile<filename>trajectory/management/commands/AirportsDatabaseLoad.py
from django.core.management.base import BaseCommand
from trajectory.management.commands.Airports.AirportDatabaseFile import AirportsDatabase
from trajectory.models import AirlineAirport
from airline.models import Airl... | StarcoderdataPython |
4817242 | <filename>website/addons/figshare/tests/test_models.py
import mock
from nose.tools import * # noqa
from tests.base import OsfTestCase, get_default_metaschema
from tests.factories import ProjectFactory, AuthUserFactory
from framework.auth import Auth
from website.addons.figshare import settings as figshare_settings
... | StarcoderdataPython |
9687447 | test = { 'name': 'q1c',
'points': 1,
'suites': [ { 'cases': [ {'code': '>>> varied_menu_only.num_rows == 22\nTrue', 'hidden': False, 'locked': False},
{ 'code': '>>> np.all(varied_menu_only.column(\'Restaurant\').take(np.arange(5)) == np.array(["O\'Charley\'s", "Coop... | StarcoderdataPython |
1763551 | <filename>twitter_app/twitter_bot/views.py
from django.shortcuts import render
import tweepy, requests
import sys, requests, json, time, os
from django.contrib.messages.views import messages
from .forms import InputForm
from django.conf import settings
CONSUMER_KEY = settings.CONSUMER_KEY
CONSUMER_SECRET = settings.C... | StarcoderdataPython |
11234704 | import json
from pathlib import Path
import requests
import sqlite3
import sys
import xml.etree.ElementTree as ET
import zipfile
from tqdm import tqdm
# Download bill XML files
congresses = ["115", "116"]
bill_types = ["hr", "s", "hjres", "sjres"]
base_url = "https://www.govinfo.gov/bulkdata/BILLSTATUS/"
bill_dir = ... | StarcoderdataPython |
3293325 | import os
import importlib.util
from pykeops.common.gpu_utils import get_gpu_number
###############################################################
# Initialize some variables: the values may be redefined later
##########################################################
# Update config module: Search for GPU
gpu_ava... | StarcoderdataPython |
11287766 | from __future__ import unicode_literals
from mkdocs_combine.mkdocs_combiner import MkDocsCombiner
| StarcoderdataPython |
5004951 | #%%
import numpy as np
import pandas as pd
import altair as alt
import anthro.io
# Load the Ozone hole data.
full_data = pd.read_csv('../processed/NASA_ozone_hole_evolution_SH_spring.csv')
data = full_data[full_data['Variable'] == 'Ozone hole area'].copy()
proc_data = pd.DataFrame()
proc_data['year'] = pd.to_datetime(... | StarcoderdataPython |
3289974 | <reponame>Jumpscale/ays_jumpscale8<filename>templates/fs/fs.btrfs/actions.py
def init_actions_(service, args):
"""
this needs to returns an array of actions representing the depencies between actions.
Looks at ACTION_DEPS in this module for an example of what is expected
"""
# some default logic fo... | StarcoderdataPython |
3333193 | from core.db import db
class Register(db.Model):
__tablename__ = 'register'
id = db.Column(db.INTEGER, autoincrement=True, primary_key=True)
register_type_id = db.Column(db.INTEGER)
name = db.Column(db.VARCHAR(128))
gender = db.Column(db.BOOLEAN)
student_number = db.Column(db.VARCHAR(32))
... | StarcoderdataPython |
6470476 | <filename>setup.py
from setuptools import setup, find_packages
setup(
name='aiy-projects-python',
version='1.4',
description='AIY Python API',
long_description='A set of Python APIs designed for the AIY Voice Kit and AIY Vision Kit, which help you build intelligent systems that can understand wha... | StarcoderdataPython |
145234 | # ============================================================================
#
# Copyright (C) 2007-2016 Conceptive Engineering bvba.
# www.conceptive.be / <EMAIL>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
... | StarcoderdataPython |
9743690 | import numpy as np
import torch
from pytorchrl.core.parameterized import Parameterized
from pytorchrl.misc.utils import gauss_log_pdf, categorical_log_pdf
DIST_GAUSSIAN = 'gaussian'
DIST_CATEGORICAL = 'categorical'
class ImitationLearning(object):
def __init__(self):
pass
@staticmethod
def compu... | StarcoderdataPython |
3470121 | # 环境变量配置,用于控制是否使用GPU
# 说明文档:https://paddlex.readthedocs.io/zh_CN/develop/appendix/parameters.html#gpu
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
import paddlex as pdx
model_dir = 'output/deeplabv3p_mobilenetv3_large_ssld/best_model'
img_file = "dataset/JPEGImages/5.png"
save_dir = 'output/deeplabv3p_mobilenet... | StarcoderdataPython |
4996942 | <reponame>jayrambhia/Twitter-Data-Mining<gh_stars>1-10
# -*- coding: utf-8 -*-
import twitter
import urllib2
import time
import re
import gdbm
opener = urllib2.build_opener()
urllib2.install_opener(opener)
api = twitter.Api(consumer_key="", consumer_secret="",access_token_key="", access_token_secret="",proxy ={})
d... | StarcoderdataPython |
9651546 | <reponame>faramarzmunshi/gluon-nlp<gh_stars>1-10
# coding: utf-8
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you unde... | StarcoderdataPython |
11295476 | <filename>tencentcloud/clb/v20180317/errorcodes.py
# -*- coding: utf8 -*-
# Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. 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 t... | StarcoderdataPython |
4924716 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.db.models.deletion
import modelcluster.fields
import wagtail.core.fields
import modelcluster.contrib.taggit
class Migration(migrations.Migration):
dependencies = [
('taggit', '0001_init... | StarcoderdataPython |
6625437 | from functools import wraps
from flask import redirect, render_template, session
def apology(page, message, code=400, data=None):
return render_template(page, error=message, data=data), code
def apologyBirth(page, message, birthdays, code=400, data=None):
return render_template(page, error=message, data=data, bir... | StarcoderdataPython |
8011128 | # USAGE
# python server.py --prototxt MobileNetSSD_deploy.prototxt --model MobileNetSSD_deploy.caffemodel --montageW 2 --montageH 2
# import the necessary packages
from imutils import build_montages # build a montage of all incoming frames
from datetime import datetime
import numpy as np
from imagezmq import imagezmq... | StarcoderdataPython |
4812926 | N=int(input())
print(sum(len(str(i))%2 for i in range(1,N+1))) | StarcoderdataPython |
1949479 | """
Jasper DR (Dense Residual) for ASR, implemented in Gluon.
Original paper: 'Jasper: An End-to-End Convolutional Neural Acoustic Model,' https://arxiv.org/abs/1904.03288.
"""
__all__ = ['JasperDr', 'jasperdr5x3', 'jasperdr10x4', 'jasperdr10x5']
import os
from mxnet import cpu
from mxnet.gluon import nn, Hyb... | StarcoderdataPython |
1806944 | <reponame>MihanEntalpo/allure-single-html-file
#! /usr/bin/env python3
"""
Allure static files combiner.
Create single html files with all the allure report data, that can be opened from everywhere.
Example:
python3 ./combine.py ../allure_gen [--dest xxx] [--remove-temp-file] [--auto-create-folders]
or
... | StarcoderdataPython |
4865247 | <gh_stars>1-10
import datetime
import json
import os
import requests
import random
import threading
import logging
from flask import Flask
from flask import request
from pymongo import MongoClient
from routing import configuration
from routing import graph
from routing import osm_handler
from routing.utils import bring... | StarcoderdataPython |
31075 | <filename>examples/kalman/gnss_kf.py
#!/usr/bin/env python
import numpy as np
from kalman_helpers import ObservationKind
from ekf_sym import EKF_sym
from laika.raw_gnss import GNSSMeasurement
def parse_prr(m):
sat_pos_vel_i = np.concatenate((m[GNSSMeasurement.SAT_POS],
m[GNSSMeasur... | StarcoderdataPython |
11208380 | # Generated by Django 3.0.7 on 2021-07-17 18:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('isisdata', '0093_merge_20210717_1853'),
]
operations = [
migrations.AlterField(
model_name='authority',
name='type_c... | StarcoderdataPython |
5104387 | <filename>api/api.py<gh_stars>0
"""Runs loopback server for backend."""
import configparser
import tornado.ioloop
import tornado.web
from csv_handler import CSVHandler
from tree_handler import TreeHandler
from registration_handler import RegistrationHandler
# pylint: disable=W0223
class BaseHandler(tornado.web.Reque... | StarcoderdataPython |
1745570 | # ----------------------------------------------------------------------
# Eltex.TAU.get_metrics
# ----------------------------------------------------------------------
# Copyright (C) 2007-2021 The NOC Project
# See LICENSE for details
# ----------------------------------------------------------------------
# NOC mo... | StarcoderdataPython |
324064 | """Test cases for the cli module."""
import click.testing
import pytest
from click.testing import CliRunner
from testfixtures import LogCapture
from scout import cli
@pytest.fixture
def runner() -> CliRunner:
"""Fixture for invoking the command-line interface."""
return click.testing.CliRunner()
def test_m... | StarcoderdataPython |
6691601 | <filename>hata/backend/formdata.py<gh_stars>1-10
# -*- coding: utf-8 -*-
__all__ = ('Formdata', )
from io import IOBase
from urllib.parse import urlencode
from json import dumps as dump_to_json
from .utils import multidict
from .headers import CONTENT_TYPE, CONTENT_TRANSFER_ENCODING, CONTENT_LENGTH
from .multipart i... | StarcoderdataPython |
6615204 | <reponame>Speccy-Rom/My-web-service-architecture
from typing import Callable
from starlette.requests import Request
from starlette.responses import JSONResponse
from app.src.exception import APIException
def http_exception_factory(status_code: int) -> Callable:
def http_exception(_: Request, exception: APIExcep... | StarcoderdataPython |
3406899 | <filename>Snake game version 2/main/game of snakes.py
# write a simple snake game in python
import pygame
import random
import time
# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
# This sets the WIDTH and HEIGHT of each... | StarcoderdataPython |
8086236 | import pandas as pd
import numpy as np
import nltk
from nltk.corpus import stopwords
from sklearn.datasets import fetch_20newsgroups
from tensorflow.keras.preprocessing.text import Tokenizer | StarcoderdataPython |
5144759 | <reponame>ab5424/agility
# Copyright (c) <NAME>
# Distributed under the terms of the MIT License
# author: <NAME>
"""Analysis functions."""
import pathlib
import sys
import warnings
import numpy as np
import pandas as pd
from agility.minimiser import mimimise_lmp
class GBStructure:
"""This is... | StarcoderdataPython |
12864689 | """
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
"""
# Write your code here
import bisect
def check(arr, x, ln, val):... | StarcoderdataPython |
11370723 | <filename>images.py
#----------------------------------------------------------------------
# This file was generated by encode-bitmaps.py
#
from wx.lib.embeddedimage import PyEmbeddedImage
Exit = PyEmbeddedImage(
b'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0'
b'RVh0U29mdHdh... | StarcoderdataPython |
9776608 | <filename>rock/tests/test_rule_parser.py
# -*- coding: utf-8 -*-
# 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 appl... | StarcoderdataPython |
105717 | from .checker import validate
from .creator import create_structure
| StarcoderdataPython |
1627315 | <reponame>vinirossa/decision-tree-algorithm
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" Entropy Functions
Description...
"""
from math import log2
def information_entropy(prob_list):
result = 0
for prob in prob_list:
if prob != 0:
result += prob * log2(prob)
return result... | StarcoderdataPython |
6638892 | # NOTE: from https://github.com/LuminosoInsight/ordered-set/blob/master/ordered_set.py
import itertools
from typing import (
Any,
Dict,
Iterable,
Iterator,
Mapping,
MutableSet,
Optional,
Sequence,
MutableSequence,
Set,
TypeVar,
)
T = TypeVar("T")
class OrderedSet(MutableSe... | StarcoderdataPython |
11395158 | <reponame>microsoft/semiparametric-distillation
import logging
import json
from functools import partial
from pathlib import Path
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
from sklearn.calibration import Calibrated... | StarcoderdataPython |
4939980 | <reponame>osmr/utct<filename>TFLearn/feed_dict_flow_cp.py
from tflearn import data_flow
class FeedDictFlowCp(data_flow.FeedDictFlow):
"""
Wrapper of TFLearn's FeedDictFlow for some types of augmentation.
"""
def __init__(self,
feed_dict,
coord,
batch... | StarcoderdataPython |
1671414 | <reponame>StevenHuang2020/Pedestrian-Segmentation
#python3 steven
import cv2
import argparse
import os,sys
#----------------------------------------------
#usgae: python .\predictBatchPath.py
#----------------------------------------------
from predictSegmentation import getPredictionMaskImg
from modules.folder.folde... | StarcoderdataPython |
3236440 | <filename>gumiyabot/bancho.py
# -*- coding: utf-8 -*-
"""
<NAME> (osu!) irc3 plugin.
"""
import asyncio
import irc3
# Bancho does not comply with the IRC spec (thanks peppy) so we need to account
# for that or else the irc3 module will not read any data
class BanchoConnection(irc3.IrcConnection):
"""asyncio prot... | StarcoderdataPython |
6478619 | from packages.pieces.GN2 import GN2
def test_flg_name():
assert(str(GN2()) == 'GN2') | StarcoderdataPython |
3577647 | #!/usr/bin/env python3
# import RPi.GPIO as GPIO
from enum import IntFlag
import timeit
import math
import time
'''
DoorState/Door class. Needs to be linked to actual hardware state etc...
'''
# Some states the door could be in
class DoorState(IntFlag):
INIT = 0 # initial state, adding this stat... | StarcoderdataPython |
4910112 | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import matplotlib.pyplot as plt
import numpy as np
import skimage
from skimage import io
import random
import math
import argparse
from torchvision import transforms
from Particle_Sim import ParticleSystem
random.seed(2574)
... | StarcoderdataPython |
1704988 | <filename>python/BugLearnAndValidate.py
'''
Created on Jun 23, 2017
@author: <NAME>, <NAME>
'''
import sys
import json
from os.path import join
from os import getcwd
from collections import Counter, namedtuple
import math
import argparse
from tensorflow.python.keras.models import Sequential
from tensorflow.python.ke... | StarcoderdataPython |
84893 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Package: mesxr.calibration
Module: utilities
Author: <NAME>, <NAME>
Affiliation: Department of Physics, University of Wisconsin-Madison
Last Updated: November 2018
Description:
This module contains a number of auxilary functions for the main timscan.py module to
... | StarcoderdataPython |
5018744 | <reponame>dgolovin/python-django-ex
from django.views.generic import TemplateView
class HomePageView(TemplateView):
template_name = 'home.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['name'] = 'Visitor'
return context | StarcoderdataPython |
1769218 | #!/usr/bin/env python3
import argparse
import json
import uuid
import requests
import sys
from string import Formatter
from errors import UserError, RequestError
from request_utils import Requests
from environment_utils import Environments
class Cli(object):
def __init__(
self,
requests_filename='... | StarcoderdataPython |
1785226 | from torchvision.datasets.vision import VisionDataset
from PIL import Image
import os
import os.path
import torch
import numpy as np
# TODO: remove `device`?
def convert_ann(ann, device):
xmin, ymin, w, h = ann['bbox']
# DEBUG
if w <= 0 or h <= 0:
raise ValueError("Degenerate bbox (x, y, w, h): ",... | StarcoderdataPython |
9687355 | <reponame>s2et/hdsplayer
import subprocess, time
doc=[]
vd=[".mp4",".mkv",".flv"]
id=[".jpg",".jpeg",".png",".ico"]
with open('/home/s2/Documents/hds/var1.txt', 'r+') as filehandle:
for line in filehandle:
t = line[:-1]
print(t)
print(line)
doc.append(t)
for ty in vd:
if ty in t:
t1=subprocess.run(["f... | StarcoderdataPython |
6656371 | from api.models import db, DocumentClass, Document
import requests
BACKEND_URL = "https://h4i-infra-server.kivaportfolio.now.sh/"
r = (
requests.post(
BACKEND_URL + "register",
data={
"email": "<EMAIL>",
"password": "<PASSWORD>",
"securityQuestionAnswer": "answ... | StarcoderdataPython |
3420230 | <filename>tests/test_split_on_grid.py
# Copyright 2020 - 2021 MONAI Consortium
# 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... | StarcoderdataPython |
5016457 | from django.test import TestCase
from django.core.management import call_command
from poradnia.judgements.factories import CourtFactory
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
class RunCourtSessionParserTestCase(TestCase):
def test_run_command_basic(self):
... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.