id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
5104142 | from django.urls import path
from . import views
app_name = "billing"
urlpatterns = [
path(
"create-checkout-session/<slug:slug>/<int:pk>/",
views.CreateCheckoutSessionView.as_view(),
name="create_checkout_session",
),
path(
"checkout-success/",
views.CheckoutSucces... | StarcoderdataPython |
1618735 | import numpy as np
data = np.loadtxt('GSRM_plate_outlines.gmt',dtype=str)
data = np.flip(data,1)
# Locate the starting position of each plate
bnds_index, = np.where(data[:,1] == '>')
n = len(bnds_index)
# Separate the boundaries of each plate and write it in a file
for i in range(n):
vi = bnds_index[i]
j1 = ... | StarcoderdataPython |
1921502 | # SPDX-License-Identifier: Apache-2.0
# Copyright 2016 Eotvos Lorand University, Budapest, Hungary
from compiler_log_warnings_errors import addError, addWarning
from utils.codegen import format_expr, format_type, format_statement, format_declaration, to_c_bool
from compiler_common import statement_buffer_value, genera... | StarcoderdataPython |
94527 | <filename>iron/pythonlib/SimulationBasics.py
import random, re, sys
import SequenceBasics
import TranscriptomeBasics
from SerializeBasics import encode_64, decode_64
class RandomBiallelicTranscriptomeEmitter:
def __init__(self,transcriptome1=None,transcriptome2=None):
self.transcriptome1 = transcriptome1
sel... | StarcoderdataPython |
6669157 | from collections import OrderedDict
# This is the structure database
MgO_structures = OrderedDict()
MgO_structures['structure_db_dir'] = 'test_LammpsStructuralMinimization'
MgO_structures['MgO_NaCl_unit'] = OrderedDict()
MgO_structures['MgO_NaCl_unit']['filename'] = 'MgO_NaCl_unit.gga.relax.vasp'
MgO_structures['MgO_N... | StarcoderdataPython |
4922047 | <reponame>Juan7655/simulacion_teoria_de_colas<filename>main.py
import time
import matplotlib.pyplot as plt
from src import manager
def waiting_times(server, n, ciclos=1):
start_time = time.time()
man.run(server, n, ciclos)
end_time = time.time() - start_time
return end_time
def complexity(serv):
... | StarcoderdataPython |
1953497 | import requests
import re
import logging
import datetime
import trafilatura
from bs4 import BeautifulSoup
class Request():
def __init__(self, lang = 'en', country = 'US', timeout_sec = 60):
self.lang = lang.lower()
self.country = country.upper()
self.http_header = self.set_http_header()
self.cookies = sel... | StarcoderdataPython |
6524270 | # Copyright (c) 2020 Oracle, Inc.
# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl.
#
import io
import os
import json
import logging
import subprocess
import oci
from fdk import response
def execute_shell_command(cmd):
try:
return (subprocess.run(cm... | StarcoderdataPython |
12857199 | import pyhf
from pyhf.parameters import ParamViewer
def test_paramviewer_simple_nonbatched(backend):
pars = pyhf.tensorlib.astensor([1, 2, 3, 4, 5, 6, 7])
parshape = pyhf.tensorlib.shape(pars)
view = ParamViewer(
parshape,
{'hello': {'slice': slice(0, 2)}, 'world': {'slice': slice(5, 7)}... | StarcoderdataPython |
6403341 | # coding: utf-8
"""
Demo for the live reloading of Flask server.
"""
from __future__ import absolute_import
# Standard imports
import os
import sys
# External imports
import flask
def main():
"""
Main function.
:return:
None.
"""
try:
# Get the `src` directory's absolute path
... | StarcoderdataPython |
306656 | from pandac.PandaModules import *
from direct.showbase import PythonUtil
TARGET_POS = {4: Vec3(0.85, 0, 0.0),3: Vec3(0.6, 0, 0.42),2: Vec3(0.27, 0, 0.6),1: Vec3(-0.08, 0, 0.63),0: Vec3(-0.59, 0, 0.29)}
FACES = PythonUtil.Enum('DEALER,ONE,TWO,THREE,FOUR,FIVE,SIX,SEVEN')
FACE_SPOT_POS = {FACES.DEALER: (-1.0, 0, 0.6),FACE... | StarcoderdataPython |
9725091 | import django
from {{ cookiecutter.pkg_name }} import context_processors
def test_django_version():
"""Test the django_version context processor.
Must return a dictionary containing the current Django version.
"""
assert context_processors.django_version(None) == {'django_version': django.get_versio... | StarcoderdataPython |
3472495 | <gh_stars>0
import setuptools
with open("README.md") as f:
long_description = f.read()
setuptools.setup(
name="twarc-csv",
version="0.2.0",
url="https://github.com/docnow/twarc-csv",
author="<NAME>",
author_email="<EMAIL>",
py_modules=["twarc_csv"],
description="A twarc plugin to outpu... | StarcoderdataPython |
9644925 | import copy
import json
import pickle
import os
from typing import List
from pretty_midi import PrettyMIDI, Instrument, Note
from .Chord import Chord
from ..utils.string import STATIC_DIR
from ..utils.utils import compute_distance, compute_destination, Logging, read_lib
from ..utils.constants import *
from ..settings... | StarcoderdataPython |
3342210 | import tkinter as tk
from tkinter import ttk
import matplotlib.pyplot as plt
import os
from mdtools.plotting_class import FilePlotting
LARGE_FONT = ("Verdana", 10)
class MDAnalysis(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
tk.Tk.wm_title(self, "Analysis of... | StarcoderdataPython |
290785 | import os
import sys
import numpy as np
from scipy.ndimage import measurements
path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.
abspath(__file__))))
if path not in sys.path:
sys.path.append(path)
from CM.CM_TUW0.rem_mk_dir import rm_file
from CM.... | StarcoderdataPython |
340130 | import argparse
import contextlib
import functools
import itertools
import os
import shutil
import time
from pathlib import Path
import numpy as np
import torch
import torch.multiprocessing as mp
import torch.nn.functional as F
from torch.utils.tensorboard import SummaryWriter
import cargan
########################... | StarcoderdataPython |
1679299 | <gh_stars>1-10
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class LevelNode:
def __init__(self, order, node):
self.order = order
self.node = node
class Solution:
def levelOrder(self, ro... | StarcoderdataPython |
110767 | <reponame>sgino209/cloudOCR<gh_stars>0
from sys import stdout
from os import path
from AbbyyOnlineSdk import *
# Recognize a file at filePath and save result to resultFilePath
def recognizeFile(processor, filePath, resultFilePath, language, outputFormat):
prediction = {}
print "Uploading.."
settings = Pr... | StarcoderdataPython |
1912677 | <filename>packages/datetime/lektor_datetime.py
from lektor.pluginsystem import Plugin
from datetime import datetime
def parse_date(str_date, fmt):
return datetime.strptime(str_date, fmt)
class DatetimePlugin(Plugin):
def on_process_template_context(self, context, **extra):
context['parse_date'] = pa... | StarcoderdataPython |
1867175 | <gh_stars>1-10
'''
Read DCS json in an iterated way
@author: avinashvarna
'''
from __future__ import print_function
import os
#import ijson.backends.yajl2_cffi as ijson
import ujson
import codecs
import datetime
from indic_transliteration import sanscript
def iter_sentences():
start = datetime.datetime.now()
... | StarcoderdataPython |
3550844 | <reponame>ColtonBarr/aigt
import os
import time
import cv2
import sys
import numpy
import random
import argparse
import logging
import pyigtl
FLAGS = None
def main():
try:
networkModuleName = FLAGS.network_module_name
sys.path.append(os.path.join(FLAGS.model_directory,os.pardir))
importSta... | StarcoderdataPython |
5057349 | <filename>h2o-bindings/bin/custom/R/gen_isolationforest.py
def update_param(name, param):
if name == 'stopping_metric':
param['values'] = ['AUTO', 'anomaly_score']
return param
return None # param untouched
extensions = dict(
required_params=['training_frame', 'x'],
validate_required_... | StarcoderdataPython |
6608020 | # DO NOT EDIT -- GENERATED BY CMake -- Change the CMakeLists.txt file if needed
firestore_client_HDRS = [
"field_path.h",
]
firestore_client_SRCS = [
"field_path.cc",
]
| StarcoderdataPython |
6419323 | <reponame>audinowho/Maybe
import sqlite3
class PokeSQL:
def __init__(self, cursor):
self.c = cursor
def dexNum(self, name):
t = (name,)
q = self.c.execute('SELECT pokemon_species_id \
FROM pokemon_species_names \
WHERE LOWER... | StarcoderdataPython |
11246233 | # Copyright 2016 - Nokia
#
# 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, sof... | StarcoderdataPython |
5010584 | <reponame>SwarmRoboticsSUSTechOPAL/RosEv3devDemo
# python3
import rospy
from std_msgs.msg import String
import getch
def talker():
pub = rospy.Publisher('chatter', String, queue_size=1)
rospy.init_node('talker', anonymous=True)
while not rospy.is_shutdown():
key = getch.getch()
hello_str =... | StarcoderdataPython |
11232647 | #!-*-coding:utf-8-*-
import sys
# import PyQt4 QtCore and QtGui modules
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5 import uic
from pylinac import PicketFence
from pylinac import picketfence
from PicketFens import Ui_MainWindow
import matplotlib.pyplot as plt
from pylinac import geometry
class... | StarcoderdataPython |
244856 | #!/usr/bin/env python3
import scapy.all as scapy
import optparse
def get_arguments():
parser = optparse.OptionParser()
parser.add_option("-t","--target", dest="ip", help="Target IP or or range of IPs you want to scan\n e.q: '**.**.**.1/24'")
(options, arguments) = parser.parse_args()
if not... | StarcoderdataPython |
6645795 | <reponame>okadalabipr/biomass
from dataclasses import make_dataclass
from typing import Dict, List
NAMES: List[str] = [
"TGFb",
"Rec",
"TGFb_pRec",
"S2",
"S3",
"S4",
"ppS2_ppS2_ppS2",
"ppS3_ppS3_ppS3",
"S4_S4_S4",
"pS2",
"pS3",
"ppS2",
"ppS3",
"ppS2_ppS2_S4",
... | StarcoderdataPython |
3466043 | <gh_stars>10-100
#!/usr/bin/python3
## Tommy
from botbase import *
_saarbruecken_cc1 = re.compile(r"Das Gesundheitsamt des Regionalverbandes meldet heute ([0-9.]+|\w+)")
_saarbruecken_cc2 = re.compile(r"Das Gesundheitsamt des Regionalverbandes meldet am Samstag (?:[0-9.]+|\w+) und am (?:heutigen )?Sonntag weitere ([0-... | StarcoderdataPython |
12844283 | <filename>python3/11.py
#! /usr/bin/env python3
part = 1
def read_input():
with open('../inputs/input11.txt') as fp:
lines = fp.readlines()
return [line.strip() for line in lines]
class Seat:
def __init__(self, x, y, state):
self.x = x
self.y = y
self.state = state
... | StarcoderdataPython |
382527 | <reponame>Vman45/LHA
from pyext import RuntimeModule
from actions.action_callback import ActionCallback
class Action:
name: str
tags: [str]
callback: ActionCallback
callback_arguments_parser: RuntimeModule
def __init__(
self,
name: str,
tags: [str],
... | StarcoderdataPython |
11341736 | import pandas as pd
import numpy as np
import math
from typing import Tuple
from scipy.integrate import solve_ivp
import matplotlib.pyplot as plt
from function_approximation import rbf_approx, approx_nonlin_func
def read_vectorfield_data(dir_path="../data/", base_filename="linear_vectorfield_data") -> Tuple[np.ndarra... | StarcoderdataPython |
1714069 | <filename>Level_1/01_Prison_Labor_Dodgers/solution.py
def solution(x, y):
"""Returns ID that is only present in one of the two lists passed as args
Args:
x: list of prisoner IDs
y: list of prisoner IDs
Returns:
int value of the additional prisoner ID
"""
try:
a =... | StarcoderdataPython |
11305194 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import annotations
import bs4
class DocumentLine:
def __init__(self, doc: Document, line: str, previous: DocumentLine = None):
self.doc = doc
self.line = line
self.idx = previous.idx + 1 if previous else 0
self._xml_... | StarcoderdataPython |
3537778 | <gh_stars>0
#!/usr/bin/env python3
###############################################################################
# #
# RMG - Reaction Mechanism Generator #
# ... | StarcoderdataPython |
11225828 | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 3 16:03:09 2020
@author: Jimit.Dholakia
"""
import requests
import os
import time
import urllib.parse
os.environ['TZ'] = 'Asia/Kolkata'
time.tzset()
url = os.getenv('GITHUB_API_URL', 'https://api.github.com') + '/emojis'
print('Emojis URL:', url)
r = requests.get(ur... | StarcoderdataPython |
372449 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2021 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unl... | StarcoderdataPython |
1899897 | <filename>python/helpers/window_func.py
from typing import Union
import numpy as np
import scipy
def window_func(name: str, m: int, **kwargs: Union[float, int]) -> np.ndarray:
"""Design a window for a given window function.
Parameters
----------
name: str
name of the window, can be any of the... | StarcoderdataPython |
9639492 | <gh_stars>0
# -*- coding: utf-8 -*-
import numpy as np
import random
class EndingRule:
def __init__(self):
self.ending_message = False
self.base_ending_rule = [self.full_board, self.only_one_side]
self.ending_condition_list = {0: self.nothing, 1: self.one_line}
self.ending_option_... | StarcoderdataPython |
3538658 | <reponame>houfu/pdpc-decisions
from pdpc_decisions import classes
def test_pdpcdecision_item_str(decisions_test_items):
assert str(decisions_test_items[1][0]) == "PDPCDecisionItem: 2016-04-21 Institution of Engineers, Singapore"
def test_get_text_as_paragraphs(decisions_gold):
document = classes.CorpusDocum... | StarcoderdataPython |
6543231 | <filename>client.py
# coding: utf-8
import socket
import json
import time
import threading
class Client(object):
def __init__(self, addr="127.0.0.1", port=12345, nickname=None, queue=None):
"""\
@param addr: 服务器ip
@param port: 服务器端口
@param nickname: 注册昵称
@param queue: 消息队列,... | StarcoderdataPython |
378265 | <filename>fem/utilities/dock_table/table_widget.py
"""
dock_table.table_widget
Table widget
author: <NAME>
"""
from __future__ import print_function, absolute_import
from qtpy import QtCore, QtWidgets, QtGui
try:
from .dock_table_ui import Ui_DockWidget
from .dock_data_table import DockDataTable
except Sy... | StarcoderdataPython |
3460219 | from enum import IntEnum
class Color:
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
SKY_BLUE = (41, 173, 255)
GRASS_GREEN = (0, 168, 68)
OCEAN_BLUE = (60, 188, 252)
DARK_BLUE = (0, 64, 88)
WOOD_BROWN = (172, 124, 0)
GRAY ... | StarcoderdataPython |
1781730 | <filename>bittensor/_config/config_impl.py<gh_stars>10-100
"""
Implementation of the config class, which manages the config of different bittensor modules.
"""
# The MIT License (MIT)
# Copyright © 2021 <NAME>
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associate... | StarcoderdataPython |
1767890 | from os.path import isfile
from psi_apps.utils.json_helper import json_loads
from psi_apps.utils.basic_response import \
(ok_resp, err_resp)
def load_file_contents(fpath):
"""Given a file path, open the file and return the contents"""
if not isfile(fpath):
user_msg = 'File not found: %s' % fpath
... | StarcoderdataPython |
8063813 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from mavencoord import MavenCoord
class MavenVersionDb:
""" This class serves as a dependency database so we can lookup
versions of packages that have been registered already.
"""
def __init__ (self):
self._db = {}
self._warnings = set()
return
de... | StarcoderdataPython |
6485649 | <reponame>shauryachawla/misc
#!/usr/bin/env python2
from sys import stdin
n = raw_input().split(' ')
k = int(n[1])
n = int(n[0])
ans = 0
for i in range(0, n):
t = int ( stdin.readline() )
if (t%k) == 0: ans += 1
print (ans)
| StarcoderdataPython |
260086 | <filename>user/views.py
from django.shortcuts import render, redirect
from django.contrib import messages
from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm
from django.contrib.auth.decorators import login_required
from django.contrib.auth import login, authenticate
from django.contrib.sites.shortcu... | StarcoderdataPython |
3477346 | <gh_stars>10-100
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of the SPORCO package. Details of the copyright
# and user license can be found in the 'LICENSE.txt' file distributed
# with the package.
"""
Convolutional Dictionary Learning
=================================
This example demonstrates... | StarcoderdataPython |
270885 | """
*Comparison Operator*
"""
import jax.numpy as jnp
from ._operator import ArrayOperator
class ComparisonOperator(ArrayOperator):
"""
Element-wise comparison operators.
"""
Equal = jnp.equal
NotEqual = jnp.not_equal
IsClose = jnp.isclose
GreaterThan = jnp.greater
GreaterE... | StarcoderdataPython |
6686267 |
def load_population (initPopFile = None, decoder = None):
"""
Args:
initPopFile (str): file name with the population to be loaded.
decoder (Decoder): decoder to decode the candidates.
Returns:
num_generations(str): number of the generation
population (list): list of candid... | StarcoderdataPython |
8049120 | <filename>gym_multi_car_racing/__init__.py
from .multi_car_racing import MultiCarRacing
from gym.envs.registration import register
register(
id='MultiCarRacing-v0',
entry_point='gym_multi_car_racing:MultiCarRacing',
max_episode_steps=1000,
reward_threshold=900
)
| StarcoderdataPython |
12803094 | from django.db import models
class Aluno(models.Model):
nome = models.CharField(max_length=30)
rg = models.CharField(max_length=9)
cpf = models.CharField(max_length=11)
data_nascimento = models.DateField()
def __str__(self):
return self.nome
class Curso(models.Model):
NIVEL = (
... | StarcoderdataPython |
4936331 | from flask import Flask, request, abort, make_response
from flask_httpauth import HTTPBasicAuth
import os, requests, json
from linebot import (
LineBotApi, WebhookHandler
)
from linebot.exceptions import (
InvalidSignatureError, LineBotApiError
)
from linebot.models import (
MessageEvent, TextMessage, Tex... | StarcoderdataPython |
9660935 | <gh_stars>0
from django.shortcuts import render
from django.views.generic.base import RedirectView
# Create your views here.
def index(request):
return render(request, "index.html", context={})
from django.views.generic import TemplateView
class Home(TemplateView):
template_name = "home.html"
class Logi... | StarcoderdataPython |
5074619 | __all__ = ["parser"]
from icevision.all import *
def parser(data_dir: Path):
parser = parsers.VocXmlParser(
annotations_dir=data_dir / "odFridgeObjects/annotations",
images_dir=data_dir / "odFridgeObjects/images",
class_map=ClassMap(["milk_bottle", "carton", "can", "water_bottle"]),
)... | StarcoderdataPython |
9664835 | # coding:utf-8
from __future__ import unicode_literals,division,print_function
__author__ = 'timmyliang'
__email__ = '<EMAIL>'
__date__ = '2020-04-29 17:07:57'
"""
"""
import os
import sys
DIR = os.path.dirname(__file__)
MODULE = os.path.join(DIR,"..","QBinding","_vendor")
if MODULE not in sys.path:
sys.path... | StarcoderdataPython |
3239274 | <reponame>isabella232/cauliflowervest
# Copyright 2017 Google Inc. 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 |
6526092 | def grades():
count = 0
total = 0
while count < 5:
grade = input(f'Enter marks for subject {count+1}: ')
if grade.isdigit():
count+=1
total = total + int(grade)
else:
print("Enter numbers only..")
if int(total)>=90:
print("A*")
elif int(total)>=80:
print("A")
elif int(total)>=... | StarcoderdataPython |
8075808 | # -*- coding: utf-8 -*-
from builtins import object
from django import forms
from django.conf import settings
from django.contrib.admin import widgets as admin_widgets
from django.utils.http import quote
from django.utils.safestring import mark_safe
if "django_thumbor" in settings.INSTALLED_APPS:
from django_thum... | StarcoderdataPython |
6465682 | # -*- coding: utf-8 -*-
import os
import sys
import smbus
import time
import datetime
import RPi.GPIO as GPIO
import Yi2k_ctrl
import subprocess
import gpsd
import threading
import runpy
import argparse
import Adafruit_Nokia_LCD as LCD
import Adafruit_GPIO.SPI as SPI
import lcd_menu as menu
from queue import Queue
fr... | StarcoderdataPython |
3277250 | from utils.db.mongo_orm import *
# 类名定义 collection
class TestReportDetail(Model):
class Meta:
database = db
collection = 'testReportDetail'
# 字段
_id = ObjectIdField() # reportDetailId
reportId = ObjectIdField()
projectId = ObjectIdField()
testSuiteId = ObjectIdField()
tes... | StarcoderdataPython |
6550376 | #<NAME>
#Codewars : @Kunalpod
#Problem name: Simple Pig Latin
#Problem level: 5 kyu
def pig_it(text):
text1 = ' '.join([x[1:]+x[0]+'ay' for x in text.split()])
return text1 if text1[-3].isalpha() else text1[:-2]
| StarcoderdataPython |
11372841 | <filename>bowtie/tests/test_layout.py
"""Test layout functionality."""
# pylint: disable=redefined-outer-name,protected-access
import pytest
from bowtie import App
from bowtie.control import Button
from bowtie.exceptions import GridIndexError, NoUnusedCellsError, SpanOverlapError
def check_all_cells_used(view):
... | StarcoderdataPython |
8086111 | import geohash
class HashConstants(object):
BIT_RADIUS_MAP = {
52: 0.5971,
50: 1.1943,
48: 2.3889,
46: 4.7774,
44: 9.5547,
42: 19.1095,
40: 38.2189,
38: 76.4378,
36: 152.8757,
34: 305.751,
32: 611.5028,
30: 1223.0056,
... | StarcoderdataPython |
1887209 | ##############################################################################
#
# Copyright (c) 2004 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SO... | StarcoderdataPython |
9732433 | <gh_stars>0
import os
def modis_operation(list_folder, source, path):
print(path)
if path.endswith("Layer1/"):
clipName = "clip1_"
mosaicName = "Mosaic1_"
if path.endswith("Layer5/"):
clipName = "clip5_"
mosaicName = "Mosaic5_"
for files in source:
file_name = (... | StarcoderdataPython |
5165019 | from time import sleep
velocidade = float(input("Qual a velocidade você está percorrendo? "))
print("Calculando....")
sleep(3)
if velocidade > 80:
multa = (velocidade-80) * 7
print("\033[:31m MULTADO!!\033[m Você ultrapassou o limite de 80km/h deverá pagar a multa de \033[:31mR${:.2f}\033[m".format(multa))
els... | StarcoderdataPython |
8093621 | import os
from base64 import b32encode
from flask_login import LoginManager, UserMixin
import pyotp
loginmanager = LoginManager()
secret = os.environ["TOTP_SECRET"]
totp = pyotp.TOTP( b32encode( bytes(secret, "utf8") ) )
del(secret)
class OnlyUser(UserMixin):
def __init__(self):
self.id = "0"
@loginman... | StarcoderdataPython |
339075 | <gh_stars>1-10
# 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
#... | StarcoderdataPython |
1774214 | # Advent Of Code 2016, day 1, part 2
# http://adventofcode.com/2016/day/1
# solution by ByteCommander, 2016-12-01
data = open("inputs/aoc2016_1.txt").read()
dirs = [(0, 1), (1, 0), (0, -1),
(-1, 0)] # dirs[0]: North, [1]: East, ... - (x,y) steps
instr = [[-1 if s[0] == "L" else 1, int(s[1:])] for s in data.sp... | StarcoderdataPython |
4871560 | <filename>utils/converter.py
# -*- coding: utf-8 -*-
# Created on Sun Mar 15 00:51:53 2020
# @author: arthurd
import os
def open_files(dirpath, ext="conllu"):
"""Get the path of all files in a directory.
Parameters
----------
dirpath : string
Name or path to the directory where the files yo... | StarcoderdataPython |
3423740 | <gh_stars>1-10
A, B, C = map(int, input().split())
if sorted([A, B, C]) == [5, 5, 7]:
print('YES')
else:
print('NO')
| StarcoderdataPython |
3390165 | # remember to call with --py-files person.py to include this one
from person import Person
from pyspark import SparkContext, SparkConf
sc = SparkContext()
# textfile gives us lines, now we call Person's parse method
people=sc.textFile("../../data/people.txt").map(Person().parse)
# find number of males and number o... | StarcoderdataPython |
399686 | <filename>tests/test_inflection_es.py<gh_stars>100-1000
# -*- fundamental -*-
#
# Tests for parsing inflection tables
#
# Copyright (c) 2021 <NAME>. See file LICENSE and https://ylonen.org
import unittest
import json
from wikitextprocessor import Wtp
from wiktextract import WiktionaryConfig
from wiktextract.inflectio... | StarcoderdataPython |
8062003 | <filename>aoc/year2019/day1/day1.py
from aocd import data
from aoc.utils import ints
def fuel(mass: int) -> int:
return mass // 3 - 2
def total_fuel(mass: int) -> int:
fuel_req = mass // 3 - 2
if fuel_req < 0:
return 0
return fuel_req + total_fuel(fuel_req)
# part 1
print(sum(map(fuel, int... | StarcoderdataPython |
11214822 | import subprocess
from glob import glob
from pathlib import Path
cwd = Path(__file__).parent
name = 'atlas'
output = cwd / '../../dist/data'
file = output / 'atlas.mbtiles'
tiles = glob(str((cwd / '../../data/**/*.mbtiles').resolve()))
if __name__ == '__main__':
file.unlink(missing_ok=True)
output.mkdir(pare... | StarcoderdataPython |
3216755 | <reponame>bozonhiggsa/BotTelegram_ImageStyleTransfer
import os
import urllib.request
from PIL import Image
import numpy as np
import tensorflow as tf
import tensorflow_hub as hub
import config
def save_image_from_message(message, telbot):
cid = message.chat.id
image_id = get_image_id_from_message(message)
... | StarcoderdataPython |
39423 | <filename>alembic/versions/0b7ccbfa8f7c_add_order_and_hide_from_menu_to_page_.py
"""Add order and hide_from_menu to Page model
Revision ID: 0b7ccbfa8f7c
Revises: <KEY>
Create Date: 2016-03-23 16:33:44.047433
"""
# revision identifiers, used by Alembic.
revision = '0b7ccbfa8f7c'
down_revision = '<KEY>'
branch_labels ... | StarcoderdataPython |
11239481 | <gh_stars>1-10
from kg.checkers import * ### @import
@chk.get_one_input
def get_one_input(file, **kwargs):
n = int(next(file))
a = list(map(int, next(file).strip().split()))
ensure(len(a) == n, "Invalid length in input", exc=Fail)
return a
@chk.get_output_for_input
def get_output_for_input(file, a, **... | StarcoderdataPython |
1672352 | <filename>examples/rmg/commented/input.py
# Data sources
database(
# overrides RMG thermo calculation of RMG with these values.
# libraries found at http://rmg.mit.edu/database/thermo/libraries/
# if species exist in multiple libraries, the earlier libraries overwrite the
# previous values
thermoLib... | StarcoderdataPython |
3247315 | <reponame>ukraine-war-info/ukraine-news-bot<gh_stars>1-10
from datetime import datetime
from typing import Any
import rich
from rich.table import Table
class timer:
def __init__(self) -> None:
self.time = datetime.now()
def getTime(self) -> str:
now = datetime.now()
delta = now - self... | StarcoderdataPython |
98191 | # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import hashlib
import json
import re
import unittest
from collections import OrderedDict
from enum import Enum
from pants.base.hash_utils import CoercingEncoder, hash_all, json_hash
from ... | StarcoderdataPython |
6443417 | import logging
import os
from cryptography.fernet import Fernet
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from shhh.api import api
from shhh.extensions import db, scheduler
def register_blueprints(app):
"""Register application blueprints."""
app.register_blueprint(api)
def create_app... | StarcoderdataPython |
12848129 | ####################################
# File name: models.py #
# Author: <NAME> #
####################################
from rss_skill import db
class Feed(db.Model):
__tablename__ = 'feed'
rss_i = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.Text... | StarcoderdataPython |
6524801 | <reponame>euribates/advent_of_code_2018
#!/usr/bin/env python3
import tools
if __name__ == "__main__":
with open('input.txt', 'r') as fh:
data = fh.read().strip()
dl = tools.DL(data)
dl.reduce()
solution = len(dl)
print(f'Solution of part 1: {solution}')
| StarcoderdataPython |
11279361 | <reponame>UserBlackBox/ctf-functions<filename>setup.py<gh_stars>0
from setuptools import setup, find_packages
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setup(
name="ctf_functions",
packages=find_packages(),
version="0.1.0",
entry_points={
},
author="... | StarcoderdataPython |
4918587 | <filename>2017/03.py
#! /usr/bin/env python3
import itertools as it
import sys
import time
from typing import Dict, Generator, List, Tuple
test = False
debug = False
stdin = False
INFILENAME = "inputs/03.txt"
for arg in sys.argv:
if arg == "--test":
test = True
INFILENAME = "inputs/03.test.txt"
... | StarcoderdataPython |
11316775 | """Package with shell specific actions, each shell class should
implement `from_shell`, `to_shell`, `app_alias`, `put_to_history` and
`get_aliases` methods.
"""
import os
#from psutil import Process
from .bash import Bash
from .fish import Fish
from .generic import Generic
from .powershell import Powershell
from .tcsh ... | StarcoderdataPython |
227646 | # coding:utf-8
from crossknight.sqink import createLogger
from crossknight.sqink.domain import isUuid
from crossknight.sqink.domain import NoteStatus
from crossknight.sqink.markdown import renderHtml
from crossknight.sqink.plist import marshalNote
from crossknight.sqink.plist import unmarshalNote
from crossknight.sqink... | StarcoderdataPython |
5138445 | <reponame>leelige/mindspore
# Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... | StarcoderdataPython |
41519 | <filename>aiomatrix/dispatcher/storage/room_events/engines/__init__.py<gh_stars>1-10
from .sqlite import SqliteEventStorageEngine
| StarcoderdataPython |
60913 | import unittest
import hail as hl
from lib.model.seqr_mt_schema import SeqrVariantSchema
from tests.data.sample_vep import VEP_DATA, DERIVED_DATA
class TestSeqrModel(unittest.TestCase):
def _get_filtered_mt(self, rsid='rs35471880'):
mt = hl.import_vcf('tests/data/1kg_30variants.vcf.bgz')
mt = hl... | StarcoderdataPython |
6428523 | <filename>tests/test_protocol.py
from olink.core.protocol import Protocol
from olink.core.types import MsgType
name = 'demo.Calc'
props = { 'count': 1}
value = 1
id = 1
args = [1, 2]
msgType = MsgType.INVOKE
error = "error"
def test_messages():
msg = Protocol.link_message(name)
assert msg == [MsgType.LINK, na... | StarcoderdataPython |
8181248 | from strings.unique_emails import unique_email_addresses
def test_unique_email_addresses():
emails = [
"<EMAIL>+<EMAIL>",
"<EMAIL>+<EMAIL>",
"<EMAIL>+<EMAIL>",
"<EMAIL>"
]
assert unique_email_addresses(emails) == 2
| StarcoderdataPython |
3501563 | <reponame>YOON-CC/Baekjoon
#문자열을 뒤집을 수 있는 것이 있다.
#슬라이스라는 것으로 문자열[::-1] 이렇게 사용하면 문자열이 뒤집힌다.
# ex) hello => olleh
a = int(input())
for _ in range(a):
n = list(input().split())
for i in range(int(len(n))):
if int(len(n[i]))>=2:
print(n[i][::-1], end=" ")
else:
print(n[i],end... | StarcoderdataPython |
6627619 | <reponame>kids-first/kf-lib-data-ingest
import os
import pytest
from click.testing import CliRunner
from pandas import DataFrame
from conftest import KIDS_FIRST_CONFIG, TEST_INGEST_CONFIG
from kf_lib_data_ingest.app import cli
from kf_lib_data_ingest.common.errors import InvalidIngestStageParameters
from kf_lib_data_... | StarcoderdataPython |
67373 | import pygame
import math
from roengine.util import Dummy
from roengine.config import PLAYER_KEYBINDS, USE_ROTOZOOM
__all__ = ["PlatformerPlayer"]
class PlatformerPlayer(pygame.sprite.Sprite):
keybinds = PLAYER_KEYBINDS
speed = 5
jump_power = 10
gravity = 0.5
climb_skill = 1
climb_velocity ... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.