id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
11243597 | <reponame>joshdabosh/autopack<gh_stars>0
import RPi.GPIO as GPIO
import time
from threading import Thread
distances = []
TRIG = 24
ECHO = 26
GPIO.setmode(GPIO.BOARD)
GPIO.setup(TRIG, GPIO.OUT) # trigger voltage setup
GPIO.setup(ECHO, GPIO.IN) # echo input setup
GPIO.output(TRIG, False)
distances = []
def sca... | StarcoderdataPython |
4938003 | import os
import cv2
import time
import itertools
import numpy as np
repository = f"{os.getcwd()}/images"
watermark_file = "watermark.png"
color = [255, 0, 0] # blue
def get_files(path):
for _, _, files in os.walk(path):
return files
def watermark(image):
watermark = cv2.imread(watermark_file)
... | StarcoderdataPython |
11353709 | <filename>cupyx/optimizing/__init__.py
from cupyx.optimizing._optimize import optimize # NOQA
| StarcoderdataPython |
8033650 | # Copyright 2020 <NAME>, Pôle OFB-INRAE ECLA, UR RECOVER
#
# 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 |
3284335 | <filename>setup.py
from setuptools import setup
with open('README.rst') as f:
long_description = f.read()
setup(
name='csvtomd',
version='0.1.1',
description='Convert your CSV files into Markdown tables.',
long_description=long_description,
url='https://github.com/mplewis/csvtomd',
license... | StarcoderdataPython |
6665257 | x = ["ala", "marcin", "zygmunt"]
print(len(x))
# x.append("zbigniew")
print(len(x))
x.remove("marcin")
for i, y in enumerate(x):
print("Element i", i, ": ", y)
if "zbigniew" in x:
print("Jest zbigniew na liscie! :)")
else:
print("kogo z nami nie ma? Zbigniewa")
| StarcoderdataPython |
3266266 | # importing the required modules
import matplotlib.pyplot as plt
import numpy as np
# setting the x - coordinates
x = np.arange(0, 2*(np.pi)*5, 0.1)
# setting the corresponding y - coordinates
y = np.sin(x)
# potting the points
plt.plot(x, y, label ='sin(x)')
# naming the x axis
# naming the y axis
plt.yla... | StarcoderdataPython |
6438469 | <reponame>jcf94/FlexTensor<filename>flextensor/testing/others/hand-craft/schedule_shift_cuda.py<gh_stars>1-10
import tvm
import math
import torch
import numpy as np
from flextensor.nn import ShiftConv2d_nhwc
shift_conv2d_shape = [
# ShiftNet(https://arxiv.org/abs/1801.09392) with input size: 256*256
(1, 128, 1... | StarcoderdataPython |
1715424 | """supervisr core form fields"""
from django.forms import ChoiceField
STATUS_CHOICE_SUCCESS = 'success'
STATUS_CHOICE_WARNING = 'warning'
STATUS_CHOICE_ERROR = 'error'
class StatusField(ChoiceField):
"""Field to show one of three different statuses"""
minimum = None
recommended = None
current = No... | StarcoderdataPython |
9787453 | <reponame>AoWangPhilly/cryptsenal
from cryptsenal.autokey import AutoKey
import pytest
def test_encrypt():
plainText = "THEFISHSWIMSATMIDNIGHT"
keys = ["gesture", "highlight", "enemy", "cane", "executive"]
cipherTexts = ["zlwycjlldmrasaeelzagaf",
"apkmtanzpbtwfbepvjqszt",
... | StarcoderdataPython |
5055136 | from django import forms
from django.conf import settings
from django.http import HttpResponse, HttpResponseRedirect, Http404
from homepage.models import *
from manager import models as mmod
from . import templater
def process_request(request):
'''Get products from the DB'''
users = mmod.User.objects.filter(i... | StarcoderdataPython |
6636195 | BRACKET_TYPE_CHAMPIONSHIP = "championship"
BRACKET_TYPE_CONSOLATION = "consolation"
GAME_TYPE_REGULAR = "REGULAR"
GAME_TYPE_PLAYOFF = "PLAYOFF"
GAME_TYPE_CONSOLATION = "CONSOLATION"
STORAGE_JSON = "json"
STORAGE_AIRTABLE = "airtable"
DATA_TYPE_GAMES = "games"
DATA_TYPE_TEAMS = "teams"
| StarcoderdataPython |
4993342 | <gh_stars>10-100
# (C) Copyright 2017- ECMWF.
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
#
# In applying this licence, ECMWF does not waive the privileges and immunities
# granted to it by virtue of its status as... | StarcoderdataPython |
1857782 | from annolid.gui.widgets.extract_frame_dialog import ExtractFrameDialog
from annolid.gui.widgets.convert_coco_dialog import ConvertCOODialog
from annolid.gui.widgets.train_model_dialog import TrainModelDialog
from annolid.gui.widgets.track_dialog import TrackDialog
from annolid.gui.widgets.glitter2_dialog import Glitte... | StarcoderdataPython |
6534319 | '''
This file is part of PM4Py (More Info: https://pm4py.fit.fraunhofer.de).
PM4Py is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... | StarcoderdataPython |
8133800 | <filename>mysockpool/exceptions.py
# coding=utf-8
"""
Copyright (c) 2018-present, Ant Financial Service Group
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.apac... | StarcoderdataPython |
11348539 | # ##############################################################################
# This file is part of df_config #
# #
# Copyright (C) 2020 <NAME> <<EMAIL>> #
# All Rights Res... | StarcoderdataPython |
8122686 | <gh_stars>0
from multiprocessing.dummy import Pool as ThreadPool
import requests
import itertools
def get_request(requests_session, urls):
try:
return requests_session.get(urls, timeout=3)
except:
return
def get_request_multi(urls):
try:
return requests.get(urls, timeout=3)
exce... | StarcoderdataPython |
5077449 | from logging import getLogger
import json
# logger = getLogger(__name__)
logger = getLogger('app')
def info(scid, res, parm, msg):
if res is not None:
response = str(res.status_code) + ':' + res.reason
url = ', ' + res.url
logger.info(response + ', ' + scid + ', ' + msg + url)
elif par... | StarcoderdataPython |
271008 | <gh_stars>0
import glob
import numpy as np
from sklearn.metrics import roc_curve, auc
import matplotlib.pyplot as plt
def read_scoring_matrix(filename):
with open(filename,'r') as f:
line = f.readline()
while(line.startswith("#")): line = f.readline()
#This will be the row containing the a... | StarcoderdataPython |
6431838 | """ Interface layer for user authentication/authorization """
import hug
from api.transport.auth import authentication
api = hug.API(__name__)
@hug.get('/', api=api, requires=authentication)
def get_user(user: hug.directives.user):
return 'hello {}!'.format(user)
| StarcoderdataPython |
110340 | <reponame>nguyenthieu95/machine_learning
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 15 10:17:15 2018
@author: thieunv
Magic method: https://www.youtube.com/watch?v=3ohzBxoFHAY
"""
class Employee:
# class variable
raise_amount = 1.04
def __init__(self, first, last, pay)... | StarcoderdataPython |
3419879 | <reponame>mttcnnff/bytewax
import time
import bytewax
def slow(x):
print("start slow")
# time.sleep(5) # Works in parallel.
# bytewax.sleep_release_gil(5) # Works in parallel.
bytewax.sleep_keep_gil(5) # Does not.
print("stop slow")
return x
def busy(x):
print("start busy")
y = 0... | StarcoderdataPython |
5056391 | <filename>apps/single_cam_detector/scripts/publish_event.py
#!/bin/bash
import redis
import time
HOST = 'localhost'
PORT = '6379'
CHANNEL = 'motion-detection-channel'
if __name__ == '__main__':
r = redis.Redis(host=HOST, port=PORT)
pub = r.publish(
channel=CHANNEL,
message='Motion detected!'
... | StarcoderdataPython |
6445567 | """
Unit testing of the piserverstatusd.py module
To run:
nosetests -s test_piserverstatusd.py
"""
import unittest
import piserverstatusd
class PiServerStatusdTestCase(unittest.TestCase):
def setUp(self):
self.daemon = piserverstatusd.StatusDaemon('/tmp/test_piserverstatusd.pid')
def test_mps_to_k... | StarcoderdataPython |
11328681 | <reponame>jfroche/groovylint
#!/usr/bin/env python3
#
# Copyright (c) 2019 Ableton AG, Berlin. All rights reserved.
#
# Use of this source code is governed by a MIT-style
# license that can be found in the LICENSE file.
"""A script to download JAR file dependencies for run_codenarc.py."""
import argparse
import loggi... | StarcoderdataPython |
5034712 | #
# PyANC350v4 example file
# by <NAME>, adapted from pyanc-example.py by <NAME>
#
from pyanc350.v4 import discover, Positioner
import time
ax = {'x': 0, 'y': 1, 'z': 2}
# define a dict of axes to make things simpler
dev_count = discover()
if dev_count != 0:
anc = Positioner(0)
# instantiate positioner as... | StarcoderdataPython |
1959349 | class EventCounter(object):
def __init__(self):
self._active_counts = dict()
self._active_counts_meta = dict()
def event(self, segment_name, meta = None):
if segment_name not in self._active_counts:
self._active_counts[segment_name] = 0
self._active_counts[segment_name] += 1
if meta is no... | StarcoderdataPython |
5098799 | <gh_stars>0
by <NAME> Telegram: @AhmedoPlus
x-x-x ACCOUNT: <EMAIL>:Bubbles12
---CheckTime: 2021/02/14 03:13 AM
---ONLINE ID: JamesJonBerry
---COUNTRY: GB
---DATEOFBIRTH: 1994-08-18
---DEACTIVATION: Yes
---DEVICES: PS4[1]
---PLAYSTATION PLUS: PlayStation Plus: 12 Month Membership [12/30/2021]
---PAYMENT METHODS: [VISA ... | StarcoderdataPython |
3581864 | from collections import OrderedDict
try:
from urllib.parse import urlunparse
from urllib.parse import urlparse
from urllib.parse import quote_plus
from .ezurllib import urlencode
except ImportError:
from urlparse import urlunparse
from urlparse import urlparse
from urllib import quote_plus
... | StarcoderdataPython |
9693978 | <reponame>benety/mongo
"""Test hook for cleaning up data files created by the fixture."""
import os
from buildscripts.resmokelib.testing.hooks import interface
class CleanEveryN(interface.Hook):
"""Restart the fixture after it has ran 'n' tests.
On mongod-related fixtures, this will clear the dbpath.
"... | StarcoderdataPython |
3467926 | <filename>yatube/core/context_processors/year.py
import datetime as dt
def year(request):
"""Создаём переменную, которая будет показывать текущий год."""
return {
'year': int(dt.date.today().strftime('%Y'))
}
| StarcoderdataPython |
1631254 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
Module that contains console widgets
"""
from __future__ import print_function, division, absolute_import
import logging
from io import StringIO
from Qt.QtCore import Qt, QSize, QStringListModel
from Qt.QtWidgets import QSizePolicy, QLineEdit, QTextEdit, QCompleter... | StarcoderdataPython |
6502179 | from copy import deepcopy
from models_old.variable import Variable
from models_old.restriction import Restriction
from models_old.linear_model import LinearModel
from models_old.base_finder import InitialBaseFinder
from models_old.internal.simplex_solver import SimplexSolver
class Simplex:
def __init__(self, line... | StarcoderdataPython |
8034488 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | StarcoderdataPython |
5045036 | <gh_stars>10-100
from panini import app as panini_app
from panini.middleware.nats_timeout import NATSTimeoutMiddleware
app = panini_app.App(
service_name="async_nats_timeout_middleware",
host="127.0.0.1",
port=4222,
)
log = app.logger
message = {
"key1": "value1",
"key2": 2,
"key3": 3.0,
... | StarcoderdataPython |
1964705 | <gh_stars>10-100
from niaaml import Pipeline
from niaaml.classifiers import MultiLayerPerceptron
from niaaml.preprocessing.feature_selection import VarianceThreshold
from niaaml.preprocessing.feature_transform import Normalizer
from niaaml.data import CSVDataReader
from niaaml.preprocessing.encoding import encode_categ... | StarcoderdataPython |
11321733 | <filename>detect_ai/detect_color.py
# import the necessary packages
import numpy as np
import cv2
# input image path
imagePath = '../demo_image/colordemo.png'
image = cv2.imread(imagePath)
boundaries = {'B': ([0, 0, 0], [255, 0, 0]),
'G': ([0, 0, 0], [0, 255, 0]),
'R': ([0, 0, 0], [0, 0,... | StarcoderdataPython |
225814 | # Copyright 2021 Spotify AB
#
# 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, so... | StarcoderdataPython |
9630462 | import praw
from psaw import PushshiftAPI
import pandas as pd
import time
import datetime as dt
import json
import json
with open('data//subreddits.json') as json_file:
data = json.load(json_file)
subreddit_list=list(data.keys())
start_epoch=int(dt.datetime(2019, 4, 23).timestamp())
api = PushshiftAPI()... | StarcoderdataPython |
6567832 | import abc
import random
class Distribution(abc.ABC):
@abc.abstractmethod
def sample(self):
pass
class Uniform(Distribution):
def __init__(self, low: float, high: float):
self.low = low
self.high = high
def sample(self):
return random.uniform(self.low, self.high)
cl... | StarcoderdataPython |
246175 | <filename>setup.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
The setup script for the calibraxis package.
.. moduleauthor:: hbldh <<EMAIL>>
Created on 2016-04-08
'''
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
import os
import sys
import re
f... | StarcoderdataPython |
8148968 | <filename>openacademy/reports/__init__.py
from . import courses_report
| StarcoderdataPython |
6493249 | <filename>Old Releases/Windows Releases/WINDOWS v1.1.0/Source Code/Windows Development/MandarinInstaller.py
import subprocess
subprocess.call([r'INSTALLER.bat'])
| StarcoderdataPython |
1929742 | <gh_stars>0
"""A library to organize your terminal output.
https://github.com/markuskimius/screen-py
"""
import os
import sys
__copyright__ = "Copyright 2019 <NAME>"
__license__ = "Apache 2.0"
##############################################################################
# UTILITIES
class Terminal(object):
__... | StarcoderdataPython |
8011478 | """
Modules that implement a Cape Explanation
"""
| StarcoderdataPython |
1765364 | <filename>pyxform/tests_v1/test_warnings.py
from pyxform.tests_v1.pyxform_test_case import PyxformTestCase
class TestWarnings(PyxformTestCase):
def test_l1(self):
self.assertPyxformXform(
name="test_l1",
md="""
| survey | | | |
... | StarcoderdataPython |
8094848 | import discord
from discord.ext import commands
from characterRecord import *
class Sheets(commands.Cog):
"""Commands related to character sheets"""
def __init__(self, bot):
self.bot = bot
@commands.command(brief = "Create new sheet", description = "Create an empty character sheet")
async def ... | StarcoderdataPython |
293994 | <gh_stars>10-100
import pandas as pd
from yellowbrick.classifier import ThreshViz
from sklearn.linear_model import LogisticRegression
if __name__ == '__main__':
# Load the data set
data = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/spambase/spambase.data', header=None)
data.ren... | StarcoderdataPython |
1943742 | <filename>lambda_functions/analyzer/binary_info.py
"""Keeps track of all information associated with and computed about a binary."""
import os
import subprocess
import tempfile
import time
from typing import Any, Dict, List, Set
import uuid
from lambda_functions.analyzer import analyzer_aws_lib, file_hash
from lambda_... | StarcoderdataPython |
8031970 | from baseDatabaseManager import BaseDatabaseManager
class ProductManager():
@staticmethod
def deleteProductFromBasket(productId, customerId):
BaseDatabaseManager.databaseType.deleteProductFromBasket(productId, customerId)
@staticmethod
def getProductDetails(productId):
productDetails=... | StarcoderdataPython |
1799574 | <gh_stars>1-10
"""
Copyright 2017 Neural Networks and Deep Learning lab, MIPT
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 appl... | StarcoderdataPython |
11224635 | <reponame>Kelos-Zhu/pyleecan
# -*- coding: utf-8 -*-
from os import remove, getcwd
from os.path import isfile, join
import pytest
from unittest.mock import patch # for unittest of input
from numpy import ones, pi, array
from pyleecan.Classes.LamSlotMag import LamSlotMag
from pyleecan.Classes.LamSlotWind import LamS... | StarcoderdataPython |
1986770 | import streamlit as st
import amplitude
import utils
import loader
import bisect
import random
import plotly as plt
import plotly.express as px
import plotly.graph_objects as go
import numpy as np
import math
import os
import pandas as pd
import session
import urllib.parse
DO_IT_BY_RANGE = (
True # DEFINES IF WE ... | StarcoderdataPython |
1855950 | <reponame>SamuelMarks/enforce
import typing
import unittest
from enforce import runtime_validation, config
from enforce.exceptions import RuntimeTypeError
class DictTypesTests(unittest.TestCase):
"""
Tests for the dictionary types
"""
def test_simple_dict(self):
"""
Verifies that unr... | StarcoderdataPython |
9654005 | import argparse
import json
import re
import operator
from datetime import datetime
import dateutil
import colorama
import difflib
from . import exceptions
from . logger import logger
from . safe_print import safe_print
from . import aws as aws_lib
from collections import OrderedDict
from difflib import SequenceMatcher... | StarcoderdataPython |
9669512 | <filename>src/epivizquindex/sample.py
import QuadTree
import EpivizQuindex
genome = {
"chr1": 249250621,
"chr10": 135534747,
"chr11": 135006516,
"chr12": 133851895,
"chr13": 115169878,
"chr14": 107349540,
"chr15": 102531392,
"chr16": 90354753,
"chr17": 81195210,
"chr18"... | StarcoderdataPython |
1836502 | # Interface for The Number Graph.
# Initial IDs:
# Thread: 2dwxho
# Comment: cju11n6
import praw
# PRAW Initialisation
r = praw.Reddit(user_agent='the-number-graph by /u/glider97')
f1 = open("latest.txt", 'r') # latest.txt stores the ids of the last comment and thread used.
latest = f1.read().split('\n') # They ... | StarcoderdataPython |
1864469 | <reponame>adoublebarrel/curriculum-vitae
import base
import json
import logging
from google.appengine.ext import ndb
from server.models.skill import Skill
class TechSkillsHandler(base.BaseHandler):
def get(self):
self.data['content'] = 'Technical Skills'
template = base.template_engine.get_template... | StarcoderdataPython |
1819046 | <filename>UServer/database/db9.py
import redis
from config import RedisHost, RedisPasswd, RedisPort
class ConstDB9:
released_addr = 'RELEASED_ADDR'
current_block = 'CUR_BLOCK'
current_num = 'CUR_NUM'
block = 'BLOCK:'
db9 = redis.StrictRedis(host=RedisHost, port=RedisPort, db=9, password=<PASSWORD>) | StarcoderdataPython |
8136127 | <filename>pandoctools/pandoctools_resolve/resolve.py
import sys
import os
import os.path as p
import click
from ..shared_vars import (pandoctools_user, pandoctools_user_data, pandoctools_core,
PandotoolsError, bash_cygpath)
def main(basename: str, fallback_basename: str=None) -> str:
""... | StarcoderdataPython |
5050690 | <reponame>fanteastick/ML-SKI
# importing
from sklearn import linear_model
from sklearn.linear_model import LinearRegression
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
from statistics import me... | StarcoderdataPython |
11325888 | # Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is govered by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd
"""Constants that define the Monorail URL space."""
# URLs of site-wide Monorail pages
HOSTING_... | StarcoderdataPython |
3250064 | <gh_stars>1-10
from typing import List
import click
import inject
from mycloud.commands.shared import async_click, authenticated
from mycloud.drive import DriveNotFoundException, FsDriveClient
@click.command(name='download')
@click.argument('remote')
@click.argument('local')
@authenticated
@inject.params(client=FsD... | StarcoderdataPython |
11211254 |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def calculateABCsaving(p: float, q: float, D_parts: pd.DataFrame):
"""
Calculate the saving based on re-assignment with classes ABC, compared with a random assignment scenario
Args:
p (float): warehouse front length in meters... | StarcoderdataPython |
6606134 | #!/usr/bin/env python
import sys
import cv2
import numpy as np
import matplotlib.pyplot as plt
import copy
import sift
class Circle_Detect:
def __init__(self, image):
self.image = image
self.dp = 1
self.minDist = 20
self.param1 = 50
self.param2 = 30
self.minRad... | StarcoderdataPython |
6516373 | <reponame>abosoar/camel_tools
# -*- coding: utf-8 -*-
# MIT License
#
# Copyright 2018-2020 New York University <NAME>
#
# 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, ... | StarcoderdataPython |
12826153 | <gh_stars>10-100
# pyflyby/test_modules.py
# License for THIS FILE ONLY: CC0 Public Domain Dedication
# http://creativecommons.org/publicdomain/zero/1.0/
from __future__ import (absolute_import, division, print_function,
with_statement)
import logging.handlers
from pyflyby._file ... | StarcoderdataPython |
1671507 | from django.db import models
class DatabaseMaintenanceTaskManager(models.Manager):
use_for_related_fields = True
def need_retry(self, **kwargs):
""" This method checks wheather a maintenance task needs retry or not.
It returns the task itself or False when there's no task that have
fa... | StarcoderdataPython |
11283463 | <filename>FaceMaskDetection/facemaskdetection.py
# -*- coding: utf-8 -*-
"""FaceMaskDetection.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1lDfb32EUzTnnK_57UtD5l3Q_tEF3ITpg
"""
# Commented out IPython magic to ensure Python compatibility.
"""... | StarcoderdataPython |
93087 | import os
import shutil
import numpy as np
import mxnet as mx
from mxnet import gluon
from mxnet.gluon import nn
from mxnet import autograd as ag
def train_one_epoch(epoch, optimizer, train_data, criterion, ctx):
train_data.reset()
acc_metric = mx.metric.Accuracy()
loss_sum = 0.0
count = 0
... | StarcoderdataPython |
11250446 | <reponame>behnazkhoshnood/boutique_ado_v1
from django.test import TestCase
from .forms import ContactForm
class TestContactForm(TestCase):
def test_email_is_requered(self):
form = ContactForm({'email': ''})
self.assertFalse(form.is_valid())
self.assertIn('email', form.errors.keys())
... | StarcoderdataPython |
11352728 | <filename>repokid/filters/utils.py
from typing import Optional
from repokid import CONFIG
from repokid.filters import FilterPlugins
from repokid.types import RepokidConfig
def get_filter_plugins(
account_number: str, config: Optional[RepokidConfig] = None
) -> FilterPlugins:
config = config or CONFIG
pl... | StarcoderdataPython |
11384029 | import pandas
import gym
import numpy as np
from sklearn.preprocessing import LabelEncoder
from keras.utils import np_utils
import tensorflow as tf
from tensorflow import keras
import os
currentDirectory = os.getcwd().replace('\\', '/')
datasetDirectory = currentDirectory.replace('/supervised-learning', '')
dataframe... | StarcoderdataPython |
4852182 | import bisect
def make_primes(n: int) -> list:
is_prime = [False, False] + ([True] * (n + 1))
for i in range(2, int(n**0.5) + 1):
if not is_prime[i]: continue
for j in range(i * 2, n + 1, i):
is_prime[j] = False
return [i for i in range(n + 1) if is_prime[i]]
X = int(input()... | StarcoderdataPython |
1939982 | <filename>CS2/7200_RPG_turn_based_battle/main.py
import pygame, sprite, colors, game_manager
pygame.init()
screen_width = 1200
screen_height = 700
screen = pygame.display.set_mode((screen_width,screen_height))
clock = pygame.time.Clock()
gm = game_manager.GameManager(screen)
#Draw all images on the screen
done = Fa... | StarcoderdataPython |
3536593 | <gh_stars>1-10
import os
from random import randint
import shutil
from myhdl import *
from rhea.models.usbext import Fx2Model
from rhea.models.usbext.fx2 import slave_fifo
from rhea.utils.test import run_testbench
# The Fx2Model has two config modes. The actual FX2 controller has
# numerous programmable modes. Th... | StarcoderdataPython |
310284 | <filename>SW_lab/sw_lab_part4/servizio_mail/shell_utility_main.py
#!/usr/bin/env python3
"""
Exercise1 sw_lab4
:author: <NAME>, <NAME>
:copyright: Copyright 2020, <NAME>, <NAME>
..
Copyright 2020 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compl... | StarcoderdataPython |
6534376 | from sqlalchemy import false, true
from api.extensions import mongo as db
from api.service import list_users
from api.service import update_balance as service
from flask import Response
import json
def create_new_transaction(transaction):
response = db.create_transaction(transaction)
return response
def upd... | StarcoderdataPython |
6583554 | <filename>importers/iff.py
import psycopg2
import psycopg2.extras
from datetime import datetime
import md5
from copy import deepcopy
cache = {}
def getFakePool(conn,stopbegin,stopend):
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
cur.execute("""
SELECT
%s as privatecode,
1 as pointorder,
l... | StarcoderdataPython |
6640599 | <reponame>jayconrod/rules_go<filename>go/private/binary.bzl<gh_stars>0
# Copyright 2014 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://w... | StarcoderdataPython |
11300487 | <filename>blog/app/views.py
# coding=utf-8
from flask import Flask, url_for, render_template, request, redirect
import models
app = Flask(__name__)
@app.route('/')
@app.route('/<id>')
def hello_world(id=None):
full = request.args.get('full', False)
if request.method == 'GET':
pass
elif resquest.met... | StarcoderdataPython |
12852825 | from typing import *
import collections
import copy
import hashlib
import math
import numpy as np
from pathlib import Path
import random
import re
from tqdm import tqdm
import traceback
import sys
from seutil import LoggingUtils, IOUtils, BashUtils
from seutil.project import Project
from roosterize.data.CoqDocument ... | StarcoderdataPython |
5191183 | #!/usr/bin/env python
"""
A pygame program to show a slideshow of all images buried in a given directory.
Originally Released: 2007.10.31 (Happy halloween!)
"""
import argparse
import os
import stat
import sys
import time
import pygame
from pygame.locals import QUIT, KEYDOWN, K_ESCAPE
file_list = [] # a list of al... | StarcoderdataPython |
11215840 | '''
A utility function such that you can test/train in-air controls without ever landing.
'''
import time
from bot_code.trainer.utils.floating_setup import bakkes
from random import random
# Calling bakkesmod too often may cause a crash.
# Therefore ratelimit it by dropping some calls.
MIN_DELAY_BETWEEN_BAKKES_CALLS ... | StarcoderdataPython |
11249803 | <reponame>Algy/pipex
import time
import numpy as np
from PIL import Image
from base64 import b64encode
from typing import Dict, Any
from html import escape
id_func = id
def repr_image(value):
buffer = value._repr_png_()
src = "data:image/png;base64," + b64encode(buffer).decode()
return "<img src='{}' sty... | StarcoderdataPython |
4938484 | <reponame>heyrict/cindy-realtime<gh_stars>1-10
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sui_hei', '%s'),
]
... | StarcoderdataPython |
11252020 | import sys
read = sys.stdin.readline
for _ in range(3):
s = 0
for _ in range(int(read())):
s += int(read())
if s > 0:
print('+')
elif s < 0:
print('-')
else:
print(0)
| StarcoderdataPython |
5011154 | import pytest
from serializers.property import PropertySerializer
from utils.time import Time
@pytest.mark.usefixtures("empty_test_db")
class TestPropertySerializer:
def test_serializer(self, create_property):
property = create_property()
assert PropertySerializer.serialize(property) == {
... | StarcoderdataPython |
200948 | <filename>superinvoke/collections/misc.py
from invoke import task
@task(variadic=True)
def help(context, collection):
"""Show available commands."""
context.run(f"invoke --list {collection}")
| StarcoderdataPython |
157985 | <reponame>zhongxixixixi/myblog-Flask
from flask import Flask, render_template, request, redirect, url_for, session
import config
from exts import db
from models import User, Question, Comment
from decorators import login_required
app = Flask(__name__)
app.config.from_object(config)
db.init_app(app)
@app.route('/')
... | StarcoderdataPython |
4892359 | <gh_stars>0
import cv2
import numpy as np
import copy
def reshape_image(image):
'''归一化图片尺寸:短边400,长边不超过800,短边400,长边超过800以长边800为主'''
width, height = image.shape[1], image.shape[0]
min_len = width
scale = width * 1.0 / 400
new_width = 400
new_height = int(height / scale)
if new_height > 800:
... | StarcoderdataPython |
1999929 | <reponame>supaflysnooka/whispers<gh_stars>0
from pathlib import Path
from whispers.utils import strip_string
class Htpasswd:
def pairs(self, filepath: Path):
for line in filepath.open("r").readlines():
if ":" not in line:
continue
creds = line.split(":")
... | StarcoderdataPython |
9636118 | import pandas as pd
from datetime import date, datetime, timedelta, timezone
######################################################
XLSX_PATH = 'wk16.xlsx'
ICAL_PATH = 'export.ics'
day_one = date(2021, 12, 13)
classes = [
'AP Psychology-Class 1',
'ACT1',
'AP Environmental Science',
'FAP1',
'AP P... | StarcoderdataPython |
1831221 | # Allow from hapiplotserver import hapiplotserver
from hapiplotserver.hapiplotserver import hapiplotserver
| StarcoderdataPython |
6441710 | <reponame>biomicrodev/broadside
import logging
from pathlib import Path
from typing import List, Any, Tuple
from natsort import natsort_keygen
from qtpy.QtCore import QAbstractTableModel, QModelIndex, Qt, QAbstractItemModel
from qtpy.QtWidgets import (
QTableView,
QAbstractItemView,
QHeaderView,
QWidge... | StarcoderdataPython |
3238621 | <gh_stars>100-1000
import theano
import theano.tensor as T
import numpy as np
# predictions is the argmax of the posterior
def accuracy_instance(predictions, targets, n=[1, 2, 3, 4, 5, 10], \
nb_classes=5, nb_samples_per_class=10, batch_size=1):
accuracy_0 = theano.shared(np.zeros((batch_size, nb_samples_... | StarcoderdataPython |
28113 | <filename>tensorflow/python/keras/distribute/mnist_multi_worker.py<gh_stars>1-10
# Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
... | StarcoderdataPython |
6530528 | <gh_stars>0
# -*- coding: utf-8 -*-
"""
------------------------------------
@Project : interfaceTest
@Time : 2021/3/8 14:16
@Auth : wrc
@Email : <EMAIL>
@File : test_login.py
@IDE : PyCharm
------------------------------------
"""
import allure
from api_doc.apis import Login
from common.Init import ru... | StarcoderdataPython |
79406 | import argparse
import base64
import binascii
import json
import msgpack
import sys
__version__ = "0.0.1"
ACTION_VALIDATE = "validate"
ACTION_DECODE = "decode"
actions = (ACTION_DECODE, ACTION_VALIDATE)
parser = argparse.ArgumentParser(description='python msgpack native formatter %s' % __version__)
parser.add_argum... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.