id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
1722156 | def test_hello():
print("test hello")
| StarcoderdataPython |
1755571 | import io
from ast import AST
from typing import Optional, TextIO, Tuple, Union
from .context import TranspilerContext
from .retokenizer import retokenize
from .transpiler import IMPL_NAME, transpile_ast, transpile_source
def source_from_filename(filename: str) -> str:
with open(filename, 'r') as script_file:
... | StarcoderdataPython |
3219932 | import sys
sys.path.append('.')
import numpy as np
from functions.Voltages import Voltages
from numpy import sin, cos, pi
import os
import matplotlib.pyplot as plt
from scipy.signal import butter, lfilter, freqz
def butter_lowpass(cutoff, fs, order=5):
nyq = 0.5 * fs
normal_cutoff = cutoff / nyq
... | StarcoderdataPython |
3230235 | <gh_stars>0
import pickle
import sys
sys.path.append("..")
from model import ECO
import paddle.fluid as fluid
# Load pickle, since pretrained model is too bigger than the threshold(150M), split them into 2 parts and then reload them
f0 = open('seg0.pkl', 'rb')
f1 = open('seg1.pkl', 'rb')
model_out = dict()
... | StarcoderdataPython |
1649654 | #!/usr/bin/env python3
import os
import psutil
import signal
import subprocess
import sys
import time
from panda import Panda
serials = Panda.list()
num_pandas = len(serials)
if serials:
# If panda is found, kill boardd, if boardd is flapping, and UsbPowerMode is CDP when shutdown,
# device has a possibility of r... | StarcoderdataPython |
3349036 | <gh_stars>0
from django.contrib import admin
from django.db import models
from django.forms.widgets import ClearableFileInput # This is what ImageFields use by default, we're going to customize ours a little.
from project.persons.models import Person
class ImageWidget(ClearableFileInput):
template_name = "image_widg... | StarcoderdataPython |
4800353 | name = 'doctest-cli'
| StarcoderdataPython |
1786074 | import os
import sys
import argparse
import shutil
#Globals
g_includedFiles = []
class COLORS:
DEFAULT = '\033[0m'
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
ERROR = '\033[91m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def printColor(text, color=COLORS.DEFAULT, resetColo... | StarcoderdataPython |
4830317 | <reponame>joshuapatel/PewDiePie
import discord
from discord.ext import commands
class EconomyPhrases(commands.Cog):
def __init__(self, bot):
self.bot = bot
async def update_shovel(self):
self.bot.econ["pos"] = await self.bot.pool.fetch("SELECT name, id FROM shovel WHERE fate = true")
... | StarcoderdataPython |
3263049 | <filename>algs4/prim_mst.py
"""
* Execution: python prim_mst.py filename.txt
* Data files: https://algs4.cs.princeton.edu/43mst/tinyEWG.txt
* https://algs4.cs.princeton.edu/43mst/mediumEWG.txt
* https://algs4.cs.princeton.edu/43mst/largeEWG.txt
*
* Compute a minimum spanning ... | StarcoderdataPython |
4835338 | #!/usr/bin/env python
"""
This class reads sqlalchemy schema metadata in order to construct
joins for an arbitrary query.
Review all the foreign key links.
"""
__author__ = "<NAME> <<EMAIL>>"
__revision__ = "$Revision: 1.11 $"
class LinkObj(object):
"""class encapsulate for foreign key"""
def __init__(self,... | StarcoderdataPython |
3321847 | <gh_stars>0
class Reply:
count_id = 00
def __init__(self, reply):
Reply.count_id += 1
self.__reply_id = Reply.count_id
self.__reply = reply
def get_reply(self):
return self.__reply
def get_reply_id(self):
return self.__reply_id
def set_reply(... | StarcoderdataPython |
3214812 | # Signals that fires when a user logs in and logs out
from django.contrib.auth import user_logged_in, user_logged_out
from django.dispatch import receiver
from .models import LoggedInUser
@receiver(user_logged_in)
def on_user_logged_in(sender, request, **kwargs):
logged_in_user_instance, _ = LoggedInUser.objects... | StarcoderdataPython |
67633 | <gh_stars>1-10
import numpy as np
import pandas as pd
from sklearn.metrics import mean_absolute_error
from statsmodels.tsa.ar_model import AR
import statsmodels.api as sm
from time import time
class diff_integ:
def __init__(self,seasons):
"""
Differentiation and Integration Module
This cl... | StarcoderdataPython |
99366 | import logging
import discord
from discord.ext import commands
class Errors(commands.Cog, name="Error handler"):
def __init__(self, bot):
self.bot = bot
self.logger = logging.getLogger(__name__)
@commands.Cog.listener()
async def on_ready(self):
self.logger.info("I'm ready!")
... | StarcoderdataPython |
1717936 | <filename>spinoffs/oryx/oryx/experimental/nn/combinator.py
# Copyright 2020 The TensorFlow Probability Authors.
#
# 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/l... | StarcoderdataPython |
3336826 | import pygame
import os
from save import is_disabled
pygame.init()
class GUI:
def __init__(self):
self.project_path = os.path.join(os.path.dirname(__file__), "images")
self.board_img = pygame.image.load(os.path.join(self.project_path, "board.png"))
self.figures_images = self.load... | StarcoderdataPython |
3260942 | import stocklab
stocklab.bundle(__file__)
| StarcoderdataPython |
4807026 | #pragma repy
def foo():
print 'OK!'
if callfunc=='initialize':
settimer(0.5, foo, ())
exitall()
| StarcoderdataPython |
144194 | <reponame>tlalexander/stitchEm
from vs import *
from camera import *
| StarcoderdataPython |
4817001 | <reponame>CHH3213/two_loggers<filename>omni_diff_rl/scripts/maddpg-master/experiments/double_ind-v1.py
# !/usr/bin/python
# -*- coding: utf-8 -*-
"""
Doubld escape environment with discrete action space
"""
from __future__ import absolute_import, division, print_function
import gym
from gym import spaces
from gym.envs.... | StarcoderdataPython |
1651972 | <reponame>gzy403999903/seahub<gh_stars>0
import os
import json
from django.core.urlresolvers import reverse
from seaserv import seafile_api
from seahub.test_utils import BaseTestCase
from tests.common.utils import randstring
class RepoTrashTest(BaseTestCase):
def setUp(self):
self.user_name = self.use... | StarcoderdataPython |
1633443 | #Crie um programa onde o usuário possa digitar vários valores numéricos e cadastre-os em uma lista. Caso o número já exista lá dentro, ele não será adicionado. No final, serão exibidos todos os valores únicos digitados, em ordem crescente.
valor=[]
while True:
v=int(input('Digite um valor: '))
if v not in valo... | StarcoderdataPython |
3228536 | import os
import numpy as np
import subprocess
from sklearn.metrics import f1_score, accuracy_score
from utils import *
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # see issue #152
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
data_dir = "../data/inference_data/"
mode = "unlabeled" # real, fake, or unlabeled
pretrain... | StarcoderdataPython |
1988 | # -*- coding: utf-8 -*-
import logging
import datetime
from flask import request, render_template
from flask_jwt_extended import (
create_access_token,
decode_token
)
from jwt.exceptions import DecodeError
from flasgger import swag_from
from http import HTTPStatus
from pathlib import Path
from sqlalchemy.orm.e... | StarcoderdataPython |
197780 | <reponame>gokudomatic/cobiv
__all__=["NodeDb"] | StarcoderdataPython |
1668626 | <filename>pwa_store_backend/pwas/migrations/0047_remove_pwa_manifest_json.py<gh_stars>0
# Generated by Django 3.2.6 on 2021-08-28 14:17
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('pwas', '0046_alter_pwa_slug'),
]
operations = [
migrations.R... | StarcoderdataPython |
1763310 | #------------------
# Author @<NAME>
# Prediction
#-------------------
from tensorflow.keras.models import load_model
from mycvlibrary import config
from collections import deque
import numpy as np
import argparse
import cv2
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--input", required=True, h... | StarcoderdataPython |
74422 | import itertools
import numpy as np
import networkx as nx
import vocab
def coref_score(instance, property_id):
return [ instance.subject_entity["coref_score"], instance.object_entity["coref_score"] ]
def el_score(instance, property_id):
return [ instance.subject_entity["el_score"], instance.object_entity["el_scor... | StarcoderdataPython |
3394162 | import smtplib
import os
from dotenv import load_dotenv
my_mail = 'From: <EMAIL>'
friend_mail = 'To: <EMAIL>'
subject_mail = 'Subject: Приглашение'
mail_text = '''\n\n Привет, %friend_name%! %my_name% приглашает тебя на сайт %website%!
%website% — это новая версия онлайн-курса по программированию.
Изучаем Python и н... | StarcoderdataPython |
3258371 | <gh_stars>10-100
from search_api import *
__version__ = "1.0.0"
__author__ = "<NAME> (@MattDMo)"
__all__ = ["articleAPI"]
if __name__ == "__main__":
print("This module cannot be run on its own. Please use by running ",
"\"from NYTimesArticleAPI import articleAPI\"")
exit(0)
| StarcoderdataPython |
1632002 | <gh_stars>0
' These seem to be accurate, but maybe I readed the barrel wrong. '
from __future__ import annotations
import random
from hijackedrole.game.stats import StatsBase
class DumbStats():
'10:KILL.LEVEL.LOOT.GOTO 10'
def __init__(self, initMaxHP: int = 5, initMaxSP: int = 5,
ATT: int = ... | StarcoderdataPython |
3212466 | <reponame>MHeasell/hearts-server<gh_stars>0
import unittest
from hearts.services.player import PlayerService, PlayerStateError
class TestPlayerService(unittest.TestCase):
def setUp(self):
self.svc = PlayerService()
def test_get_player_not_found(self):
data = self.svc.get_player(1234)
... | StarcoderdataPython |
1663272 | import time, datetime
import numpy as np
import shutil
import sys
from PIL import Image
import torch
from torch import nn
import torch.backends.cudnn as cudnn
import torch.optim as optim
from torchvision import datasets
from torch.autograd import Variable
from learning.utils_learn import *
from learning.dataloader im... | StarcoderdataPython |
3369428 | import logging
logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG)
__version__ = '0.8.3'
| StarcoderdataPython |
3242952 | <filename>submissions/make_submissions_lgbm_gs.py
import os
# For reading, visualizing, and preprocessing data
import numpy as np
import pandas as pd
import torch
import torch.nn.functional as F
from pytorch_toolbelt.utils import fs
from sklearn.metrics import make_scorer
from sklearn.model_selection import GroupKFold... | StarcoderdataPython |
1624867 | <gh_stars>1-10
# -*- coding: utf-8 -*-
# @Author: SHLLL
# @Email: <EMAIL>
# @Date: 2018-03-22 21:21:05
# @Last Modified by: SHLLL
# @Last Modified time: 2018-04-23 00:11:28
# @License: MIT LICENSE
import re
class Parser(object):
"""The html content parser."""
def __init__(self, para_url_reg, urls_queue,... | StarcoderdataPython |
53971 | <filename>base_ppo_agent.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from ray import tune
from ray.rllib.agents.ppo import PPOTrainer
from ray.tune import grid_search
import hfo_py
from soccer_env.high_action_soccer_env import HighActionSoccerEnv
def on_episode_end(info):
episode = info["episode"]
episo... | StarcoderdataPython |
3293736 | <gh_stars>1-10
from __future__ import print_function
import os
import yaml
from click.testing import CliRunner
from dagster import seven
from dagster.api.launch_scheduled_execution import sync_launch_scheduled_execution
from dagster.cli.pipeline import execute_list_command, pipeline_list_command
from dagster.core.de... | StarcoderdataPython |
98885 | #!/usr/bin/python2.7
import os
import re
import sys
import shutil
import fnmatch
import argparse
import tempfile
import subprocess
CWD = os.path.dirname(os.path.realpath(__file__))
SMALI_DEFAULT = os.path.join(CWD, 'smali.jar')
BAKSMALI_DEFAULT = os.path.join(CWD, 'baksmali.jar')
ZIPALIGN_DEFAULT = os.path.join(CWD,... | StarcoderdataPython |
3366367 | """SGTR algorithm for iteratively solving Ax=b over multiple A's and b's."""
import numpy as np
from numpy.linalg import norm as Norm
import pandas as pd
from .optimizer import Optimizer
from .ridge import Ridge
from .group_loss_function import GroupLossFunction
from .pde_loss_function import PDELossFunction
class ... | StarcoderdataPython |
170754 | num = int(input("Digite um número Natural: "))
#cont = 0
#list = []
list_div = []
for c in range(1, num + 1):
if num % c == 0:
#cont += 1
list_div.append(c)
#list.append(c)
print(list)
print('='*40)
print(f'{num} possui {len(list_div)} divisores!\n'
f'Os dividores de {num} são: {list_div}'... | StarcoderdataPython |
11123 | """Use translation table to translate coding sequence to protein."""
from Bio.Data import CodonTable # type: ignore
from Bio.Seq import Seq # type: ignore
def translate_cds(cds: str, translation_table: str) -> str:
"""Translate coding sequence to protein.
:param cds: str: DNA coding sequence (CDS... | StarcoderdataPython |
161409 | <gh_stars>1-10
#! /usr/bin/python
import redis
import base64
class RedisBackend:
_r_sample_id = 'next.sample.id'
_r_samples = 'samples'
_r_samples_hmap = 'samples.hmap'
_r_samples_features = 'samples:%s:features'
_r_species_id = 'next.species.id'
_r_species = 'species'
_r_species_hmap = '... | StarcoderdataPython |
167185 | <gh_stars>1-10
#coding=utf-8
from time import time
from urlparse import urlparse
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from mezzanine.core.models import Displayable, Ownable
from mezzanine.generic.models import Rating
from mezzanine.generic.fi... | StarcoderdataPython |
3258801 | import unittest
from decimal import Decimal
from toshi.utils import parse_int
class TestParseInt(unittest.TestCase):
def test_parse_int_string(self):
self.assertEqual(parse_int("12345"), 12345)
def test_parse_negative_int_string(self):
self.assertEqual(parse_int("-12345"), -12345)
def... | StarcoderdataPython |
1774919 | <filename>dojo/unittests/test_sslyze_parser.py
from django.test import TestCase
from dojo.tools.sslyze.parser import SslyzeXmlParser
from dojo.models import Test
class TestSslyzeXMLParser(TestCase):
def test_parse_without_file_has_no_findings(self):
parser = SslyzeXmlParser(None, Test())
self.ass... | StarcoderdataPython |
11304 | <gh_stars>1-10
# -*- coding: utf-8 -*-
import os
import util
from fabric.api import *
from fabric.state import output
from fabric.colors import *
from base import BaseTask
from helper.print_helper import task_puts
class CollectConfig(BaseTask):
"""
collect configuration
"""
name = "collect"
def run_task(sel... | StarcoderdataPython |
3253929 | <gh_stars>1000+
# main.py
import module1
# even though test was added to sys.modules
# in module1, we can still access it from here
import test
print(test())
# don't do this! It's a bad hack to illustrate how import looks
# in sys.modules for the symbol we are importing
| StarcoderdataPython |
20479 | import numpy as np
import chainer.functions as F
from chainer import Variable
def neural_stack(V, s, d, u, v):
# strengths
s_new = d
for t in reversed(xrange(s.shape[1])):
x = s[:, t].reshape(-1, 1) - u
s_new = F.concat((s_new, F.maximum(Variable(np.zeros_like(x.data)), x)))
u = F.... | StarcoderdataPython |
179988 | # coding: utf-8
from ac_engine.actions.trends import AbstractTrends
from django.conf import settings
class Trends(AbstractTrends):
EXCLUSION_SET = settings.HINT_EXCLUSION_SET
@property
def data_processor_class(self):
from ac_engine_allegro.data.data_processor import DataProcessor
return D... | StarcoderdataPython |
3355882 | <reponame>vt-dev-team/vt-randomName<gh_stars>0
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'init.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know w... | StarcoderdataPython |
1646498 | import numpy as np
import pytest
from lagom.core.transform import Clip
from lagom.core.transform import Centralize
from lagom.core.transform import Normalize
from lagom.core.transform import Standardize
from lagom.core.transform import ExpFactorCumSum
from lagom.core.transform import RunningMeanStd
from lagom.core.t... | StarcoderdataPython |
4804579 | <reponame>yoomoney/yookassa-sdk-python
# -*- coding: utf-8 -*-
from yookassa.client import ApiClient
from yookassa.domain.common.http_verb import HttpVerb
class Settings:
base_path = '/me'
def __init__(self):
self.client = ApiClient()
@classmethod
def get_account_settings(cls, params=None):
... | StarcoderdataPython |
132915 | # Under MIT License, see LICENSE.txt
from Model.DataObject.BaseDataObject import catch_format_error
from Model.DataObject.AccessorData.BaseDataAccessor import BaseDataAccessor
__author__ = 'RoboCupULaval'
class PlayInfoAcc(BaseDataAccessor):
def __init__(self, data_in):
super().__init__(data_in)
... | StarcoderdataPython |
3392835 | __author__ = '<NAME>'
__email__ = '<EMAIL>'
__version__ = '1.0'
__license__ = 'MIT'
# Step (1): Setup the environment
import numpy as np
from sklearn import datasets
from thb.datascience.ibm.KNNClassifier import KNNClassifier
# load the iris data set
iris = datasets.load_iris()
# Step (2): Define the Iris sample whi... | StarcoderdataPython |
3387791 | <gh_stars>0
from threading import Event
from mgmt.steps_base import Step, Context
from mgmt_utils import log
from com.ic_interface import Direction
class BackToOriginStep(Step):
def __init__(self, context: Context):
super(BackToOriginStep, self).__init__(context)
def run(self):
log.debug('... | StarcoderdataPython |
3241565 | <reponame>perfeelab/weichigong
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from kazoo.client import KazooClient
__name__ = "weichigong"
__version__ = '1.0.3'
__author__ = 'dashixiong'
__author_email__ = '<EMAIL>'
class zconfig:
def __init__(self, zkHosts, app, env):
self.app = app
s... | StarcoderdataPython |
3357080 | <reponame>Juliet-Chunli/cnss
'''
Module for the NetworkAgent class that can be subclassed by agents.
@author: <NAME> <<EMAIL>>
'''
from SimPy import Simulation as Sim
import networkx as nx
import random
SEED = 123456789
ADD_EDGE = "add edge"
REMOVE_EDGE = "remove edge"
ADD_NODE = "add node"
REMOVE_NO... | StarcoderdataPython |
1712820 | from django.test import TestCase
from django.core.urlresolvers import reverse
from .models import Task
from .common import is_chance, delete_all_tasks
class TaskTestCase(TestCase):
def tst_views_test1(self):
"""Количество объектов в БД при разных вероятностях."""
total = Task.objects.all().count... | StarcoderdataPython |
1690768 | # -*- coding: utf-8 -*-
from collections import OrderedDict
from datetime import datetime
import yaml
from mynt.exceptions import ConfigurationException
from mynt.fs import Directory
from mynt.utils import get_logger, normpath, URL
logger = get_logger('mynt')
class Configuration(dict):
def __init__(self, str... | StarcoderdataPython |
3382735 | import random
class Knight:
position = 0
road = None
team = 0
gs = None
def __init__(self, _road, _team, _gs):
self.road = _road
self.team = _team
self.gs = _gs
def tick(self):
self.position += 1
if self.position >= self.road.length:
self.pr... | StarcoderdataPython |
1705064 | import logging
from config import iot23_attacks_dir, iot23_data_dir
from src.iot23 import iot23_metadata, data_cleanup, get_data_sample
from src.helpers.log_helper import add_logger
from src.helpers.data_helper import prepare_data
# Add Logger
add_logger(file_name='02_prepare_data.log')
logging.warning("!!! This step... | StarcoderdataPython |
21917 | <gh_stars>1-10
import numpy as np
import os
import argparse
import tqdm
import pandas as pd
import SimpleITK as sitk
from medpy import metric
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument('--file_path', type=str, default='./results/abus_roi/0108_dice_1/')
args = parser.parse_ar... | StarcoderdataPython |
1789381 | import torch
import warnings
from binding_prediction.protein import ProteinSequence
from binding_prediction.utils import onehot
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=FutureWarning)
warnings.filterwarnings("ignore", category=DeprecationWarning)
import tensorflow as tf
c... | StarcoderdataPython |
19204 | import torch
import hcat.lib.functional
from hcat.lib.functional import IntensityCellReject
from hcat.backends.backend import Backend
from hcat.models.r_unet import embed_model as RUnet
from hcat.train.transforms import median_filter, erosion
import hcat.lib.utils
from hcat.lib.utils import graceful_exit
import os.pat... | StarcoderdataPython |
1752393 | import psutil
import time
import math
import gitlab
import os
from argparse import ArgumentParser
import configparser
MODULE_NAME = "ptl: Automatically log time in GitLab issue tracker for COMP23311 at UoM."
__version__ = "0.1.0"
def print_config(token, project_id, issue_id):
print("--:CONFIG:--\n" + "🎫 TOKEN:" + ... | StarcoderdataPython |
1623374 | <reponame>vicdashkov/ClickHouse
import time
import pytest
import requests
from tempfile import NamedTemporaryFile
from helpers.hdfs_api import HDFSApi
import os
from helpers.cluster import ClickHouseCluster
import subprocess
SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
cluster = ClickHouseCluster(__file... | StarcoderdataPython |
3239020 | from datetime import datetime
import logging
from logging.handlers import SMTPHandler, RotatingFileHandler
import os
from config import Config
from flask import Flask, session
from flask_cors import CORS
from flask_login import LoginManager, current_user
from flask_mail import Mail
from flask_migrate import Migrate
fr... | StarcoderdataPython |
3268621 | <filename>visualization.py
import argparse
import os
import matplotlib.pyplot as plt
import numpy as np
import wandb
from torchvision import transforms
from MODELS.model_resnet import *
from custom_dataset import DatasetISIC2018
from gradcam import GradCAM, GradCAMpp
from gradcam.utils import visualize_cam
parser = ... | StarcoderdataPython |
1718173 | <gh_stars>0
from django.shortcuts import render
def sensor_view(request):
return render(request, "sensor.html", {'sensor': '99'}) | StarcoderdataPython |
1703587 | """
usage: /Users/eisenham/Documents/ssbdev/crds/crds/rowdiff.py
[-h] [--ignore-fields IGNORE_FIELDS] [--fields FIELDS]
[--mode-fields MODE_FIELDS] [-v] [--verbosity VERBOSITY] [-V] [-J] [-H]
[--stats] [--profile PROFILE] [--pdb]
tableA tableB
Perform FITS table difference by rows
position... | StarcoderdataPython |
3225082 | """Test script for ftplib module."""
# Modified by <NAME>' to test FTP class and IPv6 environment
import ftplib
import threading
import asyncore
import asynchat
import socket
import StringIO
from unittest import TestCase
from test import test_support
from test.test_support import HOST
# the dummy data returned by ... | StarcoderdataPython |
3334261 | <reponame>BCNI/VisualDiscriminationTask
#!/usr/bin/env/python
# whisker/__init__.py
import logging
logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())
# http://eric.themoritzfamily.com/learning-python-logging.html
# http://stackoverflow.com/questions/12296214/python-logging-with-a-library-na... | StarcoderdataPython |
1718633 | <reponame>pubkraal/Advent<gh_stars>0
#!/usr/bin/env python3
import sys
def fuel_need(num):
return max(0, int(num / 3) - 2)
def reduced_fuel_need(num):
step = num
total = 0
for x in range(100):
more_fuel = fuel_need(step)
if more_fuel == 0:
break
total += more_fue... | StarcoderdataPython |
3206165 | <reponame>CarlosMart626/dj_blog
from django.conf.urls import url
from functools import wraps
from django.utils.decorators import available_attrs
from django.views.decorators.cache import cache_page
from djcms_blog.settings import DJCMS_BLOG_CACHE_TIME
from djcms_blog import settings
from . import views
def cache_for... | StarcoderdataPython |
1751942 | from simple_smartsheet.models import Sheet
class TestSheet:
def test_dataframe(self, mocked_sheet: Sheet) -> None:
df = mocked_sheet.as_dataframe()
assert len(df) == 3
assert df.loc[0]["Full Name"] == "<NAME>"
assert df.loc[1]["Email address"] == "<EMAIL>"
assert df.loc[2][... | StarcoderdataPython |
3243677 | import json
from pprint import pprint
from flask import jsonify
from flask import Flask, request
from pathlib import Path
import subprocess
import os
from botcommands.youtube_dlp import get_meta, get_mp4
from flask import send_file
from yt_dlp.utils import DownloadError
app = Flask(__name__)
@app.route("/")
def hell... | StarcoderdataPython |
3388217 | <filename>GPIO/NixieTube.py
# coding=utf-8
import sys
sys.path.append('..')
reload(sys)
sys.setdefaultencoding('utf8')
import time
import RPi.GPIO as GPIO
# 共阳4位数字管
class Yang4():
# 显示位数
p1 = 1
p2 = 2
p3 = 3
p4 = 4
# 显示状态
a = 5
b = 6
c = 7
d = 8
e = 9
f = 10
g = 11... | StarcoderdataPython |
3225774 | """
----------------------------------
<NAME>
AM: 2011030054
email: <EMAIL>
----------------------------------
"""
import pickle
import crypto_1
import random
from collections import namedtuple
"""
-----------------------------------------
Helpfull function
--------------------... | StarcoderdataPython |
3383955 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Create custom shapes for pyprototypr
"""
# lib
import math
# third party
from reportlab.platypus import Paragraph
from reportlab.lib.styles import ParagraphStyle
# local
from pyprototypr.utils import tools
from pyprototypr.base import BaseShape, BaseCanvas, UNITS, COLOR... | StarcoderdataPython |
3276584 | <filename>script.module.nanscrapers/lib/nanscrapers/scraperplugins/hubmovie.py
import re
import requests
import xbmc
import urllib
from ..scraper import Scraper
from ..common import clean_title,clean_search
session = requests.Session()
User_Agent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 8_4 like Mac OS X) AppleWebKit/600... | StarcoderdataPython |
3247106 | """
@name: Modules/House/Lighting/__init__.py
@author: <NAME>
@contact: <EMAIL>
@copyright: (c) 2011-2020 by <NAME>
@note: Created on May 1, 2011
@license: MIT License
@summary: This module handles the lights component of the lighting system.
"""
__updated__ = '2020-02-16'
__version_info__ = (20, 1,... | StarcoderdataPython |
3334245 | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.config import ConfigValidationError
from txircd.module_interface import Command, ICommand, IModuleData, ModuleData
from txircd.modules.xlinebase import XLineBase
from txircd.utils import durationToSeconds, ircLower, now
from zope.int... | StarcoderdataPython |
86395 | <reponame>juliensimon/optimum-graphcore
#!/usr/bin/env python
# coding=utf-8
# Copyright 2021 The HuggingFace Team 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
#
# ... | StarcoderdataPython |
123921 | __author__ = 'Claudio'
"""Demonstrate how to use Python’s list comprehension syntax to produce
the list [0, 2, 6, 12, 20, 30, 42, 56, 72, 90].
"""
def demonstration_list_comprehension():
return [idx*x for idx, x in enumerate(range(1,11))]
| StarcoderdataPython |
1654090 | <filename>peach/database/proxy.py
from peach.utils import load_resource_class
def load_db_proxy(db_conf):
db_proxy_class = load_resource_class(db_conf['proxy'])
return db_proxy_class.build(**db_conf)
class DBProxy(object):
@classmethod
def build(cls, **kwargs):
raise NotImplementedError
... | StarcoderdataPython |
3221465 | from rubrix.client.sdk.users.models import User
from rubrix.server.security.model import User as ServerUser
def test_users_schema(helpers):
client_schema = User.schema()
server_schema = ServerUser.schema()
assert helpers.remove_description(client_schema) == helpers.remove_description(
server_sche... | StarcoderdataPython |
4801496 | <reponame>tho-wa/virushack
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 21 15:18:46 2020
@author: LB
response = requests.get(
'https://hystreet.com/api/locations/',
params={},
headers={'X-API-Token': '<KEY>'},
)
json_response = response.json()
| StarcoderdataPython |
189528 | from datetime import datetime, timedelta
from airflow import DAG
default_args = {
"owner": "airflow",
"email_on_failure": False,
"email_on_retry": False,
"email": "<EMAIL>",
"retries": 1,
"retry_delay": timedelta(minutes=5),
}
with DAG(
"forex_data_pipeline",
start_date=datetime(2021,... | StarcoderdataPython |
3380029 | """
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
def levelOrder(self, root: 'Node') -> List[List[int]]:
if root is None:
return []
result, previousLayer = [], [root,]
... | StarcoderdataPython |
3329505 | # Exemplo de dado com função
def dadosPessoais(nome, idade, cidade):
print("Seu nome é {}, você tem {} anos e mora em {}.".format(nome, idade, cidade))
dadosPessoais("José", 30, "Maceió")
dadosPessoais(nome="Joaquim", idade=80, cidade="Alagoas")
| StarcoderdataPython |
4820270 | <reponame>AlexanderIbrahim1/threebodyparah2
import os
import sys
import pathlib
import subprocess
class KernelGeneratorInfo:
def __init__(self, power1, power2, csvfile, kerneldir):
# check if power1 and power2 are valid
assert 0 <= power1 <= 6
assert 0 <= power2 <= 6
# sett... | StarcoderdataPython |
3298346 | <filename>chemex/experiments/cpmg/fast/back_calculation.py
from numpy.linalg import matrix_power
from scipy.linalg import expm
from ....bases.two_states.fast import P_180Y
from ....caching import lru_cache
from .liouvillian import compute_iy_eq, compute_liouvillians, get_iy
@lru_cache()
def make_calc_observable(time... | StarcoderdataPython |
84786 | # -*- coding: utf-8 -*-
from autograd.blocks.trigo import sin
from autograd.blocks.trigo import cos
from autograd.blocks.trigo import tan
from autograd.blocks.trigo import arcsin
from autograd.blocks.trigo import arccos
from autograd.blocks.trigo import arctan
from autograd.variable import Variable
import numpy as np
i... | StarcoderdataPython |
1693490 | #!/usr/bin/env python3
"""An image analyser that finds the three most common colors in an image.
Title:
Dominant Colors
Description:
Develop a program that accepts an image
either via the devices's camera (if it has one)
or a file dialog.
Your program should intelligently determine
three of the most dominant colors i... | StarcoderdataPython |
1739999 | <reponame>ChristopherMayes/lume-orchestration-demo
from setuptools import setup, find_packages
from os import path, environ
import versioneer
cur_dir = path.abspath(path.dirname(__file__))
# parse requirements
with open(path.join(cur_dir, "requirements.txt"), "r") as f:
requirements = f.read().split()
setup(
... | StarcoderdataPython |
1783011 | <reponame>mikema2019/Machine-learning-algorithms<filename>Supervised Machine Learning Algorithms/Ensemble Methods/Gradient_Boosting.py
from Decision_Tree_CART import DecisionTree_CART
import numpy as np
import matplotlib.pyplot as plt
from sklearn.ensemble import GradientBoostingRegressor,AdaBoostRegressor
def ... | StarcoderdataPython |
1785902 | def divide_chunks(list_to_chunk, chunk_size):
# looping till length l
for i in range(0, len(list_to_chunk), chunk_size):
yield list_to_chunk[i:i + chunk_size]
| StarcoderdataPython |
3331818 | from .password import PasswordChange
from .utente import Utente
__all__ = [
"PasswordChange",
"Utente",
]
| StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.