id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
3291949 | <gh_stars>0
from pprint import pprint
import cv2
import numpy as np
frame = cv2.imread("moments.png")
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
moments = cv2.moments(hsv[:, :, 2])
x = int(moments["m10"] / moments["m00"])
y = int(moments["m01"] / moments["m00"])
gray = hsv[:, :, 2]
edge = cv2.Canny(gray, 5, 70, 3... | StarcoderdataPython |
1781330 | <gh_stars>0
def uncollapse(digits):
| StarcoderdataPython |
130659 | <reponame>lichangao1826/SearchEngine<filename>spiders/spiders/pipelines.py<gh_stars>0
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
import pymongo
from pymongo.errors impo... | StarcoderdataPython |
1776179 | <filename>Learning.py
tree_height = input("How tall is the tree:")
tree_height= int(tree_height)
spaces = tree_height-1
hashes = 1
stump_spaces = tree_height-1
while tree_height != 0:
for i in range(spaces):
print(' ',end="")
for i in range(hashes):
print(' ',end="")
spaces -=1
hashes +=2
tree_height -... | StarcoderdataPython |
1754092 | #notas = [ 5.6, 7.3, 8.4, 2.5]
#soma = 0.0
def media(notas):
soma = 0.0
for nota in notas:
soma = soma + nota
# soma = sum(notas)
media = soma / len(notas)
return media
print(media([ 5.6, 7.3, 8.4, 2.5 ]))
print('A media do aluno é:', media([1,3,8,9,7]))
print('A media do aluno é: {:.2f}'.fo... | StarcoderdataPython |
181475 | <gh_stars>0
# coding: utf8
from __future__ import print_function
import os
import sys
import numpy as np
sys.path.append('../../matchzoo/inputs')
sys.path.append('../../matchzoo/utils')
from preprocess import *
def read_dict(infile):
word_dict = {}
for line in open(infile):
r = line.strip().split()
... | StarcoderdataPython |
126865 | <filename>main.py
from ac.pre import get_yaml
from ac.compare import compare
from v1.baidu import baidu
from v2.user import user
from v2.download import download
def v1():
print('搜索关键字:'+config['keyword']+'\n搜索页数:'+str(config['pages'])+'\n输出大于'+str(
config['sim_limit'])+'%的结果\n使用搜索引擎:'+config['site']+'\n-... | StarcoderdataPython |
38748 | import unittest
import sys
#sys.path.append('../')
from models.Individual import Individual
from models.Family import Family
from models.Gedcom import Gedcom
class TestSprint1(unittest.TestCase):
def setUp(self):
SUPPORT_TAGS = {"INDI", "NAME", "SEX", "BIRT", "DEAT", "FAMC", "FAMS", "FAM", "MARR", "HUSB... | StarcoderdataPython |
4813812 | <gh_stars>1-10
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | StarcoderdataPython |
1686036 | <reponame>djsilenceboy/LearnTest
'''
Preprocess HDB merged data.
Update log: (date / version / author : comments)
2020-06-27 / 1.0.0 / <NAME> : Creation
'''
from com.djs.learn.hdb import PreprocessData
__data_type = 0
__base_file_name = "HDB_Trans_M"
__input_file_path = "../../../../../Temp/{0}.csv".forma... | StarcoderdataPython |
1759255 | <reponame>henriktao/pulumi-azure
# 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, Sequenc... | StarcoderdataPython |
1654409 | <filename>tests/pe/test_hooking.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import lief
import unittest
import logging
import os
import sys
import stat
import re
import subprocess
import tempfile
import shutil
import time
import ctypes
from subprocess import Popen
from unittest import TestCase
from utils import... | StarcoderdataPython |
3248622 | <reponame>Hazardius/walki-botow<gh_stars>0
import botsBattles
import unittest
class BotsBattlesTestCase(unittest.TestCase):
def setUp(self):
botsBattles.app.config['TESTING'] = True
self.app = botsBattles.app.test_client()
def tearDown(self):
botsBattles.app.config['TESTING'] = False... | StarcoderdataPython |
1677112 | from .base import ( # noqa
activity_base,
assign_actor,
ImproperlyConfigured,
versioning_manager,
VersioningManager
)
from .expressions import jsonb_change_key_name # noqa
from .migrations import ( # noqa
add_column,
alter_column,
change_column_name,
remove_column,
rename_tabl... | StarcoderdataPython |
4807681 | import os
import sys
import threading
from time import sleep
N = int(sys.argv[1])
k=0
string = "mavproxy.py"
def Launch_SITL_instances(i):
os.chdir("/home/aniket/ardupilot/ArduCopter/")
os.system("sim_vehicle.py -I"+str(i)+" --out=127.0.0.1:"+ str(14552 + i*10) +" --sysid "+str(i+1)+" -L L"+str(i+1))
for i in ran... | StarcoderdataPython |
1751906 |
#Este tipo de tratamento de exceção não é boa prática
#
# try:
# print(a)
# except:
# print("Erro")
########################################################################################################################
#Tratamento adequado:
try:
print(a)
try:
a = 1/0
except:
pr... | StarcoderdataPython |
1750879 | <reponame>CruizK/imbotster<filename>bot/chatbot.py
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
from chatterbot.trainers import ChatterBotCorpusTrainer
from webscraper import get_response
import random
import ruamel.yaml
bot = ChatBot(
'Terminal',
storage_adapter='chatterbot.storage.SQL... | StarcoderdataPython |
144772 | from typing import Dict
from gopay.http import Request, Response, Browser
from gopay.enums import Language
import json
JSON = 'application/json'
FORM = 'application/x-www-form-urlencoded'
class GoPay:
def __init__(self, config: dict, browser: Browser) -> None:
self.browser = browser
self.config ... | StarcoderdataPython |
3379001 | <reponame>buxx/synergine<filename>tests/test/TestCycleCallback.py
from synergine.test.TestSimulation import TestSimulation as BaseTestSimulation
from tests.src.TestCollection import TestCollection
from tests.src.TestSimulation import TestSimulation as TestSimulationSimulation
from tests.src.TestCollectionConfiguration ... | StarcoderdataPython |
1740615 | <gh_stars>1-10
import datetime
import os
import shlex
import subprocess
from tests.utils import bake_in_temp_dir, inside_dir, run_inside_dir
def check_output_inside_dir(command, dirpath):
"Run a command from inside a given directory, returning the command output"
with inside_dir(dirpath):
return subp... | StarcoderdataPython |
178585 | <reponame>liufeng-elva/storage-test2
#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@file : argument.py
@Time : 2020/11/2 10:58
@Author: Tao.Xu
@Email : <EMAIL>
"""
import os
import argparse
from storagetest.tests.argument import case_dict_2_string, exclude_case, MntParser, \
load_tests_from_testcase
def tc_be... | StarcoderdataPython |
1672660 | from struct import pack, unpack, calcsize, error as StructError
from gzip import GzipFile
import zlib
from UserDict import DictMixin
import os, io
TAG_END = 0
TAG_BYTE = 1
TAG_SHORT = 2
TAG_INT = 3
TAG_LONG = 4
TAG_FLOAT = 5
TAG_DOUBLE = 6
TAG_BYTE_ARRAY = 7
TAG_STRING = 8
TAG_LIST = 9
TAG_COMPOUND = 1... | StarcoderdataPython |
177278 | <filename>testbed/testbed/scripts/ui.py
import ipywidgets as widgets
import utils
class Layout:
def __init__(self):
self.testcase = widgets.Text(description="Testcase")
self.input_data = widgets.Text(description="Input Data Type")
self.file_size = widgets.Text(description="File Size")
... | StarcoderdataPython |
181330 | # -*- coding: utf-8 -*-
from os import path
import pytest
import csdmpy as cp
COMMON_PATH = path.join("tests", "file_read", "test_files")
def file_testing(file_, error, error_type):
with pytest.raises(error_type, match=f".*{error}.*"):
cp.load(file_)
def test_01():
file_ = path.join(COMMON_PATH, ... | StarcoderdataPython |
81965 | <reponame>TunedMystic/flask-init<gh_stars>0
import logging
from logging.handlers import RotatingFileHandler
from flask import Flask, current_app
from . import settings
from .main import main
def create_app(settings_override=None):
# Create application.
app = Flask(
import_name=__name__,
sta... | StarcoderdataPython |
3320125 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('catalogue', '0001_initial'),
('voucher', '0001_initial'),
('basket', '0001_initial'),
('partner', '0001_initial'),
... | StarcoderdataPython |
3241916 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import PySimpleGUI as sg
#----------------------------Setup---------------------------------------------#
# Lets make our plots pretty, we are not hooligans.
CB91_Blue = '#2CBDFE'
CB91_Green = '#47DBCD'
CB91_Pink = '#F3A0F2'
CB... | StarcoderdataPython |
3352332 | <gh_stars>10-100
# This file was created automatically by SWIG 1.3.29.
# Don't modify this file, modify the SWIG interface instead.
import _splitimage4
import new
new_instancemethod = new.instancemethod
def _swig_setattr_nondynamic(self,class_type,name,value,static=1):
if (name == "thisown"): return self.this.own(... | StarcoderdataPython |
3246049 | <reponame>sudo-julia/devenv
# -*- coding: utf-8 -*-
from dvnv.dvnv import main, parse_args
def run_dvnv():
main(parse_args())
if __name__ == "__main__":
run_dvnv()
| StarcoderdataPython |
4830821 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from hidefield.fields import HideField
from django.utils.encoding import python_2_unicode_compatible
class HideCharField(HideField, models.CharField):
pass
class HideTextField(HideField, models.TextField):
pass
c... | StarcoderdataPython |
87318 | <gh_stars>0
from __future__ import absolute_import
import inspect
from django.utils.functional import empty, LazyObject
from sentry.utils import warnings
from .imports import import_string
def extract_lazy_object(lo):
"""
Unwrap a LazyObject and return the inner object. Whatever that may be.
ProTip: ... | StarcoderdataPython |
138971 | <reponame>ACea15/pyNastran
from .nastran_node import NastranNode | StarcoderdataPython |
1642330 | # Below is the class House. Create a method called paint that
# takes a color as an argument and paints the house that color
# (i.e modifies the attribute color with the value of the method
# argument).
# The method doesn't need to return any values or print any
# messages. You also do NOT need to take any input!
cla... | StarcoderdataPython |
3361940 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-04-14 15:11
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('contest', '0003_auto_20170406_1637'),
]
operations = [
migrations.AlterFiel... | StarcoderdataPython |
1676411 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Provile Envelop QC test
I believe that this test was first described by GTSPP, which define minimum
and maximum ranges for different depth layers. The concept is that near the
surface one should expect more variability, thus a ... | StarcoderdataPython |
173659 | """
Operative functions to be run into the SA_algorithm.
Creation of initial value, definition of 2-D movements and dedicated
domain boundaries conditions, optimization methods and stopping criteria
are listed below.
"""
import numpy as np
from numpy import random as rnd
#-------Neighbour generation----------#
de... | StarcoderdataPython |
192877 | class Solution(object):
def reverseBits(self, n):
"""
:type n: int
:rtype: int
"""
for i in xrange(16):
a = (n >> i) & 1
b = (n >> (31-i)) & 1
if a:
n |= 1 << (31-i)
else:
n &= ~(1 << (31-i))
... | StarcoderdataPython |
1690098 | <filename>celery_app.py
from _15thnight.queue import celery
| StarcoderdataPython |
3399025 | <filename>mods/mcpython/oredictnames.py
class OreDict:
ARMOR = "mcpython:oredict:armor"
ARMOR_HEAD = "mcpython:oredict:armor:head"
ARMOR_BODY = "mcpython:oredict:armor:body"
ARMOR_LEG = "mcpython:oredict:armor:leg"
ARMOR_FOOT = "mcpython:oredict:armor:foot"
TOOL_SHOVEL = "mcpython:oredict:tool:... | StarcoderdataPython |
1637509 | import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
def problem():
"""
Rotate Matrix: Given an image represented by an NxN matrix, where each pixel in the image is 4
bytes, write a method to rotate the image by 90 degrees. Can you do this in place?
"""
# Accord... | StarcoderdataPython |
43169 | import Image, ImageDraw, ImageFont
import md5, sha
import sys, time, os
import re
tileSize = (16,16)
outputWidth = 8
outputSpare = 1
scale = 2
pathIn = 'input/'
pathOut = 'output/'
animatedTiles = []
class Tile :
pixels = None
hash = None
number = None
image = None
def __init__ (self) :
self.pixels = {}
... | StarcoderdataPython |
1600935 | from clify.command import Command
class CurrentCommand(Command):
def __init__(self):
super().__init__('current', 'Display the current revision for the database')
def setup_arguments(self, parser):
pass
def setup(self, args):
return self.parent.setup(args)
def run(self, args)... | StarcoderdataPython |
4823577 | from setuptools import setup
setup(name='ip-noticer',
version='0.1',
description='The funniest joke in the world',
url='https://github.com/N00D13/ip-noticer',
author='<NAME>',
author_email='<EMAIL>',
license='MIT',
packages=['ipnoticer'],
scripts=['bin/ip-noticer'],
... | StarcoderdataPython |
4818400 | import toml
import os
import cv2
import numpy as np
dict_toml = toml.load(open('../config.toml'))
cascade_path = dict_toml["path"]["cascades"] + "/haarcascade_frontalface_default.xml"
image_path = dict_toml["path"]["dataset"]["image"]+"/img_align_celeba/"
output_path = os.getcwd()+"/image/"
print(output_... | StarcoderdataPython |
4807391 | #----------------------------------------------------------------------
# Copyright (c) 2010-2016 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and/or hardware specification (the "Work") to
# deal in the Work without restriction, including without limitation ... | StarcoderdataPython |
1697097 | <filename>train/utils.py
import numpy as np
# See https://github.com/keras-rl/keras-rl/blob/master/rl/memory.py
def zeros_like(a, dtype='float32'):
"""Return an array of zeros with same shape as given array.
Args:
a (array_like, iterable): An object with shape attribute or an iterable.
Returns:
... | StarcoderdataPython |
1763531 | #-*-coding:utf-8-*-
import torch
from collections import Counter
import numpy as np
import argparse
import pickle
import os
import time
from torchvision import transforms
from model import EncoderClothing, DecoderClothing
from darknet import Darknet
from PIL import Image
from util import *
import cv2
import pickle a... | StarcoderdataPython |
3259269 | <reponame>nuagenetworks/nuage-tempest-plugin
# Copyright 2013 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/... | StarcoderdataPython |
3394794 | <reponame>Jshulgach/desktop_arm_joy<filename>src/desktop_arm_teleop_joy_4-15-20.py<gh_stars>1-10
#!/usr/bin/env python
import rospy
from std_msgs.msg import UInt16, String
from sensor_msgs.msg import Joy
from math import atan2
import numpy as np
import time
class RobotArmControl(object):
def __init__(self):
self... | StarcoderdataPython |
113682 | <filename>htmltree/htmltree.py
# -*- coding: utf-8 -*-
# __pragma__('kwargs')
# __pragma__('xglobs')
# __pragma__('tconv')
# __pragma__('opov')
"""
Description: Provides a general html tree class, HtmlElement and wrapper
functions for most standard non-obsolete HTML tags.
This file is part of htmltree
https://github... | StarcoderdataPython |
1685502 | #Tests for registrations - Template, anat_straightened
from commands import getstatusoutput
from nibabel import load, Nifti1Image, save
# Inputs
ext = '.nii.gz'
prefix_ants = 'tmp_'
suffix_ants = '_reg2template'
template_path = '/home/django/gleveque/data/spinalcordtoolbox_dev__testing/data/template/'
template_file ... | StarcoderdataPython |
1783621 | '''
Created on Jul 6, 2020
@author: laurentmichel
'''
from pyvo.vomas.xml_interpreter.vocabulary import Att
class AttUtils(object):
"""
Some static methods doing tests on JSON mapping elements
"""
@staticmethod
def id_matches(element, searched_id):
"""
Returns True if ele... | StarcoderdataPython |
3222316 | <reponame>pontus/metadata-submitter<filename>tests/integration/run_tests.py
"""
Run integration tests against backend api endpoints.
Deleting from db is currently not supported, objects added to db in different
should be taken into account.
"""
import asyncio
import json
import logging
from pathlib import Path
import... | StarcoderdataPython |
142036 | <reponame>ThousandMileEye/Eye<filename>eyed/driver/bacnet/bacnetd.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from threading import Thread
from bacpypes.pdu import Address
from bacpypes.app import BIPSimpleApplication
from bacpypes.service.device import LocalDeviceObject
from bacpypes import core
from app import A... | StarcoderdataPython |
160121 | <reponame>RefalMachine/diachronic-wordnets
import json
import re
from abc import abstractmethod, ABC
from collections import Counter
from operator import itemgetter
import numpy as np
from gensim.models import KeyedVectors
from scipy import spatial
class Model(ABC):
def __init__(self, params):
... | StarcoderdataPython |
3338665 | import hardware.cozmo
def setup(robot_config):
hardware.cozmo.setup_coz(robot_config)
return
def say(*args):
message = args[0]
hardware.cozmo.say(message)
return | StarcoderdataPython |
84841 | import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
COLORS = {
'1 - New': '#00CD33', # (success green)
'2 - In Progress': '#7995D4', # (royal blue)
'3 - On Hold': '#FF9000', # (warning orange)
'4 - Awaiting Caller': '#FF9000', # (warning orange)
'5 - Await... | StarcoderdataPython |
3290833 | <reponame>jessemyers/pluscal
from dataclasses import dataclass
from typing import Iterable
from pluscal.ast.base import Label, Line
from pluscal.ast.statements.base import UnlabeledStmt
@dataclass(frozen=True)
class Goto(UnlabeledStmt):
"""
Goto ::= goto <Label> ;
"""
value: Label
def render(se... | StarcoderdataPython |
4842851 | #!/usr/bin/env python3
# https://leetcode.com/problems/count-numbers-with-unique-digits/
import unittest
class Solution:
def __count(self, prefix, n):
if len(prefix) == n:
return 1
summed = 1
digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
first = 1 if len(... | StarcoderdataPython |
3225190 | import pprint
from typing import Optional, List, Tuple, Set, Dict
import numpy as np
from overrides import overrides
from sklearn.impute import SimpleImputer
from sklearn.pipeline import make_pipeline
from python import SENTENCE_IDX
from python.handwritten_baseline import SENTENCE_EMBEDDINGS
from python.handwritten_b... | StarcoderdataPython |
3325967 | from django.test import TestCase
from django.test import SimpleTestCase
from django.test import Client
class HomePageViewTestCase(SimpleTestCase):
def setUp(self):
# Every test needs a client.
self.client = Client()
def test_request_home_page(self):
response = self.client.get('/')
... | StarcoderdataPython |
141161 | #!/usr/bin/env python
#
# Copyright 2013 CSIR Meraka HLT and Multilingual Speech Technologies (MuST) North-West University
#
# 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
#
# ht... | StarcoderdataPython |
1709702 | <filename>src/lockstep/lockstep_api.py
#
# Lockstep Software Development Kit for Python
#
# (c) 2021-2022 Lockstep, Inc.
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
#
# @author <NAME> <<EMAIL>>
# @copyright 2021-2022 Lockstep, Inc.
... | StarcoderdataPython |
191578 | <reponame>cabo40/pyrichlet<filename>pyrichlet/exceptions.py
class NotFittedError(Exception):
"""Exception to raise if class method must be called after fitting."""
| StarcoderdataPython |
3223440 | r"""
.. _ref_ex_advanced2:
Mesh Refinement
---------------
Perform a mesh refinement study.
In this example the convergence of the torsion constant is investigated through an analysis of an
I Section. The mesh is refined both by modifying the mesh size and by specifying the number of
points making up the root radius.... | StarcoderdataPython |
99934 | <reponame>amirmohammadkz/personality-detection
import numpy as np
import csv
import joblib
import pickle
import sys
import keras
from keras.layers import Input, concatenate, Dropout, Masking, Bidirectional, TimeDistributed
from keras.layers import Conv3D, MaxPooling3D, Dense, Activation, Reshape, GRU, SimpleRNN, LSTM
f... | StarcoderdataPython |
3241694 | <gh_stars>1-10
'''
This file is to remain in /bin so that the resources can be properly configured on init
'''
import os
import sys
import stat
from base_autoconfig import AutoConfig
def mimic():
# make the mimic script executable
mimic_path = os.path.join(os.getcwd(), 'mimic', 'mimic')
st = os.stat(mimi... | StarcoderdataPython |
3275685 | <filename>numerical_instability_example.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Illustrates numerical instability for similar function in Theano and PyTorch.
"""
import torch
import numpy as np
import theano
import theano.tensor as T
import os
from paths import *
torch.manual_seed(7)
def func_pyto... | StarcoderdataPython |
1723913 | from random import choice
aluno1 = input('Aluno 1: ')
aluno2 = input('Aluno 2: ')
aluno3 = input('Aluno 3: ')
aluno4 = input('Aluno 4: ')
lista = [aluno1, aluno2, aluno3, aluno4]
sorteado = choice(lista)
print(f'O aluno sorteado foi {sorteado}') | StarcoderdataPython |
17531 | <filename>practical_0/fibonacci.py
def fibonacci(n):
fibonacci = np.zeros(10, dtype=np.int32)
fibonacci_pow = np.zeros(10, dtype=np.int32)
fibonacci[0] = 0
fibonacci[1] = 1
for i in np.arange(2, 10):
fibonacci[i] = fibonacci[i - 1] + fibonacci[i - 2]
fibonacci[i] = int(fibonacci[i])
print(fibonacci)
for i in... | StarcoderdataPython |
3248887 | <reponame>IL2HorusTeam/il2fb-ds-events-parser
import datetime
import re
from typing import Optional
from il2fb.commons.actors import HumanAircraftActor
from il2fb.commons.spatial import Point3D
from il2fb.ds.events.definitions.takeoff import HumanAircraftTookOffEvent
from il2fb.ds.events.definitions.takeoff import H... | StarcoderdataPython |
1623116 | """
Copyright 2017-present, Airbnb Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, sof... | StarcoderdataPython |
1607499 | #!/usr/bin/env python3
from itertools import chain, cycle, accumulate # last of which is Python 3 only
import sys
def factors(n):
def prime_powers(n):
# c goes through 2, 3, 5, then the infinite (6n+1, 6n+5) series
for c in accumulate(chain([2, 1, 2], cycle([2,4]))):
if c*c > n: break
if n%c: continue
... | StarcoderdataPython |
3280726 | <reponame>VPetras/mobile-test-app
"""Common test support for all numpy test scripts.
This single module should provide all the common functionality for numpy tests
in a single location, so that test scripts can just import it and work right
away.
"""
# fake tester, android don't have unittest
class Tester(object):
... | StarcoderdataPython |
122324 | from flask import url_for
from app.catalog.domain.product import Product
from app.cart.domain.cart import Cart
from app.order.domain.order import Order
from app.order.domain.order_state import OrderState
from app.tests import utils
def test_place(db_session, client, loginned_user):
# Given
product = Produc... | StarcoderdataPython |
27075 | ALLOWED_HOSTS = ['testserver']
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:'
}
}
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOC... | StarcoderdataPython |
3349760 | <reponame>MarshallDu0204/qd-3dt
import numba
import numpy as np
from numpy.linalg import inv
import math
import cv2
import sklearn.metrics.pairwise as skp
from scipy.spatial.transform import Rotation as R
import torch
from shapely.geometry import Polygon
class AverageMeter(object):
"""Computes and stores the ave... | StarcoderdataPython |
4823213 | <gh_stars>1-10
#!/usr/bin/python
import os, sys
def _get_my_directory():
return os.path.dirname(__file__)
def _get_template_file_path(basename):
return os.path.join( _get_my_directory(), "../templates/%s.tpl" % basename)
def _create_target_directory(sections, basedir):
base_path = os.path.join( _fin... | StarcoderdataPython |
3275911 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='ComponentSPRequirement',
fields=[
('id', models... | StarcoderdataPython |
1612769 | import asyncio
import logging
import random
from json import load
from pathlib import Path
import discord
from discord.ext import commands
from bot.constants import Channels
from bot.constants import Colours
log = logging.getLogger(__name__)
class EasterFacts(commands.Cog):
"""
A cog contains a command th... | StarcoderdataPython |
146043 | <filename>chargify.py
try:
import simplejson as json
except ImportError:
try:
import json
except ImportError:
raise EnvironmentError("You must have a JSON module installed such as simplejson")
import urllib
import urllib2
import base64
# Define all exceptions
# Corresponds to HTTP response ... | StarcoderdataPython |
2286 | # Created on Sep 7, 2020
# author: <NAME>
# contact: <EMAIL>
import os
output_dir = os.path.curdir
def skinnytk2(R=1):
"""
This function generates the relations of Skinny-n-n for R rounds.
tk ================================================> TWEAKEY_P(tk) ===> ---
SB ... | StarcoderdataPython |
3222474 | from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
import scipy
import pandas as pd
import json
from .util import *
class Crop():
def __init__(self, key):
self.key = key
self.tau = {}
self.beta = {}
self.delta = {}
self.gamma = {}
self.leontief = {}
self... | StarcoderdataPython |
3244586 | #
# ARCADIA Mocks
#
# Copyright (C) 2017 SINTEF Digital
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the MIT license. See the LICENSE file for details.
#
from arcadiamock import __VERSION__, __SERVICE_NAME__, __LICENSE__
class Store(object):
def __init__(self, ... | StarcoderdataPython |
13822 | from django.shortcuts import render, HttpResponse
from django.views.generic.list import ListView
from django.views.generic.edit import UpdateView, DeleteView, CreateView
from . models import OuverTimeRecord
from django.contrib.auth.models import User
from django.urls import reverse_lazy
from django.views import View
im... | StarcoderdataPython |
1794670 | """Connect to a Samsung printer with SyncThru service."""
import asyncio
from enum import Enum
from typing import Any, Dict, Optional, cast
import aiohttp
import demjson3
from .htmlparsers import ENDPOINT_HTML_PARSERS
ENDPOINT_API = "/sws/app/information/home/home.json"
class ConnectionMode(Enum):
... | StarcoderdataPython |
3392052 | from flavio.physics.bdecays.formfactors.b_v import bsz, sse, cln, clnexp
from flavio.classes import AuxiliaryQuantity, Implementation
from flavio.config import config
processes_H2L = ['B->K*', 'B->rho', 'B->omega', 'Bs->phi', 'Bs->K*'] # heavy to light
processes_H2H = ['B->D*', ] # heavy to heavy
def ff_function(f... | StarcoderdataPython |
1736286 | <gh_stars>0
class gRPC_API_Client_Settings(object):
"""
Store connection settings for the client for use in other classes
and methods.
"""
def __init__(self, host, port, **kwargs):
self.host = host
self.port = port
self.bindings = kwargs['bindings']
s... | StarcoderdataPython |
4822295 | def min(a, b, c, d):
if a<=b and a<=c and a<=d:
return a
if b<=a and b<=c and b<=d:
return b
if c<=a and c<=b and c<=d:
return c
if d<=a and d<=b and d<=c:
return d
a,b,c,d = [int(i) for i in input().split()]
print(min(a,b,c,d)) | StarcoderdataPython |
28641 | <reponame>zhangyiming07/QT4C
# -*- coding: utf-8 -*-
#
# Tencent is pleased to support the open source community by making QT4C available.
# Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
# QT4C is licensed under the BSD 3-Clause License, except for the third-party components listed ... | StarcoderdataPython |
1714078 | import websockets
import queue
import time
import asyncio
import threading
import uuid
import logging
import json
class Timer:
def __init__(self, timeout, callback, *args, **kwargs):
self.timeout = timeout
self.callback = callback
self.args = args
self.kwargs = kwargs
self.... | StarcoderdataPython |
1716033 | <reponame>brayvasq/food-recognition<filename>backend/entrenamiento.py
import matplotlib.pyplot as plt
import numpy as np
import math
import cv2
## Import the keras API
from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.layers import InputLayer, Input
from tensorflow.python.keras... | StarcoderdataPython |
3217395 | <reponame>darkfeline/mir.orbis<filename>tests/conftest.py
# Copyright (C) 2017 <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
#
# Un... | StarcoderdataPython |
3386878 | <filename>symbtools/test/test_quick.py
# -*- coding: utf-8 -*-
"""
Created on Mo 2016-03-14
@author: <NAME>
This file contains just dummy tests to quickly test the test-infrastructure
"""
import unittest
import inspect, os, sys
if 'all' in sys.argv:
FLAG_all = True
else:
FLAG_all = False
# own decorator f... | StarcoderdataPython |
161963 | <reponame>kaslufl/api-flask-clientes
from flask import Flask
from flask_restful import Api
from resources.cliente import Cliente, Cliente_com_codigo
from flask_cors import CORS
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:123456@localhost/smartnx'
app.config['SQLALCHEMY_TRACK_MO... | StarcoderdataPython |
3282233 | <reponame>lee0210/sproxy
import struct
DATA_HEADER_FORMAT = '>ii'
VERSION = 1
def read_request(conn):
version, length = struct.unpack(DATA_HEADER_FORMAT, conn.recv(8))
DATA_FORMAT = '>%ss'%(str(length))
data, = struct.unpack(DATA_FORMAT,conn.recv(length))
return data.decode()
def write_request(conn,... | StarcoderdataPython |
1617731 | from distutils.core import setup
setup(
name="lrupy",
packages=['lrupy'],
version="0.4",
py_modules=['lrupy.lrupy'],
description="A simple in-memory (LRU) cache implementation",
author="<NAME>",
author_email="<EMAIL>",
url="https://github.com/abhinav-upadhyay/lrupy",
download_url="h... | StarcoderdataPython |
1792909 | #! /usr/bin/env python
__author__ = 'Tser'
__email__ = '<EMAIL>'
__project__ = 'jicaiauto'
__script__ = 'init_db.py'
__create_time__ = '2020/7/2 21:45'
from sqlite3 import connect
from jicaiauto.config.config import DBCONFIG
class DB(object):
def __init__(self):
self.conn = connect(DBCONFIG().dbpath)
... | StarcoderdataPython |
75458 | __all__ = [
'get_summary_mapping',
'generate_summaryxref_files',
'merge_oed_to_mapping',
'write_exposure_summary',
'write_summary_levels',
'write_mapping_file',
]
import io
import json
import os
import warnings
import pandas as pd
from ..utils.coverages import SUPPORTED_COVERAGE_TYPES
from ..... | StarcoderdataPython |
147990 | import sys
sys.path.append('..')
import argparse
from batchgenerators.utilities.file_and_folder_operations import *
from nnunet.training.model_restore import load_model_and_checkpoint_files
from fvcore.nn.flop_count import _DEFAULT_SUPPORTED_OPS, FlopCountAnalysis, flop_count
import numpy as np
import torch
import os
j... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.