id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
3327850 | <filename>src/api/views/countdown.py
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.status import HTTP_400_BAD_REQUEST, HTTP_200_OK
from api.serializers.countdown_seralizers import (
CountdownSerializer,
CountdownDeleteSerializer,
)
from covid19.models... | StarcoderdataPython |
150123 | <filename>DICOMOFFIS/admin.py<gh_stars>0
from django.contrib import admin
from .models import eintrag
# Register your models here.
admin.site.register(eintrag) | StarcoderdataPython |
118711 | <reponame>jamesjh-lee/xor
import os, sys
import tensorflow as tf
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
sys.setrecursionlimit(1500)
import argparse
import numpy as np
from tensorflow.keras.optimizers import Adam, SGD
from tensorflow.keras.layers import Input, Dense
from tensorflow.keras.models import Model
from tenso... | StarcoderdataPython |
194735 | #!/usr/bin/env python
###########################################################################################
# Implementation of illustrating results. (Average reward for each episode)
# Author for codes: <NAME>(<EMAIL>)
# Reference: https://github.com/Kchu/LifelongRL
#############################################... | StarcoderdataPython |
1667511 | <reponame>MStarmans91/WORC
#!/usr/bin/env python
# Copyright 2016-2020 Biomedical Imaging Group Rotterdam, Departments of
# Medical Informatics and Radiology, Erasmus MC, Rotterdam, The Netherlands
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with... | StarcoderdataPython |
18723 | #B
def average(As :list) -> float:
return float(sum(As)/len(As))
def main():
# input
As = list(map(int, input().split()))
# compute
# output
print(average(As))
if __name__ == '__main__':
main()
| StarcoderdataPython |
3203677 | <reponame>MiiRaGe/miilibrary
import pytest
import responses
import mock
from celery.exceptions import Retry
from django.core.cache import cache
from django.test import SimpleTestCase
from django.test import TestCase, override_settings
from pyfakefs.fake_filesystem_unittest import TestCase as FakeFsTestCase
from mii_r... | StarcoderdataPython |
1764826 | <filename>rover/py_rf_serial/mesh.py
import os
import datetime
import time
#Local imports
import cfg
import rf_uart as ser
import json
import logging as log
on_broadcast = None
on_message = None
on_cmd_response = None
on_log = None
nodes_config = os.getenv('ROVER_NODES_CONFIG','D:\\Dev\\nRF52_Mesh\\applications\\nodes... | StarcoderdataPython |
3390924 | <gh_stars>1-10
import sys
import csv
from types import GeneratorType
from text_studio.data_loader import DataLoader
csv.field_size_limit(sys.maxsize)
class CsvLoader(DataLoader):
@staticmethod
def load(file, delimiter=","):
# TO DO: Add basic error checking to validate that the file exists
in... | StarcoderdataPython |
3365610 | <gh_stars>0
from django.apps import AppConfig
class AccountConfig(AppConfig):
name = 'nest_box_helper'
verbose_name = 'Nest Box Helper'
| StarcoderdataPython |
4803075 | import sqlite3
db = sqlite3.connect('nba.db')
db.execute("drop table IF EXISTS team")
db.execute("drop table IF EXISTS player")
db.execute("drop table IF EXISTS contract")
db.execute("drop table IF EXISTS hall_of_fame")
db.execute("drop table IF EXISTS position")
db.execute("drop table IF EXISTS all_star_team")
db.exe... | StarcoderdataPython |
3266961 | """
copyright <NAME>
10.06.2021
"""
from numpy.fft import fft, ifft, fftfreq
from numpy import real, imag
import csv
from matplotlib import pyplot as plt
#
# weekly_prices = []
# dates = []
#
# plt.plot(range(len(weekly_prices)), weekly_prices, '-b')
# plt.xlabel('Week #')
# plt.ylabel('Crude Oil Future Price')
# # ... | StarcoderdataPython |
171099 | <reponame>sonalimahajan12/Automation-scripts
import requests
import sys
def get_prices():
# Checking there is a coin passed
if len(sys.argv) > 1:
coins = sys.argv[1:]
else:
# Default coins
coins = ["BTC", "ETH", "XRP", "LTC", "BCH",
"ADA", "DOT", "LINK", "BNB", "X... | StarcoderdataPython |
4805538 | from django.shortcuts import render
from django.http import HttpResponse, Http404
from django.views import View
def test_response(request):
return HttpResponse('this is a test')
def test_view(request):
return render(request, 'test.html')
def test_404(request):
raise Http404()
class TestView(View):
... | StarcoderdataPython |
1703968 | <filename>led_cube.py
from machine import Pin
import utime
class LedCube:
def __init__(self, level_pins, led_pins):
if not len(level_pins) % len(led_pins) == 0:
raise CubeException("led_pins array length does not divide with level_pins array length. len(level_pins) = ", len(level_pins), ", le... | StarcoderdataPython |
3389431 | <filename>LeetCode/Python/1197. Minimum Knight Moves.py
"""
See the problem description at: https://leetcode.com/problems/minimum-knight-moves/
"""
class Solution:
def minKnightMoves(self, x: int, y: int) -> int:
from collections import deque
if x == 0 and y == 0: return 0
... | StarcoderdataPython |
3215869 | <filename>joommf/mesh.py
import textwrap
class Mesh(object):
"""class Mesh(lengths, mesh_spacing, scale=1e-9)
lengths: list
List of 3 lengths which make up the global atlas
mesh_spacing:
List of 3 discretisations.
Example usage:
For a rectangular block of 30x30... | StarcoderdataPython |
1756708 | <gh_stars>0
"""brainfuck interpreter adapted from (public domain) code at
http://brainfuck.sourceforge.net/brain.py"""
import asyncio
import random
import re
from cloudbot import hook
BUFFER_SIZE = 5000
MAX_STEPS = 1000000
@asyncio.coroutine
@hook.command("brainfuck", "bf")
def bf(text):
"""<prog> - executes <... | StarcoderdataPython |
4836328 | # Copyright 2017 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | StarcoderdataPython |
3297926 | #!/usr/bin/env python3
# coding: utf-8
from prompt_toolkit import prompt
from prompt_toolkit.history import InMemoryHistory
from prompt_toolkit.formatted_text import ANSI
import re
p_xor = re.compile(r'([^\s]+)\s*\^\s*([^\s]+)')
p_quotes = re.compile(r'^([^"\']+):.*')
p_b64 = re.compile(r'[A-Za-z0-9+/]+={0,2}')
p_in... | StarcoderdataPython |
1715735 | import sys
import io
import unittest
from unittest.mock import patch
from fzfaws.s3.helper.s3progress import S3Progress
import boto3
from botocore.stub import Stubber
class TestS3Progress(unittest.TestCase):
def setUp(self):
self.capturedOutput = io.StringIO()
sys.stdout = self.capturedOutput
... | StarcoderdataPython |
1768609 | from .changelog import Changelog
from .release import Release, Unreleased
| StarcoderdataPython |
1738373 | <filename>fitparse/base.py
#!/usr/bin/env python
import io
import os
import struct
import warnings
# Python 2 compat
try:
num_types = (int, float, long)
except NameError:
num_types = (int, float)
from fitparse.processors import FitFileDataProcessor
from fitparse.profile import FIELD_TYPE_TIMESTAMP, MESSAGE_T... | StarcoderdataPython |
1662400 | from typing import Any
from allauth.account.adapter import DefaultAccountAdapter
from allauth.socialaccount.adapter import DefaultSocialAccountAdapter
from django.conf import settings
from django.http import HttpRequest
class AccountAdapter(DefaultAccountAdapter):
def is_open_for_signup(self, request: HttpReque... | StarcoderdataPython |
195518 | <filename>mockfirestore/__init__.py
from .main import DocumentSnapshot, DocumentReference, Query, CollectionReference, MockFirestore | StarcoderdataPython |
3332527 | import numpy as np
import tensorflow as tf
img_shape = (2,2,2,1)
img = tf.placeholder(tf.float32, img_shape)
ksize = [1,2,2,1]
stride = [1,2,2,1]
pool, argmax = tf.nn.max_pool_with_argmax(img, ksize, stride, padding='SAME', name='pool')
img_np = np.zeros(img_shape)
img_np[0,0,0] = 1
img_np[1,1,1] = 2
with tf.Session... | StarcoderdataPython |
1603562 | import os
import torch
import logging
from model import DeepSpeech
class Observer(object):
'''
Train Observer base class.
'''
def __init__(self, logger):
self.logger = logger
def on_epoch_start(self, model, epoch): pass
def on_epoch_end(self, model, optimizer, epoch, loss_results, ... | StarcoderdataPython |
1722101 | from unittest import TestCase
from mock import Mock, patch, PropertyMock
from mangrove.datastore.database import DatabaseManager
from mangrove.form_model.field import PhotoField, TextField, FieldSet
from mangrove.form_model.form_model import FormModel
from mangrove.transport.services.MediaSubmissionService import Media... | StarcoderdataPython |
3379076 | <filename>eggbox_potential_sampler/eggbox_pes_data_source/tests/test_factory.py<gh_stars>0
# (C) Copyright 2010-2020 Enthought, Inc., Austin, TX
# All rights reserved.
import unittest
from eggbox_potential_sampler.eggbox_pes_data_source.data_source\
import EggboxPESDataSource
from eggbox_potential_sampler.eggbo... | StarcoderdataPython |
4836809 | <reponame>mariusgheorghies/python
# coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: v1.20.7
Generated by: https://openapi-generator.tech
"""
import pprint
impor... | StarcoderdataPython |
6737 | <gh_stars>0
from gtts import gTTS as ttos
from pydub import AudioSegment
import os
def generate_mp3 (segments, fade_ms, speech_gain, comment_fade_ms, language = "en", output_file_name = "generated_program_sound") :
def apply_comments (exercise_audio, segment) :
new_exercise_audio = exercise_audio
... | StarcoderdataPython |
97342 | <reponame>chrisjbillington/parpde
# Example file that finds the groundstate of a condensate in a rotating frame.
# Takes quite some time to run so you can just stop it when you run out of
# patience and run the plotting script.
# Run with 'mpirun -n <N CPUs> python run.py'
from __future__ import division, print_funct... | StarcoderdataPython |
1628783 | # -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
# Name: realizer.py
# Purpose: music21 class to define a figured bass line, consisting of notes
# and figures in a given key.
# Authors: <NAME>
#
# Copyright: Copyright © 2011 <NA... | StarcoderdataPython |
1781923 | <reponame>bopopescu/phyG
import logging
import os
import threading
from galaxy.util import asbool
from galaxy.web.framework.helpers import time_ago
from tool_shed.util import readme_util
import tool_shed.util.shed_util_common as suc
log = logging.getLogger( __name__ )
# String separator
STRSEP = '__ESEP__'
class Fo... | StarcoderdataPython |
1795222 | <reponame>xUndero/noc
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------
# BeefCLI
# ----------------------------------------------------------------------
# Copyright (C) 2007-2018 The NOC Project
# See LICENSE for details
# ------------------------------------------------... | StarcoderdataPython |
1681793 | <filename>scanpipe/tasks.py
# SPDX-License-Identifier: Apache-2.0
#
# http://nexb.com and https://github.com/nexB/scancode.io
# The ScanCode.io software is licensed under the Apache License version 2.0.
# Data generated with ScanCode.io is provided as-is without warranties.
# ScanCode is a trademark of nexB Inc.
#
# Yo... | StarcoderdataPython |
1794338 | <gh_stars>1-10
# Problem : https://www.hackerrank.com/challenges/py-set-add/problem
# Score : 10 points(MAX)
loops = input() # Quantidade de valores que entrarão
grupo = [] # Grupo para alocar esses valores
[grupo.append(input()) for i in range(int(loops))] # para cada loop adicione a palavra no grupo dist
print(l... | StarcoderdataPython |
3259841 | <filename>scripts/lasso_1-regularisation_path.py
import os.path
import numpy as np
from numpy import linalg as la
import matplotlib.pyplot as plt
import sys
sys.path.append('..')
import invprob.sparse as sparse
from invprob.optim import fb_lasso
#########################################
# This is for production only
... | StarcoderdataPython |
1678147 | <reponame>DataDog/datadog-sync-cli<gh_stars>1-10
# Unless explicitly stated otherwise all files in this repository are licensed
# under the 3-clause BSD style license (see LICENSE).
# This product includes software developed at Datadog (https://www.datadoghq.com/).
# Copyright 2019 Datadog, Inc.
from typing import Opt... | StarcoderdataPython |
1725112 | """
Bio ontology to be used in the enrichment of SAA indices by Golden Agents.
"""
from rdflib import Dataset, Graph, Namespace
from rdflib import XSD, RDF, RDFS, OWL
from rdflib import URIRef, BNode, Literal
from rdfalchemy.rdfSubject import rdfSubject
from rdfalchemy.rdfsSubject import rdfsSubject
from rdfalchemy ... | StarcoderdataPython |
3394393 | # coding=utf-8
from .eth import ADDRESS as COINBASE_ADDRESS
from .eth import MAX_TX_TRY
from .eth import MIN_GAS
from .eth import PRIVATE_KEY as COINBASE_PRIVATE_KEY
from .mixer import ADDRESS as MIXER_ADDRESS
from .mixer import PRIVATE_KEY as MIXER_PRIVATE_KEY
from .referral import REFERRAL_DUMMY
from .referral import... | StarcoderdataPython |
1718233 | <filename>a4/bert.py
import transformers
from transformers import BertModel, BertTokenizer, AdamW, get_linear_schedule_with_warmup
import torch
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix, classification_report
from torch impor... | StarcoderdataPython |
4803024 | <filename>movie/forms.py
from dal import autocomplete
from django import forms
from movie.models import Movie
class MovieForm(forms.ModelForm):
title = autocomplete.Select2ListCreateChoiceField(widget=autocomplete.ListSelect2(url='movie:movie_title_autocomplete'))
class Meta:
model = Movie
f... | StarcoderdataPython |
3270026 | <filename>nails_project/core/mixins.py<gh_stars>0
class BootstrapFormMixin:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._init_bootstrap_fields()
def _init_bootstrap_fields(self):
for (_, field) in self.fields.items():
if 'class' not in field.... | StarcoderdataPython |
4833115 | import functools
import os
import sys
from datetime import timedelta
import dotenv
from loguru import logger
import copy
from novelsave.settings import config, console_formatter
def app() -> dict:
"""Initialize and return the configuration used by the base application"""
return copy.deepcopy(config)
def l... | StarcoderdataPython |
52386 | <filename>ntc_rosetta/yang/__init__.py
import pathlib
from yangson.datamodel import DataModel
_DATAMODELS = {"openconfig": None, "ntc": None}
BASEPATH = pathlib.Path(__file__).parent
OPENCONFIG_LIB = f"{BASEPATH}/openconfig.json"
OPENCONFIG_PATH = [
BASEPATH.joinpath("YangModels/standard/ietf/RFC"),
BASEPATH... | StarcoderdataPython |
42359 | from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import BoardMember
# Post 추가
from django.core import serializers
from rest_framework.decorators import api_view, permission_classes, authentication_classes
from rest_framework.permissions import IsAuthenticated # 로그인여부 확인
f... | StarcoderdataPython |
4807174 | <reponame>YanrongXu/Leetcode<filename>Binary Search/162. Find Peak Element.py
class Solution:
def findPeakElement(self, nums: List[int]) -> int:
if not nums:
print
return -1
start, end = 0, len(nums) - 1
while start + 1 < end:
mid = (start + end) ... | StarcoderdataPython |
3235463 | from scipy.io.wavfile import read
import os
import torch
import numpy as np
MAX_WAV_VALUE = 32768.0
def load_wav_to_torch(full_path):
"""
Loads wavdata into torch array
"""
sampling_rate, data = read(full_path)
return torch.FloatTensor(data.astype(np.float32)) / MAX_WAV_VALUE, sampling_rate
d... | StarcoderdataPython |
104888 | <filename>test/transform/test_rotate.py<gh_stars>1-10
# -*- coding: utf-8 -*-
import os, sys
import numpy as np
from skimage import io
from os.path import dirname as opd
from os.path import abspath as opa
from os.path import join as opj
TEST_PATH = opa(opd(opd(__file__)))
PRJ_PATH = opd(TEST_PATH)
sys.path.insert(0, ... | StarcoderdataPython |
162306 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Hive Appier Framework
# Copyright (c) 2008-2019 Hive Solutions Lda.
#
# This file is part of Hive Appier Framework.
#
# Hive Appier Framework is free software: you can redistribute it and/or modify
# it under the terms of the Apache License as published by the Apache
# Found... | StarcoderdataPython |
34656 | <reponame>MatthiasValvekens/certvalidator
# coding: utf-8
import inspect
def type_name(value):
"""
Returns a user-readable name for the type of an object
:param value:
A value to get the type name of
:return:
A unicode string of the object's type name
"""
if inspect.isclass... | StarcoderdataPython |
1758490 | from setuptools import find_packages, setup
setup(
name='IdobataPlugin', version='0.5',
packages=find_packages(exclude=['*.tests*']),
author='<NAME>',
author_email='<EMAIL>',
url='https://github.com/kompiro/trac-idobata-plugin',
description='Trac - Idobata integration',
platforms='all',
... | StarcoderdataPython |
54095 | <reponame>FabricExile/Kraken
"""Kraken - maths.euler module.
Classes:
Euler -- Euler rotation.
"""
import math
from kraken.core.kraken_system import ks
from kraken.core.maths.math_object import MathObject
from kraken.core.maths.mat33 import Mat33
from kraken.core.maths.rotation_order import RotationOrder
rotationO... | StarcoderdataPython |
141838 | <reponame>dopplershift/siphon
# Copyright (c) 2016 University Corporation for Atmospheric Research/Unidata.
# Distributed under the terms of the MIT License.
# SPDX-License-Identifier: MIT
"""Test Coverage Dataset."""
import warnings
from siphon.cdmr.coveragedataset import CoverageDataset
from siphon.testing import g... | StarcoderdataPython |
1673764 | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.ingredient_manager),
url(r'^recipe$', views.recipe_manager)
] | StarcoderdataPython |
1671195 | import discord
from discord.ext import commands
import os
from tabulate import tabulate
from cogs.database.db import Base, Configs
from cogs.database.database import session
present_configs = os.listdir("cogs/configs")
class download(commands.Cog):
def __init__(self,bot):
self.bot = bot
def channel():
def predi... | StarcoderdataPython |
3299740 | <gh_stars>1-10
import time
from pprint import pprint
from flask_login import login_required
from flask import Blueprint, session, request
from sqlalchemy import create_engine
import dateutil.parser
import logging
from datetime import datetime, timedelta, timezone
import pytz
from utils.app import jsonify, app, get_ne... | StarcoderdataPython |
3349486 | def safe_compare_dataframes(first, second):
"""Compare two dataframes even if they have NaN values.
Args:
first (pandas.DataFrame): DataFrame to compare
second (pandas.DataFrame): DataFrame to compare
Returns:
bool
"""
if first.isnull().all().all():
return first.eq... | StarcoderdataPython |
3313300 | <filename>notebooks/unfolding/PyUnfold/make_counts.py
#!/usr/bin/env python
import numpy as np
import pandas as pd
import ROOT
from ROOT import TH1F, TH2F, TNamed
from ROOT import gROOT, gSystem
import itertools
import os
import re
if __name__ == "__main__":
formatted_df_outfile = os.path.join('/data/user/jbou... | StarcoderdataPython |
48857 | <reponame>the-scouts/incognita
import time
import geopandas as gpd
import pandas as pd
from incognita.data.scout_census import load_census_data
from incognita.geographies import district_boundaries
from incognita.logger import logger
from incognita.utility import config
from incognita.utility import filter
from incog... | StarcoderdataPython |
3281661 | #!/usr/bin/env python
# Copyright 2017 Google, 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 required by applicable law or... | StarcoderdataPython |
3277495 | import uuid
from django.db import models
from django.db.models import Sum
from django.conf import settings
from django.contrib.auth.models import User
from django_countries.fields import CountryField
from shop.models import Product
from members.models import Member
from user_profiles.models import StoreUser
from decim... | StarcoderdataPython |
13130 | <filename>hydropy/__init__.py
"""
Hydropy
=======
Provides functions to work with hydrological processes and equations
"""
| StarcoderdataPython |
1758541 | # (c) 2017 <NAME>
"""common interface for all pore geometries
should behave as follows:
-) defines default parameters for the geometry
-) provides function that takes geoname, geo params (including dim) plus
small additional number of non-geo (solver) params
(h, reconstruct, subs), and returns ge... | StarcoderdataPython |
1698610 | <reponame>Verizon/YANG-validator
#
# Copyright Verizon Inc.
# Licensed under the terms of the Apache License 2.0 license. See LICENSE file in project root for terms.
#
import sys
import threading
import asyncio
import jsonToYang
import json
import traceback
import time
import pprint
topic = None
jsonStr = None
def c... | StarcoderdataPython |
1691429 | #!/usr/bin/env python3
"""
Assumptions:
- The sequence residue lines are in upper case. I've never seen FASTQ files otherwise,
but if they aren't this will report no reads being filtered. A check would slow the
script too much.
Author: <NAME> (jorvis AT gmail)
"""
import argparse
import re
import sys
def ma... | StarcoderdataPython |
4843238 | <filename>eyecandy/helpers.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import decimal
import os
import subprocess
import sys
import time
def generate_effect():
# input, output, effect
subprocess.call(['python', sys.argv[3], sys.argv[1], sys.argv[2]])
def progressbar(it, prefix='Processing', prog='#',
... | StarcoderdataPython |
3297364 | """Reporting shifts Configuration
"""
from reporting.views import CreateIncidentReport, CreateInvolvedParties, ListIncidentTypes, ListInvolvedParties
from django.urls import path
urlpatterns = [
path('form-options/incident-types/',
ListIncidentTypes.as_view(), name="incident_types"),
path('form-option... | StarcoderdataPython |
1687945 | <gh_stars>0
'''Implements the `java_compiler_toolchain` rule.
Java compiler toolchain instances are created with `java_compiler_toolchain`
rule instances. A separate `toolchain` rule instance is used to declare a
`java_compiler_toolchain` instance has the type
`@dwtj_rules_java//java/toolchains/java_compiler_toolchain... | StarcoderdataPython |
3389881 | import tensorflow_datasets as tfds
import config
def load_dataset():
imdb, info = tfds.load('imdb_reviews',
data_dir=config.DATA_PATH,
with_info=True,
as_supervised=True)
return imdb, info
if __name__ == '__main__':
load_da... | StarcoderdataPython |
22224 | from dataclasses import dataclass
from quran.domain.entity import Entity
@dataclass
class Edition(Entity):
id: str
language: str
name: str
translator: str
type: str
format: str
direction: str
| StarcoderdataPython |
177519 | <reponame>victorcouste/great_expectations
from great_expectations.cli.upgrade_helpers.upgrade_helper_v11 import UpgradeHelperV11
from great_expectations.cli.upgrade_helpers.upgrade_helper_v13 import UpgradeHelperV13
GE_UPGRADE_HELPER_VERSION_MAP = {
1: UpgradeHelperV11,
2: UpgradeHelperV13,
}
| StarcoderdataPython |
164174 | <reponame>luckdeluxe/hardware-store
from . import stripe
def create_card(user, token):
source = stripe.Customer.create_source(
user.customer_id,
source = token
)
return source
| StarcoderdataPython |
3264341 | <reponame>kant/flight-blender
from rest_framework import serializers
from .models import GeoFence
class GeoFenceSerializer(serializers.ModelSerializer):
altitude_ref = serializers.SerializerMethodField()
class Meta:
model = GeoFence
fields = '__all__'
def get_altitude_ref(self... | StarcoderdataPython |
1775401 | import os
from interface import interface
from flask import render_template
@interface.route('/')
@interface.route('/index')
def index():
images = []
for r, d, f in os.walk('../data/16_0/'):
for file in f:
if ".png" in file:
images.append(file)
... | StarcoderdataPython |
1680117 | import sys
import random
assert sys.version_info >= (3, 7), "This script requires at least Python 3.7"
guessTotal = 0
answer = random.randint(0, 50)
playerGuess = input("Choose a number between 1 and 50.\n")
while playerGuess != answer:
while not isinstance(playerGuess, int):
try:
playerGuess... | StarcoderdataPython |
1688801 | <gh_stars>1-10
import asyncio
import logging
import pytest
from mock import Mock
from tests import run10
from traio import Scope
def test_version():
"""Just ensure we have a version string"""
from traio.__version__ import __version__
assert isinstance(__version__, str)
def test_logging():
"""Logg... | StarcoderdataPython |
115622 | <reponame>Infinity-LTD/discord_gradiusbot
import asyncio
import logging
logger = logging.getLogger('gradiusbot')
logger.info("[Public Plugin] <portals.py>: This plugin allows you to use portals to move your messages around!")
portal_dict = {}
@asyncio.coroutine
async def action(**kwargs):
message = kwargs['mes... | StarcoderdataPython |
1782600 | from django.db import models
# Create your models here.
class feedback(models.Model):
name = models.TextField()
email = models.TextField()
subject = models.TextField()
patient = models.CharField(max_length=30)
def __str__(self):
return self.name
| StarcoderdataPython |
128319 | #숫자카드게임-1
#n,m을 공백으로 구분하여 입력받기
n, m = map(int, input().split())
result = 0
for i in range(n):
data = list(map(int, input().split()))
min_value = min(data)
result = max(result, min_value)
print(result) | StarcoderdataPython |
4812477 | # -*- coding: utf-8 -*-
# Copyright (c) 2017, Frappe and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe, json, hub
from frappe.website.website_generator import WebsiteGenerator
from hub.hub.utils import autoname_increment_by_field
class HubItem(Web... | StarcoderdataPython |
104159 | <filename>Lab_6/data/core/myservices/pcpingweb01.py
#
# CORE
# Copyright (c)2010-2012 the Boeing Company.
# See the LICENSE file included in this distribution.
#
''' WAN BGP user-defined service.
'''
import os
from core.service import CoreService, addservice
from core.misc.ipaddr import IPv4Prefix, IPv6Prefix
class ... | StarcoderdataPython |
146803 | # Copyright 2006-2007 Virtutech AB
import sim_commands
def checkbit(a, bit):
if a & (1 << bit):
return 1
else:
return 0
def get_info(obj):
return [ (None, [
("PHY object", obj.phy),
] ) ] + sim_commands.get_pci_info(obj)
def get_status(obj):
csr0 = obj.csr_csr0
cs... | StarcoderdataPython |
3212415 | <filename>utils/csv_parser.py
import pandas as pd
def get_co_authorship(csv_file_path, year):
data = pd.read_csv(csv_file_path, usecols=['id', 'date', 'authors'], index_col=False)
data['publication_year'] = data['date'].apply(lambda x: x.split('-')[0])
data['publication_month'] = data['date'].apply(lambda... | StarcoderdataPython |
3363461 | from django.contrib import admin
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import Group
from .models import TUser
# Register your models here.
class TUserAdmin(UserAdmin):
form = UserChangeForm
add_form = Us... | StarcoderdataPython |
58305 | <reponame>KarrLab/python_package_tutorial<gh_stars>10-100
from . import boolean
from . import dfba
from . import ode
from . import stochastic
from . import multi_algorithm
from . import mrna_and_proteins_using_several_methods
| StarcoderdataPython |
1637400 | <reponame>JorisDeRieck/hass-nhc2
"""Support for NHC2 lights."""
import logging
from homeassistant.components.light import LightEntity, SUPPORT_BRIGHTNESS, ATTR_BRIGHTNESS
from nhc2_coco import CoCoLight, CoCo
from nhc2_coco.coco_device_class import CoCoDeviceClass
from .const import DOMAIN, KEY_GATEWAY, BRAND, LIGHT
... | StarcoderdataPython |
1719726 | import numpy as np
import torch
def getIndeices(shape,height,width,stride,dialation, offset):
H, W = shape
outHeight = (H - dialation*(height-1)-1) // stride +1
outWidth = (W - dialation*(width-1)-1) // stride +1
i0 = np.repeat(np.arange(height)*dialation, width)
i1 = stride * np.repeat(np.arange(... | StarcoderdataPython |
1631043 | <reponame>kvchen/keffbot
import binascii
import git
import sys
import os
import logging
logger = logging.getLogger('root')
__match__ = r"!update|!reload"
def on_message(bot, channel, user, message):
requires_reload = message == '!reload'
if message == '!update':
local = git.Repo(os.getcwd())
... | StarcoderdataPython |
3368313 | <filename>tests/test_fileops.py
from utils.fileops import get_abs_path
from pathlib import Path
def test_get_abs_path():
x = get_abs_path()
assert x.is_file(), "Absolute path not generated correctly!" | StarcoderdataPython |
63858 | # Generated by Django 3.1.5 on 2021-01-19 08:20
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),
('fina... | StarcoderdataPython |
190383 | <reponame>domwillcode/home-assistant
"""The mfi component."""
| StarcoderdataPython |
1675615 | import cv2
import numpy as np
import glob
from scipy.stats import multivariate_normal
import copy
out = cv2.VideoWriter('3D_GMM.avi', cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'), 5, (640, 480))
DATASET = "DETECTBUOY-FRAMES/Data"
def Ellipse_Fit(mask):
processed = mask.astype(np.uint8)
processed = cv2.... | StarcoderdataPython |
1789165 | <filename>Backend Server/AdminRoutes/admin_frontpage.py
from app import app
from db_config import *
from flask import jsonify, request
@app.route("/api/Admin/view/items_sold_unsold", methods=["GET"])
def sold_unsold_items():
conn = mysql.connection
cursor = conn.cursor()
try:
sql = f"""-... | StarcoderdataPython |
1628126 | <gh_stars>1-10
limit = int( input() )
data = []
ans = []
for y in range( limit ):
data.append( [] )
ans.append( [] )
for x in range( limit ):
data[ y ].append( [] )
data[ y ][ x ] = 0
ans[ y ].append( [] )
ans[ y ][ x ] = 0
print( "data =", data )
print( "ans =", ans )
i = 0
for y i... | StarcoderdataPython |
3396761 | <filename>mail.py
# Import smtplib for the actual sending function
import smtplib
# Import the email modules we'll need
from email.message import EmailMessage
# Open the plain text file whose name is in textfile for reading.
# Create a text/plain message
def sendMail(recipient, textbody):
msg = EmailMess... | StarcoderdataPython |
1619633 | stations = { 'acheng': 'ACB',
'aershan': 'ART',
'aershanbei': 'ARX',
'aihe': 'AHP',
'aijiacun': 'AJJ',
'ajin': 'AJD',
'akesu': 'ASR',
'aketao': 'AER',
'alashankou': 'AKR',
'alihe': 'AHX',
'alongshan': 'ASX',
'amuer': 'JTX',
'ananzhuang': 'AZM',
'anda': 'ADX',
'a... | StarcoderdataPython |
14697 | <reponame>quadramadery/bfx-hf-indicators-py<gh_stars>1-10
from bfxhfindicators.indicator import Indicator
class WMA(Indicator):
def __init__(self, args = []):
[ period ] = args
d = 0
for i in range(period):
d += (i + 1)
self._d = d
self._p = period
self._buffer = []
super().__in... | StarcoderdataPython |
3357952 | # -*- coding: utf-8 -*-
"""
S3 Microsoft Excel codec
@copyright: 2011-2021 (c) Sahana Software Foundation
@license: MIT
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 wi... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.