id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
79847 | <filename>skelebot/systems/generators/dockerfile.py
"""Dockerfile Generator"""
import os
import re
from ..execution import commandBuilder
FILE_PATH = "{path}/Dockerfile"
PY_INSTALL = "RUN [\"pip\", \"install\", \"{dep}\"]\n"
PY_INSTALL_VERSION = "RUN [\"pip\", \"install\", \"{depName}=={version}\"]\n"
PY_INSTALL_GIT... | StarcoderdataPython |
1632422 | <filename>pacote-download/d045 - jogar jokenpo.py<gh_stars>0
''' 045 Crie um programa que faça o computador jogar jokenpô com vocês'''
import random,time
lista = [1, 2, 3]
n = random.choice(lista)
if n == 1:
pc = 'pedra'
elif n == 2:
pc = 'tessoura'
else:
pc = 'papel'
escolha = int(input('Escolha um númer... | StarcoderdataPython |
3240714 | <gh_stars>100-1000
import numpy as np
import milk.unsupervised
from milk.unsupervised.kmeans import assign_centroids, repeated_kmeans
def test_kmeans():
np.random.seed(132)
features = np.r_[np.random.rand(20,3)-.5,.5+np.random.rand(20,3)]
def test_distance(dist, kwargs={}):
centroids, _ = milk.unsu... | StarcoderdataPython |
197228 | <gh_stars>0
"""Airfow DAG and helpers used in one or more istio release pipline."""
"""Copyright 2017 Istio Authors. 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://w... | StarcoderdataPython |
1676249 | <filename>numba/core/optional.py<gh_stars>1000+
import operator
from numba.core import types, typing, cgutils
from numba.core.imputils import (lower_cast, lower_builtin,
lower_getattr_generic, impl_ret_untracked,
lower_setattr_generic)
def always_ret... | StarcoderdataPython |
15745 | <gh_stars>0
# @l2g 932 python3
# [932] Beautiful Array
# Difficulty: Medium
# https://leetcode.com/problems/beautiful-array
#
# An array nums of length n is beautiful if:
#
# nums is a permutation of the integers in the range [1, n].
# For every 0 <= i < j < n, there is no index k with i < k < j where 2 * nums[k] == nu... | StarcoderdataPython |
3342073 | <gh_stars>10-100
#
# Simple Facebook crawler.
# It gets information from Facebook Groups using Facebook Graph API and saves it to files.
#
from __future__ import print_function
import time, os, sys, datetime
import requests
import json
import facebook
if len(sys.argv) != 3:
print('Usage: crawler <group_id> <tag>... | StarcoderdataPython |
3287493 | import sys
import argparse
from matplotlib import pyplot as plt
from app.models import SICImage as SIC, LMImage as LM, TEMPImage as TEMP, \
SSTImage as SST, NPRImage as NPR, NGRImage as NGR, IbandImage as IBAND, \
MbandImage as MBAND, FcImage as FC
from app.reports.analysis import hist_match, day_image, histm... | StarcoderdataPython |
84907 | <gh_stars>0
#!/usr/bin/env python
# coding: utf-8
r"""Memory usage
Run:
> aaFoamMemoryUsage.py -p <PID>
Do not use sudo, the command won't be found.
"""
from aa_foam.memory_usage import memory_usage_main
if __name__ == '__main__':
memory_usage_main()
| StarcoderdataPython |
1766798 | <reponame>kyleaton/great_expectations
from great_expectations.datasource.batch_kwargs_generator import GlobReaderBatchKwargsGenerator
def test_batch_kwargs_generator_class_name(basic_pandas_datasource):
generator = GlobReaderBatchKwargsGenerator(datasource=basic_pandas_datasource)
generator_config = generator... | StarcoderdataPython |
182373 | <reponame>MatheusLeandro01/pythonbirds<gh_stars>0
class Pessoa:
olhos = 2 # atributo de classe
def __init__(self, idade=None, nome='', *filhos): # Método construtor
self.idade = idade # atributo de objeto ou atributo de Instância
self.nome = nome
self.filhos = list(filhos) # atribut... | StarcoderdataPython |
1653217 | import serial
import serial.tools.list_ports
from time import time
from datetime import datetime
# nekaj nastavitev
n_meritev = 1 # koliko meritev pricakujemo iz Arduina
meritve_dat = 'co2_senzor_kalibracija_2.csv' # v katero datoteko bomo shranjevali meritve
def branje_in_shranjevanje_podatkov(arduino_port):
# pr... | StarcoderdataPython |
3284105 | <filename>resolwe_bio/tests/processes/test_junctions.py
# pylint: disable=missing-docstring
from resolwe.test import tag_process
from resolwe_bio.utils.test import with_resolwe_host, KBBioProcessTestCase
class JunctionsProcessorTestCase(KBBioProcessTestCase):
@with_resolwe_host
@tag_process('regtools-juncti... | StarcoderdataPython |
3356599 | <reponame>Aunsiels/CSK
from quasimodo.web_search.archit_submodule import ArchitSubmodule
class FlickrRegressionSubmodule(ArchitSubmodule):
def __init__(self, module_reference):
super().__init__(module_reference)
self._name = "Flickr regression"
self._index = 8
| StarcoderdataPython |
3216738 | """
The Song class contains the getinfo function which,
given a song title as input, returns information about
the artist, album, release date, playlist in which it
appeared, genre and subgenre of the playlist,
bpm of the song and playback time.
"""
# importing needed libraries
import pandas as pd
import os
# crea... | StarcoderdataPython |
3299440 | """
Ethereum Virtual Machine (EVM) Interpreter
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. contents:: Table of Contents
:backlinks: none
:local:
Introduction
------------
A straightforward interpreter that executes EVM code.
"""
from typing import List, Tuple
from ethereum.base_types import U256, Uint
fr... | StarcoderdataPython |
1691076 | import spacy
import re
try:
language_model = 'en_core_web_sm'
nlp = spacy.load(language_model)
except OSError:
print(f'Downloading language model "{language_model}" spaCy')
from spacy.cli import download
download(language_model)
nlp = spacy.load(language_model)
def remove_pii_name(text: str, re... | StarcoderdataPython |
73971 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (division, print_function, absolute_import,
unicode_literals)
__all__ = []
import json
import sqlite3
if __name__ == "__main__":
with open("aas/abstracts.json") as f:
data = json.load(f)
with sqlite3.conne... | StarcoderdataPython |
4825642 | def ifChuckSaysSo():
return 1=="1" | StarcoderdataPython |
21673 | """Assimp-based analyzer."""
from __future__ import absolute_import
import os
import logging
import subprocess
import pyassimp
from damn_at import (
mimetypes,
MetaDataType,
MetaDataValue,
FileId,
FileDescription,
AssetDescription,
AssetId
)
from damn_at.pluginmanager import IAnalyzer
from... | StarcoderdataPython |
1706314 | <filename>wrapper/__init__.py
Cost = float
| StarcoderdataPython |
4811093 | <filename>irc2mu.py
from sys import argv
import logging
import asyncio
#logging.basicConfig(level=logging.DEBUG)
BINDHOST = '127.0.0.1'
BINDPORT = 6668
MUHOST = argv[1]
MUPORT = int(argv[2])
class MUClientProtocol(asyncio.Protocol):
def __init__(self):
self.loop = loop
self.last_bold = "... | StarcoderdataPython |
3229406 | from typing import List
import pytest
import strawberry
from strawberry.annotation import StrawberryAnnotation
import strawberry_django
from strawberry_django import auto
from tests import models, utils
@strawberry_django.filters.filter(models.Color, lookups=True)
class ColorFilter:
id: auto
name: auto
@s... | StarcoderdataPython |
118004 | <filename>tests/test_bcc.py<gh_stars>10-100
import pytest
from iec62056_21.utils import calculate_bcc, add_bcc
class TestBcc:
def test_bcc_bytes1(self):
data = bytes.fromhex("01573202433030332839313033323430393232333929031b")
correct_bcc = chr(data[-1]).encode("latin-1")
bcc = calculate_b... | StarcoderdataPython |
129229 | # These function calls don't quite work. Fix them!
uniforms = {'Thelma': '4', 'Twi': '21', 'Dottie': '9'}
thelma_number = int uniforms['Thelma']
twi_number = int uniforms['Twi']
sum = thelma_number + twi_number
print(sum)
| StarcoderdataPython |
4806966 | import sys,os
import pymongo
import traceback
def errorHanddler(e=Exception):
print(str(e))
print(repr(e))
print(traceback.print_exc())
print(traceback.format_exc())
class PyMongoClinetUtil():
host="127.0.0.1"
port=27017
def __init__(self,host,port):
self.... | StarcoderdataPython |
1706632 | # -*- coding: utf-8 -*-
"""
Created on Sat Sep 17 01:55:45 2016
@author: gabrielfior
"""
import os
import matplotlib.pyplot as plt
import numpy as np
import cv2
import scipy.ndimage as ndimage
from pupil_detection import GetPupil, detectPupilKMeans
plot_all = False
filedir = '/Users/gabrielfior/hackzurich/bmp_pupil... | StarcoderdataPython |
150186 | <filename>various/iap_5_iteration.py
#! /usr/bin/env python2
"Interactive Python Part 5: Iteration and Repetition"
import random
from lib import cImage as image
def wandering_turtle():
"""Modify the walking turtle program so that rather than a 90 degree left or
right turn the angle of the turn is determined ... | StarcoderdataPython |
14227 | from django.urls import path
from . import views
app_name = 'trip'
urlpatterns = [
path('', views.index, name='index'),
path('tripblog/', views.AllTrip.as_view(), name="tripplan"),
path('likereview/', views.like_comment_view, name="like_comment"),
path('tripdetail/<int:pk>/', views.trip_detail, name="t... | StarcoderdataPython |
154929 | #!/usr/bin/env python3
"""problem_003.py
Problem 3: Largest prime factor
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number N?
"""
__author__ = '<NAME>'
import common.primes as prime
# PARAMETERS ########################################################... | StarcoderdataPython |
4839767 | <filename>app/api_1_0/api1_0.py<gh_stars>0
# -*- coding:utf8 -*-
import datetime
import random
import string
from app.extent import db, wechat
from app.models.model import User, QrCode
from app.utils.yunzhixun_utils import YzxAPI
from config import Config
from flask import session, jsonify, request, render_template
fr... | StarcoderdataPython |
1653489 | <reponame>GermanCentralLibraryForTheBlind/sublime-brailleMusic
import sublime
import sublime_plugin
from .data.tables import *
def plugin_loaded():
pass
class ViewUtils(object):
@property
def cursor(self):
return self.view.sel()[0]
@property
def cur_line_region(self):
"""get line... | StarcoderdataPython |
163944 | """osc_models module contains all the application level models"""
from typing import Optional
class Sequence:
"""Sequence is a model class containing a list of visual items"""
def __init__(self):
self.path: str = ""
self.online_id: str = ""
self.progress: [str] = []
self.visua... | StarcoderdataPython |
3249464 | <gh_stars>1-10
import csv
import os
import sys
import json
sys.path.insert(0, os.getcwd())
def parse_json(file_path,outfile_path):
with open(file_path,newline='') as input_file:
json_data = json.load(input_file)
test_data = json_data["data"]
csv_data = open(outfile_path, 'w')
csvwriter = csv.... | StarcoderdataPython |
3367862 | <gh_stars>0
import cv2
import numpy as np
from tricks import *
from decompositioner import *
def GuidedFiltF(img, r):
eps = 0.04
I = img
I2 = cv2.pow(I, 2)
mean_I = cv2.boxFilter(I, -1, ((2 * r) + 1, (2 * r) + 1))
mean_I2 = cv2.boxFilter(I2, -1, ((2 * r) + 1, (2 * r) + 1))
cov_I = mean_I2 - cv... | StarcoderdataPython |
12522 | <reponame>khchine5/xl<gh_stars>1-10
# -*- coding: UTF-8 -*-
# Copyright 2013-2016 <NAME>
#
# License: BSD (see file COPYING for details)
"""This module is for managing a reception desk and a waiting queue:
register clients into a waiting queue as they present themselves at a
reception desk (Empfangsschalter), and unre... | StarcoderdataPython |
3202554 | '''Tests for users'''
from .basetests import BaseTest
class TestUsers(BaseTest):
"""Test user registration and login"""
def test_user_login(self):
"""Test user login endpoint"""
response = self.login()
self.assertEqual(response.status_code, 200)
def test_missing_first_name(self):
... | StarcoderdataPython |
3396767 | class BotException(Exception):
pass
| StarcoderdataPython |
1778076 | <filename>main.py<gh_stars>0
import os
import watsonSTT
from dotenv import load_dotenv
def main():
load_dotenv()
API = os.getenv("API_KEY")
URL = os.getenv("URL")
watsonSTT.watson_start(API, URL)
if __name__ == "__main__":
main()
| StarcoderdataPython |
3239290 | <reponame>Bonsanto/directed-graph
import networkx as nx
import pandas as pd
import functools
import queue
class DirectedGraph:
def __init__(self, **kwargs):
self.source_nodes = set()
self.target_nodes = set()
self.weights = {}
self.dg = nx.DiGraph()
if len(kwargs) > 0:
... | StarcoderdataPython |
3263043 | <reponame>dkarageo/image_tagger
from pydantic import BaseModel, AnyHttpUrl
class PredictionItem(BaseModel):
"""Model for each label contained in a prediction."""
label: str
confidence: float
class PredictionResponse(BaseModel):
"""Model to be returned when a successful prediction is performed."""
... | StarcoderdataPython |
1627493 | <reponame>frostyfan109/gamma-viewer<gh_stars>0
"""Initialize jupyter nb extension path."""
from .gamma_viewer import *
def _jupyter_nbextension_paths():
return [{
'section': 'notebook',
'src': 'static',
'dest': 'gamma_viewer',
'require': 'gamma_viewer/extension'
}]
| StarcoderdataPython |
3348168 | <reponame>Hoa-Lab/audiogram
import numpy as np
import pickle
from pathlib import Path
import tensorflow.keras as keras
#--------------------------------------------------------
fd_out='./out/a04_dl_01_mod'
fd_in='./out/a04_dl_00_pp'
fd_mod=f'{fd_out}/mod_2' #mod0 - {0: 0.2, 1: 0.8}, 1 - {0: 0.5, 1: 0.5}, 2 - {0: 0.8,... | StarcoderdataPython |
14255 | import pytest
from moto import mock_ec2
from moto.ec2.models import AMIS
from aec.command.ami import delete, describe, share
@pytest.fixture
def mock_aws_config():
mock = mock_ec2()
mock.start()
return {
"region": "ap-southeast-2",
}
def test_describe_images(mock_aws_config):
# describ... | StarcoderdataPython |
3297623 | import numpy as np
from lagom.envs.spaces.base import Space
class Product(Space):
"""
A product (tuple) of elementary spaces.
"""
def __init__(self, spaces):
"""
Define a product of elementary spaces.
Example:
Product((Discrete(5), Box(-1.0, 1.0, shape=(2,... | StarcoderdataPython |
3320335 | class Solution:
def mySqrt(self, x: int) -> int:
ans = 0
while ans * ans <= x:
tmp = ans + 1
if tmp * tmp > x:
break
ans = tmp
return ans
def mySqrt(self, x: int) -> int:
"""二分优化"""
low, high = 0, x
ans = 0
... | StarcoderdataPython |
3338685 | <reponame>NREL/PowerGridworld<gh_stars>10-100
from tests.conftest import single_agent_episode_runner
from tests.agents.conftest import pv_config
from gridworld.agents.pv import PVEnv
def test_default_env(pv_config):
"""Creates an env instance and runs it (sanity check)."""
env = PVEnv(**pv_config)
assert... | StarcoderdataPython |
1683009 | <filename>commons/c2cgeoportal_commons/alembic/static/7ef947f30f20_add_oauth2_tables.py
# Copyright (c) 2020, Camptocamp SA
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of ... | StarcoderdataPython |
1614141 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '.\search.ui'
#
# Created by: PyQt5 UI code generator 5.13.0
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
from nwebrequest import WebToonInfo, ImageDownload, MakeDirectory, ch... | StarcoderdataPython |
1705434 | import os
import torch
import torchvision.transforms as tfs
import numpy as np
from torch.utils.data.dataset import Dataset
from torch.utils.data import DataLoader
from PIL import Image
from .utils import extract_episode
_SHAPENET_ID2NAME = {
'02691156': 'airplane',
'02880940': 'bowl',
'02942699': 'came... | StarcoderdataPython |
3384222 | <gh_stars>0
# Copyright (c) 2014 Red Hat, 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/LICENSE-2.0
#
# Unless required by applicable law or agree... | StarcoderdataPython |
113350 | """Factory for Python Protocol API instances."""
import asyncio
from opentrons.protocol_engine import ProtocolEngine
from opentrons.protocol_engine.clients import SyncClient, ChildThreadTransport
from opentrons.protocol_api_experimental import ProtocolContext
class ContextCreator:
"""A factory to build Python Pro... | StarcoderdataPython |
1710582 | import argparse
import sys
import sounddevice
import logging
import logging.config
logger = logging.getLogger('m2.runAudioExperiment.main')
LIST_FLAGS = ['-l', '--list-devices']
def parse_arguments(args):
'''
Creates the argument parser and returns parsed arguments.
'''
parser = argparse.ArgumentPars... | StarcoderdataPython |
183118 | from django.urls import path
from xcx_interface.controller.system.system_msg import getUserInfo, addUserToBlackList, blackList, getInterfaceList
urlpatterns = [
# 获取接口权限表
path('getInterfaceList', getInterfaceList, name='getInterfaceList'),
# 获取用户信息
path('getUserInfo', getUserInfo, name='getUserInfo'),
... | StarcoderdataPython |
3228174 | from blinker import Namespace
signals = Namespace()
job_received = signals.signal('job_received')
job_finished = signals.signal('job_finished')
job_failed = signals.signal('job_failed')
job_retried = signals.signal('job_retried')
job_succeeded = signals.signal('job_succeeded')
job_published = signals.signal('jo... | StarcoderdataPython |
1685892 | #!/usr/bin/python3
from flask import Flask
from modules import config
from modules.database import init_db
from routes import route_users, route_customs, route_bookings, route_lessons
from routes.account import route_account_public, route_account_auth
from routes.courses import route_courses_auth, route_courses_publi... | StarcoderdataPython |
3319604 | # coding: utf-8
from sqlalchemy import Column
from sqlalchemy import String
from rolling.server.extension import ClientSideDocument as Document
class ServerDocument(Document):
__tablename__ = "server"
server_address = Column(String(255), primary_key=True)
current_character_id = Column(String(255), nullab... | StarcoderdataPython |
1765926 | import requests
import json
from janda.utils.parser import *
BASE_URL = Api()
class Pururin(object):
"""Pururin API wrapper
Methods
-------
get: function
Gets doujin from id
get_random: function
Gets random doujin
search: function
Searches doujin by tags / artist / ... | StarcoderdataPython |
3215511 | <reponame>itsens/stan
#!/usr/bin/env python3
from stan.plotter import PlotlyGraph, SarGraph
from stan.parser import sar
import random
import os
import time
FILE_DIR = os.path.dirname(os.path.abspath(__file__))
PLOT_FILE_NAME = FILE_DIR + '/files/plotly_graph_example.html'
def generate_graph():
test_time = 360 ... | StarcoderdataPython |
70063 | <reponame>mwk0408/codewars_solutions
def boxes_packing(length, width, height):
total=[sorted((i,j,k)) for i,j,k in zip(length, width, height)]
res=sorted(total, key=lambda x: -min(x))
for i,j in enumerate(res[1:]):
if any((k-l)<=0 for k,l in zip(res[i], j)):
return False
return True | StarcoderdataPython |
1666580 | <filename>chocopy-rs/test/original/pa2/bad_func_def_call.py
def foo(x:str, y:bool) -> int:
return bar()
def bar() -> int:
return 1
# All of the below are bad calls
foo("Hello")
foo("Hello", False, 3)
foo("Hello", 3)
foo(1, "Hello")
baz()
| StarcoderdataPython |
3368347 | <reponame>clauddio-silva/ope-1<filename>ope-backend/src/core/controllers/user_controllers/list_users_controller.py
class ListUsersController:
def __init__(self, list_users_use_case):
self.list_users_use_case = list_users_use_case
def route(self, body):
response = self.list_users_use_case.list(... | StarcoderdataPython |
1610023 | import argparse
import os
import time
import matplotlib.pyplot as plt
import numpy as np
import PIL
import torch
import torch.optim as optim
import torchvision
from PIL import Image
from torch import nn
from torch.nn import functional as F
from models.vanilla_vae_q import QuaternionVanillaVAE
from models.vanilla_vae ... | StarcoderdataPython |
3259415 | def solution(total_lambs):
return max_payout(total_lambs) - min_payout(total_lambs)
def min_payout(LAMBs):
return (LAMBs + 1).bit_length() -1
def max_payout(LAMBs):
from math import log, ceil, sqrt
sqrt_five = sqrt(5)
return int(ceil(log((LAMBs + 1 + 0.5) * sqrt_five, (1 + sqrt_five) / 2)) - 3)
p... | StarcoderdataPython |
3220882 | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class GmapGsnap(AutotoolsPackage):
"""GMAP: A Genomic Mapping and Alignment Program for
m... | StarcoderdataPython |
3290838 | <reponame>Blue-IT-Marketing/loan-management-system<filename>gap/main.py
#!/usr/bin/env python
#
# Copyright 2007 Google 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... | StarcoderdataPython |
53571 | <reponame>kibeomKim/GACE-GDAN
import numpy as np
import torch
def norm_col_init(weights, std=1.0):
x = torch.randn(weights.size())
x *= std / torch.sqrt((x ** 2).sum(1, keepdim=True))
return x
def ensure_shared_grads(model, shared_model, gpu=False):
for param, shared_param in zip(model.parameters(),
... | StarcoderdataPython |
195899 | <gh_stars>0
#!/usr/bin/env python2
##
############
##
## Software under MIT licence
##
############
import socket
import Queue, threading, sys, select
import catch_yt as yt
import processing
class Server:
def __init__( self ):
# Host Name
self.h_name = ''
# Host Port
self.h_port ... | StarcoderdataPython |
27066 | from django.apps import AppConfig
class FeusersConfig(AppConfig):
name = 'feusers'
| StarcoderdataPython |
3204321 | X_train = X_t.iloc[train_idx]
Y_train = Y_t.loc[X_train.index]
X_test = X_t.iloc[test_idx]
Y_test = Y_t.loc[X_test.index]
def train_model(X_train, Y_train, X_test, Y_test):
model = CatboostModel()
model.fit(X_train, Y_train, X_test, Y_test)
models[molecule_type].append(model)
predictions[molecule_type... | StarcoderdataPython |
3200900 | <gh_stars>0
#!/usr/bin/env python
import requests
import pandas
import json
import os.path as op
import os
from nbaou.utils import create_record, edit_record
from nbaou.utils import get_teams, get_standings
from nbaou.config import data_dir
def set_line(cache=False, *args, **kwargs):
if not op.isdir(data_dir):
... | StarcoderdataPython |
1730524 | <reponame>geoffrey-p-morgan/symkala<filename>symkala/settings.py
"""
Django settings for symkala project.
Generated by 'django-admin startproject' using Django 1.9.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https:... | StarcoderdataPython |
3250900 | <gh_stars>1-10
#!usr/bin/env python
# -*- coding:utf-8 _*-
"""
@version: V1.0
@author: <NAME>
@contact: <EMAIL>
@time: 2018/02/25
@file: utils.py
@description:
@modify: Some helpful functions.
"""
import datetime
import re
def format_TTL(TTL):
"""
Change the time to minutes.
:param TTL:
:retur... | StarcoderdataPython |
1738382 | # -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2019 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in co... | StarcoderdataPython |
1613592 | """ Testing unittest_assertions/base.py """
from typing import (
Callable,
Iterable,
Mapping,
)
import pytest
from unittest_assertions.base import Assertion
from unittest_assertions.equality import AssertEqual
class TestBuiltinAssertion:
"""Testing builtin assertions"""
@pytest.mark.parametrize... | StarcoderdataPython |
1713916 | <reponame>isabelladegen/mlp-2021
from sklearn.linear_model import LinearRegression
from src.Data import Data
from src.configurations import Configuration
from src.models.Model import Model
class LinearRegressionModel(Model):
def __init__(self, config: Configuration, training_data: Data):
features = confi... | StarcoderdataPython |
4836143 | from __future__ import print_function
from distutils.command.build import build
from commands.java import build_javah, build_java
class jep_build(build):
sub_commands = [
('setup_java', None),
('build_java', None),
('build_javah', None),
('build_jar', None),
] + build.sub_comma... | StarcoderdataPython |
3399117 | from typing import Callable
f: Callable[[int, str], str] | StarcoderdataPython |
3270264 | <gh_stars>10-100
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright (c) 2009 <NAME> All rights reserved.
#
"""
"""
#end_pymotw_header
import sys
class NoisyImportFinder(object):
PATH_TRIGGER = 'NoisyImportFinder_PATH_TRIGGER'
def __init__(self, path_entry):
print 'Checking %s:' % path_ent... | StarcoderdataPython |
3259266 | <reponame>FinalProject-VIT/cart-analytics-core
from flask import Flask
from flask import render_template
import mysql.connector
from mysql.connector import Error
import csv
app = Flask(__name__)
def get_book_ratings_csv():
csv_path = './static/book-rating-csv/part-00000'
csv_file = open(csv_path, 'rb')
cs... | StarcoderdataPython |
83838 | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class MAneos(MakefilePackage):
"""M-Aneos"""
homepage = "https://github.com/isale-code/M-AN... | StarcoderdataPython |
1640266 | <gh_stars>1-10
import unittest
import json
from config import config
from app import create_app
from app import db
class TestAPI(unittest.TestCase):
def setUp(self):
enviroment = config['test']
self.app = create_app(enviroment)
self.client = self.app.test_client()
self.content_type ... | StarcoderdataPython |
3376520 | from behave import given, when, then
import speech_recognition as sr
import asyncio
import re
import sqlite3
from os import path
# #######TEST RECORDED SPEECH########## #
get_file = lambda f: path.join(path.dirname(path.realpath(__file__)), "/materials/" + f.lower() + ".wav")
test_file = lambda f: path.join(path.dirna... | StarcoderdataPython |
1695333 | import pandas as pd
import base64
tweets = pd.read_json(
"data/preprocessed/stream/merged_tweets_image_metadata_stream.json")
tweets.iloc[0:2].to_json("mock_api.json", orient="records")
# with open("./data/original/images/test/damage/-93.6141_30.754263.jpeg", "rb") as image_file:
# encoded_string = base64... | StarcoderdataPython |
23842 | <filename>quizme.pyw<gh_stars>0
"""GUI for taking tests based on quizme-xxx.json files.
"""
import os
import sys
import json
from random import randint
import tkinter as tk
from tkinter import font
from tkinter import ttk
from tkinter import filedialog
from tkinter import messagebox
from widgetrefs import widgets
de... | StarcoderdataPython |
3382982 | #!/usr/bin/env python
# coding: utf-8
"""
analysis and optimization
"""
import logging
import numpy as np
import pandas as pd
import seaborn as sns
import sklearn
from matplotlib import pyplot as plt
from scipy import stats
from scipy.optimize import differential_evolution
from sklearn.ensemble import RandomForestReg... | StarcoderdataPython |
102016 | <filename>app/core/utils/urls.py
# -*- encoding:utf-8 -*-
import django_sites as sites
from django.core.urlresolvers import reverse as django_reverse
URL_TEMPLATE = "{scheme}://{domain}/{path}"
def build_url(path, scheme="http", domain="localhost"):
return URL_TEMPLATE.format(scheme=scheme, domain=domain, path=... | StarcoderdataPython |
1731972 | <filename>Online Product Sales/online-baseline.py
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn.ensemble import BaggingRegressor
from sklearn.ensemble import ExtraTreesRegressor
from sklearn.ensemble import AdaBoostRegressor
from sklearn.ensemble import GradientBoostingRegressor
fr... | StarcoderdataPython |
93520 | <reponame>dobachi/PubNubExample
import os
import inspect
import pprint
from pubnub.callbacks import SubscribeCallback
from pubnub.enums import PNStatusCategory
from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub import PubNub
CHANNEL = "file_test"
pnconfig = PNConfiguration()
pnconfig.publish_key =... | StarcoderdataPython |
1627632 | <gh_stars>1-10
##Version 1.1 Sohva
import Tkinter
import time
import random
import ImageTk
top = Tkinter.Tk()
#Initialize images
grass = ImageTk.PhotoImage(file = "grass.png")
foodimage = ImageTk.PhotoImage(file = "food.png")
snakeskin = ImageTk.PhotoImage(file = "snake.png")
snakeleft = ImageTk.PhotoIm... | StarcoderdataPython |
1616680 | from commands import *
from mixes import * | StarcoderdataPython |
199925 | <gh_stars>1-10
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "licens... | StarcoderdataPython |
37528 | import json
import pytest
@pytest.fixture
def test_bib():
with open(".\\test_files\\bib.json") as file:
return json.load(file)
@pytest.fixture
def test_mixed_bib():
with open(".\\test_files\\mixed_bib.json") as file:
return json.load(file)
| StarcoderdataPython |
3336624 | from Crypto.Hash import SHA256
from Crypto.Util.number import bytes_to_long, long_to_bytes, size, getRandomNBitInteger
from storage import flag
def byten(x, n):
return (x >> (n * 8)) & 0xFF
def mask(n):
return (1 << n) - 1
def rotate(x, n, s):
return ((x >> (s - n)) | (x << n)) & mask(s)
de... | StarcoderdataPython |
188352 | <reponame>jcchan23/SAIL
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : model.py
@Time : 2022/01/17 16:00:19
@Author : <NAME>
@Version : 1.0
@Contact : <EMAIL>
@License : (C)Copyright 2021-2022, SAIL-Lab
'''
######################################## import area ##################... | StarcoderdataPython |
141583 | # Copyright 2015 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Unittests for gclient.py."""
from __future__ import print_function
import os
from chromite.lib import cros_build_lib
from chromite.lib import cros_b... | StarcoderdataPython |
91855 | <gh_stars>100-1000
# -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-08-01 21:05
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
('osf', '0121_merge_201... | StarcoderdataPython |
3287695 | from __future__ import print_function
# bustersAgents.py
# ----------------
from builtins import str
from builtins import range
from builtins import object
import util
from game import Agent
from game import Directions
from keyboardAgents import KeyboardAgent
import inference
import busters
class NullGraphics(object)... | StarcoderdataPython |
1714845 | #!/usr/bin/env python
"""
Calculator screen
"""
import curses
class Screen:
def __init__(self, stdscr: 'curses._CursesWindow', width):
"""
@param stdscr Parent window
@param width Screen width matches that of calculator keyboard
"""
# leave two characters on all sides for b... | StarcoderdataPython |
1790732 | <reponame>vincenttran-msft/azure-sdk-for-python<gh_stars>1-10
# pylint: disable=too-many-lines
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.