content stringlengths 5 1.05M |
|---|
import os
import pyotp
import alpaca_trade_api as tradeapi
import robin_stocks.robinhood as rh
from dotenv import load_dotenv
from pathlib import Path
dotenv_path = Path('.') / '.env'
load_dotenv(dotenv_path=dotenv_path)
def initAlpaca():
ALPACA_ACCESS_KEY_ID = os.getenv("ALPACA_ACCESS_KEY_ID")
ALPACA_SECRET... |
##########################################################################
#
# Copyright (c) 2015, Image Engine Design 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:
#
# * Redistrib... |
###############################################################################
# densprofiles: a collection of parameterized density profiles
###############################################################################
from functools import wraps
import numpy
import healpy
from galpy.util import bovy_coords
_R0= 8.... |
# -*- coding: utf-8; test-case-name: bridgedb.test.test_email_request; -*-
#_____________________________________________________________________________
#
# This file is part of BridgeDB, a Tor bridge distribution system.
#
# :authors: Nick Mathewson <nickm@torproject.org>
# Isis Lovecruft <isis@torproject.o... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
import torch.nn as nn
import torch.optim as optim
from backpack import backpack
from backpack.extensions import BatchGrad
from lib.BaseAlg import BaseAlg, get_device, Network,Network_NL, obs_data_a... |
aqiRanges = (0, 50, 100, 150, 200, 300, 500)
aqiDescriptions = ("Good", "Moderate", "Unhealthy for Sensitive Groups",
"Unhealthy", "Very Unhealthy", "Hazardous")
aqiDescription = ""
pm25ranges = (0, 12, 35.4, 55.4, 150.4, 250.4, 500.4)
pm10ranges = (0, 54, 154, 254, 354, 424, 604)
no2ranges = (0, ... |
from Cryptodome.PublicKey import RSA
def gen_AB_key():
print('start generate public key and private key')
print()
gen_key_and_save('A')
gen_key_and_save('B')
print()
print('end generate public key and private key')
def gen_key_and_save(name):
publickey, privatekey = RSA_gen_key()
s... |
import uuid, yaml, json, logging, pathlib
from ignition.service.framework import Service, Capability
from ignition.service.infrastructure import InfrastructureDriverCapability
from ignition.model.infrastructure import CreateInfrastructureResponse, DeleteInfrastructureResponse, FindInfrastructureResponse, Infrastructure... |
#!/usr/bin/env python3
import numpy as np
import pandas as pd
import math
import argparse
import itertools
import csv
from scipy.stats import linregress
from scipy.optimize import minimize
read_num_seq_lineage_global = None
read_num_min_seq_lineage_global = None
read_depth_seq_global = None
t_seq_global = None
kappa_... |
'''Scrape info on series'''
from bs4 import BeautifulSoup
from requests_html import HTMLSession
import requests
import pandas as pd
import time
import os
import json
from datetime import datetime
BASE_URL = "https://fmovies.to"
start = ""
retryCount = 0
def get_last_epi(series_name, season):
query = '{0}+{1}'.fo... |
from selenium import webdriver
from requests import *
from functools import *
import re
import time
import json
headers = \
{
'Host':'tools.7881.com',
'Referer':'https://tools.7881.com/publish/b/batch',
'Sec-Fetch-Mode': 'no-cors',
'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
'use... |
"""
This file contains the functional tests for the routes.
These tests use GETs and POSTs to different URLs to check for the proper behavior.
Resources:
https://flask.palletsprojects.com/en/1.1.x/testing/
https://www.patricksoftwareblog.com/testing-a-flask-application-using-pytest/
"""
import os
import... |
#!/usr/bin/env python2
#$ -S /usr/bin/python
#$ -l mem_free=1G
#$ -l arch=linux-x64
#$ -l netapp=1G
#$ -cwd
from pull_into_place import big_jobs
workspace, job_info = big_jobs.initiate()
big_jobs.run_rosetta(
workspace, job_info,
use_resfile=True,
use_restraints=True,
use_fragments=Tr... |
# The MIT License (MIT)
#
# Copyright (c) 2019 Looker Data Sciences, Inc.
#
# 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 u... |
# -*- coding: utf-8 -*-
from __future__ import print_function, absolute_import, division
import collections
from punch import version_part as vpart
from punch.helpers import import_file
class Version():
def __init__(self):
self.parts = collections.OrderedDict()
@property
def keys(self):
... |
from maru.grammeme.abstract import Grammeme
class Degree(Grammeme):
POSITIVE = 'Pos'
COMPARATIVE = 'Cmp'
|
import numpy as np
import pickle
import logging
import os
import xarray as xr
from .utils import *
def gen_feature_description(metadata_instance, sample_dim):
""" Generates the feature description dictionary given a metadata_intance and the name of the sample dimension
Args:
metadata_instance (metadat... |
import pytest
import qcelemental as qcel
import qcengine as qcng
from qcelemental.testing import compare_values
from qcengine import testing
@pytest.fixture
def h2o():
smol = """
# R=0.958 A=104.5
H 0.000000000000 1.431430901356 0.984293362719
O 0.000000000000 0.0... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'window.ui'
#
# Created: Fri Oct 12 15:31:31 2012
# by: PyQt4 UI code generator 4.9.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtWidgets
try:
_fromUtf8 = QtCore.QString.fromUtf8
except Attr... |
# -*- coding: utf-8 -*-
from flask import request, jsonify, abort, Blueprint
from app import app, db, redis_pool
from app.api import common
from app.controller import MovieRecController
from app.models import user_schema, movie_schema, rating_schema
app_controller = MovieRecController(db,
... |
dictionary = {
'À': r'\`A', 'Á': r"\'A", 'Â': r'\^A', 'Ã': r'\~A', 'Ä': r'\"A',
'Å': r'\r{A}', 'Æ': r'\AE', 'Ç': r'\c{C}', 'È': r'\`E', 'É': r"\'E",
'Ê': r'\^E', 'Ë': r'\"E', 'Ì': r'\`I', 'Í': r"\'I", 'Î': r'\^I',
'Ï': r'\"I', 'Ð': r'\DH', 'Ñ': r'\~N', 'Ò': r'\`O', 'Ó': r"\'O",
'Ô': r'\^O', 'Õ': r'\... |
from setuptools import setup
import os
from os import path
from gekkopy import version
name = "gekkopy"
description = "Python API for Gekko trading bot"
long_description = "See https://github.com/askmike/gekko for the trading bot."
this_directory = path.abspath(path.dirname(__file__))
def read(filename):
with o... |
"""add company details confirmed column
Revision ID: 1120
Revises: 1110
Create Date: 2018-03-06 09:05:13.221057
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '1120'
down_revision = '1110'
def upgrade():
op.add_column('suppliers',
sa.Co... |
#
# PySNMP MIB module DKSF-253-6-X-A-X (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DKSF-253-6-X-A-X
# Produced by pysmi-0.3.4 at Mon Apr 29 18:32:23 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... |
class STree:
def __init__(self, l):
self.l = l
self.n = len(l)
self.st = [0] * (4 * self.n)
self.islazy = [False] * (4 * self.n)
self.lazy = [0] * (4 * self.n)
self.build(1, 0, self.n - 1)
def left(self, p):
return p << 1
def right(self, p):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class KbdishEstimatedInfo(object):
def __init__(self):
self._ds_id = None
self._ds_type = None
self._inventory = None
self._out_shop_id = None
self._shop_id = No... |
import yaml
import os
class Config():
def __init__(self, params=None):
self.params = params
self.config_file_path = params.config_file_path
self.environment = params.pos_env
self._load_config_file(self.config_file_path)
if not hasattr(self, 'log_level'):
... |
import os
from django.conf import settings
from django.contrib.sites.models import Site
# setup the sites available for this project
def setup_sites():
"""
Setup sites (name, domain) available for this project (SITE_ID will decide the active site)
"""
site_info = getattr(settings, 'BOOTUP_SITES', None)... |
""" Runs the COVID Lung Ultrasound task on DeAI.
Prerequisites:
Download a chromedriver from here: https://sites.google.com/a/chromium.org/chromedriver/downloads.
Extract the chromedriver in the current folder.
Prepare the covid positive and covid negative images in separate folders.
Constants:
Use `POSITIVE_CLASS_... |
import Elements
import Visitors
class ObjectStructure:
def __init__(self):
self.elements = []
def attach(self,element: Elements.Element):
self.elements.append(element)
def detach(self,element: Elements.Element):
self.elements.remove(element)
def accept(self,visitor: Visitors... |
"""
### Usage: ctdoc [-w]
### Options:
-h, --help show this help message and exit
-w, --web build web docs
-a, --auto use auto mode (even with a plugin)
-o, --omit omit any files from autodoc?
Run from cantools root (contains setup.py, cantools/, README.md, etc), from root
of a CT plugin, or from... |
# Copyright 2018 NTT DATA
# 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 ap... |
"""
Contains the user settings class implementation and functions for
database interaction.
"""
import collections
import datetime
from models.base_model import BaseModel
from sqlalchemy import Integer, select, func
from database import DATABASE_INSTANCE
class UserSettings(BaseModel):
"""
Class that contains ... |
import math
from typing import List
from paddle.abc_paddle import ABCPaddle
class Paddle(ABCPaddle):
urdf_model = "paddle/paddle.urdf"
# The following are the paddle important joints ids.
# These are hard coded values, so always make sure to check these after changing paddle urdf model.
MOVE_AXIS_JOI... |
import re
from PIL.Image import new
from reportlab.graphics.shapes import Drawing
from svglib.svglib import svg2rlg
from reportlab.graphics import renderPDF, renderPM
import codecs
import random
import linecache
from reportlab.graphics.shapes import Drawing
from reportlab.graphics.renderSVG import SVGCanvas, draw
impo... |
import unittest
from click.testing import CliRunner
from mock import patch
from tenx.app import TenxApp
from tenx.reads_cli import reads_cli, reads_download_cmd
class TenxRdsCliTest(unittest.TestCase):
def setUp(self):
if TenxApp.config is None: TenxApp()
TenxApp.config["TENX_DATA_PATH"] = "/mnt/... |
'''
Created on 2015年12月1日
给出N个数字,不改变它们的相对位置,在中间加入K个乘号和N-K-1个加号,
(括号随便加)使最终结果尽量大。因为乘号和加号一共就是N-1个了,所以恰好每两个相邻数字之间都有一个符号。
http://www.lostscroll.com/max-value-using-and/
@author: Darren
'''
def maxValue(nums):
dp=[[0]*len(nums) for i in range(len(nums)+1)]
sumN=[0]*(len(nums)+1)
for i in range(1,len(nums)+1):
... |
class AccountRequest:
get_all_accounts_request = """
<?xml version="1.0" ?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
<soap:Header>
<context xmlns="urn:zimbra">
<authToken>%s</authToken>
<session/>
... |
from skyciv.classes.model.components.meshed_plates.meshed_plate import MeshedPlate
from skyciv.utils.helpers import next_object_key
from skyciv.classes.model.components._base_class.model_collection_component import ModelCollectionComponent
from typing import List
class MeshedPlates(ModelCollectionComponent):
"""Cr... |
# Import libraries and sklearn libraries
import numpy as np
import pandas as pd
import os
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn import neighbors, datasets
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report, c... |
# dspace/__init__.py
"""DSpace Python Client package."""
import logging
from dspace.bitstream import Bitstream # noqa
from dspace.client import DSpaceClient # noqa
from dspace.item import Item, MetadataEntry # noqa
logging.getLogger(__name__).addHandler(logging.NullHandler())
|
import iniparser2
import cmdtools
from lib import utils
from lib import statics
async def error_equip(error):
if isinstance(error, cmdtools.MissingRequiredArgument):
if error.param == "item":
await error_equip.message.channel.send(":x: Item name is required")
async def _equip(item):
ass... |
class Solution:
def solve(self, nums, k):
ans = -1
total = 0
for i in range(len(nums)):
total += nums[i]
if total <= k: ans = i
return ans
|
import os
from typing import Union
import requests
import random
from .get_hashio_storage_dir import get_hashio_storage_dir
def load_file(uri: str) -> Union[str, None]:
assert uri.startswith('ipfs://'), f'Invalid or unsupported URI: {uri}'
a = uri.split('/')
assert len(a) >= 3, f'Invalid or unsupported UR... |
import discord
from discord.ext import commands
from discord.commands import slash_command
from console import Console
import random
console = Console(True)
class help_class(commands.Cog):
def __init__(self, client):
self.client = client
@slash_command(name="help", description="Send help message.")... |
import platform
import stat
import os
import csv
from datetime import datetime
import json
import shutil
from pathlib import Path
import subprocess
from collections import defaultdict
import click
from ploomber.io.terminalwriter import TerminalWriter
from ploomber.table import Table
from pygments.formatters.terminal... |
import os.path
import fs
from .setup import *
def test_normalize():
path = '../test/'
assert fs.normalize(path) == os.path.normpath(path) |
# coding:utf8
# 端口扫描工具
# 使用方式:python portScan.py -i 192.168.1.1 -p 22
# 2017-03-23
# leafrainy (leafrainy.cc)
import socket
import re
import sys
s = sys.argv
ss = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#提示信息
def useNotic(s):
print "请按照格式输入正确的参数"
print "使用方法: python "+s[0]+" -i ip -p port"
print... |
from collections import OrderedDict
from _pytest.runner import CollectReport
from py.log import Producer
from xdist.report import report_collection_diff
from xdist.workermanage import parse_spec_config
class LoadScopeScheduling:
"""Implement load scheduling across nodes, but grouping test by scope.
This dis... |
# -*- coding: utf-8 -*-
"""Top-level package for django_inclusiveft."""
__author__ = """Bernard Parah"""
__email__ = 'barjebernard@gmail.com'
__version__ = '0.1.0'
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 26 09:13:00 2019
@author: Rajiv Sambasivan
"""
import pandas as pd
from arango import ArangoClient
import time
import traceback
import uuid
from collections import OrderedDict
class ITSM_Dataloader:
def __init__(self, conn, input_file = "da... |
# SecretPlots
# Copyright (c) 2019. SecretBiology
#
# Author: Rohit Suratekar
# Organisation: SecretBiology
# Website: https://github.com/secretBiology/SecretPlots
# Licence: MIT License
# Creation: 05/10/19, 7:47 PM
#
#
# Matrix Assemblers
from SecretPlots.assemblers import Assembler
from SecretPlots.constan... |
"""
Wrapper for handling data in lexibank packages.
"""
from importlib import import_module
from pyclts import CLTS
from csvw.dsv import UnicodeDictReader
from tqdm import tqdm
class LexibankDataset(object):
def __init__(self, package, transform=None):
"""
Load the data of a lexibank dataset.
... |
# Copyright 2020 KCL-BMEIS - King's College London
# 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... |
import os
import sys
import time
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
class IndeedBot:
def __init__(self):
"""
Initilializes the Chrome webdriver.
Sets the job search quer... |
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import parse_qs, urlparse
class MyHTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
parsed_path = urlparse(self.path)
self.send_response(200)
self.send_header('Content-Type', 'text/plain; charset=utf-8... |
from PyObjCTools import NibClassBuilder, AppHelper
import objc
objc.setVerbose(True)
NibClassBuilder.extractClasses("MainMenu")
NibClassBuilder.extractClasses("MyDocument")
import MyPDFDocument
import AppDelegate
AppHelper.runEventLoop()
|
import pytest
from .test_base import _HTTPErrorGenerator
from ...exception.master import MasterErrorCode, \
get_master_exception_class_by_error_code, get_master_exception_by_error, MasterSuccess, \
MasterSystemShuttingDown, MasterTaskDataInvalid, MasterSlaveTokenNotGiven, MasterSlaveTokenInvalid, \
MasterS... |
import argparse
import os
from typing import List
from pydantic import BaseModel
from fastapi import FastAPI, HTTPException
import uvicorn
from src.embedding_store import KGEmbeddingStore
from src.nearest_neighbours import FaissNearestNeighbours
from pathlib import Path
from dotenv import load_dotenv
from src.cli.log i... |
import datetime
import random
import csv
import json
# TODO: Fix * imports
from django.shortcuts import *
from django.contrib.auth.decorators import login_required, user_passes_test
from django.contrib.auth import logout as auth_logout
from social.apps.django_app.default.models import UserSocialAuth
from gnip_search... |
from dataclasses import dataclass
import cv2
import numpy as np
from opsi.manager.manager_schema import Function
from opsi.manager.types import RangeType, Slide
from opsi.util.cv.mat import Mat, MatBW
__package__ = "opsi.imageops"
__version__ = "0.123"
class Rotate(Function):
@dataclass
class Settings:
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
###
# Copyright (2021) Hewlett Packard Enterprise Development LP
#
# 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/L... |
# Generates a single arch xml file given arch string
import os
import subprocess
import re
import getopt
import sys
import arch_handler as ah
from my_regex import *
#==================================================================
# Global functions
def runCommand(command, arguments):
ret = subprocess.check_outpu... |
# Written by Mike Smith michaeltsmith.org.uk
from GPy.kern import Kern
from GPy.core.parameterization import Param
from paramz.transformations import Logexp
import math
from scipy.misc import factorial
import numpy as np
#TODO: Is it ok for us to just fill the rest of X in with zeros?
# these won't have any points ch... |
import pytest
from pytest import approx
from contextuality.model import Scenario, CyclicScenario, random_pr_like_model
def test_CbD_direction_influence():
for _ in range(10):
model = random_pr_like_model(n=3)
dist = model._distributions
assert approx(model.CbD_direct_influence()) == (2 * (a... |
import numpy as np
from .VariableUnitTest import VariableUnitTest
from gwlfe.MultiUse_Fxns.Runoff import CNumPerv
class TestCNumPerv(VariableUnitTest):
# @skip("not ready")
def test_CNumPerv(self):
z = self.z
np.testing.assert_array_almost_equal(
CNumPerv.CNumPerv_f(z.NYrs, z.Day... |
import os
from pathlib import Path
import subprocess
import oyaml as yaml
def create_empty_dbt_project(data_source_id: str, warehouse: str, target_dir: str):
Path(target_dir).mkdir(parents=True, exist_ok=True)
subprocess.call(
f"dbt-init --client {data_source_id} --warehouse {warehouse} --target_dir ... |
"""
Geographic coordinate conversion.
"""
import numpy as np
from . import get_ellipsoid
def geodetic_to_spherical(longitude, latitude, height):
"""
Convert from geodetic to geocentric spherical coordinates.
The geodetic datum is defined by the default :class:`harmonica.ReferenceEllipsoid`
set by th... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import unicodedata
import os
import logging
from multiprocessing import Pool
import numpy as np
import multiprocessing
import os
import logging
import shutil
import tempfile
import argparse
... |
from app import create_app ,db
from flask_script import Manager, Server
from flask_migrate import Migrate, MigrateCommand
from app.models import Quote, User, Post,Comment, Subscriber
app = create_app('production')
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('server', Server)
manager.add_com... |
import os
from hokusai.lib.command import command
from hokusai.lib.config import config
from hokusai.lib.common import shout
from hokusai.lib.exceptions import HokusaiError
@command()
def build():
docker_compose_yml = os.path.join(os.getcwd(), 'hokusai/build.yml')
legacy_docker_compose_yml = os.path.join(os.getcw... |
import os
import gym
import numpy as np
from gym import spaces
from gym.envs.registration import register
from .franka_panda import PandaAbstractEnv
class PandaReachCspaceEnv(PandaAbstractEnv, gym.Env):
metadata = {'render.modes': ['human']}
def __init__(self, render=False, reward_type="jointcol", random_ini... |
#!/usr/bin/env python3
import os
import sys
import subprocess
FRONTEND_STACK_PREFIX = "sockshop_frontend_"
BACKEND_STACK = "sockshop_backend"
def print_usage():
print("This script takes exactly one argument.")
print("Usage: {} HOSTNAME".format(sys.argv[0]))
sys.exit(1)
if __name__ == "__main__":
i... |
import unittest
import os
from programy.context import ClientContext
from programytest.aiml_tests.client import TestClient
class ThatSraiTestClient(TestClient):
def __init__(self):
TestClient.__init__(self)
def load_configuration(self, arguments):
super(ThatSraiTestClient, self).load_confi... |
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
import numpy as np
from scipy.constants import epsilon_0
from ipywidgets import IntSlider, FloatSlider, FloatText, ToggleButtons
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
f... |
secret = """
---
apiVersion: v1
kind: Secret
metadata:
name: {cfg[metadata][name]}
type: {cfg[secret_type]}
stringData: []
"""
|
from __future__ import absolute_import, division, print_function
from unittest import TestCase
import numpy as np
import pytest
import torch
import pyro.distributions as dist
from pyro.nn import AutoRegressiveNN
pytestmark = pytest.mark.init(rng_seed=123)
class AutoregressiveFlowTests(TestCase):
def setUp(sel... |
from flask import render_template, url_for, session, redirect, request
from app import webapp
from datetime import datetime, timedelta
import collections
from pytz import timezone,utc
import boto3
from boto3.dynamodb.conditions import Key
from app import send_email
ZONE = 'Canada/Eastern'
dynamodb = boto3.resource('... |
# Generated by Django 3.1.2 on 2020-11-05 20:02
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('profiles', '0002_relationship'),
]
operations = [
migrations.AlterField(
model_name='profile',
name='bio',
... |
import sys
N=int(sys.stdin.readline())
d=[0]*101
d[1]=1
d[2]=1
d[3]=1
for _ in range(N):
num = int(sys.stdin.readline())
for i in range(4, num + 1):
d[i] = d[i - 2] + d[i - 3]
print(d[num]) |
x = 9 #make x equal to 9
y = 3 #make y equal to 3
#Arithmetric Operators
print(x+y) #Addition
print(x-y) #Subtraction
print(x*y) #Multiplication
print(x/y) #Division
print(x%y) #Modulus
print(x**y) #Exponentiation
x = 9.191823
print(x//y) #floor division
#assignment operators
x = 9 # set x = 9
x += 3 # set x = x + 3
... |
import csv
import io
from django.core.management import call_command
from mock import patch
from datetime import datetime, date
from decimal import Decimal
from django.test import TestCase
from django.urls import reverse
from rest_framework.test import APIClient
from rest_framework_simplejwt.tokens import RefreshToke... |
#!/usr/bin/env python
# coding=UTF-8
"""
Desc:
Author:TavisD
Time:2019/10/15 15:31
"""
import pytest
from test.utils import HOST, http_get, http_post, get_db_session
apply_url = HOST + "device/apply/{device_id}"
return_url = HOST + "device/return/{apply_id}"
audit_url = HOST + "device/audit/{apply_id}"
cancel_url = H... |
import os
from flask import Flask, render_template, g
from gifs import get_giphy_results
from helpers import divide_chunks
app = Flask(__name__)
@app.route('/', strict_slashes=False)
def index():
gifs = get_giphy_results()
gifs = divide_chunks(gifs, int(len(gifs)/4))
return render_template(
'inde... |
from turtle import Turtle
ALIGNMENT = "center"
FONT = ("courier", 24, "normal")
class scoreBoard(Turtle):
def __init__(self):
super().__init__()
self.score = 0
with open("my_score.txt", mode = 'r') as file:
self.high_score = int(file.read())
self.color("white")
self.penup()
self.goto(0, 250)
self... |
from flask import Flask, render_template, jsonify
from quotes import QUOTES
import random
app = Flask('__name__')
@app.route("/")
def hello():
return render_template('index.html')
@app.route("/quote")
def generateQuote():
return jsonify({'quote': str(randomQuote(QUOTES))})
def randomQuote(_list_):
... |
from xv_leak_tools.log import L
from xv_leak_tools.test_components.cleanup.cleanup import Cleanup
class LinuxCleanup(Cleanup):
def cleanup(self):
L.warning("No cleanup implemented for Linux yet!")
|
# -*- coding: utf-8 -*-
import os
import pytest
from severus.translator import Translator
@pytest.fixture(scope='session')
def T():
return Translator(
os.path.join(
os.path.dirname(os.path.abspath(__file__)), 'lang1'
)
)
@pytest.fixture(scope='session')
def Tpre():
return T... |
'''
tree_constants.py holds constants used in defining decision trees,
such as column definitions.
Column definitions:
0) Split feature, -1 if leaf
1) Split threshold
2) Node number of this node (nodes are numbered in pre-order).
3) Node number of left child, -1 if leaf
4) Node number of right chi... |
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
import requests
import csv
from datetime import datetime
from datetime import timedelta
from datetime import date
from geopy.distance import vincenty
import json
from lib import csv_io
from lib import json_io
if __name__ == '__main__':
m8 = 'http://data.tainan.gov.... |
# Exercise number 4 - Python WorkOut
# Author: Barrios Ramirez Luis Fernando
# Language: Python3 3.8.2 64-bit
# Main function with no arguments
def hex_output():
decimal_num = 0
hex_num = input('Enter a hex number to convert: ')
for power, digit in enumerate(reversed(hex_num)):
decimal_num += int(... |
#
# 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... |
'''
See the namespace for available functions and the corresponding docstrings
for more information.
'''
from .npv import NPV
from .histogram import histogram
from .params import sample_params, load_params_from_file
__version__ = "0.4.1"
|
import math
from typing import List
import numpy
from nobos_commons.data_structures.geometry import Triangle
from nobos_commons.data_structures.skeletons.joint_3d import Joint3D
from nobos_commons.data_structures.skeletons.joint_visibility import JointVisibility
def get_euclidean_distance_joint3D(joint_a: Joint3D, ... |
print ("Hola Mundo!!!")
m = [5, 'old', 'new', 8, 'time', 2]
print (m[0])
print (m[-1])
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals, print_function
import pytest
from russian_tagsets import converters, ud
#from .opencorpora_aot_data import PARSE_RESULTS
class TestInternalConversion(object):
TEST_DATA = [
#Noun, Verb, ADJF, ADVB, PRTF, PRTS, NUMB, COMP, NP... |
import pickle
root_folder="/home/guillefix/code/inria/captionRLenv/"
types = pickle.load(open(root_folder+"object_types.pkl","rb"))
geometric_solid = ('cube', 'block', 'cylinder')
kitchen_ware = ('bottle', 'bowl', 'plate', 'cup', 'spoon')
animal_model = ('bear', 'bird', 'dog', 'fish', 'elephant')
food_model = ('apple'... |
import math
import copy
import random
import numpy as np
from collections import OrderedDict
import torch
from torch.distributions.kl import kl_divergence
from torch.nn.utils.convert_parameters import (vector_to_parameters,
parameters_to_vector)
from maml_trpo.utils impo... |
import math
import pprint
import os
import shutil
from multiprocessing import Pool
from functools import partial
import numpy as np
import dlib
import cv2
def generate_face(img):
# Tamanho extra para recortar o rosto
N = 60
# Shape para calcular algumas questões...
if not isinstance(img, np.ndarray):
... |
from output.models.nist_data.list_pkg.nmtoken.schema_instance.nistschema_sv_iv_list_nmtoken_min_length_3_xsd.nistschema_sv_iv_list_nmtoken_min_length_3 import NistschemaSvIvListNmtokenMinLength3
__all__ = [
"NistschemaSvIvListNmtokenMinLength3",
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.