id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
3279143 |
import exc
from bisect import bisect_right
from functools import reduce
__all__ = ['Source', 'Location', 'merge_locations']
class Source(object):
def __init__(self, text, url = None):
self.text = text
self.url = url
self.lines = [0]
for i, c in enumerate(text):
if c ... | StarcoderdataPython |
31746 | <reponame>embiem/chia-blockchain<gh_stars>1-10
import io
from typing import Any, List, Set
from src.types.sized_bytes import bytes32
from src.util.clvm import run_program, sexp_from_stream, sexp_to_stream
from clvm import SExp
from src.util.hash import std_hash
from clvm_tools.curry import curry
class Program(SExp)... | StarcoderdataPython |
3290960 | <gh_stars>1-10
#!/usr/bin/env python
#External settings
import settings
#External modules
import time
print("Use this to test clock impulses on pin "+str(settings.slavePin)+" (per settings.py)")
if settings.piMode:
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(settings.slavePin, GPIO.OUT)
el... | StarcoderdataPython |
1122 | #! /usr/bin/env python3
"""
constants.py - Contains all constants used by the device manager
Author:
- <NAME> (<EMAIL> at <EMAIL> dot <EMAIL>)
Date: 12/3/2016
"""
number_of_rows = 3 # total number rows of Index Servers
number_of_links = 5 # number of links to be sent to Cra... | StarcoderdataPython |
3277355 | import pandas as pd
import csv
from sklearn.model_selection import train_test_split
data_cross_path = '~/Code/data/argmining19-same-side-classification/data/same-side-classification/cross-topic/{}.csv'
data_within_path = '~/Code/data/argmining19-same-side-classification/data/same-side-classification/within-topic/{}.cs... | StarcoderdataPython |
180366 | <filename>task2.py
from random import randint
def main():
min_value = 1
max_value = 0
while min_value > max_value:
min_value = randint(0, 150)
max_value = randint(75, 200)
while True:
user_input = input(f'Input number in range {min_value} - {max_value}\n')
try:
... | StarcoderdataPython |
3339412 | <filename>news/urls.py
from django.urls import path
from .views import NewsListView,SportsListView,EconomyListView,PoliticsListView,LifestyleListView,EntertainmentListView
from . import views
urlpatterns = [
path('scrape/', views.scrape, name="scrape"),
path('scrape1/', views.scrape1, name="scrape1"),
path('scrape... | StarcoderdataPython |
1775032 | <reponame>RaitzeR/VAL
import random, sys, math, pygame
from pygame.locals import *
from Helpers.Helpers import *
from Helpers.IntersectingLineDetection import *
from Robot.Robot import Robot
from Robot.Sensors.Simulated.Ultrasonic import Ultrasonic
from Robot.Sensors.Simulated.Hall import Hall
from Robot.Sensors.Simul... | StarcoderdataPython |
1753227 | from flask import Flask, render_template, request
import plotly
import plotly.graph_objs as go
import plotly.express as px
import json
import io
import base64
import sys
import os
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# sys.path.append('/Desktop/myproject')
from ma... | StarcoderdataPython |
3240284 | <filename>src/gedml/launcher/trainers/__init__.py
"""
This module takes charge of training.
"""
from .base_trainer import BaseTrainer | StarcoderdataPython |
3222941 | from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer
import json
class LobbyConsumer(WebsocketConsumer):
def connect(self):
self.room_name = 'lobby'
self.room_group_name = 'chat_%s' % self.room_name
# Join room group
async_to_sync(self.cha... | StarcoderdataPython |
3386477 | #
# Copyright (c) 2017 Juniper Networks, Inc. All rights reserved.
#
"""
Mesos network manager
"""
# Standard library import
import gevent
import sys
from gevent.queue import Queue
# Application library import
import common.args as mesos_args
import common.logger as logger
from cfgm_common import vnc_cgitb
import vnc... | StarcoderdataPython |
3202000 | print("blah blah blah\n")
#This is a comment
| StarcoderdataPython |
4805040 | <filename>test/integration_test.py
import unittest
import luigi
from netCDF4 import Dataset
from iasi import DecompressDataset
from iasi.file import MoveVariables
from test_precision import TestCompareDecompressionResult
class IntegrationTest(TestCompareDecompressionResult):
@classmethod
def setUpClass(cls)... | StarcoderdataPython |
4817792 | import numpy as np
import urllib.request, json, time, os, copy, sys
from scipy.optimize import linprog
global penguin_url
penguin_url = 'https://penguin-stats.io/PenguinStats/api/'
class MaterialPlanning(object):
def __init__(self,
filter_freq=20,
filter_stages=[],
... | StarcoderdataPython |
1749244 | from pywps import Process, LiteralInput, LiteralOutput
from pywps.app.Common import Metadata
class Nap(Process):
def __init__(self):
inputs = [
LiteralInput('delay', 'Delay between every update',
default='1', data_type='float')
]
outputs = [
... | StarcoderdataPython |
184153 | from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
import sys
import codecs
import re
#remove empty lines
#tokenize and remove stopwords
def preprocess(doc):
""" Preprocess a document: tokenize words, lowercase, remove stopwords, non-alphabetic characters and empty lines"""
sw = stopwor... | StarcoderdataPython |
3257867 | <reponame>pawamoy/woof<filename>src/failprint/process.py
"""Functions related to subprocesses."""
import contextlib
import subprocess # noqa: S404 (we don't mind the security implication)
from typing import List, Optional, Tuple
from failprint import WINDOWS
from failprint.capture import Capture
from failprint.forma... | StarcoderdataPython |
3371910 | <reponame>opennms-forge/report-aux<gh_stars>0
# export_all.py
# Easy access to generate PDFs for all node pairs
import export
export.render_all_nodes_pdf()
| StarcoderdataPython |
3371253 | <reponame>ralexrivero/python_fundation
#
# Hello World program in Python
# take info from input and display
def main():
print("Hellow World")
name = input("What is your name? ")
print("Hello ", name)
if __name__ == "__main__":
main()
| StarcoderdataPython |
79076 | <reponame>BrendanFrick/great_expectations
import os
from collections import OrderedDict
import pytest
from ruamel.yaml import YAML, YAMLError
import great_expectations as ge
from great_expectations.data_context.types.base import (
DataContextConfig,
DataContextConfigSchema,
DatasourceConfig,
Datasourc... | StarcoderdataPython |
3370682 | <reponame>liwt31/Renormalizer<filename>renormalizer/mps/mpdm.py
# -*- coding: utf-8 -*-
import logging
from typing import List
import numpy as np
import scipy.linalg
from renormalizer.model import MolList, MolList2, ModelTranslator
from renormalizer.mps.backend import xp
from renormalizer.mps.matrix import tensordot... | StarcoderdataPython |
1612309 | <filename>tensorflow_mri/python/ops/recon_ops.py
# Copyright 2021 University College London. 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... | StarcoderdataPython |
1728141 | <reponame>bookRa/q-tutorials
import graphene
import resolvers
class Info(graphene.ObjectType):
id = graphene.ID(required=True)
name = graphene.String(required=True)
description = graphene.String()
class Sentence(graphene.ObjectType):
id = graphene.ID(required=True)
text = graphene.String(require... | StarcoderdataPython |
153888 | <reponame>P5-G6/graph-tool<filename>backend/tests/integration_tests.py<gh_stars>0
"""Integration tests file."""
import urllib3
import json
import sys
sys.path.append('../')
class TestClass(object):
"""Test routes class."""
mock_vetex = ["1", "2", "3", "4", "5", "6"]
mock_edges = [["1", "4", 3, True],
... | StarcoderdataPython |
1680629 | <gh_stars>0
from barbearia.barbearia import app
from flask import render_template
from barbearia.barbearia import db
from barbearia.main import main_bp
# db.create_all()
@main_bp.route('/home')
@app.route('/')
def home_page():
return render_template('home.html')
@main_bp.route("/contact")
def contact_page():
... | StarcoderdataPython |
3354483 | <filename>generators/app/templates/environment.py
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session
from config import db_url
engine = create_engine(db_url)
Session = scoped_session(sessionmaker(bind=engine))
Base = de... | StarcoderdataPython |
3385953 | # tree.py
# pylint: disable=no-member
r'''
The main LatexTree class
Initialized from a string or file name.
Methods
tree.write_chars() Recover Latex source code
tree.write_pretty() Native output format (see node.py)
tree.write_xml() Uses the `lxml` package
tree.write_bbq()
'''
impo... | StarcoderdataPython |
3353141 | <reponame>mailslurp/mailslurp-client-python<gh_stars>1-10
# coding: utf-8
"""
MailSlurp API
MailSlurp is an API for sending and receiving emails from dynamically allocated email addresses. It's designed for developers and QA teams to test applications, process inbound emails, send templated notifications, att... | StarcoderdataPython |
32717 | <reponame>Jwomers/trinity
from typing import (
Dict,
Sequence,
Tuple,
Type,
)
from eth2.beacon.on_startup import (
get_genesis_block,
get_initial_beacon_state,
)
from eth2.beacon.state_machines.configs import BeaconConfig
from eth2.beacon.types.blocks import (
BaseBeaconBlock,
)
from eth2... | StarcoderdataPython |
157980 | <reponame>robertispas/django-debug-toolbar
import functools
from django.http import Http404, HttpResponseBadRequest
def require_show_toolbar(view):
@functools.wraps(view)
def inner(request, *args, **kwargs):
from debug_toolbar.middleware import get_show_toolbar
show_toolbar = get_show_toolba... | StarcoderdataPython |
144043 | from typing import List
from flask import request
from flask_restx import Namespace, Resource
from CTFd.api.v1.helpers.request import validate_args
from CTFd.api.v1.helpers.schemas import sqlalchemy_to_pydantic
from CTFd.api.v1.schemas import APIDetailedSuccessResponse, APIListSuccessResponse
from CTFd.constants impo... | StarcoderdataPython |
141837 | <gh_stars>10-100
from typing import TypeVar, Callable
from injectable.container.injection_container import InjectionContainer
from injectable.errors.injectable_load_error import InjectableLoadError
from injectable.common_utils import get_caller_filepath
T = TypeVar("T")
def injectable_factory(
dependency: T = N... | StarcoderdataPython |
154608 | <filename>nr_all/search.py
from elasticsearch_dsl.query import Term, Bool
from nr_common.search import NRRecordsSearch
class AllRecordsSearch(NRRecordsSearch):
LIST_SOURCE_FIELDS = [
'control_number', 'oarepo:validity.valid', 'oarepo:draft', 'title',
'dateIssued', 'creator', 'creators', 'resource_... | StarcoderdataPython |
3371824 | <filename>2017/day11.py<gh_stars>1-10
# The hexagons ("hexes") in this grid are aligned such that adjacent hexes can be found to the north, northeast, southeast, south, southwest, and northwest.
# You have a path, starting where he started, you need to determine the fewest number of steps required to reach him. (A "ste... | StarcoderdataPython |
120565 | <gh_stars>0
#!/usr/bin/python
# <NAME> 10/30/2020
#
#
#
# - Gets interface stats from an IOS-XE device
#
import requests
import json
# Welcome
print("Welcome to the Netconf_IOS-XE_BGP.py Script!")
print("*" * 80)
# Variable collection
host_value = input("Host: ")
port_value = input("Port: ")
username = input("Userna... | StarcoderdataPython |
4812814 | """
A frameless window widget
"""
from AnyQt.QtWidgets import QWidget, QStyleOption
from AnyQt.QtGui import QPalette, QPainter, QBitmap
from AnyQt.QtCore import Qt, pyqtProperty as Property
from .utils import is_transparency_supported, StyledWidget_paintEvent
class FramelessWindow(QWidget):
"""
A basic fra... | StarcoderdataPython |
1778401 | #settest
from mgrslib import *
import random
g=Grid(73,-43).mgrs1000.buffer(10000)
gg=mgrsSet(random.sample(g,15))
print len(g)
print g.northernmost()
print g.southernmost()
print g.westernmost()
print g.easternmost()
print g.centeroid()
print g.exterior()
print g.interior()
z=Grid(73,-43)
k=g.nearestTo(z)
print ... | StarcoderdataPython |
36250 | <gh_stars>1-10
import pandas as pd
import mapping_module as mm
import multiprocessing as mp
from sqlalchemy import create_engine
from sys import argv
user_name = argv[1]
password = argv[2]
data_type = argv[3]
start_year = int(argv[4])
end_year = int(argv[5])
leiden_input = argv[6] #quality_func_Res --> CPM_R001
schema... | StarcoderdataPython |
192337 | <reponame>CoSandu/PythonCourses
import urllib
import json
url_in = raw_input("Enter site here: ")
html = urllib.urlopen(url_in).read()
print html
info = json.loads(html)
s = 0
for v in info["comments"]:
s = s + int(v["count"])
print s
| StarcoderdataPython |
50353 | <reponame>TheAnybodys/statistics-projects
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 26 20:23:06 2022
@author: olivi
"""
import random
result = 0
for i in range(1000000):
X = random.uniform(0.0, 1.0)
Y = random.uniform(0.0, 1.0)
if abs(X - Y) <= 0.2:
result += 1
print(result / 1000000)
| StarcoderdataPython |
3211470 |
__all__ = ["Electron_v1"]
#
# electron struct
#
def Electron_v1():
code = """
namespace edm{
struct Electron_v1{
/* Branch variables */
uint32_t RunNumber{};
unsigned long long EventNumber{};
float avgmu{};
float LumiBlock{};
... | StarcoderdataPython |
146664 | <filename>2016/12/monorail.py<gh_stars>1-10
instructions = []
regs = {}
with open('input.txt') as f:
for line in f:
element = line.strip().split()
instructions.append({'operation': element[0],
'operands': tuple(element[1:])})
try:
int(element[1])
... | StarcoderdataPython |
3281314 | import json
import logging
import os
import traceback
from abc import abstractmethod, ABC
from collections import Iterator, Iterable
from logging import Logger
from typing import Union, Any, Callable
from commentjson import commentjson
from rx import Observable, from_
from rx.core.abc import Observer
from faddist.ref... | StarcoderdataPython |
1785697 | """Resolwe models hydrate utils."""
import copy
import os
import re
from pathlib import Path
from django.core.exceptions import ValidationError
from resolwe.flow.utils import iterate_fields
def _hydrate_values(output, output_schema, data):
"""Hydrate basic:file and basic:json values.
Find fields with basic... | StarcoderdataPython |
62959 | <filename>backend/tests/improvements/test_fishing_boats.py
from backend.improvements.fishing_boats import FishingBoats
import pytest
@pytest.fixture(scope="function")
def setup_improvement():
imp = FishingBoats()
return imp
# Init
testdata = [
('food', 1),
('production', 0),
('gold', 0),
('sci... | StarcoderdataPython |
135548 | import json
import os
class JsonLoader:
"""
JsonLoader is used to load the data from all structured json files associated with the DeepInterpolation package.
"""
def __init__(self, path):
self.path = path
self.load_json()
def load_json(self):
"""
This function lo... | StarcoderdataPython |
3265516 | #!/usr/bin/env python
from setuptools import setup
from python3_gearman import __version__ as version
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name='python3_gearman',
version=version,
description=(
'Python 3 Gearman API - Client, worker, and admin client interfa... | StarcoderdataPython |
3211091 | # Importar spacy e criar o objeto nlp do Português
import ____
nlp = ____
# Processar o texto
doc = ____("Eu gosto de gatos e cachorros.")
# Selecionar o primeiro token
first_token = doc[____]
# Imprimir o texto do primeito token
print(first_token.____)
| StarcoderdataPython |
3379522 | <gh_stars>10-100
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if not h... | StarcoderdataPython |
3297425 | <gh_stars>0
#!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
def function(n = 1):
print(n)
return n * 2
x = function(69)
print(x)
| StarcoderdataPython |
1768892 | <filename>Bag.py
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.neighbors import NearestNeighbors
from sklearn.decomposition import PCA
import sys
import cv2
import numpy as np
from glob import glob
import argparse
from helpers import *
class BOV:
de... | StarcoderdataPython |
1724827 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Generated: 10/24/2021(m/d/y) 01:41:23 utc
leagues = ['Standard', 'Hardcore', 'Scourge', 'Hardcore Scourge'] | StarcoderdataPython |
3287399 | <reponame>mpuheim/Various<filename>University - Team Projects/Technicom APG/modules/utils.py<gh_stars>0
from os import mkdir
from sys import exc_clear
# make directory
def makedir(name):
try:
mkdir(name) # try to make directory
except OSError:
exc_clear() # don't show error if dire... | StarcoderdataPython |
1748382 | import os
from enum import Enum
from pathlib import Path
from os.path import join, exists
import argparse
import pathlib
import click
import numpy as np
import pandas as pd
import download_data
import dataframe
import plotter
from matplotlib import pyplot as plt
import seaborn as sns
import dataframe
import plotter... | StarcoderdataPython |
3252755 | <gh_stars>1-10
import numpy as np
class Loader(dict):
"""
方法
========
L 为该类的实例
len(L)::返回样本数目
iter(L)::即为数据迭代器
Return
========
可迭代对象(numpy 对象)
"""
def __init__(self, batch_size, X, Y=None, shuffle=True, name=None):
'''
X, Y 均为类 numpy, 可以是 HDF5
'''
... | StarcoderdataPython |
28248 | <gh_stars>100-1000
#!/usr/bin/env python3
"""
Generate the numeric limits for a given radix.
This is used for the fast-path algorithms, to calculate the
maximum number of digits or exponent bits that can be exactly
represented as a native value.
"""
import math
def is_pow2(value):
'''Calculate if a value is a p... | StarcoderdataPython |
79322 | <reponame>arcosin/ANP_TrackDriver<filename>src/sac/sac.py
import torch
import torch.nn.functional as F
import torch.optim as optim
from torch.distributions import Normal
import numpy as np
from .models import FeatureExtractor, ValueNetwork, SoftQNetwork, PolicyNetwork
from .replay_buffers import BasicBuffer
from .chec... | StarcoderdataPython |
177410 | """
从Kafka 中读取股价信息,
Spark Streaming 输出10秒时间窗的滑动均值作为预测。
"""
from pyspark.sql import SparkSession
from pyspark.sql.functions import explode
from pyspark.sql.functions import split
from pyspark.sql.functions import from_json
import pyspark.sql.types as spark_type
import pyspark.sql.functions as F
from pyspark.sql.function... | StarcoderdataPython |
3206284 | <gh_stars>1-10
# -*- coding: utf-8 -*-
"""Exercise 3 - Question.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/github/lmoroney/dlaicourse/blob/master/Exercises/Exercise%203%20-%20Convolutions/Exercise%203%20-%20Question.ipynb
"""
#@title Licensed unde... | StarcoderdataPython |
35802 | import bs4
import urllib
from base_online_scraper import base_online_scraper as scraper
BASE_URL = 'http://catalog.northeastern.edu'
INITIAL_PATH = '/course-descriptions/'
fp = urllib.urlopen(BASE_URL + INITIAL_PATH)
soup = bs4.BeautifulSoup(fp, 'lxml')
nav_menu = soup.find("div", {"id": "atozindex"}).find_all('a', h... | StarcoderdataPython |
3379270 | <filename>send-email.py
#!/usr/bin/python
import sys
import smtplib
import string
from subprocess import Popen, PIPE
stdout = Popen('ifconfig', shell=True, stdout=PIPE).stdout
output = stdout.read()
HOST = '10.1.0.1'
SUBJECT = "Linux installation complete"
if len(sys.argv) != 2:
# default value for use in old kic... | StarcoderdataPython |
3269849 | <filename>src/puzzle/steps/image/prepare_image.py
import numpy as np
from data.image import image
from puzzle.constraints.image import prepare_image_constraints
from puzzle.steps.image import _base_image_step
class PrepareImage(_base_image_step.BaseImageStep):
_prepare_image_constraints: prepare_image_constraints.... | StarcoderdataPython |
1604891 | <reponame>iRiziya/swift
class RC4:
def __init__(self):
self.state = [0] * 256
self.I = 0
self.J = 0
def init(self, key):
for i in xrange(256):
self.state[i] = i
j = 0
for i in xrange(256):
K = ord(key[i % len(key)])
S = self.state[i]
j = (j + S + K) % 256
sel... | StarcoderdataPython |
3311507 | from authorizations.cookie.entity import Cookie
from .token_object import TokenObject
class CookieObject(TokenObject):
"""
Contains routines that facilitate creating of cookie objects
"""
_entity_class = Cookie
| StarcoderdataPython |
68843 | <reponame>ulope/matrix-python-sdk<gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Matrix Python SDK documentation build configuration file, created by
# sphinx-quickstart on Tue May 3 14:25:58 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all... | StarcoderdataPython |
191408 | <reponame>af765/Flood-Warning-System<gh_stars>0
# Copyright (C) 2018 <NAME>
#
# SPDX-License-Identifier: MIT
"""This module contains a collection of functions related to
geographical data.
"""
from os import access
from .utils import sorted_by_key # noqa
from haversine import haversine
import plotly.graph_objects as... | StarcoderdataPython |
4835768 | <reponame>protodave/CriticMarkup-toolkit<filename>Sublime Text Package/Critic Markup/accept_critic.py
import sublime, sublime_plugin
import re
class AcceptCriticCommand(sublime_plugin.TextCommand):
def run(self, edit):
self.options = ['Accept', 'Reject']
# Need to find scope limits then do regex fi... | StarcoderdataPython |
24106 | import sys
from collections import defaultdict
import torch
from varclr.utils.infer import MockArgs
from varclr.data.preprocessor import CodePreprocessor
if __name__ == "__main__":
ret = torch.load(sys.argv[2])
vars, embs = ret["vars"], ret["embs"]
embs /= embs.norm(dim=1, keepdim=True)
embs = embs.c... | StarcoderdataPython |
1639344 | <gh_stars>0
from threading import Lock
# Lock 类支持 with 语句
lock = Lock()
with lock:
print('Lock is held 拿到锁了')
# 等价的 try/finally 写法
lock.acquire()
try:
print('Lock is held 拿到锁了')
finally:
lock.release()
| StarcoderdataPython |
3345931 | #! /usr/bin/env python3
import requests
import csv
import argparse
import getpass
from datetime import datetime
from datetime import timedelta
import urllib3
from os import path
from os import getcwd
import numpy as np
import time
import json
from jsonpath_ng import jsonpath, parse
# csv mapping config
# - Header tit... | StarcoderdataPython |
3225191 | """
"""
from yoyo import step
__depends__ = {'20210629_03_kqMH9'}
steps = [
step("ALTER TABLE news ADD COLUMN position INTEGER")
]
| StarcoderdataPython |
1714681 | '''
Information on available virtual machine images.
'''
from ... pyaz_utils import _call_az
from . import terms
def list_offers(location, publisher, edge_zone=None):
'''
List the VM image offers available in the Azure Marketplace.
Required Parameters:
- location -- Location. Values from: `az account... | StarcoderdataPython |
3354818 |
from sax import SAX
from sequitur import Grammar
class Motif(object):
"""
This class uses sax and sequitur to identify the motifs from a timeseries
"""
def __init__(self, timeseries, windowSize, wordSize, alphabetSize):
self.timeseries = timeseries
self.windowSize = windowSize
self.wordSize = wordSize
sel... | StarcoderdataPython |
1740240 | # noinspection PyPep8Naming
def solution(X, A):
T_fall = [None] * (X + 1)
for t, x in enumerate(A):
T_fall[x] = min(t, T_fall[x] or t)
t_max = None
for t in T_fall[1:]:
if t is None:
return -1
t_max = max(t, t_max)
return t_max
assert solution(5, [1, 3, 1, 4, 2,... | StarcoderdataPython |
7384 | import sbol2
import pandas as pd
import os
import logging
from openpyxl import load_workbook
from openpyxl.worksheet.table import Table, TableStyleInfo
from openpyxl.utils.dataframe import dataframe_to_rows
from openpyxl.styles import Font, PatternFill, Border, Side
from requests_html import HTMLSession
#wasderivedfro... | StarcoderdataPython |
22559 | <filename>src/plotComponents2D.py
import matplotlib.pyplot as plt
import numpy as np
def plotComponents2D(X, y, labels, use_markers = False, ax=None, legends = None, tags = None):
if X.shape[1] < 2:
print('ERROR: X MUST HAVE AT LEAST 2 FEATURES/COLUMNS! SKIPPING plotComponents2D().')
return
... | StarcoderdataPython |
1632751 | <filename>src/codebase/synthetic/nino3.py
"""Generate synthetic streamflow sequences based on a NINO3 sequence
"""
import os
import numpy as np
import pandas as pd
import xarray as xr
from datetime import datetime
from .synthetic import SyntheticFloodSequence
from ..path import data_path
class NINO3Linear(Synthetic... | StarcoderdataPython |
106534 | <filename>config.py
#! /usr/bin/env python2.7
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from six.moves import xrange
import argparse
class AttrDict (dict):
__getattr__ = dict.__getitem__
__setattr__ = dict.__setitem__
config = AttrDict ({
... | StarcoderdataPython |
3331246 | from services.run import handle_cron_request
from fastapi import FastAPI
from dotenv import load_dotenv
from starlette.responses import RedirectResponse
from DB.database import Base, engine, get_db
import uvicorn
from routes import image, user, auth, user_images
import os
from fastapi_utils.tasks import repeat_every
l... | StarcoderdataPython |
3216188 | <reponame>Harvard-Neutrino/phys145
import ROOT
import itertools
import Analysis
import AnalysisHelpers as AH
import Constants
#======================================================================
class WZAnalysis(Analysis.Analysis):
"""Analysis searching for the pair production of WZ with both boson dec... | StarcoderdataPython |
3316553 | # !/usr/bin/env python
# Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) 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... | StarcoderdataPython |
191413 | <filename>icekit/plugins/slideshow/content_plugins.py
"""
Definition of the plugin.
"""
from django.utils.translation import ugettext_lazy as _
from fluent_contents.extensions import ContentPlugin, plugin_pool
from . import models
@plugin_pool.register
class SlideShowPlugin(ContentPlugin):
model = models.SlideSh... | StarcoderdataPython |
1761142 | <gh_stars>0
import re
import operator
from bytewax import Executor, inp, processes
def tokenize(x):
x = x.lower()
return re.findall(r'[^\s!,.?":;0-9]+', x)
def initial_count(word):
return word, 1
ec = Executor()
flow = ec.Dataflow(inp.single_batch(open("benches/benchmarks/collected-works.txt")))
flow... | StarcoderdataPython |
3292805 | import plotly.express as px
import plotly.graph_objects as go
import dash_core_components as dcc
import dash_html_components as html
from .workout import WORKOUTS
COLORS = {"graph_bg": "#1E1E1E", "text": "#696969"}
def layout_config_panel(current_user):
"""The Dash app layout for the user config panel"""
... | StarcoderdataPython |
3276030 | import docker
import pytest
@pytest.fixture(scope="session")
def client():
return docker.from_env()
@pytest.fixture(scope="session")
def image(client):
img, _ = client.images.build(path='./src', dockerfile='Dockerfile')
return img | StarcoderdataPython |
169756 | import numpy as np
from prml.linear.classifier import Classifier
class Perceptron(Classifier):
"""
Perceptron model
"""
def fit(self, X, t, max_epoch=100):
"""
fit perceptron model on given input pair
Parameters
----------
X : (N, D) np.ndarray
tra... | StarcoderdataPython |
132694 | <gh_stars>10-100
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2014 Open Data ("Open Data" refers to
# one or more of the following companies: Open Data Partners LLC,
# Open Data Research LLC, or Open Data Capital LLC.)
#
# This file is part of Hadrian.
# Licensed under the Apache License, Version 2... | StarcoderdataPython |
32016 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Marshmallow loader for record deserialization.
Use marshmallow schema to transfor... | StarcoderdataPython |
3287534 | <filename>setup.py<gh_stars>0
from setuptools import setup
setup(
name='jsonTV',
version='0.1.1',
author='<NAME>',
author_email='<EMAIL>',
py_modules=['jsontv'],
url='http://pypi.python.org/pypi/jsonTV/',
license='APACHE 2.0',
description='A client for the Schedules Direct JSON API',
... | StarcoderdataPython |
1741928 | <reponame>hexatester/sdgs-dashboard<filename>sdgs/survey_individu/tambah/penyakit_diderita.py<gh_stars>0
import attr
from typing import Dict
@attr.dataclass
class PenyakitDiderita:
# P404
mutaber_diare: bool = False
demam_berdarah: bool = False
campak: bool = False
malaria: bool = False
flu_bu... | StarcoderdataPython |
95393 | <reponame>anuraag392/How-to-make-a-simple-dice-roll-program<filename>dice roll project 1.py<gh_stars>0
from tkinter import *
import random
root=Tk()
root.title("Dice roll")
root.geometry("500x400")
label=Label(root,font=('helvetica',250,'bold'),text='')
label.pack()
def rolldice():
dice=['\u2680','\u2681','... | StarcoderdataPython |
1695336 | <filename>uart_debugger/scripts/waveform_dup.py<gh_stars>1-10
#!/usr/bin/python
"""
Name: <NAME>
ECN Login: mg296
PUID: 0024209781
Email: <EMAIL>
Description: Copy waveforms from an existing testbench and creating a
similar testbench
"""
impor... | StarcoderdataPython |
3322299 | from putils.patterns import Singleton
from putils.filesystem import Dir
import mimetypes
import scss
from scss import Scss
from jsmin import jsmin
import os
import shutil
class StaticCompiler(object):
"""
Static files minifier.
"""
def __init__(self, path):
self.css_parser = Scss()
scss.LOAD_PATHS = path
... | StarcoderdataPython |
57296 | <filename>python/turbodbc/__init__.py
from __future__ import absolute_import
from .api_constants import apilevel, threadsafety, paramstyle
from .connect import connect
from .constructors import Date, Time, Timestamp
from .exceptions import Error, InterfaceError, DatabaseError, ParameterError
from .data_types import ST... | StarcoderdataPython |
118173 | import random
from data import participants
from whatsapp_selenium import send_messages
import time
Host_Name = 'Dorcy'
def generate_text(santa, santee, age):
return f"""Dear {santa},\
\nThis year you are {santee}'s Secret Santa!. Ho Ho Ho!\
\nThis message was automagically generated from a computer by {Host_Nam... | StarcoderdataPython |
3338282 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
from webpages import *
@pytest.fixture
def page(browser, server_url, access_token):
return RootPage(browser, server_url, access_token)
class TestRootPage(object):
def test_should_show_a_dialog_when_o... | StarcoderdataPython |
181384 | <reponame>ahmedengu/h2o-3
import h2o
from h2o.tree import H2OTree
from h2o.estimators import H2OIsolationForestEstimator
from tests import pyunit_utils
def check_tree(tree, tree_number, tree_class = None):
assert tree is not None
assert len(tree) > 0
assert tree._tree_number == tree_number
assert tre... | StarcoderdataPython |
99838 | <filename>pymt/bmi/bmi.py
class Error(Exception):
"""Base class for BMI exceptions"""
pass
class VarNameError(Error):
"""Exception to indicate a bad input/output variable name"""
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
class BMI(object):
... | StarcoderdataPython |
1780348 | <filename>aplications/departamento/views.py
from django.shortcuts import render
from django.views.generic.edit import FormView
from django.views.generic import (
TemplateView,
ListView,
CreateView,
DeleteView,
)
from .forms import NewDepartamentoForm
from .models import Departamento
from aplications.p... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.