id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
3268631 | <gh_stars>0
import torch.nn as nn
from typing import Tuple, Any
import torch
from torch.functional import Tensor
class RecurrentNeuralNetwork(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super().__init__()
self.hidden_size = hidden_size
self.input2output = nn.Linear(input_size + ... | StarcoderdataPython |
8187226 | <reponame>Francis777/CME241-Assignment<gh_stars>1-10
import sys
import gym
import numpy as np
import random
import math
from collections import defaultdict
# TODO: sarsa(lambda)
def sarsa(env, num_episodes, alpha, gamma=1.0):
def epsilon_greedy(Q, state, nA, eps):
if random.random() > eps:
retu... | StarcoderdataPython |
3263464 | <filename>djavue/renderers/vuetify.py
from typing import List
from .base import VueRenderer
class VuetifyRenderer(VueRenderer):
def _write_body(self, context: object, scripts: List[str] = []) -> None:
"""
Writes the body tag to the html
"""
root = self.component_list.root.mount(con... | StarcoderdataPython |
6592830 | <gh_stars>1-10
import numpy as np
import h5py
import convTreesToETF.VELOCIraptor_Python_Tools.velociraptor_python_tools as VPT
def convVELOCIraptorToMTF(opt,fieldsDict):
treefields = ["ID","RootTail","Tail","Head","RootHead"]
#Load in the VELOCIraptor catalogue
Redshift,halodata,walkabletree = LoadVELOCIraptor(o... | StarcoderdataPython |
9648688 | <reponame>arnavb/google-docstring-error-python
import pytest
import responses as rsps
import pypokedex
@pytest.fixture
def responses():
pypokedex.get.cache_clear()
with rsps.RequestsMock() as requests_mock:
yield requests_mock
| StarcoderdataPython |
122679 | <gh_stars>1-10
class reslice():
def __init__(self, image=[[0.0]], order=[0]):
import numpy as np
self.image = np.transpose(image, order)
def image(self: 'array_float'):
return self.image
| StarcoderdataPython |
8192604 | <reponame>akiomik/pilgram<filename>pilgram/css/blending/tests/test_soft_light.py
# Copyright 2019 <NAME>
#
# 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... | StarcoderdataPython |
8146234 | import torch
import torch.nn as nn
from genotypes import STEPS
from utils import mask2d
from utils import LockedDropout
from utils import embedded_dropout
INITRANGE = 0.04
class DARTSCell(nn.Module):
def __init__(self, n_inp, n_hid, dropout_h, dropout_x):
super().__init__() # python3 下 == super().__in... | StarcoderdataPython |
1930602 | '''
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import math
import numpy as np
from fairseq import utils
#maggie adding encoders for printing texts
from fairseq.data import encoders
#ma... | StarcoderdataPython |
3431118 | <filename>wranglesearch/extraction_statistics.py<gh_stars>0
from argparse import ArgumentParser
import glob
import inspect
import os
import pickle
import matplotlib.pyplot as plt
plt.ion()
import networkx as nx
import numpy as np
import pandas as pd
from plpy.analyze.dynamic_tracer import DynamicDataTracer
from .iden... | StarcoderdataPython |
4987618 | <filename>worker/ShanXiCrawler.py
from worker import Crawler
import pymysql
import urllib.request
from bs4 import NavigableString
import re
baseUrl = "http://www.sxdi.gov.cn/"
indexUrl = baseUrl + "gzdt/jlsc/"
opener = urllib.request.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0 (Windows NT 10.0; Win... | StarcoderdataPython |
8143231 | # -*- coding: utf-8 -*-
from tccli.services.cmq.cmq_client import action_caller
| StarcoderdataPython |
132285 | <reponame>dHonerkamp/ActiveClassifier
import numpy as np
import tensorflow as tf
from activeClassifier.tools.tf_tools import FiLM_layer
class Representation:
def __init__(self, FLAGS, name='reprNet'):
self.name = name
self.use_conv = False
self._kwargs = dict(units=FLAGS.num_hidden_fc, ac... | StarcoderdataPython |
1904878 | <filename>densenas/dense/generate_random.py
import pprint
import importlib
import copy
from configs.search_config import search_cfg
from configs.imagenet_train_cfg import cfg
from models import model_derived
from models.dropped_model import Dropped_Network
from tools import utils
from tools.config_yaml import merge_cfg... | StarcoderdataPython |
8157504 | <gh_stars>1-10
# -*- coding: utf-8 -*-
"""
tests.tests_controllers.test_controller
~~~~~~~~~~~~~~~~~~~
This script contains tests for the app Controller.
"""
import pytest
from src.controllers.controller import Controller
@pytest.fixture()
def create_controller() -> Controller:
"""Create Controller object for t... | StarcoderdataPython |
60283 | # coding: utf-8
import logging
from behave import *
import foods.kebab # type: ignore
import foods.pizza # type: ignore
from foods.formula import Formula
logger = logging.getLogger(__name__)
use_step_matcher("parse")
foods_ = []
@given(
"Mister Patate's favorite foods (a {food} is represented by a {sauce} a... | StarcoderdataPython |
125257 | <reponame>gansanay/adventofcode
# Advent of Code 2021, Day 06
# Attempting to share small, instructive, PEP8-compliant solutions!
# Any comments? Find me on:
# - Twitter: @gansanay
# - LinkedIn: https://linkedin.com/in/gansanay
from collections import Counter
from adventofcode.util.input_helpers import get_input... | StarcoderdataPython |
3247469 | import logging
import os
import requests
import time
from flask import Flask, request, jsonify
import sentry_sdk
from sentry_sdk.integrations.flask import FlaskIntegration
logging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO)
logger = logging.getLogger(__name__)
sentry_... | StarcoderdataPython |
11277421 | <reponame>palkeo/brownie<filename>brownie/project/sources.py
#!/usr/bin/python3
import json
import re
import textwrap
from hashlib import sha1
from pathlib import Path
from typing import Dict, List, Optional, Tuple
from semantic_version import NpmSpec
from brownie.exceptions import NamespaceCollision, PragmaError, U... | StarcoderdataPython |
6442355 | """
This module is used for general configurations of the project, like STMP and SQL data
and it is also used for defining general exceptions for SSH, DB and SMTP
"""
import paramiko
from smtplib import SMTP, SMTPException, SMTPConnectError, SMTPHeloError, SMTPAuthenticationError
from sqlite3 import connect, Operatio... | StarcoderdataPython |
8101231 | <reponame>damslab/reproducibility<filename>temp-uplift-submission/scikit-learn/adult_sk.py
import sys
import time
import json
import numpy as np
import scipy as sp
from scipy.sparse import csr_matrix
import pandas as pd
import math
import warnings
from sklearn.pipeline import make_pipeline
from sklearn.compose import C... | StarcoderdataPython |
4979989 | import codecs
import json
import numpy as np
import os
import pickle
import random
import tensorflow as tf
from detext.model.bert import modeling
from detext.utils import test_utils
from detext.utils import vocab_utils
def force_set_hparam(hparams, name, value):
"""
Removes name from hparams and sets hparams... | StarcoderdataPython |
334632 | <reponame>taoshen58/glm-codes
import json
import argparse
import spacy
import os
from tqdm import tqdm
def main():
# nlp = spacy.load("en", disable=['parser', 'tagger', 'ner', 'textcat'])
parser = argparse.ArgumentParser()
parser.add_argument("--input_path", type=str, required=True)
parser.add_argumen... | StarcoderdataPython |
3368564 | from typing import Callable, List, Tuple
def build_consumer(charset: List[str]) -> Callable[[str], Tuple[str, str]]:
"""Return a callable that consume anything in *charset*
and returns a tuple of the consumed and unconsumed text"""
def consumer(text: str) -> Tuple[str, str]:
consumed = []
... | StarcoderdataPython |
319370 | <reponame>Wings30306/yomdb
from django.contrib import admin
from .models import Movie, WatchlistItem
# Register your models here.
admin.site.register(Movie)
admin.site.register(WatchlistItem) | StarcoderdataPython |
1722520 | <gh_stars>0
import os
import math
from poker_trainer.cards import SUITS, RANKS, Hand
def load_hand_order():
__location__ = os.path.realpath(
os.path.join(os.getcwd(), os.path.dirname(__file__)))
files = {
'3H' : 'static/he3maxordering.txt',
'6H' : 'static/he6maxordering.txt',
... | StarcoderdataPython |
8069612 | <gh_stars>0
from django.utils.translation import ugettext_lazy as _
from allianceauth.services.hooks import MenuItemHook, UrlHook
from allianceauth import hooks
from . import urls
class ExampleMenuItem(MenuItemHook):
def __init__(self):
# setup menu entry for sidebar
MenuItemHook.__init__(
... | StarcoderdataPython |
1642191 | <filename>leetcode/931_minimum_falling_path_sum.py
class Solution:
"""
matrix dp
2 1 3 2 1 3
6 5 4 7 6 5
7 8 9 13 13 13
"""
def minFallingPathSum(self, matrix) -> int:
dp = [[0]*len(matrix[0]) for _ in range(len(matrix))]
for i, n in enumerate(matrix[0]):
... | StarcoderdataPython |
253016 | <gh_stars>1-10
from musicscore.dtd.dtd import Sequence, Element
from musicscore.musicxml.elements.xml_element import XMLElement
from musicscore.musicxml.types.complextypes.complextype import ComplexType
from musicscore.musicxml.types.simple_type import String
class VirtualLibrary(XMLElement, String):
"""
The ... | StarcoderdataPython |
3458414 | <gh_stars>0
import numpy as np
import matplotlib.pyplot as plt
# Perceptron class with all the functions
class Perceptron:
def __init__(self, inputs_num, outputs_num, epoch, learning_rate):
self.inputs_num = inputs_num
self.outputs_num = outputs_num
self.epoch = epoch
self.learning... | StarcoderdataPython |
1697271 | #!/bin/env python
# Copyright (c) 2002-2017, California Institute of Technology.
# All rights reserved. Based on Government Sponsored Research under contracts NAS7-1407 and/or NAS7-03001.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following con... | StarcoderdataPython |
8182597 | <reponame>vladaspasic/fireant<filename>fireant/slicer/totals.py
import sys
import numpy as np
import pandas as pd
MAX_TIMESTAMP = pd.Timestamp.max
MAX_NUMBER = sys.maxsize
MAX_STRING = '~~totals'
TOTALS_MARKERS = {MAX_STRING, MAX_NUMBER, MAX_TIMESTAMP}
def get_totals_marker_for_dtype(dtype):
"""
For a give... | StarcoderdataPython |
82043 | #!/usr/bin/env python2
import os
print os.environ['VAULT_PASSWORD']
| StarcoderdataPython |
1671190 | <gh_stars>10-100
import pytest
from py_wake.utils.check_input import check_input
import numpy as np
def test_check_input():
input_space = [(0, 1), (100, 200)]
with pytest.raises(ValueError, match="Input, index_0, with value, 2 outside range 0-1"):
check_input(input_space, np.array([(2, 150)]).T)
... | StarcoderdataPython |
6575781 | class ResponseProcessException(Exception):
def __init__(self, zype_exception, data, *args, **kwargs):
self.zype_exception = zype_exception
self.data = data
super(ResponseProcessException, self).__init__(*args, **kwargs)
class ZypeException(Exception):
def __init__(self, message, client... | StarcoderdataPython |
9781350 | <gh_stars>0
#!/usr/bin/env python3
# https://leetcode.com/problems/first-bad-version/
import unittest
lc278_first_bad_version = 0
def isBadVersion(version):
# pylint: disable=W0603
global lc278_first_bad_version
return lc278_first_bad_version <= version
class Solution:
def firstBadVersion(self, n... | StarcoderdataPython |
8145970 | <filename>scatter_sample.py
from __future__ import absolute_import, division, print_function
import tensorflow as tf
import numpy as np
if tf.__version__.startswith('1.13'):
tf.enable_eager_execution()
print('EARGER MODE!!')
# np_val = np.array([[[1,2,3][4,5,6][7,8,9]],[[1,2,3][4,5,6][7,8,9]]])
np_val = ... | StarcoderdataPython |
212455 | <reponame>Wang-jiahao/SimDeblur
""" ************************************************
* fileName: gopro.py
* desc: The dataset used in Deep Multi-Scale Convolutional Neural Network for Dynamic Scene Deblurring
* author: mingdeng_cao
* last revised: None
************************************************ """
import os
imp... | StarcoderdataPython |
6468590 | from setuptools import setup, find_packages
setup(
name='gym_yotrading',
version='0.0.4',
packages=find_packages(),
author='VL',
author_email='<EMAIL>',
install_requires=[
'gym>=0.12.5',
'numpy>=1.16.4',
'pandas>=0.24.2',
'matplotlib>=3.1.1'
],
package... | StarcoderdataPython |
6406152 | <filename>dae/dae/variants/tests/test_genotype.py
"""
Created on Feb 15, 2018
@author: lubo
"""
from dae.utils.regions import Region
import numpy as np
def test_11540_gt(variants_impl):
fvars = variants_impl("variants_vcf")("backends/a")
vs = fvars.query_variants(regions=[Region("1", 11539, 11542)])
v ... | StarcoderdataPython |
3356070 | ##-------------------------------------------------------------------
"""
Write a function height returns the height of a tree. The height is defined to
be the number of levels. The empty tree has height 0, a tree of one node has
height 1, a root node with one or two leaves as children has height 2, and so on
For examp... | StarcoderdataPython |
11235622 | # -*- coding: utf-8 -*-
# ---------------------------------------------------------------------
# Wipe managed object
# ---------------------------------------------------------------------
# Copyright (C) 2007-2018 The NOC Project
# See LICENSE for details
# ------------------------------------------------------------... | StarcoderdataPython |
9646263 | from django.shortcuts import render, redirect
from django.http import HttpResponse, JsonResponse
def routapp(request):
if request.method == "GET":
try:
if request.session.has_key('phoneno'):
return render(request, 'dash_mobilev3.html')
else:
return ... | StarcoderdataPython |
4951859 | <reponame>fxkuehl/keyboard<filename>scripts/genseq.py
#!/usr/bin/python3
import sys
# Keys are numbered 0-31. Even numbers are left hand, odd numbers are
# right hand, arranged such that for every left hand key x, the right
# hand mirror image is x+1.
#
# 8 | 6 | 4 | 2 0 || 1 3 | 5 | 7 | 9 ... | StarcoderdataPython |
1990562 | # -*- coding: utf-8 -*-
from io import BytesIO
from datetime import datetime
from PIL import Image
from flask import Flask, render_template, send_file
import requests
class rBytesIO(BytesIO):
def close(self, really=False):
if really:
super.close()
app = Flask("Weather Info")
tstamp_fmt = '%... | StarcoderdataPython |
212481 | """Compile Qt resource files, UI files and translations in setup.py
Can be used with PyQt4, PyQt5, PySide and PySide2. Usage of Qt bindings
wrappers like Qt.py or QtPy is also supported.
"""
import pathlib, shutil, re, subprocess
from distutils import log
import setuptools
class build_qt(setuptools.Command):
d... | StarcoderdataPython |
6622009 | <gh_stars>1-10
class GeoTIFF:
"""
GeoTIFF constructor: create class from a path to the GeoTIFF file
Parameters
----------
path_to_file : str
"""
def __init__(self, path_to_file: str):
from functions import get_gdal_info
from os.path import abspath
self.path = abspath... | StarcoderdataPython |
3320957 | <filename>src/forms.py
# -*- coding: utf-8 -*-
"""
Application forms
"""
from flask import redirect, url_for
from flask_wtf import FlaskForm
from wtforms.validators import Required, Length, EqualTo, Email
from wtforms import (
StringField, IntegerField, FileField, DateField, SelectField, HiddenField, PasswordField)... | StarcoderdataPython |
6684693 | <filename>python/language/performance/pandas_obj_to_float.py
# import libraries
import operator
from itertools import islice
from timeit import timeit
from itertools import chain
import tkinter
import pandas as pd
import matplotlib.pyplot as plt
# function 1
def fun1(l):
df = pd.DataFrame(l)
print(len(df))
... | StarcoderdataPython |
3258602 | # Generated by Django 3.1.7 on 2021-04-05 20:22
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('judge', '0003_auto_20210405_2015'),
]
operations = [
migrations.RenameField(
model_name='profile',
old_name='course',
... | StarcoderdataPython |
4943022 | """
Referral urgency related API endpoints.
"""
from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated
from ..models import ReferralUrgency
from ..serializers import ReferralUrgencySerializer
from .permissions import NotAllowed
class UrgencyViewSet(viewsets.ModelViewSet):
"""
... | StarcoderdataPython |
3394007 | <gh_stars>0
from logs import logDecorator as lD
import json, os, struct
import numpy as np
import matplotlib.pyplot as plt
config = json.load(open('../config/config.json'))
logBase = config['logging']['logBase'] + '.modules.mnistConvert.mnistConvert'
@lD.log(logBase + '.readLabel')
def readLabel(logger, fileName):... | StarcoderdataPython |
3438967 | def penultimate(a: list):
return a[-2] if len(a) > 1 else None | StarcoderdataPython |
3591516 | <gh_stars>1-10
from copy import copy
from django import template
from django.template import loader
from django.core.exceptions import ImproperlyConfigured
from .models import ContentBlock, Container
class ContainerRenderer(object):
def __init__(self, container, context, extra_context=None):
if not con... | StarcoderdataPython |
6656050 | # -*- coding: utf8 -*-
''' Файл с общими установками, распространяется с дистрибутивом
Значения по умолчанию, здесь ничего не меняем, если хотим поменять меняем в mbplugin.ini
подробное описание см в readme.md
'''
import os, sys, re
UNIT = {'TB': 1073741824, 'ТБ': 1073741824, 'TByte': 1073741824, 'TBYTE': 1073741... | StarcoderdataPython |
8076008 | <reponame>ghbrown/taylor
import copy
import itertools
import numpy as np
def implemented_rule_names():
"""
returns all implemented rules (all keys of rule dictionary)
as an iterable of strings
"""
return rule_dict().keys()
def rule_selector(rule_name):
"""
returns function pointer co... | StarcoderdataPython |
6551838 | <gh_stars>1-10
from .penn_fudan_dataset import *
| StarcoderdataPython |
1910447 | <filename>mysite/lms/tests.py
import json
import datetime
from django.utils import timezone
from django.contrib.auth.models import User
from django.core.management import call_command
from django.core.urlresolvers import reverse
from django.test import TestCase
from mock import patch, Mock
from chat.models import Cha... | StarcoderdataPython |
6495216 | <reponame>TomArcherMsft/docs-tools
import requests
import os
import subprocess
from pprint import pprint
# Clear the screen (works on Windows and Linux/macOS)
os.system('cls' if os.name == 'nt' else 'clear')
githubToken = os.getenv('GITHUB_TOKEN')
params = { "state": "open"}
headers = {'Authorization': f'token {githu... | StarcoderdataPython |
1711798 | <gh_stars>0
from ._utils import *
from .dist_utills import *
from .helpfuns import *
from .metrics import *
from .system_def import *
from .launch import *
from .transformers_utils import *
from .transformers import *
from .wtst import *
__all__ = [k for k in globals().keys() if not k.startswith("_")] | StarcoderdataPython |
3505889 | <filename>device_connector.py
# <NAME>
# August 4, 2016
#
# Device class to handle selecting the correct device
from netmiko import ConnectHandler
from netmiko import FileTransfer
from sentry_pdu import SentryPdu
class device_connector:
device_type = ''
raw_ip = ''
ip = ''
... | StarcoderdataPython |
3401512 | from setuptools import setup
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name='curieutil',
version='0.0.5',
description='Python Library to translate CURIEs to IRIs and vice versa. Python version based on the Java Implementation: https://github.com/prefixcommons/curie-util an... | StarcoderdataPython |
4967260 | import pytest
from .merge_ranges import merge_ranges
@pytest.mark.parametrize(
"meetings, merged_meetings",
[
[[(1, 3), (2, 4)], [(1, 4)]],
[[(5, 6), (6, 8)], [(5, 8)]],
[[(1, 8), (2, 5)], [(1, 8)]],
[[(1, 3), (4, 8)], [(1, 3), (4, 8)]],
[[(1, 4), (2, 5), (5, 8)], [(1,... | StarcoderdataPython |
8003809 | from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import pickle
import plotly.graph_objs as go
from geopy import Nominatim
from Doc2Vec_Evaluation import get_most_similar_tokens
from app import app
from components import Header, Table... | StarcoderdataPython |
4925824 | from antlr4.error.ErrorListener import ErrorListener
class TnsErrorListenerException(ErrorListener):
def syntaxError(self, recognizer, offendingSymbol, line, column, msg, e):
raise Exception("Syntax error: line " + str(line) + ":" + str(column) + " " + msg)
| StarcoderdataPython |
275633 |
import re
import os
from shlex import quote
from ..compiler import compiler
from ..cmd import Cmd, LongOpt
# for support glob in file parameters
class ShellPath(object):
__sots__ = '_path'
def __init__(self, path):
self._path = path
@compiler.when(ShellPath)
def compile_shell_path(compiler, cmd, ... | StarcoderdataPython |
5175730 | <gh_stars>1-10
from .icarl import icarl_accuracy_measure, icarl_cifar100_augment_data
| StarcoderdataPython |
3446083 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Gene processing.
:Author: <NAME> <<EMAIL>>
:Date: 2018-01-22
:Copyright: 2018, <NAME>
:License: CC BY-SA
"""
import os
import re
import subprocess
import pandas as pd
import pysam
class Error(Exception):
"""Base class for exceptions in this module."""
pa... | StarcoderdataPython |
9641916 | from django.contrib import admin
from django.forms import ModelForm, ValidationError
from django.utils.translation import ugettext as _
from .models import Student, Group, Journal, Exam, LogEntry
from .models.exam import ExamResult
class StudentFormAdmin(ModelForm):
def clean_student_group(self):
"""Chec... | StarcoderdataPython |
3223832 | <filename>python_code/vnev/Lib/site-packages/jdcloud_sdk/services/cdn/apis/SetReferRequest.py
# coding=utf8
# Copyright 2018 JDCLOUD.COM
#
# 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 |
303139 | <filename>test_inconsistentstations.py
# Copyright (C) 2018 <NAME>
#
# SPDX-License-Identifier: MIT
"""Unit test for the stationdata module"""
import datetime
from xmlrpc.client import boolean
from floodsystem.datafetcher import fetch_measure_levels
from floodsystem.stationdata import build_station_list
from floods... | StarcoderdataPython |
12854332 | <filename>task3/task3.py
from PIL import Image
import numpy as np
# Works when launched from terminal
# noinspection PyUnresolvedReferences
from k_means import k_means
input_image_file = 'lena.jpg'
output_image_prefix = 'out_lena'
n_clusters = [2, 3, 5]
max_iterations = 100
launch_count = 3
def main():
# Read i... | StarcoderdataPython |
6446720 |
class Solution:
def isPalindrome(self, s: str) -> bool:
n = len(s)
l, r = 0, n - 1
while l < r:
# 是非字母的
while l < r and not s[l].isalnum():
l += 1
while l < r and not s[r].isalnum():
r -= 1
# 字母的
if... | StarcoderdataPython |
251824 | import secrets
from functools import lru_cache
from pydantic import BaseSettings
from app.schemas.settings import Environment
class Settings(BaseSettings):
environment: Environment = "development"
sql_alchemy_database_url: str = "sqlite:///././sql_database.db"
token_generator_secret_key: str = secrets.t... | StarcoderdataPython |
1862887 | <filename>schema.py
from collections import namedtuple
import ndjson
import os
Address = namedtuple(
"Address",
[
"street1",
"street2",
"city",
"state",
"zip",
],
defaults=[""] * 5,
)
ParentOrganization = namedtuple(
"ParentOrganization",
[
"id",... | StarcoderdataPython |
1711320 | #!/usr/local/bin/python3
"""This program asks a user to guess a number up to 5 attempts."""
numguesses = 0
secret = 12
guess = 0
while numguesses < 5 and guess != secret:
guess = (int(input("Guess a number:")))
if guess < secret:
print("Guess higher")
elif guess > secret:
print("Guess lowe... | StarcoderdataPython |
8112134 | from acrossword import Ranker
class SemanticList(list):
"""A list with an additional method called reorder that takes:
- query: a string to rank the list's contents by"""
def set_maximum(self, maximum: int) -> None:
self.maximum = maximum
def set_delimiter(self, delimiter: str) -> None:
... | StarcoderdataPython |
3467654 | import brownie
from brownie import Vault
import pytest
def test_set_compounder_compounder_set(vault, ss_compounder, owner):
with brownie.reverts():
vault.setCompounder(ss_compounder, {'from': owner})
def test_set_compounder_not_owner(alice, vault, ss_compounder):
with brownie.reverts():
vaul... | StarcoderdataPython |
5080157 | from setuptools import setup
with open("README.md", "r") as fh:
long_description = fh.read()
INSTALL_REQUIRES = [
]
def doSetup(install_requires):
setup(
name='docstring_expander',
version='0.23',
author='<NAME>',
author_email='<EMAIL>',
url='https://github.com/joseph-hellerst... | StarcoderdataPython |
3289207 | <filename>tests/test_sox.py
import subprocess
import pytest
from training_speech import sox
@pytest.mark.parametrize('kwargs, expected_call', [
(dict(path_to_file='/path/to/foo.mp3'), 'play -q /path/to/foo.mp3'),
(dict(path_to_file='/path/to/foo.mp3', speed=1.2), 'play -q /path/to/foo.mp3 tempo 1.2'),
])
de... | StarcoderdataPython |
102198 | def main():
"""
Main command-line execution loop.
"""
print "hello!"
| StarcoderdataPython |
14334 | # Copyright (c) 2021 NVIDIA Corporation. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | StarcoderdataPython |
4958806 | import errno
import sys
import time
from datetime import datetime
from os import path, mkdir
from urllib.error import URLError
from mta_data_util import download_raw_feed, print_with_time, DEFAULT_POLL_FREQUENCY, FEED_IDS
def poll_and_store(output_dir):
with open('api.key', 'r') as f:
api_key = f.read()
... | StarcoderdataPython |
347191 | import systemd.daemon
import glob
import os
import re
import subprocess
import sys
BASEDIR = "/usr/local/cluster-prep/"
def log(msg):
print("[cluster-prep-service]: "+msg)
def determine_hostname(update_hostname=False):
if 'INSTANCE_ROLE' in os.environ:
role = os.environ['INSTANCE_ROLE']
else:
... | StarcoderdataPython |
342552 | <filename>terzani/utils/types.py
class IIIF_Photo(object):
def __init__(self, iiif, country):
self.iiif = iiif
self.country = country
def get_photo_link(self):
return self.iiif["images"][0]["resource"]["@id"]
| StarcoderdataPython |
11376520 | if __name__ == "__main__":
def solution(s, k):
if len(s) < k:
return "false"
lookup = {}
for i in range(len(s)):
if s[i] not in lookup:
lookup[s[i]] = 1
else:
lookup[s[i]] += 1
number = 0
f... | StarcoderdataPython |
6440934 | <filename>test/test_svm_classical.py
# -*- coding: utf-8 -*-
# Copyright 2018 IBM.
#
# 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
#
# Unle... | StarcoderdataPython |
1801788 | """ Comparison Analysis FinBrain Model """
__docformat__ = "numpy"
import logging
from typing import List
import pandas as pd
import requests
from gamestonk_terminal.decorators import log_start_end
from gamestonk_terminal.rich_config import console
logger = logging.getLogger(__name__)
@log_start_end(log=logger)
d... | StarcoderdataPython |
11208440 | <filename>tests/fire_groups/test_cone_of_fire.py
from ps2_analysis.fire_groups.cone_of_fire import ConeOfFire
def test_min_cof_angle():
cof: ConeOfFire = ConeOfFire(
max_angle=2.0,
min_angle=1.0,
bloom=0.1,
recovery_rate=10.0,
recovery_delay=100,
multiplier=2.0,
... | StarcoderdataPython |
3463506 | # Last update Dec,13, 2021 by JJ
import sys
import os
import screeninfo
from PIL import Image, ImageTk # Pillow module
import zipfile
if sys.version_info[0] == 2: # not tested yet
import Tkinter as tk # Tkinter -> tkinter in Python3, Tkinter in python2
from BytesIO import BytesIO # import StringIO #Python2
... | StarcoderdataPython |
318261 | import pygame
import math
from pygame.locals import *
from OpenGL.GLU import *
pygame.init()
def KeyboardEvent(moveArray, angle, keymap):
dx,dy,dz = 0,0,0
lookX, lookY, lookZ, cameraX, cameraY, cameraZ = 1, 1, 1, 0, 0, 0
mouseX = pygame.mouse.get_pos()[0]
mouseY = pygame.mouse.get_pos()[1]
oldMouseX... | StarcoderdataPython |
6692725 | <reponame>nautxx/crypto_ticker
config = {
"api_key":"",
"link":"https://min-api.cryptocompare.com/data/pricemultifull?fsyms={0}&tsyms={1}",
"frequency": 300
} | StarcoderdataPython |
6615272 | <reponame>VelionaVollerei/PMX-VMD-Scripting-Tools<filename>python/file_recompress_images.py<gh_stars>0
_SCRIPT_VERSION = "Script version: Nuthouse01 - 6/10/2021 - v6.00"
# This code is free to use and re-distribute, but I cannot be held responsible for damages that it may or may not cause.
#####################
# fir... | StarcoderdataPython |
3435301 | <reponame>tomm1e/engine
#!/usr/bin/env python
#
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
""" Interpolates test suite information into a cml file.
"""
from argparse import ArgumentParser
import sys
... | StarcoderdataPython |
11290237 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import flask
from simplekv.memory import DictStore
from kvsession import KVSessionExtension
store = DictStore()
app = flask.Flask(__name__)
app.config['SECRET_KEY'] = 'topsecret'
KVSessionExtension(store, app)
@app.route('/')
def index():
flask.session.regenerate(... | StarcoderdataPython |
3466815 | <reponame>bluehenry/python.best.practices<gh_stars>0
# -*- coding: utf-8 -*-
""" JSON Demo """
import pandas as pd
import os
import json
# Example usage of from_records method
records = [("Espresso", "5$"),
("Flat White", "10$")]
pd.DataFrame.from_records(records)
pd.DataFrame.from_records(records,
... | StarcoderdataPython |
4878583 | <reponame>vinisantos7/PythonExercicios
print("-+"*10)
print("Conersor de Bases")
print("-+"*10)
num = int(input("Digite um número inteiro: "))
print("""Escolha uma das opções para conversão:
[1] Converter para BINÁRIO
[2] Converter para OCTAL
[3] CONVERTER PARA HEXADECIMAL""")
opção = int(input("Escolha sua opção: "))... | StarcoderdataPython |
5063749 | from collections import defaultdict
from statistics import mean
from record_helper import *
import vcfpy
def generate_sv_record(records, comparison_result, sample_names):
"""
This method generates a single SV record after a call has been made over a set of input records
:param records: the input records i... | StarcoderdataPython |
11398765 | <filename>src/pattern-searching/boj_10250.py
def main():
H, W, N = input().split(' ')
H = int(H)
W = int(W)
N = int(N)
floor = H if N % H == 0 else N % H
room = (N - 1) // H + 1
print(floor * 100 + room)
if __name__ == '__main__':
[main() for _ in range(int(input()))]
| StarcoderdataPython |
1969177 | #!/usr/bin/env python
"""
* @file test.py
*
* @author <NAME>
* @date Created: Fall 2021
"""
import sys
import getopt
import http.client
import urllib
import json
from datetime import date
from time import mktime
def usage():
print('dbFill.py -u <baseurl> -p <port> -n <numUsers> -t <numTasks>')
def getUsers(... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.