text stringlengths 2 999k |
|---|
import unittest
import behave2cucumber
import json
import os
BEHAVE_JSON = os.path.dirname(os.path.realpath(__file__)) + "/fixtures/behave.json"
EXPECTED_JSON = os.path.dirname(os.path.realpath(__file__)) + "/fixtures/expected.json"
AUTORETRY_BEHAVE_JSON = os.path.dirname(os.path.realpath(__file__)) + "/fixtures/autor... |
import argparse
import inspect
import logging
import sys
from .__main__ import setup_logging
log = logging.getLogger()
DESCRIPTION = """
hic-internal is used for automation, not intend to be used by end user.
Use hicluster instead.
"""
EPILOG = ''
def impute_chromosome_internal_subparser(subparser):
parser =... |
from django.db import models
from datetime import datetime as dt
from django.contrib.auth.models import User
#cloudinary
from cloudinary.models import CloudinaryField
# Create your models here.
# category model
class Category(models.Model):
name = models.CharField(max_length=100)
# slug = models.SlugField(ma... |
# Copyright (c) 2016 Cisco Systems, 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/LICENSE-2.0
#
# Unless ... |
#!/usr/bin/env python3
# Copyright (c) 2015-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test processing of unrequested blocks.
Setup: two nodes, node0+node1, not connected to each other. Nod... |
"""13,836 Gjoneska mouse gene Ensembl IDs and gene Symbols.
2015 Gjoneska paper:
Conserved epigenomic signals in mice and humans
reveal immune basis of Alzheimer's disease.
"""
ensmusg2symbol = {
'ENSMUSG00000002012' : 'Pnck',
'ENSMUSG00000031592' : 'Pcm1',
'ENSMUSG00000002010' : 'Idh... |
# Lint as: python3
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# ... |
import sys
import os
import os.path
import hashlib
import re
import fnmatch
import time
import shutil
import errno
import tempfile
import codecs
import pickle as pickle
import stat
from stat import ST_MTIME
# We import only jumpscale as the j.system.fs is used before jumpscale is initialized. Thus the q cannot be imp... |
import connexion
import os
import sys
import json
import logging
from jupyterhub_singleuser_profiles.profiles import SingleuserProfiles
from jupyterhub_singleuser_profiles import version as singleuser_profiles_version
from functools import wraps
from urllib.parse import quote
from flask import Flask
from flask import... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import glob
import logging
import os
import shutil
from rasa_nlu_gao.components import Component
from rasa_nlu_gao.config import RasaNLUModelConfig
from rasa_nlu_gao.tok... |
""" Group all tests cases for layers"""
import pytest
import torch
from polaris.network.layers import SqueezeExcitation, ResidualBlock2D
def test_squeeze_excitation():
X = torch.tensor([[[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]]])
se = SqueezeExcitation(channels=1, ratio=1)
se.dense_linear_1.... |
from flask import Blueprint
from dmutils.user import User
from flask_login import login_user
login_for_tests = Blueprint('login_for_tests', __name__)
# Simplified example responses from the API
USERS = {
'123': {
'id': 123,
'name': 'Name',
'emailAddress': 'email@email.com',
'role'... |
"""
Solving positive definite linear systems
=========================================
This benchmark compares the performances of KeOps versus Numpy and Pytorch on a inverse matrix operation. It uses the functions :class:`torch.KernelSolve <pykeops.torch.KernelSolve>` (see also :doc:`here <../_auto_examples/pytorch/p... |
import unittest
import ramda as R
"""
https://github.com/ramda/ramda/blob/master/test/props.js
"""
d = {
'a': 1,
'b': 2,
'c': 3,
'd': 4,
'e': 5,
'f': 6,
}
class TestPropsForDict(unittest.TestCase):
def test_returns_empty_array_if_no_properties_requested(self):
self.assertEqual([], R.... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from io import BytesIO
from . import FileObject, PEObject, ELFObject, MachOObject
from ..exceptions import MISPObjectException
import logging
from typing import Optional
logger = logging.getLogger('pymisp')
try:
import lief # type: ignore
from lief i... |
import numpy as np
import unittest
import os
from recommender_pkg.metrics import dcg_score
from recommender_pkg.metrics import ndcg_score
from recommender_pkg.metrics import perform_groupwise_evaluation
class TestMetrics(unittest.TestCase):
def test_dcg_score(self):
self.assertAlmostEqual(dcg_score([1, 2,... |
import numpy as np
import matplotlib.pyplot as plt
import ytterbium as yb
from ytterbium.Yb174 import FourLevelSystem
# initialize the S-P transition in 174Yb+ as a four-level system
FLS = FourLevelSystem(sat=0.5)
# to measure the lineshape, we drive the system at different laser detunings,
# which are defined in MH... |
"""
Define an implementation to handle each repository.
"""
from .git import GitRepository # noqa
|
# -*- coding: utf-8 -*-
'''
:codeauthor: :email:`Jayesh Kariya <jayeshk@saltstack.com>`
'''
# Import Python libs
from __future__ import absolute_import
# Import Salt Testing Libs
from tests.support.unit import TestCase, skipIf
from tests.support.mock import MagicMock, patch, NO_MOCK, NO_MOCK_REASON
# Import Salt... |
import random
def simpleRandomSample(self, num, nums):
return random.sample(nums, num)
|
import io
import sys
import traceback
import warnings
from contextlib import contextmanager, ExitStack
from copy import deepcopy
from pathlib import Path
from tempfile import NamedTemporaryFile
from typing import Dict, Optional, TextIO
from IPython.core.interactiveshell import InteractiveShell
from nbformat import rea... |
import dataclasses
from typing import Optional
from dis_snek import Guild, Member, Snake
from ElevatorBot.core.destiny.lfg.scheduledEvents import delete_lfg_scheduled_events
from ElevatorBot.discordEvents.base import ElevatorSnake
from ElevatorBot.networking.http import BaseBackendConnection
from ElevatorBot.networki... |
# Copyright 2022 Google LLC
#
# 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, so... |
__doc__ = """ Module containing joint classes to connect multiple rods together. """
__all__ = ["FreeJoint", "HingeJoint", "FixedJoint", "ExternalContact", "SelfContact"]
import numpy as np
import numba
from elastica.utils import Tolerance, MaxDimension
from elastica._linalg import _batch_product_k_ik_to_ik
from math i... |
from django.core.management.base import BaseCommand, CommandError
from derbot.names.tasks import fetch_names_twoevils, fetch_names_drc, fetch_names_wftda, fetch_names_rdr
class Command(BaseCommand):
help = 'Downloads names from online databases'
def handle(self, *args, **options):
fetch_names... |
"""Test fixtures."""
import ast
import json
import os
NAPALM_TEST_MOCK = ast.literal_eval(os.getenv("NAPALM_TEST_MOCK", default="1"))
NAPALM_HOSTNAME = os.getenv("NAPALM_HOSTNAME", default="127.0.0.1")
NAPALM_USERNAME = os.getenv("NAPALM_USERNAME", default="vagrant")
NAPALM_PASSWORD = os.getenv("NAPALM_PASSWORD", de... |
from torch import nn
from functools import partial
from einops.layers.torch import Rearrange, Reduce
from torch.autograd import Variable
import torch
class PreNormResidual(nn.Module):
def __init__(self, dim, fn):
super().__init__()
self.fn = fn
self.norm = nn.LayerNorm(dim)
... |
# -*- coding: utf-8 -*-
"""\
Differnt output tests.
"""
from __future__ import unicode_literals, absolute_import
import io
from nose.tools import eq_
from segno_mimos import pyqrcode
try:
from .test_eps import eps_as_matrix
from .test_png import png_as_matrix
from .test_svg import svg_as_matrix
except (Valu... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
#import os
import sys
import os
sys.path.insert(0,os.getcwd())
import absl
from tensorflow.python.ops import parallel_for as pfor
from FixedPointStore import *
import tensorflow as tf
# im... |
# Copyright (c) 2022 NVIDIA CORPORATION & AFFILIATES.
# All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Projet : Editeur, Compilateur et Micro-Ordinateur pour
un langage assembleur.
Nom du fichier : 01-04-CodeScrolledText.py
Identification : 01-04-CodeScrolledText
Titre : Widget : Texte avec défilement et numéro ... |
#!/usr/bin/python3
"""Defines unittests for base_model.py."""
import unittest
import os
import sys
from models.base_model import BaseModel
from time import sleep
from models import storage
import models
import pep8 as pycodestyle
from unittest import mock
module_doc = models.base_model.__doc__
class TestBase_instanti... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 21 17:36:43 2021
@author: mike_ubuntu
"""
import numpy as np
import pandas as pd
from collections import OrderedDict
import pickle
import src.globals as global_var
from src.moeadd.moeadd import *
from src.moeadd.moeadd_supplementary import *
imp... |
"""
future: Easy, safe support for Python 2/3 compatibility
=======================================================
``future`` is the missing compatibility layer between Python 2 and Python
3. It allows you to use a single, clean Python 3.x-compatible codebase to
support both Python 2 and Python 3 with minimal overhea... |
"""Scripts for populating the db for the first time."""
from strops.schemes.scripts.create import create_all # noqa
def run_all():
"""Runs all scripts.
Order:
create_all()
"""
create_all()
if __name__ == "__main__":
run_all()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# "Fuzzing APIs" - a chapter of "The Fuzzing Book"
# Web site: https://www.fuzzingbook.org/html/APIFuzzer.html
# Last change: 2022-01-11 10:24:22+01:00
#
# Copyright (c) 2021 CISPA Helmholtz Center for Information Security
# Copyright (c) 2018-2020 Saarland University, au... |
from os import path
import json
import collections
import sys
output_dir = "./data/ace-event/processed-data/default-settings/json"
for fold in ["train", "dev", "test"]:
g_convert = open(path.join(output_dir, fold + "_convert.json"), "w")
to_write = []
with open(path.join(output_dir, fold + ".json"), "r") a... |
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 25 20:34:32 2014
@author: Imane
"""
import numpy as np
from os import listdir
from os.path import isfile, join
from zscoring import zscoringNII
from masking import maskdata
#Applying Z-score and saving in NII files
sourcedir = 'brainimages'
filenames = [ f for f in listd... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from config.template_middleware import TemplateResponse
from gaebusiness.business import CommandExecutionException
from tekton import router
from gaecookie.decorator import no_csrf
from aluno_app import facade
from routes.alunos import adm... |
from numpy import array
from pybimstab.polygon import Polygon
coords = array([[0, 1, 1, 0], [0, 0, 1.5, 1.5]])
x, y = 0.5, 2
polygon = Polygon(coordinates=coords)
polygon.isinside(x=x, y=y, meshgrid=False, want2plot=True)
|
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import time
from abc import abstractmethod
from time import sleep
from datafaker import compat
from datafaker.compat import safe_decode, queue
from datafaker.constant import INT_TYPES, FLOAT_TYPES, ENUM_FILE, JSON_FORMAT, MAX_QUEUE_SIZE, MIN_RECORDS_FOR_PARALLEL
from dataf... |
import paramiko as pmk
username = raw_input("Username: ")
password = raw_input("Password: ")
hostnames = ["hostname1","hostname2","hostname3"]
commands = ["hostname","nproc","ps aux","exit"]
client = pmk.SSHClient()
client.set_missing_host_key_policy(pmk.AutoAddPolicy())
for hostname in hostnames:
try:
... |
"""
lakeFS API
lakeFS HTTP API # noqa: E501
The version of the OpenAPI document: 0.1.0
Contact: services@treeverse.io
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401
from lakefs_client.api_client import ApiClient, Endpoint as _Endpoint
from lak... |
# Generated by Django 2.2 on 2021-06-11 22:39
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0011_update_proxy_permissions'),
]
operations = [
migrations.CreateModel(
name='UserProfile',
... |
import numpy as np
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func
from flask import Flask, jsonify
import datetime as dt
from dateutil.relativedelta import relativedelta
################################################... |
import trajoptpy, openravepy
import sys
def animate_traj(traj, robot, pause=True, step_viewer=1, restore=True, callback=None, execute_step_cond=None):
"""make sure to set active DOFs beforehand"""
if restore: _saver = openravepy.RobotStateSaver(robot)
if step_viewer or pause: viewer = trajoptpy.GetViewer(r... |
import re
from django.utils.regex_helper import _lazy_re_compile
# Regular expression for recognizing HEXEWKB and WKT. A prophylactic measure
# to prevent potentially malicious input from reaching the underlying C
# library. Not a substitute for good web security programming practices.
hex_regex = _lazy_re_compile(r... |
import pytest
from pyquery import PyQuery as pq
from flask_jsondash import charts_builder
from conftest import (
auth_valid,
read,
)
@pytest.mark.globalflag
def test_noset_global_flag_when_creating_dashboard(ctx, client, monkeypatch):
app, test = client
app.config['JSONDASH_GLOBALDASH'] = True
... |
import socket
import logging
import ClientServingThread
from encryption import generate_keyset, decrypt_session, encrypt_session
from protocoll import *
from passwordmanagement import hash
VERSION_NUMBER = 1
def checkVersion(versionNumber):
if (versionNumber < VERSION_NUMBER):
print("Bitte updaten")
serv... |
# encoding: utf-8
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from scipy.stats import multivariate_normal
from collections import namedtuple
# NetworkX
# https://networkx.github.io/documentation/networkx-1.9.1/reference/algorithms.component.html
# https://media.readthed... |
from django.conf import settings
from django.db import models
from django.utils.translation import gettext_lazy as _
from django_cpf_cnpj.validators import validate_cpf, validate_cnpj
from django_cpf_cnpj.cpf import cpf_to_python, CPF
from django_cpf_cnpj.cnpj import cnpj_to_python, CNPJ
__all__ = ['CPFField', 'CNPJF... |
from direct.directnotify import DirectNotifyGlobal
from pirates.movement.AnimationMixer import AnimationMixer
class BipedAnimationMixer(AnimationMixer):
notify = DirectNotifyGlobal.directNotify.newCategory('BipedAnimationMixer')
NA_INDEX = -1
IDLE_INDEX = 0
INPLACE_INDEX_0 = 1
INPLACE_INDEX_1 = 2
... |
from astropy.cosmology import wCDM
from cosmopy import Cosmology
import numpy as np
n_sample = 300 # number of test samples
n_dim = 4
center = np.array([72., .5, .5, -1.5]) # H_0, omega_m, omega_v, w
scale = np.array([8., .5, .5, 1.]) # width to uniformly distribute cosmological parameters along one direction
params... |
#
# Project:
# glideinWMS
#
# File Version:
#
# Description:
# This module implements the functions needed to keep the
# required number of idle glideins
# It also has support for glidein sanitizing
#
# Author:
# Igor Sfiligoi (Sept 7th 2006)
#
import os
import sys
import time
import string
import re
import ... |
import logging
import zope.interface
from certbot import errors
from certbot import interfaces
from certbot.plugins import dns_common
from certbot.plugins import dns_common_lexicon
import requests
logger = logging.getLogger(__name__)
DESEC_API = "https://desec.io/api/v1"
@zope.interface.implementer(interfaces.IA... |
""" -----------------------------------------------------
# TECHNOGIX
# -------------------------------------------------------
# Copyright (c) [2022] Technogix SARL
# All rights reserved
# -------------------------------------------------------
# Keywords to manage ec2 tasks
# ----------------------------------... |
import time
import warnings
import numpy as np
import pyautogui
from src.solver import BruteForceSolver
from src import vision
def on_click(x, y, button, pressed):
if not pressed: # Stop listener
return False
corners = vision.get_corners_from_user()
print(f'Corners: {corners}')
print('Get the reset but... |
# Copyright 2015 The TensorFlow 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... |
"""
Source code borrowed from https://github.com/WatChMaL/UVicWorkshopPlayground/blob/master/B/notebooks/utils/utils.py
Edited by : Abhishek .
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import math
import os
import sys
import pand... |
#!/usr/bin/env python
# Copyright (c) 2013-2014 Rackspace, 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 appli... |
# Copyright (c) 2019 NVIDIA Corporation
import torch
import torch.nn as nn
from nemo.backends.pytorch.nm import LossNM
from nemo.core.neural_types import (NeuralType, AxisType, BatchTag, TimeTag,
ChannelTag)
class CTCLossNM(LossNM):
"""
Neural Module wrapper for pytorch's ... |
"""Quirk for lumi.sen_ill.mgl01 illumination sensor."""
import logging
from zigpy.profiles import zha
from zigpy.zcl.clusters.general import Basic, Identify
from zigpy.zcl.clusters.measurement import IlluminanceMeasurement
from zigpy.zdo.types import NodeDescriptor
from .. import LUMI, BasicCluster, XiaomiCustomDevic... |
"""
A lot of this code is from the discord.py examples folder: https://github.com/Rapptz/discord.py/blob/rewrite/examples/playlist.py
The Youtube_DL code is from: https://github.com/CarlosFdez/SpueBox
Licenses can be found in the LICENSE file in the root dir
"""
import discord
from discord.ext import commands
import a... |
import numpy as np
import torch
import torch.optim as optim
import torch.nn as nn
from Losses import MultiHuberLoss
device = "cuda" if torch.cuda.is_available() else "cpu"
batch_size = 32
def train(model, criteria, training_set, testing_set, optim_wd=0.0, lr=0.001, epochs=100):
optimizer = optim.AdamW(model.par... |
# Copyright (c) 2016-2017, Neil Booth
# Copyright (c) 2017, the ElectrumX authors
#
# All rights reserved.
#
# The MIT License (MIT)
#
# 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 ... |
# coding: utf-8
"""
PDF stamper
The PDF Stamper API enables the possibility to add both static and dynamic stamps on existing PDFs. The stamps can consist of one or more barcode, hyperlink, image, line or text elements. The flow is generally as follows: 1. Make a configuration containing the stamp informa... |
# Copyright (C) 2020 sandeep.n(π.$)
# button post makker for catuserbot thanks to uniborg for the base
# by @sandy1709 (@mrconfused)
import os
import re
from telethon import Button
from AyiinXd import CMD_HANDLER as cmd
from AyiinXd import CMD_HELP, tgbot
from AyiinXd.ayiin import ayiin_cmd, edit_delete, reply_id
... |
# coding: utf-8
import ast
import gast
import inspect
import numpy as np
import onnx
from onnx import checker
from onnx import helper
from onnx import TensorProto
import code
import logging
import sys
import types
import chainer
import numpy
from ch2o.test_args import dprint
from ch2o.env import Env
from ch2o.util... |
# -*- coding: utf-8 -*-
# ----------------------------------------------------------
# SLT_DCM - fMRI TRAINING
#
# Preamble
#
#
# ----------------------------------------------------------
# --------
# Librarys
# --------
from __future__ import division
import viz
import vizact
import vizinput
import vizshape
imp... |
# Copyright (C) 2017 Beijing Didi Infinity Technology and Development Co.,Ltd.
# 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/LI... |
# -*- coding: utf-8 -*-
# Copyright (c) 2015, Sambhaji Kolate and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class VendorInvoice(Document):
pass
|
import csv
if __name__ == '__main__':
used_ports = set()
with open('iana.csv') as f:
reader = csv.DictReader(f)
for row in reader:
port = row['Port Number'].strip()
if port:
try:
used_ports.add(int(port))
except ValueE... |
# Copyright 2015-2016 Stanford University
#
# 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 ... |
from Queue import Empty
from collections import defaultdict
import os
import random
import time
import multiprocessing as mp
from multiprocessing import Process
from setproctitle import setproctitle
import traceback
from bunch import Bunch
import numpy as np
from ml_utils import chunks
import ml_utils
def get_dirs(... |
from urlobject import URLObject
from st_library.utils.helpers.store import Store
ROOT = URLObject(Store.host)
METADATA_ENDPOINT = ROOT.add_path('api/metadata/')
EXECUTION_METADATA_ENDPOINT = ROOT.add_path('api/execution-metadata/')
LOGGING_ENDPOINT = ROOT.add_path('api/logging/')
DATA_ENDPOINT = ROOT.add_path('api/d... |
import random
import unittest
from tempfile import TemporaryFile
import numpy as np
from scipy.spatial.distance import cdist
from pyclam import datasets, criterion
from pyclam.manifold import Manifold, Cluster
np.random.seed(42)
random.seed(42)
class TestManifold(unittest.TestCase):
@classmethod
def setUpC... |
from __future__ import annotations
from spark_auto_mapper_fhir.fhir_types.uri import FhirUri
from spark_auto_mapper_fhir.value_sets.generic_type import GenericTypeCode
from spark_auto_mapper.type_definitions.defined_types import AutoMapperTextInputType
# This file is auto-generated by generate_classes so do not edi... |
#!/usr/bin/python
import os
import glob
import utils
import random
import argparse
import platform
import threading
import numpy as np
from PIL import Image
from tqdm import tqdm
from math import ceil
from itertools import chain
def apply_background(back, img, path):
back.paste(img, (0, 0), img)
utils.make_dirs(path... |
from haystack.nodes.file_converter.base import BaseConverter
from haystack.nodes.file_converter.docx import DocxToTextConverter
from haystack.nodes.file_converter.image import ImageToTextConverter
from haystack.nodes.file_converter.markdown import MarkdownConverter
from haystack.nodes.file_converter.pdf import PDFToTex... |
from rllab.core.serializable import Serializable
from rllab.misc import logger
import numpy as np
import tensorflow as tf
import pyprind
from rllab.sampler.utils import rollout
from sandbox.rocky.analogy.policies.apply_demo_policy import ApplyDemoPolicy
from sandbox.rocky.analogy.dataset import SupervisedDataset
from s... |
# TODO: write tests for other stores
# import asyncio
# from pathlib import Path
# from secrets import token_bytes
# import aiosqlite
# import pytest
# from tranzact.util.ints import uint32, uint64, uint128
# from tranzact.wallet.wallet_coin_record import WalletCoinRecord
# from tranzact.wallet.util.wallet_types import... |
from dump.match_infra import MatchEngine, MatchRequest, ConnectionPool
from dump.match_helper import get_matched_keys
from .db import Db
def get_port_acl_binding(db_wrap, port, ns):
"""
Verify if the port is not bound to any ACL Table
Args:
db_wrap: utilities_common.Db() object
port: I... |
#
# Copyright (c) 2019 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/LICENSE-2.0
#
# Unless required by applicable law or ... |
import pandas as pd
import numpy as np
import csv as csv
from sklearn.ensemble import RandomForestClassifier
# Load the train file into a dataframe
train_df = pd.read_csv('../data/train.csv', header=0)
# Add Gender coumn in DF such that female = 0, Male = 1
train_df['Gender'] = train_df['Sex'].map( {'female': 0, 'mal... |
import shelve
import time
class NoPersistenceLayer(object):
"""
This is a base persistence layer for storing data. It stores current value of a sensor,
and its historic value (in case net is broken and we need to restore later
Paths are to be stored WITHOUT prefix
"""
def __init__(self):
... |
from common_fixtures import *
import requests
def test_x_forwarded_for(client):
t = client.create_registration_token()
t = client.wait_success(t)
assert t.state == "active"
headers = {"X-Forwarded-For": "1.1.1.1"}
response = requests.post(t.registrationUrl, headers=headers)
assert response.status_code == 200
ass... |
# Copyright (c) 2020 Computer Vision Center (CVC) at the Universitat Autonoma de
# Barcelona (UAB).
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
from . import SyncSmokeTest
import carla
import time
import math
class Sensor():
def __init__(se... |
import numpy as np
import pandas as pd
from pandas import DataFrame
import pandas._testing as tm
import pandas.io.formats.format as fmt
class TestEngFormatter:
def test_eng_float_formatter(self):
df = DataFrame({"A": [1.41, 141.0, 14100, 1410000.0]})
fmt.set_eng_float_format()
... |
import torch
from torch.autograd import Function
from . import knn_ext
class KNN(Function):
r"""KNN (CUDA) based on heap data structure.
Modified from `PAConv <https://github.com/CVMI-Lab/PAConv/tree/main/
scene_seg/lib/pointops/src/knnquery_heap>`_.
Find k-nearest points.
"""
@staticmethod... |
from __future__ import annotations
import itertools
import unittest
from rules_python.python.runfiles import runfiles
import sudoku_solver
class TestSudokuSolver(unittest.TestCase):
def _assert_solved_instance(self) -> None:
self.assert_solved_instance(
"example_sudoku.txt",
[
... |
import pygraphviz as pgv
import numpy as np
class Person:
def __init__(self, name,id,origin=0):
self.name = name
self.id = id
self.origin=origin
self.specs=[]
def to_js(self):
specs_js = ""
for spec in self.specs:
specs_js += spec + ', '
return " { id: "+str(self.id)+", label: '"+self.name+"'... |
import typing
from features.value_types import BOOLEAN, INTEGER
def get_correctly_typed_value(value_type: str, string_value: str) -> typing.Any:
if value_type == INTEGER:
return int(string_value)
elif value_type == BOOLEAN:
return string_value == "True"
return string_value
|
# (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org)
# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
# Mostly taken from PasteDeploy and stripped down for Galaxy
import inspect
import os
import re
import sys
from typing import Callable, Dict, List, O... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
if "__main__" != __name__:
def _private():
import io
import os
import sys
import typing
import atexit
import asyncio
import argparse
from . import connection as _connection_module
_interactive_c... |
#!/usr/bin/env python3
# Copyright (c) 2012-2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Extract _("...") strings for translation and convert to Qt stringdefs so that
they can be picked up by... |
from PyQt5.QtWidgets import QApplication, QTextEdit
from PyQt5.QtGui import QTextOption
from PyQt5.QtCore import QEvent
class MarkdownTextEdit(QTextEdit):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setWordWrapMode(QTextOption.NoWrap)
self.setCursorWidth(2)
|
#!/bin/env python
import unittest
from unittest.mock import Mock
from ats.topology import Device
from genie.metaparser.util.exceptions import SchemaEmptyParserError,\
SchemaMissingKeyError
from genie.libs.parser.iosxe.show_platform import ShowVersion,\
... |
########################################################
# Program to Download Wallpapers from #
# alpha.wallhaven.cc #
# #
# Author - Saurabh Bhan #
# ... |
from gym_example.envs.Gridworld import Gridworld
#from Gridworld import Gridworld |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: v1.16.14
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import re #... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.