id stringlengths 2 8 | text stringlengths 16 264k | dataset_id stringclasses 1
value |
|---|---|---|
3444175 | # https://www.youtube.com/watch?v=HGOBQPFzWKo&list=RDCMUC8butISFwT-Wl7EV0hUK0BQ&start_radio=1&t=181s
# Intermediate Python Programming Course (freecodecamp.org)
# Logging
import logging # 5 diff log levels
# to adjust default display behaviour of log msgs...
logging.basicConfig(level=... | StarcoderdataPython |
11270583 | <reponame>admariner/polyaxon<gh_stars>0
#!/usr/bin/python
#
# Copyright 2018-2021 Polyaxon, Inc.
#
# 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/LICENS... | StarcoderdataPython |
6448224 | from django.db import models
from cloudinary.models import CloudinaryField
# Create your models here.
class Job(models.Model):
types = (
("web_apps", "web_apps"), ("api", "api"),
("upcoming", "upcoming")
)
job_name = models.CharField(max_length=100)
job_type = models.CharField(
... | StarcoderdataPython |
1693463 | # -*- coding: utf-8 -*-
"""
FUZZY REGULATOR
1. Create an instance of the balanced arm
2. Set initial conditions
3. Prepare a fuzzy regulator
4. Begin iterating:
a)
5. Visualize results
note: all values are scaled in standard metric units
note: input params: angle, angular_velocity
note: output... | StarcoderdataPython |
227006 | <gh_stars>1-10
import requests
from dataclasses import dataclass
from blockfrost.utils import object_request_wrapper, object_list_request_wrapper
@dataclass
class AddressResponse:
@dataclass
class Amount:
unit: str
quantity: str
address: str
amount: [Amount]
stake_address: str
... | StarcoderdataPython |
6599176 | <gh_stars>0
import sqlite3
DB_FILEPATH = 'rpg_db.sqlite3'
connection = sqlite3.connect('rpg_db.sqlite3')
print("CONNECTION:", connection)
cursor = connection.cursor()
print("CURSOR", cursor)
query1 = """
SELECT count (*)
from charactercreator_character
"""
result1 = cursor.execute(query1).fetchall()
print("RESULT 1",... | StarcoderdataPython |
6700008 | <filename>muffin_rest/__init__.py
"""REST helpers for Muffin Framework."""
__version__ = "4.0.2"
__project__ = "muffin-rest"
__author__ = "<NAME> <<EMAIL>>"
__license__ = "MIT"
# Default query params
LIMIT_PARAM = 'limit'
OFFSET_PARAM = 'offset'
from .api import API # noqa
from .handler import RESTHa... | StarcoderdataPython |
3518479 | <reponame>nathanielwarner/seatsio-python
from tests.seatsioClientTest import SeatsioClientTest
from tests.util.asserts import assert_that
class RegenerateSubaccountDesignerKeyTest(SeatsioClientTest):
def test(self):
subaccount = self.client.subaccounts.create()
self.client.subaccounts.regenerate... | StarcoderdataPython |
5155071 | <filename>measurements.py<gh_stars>1-10
from operator import attrgetter
import statistics
from measure import Note
# contains measurement functions that only operate on a single measure
class SingleMeasurements:
# calculate the percentage of the measure that are rests
def percent_vacant(measure):
return float(s... | StarcoderdataPython |
1627692 | <gh_stars>0
from pydantic import BaseModel
class Favorite(BaseModel):
"""Favorite from dynamoDB"""
indexKey: str
PK: str
SK: str
createdAt: str
class ReqFavorite(BaseModel):
"""Favorite request body"""
user: str
video: str
| StarcoderdataPython |
6406904 | <gh_stars>0
import os
import sqlite3
# DB_FILEPATH = os.path.join(os.path_dirname(__file__), "..", "data", "chinook.db")
conn = sqlite3.connect('rpg_db.sqlite3')
curs = conn.cursor()
# query = 'SELECT COUNT(*) FROM armory_item;'
# curs.execute(query)
# results = curs.execute(query).fetchall()
# breakpoint()
... | StarcoderdataPython |
228033 | <gh_stars>0
from selenium import webdriver
from bs4 import BeautifulSoup
#import urllib 使用再拿掉
import time
import random
import selenium.webdriver.support.ui as ui
import time
import json
import re
def investigate_by_xpath(driver, time_wait, object, message):
# input : 等待時間, 確認目標的xpath內容, 成功回報訊息
# target : 因驗證帳密會有... | StarcoderdataPython |
12821965 | from discord_ritoman.lol.stats.match_stat import LoLMatchStat
from pkgutil import iter_modules
from pathlib import Path
from importlib import import_module
__all__ = []
# iterate through the modules in the current package
package_dir = str(Path(__file__).resolve().parent)
for (_, module_name, _) in iter_modules([pack... | StarcoderdataPython |
3449136 | <filename>tests/hdx/freshness/test_aging.py<gh_stars>1-10
"""
Unit tests for the aging code.
"""
import os
from datetime import datetime, timedelta
from os.path import join
import pytest
from hdx.database import Database
from hdx.freshness.datafreshness import DataFreshness
class TestAging:
@pytest.fixture(sco... | StarcoderdataPython |
3549412 | <filename>modeling/dynamics/bullet/bdmodel.py<gh_stars>0
import copy
import math
import modeling.geometricmodel as gm
import modeling.dynamics.bullet.bdbody as bdb
class BDModel(object):
"""
load an object as a bullet dynamics model
author: weiwei
date: 20190627
"""
def __init__(self, objinit... | StarcoderdataPython |
196640 | <reponame>flying-sheep/goatools<gh_stars>100-1000
"""Test the loading of the optional GO term fields."""
# https://owlcollab.github.io/oboformat/doc/GO.format.obo-1_4.html
__copyright__ = "Copyright (C) 2010-2018, <NAME>, <NAME>, All rights reserved."
__author__ = "<NAME>"
import os
import sys
import re
import timei... | StarcoderdataPython |
11383409 | """base
Revision ID: 3895aa356acf
Revises:
Create Date: 2019-05-19 11:34:12.741305
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic... | StarcoderdataPython |
9766608 | k, a = int(input()), list(map(int,input().split()))
s = set(a);
print(((sum(s)*k)-(sum(a)))//(k-1))
| StarcoderdataPython |
5121578 | from os import chdir, environ, path, getcwd
from shutil import rmtree
from inspect import getfile
from importlib import reload
from _pytest.tmpdir import TempPathFactory
from pytest_mock import MockerFixture
from .helpers import onerror
CWD = getcwd()
def test___import__(tmp_path_factory: TempPathFactory, mocker: ... | StarcoderdataPython |
8107513 | <reponame>skunkworksdev/Ifes_Algoritmo
a = int(input('Digite 1 para sim e 2 para não: '))
if(a == 1):
print('Você quer namorar comigo, sou gato!')
elif(a == 2): # simplesmente está confirmando
print('Você não quer namorar comigo, sou ridículo!')
else:
print('Você não quer ninguém!\n Evite piadas de tios(as) quand... | StarcoderdataPython |
6544080 | ##============================ ea_config_ex_3.py ================================
# Some of the input parameters and options in order to select the settings of the
# evolutionary algorithm are given here for the minimization of f1(x) and f2(x)
# of the ZDT 1 using NSGA-II (Genetic Algorithms).
EA_type = 'GA'
pop_size... | StarcoderdataPython |
12820751 | <gh_stars>0
# Author: <NAME>
# Class representing an ordered set of operations on a given data input
import logging
import json
from json import JSONDecodeError
from abc import ABC, abstractmethod
import ast
from google.protobuf import json_format
from ta3ta2_api import core_pb2, pipeline_pb2, problem_pb2, value_p... | StarcoderdataPython |
252608 | import os
import numpy as np
import pandas as pd
import plotly.graph_objects as go
from skimage import io
from sklearn import metrics
from sklearn.dummy import DummyClassifier
import berrytemplates as bt
from berrysort import TestDataLoader
# Der Pfad zu den Trainingsdaten
path = "BlueberryData/TrainingData/"
def ... | StarcoderdataPython |
246790 | <reponame>Blackweather/rpg-station
import pygame
from os import system
pygame.init()
j = pygame.joystick.Joystick(0)
j.init()
try:
while True:
for event in pygame.event.get():
if event.type == pygame.JOYBUTTONDOWN:
system('clear')
print("Pressed button " + str(e... | StarcoderdataPython |
88357 | import argparse
import time
import torch
from kruskals import kruskals_pytorch, kruskals_pytorch_batched
from kruskals import kruskals_cpp_pytorch, kruskals_cpp_pytorch2
parser = argparse.ArgumentParser()
parser.add_argument("--n", type=int, default=30, help="Number of nodes.")
parser.add_argument("--batch_size", typ... | StarcoderdataPython |
6454389 | # Generated by Django 2.1 on 2021-01-11 12:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0012_auto_20210111_1133'),
]
operations = [
migrations.AddField(
model_name='collaborater',
name='field',
... | StarcoderdataPython |
1880764 | <filename>azplugins/test-py/test_mpcd_reverse_perturbation.py
# Copyright (c) 2018-2020, <NAME>
# Copyright (c) 2021, Auburn University
# This file is part of the azplugins project, released under the Modified BSD License.
import hoomd
from hoomd import md
from hoomd import mpcd
hoomd.context.initialize()
try:
fr... | StarcoderdataPython |
1813443 | import scrapy
class CRateSpider(scrapy.Spider):
name = 'c_rate'
allowed_domains = ['https://www.bb.org.bd/econdata/exchangerate.php']
start_urls = ['http://https://www.bb.org.bd/econdata/exchangerate.php/']
def parse(self, response):
pass
| StarcoderdataPython |
11302702 | from django import forms
class LoginForm(forms.Form):
"""Login form implementation"""
username = forms.CharField(
max_length = 120,
required = False,
widget = forms.TextInput(
attrs = {
'placeholder':'Enter Your Email Address'
}
)
)
... | StarcoderdataPython |
1754462 | import atexit
import logging
from logging.config import dictConfig
import os
import sys
import time
import click
import docker
from .bitcoind import (BitcoindDockerController,
fetch_wallet_addresses_for_mining)
from .helpers import load_jsons, which
from .server import DATA_FOLDER, create_app,... | StarcoderdataPython |
4902126 | import unittest
import sys, os
sys.path.append(os.pardir)
from common.np import *
from common.util import im2col, col2im, clip_grads, preprocess, \
convert_one_hot, create_co_matrix, cos_similarity, most_similar, ppmi, \
create_contexts_target
class UtilTest(unittest.TestCase):
def test_im2col_transforms(... | StarcoderdataPython |
3433584 | <gh_stars>0
#!/usr/bin/python
'''The MIT License (MIT)
Copyright (c) 2017 <NAME>(<EMAIL>)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the righ... | StarcoderdataPython |
4909615 | # -*- coding: utf-8 -*-
"""provides sequencing fetching from NCBI and Ensembl
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import os
import re
import bioutils.seqfetcher
from ..exceptions import HGVSDataNotAvailableError
logger = logging.getLogger(__name__)... | StarcoderdataPython |
9649675 | <reponame>RemainAplomb/OS-Simulator-using-Python-Tkinter
"""
Group Members:
- Abaño, <NAME>
- <NAME>
- Dibansa, Rahmani
- Palattao, <NAME>
Program Description:
- This is a program which mimics and represents the Priority Process Management.
Program... | StarcoderdataPython |
17821 | #!/usr/bin/env python
import rospy
import rosbag
import os
import sys
import textwrap
import yaml
lidarmsg=None
################# read the lidar msg from yaml file and return ##############
def readlidardummy():
global lidarmsg
if lidarmsg==None:
lidarmsg= doreadlidar()
return lidarmsg
def doreadlidar():... | StarcoderdataPython |
111285 | import os
os.environ["CUDA_VISIBLE_DEVICES"]="-1"
import tensorflow as tf
from tensorflow.python.client import timeline
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data",one_hot=True)
x = tf.placeholder(tf.float32, [None, 784])
w = tf.Variable(tf.zeros([784, 1... | StarcoderdataPython |
8120733 | import unittest
import pandas as pd
from sklearn.linear_model import LogisticRegression, SGDClassifier
from sklearn.pipeline import Pipeline
import numpy as np
from sklearn.utils.estimator_checks import check_estimator
from ITMO_FS.embedded import *
from ITMO_FS.utils import weight_func
np.random.seed(42)
class T... | StarcoderdataPython |
6626201 | <filename>tests/integration/test_dynamodb.py
# -*- coding: utf-8 -*-
import unittest
import json
from localstack.services.dynamodbstreams.dynamodbstreams_api import get_kinesis_stream_name
from localstack.utils import testutil
from localstack.utils.aws import aws_stack
from localstack.utils.aws.aws_models import Kine... | StarcoderdataPython |
50 | <filename>paccmann_chemistry/utils/hyperparams.py
"""Model Parameters Module."""
import torch.optim as optim
from .search import SamplingSearch, GreedySearch, BeamSearch
SEARCH_FACTORY = {
'sampling': SamplingSearch,
'greedy': GreedySearch,
'beam': BeamSearch,
}
OPTIMIZER_FACTORY = {
'adadelta': optim... | StarcoderdataPython |
1728851 | <reponame>sunsyw/utils
# a = [x for x in range(10)]
# print(a)
#
# b = (x for x in range(10))
# print(b)
# for b1 in b:
# print(b1)
def generator():
a, b = 0, 1
for i in range(10):
yield b
a, b = b, a+b
if __name__ == '__main__':
print(generator())
a = generator()
print(next(... | StarcoderdataPython |
1658159 | <gh_stars>1-10
from dateutil.parser import parse as timeparser
import yippi
class Set(object):
def __init__(self, object):
self.object = object.find("post-set")
self._description = None
self._id = None
self._name = None
self._post_count = None
self._public = None
... | StarcoderdataPython |
8158164 | """
The sampler module uses the distance data calculated in "calc_class_distance.py" to sample synthetic data for classes
1 and 2 and samples the under represented classes by copying them in order to have a even class distribution.
"""
import configparser
from dlpipe.data_reader.mongodb import MongoDBConnect
from dlpip... | StarcoderdataPython |
111857 | import numpy as np
from sbrfuzzy import *
entrada = open("dados.txt","a")
v = np.arange(0,300.5,0.5)
v1 = variavellinguistica("População",np.arange(0,300.5,0.5))
v1.adicionar("muito-baixa","trapezoidal",[0,0,25,45])
v1.adicionar("baixa","triangular",[30,50,70])
v1.adicionar("media","triangular",[55,75,110])
v1.adicio... | StarcoderdataPython |
9681894 | """
"""
# Built-in
# Libs
from tqdm import tqdm
# Pytorch
import torch
from torch import nn
from torch.nn import functional as F
# Own modules
from mrs_utils import misc_utils
from network.backbones import encoders
from network import base_model, emau, ocr
class PSPDecoder(nn.Module):
"""
This module de... | StarcoderdataPython |
3475320 | <gh_stars>0
# Generated by Django 3.0.5 on 2020-05-11 10:21
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('cookbook', '... | StarcoderdataPython |
205416 | """
Given a m * n matrix of ones and zeros, return how many square submatrices have all ones.
Example 1:
Input: matrix =
[
[0,1,1,1],
[1,1,1,1],
[0,1,1,1]
]
Output: 15
Explanation:
There are 10 squares of side 1.
There are 4 squares of side 2.
There is 1 square of side 3.
Total number of squares = 10 + 4 +... | StarcoderdataPython |
6518475 | from typing import List, Optional
from eth_utils import to_checksum_address
from ledgereth.comms import (
Dongle,
decode_response_address,
dongle_send_data,
init_dongle,
)
from ledgereth.constants import (
DEFAULT_ACCOUNTS_FETCH,
LEGACY_ACCOUNTS,
MAX_ACCOUNTS_FETCH,
)
from ledgereth.object... | StarcoderdataPython |
84325 | <gh_stars>0
from apps.Util_apps.LogProject import logging
import apps.Util_apps.Util as Util
def funcion_si_respuesta_es_correcta(response_json):
logging.info(response_json)
def funcion_si_respuesta_no_es_correcta(url):
logging.error("No se ha podido realizar la peticion a la url {}".format(url))
if __nam... | StarcoderdataPython |
12816860 | from routeCalculator import calculateBestRoute
print(calculateBestRoute([(1, 2), (2, 3), (7, 1)]))
| StarcoderdataPython |
244284 |
import unittest
import math
from .. import Point, Triangle, Segment, Circle
from ..exceptions import *
class TriangleTestCase(unittest.TestCase):
def assertAlmostEqual(self, test_value, known_value):
self.assertTrue(
round(
float(test_value),
10) == round(
... | StarcoderdataPython |
12853786 | import yahoo_fin.stock_info as si
import pandas as pd
import os
def download_data(etfs, time_frames):
# 获取数据并存储
if not os.path.exists('./Data'):
os.makedirs('./Data')
if not os.path.exists('./Data/rawdata'):
os.makedirs('./Data/rawdata')
for ticker in etfs:
for interval in time... | StarcoderdataPython |
3477117 | import torch.nn as nn
import torch.nn.functional as F
import torch
##############################
# U-NET
##############################
class UNetDown(nn.Module):
def __init__(self, in_size, out_size, normalize=True, dropout=0.0):
super(UNetDown, self).__init__()
model = [nn.Conv2d(in_... | StarcoderdataPython |
4854458 | # -----------------------------------------------------------------------------
# Matplotlib cheat sheet
# Released under the BSD License
# -----------------------------------------------------------------------------
# Scripts to generate all the basic plots
import numpy as np
import matplotlib as mpl
import matplot... | StarcoderdataPython |
9670284 | <filename>tricks and tips/shutting down a computer.py
import os
os.system('shutdown -s') | StarcoderdataPython |
11220845 | # required to make Python treat the directories as containing packages; | StarcoderdataPython |
235816 | <reponame>pedrolp85/pydevice
from sqlalchemy import Column, ForeignKey, Integer, String
from .database import Base
class Device(Base):
__tablename__ = "device"
id = Column(Integer, primary_key=True)
model = Column(String)
mgmt_interface_id = Column(Integer, ForeignKey("l3interfaces.id"))
manufac... | StarcoderdataPython |
1857230 | <reponame>Fenghuapiao/PyLeetcode
class Solution(object):
def findMinStep(self, board, hand):
"""
:type board: str
:type hand: str
:rtype: int
"""
def dfs(line, balls, visited):
line = reduceLine(line)
if (line, balls) in visited:
... | StarcoderdataPython |
3479623 | <filename>cpf/python/training/thread_pool.py
import time
import concurrent.futures
def func1():
while True:
print("func1")
time.sleep(1)
def func2():
while True:
print("func2")
time.sleep(1)
if __name__ == "__main__":
executor = concurrent.futures.ThreadPoolExecutor(max_workers=2)
executor.submit(func... | StarcoderdataPython |
3433303 | <filename>appskel/signup/modname/utils.py
# coding: utf-8
#
$license
import OpenSSL
import cyclone.escape
import cyclone.web
import httplib
import re
import uuid
from twisted.internet import defer
from $modname.storage import DatabaseMixin
class TemplateFields(dict):
"""Helper class to make sure our
te... | StarcoderdataPython |
6623503 | <filename>active_learning_lab/data/embeddings.py
import torch
import numpy as np
from pathlib import Path
def get_embedding_matrix(name, vocab, data_dir='.data/'):
from gensim.models.word2vec import Word2VecKeyedVectors
embedding_dir = Path(data_dir).joinpath('embeddings')
embedding_dir.mkdir(parents=Tr... | StarcoderdataPython |
8035103 | #! /usr/bin/env python
import os.path
from collections import defaultdict
single_test_input = [
"acedgfb cdfbe gcdfa fbcad dab cefabd cdfgeb eafb cagedb ab | cdfeb fcadb cdfeb cdbaf"
]
test_input = [
"be cfbegad cbdgef fgaecd cgeb fdcge agebfd fecdb fabcd edb | fdgacbe cefdb cefbgd gcbe",
"edbfga begcd cb... | StarcoderdataPython |
1727958 | from soundrts.world import World
from soundrts.worldclient import DummyClient
from soundrts.worldplayercomputer import Computer
from soundrts.worldresource import Deposit
from soundrts.worldroom import Square
class Deposit(Deposit): # type: ignore
def __init__(self, type_):
self.resource_type = type_
c... | StarcoderdataPython |
8023486 | <gh_stars>10-100
# -*- coding: utf-8 -*-
"""Utility functions for running optimizers."""
import time
def float2str(x):
s = "{:.10e}".format(x)
mantissa, exponent = s.split("e")
return mantissa.rstrip("0") + "e" + exponent
def make_run_name(weight_decay, batch_size, num_epochs, learning_rate,
... | StarcoderdataPython |
3590028 | import numpy as np
import math
from numba import jit, cuda, prange
from pythonabm import cuda_magnitude
@cuda.jit
def jkr_forces_gpu(jkr_edges, delete_edges, locations, radii, jkr_forces, poisson, youngs, adhesion_const):
""" This just-in-time compiled CUDA kernel performs the actual
calculations for the... | StarcoderdataPython |
1954158 | <filename>tests/grids/test_rectilinear.py
#! /usr/bin/env python
import unittest
import numpy as np
from pymt.grids import Rectilinear, RectilinearPoints
from ..grids.test_utils import NumpyArrayMixIn
class TestRectilinearGrid(unittest.TestCase):
def assert_point_count(self, grid, point_count):
self.a... | StarcoderdataPython |
12823984 | from django.dispatch import Signal
from django.template.loader import select_template, TemplateDoesNotExist
from django.contrib.staticfiles import finders
from debug_toolbar.panels import DebugPanel
from widgy.models import Content
template_hierarchy_called = Signal(providing_args=['cls', 'kwargs', 'templates', 'use... | StarcoderdataPython |
4822508 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 0.5.0.5149 on 2015-07-06.
# 2015, SMART Health IT.
import os
import io
import unittest
import json
from . import observation
from .fhirdate import FHIRDate
class ObservationTests(unittest.TestCase):
def instantiate_from(self, filename):
... | StarcoderdataPython |
3218914 | <reponame>seukjung/sentry-custom
from __future__ import absolute_import
import mock
from sentry.testutils import TestCase
from sentry.utils.retries import TimedRetryPolicy, RetryException
class TimedRetryPolicyTestCase(TestCase):
def test_policy_success(self):
bomb = Exception('Boom!')
callable ... | StarcoderdataPython |
330643 | <filename>deeppulsarnet/model/model_output.py
import torch.nn as nn
from torch.nn.utils import weight_norm
from torch.nn import functional as F
import torch
from model.TemporalBlock import TemporalBlock
class OutputLayer(nn.Module):
def __init__(self, input_channels, intermediate, final_nonlin,
d... | StarcoderdataPython |
209839 | from time import sleep
for c in range(10, -1, -1):
sleep(1)
print(c)
print('Boom! Boom! Pow!')
| StarcoderdataPython |
6613513 | <reponame>robotlightsyou/pfb-resources<filename>sessions/003 session-numbers/exercises/cash_register_video.py
#! /usr/bin/env python3
'''
write a function that will ask for the
user for input which will be an amount
of money, then return the minimum
number of coins.
'''
user_coins = [25, 10, 5, 1]
# print return of ... | StarcoderdataPython |
3279231 | """
Functional tests for the web service using Selenium
"""
from sys import platform
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from django.test import LiveServerTestCase
from pyvirtualdisplay import Display
fr... | StarcoderdataPython |
5183632 | import errno
import os
import sys
from zmq.eventloop import ioloop
class RedirectorHandler(object):
def __init__(self, redirector, name, process, pipe):
self.redirector = redirector
self.name = name
self.process = process
self.pipe = pipe
def __call__(self, fd, events):
... | StarcoderdataPython |
8122226 | <filename>test/integration/test_env_vars.py
import os.path
import re
from six import assertRegex
from . import *
class TestEnvVars(IntegrationTest):
def __init__(self, *args, **kwargs):
IntegrationTest.__init__(self, 'env_vars', *args, **kwargs)
@skip_if_backend('msbuild')
def test_test(self):
... | StarcoderdataPython |
5029649 | <gh_stars>10-100
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('aldryn_people', '0012_auto_20150728_1114'),
]
operations = [
migrations.AddField(
model_name='p... | StarcoderdataPython |
1957649 | <reponame>radiome-flow/radiome
# -*- coding: utf-8 -*-
"""Unit test package for radiome."""
| StarcoderdataPython |
3325337 | <filename>t_9_classes/t_9_8_iterators/main.py<gh_stars>0
for element in [1, 2, 3]:
print(element)
for element in (1, 2, 3):
print(element)
for key in {'one': 1, 'two': 2}:
print(key)
for char in '123':
print(char)
for line in open("myfile.txt"):
print(line, end='')
fruits = {'1': 'apple', '2': 'lem... | StarcoderdataPython |
6543985 | <reponame>nkowdley/CarND-Behavioral-Cloning-P3<gh_stars>0
#!/usr/bin/env python
"""
A python script used for Term 1, Project 3 Behavioral Cloning
This script does data ingestion and training
"""
import csv
import cv2
import matplotlib.image as mpimg
import numpy as np
from sklearn.utils import shuffle
from sklearn.mo... | StarcoderdataPython |
4965159 | <reponame>GYosifov88/Python-Fundamentals
import re
text = input()
matches = re.finditer(r"\b(_{1})(?P<variable>[A-Za-z\d]+)\b", text)
variables_list = list()
for match in matches:
variable = match.group('variable')
variables_list.append(variable)
print(','.join(variables_list))
| StarcoderdataPython |
3278207 | <gh_stars>0
import json
import os
import sys
import time
import requests
folder = "wallets" # .json
page_num_path = folder + "/page_num.txt"
_timeout = 20
time_gap = 5
count_quick_response = 0
count_success_time = 0
def thread(wallet_name):
global _timeout, count_quick_response, time_gap, count_s... | StarcoderdataPython |
82481 | <filename>python/testData/intentions/PyInvertIfConditionIntentionTest/conditionAssignmentMultiple.py
def get_value():
return 1
<caret>if not (value := get_value()) or value <= 1:
print("Less or equal")
else:
print("Greater") | StarcoderdataPython |
9619191 | anos = int(input("Anos de Serviço: "))
valor_por_ano = float(input("Valor por ano: "))
bonus = anos * valor_por_ano
print("Bônus de R$ %5.2f" % bonus) | StarcoderdataPython |
5157806 | <filename>src/geocurrency/rates/permissions.py
"""
Permissions for Rate APIs
"""
from rest_framework import permissions
class RateObjectPermission(permissions.BasePermission):
"""
Permissions for /rates APIs
"""
def has_object_permission(self, request, view, obj):
"""
Limit modificati... | StarcoderdataPython |
4801808 | from sklearn import ensemble
#0.75091
MODELS = {
"randomforest": ensemble.RandomForestClassifier(n_estimators=200, n_jobs=-1, verbose=2),
"extratrees": ensemble.ExtraTreesClassifier(n_estimators=200, n_jobs=-1, verbose=2),
} | StarcoderdataPython |
6702905 | from oscar.apps.basket import config
class BasketConfig(config.BasketConfig):
name = 'forked_apps.basket'
| StarcoderdataPython |
5143306 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
from utopia import signals
from utopia.client import ProtocolClient
from utopia.plugins.handshake import HandshakePlugin
from utopia.plugins.protocol import ProtocolPlugin
from utopia.plugins.util import LogPlugin
from test.util import unique_identity
def test_unicode_pr... | StarcoderdataPython |
3288228 | <gh_stars>0
# -*- coding: utf-8 -*-
"""
Copyright (c) Microsoft Corporation.
Licensed under the MIT License.
"""
import os
from setuptools import setup
# Load version in dapr package.
version_info = {}
with open('dapr/version.py') as fp:
exec(fp.read(), version_info)
__version__ = version_info['__version__']
... | StarcoderdataPython |
1839775 | import hashlib
import traceback
from flask import Flask, request, make_response
from StockAnalysisSystem.core.config import Config
from StockAnalysisSystem.wechatservice.route import dispatch_wechat_message
app = Flask(__name__)
WECHAT_TOKEN = "xxxxxxx"
def load_config():
global WECHAT_TOKEN
config = Con... | StarcoderdataPython |
5118920 | <reponame>bram-rongen/contentful-management.py
from unittest import TestCase
from contentful_management.editor_interfaces_proxy import EditorInterfacesProxy
from .test_helper import CLIENT, PLAYGROUND_SPACE
class EditorInterfacesProxyTest(TestCase):
def test_editor_interfaces_proxy(self):
proxy = EditorIn... | StarcoderdataPython |
4849037 | <filename>src/loqet/file_utils.py
"""
Copyright (c) 2021, <NAME>
All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
"""
import os
import shutil
import time
from typing import Union
from loqet.loqet_configs import SAFE_MOD... | StarcoderdataPython |
326165 | from __future__ import unicode_literals
from smartmin.views import *
from sigtrac.carriers.models import Carrier
from sigtrac.reports.models import Report
from django.db.models import Avg
from django.utils import timezone
from django.shortcuts import get_object_or_404
from datetime import timedelta
import json
class ... | StarcoderdataPython |
1844256 | <gh_stars>1-10
class Solution:
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
# O(m)
while m > 0 and n > 0... | StarcoderdataPython |
8029936 | import logging
from slack_sdk.webhook import WebhookClient
from gkentn.core.handler import State
class Notifier:
def __init__(self, slack_webhook_url: str, logger: logging.Logger) -> None:
self.logger = logger
self.slack_webhook_url = slack_webhook_url
def notify(self, state: State) -> Non... | StarcoderdataPython |
5073094 |
import os
import yaml
confdir = os.getenv('INTAKE_CONF_DIR',
os.path.join(os.path.expanduser('~'), '.intake'))
conffile = os.getenv('INTAKE_CONF_FILE', None)
defaults = {'auth': {'class': 'intake.auth.base.BaseAuth'},
'port': 5000}
conf = {}
def reset_conf():
"""Set conf values... | StarcoderdataPython |
1902257 | <reponame>burdettadam/token-plugin
import json
import pytest
from base58 import b58decode
from sovtoken.constants import UTXO_CACHE_LABEL
from sovtokenfees.serializers import txn_root_serializer
from indy_node.test.request_handlers.helper import get_fake_ledger
from sovtoken import TOKEN_LEDGER_ID
from sovtoken.utxo_... | StarcoderdataPython |
1687092 | """[15 - Classe Bichinho Virtual++: Melhore o programa do bichinho virtual, permitindo que o usuário especifique quanto de comida ele fornece ao bichinho e por quanto tempo ele brinca com o bichinho. Faça com que estes valores afetem quão rapidamente os níveis de fome e tédio caem.]
"""
class bichinho():
"""[Class... | StarcoderdataPython |
3404037 | from flask import Flask, render_template
import random
import yaml
from sqlalchemy import create_engine
app = Flask(__name__)
#path_steam_user_id = './data/steam_user_id.txt'
config = yaml.safe_load(open('./src/config.yaml'))
db_username = config['mysql']['username']
db_password = config['mysql']['password']
db_en... | StarcoderdataPython |
5111086 | <gh_stars>1-10
import sys
from os.path import dirname, abspath
from src.fleets.electric_vehicles_fleet.electric_vehicles_fleet import ElectricVehiclesFleet
#from src.services.reg_service.test import fleet_name
sys.path.insert(0, dirname(dirname(dirname(abspath(__file__)))))
from dateutil import parser
from datetime imp... | StarcoderdataPython |
6604394 | from functools import partial
from glob import glob
from multiprocessing import Pool
from pprint import pprint
from typing import Dict
import os
import pickle as pkl
from Bio import SeqIO
import tensorflow as tf
from .remote_homology_serializer import serialize_remote_homology_sequence
from .vocabs import PFAM_VOCAB
... | StarcoderdataPython |
1601458 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Title : 模块
@File : __init__.py
@Author : vincent
@Time : 2020/8/28 4:53 下午
@Version : 1.0
'''
import json
import logging
import os
from flask import Blueprint, render_template, request, make_response, redirect
base_path = os.getcwd()
template_path =... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.