id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
3378453 | <reponame>wang90063/MRO-Asyn-RL
import matplotlib.pyplot as plt
import numpy as np
import glob
path ='/home/cui-group-wz/plot/RL/HO'
# path1 = '/home/cui-group-wz/Documents/Code/MRO-Asyn-RL/plot/3gpp/HO'
path2 = '/home/cui-group-wz/plot/BAN/HO'
path3 ='/home/cui-group-wz/plot/RLonline/HO'
allFiles = glob.glob(path + "... | StarcoderdataPython |
3206942 | # 功能 用ICMP协议探测主机是否在线
# 用法 python3 ping_scan.py [ip]
from scapy.all import *
import sys
import getopt
from random import randint
def ping_scan(host):
# 参数准备
ip_id = randint(0,65535)
icmp_seq = randint(0,65535)
icmp_id = randint(0,65535)
# 构建发送ICMP包
icmp = IP(dst=host,ttl=64,id=ip_id)/ICMP(seq=icm... | StarcoderdataPython |
1738663 | import pandas as pd
import re
#SOCCOM = ["infoadd, 'subject'; 'body'; 'msgcat'; 'concern(optional)'; 'code (optional)'; 'tag (optional)'",
#"handover, No# 'subject'; 'body';'msgcat'; 'concern(optional)'; 'code (optional)'; 'tag (optional)",
#"query, 'text/code/category', date(optional)"]
#def insert_msg(dt, src, sub... | StarcoderdataPython |
1646335 | #
# Copyright 2013 Free Software Foundation, Inc.
#
# This file is part of GNU Radio.
#
# This 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; either version 3, or (at your option)
# any later version.
#
# Thi... | StarcoderdataPython |
1709992 | from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import os
import json
import glob
import h5py
import numpy as np
import pickle
from PIL import Image, ImageOps
import torch
from torchmeta.utils.data.task import Task, ConcatTask, SubsetTask
from collections i... | StarcoderdataPython |
1691081 | """Debug events handler: test [un-]load modules notification"""
import unittest
import target
import pykd
import fnmatch
import testutils
class ModuleLoadHandler(pykd.eventHandler):
"""Track load/unload module implementation"""
def __init__(self, moduleMask):
pykd.eventHandler.__init__(self)
... | StarcoderdataPython |
3344154 | <filename>ET/alfred/utils/eval_util.py
import os
import json
import queue
import torch
import shutil
import filelock
import numpy as np
from PIL import Image
from termcolor import colored
from alfred.gen import constants
from alfred.env.thor_env import ThorEnv
from alfred.nn.enc_visual import FeatureExtractor
from al... | StarcoderdataPython |
4827719 | <filename>app/exceptions.py
class PlayBooksFolderNotFound(Exception):
pass
| StarcoderdataPython |
3218892 | import pandas as pd
from pathlib import Path
import sys
import numpy as np
import re
# negotiation units
nego_units = ('<sep>', '<end>', '<greet>', '<agree>', '<disagree>', '<inquire>', '<propose>', '<inform>', '<unk>')
# converter
index_to_phrases = {index : unit for index, unit in enumerate(nego_units)}
def con... | StarcoderdataPython |
1686205 | class ClassX:
def __init__(self) -> None:
self.g = 3
def k(self, u):
return u
def y(self):
m = self.k()
return m
def tr():
return 2
s = ClassX()
print(s.y())
r = "soy"
s.k(u=r) | StarcoderdataPython |
3267224 | <reponame>panagiks/cursed-parrot
import uuid
from aiohttp import web
from aiohttp_session import get_session
from aiohttp.web_response import json_response
from passlib.hash import sha512_crypt
# sha512_crypt.hash(password)
async def user_create(request):
# TODO: Make sure user doesn't already exist
try:
... | StarcoderdataPython |
4832717 | from .conftest import wait_until, wait_until_available
from rancher import ApiError
from .common import random_str
import time
def test_project_catalog_creation(admin_mc, remove_resource,
user_mc, user_factory, admin_pc,
admin_cc):
client = admin... | StarcoderdataPython |
162300 | <gh_stars>1-10
from flask import Flask, request
from flask_cors import CORS, cross_origin
import logging
import traceback
import aux
# WSGI application name
app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'
# Data archive storage location
datapath = aux.get_config('storage')
# Conf... | StarcoderdataPython |
153562 | <reponame>skjerns/mne-bids<gh_stars>10-100
"""
.. _bidspath-example:
===============================
10. An introduction to BIDSPath
===============================
BIDSPath is MNE-BIDS's working horse when it comes to file and folder
operations. Learn here how to use it.
"""
# Author: <NAME> <<EMAIL>>
#
# License: B... | StarcoderdataPython |
1686519 | <reponame>pombreda/pkgcore<gh_stars>1-10
# Copyright: 2011 <NAME> <<EMAIL>>
# License: GPL2/BSD 3 clause
import threading
import Queue
from snakeoil import compatibility
from snakeoil.demandload import demandload
demandload(
'snakeoil.process:get_proc_count',
)
def reclaim_threads(threads):
for x in threads... | StarcoderdataPython |
3207499 | # See LICENSE.Cambridge for license details.
# script to search for block RAMs to update
import sys
import re
# check arguments
if len(sys.argv) != 5:
print("Wrong arguments\nbmm_gen in out bus-width mem-size")
exit()
# read the ramb search result
f = open(sys.argv[1], "r")
lines = f.readlines()
f.close()
r... | StarcoderdataPython |
3343683 | #!/usr/bin/env python2.4
#
#
#
# $Header: /opt/cvs/VSTutorial/prepare_ligand4.py,v 1.2 2007/01/30 01:05:46 rhuey Exp $
#
import os
from MolKit import Read
from AutoDockTools.MoleculePreparation import AD4LigandPreparation
if __name__ == '__main__':
import sys
import getopt
def usage():
"Pri... | StarcoderdataPython |
4823353 | <filename>contests_atcoder/abc001/abc001_b.py<gh_stars>0
m = int(input())
if m < 100:
print("00")
elif m <= 5000:
print(str(m // 100).zfill(2))
elif m <= 30000:
print(m // 1000 + 50)
elif m <= 70000:
print((m // 1000 - 30) // 5 + 80)
else:
print("89") | StarcoderdataPython |
1626639 | <gh_stars>0
import numpy as np
import random
import re
import pickle
import os
import copy
import sys
class NERLoader:
def load(self, texts, _labels, labels2idx, tokenizer ,max_position_embeddings=512):
idx2labels = {v: k for k, v in labels2idx.items()}
original_texts = copy.deepcopy(t... | StarcoderdataPython |
1688281 | <gh_stars>0
# Author: <NAME>
import unittest
from kernel.type import TVar, Type, TFun, boolT
from kernel.term import Var, Const, Comb, Abs, Bound, Term
from kernel.thm import Thm
from logic import logic
from logic import nat
from logic import list
from logic import set
from logic import basic
from logic import functi... | StarcoderdataPython |
1702001 | from __future__ import print_function
import os
import argparse
import torch
import torch.backends.cudnn as cudnn
import numpy as np
from data import cfg
from layers.functions.prior_box import PriorBox
from utils.nms_wrapper import nms
#from utils.nms.py_cpu_nms import py_cpu_nms
import cv2
from models.faceboxes import... | StarcoderdataPython |
15752 | import scrapy
from locations.items import GeojsonPointItem
from urllib.parse import urlencode
from scrapy.selector import Selector
from locations.hours import OpeningHours
Days = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"]
class DollaramaSpider(scrapy.Spider):
name = "dollarama"
item_attributes = {"brand": "D... | StarcoderdataPython |
65478 | <filename>generate_random.py
from fractions import Fraction
import numpy as np
from numpy.random import randint
import sys
class RationLP:
def __init__(self, A, b, c):
self.A = [[Fraction(x) for x in row] for row in A]
self.b = [Fraction(x) for x in b.flat]
self.c = [Fraction(x) for x in c... | StarcoderdataPython |
3214614 | def calcular_precio_producto(coste_producto):
'''
(float)-> float
#casos de prueba
>>> calcular_precio_producto(200)
300.0
>>> calcular_precio_producto(300)
450.0
>>> calcular_precio_producto(600)
900.0
:param coste_producto:
:return:
'''
# procesos //
cos... | StarcoderdataPython |
3309287 | <gh_stars>0
# -*- coding: utf-8 -*-
# @Author: <NAME>
# @Date: 2018-10-11 23:06:10
# @Last Modified by: <NAME>
# @Last Modified time: 2018-10-12 10:48:46
# @Reference: https://stackoverflow.com/questions/3173320/text-progress-bar-in-the-console
from time import sleep
def print_progress_bar(iteration, total, prefi... | StarcoderdataPython |
1799817 | <filename>leetcode/3-hard/3-treegraph/1-wordladder/word_ladder.py<gh_stars>0
import sys
import itertools
from collections import deque, defaultdict
class Node(object):
"""Class that represents a node (vertex) in a graph"""
def __init__(self, name=None):
"""
Constructor
@param name: i... | StarcoderdataPython |
1761748 | <reponame>b8raoult/magics
# (C) Copyright 1996-2016 ECMWF.
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
# In applying this licence, ECMWF does not waive the privileges and immunities
# granted to it by virtue of... | StarcoderdataPython |
4842275 | <gh_stars>0
from asyncio import sleep, get_event_loop
from contextvars import copy_context
from functools import wraps, partial
from itertools import count
from random import randint
from typing import Tuple, Callable, TypeVar, Awaitable
T = TypeVar("T")
def retry(attempts: int = 10, delay_range: Tuple[int, int] = (... | StarcoderdataPython |
131602 | <reponame>mrbartrns/swacademy_structure
# BOJ 6148번
import sys
from collections import deque
def solve(sum_heights: int):
minimum = -1
# 기저 사례
if len(cows) == 1:
return cows[0]
if sum_heights < top:
minimum = get_value(sum_heights)
return minimum - top
last = cows.poplef... | StarcoderdataPython |
3256899 | <filename>backend/addons/account_invoice_change_currency/tests/test_account_invoice_change_currency.py
# Copyright 2018 Komit <http://komit-consulting.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import fields
from odoo.tools import float_compare
import odoo.tests.common as commo... | StarcoderdataPython |
1672718 | <filename>web/api/maestro_api/db/repo/user.py
from maestro_api.db.models.user import User, UserRole
from maestro_api.db.models.workspace import Workspace
from maestro_api.libs.datetime import now
class UserRepository:
"""
Repository to manage User related operations
"""
def create_or_update(self, na... | StarcoderdataPython |
3298868 | <filename>scalyr_agent/third_party_tls/tlslite/handshakehelpers.py
# Authors:
# <NAME>
#
# See the LICENSE file for legal information regarding use of this file.
"""Class with various handshake helpers."""
from .extensions import PaddingExtension
class HandshakeHelpers(object):
"""
This class encapsulates... | StarcoderdataPython |
4829493 | <reponame>gabrieldiaz94/RAS-Baxter-Interface
#!/usr/bin/env python
# license removed for brevity
import rospy
from std_msgs.msg import String,Int32MultiArray
from geometry_msgs.msg import Twist
from jp_baxtertry1.srv import *
global fin
fin=0
def talker():
while not rospy.is_shutdown():
global Acabe,fin
m... | StarcoderdataPython |
3309137 | import numpy as np
def value_iteration(transitions, rewards, gamma=0.95, theta=1e-5):
rewards = np.expand_dims(rewards, axis=2)
values = np.zeros(transitions.shape[0], dtype=np.float32)
delta = np.inf
while delta >= theta:
q_values = np.sum(transitions * (rewards + gamma * values), axis=2)
... | StarcoderdataPython |
127527 | <filename>strategy_mgr/migrations/0002_auto_20201217_0955.py<gh_stars>0
# Generated by Django 3.1.2 on 2020-12-17 01:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('strategy_mgr', '0001_initial'),
]
operations = [
migrations.AlterFie... | StarcoderdataPython |
17342 | <filename>pearll/agents/ga.py
from functools import partial
from typing import Callable, List, Optional, Type
import numpy as np
from gym.vector.vector_env import VectorEnv
from pearll.agents.base_agents import BaseAgent
from pearll.buffers import RolloutBuffer
from pearll.buffers.base_buffer import BaseBuffer
from p... | StarcoderdataPython |
10156 | import unittest
import datetime
import kronos
string_format_time = "%Y-%m-%d %H:%M:%S"
date_time_str = "2020-07-19 18:14:21"
class KronosTest(unittest.TestCase):
def test_get_day_of_week(self):
for i in range(len(kronos.week_days)):
date = kronos.get_date_time_from_string(f"2020-08-{10 + i} 1... | StarcoderdataPython |
70193 | <filename>basic_exercises/final/entity.py<gh_stars>0
class News:
# 允许绑定的对象
__slots__ = ('__id', '__time', '__department', '__info')
# 构造函数
def __init__(self, url, time, department, info):
self.__id = url
self.__time = time
self.__department = department
self.__info = inf... | StarcoderdataPython |
3214110 |
import path
import logging
import shutil
import os
log = logging
START_ID = "automatically created attributes start"
END_ID = "automatically created attributes end"
START_STATIC_ID = "automatically created static attributes start"
END_STATIC_ID = "automatically created static attributes end"
START_NODE_ID = 0x0011E... | StarcoderdataPython |
3351178 | """
uses py.test
sudo easy_install py
http://codespeak.net/py/dist/test.html
"""
import os
import sys
import time as sleeper
from datetime import time, datetime, timedelta
import unittest
from threading import Thread
from Queue import Queue
from Queue import Empty
from django.conf import settings
from util import ... | StarcoderdataPython |
3228129 | <filename>commmons/dataclass.py
from dataclasses import is_dataclass, fields
from typing import get_origin, get_args
__all__ = [
"as_dataclass",
"as_dataclass_list"
]
def as_dataclass(dct: dict, cls: type):
kwargs = {}
for fld in fields(cls):
if fld.name in dct:
origin = get_origi... | StarcoderdataPython |
3240350 | import asyncio
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
import voluptuous as vol
from pykdeconnect.payloads import AnyPayload
from pykdeconnect.plugin_registry import PluginRegistry
from pykdeconnect.plugins.battery import (
BatteryPayload, BatteryReceiverPlugin, BatteryThreshold
)
from... | StarcoderdataPython |
3382276 | <gh_stars>0
# -*- coding: utf-8 -*-
#
# # MIT License
#
# Copyright (c) 2020 <NAME>
#
# 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 ... | StarcoderdataPython |
168540 | from .wrapper import *
from .utils import *
from .matrix import *
from .io import *
# Setup global module state
init_wrapper()
print("**pycubool project**")
print("pycubool is a python wrapper for a cuBool library.")
print("See https://github.com/JetBrains-Research/cuBool for more information.")
| StarcoderdataPython |
9590 | <reponame>AngelOnFira/megagame-controller<filename>django/currencies/migrations/0003_auto_20211121_0701.py
# Generated by Django 3.2.8 on 2021-11-21 12:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("currencies", "0002_initial"),
]
operation... | StarcoderdataPython |
150488 | <gh_stars>0
'''
Author: <NAME>
Date: 2021-11-16 15:29:11
LastEditors: <NAME>
LastEditTime: 2021-11-29 21:42:02
Description:
FilePath: /CVMI_Sementic_Segmentation/model/builder.py
'''
import torch.nn as nn
import copy
from model.compose import Compose, MatchBlock
from utils.registry import Registry, build
BACKBONE = ... | StarcoderdataPython |
1689704 |
from anthill_tools import Discovery, Environment, Login, Admin, ApplicationInfo, ServiceError
import hashlib
import os
import sys
import json
from optparse import OptionParser
def log(data):
print data
def md5(file_name):
hash_ = hashlib.md5()
with open(file_name, "rb") as f:
for chunk in ite... | StarcoderdataPython |
1648396 | import paho.mqtt.publish as publish
import paho.mqtt.client as mqtt
import socket
import json
from datetime import datetime
import configparser
'''
Author: GYzheng, <EMAIL>
###Server side
We have two topic, one is from client to server, the other one is from client to server
1. Server->Client : sc_topic
2. Client... | StarcoderdataPython |
173435 | <filename>pypy/module/zlib/app_zlib.py
"""
Application-level definitions for the zlib module.
NOT_RPYTHON
"""
class error(Exception):
"""
Raised by zlib operations.
"""
| StarcoderdataPython |
3296336 | # -*- coding: iso-8859-1 -*-
import os
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from config import basedir
import logging
from logging import Formatter
from logging.handlers import RotatingFileHandler
app = Flask(__name__)
app.conf... | StarcoderdataPython |
3381357 | # -*- coding: utf-8 -*-
############################################################################
#
# Copyright (c) 2020 yingchengpa, 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 ob... | StarcoderdataPython |
1651249 | <filename>src/data_collection/collect_data.py
import os
import json
import logging
import hydra
from hydra.utils import to_absolute_path
from omegaconf import DictConfig
from joblib import Parallel, delayed
from src.data_collection.utils import RepoProcessor
@hydra.main(config_path=".", config_name="data_collection... | StarcoderdataPython |
4822208 | # Copyright 2021 The FedLearner 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://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | StarcoderdataPython |
1751162 | <gh_stars>0
"""
test_demultiplex.py
-------------------------------
Tests for the `demultiplex.py` module
"""
import unittest
import os
import sys
import shutil
import utils
# Include the parent directory in the PYTHONPATH for relative imports
sys.path.append('..')
import demultiplex
TEST_SAMPLE_BARCODES = {'AGGC... | StarcoderdataPython |
12224 | import json
import numpy as np
from tqdm import tqdm
# Change these based on experiment
#exp_dataset = 'mask_char_oov_test_set.db'
#exp_name = 'results_test_mask_char'
#exp_dataset = 'mask_2_oov_test_set.db'
#exp_name = 'results_test_mask_2'
#exp_dataset = 'mask_2_oov_test_set.db'
#exp_name = 'results_test_synonyms_ma... | StarcoderdataPython |
3273820 | import datetime
import json
import newspaper
from newspaper import Article
import os
import requests
from requests.auth import HTTPBasicAuth
import sqlite3
import time
keys = json.load(open("keys.json", "r"))
def connect_db():
return sqlite3.connect("data.db")
def parse_article(url, lang, featured=0, db=connect_... | StarcoderdataPython |
60578 | <gh_stars>1-10
import math
import random
import pybullet as p
import numpy as np
from pyquaternion import Quaternion
from src.bot.Robot import Robot
from src.utils.sbMath import calc_angle, get_point_towards
class SphereBot(Robot):
def __init__(self, pos, orn, config):
super().__init__(pos, orn, config.... | StarcoderdataPython |
4823469 | # Generated by Django 3.0.7 on 2020-06-16 19:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('authorization', '0005_user_banned'),
]
operations = [
migrations.AlterField(
model_name='user',
name='name',
... | StarcoderdataPython |
53047 | """ Class to serialize data for multiprocessing.
Inspired by: https://github.com/openai/baselines/blob/master/baselines/common/vec_env/__init__.py
"""
import cloudpickle
import pickle
class CloudpickleWrapper(object):
""" Uses `cloudpickle` to serialize contents. """
def __init__(self, data):
self.d... | StarcoderdataPython |
3329830 | import json
import os
import random
import time
import cv2
from PIL import Image
from image_similarity_measures.quality_metrics import fsim
class Debug:
@staticmethod
def print(content, prefix=True, inline=False, new_line=False):
head = f"{time.strftime('%Y-%m-%d %H:%M:%S', time.localtim... | StarcoderdataPython |
3392344 | <filename>High School/9th Grade APCSP (Python)/Unit 1/Unit 01.03 (Variables)/01.03.19.py
# 01.03.08 BASIC NAME PROMPT IS BASIC
number = input("Number? ")
print("Number Reversed:", number[::-1], "")
num = int(number)
rev = int(number[::-1])
diff = abs(num-rev)
print("Difference:", diff, "")
diff = str(diff)
revdiff = d... | StarcoderdataPython |
146763 | # type: ignore
from typing import Any
import qtvscodestyle as qtvsc
from PySide6.QtCore import QAbstractTableModel, QModelIndex, Qt
from PySide6.QtGui import QAction, QActionGroup, QTextOption
from PySide6.QtWidgets import (
QCheckBox,
QColorDialog,
QComboBox,
QDateTimeEdit,
QDial,
QDockWidget... | StarcoderdataPython |
4828411 | <reponame>xbankov/calamari<gh_stars>0
import random
import shutil
from tqdm import tqdm
from cfg import DATA_ROOT, MANUAL_SPLITS
random.seed(42)
def main():
root = DATA_ROOT.parent / 'dta19'
new_train = MANUAL_SPLITS / 'train'
new_valid = MANUAL_SPLITS / 'valid'
new_test = MANUAL_SPLITS / 'test'
... | StarcoderdataPython |
3320029 | import project, record, proxy
| StarcoderdataPython |
95173 | # Copyright 2015 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 agreed to in writing, ... | StarcoderdataPython |
56137 | """Library to access the webserver."""
import re
import time
import logging
logger = logging.getLogger(__name__)
from unicon.eal.expect import Spawn, TimeoutError
from unicon.utils import AttributeDict
from unicon.eal.dialogs import Dialog
MAX_RETRY_COUNT = 3
class Webserver:
def __init__(self, hostname='AST-IN... | StarcoderdataPython |
3250689 | # -*- coding: utf-8 -*-
import os
import platform
import tempfile
from pathlib import Path
from collections import defaultdict
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from snl_d3d_cec_verify import (MycekStudy,
Report,
... | StarcoderdataPython |
1702250 | """
Implementation of various calibration methods from https://github.com/JonathanWenger/pycalib.
"""
import warnings
import matplotlib.pyplot as plt
import numpy as np
import scipy.cluster.vq
import scipy.optimize
import scipy.special
import scipy.stats
import sklearn
import sklearn.isotonic
import sklearn.linear_mo... | StarcoderdataPython |
4805936 | <gh_stars>0
import os
import logging
import requests
from git import Git, Repo
from batchnfpm.config import Config, Hoster, BuildConfig
class GitWrapper:
def __init__(self, path):
if not path:
raise ValueError("path must be set")
self.path = path
def get_local_repo_path(self, o... | StarcoderdataPython |
3204039 | <filename>krankit/interactions/apps.py
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class InteractionsConfig(AppConfig):
name = "krankit.interactions"
verbose_name = _("Interactions")
def ready(self):
try:
import krankit.interactions.signals... | StarcoderdataPython |
142390 | <filename>monitoring/uss_qualifier/rid/reports.py
import datetime
from typing import List, Optional
import s2sphere
from monitoring.monitorlib import fetch
from monitoring.monitorlib.typing import ImplicitDict
from monitoring.uss_qualifier.rid.utils import (
InjectedFlight,
RIDQualifierTestConfiguration,
)
fr... | StarcoderdataPython |
85604 | <gh_stars>10-100
#!/usr/bin/env python3
from pyats import aetest
from pyats.kleenex import BringUp
class common_setup(aetest.CommonSetup):
@aetest.subsection
def connect(self, testbed, uut1_name, uut2_name,
uut1_if_name, uut2_if_name):
""" Connect to nodes in the topology """
u... | StarcoderdataPython |
4808824 | <gh_stars>0
from flask_wtf import FlaskForm
from wtforms import TextField, PasswordField, IntegerField, SelectField
## login and registration
class add_user_Form(FlaskForm):
username = TextField('Username', id='username_create')
email = TextField('Email')
password = PasswordField('Password', id='<PASSWOR... | StarcoderdataPython |
3202649 | <filename>tests/test_methods.py<gh_stars>0
from unittest.mock import Mock
from featurevis import methods
def test_gradient_ascent():
dataloaders = dict(train=dict(session1=None))
model = "model"
config = dict(
optim_kwargs=None, transform=None, regularization="module.function", gradient_f=None, p... | StarcoderdataPython |
4815865 | from ultraminifyhtml.libultraminifyhtml import *
| StarcoderdataPython |
1680673 | import pandas as pd
import tensorflow as tf
import numpy as np
class DatasetCreation():
def __init__(self, input_dictionay, output_tfr_file, output_dictionary_csv):
self.input_dictionay = input_dictionay
self.output_tfr_file = output_tfr_file
self.output_dictionary_csv = output_dictionary... | StarcoderdataPython |
3363601 | #!/usr/bin/env python3
import sys
from collections import Counter
from string import ascii_lowercase
vowels = "aeiou"
lines = list(filter(bool, [line.strip() for line in sys.stdin]))
doubles = [a + b for a, b in zip(ascii_lowercase, ascii_lowercase)]
nice_strings = 0
for line in lines:
letter_counts = Counter(lin... | StarcoderdataPython |
121151 | """Classes to represent Collection entities in the app"""
# app imports
from ntbk.entities.templates import Template
class Collection():
"""Represents a folder in the /collections directory. It can contain multiple files
Arguments:
config - Config instance
filesystem - Filesystem instance
... | StarcoderdataPython |
3228611 | <reponame>seanmacavaney/ir_datasets<filename>test/integration/clirmatrix.py
import re
import unittest
import ir_datasets
from ir_datasets.formats import GenericDoc, GenericQuery, TrecQrel
from .base import DatasetIntegrationTest
_logger = ir_datasets.log.easy()
# Note: there's > 100k combinations here, so we are onl... | StarcoderdataPython |
4842305 |
from collections import OrderedDict
import numpy as np
import numexpr as ne
from scipy.spatial import distance
from scipy import sparse
import scipy.sparse.linalg
from . import exact_geodesic
from . import subsurface
from .misc import _memo
class Surface(exact_geodesic.ExactGeodesicMixin, subsurface.SubsurfaceMixi... | StarcoderdataPython |
1647216 | <reponame>kemingy/daily-coding-problem
# Given a binary tree of integers, find the maximum path sum between two nodes.
# The path must go through at least one node, and does not need to go through
# the root.
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
... | StarcoderdataPython |
1782043 | <reponame>ariel415el/PerceptualLossGLO-Pytorch<filename>perceptual_mean_optimization/utils.py
import os
import cv2
import numpy as np
from matplotlib import pyplot as plt
import torch
from torchvision import transforms
def pt2cv(img):
img = (img.numpy() + 1) / 2
img = np.clip(img, 0, 1)
img *= 255
i... | StarcoderdataPython |
1735508 | <reponame>matthewwincott/pywfs<filename>src/pywfs/sdk.py
""""
"""
from ctypes import c_uint8, c_int16, c_int32, c_double, c_ulong, c_float, c_bool, c_char, c_char_p, create_string_buffer, byref, POINTER
import numpy as np
try:
from .helper import log
except:
from helper import log
# WFS status bits
WFS_STA... | StarcoderdataPython |
4843255 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# flask_restapi import
from tests import BaseTestCase
from flask_restapi.app import APIFlask
from flask_restapi.exceptions import APIError
app = APIFlask(__name__)
app.config['TESTING'] = True
@app.route('/json_view')
def json_view():
return {'test': True}
@app.... | StarcoderdataPython |
1603558 | <reponame>half0wl/datagovsg_api
import os
import unittest
from datagovsg import DataGovSG
class TestDataGovSG(unittest.TestCase):
def setUp(self):
self.client = DataGovSG(API_KEY=os.environ['DataGovSG_APIKEY'])
def test_build_url(self):
expected = 'https://api.data.gov.sg/v1/environment/psi... | StarcoderdataPython |
3336372 | import numpy as np
from src import generate_regression_data, PolynomialRegression, mean_squared_error
def test_polynomial_regression():
degrees = range(10)
amounts = [10, 100, 1000, 10000]
for degree in degrees:
p = PolynomialRegression(degree)
for amount in amounts:
x, y = gen... | StarcoderdataPython |
21540 | """ Copyright 2012, 2013 UW Information Technology, University of Washington
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 r... | StarcoderdataPython |
55564 | <gh_stars>1-10
import numpy as np
import cv2
import io
import matplotlib.pyplot as plt
import os
from pdf2image import convert_from_path
from PIL import Image
from PyPDF2 import PdfFileWriter, PdfFileReader
import re
import tempfile
# import tkinter as tk
# from tkinter import Frame, Text, Label
import torch
import tor... | StarcoderdataPython |
3328193 | <filename>dataSourceCI.py
import os
import re
import json
import base64
import requests
from urllib3 import *
from datetime import date
disable_warnings()
# 常量定义
name = '<NAME>'
email = '<EMAIL>'
today = str(date.today())
plus_token = os.environ['plus_token']
github_token = os.environ['repo_token']
dataSQLpath = f'ht... | StarcoderdataPython |
188497 | <reponame>chemmatcars/XModFit<gh_stars>0
import numpy as np
from scipy.interpolate import interp1d
from numpy.linalg import inv
from functools import lru_cache
from Chemical_Formula import Chemical_Formula
cf=Chemical_Formula(formula='Au')
def calc_pr(q,Iq):
"""
Calculates Moore's autocorrelation function
... | StarcoderdataPython |
14000 | <reponame>City-of-Turku/PaohServiceMatchEngine
from datetime import datetime
from pydantic import BaseModel
from typing import Optional, List
from fastapi import Query
class Service(BaseModel):
"""
A class for single service
"""
id: str
ptvId: Optional[str] = None
type: Optional[str] = None
... | StarcoderdataPython |
3211766 | # Generated by Django 3.0.4 on 2020-04-07 18:57
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
('sites', '0002_alter_domain_unique'),
]
operations = [
migrations.CreateMode... | StarcoderdataPython |
1743093 | <filename>yoyo/tests/test_cli_script.py
# Copyright 2015 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | StarcoderdataPython |
3380043 | <filename>app/api/api_v1/endpoints/order.py
from typing import List, Optional
from fastapi import APIRouter, HTTPException, Depends, status
from app.payloads import orders
from app.models.orders import OrderCreate, OrderSchema, fix_item_id, OrderUpdate
from ....db.mongodb import AsyncIOMotorClient, get_database
rout... | StarcoderdataPython |
3369165 | <gh_stars>100-1000
from .protocol import Diagnostic, DiagnosticSeverity, DocumentUri
from .typing import Callable, Iterator, List, Tuple, TypeVar
from .url import parse_uri
from .views import diagnostic_severity
from collections import OrderedDict
import functools
ParsedUri = Tuple[str, str]
T = TypeVar('T')
class D... | StarcoderdataPython |
1628631 | <gh_stars>0
#!/usr/bin/python
'''
Copyright 2018 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed t... | StarcoderdataPython |
1651034 | <filename>embedwiz/__init__.py<gh_stars>1-10
from .embedwiz import EmbedWizard
def setup(bot):
bot.add_cog(EmbedWizard(bot))
| StarcoderdataPython |
139564 | # -*- coding = utf-8 -*-
# @Time:2021/3/713:29
# @Author:Linyu
# @Software:PyCharm
import pymysql
from pymysql import *
from flask_wtf import FlaskForm
from wtforms import StringField,SubmitField
from wtforms.validators import DataRequired
import random
from matplotlib import pyplot as plt
from wordcloud import WordCl... | StarcoderdataPython |
22106 | from getpass import getpass
from colorama import init, Fore, Back, Style
yes = ['Y', 'y', 'YES', 'yes', 'Yes']
class interface(object):
"""
Terminal CLI
"""
def log(self, arg, get=False):
if not get:
print("[*]: {} ".format(arg))
else:
return "[*]: {} ".format(a... | StarcoderdataPython |
1746973 | from django.shortcuts import redirect
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from rest_framework_security.authentication.next_steps import NextStepBase
from rest_framework_security.otp import config
class NextStep(NextStepBase):
step_name = "otp"
def get_allow... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.