id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
3261527 | from typing import Union
def submit_event(key: str, value: Union[int, float, bool]):
"""
Register another event by a key and with a numeric value.
:param key: Identifier of the event.
:param value: Value of the event.
:return: None
"""
pass
| StarcoderdataPython |
3352411 | from django.conf.urls import url, include
from tastypie import fields
from tastypie.api import NamespacedApi
try:
from pieguard.authorization import GuardianAuthorization as AuthorizationClass
except ImportError:
from tastypie.authorization import DjangoAuthorization as AuthorizationClass
from tastypie.consta... | StarcoderdataPython |
3289003 | import lldb
from lldbsuite.test.lldbtest import *
from lldbsuite.test.decorators import *
import lldbsuite.test.lldbutil as lldbutil
import unittest2
class TestSwiftHealthCheck(TestBase):
NO_DEBUG_INFO_TESTCASE = True
mydir = TestBase.compute_mydir(__file__)
@swiftTest
@skipIfDarwinEmbedded
def ... | StarcoderdataPython |
1691318 | # coding: utf-8
import pprint
import six
from enum import Enum
class AbstractApplicationUserUpdate:
swagger_types = {
'name': 'str',
'request_limit': 'int',
'state': 'CreationEntityState',
}
attribute_map = {
'name': 'name','request_limit': 'requestLimit','state': '... | StarcoderdataPython |
113863 | from __future__ import annotations
import abc
from typing import Any, Iterable
import jsonpath_ng
from storage.var import BaseVar
class JsonPath(BaseVar[Any, Any]):
json_path: Any
def __init__(self, json_path):
self.json_path = json_path
@classmethod
def from_str(cls, json_path: str):
... | StarcoderdataPython |
3382824 | <reponame>mindspore-ai/models
# Copyright 2022 Huawei Technologies Co., Ltd
#
# 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 ... | StarcoderdataPython |
73031 | from configHandler import loadConfigData
from clientClass import Client
def main():
mainConfig = loadConfigData("../../config.json")
PORT = mainConfig["PORT"]
SERVER_IP = mainConfig["SERVER_IP"]
SERVER_ADDRESS = (SERVER_IP, PORT)
client = Client(PORT, SERVER_IP, SERVER_ADDRESS)
client.sen... | StarcoderdataPython |
149856 | <filename>ch09/modadmin.py
from moduser import User
class Admin(User):
"""This is a special user with special rights."""
def __init__(self, first_name, last_name, zip, age):
"""Initialize attributes of the parent class."""
super().__init__(first_name, last_name, zip, age)
self.privs = P... | StarcoderdataPython |
1675174 | <filename>01/aoc_d01p1.py
"""
--- Day 1: Inverse Captcha ---
The night before Christmas, one of Santa's Elves calls you in a panic. "The printer's broken! We can't print the Naughty or Nice List!" By the time you make it to sub-basement 17, there are only a few minutes until midnight. "We have a big problem," she says... | StarcoderdataPython |
132378 | # Non-dependent modules
import data
# Dependent modules
try:
import pymc
except ImportError:
print('-----------------------------------------------------------')
print('-----------------------------------------------------------')
print('WARNING: Not loading model in xastropy.fN \n Install pymc if yo... | StarcoderdataPython |
1721440 | text = "oi apareceu 2x batata 1x e oi 2x"
words = text.split()
summary = {word: words.count(word) for word in set(words)}
print(summary)
| StarcoderdataPython |
3226574 | <gh_stars>0
import json
import pytest
CONFIG = {
'api_endpoint': 'https://my.nsone.net',
# The api authentication key.
'api_key': 'testkey',
'metrics': {'qps': [{"test.com": None}], 'usage': [{"test.com": None}], 'pulsar': None, 'ddi': None},
}
CONFIG_NOMETRICS = {
'api_endpoint': 'https://test.c... | StarcoderdataPython |
1751752 | from .end_model import EndModel
from .label_model import (
LabelModel,
MajorityClassVoter,
MajorityLabelVoter,
RandomVoter,
)
from .tuners import RandomSearchTuner
__all__ = [
"EndModel",
"LabelModel",
"MajorityClassVoter",
"MajorityLabelVoter",
"RandomVoter",
"RandomSearchTuner... | StarcoderdataPython |
1785057 | <filename>Day 22 - Pong Game/my_global_constants.py
WIDTH, HEIGHT = 700, 480
X_WALL, Y_WALL = .9 * WIDTH / 2, .9 * HEIGHT / 2
ALIGN = 'center'
FONT = ('Arial', 20, 'normal')
GAME_SPEED = .001
BALL_SPEED = 5
BALL_PLAYER_DIST = 40
PLAYER_SPEED = 50
| StarcoderdataPython |
3320354 | <reponame>soarlab/gandalv
import re
import os
import sys
def invert_single_assertion(file_string,match,replacement,assertion):
"""Invert an assertion by replacing the old one, using the regex match"""
repl_string = assertion + '(' + match.group(1) + replacement + match.group(3) + ')'
result = file_string[:match... | StarcoderdataPython |
3307778 | <filename>Probability Statistics Intermediate/Calculating probabilities-134.py
## 2. Probability of renting bikes ##
import pandas
bikes = pandas.read_csv("bike_rental_day.csv")
# Find the number of days the bikes rented exceeded the threshold.
days_over_threshold = bikes[bikes["cnt"] > 2000].shape[0]
# Find the tota... | StarcoderdataPython |
104930 | <reponame>brkronheim/BNNs-for-SUSY
"""datagroup.py
Written by Karbo in the summer of 2017 and modified by Braden in the spring of 2019
This code reads the data output of the individual susyhit and prospino datafiles
and writes them into one document. The program takes the following three arguments:
* the name of ... | StarcoderdataPython |
3394632 | # -*- coding: utf-8 -*-
import os, time, logging, urllib, socket
from sentry_sdk.integrations.logging import LoggingIntegration
from requests import Session, Response, exceptions
from requests.adapters import HTTPAdapter
from requests.structures import CaseInsensitiveDict
from requests.utils import get_encoding_from_h... | StarcoderdataPython |
88397 | """
Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary
representation of that number. You can guarantee that input is non-negative.
Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
"""
def count_bit... | StarcoderdataPython |
3237683 | import os
import signal
import subprocess
import time
from unittest import TestCase
from scripttest import TestFileEnvironment
from .cli import setup_user_dir
from .meter import Meter
from .utils import create_executable
d = os.path.dirname(__file__)
PROJECT_PATH = os.path.abspath(os.path.join(d, os.pardir))
def cr... | StarcoderdataPython |
4829054 | <gh_stars>1-10
import FWCore.ParameterSet.Config as cms
process = cms.Process("CALIB")
process.MessageLogger = cms.Service("MessageLogger",
debugModules = cms.untracked.vstring(''),
QualityReader = cms.untracked.PSet(
threshold = cms.untracked.string('INFO')
),
cout = cms.untracked.PSet(
... | StarcoderdataPython |
3377828 | <reponame>steemfans/steem-lightdb<filename>transfer/user_relation.py
#!/usr/bin/python3
#encoding:UTF-8
import json, os, sys, time
import utils.TransferTasks as tasks
import utils.utils as utils
from utils.BlockProcess import BlockProcess as BlockProcess
import asyncio, aiomysql
from multiprocessing import Pool
from co... | StarcoderdataPython |
1656166 | import json
from aws_cdk import (
aws_apigateway,
aws_lambda,
aws_lambda_python,
aws_logs,
aws_s3,
aws_secretsmanager,
aws_ssm,
core,
)
class IntegrationStack(core.Stack):
def __init__(
self,
scope: core.Construct,
construct_id: str,
identifier: str... | StarcoderdataPython |
1683743 | #!/usr/bin/env python
import ari
import logging
import threading
logging.basicConfig(level=logging.ERROR)
client = ari.connect('http://localhost:8088', 'asterisk', 'asterisk')
# Note: this uses the 'extra' sounds package
sounds = ['press-1', 'or', 'press-2']
channel_timers = {}
class MenuState(object):
"""A s... | StarcoderdataPython |
4838358 | <filename>extras/test.py
import datetime
x = 2
def main():
#experimenting with scope
global x
print(x)
x = 3
#experimenting with datetimes and time deltas
startdate = datetime.datetime(2021,4,22,1,0,0)
startdate = datetime.datetime(9999,1,1,0,0,0)
enddate = datetime.datetime.now()
... | StarcoderdataPython |
1790721 | <gh_stars>1-10
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pickle
import time
import discord
from discord import Game
from discord.ext.commands import Bot
from lstm_network import create
NEURAL_NET = create()
BOT_PREFIX = '!'
# Get at https://discordapp.com/developers/applications/me
TOKEN = open('../Bot/... | StarcoderdataPython |
18659 | <reponame>anconaesselmann/LiveUnit
import unittest
import os
if __name__ == '__main__' and __package__ is None:
from os import sys, path
sys.path.append(path.abspath(path.join(__file__, "..", "..")))
sys.path.append(path.abspath(path.join(__file__, "..", "..", "..", "classes_and_tests")))
from php.functio... | StarcoderdataPython |
3399663 | # ===-- toCSV.py - CSV converter tool --------------------------*- Python -*-===
#
# Part of the LOMP project, under the Apache License v2.0 with LLVM Exceptions.
# See https:llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#
# ===-------------------------------... | StarcoderdataPython |
3275408 | <filename>chapter1/hello-world.py
# -*- coding: utf-8 -*-
# Exercise 1.2
# Author: <NAME>
print("Hello, World!")
"""
Trial run
python3 hello-world.py
Hello, World!
"""
| StarcoderdataPython |
1709933 | <gh_stars>0
import grpc
import random
import time
from absl import app
from absl import flags
from concurrent import futures
from lib import telemetry
FLAGS = flags.FLAGS
flags.DEFINE_integer('grpc_port', 50090, 'Port for gRPC services.')
def main(argv):
server = grpc.server(futures.ThreadPoolExecutor(max_worke... | StarcoderdataPython |
16555 | # -*- coding: utf-8 -*-
"""
1556. Thousand Separator
Given an integer n, add a dot (".") as the thousands separator and return it in string format.
Constraints:
0 <= n < 2^31
"""
class Solution:
def thousandSeparator(self, n: int) -> str:
res = ""
str_n = str(n)
count = 0
ind = ... | StarcoderdataPython |
3306439 | import unittest
import logging
import tempfile
import os
import docker
from .context import WDL
class TestTaskRunner(unittest.TestCase):
def setUp(self):
logging.basicConfig(level=logging.DEBUG, format='%(name)s %(levelname)s %(message)s')
self._dir = tempfile.mkdtemp(prefix="miniwdl_test_taskrun_... | StarcoderdataPython |
92754 | from __future__ import annotations
from typing import TYPE_CHECKING, Dict, List, Optional, Union
import datetime
from ..utils import Snowflake
from .embed import Embed
from .threads import Thread
from .attachments import Attachment
from .components import ActionRow
if TYPE_CHECKING:
from ..state import State
... | StarcoderdataPython |
1758048 | # Generated by Django 3.2.6 on 2021-09-20 19:47
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('digiapp', '0002_auto_20210918_0949'),
]
operations = [
migrations.RenameField(
model_name='good... | StarcoderdataPython |
84208 | import argparse
import sys
import mdtraj as md
import numpy as np
import matplotlib.pyplot as plt
from numpy import linalg as LA
from sklearn import cluster, datasets
from scipy.optimize import minimize
from sklearn.neighbors import kneighbors_graph
from sklearn.manifold import SpectralEmbedding
from scipy.spatial.dist... | StarcoderdataPython |
1782901 | <filename>Python/sniffer.py
from scapy.all import *
# Task 1A: A simple sniffing program that was given to us.
def got_packet(pkt):
pkt.show()
print('Sniffing...')
pkt = sniff(iface='enp0s3', filter='icmp', prn=got_packet)
| StarcoderdataPython |
1660938 | <gh_stars>100-1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AlipayMerchantWeikeBillModifyModel(object):
def __init__(self):
self._actual_service_charge = None
self._alipay_trans_serial_no = None
self._bill_month ... | StarcoderdataPython |
1714819 | <filename>PercorsoDati/Lab3-4/etl/utils.py<gh_stars>10-100
import numpy as np
@np.vectorize
def remove_dollar(label: str):
return float(label.replace("$", "").replace(",", ""))
| StarcoderdataPython |
133838 | """
Convert tabular data from
Tabular Benchmarks for Joint Architecture and Hyperparameter Optimization
<NAME> <NAME>
https://arxiv.org/pdf/1905.04970.pdf.
"""
import urllib
import tarfile
from pathlib import Path
from typing import Optional
import pandas as pd
import numpy as np
import ast
import h5py
from syne_t... | StarcoderdataPython |
1607786 | import torch
from torch.utils.data.dataset import Dataset
import numpy as np
import pandas as pd
import cv2
from albumentations import Compose, Flip, RandomScale, ShiftScaleRotate, RandomBrightnessContrast, Rotate, RandomCrop, CenterCrop, Resize, Blur, CLAHE, Equalize, Normalize, OneOf, IAASharpen, IAAEmboss
from sklea... | StarcoderdataPython |
1767453 | #!/usr/bin/env python3
import json
import datetime
import os.path
from franken import crane, trivy
with open("conf/scan.json") as config_file:
config_data = json.load(config_file)
result = {}
date_str = datetime.datetime.now().strftime("%Y%m%d%H")
output_home = os.path.join("output", "scan-" + date_str)
if not o... | StarcoderdataPython |
3376588 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the migratoryBirds function below.
def migratoryBirds(arr):
d = {}
max_ = 0
a = []
for i in arr:
if i in d.keys():
d[i] += 1
else :
d[i] = 1
for i in d:
... | StarcoderdataPython |
99986 | <gh_stars>10-100
from astrometry.util.fits import fits_table
from glob import glob
import os
import numpy as np
'''After DR5 we moved a bunch of CP input files that were in a
NonDECaLS-DR5 directory into NonDECaLS, and also rationalized some
duplicate files, including deleting some "v1" CP files in favor of
"v2" versi... | StarcoderdataPython |
1777298 | <gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 28 16:38:27 2018
@author: song
"""
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 12 20:49:19 2018
@author: song
"""
# -*- coding: utf-8 -*-
"""
Created on Tue April 3 10:56:53 2018
Convolutional VAriational Au... | StarcoderdataPython |
3236864 | #!/usr/bin/python2.7
# Copyright 2010 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.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | StarcoderdataPython |
4804203 | from gqa_dataset import *
def calc_statistics():
with open('{}/full_vocab.json'.format('meta_info/'), 'r') as f:
vocab = json.load(f)
ivocab = {v: k for k, v in vocab.items()}
with open('{}/answer_vocab.json'.format('meta_info/'), 'r') as f:
answer = json.load(f)
inv_answer = ... | StarcoderdataPython |
1610444 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2013-2014 eNovance Inc. 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/L... | StarcoderdataPython |
1707036 | <filename>instr_helpers.py<gh_stars>1-10
#!/usr/bin/python3
def isreg(d):
if type(d) == dict:
return 'register' in d.keys()
return False
def is_half_width(r):
if 'half_width' in r.keys():
if r['half_width']:
return 'w'
return ''
def safe_pullregs(operands):
rs = []
... | StarcoderdataPython |
3393045 | <gh_stars>0
import os
import sys
import time
import json
import unittest
from jc.exceptions import ParseError
import jc.parsers.stat_s
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
# Set the timezone on POSIX systems. Need to manually set for Windows tests
if not sys.platform.startswith('win32'):
os.envir... | StarcoderdataPython |
98720 | from decimal import Decimal as D
from django.db.models import Sum
from django.test import TestCase, TransactionTestCase
from oscar.test.factories import UserFactory
import mock
from oscar_accounts import facade, exceptions
from oscar_accounts.models import Account, Transfer, Transaction
from oscar_accounts.test_facto... | StarcoderdataPython |
1745351 | <gh_stars>1-10
import nose
import angr
import logging
l = logging.getLogger("angr_tests.managers")
import os
location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries/tests'))
addresses_fauxware = {
'armel': 0x8524,
'armhf': 0x104c9, # addr+1 to force thumb
#'i386': 0x804... | StarcoderdataPython |
1764561 | import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
df_forest = pd.read_excel(r'/Users/talen/Downloads/Other Datasets/Forest.xlsx')
#Checking whether there is missing data in the dataframe
print(df_forest.isnull().sum().sum())
#Use the first column — class as the result, wher... | StarcoderdataPython |
1605961 | <filename>tax/python/antchain_sdk_tax/models.py
# -*- coding: utf-8 -*-
# This file is auto-generated, don't edit it. Thanks.
from Tea.model import TeaModel
from typing import List
class Config(TeaModel):
"""
Model for initing client
"""
def __init__(
self,
access_key_id: str = None,
... | StarcoderdataPython |
127675 | from model.exam import ExamData
from dbjudge.connection_manager.manager import Manager
from dbjudge import squema_recollector, exceptions
from PyQt5.QtCore import pyqtSlot, QItemSelectionModel
class Exam_controller():
def __init__(self, selection_view, exam_view, results_view):
self.selection_view = sele... | StarcoderdataPython |
1719708 | from utils import *
from rtid_out_info import RtidOutInfo
from rtid_config import RTIDConfig
from content_manager import ContentManager
from datetime import datetime
from os import path, makedirs
import json
import praw
import secret
import sys
class RTID(Logger):
def __init__(self, rtid_config: RTIDConfig):
super(... | StarcoderdataPython |
3244691 | <filename>bot/cogs/error_handler.py
import datetime
import logging
from concurrent.futures._base import TimeoutError
import sentry_sdk
import discord
from discord.ext import commands
from bot.bot_client import Bot
from bot.utils.context import Context
class CommandErrorHandler(commands.Cog):
def ... | StarcoderdataPython |
3821 | <filename>Py3Challenges/saves/challenges/c6_min.py
"""
To master this you should consider using the builtin-``min``-function.
"""
from ...challenge import Challenge
from random import randint
x = []
for _ in range(randint(2, 10)):
x.append(randint(1, 100))
intro = f"You have to print the lowest value of {', '.jo... | StarcoderdataPython |
3366746 | from plenum.test.view_change.helper import view_change_in_between_3pc
def test_view_change_in_between_3pc_all_nodes(txnPoolNodeSet, looper,
wallet1, client1):
"""
- Slow processing 3PC messages for all nodes
- do view change
"""
view_change_in_between_... | StarcoderdataPython |
1766329 | """Contains a Graph Attention Network v2 and associated layers."""
from typing import Any, Callable, Optional, Tuple, Union
import tensorflow as tf
from tensorflow_gnn.graph import graph_constants as const
from tensorflow_gnn.graph import graph_tensor as gt
from tensorflow_gnn.graph import graph_tensor_ops as ops
from... | StarcoderdataPython |
78469 | <reponame>rasapala/OpenVINO-model-server<gh_stars>0
#
# Copyright (c) 2018 Intel Corporation
#
# 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/LIC... | StarcoderdataPython |
1667441 | # turns out the database was probably never read properly!
# as some lines have a line ending after a tab!
foo = open('dhcp-db.txt','r').readlines()
bar = [x.replace('\n','') for x in foo]
zot = [x.split('\t') for x in bar]
l = [len(x) for x in zot if len(x) != 4]
print('l = (should be header only)',l)
if len(l) > 1:
... | StarcoderdataPython |
1678195 | import networkx as nx
import pandas as pd
# # load baseline adjacency matrix
# df_baseline_1 = pd.read_excel('donor_receiver_2019.xlsx', sheet_name='donor_2019', index_col=0)
# print(df_baseline_1.head())
# df_baseline_1 = df_baseline_1.astype(int)
# df_baseline_2 = pd.read_excel('donor_receiver_2019.xlsx', sheet_name... | StarcoderdataPython |
1730998 | from .core import Metrika
| StarcoderdataPython |
1777151 | import cv2
import numpy as np
import tensorflow as tf
class Tracker:
view_a = None
view_b = None
start_pos = np.asarray([0, 0])
dist_thresh = 0
infer = True
def __init__(self, frame, bbox, color):
self.tracker = cv2.TrackerKCF_create()
self.color = color
self.tracker.i... | StarcoderdataPython |
112475 | # GENERATED BY KOMAND SDK - DO NOT EDIT
from .add_feed.action import AddFeed
from .add_watchlist.action import AddWatchlist
from .blacklist_hash.action import BlacklistHash
from .delete_feed.action import DeleteFeed
from .delete_watchlist.action import DeleteWatchlist
from .get_binary.action import GetBinary
from .isol... | StarcoderdataPython |
3230611 | import pandas as pd
import pickle
from nltk.corpus import stopwords
from nltk.stem import SnowballStemmer
from nltk.tokenize import RegexpTokenizer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from scipy import sparse
import re
import gensim
import m... | StarcoderdataPython |
84370 | <gh_stars>10-100
# Copyright (c) 2018-present, Royal Bank of Canada.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from abc import ABCMeta
import torch
from advertorch.utils import replicate_input
class Attack(obje... | StarcoderdataPython |
4802041 |
from metatester import Base
class Derived(Base):
def bar(self):
return 'bar'
d = Derived()
print(d.foo()) | StarcoderdataPython |
3234068 | import time
import typing
import requests
from jose import jwt
import baseline_cloud.core.aws.cognito
import baseline_cloud.core.aws.secrets
import baseline_cloud.core.aws.ssm
from baseline_cloud.core import aws
from baseline_cloud.core.config import config
def create(sub: str, minutes: typing.Optional[int] = 0, ho... | StarcoderdataPython |
33800 | <filename>tests/test_local_tile_server.py
from os import path
from unittest import mock
from common_for_tests import make_test_raster
from tornado.testing import gen_test, AsyncHTTPTestCase
from tornado.concurrent import Future
import telluric as tl
from telluric.util.local_tile_server import TileServer, make_app, Til... | StarcoderdataPython |
4835113 | import unittest
from businessPage.loginPage import LoginPage
from common.myunit import MyUnit
from common.selenium_driver import logger
class TestLoginPage(MyUnit):
csv_file = '../data/user.csv'
def testLogin01(self):
l = LoginPage(self.driver)
row = l.get_csv_data(self.csv_file,1)
... | StarcoderdataPython |
3249229 | import pprint
import svn.remote
import svn.exception
import platform
import struct
import os
import curses
import time
import sys
import signal
import argparse
import tempfile
from subprocess import call
import logging
parser = argparse.ArgumentParser()
parser.add_argument('-url', dest = 'svn_url', help = 'input svn r... | StarcoderdataPython |
1783245 | import lib.calc_commands
import lib.calc_history
import lib.calc_operations | StarcoderdataPython |
1789151 | from xdump.base import BaseBackend
from xdump.cli.utils import apply_decorators, import_backend
def test_import_backend():
backend_class = import_backend("xdump.sqlite.SQLiteBackend")
assert issubclass(backend_class, BaseBackend)
def test_apply_decorators():
def dec1(func):
func.foo = 1
... | StarcoderdataPython |
1686047 | <reponame>vivian-dai/Competitive-Programming-Code
def base_convert(b):
ret = ""
if b[0] >= 'A' and b[0] <= 'Z':
a = 0
ind = len(b) - 1
for c in b:
a += (ord(c) - ord('A') + 1)*pow(26, ind)
ind -= 1
ret = str(a)
else:
b = int(b)
while b ... | StarcoderdataPython |
3292061 | <filename>wradlib/tests/__init__.py<gh_stars>0
# Copyright (c) 2011-2018, wradlib developers.
# Distributed under the MIT License. See LICENSE.txt for more info.
"""
wradlib_tests
=============
"""
from . import test_adjust # noqa
from . import test_atten # noqa
from . import test_clutter # noqa
from . import tes... | StarcoderdataPython |
68762 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# pylint: disable=missing-docstring
import json
from datetime import date, datetime
from .common import common
class jsonl(object):
""" jsonl exporter plugin.
As opposed to json exporter jsonl serializes messages as one JSON object per line, not as
one giant ... | StarcoderdataPython |
1606168 | import unittest
from starlette.testclient import TestClient
from policyguru.main import app
client = TestClient(app)
class TestMain(unittest.TestCase):
def test_root(self):
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"msg": "Hello World"}
| StarcoderdataPython |
3382773 | import numpy as np
import metrosampler.sampler as sr
import metrosampler.posterior as sp
import metrosampler.constraints as sc
import matplotlib as mpl
mpl.use('TkAgg')
import matplotlib.pyplot as plt
def generate_samples():
# Create distribution and initial covariance matrix for proposal
constraints = sc.C... | StarcoderdataPython |
14610 | #!/usr/bin/env python
#
# pyFlow - a lightweight parallel task engine
#
# Copyright (c) 2012-2017 Illumina, Inc.
# 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 source ... | StarcoderdataPython |
3311932 | <gh_stars>0
# This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY;... | StarcoderdataPython |
3369755 | import argparse
from youtube_uploader_selenium import YouTubeUploader
from typing import Optional
import json
import os
if __name__ == "__main__":
with open('final_sleep_video.json',encoding='utf8') as json_file:
videos = json.load(json_file)
for v in videos:
v_src = v['path']
... | StarcoderdataPython |
3233230 | <gh_stars>10-100
#!/usr/bin/env python3
import requests
import json
from enum import Enum
PUBLIC_API_BASE_URL = "http://localhost:8080/api"
PRIVATE_API_BASE_URL = "http://localhost:9090/api"
HEADERS = {'Content-Type': 'application/json'}
class Scope(Enum):
PUBLIC = 0
PRIVATE = 1
def api_url(path, scope=Scope.... | StarcoderdataPython |
3237754 | from typing import Dict
from typing import List
from typing import Union
class Item:
type = 'item'
def __init__(self, name: str, weight: int, size: int) -> None:
self.name = name
self.weight = weight
self.size = size
self.equippable = False
self.equippable_pos... | StarcoderdataPython |
1724498 | from decimal import Decimal
from datetime import datetime
from mockdatagen.helpers import MockGen
from money.models import CurrencyData, Denomination, VAT, VATPeriod, AccountingGroup
@MockGen.register
class CurrencyDataGen:
model = CurrencyData
@staticmethod
def func():
CurrencyData.objects.get_... | StarcoderdataPython |
3247458 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import click
from jira import JIRAError
from prettytable import PrettyTable
from jirainfo import helpers
from jirainfo.jirahelper import JiraHelper
import time
ISSUE_TYPE_MAPPING = {
'features': ['task', 'aufgabe', 'story'],
'bugs': ['bug']
}
@click... | StarcoderdataPython |
3295581 | <gh_stars>0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is subject to the terms and conditions defined in
# file 'LICENSE.md', which is part of this source code package.
#
from kubernetes.utils import filter_model
class NodeAddress(object):
"""
https://kubernetes.io/docs/api-reference/v1/defi... | StarcoderdataPython |
110805 | # Generated by Django 3.1.2 on 2020-10-28 20:29
import cloudinary.models
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0012_alter_user_first_name_max_length'... | StarcoderdataPython |
894 | <reponame>guilhermebc/docker-playground<filename>email-worker-compose/app/sender.py
import psycopg2
import redis
import json
from bottle import Bottle, request
class Sender(Bottle):
def __init__(self):
super().__init__()
self.route('/', method='POST', callback=self.send)
self.fila = redis.... | StarcoderdataPython |
1797852 | <reponame>Ostnor/DoS_SDN<filename>src/main/python/attack_prevention/DoSAttackProtection.py
#!/usr/bin/env python
import logging
from ..PythonServer import PacketStreamerHandler
class DoSAttackProtection(object):
def __init__(self):
self.logger = PacketStreamerHandler.log | StarcoderdataPython |
3305142 | <filename>rrd/config.py
# -*-coding:utf8-*-
# app config
import os
LOG_LEVEL = os.environ.get("LOG_LEVEL", 'WARNING')
SECRET_KEY = os.environ.get("SECRET_KEY", "secret-key")
PERMANENT_SESSION_LIFETIME = os.environ.get("PERMANENT_SESSION_LIFETIME", 3600 * 24 * 30)
SITE_COOKIE = os.environ.get("SITE_COOKIE", "open-falco... | StarcoderdataPython |
4808762 | <reponame>jbushago/GamestonkTerminal<filename>custom_pre_commit/check_doc.py<gh_stars>1-10
import argparse
import os
import sys
from typing import List, Optional
def clean_input(text: str) -> List[str]:
text = text.replace(" str ", "")
text = text.strip()
text = text.replace("CHOICES_COMMANDS", "")
te... | StarcoderdataPython |
196972 | # This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
import binascii
import os
import pytest
from cryptography.ha... | StarcoderdataPython |
3329059 | <filename>web/work/model.py<gh_stars>0
# -*- coding: utf-8 -*-
# @File : model.py
# @Coder : Einsfat
# @Date : 2021/7/14 23:18
from sqlalchemy import Column, TIMESTAMP, String, Integer, BigInteger, func
from web.common.db.db_base import Base
class BaseModel(Base):
"""
基础Model模型对象
"""
__abstract_... | StarcoderdataPython |
160243 | import datetime
import os
import copy
import json
import numpy as np
from pytz import timezone
from gamified_squad import GamifiedSquad
from agent import CustomAgent
import generic
import evaluate
SAVE_CHECKPOINT = 100000
def train():
time_1 = datetime.datetime.now()
config = generic.load_config()
env =... | StarcoderdataPython |
1753071 | import uuid
from typing import List, Dict
import unittest
from selfhost_client import SelfHostClient, UserType, PolicyType, UserTokenType, CreatedUserTokenResponse
class TestIntegrationUsersClient(unittest.TestCase):
"""
Run these tests individually because Self-Host will return HTTP 429 Too Many Requests o... | StarcoderdataPython |
3261597 | <reponame>qeedquan/misc_utilities
from keras.datasets import mnist
from PIL import Image
import os
folder = "mnist_data/"
try:
os.mkdir(folder)
except:
pass
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
hist = dict.fromkeys(test_labels, 0)
for i in range(len(test_images)):
... | StarcoderdataPython |
6570 | # -*- coding: utf-8 -*-
"""This python module aims to manage
`DokuWiki <https://www.dokuwiki.org/dokuwiki>`_ wikis by using the
provided `XML-RPC API <https://www.dokuwiki.org/devel:xmlrpc>`_. It is
compatible with python2.7 and python3+.
Installation
------------
It is on `PyPi <https://pypi.python.org/pypi/dokuwik... | StarcoderdataPython |
3390659 | """Flood Warning System
returns either, "high" "moderate" or "low" risk of flooding
probability of flooding is computed via a range of inputs,
current level over the typical maximum, the higher the current
level the higher the assumed risk of flooding (if in flood flood level high)
relative level, if the level is re... | StarcoderdataPython |
3286074 | from main import CMDApp
def tF(args):
print(f't {args}')
def cF(args):
print(f'c {args}')
def gF(args):
print(f'g {args}')
app = CMDApp()
app.setCommands({
"t": tF,
"c": cF,
"g": gF
})
app.setMinimumArgs({
"t": 3,
"c": 2
})
app.setHelp({
"t": "The t command",
"c": "The c command",
"g": "The g command"... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.