id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
187211 | <gh_stars>100-1000
import click
from .history import clone
from . import config
def validate_remote(ctx, param, value):
if value:
try:
remote, branch = value.split('/')
return (remote, branch)
except ValueError:
raise click.BadParameter('remote need to be in fo... | StarcoderdataPython |
4805294 | <filename>array/array.py
#id array
class Array:
def __init__(self, size, arrayType = int):
assert size >0, 'Array size must be > 0'
self.size = size
self.items = [arrayType(0)] * size
self.arrayType = arrayType
def __len__(self):
return self.size
def __getitem__(sel... | StarcoderdataPython |
3346816 | <filename>tools/relocate_svn.py
#!/usr/bin/env python
#
## Natural Language Toolkit: update svn repository to new UUID
#
# Copyright (C) 2001-2012 NLTK Project
# Author: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# URL: <http://www.nltk.org/>
# For license information, see LICENSE.TXT
# NB Should work on all platform... | StarcoderdataPython |
1630756 | import numpy as np
from PIL import Image
import os
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
from torch.utils.data import DataLoader
import time
from sklearn.model_selection import train_test_split
import shutil
import pickle
def is_greyscale(img):
sh = np.array(img).shape
if len(sh) <... | StarcoderdataPython |
54235 | from fastapi import APIRouter, Depends
from fastapi.responses import ORJSONResponse
from di import GetPrizeInteractorFactory
from domain.entity import Prize, PrizeResponse, ValidationErrorResponse, now
from usecase.interactor import GetPrizeInteractor
router = APIRouter()
@router.get(
"/{user_id}",
response... | StarcoderdataPython |
3353208 | <filename>py_tdlib/constructors/call_protocol.py<gh_stars>10-100
from ..factory import Type
class callProtocol(Type):
udp_p2p = None # type: "Bool"
udp_reflector = None # type: "Bool"
min_layer = None # type: "int32"
max_layer = None # type: "int32"
| StarcoderdataPython |
3299887 | <reponame>ikuokuo/start-pytorch
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# pylint: disable=missing-docstring
import cv2 as cv
import numpy as np
import albumentations as A
from albumentations.pytorch.transforms import ToTensorV2
import torch
from torch.utils.data import Dataset
class Wheat(Dataset):
def __i... | StarcoderdataPython |
1675329 | import os
import selenium
from selenium import webdriver
import time
from PIL import Image
import io
import requests
q = input("Enter object to search: ")
tdir = input("Enter dir to store image: ")
url = "https://www.google.com/search?q={}&tbm=isch&tbs=sur%3Afc&hl=en&ved=0CAIQpwVqFwoTCKCa1c6s4-oCFQAAAAAdAAAAABAC&biw=... | StarcoderdataPython |
1632312 | <gh_stars>0
import torch.nn as nn
from inspect import signature
import torch
import torch.nn.functional as F
from functools import partial
class SelfModulationBN2D(nn.Module):
def __init__(self, in_features : int, latent_size : int = 128):
super().__init__()
s... | StarcoderdataPython |
1687393 | #!/usr/bin/env python3
#
# Copyright 2018 The Bazel 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 ... | StarcoderdataPython |
1763327 | import cPickle
import sys
from moduleUsefulFunctions_20180215 import *
from random import randint
import subprocess
#ver16 denovoClustering code onwards definition of clusterObject
class clusterObject:
__slots__=['reference','dictKmers','numberOfReads','forAlignment','listSeqIndices']
def __init__(self,ref... | StarcoderdataPython |
3275621 | #!/usr/bin/python
import sys
import os
import struct
import pygame
from pygame.locals import *
# Main loop default setup
index = 0
see_sun = False
if '-h' in sys.argv or len(sys.argv) != 2:
print """
Usage: openscrolls_skyviewer <file>
Keys:
PageDown / PageUp Navigate through the differen... | StarcoderdataPython |
72294 | <filename>environment/cogment_verse_environment/utils/serialization_helpers.py
# Copyright 2021 AI Redefined Inc. <<EMAIL>>
#
# 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.a... | StarcoderdataPython |
117144 | <gh_stars>1-10
# Copyright 2020 Huawei Technologies Co., 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/licenses/LICENSE-2.0
#
# Unless required by applicable l... | StarcoderdataPython |
3228185 | import unittest
import numpy as np
from sklearn.gaussian_process import GaussianProcessClassifier
from sklearn.naive_bayes import GaussianNB
from skactiveml.base import SkactivemlClassifier
from skactiveml.classifier import ParzenWindowClassifier, SklearnClassifier
from skactiveml.pool import MonteCarloEER, ValueOfIn... | StarcoderdataPython |
1741959 | import torch.nn as nn
from net import resnet50
from misc import torchutils
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self, num_classes=200):
super().__init__()
self.num_classes = num_classes
self.resnet50 = resnet50.resnet50(pretrained=True, strides=(2, 2, 2, 1))
... | StarcoderdataPython |
167041 | <gh_stars>0
from __future__ import annotations
from ...scrap_worker.subsystems import (
HeartbeatSubsystem,
ElectionSubsystem,
QuellUprisingSubsystem,
UnionAttendanceSubsystem,
UnionLeadershipSubsystem,
UnionMembershipSubsystem,
WorkloadPreprocessorSubsystem,
)
from ..mocks.kafka import Kaf... | StarcoderdataPython |
1604351 | from .automl import AutoML # noqa: F401
| StarcoderdataPython |
3210064 | <reponame>jakjus/csgomath_engine
import mysql.connector
import os
class Uploader:
def __init__(self, extracted_data):
self.extracted_data = extracted_data
def upload(self):
self.connect()
self.insert()
self.close()
def connect(self):
root_pass = os.environ.get('MA... | StarcoderdataPython |
56068 | # Create a calculator function
# The function should accept three parameters:
# first_number: a numeric value for the math operation
# second_number: a numeric value for the math operation
# operation: the word 'add' or 'subtract'
# the function should return the result of the two numbers added or subtracted
# based on... | StarcoderdataPython |
118120 | <reponame>ponyatov/datalang
from .object import *
## input/output object
class IO(Object):
pass
## directory
class Dir(IO):
pass
## file
class File(IO):
pass
| StarcoderdataPython |
3390836 | <filename>Fast Speedy/long_fast_speedy.py
#!/usr/bin/env python
import random
from Crypto.Util.number import *
def drift(R, B):
n = len(B)
ans, ini = R[-1], 0
for i in B:
ini ^= R[i-1]
R = [ini] + R[:-1]
return ans, R
flag = open('flag.png', 'r').read()
flag = bin(int(flag.encode('hex'), ... | StarcoderdataPython |
76282 | <gh_stars>0
from PyQt5.QtWidgets import QWidget, QPushButton, QGridLayout, QComboBox,\
QMessageBox, QHBoxLayout, QLabel, QGroupBox, QSpinBox, \
QButtonGroup, QRadioButton
import os
from character import Character
from rule_constants import TRIALS, ATTACK_EFFECTS
... | StarcoderdataPython |
1677052 | <gh_stars>0
""" Send an event when a request changes it state """
import logging
from pinakes.main.catalog.services.handle_approval_events import (
HandleApprovalEvents,
)
logger = logging.getLogger("approval")
class SendEvent:
"""SendEvent service class"""
EVENT_REQUEST_STARTED = "request_started"
... | StarcoderdataPython |
1680953 | <reponame>tryagainconcepts/graphql-server
import json
from urllib.parse import urlencode
import pytest
from .app import create_app, url_string
from .schema import AsyncSchema
def response_json(response):
return json.loads(response.body.decode())
def json_dump_kwarg(**kwargs):
return json.dumps(kwargs)
d... | StarcoderdataPython |
177543 | <filename>poradnia/advicer/views.py
from atom.ext.crispy_forms.views import FormSetMixin
from atom.views import ActionMessageMixin, ActionView, FormInitialMixin
from braces.views import (
FormValidMessageMixin,
LoginRequiredMixin,
SelectRelatedMixin,
StaffuserRequiredMixin,
UserFormKwargsMixin,
)
fr... | StarcoderdataPython |
3359560 | <reponame>rune-labs/runeq-python<filename>runeq/v2sdk/patients.py
"""
Models for querying patient metadata.
"""
from typing import Iterable
from .common import SetMemberBase, QueryBase, SetBase
from .devices import DeviceQuery, DeviceSet
from .graph.model import GraphID
def _patient_graph_id(patient_id: str) -> str... | StarcoderdataPython |
3360776 | <filename>metrilyx/server/response.py
class ResponseData(object):
def __init__(self, _id, _type, **kwargs):
self.id = _id
self.type = _type
if type(kwargs["data"]) not in (list, tuple, dict):
raise RuntimeError("Invalid data type. Must be a list or tuple!")
... | StarcoderdataPython |
4836594 | <filename>src/html2ans/parsers/utils.py
import six
from bs4.element import NavigableString, Tag
def has_attributes(tag, filter_types=('id', 'class', 'style')):
"""
Helper function to check if a tag has attributes (excluding the given ``filter_types``).
"""
if isinstance(tag, Tag) and tag.attrs:
... | StarcoderdataPython |
3366252 | #!/usr/bin/env python
# #############################################################################
# Copyright : (C) 2017 by Teledomic.eu All rights reserved
#
# Name: mytb.ipc.win_mutex
#
# Description: mutex for windows os
#
# #############################################################################
i... | StarcoderdataPython |
1793823 | <gh_stars>1-10
from math import sqrt, pow, fabs
DBL_MAX = 1.7976931348623158e+308 #taken from Visual C++
DBL_EPS = 0.0000000000001
def euclidean_distance_coords(x1, y1, x2, y2):
return sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2))
def euclidean_distance_points(p1, p2):
return euclidean_distance_coords(p1.x(),... | StarcoderdataPython |
27871 | #!/usr/bin/env python3
import os.path
import subprocess
import shutil
def get_compiler_path():
compiler_path = os.path.abspath("../../debug-compiler-theory-samples/llvm_4")
if not os.path.exists(compiler_path):
raise ValueError('compiler llvm_4 not found')
return compiler_path
class Runner:
d... | StarcoderdataPython |
198142 | import socket
UDPSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
listen_addr = ("", 200)
UDPSock.bind(listen_addr)
while True:
data, addr = UDPSock.recvfrom(1024)
print(data.strip(), addr)
UDPSock.sendto('Reply from server: {}'.format(data), addr)
| StarcoderdataPython |
1773123 | for i in range(7, 1001, 10):
print(i) | StarcoderdataPython |
3320430 | import unittest
import requests
from mock import Mock
from mock import patch
from .context import app
class TwiMLTest(unittest.TestCase):
def setUp(self):
self.app = app.test_client()
def assertTwiML(self, response):
self.assertTrue("<Response>" in response.data, "Did not find " \
... | StarcoderdataPython |
61434 | <filename>src/core/src/tortuga/utility/xmlParserUtility.py
# Copyright 2008-2018 Univa Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENS... | StarcoderdataPython |
44437 | # In The Name of God
# =======================================
# [] File Name : pipe.py
#
# [] Creation Date : 27-11-2019
#
# [] Created By : <NAME> <<EMAIL>>
# =======================================
import os
def child(n, w):
print('I am Child')
f = os.fdopen(w, 'w')
# the old way
f.write('hello %d... | StarcoderdataPython |
22586 | from collections import namedtuple
import numpy as np
import talib
from jesse.indicators.ma import ma
from jesse.indicators.mean_ad import mean_ad
from jesse.indicators.median_ad import median_ad
from jesse.helpers import get_candle_source, slice_candles
BollingerBands = namedtuple('BollingerBands', ['upperband', 'm... | StarcoderdataPython |
59221 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
# 根目录配置
# 要求将浏览的文件目录挂载到statics/mountfile目录,没有对任意位置的目录做兼容性测试,因为我准备使用docker容器运行程序,正好是挂载方式。
# 使用normpath对windows和linux的路径分隔符做兼容
baseroot = os.path.normpath(os.path.join(os.path.dirname(__file__), 'statics/mountfile'))
def root():
return baseroot
# 数据库配置
dbconf... | StarcoderdataPython |
1721926 | <reponame>who0sy/custom_crawler
# -*- coding: utf-8 -*-
# 百度企业信用-通用配置
baidu_custom_settings = {
"REDIRECT_ENABLED": False, # 禁止重定向
"RETRY_ENABLED": True, # 自定义重试
"RETRY_TIMES": 19,
"DOWNLOAD_TIMEOUT": 25,
# "COOKIES_ENABLED": False, # 设置False,在headers里面传递cookie
"ITEM_PIPELINES": {
... | StarcoderdataPython |
3223166 | <filename>bindings/python/cntk/tests/onnx_test_helper.py
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE.md file in the project root
# for full license information.
# ==============================================================================
import os
import re
import ... | StarcoderdataPython |
3380749 | <filename>src/wai/annotations/core/logging/_StreamLogger.py
from typing import Callable, TypeVar
from ..stream import StreamProcessor, ThenFunction, DoneFunction
from ..stream.util import RequiresNoFinalisation
InputElementType = TypeVar("InputElementType")
class StreamLogger(
RequiresNoFinalisation,
Stream... | StarcoderdataPython |
3271715 | <gh_stars>0
from flask import Flask, send_from_directory
app = Flask(__name__)
@app.route('/debug')
def debug(): return 'alive'
@app.route('/')
@app.route('/index')
def index(): return send_from_directory('static', 'index.html')
| StarcoderdataPython |
91154 | <reponame>marcuusmelo/radar_do_carro_web
from django.shortcuts import render, redirect
from django.http import HttpResponse, JsonResponse
from django_tables2 import RequestConfig
from django.contrib.auth.decorators import login_required, permission_required
from django.http import HttpResponse
from django.shortcuts imp... | StarcoderdataPython |
3380901 | <gh_stars>0
import csv #nice module for writing out to csv files
from bs4 import BeautifulSoup
import codecs
import sys
olex_file = input("Please enter the file name of the scan results ")
olex = open(olex_file,'r')
csv_f = csv.reader(olex)
csv_reader = list(csv_f)
url_olex = input("Please enter the file name of the ... | StarcoderdataPython |
13852 | """
This module tests utils
"""
from unittest.mock import patch, MagicMock
from superset_patchup.utils import get_complex_env_var, is_safe_url, is_valid_provider
from superset_patchup.oauth import CustomSecurityManager
class TestUtils:
"""
Class to test the utils module
"""
@patch("superset_patchup.... | StarcoderdataPython |
63975 | from time import clock
import sys
sys.path.append('../../../')
print (sys.path)
from tspdb.src.data import generateHarmonics as gH
from tspdb.src.data import generateTrend as gT
import tspdb.src.data.generateARMA as gA
import numpy as np
from tspdb.src.hdf_util import write_data
import matplotlib.pyplot as pl... | StarcoderdataPython |
182556 | # test that console.log can be accessed from the browser
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
# enable browser logging
d = DesiredCapabilities.CHROME
d['loggingPrefs'] = { 'browser':'ALL' }
browser = webdriver.Chrome(desired_capabilities=d)
... | StarcoderdataPython |
24977 | from . import *
class BICClassifier(Classifier):
# These prefixes came from from http://editeur.dyndns.org/bic_categories
LEVEL_1_PREFIXES = {
Art_Design: 'A',
Biography_Memoir: 'B',
Foreign_Language_Study: 'C',
Literary_Criticism: 'D',
Reference_Study_Aids: 'G',
... | StarcoderdataPython |
3281963 | from typing import List
from .baserouter import BaseRouter
class CrudRouter(BaseRouter):
def __init__(
self,
request_schema,
response_schema,
model,
**kwargs
):
super().__init__()
self.request_schema = request_schema
s... | StarcoderdataPython |
190763 | <filename>logFileReplay-raw/send_data_py3.py
# -*- coding: utf-8 -*-
import arrow
import json
import os
import sys
import time
import urllib3
import importlib
import requests
from configparser import ConfigParser
from optparse import OptionParser
import logging
import regex
MAX_RETRY_NUM = 10
RETRY_WAIT_TIME_IN_SEC = ... | StarcoderdataPython |
1675596 | <gh_stars>1-10
# Copyright (c) 2022 Mira Geoscience Ltd.
#
# This file is part of geoapps.
#
# geoapps is distributed under the terms and conditions of the MIT License
# (see LICENSE file at the root of this source code package).
def string_name(value: str, characters: str = ".") -> str:
"""
Find and repl... | StarcoderdataPython |
1661607 | <reponame>benoitc/cablesgate
#!/usr/bin/env python
# -*- coding: utf-8 -
# Copyright (c) 2010 <NAME> <<EMAIL>>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all co... | StarcoderdataPython |
4824335 | # -*- coding: utf-8 -*-
"""Backend management system classes
Used to communicate with providers without using CFME facilities
"""
from __future__ import absolute_import
import os
from datetime import datetime, timedelta
import pytz
from azure.common import AzureConflictHttpError
from azure.common.credentials import ... | StarcoderdataPython |
3398077 | <filename>tests/functional/data/name_clash_with_entry_point/matching_name/__init__.py
print("Running matching_name/__init__.py as", __name__)
| StarcoderdataPython |
3214295 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 22 15:47:38 2020
@author: xyz
"""
def main():
x = 15
if x > 5:
print("X is larger than five!")
else:
print("X is less than or equal to five!")
main()
| StarcoderdataPython |
3352942 | <reponame>Jesus-Lares/Detector_de_Cubrebocas
import cv2
import mediapipe as mp
mp_face_detection = mp.solutions.face_detection
labels = ["Con_mascarilla","Sin_mascarilla"]
recognition = cv2.face.LBPHFaceRecognizer_create()
recognition.read("./Models/ModelTrain.xml")
cap = cv2.VideoCapture(0,cv2.CAP_DSHOW)
with mp_f... | StarcoderdataPython |
4829740 | #!/usr/bin/env python
import os
import sys
import math
sys.path.insert(0, os.pardir)
sys.path.insert(0, os.path.join(os.pardir, 'openmoc'))
from testing_harness import TrackingTestHarness
from input_set import PinCellInput
import openmoc
class TrackingPinCellCMFDTestHarness(TrackingTestHarness):
"""Tests trackin... | StarcoderdataPython |
3345649 | from __future__ import absolute_import
import numpy as np
import keras
import logging
import cv2
from concurrent.futures import ThreadPoolExecutor
from .base import Model
from .keras import KerasModel
class AWSRekognitionModel(Model):
"""Creates a :class:`Model` instance for the use of the AWS API.
"""
... | StarcoderdataPython |
3310652 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# simple script to call imageviewer app
# 2015-05-21
#
import felapps
felapps.imageviewer.run(maximize=True, logon=False, debug=False)
| StarcoderdataPython |
1621696 | <reponame>bendikrb/podme_api<gh_stars>1-10
import unittest
from podme_api.client import PodMeClient
podme_client = PodMeClient("<EMAIL>", "example")
class TestPodMeClient(unittest.TestCase):
def test_login(self):
self.assertEqual(1, 1)
if __name__ == '__main__':
unittest.main()
| StarcoderdataPython |
3330151 | """A Spawner for the EGI Notebooks service
"""
import base64
import uuid
from kubernetes.client import V1ObjectMeta, V1Secret
from kubernetes.client.rest import ApiException
from kubespawner import KubeSpawner
from traitlets import Unicode
class EGISpawner(KubeSpawner):
token_secret_name_template = Unicode(
... | StarcoderdataPython |
3370828 | <gh_stars>0
import os, sys, time
from time import strftime
import logging
import names
import numpy as np
from PyQt5 import QtCore, QtGui, QtWidgets
import cv2
import enum
from control.micromanager import Camera
from detection import get_robot_control
import imageio
import matplotlib.pyplot as plt
class... | StarcoderdataPython |
1601489 | from logging import getLogger
import traceback
from .cancel_order import cancel_order
logger = getLogger("__main__").getChild(__name__)
def cancel_orders(exchange_name, orders):
logger.debug("start")
logger.debug(exchange_name)
logger.debug(orders)
results = []
for order in orders:
logger... | StarcoderdataPython |
66916 | <reponame>jiwon1219/couchers
import grpc
import requests
from couchers.config import config
from couchers.db import session_scope
from couchers.models import User
from pb import bugs_pb2, bugs_pb2_grpc
class Bugs(bugs_pb2_grpc.BugsServicer):
def _version(self):
return config["VERSION"]
def Version(s... | StarcoderdataPython |
34530 | <gh_stars>1-10
# Copyright (C) 2019 by eHealth Africa : http://www.eHealthAfrica.org
#
# See the NOTICE file distributed with this work for additional information
# regarding copyright ownership.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with
# ... | StarcoderdataPython |
4804315 | import random
def gen_rand(x):
a=random.randint(0,x)
return a
a=[gen_rand(a) for a in range(0,100)]
print(a)
def sorter(arr):
dic={}
for item in arr:
if arr.count(item) not in dic.keys():
dic[arr.count(item)]=[item]
else:dic[arr.count(item)].append(item)... | StarcoderdataPython |
1779183 | import unittest
import numpy as np
from numpy.random import RandomState
from trojai.datagen.datatype_xforms import ToTensorXForm
from trojai.datagen.image_entity import GenericImageEntity
class TestDatatypeTransforms(unittest.TestCase):
def setUp(self):
pass
def test_ToTensor1(self):
img = G... | StarcoderdataPython |
3385440 | <filename>bluebottle/activities/migrations/0010_activity_transition_date.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2019-10-07 19:01
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('activities', '0... | StarcoderdataPython |
1690865 | <reponame>jaumejordan/simfleet
# -*- coding: utf-8 -*-
import json
from asyncio import CancelledError
import faker
from loguru import logger
from spade.agent import Agent
from spade.behaviour import CyclicBehaviour
from spade.message import Message
from spade.template import Template
from .protocol import REQUEST_PR... | StarcoderdataPython |
1609711 | from .backgroundSubtractor import BackgroundSubtractor
from .boundingBox import BoundingBox
from .videoController import VideoController
from .humanSkeleton import HumanSkeleton2D | StarcoderdataPython |
3303549 | from pathlib import Path
from obsidian_tools.watch import handle_match, replace_youtube_links, main
def test_replace_youtube_links():
text_pre = (Path(__file__).parent / "test_data" / "watch_test_pre.md").read_text()
text_post = (Path(__file__).parent / "test_data" / "watch_test_post.md").read_text()
new... | StarcoderdataPython |
3326350 | <gh_stars>0
import shutil
import tempfile
import jinja2
import os
from slex import inspect_ex
from . import paths
from . import utils
def find_docs_root_dir(start_path):
path = start_path
while os.path.basename(path) not in ('doc', 'docs'):
temp_path = os.path.dirname(path)
if temp_path == p... | StarcoderdataPython |
1693171 | import cv2
import os
from hdn.core.config import cfg
'''This script is using for transform POT dataset from video to img frames.'''
if __name__ == "__main__":
import os, shutil
result_path = cfg.BASE.PROJ_PATH + 'experiments/tracker_homo_config/results/POT/HDN'
for i in os.listdir(result_path):
or... | StarcoderdataPython |
61397 | #!/usr/bin/env python3
import RPi.GPIO as GPIO
import subprocess
import time
from gpiozero import OutputDevice
SLEEP_INTERVAL = 3 # (seconds) How often we check the core temperature.
GPIO_PIN = 13 # Which GPIO pin you're using to control the fan.
DEBUG_LOGGING = False
def setup():
if DEBUG_LOGGING: print('Set... | StarcoderdataPython |
4812888 | def test_disabled_pandas(spacy_disabled_pandas_doc):
# ensure that pandas extension is not set
assert not spacy_disabled_pandas_doc.has_extension("conll_pd")
for sent in spacy_disabled_pandas_doc.sents:
assert not sent.has_extension("conll_pd")
for token in spacy_disabled_pandas_doc:
as... | StarcoderdataPython |
1689839 | <filename>Algorithms/Intervention/degree.py
from networkx import all_neighbors
from networkx.exception import NetworkXError as nxerror
from random import random
def intervene(graph,opts):
try:
graph.successors
except AttributeError:
graph.successors = graph.neighbors
o = graph.values["opinion"]
eh ... | StarcoderdataPython |
3346071 | <filename>llama/LlamaApi.py
from .Config import EXPORT_DIR, EXPORT_INDEX_JSON
from .Filters import Filters
from .LlamaStats import LlamaStats
from .operations import filter_by_person, parse_timecolumn
from .plotting import multipage_plot_or_show
from .common import (
require, as_list, read_json, read_csv,
write_or_... | StarcoderdataPython |
1792886 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Módulo bissecção: Método da bissecção ou dicotomia para resolver equações
import math
import numpy as np
# Resolve equação pelo método da bissecção.
# Entradas: função, extremos do chute inicial, tolerancia e criticidade de parada
# Retorno: solução, número de iteraçõ... | StarcoderdataPython |
41780 | <reponame>mardukbp/robotcode
from __future__ import annotations
from asyncio import CancelledError
from typing import TYPE_CHECKING, Any, List, Optional
from ....jsonrpc2.protocol import rpc_method
from ....utils.async_event import async_tasking_event
from ....utils.logging import LoggingDescriptor
from ..has_extend_... | StarcoderdataPython |
38094 | import unittest
def navigation(rows, cols, x, y):
if 1 <= x <= rows - 2 and 1 <= y <= cols - 2:
return [(x - 1 , y - 1), ( x - 1, y), ( x - 1, y + 1),
( x , y),
(x + 1 , y - 1), ( x + 1, y), ( x + 1, y + 1)]
return []
def hourglassSum(arr):
if n... | StarcoderdataPython |
3306398 | from __future__ import division
import numpy as np
import numpy.linalg as la
from ...utils import splogdet, spsolve
from ...steps import metropolis
from pysal.spreg.utils import spdot
#############################
# SPATIAL SAMPLE METHODS #
#############################
def logp_rho_cov(state, val):
"""
Th... | StarcoderdataPython |
151250 | # -*- coding: utf-8 -*-
from django.db import models, migrations
from allauth.socialaccount.models import SocialAccount
def copy_fb_data(apps, schema_editor):
model = apps.get_model('xsd_members', 'MemberProfile')
db_alias = schema_editor.connection.alias
objects = model.objects.using(db_alias).all()
... | StarcoderdataPython |
4834406 | <filename>airtng_flask/models/vacation_property.py
from airtng_flask.models import app_db
db = app_db()
class VacationProperty(db.Model):
__tablename__ = "vacation_properties"
id = db.Column(db.Integer, primary_key=True)
description = db.Column(db.String, nullable=False)
image_url = db.Column(db.Str... | StarcoderdataPython |
79911 | <reponame>scravy/ornament
from __future__ import annotations
import unittest
from apm import *
class DictionaryMatchingTests(unittest.TestCase):
def test_empty_dict(self):
self.assertTrue(match({}, {}))
def test_empty_subdict(self):
self.assertTrue(match({"a": 3}, {}))
def test_empty_... | StarcoderdataPython |
163934 | <filename>topcollaborator/cogs/fpl.py
from discord.ext import commands
import discord
import requests,json
import aiohttp
import asyncio
class FPL_commands(commands.Cog):
def __init__(self,bot):
self.bot=bot
self.FPL_URL = "https://fantasy.premierleague.com/api/"
self.Fixture= "fixtures/?e... | StarcoderdataPython |
196066 | <reponame>ffreemt/epub2txt<filename>epub2txt/browse_filename.py<gh_stars>0
"""Browse to a file.
https://pythonspot.com/tk-file-dialogs/
filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes=(("jpeg files","*.jpg"),("all files","*.*")))
"""
# import sys
from pathlib import Path
import tkinter as ... | StarcoderdataPython |
167390 | <reponame>danielspg/skip_list
# Python3 code for searching and deleting element in skip list
import random
class Node(object):
'''
Class to implement node
'''
def __init__(self, key, level):
self.key = key
# list to hold references to node of different level
self.forward = [... | StarcoderdataPython |
3235713 | """
<USAGE>
python main.py FUNCTION [ARGS]
<FUNCTION>
- pre_processing
ARGS: [TRAIN(default) | TEST]
- train_nn
- test_nn
ARGS: [n] (The parameters of the n-th epoch will be used.)
"""
import pdb # noqa: F401
# import numpy as np
import scipy.io as scio
import deepdish as dd
from os import path
from glob i... | StarcoderdataPython |
3281130 | from flask_sqlalchemy import SQLAlchemy
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_login import LoginManager
from flask_migrate import Migrate
from config import config_options
from flask_bootstrap import Bootstrap
bootstrap = Bootstrap()
migrate = Migrate()
db = SQLAlchemy()
login_manager... | StarcoderdataPython |
3282934 | # Generated by Django 2.1.2 on 2018-10-31 11:07
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('mediumwave', '0012_transmitter_country_name'),
]
operations = [
migrations.RemoveField(
model_name='station',
name='country'... | StarcoderdataPython |
3388571 | <reponame>devssa/dev-jobs-bo
import telebot
import env
from services.github_api import GitHubApi
from msgs import bot_msgs as msg
from random import choice
bot = telebot.TeleBot(env.TOKEN)
bot.remove_webhook()
@bot.message_handler(commands=['jobs'])
def send_jobs(message):
jobs = GitHubApi().get_jobs()
if jo... | StarcoderdataPython |
3277592 | <filename>froide/campaign/__init__.py
default_app_config = 'froide.campaign.apps.CampaignConfig'
| StarcoderdataPython |
112188 | #!/usr/bin/env python3
import unittest
from dockerfile_parse import DockerfileParser
from tests_functional import DoozerRunnerTestCase
class TestBasicRebase(DoozerRunnerTestCase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def setUp(self):
super().setUp()
d... | StarcoderdataPython |
4838964 | <reponame>GitProfAn/100DaysOfAlgo
# Solution 1
# O(nlog(n)) time / O(n) space
# n - length of the array
def sortedSquaredArray(array):
sortedSquares = [0 for _ in array]
for idx in range(len(array)):
value = array[idx]
sortedSquares[idx] = value * value
sortedSquares.sort()
return sor... | StarcoderdataPython |
40849 | <reponame>ondiiik/meteoink
from config import pins
from machine import Pin, PWM
from utime import sleep_ms
def play(*pattern):
if pins.BUZZER < 0:
return
for tone in pattern:
if isinstance(tone, int):
sleep_ms(tone)
else:
beeper = PWM(Pin(pins.BUZZER), f... | StarcoderdataPython |
78230 | class Node:
"""链表节点类"""
def __init__(self):
self.data = 0
self.next = None
class LinkedListStack:
"""链表结构堆栈类"""
def __init__(self):
"""初始化堆栈的属性"""
self.head = Node()
self.top = self.head # 堆栈的顶端,当前表示堆栈为空
def is_empty(self):
"""判断堆栈是否为空"""
i... | StarcoderdataPython |
3215312 | <reponame>Lisanaaa/BlockChainParser
#!/usr/bin/env python
import requests
from bs4 import BeautifulSoup
import os.path
# This part is for the initialization of the crawler parameters
# N = int(sys.argv[1]) # This is the the limit on the number of pages to retrieve
directory = 'download' # This is the directory name ... | StarcoderdataPython |
163478 | from __future__ import annotations
import copy
import typing
class Activity:
def __init__(self, start_time: float, finish_time: float) -> None:
self.start_time = start_time
self.finish_time = finish_time
def __iter__(self) -> typing.Iterator[float]:
for item in (self.start_time, self... | StarcoderdataPython |
1738742 | <filename>courses/backend/Learn Django by Creating Projects/projects/news/pages/tests.py
from django.test import TestCase
from django.http import response
from django.test import TestCase, SimpleTestCase
from django.urls.base import reverse
from django.contrib.auth import get_user_model
# Create your tests here.
cla... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.