text stringlengths 2 999k |
|---|
"""
WSGI config for loginProject project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_... |
from __future__ import unicode_literals
import six
import time
import os
import os.path
import zipfile
import logging
try:
from urllib.request import urlopen
except ImportError:
from urllib import urlopen
from .settings import *
class Geonames(object):
logger = logging.getLogger('cities_light')
de... |
from flask import make_response, jsonify, g
from .common import delete_dataset_common
from ....common.corpora_orm import CollectionVisibility, DatasetArtifactFileType
from ....common.entities import Dataset, Collection
from ....common.entities.geneset import GenesetDatasetLink
from ....api_server.db import dbconnect
f... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: list_agent.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf ... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def constructFromPrePost(self, pre, post):
"""
:type pre: List[int]
:type post: List[int]
:rtype: TreeNod... |
from typing import Any, Dict
from sanic.request import Request
from sanic_openid_connect_provider.exceptions import TokenError
from sanic_openid_connect_provider.utils import get_provider
async def validate_userinfo_params(request: Request) -> Dict[str, Any]:
provider = get_provider(request)
if request.met... |
from pathlib import Path
from flask import Flask, request, jsonify
#from flask_marshmallow import Marshmallow
from synapser.controllers.base import VERSION_BANNER
from synapser.core.data.api import RepairRequest, CoverageRequest
from synapser.core.exc import SynapserError, BadRequestError
from typing import List
def... |
from enum import Enum, auto
class AutoName(Enum):
def _generate_next_value_(name: str, start, count, last_values): # type: ignore
return name.lower()
class Status(AutoName):
ONLINE = auto()
AWAY = auto()
|
from __future__ import (absolute_import, division, print_function, unicode_literals)
from builtins import *
import wizzat.testutil
import wizzat.pghelper
class DBTestCase(wizzat.testutil.TestCase):
db_info = {
'host' : 'localhost',
'port' : 5432,
'user' : 'wizzat',
... |
# 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... |
from __future__ import print_function
import os
import six
from six import StringIO
from django.conf import settings
from django.core import files
from django.core.files.storage import FileSystemStorage
from django.core.urlresolvers import reverse
from database_files import models
from database_files import utils
fr... |
"""
Use the CAA in order to project the points
Then computes for each projections the r2
This model is inspired by random projections classification models
"""
import numpy as np
from model.caa import CAAModel
class HashCAA(CAAModel):
def transform(self, x):
"""
Transforms the set of points b... |
import os
import sys
import subprocess
import filecmp
import glob
from beschi.writer import Writer
import beschi.writers
CODE_OUTPUT_DIR = "out/generated"
DATA_OUTPUT_DIR = "out/data"
HARNESS_SRC_DIR = "test/_harnesses"
HARNESS_BIN_DIR = "out/executables"
ALL_WRITERS = beschi.writers.all_writers | beschi.writers.exp... |
import glob
import random
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '2'
import torch
import torch.nn as nn
import numpy as np
from torch.utils.data.dataset import random_split
from torch.utils.data import DataLoader
import torch.optim as optim
import torch.optim.lr_scheduler as lr_scheduler
import torch.nn as nn
i... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
Script to fetch waveform data from IRIS for all 63 events in
C. Alvizuri and C. Tape. Full moment tensors for small events (Mw < 3) at
Uturuncu volcano, Bolivia. Geophys. J. Int., 206(3):1761{1783, 2016. doi:
10.1093/gji/ggw247.
Usage:
python... |
# flake8: noqa
import csv
import os
from pathlib import Path
from tempfile import TemporaryDirectory
from pytest import mark
import torch
from torch import nn
from torch.optim import Adam
from torch.utils.data import DataLoader
from catalyst import data, dl
from catalyst.contrib.datasets import MNIST
from catalyst.c... |
import torch
import torch.nn as nn
class Shufflenet(nn.Module):
def __init__(self, inp, oup, mid_channels, *, ksize, stride):
super(Shufflenet, self).__init__()
self.stride = stride
assert stride in [1, 2]
assert ksize in [3, 5, 7]
self.base_mid_channel = mid_channels
... |
nome = input("Primeiro nome: ")
nome1 = input("Segundo nome: ")
first = ""
second = ""
if nome == nome1:
print("\n" + nome + " - " + nome1)
exit()
for i in range(len(nome) if len(nome) < len(nome1) else len(nome1)):
if ord(nome[i]) < ord(nome1[i]):
first = nome
second = nome1
brea... |
"""
Module test_03_filter
====================
Tests for the filter module.
"""
# chemoinformatics
from rdkit import Chem
# tests
import pytest
from npfc.filter import Filter
# debug
import logging
logging.basicConfig(level=logging.ERROR)
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ FIXTURES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ... |
import os
import argparse
import logging
import json
from datetime import datetime, date
from pprint import pprint
from uzemszunet.utils import order_list, encode_json
from uzemszunet.sendmail import (
EmailTipus, handle_email
)
from uzemszunet.config import cfg, init_logger
from uzemszunet.eon import Eon
from uz... |
#!python
import unittest
import io
from opendis.dis7 import *
from opendis.PduFactory import *
from opendis.DataOutputStream import DataOutputStream
class TestSignalPdu(unittest.TestCase):
def test_parse_and_serialize(self):
with open('SignalPdu.raw', 'rb') as f:
data = f.read()
... |
from __future__ import absolute_import, division, print_function, unicode_literals
import os, sys, re, socket, time, io, gzip, logging, concurrent.futures
from functools import partial
from datetime import datetime
from dateutil.parser import parse as dateutil_parse
from dateutil.relativedelta import relativedelta
fro... |
"""Contains Base class for batch_l2_grad."""
from __future__ import annotations
from typing import TYPE_CHECKING, Callable, List, Tuple
from torch import Tensor
from torch.nn import Module
from backpack.core.derivatives.basederivatives import BaseParameterDerivatives
from backpack.extensions.firstorder.base import F... |
"""BookManager URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class... |
# -*- coding: utf-8 -*-
#
# Copyright 2017 Ricequant, 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 ... |
# coding=utf-8
import datetime
import uuid
from django.db import models
from django.forms import ModelForm
from django.forms import DateInput
from Child import Child
"""Model for Disease History, which records a child's disease history.
This model references the Signature model and the Child model. All
fields are ... |
#!/usr/bin/env python
import re
from ..debugging import bacpypes_debugging, ModuleLogger
from ..task import OneShotTask
from ..primitivedata import Atomic, Null, BitString, CharacterString, \
Date, Integer, Double, Enumerated, OctetString, Real, Time, Unsigned
from ..basetypes import PropertyIdentifier, DateTime... |
import discord
import os
from helpers import get_gif, parse, check_admin_permissions
import helpers
commands = ["lsprope", "lsenabled", "listenabled"]
requires_mention = False
accepts_mention = False
description = "Erlaubte Befehle auflisten"
async def execute(message):
dir_path = helpers.dir_path + "/server_act... |
print('asdasdasd')
print('asdasdasd')
print('asdasdasd')
print('asdasdasd')
print('asdasdasd')
print('asdasdasd')
print('asdasdasd') |
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import include
from django.urls import path
import apps.core.urls
urlpatterns = [
path("", include(apps.core.urls)),
path("admin/", admin.site.urls),
] + static(settings.MEDIA_URL, doc... |
__title__ = "binance.py"
__author__ = "Th0rgal"
__license__ = "MIT"
__version__ = "0.0.0"
from .definitions import *
from .client import Client
|
# coding: utf-8
import re
import six
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class TagItem:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribu... |
from flask import Flask, render_template
from db_connector.db_connector import connect_to_database, execute_query
app = Flask(__name__)
#the route is what you will type in browser
@app.route('/hello')
#the name of this function is just a cosmetic thing
def hello():
#this is the output returned to browser
retu... |
from abc import ABCMeta, abstractmethod
from datetime import datetime
from uuid import uuid4
from api.utils import all_subclasses
CTIM_DEFAULTS = {
'schema_version': '1.0.17',
}
RESOLVED_TO = 'Resolved_To'
class Mapping(metaclass=ABCMeta):
def __init__(self, observable):
self.observable = observab... |
import asyncio
import aiohttp
import pandas
from concurrent.futures import ThreadPoolExecutor
from fpl import FPL
from fpl.constants import API_URLS
from fpl.utils import fetch, logged_in
class FPLTransfers():
'''
'''
def __init__(self, email=None, password=None):
'''
Placeholder - the... |
from fpdf import FPDF
# Author: @NavonilDas
class MyPdf(FPDF):
def header(self):
# Uncomment the line below to add logo if needed
# self.image('somelogo.png',12,10,25,25) # Draw Image ar (12,10) with height = 25 and width = 25
self.set_font("Arial", "B", 18)
self.text(27, 10, "Ge... |
# Copyright 2017 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... |
import youtube_dl
from tkinter import Tk, Label, Button, Text
class app_gui:
print("running")
def __init__(self):
self.master = Tk()
self.master.title("Youtube Downloader")
self.master.label = Label(self.master, text="Enter a youtube link to download!")
self.master.label.pack(... |
# -*- coding: utf-8 -*-
"""
NEEDS CLEANUP
"""
import logging
from os.path import join
import utool as ut
from wbia.algo.hots import _pipeline_helpers as plh # NOQA
from wbia.algo.hots.neighbor_index import NeighborIndex, get_support_data
(print, rrr, profile) = ut.inject2(__name__)
logger = logging.getLogger('wbia')
... |
from imix.models.builder import VQA_MODELS
from imix.models.vqa_models.base_model import BaseModel
from copy import deepcopy
from pytorch_transformers import BertConfig
from .modeling_bert import BertImgForPreTraining
from imix.utils.registry import Registry
from collections import OrderedDict
import torch
BERT = Reg... |
VALID_PYTHON_VERSIONS = ['2.7', '3.4', '3.5', '3.6', '3.7']
STRATEGIES = ['OEC', 'normal', 'dependency']
MATCH_PATTERNS = ['strong', 'weak', 'best_effort']
|
# Authors: Edouard Oyallon, Sergey Zagoruyko
import torch
from torch.nn import ReflectionPad2d
from collections import namedtuple
BACKEND_NAME = 'torch'
def iscomplex(x):
return x.size(-1) == 2
def isreal(x):
return x.size(-1) == 1
class Pad(object):
def __init__(self, pad_size, input_size, pre_pad=Fal... |
from click.testing import CliRunner
from linotype.__main__ import main
def test_main():
runner = CliRunner()
result = runner.invoke(main, [])
assert result.output == '()\n'
assert result.exit_code == 0
|
_base_ = "./fovea_r50_fpn_4x4_1x_coco.py"
model = dict(pretrained="torchvision://resnet101", backbone=dict(depth=101))
|
# Copyright (C) 2021, Mindee.
# This program is licensed under the Apache License version 2.
# See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details.
from typing import Any, List, Union
import numpy as np
import tensorflow as tf
from doctr.io.elements import Document
from d... |
import json
from django.core.serializers.json import DjangoJSONEncoder
from django.db import models
from django.utils.encoding import force_str
from wagtail.blocks import Block, BlockField, StreamBlock, StreamValue
from wagtail.rich_text import get_text_for_indexing
class RichTextField(models.TextField):
def __... |
# coding=utf8
import sys
import table2excel
def run_test():
table = [["a", "b", "c"], [1, 2, 3], [4, 5, 6]]
excel = table2excel.dumpExcel('test', table)
sys.stdout.write(excel)
sys.stdout.flush()
if __name__ == "__main__":
run_test()
|
##############################################################################
# example fibonacci number code;
# you do not have to modify this code in any way
##############################################################################
def fibs(n):
'''
This function computes the first n fibonacci numbers... |
from ...ext.ellipsoid import rsa_mda, rsa_md |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-07-28 05:21
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('tournament', '0031_auto_20160728_0520'),
]
operations = [
migrations.RenameModel(
old_name='Pairing',
... |
import cupy as cp # noqa
import cupyx.scipy.sparse as sparse # noqa
import numpy as np
from graph_tool.spectral import adjacency
from tqdm import tqdm
import torch
from torch.utils.dlpack import to_dlpack
class RandomWalkSimulator:
"""
The class RandomWalkSimulator is designed to run a fast simulations of a ... |
# 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... |
import logging
from typing import List, Tuple, Dict, Optional
import aiosqlite
from maize.types.coin_spend import CoinSpend
from maize.util.db_wrapper import DBWrapper
from maize.util.ints import uint32
log = logging.getLogger(__name__)
class WalletPoolStore:
db_connection: aiosqlite.Connection
db_wrapper:... |
"""The builtin str implementation"""
from rpython.rlib import jit
from rpython.rlib.jit import we_are_jitted
from rpython.rlib.objectmodel import (
compute_hash, compute_unique_id, import_from_mixin)
from rpython.rlib.buffer import StringBuffer
from rpython.rlib.rstring import StringBuilder, replace
from pypy.int... |
# -*- coding: utf-8 -*-
from django.http import HttpResponseForbidden
from django.template import loader
from django.utils.translation import ugettext_lazy as _
# 普通用户
def _requred_forbid(msg):
t = loader.get_template('limit_ip.html')
content = t.render({'message': msg })
return HttpResponseForbidden(cont... |
__version__ = '0.0.0'
short_version = __version__
def parse_version_info(version_str):
version_info = []
for x in version_str.split('.'):
if x.isdigit():
version_info.append(int(x))
elif x.find('rc') != -1:
patch_version = x.split('rc')
version_info.append(i... |
import ConfigParser
import os
import sys
def irida_config():
try:
config=read_config()
confdict = {section: dict(config.items(section)) for section in config.sections()}
return confdict
except Exception as e :
print(str(e),' Could not read configuration file')
def read_config():... |
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import collections
import os
import re
import sys
import shutil
import copy
import socket
import six
from ordereddict_ba... |
"""
Utility functions for end-to-end tasks
"""
import json
import os
import pickle
from os import makedirs, remove
from os.path import join, exists, splitext, basename, relpath
from pathlib import Path
import langdetect
from bs4 import BeautifulSoup
from librosa.output import write_wav
from pydub import AudioSegment
... |
import numpy as np
from scipy.signal import resample
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import RobustScaler
def upsample_signal(data, sampling_factor, sampler=None):
"""
data is a time series sequence(nd_array) numpy data
... |
"""
The ``memory`` taxon groups applets implementing interfaces to memory technology devices (volatile
and non-volatile) that include no functionality beyond manipulating data.
Examples: SPI flash, I²C EEPROM.
Counterexamples: SPI flash on an FPGA board that requires coordinated reset (use taxon
``program``), flash ma... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This subpackage contains classes and functions for defining and converting
between different physical units.
This code is adapted from the `pynbody
<https://github.com/pynbody/pynbody>`_ units module written by Andrew
Pontzen, who has granted the Ast... |
import asyncio
import json
import os
import time
import warnings
import wave
from queue import Queue
from typing import Callable
import numpy as np
import pvporcupine
import sounddevice as sd
import vosk
from fluxhelper import osInterface
from speech_recognition import AudioFile, Recognizer, UnknownValueError
from ten... |
from .agent import Agent
from .beeper import Beeper
from .direction import Direction, load_direction_from_save
from .position import Position, load_position_from_save
DEFAULT_PAUSE_DURATION = 0
def load_robot_from_save(robot_save):
return Robot(
position=load_position_from_save(robot_save['position']),
... |
# Copyright 2021 The Flax 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 applicable law or agreed to in wri... |
# encoding=utf-8
from rest_framework import serializers
from lepus.models import *
from lepus.serializers import BaseSerializer, TeamSerializer, CategorySerializer
from lepus.signals import send_realtime_event
class AdminUserSerializer(BaseSerializer):
class Meta:
model = User
fields = ("id", "us... |
# Copyright 2011 OpenStack Foundation
# 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 requ... |
from pairs.ir.block import pairs_block
from pairs.ir.variables import VarDecl
from pairs.sim.lowerable import Lowerable
class VariablesDecl(Lowerable):
def __init__(self, sim):
super().__init__(sim)
@pairs_block
def lower(self):
for v in self.sim.vars.all():
VarDecl(self.sim, ... |
# -*- coding: utf-8 -*-
## ! DO NOT MANUALLY INVOKE THIS setup.py, USE CATKIN INSTEAD
from distutils.core import setup
from catkin_pkg.python_setup import generate_distutils_setup
# fetch values from package.xml
setup_args = generate_distutils_setup(
packages=['autonomous_agent_template'],
package_dir={'': 's... |
# This file is part of the pyMOR project (https://www.pymor.org).
# Copyright 2013-2021 pyMOR developers and contributors. All rights reserved.
# License: BSD 2-Clause License (https://opensource.org/licenses/BSD-2-Clause)
from collections import namedtuple
from pymor.core.base import ImmutableObject
from pymor.model... |
from layers import *
from cross_replica_batch_norm import *
from tpu_normalization import *
|
# DO NOT MODIFY THIS FILE DIRECTLY. THIS FILE MUST BE CREATED BY
# mf6/utils/createpackages.py
from .. import mfpackage
from ..data.mfdatautil import ListTemplateGenerator, ArrayTemplateGenerator
class ModflowNam(mfpackage.MFPackage):
"""
ModflowNam defines a nam package.
Parameters
----------
s... |
def palindrome(string):
from re import sub
s = sub('[\W_]', '', string.lower())
return s == s[::-1] |
#!/usr/bin/env python
import os
import setupcfg
os.chdir(os.path.dirname(__file__))
data = setupcfg.load()
print(data)
|
from django.db import models
class Team(models.Model):
competition = models.CharField(max_length=40)
name = models.CharField(max_length=80)
city = models.CharField(max_length=80)
login = models.CharField(max_length=20)
password = models.CharField(max_length=20)
score = models.Positive... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 10 14:33:19 2019
@author: ziskin
"""
from PW_paths import work_yuval
from pathlib import Path
cwd = Path().cwd()
# TODO: build curve fit tool with various function model: power, sum of sin ...
# TODO: no need to build it, use lmfit instead:
# TODO: ... |
import numpy as np
import numpy.random as npr
import numpy.linalg as npl
import os
import pickle as pkl
'''
File containing helper functions for details about target P and
drawing samples / loading mcmc samples from file
'''
######## functions related to setting P and sampling from it ########
def sam... |
''' Define the sublayers in encoder/decoder layer '''
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
from models.Modules import ScaledDotProductAttention
__author__ = "Yu-Hsiang Huang"
class MultiHeadAttention(nn.Module):
''' Multi-Head Attention module '''
def __init__(self, n_head... |
import pysam
from .utils import toDataFrame
from .Helper import get_range_helper
import pandas as pd
from aiocache import cached, Cache
from aiocache.serializers import JsonSerializer, PickleSerializer
__author__ = "Jayaram Kancherla"
__copyright__ = "jkanche"
__license__ = "mit"
class GtfParsedFile(object):
"""... |
import os
import requests
def file_exists(file_name):
return os.path.exists(os.path.abspath('')+'/'+file_name)
csvs_url = [
'http://dados.ufrn.br/dataset/8bf1a468-48ff-4f4d-95ee-b17b7a3a5592/resource/ff0a457e-76fa-4aca-ad99-48aebd7db070/download/docentes.csv',
'http://dados.ufrn.br/dataset/c8650d55-3c5a-4... |
"""first_project URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/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... |
"""snifula URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/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... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015-2018 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/LICENSE-2.0
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import smbus
import time
import datetime
import threading
ADDRESS = 0x76 # 7bit address (will be left shifted to add the read write bit)
READ_INT = 2 # [sec]
LOG_INT = 600 # [sec]
DEBUG = True
# Print a given message with the date
def print_date_msg(msg):
d = datetime.... |
from setuptools import find_packages, setup
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name="GodingWal-game-utils",
version="1.2",
author="Goding Wal",
author_email="datacreativellc@gmail.com",
description="Gameplay logic for Rock-Paper-Scissors",
long_descript... |
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash
db = SQLAlchemy()
class Base (db.Model):
__abstract__ = True
created_at = db.Column(db.DateTime, default=datetime.utcnow)
updated_at = db.Column(db.DateTime,
... |
# -*- coding: utf-8 -*-
# Copyright (2018) 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/LICENSE-2.0
#
# Unless... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from base import BaseModel
from model.mem_transformer import MemTransformerLM
from model.gru_ae import *
import numpy as np
class Seq_Attention(BaseModel):
def __init__(
self,
transformer_state_path,
num_classes,
code... |
#!/usr/bin/env python
import codefast as cf
import numpy
red = cf.format.red
green = cf.format.green
def cer(r: str, h: str):
'''Character Error Rate
(S + D + I) /N
S: substitution
D: Deletion
I: Insertion
'''
d = numpy.zeros((len(r) + 1) * (len(h) + 1), dtype=numpy.uint16)
d = d.res... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/3/9 10:44
# @Author : yaoh
# @email : hyao666@foxmail.com
# @File : network2.py
# @Software: PyCharm Community Edition
from api_of_data_prepare import read_data_of_label
from api_of_network import *
from sklearn.model_selection import trai... |
from multiprocessing import Pool
import mmcv
import numpy as np
from mmcv.utils import print_log
from terminaltables import AsciiTable
from .bbox_overlaps import bbox_overlaps
from .class_names import get_classes
def average_precision(recalls, precisions, mode='area'):
"""Calculate average precision (for single... |
from fenics import *
from fenics_adjoint import *
import numpy as np
from pyadjoint import Block
from pyadjoint.overloaded_function import overload_function
def get_coefficient(func, coord1, coord2, gradient=False, grad_idx=None):
return func(coord1, coord2)
backend_get_coefficient = get_coefficient
class Coe... |
import os.path
import os
import shutil
from dbt.task.base_task import BaseTask
class CleanTask(BaseTask):
def __is_project_path(self, path):
proj_path = os.path.abspath('.')
return not os.path.commonprefix(
[proj_path, os.path.abspath(path)]
) == proj_path
def __is_prote... |
# Copyright 1997 - 2018 by IXIA Keysight
#
# 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, p... |
from __future__ import absolute_import, division, print_function
from .common import Benchmark
import numpy as np
avx_ufuncs = ['sqrt',
'absolute',
'reciprocal',
'square',
'rint',
'floor',
'ceil' ,
'trunc']
stride = [1,... |
"""
Differential synchronization logic for server.
"""
# TODO: make edits a queue
# TODO: substitute diffs for patches? otoh patches seem more succinct?
from geventwebsocket import WebSocketError
import diff_match_patch as dmp
import json
from hashlib import md5
# {key=client_id <str>, val={server_shadow <{str,[int,i... |
from __future__ import print_function
from __future__ import division
import math
import torch
import torch.nn as nn
from torch.nn import Parameter
from torchkit.head.localfc.common import calc_logits
class CosFace(nn.Module):
""" Implement of CosFace (https://arxiv.org/abs/1801.09414)
"""
def __init__(s... |
from django.urls import path
from .views import (
DashboardView,
UserListView, ParcelListView, SearchIDView, TestView, UserExistsJSON)
app_name = "customer"
urlpatterns = [
path('', DashboardView.as_view(), name='dashboard'),
path('user/', UserListView.as_view(), name='user'),
path('parcel/', Parc... |
#-*-coding:utf-8-*-
import json
import time
import web
__author__ = 'george.yang'
class tool:
def getip(self):
print 'getip'
data={}
data["ip"]=web.ctx['ip']
data["id"]=1
data["time"]= long(time.time())
outJson={}
outJson["errorCode"] = 0
outJson["... |
import graphene
from django.core.exceptions import ValidationError
from ...webhook import models
from ...webhook.error_codes import WebhookErrorCode
from ..core.mutations import ModelDeleteMutation, ModelMutation
from ..core.types.common import WebhookError
from .enums import WebhookEventTypeEnum
from .types import We... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.