text stringlengths 1 927k |
|---|
from runner_master import runner
import os
import io
import torch
import logging
from PIL import Image, ImageFile
from runner_master.runner.data import datasets
# to fix "OSError: image file is truncated"
ImageFile.LOAD_TRUNCATED_IMAGES = True
class ImagenameDataset(datasets.ImglistDatasetV2):
def getitem(self, i... |
#!/usr/bin/env python3
"""
Setup for the slack-backup project
"""
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(name="slack-backup",
packages=["slack_backup"],
version="0.7",
description="Make copy of slack converstaions",
author="Roman Do... |
import json
from transformers.tokenization_utils import PreTrainedTokenizer
from yacs.config import CfgNode
from openprompt.data_utils.data_utils import InputFeatures
import re
from openprompt import Verbalizer
from typing import *
import torch
import torch.nn as nn
import torch.nn.functional as F
from openprompt.utils... |
"""Add price
Revision ID: 57642bbc5015
Revises: 6b66b7cc2f1f
Create Date: 2021-11-18 17:58:58.263480
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '57642bbc5015'
down_revision = '6b66b7cc2f1f'
branch_labels = None
depends_on = None
def upgrade():
# ### ... |
# Protean
from protean.core.field.basic import String
from protean.utils.container import BaseContainer
class CustomBaseContainer(BaseContainer):
def __new__(cls, *args, **kwargs):
if cls is CustomBaseContainer:
raise TypeError("CustomBaseContainer cannot be instantiated")
return super... |
from typing import Type
from ...caches import BaseXMLLayerCache, XMLLayerFileCache, XMLLayerNoCache
from ..base import BaseMapper
from ..consts import PACKAGE_NAME
class XMLLayerCacheMapper(BaseMapper[Type[BaseXMLLayerCache]]):
@classmethod
def default_mapper(cls) -> "XMLLayerCacheMapper":
default_ma... |
# -*- coding: utf-8 -*-
"""
.. autoclass:: Blueprint
"""
from sanic.blueprints import Blueprint as BaseBlueprint, FutureRoute
__all__ = ('Blueprint',)
class Blueprint(BaseBlueprint):
"""Create a new blueprint.
:param name: unique name of the blueprint
:param url_prefix: URL to be prefixed before all ro... |
import setuptools
import subprocess
with open("README.md", "r") as fh:
long_description = fh.read()
packages = [dep.rstrip('\n') for dep in open("requirements.txt", "r")]
def get_git_version():
return subprocess.check_output(['git', 'describe','--dirty', '--tags']).strip()
setuptools.setup(
name="VTunit"... |
# Copyright [yyyy] [name of copyright owner]
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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.or... |
"""
Node classes (`Apply`, `Variable`) and expression graph algorithms.
"""
from __future__ import absolute_import, print_function, division
from collections import deque
from copy import copy
from itertools import count
import theano
from theano import config
from theano.gof import utils
from six import string_types... |
#!/usr/bin/env python
import krylov
import splitting
import tool
import numpy as np
import math
import metric
import accel
def parse_args():
"""command line arguments"""
import argparse
parser = argparse.ArgumentParser(description='benchmark LCP solvers')
parser.add_argument('filenames', nargs=... |
# Copyright 2014 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.
from telemetry.page import page as page_module
from telemetry.page import page_set as page_set_module
class IntlJaZhPage(page_module.Page):
def __init__(... |
import torch
import torch.nn as nn
class ChamferLoss(nn.Module):
def __init__(self):
super(ChamferLoss, self).__init__()
self.use_cuda = torch.cuda.is_available()
def forward(self, preds, gts, reverse=True, bidirectional=True):
def compute_loss(preds, gts):
P = self.batch... |
"""
Copyright (c) 2019 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writin... |
#!/usr/bin/env python
""" a small class for Principal Component Analysis
Usage:
p = PCA( A, fraction=0.90 )
In:
A: an array of e.g. 1000 observations x 20 variables, 1000 rows x 20 columns
fraction: use principal components that account for e.g.
90 % of the total variance
Out:
p.U, p.d, p.Vt: f... |
# Copyright 2018 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://www.apache.org/licenses/LICENSE-2.0
#
# or in the "license... |
import sqlite3
import datetime
import time
#import Read1
#import sync
#from datetime import datetime
conn = sqlite3.connect('att.db')
c = conn.cursor()
def db(sid):
#conn = sqlite3.connect('att.db')
#c = conn.cursor()
start_time = time.time()
c.execute('''CREATE TABLE IF NOT EXISTS attendance(ID intege... |
from mycroft import MycroftSkill
from mycroft.messagebus import Message
import json
from .lib import MqttService
class MessageListener(MycroftSkill):
# Initializing the skill
def initialize(self):
self.log.info("Initializing Skill MessageListener")
self.add_event('speak', self.handler_s... |
from binance_d import RequestClient
from binance_d.constant.test import *
from binance_d.base.printobject import *
from binance_d.model.constant import *
request_client = RequestClient(api_key=g_api_key, secret_key=g_secret_key)
result = request_client.get_position()
PrintMix.print_data(result) |
"""Top-level package for spectra."""
from .conv_spectrum import ConvSpectrum
from .sticks_spectrum import SticksSpectrum
__author__ = """Jonathon Vandezande"""
__email__ = "jevandezande@gmail.com"
__version__ = "0.4.0"
__all__ = ["ConvSpectrum", "SticksSpectrum"] |
import sm
import aslam_backend as aopt
import aslam_cv as cv
import numpy as np
def addPoseDesignVariable(problem, T0=sm.Transformation()):
q_Dv = aopt.RotationQuaternionDv( T0.q() )
q_Dv.setActive( True )
problem.addDesignVariable(q_Dv)
t_Dv = aopt.EuclideanPointDv( T0.t() )
t_Dv.setActive( True )... |
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file ex... |
# 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 not u... |
#!/usr/bin/env python
"""@package docstring
File: me_zrl_bound_evolvers.py
Author: Adam Lamson
Email: adam.lamson@colorado.edu
Description:
"""
import numpy as np
# from scipy.integrate import dblquad
from .me_helpers import dr_dt, convert_sol_to_geom
from .me_zrl_odes import (rod_geom_derivs_zrl, calc_moment_derivs_... |
from .base_command import AntiPetrosBaseCommand
from .flag_command import AntiPetrosFlagCommand
from .creation_decorators import auto_meta_info_command, auto_meta_info_group
from .base_group import AntiPetrosBaseGroup
from .command_category import CommandCategory |
#!/usr/bin/env python
# Copyright (c) 2004 Damien Miller <djm@mindrot.org>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED ... |
import zipfile
import argparse
import os
from squad_preprocess import maybe_download
def setup_args():
parser = argparse.ArgumentParser()
parser.add_argument("--download_dir", required=True) # where to put the downloaded glove files
return parser.parse_args()
def main():
args = setup_args()
glove... |
from typing import List, Tuple, Dict, Any
from collections import Counter
import pretty_midi
import matplotlib.pyplot as plt
import librosa.display
import os
from os import listdir, walk
from os.path import isfile, isdir, join
from sys import argv
import traceback
import logging
import numpy as np
from shutil import co... |
import boto3
def get_event_client(access_key, secret_key, region):
"""
Returns the client object for AWS Events
Args:
access_key (str): AWS Access Key
secret_key (str): AWS Secret Key
region (str): AWS Region
Returns:
obj: AWS Cloudwatch Event Client Obj
"""
r... |
import logging
from finorch.config.config import api_config_manager
from finorch.sessions.cit.client import CITClient
from finorch.sessions.abstract_session import AbstractSession
from finorch.sessions.cit.wrapper import CITWrapper
from finorch.transport.ssh import SshTransport
class CITSession(AbstractSession):
... |
import _plotly_utils.basevalidators
class LineValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(
self, plotly_name='line', parent_name='scattergeo.marker', **kwargs
):
super(LineValidator, self).__init__(
plotly_name=plotly_name,
parent_name=paren... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
from google.protobuf import descriptor
from google.protobuf import message
from google.protobuf import reflection
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)
import uits_pb2
DESCRIPTOR = descriptor.FileDescriptor(
name='... |
def wer(r, h):
"""
Calculation of WER with Levenshtein distance.
Works only for iterables up to 254 elements (uint8).
O(nm) time ans space complexity.
Parameters
----------
r : list
h : list
Returns
-------
int
Examples
--------
>>> wer("who is there".split(),... |
# Copyright (c) 2013, Blue Lynx and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
import math
from frappe.utils import getdate, get_time, flt
from datetime import datetime, timedelta, date, time
import calendar
def execute(fil... |
from os import path
from setuptools import find_packages
from setuptools import setup
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, "README.md")) as f:
long_description = f.read()
with open(path.join(this_directory, "LICENSE")) as f:
license_text = f.read()
setu... |
# Generated by Django 2.1.2 on 2019-01-11 14:48
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mrp_system', '0036_auto_20190111_1357'),
]
operations = [
migrations.AddField(
model_name='billofmaterials',
name='a... |
# coding=utf-8
# Copyright 2018 Mesh TensorFlow authors, T5 Authors and HuggingFace Inc. team.
#
# 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... |
# -*- coding: utf-8 -*-
"""Config component.
This module defines the config Component.
<config>
</config>
"""
from . import AbstractComponent
class configComponent(AbstractComponent):
def __init__(self):
self._xmlns = {}
self.attributes = {}
self.parent_xmlns = {}
self._childre... |
from django.apps import AppConfig
class InvoicebookConfig(AppConfig):
name = 'InvoiceBook' |
import pickle
import numpy as np
from typing import List
from fastapi import FastAPI
from pydantic import BaseModel, conlist
app = FastAPI(title="Predicting Wine Class with batching")
# Open classifier in global scope
with open("models/wine-95-fixed.pkl", "rb") as file:
clf = pickle.load(file)
class Wine(Base... |
# run flags
make_dirs = True
make_scp = True
do_sptk_pitch_analysis = False
do_reaper_pitch_analysis = False
do_glott_vocoder_analysis = False
make_dnn_train_data = False
make_dnn_infofile = False
do_dnn_training = False
do_glott_vocoder_synthesis = True
# directories
prjdir = '/l/CODE/GlottDNN' # add your own local i... |
# Copyright 2021 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 or agreed to in writing, ... |
"""Binary sensor platform for Pandora Car Alarm System."""
__all__ = ["ENTITY_TYPES", "async_setup_entry"]
import logging
from functools import partial
from typing import Any, Dict
import attr
from homeassistant.components.binary_sensor import (
DEVICE_CLASS_CONNECTIVITY,
DEVICE_CLASS_DOOR,
DEVICE_CLASS_M... |
def cycle_sort(data: list):
cap = len(data)
for start in range(0, cap - 1):
# get item
item = data[start]
# get new pos for said item
pos = start
for i in range(start + 1, cap):
if data[i] < item:
pos += 1
# if there isnt a new pos, ski... |
""" #EmbraceTheS's options menu state. """
import state
import menu
import globes
import pygame
import joystick
import volume
class Options(state.State):
""" Option menu state with the options to clear high scores, and
adjust brightness/volume (not yet implemented) """
TEXT = []
BACKGROUND = Non... |
import pytest
from etcdb import OperationalError
from etcdb.lock import Lock, ReadLock, WriteLock
def test_readers(etcdb_connection):
cur = etcdb_connection.cursor()
cur.execute('CREATE TABLE bar(id int not null PRIMARY KEY)')
lock = ReadLock(etcdb_connection.client, 'foo', 'bar')
lock.acquire(ttl=0)... |
#!/usr/bin/env python3
'''
Created by Conan Albrecht <doconix@gmail.com>
Apache open source license.
November, 2017
'''
##################################################
### Unique id generator. Similar to uuid1() but
### also includes the process id.
###
### Note that upping the counter requires a global lock.
#... |
import requests
import os
import time
def get_page(i):
url = r'https://shr32taah3.execute-api.us-east-1.amazonaws.com/Prod/applications/browse?pageSize=12&pageNumber=%d&searchText=&category=&runtime=&verified=&sortFields='
page = requests.get(url%i)
return eval(page.text.replace("true", "True").replace("fa... |
class MultipartProblem:
"""A container for multiple related Problems grouped together in one
question. If q1 is a MPP, its subquestions are accessed as q1.a, q1.b, etc.
"""
def __init__(self, *probs):
self.problems = probs
# TODO: This should be ordered.
self._prob_map = {}... |
# !usr/bin/env python
# -*- coding: utf-8 -*-
#
# Licensed under a 3-clause BSD license.
#
from __future__ import print_function, division, absolute_import
from flask import request
def process_request(request=None, as_dict=None, param=None):
'''Generally process the request for POST or GET, and build a form dic... |
import os
import re
from django import template
from django.conf import settings
from django.contrib import admin
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import MultipleObjectsReturned
from django.urls import reverse
from django.db.models import Model
from django.template... |
from libs.Screen import *
class App_tpl(object):
@staticmethod
def hello():
print(" _ _ _ _ _ ")
print(" | |__(_) | | |_ ___ _ _ _ __ ")
print(" | '_ \ | | | _/ -_) '_| ' \ ")
print("__|_.__/_|_|_|\__\___|_| |_|_|_|_... |
# Generated by Django 2.1.5 on 2019-02-16 07:42
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('people', '0008_personpage_short_intro'),
]
operations = [
migrations.AddField(
model_name='personpage',
name='alt_sh... |
# this code is based on original work by @jasonwbarnett.
# https://github.com/pyro2927/SouthwestCheckin/issues/70#issuecomment-921166994
import json
import time
import re
import os
import random
import string
import sys
from pathlib import Path
from seleniumwire import webdriver
from selenium.webdriver.chrome.options ... |
#!/usr/bin/env python
# Copyright (c) 2015
# - Zachary Cutlip <uid000()gmail.com>
#
# See LICENSE for more details.
#
import sys
import socket
import time
import base64
from bowcaster.common import Logging
HOST="10.12.34.1"
#HOST="192.168.127.141"
class SetFirmwareRequest(object):
"""
Generate a "SetFir... |
import os
import FWCore.ParameterSet.Config as cms
from FWCore.ParameterSet.VarParsing import VarParsing
from Configuration.StandardSequences.Eras import eras
def get_root_files(path):
files = os.listdir(path)
root_files = [f for f in files if f.endswith(".root")]
full_paths = [os.path.join(path, f) for f... |
import pytest
from rasa.core.channels.channel import UserMessage
from rasa.core.domain import Domain
from rasa.core.events import SlotSet, ActionExecuted, Restarted
from rasa.core.tracker_store import (
TrackerStore,
InMemoryTrackerStore,
RedisTrackerStore,
SQLTrackerStore,
)
from rasa.utils.endpoints ... |
log_level = 'INFO'
load_from = None
resume_from = None
dist_params = dict(backend='nccl')
workflow = [('train', 1)]
checkpoint_config = dict(interval=10)
evaluation = dict(interval=10, metric='mAP', key_indicator='AP')
optimizer = dict(
type='Adam',
lr=5e-4,
)
optimizer_config = dict(grad_clip=None)
# learning... |
# ---------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# ---------------------------------------------------------
from os import PathLike
from pathlib import Path
from typing import Any, Dict, Union
from azure.ai.ml.constants import BASE_PATH_CONTEXT_KE... |
import argparse
import logging
from pixelsort.interval import choices as interval_choices
from pixelsort.sorting import choices as sorting_choices
from pixelsort.constants import DEFAULTS
def parse_args():
parser = argparse.ArgumentParser(description="Pixel mangle an image.")
parser.add_argument("image", help... |
# -*- coding: utf-8 -*-
from __future__ import division, absolute_import, unicode_literals
from django.utils.translation import ugettext_lazy
import djadmin2
from djadmin2 import renderers
from djadmin2.actions import DeleteSelectedAction
# Import your custom models
from .actions import (CustomPublishAction, Publish... |
# Copyright (C) 2018 The Electrum developers
# Distributed under the MIT software license, see the accompanying
# file LICENCE or http://www.opensource.org/licenses/mit-license.php
from typing import Optional, Dict, List, Tuple, TYPE_CHECKING, NamedTuple, Callable
from enum import Enum, auto
from .util import bfh, bh... |
"""meusite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
torch.manual_seed(1)
word_to_ix = {"hello": 0, "world": 1}
#first argument is the size of the embedded matrix. The second argument is the dimension of each word embedding.
embeds = nn.Embedding(2, 5) # 2 words in vocab, 5... |
import firebase_admin
from firebase_admin import credentials,firestore
from firebase_admin import storage
cred = credentials.Certificate("./adminKey.json")
firebase_admin.initialize_app(cred, {
'storageBucket': 'women-e598c.appspot.com'
})
#Database Methods
db = firestore.client()
#discrip = ""
title = "GenderEq... |
from __future__ import annotations
import base64
import hashlib
import inspect
import json
import os
import sys
import traceback
from collections import defaultdict
from logging import Logger
from multiprocessing import Pipe, Process
from multiprocessing.connection import Connection
from multiprocessing.pool import Th... |
"""randomdest.py - dearpygui app to plot random destinations"""
import math
import os
import random
import requests
from dotenv import load_dotenv
from dearpygui.core import *
from dearpygui.simple import *
# globals/constants
EARTH_RADIUS = 6378.1
MAX_DIST = 16 # destination radius in KM
maps_key = ""
BASE_URL = "... |
from typing import Callable, List, Optional, Union
import datahub.emitter.mce_builder as builder
from datahub.configuration.common import ConfigModel, KeyValuePattern
from datahub.configuration.import_resolver import pydantic_resolve_key
from datahub.ingestion.api.common import PipelineContext
from datahub.ingestion.t... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from optionaldict import optionaldict
from teambition.api.base import TeambitionAPI
class Works(TeambitionAPI):
def get(self, id=None, parent_id=None, page=None, count=None, all=None):
"""
获取文件信息
详情请参考
... |
import csv
import sys
bom = {}
reader = csv.reader(sys.stdin)
header = next(reader)
columns = {}
for (column_name, column_number) in zip(header, range(0, len(header))):
columns[column_name.strip()] = column_number
# Digikey ignores the headers and makes one map columns, so this
# is unnecessary and also annoyin... |
from lndynamic import LNDynamic
api_id = 'YOUR API ID'
api_key = 'YOUR API KEY'
api = LNDynamic(api_id, api_key)
print api.request('vm', 'list') |
from flask import Flask
from flask_middleware_jwt import Middleware, middleware_jwt_required
app = Flask(__name__)
app.config['MIDDLEWARE_URL_IDENTITY'] = 'http://0.0.0.0:5000'
app.config['MIDDLEWARE_VERIFY_ENDPOINT'] = '/token/verify'
app.config['MIDDLEWARE_BEARER'] = True
app.config['MIDDLEWARE_VERIF... |
from common.python.simulations import BlockSimulation, properties_from_ini
from collections import deque
# max queue size
MAX_QUEUE = 1023
# min FPGA deadtime between queued pulses
MIN_QUEUE_DELTA = 4
# time taken to clear queue
QUEUE_CLEAR_TIME = 4
NAMES, PROPERTIES = properties_from_ini(__file__, "pulse.block.in... |
from fontTools.misc.py23 import *
from fontTools.misc import sstruct
from . import DefaultTable
from fontTools.misc.textTools import safeEval
from .BitmapGlyphMetrics import BigGlyphMetrics, bigGlyphMetricsFormat, SmallGlyphMetrics, smallGlyphMetricsFormat
import struct
import itertools
from collections import deque
im... |
def generate_gaussianFile(geom, grid, logger, outdir="./", igrid=0, maxbq=200):
gaussianfile = outdir + \
"input_batch_{:05d}.com".format(igrid)
f = open(gaussianfile, "w")
# f.write("%OldChk=/home/aartigas/chk/molecule_spe.chk\n".format())
f.write("%nproc=8\n".format())
f.write("%mem=1000MB\... |
import torch
from mmdet.core import force_fp32, images_to_levels
from ..builder import HEADS
from ..losses import carl_loss, isr_p
from .retina_head import RetinaHead
@HEADS.register_module()
class PISARetinaHead(RetinaHead):
"""PISA Retinanet Head.
The head owns the same structure with Retinanet Head, but ... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
from itertools import chain
import numpy as np
import torch
from torch import nn as nn
from torch.autograd import Variable
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
from tqdm import tqdm
import sys
from diff_repres... |
# Copyright 2019 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
class Solution:
def search(self, nums: List[int], target: int) -> bool:
i,j=0,len(nums)
while i<j:
m=i+(j-i)//2
if nums[m]==target: return True
if nums[m]>nums[i]:
if target>=nums[i] and target<nums[m]:
j=m
else:... |
import tvm
from tvm import relay
from tvm import relay
from tvm.runtime.vm import VirtualMachine
from tvm.contrib.download import download_testdata
from SimpleModel import Net
import numpy as np
import cv2
# PyTorch imports
import torch
import torchvision
# Time library for speed check
import time
in_size = 32
inpu... |
# -*- coding: utf-8 -*-
#/usr/bin/env python
import numpy as np
import matplotlib.pylab as plt
from timer import Timer
from chebpy import ETDRK4FxCy, ETDRK4FxCy2, BC, ETDRK4
from chebpy import ROBIN, DIRICHLET
def test_etdrk4fxcy():
'''
The test function is
u = e^[f(x,y) - t]
where
... |
from flask import Flask, jsonify,render_template,request
from config import API_KEY
import datetime
from collections import defaultdict
import requests
import pandas as pd
import sys
import logging
from itertools import repeat
app = Flask(__name__)
gunicorn_error_logger = logging.getLogger('gunicorn.error')
app.logger... |
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
#
# 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 Licens... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import cv2
import math
class IntersectionDetector:
def __init__(self):
self.lower_blue = np.array([85, 90, 120], np.uint8)
self.upper_blue = np.array([115, 255, 255], np.uint8)
def fn_find_intersection_line(self, img_trans):
... |
# Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
import math
import warnings
import weakref
import numpy as np
from jax import lax, ops, tree_flatten, tree_map, vmap
from jax.flatten_util import ravel_pytree
from jax.nn import softplus
import jax.numpy as jnp
from jax.scipy.linalg ... |
import numbers, random
class Sprite1d:
"""A one-dimensional sprite with subpixel positioning."""
def __init__(self, icon, color_list, speed=0, acceleration=0, bound=(0, 1),
position=0, center=None):
self.color_list = color_list
if hasattr(color_list, 'dtype'):
self... |
from .response import get_response
from .lambda_proxy_response import get_lambda_proxy_response |
# -*- coding: utf-8 -*-
"""
pagarmecoreapi
This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ).
"""
import pagarmecoreapi.models.get_customer_response
import pagarmecoreapi.models.paging_response
class ListCustomersResponse(object):
"""Implementation of the 'ListCustomersResp... |
""" Configuration and utilities for service logging
"""
import logging
from typing import Optional, Union
from aiodebug import log_slow_callbacks
from aiohttp.log import access_logger
from servicelib.logging_utils import config_all_loggers
LOG_LEVEL_STEP = logging.CRITICAL - logging.ERROR
def setup_logging(*, lev... |
class Solution(object):
def sortArrayByParity(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
result = []
for i in A:
if i%2 == 0:
result.insert(0,i)
else:
result.append(i)
... |
# Copyright (c) 2020-2022 The PyUnity Team
# This file is licensed under the MIT License.
# See https://docs.pyunity.x10.bz/en/latest/license.html
from pyunity import Behaviour, GameObject, SceneManager, Material, RGB, Mesh, Vector3, MeshRenderer, WaitForSeconds
class Switch(Behaviour):
async def Start(self):
... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from __future__ import absolute_import, print_function
import io
import re
from glob import glob
from os.path import basename
from os.path import dirname
from os.path import join
from os.path import splitext
from setuptools import find_packages
from setuptools import se... |
import os
import pystac
from pystac.utils import str_to_datetime
import rasterio as rio
from shapely.geometry import box, mapping, shape
from stactools.cgls_lc100.constants import (
PROVIDER_NAME, ITEM_TIF_IMAGE_NAME, DISCRETE_CLASSIFICATION_CLASS_NAMES,
DISCRETE_CLASSIFICATION_CLASS_PALETTE)
def create_ite... |
import syncconnect
import responses
import unittest
class TestRequester(unittest.TestCase):
EXPECTED = 'expected'
URL = 'http://ford.url'
def queue(self, status_code, **kwargs):
""" queue fake responses with passed status code """
if not kwargs:
json = {'message': self.EXPECT... |
'''
Copyright 2016, United States Government, as represented by the Administrator of
the National Aeronautics and Space Administration. All rights reserved.
The "pyCMR" platform is licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may ... |
class IndeedCursor(JobCursor):
def __init__(self, title: str, location: str, radius: int = 25):
base_url = "https://www.indeed.com/jobs?"
self._title = title
self._location = location
title_esc = ul.quote(self._title, safe='')
location_esc = ul.quote(self._location, safe='')... |
# Copyright 2019 The Simons Foundation, Inc. - All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ap... |
"""Generic functions related to Jira."""
from typing import Any, Dict
import httpx
async def post_jira_issue(url: str, jira_user: str, jira_token: str, payload: Dict[str, Any]) -> Dict[str, Any]:
"""Post payload to create jira issue.
Args:
url (str): url
jira_user (str): jira username
... |
from shutil import copyfile
from pathlib import Path
from django.apps import apps
from django.conf import settings
from django.core.management.base import BaseCommand
class Command(BaseCommand):
def setup(self, options):
self.theme_name = options['name']
self.theme_path = Path(options['name'])
... |
from django.contrib.auth.models import User
from django.urls import reverse, resolve
from django.test import TestCase
from ..views import BoardListView
from ..models import Board
class BoardsTests(TestCase):
def setUp(self):
username = 'joe'
password = '123'
_ = User.objects.create_user(us... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.