id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
392267 | # -*- coding: utf-8 -*-
# Copyright 2010-2014, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this... | StarcoderdataPython |
9715467 | """
mnist_svm
~~~~~~~~~
A classifier program for recognizing handwritten digits from the MNIST
data set, using an SVM classifier."""
#### Libraries
# My libraries
import mnist_loader
# Third-party libraries
from sklearn import svm
def svm_baseline():
training_data, validation_data, test_data = mnist_loader.lo... | StarcoderdataPython |
9618978 | # Generated by Django 2.0.2 on 2018-03-04 18:16
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('topi... | StarcoderdataPython |
8100069 | <filename>sketches/krzywizna-calki.py
#!/usr/bin/env python
# coding: utf-8
import matplotlib.pyplot as plt
import latexrc
from numpy import linspace
from numpy import sqrt, cos, arccos, exp
#-------------------------------------------------------------------------------
# parameters
R = 6371.0
H = R / 50
Hscale = R... | StarcoderdataPython |
352472 | import socket, cfg, time, subprocess
from threading import Thread
from modules.show_banner import *
from modules.clear_screen import *
from modules.socket_listener import *
from modules.cleanup_code import *
cfg.global_variables()
def listener_console():
while True:
try:
input = ... | StarcoderdataPython |
8107934 | <reponame>AndreaGuarracino/bh20-seq-resource
#! /usr/bin/env python3
#
# Check for updates on Arvados, pull the TTL and
# push into Virtuoso
#
# You can run this in a Guix container with
#
# ~/opt/guix/bin/guix environment -C guix --ad-hoc python python-requests curl --network -- python3 ./scripts/update_virtuoso/chec... | StarcoderdataPython |
11234117 | <filename>pyhybro/__init__.py
from pyhybro.optimizer_base import OptimizerBase
from pyhybro.problem import Problem
from pyhybro.OptimizationResult import OptimizationResult, ReferenceSet
| StarcoderdataPython |
6599566 | <gh_stars>1-10
# The framework was adapted from https://github.com/theislab/dca/blob/master/dca/network.py
import numpy as np
import os
import pickle
import tensorflow as tf
from tensorflow.keras.layers import Input, Dense, Dropout, Lambda, Concatenate
from tensorflow.keras import Model
from tensorflow.keras.regulari... | StarcoderdataPython |
390146 | <filename>tests/urlpatterns_reverse/urls.py<gh_stars>1-10
from django.conf.urls import include, url
from .views import (
absolute_kwargs_view, defaults_view, empty_view, empty_view_partial,
empty_view_wrapped, nested_view,
)
other_patterns = [
url(r'non_path_include/$', empty_view, name='non_path_include'... | StarcoderdataPython |
5051145 |
import sys
import os
import time
import string
import re
import time
import shutil
from mimetypes import types_map
from urllib import quote, unquote
from resources.markup import *
APP_ROOT, file_name = os.path.split(os.path.abspath(__file__))
TEMPLATES = os.path.join(APP_ROOT, "resources", "TEMPLATES")
... | StarcoderdataPython |
5017510 | #!/usr/bin/python3
"""
For creating SVG code from a tikz diagram
"""
import find_block
import os
import subprocess
import nowiki_block
class TikzDiagramException(Exception):
def __init__(self, message):
super().__init__(message)
def tikz_diagram_processor(tikz_diagram):
tikz_diagram = (
"\\b... | StarcoderdataPython |
6416795 | <filename>utls/add_exon_average_expression.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Add average expression level of each exon to each variant
1. Exon expression level file:
/groups/umcg-bios/prm02/projects/expression/combined_exon_count_run_1_passQC.TMM.txt.gz
2. Use the mean of all samples in the file.... | StarcoderdataPython |
6424921 | from tkinter import *
from tkinter import ttk
from tkinter import messagebox
import tobjcreator as tobjcreator
import os
import sys
def create(*args):
if not os.path.exists(source_tobj.get()):
messagebox.showerror("Error","Source TOBJ file doesn't exist.")
elif len(dds_path.get()) > 255:
messagebox.showerror("Er... | StarcoderdataPython |
3580533 | <filename>11_python-data-science-toolbox-(part-2)/1-using-iterators-in-pythonland/06_using-zip.py
'''
06 - Using zip
Another interesting function that you've learned is zip(), which takes any number of
iterables and returns a zip object that is an iterator of tuples. If you wanted to print
the values of a zip object,... | StarcoderdataPython |
9717955 | <reponame>Jatin-Madaan/Raspberrypi3
# show the temperature of processor on thinkspeak pi3 B+
import http.client
import urllib
import sys
import time as t
sleep = 5
key = '<KEY>'
def temperature():
while True:
temp = int(open('/sys/class/thermal/thermal_zone0/temp').read())
temp = temp / 1000
... | StarcoderdataPython |
11336760 | import argparse
import random
import torch
from dqn.agent import DQNAgent
from dqn.replay_buffer import ReplayBuffer
from dqn.wrappers import *
def parse_args():
parser = argparse.ArgumentParser("DQN experiments for Atari games")
parser.add_argument("--seed", type=int, default=42, help="which seed to use")
... | StarcoderdataPython |
4810659 | <filename>cocoLRPapi-master/PythonAPI/evalDemoLRP.py
import os
from pycocotools.coco import COCO
from pycocotools.cocoevalLRP import COCOevalLRP
# from boxmapDist import calc_boxmap_FP_FN
def calc_LRP(algorithm,tau=0.50):
#initialize COCO ground truth api
annFile = os.path.join('./','LRP','output',algorithm,"target... | StarcoderdataPython |
3325819 | import json
import logging
import aiohttp
from expiringdict import ExpiringDict
from datetime import datetime, timedelta
from .const import (
DEFAULT_DATA_CACHE_SECONDS,
DEFAULT_NAS_LANGUAGE,
DEFAULT_PROTOCOL,
LINKSTATION_API_ACTION_PARAM_NAME,
LINKSTATION_API_AUTH_REPONSE_PAGEMODE,
LINKSTATION... | StarcoderdataPython |
1832961 | <filename>DB_api.py<gh_stars>0
# -*- coding: utf-8 -*-
#working for Python 2.7.17
"""
Comment: API for interaction with the Deutsch Bahn REST APIs
Special: You HAVE TO subscribe to the chosen "sub-APIs" for all methods to work
"""
__author__ = "<NAME>"
__maintainer__ = "<NAME>"
__version__ = "0.0.1"
__status__... | StarcoderdataPython |
1838030 | <gh_stars>1-10
import numpy as np
from timeit import default_timer as timer
import torch.nn as nn
import torch
from torch import optim
import pandas as pd
class trainer():
def __init__(self, model, params):
"""
"""
# Set model.
self.model = model
# Se... | StarcoderdataPython |
3252854 | from django import forms
from .models import Comment, RacerProfile
class AddCommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('racer', 'comment_type', 'text')
labels = {
'comment_type': ('Choose the type of your comment'),
'text': ('Enter your comm... | StarcoderdataPython |
212987 | <reponame>brigitteunger/katas
import unittest
class Solution:
def lengthOfLastWord(self, s: str) -> int:
if not s:
return 0
s = s.rstrip()
words = s.split(' ')
return len(words[-1])
class TestLengthOfLastWord(unittest.TestCase):
def setUp(self):
self.sol =... | StarcoderdataPython |
3205336 | <gh_stars>0
from turtle import Turtle
MOVE_DISTANCE = 20
class Paddle(Turtle):
def __init__(self, paddle_side):
super().__init__()
self.penup()
self.shape("square")
self.shapesize(stretch_wid=5, stretch_len=1)
self.color("white")
self.paddle_side = paddle_side.low... | StarcoderdataPython |
3437650 | <reponame>factorlibre/web_action_request
from openerp import models, fields, api
class Setting(models.TransientModel):
_name = 'web.action.request.setting'
_description = 'test the request'
_inherit = 'res.config.settings'
action = fields.Many2one('ir.actions.act_window', required=True)
user = fi... | StarcoderdataPython |
1707485 | <filename>tests/test_middleware.py
import logging
from io import BytesIO
from wsgiref.util import setup_testing_defaults
from pytest import fixture
from .context import WSGIListenerMiddleware, DEFAULT_LISTENER_LOG_NAME
@fixture
def environ_factory():
def _environ_factory(**kwargs):
environ = dict(kwargs)... | StarcoderdataPython |
8189479 | <filename>api/authorization_endpoint.py
#
# Copyright (C) 2019-2021 Authlete, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unles... | StarcoderdataPython |
1680583 | from download_file_if_not_exists import download_files_if_not_exist
# Disclaimer: This script is called by qmake or CMake. It is not necessary to call it manually.
# Download all the assets as .zip files from meshes.mailbase.info, unzips them, moves them in assets/*, and finally removes the .zip files.
# Already down... | StarcoderdataPython |
4874653 | <filename>habitat/tasks/rearrange/sub_tasks/reach_sensors.py
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from habitat.core.embodied_task import Measure
from habitat... | StarcoderdataPython |
6511935 | from ExcelToSQL import ExcelToSQL as esql
esql()
# excToSQL.TakeUserRequirements()
# excToSQL.CheckWhichOperationToRun() | StarcoderdataPython |
11237742 | <filename>boards/ZCU111/rfsoc_qpsk/drivers/qpsk_overlay.py
from pynq import Overlay
import xrfclk
import xrfdc
import os
import numpy as np
import ipywidgets as ipw
from rfsoc_qpsk import dma_timer, sdr_plots, qpsk_rx, qpsk_tx
class TimerRegistry():
"""Helper class to track active timer threads.
This can be... | StarcoderdataPython |
3234590 | #
# Verified
#
from manimlib.imports import *
# Helpers
def get_shadow(mobject, opacity=0.5):
result = mobject.deepcopy()
result.apply_function(lambda p: [p[0], p[1], 0])
color = interpolate_color(
mobject.get_fill_color(), BLACK,
mobject.get_fill_opacity()
)
# color = BLACK
re... | StarcoderdataPython |
4884751 | <reponame>jenningsm42/mini-mmo-server
from server.server import register_handler
from server.message_type import MessageType
from server.message import Message
from server.proto.PlayerJoin_pb2 import (
PlayersResponse, JoinRequest, PlayerJoin)
from server.service.player import PlayerService
from server.service.cha... | StarcoderdataPython |
1980502 | <filename>src/reader/test_cases/test_perseus_import_lexicon.py
from xml.dom.minidom import parseString
from . import TestReader
from reader.importer.Perseus import PerseusTextImporter
from reader.models import Division, Verse
from reader.importer.batch_import import ImportTransforms
from reader.importer.Lexicon import ... | StarcoderdataPython |
6626874 | import os
import numpy as np
import argparse
import json
import torch
import cv2
import scipy.io as sio
import matplotlib.pyplot as plt
import sys
sys.path.append('..')
import PnP
import models
def parse_arguments():
parser = argparse.ArgumentParser(description='PyTorch Training')
parser.add_argument('--confi... | StarcoderdataPython |
9641715 | """This module implements a PDT distribution sub-class using a Gaussian mixture model
"""
import os
import sys
import numpy as np
from scipy.stats import rv_continuous
from scipy import integrate as sciint
from scipy import interpolate as sciinterp
from qp import sparse_rep
from qp.factory import add_class
from qp.inte... | StarcoderdataPython |
1806294 | from django.conf import settings
from django.contrib.auth.mixins import LoginRequiredMixin as OrigLoginRequiredMixin
from django.contrib.auth.views import LoginView as OrigLoginView
from django.contrib.auth.views import LogoutView # noqa F401
from django.db.models import fields as model_fields
from django.shortcuts im... | StarcoderdataPython |
3585038 | <reponame>mahidharc/iudx-auth-server<filename>test/test-auth.py
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
import os
from init import consumer
from init import provider
from init import resource_server
from init import expect_failure
RS = "iisc.iudx.org.in"
expect_failure(True)
r = consumer.get_policy... | StarcoderdataPython |
3229368 | import datetime
from uuid import uuid4
from typing import Set
from fastapi import FastAPI, Security
from fastapi.testclient import TestClient
from pytest_mock import MockerFixture
from fastapi_jwt import JwtAccessBearer, JwtAuthorizationCredentials, JwtRefreshBearer
app = FastAPI()
access_security = JwtAccessBearer... | StarcoderdataPython |
9780056 | <reponame>fernandezc/spectrochempy_gui
import os
from ..Qt import QtCore, QtGui
from ..python2_3 import asUnicode
from .Parameter import Parameter, registerParameterType
from .ParameterItem import ParameterItem
from ..widgets.SpinBox import SpinBox
from ..widgets.ColorButton import ColorButton
from ..colormap import Co... | StarcoderdataPython |
5079291 | <reponame>fortyninemaps/karta
import unittest
import os.path
import numpy as np
from test_helper import TMPDATA
import karta
from karta.raster import _gdal
class GdalTests(unittest.TestCase):
def test_numpy_type_coercion(self):
self.assertEqual(_gdal.numpy_dtype(2), np.uint16)
self.assertEqual(_g... | StarcoderdataPython |
6457419 | from pydantic import Field, BaseModel
from typing import Optional
from datetime import datetime
class WeekSave(BaseModel):
"""设备每周节能率模型
上周最后一条和本周最后一条累积数差值
"""
# 设备序列号
serial_number: str = Field('', title="设备序列号")
# 周节能率的最后一天
log_date: str = Field('', title="结束日期")
prev_time: Option... | StarcoderdataPython |
6494269 | <filename>test/test_preprocessor.py
"""
.. codeauthor:: <NAME> <<EMAIL>>
"""
import pytest
from dataproperty import LineBreakHandling, Preprocessor
class Test_Preprocessor_update:
def test_normal(self):
preprocessor = Preprocessor()
assert preprocessor.strip_str is None
assert preprocess... | StarcoderdataPython |
11354383 | # -*- coding: utf-8 -*-
# Author: XuMing <<EMAIL>>
# Data: 17/10/16
# Brief:
config = {
"qa_examples_file": "../data/qa.examples.train.e2e.top10.filter.tsv",
"word_embeddings_file": "../data/word_embedding/glove.6B.100d.txt",
"vocabulary_size": 400000,
"embedding_size": 100,
"num_classes": 6,
"... | StarcoderdataPython |
11304612 | <gh_stars>0
from __future__ import print_function
from functools import partial
from urllib.request import urlretrieve
import pandas as pd
import torch
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
# hyper-opt
from ... | StarcoderdataPython |
4952878 | # Generated by Django 3.1.3 on 2020-12-02 21:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0008_auto_20201130_2256'),
]
operations = [
migrations.AddField(
model_name='unemploymentbyindustry',
name='... | StarcoderdataPython |
1636458 | # Generated by Django 3.1.13 on 2021-12-10 11:04
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("covid_cases", "0001_initial"),
]
operations = [
migrations.CreateModel(
name="SACoronavirusCounter",
... | StarcoderdataPython |
9693142 | <filename>Machine Learning Projects/Speech Controlled LED/speech_led.py
import os
import time
import playsound
import speech_recognition as sr
from gtts import gTTS
import serial
import time
ser = serial.Serial('COM4', 9600)
print(ser.open().value())
text=input("Enter which led should be turned on GREEN /RED... | StarcoderdataPython |
9653177 | import torch as th
from torch.utils.data import Dataset
import pandas as pd
import os
import numpy as np
import ffmpeg
class VideoLoader(Dataset):
"""Pytorch video loader."""
def __init__(
self,
csv,
framerate=1,
size=112,
centercrop=False,
):
... | StarcoderdataPython |
8051036 | <filename>mindspore/python/mindspore/_extends/graph_kernel/expanders/maximum_grad.py
# Copyright 2020-2022 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
#
# htt... | StarcoderdataPython |
3222760 | import datetime
import django.test
from django.utils import timezone
from ftc.models import Organisation, OrganisationType, Scrape, Source
class TestCase(django.test.TestCase):
def setUp(self):
ot = OrganisationType.objects.create(title="Registered Charity")
ot2 = OrganisationType.objects.create... | StarcoderdataPython |
1790912 | def mailbox_data():
return [
{"section": "Capture", "endpoints": [
{"name": "displayCapture", "args": ["str usr_uid", "JCapture cap", "list<JDevicePoint> points" ], "chatty": True },
{"name": "requestActiveCapture", "args": ["int test", "long other test"], "qml_only": True },
... | StarcoderdataPython |
3416994 | import pyautogui, time
time.sleep(5)
file = open('spam.txt', 'r', encoding='utf-8' )
for row in file:
pyautogui.typewrite(row)
pyautogui.press('enter')
time.sleep(0.1) | StarcoderdataPython |
1804994 | <filename>src/api_gateway_lambda_proxy/response.py
"""Data classes for response of AWS Lambda proxy integration."""
from __future__ import annotations
import dataclasses
import json
from dataclasses import field
from typing import Any, Dict, List, Optional
RawProxyResponse = Dict[str, Any]
@dataclasses.dataclass()... | StarcoderdataPython |
11353364 | # coding=utf-8
# Copyright (C) 2020 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Services for working with Change Log via UI."""
from lib import base, factory
from lib.constants import objects, element
from lib.page.widget import change_log
from lib.utils import ui_util... | StarcoderdataPython |
57953 | <filename>clinja/__init__.py<gh_stars>0
from .clinja import ClinjaDynamic, ClinjaStatic
__version__ = "1.1.0"
__author__ = "<NAME> <<EMAIL>>"
| StarcoderdataPython |
11237419 | import pickle
import cv2
import numpy as np
def saveDescriptorListFile(descriptor, descriptorFilename):
file = open(descriptorFilename,"wb")
pickle.dump(descriptor, file)
file.close()
def readDescriptorListFile(descriptorFilename):
file = open(descriptorFilename,"rb")
descriptorList = pickle.l... | StarcoderdataPython |
5158217 | <filename>src/doom_replay.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
################################################################################
# Copyright (c) 2017. <NAME>, <NAME>, <NAME>, #
# <NAME>. All rights reserved. #
# See the accompanying LICENSE file fo... | StarcoderdataPython |
1850073 | """
Provides an interface to CUDA for running the parallel IBDTW and
partial IBDTW algorithms
"""
import pycuda.autoinit
import pycuda.driver as drv
import pycuda.gpuarray as gpuarray
import pycuda.cumath
import numpy as np
import matplotlib.pyplot as plt
import time
import scipy.io as sio
import pkg_resources
import ... | StarcoderdataPython |
9613380 | <gh_stars>0
import os
import click
import math
import datetime
from fb_dfg import config
from fb_dfg import main
from fb_dfg import utils
@click.group()
def cli():
pass
@click.command()
@click.option('--partner_id', '-id', help='Facebook Data for Good Partner ID.')
def set_partner_id(partner_id):
config.set... | StarcoderdataPython |
1795622 | from ..Base import Base
from ..info import Info
from ..apk import register
from ..tools import *
TITLE = 'SQL injection detection'
LEVEL = 2
INFO = 'Detect whether there are usage conditions for SQL injection in the App'
class SQLInjectCheck(Base):
def scan(self):
strline = cmdString('grep -r "Landroid/d... | StarcoderdataPython |
291966 | class Point2D():
def __init__(self, x,y):
self.coord = [x,y]
def __str__(self):
return f'Point:({self.coord[0]},{self.coord[1]})'
def __eq__(self,other):
return (self.coord[0]==other.coord[0])&(self.coord[1]==other.coord[1])
def __ne__(self,other):
return (self.coord[0]... | StarcoderdataPython |
8007935 | """empty message
Revision ID: 94a5b5198867
Revises:
Create Date: 2022-03-12 00:15:21.130502
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "94a5b5198867"
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto genera... | StarcoderdataPython |
1950833 | <filename>Code/StatusCatalog.py
# === Imports ==================================================================
# Custom imports
from . import GlobalConstants as GC
from . import configuration as cf
from . import static_random
from . import CustomObjects, ActiveSkill, HelpMenu
from . import Utility, Engine
from... | StarcoderdataPython |
8110295 | <filename>projektrouska/migrations/0005_auto_20210104_2014.py
# Generated by Django 3.1 on 2021-01-04 19:14
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('projektrouska', '0004_auto_20210104_0341'),
]
operations... | StarcoderdataPython |
3230897 | import pprint
import argparse
import numpy as np
import yaml
import random
import os
import csv
import json
import train
import gridworld
def generate_random_grid(base, num_event_cells, period_range, bound, mode='linear', stack=True, event_region=None, extra_event_region=[]):
min_period, max_period = period_ra... | StarcoderdataPython |
1695342 | <reponame>wenhanshi/project-in-BUPT
import socket
import struct
import queue
import sys
import getopt
import random
import threading
dns_data = {} # file that contains DNS info
dns_server = '10.3.9.5' # remote DNS server
port = 53 # DNS port
query_buf = queue.Queue() # DNS query queue
ans_buf = queue.Queue() # D... | StarcoderdataPython |
1861085 | <reponame>earthcomfy/recipe-api
from .base import *
DEBUG = True
ALLOWED_HOSTS = ['localhost']
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
| StarcoderdataPython |
297886 | <reponame>ollfkaih/lego
class ParserException(Exception):
"""
Base exception for the email parser.
"""
pass
class ParseEmailException(ParserException):
"""
Raised when the parser can't create a email.message.Message object of the raw string or bytes.
"""
pass
class MessageIDNotExis... | StarcoderdataPython |
5098950 | <filename>tests/test_lambda_integration.py
from io import BytesIO, StringIO
import requests
import lambda_requests
from tests.base import (
BINARY_PAYLOAD,
HTTP_URL_PREFIX,
LAMBDA_URL_PREFIX,
UNICODE_PAYLOAD,
PatcherBase,
)
def _seek_reset_request(accessor, url_path, *args, **kwargs):
if "fi... | StarcoderdataPython |
4935608 | import math
n = int(input("Enter the number till where the series ius to be printed = "))
for i in range(1,n+1):
k = math.pow(i,3)
j = k + 2*i
print(j)
| StarcoderdataPython |
1667247 | <reponame>mrunibe/MIALab
from tensorflow.python.platform import app
import os
import argparse
import sys
import numpy as np
sys.path.insert(0, os.path.join(os.path.dirname(sys.argv[0]), '..')) # append the MIALab root directory to Python path
# fixes the ModuleNotFoundError when executing main.py in the console aft... | StarcoderdataPython |
1760074 | from torchvision import datasets, transforms
import math
import random
import torch
import copy
import csv
from datetime import datetime
import os
import numpy as np
from torch.utils.data import Dataset, DataLoader
from torch import nn
from trainer import Tester
class Utils():
def get_dataset_dist(self, args):
... | StarcoderdataPython |
8079874 | <filename>Chapter09/Edge_detection_Kernel.py
#Edge dection kernel
#Built with SciPy
#Copyright 2018 <NAME> MIT License. READ LICENSE.
import matplotlib.image as mpimg
import numpy as np
import scipy.ndimage.filters as filter
import matplotlib.pyplot as plt
#I.An edge dectection kernel
kernel_edge_detection = np.array... | StarcoderdataPython |
5059151 | import warnings
warnings.filterwarnings("ignore")
import re
from nltk import word_tokenize, pos_tag
import pandas as pd
import numpy as np
from profanity_check import predict, predict_prob
from emot import emoji, emoticons
from bs4 import BeautifulSoup
from flair.models import TextClassifier, SequenceTagger
from flair... | StarcoderdataPython |
6616474 | import numpy as np
from matplotlib.path import Path
class BinaryRenderer:
def __init__(self, size):
self.map = np.zeros(size, dtype=bool)
self.xx, self.yy = np.meshgrid(range(size[1]), range(size[0]))
self.xy = np.vstack((self.xx.flatten(), self.yy.flatten())).T
def circle(self, x, ... | StarcoderdataPython |
1979634 | <filename>package/no_of_letters_in_string.py
def nols():
a=input('enter string ')
b=input('enter letter ').strip()
count=0
for i in range(len(a)):
if(a[i]==b):
count+=1
print(count)
nols()
| StarcoderdataPython |
5020499 | from pyjokes.jokes_en import jokes_en
from pyjokes.jokes_de import jokes_de
from pyjokes.jokes_es import jokes_es
from pyjokes.jokes_gl import jokes_gl
from pyjokes.jokes_eu import jokes_eu
from pyjokes.jokes_it import jokes_it
from pyjokes.jokes_se import jokes_se
def _test_joke_length(joke):
assert len(joke) <=... | StarcoderdataPython |
76667 | <filename>setup.py
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import os
import platform
import re
from setuptools import setup, Extension
python_version = platform.python_version()
system_name = platform.system()
print("build for python{} on {}".format(python_version, system_name))
# Arguments
actrie_dir = ""
ali... | StarcoderdataPython |
1899630 | <gh_stars>0
# ------------------------------------------------------------------- #
# Copyright (c) 2007-2008 Hanzo Archives Limited. #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #
# you may not us... | StarcoderdataPython |
3469065 | <filename>RPI/Master/co2Sensor.py
# ***************************************************
# * By Group 5 @ HSLU I.BSCI.HS18.IOT *
# ****************************************************
import serial
import time
class Co2Sensor:
def __init__(self):
self.arduino_serial = None
self.initia... | StarcoderdataPython |
4998120 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@文件 :data_interface.py
@说明 :数据接口
@时间 :2020/07/29 14:13:14
@作者 :Riven
@版本 :1.0.0
'''
import abc
'''
定义一个接口
'''
class DataInterface(metaclass=abc.ABCMeta):
# For Test
# path = ' 123543'
# def __init__(self):
# sel... | StarcoderdataPython |
6589883 | from spyd.registry_manager import register
from spyd.permissions.functionality import Functionality
from spyd.game.client.exceptions import GenericError
from spyd.game.command.command_base import CommandBase
@register("command")
class RoomCommand(CommandBase):
name = "room"
functionality = Functionality("spyd.... | StarcoderdataPython |
5156849 | <reponame>rog-works/lf3py
from types import ModuleType
from typing import Any, Dict, List, Optional, Tuple
from typing_extensions import Protocol
from lf3py.app.app import App
from lf3py.lang.dict import deep_merge
from lf3py.lang.module import import_module
from lf3py.lang.sequence import first, flatten, last
from lf... | StarcoderdataPython |
9664981 | from bs4 import BeautifulSoup
def normalise(text):
no_html = BeautifulSoup(text).get_text()
return no_html
| StarcoderdataPython |
3552526 | <gh_stars>0
"""
Normalizes the audio of a video file.
"""
import argparse
import os
import subprocess
def ffprobe_duration(filename: str) -> float:
"""
Uses ffprobe to get the duration of a video file.
"""
cmd = f"static_ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=... | StarcoderdataPython |
6604469 | #!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = '<NAME>'
__version__ = '0.1'
from os.path import dirname, abspath
from argparse import ArgumentParser
import re
parser = ArgumentParser(description='Update ChibiOS halconf and mcuconf from STM32CubeMX project files.')
parser.add_argument('cube', type=str, help='S... | StarcoderdataPython |
11257267 | """
Tests for views in eCommerce app.
"""
from unittest.mock import patch
from django.apps.registry import apps
from django.core import mail
from django.core.urlresolvers import reverse
from django.test import TestCase
from ecommerce.cart import Cart
from ecommerce.models import Order
from pages.models import Custom... | StarcoderdataPython |
1814233 | <gh_stars>0
import json
import xml.etree.ElementTree as ET
def export(annotation_files, output_dir):
for annotation_file in annotation_files:
export_file(annotation_file, output_dir)
def export_file(annotation_file, output_dir):
xml = build_xml(annotation_file)
output_file_path = (output_dir / a... | StarcoderdataPython |
6511806 | <gh_stars>0
# This program 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 later version.
#
# This program is distributed in the hope t... | StarcoderdataPython |
11322345 | ################################################################################
# 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... | StarcoderdataPython |
9652009 | <reponame>anniyanvr/ray<gh_stars>0
import unittest
from unittest.mock import Mock, MagicMock
from ray.rllib.examples.env.random_env import RandomEnv
from ray.rllib.utils.pre_checks.env import check_gym_environments
class TestGymCheckEnv(unittest.TestCase):
def test_has_observation_and_action_space(self):
... | StarcoderdataPython |
5178859 | import string
def is_pangram(sentence):
for c in string.ascii_lowercase:
if c not in sentence.lower():
return False
return True
| StarcoderdataPython |
3556095 | from django.db import models
class User(models.Model):
created = models.DateTimeField(auto_now_add=True)
first_name = models.CharField(max_length=63)
last_name = models.CharField(max_length=63)
| StarcoderdataPython |
1833610 | <gh_stars>0
from decimal import Decimal
from nose.tools import eq_
import test_utils
from lib.sellers.models import Seller, SellerPaypal, SellerProduct
from lib.transactions import constants
from lib.transactions.models import Transaction
from lib.transactions.utils import completed, refunded, reversal
class TestIP... | StarcoderdataPython |
8076950 | import mock
from django.conf import settings
from django.test import TestCase
from . import CommonCommandsTestMixin, call_command_real as call_command
global_mock = mock.MagicMock()
class TestInitCommand(CommonCommandsTestMixin, TestCase):
def setUp(self):
super(TestInitCommand, self).setUp()
p... | StarcoderdataPython |
6552157 | <filename>Part-2/generators.py
# def yrange(n):
# i=0
# while i<n:
# yield i
# i+=1
# y=yrange(4)
# # print y
# print y.next()
# print y.next()
# print y.next()
# print y.next()
# print y.next()
def myCustomerGenerator():
print("Start Generator")
i=0
while(i<10):
yield i
... | StarcoderdataPython |
1960784 | <filename>pyorb_core/rb_library/affine_decomposition.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 10 14:41:45 2018
@author: <NAME>
@email : <EMAIL>
"""
import numpy as np
import pyorb_core.algebraic_utils as alg_ut
class AffineDecomposition( ):
def __init__( self ):
return
... | StarcoderdataPython |
8074273 | from mock_server.api import Response
import json
def provider(request):
if request.uri == '/abc':
headers = [("Content-Type", "application/json; charset=utf-8")]
content = {"name": "Tomas", "surname": "Hanacek"}
return Response(json.dumps(content), headers, 200)
| StarcoderdataPython |
183626 | <filename>examples/api/profile/update_profile.py
from instauto.api.client import ApiClient
import instauto.api.actions.structs.profile as pr
from instauto.api.structs import WhichGender
client = ApiClient.initiate_from_file('.instauto.save')
# With the update object, you can update multiple attributes at the same time... | StarcoderdataPython |
4952479 | <reponame>computing-intelligence/lottery
# @Time : 2021-08-31 10:49
# @Author : 老赵
# @File : lottery.py
import random
import time
from collections import Counter
from tqdm import tqdm
class Lottery:
def __init__(self, codes, winner_nums):
self.codes = codes
self.winner_nums = winner_nums
... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.