id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
338168
<gh_stars>0 # Copyright 2021 RangiLyu. # # 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...
StarcoderdataPython
5107176
<reponame>bavard-ai/bavard-ml-utils import time import typing as t from abc import ABC, abstractmethod from fastapi import HTTPException, status from loguru import logger from bavard_ml_utils.persistence.record_store.base import BaseRecordStore, Record from bavard_ml_utils.types.utils import hash_model class Servic...
StarcoderdataPython
8190821
import enum from sims4.tuning.dynamic_enum import DynamicEnum class BouncerRequestStatus(enum.Int, export=False): INITIALIZED = 0 SUBMITTED = 1 SIM_FILTER_SERVICE = 2 SPAWN_REQUESTED = 3 FULFILLED = 4 DESTROYED = 5 class BouncerRequestPriority(enum.Int): GAME_BREAKER = 0 EVENT_VIP = 1 ...
StarcoderdataPython
157046
<reponame>samlowe106/Saved-Sorter-For-Reddit<gh_stars>1-10 import unittest """ Unless otherwise stated, none of the URLs used for testing should be dead. """ class TestURLS(unittest.TestCase): """Verifies that the URLs module works as intended""" def test_determine_name(self): """Verifies that deter...
StarcoderdataPython
3349844
<reponame>antoine-spahr/MNIST-classification-LeNet5<filename>src/dataset/MNISTDataset.py<gh_stars>0 import torchvision import torchvision.transforms as tf import torch.utils.data import PIL.Image class MNISTDataset(torch.utils.data.Dataset): """ Define a MNIST dataset (and variant) that return the data, targt ...
StarcoderdataPython
381205
<reponame>vabkar8/questionpapergen<filename>app.py import sentry_sdk from sentry_sdk.integrations.flask import FlaskIntegration from flaskapp import create_app from flaskapp.config import DevelopmentConfig sentry_sdk.init( dsn= "https://1fdf413ccfcc4a249f79519bfc269965@o374456.ingest.sentry.io/5192531", i...
StarcoderdataPython
8111848
<filename>third_party/zhon/tests/test-pinyin.py """Tests for the zhon.pinyin module.""" import random import re import unittest from zhon import pinyin NUM_WORDS = 50 # Number of random words to test WORD_LENGTH = 4 # Length of random words (number of syllables) NUM_SENT = 10 # Number of random sentences ...
StarcoderdataPython
4965585
# apis_v1/views/views_measure.py # Brought to you by We Vote. Be good. # -*- coding: UTF-8 -*- from config.base import get_environment_variable from django.http import HttpResponse import json from measure.controllers import add_measure_name_alternatives_to_measure_list_light, measure_retrieve_for_api, \ retrieve_m...
StarcoderdataPython
363327
# Django from django.urls import path # Views from .views import login_view, signup_view, logout_view app_name = 'auth' urlpatterns = [ path('', login_view, name='login'), path('logout', logout_view, name='logout'), path('register', signup_view, name='register') ]
StarcoderdataPython
9795291
from .is_iterable_of import is_iterable_of from .is_list import is_list class is_list_of(is_iterable_of): """ Generates a predicate that checks that the data is a list where every element of the data is valid according to the given predicate. """ prerequisites = [is_list]
StarcoderdataPython
11342705
<filename>crypt.py #!/usr/bin/env python #coding=utf-8 import sys import os import json import shutil import subprocess import argparse ############################################################ #http://www.coolcode.org/archives/?article-307.html #######################################################...
StarcoderdataPython
11347153
from unittest import TestCase from app.core.result import Result class TestResult(TestCase): def test___unsuccessful_by_default(self): result = Result() self.assertEqual(False, result.was_success) self.assertEqual(False, result.was_error) def test_set_success(self): result = ...
StarcoderdataPython
153900
from haystack.query import SearchQuerySet from search.services.suggest import SuggestBase class SuggestInvestigator(SuggestBase): @classmethod def _query(cls, term): sqs = SearchQuerySet() raw_results = sqs.filter(investigator_name=term).order_by('-investigator_complaint_count')[:5] ...
StarcoderdataPython
6577115
from django.db import models from django.contrib import admin from django.contrib.admin.views.main import ChangeList from django.utils.translation import gettext as _, get_language from martor.widgets import AdminMartorWidget from .models import Post, Category, Tag class CustomPostChangeList(ChangeList): def __i...
StarcoderdataPython
11373136
<reponame>wyaadarsh/LeetCode-Solutions<filename>Python3/0265-Paint-House-II/soln.py class Solution: def minCostII(self, costs): """ :type costs: List[List[int]] :rtype: int """ if not costs: return 0 n, k = len(costs), len(costs[0]) for i in range(1, n): ...
StarcoderdataPython
6457308
import pcp_utils import sys import os import click import yaml import random RANDOM_SEED = 0 # add gym and baseline to the dir gym_path = pcp_utils.utils.get_gym_dir() baseline_path = pcp_utils.utils.get_baseline_dir() sys.path.append(gym_path) sys.path.append(baseline_path) # make symbolic link of the mesh under ...
StarcoderdataPython
6653181
<reponame>mattslezak-shell/PROJ_Option_Pricing_Matlab<filename>CTMC/Diffusion_3D/price_3d_ctmc.py<gh_stars>0 # Generated with SMOP 0.41-beta try: from smop.libsmop import * except ImportError: raise ImportError('File compiled with `smop3`, please install `smop3` to run it.') from None # price_3d_ctmc.m ...
StarcoderdataPython
5190125
import sys import threading import weakref class RunSelfFunction(object): def __init__(self, should_raise): # The links in this refcycle from Thread back to self # should be cleaned up when the thread completes. self.should_raise = should_raise self.thread = threading.Thread(targe...
StarcoderdataPython
8169127
# %% class StigmataSet: """Class for Stigmata Objects""" def __init__(self,name,set2,set3): self.name = name self.set2 = set2 self.set3 = set3 def __setattr__(self,setability2,setability3): self.setbility.update( { 2:setability2, ...
StarcoderdataPython
4836513
<gh_stars>1-10 import unittest import numpy as np from dataset.assemble.NorbAssembler import NorbAssembler class Test_NorbAssembler(unittest.TestCase): def setUp(self): self._norbAssember = NorbAssembler() def test_stereoPairsAreSeparated_AndCategoriesUpdated(self): firstImage = np.arange(0...
StarcoderdataPython
1943997
##################### ### Basic Imports ### ##################### import random ###################### ### Custom Imports ### ###################### from . import definitions from . import classes from . import help from . import commands ###################### # Basic Settings# def setname(): # Set your characters ...
StarcoderdataPython
8002671
# from SPARQLWrapper import SPARQLWrapper, JSON import argparse import wikidata parser = argparse.ArgumentParser( description='Fixes labels for various usages.') parser.add_argument('-s', help='source file', default='qids.txt') parser.add_argument('-p', help='property', default='P1705') args = parser.parse_args()...
StarcoderdataPython
1996173
<reponame>zhengzangw/Fed-SINGA import argparse from singa import tensor from src.client.app import Client from src.server.app import Server max_epoch = 3 def main_server(s): s.start() s.pull() for i in range(max_epoch): print(f"[Server] On epoch {i}") s.push() s.pull() s.c...
StarcoderdataPython
3474777
# coding=utf-8 # Copyright 2018 The Tensor2Tensor Authors. # # 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...
StarcoderdataPython
6553376
from . import controllers, defines, hooks, infos, parameters, parts, util
StarcoderdataPython
3507356
from .error_utils import BuildSystemException def load_export_list_from_def_file(def_file, winapi_only, for_winapi): export_section_found = False export_list = [] lines = [line.rstrip('\r\n') for line in open(def_file)] line_number = 0 inside_export = False for line in lines: line_numb...
StarcoderdataPython
11383961
<filename>utils.py import cv2 def split_board_image(floc, fname, out_dir, board=None): img = cv2.imread(floc) square_size = 150 for r in range(0, img.shape[0], 150): i = r // square_size for c in range(0, img.shape[1], 150): j = c // square_size if board: piece = board[i][j] ...
StarcoderdataPython
238941
#!/usr/bin/env python import os try: import readline # NOQA except ImportError: pass from pprint import pprint # NOQA from coaster.sqlalchemy import BaseMixin from coaster.utils import buid from flask import Flask from nodular import * # NOQA class User(BaseMixin, db.Model): __tablename__ = 'user' ...
StarcoderdataPython
4908482
""" This module contains classes intended to parse and deal with data from Roblox roblox badge endpoints. """ from .bases.baserobloxbadge import BaseRobloxBadge from .utilities.shared import ClientSharedObject class RobloxBadge(BaseRobloxBadge): """ Represents a Roblox roblox badge. Attributes: ...
StarcoderdataPython
4855704
<filename>src/oci/data_connectivity/models/__init__.py # coding: utf-8 # Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown a...
StarcoderdataPython
9697126
<reponame>bjonnh/fomu-playground<filename>litex_things/deps/litescope/litescope/software/dump/common.py def dec2bin(d, width=0): if d == "x": return "x"*width elif d == 0: b = "0" else: b = "" while d != 0: b = "01"[d&1] + b d = d >> 1 return b.zfi...
StarcoderdataPython
32002
import numpy as np from scipy import interpolate, signal from scipy.special import gamma import ndmath import warnings import pkg_resources class PlaningBoat(): """Prismatic planing craft Attributes: speed (float): Speed (m/s). It is an input to :class:`PlaningBoat`. weight (float): Weigh...
StarcoderdataPython
5060725
from __future__ import annotations from transformers import RobertaTokenizer, XLMRobertaTokenizerFast try: from icu import Locale, BreakIterator icu_available = True except ImportError: icu_available = False from pelutils.jsonl import load_jsonl ENTITY_UNK_TOKEN = "[UNK]" ENTITY_MASK_TOKEN = "[MASK]" c...
StarcoderdataPython
11351759
import discord from .utils import Time from .fluctlight_ext import Fluct from .db.jsonstorage import JsonApi async def report_lect_attend(bot, attendants: list, week: int) -> None: report_json = JsonApi.get('LectureLogging') guild = bot.get_guild(784607509629239316) report_channel = discord.utils.get(guil...
StarcoderdataPython
12810558
<gh_stars>0 class Config(object): """ Wrapper class for various (hyper)parameters. """ def __init__(self): # about the model architecture self.cnn = 'vgg16' # 'vgg16' or 'resnet50' self.max_caption_length = 20 self.dim_embedding = 512 self.num_lstm_units = ...
StarcoderdataPython
4896379
<gh_stars>10-100 """A set of utils to generate Tensorflow Dataset instances.""" import logging import tensorflow as tf import word2vec.utils.vocab as vocab_utils logger = logging.getLogger(__name__) __all__ = ('get_w2v_train_dataset') def ctx_idxx(target_idx, window_size, tokens): """Return positions of cont...
StarcoderdataPython
359457
import os, random, pickle from thebutton.parser import parse from thebutton.standardwaitstep import StandardWaitStep COMPLETED_CHALLENGES_PATH = "completed_challenges.pkl" def load_completed(): try: with open(COMPLETED_CHALLENGES_PATH, "rb") as f: return pickle.load(f) except FileNotFoun...
StarcoderdataPython
8031248
from eru.utils import init_gpu from eru.model import Model from eru.layers import GRU, Dense, Input, Activation import random import torch from urllib.request import urlopen from torch.autograd import Variable init_gpu(3) url = "https://stuff.mit.edu/afs/sipb/contrib/pi/pi-billion.txt" html = urlopen(url).read() pi ...
StarcoderdataPython
8147208
<reponame>quentin-ma/study-task-scheduling<gh_stars>1-10 """Module containing the generation of tasks for scheduling algorithms. Each task contains parameters that indicate its identifier, its processing time, dependencies, and others. """ import random class Task: """ Task object. Attributes -----...
StarcoderdataPython
1964588
<gh_stars>0 import os from cloudburst.client.client import CloudburstConnection cloudburst = None def get_or_init_client(): global cloudburst if cloudburst is None: ip = os.environ.get("MODIN_IP", None) conn = os.environ.get("MODIN_CONNECTION", None) cloudburst = CloudburstCo...
StarcoderdataPython
9774881
<gh_stars>0 import json import os import pytest from freezegun import freeze_time from actors_films import display_output, get_actor, get_movies, write_to_disk from classes import Actor, Movie @pytest.fixture def mock_retrieve_celebs(monkeypatch): monkeypatch.setattr( "imdb_calls.retrieve_celebs", ...
StarcoderdataPython
1982883
""" btclib build script for setuptools. """ from setuptools import find_packages, setup # type: ignore import btclib with open("README.md", "r", encoding="ascii") as file_: longdescription = file_.read() setup( name=btclib.name, version=btclib.__version__, url="https://btclib.org", project_url...
StarcoderdataPython
6592512
""" MIT License Copyright (c) 2020 GamingGeek 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 to use, copy, modify, merge, publish, di...
StarcoderdataPython
1736722
#!/usr/bin/env python # encoding: utf-8 """ This module summarises the tasks that are to be run daily. """ import luigi from tasks.ingest.list_hdfs_content import CopyFileListToHDFS from tasks.analyse.hdfs_analysis import GenerateHDFSSummaries from tasks.analyse.hdfs_reports import GenerateHDFSReports from tasks.backu...
StarcoderdataPython
3345640
#! /usr/bin/env python ############################################################################## ## DendroPy Phylogenetic Computing Library. ## ## Copyright 2010-2015 <NAME> and <NAME>. ## All rights reserved. ## ## See "LICENSE.rst" for terms and conditions of usage. ## ## If you use this work or any portio...
StarcoderdataPython
6689013
import socket host = '' port = 5000 backlog = 5 size = 1024 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host, port)) s.listen(backlog) while 1: client, address = s.accept() data = client.recv(size) if data: print(data) print(len(data)) client.close()
StarcoderdataPython
3417743
<gh_stars>0 # This file is part of the pyMOR project (http://www.pymor.org). # Copyright Holders: <NAME>, <NAME>, <NAME> # License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) from __future__ import absolute_import, division, print_function import pprint import pkgutil import sys import numpy a...
StarcoderdataPython
6444487
<filename>karesansui/gadget/host.py<gh_stars>10-100 # -*- coding: utf-8 -*- # # This file is part of Karesansui. # # Copyright (C) 2009-2012 HDE, Inc. # # 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...
StarcoderdataPython
4959746
<filename>scripts/hello_world.py # -*- encoding: utf-8 -*- print('Hello world!')
StarcoderdataPython
363157
<reponame>SqrtMinusOne/ERMaket_Experiment<gh_stars>0 # -*- coding: utf-8 -*- # Resource object code # # Created by: The Resource Compiler for PyQt5 (Qt v5.14.2) # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore qt_resource_data = b"\ \x00\x00\x01\xe8\ \x89\ \x50\x4e\x47\x0d\x0a\x1a\x0...
StarcoderdataPython
5126733
# internal projects import sys import re # python packages from vertex import Vertex from read_file import read_file, extract class Graph: ''' this class creates a graph or digraph. a graph is like a tree, but allows cycles and loops. its methods allow certain checks and passes on the graph. ''' ...
StarcoderdataPython
274978
import os from glob import glob from nltk import ToktokTokenizer import numpy as np from nltk.translate.bleu_score import SmoothingFunction from fast_bleu import * os.system("set -x; python setup.py build_ext --build-lib=./") # min_n = 2 max_n = 5 weights = np.ones(max_n) / float(max_n) def nltk_org_bleu(refs, hyp...
StarcoderdataPython
6413427
"""Utility implementations for docstrings. """ import inspect import os import re from enum import Enum from inspect import Signature from typing import Any from typing import Callable from typing import List from typing import Match from typing import Optional from typing import Pattern from typing impo...
StarcoderdataPython
3493567
<reponame>CaptainE/lcnn<filename>bts/pytorch/bts_test.py # Copyright (C) 2019 <NAME> # # This file is a part of BTS. # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the Licen...
StarcoderdataPython
79387
""" Copyright (c) 2019 Red Hat, Inc All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. """ from textwrap import dedent import sys from flexmock import flexmock import pytest import atomic_reactor.utils.koji as koji_util from atomi...
StarcoderdataPython
4845524
<gh_stars>0 #!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import setuptools from dbsavior import __version__ as version here = os.path.abspath(os.path.dirname(__file__)) sys.path.insert(0, here) with open("README.md", "r") as fh: long_description = fh.read() requirements_path = os.path.joi...
StarcoderdataPython
9667060
from __future__ import print_function import sys import time import numpy as np from pyspark import SparkContext if __name__ == "__main__": sc = SparkContext(appName="PythonLR") D = 10 p = 4 iterations = 20 N = 10 if len(sys.argv)>1: N = int(sys.argv[1]) if len(sys.argv)>2: ...
StarcoderdataPython
3569048
""" Authors: <NAME> (<EMAIL>), <NAME> (<EMAIL>) Copyright © 2021, United States Government, as represented by the Administrator of the National Aeronautics and Space Administration. All rights reserved. The HybridQ: A Hybrid Simulator for Quantum Circuits platform is licensed under the Apache License, Versio...
StarcoderdataPython
381937
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Project : tql-Python. # @File : coordinate # @Time : 2019-09-22 16:00 # @Author : yuanjie # @Email : <EMAIL> # @Software : PyCharm # @Description : import re import requests url = 'https://blog.csdn.net/Yellow_python/article/deta...
StarcoderdataPython
3478240
__all__ = ["ModelAdapter"] from icevision.models.torchvision.lightning_model_adapter import * from icevision.models.torchvision.retinanet.prediction import * class ModelAdapter(RCNNModelAdapter): """Lightning module specialized for retinanet, with metrics support. The methods `forward`, `training_step`, `va...
StarcoderdataPython
8170253
""" MIT License Copyright (c) 2020 ValkyriaKing711 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 to use, copy, modify, merge...
StarcoderdataPython
11214087
<gh_stars>1-10 import convst from setuptools import setup, find_packages from codecs import open import numpy import os ROOT = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(ROOT, 'README.md'), encoding="utf-8") as f: README = f.read() setup( name="convst", description="The Convolut...
StarcoderdataPython
9720900
x = list(input().replace(" ","")) y = list(input().replace(" ","")) from collections import Counter x = Counter(x) y = Counter(y) for i,j in y.items(): if i in x: if j<=x[i]: pass else: print("NO") break else: print("NO") break else: print(...
StarcoderdataPython
8134755
<gh_stars>0 #!/usr/bin/env python # -*- coding: utf-8 -*- """:Mod: test_model :Synopsis: :Author: servilla :Created: 11/25/18 """ import os import sys import time import unittest import daiquiri import pendulum from soh.config import Config from soh.model.soh_db import SohDb sys.path.insert(0, os.path....
StarcoderdataPython
1734319
import os import requests log = open("./tests/latest.stylelog", "w") results = os.popen("pycodestyle ./parameterparser/*.py").read() lines = results.strip().splitlines() url = None url_failed = "https://img.shields.io/badge/pycodestyle-failed-red.svg" url_success = "https://img.shields.io/badge/pycodestyle-success-br...
StarcoderdataPython
3386419
from selenium.webdriver.common.by import By class ProductsPageLocator(object): IMG_BROKEN = (By.XPATH, '//img[contains(@src, "jpgWithGarbageOnItToBreakTheUrl")]') SHOPPING_CART_LABEL = (By.XPATH, '//div[@id="shopping_cart_container"]//span[contains(@class,"shopping_cart_badge")]') SHOPPING_CART_ITEM = (By.XPATH...
StarcoderdataPython
9780677
""" A one-time parser for dataset "B" containing information about French zones. """ import argparse import csv import os import xml.etree.ElementTree as et import fetch DATASET_B_URL = 'https://www.data.gouv.fr/fr/datasets/r/eeebe970-6e2b-47fc-b801-4a38d53fac0d' OUTPUT_HEADER = [ 'zone_id', 'zone_code', ...
StarcoderdataPython
12815406
<filename>rtmlparse/elements/readoutnoise.py from lxml import etree from .baseelement import BaseElement from .misc import auto_attr_check @auto_attr_check class ReadoutNoise(BaseElement): Base64Data = str Description = str Uri = str Value = float def __init__(self, parent, name=None, uid=None):...
StarcoderdataPython
1772014
<reponame>taojy123/PokemonCard # Generated by Django 2.1.4 on 2019-09-02 08:13 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ...
StarcoderdataPython
349237
<filename>render/DroneRender.py<gh_stars>10-100 import bpy from math import radians import sys import os import argparse import pyexcel def get_dataset(dataset): if dataset == 'suncg': return suncg.SunCG() if dataset == 'matterport3d': return matterport3d.Matterport3D() if dataset == 'st...
StarcoderdataPython
1925631
from .config import ConfigLoader
StarcoderdataPython
291019
import datetime from marshmallow import Schema, fields class DeadlineSchema(Schema): id = fields.Int(dump_only=True) name = fields.Str(required=True) date = fields.DateTime(required=True) status = fields.Str() class DeadlineUpdateSchema(Schema): name = fields.Str() date = fields.DateTime() ...
StarcoderdataPython
1602166
<filename>TCP_Connection/server.py ''' Assignment 2 Server for image classification Author: fanconic ''' import base64 from threading import Thread from queue import Queue from PIL import Image import socket, json from keras.preprocessing import image from keras.applications.resnet50 import ResNet50, preprocess_input,...
StarcoderdataPython
3417821
from django.test import TestCase from .preprocess import PreProcessor from django.conf import settings from .models import Build DATA_ROOT_DIRECTORY = settings.DATA_ROOT_DIRECTORY # Create your tests here. class PreprocessTestCase(TestCase): def setUp(self): self.processor = PreProcessor(data_root_direc...
StarcoderdataPython
236502
from distutils.core import setup from Cython.Build import cythonize from setuptools import Extension from os import path import numpy as np ext_package = 'boilerplate' cython = [Extension('utils', [path.join(ext_package, 'utils.pyx')], include_dirs=[np.get_include()]) ] setup(...
StarcoderdataPython
248669
<reponame>Matheus-Henrique-Burey/Curso-de-Python print('=-' * 15) print('CALCULADORA') print('=-' * 15) opcao = 0 num1 = int(input('Digite um numero: ')) num2 = int(input('Digite outro numero: ')) while not opcao == 5: print('-' * 30) print('''Qual operação voce deseja realizar: [ 1 ] SOMAR [ 2 ] MULT...
StarcoderdataPython
9642311
#!/usr/bin/python def outlierCleaner(predictions, ages, net_worths): """ Clean away the 10% of points that have the largest residual errors (difference between the prediction and the actual net worth). Return a list of tuples named cleaned_data where each tuple is of the ...
StarcoderdataPython
9664947
#!/usr/bin/python3 # ____ _ _ ____ _ _ _ # / ___|___ _ __ ___ _ __ ___ _ _ _ __ (_) |_ _ _ / ___|___ _ __ | |_ _ __ ___ | | | ___ _ __ # | | / _ \| '_ ` _ \| '_ ` _ \| | | | '_ \| | __| | | | | / _ \| '_ \| __| '__/ _ \| | |...
StarcoderdataPython
5023771
import uuid import pytest import requests from selenium.webdriver.common.action_chains import ActionChains from baselayer.app.env import load_env from skyportal.tests import api env, cfg = load_env() endpoint = cfg['app.sedm_endpoint'] sedm_isonline = requests.get(endpoint, timeout=5).status_code in [200, 400] def a...
StarcoderdataPython
3389384
<reponame>neelmraman/defopt from pathlib import Path import nox from nox import Session, session python_versions = ['3.5', '3.6', '3.7', '3.8', '3.9', '3.10'] nox.options.sessions = ['tests', 'docs'] nox.options.reuse_existing_virtualenvs = True @session(python=python_versions) @nox.parametrize('old', [False, True]...
StarcoderdataPython
3474237
import numpy as np from apvisitproc import apVisit2input as ap import os DATAPATH = os.path.dirname(__file__) KIC = 'testKIC' FITSFILEPATH = os.path.join(DATAPATH, 'apVisit-r5-7125-56557-285.fits') # One set of locID, mjd, and fiberID that exist in the test Visitlist locID = 5215 mjd = 55840 fiberID = 277 def test_l...
StarcoderdataPython
3495622
<reponame>0mza987/azureml-examples # description: deploy sklearn ridge model trained on diabetes data to AKS # imports import json import time import mlflow import mlflow.azureml import requests import pandas as pd from random import randint from pathlib import Path from azureml.core import Workspace from azureml.co...
StarcoderdataPython
68754
# -*- coding: utf-8 -*- # Copyright (c) 2020, Matgenix SRL, All rights reserved. # Distributed open source for academic and non-profit users. # Contact Matgenix for commercial usage. # See LICENSE file for details. """Module containing custodian validators for SISSO.""" import os from custodian.custodian import Vali...
StarcoderdataPython
1821064
<filename>build.py import logging import sys from mkdocs.config import load_config from mkdocs.commands import build if __name__ == "__main__": logging.basicConfig( stream=sys.stdout, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=0, ) build.build(load_config...
StarcoderdataPython
139621
<reponame>luigiberrettini/build-deploy-stats<gh_stars>1-10 #!/usr/bin/env python3 from dateutil import parser from statsSend.session import Session from statsSend.utils import print_exception from statsSend.urlBuilder import UrlBuilder from statsSend.teamCity.teamCityProject import TeamCityProject class TeamCityStat...
StarcoderdataPython
1795633
<gh_stars>10-100 #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ ------------------------------------------------- File Name:normalizedFunc Description : 实现几种常用的标准化函数 Email : <EMAIL> Date:2017/12/10 """ import numpy as np # min-max 标准化 # 按列 def min_max_normalized(data): """标准化 最大最小值标准化 ...
StarcoderdataPython
11201193
#coding: utf-8 from __future__ import absolute_import, division, print_function try: import numexpr except: pass import numpy as np import pyoperators as po from .core import ( BlockColumnOperator, CompositionOperator, ConstantOperator, DiagonalBase, IdentityOperator, MultiplicationOperator, Operator, R...
StarcoderdataPython
6638777
<filename>2016/10/part1.py<gh_stars>0 from pathlib import Path puzzle_input_raw = (Path(__file__).parent / "input.txt").read_text() import re from collections import defaultdict instructions = puzzle_input_raw.splitlines() GIVE_VALUE_PATTERN = re.compile(r"value (\d+) goes to bot (\d+)") BOT_GIVE_PATTERN = re.compi...
StarcoderdataPython
8090391
""" This module contains the tests for the automatic noise suppression extension. """ import numpy as np import pytest from spokestack import utils from spokestack.context import SpeechContext from spokestack.nsx.webrtc import AutomaticNoiseSuppression np.random.seed(42) def test_construction(): nsx = Automatic...
StarcoderdataPython
8138983
<filename>prod2vec_train.py import json import gensim from snowflake_client import SnowflakeClient def train_product_2_vec_model(sessions, min_c=2, size=48, window=3, iterations=20, ns_exponent=0.75): """ Wrap gensim standard word2vec model, providing sensible parameters from other experiments with prod2vec. ...
StarcoderdataPython
11234866
<gh_stars>10-100 from django.db import models from django.core.mail import send_mail from django.core.urlresolvers import reverse import os import urllib.parse import uuid # Create your models here. class Subscriber(models.Model): email = models.EmailField(max_length=254) active = models.BooleanField(default...
StarcoderdataPython
321631
import warnings from typing import Any import bs4 from django.utils.functional import cached_property from tate.legacy.finders import DocumentFinder, ImageFinder, PageFinder from tate.legacy.utils.classes import CommandBoundObject from wagtail.images import get_image_model Image = get_image_model() class BaseParser...
StarcoderdataPython
3424971
""" aio asynchronous (nonblocking) input output package """ from .wiring import WireLog
StarcoderdataPython
36257
<gh_stars>1-10 from cymepy.export_manager.base_definations import ExportManager from cymepy.common import EXPORT_FILENAME import json import os class Writer(ExportManager): def __init__(self, sim_instance, solver, options, logger, **kwargs): super(Writer, self).__init__(sim_instance, solver, options, logge...
StarcoderdataPython
6426909
""" 函数参数 实际参数 """ # 位置形参:实参必填 # 缺少实参 # TypeError: func01() missing 1 required positional argument: 'p3' # 实参过多 # TypeError: func01() takes 3 positional arguments but 4 were given def func01(p1, p2, p3): print(p1) print(p2) print(p3) # 默认形参:实参可选 # 必须从右向左依次存在 def func02(p1=0, p2="", p3=0.0): ...
StarcoderdataPython
6471070
import pytest import uuid from app.models.Connector import PrsConnectorCreate, PrsConnectorEntry from fastapi import HTTPException def test_connector_create(): data = PrsConnectorCreate() conn = PrsConnectorEntry(data=data) try: uuid.UUID(conn.id) except ValueError as ex: assert False, ...
StarcoderdataPython
3472988
from hexapod.models import VirtualHexapod from tests.kinematics_cases import case1, case2 from tests.helpers import assert_hexapod_points_equal CASES = [case1, case2] def assert_kinematics(case, assume_ground_targets): hexapod = VirtualHexapod(case.given_dimensions) hexapod.update(case.given_poses, assume_gr...
StarcoderdataPython
4965698
import plotly import pickle from src.plotting.pages.linkShare import figure_generator as fg # Case when user tried to access some incorrect shared link def test_incorrect_link_handling(): # Throw error if no or wrong object type returned assert isinstance(fg.make_graph(), plotly.graph_objs._figure.Figure) d...
StarcoderdataPython
6441984
<reponame>lixiaoy1/nova # Copyright 2012 Nebula, Inc. # Copyright 2013 IBM Corp. # # 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....
StarcoderdataPython
3406794
<filename>challenge_4/python/sarcodian/src/challenge_4.py """ Each root has two subtrees, each subtree may have a root Each tree has the format ['parent', ['child1', ['child1.1'],['child1.2']], ['child2', ['child2....
StarcoderdataPython