text stringlengths 2 999k |
|---|
from rest_framework import permissions
class UpdateOwnProfile(permissions.BasePermission):
"""Allow users to edit their own profile"""
def has_object_permission(self, request, view, obj):
"""Check user is trying to edit their own profile"""
if request.method in permissions.SAFE_METHODS:
... |
"""Test OdT reading and writing."""
from io import StringIO
import pytest
import gio
def test_read_odt():
"""Test the basics.
"""
ds = gio.read_odt('data/OdT/3d_horizon/Segment_ILXL_Single-line-header.dat')
assert ds['twt'].shape == (54, 57)
assert ds['twt'].mean() - 661.88136 < 1e-5
ds = g... |
#!/usr/bin/python
'''
Extract _("...") strings for translation and convert to Qt stringdefs so that
they can be picked up by Qt linguist.
'''
from __future__ import division,print_function,unicode_literals
from subprocess import Popen, PIPE
import glob
import operator
import os
import sys
OUT_CPP="qt/quicknodesstrings... |
__copyright__ = "Copyright (c) 2021 Jina AI Limited. All rights reserved."
__license__ = "Apache-2.0"
from jina import Flow
from ...minranker import MinRanker
def test_integration(documents_chunk):
with Flow().add(uses=MinRanker, uses_with={'metric': 'cosine'}) as flow:
resp = flow.post(on='/search', in... |
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 22 03:15:03 2016
@author: utkarsh
"""
# RIDGEFILTER - enhances fingerprint image via oriented filters
#
# Function to enhance fingerprint image via oriented filters
#
# Usage:
# newim = ridgefilter(im, orientim, freqim, kx, ky, showfilter)
#
# Arguments... |
import inspect
from .task import *
def dir_classes(cls):
for member_name in dir(cls):
member = getattr(cls, member_name)
if (not member_name.startswith('_')) and inspect.isclass(member):
yield member
def default_predicate(task):
return True
def get_tasks(cls, predicate = default_p... |
from sklearn.linear_model import LinearRegression
from skpro.workflow.table import Table
from skpro.metrics import log_loss
from skpro.workflow import Model
from skpro.workflow.manager import DataManager
from skpro.workflow.cross_validation import grid_optimizer
from skpro.parametric import ParametricEstimator
from sk... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from typing import (
TYPE_CHECKING,
Any,
Dict,
List,
Optional,
Sequence,
Set,
Union,
... |
from hytra.pluginsystem import image_provider_plugin
import numpy as np
from libdvid import DVIDNodeService
try:
import json_tricks as json
except ImportError:
import json
class DvidImageLoader(image_provider_plugin.ImageProviderPlugin):
"""
Computes the subtraction of features in the feature vector
... |
"""Class with result of TweetSearchRunner task."""
from dataclasses import dataclass
@dataclass
class SearchTweetsResult:
"""Class with result of TweetSearchRunner task."""
downloaded_count: int
|
#!/usr/bin/python
# -*- coding:utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
# 数据
Y = np.random.normal(loc=0.0, scale=1.0, size=10000)
X = np.random.random(size=10000)
# 例子 1:
plt.figure()
_ = plt.hist2d(X, Y, bins=25)
plt.show()
# 例子 2:
plt.figure()
_ = plt.hist2d(X, Y, bins=100)
# add a colorbar le... |
# coding=utf-8
"""
"""
import unittest
import os
from md_utils.md_common import silent_remove, diff_lines
from md_utils.plot_csv import main
__author__ = 'mayes'
DATA_DIR = os.path.join(os.path.dirname(__file__), 'test_data')
CSV_DIR = os.path.join(DATA_DIR, 'plot_csv')
CSV_FILE = os.path.join(CSV_DIR, 'identity.cs... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.test import TestCase
from django.test import Client
class BorgTestCase(TestCase):
def setUp(self):
self.robots_client = Client()
self.robots_response = self.robots_client.get("/robots.txt")
self.humans_client = Client()
s... |
from lk_db.ents.Ent import Ent
class EntPerson(Ent):
pass
|
# Copyright(c) Microsoft Corporation.
# Licensed under the MIT license.
import pip
import sys
import warnings
from distutils.version import LooseVersion
pipversion = LooseVersion(pip.__version__ )
if pipversion >= LooseVersion("19.3"):
from wheel import pep425tags
from pip._internal.main import... |
#!/usr/bin/env python
#
# Copyright 2015 Google 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 requir... |
def DNA_strand(dna):
n=[]
for i in range(len(dna)):
if dna[i]=='A':
n.append('T')
break
elif dna[i]=='T':
n.append('A')
break
elif dna[i]=='C':
n.append('G')
break
else:
n.append('C')
... |
#!/usr/bin/env python3.7
import os, sys
import urllib.request
import xml.etree.ElementTree as ET
import pprint
# Append module path for the example, since we're in a sub directory
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
from lib.forecast import generateForecast
# Read the airpor... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Created on 26/10/2014
@author: Vagner Clementino
@summary: Classe que gerencia o lançamento de exceção para todo o software
@version: 0.9
'''
from control_asfbugscaper.LogManager import LogManager
class ASFBugScraperError(Exception):
'''
Classe para gere... |
from sims.sim_info_tests import SimInfoTest
import caches
import sims.sim_info_types
@caches.cached
def get_disallowed_ages(affordance):
disallowed_ages = set()
for test in affordance.test_globals:
if isinstance(test, SimInfoTest):
if test.ages is None:
continue
... |
from .low.node import Node
from .data import Data
from .low.metadata import Metadata, Properties
from uuid import UUID
from typing import Set, List, Union
class DataSet(Node):
def __init__(self,
data_set_name: str,
parent,
bucket,
uuid: Union[Non... |
import _plotly_utils.basevalidators
class SizeValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(
self,
plotly_name='size',
parent_name='scattermapbox.marker.colorbar.title.font',
**kwargs
):
super(SizeValidator, self).__init__(
plotly_na... |
#!/usr/bin/env python
import struct
fp = open("basindepth_OpenSHA.txt", "r")
map = {}
def keyGen(lat, lon):
return str(lat) + "_" + str(lon)
minLat = 999.0
minLon = 999.0
maxLat = -999.0
maxLon = -999.0
inc = 0.01
print "loading ascii"
num = 0
for line in fp:
line = line.strip()
split = line.split()
lat ... |
#!/usr/bin/env python
#
# Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# 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... |
# coding = utf-8
import os
import datetime
import sys
Date = datetime.datetime.now()
environ = os.environ
UserName = environ['USER']
UserHome = environ['HOME']
ExcutableName = os.path.split(sys.argv[0])[-1].split('.')[0] |
""" This module gathers optimization functions."""
# Authors: Hamza Cherkaoui <hamza.cherkaoui@inria.fr>
# License: BSD (3-clause)
import time
import warnings
import numpy as np
from scipy.optimize.linesearch import line_search_armijo
def fista(grad, obj, prox, x0, momentum=True, max_iter=100, step_size=None,
... |
def checkout(cash: float, list: dict) -> float:
"""
build a function that sums up the value of the grocery list and subtracts that
from the cash passed into the function.
return the "change" from the cash minus the total groceries value.
"""
price = sum(list.values())
change = -(price - cash... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Port utilisation code for many switches
Copyright (c) 2021 Cisco and/or its affiliates.
This software is licensed to you under the terms of the Cisco Sample
Code License, Version 1.1 (the "License"). You may obtain a copy of the
License at
https://develop... |
#coding=utf-8
import os, glob
import sys
import commands
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import matplotlib.pyplot as plt
import numpy as np
import string
import random
import time
import uuid
import shutil
import operator
import cv2
import numpy as np
import codecs
reload(sys)
sys.setde... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# **************************************************************************
# Copyright © 2017-2020 jianglin
# File Name: elasticsearch_backend.py
# Author: jianglin
# Email: mail@honmaple.com
# Created: 2017-09-20 15:13:22 (CST)
# Last Update: Monday 2020-05-18 22:53:15 (... |
#!/usr/bin/python3
"""
Simple NordVPN Prometheus Exporter
"""
import re
import subprocess
import os
import argparse
from flask import Flask
from prometheus_client import make_wsgi_app, Gauge, Info, Counter
from waitress import serve
__author__ = "veerendra2"
__license__ = "Apache 2.0"
__maintainer__ = "veerendra2"
... |
#!/usr/bin/env python3
# Copyright (c) 2014-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 mempool limiting together/eviction with the wallet
from test_framework.test_framework import Bitc... |
"""sv_test_34274 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from... |
# http://wiki.glidernet.org/wiki:ogn-flavoured-aprs
# For ADSB data type is always UNKNOWN
label_by_type = {
"UNKNOWN": "Unknown",
"GLIDER": "Fixed wing aircraft",
"TOWPLANE": "Fixed wing aircraft",
"HELICOPTER": "Helicopter",
"PARACHUTE": "Parachute",
"DROPPLANE": "Fixed wing aircraft",
"FI... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The setup script."""
from setuptools import find_packages
from setuptools import setup
with open("README.md", "r") as f:
readme = f.read()
with open("requirements.txt", "r") as f:
requirements = f.readlines()
with open("test-requirements.txt", "r") as f:
... |
import Levenshtein
import json
from string_util import cleanString, convert_html_entities
'''
This script merges event locations from camp-locations-2013.json
into events from playaevents-events-2013.json
(The Playa Events API Events feed)
'''
# Threshold under which to discard partial string matches
MATCH_... |
from django.conf.urls import url
from . import views
from django.conf import settings
from django.conf.urls.static import static
#app_name = 'pictures'
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^search/', views.search_results, name='searchresults'),
url(r'^location/(?P<location>\w+)/', ... |
from scipy.cluster.vq import kmeans
import numpy as np
import pymc3 as pm
import theano.tensor as tt
cholesky = pm.distributions.dist_math.Cholesky(nofail=True, lower=True)
solve_lower = tt.slinalg.Solve(A_structure='lower_triangular')
solve_upper = tt.slinalg.Solve(A_structure='upper_triangular')
solve = tt.slinalg.... |
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
from mpl_toolkits.axes_grid1 import make_axes_locatable
from pyadlml.dataset.stats import contingency_duration, contingency_triggers,\
contingency_triggers_01
from pyadlml.dataset.plot.util import func_formatter_seconds2time, \
heatmap_square... |
from django.contrib.contenttypes.fields import (
GenericForeignKey, GenericRelation,
)
from django.contrib.contenttypes.models import ContentType
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
friends = models.ManyToManyFiel... |
#!/usr/bin/python
#
# Copyright: Ansible Team
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
... |
import os
import csv
import locale
import copy
budget = os.path.join("Resources","budget_data.csv")
date = []
profit =[]
months = 0
total_profit = 0
average = 0
increase = []
decrease = []
new_prof = []
average_p = 0
d_month = 0
d_index = []
i_month = 0
with open(budget, newline='') as csvfile:
csvreader = csv... |
# --------------------------------------------------------
# OpenVQA
# Written by Yuhao Cui https://github.com/cuiyuhao1996
# --------------------------------------------------------
from openvqa.core.base_cfgs import BaseCfgs
class Cfgs(BaseCfgs):
def __init__(self):
super(Cfgs, self).__init__()
... |
from __future__ import annotations
from functools import wraps
from sys import getsizeof
from typing import (
TYPE_CHECKING,
Any,
Callable,
Collection,
Hashable,
Iterable,
List,
Sequence,
Tuple,
cast,
)
import warnings
import numpy as np
from pandas._config import get_option
... |
def has_model_changed(old: dict, new: dict):
exc = ['last_changed_on', 'last_changed_by']
items = (i for i in old.items() if i[0] not in exc)
for ok, ov in items:
if new.get(ok) != ov:
return True
return False
|
#
# Copyright (c) 2013-2018 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# All Rights Reserved.
#
from cgtsclient.common import utils
from cgtsclient import exc
from cgtsclient.v1 import ihost as ihost_utils
from cgtsclient.v1 import istor as istor_uti... |
"""
Setup file for pyflow.
Use setup.cfg to configure your project.
This file was generated with PyScaffold 4.1.1.
PyScaffold helps you to put up the scaffold of your new Python project.
Learn more under: https://pyscaffold.org/
"""
from setuptools import setup
if __name__ == "__main__":
try:
... |
# qubit number=3
# total number=12
import numpy as np
from qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ
import networkx as nx
from qiskit.visualization import plot_histogram
from typing import *
from pprint import pprint
from math import log2
from collectio... |
from __future__ import unicode_literals
import errno
import os
import shlex
import subprocess
import sys
import syslog
import time
from traceback import format_exception
from cyder.base.mixins import MutexMixin
from cyder.base.utils import (
copy_tree, dict_merge, Logger, run_command, set_attrs, shell_out)
from c... |
# -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.async_support.base.exchange import Exchange
# -----------------------------------------------------------------------------
try... |
#!/usr/bin/python
try:
integer_types = (int, long)
except NameError: # Python 3
integer_types = (int,)
xrange = range
from planegeometry.algorithms.geomtools import oriented_area
from planegeometry.structures.points import Point
from planegeometry.structures.segments import Segment
def swap(L, left, ri... |
"""PlasmaPy tests and test helpers."""
from . import helpers
|
# Copyright Contributors to the Amundsen project.
# SPDX-License-Identifier: Apache-2.0
import logging
import textwrap
import time
from random import randint
from typing import (Any, Dict, Iterable, List, Optional, Tuple, # noqa: F401
Union, no_type_check)
import neo4j
import neobolt
from amundse... |
"""
tasks.filemap
~~~~~~~~~~~~~
tests/filename_map.yml validity checks
"""
import pathlib
import re
import yaml
from invoke import task # pylint: disable=3rd-party-module-not-gated
from tasks import utils
CODE_DIR = pathlib.Path(__file__).resolve().parent.parent
FILENAME_MAP_PATH = CODE_DIR / "tests" / ... |
# Copyright (c) 2020 PaddlePaddle 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 appli... |
import pytest
import python_on_whales
from python_on_whales import DockerClient, DockerException
from python_on_whales.utils import PROJECT_ROOT
pytestmark = pytest.mark.skipif(
not python_on_whales.docker.compose.is_installed(),
reason="Those tests need docker compose.",
)
docker = DockerClient(
... |
from fileops import resolve_path, get_mode, mode_isdir, auto, chdir
from printing import eprint
def complete_cd(self, text, line, begidx, endidx):
return self.directory_complete(text, line, begidx, endidx)
def do_cd(self, line):
"""cd DIRECTORY
Changes the current directory. ~ expansion is supported,... |
#!/usr/bin/env python3
# Copyright (c) 2014-2017 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 resurrection of mined transactions when the blockchain is re-organized."""
from test_framework.te... |
#!/usr/bin/python
# -*- coding:utf8 -*-
"""
Author: Haoming Chen
E-mail: chenhaomingbob@163.com
Time: 2019/12/23
Description: 使用gt信息
"""
import time
import argparse
# import vision essentials
import cv2
import numpy as np
import tensorflow as tf
import logging
# import Network
from network_MSRA152 impo... |
#
# Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
#
#
# analytics_db.py
# Implementation of database purging
#
import redis
import pycassa
from pycassa.pool import ConnectionPool
from pycassa.columnfamily import ColumnFamily
from pycassa.types import *
from pycassa import *
from sandesh.viz.constants... |
# Author : Harikrishnan
# Date: 12 Mar 2018
# import subprocess
import speech_recognition as sr
from pip._vendor import requests
# How to reach TV
url = 'http://192.168.1.8:8060/keypress/'
payload = {'key': 'val'}
headers = {}
# enter the name of usb microphone that you found using lsusb. In OSX system_profiler ... |
import typing
def is_optional(annotation):
try:
origin = annotation.__origin__
except AttributeError:
return False
if origin is not typing.Union:
return False
return annotation.__args__[-1] is type(None)
def _cast(key, value, cls):
try:
# Check if it's typing.List... |
# Copyright 2019 XLAB d.o.o.
#
# 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 wri... |
import math
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return '({:.2f}, {:.2f})'.format(self.x, self.y)
p = Point(2.34, 5.67)
print ("%.2f" % p.x)
print ("%.2f" % p.y)
point = Point(-18.5, 13.5)
print(point)
|
import bottle
from functools import wraps
from time import time
from bottle import request
from sqlalchemy.exc import SQLAlchemyError
from ICECREAM.cache import RedisCache
from ICECREAM.db_initializer import DataBaseConnectionManager
import logging
logger = logging.getLogger()
def timing(f):
@wraps(f)
def w... |
from __future__ import print_function
import os
import time
import numpy as np
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
import torch.nn.functional as F
import argparse
import distiller
import load... |
import cv2
import os
def capture():
cam = cv2.VideoCapture(0) #uses the webcam
cam.set(3, 640) #set video width
cam.set(4, 480) #set video height
face_detector = cv2.CascadeClassifier('face.xml') #uses the data from the xml file
#give the face an id
face_id = "1"
print("Starting face capture... |
import numpy
from amuse.test import amusetest
from amuse.units import units
from amuse.ext.roche_radius import Roche_Orbit, sepinsky_formula
class TestRocheRadius(amusetest.TestCase):
def test1(self):
""" Test that the basic numbers from Sepinsky are not unreasonable. """
self.assertAlmostEqual(... |
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
X, Y = np.meshgrid(np.arange(15), np.arange(10))
U = V = np.ones_like(X)
phi = (np.random.rand(15, 10) - .5) * 150
ax.quiver(X, Y, U, V, angles=phi)
print(phi)
plt.show()
|
# -*- coding: utf-8 -*-
'''
:codeauthor: :email:`David Homolka <david.homolka@ultimum.io>`
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt Testing Libs
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.unit import TestCase
fro... |
from flask import Flask,request,jsonify,render_template,Markup
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from flask_restful import Resource, Api
from flask_cors import CORS
import requests
import pprint
import json
import os
#init app
app = Flask(__name__)
basedir = os.path.absp... |
import os
from django.utils.translation import ugettext_lazy as _
# Django secret key
# (django fails to start without this)
# (we should not be using this feature in internal source codes)
SECRET_KEY = 'ingh@z0l($25krankw@=b#&5xoq&txi1lj(4qny$0t@=k-_v2^'
# source code location
BASE_DIR = os.path.dirname(os.path.abs... |
# Copyright (c) Microsoft 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 agreed to in wri... |
from nodes.collisionshape import _CollisionShape, CollisionShape, CollisionRect
from pygame import mouse
from event import Event
from typing import List
# TODO: upgrade code with help 'input' module
active_widget = None
active_events = [
False
]
last_active_events = active_events.copy()
class _RectWidget(Col... |
#!/usr/bin/env python3
import ctypes
basic_dll = ctypes.CDLL('fourier_basic.so')
basic_dll.density_fourier_capi_float.restype = ctypes.c_int
basic_dll.density_fourier_capi_float.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_long, ctypes.c_long, ctypes.c_float, ctypes.c_float]
basic_dll.dens... |
"""Test the EOS interfaces."""
__copyright__ = """
Copyright (C) 2020 University of Illinois Board of Trustees
"""
__license__ = """
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 restr... |
"""Tuya Home Assistant Base Device Model."""
from __future__ import annotations
from dataclasses import dataclass
import json
import logging
from typing import Any
from tuya_iot import TuyaDevice, TuyaDeviceManager
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entit... |
import argparse
import multiprocessing as mp
import os
import random
import numpy as np
import torch
import torch.optim as optim
import wandb
from ogb.graphproppred import Evaluator
# noinspection PyUnresolvedReferences
from data import SubgraphData
from utils import get_data, get_model, SimpleEvaluator, NonBinaryEva... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 4.0.0-a53ec6ee1b on 2019-01-22.
# 2019, SMART Health IT.
import os
import io
import unittest
import json
from . import contract
from .fhirdate import FHIRDate
class ContractTests(unittest.TestCase):
def instantiate_from(self, filename):
... |
"""Create xUnit result files."""
from datetime import timedelta
from junitparser import Failure, JUnitXml, Properties, Property, TestCase, TestSuite
from utility.log import Log
log = Log(__name__)
def generate_test_case(name, duration, status, polarion_id=None):
"""Create test case object.
Args:
n... |
# Created on Thu Oct 8 17:53:07 2015
# @author: pasca
def compute_noise_cov(cov_fname, raw):
"""
Compute noise covariance data from a continuous segment of raw data.
Employ empty room data (collected without the subject) to calculate
the full noise covariance matrix.
This is recommended for analy... |
import gym
import numpy as np
import torch
from torch import nn
from torch.autograd import Variable
from torch import optim
from torch.nn import functional as F
env = gym.make('FrozenLake-v0')
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(16, 64)
... |
#!/usr/bin/env python
#
# Use the raw transactions API to spend CRCTs received on particular addresses,
# and send any change back to that same address.
#
# Example usage:
# spendfrom.py # Lists available funds
# spendfrom.py --from=ADDRESS --to=ADDRESS --amount=11.00
#
# Assumes it will talk to a circuitd or circui... |
#
E_LEN = "No es posible operar vectores de diferente módulo"
|
import os
from pathlib import Path
import pytest
import scrapli
from scrapli import Scrape
UNIT_TEST_DIR = f"{Path(scrapli.__file__).parents[1]}/tests/unit/"
def test__str():
conn = Scrape(host="myhost")
assert str(conn) == "Scrape Object for host myhost"
def test__repr():
conn = Scrape(host="myhost"... |
import FWCore.ParameterSet.Config as cms
import RecoTracker.IterativeTracking.iterativeTkConfig as _cfg
from Configuration.Eras.Modifier_fastSim_cff import fastSim
#for dnn classifier
from Configuration.ProcessModifiers.trackdnn_cff import trackdnn
from RecoTracker.IterativeTracking.dnnQualityCuts import qualityCutDic... |
from django.conf.urls import url
from django.views.generic.base import RedirectView
from .views import (
ProductCreateView,
ProductDetailView,
ProductDownloadView,
ProductListView,
ProductUpdateView,
... |
#-----------------------------------------------------------------------------
# Copyright (c) 2013, PyInstaller Development Team.
#
# Distributed under the terms of the GNU General Public License with exception
# for distributing bootloader.
#
# The full license is in the file COPYING.txt, distributed with this softwa... |
from typing import List, Any
from deliverable_model.batch_like_dict import BatchLikeDict
class Response(BatchLikeDict):
def __init__(self, data: List[Any]):
self.data_history = []
self["data"] = data
@classmethod
def from_dict(cls, data) -> "Response":
self = cls(None)
fo... |
#!/usr/bin/env python2
#
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
from test_framework.mininode import *
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
import logging
... |
from django import template
from django.contrib.contenttypes.models import ContentType
from django.urls import reverse
from ..forms import CommentForm
from ..hooks import hookset
from ..models import Comment
register = template.Library()
@register.filter
def can_edit_comment(comment, user):
return hookset.load_... |
from .mapper import ApiResponse, ApiResponseInterface
from .mapper.types import Timestamp, AnyType
from .model import Reel
from .model.unpredictable import ReelUnpredictableContainer
__all__ = ['ReelsMediaResponse']
class ReelsMediaResponseInterface(ApiResponseInterface):
reels_media: [Reel]
reels: ReelUnpre... |
#!/usr/bin/env python3
# Multiplication table (from 2 to 6)
numbers = [2,3,4,5,6]
for num in numbers:
# Iterate 12 times from i = 1 to 12
for i in range(1, 13):
print(i, 'x', num, '=', num*i, end="\t")
|
import logging
from reconcile.utils import gql
from reconcile import queries
from reconcile.utils.jenkins_api import JenkinsApi
INSTANCES_QUERY = """
{
instances: jenkins_instances_v1 {
name
token {
path
field
version
format
}
plugins
}
}
"""
QONTRACT_INTEGRATION = "jenk... |
def SelectHullsMask(*args, **kwargs):
pass
def PolygonCollapseFaces(*args, **kwargs):
pass
def PaintGrid(*args, **kwargs):
pass
def TwoPointArcToolOptions(*args, **kwargs):
pass
def TwoSideBySideViewArrangement(*args, **kwargs):
pass
def ResetLattice(*args, **kwargs):
pass
def PaintE... |
import re
from textwrap import dedent
from parso.python.token import PythonTokenTypes
from parso.python import tree
from parso.tree import search_ancestor, Leaf
from parso import split_lines
from jedi._compatibility import Parameter
from jedi import debug
from jedi import settings
from jedi.api import classes
from je... |
version_info = (5, 6, 0)
pre_info = ''
dev_info = ''
def create_valid_version(release_info, epoch=None, pre_input='', dev_input=''):
'''
Creates a pep440 valid version of version number given a tuple integers
and optional epoch, prerelease and developmental info.
Parameters
----------
release_... |
#!/usr/bin/env python
# Copyright (c) 2014 Freescale Semiconductor, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# o Redistributions of source code must retain the above copyright notic... |
# ---------------------------------------------------------------------
# Vendor: Brocade
# OS: CER-ADV
# ---------------------------------------------------------------------
# Copyright (C) 2007-2013 The NOC Project
# See LICENSE for details
# ---------------------------------------------------------------------
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.