content stringlengths 5 1.05M |
|---|
import json
import time
import pytest
from flask import current_app
from app.models import BlacklistToken
from app import db
from app.auth.decorators import get_token_auth_header
from app.auth.errors import AuthError
def register_user(client):
return client.post(
'/auth/register',
data=json.dumps(... |
# -*- coding: utf-8 -*-
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the... |
import os
import sys
# os.system('python ./print.py')
def if_name():
if args.imdb_name == 'voc_2007_trainval':
path = './data/VOCdevkit2007/VOC2007/ImageSets'
else:
if args.imdb_name == 'polyp_2007_trainval':
path = './data/polyp_dataset2007/VOC2007/ImageSets'
elif args.imdb_n... |
#!/usr/bin/python
# =====================================================================================================
# Author : Eric Repec (eric.repec@mysticriver.consulting)
# Version: 0.4
# Date created: 5/1/2020
# Description: Python example to post metric to OpsRamp Metric API V2
# ===========================... |
# Copyright (c) 2018, salesforce.com, inc.
# All rights reserved.
# Licensed under the BSD 3-Clause license.
# For full license text, see the LICENSE file in the repo root
# or https://opensource.org/licenses/BSD-3-Clause
import torch
from matchbox import MaskedBatch
from matchbox.compat import MAYBE_VARIABLE, TENSOR... |
from django.http import Http404
from django.utils.functional import cached_property
from bitcaster.models import Application
from bitcaster.state import state
from bitcaster.web.views.organization.mixins import SelectedOrganizationMixin
class SelectedApplicationMixin(SelectedOrganizationMixin):
permissions = ['m... |
import unittest
from ticket_cli.time_format import getTime, getDate
class DateTestCase(unittest.TestCase):
"""Tests for the two methods in time_format.py"""
unformatted_1 = '2001-03-12T21:50:50Z'
unformatted_2 = '2010-06-08T03:15:45Z'
def test_date(self):
formatted_date_1 = getDate(self.unfo... |
import os
import numpy as np
import kelpie.vasp_output_parser as vasp_output_parser
class DOSError(Exception):
"""Base class to handle error(s) related to density of states."""
pass
class DOS(object):
"""Base class to store density of states data from a calculation."""
def __init__(self, vasprunxml... |
class AdminPage:
input_login = "input-username"
input_pass = "input-password"
|
import requests
import pickle
# ##return the number of SHA keys
# for each in [ '/Users/arvindchandrasekarreddy/Desktop/SIT723/FIles /SAMPLE OF 2000/sha256_Good.txt' , '/Users/arvindchandrasekarreddy/Desktop/SIT723/FIles /SAMPLE OF 2000/sha256_bad.txt' ]:
# with open(each, "rb") as fp: # Unpickling
# ... |
class Secret():
username="d" # write the username here
password="" # write the password here
|
import logging
_logger = logging.getLogger(__name__)
from sys import stdout
import os.path
import pytest
PLOTS_DIR = os.path.join(os.path.dirname(__file__), 'plots')
SCREENSHOTS_DIR = os.path.join(os.path.dirname(__file__), 'screenshots')
logging.getLogger('matplotlib').setLevel(logging.WARNING)
def pytest_addoptio... |
# file mygame/commands/make_latin_noun.py
from evennia import Command
from evennia import create_object
# Redefining ObjManipCommand for room building
from evennia.commands.default.building import ObjManipCommand
#from evennia.utils.utils import class_from_module
from django.conf import settings
#COMMAND_DEFAULT_CLASS... |
import random
import string
import os
import requests
from itertools import cycle
import base64
from random import randint
from lxml.html import fromstring
import requests
import traceback
from colorama import init, Fore as cc
from os import system, name
from time import sleep
init()
dr = DR = r = R = cc.LIGHTRED_EX
g... |
print("[-+-] starting pdf_csv.py...")
print("[-+-] import a pdf and convert it to a csv")
# -----------------------------------------------------------------------------
print("[-+-] importing required packages for pdf_csv.py...")
import os
import tabula # simple wrapper for tabula-java, read tables from PDF into csv
... |
import logging
import urllib
def info():
try:
ip = urllib.urlopen('http://automation.whatismyip.com/n09230945.asp').read()
except Exception as e:
logging.exception(e)
ip = 'Could connect myip service'
return 'external ip: %s' % ip
|
import pytest
from pytest import raises
from .utils import staticmethods
skip = pytest.mark.skip
xfail = pytest.mark.xfail
from markup.src import html
@staticmethods
class Test_html:
def test_formats_attributes_into_open_tag():
assert html.html('hr', {'foo': 'bar'}, []) == '<hr foo="bar" />'
asse... |
from pvops import text
from pvops import text2time
from pvops import timeseries
from pvops import iv |
import numpy as np
path = 'data/'
dtimes = np.arange('2019-01-01 10:00:00', '2025-12-31 22:00:00', dtype='datetime64[m]')
print(len(dtimes))
dty = np.dtype([('Date', 'datetime64[m]'), ('No1', 'f'), ('No2', 'f')])
# Defines the special dtype object for the structured array
data = np.zeros(len(dtimes), dtype=dty)
# Ins... |
class Solution:
def XXX(self, root: TreeNode) -> bool:
def func(root1, root2):
try:
if root1.val == root2.val:
return func(root1.left, root2.right) and func(root1.right, root2.left)
else:
return False
except:
... |
def config_app(app):
app.config['DEBUG'] = True
app.config['SECRET_KEY'] = 'jdskdu29uhr2uh2uheufujhe287'
app.config['SECURITY_PASSWORD_SALT'] = b'djskhfusdifwuhfsdkjf'
app.config['SECURITY_PASSWORD_HASH'] = 'bcrypt'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////geodata/weppcloud_runs/standal... |
from redbot.core.commands import BadArgument
def positive_int(arg: str) -> int:
"""This is a type hint for Red to require a positive int
It *can* be used as a function but I wouldn't recommend it :p
"""
try:
ret = int(arg)
except ValueError: # Raised if it's not an int
raise Bad... |
import traci
import torch as T
import numpy as np
import random
import timeit
import os
# phase codes based on environment.net.xml
PHASE_EW_GREEN = 0 # action 0 code 00
PHASE_EWP_YELLOW = 1
PHASE_EW_YELLOW = 2
PHASE_NS_GREEN = 3 # action 1 code 01
PHASE_NSP_YELLOW = 4
PHASE_NS_YELLOW = 5
PHASE_EWV_GREEN = 6 # actio... |
import numpy as np
import keras
from keras import backend as K
def image_preprocessing_cam(image_data, image_size):
"""
Preprocessing for class activation maps. The function will reshape the image data and normalize it.
Arguments:
image_data : this is the image that is read in
image_size : this i... |
# Kornpob Bhirombhakdi 20200331
import numpy as np
import pandas as pd
def axeapcorr(aXeSPCdata,apcorrmod,outputpath=None):
"""
Input:
aXeSPCdata = data from SPC or opt.SPC output files from aXe reduction.
apcorrmod = model for aperture correction (i.e., apcorr = f(wavelength, apsize)).
ou... |
import os
import logging
from bs4 import BeautifulSoup
from urllib.request import urlopen
from pandas import DataFrame, read_csv
log = logging.getLogger(__name__)
default_url = "http://www.baseball-reference.com/players/gl.cgi?id=murphda08&t=b&year=2016"
def get_gamelog(url=default_url):
with urlopen(url) as web... |
# Copyright 2021 ZTE corporation. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
# pylint: disable=invalid-name
import os
import sys
import argparse
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
try:
import Masternet
from evolution_search import get_latency
except ImportError:
pri... |
from rest_framework import serializers
from resume.models import Resume
class ResumeSerializers(serializers.ModelSerializer):
def get_job_seeker(self, obj):
return {
'id': obj.job_seeker.user.id,
'full name': obj.job_seeker.user.get_full_name(),
'username': obj.job_se... |
# -*- coding:utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from yepes.fields.calculated import CalculatedField
class BooleanField(CalculatedField, models.BooleanField):
def deconstruct(self):
name, path, args, kwargs = super(BooleanField, self).deconstruct()
pa... |
""""
Copyright © Krypton 2021 - https://github.com/kkrypt0nn (https://krypt0n.co.uk)
Description:
This is a template to create your own discord bot in python.
Version: 4.1
"""
import json
import os
import platform
import random
import sys
import sqlite3
import disnake
from disnake import ApplicationCommandInteractio... |
# Copyright (c) 2020-2021, NVIDIA 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 agre... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'tanchao'
import sys
def travel_profile(hotels, reqs):
hotels.sort(key=lambda hotel: len(hotel['facilities']), reverse=True)
for req in reqs:
res = ''
for hotel in hotels:
if hotel['price'] <= req['price'] and comp(req['f... |
# Generated by Django 2.1.1 on 2018-09-17 02:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('crcapp', '0002_auto_20180909_1600'),
]
operations = [
migrations.AlterField(
model_name='customer',
name='driverLice... |
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait as Wait
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.common.by import By
from time import sleep
class Video:
"""
This class is used to provide the video information that will be s... |
from celery import Celery
from docker import APIError
from spindocker.utils import r, client, RUNNING, STOPPED
import os
celery = Celery('spin_docker',
broker='amqp://',)
# Timeout intervals
DISABLE_TIMEOUTS = os.environ.get('DISABLE_TIMEOUTS')
INITIAL_TIMEOUT_INTERVAL = int(os.environ['INITIAL_TIMEO... |
from templog.temp import TempReader
from time import sleep
from os.path import isfile
from os import remove
def test_temp_reader():
tr = TempReader()
tr.init_device()
sleep(1.1)
assert tr.get_temp() != 0
tr.cleanup()
file_name = "temp_log.h5"
assert isfile("temp_log.h5")
remove(... |
####lexikon######
neutra= ["Kind", "Auto", "Buch", "Schaf", "Schiff", "Lied", "Haus"]
feminina= ["Frau", "Mutter", "Studentin", "Gitarre", "Wolke"]
maskulina= ["Mann", "Vater", "Stundent", "Hof", "Stift"]
plurale= ["Kinder", "Autos", "Bücher", "Schafe", "Schiffe", "Lieder", "Häuser", "Frauen", "Mütter", "Studentinn... |
from __future__ import absolute_import
import re
import io
import os
import sys
import os.path
from distutils.core import setup, Extension
with io.open("src/pyrogg.pyx", encoding="iso8859-1") as f:
version = re.search('__version__\s*=\s*"([0-9.]+)"', f.read(1024)).group(1)
EXT_MODULE = "pyrogg"
setup_args = {}
D... |
#!/usr/bin/env pytest
# -*- coding: utf-8 -*-
###############################################################################
# $Id$
#
# Project: GDAL/OGR Test Suite
# Purpose: Test read/write functionality for GeoTIFF format.
# Author: Frank Warmerdam <warmerdam@pobox.com>
#
#######################################... |
# coding: utf-8
from czsc.enum import Factors, Signals
def test_factors():
for k, v in Factors.__members__.items():
if k == "Other":
continue
assert k == v.value.split("~")[0], "{} - {}".format(k, v.value)
def test_signals():
for k, v in Signals.__members__.items():
if k =... |
##############################################################################
#
# Copyright (c) 2007 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOF... |
import torch
from numpy import random
import cv2
import numpy as np
from fastapi.logger import logger
from models.experimental import attempt_load
from utils.general import (
check_img_size,
non_max_suppression,
scale_coords,
set_logging,
)
from utils.plots import plot_one_box
from utils.torch_utils im... |
# ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by Bin Xiao (Bin.Xiao@microsoft.com)
# Modified by Xingyi Zhou
# ------------------------------------------------------------------------------
from __future__ import a... |
# -*- coding: utf-8 -*-
__author__ = 'Sergey Smirnov <smirnoffs@gmail.com>'
from django.conf.urls import include, url
urlpatterns = [
url(r'^$', 'opencart.views.opencart_orders', name='opencart_orders'),
url(r'^opencart/import_last_orders/$', 'opencart.views.import_last_orders', name='import_orders'),
]
|
import os
import re
import sys
from functools import reduce
import operator
# Read arguments
if len(sys.argv) != 2:
raise ValueError('Please provide a filename input')
filename = sys.argv[1]
# Read file
file_data = open(os.getcwd() + '/' + filename, 'r')
#
# Parse file
#
matrix = []
for line in file_data.readl... |
# -*- coding: utf-8 -*-
'''
In-memory buffer interface.
'''
from __future__ import absolute_import
from __future__ import unicode_literals
# Import pythond stdlib
import logging
import datetime
log = logging.getLogger(__name__)
class MemoryBuffer(object):
'''
Memory buffer class.
'''
def __init__(s... |
#!/usr/bin/env python3
# -*- coding: iso-8859-15 -*-
from cyvec3 import vec3
v1 = vec3(3,0+4j,0)
v2 = vec3(3,2-4j,1-2j)
print(v1.length())
print(v1.square_length())
print(v1.dot(v2))
print(v2.dot(v1))
|
# import the following dependencies
import asyncio
from event_processor import log_loop
from socket_server import handler
import websockets
import global_defs
from contract_functions import load_auctions
global_defs.JOIN = {}
global_defs.AUCTIONS = {}
load_auctions()
def main():
loop = asyncio.get_event_loop()
... |
"""Management commands for quests."""
|
"""A GRU layer."""
import numpy
import random
import sys
import theano
from theano.ifelse import ifelse
from theano import tensor as T
from rnnlayer import RNNLayer
class GRULayer(RNNLayer):
"""A GRU layer.
Parameter names follow convention in Richard Socher's CS224D slides.
"""
def create_vars(self, create_... |
# ------------------------------------------------------------------------------
#
# Project: pygeofilter <https://github.com/geopython/pygeofilter>
# Authors: Fabian Schindler <fabian.schindler@eox.at>
#
# ------------------------------------------------------------------------------
# Copyright (C) 2021 EOX IT Servic... |
import cv2
frameWidth = 700
frameHeight = 500
# number plate cascade
numPlateCascade = cv2.CascadeClassifier("haarcascade_russian_plate_number.xml")
# Threshold for area
minArea = 200
color = (255,0,255)
# video on using webcam
cap = cv2.VideoCapture(0)
cap.set(3, 700) #setting width
cap.set(4, 500) #setting height
cap... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from rest_framework import serializers
from .models import Store
class StoreSerializer(serializers.ModelSerializer):
"""
Serializer for Store model
"""
class Meta:
model = Store
|
#
# Incremental Saves
# Save your blend files with an incrementing version number.
#
# Shortcut key: Shift-Ctrl-S
# * This overrides the "Save As" hotkey. If you want to keep Shift-Ctrl-S
# for "Save As", edit the hotkey below to your desired shortcut before
# you load the add-on into Blender.
# * When you disable ... |
# coding=utf-8
# Copyright 2019 The TensorFlow Datasets 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 the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... |
# @file dsc_translator_test.py
# Tests for the translator for the EDK II DSC data model object
#
# Copyright (c) Microsoft Corporation
#
# SPDX-License-Identifier: BSD-2-Clause-Patent
##
import unittest
import os
import tempfile
from edk2toollib.uefi.edk2.parsers.dsc_parser import DscParser
# from edk2toollib.uefi.edk2... |
#!/usr/bin/env python3
# @generated AUTOGENERATED file. Do not Change!
from dataclasses import dataclass
from datetime import datetime
from gql.gql.datetime_utils import DATETIME_FIELD
from gql.gql.graphql_client import GraphqlClient
from functools import partial
from numbers import Number
from typing import Any, Call... |
import torch
from torch import nn
from .modules import ConvLeakyReLU, ConvBnLeakyReLU
from .modules import SelfAttention
class MapDiscriminator(nn.Module):
'''
The Map Discriminator
Args:
map_channels (default: int=3): Number of Map input channels
roi_channels (default: int=3): Number of ... |
#
# @lc app=leetcode id=1247 lang=python3
#
# [1247] Minimum Swaps to Make Strings Equal
# https://leetcode.com/problems/minimum-swaps-to-make-strings-equal/
#
import unittest
# @lc code=start
class Solution:
def minimumSwap(self, s1: str, s2: str) -> int:
"""s1 and s2 are of equal length and only contain ... |
#!/opt/anaconda/bin python
from pageRank import MRpageRank
import time
import sys
import subprocess as sp
outPATH = '/user/lteo01/HW9/output' # Altiscale
#outPATH = '/user/root/HW9/output' # docker
SOURCE = sys.argv[1]
RUNMODE = sys.argv[2]
ITER = sys.argv[3]
D = sys.argv[4]
N = sys.argv[5]
sp.Popen(['hadoop', 'fs'... |
#!/usr/bin/env python3
"""
Description: Get pisture collections from www.toutiao.com
Tip: This script comes from https://github.com/smslit/spider-collection/tree/master/ttpic
Link: https://www.smslit.top/2018/06/21/spider-practice-pic-dog/
"""
__author__ = '5km(smslit)'
__date__ = '20180627'
import os
import requests... |
from pwtools.sql import sql_column
import pytest
def test_sql_column():
x = sql_column(key='foo',
sqltype='integer',
lst=[1,2,3])
for num, xx in zip([1,2,3], x):
assert xx.sqlval == num
assert xx.fileval == num
x = sql_column(key='foo',
... |
# Example usage
# python compute_mask.py swa4D.nii.gz mask.nii.gz
# python compute_mask.py swa*.nii mask.nii.gz
from nipy.neurospin.utils.mask import compute_mask_files
import sys
if __name__ == '__main__':
if len(sys.argv) < 3:
print """Usage : python compute_mask [ -s copyfilename ] inputfilename(s) out... |
from datetime import datetime
def convert_epoch_to_utc_datetime(epoch: int) -> datetime:
return datetime.utcfromtimestamp(epoch)
def convert_epoch_to_human_readable_date(epoch: int) -> str:
"""Convert epoch timestamp into a human readable date
Get the date (in UTC)
Args:
epoch (int):
R... |
"""
Demonstrates logical operators
"""
b1 = True #Four variables used in the demonstrations below
b2 = False
b3 = False
b4 = True
result1 = b1 and b2 #Result of b1 and'ed with b2
print("b1 and b2 is", result1) ... |
import vk_api
import requests
from time import sleep
from source.static.methods import webp_to_png
from os import remove
import logging
class VkApi:
def __init__(self, token: str):
self.vk = vk_api.VkApi(token=token)
self.logger = logging.getLogger('vk')
def get_self_id(self) -> int:
... |
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'variables': {
'hb_directory': '../third_party/externals/harfbuzz',
},
'targets': [
{
'target_name': 'harfbuzz',
'type': 'sta... |
#!/usr/bin/env python3
import testbench
import socket
class TestVirtualMachine(testbench.TestCase):
def test_binary_exists(self):
sftp = self.ssh.open_sftp()
filename = "/usr/sbin/apache2"
try:
sftp.stat(filename)
except FileNotFoundError:
self.fail("File d... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
"""
About: Basic example to test quantum connection with Qontainernet
"""
import time
import csv
import os
import numpy as np
from itertools import filterfalse
from comnetsemu.cli import CLI
from comnetsemu.net import Containernet
from mininet.link impo... |
import importlib
import inspect
from django import template
from django.template.response import TemplateResponse
from django.urls import resolve, Resolver404
from tag_parser.basetags import BaseNode
register = template.Library()
@register.tag("include_view")
class ImportViewNode(BaseNode):
min_args = 1
max... |
from django.apps import AppConfig
class AutoRestConfig(AppConfig):
name = 'auto_rest'
|
#!/usr/bin/env python3
# Copyright © 2020 Red Hat 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... |
"""Provides named imports for lambda deployment."""
from api_batch_show.main import lambda_handler as api_batch_show_lambda_handler
from api_batch_create.main import lambda_handler as api_batch_create_lambda_handler
from api_workforce_show.main import lambda_handler as api_workforce_show_lambda_handler
from api_batch_... |
# -*- coding: utf-8 -*-
__author__ = 'zhiquan'
import re
import codecs
# input_file = codecs.open("data/source.txt", 'rb', encoding='utf8')
# 暂存无页眉页脚原始文本
# output_file = codecs.open("data/source_without_header.txt", 'wb', encoding='utf8')
# 去除页眉页脚
'''page_header_re = re.compile(u"普通高等.*专业介绍")
for line in input_file... |
#Uzdevums. Noprasiet lietotājam mēneša algas apjomu un nostrādāto gadu skaitu.
#Izvadiet bonusu.
#Piemērs 5 gadu stāžs, 1000 Eiro alga, bonuss būs 450 Eiro.
salary = float(input("what is your salary "))
years = float(input("How long do you work here "))
bonuss = (years-2)*0.15*salary
bonuss = round(bonuss, 2) # s... |
from datetime import date
class TimeInterval(object):
start = None
end = None
def __init__(self, start, end):
assert start is None or isinstance(start, date), \
"start should be a date instance"
assert end is None or isinstance(end, date), \
"end should be a date i... |
from aero.Rocket import Rocket
import numpy as np
from aero.Functions.Models.Thrust import Thrust
def Mass_Non_Lin(t: float, Rocket: Rocket):
if t>Rocket.get_burn_time():
mass = Rocket.get_empty_mass() + Rocket.get_motor_mass() - Rocket.get_propel_mass()
dmassdt = 0
else:
tt = np.linsp... |
# -*- coding: utf-8 -*-
#
# Common (non-language-specific) configuration for Read The Docs & Sphinx
#
# Based on a Read the Docs Template documentation build configuration file,
# created by sphinx-quickstart on Tue Aug 26 14:19:49 2014.
#
# This file is imported from a language-specific conf.py (ie en/conf.py or
# zh_... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from django import forms
from .models import Environment,WorkOrder,WorkOrderFlow,WorkOrderGroup,Vars,VarsGroup,ConfigCenter
from django_celery_results.models import TaskResult
class ConfigCenter_form(forms.ModelForm):
class Meta:
model = ConfigC... |
import os
from shutil import copyfile
from setuptools import setup
from setuptools.command.install import install
path = os.path.dirname(os.path.realpath(__file__))
unit_dir = os.path.join(path, 'scripts', 'systemd')
class CustomInstallCommand(install):
def run(self):
if os.path.isdir('/etc/systemd/syst... |
class Node:
def __init__(self, value):
self.value = value
self.status = False
def mark_node(self):
self.status = True
def reset_node_status(self):
self.status = False
|
from typing import Sequence, Dict
import numpy as np
from abm1559.config import rng
from abm1559.utils import (
constants,
)
from abm1559.chain import Block
from abm1559.users import User, User1559
def spawn_poisson_demand(timestep: int, demand_lambda: float, UserClass, rng: np.random.Generator = rng, **kwargs)... |
#!/usr/bin/env python3
import numpy as np
import speech_recognition as sr
from subprocess import call
from time import sleep
from topics.date import DateAgent
from topics.time import TimeAgent
from topics.definition import DefinitionAgent
from topics.default import DefaultAgent
from topics.music import MusicAgent
fro... |
from fmskill.utils import make_unique_index
import pandas as pd
import warnings
from mikeio import eum
from ..observation import PointObservation, TrackObservation
from ..comparison import PointComparer, TrackComparer
from .abstract import ModelResultInterface, MultiItemModelResult, _parse_itemInfo
class _DataFrameB... |
'''
Authors: Nishant Kumar.
Copyright:
Copyright (c) 2018 Microsoft Research
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
... |
from ..Channel import Channel
from ..Utilities import counter
demFlowCounter = counter()
class DemandFlow(Channel):
"""
This is a component that will force the solver to assign a specific mass flow rate at a point in the system.
This is also used to initially introduce fluids to the engine.
It is inad... |
from django.http import HttpResponse, JsonResponse
from rest_framework.parsers import JSONParser
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import api_view, permission_classes, \
authentication_classes
fro... |
from copy import deepcopy
import math
import rastervision as rv
from genetic.semantic_segmentation_backend import (
SemanticSegmentationBackend)
from genetic.simple_backend_config import (
SimpleBackendConfig, SimpleBackendConfigBuilder)
GP_SEMANTIC_SEGMENTATION = 'GP_SEMANTIC_SEGMENTATION'
class TrainOptio... |
"""
This is module should not import any other runez module, it's the lowest on the import chain
"""
import pathlib
import re
from collections import defaultdict
from runez.system import _R, flattened, joined, stringified
def parsed_tabular(content):
"""
Args:
content (str): Tabular output, such as ... |
#
# CIN.py
#
# (c) 2020 by Andreas Kraft
# License: BSD 3-Clause License. See the LICENSE file for further details.
#
# ResourceType: ContentInstance
#
from typing import Tuple
from Constants import Constants as C
from Validator import constructPolicy
from .Resource import *
import Utils
# Attribute policies for this... |
'''
_ _ _
__| |_ _____ | | | __ _
/ _` \ \ /\ / / _ \| | |/ _` |
| (_| |\ V V / (_) | | | (_| |
\__,_| \_/\_/ \___/|_|_|\__,_|
An official requests based wrapper for the Dwolla API.
This file contains functionality for all OAuth related endpoints.
'''
import constants as c
from ... |
import torch
import torch.optim as optim
from torch.autograd import Variable
from dataloader import SVMDataset
from torch.utils.data import DataLoader
import argparse
from tensorboardX import SummaryWriter
import os
from models import SVMRegressor, Generator8, UGen, Critic3, Critic4, Critic8
import re
import pickle
imp... |
import unittest
from unittest.mock import patch, call
from unittest.mock import MagicMock
from python_sqs_consumer.processor import S3Processor, S3RecordProcessor, SQSMessageProcessor, SQSMessagesProcessor, SNSRecordProcessor
class TestProcessor(unittest.TestCase):
def test_s3_processor(self):
mock = {"R... |
import os, sys
import numpy as np
from data3d.suncg_utils.suncg_preprocess import read_summary
from data3d.suncg_utils.celing_floor_room_preprocessing import preprocess_cfr
PARSED_DIR = '/DS/SUNCG/suncg_v1/parsed'
def rename_file():
file_names = os.listdir(PARSED_DIR)
file_names.sort()
num = len(file_names)
f... |
"""
Code to experiment with writing things to xarray datasets, especially
regarding coordinates.
"""
import numpy as np
import xarray as xr
import pandas as pd
NT, NR, NC = (4,5,6)
Lon = np.linspace(-130,-122,NC)
Lat = np.linspace(42,52,NR)
lon, lat = np.meshgrid(Lon,Lat)
time = pd.date_range(start='1/1/2021', perio... |
from rest_framework import serializers
from .models import Event
class EventSerializer(serializers.ModelSerializer):
class Meta:
model = Event
fields = ('title', 'body', 'created_on')
|
test = { 'name': 'q2_1',
'points': 2,
'suites': [ { 'cases': [ { 'code': '>>> full_data.num_rows == 492\n'
'True',
'hidden': False,
'locked': False},
... |
def listtest(tlist):
tlist.append("1")
listtest(tlist)
inlist = ["0"]
listtest(inlist)
print inlist |
# -*- coding: utf-8 -*-
from yacs.config import CfgNode
from .builder import build_collate, build_folder, build_transformers, build_loader
from .config import get_datasets_cfg
__all__ = [
'get_datasets_cfg',
'build_collate', 'build_folder', 'build_transformers', 'build_loader',
]
|
from flask import render_template, flash, redirect
from app import app
@app.route('/')
@app.route('/index')
def index():
return render_template('index.html',
title='Home'
)
@app.route('/about')
def about():
return render_template('about.html',
title='About'
)
@app.route('/visualizatio... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.