id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
3204772 | # Copyright (c) 2012--2013 King's College London
# Created by the Software Development Team <http://soft-dev.org/>
#
# 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 without restriction, inclu... | StarcoderdataPython |
159427 | <gh_stars>1-10
from django.conf import settings
from . import models, utils
from .utils import rename_key, ensure, first, merge, splitfilter
import logging
import requests, requests.exceptions
import backoff
from collections import OrderedDict
LOG = logging.getLogger()
class BPError(RuntimeError):
data = None
... | StarcoderdataPython |
1749067 | <reponame>Poseidon-Dev/janus
import importlib
from core import config
bot = config.BOT
@bot.event
async def on_ready():
"""
Initializes bot and all application modeules specified in config
"""
for extension in config.STARTUP_COGS:
try:
importlib.import_module(extension)
... | StarcoderdataPython |
4839008 | <reponame>young24/LFP-simulation-in-turtle-brain
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 6 13:35:38 2016
get_actual_position_of_synaptic_input
@author: young
"""
import numpy as np
import neuron
import LFPy
# TODO: Check if kCSD is usable
if __name__ == '__main__':
#cell_z_pos = 150
cell_parame... | StarcoderdataPython |
3236195 | <gh_stars>10-100
import argparse
import sys
from .btc import encoder, decoder, error, list_to_dict, dict_to_list, ordered_dict
try:
unicode
except NameError:
unicode = str
_description = 'sort elements of a list'
# TODO: add support for dates (date_added, date_completed)
def main():
parser = argparse.Ar... | StarcoderdataPython |
1651886 | <reponame>vishvananda/dagster
import os
import zipfile
def zip_folder(folder_path, output_path):
contents = os.walk(folder_path)
try:
zip_file = zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED)
for root, folders, files in contents:
# Include all subfolders, including empty o... | StarcoderdataPython |
1745905 | T=int(input())
for t in range(T):
n=int(input())
L=[None]+list(map(int,input().split()))
visited=[False]*(n+1)
alone=[]
for start in range(1,n+1):
if visited[start]:
continue
v=start
while not visited[v]:
visited[v]=True
v=L[v]
w=st... | StarcoderdataPython |
1763873 | <reponame>lorenanicole/almost_funded
from django.db import models
# Create your models here.
class Category(models.Model):
category = models.CharField(max_length=100)
def __unicode__(self):
return self.category
class Campaign(models.Model):
SOURCESCHOICE = (
(0, 'kickstarter'),
(... | StarcoderdataPython |
173070 | from queue import Queue
from threading import Thread
import logging
class AudioThread:
def __init__(self, stream, chunk, timeout=0, rate=16000):
self.run = True
self.queue = Queue(maxsize=0)
self.thread = Thread(target=self.read_stream, args=(stream, chunk, rate, timeout))
self.thr... | StarcoderdataPython |
3352328 | <gh_stars>1-10
cost_payload = {
"line_items": [
{
"page_count": 32,
"pod_package_id": "0600X0900BWSTDPB060UW444MXX",
"quantity": 20
},
{
"page_count": 324,
"pod_package_id": "0425X0687BWSTDLW060UC444GRB",
"... | StarcoderdataPython |
16992 | """The File Propagator"""
| StarcoderdataPython |
69067 | <gh_stars>0
import os
import glob
import pandas as pd
import numpy as np
from collections import deque
import logging
from qcodes import (
Instrument,
ManualParameter,
validators as vals
)
from time import time
from datetime import datetime
log = logging.getLogger(__name__)
class LeidenFridge(Instrument):... | StarcoderdataPython |
1711387 | <reponame>oswalgopal/oppia<filename>core/domain/question_validators_test.py
# coding: utf-8
#
# Copyright 2020 The Oppia 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 Lic... | StarcoderdataPython |
1688060 | x = 1 # int
y = 2.5 # float
z = 1j # complex
# to verify the type of any object in python use the "type()" func
print(type(x))
print(type(y))
print(type(z))
| StarcoderdataPython |
5090 | <gh_stars>1-10
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Genera... | StarcoderdataPython |
48463 | from ...isa.inst import *
import numpy as np
class Vwmacc_vv(Inst):
name = 'vwmacc.vv'
# vwmacc.vv vd, vs1, vs2, vm
def golden(self):
if self['vl']==0:
return self['ori']
result = self['ori'].copy()
maskflag = 1 if 'mask' in self else 0
vstart = self['v... | StarcoderdataPython |
4834301 | <gh_stars>1-10
# -----------------------------------------------------------------------------
# Copyright (C) 2019-2021 The python-ndn authors
#
# This file is part of python-ndn.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# Yo... | StarcoderdataPython |
1735581 | # -*- coding: utf-8 -*-
"""Mssql."""
from __future__ import annotations
from abc import ABC
from contextlib import contextmanager
from json import dumps
from logging import getLogger
from typing import TYPE_CHECKING, Any, Dict, Generator
from .persistor import Persistor as BasePersistor
from .service import Service,... | StarcoderdataPython |
1738807 | # Copyright 2010-2011 OpenStack Foundation
# Copyright (c) 2013 Hewlett-Packard Development Company, L.P.
#
# 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/licens... | StarcoderdataPython |
1622579 | from distutils.core import setup
from Cython.Build import cythonize
import numpy
setup(ext_modules = cythonize('chimeramate_main.pyx'),include_dirs=[numpy.get_include()])
| StarcoderdataPython |
3360593 | <reponame>mariozaizar/email.sublime-syntax
import sublime
import sublime_plugin
import html
import re
from base64 import b64decode
from datetime import timezone
from email.utils import parsedate_to_datetime
class EmailViewListener(sublime_plugin.ViewEventListener):
SYNTAX = 'email.sublime-syntax'
@classmet... | StarcoderdataPython |
54286 | __all__ = ()
from ...backend.utils import istr
AUDIT_LOG_REASON = istr('X-Audit-Log-Reason')
RATE_LIMIT_REMAINING = istr('X-RateLimit-Remaining')
RATE_LIMIT_RESET = istr('X-RateLimit-Reset')
RATE_LIMIT_RESET_AFTER = istr('X-RateLimit-Reset-After')
RATE_LIMIT_LIMIT = istr('X-RateLimit-Limit')
# to send
RATE_LIMIT_PR... | StarcoderdataPython |
29105 | from villas.controller.components.gateway import Gateway
class VILLASrelayGateway(Gateway):
def __init__(self, manager, args):
# Some default properties
props = {
'category': 'gateway',
'type': 'villas-relay',
'realm': manager.realm,
'name': args['i... | StarcoderdataPython |
1764337 | <reponame>fief-dev/fief<filename>backend/tests/test_apps_auth_user.py<gh_stars>1-10
from typing import Optional
import httpx
import pytest
from fastapi import status
from tests.types import TenantParams
@pytest.mark.asyncio
@pytest.mark.workspace_host
@pytest.mark.parametrize("method", ["GET", "POST"])
class TestUs... | StarcoderdataPython |
3355389 | <gh_stars>1-10
# encoding: utf-8
import random
__author__ = "<NAME>"
__email__ = "uni at lampep.de"
class AbstractNode:
"""
Parameter
---------
Attributes
----------
"""
def __init__(self, node_id):
self.crnt_movement_pattern = None
self.dict_of_movement_pattern = {}
... | StarcoderdataPython |
3311111 | from config import GOOGLE_API_KEY as google_api_key
from requests import get as rget
from urllib.request import quote
from math import floor as mfloor
from audiovisuaali import send
from datetime import datetime
from json import loads
from time import time
async def time_new(message, client, arguments):
... | StarcoderdataPython |
3251180 | import requests,json,os
# server酱开关,填off不开启(默认),填on同时开启cookie失效通知和签到成功通知
sever = os.environ["SERVE"]
# 填写server酱sckey,不开启server酱则不用填
sckey = os.environ["SCKEY"]
# 填入glados账号对应cookie
cookie = os.environ["COOKIE"]
def start():
url= "https://glados.rocks/api/user/checkin"
url2= "https://glados.rocks/api/u... | StarcoderdataPython |
34533 | # Copyright (c) 2019 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://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... | StarcoderdataPython |
3305881 | <gh_stars>0
from collections import namedtuple
import re
import nltk
from django.db.models import Count
from django.core.cache import cache
from .models import BlogAuthor, BlogPost, Comment
def get_total_num():
"""
Get total number of blog posts, bloggers and comments
return a named tuple of numbers
"... | StarcoderdataPython |
168244 | """Utility to store int or float parameters with a label
The label is added merely for information: there is no
extra functionality associated with it.
The module has a factory class Parameter(value, label)
which returns either ParameterInt ot ParameterFloat
depending on type(value).
"""
class ParameterInt(int):
... | StarcoderdataPython |
1611205 | #!/usr/bin/env python
from fs.errors import FSError
from fs.opener import opener
from fs.path import pathsplit, abspath, isdotfile, iswildcard
from fs.commands.runner import Command
from collections import defaultdict
import sys
class FSls(Command):
usage = """fsls [OPTIONS]... [PATH]
List contents of [PATH]"""
... | StarcoderdataPython |
3207030 | <filename>nnpy/utils.py
import numpy as np
def forward(net, x):
for layer in net:
x = layer.forward(x)
# print('f', layer.name, x.shape)
return x
def backward(net, loss):
grad = loss.backward()
for layer in reversed(net):
grad = layer.backward(grad)
# print('b', layer... | StarcoderdataPython |
1710937 | <filename>testrunner.py
from collections import defaultdict
from functools import wraps
from unittest.util import strclass
from couchdbkit import Database, ResourceNotFound
from couchdbkit.ext.django import loading
from couchdbkit.ext.django.testrunner import CouchDbKitTestSuiteRunner
import datetime
from django.conf i... | StarcoderdataPython |
3348422 | # Generated by Django 2.1.5 on 2019-02-04 22:22
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='CuttingJobs',
fields=[
... | StarcoderdataPython |
3265230 |
import wx
from ..settings import SettingsManager
class Slider(wx.Panel):
def __init__(self, parent, id, widget, key, dtype='float', digits=2):
wx.Panel.__init__(self, parent, id)
self.widget = widget
sizer = wx.BoxSizer(wx.HORIZONTAL)
self.dtype = dtype
... | StarcoderdataPython |
1788302 | #!/usr/bin python3
"""
Response structure
------------------
Utilities to verify and format the structure of response arrays.
Author: <NAME> <<EMAIL>>
Created: 23 May 2020
License: MIT
Contributors: <NAME>
"""
# Imports
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~... | StarcoderdataPython |
1761017 | <gh_stars>0
import os
import sys
from datetime import datetime
from functools import lru_cache
from vnpy.event import EventEngine, Event
from vnpy.trader.engine import BaseEngine, MainEngine
from vnpy.trader.event import (
EVENT_TICK, EVENT_TIMER, EVENT_ORDER, EVENT_TRADE, EVENT_POSITION)
from vnpy.trader.constant... | StarcoderdataPython |
3329625 | <gh_stars>1-10
import functools
from . import errors
from .spec import Specification
def authorize(spec: Specification):
def decorator(func):
resource_name = func.__qualname__
@functools.wraps(func)
def wrapper(controller, request, response):
client = request.context.client
... | StarcoderdataPython |
3217679 | <reponame>rkothapalli/jazz
import sys
import os
import json
sys.path.insert(0, 'library')
from components.logger import Logger
from components.config import Config
# import installed package
import requests
def handler(event, context):
# initialize logger module
logger = Logger(event, context)
# Load c... | StarcoderdataPython |
1629428 | <reponame>Bogusik/microrm<filename>microrm/__init__.py<gh_stars>0
from microrm.declarative import (
Query,
Column,
Expression
)
from microrm.model import Model
from microrm.validators import (
Validator
) | StarcoderdataPython |
3345767 | <filename>setup.py
import setuptools
classifiers = [
(
'Programming Language :: Python :: %s' % x
)
for x in '3.1 3.2 3.3 3.4 3.5'.split()
]
setuptools.setup(
name='nickel',
description='Minimalistic programming language tailored to run on chlorophyte VM.',
version='0.0.1',
licen... | StarcoderdataPython |
3348450 | from setuptools import setup
setup(
name='waity',
version='0.2',
description='wait any condition',
url='http://github.com/ilyubin/waity',
download_url='https://github.com/peterldowns/mypackage/archive/0.2.tar.gz',
author='<NAME>',
author_email='<EMAIL>',
license='MIT',
packages=['w... | StarcoderdataPython |
4842260 | <reponame>synteny/AuroraBot
from time import sleep
from messaging.settings import RABBIT_HOST, RABBIT_LOGIN, RABBIT_PASSWORD
__author__ = 'arik'
import pika
def getConnection():
credentials = pika.PlainCredentials(RABBIT_LOGIN, RABBIT_PASSWORD)
connection = pika.BlockingConnection(pika.ConnectionParameters(
... | StarcoderdataPython |
1661616 | <reponame>HyeonseoJUNG/DB2_TermPJT
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'recommand_page2.ui'
#
# Created by: PyQt5 UI code generator 5.15.6
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you ... | StarcoderdataPython |
1730873 | <reponame>poltextlab/nyt_hybrid_classification_workflow<filename>preproc_in_Spark/NYT_prepare_corpus.py
# import libraries
from pyspark.sql import SparkSession
from pyspark import SparkConf
from pyspark.sql.types import *
from pyspark.sql.functions import count, when
from pyspark.ml.feature import RegexTokeniz... | StarcoderdataPython |
121254 | <gh_stars>1-10
import logging
import warnings
from .exceptions import ConfigError
logger = logging.getLogger(__name__)
class Ctl:
def __init__(self, config):
warnings.warn('Ctl is deprecated, use lmctl.config.Config instead', DeprecationWarning)
self.config = config
self.environmen... | StarcoderdataPython |
34956 | <gh_stars>1-10
#This script is going to be used API calls but first it will serve as a testing script.
from IOTA_Module import *
from Configuration_Module import *
from Tools_Module import *
from UserProfile_Module import *
from Cryptography_Module import *
from NodeFinder_Module import *
from DynamicPublicLedger_Modu... | StarcoderdataPython |
184683 | <reponame>GloryKwon/Hungry_Genie<gh_stars>0
from numpy import dot
from numpy.linalg import norm
import numpy as np
import pandas as pd
import re
import pymysql
def cos_similarity(A, B):
return dot(A, B)/(norm(A)*norm(B)) # cosine similarity
# DB 접속
conn = pymysql.connect(
host='127.0.0.1',
port=... | StarcoderdataPython |
1679097 | <filename>agenda/models.py
from django.db import models
class Event(models.Model):
displayed = models.BooleanField(default=False)
pict = models.ImageField(upload_to="event", blank=True)
title = models.CharField(default="", max_length=300)
desc = models.TextField()
def __str__(self):
return... | StarcoderdataPython |
3344139 | # https://pythonhosted.org/setuptools/setuptools.html#namespace-packages
# __import__('pkg_resources').declare_namespace(__name__)
import mapzen.whosonfirst.pip
import mapzen.whosonfirst.placetypes
import shapely.geometry
import logging
def reverse_geocoordinates(feature):
props = feature['properties']
lat ... | StarcoderdataPython |
3257239 | <filename>ckanext/example_theme/v09_snippet/plugin.py<gh_stars>1000+
../v08_custom_helper_function/plugin.py | StarcoderdataPython |
51212 | <gh_stars>0
# WSGI Server for Development
# Use this during development vs. apache. Can view via [url]:8001
# Run using virtualenv. 'env/bin/python run.py'
from app import app
app.run(host='127.0.0.1', port=5000, debug=True)
| StarcoderdataPython |
3218037 | <reponame>pbellon/gist
import argparse
import sys
import json
from .utils import as_obj
def command_arg(*args, **kwargs):
"""
Small tweak to build argparse.add_argument() arguments through a command
declaration (see `command` decorator and `Command.add_arguments` method)
"""
class CommandArg:
... | StarcoderdataPython |
185939 | <gh_stars>1-10
from sys import platform
if platform[:3] == 'win':
__keydict = {
0x3b : 'f1',
0x3c : 'f2',
0x3d : 'f3',
0x3e : 'f4',
0x3f : 'f5',
0x40 : 'f6',
0x41 : 'f7',
0x42 : 'f8',
0x43 : 'f9',
0x44 : 'f10',
0x... | StarcoderdataPython |
1657973 | <gh_stars>0
import pytest
from eth_utils import is_checksum_address
from rotkehlchen.assets.asset import Asset, EthereumToken
from rotkehlchen.assets.resolver import AssetResolver, asset_type_mapping
from rotkehlchen.errors import DeserializationError, UnknownAsset
from rotkehlchen.typing import AssetType
def test_u... | StarcoderdataPython |
155472 | <filename>deepxde/backend/tensorflow_compat_v1/__init__.py<gh_stars>100-1000
import os
os.environ["TF_FORCE_GPU_ALLOW_GROWTH"] = "true"
from .tensor import * # pylint: disable=redefined-builtin
| StarcoderdataPython |
1779463 | <gh_stars>10-100
# Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law... | StarcoderdataPython |
3376827 | <gh_stars>0
"""
Move with a Sprite Animation
Simple program to show basic sprite usage.
Artwork from http://kenney.nl
If Python and Arcade are installed, this example can be run from the command line with:
python -m arcade.examples.sprite_move_animation
"""
import arcade
import random
import os
SCREEN_WIDTH = 800
S... | StarcoderdataPython |
3346550 | <gh_stars>0
from covid_api.views.adicionales.municipio_poblacion import MunicipioPoblacionViewSet
from covid_api.views.adicionales.entidad_poblacion import EntidadPoblacionViewSet
__all__ = [
'MunicipioPoblacionViewSet',
'EntidadPoblacionViewSet',
]
| StarcoderdataPython |
1697641 | import pytest
from flask import Flask
from flask_mux import Mux
from testing.test_cases.router import auth_router, api_router, admin_router
@pytest.fixture
def mux():
app = Flask(__name__)
mux = Mux(app)
mux.use('/auth', auth_router)
mux.use('/api', api_router)
mux.use('/admin', admin_router)
... | StarcoderdataPython |
1635448 | <gh_stars>1-10
import os
MONGO_HOST = os.environ.get('MONGO_HOST', 'localhost')
MONGO_PORT = os.environ.get('MONGO_PORT', 27017)
MONGO_DBNAME = os.environ.get('MONGO_DBNAME', 'atlas')
DATE_FORMAT = '%Y-%m-%d %H:%M:%S GMT'
# Enable reads (GET), inserts (POST), and DELETE for resources/collections.
RESOURCE_METHODS = ... | StarcoderdataPython |
196765 | <filename>turbustat/moments/tests/test_make_moments.py
# Licensed under an MIT open source license - see LICENSE
from __future__ import print_function, absolute_import, division
import numpy.testing as npt
import astropy.units as u
import os
from glob import glob
import pytest
from .. import Moments
from ...tests._t... | StarcoderdataPython |
1723739 | from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
class LogotipoVertical(BoxLayout):
def __init__(self, height=100, text='Calhambeque', font_size=30, **kwargs):
super().__init__(**kwargs)
self.orientation = 'vertical'
self.size_hint_y = None
self.height = he... | StarcoderdataPython |
3239036 | def rdkit2amberpdb(mol_pdb_txt):
"""
Converts a PDB block from openbabel or rdkit like format to the PDB block in rism pdb format
:param mol_pdb_txt: pdb block with openbabel or rdkit like format
:return: string with a pdb block in rism pdb comparable format
"""
mol_new_lines = []
atom_cou... | StarcoderdataPython |
1602741 | <reponame>braddillman/fashion
'''
ServiceRegistry
'''
import logging
from packaging.specifiers import SpecifierSet
from packaging.version import Version
class CodeRegistry(object):
'''
ServiceRegistry
'''
def __init__(self, dba):
'''Constructor.'''
self.dba = dba
self.servic... | StarcoderdataPython |
4829805 | <filename>src/scripts/modeling/model_selection.py
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:light
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.5.0
# kernelspec:
# display_name: Python 3
# language: python
# ... | StarcoderdataPython |
1746615 | num = input('Enter any number : ')
try:
val = int(num)
if num == str(num)[::-1]:
print('The given number is PALINDROME')
else:
print('The given number is NOT a palindrome')
except ValueError:
print("That's not a valid number, Try Again !") | StarcoderdataPython |
1705404 | <gh_stars>0
# -*- coding: utf-8 -*-
# Copyright (c) 2018, <NAME> and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from frappe_metrc.utils import get_metrc
metrc = get_metrc("plant_batch")
class PlantBa... | StarcoderdataPython |
3242483 | """
Strain Analysis of Flower in Washington State
Copyright (c) 2022 Cannlytics
Authors: <NAME> <<EMAIL>>
Created: 2/17/2022
Updated: 2/17/2022
License: MIT License <https://opensource.org/licenses/MIT>
Description: This script calculates various statistics about strains from the
Washington State traceability data (2... | StarcoderdataPython |
3272341 | import subprocess
from pathlib import Path
from datetime import datetime
from setuptools import setup, find_packages
def shell(*args):
out = subprocess.check_output(args)
return out.decode("ascii").strip()
def write_version(version_core, pre_release=True):
if pre_release:
time = shell("git", "lo... | StarcoderdataPython |
1799559 | <reponame>Robin8Put/pmes
from motor import MotorClient
class DatabaseClient:
def __init__(self):
self.client = MotorClient()
self.withdraw_db = self.client.withdraw_db
self.available_tokens = self.withdraw_db.available_tokens
self.withdraw_requests = self.withdraw_db.withdraw_re... | StarcoderdataPython |
188138 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | StarcoderdataPython |
83795 | # AUTOGENERATED! DO NOT EDIT! File to edit: nbs/config.ipynb (unless otherwise specified).
__all__ = ['AppConfig', 'PathConfig', 'TrainConfig']
# Cell
class AppConfig:
SEED = 8080
NUM_CLASSES = 7
class PathConfig:
# DATA_PATH = '/content/data'
# IMAGE_PATH = '/content/data/images'
# ... | StarcoderdataPython |
3253748 | <reponame>archerckk/PyTest<gh_stars>0
#判断一个年份是不是润年,能被4整除,并且不被100整除,或者能被400整除
year=input('请输入你要查询的年份:')
while not year.isdigit():
print('你输入的不是一个有效的年份!请重新输入:',end='')
year=input()
year=int(year)
if (year%4==0 and year%100!=0) or year%400==0:
print(str(year)+'是闰年!!!')
else:
print(str(year)+'不是闰年!... | StarcoderdataPython |
1628496 | <reponame>mateusnr/hackerrank-solutions
a = int(raw_input())
b = int(raw_input())
m = int(raw_input())
print pow(a,b)
print pow(a,b,m)
| StarcoderdataPython |
27422 | <gh_stars>0
"""
DIRBS dimension function for duplicate threshold within a time period.
Copyright (c) 2018 Qualcomm Technologies, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the
limitations in the disclaimer below) provided ... | StarcoderdataPython |
3321181 | <reponame>scottwedge/xdmf
from Xdmf import *
import XdmfCore
import timeit
import os
import time
numberArrays = 10000
arraySize = 100
h5file = os.getcwd() + "/timing.h5"
xmffile = os.getcwd() + "/timing.xmf"
class TimedWrite():
def __init__(self):
self.domain = XdmfDomain.New()
grid = XdmfUnstruc... | StarcoderdataPython |
3224536 | from jina.peapods.runtimes.head import HeadRuntime
if False:
from argparse import Namespace
def pod(args: 'Namespace'):
"""
Start a Pod
:param args: arguments coming from the CLI.
"""
from jina.peapods.pods import Pod
try:
with Pod(args) as p:
p.join()
except Key... | StarcoderdataPython |
3274646 | import datetime
from unittest import TestCase
from datautils import date_hole_printer, generate_dt_list
class TestDataUtils(TestCase):
def test_generate_date_list(self):
start_p = datetime.date(2018, 1, 1)
end_p = datetime.date(2018, 1, 3)
expected = [datetime.date(2018, 1, 1), datetime.... | StarcoderdataPython |
3296908 | #!/usr/bin/env python3
# Copyright 2015 Conchylicultor. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless req... | StarcoderdataPython |
3328668 | import random
vowels = 'aaaaaaaaaaaaaeeeeeeeeeeeeeiiiiiiiiioooooooooouuuuyy'
consonants = 'bbbbbbbbcccddddddffffffggghhhjjkkkkkkkllllllmmmmmmmmnnnnnnnppppppqrrrrrrsssssssssstttttttvvvvwxz'
name = ''
vowels_saturation = 0
consonants_saturation = 0
while(len(name) < random.randrange(3,12)):
if(random.randrange(-3*vow... | StarcoderdataPython |
188609 | <filename>log_topic/emit_log_topic.py
import pika
import sys
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='topic_logs', exchange_type='topic')
routing_key = sys.argv[1] if len(sys.argv) > 2 else 'anonymous.info'
message... | StarcoderdataPython |
4840512 | <reponame>moritzschaefer/moritzsphd_pub
import pandas as pd
# TODO here I could also use the transcript list from Daniel
def _filter_best_transcript(db, gene):
transcripts = db.children(db[gene], featuretype='transcript')
for appris_type in [
'appris_principal_1',
'appris_principal_2',... | StarcoderdataPython |
1766473 | <filename>5_flutter_analysis_tools/flutter_utilities.py
import numpy as np
from scipy.optimize import curve_fit
from scipy.fft import fft
def sin_func(t, A, phi, omega):
return A*np.sin(omega*t+phi)
def sin_cos_func(t, a, b, c, omega):
return a + b*np.cos(omega*t) + c*np.sin(omega*t)
def extract_sinusoid... | StarcoderdataPython |
51976 | from mission.constants.missions import Gate, Path
from conf.vehicle import is_mainsub
HYDROPHONES_PINGER_DEPTH = 3.0
NONSURFACE_MIN_DEPTH = 0.6
# gate = Gate(
# depth=1.0,
# initial_approach_target_percent_of_screen=.45,
# gate_width_threshold=0.4,
# pre_spin_charge_dist=16 if is_mainsub else 12,
# ... | StarcoderdataPython |
1698959 | # -*- coding: utf-8 -*-
""" Functions for generating fake JSON data """
from __future__ import (
absolute_import,
division,
print_function,
unicode_literals,
)
from builtins import *
import json
from scriptabit import HabiticaTask
def get_fake_stats(
_id='this is not a common guid',
con=10,
... | StarcoderdataPython |
3266606 | <filename>training.py
import random
import json
import pickle
import numpy as np
import nltk
# nltk.download()
nltk.download('wordnet')
from nltk.stem import WordNetLemmatizer
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation, Dropout
from tensorflow.keras.optimi... | StarcoderdataPython |
3305386 | from datetime import datetime, timedelta
from freezegun import freeze_time
from freezegun.api import FakeDatetime
from mock import Mock, call
import pytest
import six.moves.urllib as urllib
from sqlalchemy.orm.exc import NoResultFound
from bs4 import BeautifulSoup
from flask import json, url_for
from app.models impor... | StarcoderdataPython |
48443 | # modified from utils/models/segmentation/erfnet.py
# load pretrained weights during initialization of encoder
import torch
import torch.nn as nn
import torch.nn.functional as F
from .common_models import non_bottleneck_1d
from .builder import MODELS
class DownsamplerBlock(nn.Module):
def __init__(self, ninput,... | StarcoderdataPython |
1740918 | from django import forms, template
from django.template.loader import render_to_string
from ..protections import ProtectionList
register = template.Library()
@register.simple_tag(takes_context=True)
def render_protection(context, protectiontup):
result, protection = protectiontup
protection = protection.ins... | StarcoderdataPython |
103648 | <reponame>l33tdaima/l33tdaima<filename>p129m/sum_numbers.py<gh_stars>1-10
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
from local_packages.binary_tree import TreeNode
clas... | StarcoderdataPython |
3219366 | <gh_stars>0
#crie um programa que faça o computador jogar jokenpô com voçe.
import random
geraN = random.randint(1,3)
jogador = int(input('escolha um numero \n'
'(1) para pedra \n'
'(2) para papel \n'
'(3) para tesoura'))
if jogador >= 4 or jogador <= 0:
p... | StarcoderdataPython |
3254160 | <gh_stars>1-10
__author__ = 'Elahe'
# This is to
#1. creat the database
#2. generate the field data (indep of teh schedule)
import numpy as np
import ephem
import FBDE
import time
# my modules
import CreateDB
import FieldDataGenerator as dgen
def initial_setup(site, end_date):
# create database and data stru... | StarcoderdataPython |
1794792 | <filename>mfa/methods/recovery.py
import pyotp
from django.contrib.auth.hashers import check_password
from django.contrib.auth.hashers import make_password
name = 'recovery'
def register_begin(user):
secret = pyotp.random_base32()
totp = pyotp.TOTP(secret, digits=10)
code = totp.now()
code = '%s-%s' ... | StarcoderdataPython |
17645 | <reponame>liqi17thu/Stand-Alone-Self-Attention
import torch
import torchvision.datasets as datasets
import torchvision.transforms as transforms
from lib.data.data_util import ImageNetPolicy, ToBGRTensor
from lib.config import cfg
from lib.data.transformer_v2 import get_transforms
def finetune_imagenet():
transfo... | StarcoderdataPython |
3330713 | <filename>gen/fetch.py<gh_stars>0
# -*- coding: utf-8 -*-
import os
import pathlib
import urllib.parse
import bs4
import requests
ROOT = os.path.dirname(os.path.abspath(__file__))
# enable caching files
CACHING = True
link = 'https://docs.zeek.org/en/stable/script-reference/scripts.html'
resp = requests.get(link)
i... | StarcoderdataPython |
3299421 | # STAIRCASE HACKERRANK SOLUTION:
# creating a function to print the staircase.
def staircase(n):
# creating a for-loop to print the staircase for the indicated amount of rows.
for i in range(1, n + 1):
# printing the staircase.
print(str('#' * i).rjust(n))
# receiving inpu... | StarcoderdataPython |
1617450 | from pyxdsm.matrix_eqn import MatrixEquation
################################
# define the system
################################
lin_system = MatrixEquation()
lin_system.add_variable(1, size=1, text="a")
lin_system.add_variable(2, size=1, text="b")
lin_system.add_variable(3, size=1, text="c")
lin_syst... | StarcoderdataPython |
21047 | <filename>kirbyClass.py
from crossingClass import *
from joinClass import *
from strandClass import *
from componentClass import *
class Kirby:
def __init__(self,crossings,joins):
self.crossings=crossings
self.joins=joins
strands=[] #makes list of strands
for c in crossings:
for i ... | StarcoderdataPython |
4822490 |
import alpaca_trade_api as tradeapi
# get s&p500
import pandas as pd
def collect(api, STOCK_NUM, type, TRAINBARLENGTH, Time):
table=pd.read_html('https://en.wikipedia.org/wiki/List_of_S%26P_500_companies')
df = table[0]
sp = df['Symbol']
import os, os.path
barset = []
for symbol in range(STOCK_NUM, STOCK_NUM +... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.