text stringlengths 1 927k |
|---|
import unittest
from os.path import join
from robot import api, model, parsing, reporting, result, running
from robot.api import parsing as api_parsing
from robot.utils.asserts import assert_equal, assert_true
class TestExposedApi(unittest.TestCase):
def test_execution_result(self):
assert_equal(api.E... |
from tortoise import Tortoise
from loguru import logger
from app.core.config import DB_TYPE, DB_USER, DB_PASSWORD, DB_HOST, DB_PORT, DATABASE
DB_URL = f'{DB_TYPE}://{DB_USER}:{DB_PASSWORD}@{DB_HOST}:{DB_PORT}/{DATABASE}'
async def init():
"""初始化连接"""
logger.info(f'Connecting to database')
await Tortois... |
import random
import pytest
import torch
from torch.autograd import gradcheck
import kornia
from kornia.geometry.homography import find_homography_dlt, find_homography_dlt_iterated
from kornia.testing import assert_close
class TestFindHomographyDLT:
def test_smoke(self, device, dtype):
points1 = torch.r... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib
import os
from glob import glob
from matplotlib.colors import LogNorm
from scipy.optimize import curve_fit
from astropy.table import Table
import astropy.io.fits as fits
from astropy.stats import LombSc... |
from Qt.QtCore import *
from Qt.QtGui import *
from Qt.QtWidgets import *
import findWidget_UIs as ui
class findWidgetClass(QWidget, ui.Ui_findReplace):
searchSignal = Signal(str)
replaceSignal = Signal(list)
replaceAllSignal = Signal(list)
def __init__(self, parent):
super(findWidgetClass, sel... |
import hashlib
import base64
def hash_email(email):
m = hashlib.sha256()
m.update(email.encode('utf-8'))
return base64.urlsafe_b64encode(m.digest())
def user_logging_string(user):
if user.is_anonymous:
return 'User(anonymous)'
return 'User(id={}, role={}, hashed_email={})'.format(user.i... |
import numpy as np
class Main:
def __init__(self):
self.li = list(map(int, input().split()))
self.np_li = np.array(self.li)
def output(self):
print(np.reshape(self.np_li, (3,3)))
if __name__ == '__main__':
obj = Main()
obj.output() |
"""
Common DBM Layer classes
"""
from __future__ import print_function
__authors__ = ["Ian Goodfellow", "Vincent Dumoulin"]
__copyright__ = "Copyright 2012-2013, Universite de Montreal"
__credits__ = ["Ian Goodfellow"]
__license__ = "3-clause BSD"
__maintainer__ = "LISA Lab"
import functools
import logging
import num... |
# Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.c (the "License");
# you may not use this file except in compliance with the License.
# Credits goes to @AvinashReddy3108 for creating this plugin
# edited to work on Uniborg by @Mayur_Karaniya
#
"""
This... |
##Local indexes
homeI = 0
startI = 1
# Goal area
goalI = 57 # local goal index
goalAreaStartI = 52 # local index where goal are starts
#Stars
starI = [6,12,19,25,32,38,45,51] # start indexes
starAtGoalI = 51 # star infront of goal area
#Globes
globeAtStartI = [1]
globeEnemy = [14,27,40]
globeSafeI = [1,9,22,35,48]
gl... |
from django.db.models.signals import post_save
from django.dispatch import receiver
from applications import models
# Delete DraftApplication when application submitted
@receiver(post_save, sender=models.Application)
def clean_draft_application(sender, instance, created, *args, **kwargs):
if not created:
... |
""" $lic$
Copyright (C) 2016-2019 by The Board of Trustees of Stanford University
This program is free software: you can redistribute it and/or modify it under
the terms of the Modified BSD-3 License as published by the Open Source
Initiative.
This program is distributed in the hope that it will be useful, but WITHOU... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'Z:\Users\Yintai Zhang\Research\ExperimentManger_Test_2\DDSMonitor.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_DDSMonitor(ob... |
from math import atan2, sqrt
from cereal import car
from common.numpy_fast import interp
from common.realtime import DT_DMON
from selfdrive.hardware import TICI
from common.filter_simple import FirstOrderFilter
from common.stat_live import RunningStatFilter
EventName = car.CarEvent.EventName
# **********************... |
from vivid.common import ParametersMixin
class Endpoint(ParametersMixin, object):
"""
Descriptor that describes an attribute which acts
as a function making an HTTP request. Return a
bound endpoint attached to this and the base API.
"""
def __init__(self, method, path, *parameters):
... |
import re
from typing import List
import numpy as np
# pylint: disable=too-few-public-methods
ID_SEP = re.compile(r"[-:]")
class WordAlignmentPreprocessor(object):
"""A preprocessor for word alignments in a text format.
One of the following formats is expected:
s1-t1 s2-t2 ...
s1:1/w1 s2... |
#!/usr/bin/env python
'''
DISTRIBUTION STATEMENT A. Approved for public release: distribution unlimited.
This material is based upon work supported by the Assistant Secretary of Defense for
Research and Engineering under Air Force Contract No. FA8721-05-C-0002 and/or
FA8702-15-D-0001. Any opinions, findings, conclu... |
import errno
import functools
import grp
import json
import logging
import os
import pwd
import re
from six.moves import configparser
import six
from leapp.libraries.stdlib import CalledProcessError, api, run
from leapp.models import SysctlVariablesFacts, SysctlVariable, ActiveKernelModulesFacts, ActiveKernelModule, ... |
#!/usr/bin/python
# This scripts takes the odom from TF published by Cartographer and publishes it as an individual topic. Only required when used with real robot.
import rospy
from nav_msgs.msg import Odometry
from geometry_msgs.msg import Pose, Twist
import tf
#Node to handle calculating and publishing odometry
cl... |
# -*- coding: utf-8 -*-
# Copyright 2020 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 o... |
# Copyright 2019 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... |
from __future__ import unicode_literals
import os
import asyncio
import subprocess
import youtube_dl
from Python_ARQ import ARQ
from pytgcalls import GroupCall
from sys import version as pyver
from pyrogram import Client, filters
from misc import HELP_TEXT, START_TEXT, REPO_TEXT
from functions import (
transcode,
... |
WIFI_SSID = "please enter your wifi ssid"
WIFI_PASS = "please enter your wifi password"
LINE_TOKEN= "please enter your line notify token"
MOVING_DET_DIFF = 10
MOVING_DET_LIGHT_MAX = 200 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
# Copyright (C) 2010-2011 Richard Lincoln
#
# 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, publish... |
import os
import re
import textwrap
import pytest
from conans import load
from conans.model.ref import ConanFileReference, PackageReference
from conans.test.assets.genconanfile import GenConanfile
from conans.test.utils.tools import TestClient
@pytest.fixture
def conanfile():
conan_file = str(GenConanfile().wit... |
import komand
import json
import requests
from .schema import ShutdownDropletInput, ShutdownDropletOutput
class ShutdownDroplet(komand.Action):
def __init__(self):
super(self.__class__, self).__init__(
name="shutdown_droplet",
description="Shuts down the droplet from a specified im... |
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 20 20:24:20 2011
Author: Josef Perktold
License: BSD-3
"""
from statsmodels.compat.python import range
import numpy as np
import statsmodels.base.model as base
from statsmodels.regression.linear_model import OLS, GLS, WLS, RegressionResults
def atleast_2dcols(x):
... |
import torch
import torch.nn as nn
from mmcv.runner import BaseModule
from torch.nn import functional as F
from mmcv.cnn.utils.weight_init import trunc_normal_init
from ..builder import build_loss
from ..registry import HEADS
from .cls_head import ClsHead
from openmixup.utils import print_log
@HEADS.register_module
... |
# 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, software
# distributed under the... |
"""
ASGI config for clubChinois project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_S... |
# Copyright (C) 2010 Google 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:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the f... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import codecs
import gdb
from capstone import *
import pwndbg.arguments
import pwndbg.color
import pwndbg.... |
import matplotlib
matplotlib.use('Agg')
from matplotlib.collections import PolyCollection
from numpy.fft import fft, fftfreq, fftshift
from locker import mkdir
from locker.analysis import *
from locker.data import *
from scripts.config import params as plot_params, FormatedFigure
def generate_filename(cell, contrast)... |
# -*- coding: utf-8 -*
# Copyright (c) 2019 BuildGroup Data Services, Inc.
# All rights reserved.
# This software is proprietary and confidential and may not under
# any circumstances be used, copied, or distributed.
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from caravaggio_rest... |
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2018-2019 Fetch.AI 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 ... |
import nltk
import pandas as pd
try:
import libvoikko
except ModuleNotFoundError:
from voikko import libvoikko
import logging
from nltk.corpus import stopwords
logger = logging.getLogger(__name__)
nltk.download('stopwords')
EMAIL_REGEX = (
r"(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]... |
import numpy as np
from algorithms import helpers
def test_QR(Ntests):
passed = 0
critical = 0
for _ in range(Ntests):
try:
n = np.random.randint(2, 11)
X = np.random.uniform(low=0.0,
high=100.0,
size=(n, n... |
#!/usr/bin/env python
print("Hello World!") |
'''
Created on January 2020.
@author: Soroosh Tayebi Arasteh <soroosh.arasteh@fau.de>
https://github.com/tayebiarasteh/
'''
from Layers.Base import *
import numpy as np
import pdb
from Layers import Sigmoid, FullyConnected, TanH
import copy
class LSTM(base_layer):
def __init__(self, input_size, hidden_size, out... |
# -*- coding: utf-8 -*-
# Copyright (c) 2015, MN Technique and Contributors
# See license.txt
from __future__ import unicode_literals
import frappe
import unittest
# test_records = frappe.get_test_records('EPI Catalog Listing')
class TestEPICatalogListing(unittest.TestCase):
pass |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from frappe import _
def get_data():
return [
{
"module_name": "Nodux Stock One",
"color": "darkgrey",
"icon": "octicon octicon-file-directory",
"type": "module",
"hidden": 1
},
{
"module_name": "Stock",
"_doctype": "Stock One... |
# model settings
model = dict(
type='FCOS',
pretrained='open-mmlab://resnet50_caffe',
backbone=dict(
type='ResNet',
depth=50,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_cfg=dict(type='BN', requires_grad=False),
style='caffe'),
ne... |
from scipy.io import arff
from sklearn.pipeline import Pipeline
from sklearn.utils import shuffle
from ModelScorer import ModelScorer
import pandas as pd
from Plotter import *
import warnings
#warnings.simplefilter(action='ignore', category=FutureWarning)
warnings.filterwarnings("ignore")
pd.set_option('display.expand_... |
import pytest
from seq_features import *
def test_n_neg_for_single_E_or_D():
"""Perform unit tests on n_neg."""
assert n_neg('E') == 1
assert n_neg('D') == 1
def test_n_neg_for_empty_sequence():
assert n_neg('') == 0
def test_n_neg_for_longer_sequences():
assert n_neg('ACKLWTTAE') == 1
... |
from . import cifar_resnet, densenet, my_resnet, resnet |
# This Python file uses the following encoding: utf-8
"""autogenerated by genpy from hector_uav_msgs/LandingActionGoal.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
import geometry_msgs.msg
import hector_uav_msgs.msg
import genpy
import actionlib_ms... |
from typing import Callable, Dict, Any, Union
import numpy as np
from keanu.vartypes import (numpy_types, tensor_arg_types, runtime_numpy_types, runtime_pandas_types,
runtime_primitive_types, runtime_bool_types, runtime_int_types, runtime_float_types,
primitive_... |
# Copyright 2016, 2017 IBM Corp.
#
# 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 writin... |
# -*- coding: utf-8 -*-
def create_entry(date, description, change):
return (list(map(int, date.split("-"))), description, change)
def format_entries(currency, locale, entries):
if currency == "USD":
symbol = "$"
elif currency == "EUR":
symbol = u"€"
if locale == "en_US":
he... |
from portality.lib import dataobj, swagger
from portality import models
from portality.util import normalise_issn
from copy import deepcopy
BASE_ARTICLE_STRUCT = {
"fields": {
"id": {"coerce": "unicode"}, # Note that we'll leave these in for ease of use by the
"created_date": {"coerc... |
# -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import sys
if sys.version_info[0] == 3:
xrange = range
import warnings
class TimeSuite:
sample_time = 0.1
... |
#!/home/tarasen/Studying/3kurs/kursova/Django-Agregator-Site/env/bin/python3
#
# The Python Imaging Library
# $Id$
#
# this demo script illustrates how a 1-bit BitmapImage can be used
# as a dynamically updated overlay
#
import sys
if sys.version_info[0] > 2:
import tkinter
else:
import Tkinter as tkinter
fr... |
from sklearn.datasets import load_iris
import pandas as pd
ds = load_iris()
df = pd.DataFrame(data= ds["data"], columns=ds["feature_names"])
target_names = [ds.target_names[x] for x in ds.target]
df['species'] = target_names
print(df) |
from object_detection.core.target_assigner import TargetAssigner
import tensorflow as tf
from object_detection.core import box_list
class TargetAssignerExtend(TargetAssigner):
def assign(self, anchors, groundtruth_boxes, groundtruth_labels=None,
**params):
"""Assign classification and regres... |
#
# test_util.py
#
# This source file is part of the FoundationDB open source project
#
# Copyright 2013-2018 Apple Inc. and the FoundationDB project authors
#
# 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 ... |
# Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
#
# 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://w... |
# -*- coding: utf-8 -*-
"""Experiments Metrics controller."""
import platiagro
from projects.exceptions import NotFound
class MetricController:
def __init__(self, session):
self.session = session
def list_metrics(self, project_id: str, experiment_id: str, run_id: str, operator_id: str):
"""
... |
import clip
import sys
import torch
from torchvision import transforms
from torchvision.transforms import functional as TF
from kornia import augmentation, filters
from torch import nn
from torch.nn import functional as F
import math
import lpips
from PIL import Image
sys.path.append("./guided-diffusion")
from guided... |
from django.contrib import messages
from django.core.exceptions import PermissionDenied, SuspiciousOperation
from django.db import IntegrityError, transaction
from django.db.models import Exists, Max, OuterRef, Q
from django.forms.models import inlineformset_factory
from django.shortcuts import get_object_or_404, redir... |
import shutil
from genrl.agents import A2C
from genrl.environments import VectorEnv
from genrl.trainers import OnPolicyTrainer
def test_a2c():
env = VectorEnv("CartPole-v0", 1)
algo = A2C("mlp", env, rollout_size=128)
trainer = OnPolicyTrainer(algo, env, log_mode=["csv"], logdir="./logs", epochs=1)
t... |
import os
import numpy as np
from numpy.testing import assert_allclose
import pytest
import scipy.io
import scipy.stats
import cic
def cases():
"""
Loads all filenames of the pre-calculated test cases.
"""
case_dir = os.path.join(
os.path.dirname(os.path.realpath(__file__)),
'cases'
... |
from flask import *
from peewee import *
import sys
from playhouse.shortcuts import model_to_dict, dict_to_model
from base64 import b64encode
app = Flask(__name__)
musa_db = MySQLDatabase(
"musa", host="localhost", port=3306, user="euterpe", passwd="An6248322")
class MySQLModel(Model):
"""Database model"""
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class HealthServiceFamilyDoctorDrugDTO(object):
def __init__(self):
self._catalogue_listed = None
self._dosage_forms = None
self._drug_classification = None
self._genera... |
import numpy as np
import warnings
from .._explainer import Explainer
from packaging import version
from ..tf_utils import _get_session, _get_graph, _get_model_inputs, _get_model_output
keras = None
tf = None
tf_ops = None
tf_backprop = None
tf_execute = None
tf_gradients_impl = None
def custom_record_gradient(op_name... |
import requests
import urllib.request
import time
import urllib
import re
import csv
import sys
from bs4 import BeautifulSoup
def uni_tech_sydney():
url = "https://www.uts.edu.au/about/faculty-engineering-and-information-technology/computer-science/school-computer-science-staff"
headers = {'User-Agent': 'Mozil... |
from dataset import tiny_dataset
from bbox_codec import bbox_encode
from resnet50_base import Localization_net2
from torch.utils.data import DataLoader,random_split
import torch as t
import tqdm
from torch.utils.tensorboard import SummaryWriter
import torch.nn as nn
import torch.optim as optim
import argparse
from loss... |
# Copyright 2019 TerraPower, 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 writi... |
# -*- coding: utf-8 -*-
"""
@author: Chris Lucas
"""
import math
import numpy as np
from shapely.geometry import (
Polygon, MultiPolygon, LineString, MultiLineString, LinearRing
)
from shapely import wkt
from building_boundary import utils
def line_orientations(lines):
"""
Computes the orientations of... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from numpy import array, zeros, linspace, meshgrid, ndarray
from numpy import float64, float128, complex128, complex256
from numpy import exp, sin, cos, tan, arcsin, arctan
from numpy import floor, ceil
from numpy.fft import fft, ifft
from numpy import pi
from numpy import c... |
from _warnings import warn
import matplotlib
from batchgenerators.utilities.file_and_folder_operations import *
from sklearn.model_selection import KFold
matplotlib.use("agg")
from time import time, sleep
import torch
import numpy as np
from torch.optim import lr_scheduler
import matplotlib.pyplot as plt
import sys
fro... |
# coding: utf-8
import re
import six
from huaweicloudsdkcore.sdk_response import SdkResponse
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class ListPostgresqlDbUserPaginatedResponse(SdkResponse):
"""
Attributes:
openapi_types (dict): The key is attribute name
... |
import json
import sys
from parchmint import Device
sys.path.append("/usr/lib/freecad-python3/lib")
import Draft
import FreeCAD
import Mesh
import Part
from threedprinting.components.box import Box
from threedprinting.components.connection import createConnection
from threedprinting.components.droplet import DropletG... |
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from realtor.models import Realtors, Positions
class Realtor(forms.ModelForm):
name = forms.CharField(required=True, widget=forms.TextInput(attrs={'class': 'form-control validate'}))
ema... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft and contributors. 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 ... |
from datetime import datetime, timedelta
import sqlite3
from discord import Embed, AllowedMentions
from discord.ext import commands
from pytz import timezone
class Member_Log(commands.Cog):
"""メンバー用のログ機能関連のコマンドがあります。"""
def __init__(self, bot):
self.bot = bot
self.welcome_notice = []
... |
#!/usr/bin/env python3
# -*- encoding: UTF8 -*-
from dnsuptools.dnsupdate import defaultDictList, MatchUpperLabels, DNSUpdate
from dnsuptools.tlsarecgen import tlsaRecordsFromCertFile, tlsaFromFile
from dnsuptools.dkimrecgen import dkimFromFile
from simpleloggerplus import simpleloggerplus as log
import re
import pyc... |
def add(x, y):
return x + y
def crunchNumbers():
print("How do you want me to crunch two numbers? ")
crunchFunction = input("Type add or something else: ")
num1 = input('First number: ')
num2 = input('Second number: ')
if crunchFunction == "add":
answer = add(num1, num2)
elif cru... |
from flask import Flask, render_template, request, redirect, session, flash, url_for
app = Flask(__name__)
app.secret_key = 'alura'
class Jogo:
def __init__(self, nome, categoria, console):
self.nome = nome
self.categoria = categoria
self.console = console
class Usuario:
def __init__... |
#!/usr/bin/env python3
""" A command line interface for the Deepmap API. """
import argparse
import sys
import os
from deepmap_cli.constants import USER_CONFIG_PATH
from deepmap_cli.cli_requests import make_request
def init_cli():
""" Initializes the CLI. """
parser = argparse.ArgumentParser(
prog='... |
# Условие:
# Написать простую функцию, которая будет возвращать век, на основе года.
# Пример:
# get_century(2021) -> 21
# get_century(1999) -> 20
# get_century(2000) -> 20
# get_century(101) -> 2
import unittest
def get_century(n: int) -> int:
a, b = divmod(n, 100)
return a + 1 if b > 0 else a
class Tes... |
import os
import sys
import time
import glob
import numpy as np
import torch
import utils
import logging
import argparse
import torch.nn as nn
import genotypes
import torch.utils
import torchvision.datasets as dset
import torch.backends.cudnn as cudnn
from torch.autograd import Variable
from model import NetworkCIFAR ... |
import unittest
from unittest import mock
import requests
from flask.ext.testing import TestCase
from app import db, models
from app.app import app
from config import config
from .mock_github import requests_get_stub
app.config.from_object(config['testing'])
class AppTestCase(TestCase):
def create_app(self):
... |
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
import cv2
import numpy as np
import tensorflow as tf
from tensorflow.python.saved_model import tag_constants
from yolov3.dataset import Dataset
from yolov3.yolov4 import Create_Yolo
from yolov3.utils import load_yolo_weights, detect_image, image_preprocess, postproces... |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
# Database Module
# --------------------
from __future__ import unicode_literals
import re
import time
import frappe
import datetime
import frappe.defaults
import frappe.model.meta
from frappe import _
from time impo... |
from django.contrib import admin
from .models import Chat
class ChatAdmin(admin.ModelAdmin):
list_display = ("pk",)
admin.site.register(Chat, ChatAdmin) |
#!/usr/bin/env python
# coding: utf-8
"""
The Clear BSD License
Copyright (c) – 2016, NetApp, Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below) provided that the following conditions are met... |
import unittest
from db import mssql
def connect_mssql():
obj_sql = mssql.MsSqlDb(None)
conn = obj_sql.get_connection
if conn is None:
return False
else:
return True
class MyTest(unittest.TestCase):
def test(self):
self.assertTrue(connect_mssql(), True)
if __name__... |
#!/usr/bin/env python3
import asyncio
import logging
import uuid
from bleak import BleakScanner, BleakClient
# Enable debug output
# logging.basicConfig(level=logging.DEBUG)
DEVICE_NAME = "m5-stack"
SERVICE_UUID = uuid.UUID("4fafc201-1fb5-459e-8fcc-c5c9c331914b")
CHAR_UUID = uuid.UUID("beb5483e-36e1-4688-b7f5-ea0736... |
import boto3
import configparser
def main():
"""
Description:
- Sets up a Redshift cluster on AWS
Returns:
None
"""
KEY = config.get('AWS','KEY')
SECRET = config.get('AWS','SECRET')
DWH_CLUSTER_IDENTIFIER = config.get("DWH","DWH_CLUSTE... |
import pickle
import sys
import ast
import re
import json
from word2number import w2n
import os, sys
try:
location=sys.argv[1]
except Exception as e:
location='roma'
try:
type_=sys.argv[2]
except Exception as e:
type_='needs'
with open('OUTPUT/'+location+'_'+type_+'.p','rb') as handle:
need_dict=pickle.load(h... |
import sys
from limix.core.old.cobj import *
from limix.utils.preprocess import regressOut
import numpy as np
import scipy.linalg as LA
import copy
def compute_X1KX2(Y, D, X1, X2, A1=None, A2=None):
R,C = Y.shape
if A1 is None:
nW_A1 = Y.shape[1]
#A1 = np.eye(Y.shape[1]) #for now this creates... |
# RedisEdge realtime video analytics video capture script
import argparse
import cv2
import redis
import time
from urllib.parse import urlparse
class SimpleMovingAverage(object):
''' Simple moving average '''
def __init__(self, value=0.0, count=7):
self.count = int(count)
self.current = float(v... |
"""
Module that implements the EppClient class
"""
try:
# use gevent if available
import gevent.socket as socket
import gevent.ssl as ssl
except ImportError:
import socket
import ssl
import struct
from collections import deque
import logging
from six import PY2, PY3
from past.builtins import xrang... |
import findspark
findspark.init()
from pyspark import SparkContext
from pyspark.streaming import StreamingContext
sc = SparkContext(appName="tweetStream")
# Create a local StreamingContext with batch interval of 1 second
ssc = StreamingContext(sc, 1)
# Create a DStream that conencts to hostname:port
lines = ssc.socketT... |
# Automatically generated from system headers.
# DO NOT EDIT.
import ctypes
from .syscalldef import CType, SysCallSig, SysCallParamSig
PTRACE_TRACEME = 0
PTRACE_PEEKTEXT = 1
PTRACE_PEEKDATA = 2
PTRACE_PEEKUSER = 3
PTRACE_POKETEXT = 4
PTRACE_POKEDATA = 5
PTRACE_POKEUSER = 6
PTRACE_CONT = 7
PTRACE_KILL = 8
PTRACE_SIN... |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivat... |
#!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2015 Thomas Voegtlin
#
# 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... |
import sevenbridges as sbg
from pathlib import Path
# generate the list of files
def list_files_recursively(
api,
query,
parent,
files=[],
folder_name="",
):
"""List all the files in a project.
:param api: API object generated by sevenbridges.Api()
:type api: Sevenbridges API Object
... |
import subprocess
import sys
import json
def print_time(t):
output = {
'items': [
{
'uid': 'result',
'type': 'file',
'title': t,
'subtitle': sys.argv[1],
'arg': sys.argv[1],
'icon': {
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.