id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
4816389 | <reponame>crocs-muni/cert-validataion-stats
"""This package contains analytical functions and tools for quantitative analysis of certificate datasets."""
__version__ = '1.1'
__author__ = '<NAME>'
__all__ = (
'CertAnalyser',
'ChainValidator',
)
from .cert_analyser import CertAnalyser
from .chain_validator impo... | StarcoderdataPython |
119595 | <reponame>zerforschung/Covid32Counter<filename>firmware/captive_bvg.py<gh_stars>10-100
import gc
import util
import uuurequests
# collect all hidden form fields from HTML
def parseFormValues(text: str) -> str:
startIndex = 0
postFields = []
postFields.append("termsOK=1")
postFields.append("button=kos... | StarcoderdataPython |
102120 | import pexpect
from pexpect import exceptions
import time
from rassh.managers.expect_manager import ExpectManager
from rassh.managers.expect_commands import ExpectCommands
from rassh.managers.blackhole_telnet_commands import BlackholeTelnetCommands
import logging
logging.basicConfig(level=logging.INFO)
logger = loggi... | StarcoderdataPython |
3242166 | #!/usr/bin/env python3
'''
Load data files from the game's "data" directory.
'''
# TODO: Add caching.
import os
import sys
base_dir = os.path.dirname(sys.executable if hasattr(sys, "frozen") else sys.argv[0])
data_dir = os.path.normpath(os.path.join(base_dir, 'data'))
if not os.path.isdir(data_dir):
try_base_di... | StarcoderdataPython |
1726711 | <reponame>Rexarrior/ALT
import json
import pickle
import os
from typing import Dict, Iterable, TypeVar, Type, List, Union, Any
if __package__:
from link_analysis.models import Header, DocumentHeader, CleanLink
else:
from models import Header, DocumentHeader, CleanLink # type: ignore
# Don't forget to add to ... | StarcoderdataPython |
1676135 | #!/usr/bin/env python
# coding: utf-8
# this code is a modification of:
# notes:
# todo : I canceled the randomize weights for the last layer + freezed the weights for all of the layers (some weights were trained anyway).
#todo : mayb -- save to fule during evaluate function the outputs
# **Outline of Steps**
# + ... | StarcoderdataPython |
3272746 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
GWCS - Generalized World Coordinate System
==========================================
Generalized World Coordinate System (GWCS) is an Astropy affiliated package
providing tools for managing the World Coordinate System of astronomical data.
G... | StarcoderdataPython |
3338895 | import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
import tensorflow as tf
import numpy as np
import sys
sys.path.append("..")
from utils import *
from funcs import *
from sklearn.metrics import log_loss
from sklearn.metrics import confusion_matrix
from sklear... | StarcoderdataPython |
87973 | from wpilib.command import Command
import robotmap
import subsystems
import oi
class TankLiftTeleopDefault(Command):
def __init__(self):
super().__init__('TankLiftTeleopDefault')
self.requires(subsystems.drivelift)
self.setInterruptible(True)
self.setRunWhenDisabled... | StarcoderdataPython |
3275452 |
from scriptcore.testing.testcase import TestCase
from scriptcore.filesystem.mimetype import MimeType
class TestMimeType(TestCase):
def test_guess_type(self):
"""
Test guess type
:return: void
"""
data = [
('.pdf', 'application/pdf'),
('... | StarcoderdataPython |
3350391 | <gh_stars>0
"""
These for the flow builder, the flow builder is the code
which build flows from Operators using the greater than
mathematical Operator (>).
"""
import pytest
import os
import sys
sys.path.insert(1, os.path.join(sys.path[0], ".."))
from mabel.logging import get_logger
from mabel.operators import Filte... | StarcoderdataPython |
1693979 | <filename>mokapapp/lib.py
"""lib.py
General class and function library for updating Moka panels.
"""
import argparse
import configparser
import itertools
import logging
import requests
logger = logging.getLogger(__name__)
def _config_reader(config_file):
config = configparser.ConfigParser()
config.read(con... | StarcoderdataPython |
161740 | """
Data loader for TUM RGBD benchmark
@author: <NAME>
@date: March 2019
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import sys, os, random
import pickle
import numpy as np
import os.path as osp
import torch... | StarcoderdataPython |
1765717 | """Reward processors
Each method takes the metadata with the following keys:
- env_reward: MiniWoB official reward
- raw_reward: Raw task reward without time penalty
- done: Whether the task is done
Then it returns a reward (float).
"""
def get_original_reward(metadata):
return float(metadata['env_rew... | StarcoderdataPython |
136225 | from setuptools import setup
setup(name='gym_gridworld',
version='0.0.1',
install_requires=['gym'],
author="<NAME>",
author_email="<EMAIL>",
description="A Gym environment representing a 2d rectangular grid world",
packages=setuptools.find_packages(),
)
| StarcoderdataPython |
72688 | #!/bin/python3
from contextlib import contextmanager
# pip3 install datetime
import datetime
import errno
import time
import shutil
import sys
import tempfile
from os import listdir, sep as os_sep
from os.path import isdir, isfile, join
# local imports
import consts
from args import Arguments, UpdateType
from github ... | StarcoderdataPython |
3263848 | # -*- coding: utf-8 -*-
"""
Created on Thu Feb 27 15:02:55 2020
@author: posch
"""
import numpy as np
class model():
# HOOK
def hook(SIG_old,dEPS,E, DT):
dSIG = E * dEPS
SIG = SIG_old + dSIG * DT
return SIG
# KELVIN VOIGT
def kelvinvoigt(E... | StarcoderdataPython |
1713238 | # -*- coding: utf-8 -*
content = {
'综述':
{
'综述型简介':
[
"唐三彩以三彩统称,年代另述,而非以“唐三彩”一言以蔽之。所谓唐三彩,“唐”为时代,“三彩”指工艺,仅指公元618年-公元907年所烧造的三彩器物,距今有1300多年的历史。",
],
'唐三彩的历史':
[
"1899年勘探某铁路的时候,古器物学家罗振宇和王国维发现了之前未命名过... | StarcoderdataPython |
3291095 | from featuretools.primitives import AggregationPrimitive
from featuretools.variable_types import Numeric
from tsfresh.feature_extraction.feature_calculators import abs_energy
class AbsEnergy(AggregationPrimitive):
"""Returns the absolute energy of the time series
which is the sum over the squared values.
... | StarcoderdataPython |
161744 | <filename>examples/similarity_conf.py
"""
This module gives an example of how to configure similarity measures
computation.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from amaze import KNNBasic
from amaze import Dataset
from amaze.model_selection i... | StarcoderdataPython |
47153 | <filename>tests/test_admin.py<gh_stars>0
"""Test Admin interface provided by Improved User"""
import os
import re
from django import VERSION as DjangoVersion
from django.contrib.admin.models import LogEntry
from django.contrib.auth import SESSION_KEY
from django.test import TestCase, override_settings
from django.test... | StarcoderdataPython |
1716564 | #!/usr/bin/env python
import yaml
from netmiko import ConnectHandler
from netmiko import Netmiko
from pprint import pprint
from ciscoconfparse import CiscoConfParse
filename = "/home/dcarrasco/.netmiko.yml"
with open(filename) as f:
yaml_dict = yaml.load(f)
device = yaml_dict['cisco4']
Node = {
"host": device['... | StarcoderdataPython |
1774234 | <gh_stars>0
import sounddevice
import pydub
import time
import numpy
class Audio():
def __init__(self, filepath=None):
if filepath is not None:
self.openfile(filepath)
def openfile(self, filepath):
if ".mp3" in filepath:
self.segment = pydub.AudioSegment.from_file(filep... | StarcoderdataPython |
107800 | import re
from emoji.unicode_codes import UNICODE_EMOJI
from nonebot import on_regex
from nonebot.params import RegexDict
from nonebot.plugin import PluginMetadata
from nonebot.adapters.onebot.v11 import MessageSegment
from .config import Config
from .data_source import mix_emoji
__plugin_meta__ = PluginM... | StarcoderdataPython |
1733084 | <gh_stars>0
import cloudinary.uploader
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import redirect
from django.urls import reverse_lazy
from django.views import generic as generic_views
from mytravelblog.main_app.forms.travel_picture import *
from mytravelblog.main_app.models import... | StarcoderdataPython |
39410 | <reponame>popravich/rdbtools3
from .parser import parse_rdb_stream, RDBItem
from .exceptions import FileFormatError, RDBValueError
__version__ = '0.1.2'
(RDBItem, parse_rdb_stream,
FileFormatError, RDBValueError) # pragma: no cover
| StarcoderdataPython |
167346 | <reponame>opimentel-github/astro-lightcurves-classifier
from __future__ import print_function
from __future__ import division
from . import _C
import torch
import torch.nn as nn
from fuzzytorch.models.basics import MLP, Linear
###########################################################################################... | StarcoderdataPython |
3334947 | import matplotlib.pyplot as plt
import seaborn as sns
def hist(series, rotate_labels_by=None, **kwargs):
fig, ax = plt.subplots()
sns.distplot(series, ax=ax, **kwargs)
if rotate_labels_by:
plt.setp(ax.get_xticklabels(), rotation=rotate_labels_by)
return fig
def bars(series, rotate_labels_by=... | StarcoderdataPython |
1773864 | <gh_stars>1-10
import os
f = [i for i in os.listdir("test_images")]
for alg in ["RO","DE","PSO","GWO","JAYA","GA"]:
for n in [4,6,8]:
for t in f:
cmd = "python3 segment.py test_images/%s %d 20 2000 %s RI segmentations/%s_20_2000_%s_%d" % \
(t,n,alg,t[:-4],alg,n)
... | StarcoderdataPython |
3263711 | <filename>py2markdown/__init__.py
'''
# py2markdown
Py2markdown converts a python file to a markdown file where all top level
level `""" comments """` are rendered as markdown, and everything else
is rendered as code blocks.
The `README.md` for this repo was generated by running:
$ py2markdown py2markdown/__init... | StarcoderdataPython |
1696602 | #!/usr/bin/env python3.6
import pyperclip
import unittest
from credential import Credential
class TestCredential(unittest.TestCase):
"""
Test class that defines test cases for the credential class behaviousrs
"""
def setUp(self):
"""
use set up method
"""
self.new_cred... | StarcoderdataPython |
28884 | import os
file=open("C:/Users/michael.duran\OneDrive - <NAME>/Documents/Audisoft/Thomas/Inmofianza/TeamQA/SeleniumInmofianza/src/classes/datos.txt","w")
file.write("Primera línea" + os.linesep)
file.write("Segunda línea")
file.close() | StarcoderdataPython |
1717666 | <filename>Lectures/tex/codes/lecture20.py
import numpy
import matplotlib
from matplotlib import pyplot
from scipy.optimize import fsolve
matplotlib.rcParams.update({'font.size':18, 'figure.figsize':(10,6)})
def relax_dirichlet(p, q, f, interval, bcs, N):
x, dx = numpy.linspace(interval[0], interval[1], N+2, retst... | StarcoderdataPython |
1618909 | from django.shortcuts import render_to_response
from django.template import RequestContext
# Create your views here.
def index(request,):
return render_to_response('blogs/index.html', context_instance=RequestContext(request))
| StarcoderdataPython |
33984 | # -*- coding: utf-8 -*-
"""
Microsoft-Windows-UAC-FileVirtualization
GUID : c02afc2b-e24e-4449-ad76-bcc2c2575ead
"""
from construct import Int8sl, Int8ul, Int16ul, Int16sl, Int32sl, Int32ul, Int64sl, Int64ul, Bytes, Double, Float32l, Struct
from etl.utils import WString, CString, SystemTime, Guid
from etl.dtyp import S... | StarcoderdataPython |
1740898 | import matplotlib.pyplot as plt
def pie_chart():
numbers = [40, 35, 15, 10]
labels = ['Python', 'Ruby', 'C++', 'PHP']
fig1, ax1 = plt.subplots()
ax1.pie(numbers, labels=labels)
plt.show()
if __name__ == '__main__':
pie_chart()
| StarcoderdataPython |
52675 | # tests/test_provider_MissionCriticalCloud_cosmic.py
# Automatically generated by tools/makecode.py (24-Sep-2021 15:14:40 UTC)
def test_provider_import():
import terrascript.provider.MissionCriticalCloud.cosmic
def test_resource_import():
from terrascript.resource.MissionCriticalCloud.cosmic import cosmic_a... | StarcoderdataPython |
4803856 | <filename>midi_transformer/modules/emb.py
import numpy as np
import torch
from torch import nn
import math
class Embeddings(nn.Module):
def __init__(self, n_token, d_emb):
super(Embeddings, self).__init__()
self.lut = nn.Embedding(n_token, d_emb)
self.d_emb = d_emb
def forward(self, x)... | StarcoderdataPython |
163519 | <gh_stars>1-10
import re
import os
import pandas as pd
import csv
import shutil
from circmimi.reference import gendb
from circmimi.reference.species import species_list
from circmimi.seq import parse_fasta
from circmimi.reference import resource as rs
from circmimi.reference.utils import cwd
from circmimi.reference.mir... | StarcoderdataPython |
65868 | from __future__ import annotations
from typing import Optional
from .node import Node
from .terms import Field, Star
from .utils import copy_if_immutable, ignore_copy
class Selectable(Node):
def __init__(self, alias: Optional[str]) -> None:
self.alias = alias
def as_(self, alias: str) -> Selectabl... | StarcoderdataPython |
3358630 | import numpy as np
data = [1, 2, 3]
arr = np.array(data)
data2 = arr * 10
print(data2) | StarcoderdataPython |
4815497 | <reponame>KXXH/SCU_JWC_assist
TEST_URL = "http://zhjw.scu.edu.cn/main/showPyfaInfo"
| StarcoderdataPython |
3201533 | <filename>macro/merge-hdf5.py
# -*- coding: utf-8 -*-
#! /usr/bin/env python3
import os
import argparse
import warnings
from itertools import chain
import glob
from collections import defaultdict
import numpy as np
import h5py
def _check_pathes(pathes, strict=True):
filtered = []
for path in pathes:
if... | StarcoderdataPython |
105106 | <reponame>pauldicarlo/PySailocus<gh_stars>0
'''
@author: <NAME>
@copyright: 2018 <NAME>
@license: MIT
@contact: https://github.com/sailocus/PySailocus
'''
from pysailocus.geometry.Point import Point
from pysailocus.geometry.Line import newPointOnLine, getSlope
########################################################... | StarcoderdataPython |
3205196 | <filename>Desafio063.py<gh_stars>0
#Escreva um pgm que leia um numero n inteiro qualquer e mostre na tela os n primeiros elementos de uma sequencia de Fibonacci. Ex: 0->1->1->2->3->5->8
#Sempre começa com 0 e 1 depois vem 1 2 3 5 8
print('{:@^40}'.format(' Sequência de Fibonacci '))
n = int(input('Quantos valores da s... | StarcoderdataPython |
1728487 | data = zip('1234', [1, 2, 3, 4, 5, 6])
print(data)
# 在转换为列表时,使用了zip对象中的全部元素,zip对象中不再包含任何内容
print(list(data))
# 如果需要再次访问其中的元素,必须重新创建zip对象
data = zip('1234', [1, 2, 3, 4, 5, 6])
print(tuple(data))
data = zip('1234', [1, 2, 3, 4, 5, 6])
# zip对象是可迭代的,可以使用for循环逐个遍历和访问其中的元素
for item in data:
print(item) | StarcoderdataPython |
2217 | <gh_stars>0
#!/usr/bin/env python3
"""
cidr_enum.py is a very simple tool to help enumerate IP ranges when being used with other tools
"""
import argparse
import netaddr
def enum_ranges(ranges, do_sort):
cidrs=[]
for r in ranges:
try:
cidrs.append(netaddr.IPNetwork(r))
except Exception as e:
print("Error... | StarcoderdataPython |
3395607 | from django.conf.urls import patterns, url
import views
urlpatterns = patterns('',
url(r'^(?P<contest_id>[0-9]+)/$', views.contest, name='contest'),
url(r'^(?P<contest_id>[0-9]+)/feedback$', views.feedback, name='feedback'),
url(r'^(?P<contest_id>[0-9]+)/signup$', views.signup, name='signup'),
url(r'^(?P... | StarcoderdataPython |
1716774 | <reponame>mlcommons/peoples-speech
# Adapter from second half of this answer: https://stackoverflow.com/a/44084038
class SparkListener:
def onApplicationEnd(self, applicationEnd):
pass
def onApplicationStart(self, applicationStart):
pass
def onBlockManagerRemoved(self, blockManagerRemove... | StarcoderdataPython |
3359175 | <reponame>normthenord/Discord_Bot
import discord
import random
import os
import dotenv
from dotenv.compat import to_env
dotenv.load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = '''NormTheNord's Bot Server'''
client = discord.Client()
@client.event
async def on_ready():
for guild in client.guilds:
... | StarcoderdataPython |
127008 | <gh_stars>10-100
from django.core.management.base import BaseCommand
from atlas import factories
class Command(BaseCommand):
help = "Load mock data"
def handle(self, *args, **options):
raise NotImplementedError("TODO")
ceo = factories.ProfileFactory.create(ceo=True)
print(f"Created {... | StarcoderdataPython |
158768 | <filename>tests/utils.py
import torch
from time import time
# convert dense matrix with explicit zeros to sparse matrix
def dense_to_sparse(w, mask, block):
Z = w.size(0)
ret = torch.empty((Z, mask.sum(), block, block), dtype=w.dtype, device=w.device)
nnz = mask.nonzero()
h, i, j = nnz[:, 0], nnz[:, 1], nnz[:,... | StarcoderdataPython |
3348805 | <reponame>mananeau/GPT2
import glob
import os
import time
from multiprocessing import Pool
import ftfy
import numpy as np
import tensorflow as tf
from tqdm import tqdm
import encoder
base_dir = "gs://pre-training-bucket/german_gpt2/pretraining_data/raw/shards_wiki" # Path to where your .txt files are located
files_p... | StarcoderdataPython |
1704087 | import pygame
from sprites.scenario import Asset
from extras.util import load_image, Image
from sprites.trucker import State
class Obstacle(Asset):
def fetch_image(self):
img = load_image(Image.TRASH)
return pygame.transform.scale(img, (64, 102))
def __init__(self, fy, sy):
... | StarcoderdataPython |
3328129 | <gh_stars>1-10
import os
import pandas as pd
from datetime import datetime
def stripTags(string):
if "<" in string and ">" in string and string.find("<") < string.find(">"):
iFirst = string.find("<")
iEnd = string.find(">")
strOut = string[:iFirst] + string[iEnd + 1:]
return strip... | StarcoderdataPython |
54816 | <filename>app.py
import logging
import os
from datetime import datetime, timedelta
import json
import sys
from flask import Flask, request, make_response, jsonify
from raven.contrib.flask import Sentry
import app_config
import hmac
from hashlib import sha1
from rq import Queue
from rq.job import Job
from worker impo... | StarcoderdataPython |
3361176 | global glb_dict
glb_dict = {}
def addItem(key, value):
glb_dict[key]=value
def getItem(key):
return glb_dict[key] | StarcoderdataPython |
3361027 | # Copyright 2014 - Mirantis, Inc.
# Copyright 2015 - StackStorm, Inc.
# Copyright 2017 - Brocade Communications Systems, Inc.
# Copyright 2018 - Extreme Networks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You ma... | StarcoderdataPython |
3380927 | import sys
import numpy as np
from scipy.special import erfc, erfcinv, expm1
def trandn(l,u):
## truncated normal generator
# * efficient generator of a vector of length(l)=length(u)
# from the standard multivariate normal distribution,
# truncated over the region [l,u];
# infinite values for 'u' a... | StarcoderdataPython |
1747381 | <reponame>nicthib/pyanthem
import os, random, sys, time, csv, pickle, re, pkg_resources, mido, h5py
os.environ['PYGAME_HIDE_SUPPORT_PROMPT']="hide"
from tkinter import *
from tkinter.ttk import *
from tkinter import filedialog as fd
from tkinter import simpledialog as sd
from ttkthemes import ThemedTk
from scipy.io i... | StarcoderdataPython |
197204 | <reponame>Juna2/grasp_detection
#!/usr/bin/env python
'''Converts Cornell Grasping Dataset data into TFRecords data format using Example protos.
The raw data set resides in png and txt files located in the following structure:
dataset/03/pcd0302r.png
dataset/03/pcd0302cpos.txt
'''
'''
1. Check variable "da... | StarcoderdataPython |
3297955 | <gh_stars>1-10
# 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 soundfile as sf
import torch
import torchaudio.compliance.kaldi as kaldi
class LogMelFeatureReader:
"""... | StarcoderdataPython |
158901 | """In memory storage classes."""
from __future__ import absolute_import
import logging
import threading
from collections import Counter
from six.moves import queue
from splitio.models.segments import Segment
from splitio.storage import SplitStorage, SegmentStorage, ImpressionStorage, EventStorage, \
TelemetryStor... | StarcoderdataPython |
174358 | # python3
# Copyright 2018 DeepMind Technologies Limited. 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 re... | StarcoderdataPython |
125212 | <filename>src/dataset/__init__.py
from .backend import Backend
from .dataset_ycb import YCB
from .dataset_generic import GenericDataset
__all__ = (
'GenericDataset',
'YCB',
'Backend'
) | StarcoderdataPython |
108102 | <gh_stars>1-10
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: Inverted_index_cn.py
Description : 爬取新浪财经网股票公司每日公告
Author : charl
date: 2018/9/5
-------------------------------------------------
Change Activity: 2018/9/5:
---------------------... | StarcoderdataPython |
95069 | <filename>vnpy/gateway/comstar/comstar_gateway.py
from datetime import datetime
from typing import Optional, Sequence, Dict
from enum import Enum
import pytz
from vnpy.event import EventEngine
from vnpy.trader.gateway import BaseGateway
from vnpy.trader.constant import (
Exchange,
Product,
Offset,
Orde... | StarcoderdataPython |
23958 | # 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 Jemalloc(AutotoolsPackage):
"""jemalloc is a general purpose malloc(3) implementation that... | StarcoderdataPython |
50918 | <reponame>yasuotakei/torrent_parser<filename>tests/test_create.py
from __future__ import unicode_literals
import collections
import hashlib
import io
import os.path
import unittest
from torrent_parser import TorrentFileParser, TorrentFileCreator
class TestCreate(unittest.TestCase):
TEST_FILES_DIR = os.path.join... | StarcoderdataPython |
3397423 | # -*- coding: utf-8 -*-
# MIT license
#
# Copyright (C) 2019 by XESS Corp.
#
# 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 rights
# to... | StarcoderdataPython |
171964 | import numpy as np
from .Layer import Layer
class Sign():
"""Sign Layer
f(x) = 1 for x > 0
f(x) = 0 for x = 0
f(x) = -1 for x < 0
Attributes:
input_shape = [N, C, H, W]: The shape of the input tensor
output_shape = [N, C, H, W]: The shape of the resulting output ... | StarcoderdataPython |
1750797 | # Write a function called "show_excitement" where the string
# "I am super excited for this course!" is returned exactly
# 5 times, where each sentence is separated by a single space.
# Return the string with "return".
# You can only have the string once in your code.
# Don't just copy/paste it 5 times into a single va... | StarcoderdataPython |
3267929 | # -*- coding: utf-8 -*-
import unittest
import pytest
from calvin.utilities.attribute_resolver import AttributeResolver
class AttributeResolverTester(unittest.TestCase):
def test_cpu_resources(self):
"""
Tests valid cpu resources in the indexed_public field
"""
att = AttributeRes... | StarcoderdataPython |
3393643 | import datetime
from math import ceil
from typing import List
from idact.core.config import ClusterConfig
from idact.core.retry import Retry
from idact.detail.allocation.allocation_parameters import AllocationParameters
from idact.detail.entry_point.fetch_port_info import fetch_port_info
from idact.detail.entry_point.... | StarcoderdataPython |
4837551 | <reponame>chrisbubernak/recipe-scrapers<filename>recipe_scrapers/simplyrecipes.py
from ._abstract import AbstractScraper
from ._utils import get_minutes, normalize_string, get_yields
class SimplyRecipes(AbstractScraper):
@classmethod
def host(cls):
return "simplyrecipes.com"
def title(self):
... | StarcoderdataPython |
3251297 | #!/usr/bin/env python3
import unittest
from dataclasses import dataclass
from typing import List, Optional, Sequence
from common import open_fixture
def abs(n: int) -> int:
if n < 0:
return -n
return n
def in_plane(a: int, b: int, n: int) -> bool:
if n < a and n < b:
return False
i... | StarcoderdataPython |
92968 | <filename>test_list.py
import time
# xrange = range
def test1():
c = 1000000
a = []
tm = time.time()
for i in xrange(c):
a.append(i)
print "python-append(1000000)", time.time() - tm
def test2():
c = 100000
a = []
tm = time.time()
for i in xrange(c):
a.insert(0, i)
print "python-insert(100000)", time.... | StarcoderdataPython |
3380661 | import tensorflow as tf
import numpy as np
from model import recon2recon
sess = tf.Session()
model = recon2recon(sess,'arch1_10','../../../data/processed/train_10_500/',
'../../../data/processed/test_10_500/',
'../../../data/processed/val_10_500/')
model.... | StarcoderdataPython |
121014 |
DASHBOARD = 'mydashboard'
DISABLED = False
ADD_INSTALLED_APPS = [
'openstack_dashboard.dashboards.mydashboard',
] | StarcoderdataPython |
3285366 | #!/usr/bin/env python3
# Copyright (c) 2020 The Bitcoin Unlimited developers
"""
Tests the electrum call 'blockchain.transaction.get'
"""
import asyncio
from test_framework.util import assert_equal, p2p_port
from test_framework.test_framework import BitcoinTestFramework
from test_framework.loginit import logging
from t... | StarcoderdataPython |
3269690 | from pylgbst.hub import TrainHub
from pylgbst import get_connection_gattool
from pylgbst.peripherals import Motor
import time
def callback(value):
print("Voltage: %s" % value)
conn = get_connection_gattool(hub_mac='90:84:2B:0F:D1:F8') #auto connect does not work
hub = TrainHub(conn)
for device in hub.periphera... | StarcoderdataPython |
117598 | # -*- coding: utf-8 -*-
from typing import Optional
import uvicorn
from fastapi import FastAPI, Query, Path, Response
from rarbg import *
tags_metadata = [
{
"name": "Search",
"externalDocs": {
"description": "Available Categories",
"url": "https://github.com/Apocalypsor/... | StarcoderdataPython |
1704236 | #!/usr/bin/env python
import npyscreen
import sys
import os
import mipexpect
import getopt
import mipass
import platform
import time
default_opt = \
"""% set dynamic socks proxy
% -D 1080
% forward a local port to a service at a remote port, e.g. vnc @ host:1
% -L 5901
% -L 5901:1.2.3.4:5901
% forward a remote port ... | StarcoderdataPython |
1635162 | from panda3d.core import *
from direct.distributed import DistributedObject
from direct.directnotify import DirectNotifyGlobal
from direct.interval.IntervalGlobal import *
class DistributedPresent(DistributedObject.DistributedObject):
notify = DirectNotifyGlobal.directNotify.newCategory('DistributedPresent')
... | StarcoderdataPython |
1769851 | from mythic_payloadtype_container.MythicCommandBase import *
import json
class PwdArguments(TaskArguments):
def __init__(self, command_line):
super().__init__(command_line)
self.args = {}
async def parse_arguments(self):
pass
class PwdCommand(CommandBase):
cmd = "pwd"
needs_ad... | StarcoderdataPython |
3268300 | from . import db
from utils import s_to_hms, hms_to_s
class OrderableMixin:
# TODO: implement testing
order = db.Column(db.Integer, index=True)
def _get_model_class(self):
for c in db.Model._decl_class_registry.values():
if (hasattr(c, '__tablename__') and
c.__ta... | StarcoderdataPython |
47006 | from typing import Callable
from putput.presets import displaCy
from putput.presets import iob2
from putput.presets import luis
from putput.presets import stochastic
def get_preset(preset: str) -> Callable:
"""A factory that gets a 'preset' Callable.
Args:
preset: the preset's name.
Returns:
... | StarcoderdataPython |
1691566 | <gh_stars>1-10
import discord
import re
from discord.ext.commands import command, Cog
import asyncio
from botutils.searchforlinks import get_ffn_url_from_query, get_ao3_url_from_query
from brain.ffn_brain import ffn_searcher
from brain.ao3_brain import ao3_searcher
class GSearchCog(Cog):
def __init__(self, bot):
... | StarcoderdataPython |
3251352 | <filename>ecomm_app/job_worker.py
#!/usr/bin/env python
import os
import logging
# import the app's tasks
import ecomm_app.ecommerce.tasks
name = "ecommerce-worker"
log = logging.getLogger(name)
log.info("Start - {}".format(name))
default_broker_url = "pyamqp://rabbitmq:rabbitmq@localhost:5672//"
default_backend_u... | StarcoderdataPython |
1713983 | <reponame>malvidin/assemblyline-service-yara
import json
import logging
import os
import re
import subprocess
import tempfile
from assemblyline.common.str_utils import safe_str
class YaraValidator(object):
def __init__(self, externals=None, logger=None):
if not logger:
from assemblyline.comm... | StarcoderdataPython |
1780456 | import json
import time
from threading import Thread
import requests
class HSocket:
"""
Client HSocket that communicates with the remote server HSocket
"""
def __init__(self, host, auto_connect=True): # type: (str, bool) -> None
"""
Initializes the HSocket
:pa... | StarcoderdataPython |
1657096 | <gh_stars>0
from unittest import TestCase
from artificial_idiot.game.game import Game
from artificial_idiot.game.state import State
from artificial_idiot.evaluation.evaluator_generator import (
NaiveEvaluatorGenerator, AdvanceEG
)
from artificial_idiot.util.json_parser import JsonParser
from artificial_idiot.search... | StarcoderdataPython |
33397 | import collections
import contextlib
import os.path
import typing
from contextlib import ExitStack
from pathlib import Path
from typing import BinaryIO, Dict, Optional, Generator, Iterator, Set
from mercury_engine_data_structures import formats, dread_data
from mercury_engine_data_structures.formats.base_resource impo... | StarcoderdataPython |
115849 | <gh_stars>0
"""
Unit test cases for items.py
"""
from .. import items
class TestItems:
def test_file_item(self):
file_item = items.FileItem()
file_item['name'] = 'foo'
assert file_item['name'] == 'foo', \
'Attribute "name" from FileItem does not retain the value.'
fil... | StarcoderdataPython |
88778 | <gh_stars>100-1000
import sys
import l_bp
from exceptions import MissingProbabilitiesException
class BreakpointInterval(object):
'''
Class for storing the range and probability distribution
of a breakpoint
'''
# Constant value for slop padding
SLOP_PROB = 1e-100
def __init__(self, chrom, ... | StarcoderdataPython |
1739784 | ####################################################### README #########################################################
# This file consists of function that convolves an image with a receptive field so that input to the network is
# close to the form perceived by our eyes.
##########################################... | StarcoderdataPython |
6483 | <gh_stars>0
#!/usr/bin/python
# mp4museum.org by <NAME> 2019
import os
import sys
import glob
from subprocess import Popen, PIPE
import RPi.GPIO as GPIO
FNULL = open(os.devnull, "w")
# setup GPIO pin
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)
GPIO.setup(13, GPIO.IN, pull_up_down ... | StarcoderdataPython |
1611553 | <filename>tests/v2/test_rspv.py
import json
from tests.v2.basecases import TestBaseCase
class RSpvsTestCase(TestBaseCase):
"""
test class for the comment endpoint
"""
def test_rspv_created_with_str(self):
"""Test if a comment is posted"""
auth_token = self.user_login()
respon... | StarcoderdataPython |
4812470 | import pytest
import json
from fastapi.security import OAuth2PasswordRequestForm
from app.api.v1.endpoints.authorization import login_for_access_token
from app.core import crud
from app.core.authorization import get_password_hash
from app.core.schemas.users import UserInDB
# @pytest.mark.parametrize(
# "email, p... | StarcoderdataPython |
29630 | import unittest
from unittest.mock import patch, Mock
from werkzeug.datastructures import FileStorage
import io
import json
from app import app
from app.models.base import db
from app.models.user import User
from app.auth.views import UserPassportphotoView
from app.auth import views
class AuthUploadPassportPhotoTes... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.