content stringlengths 5 1.05M |
|---|
from mist.api.clouds.models import Cloud
from mist.api.exceptions import PolicyUnauthorizedError, CloudNotFoundError
from mist.api import config
import logging
logging.basicConfig(level=config.PY_LOG_LEVEL,
format=config.PY_LOG_FORMAT,
datefmt=config.PY_LOG_FORMAT_DATE)
log =... |
#!/usr/bin/python3
import getpass
from tools.secret_manager import SecretManager
if __name__ == '__main__':
sec = SecretManager()
print('Setting up credentials to thermal camera:\n')
login = input('Please enter login: ')
password = getpass.getpass('Please enter password: ', stream=None)
ip = input... |
import dataclasses
import enum
import typing
from vkmodels.bases.object import ObjectBase
@dataclasses.dataclass
class AppPost(
ObjectBase,
):
id: typing.Optional[int] = None
name: typing.Optional[str] = None
photo_130: typing.Optional[str] = None
photo_604: typing.Optional[str] = None
@datacla... |
"""
functions for calculating theoretical noise levels of LOFAR equipment.
For more information about the math used here read the `sensitivity of the
LOFAR array page
<http://www.astron.nl/radio-observatory/astronomers/lofar-imaging-capabilities-sensitivity/sensitivity-lofar-array/sensiti>`_.
To check the values calc... |
''' Conversion script for writing teq_csv format to png '''
import sys
from collections import defaultdict
import graphviz as gv
_styles = {
'graph': {
'label': 'Operation Graph',
'fontsize': '16',
'fontcolor': 'white',
'bgcolor': '#333333',
'rankdir': 'BT',
},
'no... |
# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-
# ex: set sts=4 ts=4 sw=4 noet:
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the datalad package for the
# copyright and license terms.
#
# ## ### ##... |
# -*- coding: utf-8 -*-
from Products.Five.browser import BrowserView
CALL_RESULT = 'Browser view call result'
class TestingBrowserCallView(BrowserView):
def index(self):
""" """
return CALL_RESULT
|
from django.conf import settings
from django.contrib import admin
from topics.models import Topic, TopicCollection
class TopicAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("name",)}
list_display = ('name', 'category')
search_fields = ('name', 'category')
class Media:
js = [setti... |
#!/usr/bin/python
######################################
# @file histogram.py
# @author Douglas Applegate
# @date 5/29/07
# @brief outputs a histogram in lc format given input lc format & bin structure
######################################
from optparse import OptionParser
import os
import re
import sys
############... |
from pandocfilters import toJSONFilter, toJSONFilters, Math, Para, Image, RawInline, Str, LineBreak
import sys
import re
import os
def processImage(key, value, _format, _meta):
if key == "RawInline":
[format, source] = value
if source.startswith('<br'):
return LineBreak()
else:
imageSource =... |
from pytorch_lightning.metrics.regression.mean_squared_error import MeanSquaredError
from pytorch_lightning.metrics.regression.mean_absolute_error import MeanAbsoluteError
from pytorch_lightning.metrics.regression.mean_squared_log_error import MeanSquaredLogError
from pytorch_lightning.metrics.regression.explained_vari... |
# Copyright 2019 DeepMind Technologies Limited
#
# 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 agr... |
import re
import string
from copy import deepcopy
class SingletonMeta(type):
_instance = None
def __call__(self):
if self._instance is None:
self._instance = super().__call__()
return self._instance
class Designs(list, metaclass=SingletonMeta):
def add_design(self, spec):
... |
def is_iterable(candidate)->bool:
"""Return boolean representing whetever given object is an iterable.
candidate, object to identify iterability property of.
"""
try:
iter(candidate)
return True
except TypeError:
return False |
import django_tables2 as tables
from django_tables2 import A
def shorten_hash_text(record):
return record['hash'][:10] + '...' + record['hash'][-10:]
class OverviewTable(tables.Table):
height = tables.Column(orderable=False)
hash = tables.LinkColumn('presenter:detail', args=[A('hash')], orderable=False,... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
from pdb import set_trace
from prjmgr import PrjMgr
import pprint
import json
import os
__date__ = "27-07-2021"
__version__ = "1.2.1"
__author__ = "Marta Materni"
def pp(data, wd=60):
return pprint.pformat(data, indent=2, width=wd)
class TeimPrjText(ob... |
import re
import os
import yaml
import pickle
import argparse
import pandas as pd
import numpy as np
import multiprocessing as mp
import project.evaluation.run as r
from os.path import exists
from d... |
# Based on the astropy test suite (v4.2.1)
# (https://github.com/astropy/astropy/blob/v4.2.1/astropy/cosmology/tests/test_cosmology.py)
from io import StringIO
from typing import Type
import numpy as np
import pytest
import torch
from pytest import mark
from torch import tensor
import phytorch.cosmology.drivers.analy... |
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('',
url('^robots.txt$', 'base.views.robots'),
url('^services/graphite/(prod|stage|trunk)$', 'base.views.graphite',
name='graphite'),
url('^services/monitor$', 'base.views.monitor', name='monitor'),
url('^services/setting... |
import numpy as np
import os
import pickle
from PIL import Image
#**************************************************************************
file_Name = "PICKEL/New.pkl"
img_data_list=[]
#**************************************************************************
data_path='New'
data_dir_list = os.listdir(d... |
import pygame
from pygame.locals import QUIT, KEYDOWN, KEYUP, K_d, K_a, K_w, K_s, Rect
import math
tela = pygame.display.set_mode((800, 600), 0, 32)
r1 = {"rect":Rect((100, 100), (200, 100)),
"velX":0, "velY":0, "cor":(255, 0, 0)}
cor = (0, 0, 255)
h = 1
a = 87.0 / 180.0 * math.pi
vel = 200.0
tempo = 1.0
acc = 0.... |
import math
import IceRayCpp
def name( ):
return "line"
def make( P_height = 1 + 1 + (math.sqrt(5)-1)/2, P_sample = 32 ):
line = IceRayCpp.LightLine()
line.start( IceRayCpp.MathTypeCoord3D().load( -2, -2, P_height ) )
line.end( IceRayCpp.MathTypeCoord3D().load( 2, 2, P_height ) )
... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 6 11:36:21 2021
@author: Gloria Lee
"""
# Updated 06/11
# Import Packages
from serial import Serial
import time
import sys
import csv
import math
# Protocol Class takes in input from the GUI and sends to optoplate and platereader
class Protocol(object):
# GUI Inputs... |
"""Tests for task helpers"""
import pytest
from channels import task_helpers
from open_discussions.features import HOT_POST_REPAIR
@pytest.mark.parametrize("delay", [200, 100])
def test_maybe_repair_post_in_host_listing(mocker, settings, delay):
"""Test that maybe_repair_post_in_host_listing triggers the task co... |
from __future__ import division
from cyvlfeat.sift.dsift import dsift
from cyvlfeat.sift.sift import sift
import numpy as np
from numpy.testing import assert_allclose
from cyvlfeat.test_util import lena
img = lena().astype(np.float32)
half_img = img[:, :256]
def test_dsift_non_float_descriptors():
i = img.copy(... |
# -*- coding: utf-8 -*-
import dataiku
from dataiku import pandasutils as pdu
import pandas as pd
import numpy as np
import os
import census_resources
import common
from dataiku.customrecipe import *
import feature_selection
import census_metadata
import random
process_date = common.get_date()
#----------------------... |
import subprocess
def check_packages_security(full_report=True):
"""Using safety package, check out the known vulnerabilities
of the installed packages.
For more details you can look at the package page :
https://github.com/pyupio/safety
Parameters
----------
full_report: True
W... |
#############################################################
## ##
## Copyright (c) 2003-2017 by The University of Queensland ##
## Centre for Geoscience Computing ##
## http://earth.uq.edu.au/centre-geoscience-computing ##
## ... |
# Copyright 2017-2019 Amazon.com, Inc. or its 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. A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file ... |
"""empty message
Revision ID: 94d2c442fe79
Revises: 72790a2cd07f
Create Date: 2017-09-26 12:42:12.279919
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '94d2c442fe79'
down_revision = '72790a2cd07f'
branch_labels = None
depends_on = None
def upgrade():
# ... |
import matplotlib.pyplot as plt
import numpy as np
import scipy.io as scio
from sklearn import svm
import plotData as pd
import visualizeBoundary as vb
import gaussianKernel as gk
# ===================== Part 1: Loading and Visualizing Data =====================
# We start the exercise by first loading and visualizing... |
# Copyright (c) 2019 Markus Ressel
# .
# 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 rights
# to use, copy, modify, merge, publis... |
import re
class Tools():
def Convert(self, number):
number_type = Tools.TypeCheck(self, number)
if number_type == False:
return False
print(f"Konwertowanie {number_type.upper()}: {number}")
if number_type == "binarna":
binarna = number
# Liczba sz... |
print('GERADOR DE PA: ')
print('-=-'*10)
termo = int(input('Primeiro termo: '))
razao = int(input('Razão da PA: '))
termos = 0
cont = 1
while cont <= 10:
print(f'{termo} -> ',end='')
termo += razao
cont+=1
termos+=1
print('PAUSA')
cont = 1
opcao = int(input('Quantos termos você quer mostrar a mais?... |
#!/usr/bin/env python
import os
BOT_COMMAND = "bender"
BOT_OPTION_NEW = "new"
BOT_OPTION_SAVE = "save"
BOT_OPTION_DISCARD = "discard"
BOT_OPTION_LIST = "list"
BOT_OPTION_EXIT = "exit"
BOT_OPTION_HELP = "help"
BOT_ATTR_TAGS = "--tags"
BOT_UNICODE = u"\U0001F916"
file_list = []
user_contents = ""
is_content_mode = ... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# addressbook
# https://github.com/tgorka/addressbook
#
# Copyright (C) 2016 Tomasz Gorka <http://tomasz.gorka.org.pl>
#
import unittest
import addressbook
from addressbook import exception
import tests
class ApiTestCase(unittest.TestCase):
"""
Test case of th... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pymoo.factory import get_problem, get_performance_indicator, get_reference_directions, get_visualization
from pymoo.performance_indicator.hv import Hypervolume
import os
import sys
# important methods -> ref_point
ref_point = np.array([ 2.9699... |
# Copyright 2013-2015 ARM Limited
#
# 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 w... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import math
from collections import OrderedDict
from torch.autograd import Variable
import os
from torch import Tensor
class OUNoise:
def __init__(self, action_dimension, scale=0.1, mu=0, theta=0.15, sigma=0.2):
self.act... |
##########################################################################
#
# pgAdmin 4 - PostgreSQL Tools
#
# Copyright (C) 2013 - 2020, The pgAdmin Development Team
# This software is released under the PostgreSQL Licence
#
##########################################################################
from flask_babelex... |
from layeredGraphLayouter.iLayoutProcessor import ILayoutProcessor
from layeredGraphLayouter.containers.constants import NodeType, PortType,\
PortSide, PortConstraints
from layeredGraphLayouter.containers.lNode import LNode
from copy import copy
from layeredGraphLayouter.containers.lGraph import LGraph
from layere... |
#
# * The source code in this file is based on the soure code of NumPy.
#
# # NLCPy License #
#
# Copyright (c) 2020-2021 NEC Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are... |
#!/usr/bin/env python
# Copyright 2016 OpenMarket Ltd
# Copyright 2020 The Matrix.org Foundation C.I.C.
#
# 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/... |
# encoding: utf-8
# module Wms.RemotingObjects.Barcodes.ColliReferences calls itself ColliReferences
# from Wms.RemotingObjects,Version=1.23.1.0,Culture=neutral,PublicKeyToken=null
# by generator 1.145
# no doc
# no important
from __init__ import *
# no functions
# classes
class ColliBarcodeResult(object):... |
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.backends im... |
"""Adapted from:
@longcw faster_rcnn_pytorch: https://github.com/longcw/faster_rcnn_pytorch
@rbgirshick py-faster-rcnn https://github.com/rbgirshick/py-faster-rcnn
Licensed under The MIT License [see LICENSE for details]
"""
from __future__ import print_function
import torch
import torch.nn as nn
import to... |
from datetime import timedelta
from typing import Dict, Optional, List
import pytest
from pytest import fixture
from resotocore.error import NoSuchTemplateError
from resotocore.query.model import Template
from resotocore.query.template_expander import render_template, TemplateExpanderBase, TemplateExpander
from resot... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may... |
#
# Copyright (c) 2018 ISP RAS (http://www.ispras.ru)
# Ivannikov Institute for System Programming of the Russian Academy of Sciences
#
# 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
#
# h... |
"""
Running tests for django without using django-admin.py
Or using manage.py.
Bassically runnig just by executing this file.
Thanks to:
- http://stackoverflow.com/q/3841725/636136
- http://stackoverflow.com/a/3851333/636136
- http://stackoverflow.com/a/12260597/636136
"""
import os
import sys
import djan... |
import errno
import requests
from twisted.python import log
import delbert.plugin
class Weather(delbert.plugin.Plugin):
"""
Plugin that handles looking up weather at various locations.
"""
def __init__(self, config={}):
super(Weather, self).__init__('weather')
self._api_key = None
... |
import logging
import pytest
import uuid
from pygame.math import Vector2
import pygame
import random
import cv2
import math
from .base_render import BaseRender
from .env_render import EnvRender
from gobigger.utils import FOOD_COLOR, THORNS_COLOR, SPORE_COLOR, PLAYER_COLORS, BACKGROUND, RED, WHITE
from gobigger.utils i... |
"""
This code here has some functions that we will call in our tests.
"""
import os.path as path
def add(a: int, b: int) -> int:
"""
A simple function for adding 2 numbers
:param a: first term
:param b: second term
:return: sum
"""
return a + b
def error() -> None:
"""
Raises an... |
# Copyright 2017 Netflix, 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... |
import logging
import aiohttp
import unittest
import aiounittest
from vcr import VCR
from hypotonic import Hypotonic
logger = logging.getLogger('hypotonic')
logger.setLevel(logging.INFO)
logger.addHandler(logging.StreamHandler())
vcr = VCR(cassette_library_dir='./tests/cassettes')
class TestHypotonic(aiounittest.A... |
'''
Author: Ligcox
Date: 2021-04-06 15:20:21
LastEditors: Ligcox
LastEditTime: 2021-07-21 16:26:50
Description:
Apache License (http://www.apache.org/licenses/)
Shanghai University Of Engineering Science
Copyright (c) 2021 Birdiebot R&D department
'''
import tensorflow as tf
from tensorflow import keras
from tensorfl... |
import argparse
import zipfile
import pathlib
import warnings
class TeamMember:
def __init__(self, first_names, last_names):
self.first_names = first_names
self.last_names = last_names
def __str__(self):
# lastname1-firstname1_lastname2-firstname2
return "-".join(self.last_nam... |
"""
A Text classification based AI that detects the
Movie review written in the .txt file,
The movie review is written in one line in the
.txt just to compress it and make the AI think it as
one whole review. Otherwise the AI thinks it as different
reviews and gives multiple predictions. But ... |
import glob
import itertools
import json
import math
import os
from datetime import datetime
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import tensorflow as tf
from IPython import display
from sklearn import metrics
from operator import itemgetter
import dataHandler ... |
from django.db.models import Q, Count
from picasso.index.models import Tag, Listing
__author__ = 'tmehta'
def get_current_tags(request):
full_tags = Tag.objects.annotate(num_listings=Count('listings')).filter(parent_tag=None, visible=True).order_by(
'-num_listings')
all_tags = Tag.objects.annotate(nu... |
from .db import database, Settings, CardTag, Card, Tag
def init(filename, **kwargs):
database.init(filename, **kwargs)
database.create_tables([Settings, Card, Tag, CardTag])
Settings.get_or_create()
|
from .xp import Experiment
from .stdout import stdout_to
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
*t4mon* - T4 monitoring functional tests
"""
from __future__ import print_function, absolute_import
import re
import tempfile
from os import sep
from test.functional_tests import base as b
import pandas as pd
import pytest
from t4mon import collector
from t4mon.sftp... |
def nba_extrap(ppg, mpg):
return 0 if ppg == 0 else round(ppg * (48 / mpg), 1) |
#!/usr/bin/python3 -u
import fileinput
def appendLine(path, line):
with open(path, "a") as f:
f.write(line + "\n")
def searchAndReplace(path, pattern, value):
for line in fileinput.input(path, inplace = True):
print line.replace(pattern, value),
def setServerAddress(address):
etm_dir = '../etm'
env_var... |
"""This module is providing some helper to report stuff running on zos
- get_public_ip_usage example:
```python
JS-NG> j.tools.zos.reporting.get_public_ip_usage()
+========================= RESERVED IPS =========================+
user: vdc_magidentfinal_test6 | tid: 1751 | wid: 7955
user: d... |
from pathlib import Path
from typing import Dict, Text
import pytest
import rasa.shared.utils.io
import rasa.utils.io
from rasa.core import training
from rasa.shared.core.domain import Domain
from rasa.shared.core.events import (
UserUttered,
ActionExecuted,
ActionExecutionRejected,
ActiveLoop,
Fo... |
# Convierte una matriz de adyacencia de ARACNe
# en una matriz completa en formato tsv
import sys, os
import pandas as pd
from pathlib import Path
fout = Path(sys.argv[1]).stem + '-complete.tsv'
lines = [line.rstrip('\n') for line in open(sys.argv[1])]
rows = []
gnames = []
c = 0
for l in lines:
vals = l.split()... |
import os
import io
import numpy as np
from PIL import Image
from abeja.datasets import Client
import torch
import torch.utils.data
import torchvision.transforms as transforms
from tensorboardX import SummaryWriter
from net import SimpleNet
from utils.callbacks import Statistics
batch_size = 32
num_classes = 2
epo... |
import datetime
def stop_watch(func, **kwargs):
# print("kwargs = {} in stop_watch()".format(kwargs))
# print("func =")
ss = str(func)
# print(ss)
func_name = ss.split()[1]
# print("func_name =")
# print("{}()".format(func_name))
s = datetime.datetime.now()
ret = func(**kwargs)
e = dateti... |
from tkinter import Tk, Label
from os import startfile, path, getcwd, chdir
def help_screen():
window = Tk()
window.geometry("250x422")
window.title("Help")
bindings = Label(window, text="---Note Bindings--- \n \n"
"[Ctrl-s] = Save Note \n"
... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : LeetCode410.py
@Time : 2020/08/22 21:22:43
@Author : kangqing
@Contact : kangqing.37@gmail.com
@Software: VS Code
@Desc : LeetCode410 分割数组的最大值
'''
# here put the import lib
from typing import List
class Solution:
def splitArray(self... |
from pyspark import SparkContext, SparkConf
if __name__ == "__main__":
conf = SparkConf().setAppName("sameHosts").setMaster("local[1]")
sc = SparkContext(conf = conf)
julyFirstLogs = sc.textFile("in/nasa_19950701.tsv")
augustFirstLogs = sc.textFile("in/nasa_19950801.tsv")
julyFirstHo... |
from datetime import timedelta
from django.utils import timezone
from lego.apps.events.models import Event, Registration
from lego.apps.events.tests.utils import get_dummy_users
from lego.apps.users.models import AbakusGroup, User
from lego.utils.test_utils import BaseTestCase
class DeleteUserTestCase(BaseTestCase)... |
"""
Created on Oct 7, 2013
@author: mmendez
"""
import pandas as pd
import os
def group(config_file, group_and_comparisons, group_id):
header = []
genes_counts = []
group = [group
for group in group_and_comparisons['group_definitions']
if group_id == group['id']][0]
for d... |
from flask import current_app as app, render_template, abort
from flask.views import MethodView
from .models import make_model, make_paginator, Category, Tag, Author
from quokka.utils.text import slugify_category, normalize_var, slugify
class BaseView(MethodView):
def set_content_var_map(self, context, content):
... |
"""This file will contain all common models"""
from enum import Enum
from typing import Optional
class RecordingType(Enum):
"""This enum represents all possible visual data types."""
UNKNOWN = 0
PHOTO = 1
VIDEO = 2
RAW = 3
def __eq__(self, other):
if isinstance(other, RecordingType):
... |
import re
import subprocess
import time
import typing
from PIL import Image, ImageDraw, ImageFont
import qrcode
BASE_IMAGE = "/home/signage/initial-screen/initial-screen-base.png"
FONT_FILE = "/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf"
OUTPUT_TO = "/var/tmp/initial-screen.png"
HOSTAPD_CONF = "/etc/hostapd/... |
import os
import sys
import time
import numpy as np
from sklearn import svm
import logging
logging.basicConfig(level=logging.INFO)
from robo.fmin import fabolas
# Example script to optimize the C and gamma parameter of a
# support vector machine on MNIST with Fabolas.
# Have a look into the paper " Fast Bayesian O... |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
##
## model.py
##
"""
The `Model` class is a lazy container for constraints and an objective function.
It is lazy in that it only stores the constraints and objective that are added
to it. Processing only starts when solve() is called, and this does not modify
... |
#!/usr/bin/env python
# Written by Henry 'Pi' James
# see LICENSE.txt for license information
from sys import *
from os.path import *
from sha import *
from BitTornado.bencode import *
NAME, EXT = splitext(basename(argv[0]))
VERSION = '20021119'
print '%s %s - change the suggested filename in a .torrent file' % (NA... |
"""Test a Survey class"""
from .asserters import *
|
import json
from typing import Dict
from responses import RequestsMock
from hollowman import conf
from hollowman.app import application
from hollowman.auth.jwt import jwt_auth, jwt_generate_user_info
from itests.util import BaseTestCase, USER_WITH_MULTIPLE_ACCOUNTS_AUTH_KEY
from tests.utils import with_json_fixture
... |
configs = {
##############################################
# Camera Settings
##############################################
'camera_res' : (1280, 720 ), # any amera: Camera width & height
'fps' : 30, # any camera: 1/10, 15, 30, 40, 90, 120, 180
'fourcc' : ... |
import unittest
import list_ops
# Tests adapted from problem-specifications//canonical-data.json @ v2.2.0
class ListOpsTest(unittest.TestCase):
# test for append
def test_append_empty_lists(self):
self.assertEqual(list_ops.append([], []), [])
def test_append_empty_list_to_list(self):
se... |
# Copyright 2017 Palantir Technologies, Inc.
import contextlib
import debug_tools
import os
import re
import sys
import pydocstyle
from pyls import hookimpl, lsp
log = debug_tools.getLogger(__name__)
# PyDocstyle is a little verbose in debug message
pydocstyle_logger = debug_tools.getLogger("pyls." + pydocstyle.util... |
"""
Classes for reading and writing pcap files
(c) 2015 Massachusetts Institute of Technology
"""
import multiprocessing
import logging
logger = logging.getLogger(__name__)
import dpkt
class PcapWriter(multiprocessing.Process):
"""
Very simple class to create a pcap file from a network stream
... |
import xmlrpc.client
from doku.cookie_safe_transport import CookiesSafeTransport
from doku.cookie_transport import CookiesTransport
class Client:
__proxy: xmlrpc.client.ServerProxy
def __init__(self, domain, username, password, ssl=True, basepath='/'):
transport = CookiesSafeTransport() if ssl else ... |
from block import *
import time
import base64
from logging import ERROR, WARN, INFO, DEBUG
class dump(Block):
def on_load(self, config):
self.config = config
self.add_port("input", Port.PUSH, Port.UNNAMED, [])
self.add_port("rpc", Port.QUERY, Port.UNNAMED, [])
self.sleep_time = config["sleep"] if con... |
import mock
import os
import unittest
from os_code_profiler.decorators.nova import \
NovaServiceProfilingException, \
Service, \
_ServiceDecorator, \
_Dumper
def fake_start(builtins=False, profile_threads=True):
raise(Exception('This should not be called'))
class FakeConfig():
def __init__(... |
import time
import unittest
import sys
from hamcrest import assert_that, less_than
from hamcrest import is_
import os
from tests.system_tests import NetmanTestApp, create_session, get_available_switch
class GunicornCompatibilityTest(unittest.TestCase):
def test_run_netman_with_a_gunicorn_wrapper(self):
... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from .oneshot import SamplingSearch
from .differentialevolution import DifferentialEvolution
from .optimizerlib import Ra... |
from nlplr.utils.context_preview.filter_traces import LogFilterTraces
from nlplr.utils.context_preview.marker import Marker
from nlplr.utils.context_preview.visualizer import HeuristicsGraph
from pm4py.objects.log.log import EventLog
import tkinter as tk
from tkinter import filedialog
from typing import List, Dict
i... |
"""
Premium Question
"""
__author__ = 'Daniel'
def read4(buf):
"""
read 4 chars to buf
:type buf: List[str]
:rtype: int
"""
return 0
class Solution(object):
def __init__(self):
self.prev = []
def read(self, buf, n):
"""
read n chars to buf, called multiple t... |
"""
Use this file to check and inspect the loaded policy. I think an easy way is to take
saved replay buffers, then plot the observations. But maybe we should support loading
a policy as well to visualize the rollouts? So this is both `teaching/offline_rl.py`
and `teaching/load_policy.py`.
Note: for now, passing in ex... |
import unittest
import munch
import basecrm
from basecrm.test.testutils import BaseTestCase
class PipelinesServiceTests(BaseTestCase):
def test_service_property_exists(self):
self.assertTrue(hasattr(self.client, 'pipelines'))
def test_method_list_exists(self):
self.assertTrue(hasattr(self.cl... |
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from CrawlerUtils.BaseDriver import CrawlerBaseDriver
from selenium.common.exceptions import InvalidSessionIdException
import random
import time
class Dri... |
# -*- coding: utf-8 -*-
from .core import Base
from .user import User, EnterpriseUser
from .tenant import Tenant
__all__ = [
'Base',
'User', 'EnterpriseUser',
'Tenant'
]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 19 18:46:29 2019
@author: tatvam
"""
# Regression Template
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
np.set_printoptions(threshold=np.inf)
# Importing the dataset
dataset = pd.read_csv('train... |
"""
Properties - Decorators
Class - PointExt3
"""
from B_Point import Point
class PointExt3(Point):
_defaut_Color = None
def __init__(self, x, y):
super().__init__(x + 2, y + 2)
self.__color = PointExt3._defaut_Color
@property
def Color(self):
return self.__... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.