id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
114001 | <reponame>Slavkata/Forecast-Report
# Code in this file is taken from this site
# http://www.codiply.com/blog/hyperparameter-grid-search-across-multiple-models-in-scikit-learn/
# and modified to fit my program.
import pandas as pd
from sklearn.grid_search import GridSearchCV
import numpy as np
class EstimatorSelectio... | StarcoderdataPython |
21962 | <filename>school/lecture1/isi_cv_02_task.py
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 19 20:41:09 2017
@author: pd
"""
#from IPython import get_ipython
#get_ipython().magic('reset -sf')
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.tree import DecisionTreeClass... | StarcoderdataPython |
92443 | <reponame>entityoneuk/lusid-python-tools
import lusid
import lusid.models as models
import logging
logger = logging.getLogger()
def create_transaction_type_configuration(api_factory, alias, movements):
"""
This function creates a transaction type configuration if it doesn't already exist.
Parameters
... | StarcoderdataPython |
1606850 | <reponame>janbernloehr/watering
#!/usr/bin/python
# wiring stuff
from time import sleep
import wiringpi as wiringpi
# web stuff
import json
import falcon
# data stuff
import dataset
from datetime import date, datetime, timedelta
# constants
WATERING = 1
INPUT = 0
OUTPUT = 1
PWM_OUTPUT = 2
GPIO_CLOCK = 3
SOFT_PWM_O... | StarcoderdataPython |
3286040 | # pretty printing for stage 2.
# put "source /path/to/stage2_gdb_pretty_printers.py" in ~/.gdbinit to load it automatically.
import re
import gdb.printing
class TypePrinter:
no_payload_count = 4096
# Keep in sync with src/type.zig
# Types which have no payload do not need to be entered here.
payload_t... | StarcoderdataPython |
20950 | <filename>pkg/agents/team4/trainingAgent/findBestConfigs.py
# TODO: autmatate finding best agents
| StarcoderdataPython |
3364621 | <gh_stars>1-10
# Generated by Django 3.2 on 2021-04-29 14:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('school_management_app', '0013_alter_tcomment_created_on'),
]
operations = [
migrations.AlterField(
model_name='news... | StarcoderdataPython |
90607 | from enum import Enum
import logging
import dbus
try:
from gi.repository import GObject
except ImportError:
import gobject as GObject
from .dbus_bluez_interfaces import Characteristic, Service, string_to_dbus_array
logger = logging.getLogger(__name__)
class BluenetUuids(object):
SERVICE = 'FBE51523-B3... | StarcoderdataPython |
110023 | <reponame>vtta2008/pipelineTool
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Script Name: toolBoxII
Author: <NAME>/Jimmy - TD artist
Warning: This is the most complex code structure I have build, it is using more advanced maya features alongside
more advanced python features than before.
Descript... | StarcoderdataPython |
3963 | _all__ = ["db_handler","coin_value_handler"] | StarcoderdataPython |
3341467 | from .common_algos import bin_to_decimal, hex_to_decimal | StarcoderdataPython |
186942 | <filename>main.py
import os
import requests
from urllib.parse import urlparse
from dotenv import load_dotenv
import argparse
def configure_parser():
parser = argparse.ArgumentParser(description="""
Программа для сокращения URL (битлинка) и получения количества переходов по битлинку.
Программа взаимодейс... | StarcoderdataPython |
1744744 | # This file used by autocompletion module, don't use it in other purposes
class ScAddr:
def IsValid(self, other):
pass
def ToInt(self, other):
pass
def __eq__(self, other):
pass
def __ne__(self, other):
pass
def __rshift__(self, other):
pass
def rshi... | StarcoderdataPython |
3234691 | <reponame>Nik-Menendez/PyCudaAnalyzer<gh_stars>0
import os
from hep.cms.Dataset.CMSDataset import CMSDataset
from hep.root.TFile import TFile
# ______________________________________________________________________ ||
skim_dir = "/cmsuf/data/store/user/t2/users/klo/HToZaToLLGG/UFHZZLiteAnalyzer/HToZA_MC17_bkg/"
input... | StarcoderdataPython |
34700 | <gh_stars>1-10
import boto3
import json
import urllib.request
import os
from . import reflect
def publish(name, payload):
if os.environ.get("NODE_ENV") == "testing":
try:
dump = json.dumps({"name": name, "payload": payload})
data = bytes(dump.encode())
handler = urllib... | StarcoderdataPython |
1789124 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# */AIPND-revision/intropyproject-classify-pet-images/get_pet_labels.py
#
# PROGRAMMER: <NAME>
# DATE CREATED: 9/4/19
# REVISED DATE: 9/4/19
# PURPOSE: Create the ... | StarcoderdataPython |
1649462 | <gh_stars>100-1000
from vit.formatter.description_count import DescriptionCount
class DescriptionTruncatedCount(DescriptionCount):
def format(self, description, task):
if not description:
return self.empty()
truncated_description = self.format_description_truncated(description)
... | StarcoderdataPython |
99594 | from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response
from pyramid.view import view_config
import pyramid.httpexceptions as exc
import re
from pyramid.request import Request
from _pybgpstream import BGPStream, BGPRecord, BGPElem
from datetime impor... | StarcoderdataPython |
3268991 | # -*- coding: utf-8 -*-
"""rackio/logger/logdict.py
This module implements a dictionary based Class to hold
the tags to be logged.
"""
class LogTable(dict):
def __init__(self):
pass
def validate(self, period, tag):
if not type(period) in [int, float]:
return False
... | StarcoderdataPython |
1708559 | <reponame>BGTCapital/hummingbot
#!/usr/bin/env python
from os.path import join, realpath
import sys; sys.path.insert(0, realpath(join(__file__, "../../../../../")))
from hummingbot.connector.exchange.kraken.kraken_user_stream_tracker import KrakenUserStreamTracker
from hummingbot.connector.exchange.kraken.kraken_auth ... | StarcoderdataPython |
134285 | from tests.cli_client.CLI import CLI
def main():
cli: CLI = CLI()
cli.mock_run()
if __name__ == "__main__":
main()
| StarcoderdataPython |
3246823 | import turtle
import math
bob = turtle.Turtle()
def square(t, length):
for i in range(4):
t.fd(length)
t.lt(90)
def polygon(t, length, n):
degrees = 360/n
for i in range(n):
t.fd(length)
t.lt(degrees)
def circle(t, r):
circumference = 2*3.14*r
length = circumference ... | StarcoderdataPython |
3227569 | <reponame>anglebinbin/Barista-tool<filename>gui/network_manager/history_manager.py<gh_stars>1-10
class HistoryManager():
def __init__(self, maxSize=100):
""" Initialize HistoryManager which saved maximal maxSize states.
The maxSize+1 insertion removes the first
"""
self.history =... | StarcoderdataPython |
183889 | <reponame>DonDzundza/Berkeley-AI-Course-Projects
# shopSmart.py
# ------------
# Licensing Information: Please do not distribute or publish solutions to this
# project. You are free to use and extend these projects for educational
# purposes. The Pacman AI projects were developed at UC Berkeley, primarily by
# <NAME> (... | StarcoderdataPython |
1702774 | <reponame>tobiasraabe/locus-of-control
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from bld.project_paths import project_paths_join as ppj
LOC_MAP = {
"LOC_LUCK": "Item 3",
"LOC_ACHIEVED_DESERVE": "Item 2",
"LOC_POSSIBILITIES": "Item 8",
"LOC_LIFES_COURSE": "Item 1",
"L... | StarcoderdataPython |
3203314 | <filename>skill/quotes.py
quotes = [
{
"headline": "<NAME> über schlechte Chancen",
"content": "Wenn etwas wichtig genug ist, dann mach es, auch wenn alle Chancen gegen dich stehen."
},
{
"headline": "<NAME> über den Aufbau einer Firma",
"content": "Eine Firma aufzubauen ist ... | StarcoderdataPython |
92797 | <reponame>Time-xg/bookmanager_django<filename>user/models.py
from django.db import models
# Create your models here.
class UserInfo(models.Model):
# USER_CHOICES = (
# ('reader', 'Reader'),
# ('admin', 'Administrator'),
# )
# GENDER_CHOICES = (
# ('male', 'male'),
# ('fema... | StarcoderdataPython |
1656670 | # ================
# User Mixin
# ================
#
import json
from django.http import Http404
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from rest_framework import serializers
from .models import User as UserModel
class UserValidationMixin(object):
"""
Mixin... | StarcoderdataPython |
1696708 | <filename>src/tests/helpers/wsdl_locations.py
TEXT_CASING_WSDL = "https://www.dataaccess.com/webservicesserver/TextCasing.wso?WSDL"
| StarcoderdataPython |
3249532 | import os
import os.path
import hashlib
import errno
from tqdm import tqdm
import gzip
import tarfile
import time
import zipfile
def gen_bar_updater(pbar):
def bar_update(count, block_size, total_size):
if pbar.total is None and total_size:
pbar.total = total_size
progress_bytes = coun... | StarcoderdataPython |
3314197 | <filename>tests/test_fastq_filter.py
# Copyright (c) 2021 Leiden University Medical Center
#
# 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 ... | StarcoderdataPython |
68484 | <filename>core/ai/behaviors/__init__.py
from core.ai.behaviors.base import Behavior
from core.ai.behaviors.meleeattack import MeleeAttack
from core.ai.behaviors.move import Move
from core.ai.behaviors.wait import Wait
| StarcoderdataPython |
59877 | <filename>python/motorModule.py
#!/usr/bin/env python3
import os
import robomodules as rm
from messages import *
import RPi.GPIO as GPIO
import time
import signal
import sys
ADDRESS = os.environ.get("BIND_ADDRESS","localhost")
PORT = os.environ.get("BIND_PORT", 11293)
FREQUENCY = 0
LEFT_PWM = 32
LEFT_1 = 36
LEFT_2... | StarcoderdataPython |
180788 | <gh_stars>100-1000
from ._optimization import *
__all__ = [name for name in dir() if name[0] != '_']
| StarcoderdataPython |
4817553 | # Copyright 1999-2018 Alibaba Group Holding 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 law or a... | StarcoderdataPython |
3330723 | <reponame>adrienlachaize/dezede
from django.test import TestCase
from .utils import HTMLAnnotatedCharList, AnnotatedDiff
class HTMLAnnotatedCharListTestCase(TestCase):
def setUp(self):
self.html_annotated_char_list = HTMLAnnotatedCharList('<p>blabla</p>')
def test_annotate(self):
self.html_a... | StarcoderdataPython |
4801381 | <gh_stars>10-100
from cisco_sdwan_policy.BaseObject import BaseObject
class Sequence(BaseObject):
def __init__(self,id,name,type,base_action,ip_type,match,actions,**kwargs):
self.id = id
self.name = name
self.type = type
self.baseAction = base_action
self.ip_type=ip_type
... | StarcoderdataPython |
156216 | import unittest
from app.models import Articles
class TestArticle(unittest.TestCase):
'''
Test Class to test the behaviour of the Article class
'''
def setUp(self):
'''
Set up that will run before every Test
'''
self.new_article = Articles("Palestinians evacuate the body of Palestinian journalist... | StarcoderdataPython |
3366827 | <filename>src/afancontrol/temp/file.py
import glob
import re
from pathlib import Path
from typing import Optional, Tuple
from afancontrol.configparser import ConfigParserSection
from afancontrol.temp.base import Temp, TempCelsius
def _expand_glob(path: str):
matches = glob.glob(path)
if not matches:
... | StarcoderdataPython |
3268699 | <filename>datastructure/practice/c1/p_1_34.py
import random
def make_a_mistake(s):
index = random.randint(0, len(s) - 1)
c = s[index]
while not ord('A') <= ord(c) <= ord('z'):
index = random.randint(0, len(s) - 1)
c = s[index]
new_c = chr(random.randint(ord('A'), ord('z')))
chars ... | StarcoderdataPython |
3304406 | <reponame>gebeto/python<filename>s3/main.py
import boto3
import botocore
import time
import os
BUCKET_NAME = 'tms-system-docs'
resource = boto3.resource('s3',
aws_access_key_id=os.getenv("AWS_ACCESS_KEY_ID"),
aws_secret_access_key=os.getenv("AWS_SECRET_ACCESS_KEY"),
)
client = resource.meta.client
def get_resour... | StarcoderdataPython |
3317202 | <reponame>Plasmakatt/farmerextreme<filename>debug/cameraextreme.py
#!/usr/bin/python -Btt
import sys
import os
import time
sys.path.append(os.path.dirname(os.path.realpath(__file__)) + "/../lib")
print(os.path.dirname(os.path.realpath(__file__)) + "/../lib")
from cameracontrol import CameraControl
def main():
t... | StarcoderdataPython |
4817378 | <gh_stars>0
#!/usr/bin/python3
"""
Sensors aggregation and storage.
https://github.com/dimitar-kunchev/NR-VentilationMonitoring
@author: <NAME>
@license: See the LICENSE file
@email: <EMAIL>
"""
import RPi.GPIO as GPIO
import serial
import time
import pymysql
import configparser
import json
import os
import sys
import ... | StarcoderdataPython |
3370926 | import kafka
import time
import redis
from arguments import configs
from helpers import get_absolute_links, normalize_url, to_sha1
if __name__ == "__main__":
producer = kafka.KafkaProducer(bootstrap_servers=configs.kafka_host)
exist_urls = redis.StrictRedis(host=configs.redis_host, port=configs.redis_port,
... | StarcoderdataPython |
3374459 | <filename>lib/JumpScale/clients/openvcloud/Client.py
from JumpScale import j
from JumpScale.clients.portal.PortalClient import ApiError
import time
import datetime
import os
import requests
def refresh_jwt(jwt, payload):
if payload['iss'] == 'itsyouonline':
refreshurl = "https://itsyou.online/v1/oauth/jwt/... | StarcoderdataPython |
1758653 | # Variables generales
jugador_x = 0
# Gameloop
while True:
if termina_juego():
break
# Revisamos teclas
if tecla_derecha:
# Actualizamos datos
jugador_x += 1
# Pintamos de acuerdo los nuevos datos
pintar_jugador(jugador_x)
| StarcoderdataPython |
3327779 | """Python client."""
import logging
import sys
import cosmosid.api.upload as upload
import cosmosid.utils as utils
from cosmosid.api import auth
from cosmosid.api.analysis import Analysis
from cosmosid.api.artifacts import Artifacts
from cosmosid.api.files import Files, Runs
from cosmosid.api.import_workflow import I... | StarcoderdataPython |
1605277 | <filename>World 3/Exercise 82.py
import os
odds = []
evens = []
general = []
while True:
os.system('cls' if os.name == 'nt' else 'clear')
numbers=float(input("Type a value: "))
general.append(numbers)
if numbers % 2 == 0:
odds.append(numbers)
else:
evens.append(numbers)
if numb... | StarcoderdataPython |
1674763 | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... | StarcoderdataPython |
1758180 | <filename>src/ite/algs/causal_multitask_gaussian_processes/model.py
# Copyright (c) 2019, <NAME>
# Licensed under the BSD 3-clause license (see LICENSE.txt)
# third party
import GPy
import numpy as np
import pandas as pd
from sklearn.neighbors import KNeighborsRegressor
# ite absolute
from ite.utils.metrics import Hi... | StarcoderdataPython |
3368940 | """
System tests for execute multiple policies
"""
from time import sleep
from cafe.drivers.unittest.decorators import tags
from test_repo.autoscale.fixtures import AutoscaleFixture
class ExecuteMultiplePoliciesTest(AutoscaleFixture):
"""
System tests to verify execute multiple scaling policies' scenarios
... | StarcoderdataPython |
3341290 | <reponame>RedDrum-Redfish-Project/RedDrum-Frontend
# Copyright Notice:
# Copyright 2018 Dell, Inc. All rights reserved.
# License: BSD License. For full license text see link: https://github.com/RedDrum-Redfish-Project/RedDrum-Frontend/LICENSE.txt
import os
from .resource import RfStaticResource
from .generate... | StarcoderdataPython |
1618338 | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
class PySrsly(PythonPackage):
"""srsly: Modern high-performance serialization utilities for Python."""
homepage ... | StarcoderdataPython |
3317727 | <reponame>calico/stimulated_emission_imaging<filename>figure_generation/figure_A9.py<gh_stars>1-10
import os
import numpy as np
import matplotlib.pyplot as plt
import np_tif
from stack_registration import bucket
def main():
assert os.path.isdir('./../images')
if not os.path.isdir('./../images/figur... | StarcoderdataPython |
3311121 | <gh_stars>10-100
"""cyme.branch.httpd
- Our embedded WSGI server used to serve the HTTP API.
"""
from __future__ import absolute_import
from eventlet import listen
from eventlet import wsgi
from django.core.handlers import wsgi as djwsgi
from django.core.servers.basehttp import AdminMediaHandler
from requests impo... | StarcoderdataPython |
4826149 | import sys
import os
import time
import math
import torch
import numpy as np
from PIL import Image, ImageDraw, ImageFont
from torch.autograd import Variable
import torch.nn.functional as F
import cv2
from scipy import spatial
import struct
import imghdr
import cython
from scipy.special import softmax
#TensorRT stu... | StarcoderdataPython |
1651625 | <gh_stars>10-100
import math
def main():
x = float(raw_input("Enter the number: "))
guess = x / 2
guess1 = nextGuess(guess,x)
print "The square root is", guess1
def nextGuess(guess,x):
g = int(raw_input("Enter the number of iterations: "))
for i in range(g):
guess = (guess + (x/guess))/2
diff = math.s... | StarcoderdataPython |
5705 | # -*- coding: utf-8 -*-
# Copyright 2019 <NAME>. All Rights Reserved.
#
# Licensed under the MIT License;
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/MIT
#
# Unless required by applicable law or agreed to in writing... | StarcoderdataPython |
67377 | <reponame>wangyushengcp3/pytorch-auto-drive<filename>utils/datasets/culane.py
import torchvision
import os
import pickle
import numpy as np
from tqdm import tqdm
from PIL import Image
# CULane direct loading (work with the segmentation style lists)
class CULane(torchvision.datasets.VisionDataset):
def __init__(se... | StarcoderdataPython |
1664685 | <filename>deepmd/xyz2raw.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import json
import argparse
from collections import Counter
from ase.io import read, write
from tqdm import tqdm
import dpdata
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'-... | StarcoderdataPython |
1751893 | import psutil
from monitor.host import base
class HostMonitorPsutilDriver(base.BaseHostMonitorDriver):
def get_vmem_total(self):
return psutil.virtual_memory().total
def get_vmem_used(self):
return psutil.virtual_memory().used
def get_disk_io(self):
current_disk_io = psutil.dis... | StarcoderdataPython |
3283683 | # Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import os
import socket
import llnl.util.tty as tty
from spack import *
def cmake_cache_entry(name, value, vtype=None)... | StarcoderdataPython |
3301177 | from scipy import fftpack
import matplotlib.pyplot as plt
import sys
import numpy as np
image = plt.imread(sys.argv[1]) # flatten=True gives a greyscale image
fft2 = fftpack.fft2(image)
plt.imshow(20*np.log10(abs(fft2)))
plt.show()
| StarcoderdataPython |
1667284 | # -*- coding: utf-8 -*-
"""The decompressor interface."""
import abc
class Decompressor(object):
"""Decompressor interface."""
# pylint: disable=redundant-returns-doc
@abc.abstractmethod
def Decompress(self, compressed_data):
"""Decompresses the compressed data.
Args:
compressed_data (bytes)... | StarcoderdataPython |
1614978 | <reponame>daicang/Euler<gh_stars>0
# Find a*b, for |a|, |b| in range(1000), s.t. x^2 + a*x + b
# produces maxium number of primes for consecutive values of n
def prime_under(n):
primes = [2]
for x in range(3, n):
for p in primes:
if p * p > x:
primes.append(x)
... | StarcoderdataPython |
3236194 | <reponame>mrcrilly/vs-vlan-db
from vsvlandb import api
from flask import render_template, request
from flask.ext import restful
# Define our endpoints:
class ApiVLANs(restful.Resource):
def get(self):
return {'get': 'Not implemented'}
def post(self):
return {'post': 'Not implemented'}
... | StarcoderdataPython |
59516 | <filename>src/nepal/tests/test_container.py<gh_stars>1-10
# encoding: utf-8
from __future__ import print_function
import json
import pytest
from nepal.models.container import Container
from nepal.models.node import Node
from profile.models.user import User
from toolbox.icepick import ordered
@pytest.mark.django_db... | StarcoderdataPython |
18520 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# from unittest import mock
# from datakit_dworld.push import Push
def test_push(capsys):
"""Sample pytest test function with a built-in pytest fixture as an argument.
"""
# cmd = Greeting(None, None, cmd_name='dworld push')
# parsed_args = mock.Mock()
... | StarcoderdataPython |
3361156 | <reponame>Wooble/rustplus<filename>rustplus/api/remote/heartbeat.py
import asyncio
import time
class HeartBeat:
def __init__(self, rust_api) -> None:
self.rust_api = rust_api
self.next_run = time.time()
self.running = False
async def start_beat(self) -> None:
if self.running... | StarcoderdataPython |
117781 | # Generated by Django 2.0.13 on 2020-03-04 14:55
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('ddcz', '0023_skills'),
]
operations = [
migrations.RenameModel(
old_name='Dovednosti',
new_name='Skill',
),
]
| StarcoderdataPython |
3216942 | <filename>Redmash/redmash_db.py
#/u/GoldenSights
import traceback
import sys
import time
import datetime
import string
import sqlite3
'''USER CONFIGURATION'''
#TIMESTAMP = '%A %d %B %Y'
TIMESTAMP = '%a %d %b %Y'
#The time format.
# "%A %d %B %Y" = "Wendesday 04 June 2014"
#http://docs.python.org/2/library/time.html#... | StarcoderdataPython |
91621 | <reponame>rajeevs1992/pyhealthvault
from healthvaultlib.helpers.requestmanager import RequestManager
class Method:
def __init__(self, request, response):
self.request = request
self.response = response
def execute(self, connection):
requestmgr = RequestManager(self, connection)
... | StarcoderdataPython |
1762974 | from shared.utils import get_db_ref
db = get_db_ref()
class ModelBasic(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
model_name = db.Column(db.String(50), nullable=False)
model_dataset = db.Column(db.Integer, db.ForeignKey('data_file.id'))
model_type = db.Column(db.Inte... | StarcoderdataPython |
3369975 | ##
# Copyright (c) 2013-2017 Apple 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.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | StarcoderdataPython |
3329291 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 18 14:18:42 2020
@author: paul
"""
import cv2
import numpy as np
import matplotlib.pyplot as plt
import glob
import re
import os
import random
import shutil
from scipy import stats
#Data sample
src=r"..\image_bbox_slicer-master\slice_output"
dst_perc=r"..\image_bbox_sli... | StarcoderdataPython |
3247529 | <filename>app/producer.py
from kafka import KafkaProducer
import time
# connect to Kafka
producer = KafkaProducer(bootstrap_servers='kafka:9092')
def emit():
for i in range(100):
print(f'send message {i}')
str_res = f'{i}'
producer.send('foobar', str_res.encode())
time.sleep(1)
i... | StarcoderdataPython |
67098 | # Using Keras to load our model and images
from keras.models import load_model
from keras.preprocessing import image
# To grab environment variables, image directories, and image paths
import os
from os.path import isfile, join
# To sort our image directories by natural sort
from natsort import os_sorted
# To turn o... | StarcoderdataPython |
1657726 | from utime import sleep_us
from machine import Pin
class IR_OUT:
SHORT = 562
LONG = 1686 # A long pulse burst is 1686us long, thats 3 times a short pulse burst
def __init__(self):
self.pin = Pin(4, Pin.OUT)
@micropython.viper
def pulse2(self, cycles): # Probably a very hacky solution, ... | StarcoderdataPython |
3313562 | <gh_stars>0
"""Create a frequency table with descending order of frequency."""
from collections import Counter
def frequency_table(nums):
"""Return a frequency table for given number list."""
table = Counter(nums)
print('Number\tFrequency')
for num in table.most_common():
print(f'{num[0]}\t{nu... | StarcoderdataPython |
3355559 | <gh_stars>1-10
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import re
class AtWikiStripper(object):
# Comment: `// comment`
COMMENT = re.compile(r'^//')
# Inline annotation: `&color(#999999){text}`, `&nicovideo(url)`
INLINE_ANN = re.compile(r'&[a... | StarcoderdataPython |
1639630 | from django.apps import AppConfig
class UpdownConfig(AppConfig):
name = 'updown'
| StarcoderdataPython |
45899 | import sys
from django.apps import apps
from django.core.management import BaseCommand
from viewwork import BaseViewWork
from viewwork.models import Menu
class Command(BaseCommand):
def add_arguments(self, parser):
super().add_arguments(parser)
parser.add_argument('action', action='store', type... | StarcoderdataPython |
178941 | <filename>main.py
import pygame
from pygame.locals import *
from sys import exit
pygame.init()
largura = 640
altura = 480
preto = (0,0,0)
tela = pygame.display.set_mode((largura, altura))
pygame.display.set_caption('Sprites')
| StarcoderdataPython |
85939 | """
Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: MIT-0
"""
from test.testlib.testcase import BaseTestCase
from cfnlint import conditions
class TestEquals(BaseTestCase):
""" Test Equals Logic """
def test_equal_value_string(self):
""" Test equals set... | StarcoderdataPython |
65123 | import os
from dvc.repo.scm_context import scm_context
from dvc.utils import relpath, resolve_output, resolve_paths
from dvc.utils.fs import path_isin
from ..exceptions import InvalidArgumentError, OutputDuplicationError
from . import locked
@locked
@scm_context
def imp_url(
self,
url,
out=None,
fna... | StarcoderdataPython |
1645574 | <reponame>persona7548/cyphersAPI
import requests
import time
import pandas
import json
import csv
headers = {'Content-Type': 'application/json; charset=utf-8','apikey' :'***********'}
equipment = list(["101","102","103","104","105","106","202","203","301","302","303","304","305","107","204","205"])
csvfile = pandas.re... | StarcoderdataPython |
3399303 | <reponame>KevinLuo41/LeetCodeInPython
#!/usr/bin/env python
# encoding: utf-8
"""
sort_list.py
Created by Shengwei on 2014-07-21.
"""
# https://oj.leetcode.com/problems/sort-list/
# tags: easy / medium, linked-list, merge sort, D&C, recursion
"""
Sort a linked list in O(n log n) time using constant space complexity.... | StarcoderdataPython |
1754634 | import warnings
warnings.filterwarnings('ignore')
import os
import pandas as pd
import math
import time
import random
import shutil
import numpy as np
import pandas as pd
from sklearn.model_selection import StratifiedKFold, GroupKFold, KFold
from tqdm.auto import tqdm
#from functools import partial
import sys
sys... | StarcoderdataPython |
1740011 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017 Google
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# ----------------------------------------------------------------------------
#
# *** AUTO GENERATED CODE *** AUTO GENERATED CODE ***
#
... | StarcoderdataPython |
3291574 | from project import socketio
from project.solution.observer import Observer
from project.controller.smart_tv_controller import block_tv
ob_on = False
@socketio.on("observerConnect")
def observer_connect():
global ob_on
observer = Observer()
observer.messages_types = ("status", "notification", "confirmati... | StarcoderdataPython |
3326548 | from django.db import models
from jsonfield import JSONField
from generic_serializer import SerializableModel
from test_app.models import DataProvider
class OauthConfig(models.Model, SerializableModel):
data_provider = models.OneToOneField(DataProvider, related_name="oauth_config", on_delete=models.CASCADE)
... | StarcoderdataPython |
1637696 | <reponame>matroid/matroid-python<filename>test/test_detectors_labels.py
import os
import time
from datetime import datetime
import pytest
from test.data import TEST_IMAGE_FILE, RANDOM_MONGO_ID, TEST_IMAGE_URL
from matroid.error import APIConnectionError, InvalidQueryError, APIError
from test.helper import print_test_p... | StarcoderdataPython |
154281 | <filename>scripts/sentenceLengths.py
import sys
mapping = {}
total = 0
with open(sys.argv[1], 'r') as f:
for line in f:
total += 1
l = len(line.split())
mapping[l] = mapping.get(l, 0) + 1
print(mapping)
percentiles = {}
sumSoFar = 0
for l in sorted(mapping.keys()):
sumSoFar += mapping[l... | StarcoderdataPython |
3273176 | <filename>src/distance.py
def distance_matrix(patches, metric):
return distance_matrix_symmetrical(patches, metric)
# Assumes the metric is symmetrical.
def distance_matrix_symmetrical(patches, metric):
width = len(patches)
matrix = []
for y in range(width):
row = [float(metric(patches[x], patc... | StarcoderdataPython |
3246041 | import copy
import warnings
from collections import OrderedDict
from typing import List, Union
import numpy as np
import torch
__all__ = [
"normalize_image",
"channels_first",
"scale_intrinsics",
"pointquaternion_to_homogeneous",
"poses_to_transforms",
"create_label_image",
]
def normalize_i... | StarcoderdataPython |
3272899 | <gh_stars>0
import unittest
from main import get_age
class TestSum(unittest.TestCase):
def test(self):
self.assertEqual(get_age("2 years old"), 2)
self.assertEqual(get_age("4 years old"), 4)
self.assertEqual(get_age("5 years old"), 5)
self.assertEqual(get_age("7 years old"), 7)
... | StarcoderdataPython |
195478 | # Copyright (c) 2015-2019 The Switch Authors. All rights reserved.
# Licensed under the Apache License, Version 2.0, which is in the LICENSE file.
"""
Defines load zone parameters for the Switch model.
INPUT FILE INFORMATION
Import load zone data. The following tab-separated files are
expected in the input di... | StarcoderdataPython |
4819092 | model_name = "bedroom_full2b"
epoch_load = "latest"
print("pointnetae", model_name, epoch_load)
data_dir = "../data"
split_dir = "../splits"
rooms_subdir = "Rooms"
roominfos_subdir = "RoomInfos"
model_params_subdir = "ModelParameters"
model_training_reconstructions_subdir = "TrainingReconstructions"
model_testing_rec... | StarcoderdataPython |
3253644 | import math
import numpy
class DelayBlock(object):
""" A block of delays for a subvertex
"""
def __init__(
self, n_delay_stages, delay_per_stage, vertex_slice):
self._delay_per_stage = delay_per_stage
self._n_delay_stages = n_delay_stages
n_words_per_row = int(math.ce... | StarcoderdataPython |
71110 | import re
from collections import namedtuple
from copy import copy
from difflib import SequenceMatcher
from pprint import pformat
from bs4 import BeautifulSoup
from bs4 import NavigableString
from bs4 import Tag
logger = None
def restore_refs(old_content: str,
new_content: str,
re... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.