id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
8055110 | import httplib
import urllib
import urlparse
import BaseHTTPServer, SimpleHTTPServer
import json
from settings import SERVER_PORT, PROTOCOL, HOSTNAME, PORT, CLIENT_ID, CLIENT_SECRET
class StoppableHttpServer(BaseHTTPServer.HTTPServer):
def serve_forever(self):
self.stop = False
while not self.stop... | StarcoderdataPython |
172683 | <reponame>vfdev-5/ignite-examples
from argparse import ArgumentParser
from pathlib import Path
from train import run
if __name__ == "__main__":
parser = ArgumentParser()
parser.add_argument("config_cv_folder", type=str,
help="Folder with configuration files")
args = parser.parse_a... | StarcoderdataPython |
6607248 | import click
from ocrd.decorators import ocrd_cli_options, ocrd_cli_wrap_processor
from gbn.sbb.predict import OcrdGbnSbbPredict
from gbn.sbb.binarize import OcrdGbnSbbBinarize
from gbn.sbb.crop import OcrdGbnSbbCrop
from gbn.sbb.segment import OcrdGbnSbbSegment
@click.command()
@ocrd_cli_options
def ocrd_gbn_sbb_pre... | StarcoderdataPython |
154964 | '''
Function:
视频下载器基类
Author:
Charles
微信公众号:
Charles的皮卡丘
'''
import requests
from ..utils import Downloader
'''视频下载器基类'''
class Base():
def __init__(self, config, logger_handle, **kwargs):
self.source = None
self.session = requests.Session()
self.session.proxies.update(config['... | StarcoderdataPython |
1915842 |
#Python has a set of built-in methods that you can use on dictionaries.
Method Description
---------------------------------------------------------------------------------------------------------------------------------------------------------------------
clear() Removes all the elements from the d... | StarcoderdataPython |
6542980 | <reponame>ninapavlich/scout-and-rove
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from django.contrib.sites.models import Site
try:
from django.apps import apps
get_model = apps.get_model
except:
from django.db.models.loading import get_model
from scou... | StarcoderdataPython |
170454 | <filename>main.py
from app.server import app
import os
production = os.environ.get("PRODUCTION", False)
if __name__ == "__main__":
if production:
app.run(debug=True)
else:
app.run(debug=True,port="2020") | StarcoderdataPython |
3513846 | import math
from math import pi, cos, sin, sqrt, atan
def sign(x):
if x > 0:
return 1
elif x < 0:
return -1
else:
return 0
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return '({:.2f}, {:.2f})'.format(self.x, self.... | StarcoderdataPython |
330042 | import pandas as pd
from sklearn import linear_model
from sklearn.preprocessing import StandardScaler
# Assign the data to predictor and outcome variables
train_data = pd.read_csv('data.csv', header=None)
X = train_data.iloc[:,:-1]
y = train_data.iloc[:,-1]
# Create the standardization scaling object
scaler = Standar... | StarcoderdataPython |
9633347 | #!/usr/bin/env python3
# coding: utf-8
r"""
冻结集合类型。
::
+-> Container: obj.__contains__(self, item) # item in obj
|
+-> Sized: obj.__len__(self) # len(obj)
|
+-> Iterable: obj.__iter__(self) # iter(obj)
|
+-... | StarcoderdataPython |
3202461 | #!/usr/bin/env python
"""
test_gitdl
----------------------------------
Tests for `gitdl` module.
"""
import json
import os
import unittest
import pytest
from mock import patch
import requests
import requests_mock
from gitdl import gitdl
class TestGitdl(unittest.TestCase):
def test_params_invalid_api_token... | StarcoderdataPython |
65746 | <filename>wrangalytics/config/api.py
def debug(x):
print(x)
### Notebook Magics
# %matplotlib inline
def juptyerConfig(pd, max_columns=500, max_rows = 500, float_format = '{:,.6f}', max_info_rows = 1000, max_categories = 500):
pd.options.display.max_columns = 500
pd.options.display.max_rows = 500
pd.o... | StarcoderdataPython |
3556157 | from bs4 import BeautifulSoup as bs
from win10toast import ToastNotifier
from urllib.request import urlopen,Request
header = {'User-Agent':'Mozilla'}
request = Request("https://www.worldometers.info/coronavirus/country/nigeria/", headers= header)
html = urlopen(request)
html.readline()
soup = bs (html, 'html.parser')... | StarcoderdataPython |
1982078 | <reponame>krisshol/bach-kmno
#
# Copyright (c) 2013-2018 Quarkslab.
# This file is part of IRMA project.
#
# 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 in the top-level directory
# of this dist... | StarcoderdataPython |
9665562 | import django_tables2 as tables
from django.utils.safestring import mark_safe
from django_tables2.utils import Accessor
from dcim.models import Interface
from tenancy.tables import TenantColumn
from utilities.tables import (
BaseTable, BooleanColumn, ButtonsColumn, ChoiceFieldColumn, ContentTypeColumn, LinkedCount... | StarcoderdataPython |
9750415 | <reponame>afq984/viewtools
import reprlib
import collections.abc
from typing import Sequence, Any
class SequenceView:
__slots__ = ('_seq', '_range')
def __init__(self, seq: Sequence[Any], *, _range=None):
if not isinstance(seq, collections.abc.Sequence):
raise TypeError(f'seq must be a se... | StarcoderdataPython |
8160620 | <gh_stars>0
from confluent_kafka import Consumer, KafkaException
import sys
import json
import logging
from pprint import pformat
"""
twitter-kafka-consumer
This is a basic python consumer that reads twitter data from a kafka topic.
Usage:
- Operation requires a running instance of kafka
- "twitter-kafka-producer" r... | StarcoderdataPython |
238246 | <filename>tests/test_decentrafact.py
import pytest
import brownie
from brownie import FactItem, VoteManager, interface, chain
from scripts.helpful_scripts import get_account, get_contract
@pytest.fixture
def deploy_fact():
account = get_account()
fact_item = FactItem.deploy(
{"from": account}
)
... | StarcoderdataPython |
3300456 | <filename>examples/run.py
import logging
from web_client import create_app
# os.system("killall -9 gunicorn")
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
app = create_app()
if __name__ == '__main__':
## production
# current_dir_path = os.path.abspath(os.path.dirname(__file__))
# os.sys... | StarcoderdataPython |
269337 | from functools import partial
from unittest import TestCase
from py4j.java_gateway import java_import
from pymrgeo.rastermapop import RasterMapOp
class RasterMapOpTestSupport(TestCase):
def __init__(self, mrgeo):
self._mrgeo = mrgeo
jvm = self._mrgeo._get_jvm()
# Import the raster map op... | StarcoderdataPython |
6450322 | # Copyright (c) 2020 NVIDIA Corporation. All rights reserved.
# This work is licensed under the NVIDIA Source Code License - Non-commercial. Full
# text can be found in LICENSE.md
import torch
import torch.utils.data as data
import os, math
import sys
import time
import random
import numpy as np
import numpy.random as... | StarcoderdataPython |
4841914 | from cffi import FFI
ffibuilder = FFI()
ffibuilder.set_source(
"aiortc.codecs._opus",
"""
#include <opus/opus.h>
""",
libraries=["opus"],
)
ffibuilder.cdef(
"""
#define OPUS_APPLICATION_VOIP 2048
#define OPUS_OK 0
typedef struct OpusDecoder OpusDecoder;
typedef struct OpusEncoder OpusEncoder;
ty... | StarcoderdataPython |
9687542 | <reponame>vikpe/chromato<filename>chromato/validation.py<gh_stars>0
import numbers
import string
from chromato import constants
def is_bool(value) -> bool:
return isinstance(value, bool)
def is_int(value) -> bool:
return not is_bool(value) and isinstance(value, int)
def is_int_in_range(value, range_from,... | StarcoderdataPython |
5138316 | from unittest import TestCase
from SortArrayParity2 import sortArrayByParityII
class Test(TestCase):
def test_sort_array_by_parity_ii(self):
self.assertEqual(sortArrayByParityII([4, 2, 5, 7]), [4, 5, 2, 7])
self.assertEqual(sortArrayByParityII([4, 2, 5, 7]), [4, 7, 2, 5])
self.assertEqual(... | StarcoderdataPython |
11286787 | # -*- coding: utf8 -*-
import win32gui
import win32con
import sys
from PyQt5 import QtWidgets, QtGui, QtCore
class CheckItemModel(QtGui.QStandardItemModel):
def __init__(self, parent, callback):
super(CheckItemModel, self).__init__(parent)
self.itemChanged.connect(self.onItemChanged)
... | StarcoderdataPython |
3237368 | <filename>SoundForge.py
import sys
import random
import math
import os
import pyaudio
import pygame
from pygame.locals import *
from random import *
import numpy
from numpy import sqrt, log
from recorder import SwhRecorder #http://www.swharden.com/blog/2013-05-09-realtime-fft-audio-visualization-with-python/
from fre... | StarcoderdataPython |
6632022 | <reponame>willuvbb/test_fastapi_template
import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from application.initializer import IncludeAPIRouter
from application.main.config import settings
def get_application():
_app = FastAPI(title=settings.API_NAME,
... | StarcoderdataPython |
8113343 | <filename>wagtail_events/models.py
from django.db import models
from wagtail.admin.edit_handlers import FieldPanel, StreamFieldPanel, MultiFieldPanel
from wagtail.core.blocks import CharBlock, TextBlock, BlockQuoteBlock
from wagtail.core.fields import StreamField
from wagtail.core.models import Page
from wagtail.images... | StarcoderdataPython |
8098244 | <reponame>scuzzilla/snmp-poller
'''
### pysnmp_logging
#
Author: <NAME>
em@il: <EMAIL>
Starting date: 21-04-2021
Last change date: 19-08-2021
Release date: TBD
'''
def pysnmp_logging(logging_file_path):
'''
logging function
'''
import logging
# logger creation
log... | StarcoderdataPython |
11282613 | # Copyright (c) Open-MMLab. All rights reserved.
__version__ = '0.17.0'
short_version = __version__
| StarcoderdataPython |
1949348 | <reponame>KuipersT/CS2900-Lab-2<filename>tester/cp2.py<gh_stars>0
test = {
'name': 'checkpoint-2',
'points': 1,
'suites': [
{
'cases': [
{
'code': r"""
>>> # It seems X is undefined. Have you defined it correctly?
... | StarcoderdataPython |
1660802 | <reponame>sbesson/ansible-all
#! /usr/bin/env python
import requests
import subprocess
GH_SEARCH_API = ('https://api.github.com/search/repositories'
'?q=ansible-role-+in:name+org:ome+fork:true')
def get_repos():
response = requests.get(GH_SEARCH_API)
repos = response.json()['items']
wh... | StarcoderdataPython |
11354604 | <reponame>iBug/OmniAE<filename>daemon.py
#!/usr/bin/env python3
import sys
import time
import subprocess
PYTHON = sys.executable
try:
while True:
cmd = [PYTHON, "main.py"]
cp = subprocess.run(cmd)
if cp.returncode != 0:
print("Program exited unexpectedly, sleeping before rest... | StarcoderdataPython |
3548282 | <reponame>ZviBaratz/pylabber
"""
Definition of the :class:`TaskResultViewSet` class.
"""
from typing import Tuple
from accounts.filters.task_result import TaskResultFilter
from accounts.serializers.task_result import TaskResultSerializer
from django_celery_results.models import TaskResult
from pylabber.views.defaults ... | StarcoderdataPython |
150930 | from iter_helpers import transpose
from iter_helpers import scalar_product
from utils import profile
from utils import timer
from linked_list import Node
from linked_list import flatten_linked_list
from os import stat
from os import listdir
from utils import calculate_stats
@profile
def some_function():
return su... | StarcoderdataPython |
11357229 | """
test_readers
~~~~~~~~~~~~
:copyright: Copyright 2020 by <NAME>
:license: Apache License 2.0, see LICENSE for details.
"""
from pycmark.readers import LineReader
from pycmark_vfm.readers import WalledBlockReader
def test_WalledBlockReader():
text = ("===wall\n"
"Lorem ipsum dolor... | StarcoderdataPython |
362355 | # -*- coding: utf-8 -*-
import sys
lines = []
for line in sys.stdin:
lines.append(line.split())
N, M, S, D = lines[0]
cakes = lines[1]
for i in range(2, M):
print(lines[M]) | StarcoderdataPython |
3288167 | '''
agents
======
The following methods allow for interaction into the Tenable.io
`agents <https://cloud.tenable.com/api#/resources/agents>`_
API endpoints.
Methods available on ``tio.agents``:
.. rst-class:: hide-signature
.. autoclass:: AgentsAPI
.. automethod:: details
.. automethod:: list
.. autom... | StarcoderdataPython |
1721399 | # @author <NAME>
# @copyright Copyright (c) 2008-2015, <NAME> aka LONGMAN (<EMAIL>)
# @link http://longman.me
# @license The MIT License (MIT)
import re
import jsbeautifier
class JsFormatter:
def __init__(self, formatter):
self.formatter = formatter
self.o... | StarcoderdataPython |
9677512 | import logging
from hootingyard.api.stories import get_all_show_information
log = logging.getLogger(__name__)
def main():
for show in get_all_show_information():
if len(show.stories) == 0:
print(show.id)
if __name__ == "__main__":
logging.basicConfig()
logging.getLogger("").setLevel... | StarcoderdataPython |
5014124 | <reponame>ainterr/scoring_engine<filename>engine/poller.py
from threading import Thread, Event
from time import sleep
import pkgutil
from . import models, settings, plugins
import logging
logger = logging.getLogger(__name__)
PLUGINS = {}
def get_plugins():
modules = {}
for loader, name, ispkg in pkgutil.wa... | StarcoderdataPython |
4957328 | <reponame>bo3b/iZ3D<filename>lib/python27/Lib/site-packages/wx-2.8-msw-ansi/wx/tools/Editra/src/ebmlib/clipboard.py
###############################################################################
# Name: clipboard.py #
# Purpose: Vim like clipboard ... | StarcoderdataPython |
8136568 | <gh_stars>0
# credit: https://codereview.stackexchange.com/questions/203319/greedy-graph-coloring-in-python
def color_nodes(graph):
color_map = {}
# Consider nodes in descending degree
for node in sorted(graph, key=lambda x: len(graph[x]), reverse=True):
neighbor_colors = set(color_map.get(neigh) f... | StarcoderdataPython |
3547161 | <reponame>ABorovtsov/Sql-Metadata<gh_stars>1-10
from textwrap import indent
import numpy as np
import pandas as pd
import pathlib
class MetaExporter:
def __init__(self, link_generator = None):
self.link_gen = link_generator
def to_df(self, metas):
df = pd.DataFrame([meta.as_json() ... | StarcoderdataPython |
1803514 | from setuptools import setup
setup(
name='depends-on-pkg-with-extras',
version='3.0.0',
# In versions <= 0.7.4, when walking the requirements tree, we would
# stop after seeing a requirement key once. So if we saw foo, a future
# foo[bar] would be ignored. Or seeing foo[bar], we'd ignore foo[baz].
... | StarcoderdataPython |
3553151 | <gh_stars>1-10
from psycopg2 import connect
from model import Location
class DatabaseManager:
def __init__(self, host, user, pwd, db, locations_table, port=5432):
self.host = host
self.port = port
self.user = user
self.pwd = <PASSWORD>
self.db = db
self.locations_t... | StarcoderdataPython |
9707842 | <filename>generators/adc_sar_capdrv_nsw_array_verify.py
# -*- coding: utf-8 -*-
import pprint
import bag
#from laygo import *
import laygo
import numpy as np
import yaml
import matplotlib.pyplot as plt
lib_name = 'adc_sar_templates'
cell_name = 'capdrv_nsw_array_8b'
impl_lib = 'adc_sar_generated'
tb_lib = 'adc_sar_t... | StarcoderdataPython |
3407834 | <reponame>BjoernBiltzinger/astromodels
# code to demonstrate how to create a spectra object for dark matter models
# author: <NAME> (<EMAIL>)
# date: Oct 26, 2016
from threeML import *
# DMFitFunction uses the Pythia-generated table from the standard Fermi Science Tools which is appropriate for 2 GeV < mass < 10 TeV
... | StarcoderdataPython |
3480878 | <reponame>klahox/netbox
from __future__ import unicode_literals
from django import forms
from utilities.forms import BootstrapMixin
OBJ_TYPE_CHOICES = (
('', 'All Objects'),
('Circuits', (
('provider', 'Providers'),
('circuit', 'Circuits'),
)),
('DCIM', (
('site', 'Sites'),
... | StarcoderdataPython |
239812 | <filename>main.py
import argparse
import sys
from CONST import *
def arg_parser(args):
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description="Parse arguments for DQN-Atari Experiment",
epilog="python main.py ")
parser.add_argument(
'... | StarcoderdataPython |
8109279 | <filename>vb2py/PythonCard/samples/turtle/scripts/goldenSection.py
# adapted from Just example at:
# http://just.letterror.com/ltrwiki/DrawBot
# the main downside to this version that I see
# is that apparently the Oval primitive or underlying
# Mac OS X draw calls change the thickness
# of the oval outline as well as... | StarcoderdataPython |
1998005 | # Copyright 2021 LINE Corporation
#
# LINE Corporation licenses this file to you 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:
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... | StarcoderdataPython |
4904658 | from typing import Collection, Hashable
class MutuallyExclusiveError(ValueError):
def __init__(self, *fields: str):
fields_string = ", ".join(fields)
super(MutuallyExclusiveError, self).__init__(
f"The {fields_string} fields are mutually exclusive"
)
class DuplicateItemsErr... | StarcoderdataPython |
1750038 | """
File: caesar.py
Name:
------------------------------
This program demonstrates the idea of caesar cipher.
Users will be asked to input a number to produce shifted
ALPHABET as the cipher table. After that, any strings typed
in will be encrypted.
"""
# This constant shows the original order of alphabetic sequence.
... | StarcoderdataPython |
11313490 | <reponame>ximury/python
# kwargs(keyword arguments)在args之后表示成对键值对
def foo(*args, **kwargs):
print('args = ', args)
print('kwargs = ', kwargs)
print('*********************')
if __name__ == '__main__':
foo(1, 2, 3)
foo(a=1, b=2, c=3)
foo(1, 2, 3, a=1, b=2, c=3)
foo('a', 1, None, a... | StarcoderdataPython |
5097104 | with open('README.rst', 'r') as f:
readme = f.read()
#from distutils.core import setup, Extension
from setuptools import setup, Extension
from pyNNST import __version__
setup(name='pyNNST',
version=__version__,
author='<NAME>',
author_email='<EMAIL>',
description='Definition of non-sta... | StarcoderdataPython |
3581553 | from unittest import TestCase
from series_tiempo_ar.custom_exceptions import FieldTitleTooLongError
from series_tiempo_ar.readers.csv_reader import CSVReader
from series_tiempo_ar.validations.csv_validations import (
TitleLengthValidation,
ValidationOptions,
)
from tests.helpers import csv_path
class TestTit... | StarcoderdataPython |
11396420 | from django.db import models
NN_CHOICES = (
('rnn', 'RNN - Recurrent neural network'),
('gan', 'GAN - Generative Adversarial Network'),
)
GENRE_CHOICES = (
('comedy', 'Comedy'),
('horror', 'Horror'),
('thriller', 'Thriller'),
('documentary', 'Documentary'),
('drama', 'Drama'),
('histo... | StarcoderdataPython |
5050860 | from ._getter import FEATURES
from ._getter import get_feature
from .container import FeatureList
from .container import ModuleOutput
from .features import Barrier
from .features import Empty
from .features import ExpiryTime
from .features import LogMoneyness
from .features import MaxLogMoneyness
from .features import ... | StarcoderdataPython |
1968825 | <reponame>k20human/roby2000
from pymercure.consumer import Consumer
from gpiozero import Robot
import json
import time
class Movement:
def __init__(self, logger):
self._logger = logger
self._robot = Robot(left=(24, 23, 21), right=(20, 16, 18))
self._consumer = Consumer('http://192.168.1.183... | StarcoderdataPython |
5066811 | <reponame>lkmhaqer/gtools-python<gh_stars>1-10
# file: op_webgui/urls.py
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from op_webgui import views
app_name = 'op_webgui'
urlpatterns = [
url(
r'^$',
views.index,
name='index'
),
url(
... | StarcoderdataPython |
4927307 | """
DIAS Finder API (see Readme)
"""
import json
import os
from typing import Dict
from urllib.parse import quote, urlencode
import geopandas as gpd
import pandas
import requests
from dateutil.parser import parse
from requests import Request
from requests.adapters import HTTPAdapter
from shapely.geometry import Po... | StarcoderdataPython |
307152 | <reponame>mvenouziou/DETR_for_TF
# imports
import tensorflow as tf
import tensorflow_addons as tfa
import tokenizers
import prediction_heads
import model
class DETR_MultiClassifier(tf.keras.Model):
"""
This is an adaption that takes an existing DETR model created above and treats
it as a (multilabel) clas... | StarcoderdataPython |
3513650 | <gh_stars>10-100
from tfsnippet.utils import (validate_int_tuple_arg, InputSpec,
get_static_shape, validate_enum_arg)
def validate_conv2d_input(input, channels_last, arg_name='input'):
"""
Validate the input for 2-d convolution.
Args:
input: The input tensor, must be ... | StarcoderdataPython |
8176133 | import cubicsuperpath, simplepath, cspsubdiv
from xml.dom import minidom
import argparse
import json
import os
import sys
import simplify
def flatten(p, flat=10.0, round_to_int=True):
"""
Flatten a bezier curve to polylines or simple x,y coordinates
Arguments:
* p: path array
* flat: Flattenin... | StarcoderdataPython |
8149468 | # rest.exceptions - Exceptions raised by the rest client library
# coding: utf-8
#
# Copyright 2010 Guardis SPRL, Liège, Belgium.
# Authors: <NAME> <<EMAIL>>
#
# This software cannot be used and/or distributed without prior
# authorization from Guardis.
class ApiException(Exception):
def __init__(self, message, co... | StarcoderdataPython |
6542152 | #!/usr/bin/env python
from graph_obj import Edge, Node, Graph
from collections import defaultdict
import argparse
import re
def parse_args():
parser = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("... | StarcoderdataPython |
1715648 | from urllib import parse
from .islands import island_netloc_table, island_class_table, IslandNotDetectError
__author__ = 'zz'
def determine_island_name(url):
netloc = parse.urlparse(url).netloc
for url, name in island_netloc_table.items():
if url == netloc:
return name
else:
ra... | StarcoderdataPython |
11205807 | <gh_stars>1-10
# -*- encoding: utf-8 -*-
"""
Copyright (c) 2019 - present AppSeed.us
"""
import os
from app.home import blueprint
from flask import render_template, redirect, url_for, request, abort
from flask_login import login_required, current_user
from app import login_manager
from jinja2 import TemplateNotFound
f... | StarcoderdataPython |
12828673 | <reponame>pixelherodev/oboeta
#!/usr/bin/env python3
# Generate Cloze Deletions from Standard Input
# Written in 2012 by 伴上段
#
# To the extent possible under law, the author(s) have dedicated all copyright
# and related and neighboring rights to this software to the public domain
# worldwide. This software is distribu... | StarcoderdataPython |
3384630 |
try:
""" DocumentMediator listens to change in a single document and triggers
functions when such document change.
"""
from .document import ViewMediatorDAV as DocumentMediator
""" QueryMediator listens to the result of a query and triggers
functions when the result of such q... | StarcoderdataPython |
8162105 | def aumentar(num, porcentagem):
"""
-> Calcula o valor acrescido de uma determinada porcentagem
:param num: numero que será acrescido da porcentagem
:param porcentagem: valor da porcentagem a ser calculada
:return: o resultado do cálculo
"""
resultado = num + (num * (porcentagem / 100))
... | StarcoderdataPython |
343649 | <gh_stars>1-10
from alambi.models import User, Tag
from alambi.utils import ThemeName
from flask_wtf import FlaskForm
from flask_wtf.file import FileAllowed
from wtforms import (StringField, BooleanField, TextAreaField, SubmitField, SelectField,
RadioField, FileField, PasswordField, IntegerFie... | StarcoderdataPython |
11363472 | #!/usr/bin/env python3
"""
Copyright 2017 <NAME>. See LICENSE for details.
"""
import collections
import time
class SX127xSettings(dict):
"""Base class for SX127x device settings.
Modem, RF, LoRa and FSK settings are derived from this.
"""
def __init__(self, stngs_dict={}):
"""Validates any... | StarcoderdataPython |
8174760 | <reponame>nha6ki/python_source_separation
#wave形式の音声波形を読み込むためのモジュール(wave)をインポート
import wave as wave
#numpyをインポート(波形データを2byteの数値列に変換するために使用)
import numpy as np
#可視化のためにmatplotlibモジュールをインポート
import matplotlib.pyplot as plt
#sounddeviceモジュールをインポート
import sounddevice as sd
#読み込むサンプルファイル
sample_wave_file=... | StarcoderdataPython |
8093476 | """STACK Configs."""
from typing import Dict, List, Optional
import pydantic
class StackSettings(pydantic.BaseSettings):
"""Application settings"""
name: str = "titiler-pds"
stage: str = "production"
owner: Optional[str]
client: Optional[str]
project: Optional[str]
additional_env: Dic... | StarcoderdataPython |
1840544 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import sys
import json
import torch
import argparse
import numpy as np
import pandas as pd
sys.path.insert(1, os.path.join(sys.path[0], '..'))
from config import *
from collections import Counter
from preprocessing.instagram import preprocess, split_dataset
from pr... | StarcoderdataPython |
4816683 | <filename>week5/funcMaiorPrimo.py<gh_stars>1-10
def ehprimo(numero):
if numero == 2 or numero == 3 or numero == 5 or numero == 7:
return True
elif numero == 1:
return False
else:
if numero % 2 == 0 or numero % 3 == 0 or numero % 5 == 0 or numero % 7 == 0 or numero % 11 == 0 or numer... | StarcoderdataPython |
6577432 | <filename>src/relevance/features/gen_distance_feat.py
"""
__file__
genFeat_distance_feat.py
__description__
This file generates the following features for each run and fold, and for the entire training and testing set.
1. jaccard coefficient/dice distance between query & title, query & description,... | StarcoderdataPython |
1853824 | <reponame>blayhem/uc3m-GA-nqueens<filename>AG_N_reinas.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import random as r
import sys
import math
import functools as ft
import requests
import multiprocessing
import concurrent.futures
'''
# Debugging & analysis tools:
import time
import csv
# https://pypi.python.org... | StarcoderdataPython |
8079783 | # Copyright 2018-2022 Streamlit 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 agreed to in wr... | StarcoderdataPython |
4842376 | # Snippet 2.
# Retrieving protein target information via API using Python client.
from chembl_webresource_client.new_client import new_client
target = new_client.target
hits = target.filter(target_synonym__exact='TSHR', organism='Homo sapiens')
| StarcoderdataPython |
6617049 | # Copyright (c) 2015 Rackspace, 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 agreed to in wr... | StarcoderdataPython |
3473623 | <reponame>Django-Lessons/demo-proj-lesson-43
from django.contrib import admin
from land.models import Product
class ProductAdmin(admin.ModelAdmin):
pass
admin.site.register(Product, ProductAdmin)
| StarcoderdataPython |
11228856 | <gh_stars>1-10
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/11/28 14:08
# @Author : Tao.Xu
# @Email : <EMAIL>
import gitlab
from tlib.log import log
from tlib.retry import retry_call
# =============================
# --- Global
# =============================
logger = log.get_logger()
class ... | StarcoderdataPython |
1655320 | from flask import Blueprint, request
from base.db import get_db
from user.service import UserService
bp = Blueprint('users', __name__, url_prefix='/api/v1/users')
@bp.route('', methods=['GET', 'POST'])
def users():
"""
Create a new user
"""
response = None
db = get_db()
user_service = UserS... | StarcoderdataPython |
8119790 | """$Id: iso639codes.py 699 2006-09-25 02:01:18Z rubys $"""
__author__ = "<NAME> <http://intertwingly.net/> and <NAME> <http://diveintomark.org/>"
__version__ = "$Revision: 699 $"
__date__ = "$Date: 2006-09-25 02:01:18 +0000 (Mon, 25 Sep 2006) $"
__copyright__ = "Copyright (c) 2002 <NAME> and <NAME>"
isoLang = \
{... | StarcoderdataPython |
3307519 | import ast
CDL_FN = '../data/CDL_crops.txt'
with open(CDL_FN, 'r') as file:
for line in file:
break
CDL_NAMES = ast.literal_eval(line)
CDL_LABELS = dict((v,k) for k,v in CDL_NAMES.items()) | StarcoderdataPython |
3533977 | <reponame>demetoir/MLtools
import random
import time
class Process:
def __init__(self):
self.call_count = 0
self.url = None
self.job_idx = None
def task(self, url=None, job_idx=None):
if url is None:
url = self.url
if job_idx is None:
... | StarcoderdataPython |
3408686 | <gh_stars>1-10
##
# Copyright (c) 2007-2013 <NAME>. 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
#
# ... | StarcoderdataPython |
11242144 | <reponame>dbstein/ipde
from .modified_helmholtz import AnnularModifiedHelmholtzSolver
class AnnularPoissonSolver(AnnularModifiedHelmholtzSolver):
"""
Spectrally accurate Poisson solver on annular domain
Solves Lu = f in the annulus described by the Annular Geometry AG
Subject to the Robin boundary con... | StarcoderdataPython |
5143388 | # Main configuration file for game
# global game settings configured from here
# Set game values
SCREENSIZE = [640, 360] # Game resolution
FULLSCREEN = False # Window or fullscreen
SOUND = False # All sound on or off
SCROLL_MAP = True
TILESIZE ... | StarcoderdataPython |
9770516 | #!/usr/bin/env python3
#coding=utf-8
f = open("e:\Git\coding-practice\Python\\base\\test.txt", "r+")
c = f.read(5) #读取10个字节
print(c)
c = f.readline()
print(c)
c = f.readlines()
print(c)
f.write("I like apple")
c = f.readlines()
print(c) | StarcoderdataPython |
9786757 | # Copyright (c) 2014 IBM Corp.
#
# 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 agre... | StarcoderdataPython |
4863468 | <filename>collGisFile2Json.py
#coding=utf-8
import json
from openpyxl import load_workbook
from openpyxl import Workbook
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
def resolveJson(path):
file = open(path, "rb")
fileJson = json.load(file)
futures = fileJson["obj"]["companies"]
return (futur... | StarcoderdataPython |
8071579 | #!/usr/bin/env python
import argparse
import math
from collections import Counter
from spawningtool.parser import parse_replay
def map_replays(filenames, map_fn, results, update_fn, cache_dir=None, **kwargs):
for filename in filenames:
filename = filename.rstrip('\n')
replay = parse_replay(filena... | StarcoderdataPython |
115542 | <filename>ebcli/operations/platform_version_ops.py
# Copyright 2015 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://aws.amazon.... | StarcoderdataPython |
5033309 | #!/usr/bin/env python
import sys
import subprocess
try:
import gtk
except:
print >> sys.stderr, "You need to install the python gtk bindings"
sys.exit(1)
# import vte
try:
import vte
except:
error = gtk.MessageDialog (None, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK,
'You need to install... | StarcoderdataPython |
9761726 | <filename>check_if_list_empty.py
# Write a function to return boolean if the list is empty?
# a) using None
# b) using len()
def check_if_empty_list(alist):
#if alist is None:
if len(alist) == 0:
return True
else:
return False
check = check_if_empty_list([2,3])
print(check)
| StarcoderdataPython |
4803218 | <reponame>msinghartinger/pyipn<gh_stars>0
import numpy as np
from .geometry import GRBLocation
class GRB(object):
def __init__(self, ra, dec, distance, K, t_rise, t_decay):
"""
A GRB that emits a spectrum as a given location
:param ra: RA of the GRB
:param dec: DEC of the GRB
... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.