id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
1771071 | import pytest
import mock
from datetime import datetime
from app.lib.room_list import RoomList
class TestRoomList():
def test_it_takes_a_list_of_rooms_as_an_argument(self):
rooms = ['Big One', 'Little One', 'Cardboard One']
room_list = RoomList(rooms)
assert room_list.rooms == rooms
@... | StarcoderdataPython |
173567 | from utilities import utils
from text_processing import text_normalizer
import pickle
import re
import os
import pickle
from time import time
from text_processing import abbreviations_resolver
class SearchEngineInsensitiveToSpelling:
def __init__(self, abbreviation_folder = "../model/abbreviations_dicts", loa... | StarcoderdataPython |
4841908 | <gh_stars>1-10
from setuptools import setup
setup(
name='kitsh',
version='0.1.0',
author='<NAME>',
packages=[
'kitsh'
],
package_data={'': ['static/*', 'templates/*']},
include_package_data=True,
zip_safe=False
)
| StarcoderdataPython |
3374401 | import struct
from abc import ABCMeta, abstractmethod
from typing import Tuple, Optional, List, Set, Union, NamedTuple, Deque
from bxcommon import constants
from bxcommon.messages.abstract_block_message import AbstractBlockMessage
from bxcommon.messages.bloxroute import compact_block_short_ids_serializer
from bxcommo... | StarcoderdataPython |
89312 | <reponame>toanquachp/dl_stock_prediction
from utils import plot_figures
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler, StandardScaler
from tensorflow.keras.layers import Input, LSTM, Flatten, ... | StarcoderdataPython |
1720488 | __author__ = '<NAME>'
import asyncio
import logging
import re
from datetime import datetime, date, timedelta
from ipaddress import IPv4Address, IPv6Address
from typing import Optional, Dict, Deque, Tuple, Any, cast
import simplejson
from geolite2 import maxminddb
from monetdblite.exceptions import DatabaseError
from... | StarcoderdataPython |
1657218 | # -*- coding: utf-8 -*-
def command():
return "start-component"
def init_argument(parser):
parser.add_argument("--component-no", required=True)
parser.add_argument("--instance-nos", required=True)
def execute(requester, args):
component_no = args.component_no
instance_nos = args.instance_nos
... | StarcoderdataPython |
1611053 | import pytest
from thefuck.types import Command
from thefuck.rules.brew_uninstall import get_new_command, match
@pytest.fixture
def output():
return ("Uninstalling /usr/local/Cellar/tbb/4.4-20160916... (118 files, 1.9M)\n"
"tbb 4.4-20160526, 4.4-20160722 are still installed.\n"
"Remove all... | StarcoderdataPython |
3253986 | # -*- coding: utf-8 -*-
from django.db import migrations, models
import django.core.validators
import django.contrib.auth.models
import django.utils.timezone
from django.conf import settings
import rich_editor.fields
import autoimagefield.fields
class Migration(migrations.Migration):
dependencies = [
('auth', '00... | StarcoderdataPython |
1645931 | # -*- coding: utf-8 -*-
"""
Adapters
--------
.. contents::
:backlinks: none
The :func:`authomatic.login` function needs access to functionality like
getting the **URL** of the handler where it is being called, getting the **request params** and **cookies** and
**writing the body**, **headers** and **sta... | StarcoderdataPython |
1752506 | <gh_stars>0
from __future__ import absolute_import
from .version import __version__
| StarcoderdataPython |
1609205 | <filename>swarmcg/scoring/__init__.py
from .angles import get_AA_angles_distrib, get_CG_angles_distrib
from .bonds import get_AA_bonds_distrib, get_CG_bonds_distrib
from .dihedrals import get_AA_dihedrals_distrib, get_CG_dihedrals_distrib
from .sasa import compute_SASA
from .rg import compute_Rg
from .distances import ... | StarcoderdataPython |
3370919 | import os
import pandas as pd
from typing import Any
from django.contrib.gis.geos import LineString, MultiLineString
def mission_planner_convert_log(url: str) -> list:
""" This function takes in a string url of the .waypoints, .txt or .json
file exported from the mission planner flight plan
... | StarcoderdataPython |
3326155 | from data.my_collection import cards as my_col
# from data.nastya_collection import cards as my_col
from dataobjects.collection import Collection
from dataobjects.mask import Mask
from dataobjects.deck import Deck
from dataobjects import constants
my_col_object = Collection()
my_col_object.cards = my_col
# m = Mask()... | StarcoderdataPython |
1683597 | <reponame>NaverCloudPlatform/ncloud-sdk-python
# coding: utf-8
"""
server
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class GetBlockStorageInstanceListRequest(object):
"""NOTE: This class is auto generated by the swagger c... | StarcoderdataPython |
1755572 | <filename>ast-transformations-core/src/test/resources/org/jetbrains/research/ml/ast/gumtree/tree/data/class/in_3.py<gh_stars>1-10
class A(object):
def __init__(self, arg):
self._arg = arg | StarcoderdataPython |
1604496 | <gh_stars>1-10
# -*- coding: utf-8 -*-
# Copyright 2010-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... | StarcoderdataPython |
188577 | <reponame>rogeriopaulos/finpy<gh_stars>0
import datetime as dt
import logging
import os
import urllib
from abc import ABC, abstractmethod
import telegram
from pymongo import MongoClient
from pymongo.errors import BulkWriteError, ConnectionFailure
from requests.exceptions import ConnectionError, Timeout, TooManyRedirec... | StarcoderdataPython |
182044 | <filename>chip8.py<gh_stars>0
# Python emulator for Chip-8
import random
MEMSIZE = 0x1000
REGSIZE = 0x10
CHIP8_STRT = 0x200
memory = bytearray(MEMSIZE)
V = bytearray(REGSIZE)
I = random
PC = CHIP8_STRT
Instr_H = 0x00
Instr_L = 0x00
def Ifetch(prog_cntr):
global Instr_H
global Instr_L
Instr_H = memory[p... | StarcoderdataPython |
181453 | <filename>operators.py
from functools import reduce
from math import factorial
import numpy as np
import scipy.sparse as sp
def differences(accuracy, order):
# Implemented based on the article here: http://web.media.mit.edu/~crtaylor/calculator.html
# By the properties of square Vandermonde matrices this mat... | StarcoderdataPython |
1620875 | import gym
import torch
import tensorboardX
from agents import TD3
import argparse
import os
import utils
import numpy as np
def main(args):
env = gym.make(args['env_name'])
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
action_dim = env.action_space.shape[0]
max_action = en... | StarcoderdataPython |
1696536 | <reponame>kfarrelly/nucleo
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime, dateutil.parser, parse, requests, stream, sys
from allauth.account.adapter import get_adapter
from allauth.account import views as allauth_account_views
from allauth.utils import build_absolute_uri
from django... | StarcoderdataPython |
3252542 | import ascii_chess
from ascii_chess.ascii_board import *
from ascii_chess.chess_rules import parse_square
def test_is_functional():
# TODO: include assertions
side = 10
board = ChessBoard(side, 0, 0.7)
print board
for p in ascii_pieces:
pp = ascii_pieces[p]
print pp
pri... | StarcoderdataPython |
4811446 | import re
from itertools import chain
import collections
import math
from nltk.translate.bleu_score import sentence_bleu, SmoothingFunction, ngrams, brevity_penalty
from collections import Counter
from fractions import Fraction
from .wer import *
import numpy as np
from rouge import Rouge
import logging
logging.basicCo... | StarcoderdataPython |
3380139 | <gh_stars>0
'''
https://leetcode.com/problems/palindrome-partitioning/
131. Palindrome Partitioning
Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s.
A palindrome string is a string that reads the same backward ... | StarcoderdataPython |
3382729 | from brownie import *
DEADLINE = 999999999999
def test_gas_refund(helper, accounts):
""" Test if a gas reduction is achieved by burning tokens """
tx = helper.burnBuyAndFree(1000000, 25, {'from': accounts[0], 'value': "1 ether"})
assert tx.gas_used < 700000
| StarcoderdataPython |
1792959 | from PIL import Image
def split1(im):
return [im]
def split2(im):
return [im]
def split3(im: Image):
return [
im.crop((0, 0, 128, 128)),
im.crop((0, 128, 128, 257)),
im.crop((128, 0, 257, 128))
]
def split4(im):
return [
im.crop((0, 0, 128, 128)),
im.c... | StarcoderdataPython |
3383603 | import logging
import faulthandler
import os
import sys
from client.ui import app
from client.data_manage import data_dir
def _redirect_streams():
logs_dir = data_dir.get_data_dir()
sys.stdout = open(os.path.join(logs_dir, 'app.log'), 'w')
sys.stderr = open(os.path.join(logs_dir, 'error.log'), 'w')
def... | StarcoderdataPython |
3353710 | <gh_stars>1-10
# =============================================================================
#
# EZID :: newsfeed.py
#
# Interface to the EZID RSS news feed.
#
# This module should be imported at server startup so that its daemon
# thread is started in advance of any UI page requests.
#
# Author:
# <NAME> <<EMAIL>>... | StarcoderdataPython |
4803854 | <gh_stars>0
"""
mmvt_cv.py
Define any type of collective variable (or milestone shape) that might
be used in an MMVT calculation.
"""
import seekr2.modules.common_base as base
import seekr2.modules.mmvt_base as mmvt_base
def make_mmvt_spherical_cv_object(spherical_cv_input, index):
"""
Create a SphericalCV ob... | StarcoderdataPython |
4820869 | import numpy as np
import cv2
from keras.models import Model, Sequential
from keras.layers import Input, Dense, Reshape, Flatten
from keras.layers.convolutional import Convolution2D, Conv2DTranspose
from keras.layers.normalization import BatchNormalization
from keras.layers.advanced_activations import LeakyReLU
from ke... | StarcoderdataPython |
1663397 | <gh_stars>1-10
import itertools
from collections import defaultdict
from noise_robust_cobras.noise_robust import find_cycles
from noise_robust_cobras.noise_robust.datastructures.cycle import Cycle
class CycleIndex:
"""
Cycle index is a class that keeps track of a set of cycles
Cycles are added th... | StarcoderdataPython |
9338 | <gh_stars>10-100
import re
from argparse import ArgumentParser
from multiprocessing import Pool, Manager, Process
from pathlib import Path
from .utils import UnityDocument
YAML_HEADER = '%YAML'
class UnityProjectTester:
"""
Class to run tests on a given Unity project folder
"""
AVAILABLE_COMMANDS = ... | StarcoderdataPython |
75188 | from array import array
import os
import numpy as np
import imageio
imageio.plugins.ffmpeg.download()
from moviepy.editor import *
import pygame
import sys
import uuid
import nltk
from nltk.corpus import PlaintextCorpusReader
import random
import librosa as lib
from matplotlib import pyplot as plt
import... | StarcoderdataPython |
54876 | import unittest
from django.core.exceptions import ValidationError
from petstagram.common.validators import MaxFileSizeInMbValidator
class FakeFile:
size = 5
class FakeImage:
file = FakeFile()
class MaxFileSizeInMbValidatorTests(unittest.TestCase):
def test_when_file_is_bigger__expect_to_raise(self):... | StarcoderdataPython |
3381991 | <reponame>astrobase/cli
import shutil
import typer
from astrobase_cli.schemas.command import Command
app = typer.Typer(help="Run preflight and status checks.")
@app.command()
def commands() -> None:
"""
Check that the cli can access certain commands in your PATH.
"""
message = ""
for command in... | StarcoderdataPython |
1658665 | <filename>feeds/migrations/0004_auto_20180802_0226.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-08-02 02:26
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('feeds', '0003_delete_hello'),
]
oper... | StarcoderdataPython |
3277946 | import time
end = input('Pick a number. ')
start_time = time.time()
allNums = []
for x in range(0, end+1):
allNums.append(x)
mid = 0
sum = 0
for x in allNums:
for y in str(x):
sum = sum + int(y)
print("The sum of all the digits of the numbers between 1 and {} is {}.".format(end, sum))
print("--- ... | StarcoderdataPython |
1692007 | <filename>examples/ptb/char_rnn.py
#!/usr/bin/env python
# ******************************************************************************
# 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 m... | StarcoderdataPython |
12238 | <filename>scripts/analysis_one.py
name = input('Enter file name: ')
lst=list()
lst2=list()
with open(name) as f:
for line in f:
#print(line)
blops=line.rstrip()
blop=blops.split()
#for val in blop:
my_lst = [float(val) for val in blop]#list_comprehension
for ... | StarcoderdataPython |
69767 | <reponame>ShAlireza/Yektanet
from .short_url_service import ShortenedURLService
__all__ = ('ShortenedURLService',)
| StarcoderdataPython |
3234909 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from datetime import timedelta
from eventbrite.compat import PY3
from eventbrite.models import EventbriteObject
from requests.structures import CaseInsensitiveDict
from .base import unittest, mock
class TestEventbriteObject(unitt... | StarcoderdataPython |
1700459 | """
This module extends and defines Torndo RequestHandlers.
Classes:
* MainHandler - this is the main RequestHandler subclass, that is mapped to
all URIs and serves as a dispatcher handler.
* DefaultHandler - this class serves all the URIs that are not defined
within ... | StarcoderdataPython |
172547 | #!/usr/bin/env python
from setuptools import setup
setup(
name='eve-arango',
version='0.3.3',
description='Eve ArangoDB data layer',
long_description=open('README.rst').read(),
author='<NAME>',
author_email='<EMAIL>',
url='https://github.com/tangram/eve-arango',
license='MIT',
pac... | StarcoderdataPython |
1617287 | <gh_stars>10-100
import os
import glob
import json
import shutil
from multiprocessing import Pool
import fire
import easyocr
import numpy as np
import torch
from PIL import Image
from skimage import transform
from skimage.feature import canny
from skimage.color import rgb2gray, gray2rgb
def multi_boxes_mask(image, ... | StarcoderdataPython |
1690844 | <filename>kusto-logging/tests/test_ql.py
"""Simulated testing without a Kusto cluster"""
import logging
import time
import threading
from queue import Queue
from logging.handlers import QueueHandler, QueueListener
import pytest
from azure.kusto.data import KustoConnectionStringBuilder
from azure.kusto.data.exceptions... | StarcoderdataPython |
28784 | from functools import reduce
data = []
with open("aoc6.inp") as rf:
sets = []
for l in rf:
if l == "\n":
data.append(sets)
sets = []
else:
sets.append(set([c for c in l.strip()]))
a1 = a2 = 0
for sets in data:
a1 += len(reduce(lambda s1, s2: s1 | s2, s... | StarcoderdataPython |
3347569 | # Copyright L.P.Klyne 2013
# Licenced under 3 clause BSD licence
# $Id: UPNPBrisa.py 3199 2009-06-15 15:21:25Z philipp.schuster $
#
# Class to interface with Brisa UPnP framework
#
# <NAME>
#
import logging, threading
from brisa.core.reactors import install_default_reactor
reactor = install_default_reactor()
fr... | StarcoderdataPython |
3293289 | """Mixin classes."""
from typing import Protocol
class Lockable(Protocol):
@property
def lock(self) -> Lock:
...
class AtomicCloseMixin:
def atomic_close(self: Lockable) -> int:
with self.lock:
# perform actions
...
class AtomicOpenMixin:
def atomic_open(se... | StarcoderdataPython |
1650765 | import backtrader as bt
import pandas as pd
import numpy as np
class NetTradeStrategy(bt.Strategy):
params=(('p1',12),('p2',26),('p3',9),)
def __init__(self):
self.order = None
#获取MACD柱
self.macdhist = bt.ind.MACDHisto(self.data,
period_me1=self.p.p1,
... | StarcoderdataPython |
11219 | """The devolo_home_control integration."""
from __future__ import annotations
import asyncio
from functools import partial
from types import MappingProxyType
from typing import Any
from devolo_home_control_api.exceptions.gateway import GatewayOfflineError
from devolo_home_control_api.homecontrol import HomeControl
fr... | StarcoderdataPython |
162054 | #!/usr/bin/env python3
from datetime import datetime
from html.parser import HTMLParser
from openpyxl import Workbook
import os
now = datetime.now()
current_time = now.strftime("%Y%m%d")
#with open("Logistics_133800_20200528.xls") as f: // use for testing
# add path to file
path = r'C:\Users\Username\Path\To\Logist... | StarcoderdataPython |
4840828 | # Generated by Django 3.1.7 on 2021-04-13 17:46
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... | StarcoderdataPython |
1600305 | <gh_stars>0
import numpy as np
from simplenn import Network
from simplenn.layer import Dense
from simplenn.activation import ReLu
from simplenn.activation import SoftMaxLoss
from simplenn.layer.dropout import Dropout
from simplenn.metrics.loss import CategoricalCrossEntropy
from simplenn.metrics import Accuracy
from ... | StarcoderdataPython |
172187 | from multiprocessing import Process, Queue, Lock
from Queue import Empty
from core.utilities import logging_handler_setup
class Device(object):
layout_type = "Layout"
def __init__(self):
# Output queue
self.out_queue = Queue()
# Input Queue
self.in_queue = Queue()
# M... | StarcoderdataPython |
1676451 | <reponame>sideroff/python-exercises
def get_input_prices():
input_text = input('Enter a price or "stop": ')
prices = []
while input_text != 'stop':
new_price = None
try:
new_price = float(input_text)
except:
print('Input could not be parsed. Please choose ano... | StarcoderdataPython |
3264996 | <reponame>levan92/detectron2<filename>projects/train_pp/config.py<gh_stars>1-10
# -*- coding = utf-8 -*-
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from detectron2.config import CfgNode as CN
def add_IN_config(cfg: CN):
"""
Add config for densepose head.
"""
_C = cfg
_... | StarcoderdataPython |
97044 | <gh_stars>0
"""SPADL schema for StatsBomb data."""
from typing import Optional
import pandera as pa
from pandera.typing import DateTime, Object, Series
from socceraction.data.schema import (
CompetitionSchema,
EventSchema,
GameSchema,
PlayerSchema,
TeamSchema,
)
class StatsBombCompetitionSchema(... | StarcoderdataPython |
1688791 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from .ensemble_trainer import EnsembleTrainer, EnsembleTrainer_Deprecated
from .hogwild_trainer import HogwildTrainer
from .trainer import TaskTrainer, Trainer, TrainingState
__all__ = [
"Trainer",
"TrainingState",
... | StarcoderdataPython |
1791705 | import wx
class AutoResizeTextCtrl(wx.TextCtrl):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.min_auto_width = self.get_width()
self.Bind(wx.EVT_KEY_UP, self.on_key_up)
self.add_width = 10
self.auto_resize()
def on_key_up(self, event):
... | StarcoderdataPython |
55610 | import plotly.graph_objects as go
large_rockwell_template = dict(
layout=go.Layout(title_font=dict(family="Rockwell", size=24))
)
fig = go.Figure()
fig.update_layout(title='Figure Title', template=large_rockwell_template)
fig.show()
| StarcoderdataPython |
3288618 | # Copyright (c) 2018 <NAME>.
# Cura is released under the terms of the LGPLv3 or higher.
from typing import Any
from UM.Qt.ListModel import ListModel
from PyQt5.QtCore import pyqtSlot, Qt
class SidebarCustomMenuItemsModel(ListModel):
name_role = Qt.UserRole + 1
actions_role = Qt.UserRole + 2
menu_item_r... | StarcoderdataPython |
92396 | <filename>api/api_fanfic.py
from django.conf import settings
from django.contrib.sites.shortcuts import get_current_site
from django.core.mail import BadHeaderError, send_mail
from rest_framework import permissions, views, status
from rest_framework.response import Response
from fanfics.models import Fanfic
class Sh... | StarcoderdataPython |
1795713 | from sqlalchemy import create_engine
import pandas as pd
import time
uri = f"mssql+pyodbc://AGR-DB17.sfso.no/AgrHam_PK01?driver=ODBC+Driver+17+for+SQL+Server"
engine = create_engine(uri)
| StarcoderdataPython |
1740874 | <filename>main.py
# std
import argparse
from argparse import Namespace, ArgumentParser
from pathlib import Path
from typing import Tuple
import uuid
from config.config import Config
from log import log
from scheduler_device import add_scheduler_job
def parse_arguments() -> Tuple[ArgumentParser, Namespace]:
parse... | StarcoderdataPython |
1751200 | x = int(input("digite um valor "))
def falar(palavra):
print(palavra + "!!")
def tossir():
falar("cough")
def espirrar():
falar("atchoo")
for i in range(x):
tossir()
espirrar()
| StarcoderdataPython |
3311383 | from rest_framework import serializers
from blog.models import Post, Tags
class TagsSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Tags
fields = ('name', )
class PostsSerializer(serializers.HyperlinkedModelSerializer):
tags = TagsSerializer(many=True, read_only=True... | StarcoderdataPython |
3304362 | # cmdline options
# Author: <NAME>
import sys
from .phase_snp import phase_snp
from .config import APP
def __usage(fp = sys.stderr):
msg = "\n"
msg += "Usage: %s <command> [options]\n" % APP
msg += "\n" \
"Commands:\n" ... | StarcoderdataPython |
141988 | import sys
def convert(f_in, f_out, f_features):
features = []
labels = []
for line in f_in.readlines():
words = line.strip().split(" ")
labels.append(int(round(float(words[0]))))
features.append(zip(xrange(1,len(words)+1), words[1:]))
indexes = map(lambda x: int(x)-1, f_features.readline().split())
... | StarcoderdataPython |
160713 | <reponame>denyingmxd/Torchssc
# encoding: utf-8
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from models.DDR import *
class SimpleRB(nn.Module):
def __init__(self, in_channel, norm_layer, bn_momentum):
super(SimpleRB, self).__init__()
self.path = nn.Seque... | StarcoderdataPython |
1623739 | <filename>Algorithms/A Number After a Double Reversal/solution.py
class Solution:
def isSameAfterReversals(self, num: int) -> bool:
return str(num) == str(num).rstrip("0") or num == 0
| StarcoderdataPython |
61612 | <gh_stars>10-100
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
import os
import sys
import socket
import logging
#logging.basicConfig()
# configure root logger
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
log_handler = logging.StreamHandler(stream=sys.stderr)
log_formatter = logging.Form... | StarcoderdataPython |
18288 | <gh_stars>0
import unittest
from selenium import webdriver
from tests import Base
class WebKitGTKDriverBenchmarkTest(Base.Base):
def getDriver(self):
return webdriver.WebKitGTK()
if __name__ == "__main__":
unittest.main()
| StarcoderdataPython |
73561 | import os, sys
import numpy as np
from math import sqrt
# testing without install
#sys.path.insert(0, '../build/lib.macosx-10.9-x86_64-3.8')
import poppunk_refine
# Original PopPUNK function (with some improvements)
def withinBoundary(dists, x_max, y_max, slope=2):
boundary_test = np.ones((dists.shape[0]))
fo... | StarcoderdataPython |
87819 | <reponame>Willsparker/FYP_EdgeDetection
import cv2
import os
import re
from math import hypot
import numpy as np
CurPath = os.path.dirname(__file__)
# Path to output txt file:
iris_pos_file = CurPath + '/PrintedImages/IrisPositions.txt'
image_dir = CurPath + '/PrintedImages/'
output_dir = CurPath + '/PrintedIris/'
#... | StarcoderdataPython |
1688131 | from math import ceil
budget = float(input())
students = int(input())
price_flour_package = float(input())
price_single_egg = float(input())
price_single_apron = float(input())
free_flour_packages = students // 5
price = price_single_apron * ceil(students * 1.2) + price_single_egg * 10 * students + price_flour_packa... | StarcoderdataPython |
157810 | <gh_stars>0
#===============================================
#RESOLUTION KEYWORDS
#===============================================
oref = 0 #over refine factor - should typically be set to 0
n_ref = 32 #when n_particles > n_ref, octree refines further
zoom_box_len = 100 #kpc; so the box will be +/- zoom_box_len from th... | StarcoderdataPython |
1630780 | import clr
clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager
doc = DocumentManager.Instance.CurrentDBDocument
clr.AddReference("RevitNodes")
import Revit
clr.ImportExtensions(Revit.Elements)
clr.Imp... | StarcoderdataPython |
3246603 | <reponame>karmanya007/pdf2audio
from io import StringIO
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfparser impor... | StarcoderdataPython |
10069 | """
Crack a password using a genetic algorithm!
"""
import random as rnd
def main():
"""
This file implements a genetic algorithm to solve the problem of
cracking a given password, by creating 'generations' of different
words, selecting the best, breeeding them, applying a simple crossover
(randomi... | StarcoderdataPython |
4816837 | <reponame>mcculloh213/alchemist-stack
from alchemist_stack.repository.models import Base
from sqlalchemy import Column, Integer, DateTime
class ExampleTable(Base):
__tablename__ = 'example'
primary_key = Column('id', Integer, primary_key=True)
timestamp = Column(DateTime(timezone=True), nullable=... | StarcoderdataPython |
1624297 | import shutil
import yaml
DEFAULT_FRONT_MATTER_END = u"\n...\n"
def loads(file_contents, front_matter_end=DEFAULT_FRONT_MATTER_END):
end = file_contents.find(front_matter_end)
if end == -1:
return (None, file_contents)
return (yaml.load(file_contents[:end]),
file_contents[end + len(... | StarcoderdataPython |
1796631 | <filename>globalpkg/mydb.py<gh_stars>0
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'laifuyu'
import configparser
import sys
import mysql.connector
from globalpkg.global_var import logger
class MyDB:
"""动作类,获取数据库连接,配置数据库IP,端口等信息,获取数据库连接"""
def __init__(self, config_file, db):
config = ... | StarcoderdataPython |
11012 | """Test module ``plot_profile/utils.py``."""
# Standard library
import logging
# First-party
from plot_profile.utils import count_to_log_level
def test_count_to_log_level():
assert count_to_log_level(0) == logging.ERROR
assert count_to_log_level(1) == logging.WARNING
assert count_to_log_level(2) == loggi... | StarcoderdataPython |
1640418 | <filename>bin/process_bigrams.py
# Intended to be used with count_2w.txt which has the following format:
# A B\tFREQENCY
# Sometimes "A" is "<S>" for start and "</S>" for end.
# Output is similar with all output lower-cased (including "<S>" and "</S>").
import collections
from src.data import data
all_results = colle... | StarcoderdataPython |
4816060 | <reponame>ev-agelos/acr-server
from django.shortcuts import render
from django.contrib.auth.models import User
from laptimes.models import Laptime
def index(request):
laptimes = Laptime.objects.order_by('-id')[:5]
return render(request, 'index.html', context=dict(laptimes=laptimes))
def drivers(request):
... | StarcoderdataPython |
131789 | <gh_stars>0
"""
.. module: lemur.destinations.service
:platform: Unix
:copyright: (c) 2018 by Netflix Inc., see AUTHORS for more
:license: Apache, see LICENSE for more details.
.. moduleauthor:: <NAME> <<EMAIL>>
"""
from sqlalchemy import func
from lemur import database
from lemur.models import certificate... | StarcoderdataPython |
4809585 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import pkg_resources
import cProfile
import os
import pyprof2html
def main():
"""Do the profiling work."""
from KOPy.targets import TargetList
filename = pkg_resources.resource_filename('KOPy.tests', 'data/big_starlist.txt')
profile = cProfile.Profile... | StarcoderdataPython |
1638696 | import errno
import os
import pickle
import unittest
import libtorrent as lt
ALL_CATEGORIES = (
lt.generic_category(),
lt.system_category(),
lt.libtorrent_category(),
lt.upnp_category(),
lt.http_category(),
lt.socks_category(),
lt.bdecode_category(),
lt.i2p_category(),
)
class ErrorC... | StarcoderdataPython |
135801 | <reponame>Pugavkomm/-test-multy_cognitive_tasks
from typing import Tuple
import numpy as np
def _compare_time(f_time, interval):
"""
Compares time with interval less than interval
Args:
f_time ([type]): [description]
interval ([type]): [description]
Returns:
[type]: [descrip... | StarcoderdataPython |
1754059 | <reponame>bmoretz/Mastering-Flask
"""initial migration
Revision ID: 462cbdc2765a
Revises:
Create Date: 2019-03-19 09:40:21.801310
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = None
branch_labels = None
depends_on = None
def upgrade(... | StarcoderdataPython |
4772 | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
"""
Calibration Controller
Performs calibration for hue, center of camera position, and servo offsets
"""
import os
import cv2
import time
import json
import argparse
import datetime
import numpy as np
import logging as log
from env import Moa... | StarcoderdataPython |
3205240 | <reponame>nissimergas/ipre
from time import sleep
from PyQt4 import QtGui
from PyQt4.QtCore import QTimer
from PyQt4.QtCore import QRect, QPropertyAnimation
import json
import requests
import subprocess
import os
class Robot:
def __init__(self,x,y,id,ventana):
self.x=((x-22)//37)
self.y=((y-146)... | StarcoderdataPython |
1750717 | # -*- coding: utf-8 -*-
"""
test.test_avps
~~~~~~~~~~~~~~
This module contains the Diameter protocol AVP unittests.
:copyright: (c) 2020 <NAME>.
:license: MIT, see LICENSE for more details.
"""
import unittest
import os
import sys
import datetime
testing_dir = os.path.dirname(os.path.abspath... | StarcoderdataPython |
33516 | from gurobipy import *
from itertools import combinations
from time import localtime, strftime, time
import config
from fibonew2 import (
AK2exp, InitMatNew, MatroidCompatible, Resol2m, bi, bs, disjoint, rankfinder,
ib, sb)
from timing import endlog, log
def CheckOneAK(mbases,gset,rnk):
'''
We check ... | StarcoderdataPython |
1751357 | """Test other aspects of the server implementation."""
import os
import socket
import unittest
from aiosmtpd.controller import Controller
from aiosmtpd.handlers import Sink
from aiosmtpd.smtp import SMTP as Server
from smtplib import SMTP
def in_wsl():
# WSL 1.0 somehow allows more than one listener on one port... | StarcoderdataPython |
1786122 | <reponame>Aetf/fathom<filename>fathom/deepq/database.py
from __future__ import absolute_import, print_function, division
import numpy as np
class database(object):
def __init__(self, params):
self.size = params['db_size']
self.img_scale = params['img_scale']
self.states = np.zeros([self.s... | StarcoderdataPython |
147586 | <filename>ionoscloud/api/nat_gateways_api.py
from __future__ import absolute_import
import re # noqa: F401
import six
from ionoscloud.api_client import ApiClient
from ionoscloud.exceptions import ( # noqa: F401
ApiTypeError,
ApiValueError
)
class NATGatewaysApi(object):
def __init__(self, api_client=... | StarcoderdataPython |
3354215 | import notification_method
import datetime
from database import *
def send_asap_notifications():
meeting = Meeting.get_or_none(Meeting.notified_asap==False)
while meeting:
batch = meeting.batch
notification_methods = list(meeting.group.notification_methods)
for method in notification_me... | StarcoderdataPython |
72257 | import logging
def setup_logging():
# Create root logger
logger = logging.getLogger('')
logger.setLevel(logging.DEBUG)
# Create stream handler
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# Create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.