id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
1784225
<filename>asyncgTTS/_decos.py<gh_stars>1-10 from __future__ import annotations from functools import wraps from typing import TYPE_CHECKING, Any, Callable, cast from .errors import NoInitialisedSession if TYPE_CHECKING: from typing import TypeVar from typing_extensions import ParamSpec _R = TypeVar("_R...
StarcoderdataPython
1616096
# coding: utf-8 from django.contrib import admin from .models import TarotJoueur, TarotPartie, TarotParticipant, TarotJeu from django.utils.safestring import mark_safe from . import forms class TarotJoueurAdmin(admin.ModelAdmin): list_display = ('owner', 'pseudo', 'email') list_filter = ('owner',) # search...
StarcoderdataPython
3218275
<filename>reviewboard/webapi/tests/test_server_info.py from __future__ import unicode_literals from django.utils import six from reviewboard.webapi.resources import resources from reviewboard.webapi.tests.base import BaseWebAPITestCase from reviewboard.webapi.tests.mimetypes import server_info_mimetype from reviewboa...
StarcoderdataPython
4835174
# number = None # while (not number) or not (number > 0): # try_number = input("Please enter a number > 0: ") # try: # number = float(try_number) # print("Got it!") # except ValueError as err: # print("Error: ", err) # try: # file_handle = open("my_file") # except IOError as err...
StarcoderdataPython
1744336
<gh_stars>0 # -*- coding: utf-8 -*- import urllib import urllib2 import json import os import collections import xml.etree.ElementTree as ET url = u'http://thetvdb.com/api' api_key = u'<KEY>' # GetSeries.php?seriesname=<seriesname> # GetSeriesByRemoteID.php?imdbid=<imdbid> def search(term): data = dict(seriesna...
StarcoderdataPython
3355003
# coding=utf-8 """Annotations parsing feature tests.""" from typing import Dict import pytest from pytest_bdd import given, scenario, then, when from yummy_cereal import AnnotationsParser from ..models.menus.course import Course from ..models.menus.dish import Dish from ..models.menus.menu import Menu @pytest.fixt...
StarcoderdataPython
3391672
<gh_stars>0 from __future__ import unicode_literals import django from django.conf import settings from django.core.management import call_command def main(): # Dynamically configure the Django settings with the minimum necessary to # get Django running tests settings.configure( MIDDLEWARE=( ...
StarcoderdataPython
1724503
<reponame>choonho/identity import logging from google.protobuf.json_format import MessageToDict from spaceone.core import pygrpc from spaceone.core.connector import BaseConnector from spaceone.core.utils import parse_endpoint from spaceone.identity.error.error_authentication import * _LOGGER = logging.getLogger(__na...
StarcoderdataPython
1788482
<gh_stars>0 import math import numpy as nx from pylab import linspace import PQmath from numpy.random import normal if __name__=='__main__': if 0: P = nx.array( [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], [1, 2.1, 3.01, 4, 5, 6]] ) P.transpose() else: ...
StarcoderdataPython
3339435
<gh_stars>100-1000 from unittest_reinvent.running_modes.lib_invent_tests.logger_tests import * from unittest_reinvent.running_modes.lib_invent_tests.reinforcement_learning_tests import * from unittest_reinvent.running_modes.lib_invent_tests.scoring_strategy_tests import * from unittest_reinvent.running_modes.lib_invent...
StarcoderdataPython
1643635
<filename>AdventOfCode2020/solutions/day01/puzzle1.py #!/usr/bin/env python3 from itertools import combinations tab = [] with open("input", 'r', encoding="utf8") as input: for number in input: number = number[:-1] tab.append(int(number)) # part 1 comb_list = (list(combinations(tab, r=2))) for i ...
StarcoderdataPython
1603088
<filename>pe0001.py def pe0001(upto): total = 0 for i in range(upto): if i % 3 == 0 or i % 5 == 0: total += i return total print(pe0001(1000))
StarcoderdataPython
1605057
import abc import nakama.client import nakama.config import nakama.types class BaseApi(abc.ABC): def __init__( self, http_client: nakama.client.HttpClient, nakama_config: nakama.config.NakamaConfig ): self.http_client = http_client self.nakama_config = nakama_config class AccountApi...
StarcoderdataPython
44681
<gh_stars>0 from django.contrib import admin # Register your models here. from goodsManage.models import * class GoodInventoryInline(admin.TabularInline): model = GoodInventory extra = 1 @admin.register(GoodKind) class GoodKindAdmin(admin.ModelAdmin): list_display = [f.name for f in GoodKind._meta.fields...
StarcoderdataPython
3392982
"""A module contains as set API for the puzzle grids.""" import string import random from abc import ABC, abstractmethod from types import TracebackType from typing import Any, List, Optional, Sequence, Type, Union from loguru import logger as _logger from puzzle.properties import Coordinate, GridSize, LetterCoordina...
StarcoderdataPython
3303861
import os import unittest from datetime import datetime as dt from satstac.sentinel.cli import parse_args testpath = os.path.dirname(__file__) class Test(unittest.TestCase): def test_parse_no_args(self): with self.assertRaises(SystemExit): parse_args(['']) with self.assertRaises(Sy...
StarcoderdataPython
98786
<reponame>tabulon-ext/moban import csv from lml.plugin import PluginInfo from moban import constants @PluginInfo(constants.DATA_LOADER_EXTENSION, tags=["custom"]) def open_custom(file_name): with open(file_name, "r") as data_csv: csvreader = csv.reader(data_csv) rows = [] for row in csvr...
StarcoderdataPython
1622335
<gh_stars>1-10 """ app.routes.report ================= """ import json from flask import Blueprint, Response, current_app, make_response, request from app.extensions import csrf_protect blueprint = Blueprint("report", __name__, url_prefix="/report") @blueprint.route("/csp_violations", methods=["POST"]) @csrf_prote...
StarcoderdataPython
1702137
<reponame>dasyak/winagent import asyncio import json import subprocess from time import perf_counter import requests from agent import WindowsAgent class TaskRunner(WindowsAgent): def __init__(self, task_pk): super().__init__() self.task_pk = task_pk self.task_url = f"{self.astor.server}...
StarcoderdataPython
1784610
<reponame>alex-dow/sourcelyzer<filename>sourcelyzer/rest/utils/auth.py from base64 import b64encode, b64decode import hashlib import os class InvalidAuthToken(Exception): pass def gen_auth_token(username, password, userid, session_id, encoding='utf-8'): salt = os.urandom(128) if isinstance(session_id, st...
StarcoderdataPython
3299310
from sklearn.feature_extraction.text import CountVectorizer class FeatureExtractor(): def buildVectorizer(self, data, kwargs): """ Constructs a CountVectorizer based on the given data. Args: data: Data to train the CountVectorizer """ # Instantiate CountVect...
StarcoderdataPython
3280191
""" Very basic Q-learning model to play frozen lake from the gym library. No hidden layers, simple q-table update method and exponential explore/exploit rate of decay. """ import numpy as np import gym import random import time from IPython.display import clear_output env = gym.make("FrozenLake-v0") action_space = e...
StarcoderdataPython
169339
<filename>test/integration/test_command.py import os.path import re from six import assertRegex from . import * class TestCommand(IntegrationTest): def __init__(self, *args, **kwargs): IntegrationTest.__init__( self, os.path.join(examples_dir, '07_commands'), *args, **kwargs ) de...
StarcoderdataPython
3308689
from setuptools import setup with open ( "README.md" , "r" ) as fh : long_description = fh . read () setup( name="organizador", version="0.1.1", description="Organiza archivos en carpetas teniendo como referencia las similitudes en sus nombres.", long_description = long_description , long_desc...
StarcoderdataPython
3307059
<gh_stars>0 import enum class StrEnumMeta(enum.EnumMeta): auto = enum.auto def from_str(self, member: str): try: return self[member] except KeyError: # TODO: use `add_suggestion` from torchvision.prototype.utils._internal to improve the error message as # ...
StarcoderdataPython
1604223
# functionaltests/tests.py # -*- coding: utf-8 -*- from django.test import LiveServerTestCase from selenium import webdriver from selenium.webdriver.common.keys import Keys class HomePageTest(LiveServerTestCase): def setUp(self): self.browser = webdriver.Firefox() self.browser.implicitly_wait(1)...
StarcoderdataPython
150305
<reponame>tgragnato/geneva import logging import pytest import actions.tree import actions.drop import actions.tamper import actions.duplicate import actions.sleep import actions.utils import actions.strategy import evaluator import evolve import layers.layer from scapy.all import IP, TCP, Raw def test_mate(logger)...
StarcoderdataPython
1763270
<reponame>WillDaSilva/daily-questions from datetime import date, timedelta from dateutil.parser import parse def working_days(year, weekend=(5, 6), holidays=tuple()): year_start, year_end = date(year, 1, 1), date(year, 12, 31) year_range = range((year_end - year_start).days + 1) year_dates = (year_start + ...
StarcoderdataPython
1759157
#! python # coding:utf-8 import svgwrite import maya.cmds as cmds import nnutil as nu def draw_edge(filepath, imagesize=4096, stroke_width=1, integer_mode=False, normalize=True): """ 選択エッジを svg 形式で指定したパスに書き出す integer_mode: True で UV 座標をピクセル変換後に端数を切り捨てる 水平垂直ラインをそのままテクスチャとして使用したい場合等に使う normaliz...
StarcoderdataPython
3220612
<reponame>Yunicorn228/web-tools import logging from server.auth import user_mediacloud_client, user_admin_mediacloud_client from flask import request logger = logging.getLogger(__name__) MAX_SOURCES = 60 def media_search_with_page(search_str, tags_id=None, **kwargs): link_id = request.args.get('linkId', 0) ...
StarcoderdataPython
150717
<reponame>zeemzoet/nuke import nukescripts axis = 1 nuke.thisNode()['code'].execute() _input = checkInput() if _input['cam'] and _input['geo']: ### checks how many vertices are selected i = 0 for vertex in nukescripts.snap3d.selectedPoints(): i += 1 if i: gen = nukescripts.snap3d.selectedPoints() poin...
StarcoderdataPython
4811615
<reponame>sudeep0901/python<filename>FaceDetection/readimagewithcv2.py import numpy as np import cv2 img = cv2.imread('image.jpg') # print(img) while True: cv2.imshow('mandrill', img) if cv2.waitKey(1) & 0xFF == 27: # getting escape key break cv2.imwrite("final_image.png", img) cv2.destroy...
StarcoderdataPython
3227195
# -*- coding: utf-8 -*- """Header here.""" import numpy as np def borehole_model(x, theta): """Given x and theta, return matrix of [row x] times [row theta] of values.""" return f def borehole_true(x): """Given x, return matrix of [row x] times 1 of values.""" return y
StarcoderdataPython
107016
from . import tools import os from datetime import datetime import logging import matplotlib.cm as mplcm import matplotlib.pyplot as plt import numpy as np from ipywidgets import Layout import ipywidgets as widgets from IPython.display import display import cv2 DEFAULT_EXTENSIONS = ['jpg', 'png', 'tif', 'iff', '...
StarcoderdataPython
3279446
# 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 json import warnings import pulumi import pulumi.runtime from typing import Union from . import utilities, tables class Cluster...
StarcoderdataPython
1627811
<gh_stars>1-10 """ 백준 6764번 : Sounds fishy! """ nums = [int(input()) for _ in range(4)] if nums[0] == nums[1] == nums[2] == nums[3]: print("Fish At Constant Depth") elif nums[0] < nums[1] < nums[2] < nums[3]: print("Fish Rising") elif nums[0] > nums[1] > nums[2] > nums[3]: print("Fish Diving") else: pr...
StarcoderdataPython
81066
<reponame>likx2/HypeFans import datetime from django.db import models from django.contrib.auth.models import AbstractUser from core.utils.func import user_avatar from unixtimestampfield.fields import UnixTimeStampField from django_countries.fields import CountryField from dateutil.relativedelta import relativedelta imp...
StarcoderdataPython
30578
#!/usr/bin/python # 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, software # di...
StarcoderdataPython
157962
<filename>mipqctool/controller/inferschema.py import os from mipqctool.model.qcfrictionless import QCtoDC, CdeDict, QcTable from mipqctool.controller.tablereport import TableReport class InferSchema(object): def __init__(self, table, csvname, sample_rows=100, maxlevels=10, cdedict=None, na_empty_strings_only...
StarcoderdataPython
1762726
<gh_stars>1-10 # -*- coding: utf-8 -*- # Zinc dumping and parsing module # (C) 2016 VRT Systems # # vim: set ts=4 sts=4 et tw=78 sw=4 si: import base64 import binascii import datetime import random import string import sys import traceback import six import hszinc from hszinc import VER_3_0, Grid, MODE_ZINC, MODE_JSO...
StarcoderdataPython
3325201
<reponame>kids-first/kf-lib-data-ingest import os import pytest from conftest import TEST_DATA_DIR from kf_lib_data_ingest.etl.configuration.base_config import ( AbstractConfig, ConfigValidationError, PyModuleConfig, YamlConfig, ) from kf_lib_data_ingest.etl.configuration.ingest_package_config import ...
StarcoderdataPython
174299
import datetime from http import HTTPStatus from sanic.response import json from core.helpers import jsonapi from apps.commons.errors import DataNotFoundError from apps.news.models import News from apps.news.repository import NewsRepo from apps.news.services import UpdateService async def update(request, id): r...
StarcoderdataPython
4808294
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Arduino lock-in amplifier """ __author__ = "<NAME>" __authoremail__ = "<EMAIL>" __url__ = "https://github.com/Dennis-van-Gils/DvG_Arduino_lock-in_amp" __date__ = "31-08-2021" __version__ = "2.0.0" # pylint: disable=invalid-name import os import sys import time as Time...
StarcoderdataPython
3348675
from typing import Tuple from math import sqrt class Algorithm: """A base levelling algorithm.""" @classmethod def calc(cls, before: int, after: int, inc: int) -> Tuple[int, int, bool]: """Returns the level, xp required to level up, whether the current xp gain is a levelup.""" bl, _ = cls...
StarcoderdataPython
1699179
<reponame>Arnaav-Singh/Beginner-code x = int(input("Enter your Sales amount: ")) if x >= 500000: print(x*10/100+x) elif x <=500000: print( x*5/100+x)
StarcoderdataPython
87367
<reponame>shitchell/rpi-server #!/usr/bin/env python3 from importlib.machinery import SourceFileLoader import readline import glob import http.server import socketserver import urllib import glob import random import time import sys import os SCRIPT_FILEPATH = os.path.realpath(__file__) SCRIPT_DIRPATH = os.path.dirna...
StarcoderdataPython
3314698
<gh_stars>1-10 from sandbox import Scene from sandbox.property import LinesCoincidenceProperty, PointInsideAngleProperty from .base import ExplainerTest class InsideTriangle1(ExplainerTest): def createScene(self): scene = Scene() A, B, C = scene.nondegenerate_triangle(labels=('A', 'B', 'C')).poin...
StarcoderdataPython
4829738
<filename>server/inventario/managers.py import hashlib import uuid from datetime import timedelta, datetime from time import time from sqlalchemy.exc import IntegrityError from server.common.managers import SuperManager from .models import * from ..user.models import User from openpyxl import load_workbook, Workbook ...
StarcoderdataPython
129436
<reponame>Debagboola/Django-Portfolio-and-Blog-App<gh_stars>0 from django.db import models # Create your models here. class Category(models.Model): name = models.CharField(max_length=20) class Post(models.Model): title = models.CharField(max_length=255) body = models.TextField() created_on = models....
StarcoderdataPython
3260192
from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from .forms import ProfileForm from django.contrib import messages # Create your views here. @login_required def profile_view(request): return render(request, 'oauth/profile.html') @login_required def change_p...
StarcoderdataPython
1604806
<reponame>Tejas-Nanaware/Learning-OpenCV<filename>haar cascades/own haar cascade/get files.py import urllib.request import cv2 import numpy as np import os print("Hi") def store_raw_images(): print("getting url") # neg_images_link = 'http://image-net.org/api/text/imagenet.synset.geturls?wnid=n00007846' # neg_i...
StarcoderdataPython
3380332
<filename>tests/test_validator.py<gh_stars>10-100 import yaml from dbd.db.db_schema import DbSchema def test_schema_validation(): with open('./tests/fixtures/schemas/schema1.yaml', 'r') as f: code = yaml.safe_load(f.read()) result, errors = DbSchema.validate_code(code) assert result w...
StarcoderdataPython
3255387
<reponame>PDA-UR/DIPPID-py<filename>DIPPID.py import sys import json from threading import Thread from time import sleep from datetime import datetime import signal # those modules are imported dynamically during runtime # they are imported only if the corresponding class is used #import socket #import serial #import ...
StarcoderdataPython
3312554
import time import os import sys from pathlib import Path import numpy as nump import pandas as panda import uuid import csv import inspect import re import platform import requests import json from datetime import datetime from tir.technologies.core.config import ConfigLoader from tir.technologies.core.logging_config ...
StarcoderdataPython
3249920
<reponame>alekseystryukov/quarterly_report<gh_stars>0 from django.shortcuts import render, get_object_or_404 from django.core.serializers.json import DjangoJSONEncoder from django.db.models import Q from companies.models import Company import json def index(request): context = { "companies": None, ...
StarcoderdataPython
3326577
# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/master/LICENSE from __future__ import absolute_import import sys import pytest import numpy import awkward1 def test(): one = awkward1.Array([999, 123, 1, 2, 3, 4, 5]) two = awkward1.Array([999])[:0] three = awkward1.Array([]) ...
StarcoderdataPython
128466
<gh_stars>0 import sys import pickle import json import os import math import networkx as nx from collections import defaultdict from net_init import load_network from net_init import generate_random_outs_conns_with_oracle as gen_rand_outs_with_oracle from network.sparse_table import SparseTable from network.communica...
StarcoderdataPython
3277730
<reponame>SpiderOak/enkube<gh_stars>0 # Copyright 2018 SpiderOak, 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 b...
StarcoderdataPython
34433
from datetime import datetime import timebomb.models as models def test_Notification(): notif = models.Notification("message") assert notif.content == "message" assert notif.read is False assert str(notif) == "message" def test_Player(): player = models.Player("name", "id") assert player....
StarcoderdataPython
171545
from . import db from werkzeug.security import generate_password_hash, check_password_hash from flask_login import UserMixin from . import login_manager from datetime import datetime, date @login_manager.user_loader def load_user(userName): return User.query.get(str(userName)) class User(UserMixin, db.Model): ...
StarcoderdataPython
3261075
import unittest import logging from common import loginit from mock import Mock, patch, mock_open from sensors.temperature.ds18b20 import Ds18b20 class TempSensorTest(unittest.TestCase): goodData = "93 01 4b 46 7f ff 0d 10 32 : crc=32 YES\n93 01 4b 46 7f ff 0d 10 32 t=25187" badCrc = "93 01 4b 46 7f ff 0d...
StarcoderdataPython
154966
""" Modified from https://github.com/facebookresearch/fvcore """ __all__ = ["Registry"] class Registry: """A registry providing name -> object mapping, to support custom modules. To create a registry (e.g. a backbone registry): .. code-block:: python BACKBONE_REGISTRY = Registry('BACKBONE')...
StarcoderdataPython
99422
<reponame>kotofey97/yatube_project_finale from django.contrib.auth import get_user_model from django.contrib.auth.forms import (PasswordChangeForm, PasswordResetForm, SetPasswordForm, UserCreationForm) User = get_user_model() class CreationForm(UserCreationForm): class Meta...
StarcoderdataPython
1750387
<reponame>fabric-testbed/core-api # coding: utf-8 from __future__ import absolute_import from datetime import date, datetime # noqa: F401 from typing import List, Dict # noqa: F401 from swagger_server.models.base_model_ import Model from swagger_server import util class Model200OkPaginatedLinks(Model): """NO...
StarcoderdataPython
1706999
<reponame>kaiwinut/hateyugemu import argparse def show_banner(): banner = """ =================================================\n\n はぁって言うゲーム\n\n =================================================\n\n """ print(banner) def show_players(players): player_list = "Players: " for i, name in enumerat...
StarcoderdataPython
3232622
import matplotlib.pyplot as plt import pandas as pd import pathlib import sys source = "res_floor.csv" if len(sys.argv) < 2 else sys.argv[1] ds = pd.read_csv(source, index_col=None) fig, (ax1, ax2, ax3) = plt.subplots(1, 3) # problem: tol was 0.001 but mean error is close to 0.015 ax1.boxplot((ds.true_scale - ds...
StarcoderdataPython
4814313
#!/usr/bin/env python # -*- coding: utf-8 -*- # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: © 2021 Massachusetts Institute of Technology. # SPDX-FileCopyrightText: © 2021 <NAME> <<EMAIL>> # NOTICE: authors should document their contributions in concisely in NOTICE # with details inline in source files...
StarcoderdataPython
1676215
<filename>python_liftbridge/python_liftbridge.py from logging import getLogger from logging import NullHandler import python_liftbridge.api_pb2 from python_liftbridge.base import BaseClient from python_liftbridge.errors import handle_rpc_errors, handle_rpc_errors_in_generator, ErrDeadlineExceeded, ErrChannelClosed fro...
StarcoderdataPython
162166
"""Some utility functions for working with TfJobs.""" import datetime import logging import time from kubernetes import client as k8s_client from kubeflow.testing import util GROUP = "argoproj.io" VERSION = "v1alpha1" PLURAL = "workflows" KIND = "Workflow" def log_status(workflow): """A callback to use with wait...
StarcoderdataPython
3337058
from typing import List, Optional, Type from vaccine.base_application import BaseApplication from vaccine.models import Message, User class AppTester: DEFAULT_USER_ADDRESS = "27820001001" DEFAULT_CHANNEL_ADDRESS = "27820001002" DEFAULT_TRANSPORT_NAME = "test_transport" DEFAULT_TRANSPORT_TYPE = Messag...
StarcoderdataPython
1757394
# Given a sorted array containing only 0s and 1s, find the transition point. Transition point is where 0 ends and 1 begins # https://www.geeksforgeeks.org/find-transition-point-binary-array/ # https://practice.geeksforgeeks.org/problems/find-transition-point-1587115620/1/ # time is O(logn) | Space is O(1) def tra...
StarcoderdataPython
167793
<filename>bot/plugins/inline.py # © its-leo-bitch from bot import bot from bot.utils import langs, lang_names from pyrogram import types, errors from piston import Piston import asyncio import time piston = Piston() execute = {} NEXT_OFFSET = 25 @bot.on_inline_query() async def inline_exec(client, query): stri...
StarcoderdataPython
1770838
"""Module tiktalik.connection""" # Copyright (c) 2013 Techstorage sp. z o.o. # # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Software without restriction, including without limitation the rights to ...
StarcoderdataPython
195823
import logging from kafka.errors import KafkaError, KafkaTimeoutError from kafka import KafkaProducer from data.logs_model.shared import epoch_ms from data.logs_model.logs_producer.interface import LogProducerInterface from data.logs_model.logs_producer.util import logs_json_serializer from data.logs_model.logs_produ...
StarcoderdataPython
3390353
<reponame>AsiaLi/rust #coding: utf8 from rust.command.base_command import BaseCommand from rust.resources.db.user import models as user_models from rust.resources.business.user.login_service import LoginService MANAGER_USER_NAME = 'manager' class Command(BaseCommand): def handle(self, *args): """ 创建系统管理员 """...
StarcoderdataPython
3303063
<filename>number_chart.py n = int(input("Enter the value of n : ")) size = n + (n - 1) center = n - 1 temp = [] answer = [] for i in range(size): temp.append("T") for i in range(size): answer.append(temp[:]) for digit in range(1, n + 1): expansion = digit + (digit - 1) position = ...
StarcoderdataPython
3354873
import threading from time import sleep def intervalExecute(interval, func, *args, **argd): ''' @param interval: execute func(*args, **argd) each interval @return: a callable object to enable you terminate the timer. ''' cancelled = threading.Event() def threadProc(*args, **argd): while...
StarcoderdataPython
3398278
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri May 17 13:34:59 2019 @author: atekawade """ import numpy as np def get_patches(img, patch_size = None, steps = None): stepy, stepx = steps my, mx = img.shape py, px = patch_size[0], patch_size[1] nx, ny = int(np.ceil(mx/px))...
StarcoderdataPython
3213710
"""Test functions related to the model creation, loading, saving and prediction.""" import os import shutil import pytest from autopylot.cameras import Camera from autopylot.datasets import preparedata from autopylot.models import architectures, utils from autopylot.utils import memory, settings dirpath = os.path.joi...
StarcoderdataPython
3234069
#!/usr/bin/python # -*- coding: utf-8 -*- """ Modelagem em tempo real | COVID-19 no Brasil -------------------------------------------- Ideias e modelagens desenvolvidas pela trinca: . <NAME> . <NAME> . <NAME> Esta modelagem possui as seguintes características: a) NÃO seguimos modelos paramétricos => Não existem dur...
StarcoderdataPython
11176
<filename>engine/sentiment_analysis.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Mar 14 17:42:27 2018 @author: zgeorg03 """ import re import json # Used for converting json to dictionary import datetime # Used for date conversions import matplotlib.pyplot as plt import numpy as np from sentim...
StarcoderdataPython
3248565
<reponame>rishusingh022/My-Journey-of-Data-Structures-and-Algorithms<filename>Project Euler Problems/Problem30.py def check_self_behaviour(num,pow): return num == sum([int(elem)**pow for elem in str(num)]) final_ans = 0 for i in range(2,1000000): if check_self_behaviour(i,5): final_ans += i print(f...
StarcoderdataPython
1735031
<reponame>ruoshengyuan/louplus-dm import datetime import pandas as pd base = datetime.date(2018, 10, 30) numdays = 80 # 所有的十月三十号以后的八十天的 list date_list = [base + datetime.timedelta(days=x) for x in range(0, numdays)] # 获取从 start 到 dest 的数据并插入数据库中 def getTickets(start, dest, driver, date_list, conn): cursor = con...
StarcoderdataPython
79347
<filename>leekspin/server.py # -*- coding: utf-8 -*- """Module for creating ``@type [bridge-]server-descriptor``s. .. authors:: <NAME> <<EMAIL>> 0xA3ADB67A2CDB8B35 <NAME> <<EMAIL>> .. licence:: see LICENSE file for licensing details .. copyright:: (c) 2013-2014 The Tor Project, Inc. (c) 20...
StarcoderdataPython
179840
from .context import polarity def test_pos_polarity_result(): assert polarity.polarity_result(0.8) == 'positive' def test_neg_polarity_result(): assert polarity.polarity_result(-0.8) == 'negative' def test_neutral_polarity_result(): assert polarity.polarity_result(0) == 'neutral'
StarcoderdataPython
137380
# Generated by Django 4.0.2 on 2022-03-23 11:56 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('base', '0036_profile_following'), ('base', '0037_reportcomments_reportposts_delete_report'), ] operations = [ ]
StarcoderdataPython
3215436
# Copyright 2022 Google 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 agreed to in writing, s...
StarcoderdataPython
139709
#!/usr/bin/env python # encoding: utf-8 # The MIT License (MIT) # Copyright (c) 2018-2020 CNRS # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limita...
StarcoderdataPython
117684
<reponame>anoadragon453/synapse-config-generator # -*- coding: utf-8 -*- # Copyright 2014 - 2016 OpenMarket Ltd # # 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/l...
StarcoderdataPython
1627491
<gh_stars>1-10 class Solution(object): def isHappy(self, n): """ :type n: int :rtype: bool """ cycle_members = {4, 16, 37, 58, 89, 145, 42, 20} def getn(n): res = 0 while n: res += (n % 10)**2 n = n // 10 ...
StarcoderdataPython
3364860
<reponame>kosarkarbasi/python_course<filename>tutproject/blog/admin.py from django.contrib import admin from .models import * # Register your models here. admin.site.register(Blog) admin.site.register(Author) admin.site.register(Entry) # admin.site.register(person)
StarcoderdataPython
119533
#!/usr/bin/env python # 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 # "L...
StarcoderdataPython
1628161
<filename>app/domain/repository/musical_weather_repository.py from datetime import datetime from domain.model.city import CityInDb, City from domain.repository.abstract_repository import AbstractRepository from domain.model.track import TrackInDb class MusicalWeatherRepository(AbstractRepository): def get_all(se...
StarcoderdataPython
3300218
"""Module for running function evaluations in separate processes and measuring time Classes: CodeBenchmark """ from multiprocessing import Process, Queue from signal import signal, alarm, SIGALRM from time import time from benchmike import exceptions as err from benchmike.customlogger import CustomLogger, LOG...
StarcoderdataPython
126424
def do(i): return i + 2
StarcoderdataPython
1632146
# Library imports import random # Project imports from hiddil.crypt import PublicKey, b64_encode, b64_decode from storage import Storage from storage.uid import UID from hiddil.exceptions import * class Block: BLOCK_NUM_MAX = 999999999999999 BLOCK_NUM_MIN = 1 def __init__(self, block_number: int, stor...
StarcoderdataPython
4822909
<filename>parameters.py<gh_stars>1-10 import csv import numpy as np import sys import time import random from typing import List , Tuple , Optional , Dict , Callable , Any import copy from matrix_implementations import * from measurement import measure, generate_input ### For benchmark functions OptTuple3i = Optional[...
StarcoderdataPython
3397302
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c)2012 Rackspace US, Inc. # 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.ap...
StarcoderdataPython
1693671
# Generated by Django 2.0.13 on 2019-09-26 10:16 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tracking', '0002_auto_20180918_2014'), ] operations = [ migrations.AddField( model_name='visitor', name='medium', ...
StarcoderdataPython
3283639
import pyfastnoisesimd.extension as ext import concurrent.futures as cf import numpy as np from enum import Enum _MIN_CHUNK_SIZE = 8192 def empty_aligned(shape, dtype=np.float32, n_byte=ext.SIMD_ALIGNMENT): """ Provides an memory-aligned array for use with SIMD accelerated instructions. Should b...
StarcoderdataPython