id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
3327528 | ############################################################################
# Copyright 2017-2018 Intel Corporation
#
# 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.... | StarcoderdataPython |
3371982 | <filename>app/utils.py
import math
# from https://stackoverflow.com/questions/24727773/detecting-rectangle-collision-with-a-circle
def collision_rect_circle(rleft, rtop, width, height,
center_x, center_y, radius):
rright, rbottom = rleft + width, rtop + height
cleft, ctop = center_x-radius... | StarcoderdataPython |
1694415 | from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
handler404 = 'public_api_site.api.views.default'
urlpatterns = patterns('',
# Documentation says location vs locations - adding until it's figured out
# Judas (ston) 6... | StarcoderdataPython |
1765505 | <filename>starminder.py<gh_stars>10-100
#!/usr/bin/env python
"""Main Starminder script."""
from datetime import datetime
import random
from typing import Callable, Optional, Union
import boto3
from emoji import emojize
from github import Github
from github.AuthenticatedUser import AuthenticatedUser
from github.Re... | StarcoderdataPython |
2480 | <reponame>XiaoboLinlin/scattering
import itertools as it
import numpy as np
import mdtraj as md
from progressbar import ProgressBar
from scattering.utils.utils import get_dt
from scattering.utils.constants import get_form_factor
def compute_van_hove(trj, chunk_length, water=False,
r_range=(0, 1... | StarcoderdataPython |
121582 | """Clowder API
This module provides simple wrappers around the clowder Collections API
"""
import json
import logging
import requests
from pyclowder.utils import StatusMessage
def create_empty(connector, host, key, collectionname, description, parentid=None, spaceid=None):
"""Create a new collection in Clowder... | StarcoderdataPython |
56880 | <filename>prodigy.py
#!/usr/bin/python3
import re
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--input", metavar = "FILE", help = "Please enter the file (with extension) that you wish to parse", default = "orfs.fa")
parser.add_argument("-o", "--output", ... | StarcoderdataPython |
3231030 | <gh_stars>10-100
def a():
pass
# asdfasdf
def b():
pass
@dec1
@dec2
def a():
pass
# Foo
# Bar
def b():
pass
class Foo:
b = 0
def bar():
pass
def bar2():
pass
@decoratedclass
class Baz:
def zorp():
pass
def testing345():
pass
def b(n):
pass
... | StarcoderdataPython |
3382999 | # A constant to define how much folds should be used
N_FOLDS = 5
# A constant to define an epsilon value for avoiding division by zero
EPSILON = 1e-10
| StarcoderdataPython |
164294 | # 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 under the Apache License, Version 2.0 (the
# "License"); you may... | StarcoderdataPython |
3219413 | from cryptography.fernet import Fernet
key = b'<KEY>
input_file = 'test-criptato.txt'
output_file = 'test-decriptato.txt'
with open(input_file, 'rb') as f:
data = f.read()
fernet = Fernet(key)
encrypted = fernet.decrypt(data)
with open(output_file, 'wb') as f:
f.write(encrypted) | StarcoderdataPython |
1687361 | <filename>pub_data_visualization/production/load/entsoe/paths.py
"""
Folders where the raw production data provided by ENTSO-E
and the transformed dataframes are saved.
"""
import os
#
from .... import global_var
folder_production_entsoe_raw = os.path.join(global_var.path_public_data,
... | StarcoderdataPython |
4838373 | # Copyright (C) 2011 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the ... | StarcoderdataPython |
57076 | #
# -*- coding: utf-8 -*-
#
# Copyright (c) 2019 Intel Corporation
#
# 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 |
1654572 | """Tests for the views of the sprints app."""
from django.test import TestCase, RequestFactory # NOQA
from mock import MagicMock
from .. import views
class BacklogViewTestCase(object):
"""Tests for the ``BacklogView`` view class."""
longMessage = True
def setUp(self):
super(BacklogViewTestCase... | StarcoderdataPython |
3307494 | <filename>functions.py
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:light
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.9.1
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
fr... | StarcoderdataPython |
1760726 | <filename>run_realtime.py
import argparse
import logging
import matplotlib.pyplot as plt
import numpy as np
import torch.utils.data
from hardware.camera import RealSenseCamera
from hardware.device import get_device
from inference.post_process import post_process_output
from utils.data.camera_data import CameraData
fr... | StarcoderdataPython |
42330 | <filename>Algorithms_medium/0034. Find First and Last Position of Element in Sorted Array.py
"""
0034. Find First and Last Position of Element in Sorted Array
Medium
Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.
If target is not found in the ... | StarcoderdataPython |
3249654 | <gh_stars>0
from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated
class NormalUserViewSet(viewsets.ModelViewSet):
"""
A simple ViewSet for objects filtered by their 'owner' attribute.
To use it, at minimum you'll need to provide the `serializer_class` attribute and
... | StarcoderdataPython |
3265629 | from jno.commands.command import Command
from jno.commands.setdefault import SetDefault
from jno.commands.init import Init
from jno.commands.jnoserial import JnoSerial
from jno.commands.build import Build
from jno.commands.upload import Upload
from jno.commands.boards import Boards
from jno.commands.ports import Ports
... | StarcoderdataPython |
3369398 | import os
from scrapy.utils.misc import load_object
from scrapyd.config import Config
def get_application(config=None):
"""Overide default get_application in Scrapy."""
if config is None:
config = Config()
# Override http_port by $PORT environment variable in Heroku.
# Override bind_a... | StarcoderdataPython |
3241197 | <reponame>felixkam93/climateObservation
import requests
import json
import csv
import datetime
import logging
import sys
logging.basicConfig(filename='/home/pi/climate/climate.log',level=logging.DEBUG)
url = 'http://192.168.1.131:3000/api/climates'
ROOM_ID='581f6102c34ccfe0154577f7'
CSVFILE='/home/pi/climate/file.csv'... | StarcoderdataPython |
3368459 | <gh_stars>1-10
""" Aula - 022 - Módulos e Pacotes
"""
'''
Modularização:
-> Surgiu no início da década de 60.
-> Sistemas ficando cada vez maiores.
-> Foco: dividir um programa grande.
-> Foco: aumentar a legibilidade.
-> Foco: facilitar a manutenção.
'''
# Teoria:
'''
def fatorial(n)... | StarcoderdataPython |
82634 | <reponame>skandupmanyu/facet<gh_stars>0
import numpy as np
import pandas as pd
import pytest
from joblib import Parallel, delayed
from pandas.testing import assert_frame_equal
from facet.data import Sample
def test_sample_init(boston_df: pd.DataFrame, boston_target: str) -> None:
# check handling of various inva... | StarcoderdataPython |
38992 | # -*- coding: utf-8 -*-
"""Module where all interfaces, events and exceptions live."""
from . import _
from plone.app.vocabularies.catalog import CatalogSource
from plone.namedfile.field import NamedBlobImage
from plone.supermodel import model
from z3c.relationfield.schema import RelationChoice
from zope import schema... | StarcoderdataPython |
3367895 | from rest_framework import generics
from rest_framework import permissions
from permissions import IsOwnerOrReadOnly
from bilgecode.apps.passage_planner.models import Passage
from serializers import PassageSerializer
from django.contrib.auth.models import User
from serializers import UserSerializer
class PassageLi... | StarcoderdataPython |
3245195 | from skeleton import SkeletonClass
def main():
skeleton_class = SkeletonClass()
skeleton_class.greet()
if __name__ == "__main__":
main()
| StarcoderdataPython |
1757883 | my_name = 'Ryu'
print(my_name)
def print_name():
my_name = "Crystal"
print(f'Name is {my_name}')
print_name()
print(my_name)
def print_name_again():
global my_name
my_name = "yoshi"
print(f'Name is {my_name}')
print_name_again()
print(my_name) | StarcoderdataPython |
1668449 | <reponame>SousaPedro11/fail2ban-telegram
from flask import Flask
from flask_restful import Api
api = Api()
def create_app(config_name='config.Config'):
app = Flask(__name__)
app.config.from_object(config_name)
# Registra a Blueprint de HTTPAuth
from app.authorization import http_auth
app.regist... | StarcoderdataPython |
1678625 | from .transforms import *
from .readers import *
from .outputs import *
from .evaluations import *
| StarcoderdataPython |
1699075 | <reponame>Fenghuapiao/PyLeetcode<gh_stars>1-10
# The read4 API is already defined for you.
# @param buf, a list of characters
# @return an integer
# def read4(buf):
class Solution(object):
def read(self, buf, n):
"""
:type buf: Destination buffer (List[str])
:type n: Maximum number... | StarcoderdataPython |
3235831 | # Write a function named collatz() that has one parameter named number. If number is even, then collatz() should print number // 2 and return this value. If number is odd, then collatz() should print and return 3 * number + 1.
#
# Then write a program that lets the user type in an integer and that keeps calling collatz... | StarcoderdataPython |
49113 | <filename>setup.py
from setuptools import setup
setup(version='1.5')
| StarcoderdataPython |
4842819 | """
@author : <NAME>
@version : 1.0
"""
from django.db import models
class Class(models.Model):
code = models.CharField(max_length=10, unique=True)
title = models.CharField(max_length=150)
description = models.TextField(blank=True)
def __iter__(self):
return [self.code, self.title]
class... | StarcoderdataPython |
138645 | from PIL import Image
import pytesseract
import sys
from pdf2image import convert_from_path
import os
DATASET_DIR = "../../adil-dataset"
TXT_DIR = os.path.join(DATASET_DIR, "txt")
if os.path.exists(TXT_DIR):
print("Folder already exist")
else:
os.mkdir(TXT_DIR)
print("Txt folder created")
for filename in... | StarcoderdataPython |
3372186 | <reponame>JasXSL/ExiWoW-VH
# Used for MS & Config reading/writing
# Reads from screen and harddrive
from ctypes import windll, Structure, c_long, byref
import sys, os, json, subprocess, psutil, pyperclip
class vhWindows:
cursor = {"x":0,"y":0}
server = "vibhub.io"
deviceID = "TestDevice"
appName = "V... | StarcoderdataPython |
1633264 | <filename>server/analysis/tests/test_preprocessing.py
#
# OtterTune - test_preprocessing.py
#
# Copyright (c) 2017-18, Carnegie Mellon University Database Group
#
import unittest
import numpy as np
from analysis.preprocessing import DummyEncoder, consolidate_columnlabels
class TestDummyEncoder(unittest.TestCase):
... | StarcoderdataPython |
50309 | <reponame>mfomicheva/OpenNMT-tf
# -*- coding: utf-8 -*-
import os
import tensorflow as tf
from opennmt.utils import Vocab
from opennmt.tests import test_util
class VocabTest(tf.test.TestCase):
def testSimpleVocab(self):
vocab = Vocab()
self.assertEqual(0, vocab.size)
vocab.add("toto")
vocab.ad... | StarcoderdataPython |
1635346 | <gh_stars>10-100
from requests import get
from sys import argv as args
from threading import Thread
from time import sleep, time
def sendMessage(headers):
while True:
startTime = time()
try:
res = get('https://web.ewt360.com/customerApi/api/studyprod/lessonCenter/getUserTimeRanking', headers=headers, timeout=... | StarcoderdataPython |
3256545 | <filename>speechrecog/dashmain.py<gh_stars>0
from jesica4 import create_dashboard
from jesica4 import command_light
from jesica4 import command_SoundSystem
from jesica4 import command_Door
from jesica4 import command_detectsound
app = create_dashboard()
app.run_server(debug=False) | StarcoderdataPython |
1630691 | import io
import os
import re
import shutil
import unittest
from orderedattrdict import AttrDict
from nose.tools import ok_
from . import folder
from gramex import variables
from gramex.install import init, _ensure_remove
from shutilwhich import which
class TestInit(unittest.TestCase):
@classmethod
def setUp(... | StarcoderdataPython |
155188 | import cv2
import numpy as np
import pyzbar.pyzbar as pyzbar
from pyzbar.pyzbar import ZBarSymbol
import sqlite3
from sqlite3 import Error
import time
class TimeStamp:
def __init__(self, db = 'payroll.db'):
self.db = db
def scan_qr(self):
cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)... | StarcoderdataPython |
83343 | import jiwer
import jiwer.transforms as tr
from jiwer import compute_measures
from typing import List
def compute_wer(predictions=None, references=None, concatenate_texts=False):
if concatenate_texts:
return compute_measures(references, predictions)
else:
incorrect = 0
total = 0
... | StarcoderdataPython |
3296920 | import json
import os
import sys
import argparse
import numpy as np
import tensorflow as tf
import model, encoder
def score_tokens(*, hparams, tokens):
# tokens is 1d, but model expects a batch of token-lists, so make a batch of 1
x = tf.stack([tokens])
lm_output = model.model(hparams=hparams, X=x, past=... | StarcoderdataPython |
3235566 | <filename>machine-learning/ml-algos/linear_regression.py
#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
def abline(slope, intercept):
"""Plot a line from slope and intercept"""
axes = plt.gca()
x_vals = np.array(axes.get_xlim())
y_vals = intercept + slope * x_vals
plt.pl... | StarcoderdataPython |
1756048 | # coding=utf-8
# Copyright 2021 Pandora Media, LLC.
#
# 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... | StarcoderdataPython |
3213076 | <filename>01-Featurization/featurizeRMSD.py
### Featurization based on RMSD from the native state for the protein folding trajectories
### Required packages: mdtraj, numpy
### @<NAME>, <EMAIL>
import mdtraj as md
import numpy as np
# Read the list of MD trajectories to featurize
trajnames = [ line.rstrip() for line i... | StarcoderdataPython |
1733537 | import pandas as pd
from sklearn.linear_model import LogisticRegression
import pickle
if __name__ == '__main__':
# create df
train = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/titanic.csv') # change file path
# drop null values
train.dropna(inplace=True)
# features a... | StarcoderdataPython |
52438 | <gh_stars>0
"""
Given two binary strings a and b, return their sum as a binary string.
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
Constraints:
1 <= a.length, b.length <= 104
a and b consist only of '0' or '1' characters.
Each string does not cont... | StarcoderdataPython |
123718 | <reponame>zoek1/Birdwatching<filename>aave-server/app/scripts/get_contracts.py
import web3
import json
import os
network = os.getenv('NETWORK_URL')
address = os.getenv('ADDRESS_NETWORK', '0x9C6C63aA0cD4557d7aE6D9306C06C093A2e35408')
contract_path = os.getenv('CONTRACT_JSON_PATH')
abi = json.load(open(contract_path))
... | StarcoderdataPython |
24159 | import os
import shutil
import pychemia
import tempfile
import unittest
class MyTestCase(unittest.TestCase):
def test_incar(self):
"""
Test (pychemia.code.vasp) [INCAR parsing and writing] :
"""
print(os.getcwd())
iv = pychemia.code.vasp.read_incar('tests/data/vasp_0... | StarcoderdataPython |
3242560 | #!/usr/bin/env python
import roslib
roslib.load_manifest('lg_common')
import rospy
import urllib
import json
from urlparse import urlparse
from std_msgs.msg import String
from std_msgs.msg import Bool
from lg_common.srv import USCSMessage, USCSMessageResponse, InitialUSCS, InitialUSCSResponse
from interactivespaces_... | StarcoderdataPython |
3214001 | <filename>exec_date_aggs.py
'''
- This py script executes time aggregations for 1 year history of a data source, comprised of 12 separate tables.
- When combined with its corresponding string, it allowed for easy automation of many taks such as adding suffixes to new generated attributes.
- It also generates a log f... | StarcoderdataPython |
1623861 | <gh_stars>1-10
from typing import Union
from ansitable import ANSITable
from mathpad.val import Val
from mathpad.equation import Equation
def tabulate(*entities: Union[Val, Equation]):
"Prints a list of values or relations consistent with the display environment"
# TODO: latex version in supporting IPython e... | StarcoderdataPython |
3336201 | <reponame>ctralie/IsometryBlindTimeWarping<filename>CoverSongSync.py
import numpy as np
import matplotlib.pyplot as plt
import scipy.io as sio
import scipy.ndimage
import sys
import time
import pyrubberband as pyrb
from SlidingWindowVideoTDA.VideoTools import *
from Alignment.AlignmentTools import *
from Alignment.DTWG... | StarcoderdataPython |
3202352 | """
Download data from APIs
"""
from mimetypes import MimeTypes
from pathlib import Path
from typing import Iterator, Optional
from flask import Response, send_from_directory, stream_with_context
from werkzeug.utils import secure_filename
from restapi.config import DATA_PATH
from restapi.exceptions import NotFound
fr... | StarcoderdataPython |
1702125 | from a2ml.api.base_a2ml import BaseA2ML
from a2ml.api.utils.show_result import show_result
class A2MLExperiment(BaseA2ML):
"""Contains the experiment operations that interact with provider."""
def __init__(self, ctx, provider=None):
"""Initializes a new a2ml experiment.
Args:
ctx (... | StarcoderdataPython |
1613945 | <filename>src/services/rp/rp.py<gh_stars>1-10
#! /usr/bin/env python3
import ssl
import jinja2
import yaml
from flask.app import Flask
from flask.globals import request, current_app
from flask.json import jsonify
from flask.templating import render_template
from jwkest.jwk import keyrep
from oic.oic.message import Aut... | StarcoderdataPython |
136648 | import os
os.system('xdg-open https://www.instagram.com/shubhamg0sai')
| StarcoderdataPython |
160662 | # [351] Android Unlock Patterns
# Description
# Given an Android 3x3 key lock screen and two integers m and n, where 1 <= m <= n <= 9,
# count the total number of unlock patterns of the Android lock screen, which consist
# of minimum of m keys and maximum n keys.
# Rules for a valid pattern:
# 1) Each pattern must ... | StarcoderdataPython |
1602164 | <gh_stars>0
registro = []
pessoa = []
notas = []
while True:
nome = str(input('Nome: ')).capitalize().strip()
pessoa.append(nome)
n1 = float(input('Nota 1: '))
notas.append(n1)
n2 = float(input('Nota 2: '))
notas.append(n2)
pessoa.append(notas[:])
notas.clear()
me... | StarcoderdataPython |
4804053 | from modpy.optimize._constraints import Constraints, Bounds, LinearConstraint, NonlinearConstraint, prepare_bounds
from modpy.optimize._root_scalar import bisection_scalar, secant_scalar, newton_scalar
from modpy.optimize._lsq import lsq_linear
from modpy.optimize._nl_lsq import least_squares
from modpy.optimize._l... | StarcoderdataPython |
3398875 | <filename>mobile/mobile_app/admin.py
from django.contrib import admin
from .models import TwoFactor
admin.site.register(TwoFactor) | StarcoderdataPython |
89616 | <gh_stars>0
from .dataset import LRWDataset
from .dataset_lrw1000 import LRW1000_Dataset
from .dataset import AVDataset
from .cvtransforms import * | StarcoderdataPython |
1791780 | <reponame>qqsuhao/object-detection-GUI-QT
# -*- coding:utf8 -*-
# @TIME : 2021/12/17 17:03
# @Author : <NAME>
# @File : test.py
import random
import math
import time
import threading
from PyQt5.QtChart import (QAreaSeries, QBarSet, QChart, QChartView,
QLineSeries, QPieSeries, QSca... | StarcoderdataPython |
1745091 | <reponame>rcmckee/BPT
from torch.utils.data import Dataset
from scipy.sparse import coo_matrix
from torchtext import datasets
from .base import GraphBatcher, Batch
import numpy as np
import torch as th
import dgl
def get_nli_dataset(name='snli'):
if name == 'snli':
return datasets.SNLI
elif name == 'm... | StarcoderdataPython |
3377248 | """.. include:: README.md"""
from .abstract_action_space import AbstractActionSpace
from .composite import Composite
from .grid import Grid
from .vertical_grid import VerticalGrid
from .horizontal_grid import HorizontalGrid
from .joystick import Joystick
from .set_position import SetPosition
| StarcoderdataPython |
3329822 | <filename>web_logic/enums.py
import enum
class publicationStatus(enum.Enum):
Submited = "s"
Accepted = "a"
Published = "p"
class studentTypes(enum.Enum):
FirstDegree = "b"
SecondDegreeProject = "mp"
SecondDegreeThesis = "mt"
ThirdDegree = "p"
class buttonTypes(enum.Enum):
Download ... | StarcoderdataPython |
90919 | <gh_stars>0
from django.shortcuts import render
from rest_framework import generics, authentication, permissions
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.settings import api_settings
from users.serializers import UserSerializer
class CreateuserView(generics.CreateAPIView):
'... | StarcoderdataPython |
1611408 | <filename>tests/i18n/urls.py
from django.conf.urls.i18n import i18n_patterns
from django.http import HttpResponse, StreamingHttpResponse
from django.urls import path
from django.utils.translation import gettext_lazy as _
urlpatterns = i18n_patterns(
path('simple/', lambda r: HttpResponse()),
path('streaming/',... | StarcoderdataPython |
187345 | <reponame>samuelstanton/lambo
import hydra
import wandb
import pandas as pd
import time
import numpy as np
import torch
import random
from torch.nn import functional as F
from pymoo.factory import get_performance_indicator
from botorch.utils.multi_objective import infer_reference_point
from lambo.models.mlm import ... | StarcoderdataPython |
160863 | <filename>operations/sgRNAProcessing/UpdateGroupReferences.py
#!/bin/env python
# Take a set of sgRNA_Groups and attempt to map them
# to better references
import sys, string, argparse
import MySQLdb
import Config
import Database
from classes import Lookups
with Database.db as cursor :
cursor.execute( "SELECT sgr... | StarcoderdataPython |
1722174 | <filename>lists/remove_even_numbers.py
#!/bin/env python3
# Path: python-dynamic-programming/lists/remove_even_numbers.py
# Create a funtion to remove even numbers from a list
'''
step 1: Define a function that takes a list as an argument
step 2: Create a new list
step 3: Iterate through the list
step 4: Filter - If ... | StarcoderdataPython |
75665 | from __future__ import absolute_import
from __future__ import print_function
from pysnptools.util.mapreduce1.runner import *
import logging
import fastlmm.pyplink.plink as plink
import pysnptools.util as pstutil
import pysnptools.util.pheno as pstpheno
import numpy as np
from fastlmm.inference import LMM
import scipy.s... | StarcoderdataPython |
119631 | # Задача 2. Вариант 34
# Напишите программу, которая будет выводить на экран наиболее понравившееся
# вам высказывание, автором которого является Платон. Не забудьте о том,
# что автор должен быть упомянут на отдельной строке.
# <NAME>.
# 31.03.2016
print ('\nНикто не знает, что такое смерть и не есть ли она велич... | StarcoderdataPython |
1626174 | <gh_stars>0
from .plugin import Include
| StarcoderdataPython |
104976 | from domain.entities.value_objects.cashback import Cashback
| StarcoderdataPython |
1712548 | <filename>batchflow/tests/research_test.py
""" Tests for Research and correspong classes. """
# pylint: disable=no-name-in-module, missing-docstring, redefined-outer-name
import os
from contextlib import ExitStack as does_not_raise
import pytest
import numpy as np
from batchflow import Dataset, Pipeline, B, V, C
from... | StarcoderdataPython |
3329345 | def solution(x, y, d):
if y < x or d <= 0:
raise Exception("Invalid argument")
if (y - x) % d ==0:
return (y - x) // d
else:
return (y - x) // d + 1
print(solution(10, 85, 30))
print(solution(10, 10, 2))
# print(solution(10, 5, 30))
# print(solution(10, 85, -30))
| StarcoderdataPython |
1759627 | from Products.validation import validation as validationService
from bika.lims.testing import BIKA_FUNCTIONAL_TESTING
from bika.lims.tests.base import BikaFunctionalTestCase
from plone.app.testing import login
from plone.app.testing import TEST_USER_NAME
import unittest
class Tests(BikaFunctionalTestCase):
layer... | StarcoderdataPython |
1616839 | # Generated by Django 2.2.9 on 2020-01-01 20:51
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('datasets', '0015_profileindicator_label'),
]
operations = [
migrations.AddField(
model_name='pr... | StarcoderdataPython |
3321853 | import fractions
#Software by francote
print("Triangulacion de matrices 3x3")
def main():
print("A B C")
print("D E F")
print("G H I")
A = int(input("Valor de A : "))
B = int(input("Valor de B : "))
C = int(input("Valor de C : "))
D = int(input("Valor de D : "))
E = int(input("Valor d... | StarcoderdataPython |
4816759 | <reponame>luerhard/edge_gravity
"Docstring yay"
__version__ = "0.0.3" | StarcoderdataPython |
41717 | import numpy as np
def bowl(vs, v_ref=1.0, scale=.1):
def normal(v, loc, scale):
return 1 / np.sqrt(2 * np.pi * scale**2) * np.exp( - 0.5 * np.square(v - loc) / scale**2 )
def _bowl(v):
if np.abs(v-v_ref) > 0.05:
return 2 * np.abs(v-v_ref) - 0.095
else:
return ... | StarcoderdataPython |
91854 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 5 12:38:45 2017
@author: abench
"""
import cv2
camera_num=0
camera=cv2.VideoCapture(camera_num)
fourcc=cv2.VideoWriter_fourcc(*'XVID')
out=cv2.VideoWriter('output.avi',fourcc,20.0,(640,480))
while(camera.isOpened()):
ret,frame=camera.read()
if ret==True:
... | StarcoderdataPython |
1635195 | <filename>backend/db/base/schemas.py
from pydantic import BaseModel
from tortoise.contrib.pydantic import PydanticModel, pydantic_model_creator
from db.base.models import File
from config import DOMAIN_BACKEND
class Status(BaseModel):
message: str
class GetFile(PydanticModel):
id: int
url: str = None
... | StarcoderdataPython |
3236407 | from selenium import webdriver
import time
import requests
# 这个地方是通过观察html代码得到的,因为我先前通过find方法定位switch始终提示我没有这个元素,那么我就猜想它肯定是被隐藏或者嵌套在别的
# frame中了
login_url = 'http://xui.ptlogin2.qq.com/cgi-bin/xlogin?proxy_url=http%3A//qzs.qq.com/qzone/v6/portal/proxy.html' \
'&daid=5&&hide_title_bar=1&low_login=0&qlogin_au... | StarcoderdataPython |
1760586 | <filename>2015/04/p1.py
import hashlib
puzzle_input = b"iwrupvqb"
number = 100000
while True:
key = puzzle_input + str(number).encode()
if hashlib.md5(key).hexdigest()[:5] == "00000":
break
number += 1
print(number)
# Runs way faster than I expected, lol
| StarcoderdataPython |
3385433 | import cv2
import numpy as np
img=cv2.imread("kare2.jpeg") # benim şeklim içerdeki kareleri neden bulmuyor, kare3 ün yamukluğunu düzelt(araştırma), en büyük kareyi bul(alandan yola çık(h*w))
frame=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(frame, (7, 7), 2)
edge = cv2.Canny(blur, 0, 50, 3)
contour... | StarcoderdataPython |
1600265 | <filename>LaGou/config.py
MONGO_URL = 'localhost'
# 数据库名
MONGO_DB = 'lagou'
# 表名
MONGO_TABLE = 'Python'
# 拉勾网用户名和密码
USERNAME = '123'
PASSWORD = '<PASSWORD>' | StarcoderdataPython |
35991 | <filename>scripts/rpc/cmd_parser.py<gh_stars>1000+
args_global = ['server_addr', 'port', 'timeout', 'verbose', 'dry_run', 'conn_retries',
'is_server', 'rpc_plugin', 'called_rpc_name', 'func', 'client']
def strip_globals(kwargs):
for arg in args_global:
kwargs.pop(arg, None)
def remove_nul... | StarcoderdataPython |
1674432 | <reponame>ChaosCodes/beta-recsys
"""isort:skip_file."""
import argparse
import os
import sys
sys.path.append("../")
from torch.utils.data import DataLoader
from tqdm import tqdm
from beta_rec.core.eval_engine import SeqEvalEngine
from beta_rec.core.train_engine import TrainEngine
from beta_rec.datasets.seq_data_util... | StarcoderdataPython |
26505 | version = "2018-04-26" | StarcoderdataPython |
1705139 | """rnnt is a python package for RNN-Transduction loss support in TensorFlow==2.0
This loss function is well described here - https://arxiv.org/pdf/1211.3711.pdf
"""
from .rnnt import (
rnnt_loss,
)
| StarcoderdataPython |
1730756 | <reponame>JoseArtur/phyton-exercices<filename>PyUdemy/Day3/PizzaOrder.py
print("Welcome to Python Pizza Deliveries!!")
size = input("What size pizza do you want? S, M or L\n").upper()
add_pepperoni = input("Do you want pepperoni? Y or N\n").upper()
extra_cheese = input("Do you want extra cheese? Y or N\n").upper()
bill... | StarcoderdataPython |
3345188 | <reponame>yoki31/aiopyarr<filename>example.py
"""Example usage of aiopyarr."""
import asyncio
from aiopyarr.models.host_configuration import PyArrHostConfiguration
from aiopyarr.radarr_client import RadarrClient
IP = "192.168.100.3"
TOKEN = "xxxxxxxxxxxxxxxx<PASSWORD>"
async def async_example():
"""Example usage... | StarcoderdataPython |
3384956 | """
glglobs are almagamated lists, useful for drawing comparisons between lists.
renamed to glglob as it clashes with a matplotlib and python module name
"""
import sys, os, csv, string, math, numpy, pickle
from numpy import array, zeros, object_, arange
from copy import deepcopy
from operator import itemgetter
fr... | StarcoderdataPython |
3316364 | """
Visualization functions for different classifiers.
Contains plots for decision boundaries.
"""
import numpy as np
import scipy.stats as st
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
def plotc(parameters, ax=[], color='k', gridsize=(101, 101)):
"""
Plot a linear classifier... | StarcoderdataPython |
108110 | """Test Service EHA client"""
# -*- coding: utf-8 -*-
import pytest
import allure
@pytest.fixture()
def maket3_test_5_con1(test_server_5_1, check_side_mea809, data_maket_mea809, ):
return test_server_5_1(data_maket_mea809, data_maket_mea809["server_port1"], "test_5")
@allure.step("Test connect_from EHA_port... | StarcoderdataPython |
3240627 | <reponame>braemt/attentive-multi-task-deep-reinforcement-learning<gh_stars>10-100
# Copyright 2017 the pycolab 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
#
# https://www.apac... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.