id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
1706754 | <filename>archive/openstack_api.py<gh_stars>10-100
#!/usr/bin/python
import httplib
import json
class API(object):
"""API object to connect to an OpenStack environment."""
def __init__(self, osurl=None, osuser=None, ospassword=None):
self.url = osurl or "10.63.165.20"
self.osuser = osuser... | StarcoderdataPython |
69032 | <filename>tests/api/test_incidents.py<gh_stars>0
import datetime
import json
import random
import pytest
from django.urls import reverse
from faker import Faker
from rest_framework.test import force_authenticate
from response import serializers
from response.core.views import IncidentsByMonthViewSet, IncidentViewSet
... | StarcoderdataPython |
3237540 | <reponame>ivanprjcts/installib<gh_stars>0
import os
from installib.obfuscation_checker import assert_not_equal_hash
from installib.compare import compare_versions_str
from installib.windows import get_file_properties
WINDOWS_ASSEMBLY_GAC_MSIL_PATH = "C:\Windows\\assembly\GAC_MSIL\\"
WINDOWS_DOTNET_ASSEMBLY_GAC_MSIL_... | StarcoderdataPython |
3302911 | __author__ = 'ignacio'
| StarcoderdataPython |
20849 | <reponame>paleomau/MGOL_BOOTCAMP
from flask import Flask, request, render_template
from functions import read_json
import os
# Mandatory
app = Flask(__name__) # __name__ --> __main__
# ---------- Flask functions ----------
@app.route("/") # @ --> esto representa el decorador de la función
def home():
""" Def... | StarcoderdataPython |
3261093 | <filename>tests/test_crop.py
"""Test `crop` command."""
import unittest
from PIL import Image
from click.testing import CliRunner
from imgwrench.commands.crop import crop
from imgwrench.param import RATIO
from .images import (
white100x100_img,
white117x100_img,
white100x123_img,
white150x100_img,
)... | StarcoderdataPython |
79800 |
from main import keys
import jwt
import pyrtk
def create_jwt(user_id):
return jwt.encode({'user_id': user_id}, keys['JWT_KEY'], algorithm="HS256").decode('utf-8')
def create_rtk(user_id):
return pyrtk.create_token(user_id, keys['RTK_KEY'])
def decode_jwt(user_id):
pass
def decode_rtk(user_id):
... | StarcoderdataPython |
3240439 | <filename>apps/statistics/admin.py
from django.contrib import admin
from .models import Statistic
class StatisticAdmin(admin.ModelAdmin):
model = Statistic
admin.site.register(Statistic, StatisticAdmin)
| StarcoderdataPython |
4822572 | from django.contrib import admin
from .models import Post, Category, Comment
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
list_display = ('post_title', 'category', 'created_on')
list_filter = ('category', 'created_on',)
search_fields = ('post_title', 'category',)
@admin.register(Comment)
cl... | StarcoderdataPython |
183887 | <reponame>flother/ember
from dataclasses import dataclass
import json
import mimetypes
import sqlite3
class TileNotFound(ValueError):
pass
class Metadata:
"""
Key/value store for settings for a tileset's settings.
<https://github.com/mapbox/mbtiles-spec/blob/master/1.3/spec.md#metadata>
"""
... | StarcoderdataPython |
3216153 |
# coding: utf-8
# In[5]:
import pickle
import tensorflow as tf
import numpy as np
import tf_util
import gym
import load_policy
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
import matplotlib.pyplot as plt
from torch.optim.lr_scheduler import StepLR
class CN... | StarcoderdataPython |
4842274 | <reponame>grigi/pybbm
# -*- coding: utf-8 -*-
import math
from django.contrib.auth.decorators import login_required
from django.core.exceptions import ObjectDoesNotExist, PermissionDenied
from django.core.urlresolvers import reverse
from django.contrib import messages
from django.db.models import F, Q
from django.htt... | StarcoderdataPython |
93692 | <reponame>d3b-center/d3b-release-maker
#!/usr/bin/env python
import click
import re
import subprocess
from d3b_release_maker.release_maker import make_release, new_notes
def get_repository():
"""
Try to retrieve the github repository by extracting it from the current git
repository's 'origin' url.
""... | StarcoderdataPython |
175103 | import tcatpost
import datetime
def get_info(startLocations, endLocations):
bus_info = {}
for startLocation in startLocations:
for endLocation in endLocations:
key = startLocation[0]["Name"] + "|" + endLocation[0]["Name"]
bus_info[key] = {}
routes, boardTimes, offTi... | StarcoderdataPython |
136515 | #!/usr/bin/python
# Copyright: Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
... | StarcoderdataPython |
25855 | <reponame>darioblanco/blogjaguar
# Copyright 2011 <NAME>
#
# 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 |
1622151 | """Unit test package for kanboard_copier."""
| StarcoderdataPython |
1790189 | <filename>todb/importer.py
from datetime import datetime
from typing import List
from todb.db_client import DbClient
from todb.logger import get_logger
from todb.util import split_in_half, seconds_between
INSERT_ONE_BY_ONE_THRESHOLD = 8
class Importer(object):
def __init__(self, db_client: DbClient) -> None:
... | StarcoderdataPython |
3270362 | <gh_stars>0
from enums.argument_enum import ArgumentEnum
class Challenge(ArgumentEnum):
OCREvaluation = 'ocr-evaluation'
| StarcoderdataPython |
179876 | <reponame>danieldrichards/NFT<gh_stars>0
from setuptools import setup
import io
def version():
"""Return version string."""
with io.open('nft/nft.py') as input_file:
for line in input_file:
if line.startswith('__version__'):
return ast.parse(line).body[0].value.s
with io.ope... | StarcoderdataPython |
3257983 | # uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]
# Embedded file name: T:\InGame\Gameplay\Scripts\Server\situations\situation_goal_purchased_object.py
# Compiled at: 2020-07-15 22:36:24
# Size of source mo... | StarcoderdataPython |
1760405 | from sklearn.pipeline import Pipeline
from sklearn.svm import SVC
from sklearn.preprocessing import StandardScaler
from pandas import DataFrame
def svm_training (training_X,training_y):
'''
Input:
training_X: a dataframe of feature matrix created by Tagged_Maf.make_feature_table
training_Y: a list of corresponding... | StarcoderdataPython |
57325 | from textwrap import dedent
import os
import subprocess
import numpy
import pandas
from wqio.tests import helpers
from wqio.utils import numutils
def _sig_figs(x):
""" Wrapper around `utils.sigFig` (n=3, tex=True) requiring only
argument for the purpose of easily "apply"-ing it to a pandas
dataframe.
... | StarcoderdataPython |
1613730 | import os
try:
from urllib.request import urlretrieve
except ImportError:
from urllib import urlretrieve
from tqdm.auto import tqdm
LOCAL_CACHE_DIR = os.path.join(os.path.expanduser("~"), "implicit_datasets")
def download_file(url, local_filename):
""" Simple wrapper around urlretrieve that uses tqdm t... | StarcoderdataPython |
3388018 | import os
from .base import StorageBackend
from muninn.schema import Mapping, Text, Boolean
import muninn.util as util
from muninn.exceptions import Error
import muninn.config as config
from muninn.util import product_size
class _FSConfig(Mapping):
_alias = "fs"
root = Text()
use_symlinks = Boolean(opt... | StarcoderdataPython |
176438 | <filename>examples/rds/v3/log.py<gh_stars>10-100
#!/usr/bin/python
# -*- coding: UTF-8 -*-
from openstack import connection
projectId = "xxxxxxxxxxxxxx"
cloud = "xxxxxxxxxxxxxx" # cdn use: cloud = "myhwclouds.com"
region = "xxxxxxxxxxxxxx" # example: region = "cn-north-1"
AK = "<KEY>"
SK = "<KEY>"
conn = connect... | StarcoderdataPython |
3373300 | # This extension is intended to be built with autocython. To trigger a build on a
# new platform, run the code that imports the extension, or run:
# python -m autocython
# in this directory.
from setuptools import setup
from setuptools.extension import Extension
from Cython.Distutils import build_ext
from autocython im... | StarcoderdataPython |
3284501 | #!/usr/bin/env python3
# Author: <NAME> <<EMAIL>>
"""Analyzes pure commenters."""
from glob import glob
import pandas as pd
import networkx as nx
DATA_FILE = "./312_author_data/data.csv"
NETWORKS_FOLDER = "./200_yearly_networks/"
METRICS_FILE = "./313_author_metrics/metrics.csv"
GENDER_FILE = "./350_gender_estimat... | StarcoderdataPython |
1613128 |
import sys
sys.path.append("..")
from common.utils import Node
from rust.long_macros import *
#%%
def paintLineOn(buff, text, indent):
buff += indent + text + "\n"
return buff
def paint_type(typeName):
if typeName.value == "Generic":
base, *args = typeName.children
base, a... | StarcoderdataPython |
1612286 | import ctypes
class GD32VF1xxUsbfs:
class Type(ctypes.Structure):
""" USB full speed global registers
"""
_fields_ = [
("GOTGCS" , ctypes.c_uint32), # Address offset: 0x0, Global OTG control and status register (USBFS_GOTGCS)
("GOTGINTF" , ctypes.c_uin... | StarcoderdataPython |
4810342 | <filename>tests/test_controllers/test_auth.py<gh_stars>0
from freezegun import freeze_time
import jwt
import pytest
from src.controllers.auth import AuthenticationController
from src.models.user import User
def test_verify_user_should_pass_when_user_provides_correct_credential(mocker):
mocker.patch(
"src... | StarcoderdataPython |
3293968 | import os
import glob
import argparse
def findUnMatched():
parser = argparse.ArgumentParser(description = "TrainArgs");
parser.add_argument('--mp4_dir', type=str, default="voxceleb2/dev/mp4", help='', required = True);
parser.add_argument('--txt_dir', type=str, default="voxceleb2/dev/txt", help='', requi... | StarcoderdataPython |
29311 | <gh_stars>1-10
import re
from flask import Flask, request
app = Flask(__name__)
def generate_whitelist():
whitelist = []
with open('/whitelist.txt', 'r') as f:
for line in f.readlines():
if line.strip().endswith('d.wott.local'):
whitelist.append(line.strip())
return wh... | StarcoderdataPython |
1721234 | <gh_stars>10-100
from urllib.parse import urljoin
from akismet import Akismet, SpamStatus
from django.contrib.sites.shortcuts import get_current_site
from django.core.exceptions import ImproperlyConfigured
from django.utils.encoding import smart_str
import fluent_comments
from fluent_comments import appsettings
def... | StarcoderdataPython |
3356761 | <reponame>SeanMabli/aiinpy
import numpy as np
class stablesoftmax:
def __repr__(self):
return 'stablesoftmax()'
def forward(self, input):
a = np.exp(input - np.max(input))
return a / np.sum(a)
def backward(self, input):
forward = np.exp(input - np.max(input)) / np.sum(np.exp(input - np.max(inpu... | StarcoderdataPython |
1766477 | <reponame>linea-it/tno
from rest_framework import viewsets
from des.models import SummaryDynclass
from des.serializers import SummaryDynclassSerializer
class SummaryDynclassViewSet(viewsets.ModelViewSet):
queryset = SummaryDynclass.objects.all()
serializer_class = SummaryDynclassSerializer
ordering_fiel... | StarcoderdataPython |
3233505 | <filename>tools.py
from flask import Blueprint
from flask import request, render_template, abort
from flask import current_app as app
bp = Blueprint('tools', __name__)
@bp.route('/myip')
def myip():
ip = request.headers.get(app.config['REMOTE_ADDR_HEADER'], request.remote_addr)
return render_template('m... | StarcoderdataPython |
3377434 | """Benchmark for `cdjs`
Benchmark compares:
- standard `json` with `bson.json_util.default` handler
- `orjson` with `bson.json_util.defaul` handler
- `orjson` with `cdjs.serialize` handler
- `orjson` with `cdjs.do_nothing` handler as a baseline
"""
from datetime import timedelta
from random import ran... | StarcoderdataPython |
1694328 | <reponame>JamaSoftware/analyze-python
import unittest
from .format_test import FormatTestCase
from .client_test import * # pylint: disable=wildcard-import
if __name__ == '__main__':
unittest.main()
| StarcoderdataPython |
40559 | <gh_stars>0
import sys
def solve2(n, m):
if n == 1 and m == 1:
return []
check = []
count = 1
for i in xrange(n):
for j in xrange(m):
if j + 1 <= m and (count + 1 <= (n * m)) and not(count + 1 > m * (i + 1)):
check.append([count, count + 1])
if (i... | StarcoderdataPython |
139314 | <gh_stars>1-10
# -*- coding: utf-8 -*-
"""Generic Embulk Task."""
from pathlib import Path
from typing import Dict, Optional
from luft.common.config import (AWS_ACCESS_KEY_ID, AWS_BUCKET, AWS_ENDPOINT, AWS_SECRET_ACCESS_KEY,
BLOB_STORAGE, EMBULK_DEFAULT_TEMPLATE, GCS_APP_NAME,
... | StarcoderdataPython |
3360016 | """add ht sequence.
Revision ID: a32c725ae353
Revises: <KEY>
Create Date: 2020-11-16 16:41:01.995768
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "a32c725ae353"
down_revision = "<KEY>"
branch_labels = None
depends_on = None
def upgrade():
op.execute("CRE... | StarcoderdataPython |
1686529 | from django.shortcuts import render, get_object_or_404, redirect
from .models import Post
from .forms import ArticleForm
from django.utils import timezone
# Create your views here.
def home(request):
articles = Post.objects.filter(author=request.user)
return render(request, "articles/index.html", {"articles":... | StarcoderdataPython |
3224210 | <gh_stars>10-100
import os
COWIN_URL = os.getenv('COWIN_URL')
STATES_URL = f'{COWIN_URL}admin/location/states/'
DISTRICTS_URL = f'{COWIN_URL}admin/location/districts/'
CALENDAR_BY_DISTRICT_PUBLIC_URL = f'{COWIN_URL}appointment/sessions/public/calendarByDistrict/'
CALENDAR_BY_DISTRICT_URL = f'{COWIN_URL}appointment/ses... | StarcoderdataPython |
3379562 | <filename>python/examples/encryption/encrypt.py<gh_stars>100-1000
# Copyright (c) 2020 PaddlePaddle 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:... | StarcoderdataPython |
1768901 | from django.core.management.base import BaseCommand, CommandError
import re
import requests
import pprint
from pokemon_api.models import Pokemon, Stats, EvolutionChain
URL_EVOLUTION = "https://pokeapi.co/api/v2/evolution-chain/"
URL_POKEMON = "https://pokeapi.co/api/v2/pokemon/"
class Command(BaseCommand):
help ... | StarcoderdataPython |
50776 | import unittest
import collections_and_iterators
""" Linked lists - TESTS
Testing Collections programming examples from collections.py
"""
class TestObjectMethods(unittest.TestCase):
def setUp(self):
self.singleLinkList = collections_and_iterators.SinglyLinkedList()
self.singleLink... | StarcoderdataPython |
3395137 | from ..cooking_machine.models import TopicModel
from topicnet.cooking_machine.models.thetaless_regularizer import artm_dict2df
from gensim.models import KeyedVectors
from gensim.models.keyedvectors import Word2VecKeyedVectors
import pandas as pd
import numpy as np
def topic_model_to_keyed_vectors(model: TopicModel, m... | StarcoderdataPython |
3203691 | <gh_stars>1-10
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2021/1/10 12:53 下午
# @Author : WPrince
# @Site :
# @File : SQLBase.py
# @Software: PyCharm
import sqlite3
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
def create_db_connection():
"""
establish a... | StarcoderdataPython |
1799672 | <reponame>lucasLB7/LucasPortfiolio<filename>portfolio_main/admin.py
from django.contrib import admin
from .models import Resume
admin.site.register(Resume)
# admin.site.register(new_laminate_input2) | StarcoderdataPython |
3380595 | """ Dummy interface with the segmentation model """
from typing import List
import numpy as np
from .seg_base import SegBase
class SegDummy(SegBase):
""" Class for segmentation dummy interface """
def __init__(self, _home: str) -> None:
# init method for consistent API
return
def convert_... | StarcoderdataPython |
102076 | <reponame>CodedLadiesInnovateTech/python-challenges<filename>Phase-3/Python Challenge/Day-88.py
'''
1. Write a Python program to find three numbers from an array such that the sum of three numbers equal to a given number
Input : [1, 0, -1, 0, -2, 2], 0)
Output : [[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]
2. Write ... | StarcoderdataPython |
3232891 | <gh_stars>0
"""ECCO v4 Python: read_bin_gen
This module includes utility routines for loading general binary files,
not necessarily in the lat-lon-cap layout. For LLC type data, see read_bin_llc.
.. _ecco_v4_py Documentation :
https://github.com/ECCO-GROUP/ECCOv4-py
"""
from __future__ import division,... | StarcoderdataPython |
132724 | # Copyright 2018-2020 Xanadu Quantum Technologies 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 |
4066 | '''
pymmh3 was written by <NAME> and enhanced by <NAME>, and is placed in the public
domain. The authors hereby disclaim copyright to this source code.
pure python implementation of the murmur3 hash algorithm
https://code.google.com/p/smhasher/wiki/MurmurHash3
This was written for the times when you do not want to c... | StarcoderdataPython |
173003 | <reponame>YannickDieter/beam_telescope_analysis
#!/usr/bin/env python
from setuptools import setup, find_packages, Extension # This setup relies on setuptools since distutils is insufficient and badly hacked code
import numpy as np
from distutils.command.build_ext import build_ext
from Cython.Build import cythonize
im... | StarcoderdataPython |
3361942 | <filename>examples/waterbodies.conflux.py<gh_stars>0
import xarray as xr
product_name = 'waterbodies'
version = '0.0.1'
resampling = 'nearest'
output_crs = 'EPSG:3577'
resolution = (-25, 25)
input_products = {
'wofs_albers': ['water'],
}
def transform(inputs: xr.Dataset) -> xr.Dataset:
# ignore sea, terrain... | StarcoderdataPython |
111331 | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2017-10-09 14:08
from __future__ import unicode_literals
from django.db import migrations, models
import re
import django.db.models.deletion
def calculate_num_questions(resource, ScormElement):
re_objective_id_key = r'^cmi.objectives.([0-9]+).id$'
top_key =... | StarcoderdataPython |
196541 | <reponame>danieliheonu/bigfastapi
import random
import re
import validators
import fastapi
import json
import pkg_resources
DATA_PATH = pkg_resources.resource_filename('bigfastapi', 'data/')
def generate_short_id(size=9, chars='ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
return ''.join(random.choice(chars) for _ in ... | StarcoderdataPython |
1680861 | <reponame>danielfrascarelli/esys-particle
#############################################################
## ##
## Copyright (c) 2003-2017 by The University of Queensland ##
## Centre for Geoscience Computing ##
## http://earth.uq.edu.au/cent... | StarcoderdataPython |
1675526 | from __future__ import annotations
import asyncio
import datetime
import typing
from . import base, fields
from .chat_invite_link import ChatInviteLink
from .chat_location import ChatLocation
from .chat_member import ChatMember
from .chat_permissions import ChatPermissions
from .chat_photo import ChatPhoto
from .inpu... | StarcoderdataPython |
1680477 | from .embpy import embed
| StarcoderdataPython |
4831207 | <gh_stars>1-10
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.homePage, name='home'),
url(r'^message/$', views.messagePage, name='message'),
url(r'^represent/', views.meetTheReps, name='represent'),
url(r'^calendar/$', views.calEvents, name='calendar'),
url(r'... | StarcoderdataPython |
127932 | from django.conf import settings
from django.core.management.base import BaseCommand
from ... import invitations
class Command(BaseCommand):
help = "Create invitation for user to set up TOTP"
def add_arguments(self, parser):
parser.add_argument('username')
parser.add_argument('--duration', t... | StarcoderdataPython |
67654 | <gh_stars>10-100
from kubectl.kubectl import Kubectl
| StarcoderdataPython |
4811638 | <filename>Core/overseer/overseer.py<gh_stars>0
# overseer.py
#
# Abstract class definition for the MyTardis overseer class.
#
# written by <NAME> <<EMAIL>>
#
# Last updated: 05 Aug 2020
#
from urllib.parse import urlparse
# Import minions
from .project_minion import ProjectMinion
from .experiment_minion import Experi... | StarcoderdataPython |
3320749 | <reponame>iscc/iscc-sdk<gh_stars>1-10
import pytest
from iscc_samples import images, texts, audios, videos
import shutil
from PIL import Image, ImageDraw
@pytest.fixture(scope="module")
def jpg_file(tmp_path_factory) -> str:
dst = tmp_path_factory.mktemp("data") / "img.jpg"
shutil.copy(images("jpg")[0], dst)
... | StarcoderdataPython |
1643252 | from enum import Enum
class TmpLabelName(Enum):
tmp = "Tmp"
| StarcoderdataPython |
60445 | """
``$ drafttopic fetch_text -h``
::
Fetches text for labelings using a MediaWiki API.
Usage:
fetch_text --api-host=<url> [--labelings=<path>] [--output=<path>]
[--verbose]
Options:
-h --help Show this documentation.
--api-host=<url> ... | StarcoderdataPython |
155103 | #!/usr/bin/env python
"""
This program will clean out missing mate pairs from a FASTQ file.
Matching mates will be written into a new FASTQ file.
@author: <NAME> <<EMAIL>>
@copyright: 2012
@version: 0.1
@since: 2012-04-13
"""
import sys
print sys.argv
# Open input file
inFile = open(sys.argv[1], "r")
# Open output... | StarcoderdataPython |
186025 | <gh_stars>0
def test():
assert gato_hash == nlp.vocab.strings["gato"], "Você atribuiu o código hash corretamente?"
assert 'nlp.vocab.strings["gato"]' in __solution__, "Você selecionou a string corretamente?"
assert gato_string == "gato", "Você selecionou a string corretamente?"
assert (
"nlp.voc... | StarcoderdataPython |
1700821 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
import OAparser
if sys.argv[1]:
logfile = sys.argv[1]
parser = OAparser.Parser(logfile)
#for i in parser.log:
# print(i, parser.log[i])
| StarcoderdataPython |
1703220 | <reponame>MacroYau/PyHK80
from hk80 import coordinates
class LatLon:
"""
Representation of WGS 84 latitude and longitude.
"""
def __init__(self, latitude, longitude):
"""
Constructor with latitude and longitude.
Parameters
----------
latitude : float
... | StarcoderdataPython |
4838458 | __version__ = "0.2.1dev"
from .scenario import DeflexScenario # noqa: F401
from .scenario import Scenario # noqa: F401
| StarcoderdataPython |
1667626 | <filename>gork/utils.py
from gork.palette import COLOR_TREE, PALETTE
from gork.structs import RGB, Color
DEFAULT_PIXEL_SIZE = 10
DEFAULT_N_CLUSTERS = 256
def get_nearest_color(rgb: RGB) -> Color:
distance, result = COLOR_TREE.query(rgb.as_tuple)
return PALETTE[result]
| StarcoderdataPython |
3231047 | def outer():
x=3
def inner():
y=3
res=x+y
return res
return inner
a= outer()
print(a())
print(a.__name__)
| StarcoderdataPython |
1688906 | <reponame>hwp/apkit
"""
visualize.py
Copyright (c) 2017 Idiap Research Institute, http://www.idiap.ch/
Written by <NAME> <<EMAIL>>
"""
import numpy as np
import matplotlib.pyplot as plt
def plot_wave(fs, signal):
"""Plot wave of singals.
Args:
fs : sample rate.
signal : multi-channel ti... | StarcoderdataPython |
3275940 | <gh_stars>0
# Generated by Django 3.0.6 on 2020-05-10 23:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0005_auto_20200510_2150'),
]
operations = [
migrations.AlterField(
model_name='user',
name='... | StarcoderdataPython |
3347007 | <gh_stars>0
from flask import Flask, render_template, request
from manager import Manager
from technician import Technician
from user import User
from student import Student
import datetime
import json
app = Flask(__name__)
m = Manager()
t = Technician()
u = User()
s = Student()
@app.route('/')
def hello():
... | StarcoderdataPython |
3209929 | <gh_stars>1-10
"""
This module allows users to inspect the conditions under which a smart contract was deployed.
"""
import logging
import os
import time
from typing import Dict, Optional
from eth_typing.evm import ChecksumAddress
from web3 import Web3
CONFIG_KEY_WEB3_INTERVAL = "web3_interval"
CONFIG_KEY_WEB3_LAST_C... | StarcoderdataPython |
1794069 | #!/usr/bin/env python
# -*- coding: utf8 -*-
import MFRC522
import signal
import time
import picamera
import base64
import requests
import json
import RPi.GPIO as GPIO
from subprocess import call
continue_reading = True
def end_read(signal, frame):
global continue_reading
print('Ctrl+C captured, ending read... | StarcoderdataPython |
1647032 | <reponame>kbelsvik/career-skills-capstone<filename>careers-api/functions/word_preprocessing.py
import re, unicodedata
import nltk
import contractions
from nltk import word_tokenize
from nltk.stem import WordNetLemmatizer
from nltk.corpus import stopwords
def preprocess_list(list_of_summaries):
list_preprocessed_su... | StarcoderdataPython |
3364592 | <reponame>snehangsude/Caeser-Cipher
from data import alphabet
class Cipher:
"""class contains methods to encrypt and decryot a text based on move"""
def __init__(self):
self.list = []
self.new_word = []
def convert(self, text=""):
"""Converts the input text into a list"""
... | StarcoderdataPython |
3245934 | import logging
import re
from flatten_json import flatten
import archiver.ena
from archiver import biostudies, ena, biosamples
from archiver.dsp_post_process import dsp_attribute, fixed_dsp_attribute
from archiver.instrument_model import to_dsp_name
from conversion.json_mapper import JsonMapper, json_array, json_obje... | StarcoderdataPython |
164708 | <filename>api/api/utils/marshmallow.py
"""Injection of generated marshmallow schemas into SQLAlchemy model classes.
Adapted from https://marshmallow-sqlalchemy.readthedocs.io/en/latest/recipes.html#automatically-generating-schemas-for-sqlalchemy-models
"""
from marshmallow_sqlalchemy import ModelConversionError, SQLA... | StarcoderdataPython |
1721729 | <reponame>flx42/DALI
# Copyright (c) 2019, NVIDIA CORPORATION. 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
#
# Unle... | StarcoderdataPython |
3247096 | <gh_stars>0
"""empty message
Revision ID: 01ca5c43ac9d
Revises: 73bce8369050
Create Date: 2021-12-26 00:20:31.060311
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "01ca5c43ac9d"
down_revision = "73bce8369050"
branch_labels = None
depends_on = None
def upgra... | StarcoderdataPython |
3331126 | import functools
from contextlib import closing
from copy import deepcopy
from xml.etree import ElementTree
from zipfile import ZipFile
from heroicons._compat import open_binary, str_removeprefix
class IconDoesNotExist(Exception):
pass
@functools.lru_cache(maxsize=128)
def _load_icon(style: str, name: str) -> ... | StarcoderdataPython |
161257 | import math
from collections import OrderedDict
import logging
logger = logging.getLogger(__name__)
import numpy as np
import torch
import tensorflow as tf
from paragen.generators import AbstractGenerator, register_generator
from paragen.utils.io import remove
from paragen.utils.runtime import Environment
@register... | StarcoderdataPython |
1606963 | <reponame>grecoe/teals<gh_stars>0
import json
class Configuration:
CONFIG_USERS = 'user_file'
CONFIG_HISTORY = "history"
def __init__(self, config_file):
self.config_file = config_file
self.data = None
self._load()
def get_history_file(self):
return self.data[Configu... | StarcoderdataPython |
6005 | <reponame>MyWay/Create-Your-Own-Image-Classifier
#!/usr/bin/env python3
""" train_args.py
train_args.py command-line args.
"""
import argparse
def get_args():
"""
"""
parser = argparse.ArgumentParser(
description="This script lets you train and save your model.",
usage="python3 train.py f... | StarcoderdataPython |
1692587 | import os
import numpy as np
import warnings
import scipy.constants as sc
import optical_models as om
class Metal:
'''
Outline for a class describing metals.
'''
def __init__(self, model,modelparams):
if model=='DrudeSommerfeld':
if np.size(modelparams)!=2:
raise Exception('modelparams must have exa... | StarcoderdataPython |
3229574 | <reponame>anurag-gandhi/pandas-profiling
import pandas as pd
from pandas_profiling import ProfileReport
from pandas_profiling.utils.cache import cache_file
if __name__ == "__main__":
file_name = cache_file(
"titanic.csv",
"https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.c... | StarcoderdataPython |
3349299 | <reponame>akulakov/explore<filename>explore/items.py
from shared import Object
class Item(Object):
pass
celtic_knife = Item("Knife", '🔪', 1000)
celtic_knife.description = """
A knife with a celtic knot engraved on the hilt. The knife is sunk into a heavy stone
and cannot be removed.
"""
clover = Item("Clover"... | StarcoderdataPython |
17409 | from django.core.exceptions import FieldError
from staff.models import Staff
import re
def get_choices():
# choices in a seperated funtion to change it easier
STATUS_CHOICES = (
('', ''),
('Test', 'Test'),
('Fertig', 'Fertig'),
('Löschen', 'Löschen'),
('Vertrieb', 'Vert... | StarcoderdataPython |
3321004 | <reponame>Frederick-S/braindump<filename>migrations/versions/3b4b395f61a9_initial_migration.py<gh_stars>100-1000
"""Initial Migration
Revision ID: <PASSWORD>
Revises: None
Create Date: 2016-05-12 18:37:31.644301
"""
# revision identifiers, used by Alembic.
revision = '<PASSWORD>'
down_revision = None
from alembic i... | StarcoderdataPython |
76330 |
from dataset.animeface import (
AnimeFace,
AnimeFaceCelebA,
AnimeFaceSR,
AnimeFaceXDoG,
AnimeFaceLabel,
AnimeFaceOneHot
)
from dataset.portrait import (
DanbooruPortrait,
DanbooruPortraitCelebA,
DanbooruPortraitSR,
DanbooruPortraitXDoG
)
from dataset.danbooru import (
Danb... | StarcoderdataPython |
3378218 | import sys
import math
import random
class emotion:
def __init__(self,call):
self.call=call
def look_around(self):
data = [0x16,0x01,0x01]
self.call.blewrite(data)
self.call.blewait()
def smile(self):
data = [0x16,0x01,0x27]
self.call.blewrite(data)
s... | StarcoderdataPython |
66268 | #! /usr/bin/env python
# $Id: normalize.py,v 1.1 2004/11/17 09:33:01 mliang Exp $
# normalizes values to 1.0
import sys,os
import getopt
import fileinput
from Numeric import *
from MLab import *
def eusage():
print "Usage: %s [OPTIONS] [FILENAME...]" % os.path.basename(sys.argv[0])
sys.exit()
def myfmt(obj):... | StarcoderdataPython |
1798805 | <reponame>xmmmmmovo/MyAlgorithmSolutions
"""
面试题 17.16. 按摩师
一个有名的按摩师会收到源源不断的预约请求,每个预约都可以选择接或不接。
在每次预约服务之间要有休息时间,因此她不能接受相邻的预约。
给定一个预约请求序列,替按摩师找到最优的预约集合(总预约时间最长),
返回总的分钟数。
注意:本题相对原题稍作改动
输入: [1,2,3,1]
输出: 4
解释: 选择 1 号预约和 3 号预约,总时长 = 1 + 3 = 4。
输入: [2,7,9,3,1]
输出: 12
解释: 选择 1 号预约、 3 号预约和 5 号预约,总时长 = 2 + 9 + 1 = 12。
输入:... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.