id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
134514 | # -*- coding: utf-8 -*-
# Copyright 2018 <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 appli... | StarcoderdataPython |
103028 | <filename>koosli/decorators.py
# -*- coding: utf-8 -*-
from functools import update_wrapper
from flask import g, request, redirect, url_for, current_app, abort
def admin_required(user):
'''Ensure that the currently logged in user is an admin.
If user is not logged in, redirect to login page.
'''
d... | StarcoderdataPython |
4836737 | <reponame>RubenvanHeusden/HFO-Robotkeeper<filename>example/test_keepers/lowlevelactionset.py
from actionset import ActionSet
import hfo
class LowLevelActionSet(ActionSet):
def __init__(self):
ActionSet.__init__(self, action_set="low_level")
self._action_list = [(hfo.DASH, 80, angle) for angle in [0... | StarcoderdataPython |
1781629 | # Python - 3.6.0
def folding(a, b):
count = 0
while a > 0 and b > 0:
minval = min(a, b)
a, b = max(a - minval, minval), min(a - minval, minval)
count += 1
return count
| StarcoderdataPython |
3345073 | """
The const argument of add_arguments() is used to hold connstant values that are not read from the command line but are required for the
various ArguemntParser actions. The two common uses of it are:
1>
When add_arguemt() is called with action='store_const' or action='append_const'. These actions add the consts va... | StarcoderdataPython |
4842131 | #! /usr/bin/env python
from time import sleep, time
import rospy
from std_msgs.msg import String, Int32
from o2as_debug_monitor.msg import PressureSensoState
if __name__ == "__main__":
# Initialize the ROS node
rospy.init_node("test_debug_monitor")
# Initialize publishers
pub1 = rospy.Publisher("/o2as_state/k... | StarcoderdataPython |
3217442 | #this text game will help you determine which phone is best for you by answering 3 questions. So from this the program will use the input to calculate the phone that is best for he/she.
import random
def main():
Name= raw_input("Your name:")
phone= raw_input ("Your current phone:")
sp= smartphone()
cp= currentPho... | StarcoderdataPython |
194769 | <gh_stars>1-10
# Testbed to perform experiments in order to determine best values for
# the node numbers in LRU cache. Tables version.
from time import time
from tables import *
import tables
print "PyTables version-->", tables.__version__
filename = "/tmp/junk-tables-100.h5"
NLEAVES = 2000
NROWS = 1000
class Parti... | StarcoderdataPython |
1736256 | <filename>lbry/wallet/network.py
import logging
import asyncio
import json
from time import perf_counter
from operator import itemgetter
from typing import Dict, Optional, Tuple
import aiohttp
from lbry import __version__
from lbry.error import IncompatibleWalletServerError
from lbry.wallet.rpc import RPCSession as B... | StarcoderdataPython |
36065 | import sys
sys.path.append("/home/ly/workspace/mmsa")
seed = 1938
import numpy as np
import torch
from torch import nn
from torch import optim
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
from models.bigru_rcnn_gate import *
from utils.train import *
from t... | StarcoderdataPython |
3292078 |
from NENV import *
import binhex
class NodeBase(Node):
pass
class _Ignore_Deprecation_Warning_Node(NodeBase):
"""
"""
title = '_ignore_deprecation_warning'
type_ = 'binhex'
init_inputs = [
]
init_outputs = [
NodeOutputBP(type_='data'),
]
color = '#32DA... | StarcoderdataPython |
118347 | from django.contrib import admin
from .models import Time
# register models to show up on admin page
admin.site.register(Time) | StarcoderdataPython |
3362038 | <reponame>LinWeizheDragon/AutoFidgetDetection
import os
import json
import cv2
import math
import numpy as np
import pandas as pd
from utility.base_config import *
from scipy.signal import savgol_filter
from utility.colors import *
from utility.decompose_string import decompose_string, decompose_string_hand
from compo... | StarcoderdataPython |
3391651 | from flask import Blueprint, render_template, flash
from flask_application_tutorial.auth import get_db
bp = Blueprint("articles", __name__, url_prefix="/articles")
@bp.route("/articles")
def articles():
# open connection
con = get_db()
# return articles
articles = con.execute("SELECT * FROM articles... | StarcoderdataPython |
3396424 | <reponame>StichtingIAPC/swipe
# -*- coding: utf-8 -*-
# Generated by Django 1.11.9 on 2018-05-29 18:22
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('sales', '... | StarcoderdataPython |
136499 | <filename>tests/v1/test_user_register.py
import pytest
from flask import url_for
from api.blueprints.v1.resources.user_register import User
class TestUserResource:
def test_user_register_with_missing_user_data(self, client):
res = client.post(url_for('v1.userregister'))
assert res.status_code == ... | StarcoderdataPython |
120594 | <reponame>ScorpionResponse/freelancefinder<gh_stars>1-10
"""Wrapper for hackernews."""
import datetime
import logging
import bleach
import hackernews
from django.utils import timezone
from jobs.models import Post
logger = logging.getLogger(__name__)
class HackerHarvest(object):
"""Wrapper client for hackerne... | StarcoderdataPython |
192232 | <filename>setup.py
#!/usr/bin/env python3
import os
from setuptools import setup
from pathlib import Path
thisDir = Path(__file__).parent
setup(use_scm_version = True)
| StarcoderdataPython |
1623800 | <gh_stars>0
'''
Gameprogrammierung mit Python und Pygame Zero
Version 1.00, 22.09.2021
Der Hobbyelektroniker
https://community.hobbyelektroniker.ch
https://www.youtube.com/c/HobbyelektronikerCh
Die Rechte der unten angegebenen Quellen sind zu beachten!
Der restliche Code kann mit Quellenangabe frei verwen... | StarcoderdataPython |
45707 | <reponame>ggsdc/corn
from .RoutesGenerator import RoutesGenerator
from .MIPModel import MIPModel
from collections import defaultdict, OrderedDict
from pytups import SuperDict, TupList
from datetime import datetime
import pulp as pl
import pickle
import json
import itertools
class PeriodicMIP(MIPModel):
def __init... | StarcoderdataPython |
1615414 | <filename>super_resolution/EDSR-PyTorch/src/example.py
import torch
import utility
import data
import model
import loss
from option import args
from trainer import Trainer
from benchmark import benchmarking
import os
data_dir = os.environ['TESTDATADIR']
assert data_dir is not None, "No data directory"
print('TESTDATA... | StarcoderdataPython |
3299292 | '''
Author: Mitchell
This code is used to find the mahalanobis distance between three variables and highlight points of interest
- Edited by <NAME> for app purposes
'''
import pandas as pd
import numpy as np
import scipy as sp
import scipy.signal as sg
from scipy.stats import chi2
import plotly.graph_objects as go
fr... | StarcoderdataPython |
4801331 | # -*- codeing = utf-8 -*-
from bs4 import BeautifulSoup # 网页解析,获取数据
import re # 正则表达式,进行文字匹配`
import urllib.request, urllib.error # 制定URL,获取网页数据
import xlwt # 进行excel操作
import time
import random
import re
import time
import requests
import threading
from lxml import html
etree=html.etree
from bs4 import BeautifulSo... | StarcoderdataPython |
83639 | """
Use cases related to writing data to an output repository.
"""
import logging
import warnings
from pathlib import Path
from typing import List
from openpyxl import load_workbook
from engine.repository.datamap import InMemorySingleDatamapRepository
from engine.use_cases.parsing import ParseDatamapUseCase
from eng... | StarcoderdataPython |
3390412 | """
Unit tests for SyncWorker.py
"""
import unittest
func = __import__("SyncWorker")
def mock_event(text_value=""):
return {
"channel_name": ["test_channel"],
"command": ["/slack-unittest"],
"user_name": ["test_user_namee"],
"user_id": ["test_user_id"],
"text": [text_value... | StarcoderdataPython |
4827593 | <gh_stars>1-10
# import json
import datetime
from httpretty import HTTPretty
from social.p3 import urlencode
from social.exceptions import AuthMissingParameter
from tests.open_id import OpenIdTest
JANRAIN_NONCE = datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ')
class LiveJournalOpenIdTest(OpenIdTest):
... | StarcoderdataPython |
4809433 | """Hadith Reader
This script work as the main script for the hadith reader.
It runs the hadith reader application.
It creates an instance of QApplication class. It then creates an instance
of the QMainWindow class and passes the instance as argument to the setupUi
method of the Ui_MainWindow class. The Ui_MainWindow ... | StarcoderdataPython |
3365967 | <gh_stars>1-10
import math
import traceback
from datetime import datetime
from time import sleep
from typing import *
from github import Github, RateLimitExceededException
from github.GithubException import GithubException
from github.NamedUser import NamedUser
from github.Repository import Repository
from . import _... | StarcoderdataPython |
1702435 | <filename>com/dfu/sqoopetl/model/DBTableInfo.py<gh_stars>1-10
#!/usr/bin/env python
#-*- encoding: utf-8 -*-
'''
Created on 2018年7月17日
@author: zuiweng.df
'''
"""
数据库信息
"""
class ConnDBInfo(object):
def __init__(self,ip,port,dbName,userName,passwd):
self.ip=ip;
self.port=port;
... | StarcoderdataPython |
1610781 | from .resource import Resource
from collections import Iterator
import copy
try:
# python 2
from urllib import quote
except ImportError:
# python 3
from urllib.parse import quote
class Pages(Iterator):
def __init__(self, opts, url, path, params):
if isinstance(path, list):
pag... | StarcoderdataPython |
3204281 | from dash import dcc, html
import plotly.express as px
class Boxplot(html.Div):
def __init__(self, name, df):
"""
:param name: name of the plot
:param df: dataframe
"""
self.html_id = name.lower().replace(" ", "-")
self.df = df
self.name = name
self.fig... | StarcoderdataPython |
1754787 | <gh_stars>0
# read the data from data source
# save it in the data/raw for further process
import os
from get_data import read_params, get_data
import argparse
def load_and_save(config_path):
config = read_params(config_path)
df = get_data(config_path)
new_cols = [col.replace(" ", "_") for col in df.column... | StarcoderdataPython |
56081 | # -*- coding: utf-8 -*-
"""Basic calculation classes including add, sub, mul, and div.
- Author: <NAME>
- Contact: <EMAIL>
"""
from abc import ABC
class Calculator(ABC):
"""An abstract class of basic computations."""
def operate(self: "Calculator", left: int, right: int) -> int:
"""Operate the defi... | StarcoderdataPython |
3203596 | '''
Calculando total
'''
from vendas_project.vendas.models import SaleDetail
from django.db.models import Sum, F, FloatField
''' ------------ '''
q = SaleDetail.objects.filter(sale=1).values('price_sale', 'quantity')
q.aggregate(Sum(F('price_sale') * F('quantity')), output_field=FloatField())
# falhou
''' ------------... | StarcoderdataPython |
3332449 | <reponame>Clemson-DPA/dpa-pipe-backend
from rest_framework import routers
from locations import rest_api as loc_api
from products import rest_api as product_api
from ptasks import rest_api as ptask_api
from users import rest_api as user_api
api_router = routers.DefaultRouter()
# ---- locations
api_router.register(
... | StarcoderdataPython |
1791529 | <reponame>megmogmog1965/PythonMachineLearning<gh_stars>1-10
#!/usr/bin/env python
# encoding: utf-8
'''
Created on Apr 15, 2017
@author: <NAME>
'''
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.svm import SVC
from sklearn.preprocessing import StandardScaler
from sklearn... | StarcoderdataPython |
67694 | <gh_stars>1-10
'''
Note: http://bugs.python.org/issue11077 seems to indicate that tk is
supposed to be thread-safe, but everyone else on the net insists that
it isn't. Be safe, don't call into the GUI from another thread.
'''
try:
import tkinter as tk
except ImportError:
print("pyfrc robot simul... | StarcoderdataPython |
1634910 | import os
from flask import render_template, redirect, url_for, flash
import flask_login
import scrypt
from simple_recipes import app, login_manager
from simple_recipes.db.users import *
from simple_recipes.forms import UserForm
class User(flask_login.UserMixin):
pass
@login_manager.user_loader
def user_loade... | StarcoderdataPython |
3353269 |
import pytest
import {{ cookiecutter.package_name }} as pkg
def test_simple():
assert pkg.remove_this() == 42
| StarcoderdataPython |
148997 | #!/usr/bin/env python
# Does a kind of grep that prints lines between two given regular expressions
# (where between is inclusive)
import re
import sys
import optparse
#-- main stuff
def parsePositionalArgs (argv, parser) :
if (len (argv) <= 1) :
parser.error("must supply more args")
else :
s... | StarcoderdataPython |
12232 | """TilePyramid creation."""
import pytest
from shapely.geometry import Point
from shapely.ops import unary_union
from types import GeneratorType
from tilematrix import TilePyramid, snap_bounds
def test_init():
"""Initialize TilePyramids."""
for tptype in ["geodetic", "mercator"]:
assert TilePyramid(... | StarcoderdataPython |
166201 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
import joblib
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.optim import Adam, SGD
import tqdm
import itertools
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsCla... | StarcoderdataPython |
179293 | <gh_stars>0
""" Problem: sWAP cASE || Task:
You are given a string and your task is to swap cases. In other words, convert all lowercase letters to uppercase letters and vice versa.
Created on Wed Oct 10 10:50:38 2018
@author: nagiAI
"""
import string
def swap_case(s):
result = ""
for i in s:
if (ord(... | StarcoderdataPython |
3302242 | import math
from fractions import Fraction
globals()["\x5f\x5f\x6e\x61\x6d\x65\x5f\x5f"] = "\x4a\x73\x6b\x4d\x61\x66\x73\x2e\x70\x79"
__description__ = "Jsk Troll's Python toolkit for easy maths ;) "
if not __name__ in __file__:
rename(__file__, __name__)
message = "Try again."
raise Exception(message)
def sign(n)... | StarcoderdataPython |
133413 | # pylint: disable=no-member, missing-docstring
from unittest import TestCase
from pytest import mark
from celery import shared_task
from django.test.utils import override_settings
from edx_django_utils.cache import RequestCache
@mark.django_db
class TestClearRequestCache(TestCase):
"""
Tests _clear_request... | StarcoderdataPython |
162674 | # Generated from JavaLexer.g4 by ANTLR 4.9.3
from antlr4 import *
from io import StringIO
import sys
if sys.version_info[1] > 5:
from typing import TextIO
else:
from typing.io import TextIO
def serializedATN():
with StringIO() as buf:
buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\... | StarcoderdataPython |
132004 | <filename>tests/test_maze.py
#!usr/bin/python3
import sys, os
sys.path.append(os.path.realpath(os.path.dirname(__file__)+"/.."))
from classes.maze import Maze, Cell
class TestingMaze:
def test_width(self):
maze = Maze(20, 5)
assert maze.getCols() == 20
def test_min_width(self):
m... | StarcoderdataPython |
4833766 | <filename>test_script.py
import unittest
import script
import setupFolder #to set up folder structure for test cases
import os
import string
import shutil #to do force remove
import random
from random import randint
class TestReadfile(unittest.TestCase):
def setUp(self):
print("SETUP")
self.rootFol... | StarcoderdataPython |
3307305 | # 4/29/2018
from __future__ import division
import calendar
import csv
from collections import Counter
import gensim
import matplotlib.pyplot as plt
from math import sqrt
import numpy as np
import pandas as pd
import platform
import os
import random
import re, ast
import scipy
import sklearn
from sklearn import linear_... | StarcoderdataPython |
3239972 | """
ASDF tags for geometry related models.
"""
from asdf import yamlutil
from ..gwcs_types import GWCSTransformType
from .. geometry import (ToDirectionCosines, FromDirectionCosines,
SphericalToCartesian, CartesianToSpherical)
__all__ = ['DirectionCosinesType', 'SphericalCartesianType']
cla... | StarcoderdataPython |
1643852 | # coding: utf-8
import logging
from enum import IntEnum, auto
from PyQt5 import uic
from PyQt5.QtCore import (QAbstractTableModel, QModelIndex, Qt)
from PyQt5.QtWidgets import (QHeaderView,
QDataWidgetMapper)
from mhw_armor_edit.assets import Assets
from mhw_armor_edit.editor.models impor... | StarcoderdataPython |
3355654 | <gh_stars>0
def fat(n):
print(n)
return 1 if (n < 1) else n * fat(n-1)
x = fat(5)
print(x)
| StarcoderdataPython |
161294 | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import ... | StarcoderdataPython |
68810 | # ----------------------------------------------------------------------
# inv.ResourceGroup tests
# ----------------------------------------------------------------------
# Copyright (C) 2007-2018 The NOC Project
# See LICENSE for details
# ----------------------------------------------------------------------
# NOC ... | StarcoderdataPython |
1696869 | logs = {
"img": [
"[INFO] Loading input image: {}",
"[ERROR] On '{}': you need to pass the image path!",
"\te.g. --img='Pictures/notNord.jpg'"
],
"out": [
"[INFO] Set output image name: {}",
"[ERROR] On '{}': no output filename specify!",
"\te.g. --out='Pict... | StarcoderdataPython |
10027 | """
Pycovjson - Command line interface
Author: rileywilliams
Version: 0.1.0
"""
import argparse
from pycovjson.write import Writer
from pycovjson.read_netcdf import NetCDFReader as Reader
def main():
"""
Command line interface for pycovjson - Converts Scientific Data Formats into CovJSON and saves to disk.
... | StarcoderdataPython |
3268451 | <gh_stars>0
import boto3
dynamoDB = boto3.resource('dynamodb')
table = dynamoDB.Table('users')
def lambda_handler(event, context):
# TODO implement
print(event)
event = event['queryStringParameters']
email = event['email']
data = {"email":email}
print("This is email: " + email)
print("This... | StarcoderdataPython |
182513 | <gh_stars>1-10
import nltk
from nltk.corpus import stopwords
import heapq
nltk.download('stopwords')
nltk.download('punkt')
def nltk_summarizer(raw_text):
stop_words = set(stopwords.words("english"))
word_frequencies = {}
for word in nltk.word_tokenize(raw_text):
if word not in stop_words:
... | StarcoderdataPython |
169627 | from src.Shared.Helpers.Transformer import Transformer
from src.User.Domain.Entities.User import User
class UserTransformer(Transformer):
# roleTransformer: RoleTransformer
def __init__(self):
super()
# self.roleTransformer = RoleTransformer()
def transform(self, user: User):
retu... | StarcoderdataPython |
18707 | import os
import sys
import json
import argparse
import numpy as np
sys.path.append('Camera_Intrinsics_API/')
from get_camera_intrinsics import CameraIntrinsicsHelper
if __name__=='__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
"--input_dir",
type=str,
default='dat... | StarcoderdataPython |
1659828 | <filename>src/genie/libs/parser/iosxe/tests/test_show_install.py<gh_stars>1-10
#!/bin/env python
import unittest
from unittest.mock import Mock
from pyats.topology import Device
from genie.metaparser.util.exceptions import SchemaEmptyParserError,\
SchemaMissingKeyError
from geni... | StarcoderdataPython |
3257215 | <reponame>kevinnguyenhoang91/PodToBUILD
import json
import os
def render_podfile(pods):
"""
This renders out a podfile for a build test
"""
print("project 'PodsHost/PodsHost.xcodeproj'")
print("target 'ios-app' do")
skip_pods = [
# This a macOS pod build we build for iOS
# I... | StarcoderdataPython |
3271600 | # Copyright (c) 2020, <NAME>.
# Distributed under the MIT License. See LICENSE for more info.
"""A module defining plots for PCA variance."""
from matplotlib import pyplot as plt
from matplotlib.ticker import MaxNLocator
import numpy as np
from psynlig.colors import generate_colors
def _create_figure_if_needed(axi, f... | StarcoderdataPython |
8847 | <gh_stars>0
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
import numpy as np
import random
from datetime import datetime
import sys
import argparse
import torch
import os
from inspect import currentframe, getframeinfo
GEOSCORER_DIR = os.path.dirname(os.path.realpath(__file__))
CRAFTASSIST_DIR = os.path.joi... | StarcoderdataPython |
46418 | """
Metrics for (mulit-horizon) timeseries forecasting.
"""
from pytorch_forecasting.metrics.base_metrics import (
DistributionLoss,
Metric,
MultiHorizonMetric,
MultiLoss,
MultivariateDistributionLoss,
convert_torchmetric_to_pytorch_forecasting_metric,
)
from pytorch_forecasting.metrics.distrib... | StarcoderdataPython |
1734343 | import turtle
def polygon(sides, length):
t = turtle.Turtle()
t.color("lime")
t.speed(0)
angle = 360 / sides
for side in range(sides):
t.forward(length)
t.right(angle)
t.hideturtle()
for n in [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]:
polygon(n, 35)
input()
| StarcoderdataPython |
80453 | <reponame>waweru12/The-news-highlighter
import unittest
from app.models import Source
from app.models import Article
class SourceTest(unittest.TestCase):
'''
Test Class to test the behaviour of the Source class
'''
def setUp(self):
'''
Set up method that will run before every Test
... | StarcoderdataPython |
156798 | <filename>registrobrepp/contact/brcreatecontactcommand.py
from eppy.doc import EppCreateContactCommand
from registrobrepp.common.authinfo import AuthInfo
from registrobrepp.contact.disclose import Disclose
from registrobrepp.contact.phone import Phone
from registrobrepp.contact.postalinfo import PostalInfo
class BrE... | StarcoderdataPython |
3244989 | <reponame>kyapp69/GCodeViewer
import logging
import OpenGL
OpenGL.FORWARD_COMPATIBLE_ONLY = True
# ^ See http://pyopengl.sourceforge.net/documentation/deprecations.html
import OpenGL.GL as gl
class ShaderLoader(object):
@classmethod
def load_vertex_shader(cls, file_path):
shader_id = gl.glCreateShade... | StarcoderdataPython |
136691 | # price.py
from .helper_functions import (build_url, load_data, timestamp_to_date,
date_to_timestamp)
def get_current_price(fsyms, tsyms, e='all', try_conversion=True, full=False,
format='raw'):
"""Get latest trading price or full trading information i... | StarcoderdataPython |
4834733 | import distributedGrepTest
import wordCountTest
import URLFrequencyTest
import json
f = open("wordcount.json", 'r')
worcountconfig = f.read()
f.close()
worcountconfig = json.loads(worcountconfig)
wordCountTest.test(worcountconfig["inputfile"], worcountconfig["outputdir"])
f = open("distributedgrep.json", 'r')
distrib... | StarcoderdataPython |
1728519 | '''
area_curves.py
Find the area enclosed by two curves between two points
'''
from sympy import Integral, Symbol, SympifyError, sympify
def find_area(f, g, var, a, b):
a = Integral(f-g, (var, a, b)).doit()
return a
if __name__ == '__main__':
f = input('Enter the upper function in one variable: ')
g... | StarcoderdataPython |
1701923 | # wallstop.py
import time
import brickpi3
import grovepi
BP = brickpi3.BrickPi3()
ultrasonic_sensor_port = 4
try:
while grovepi.ultrasonicRead(ultrasonic_sensor_port) > 15:
print("Sensor: %6d Motor A: %6d B: %6d C: %6d D: %6d" \
% (grovepi.ultrasonicRead(ultrasonic_sensor_port), \
BP.get_motor_encoder(B... | StarcoderdataPython |
3357903 |
class ModelManager( object ):
pass
class ModelSerializer( object ):
pass
| StarcoderdataPython |
3292019 | import unittest
from datetime import timedelta
from datetimerange import DateTimeRange
from logreader.lineage import Lineage
from tests.character_factories import eve, female
class TestLineage(unittest.TestCase):
def test_duration_at_least_eve_fertility(self):
e = eve()
sut = Lineage(e)
... | StarcoderdataPython |
1618468 | import sys
import logging
from datetime import datetime
from pathlib import Path
from nltk.tokenize import sent_tokenize
from base import dataset, embedding_index, embedding_model, word_weight, sentence_splitter
from base.dataset import Dataset
from base.document import Document
from base.embedding_index import Embed... | StarcoderdataPython |
3214929 | import json
import multiprocessing
import time
import requests
import snappi
from flask import Flask, Response, request
from otg_gnmi.common.utils import init_logging, get_current_time
from tests.utils.common import get_mockserver_status
from tests.utils.settings import MockConfig
app = Flask(__name__)
CONFIG = Mock... | StarcoderdataPython |
3382679 | <reponame>subhacom/mbnet
# kc_ggn_feedback_dclamp.py ---
# Author: <NAME>
# Created: Tue Aug 20 10:58:08 2019 (-0400)
# Last-Updated: Wed Dec 11 17:32:49 2019 (-0500)
# By: <NAME>
# Version: $Id$
# Code:
"""This script for testing expansion of the dynamic range of a KC due to GGN inhibition.
Instead of run... | StarcoderdataPython |
3209124 | <reponame>HarduinLearnsCoding/Pattern-Recognition
from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
#optimizing fn generation
def gauss(x, K, B, x0, stddev):
return K + B * np.exp(-(x - x0) ** 2 / (2 * stddev ** 2))
def gaussia... | StarcoderdataPython |
106723 | import os
import json
from pathlib import Path
import pem
from Crypto.PublicKey import RSA
from jupyterhub.handlers import BaseHandler
from illumidesk.authenticators.utils import LTIUtils
from illumidesk.lti13.auth import get_jwk
from tornado import web
from urllib.parse import urlencode
from urllib.parse import ... | StarcoderdataPython |
108992 | class NCBaseError(Exception):
def __init__(self, message) -> None:
super(NCBaseError, self).__init__(message)
class DataTypeMismatchError(Exception):
def __init__(self, provided_data, place:str=None, required_data_type:str=None) -> None:
message = f"{provided_data} datatype isn't supported for... | StarcoderdataPython |
1681211 | <reponame>nagylzs/python-venus-lib
"""PostgreSQL database adapter package.
Uses the psycopg2 extension."""
import copy
import getpass
import os
import re
import sys
import psycopg2
from venus.db.dbo import connection
# http://www.postgresql.org/docs/9.2/static/libpq-pgpass.html
_PGPASS_PAT = re.compile(r"([^:]+):([... | StarcoderdataPython |
182372 | # Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma de
# Barcelona (UAB).
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
from carla.settings import CarlaSettings
class Experiment(object):
def __init__(self):
... | StarcoderdataPython |
3260952 | <filename>testpy/testnumpy.py
import numpy as np
x = np.int_([1, 2])
y = np.int_([[2, 4, 6],
[3, 3, 3]])
print np.dot(x, y)
z = np.zeros((2, 3))
print z
| StarcoderdataPython |
3284643 | # Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import
import errno
import os
import shutil
import zipfile
from argparse import ArgumentParser, Namespace
from collections import defaultdict
from textwrap... | StarcoderdataPython |
4826328 | <reponame>154544017/PetrarchChineseServer
# -*- coding: utf-8 -*-
from resource import db
class AnalycisEventResultSubThread(db.Model):
# 事件分类结果
id = db.Column(db.Integer, primary_key=True)
text_id = db.Column(db.String(255))
recall_rate = db.Column(db.DECIMAL)
accuracy_rate = db.Column(db.DECIMAL)
event_num =... | StarcoderdataPython |
139376 | <filename>sp/apps.py
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
class SPConfig(AppConfig):
name = "sp"
verbose_name = _("SAML SP")
| StarcoderdataPython |
3307989 | import scrapy
from rt.items import *
import re
class PersonSpider(scrapy.Spider):
name = 'person'
allowed_domains = ['rottentomatoes.com']
# start_urls = ['https://www.rottentomatoes.com/m/blade_runner_2049']
start_urls = ['https://www.rottentomatoes.com/celebrity/ben_affleck']
def parse(self, res... | StarcoderdataPython |
1769918 | <filename>artifact_py/completion.py
# artifact_py: the design documentation tool made for everyone.
#
# Copyright (C) 2019 <NAME> <github.com/vitiral>
#
# The source code is Licensed under either of
#
# * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or
# http://www.apache.org/licenses/LICENSE-2.0)
#... | StarcoderdataPython |
66606 | from __future__ import unicode_literals
import requests
from .basemanager import BaseManager
from .constants import XERO_API_URL
class TrackingCategoryOptionsManager(BaseManager):
def __init__(self, credentials, user_agent=None):
from xero import __version__ as VERSION
self.credentials = creden... | StarcoderdataPython |
3362569 |
"""
Copyright 2015, MASSACHUSETTS INSTITUTE OF TECHNOLOGY
Subject to FAR 52.227-11 – Patent Rights – Ownership by the Contractor (May 2014).
SPDX-License-Identifier: BSD-3-Clause
Return codes
ref: http://www.cardwerk.com/smartcards/smartcard_standard_ISO7816-4_6_basic_interindustry_commands.aspx
ref: http:/... | StarcoderdataPython |
3371817 | <reponame>pgromano/sampy
import numpy as np
__all__ = [
'check_array',
'set_random_state',
'cache_property',
]
def check_array(X, ensure_1d=False, ensure_2d=False, squeeze=False,
atleast_2d=False, feature_axis='col', reduce_args=False,
dtype=None):
""" Check Array
Parameters
----------
X : array-l... | StarcoderdataPython |
3353366 | import asyncio
import hmac
from json import loads
from urllib.parse import parse_qs, urlencode
import aiohttp
import aiohttp_jinja2
from aiohttp import web
from aiohttp_session import get_session
routes = web.RouteTableDef()
def sign(key, msg):
return hmac.new(key.encode("ascii"),
msg=msg.en... | StarcoderdataPython |
3255590 | <filename>plugins/mixins/aws_service.py
from systems.plugins.index import ProviderMixin
from utility.data import ensure_list
import os
import boto3
import random
class AWSServiceMixin(ProviderMixin('aws_service')):
@classmethod
def generate(cls, plugin, generator):
super().generate(plugin, generator... | StarcoderdataPython |
1616264 | #!/usr/bin/env python3
""" Produces list of map cell values, and cell offsets where they first appear """
import sys
import argparse
from itsybitser import hextream
def main():
""" Program entry point """
parser = argparse.ArgumentParser(
description=(
"Takes Hextream-encoded map data (as... | StarcoderdataPython |
3372231 | # Copyright (c) 2016 Universidade Federal Fluminense (UFF)
# Copyright (c) 2016 Polytechnic Institute of New York University.
# This file is part of noWorkflow.
# Please, consult the license terms in the LICENSE file.
"""Lightweight objects for storage during collection"""
from __future__ import (absolute_import, print... | StarcoderdataPython |
1669677 | # -*- coding: utf-8 -*-
from . import settings, config
from . import install
from .oset import OrderedSet
from .adict import AttrDict
from .package import Package, PKG_STATUS_STR, PKG_STATUS_NAMES
from .utils import print_graph, print_array
from .output import ( info as _,
warn as _w,
... | StarcoderdataPython |
185193 | <filename>grades/migrations/0009_auto_20200514_1432.py<gh_stars>0
# Generated by Django 3.0 on 2020-05-14 14:32
from django.db import migrations
def create_through_relations(apps, schema_editor):
Tag = apps.get_model("grades", "Tag")
CourseTag = apps.get_model("grades", "CourseTag")
for tag in Tag.object... | StarcoderdataPython |
131492 | # Copyright (c) 2018, <NAME>,
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the fol... | StarcoderdataPython |
3308099 | class Persona:
def __init__(self, nombre):
self.nombre = nombre
def __del__(self):
print("Ha muerto {}".format(self.nombre))
| StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.