id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
3260062 | <filename>apps/core/__init__.py
from bluebottle.bb_tasks import taskmail
| StarcoderdataPython |
1667733 | import sys
import numpy as np
import sounddevice as sd
import speech_recognition as sr
from googletrans import Translator
from kivy.uix.widget import Widget
from scipy.io.wavfile import write
class MyGrid(Widget):
def button_record_translate(self):
"""
Record and translate the given text.
... | StarcoderdataPython |
1766821 | <gh_stars>0
# import the necessary packages
from pyimagesearch import imutils
import numpy as np
import argparse
import cv2
def find_screen(vid):
oldRect = np.zeros((4, 2), dtype = "float32")
rect = np.zeros((4, 2), dtype = "float32")
while(True):
_, image = vid.read()
#image = cv2.imr... | StarcoderdataPython |
3314257 | from django.conf.urls import url
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url('^$', views.index, name='home'),
url(r'^search/', views.search_results, name='search_results'),
url(r'^singleimage/(\d+)', views.single_photo, name='singleIma... | StarcoderdataPython |
3319794 | <reponame>mwhchen/quantecon<filename>python_oop/plot_market.py
import matplotlib.pyplot as plt
import numpy as np
from market import Market
# Baseline ad, bd, az, bz, tax
baseline_params = 15, .5, -2, .5, 3
m = Market(*baseline_params)
q_max = m.quantity() * 2
q_grid = np.linspace(0.0, q_max, 100)
pd = m.inverse_dem... | StarcoderdataPython |
25924 | """Represent a class to generate a meme."""
from PIL import Image, ImageDraw, ImageFont
from os import makedirs
from random import randint
from textwrap import fill
class MemeGenerator:
"""
A class to generate a meme.
The following responsibilities are defined under this class:
- Loading of an image... | StarcoderdataPython |
193780 | #!/usr/bin/env python3
"""
Loss
"""
import tensorflow as tf
def calculate_loss(y, y_pred):
"""calculates the softmax cross-entropy loss of a prediction
Args:
y is a placeholder for the labels of the input data
y_pred is a tensor containing the network’s predictions
Returns:
a ten... | StarcoderdataPython |
181008 | from datetime import datetime
import os
import random
import re
import threading
import time
import json
import yaml
from cmg.event import Event
from cmg.utilities import ReadWriteLock
from study_tool.card import Card
from study_tool.card import SourceLocation
from study_tool.card_set import CardSet
from study_tool.car... | StarcoderdataPython |
3264879 | import numpy as np
import time
import sys
import matplotlib.pyplot as plt
from hamiltonian import *
class EigRNN:
"""
Finds the lowest eigenvalue of a symmetric matrix
by minimizing the Rayleigh quotient with gradient
descent
"""
def __init__(self,A,eps=1e-4,maxiter=1000):
"""
A... | StarcoderdataPython |
162939 | <filename>rel2/bluecat_app/bin/bluecat/ip4_address.py
from entity import entity
from api_exception import api_exception
"""
IPv4 address obejcts.
"""
class ip4_address(entity):
"""Instantiate an ipv4_address.
:param api: API instance used by the entity to communicate with BAM.
:param soap_entity: the SO... | StarcoderdataPython |
163744 | <reponame>rmmbear/tweet-archiver<filename>tweetarchiver/tests/test_live.py<gh_stars>0
import logging
from bs4 import BeautifulSoup as BS
from tweetarchiver import Tweet, download, HTML_PARSER
LOGGER = logging.getLogger(__name__)
COMPAREVARS = [
"tweet_id",
"thread_id",
"timestamp",
"account_id",
... | StarcoderdataPython |
1625540 | <gh_stars>1-10
from mythril.laser.ethereum.transaction.transaction_models import MessageCallTransaction, ContractCreationTransaction, get_next_transaction_id
from z3 import BitVec
from mythril.laser.ethereum.state import GlobalState, Environment, CalldataType, Account, WorldState
from mythril.disassembler.disassembly i... | StarcoderdataPython |
1716228 | from transformers import BertConfig
class RelicConfig(BertConfig):
def __init__(
self,
entity_vocab_size=10000,
entity_embedding_dim=300,
use_batch_negatives=True,
random_negatives=4096,
**kwargs
):
super().__init__(**kwargs)
self.entity_vocab_si... | StarcoderdataPython |
124289 | <reponame>jentjr/observations
import os
import re
from io import StringIO
import numpy as np
import pandas as pd
import requests
def get_stations(variable='RD'):
"""get knmi stations from json files according to variable
Parameters
----------
variable : str, optional
[description], by defaul... | StarcoderdataPython |
3363683 | #!/usr/bin/env python3
class Application:
def __init__(self, app_id, user_id, sensor_list, ip, port, ram_req, cpu_req, app_path, algo_path):
self.app_id = app_id
self.user_id = user_id
self.sensor_list = sensor_list
self.ip = ip
self.port = port
self.ram_req = ram_r... | StarcoderdataPython |
55650 | import numpy as np
import matplotlib.pyplot as plt
from .integrate import Integrate
class Riemann(Integrate):
"""
Compute the Riemann sum of f(x) over the interval [a,b].
Parameters
----------
f : function
A single variable function f(x), ex: lambda x:np.exp(x**2)
"""
def _... | StarcoderdataPython |
1627401 | <reponame>nghia-tran/f5-common-python
# Copyright 2015-2106 F5 Networks Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | StarcoderdataPython |
3257281 | <gh_stars>1-10
# -*- coding: utf-8 -*-
"""
@author: WZM
@time: 2021/1/29 15:44
@function:
"""
import torch
import torch.nn as nn
import torchvision
# print("PyTorch Version: ", torch.__version__)
# print("Torchvision Version: ", torchvision.__version__)
__all__ = ['DenseNet121', 'DenseNet169', 'DenseNet201', 'DenseNe... | StarcoderdataPython |
4817198 | import argparse
import os
from .utils import test_adaptive_thresholding_algorithms, test_edge_detection_algorithms
from .tools.logger_base import log as log_message
def test_algorithms_main():
"""Main entry point for the test algorithms script"""
# Parsing arguments
ap = argparse.ArgumentParser()
ap... | StarcoderdataPython |
32695 | from behave import *
import requests
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token
use_step_matcher("re")
@given("that I am a registered host of privilege walk events and exists events on my username")
def step_impl(context):
context.username = "12thMan"
conte... | StarcoderdataPython |
153692 | from django.views.generic.edit import FormView
from django.views.generic import DetailView
from django.core.urlresolvers import reverse
from .models import VideoCategory, Video
from .forms import UploadVideoForm
class HomeView(FormView):
template_name = 'home.html'
form_class = UploadVideoForm
success_u... | StarcoderdataPython |
189590 | <gh_stars>0
from Line import Line
from Rectangle import Rectangle
from Text import Text
from Picture import Picture
if __name__ == '__main__':
picture1 = Picture()
picture1.add(Line())
picture1.add(Rectangle())
picture2 = Picture()
picture2.add(Text())
picture2.add(Line())
picture2.add(Re... | StarcoderdataPython |
1754066 | <reponame>commis/FATE
#
# Copyright 2019 The FATE Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Un... | StarcoderdataPython |
93577 | <gh_stars>0
# ~\~ language=Python filename=test/test_codelets.py
# ~\~ begin <<lit/code-generator.md|test/test_codelets.py>>[0]
import numpy
import pytest
from fftsynth import generator, parity
from kernel_tuner import run_kernel # type: ignore
@pytest.mark.parametrize('radix,c_type', [(2, 'float2'), (4, 'float2... | StarcoderdataPython |
1610194 | i = "global"
def f(n):
i = "hello"
# The iterator element will get set, but only
# if the range is non-empty
print [0 for i in xrange(n)]
print n, i * 3
f(0)
f(5)
i = 0
# Though if the ifs empty out the range, the
# name still gets set:
print [0 for i in xrange(5) if 0]
print i
i = "global"
def... | StarcoderdataPython |
116049 | #!coding:utf8
#author:yqq
#date:2019/12/26 0026 17:28
#description: EOS 相关的handler
import logging
import eospy
import eospy.keys
import pytz
import json
import sql
import re
from base_handler import BaseHandler
from utils import decimal_default, get_linenumber
from eospy.types import Transaction
fr... | StarcoderdataPython |
37542 | <reponame>brsynth/rplibs
"""
Created on May 28 2021
@author: <NAME>
"""
from unittest import TestCase
from copy import deepcopy
from rplibs import rpReaction
class Test_rpReaction(TestCase):
def setUp(self):
self.reactants = {
"CMPD_0000000010": 1,
"MNXM1": 1
}
s... | StarcoderdataPython |
45396 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
'''
__new__ __init__
'''
class Programer(object):
def __new__(self, *args, **kwargs):
print 'call __new__ method!'
print args
return object.__new__(self, *args, **kwargs)
def __init__(self,name,age):
prin... | StarcoderdataPython |
20010 | """The WaveBlocks Project
Plot some quadrature rules.
@author: <NAME>
@copyright: Copyright (C) 2010, 2011 <NAME>
@license: Modified BSD License
"""
from numpy import squeeze
from matplotlib.pyplot import *
from WaveBlocks import GaussHermiteQR
tests = (2, 3, 4, 7, 32, 64, 128)
for I in tests:
Q = Gauss... | StarcoderdataPython |
1732702 | def main():
with open("day_7_input.txt") as f:
puzzle_input = [int(x) for x in f.read().split(",")]
puzzle_input.sort()
median = puzzle_input[len(puzzle_input) // 2]
fuel_one = sum(abs(n - median) for n in puzzle_input)
print(f"Part 1: {fuel_one}")
mean = int(sum(puzzle_input) / len(pu... | StarcoderdataPython |
1704543 | <gh_stars>1000+
lambda a :
a + 1
| StarcoderdataPython |
1732378 | <filename>test_project/zmija_config.py
def file_filter(file_path):
return file_path.endswith('.cpp') or file_path.endswith('.txt') | StarcoderdataPython |
1684851 | <gh_stars>10-100
# -*- coding: utf-8 -*-
# Copyright (C) 2021 GIS OPS UG
#
#
# 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 requir... | StarcoderdataPython |
1609415 | <reponame>Wellheor1/l2<gh_stars>0
from django.urls import path
from . import views
urlpatterns = [
path('generate', views.directions_generate),
path('add-additional-issledovaniye', views.add_additional_issledovaniye),
path('rmis-directions', views.directions_rmis_directions),
path('rmis-direction', vie... | StarcoderdataPython |
43194 | '''
<NAME>
CS100-031 Fall 2021
HW12 December 10, 2021
'''
#1
def safeOpen(inFile):
try:
file = open(inFile)
return file
except:
return None
#2
def safeFloat(inFloat):
try:
newFloat = float(inFloat)
return newFloat
except ValueError:
return 0.0
#3
def av... | StarcoderdataPython |
1661002 | <gh_stars>1000+
""" script to discover feature axis in the latent space """
"""
pre-requisite: this code needs pre-generated feature-image pairs, stored as pickle files located at:
project_root/asset_results/pggan_celeba_sample_pkl
"""
import os
import sys
import time
import pickle
import numpy as np
import tensorfl... | StarcoderdataPython |
1705809 | <filename>tests/test_appconfig_template.py
from mdr import appconfig_template as ac
| StarcoderdataPython |
4835781 | import PySimpleGUI as sg
class menuScreen:
def __init__(self):
#theme
#sg.theme("Dark Brown")
#layout
layout = [
[sg.Button("Singleplayer", key="single"), sg.Button("Multiplayer", key="multi")],
[sg.Radio("Easy", "dif", key="easy", default=True), sg.Radio("In... | StarcoderdataPython |
1631178 | from distutils.core import setup
setup(name='SDRTspendfrom',
version='1.0',
description='Command-line utility for sdrt "coin control"',
author='<NAME>',
author_email='<EMAIL>',
requires=['jsonrpc'],
scripts=['spendfrom.py'],
)
| StarcoderdataPython |
3369589 | # our main file.
import speech_recognition as sr
# Criar um reconhecedor
r = sr.Recognizer()
# Abrir o microfone para captura
with sr.Microfone() as source:
audio = r.listen(source) # Define microfone como fonte de áudio
print(r.recognize_google(audio))
| StarcoderdataPython |
1718541 | <reponame>js4785/gennyc
# -*- coding: utf-8 -*-
"""Surveys
"""
from wtforms import Form, fields, validators
class UserInterests(Form):
"""User interests."""
hobbies = \
fields.SelectMultipleField('What are some of your hobbies and interests?',
choices=[('hobbies-craft... | StarcoderdataPython |
91937 | <gh_stars>0
"""Seta o encoding para utf-8"""
# -*- coding: utf-8 -*-
"""Efetua o importa da bilioteca para plotar os gráficos"""
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objects as go
import plotly.figure_factory as ff
"""Efetua importa da biblioteca json"... | StarcoderdataPython |
1707078 | from ode_FE import ode_FE
import matplotlib.pyplot as plt
for dt, T in zip((0.5, 20), (60, 100)):
u, t = ode_FE(f=lambda u, t: 0.1*(1 - u/500.)*u, \
U_0=100, dt=dt, T=T)
plt.figure() # Make separate figures for each pass in the loop
plt.plot(t, u, 'b-')
plt.xlabel('t'); ... | StarcoderdataPython |
1776221 | import shutil
import traceback
from abc import ABC, abstractmethod
from pathlib import Path, PurePath
from tempfile import TemporaryDirectory
from typing import List, IO, Optional
from zipfile import ZipFile
import yaml
from opera.error import ParseError, OperaError
from opera.utils import determine_archive_format
... | StarcoderdataPython |
1660599 | from setuptools import setup, find_packages
setup(
name='battle-city-ai',
version='0.1',
description='whatever',
packages=find_packages(exclude=['tests', 'docs']),
install_requires=[
'pygame==1.9.4',
],
include_package_data=True,
extras_require={
'test': [
'p... | StarcoderdataPython |
164455 | <reponame>spethso/Raspberry-RoomTemperature-AzureIoTHub
import sys
import iothub_service_client
from iothub_service_client import IoTHubRegistryManager, IoTHubRegistryManagerAuthMethod
from iothub_service_client import IoTHubDeviceStatus, IoTHubError
import json
connectionData = json.load(open('connectionData.json'))
... | StarcoderdataPython |
1696739 | from datetime import datetime
from typing import TypedDict, Dict, List, Any, Tuple, Optional
from bs4 import BeautifulSoup
class InfoboxMetadata(TypedDict, total=False):
updated_at: datetime
released_at: datetime
published_at: datetime
status: str
platforms: List[str] # Windows/macOS/Linux/etc
... | StarcoderdataPython |
4840836 | #pylint: disable = C0330
'''Run feature extraction'''
import os
import sys
from functools import reduce
import qcrit.extract_features
from qcrit.textual_feature import setup_tokenizers
from download_corpus import download_corpus
from corpus_categories import composite_files, genre_to_files
def main():
'''Main'''
c... | StarcoderdataPython |
48340 | #!/usr/bin/env python3
# This is the master ImageAnalysis processing script. For DJI and
# Sentera cameras it should typically be able to run through with
# default settings and produce a good result with no further input.
#
# If something goes wrong, there are usually specific sub-scripts that
# can be run to fix th... | StarcoderdataPython |
1714248 | class TransformOrientation:
matrix = None
name = None
| StarcoderdataPython |
159622 | import pytest
import json
import hsc_compile
import hsc_deploy
aergo = None
hsc_address = "AmgUPYeR2w8Hrh4pauwDRzykGUjvRTNEoH65S6xXawoy3CAZrEda"
pond_creator = "AmLaWMFr8jpJqLVwGrEnsX62mKEm62ztjSsAmB2APL3Z9qeGyk1s"
def call_function(func_name, args):
return hsc_deploy.call_sc(aergo, hsc_address, 'callFunctio... | StarcoderdataPython |
1755548 | <filename>run.py
#!/usr/bin/env python3.6
import random
from user import User
from credentials import Credentials
# Functions to add credentials
def create_new_credential(site_name,account_name, account_password):
"""Function to create a new account and its credentials"""
new_credential = Credentials(site_n... | StarcoderdataPython |
4818843 | # Copyright 2020 Amazon.com, Inc. or its affiliates. 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.
# A copy of the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in th... | StarcoderdataPython |
1664750 | import unittest
from email_scraper.scrape import extract_emails, deobfuscate_html, scrape_emails
class TestExtractor(unittest.TestCase):
def test_basic(self):
self.assertEqual(extract_emails('hello world'), [])
self.assertEqual(extract_emails('hello <EMAIL> world'), ['<EMAIL>'])
self.asse... | StarcoderdataPython |
145903 | NO_ERROR = 0
MISTAKE = 1
FIXED_MISTAKE = 2
CHEAT = 3
ACROSS = 0
DOWN = 1
def make_hash(data):
try:
from hashlib import md5
m = md5()
except:
import md5
m = md5.new()
m.update(data)
return m.hexdigest()
class BinaryFile:
def __init__(self, filename=None):
if... | StarcoderdataPython |
16982 | <reponame>Sebastian-dm/pilferer<filename>pilferer/engine.py
import tcod
from input_handlers import handle_keys
from game_states import GameStates
from render_functions import clear_all, render_all, RenderOrder
from map_objects.game_map import GameMap
from fov_functions import initialize_fov, recompute_fov
from entit... | StarcoderdataPython |
4840700 | # All rights reserved.
# Keredit
# Licensed under the Raphielscape Public License, Version 1.d (the "License");
# you may not use this file except in compliance with the License.
from telethon import events
from telethon.errors.rpcerrorlist import YouBlockedUserError
from userbot.events import register
from ... | StarcoderdataPython |
180332 | <gh_stars>1-10
from src.domain.git import push_origin_upstream, create_branch, checkout, delete_branch, pull
from src.domain.output import output
def load_branch_into_workstream(workstream, branchName):
return [
checkout("master"),
pull(),
delete_branch(workstream, force=True),
ch... | StarcoderdataPython |
21429 | print('Interrogando um suspeito: ')
pg1 = str(input("Telefonou para a vítma?(S/N)\n").upper().strip())
pg2 = str(input('Esteve no local do crime?(S/N)\n').upper().strip())
pg3 = str(input('Mora perto da vítma?(S/N)\n').upper().strip())
pg4 = str(input('Devia para a vítma?(S/N)\n').upper().strip())
pg5 = str(input('Já t... | StarcoderdataPython |
3331384 | from app import db
import datetime
from flask_login import current_user
import pytz
from sqlalchemy import and_, or_
from sqlalchemy.orm import aliased
# exact match, provides text input
class Filter:
def __init__(self, column, nullable=False):
self.column = column
self.nullable = nullable
def... | StarcoderdataPython |
4804570 | """
Intended for use in Jupyter notebooks like:
%run -m datasci.notebook.init
Or:
from datasci.notebook.init import *
"""
# pylint: disable=unused-import
# stdlib
import sys
import os
import re
import math
import time
import random
import logging
import gzip
import json
import operator
import itertools
import... | StarcoderdataPython |
3309682 | from fastapi import APIRouter, Header
from uuid import UUID
from pydantic import BaseModel
from .example_loader import load_example
from .models import Profile
from fastapi.responses import JSONResponse
route = APIRouter()
class ServiceRequestBody(BaseModel):
resourceType: str
meta: Profile
@route.get("/Se... | StarcoderdataPython |
4813132 | #!/usr/bin/python
print "/* -*- C -*- */"
handlers = { 'first' : [ 'alpha', 'bravo', 'charlie' ],
'second': [ 'delta','echo', 'foxtrot', 'golf' ],
'third' : [ 'hotel', 'india' ],
'fourth' : [ 'juliet' ],
'fifth' : [ 'kilo', 'lima', 'mike' ],
}
o... | StarcoderdataPython |
3289232 | from . import base_api_core
class SysInfo(base_api_core.Core):
def __init__(self, ip_address, port, username, password, secure=False, cert_verify=False, dsm_version=2):
super(SysInfo, self).__init__(ip_address, port, username, password, secure, cert_verify, dsm_version)
def fileserv_smb(self):
... | StarcoderdataPython |
3363060 | import os
import base64
import time
from algosdk.v2client import algod, indexer
from algosdk.future import transaction
from algosdk import encoding, account, mnemonic, error
from pyteal import compileTeal, Mode
from contracts import manager
ALGOD_ENDPOINT = os.environ['ALGOD_ENDPOINT']
ALGOD_TOKEN = os.environ['ALGO... | StarcoderdataPython |
3299191 | <reponame>Amiao-miao/all-codes<filename>month02/day15/thread_lock.py
from threading import Lock,Thread,Event
# lock=Lock()
e=Event()
a=b=1
def fun():
while True:
# lock.acquire()
if a!=b:
print(f"a={a},b={b}")
e.set()
# lock.release()
t=Thread(target=fun)
t.start()
whi... | StarcoderdataPython |
3241390 | <filename>coaching/core/views.py
from django.shortcuts import render, HttpResponse
from . models import subject, student
from reportlab.pdfgen import canvas
from django.http import FileResponse
def home(request):
return render(request, 'index.html')
def courses(request):
courses=subject.objects.all... | StarcoderdataPython |
3367210 | <reponame>timothyjlaurent/shipyard
# Copyright <NAME> and contributors.
#
# 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... | StarcoderdataPython |
3226263 | <reponame>kisekizzz/GraphGallery<gh_stars>0
import numpy as np
import scipy.sparse as sp
from ..transforms import Transform
from graphgallery import intx
class NeighborSampler(Transform):
def __init__(self, max_degree: int = 25,
selfloop: bool = False):
super().__init__()
... | StarcoderdataPython |
3357566 | from django.contrib import admin
from cdl_rest_api import models
admin.register(models.Experiment)
admin.register(models.UserProfile)
admin.register(models.ExperimentResult)
| StarcoderdataPython |
3282532 | def pavel_rscripts():
"""<NAME> Provides the WSPR Analysis Script written in R
Source: git clone https://github.com/pavel-demin/wsprspots-analyzer.git
The following has been constructed to feed each of the three script via
Python.
Requirements:
* R Language base
* R Packages: ggpl... | StarcoderdataPython |
1623165 | import traceback
from django.core.exceptions import ValidationError
from django.utils.html import format_html
from django.utils.safestring import mark_safe
from base.admin import *
from core.models import *
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.c... | StarcoderdataPython |
66083 | from rest_framework.renderers import BrowsableAPIRenderer
# From: https://bradmontgomery.net/blog/disabling-forms-django-rest-frameworks-browsable-api/
class BrowsableAPIRendererWithoutForms(BrowsableAPIRenderer):
"""Renders the browsable api, but excludes the html form."""
def get_context(self, *args, **kwa... | StarcoderdataPython |
3307113 | # Your task is to transform a max heap to a min heap!
class HeapTransformer:
def __init__(self, heap):
self.heap = heap
def transform(self):
for i in range((len(self.heap) - 2) // 2, -1, -1):
self.__fix_down(i)
def __fix_down(self, index):
left_index = 2 * index + 1
... | StarcoderdataPython |
1782159 | <filename>hexrd/ui/image_mode_widget.py
from PySide2.QtCore import QObject, Signal
from hexrd.ui.hexrd_config import HexrdConfig
from hexrd.ui.ui_loader import UiLoader
class ImageModeWidget(QObject):
# The string indicates which tab was selected
tab_changed = Signal(str)
# Tell the image canvas to sho... | StarcoderdataPython |
1638756 | import logging
import unittest
from geocode_array.geocode_array import _find_mean_pos, _find_dist_mean, combine_geocode_results, \
combine_double_geocode_results
class TestGeocodeArray(unittest.TestCase):
def setUp(self) -> None:
logging.basicConfig(level=logging.DEBUG,
fo... | StarcoderdataPython |
69606 | #!/usr/bin/env python3
"""
Author : NowHappy <<EMAIL>>
Date : 2021-10-13
Purpose: Ransom Note
"""
import argparse
import random
import os
# --------------------------------------------------
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Ransom Note'... | StarcoderdataPython |
1641708 | <gh_stars>1-10
import pyqtgraph
from pyqtgraph.Qt import QtGui
from pyqtgraph.Qt import QtCore
import numpy as np
import math
from osu_analysis import BeatmapIO, ReplayIO, StdMapData, StdReplayData, Gamemode
from app.misc._utils import Utils
from app.misc._osu_utils import OsuUtils
from app.misc._hitobject_plot impo... | StarcoderdataPython |
23695 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distrib... | StarcoderdataPython |
3350029 | # Copyright 2016 Mirantis 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... | StarcoderdataPython |
146395 | import requests
from astroquery.simbad import Simbad
import numpy as np
import pandas as pd
from astropy.table import QTable, Table, Column
from astropy import units as u
import urllib
import re
import bs4
import math
import matplotlib.pyplot as plt
def plot(star_name):
# Convert the names of stars to HIP numbers... | StarcoderdataPython |
1667433 | <reponame>saul1917/PSPclassification
import cv2
img1 = cv2.imread('ART_00272_otsu.jpg')
img2 = cv2.imread('ART_00283_kittler.jpg')
print(img1.size)
print(img2.size)
dst = cv2.addWeighted(img1,0.7,img2,0.3,0)
cv2.imshow('dst',dst)
cv2.waitKey(0)
cv2.destroyAllWindows()
| StarcoderdataPython |
3261457 | from distutils.core import setup,Extension
import os
incdir = os.path.normpath(os.path.join(os.path.dirname(__file__), "..",
"ArrayHash"))
setup(name='kharon',
version='0.4',
packages = ['kharon',],
ext_modules=[
Extension('kharon.pyarrayhash... | StarcoderdataPython |
117478 | <filename>ocdskingfisher/maindatabase/migrations/versions/c9b3a2f75f20_gather_fetch_info.py
"""gather_fetch_info
Revision ID: <KEY>
Revises: <PASSWORD>
Create Date: 2018-09-12 15:32:56.683032
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision... | StarcoderdataPython |
1775951 | import math
from math import log2, exp
import numpy as np
import torch
from torch import nn
from torch.nn.functional import softplus
import torch.nn.functional as F
from torch.autograd import grad
from typing import List, Callable, Union, Any, TypeVar, Tuple
# from torch import tensor as Tensor
Tensor = TypeVar('torc... | StarcoderdataPython |
3248 | import os
from pathlib import Path
def write(file_name, content):
Path(os.path.dirname(file_name)).mkdir(parents=True, exist_ok=True)
with open(file_name, 'w') as file:
file.write(content)
def read_line_looping(file_name, count):
i = 0
lines = []
file = open(file_name, 'r')
line = fi... | StarcoderdataPython |
1660001 | import pytest
from rest_framework import status
from rest_framework.reverse import reverse
from know_me import models, serializers
url = reverse("know-me:legacy-user-list")
@pytest.mark.integration
def test_get_legacy_user_list(
api_client, api_rf, legacy_user_factory, user_factory
):
"""
Sending a GE... | StarcoderdataPython |
1758400 | <reponame>open-contracting/yapw
import pickle
import pytest
from yapw.util import default_encode, json_dumps
def test_json_dumps():
assert json_dumps({"a": 1, "b": 2}) == b'{"a":1,"b":2}'
@pytest.mark.parametrize(
"args,expected",
[
(({"a": 1, "b": 2}, "application/json"), b'{"a":1,"b":2}'),
... | StarcoderdataPython |
100495 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-08-03 15:45
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('player', '0009_tournament_type'),
]
operations = [
migrations.AlterField(
... | StarcoderdataPython |
90594 | import requests
from requests.exceptions import RequestException
import json
import time
import hmac
from hashlib import sha256
from urllib.parse import urlencode
from logging import getLogger
from .exception import APIError
class API(object):
"""
HTTP APIのラッパークラス
https://lightning.bitflyer.com/docs#http... | StarcoderdataPython |
128528 | <filename>Arrays/problem-1.py
# 1. Two Sum
class Solution:
# Approach 1 : Naive
def twoSum1(self, nums, target):
for i in range(len(nums)-1):
for j in range(i+1, len(nums)):
if nums[i]+nums[j] == target:
return [i, j]
return None
# Approac... | StarcoderdataPython |
3292069 | import logging
import os
import sqlite3
import traceback
from decimal import Decimal
from twisted.internet import defer, task, threads
from twisted.enterprise import adbapi
from lbryschema.claim import ClaimDict
from lbryschema.decode import smart_decode
from lbrynet import conf
from lbrynet.cryptstream.CryptBlob impo... | StarcoderdataPython |
105672 | #!/usr/bin/env python
import glob
import numpy as np
import astropy.io.fits as fits
import scipy.optimize as opt
import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.rcParams['font.family'] = 'Times New Roman'
mpl.rcParams['font.size'] = '15'
mpl.rcParams['mathtext.default'] = 'regular'
#mpl.rcParams['xtic... | StarcoderdataPython |
3328303 | from datetime import date, datetime
def dict2akn(dict):
akn = {}
verTs = datetime.utcfromtimestamp(float(dict['versions'][0]['versionTimestamp']/1000))
verDate = str(verTs.date())
docType = dict['extraFieldValues'].pop('documentType')
if(docType == 'ΠΡΑΞΗ'):
docType = 'act'
else:
... | StarcoderdataPython |
58969 | import numpy as np
from sklearn.preprocessing import MinMaxScaler, StandardScaler
from sklearn.cross_validation import train_test_split
import theanets
import climate
climate.enable_default_logging()
X_orig = np.load('/Users/bzamecnik/Documents/music-processing/music-processing-experiments/c-scale-piano_spectrogram_2... | StarcoderdataPython |
3302335 | <reponame>q0w/snug
import asyncio
import inspect
import urllib.request
from operator import methodcaller
import snug
async def awaitable(obj):
"""an awaitable returning given object"""
await asyncio.sleep(0)
return obj
class MockAsyncClient:
def __init__(self, response):
self.response = res... | StarcoderdataPython |
4808726 | import random
import hashlib
import string
from flask_bootstrap import Bootstrap
from flask import Flask, render_template, request, url_for, redirect
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, IntegerField, BooleanField
from wtforms.validators import InputRequired, Optional
from wtf... | StarcoderdataPython |
3351623 | <reponame>huzexi/SADenseNet<filename>components/datasets/lytro/__init__.py
import cv2
from components.utils import lf_raw2bgr, im2double, lf_bgr2ycrcb
def load_item(pth_img, a_raw, a_preserve):
"""
Load structured BGR and YCrCb matrix from path of a raw LF.
:param pth_img: Path of a raw LF.
:param a_... | StarcoderdataPython |
3372215 | from django.db import models
from django.contrib.auth.models import User
import datetime
class Schoolmodule(models.Model):
datecreated= models.DateTimeField(auto_now_add=True)
def current_date_time():
current = datetime.datetime.now()
newcurrent = str(current)
mydate=newcurrent[0:19]
return mydate
class Prov... | StarcoderdataPython |
1777704 | <reponame>auto-flow/oxygen<gh_stars>10-100
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : <NAME>
# @Date : 2020-12-20
# @Contact : <EMAIL>
import unittest
from ultraopt.multi_fidelity import HyperBandIterGenerator, SuccessiveHalvingIterGenerator, CustomIterGenerator
class TestMultiFidelity(unittest... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.