text stringlengths 3.07k 12.6k |
|---|
from __future__ import absolute_import
import sys
from datetime import datetime
from xml.etree.ElementTree import Element, SubElement, tostring
from xml.sax.saxutils import escape
from .helpers import datetime_to_api_timezone
from .constants import (AUTOTASK_API_QUERY_ID_LIMIT,
AUTOTASK_API_QUER... |
# -*- coding: utf-8 -*-
# @Time : 19-11-19 22:10
# @Author : <NAME>
# @Reference : None
# @File : cut_twist_join.py
# @IDE : PyCharm Community Edition
"""
将身份证正反面从原始图片中切分出来,如果方向不正确则旋转。使用传统图像处理方法实现。
需要的参数有:
1.图片所在路径。
2.图片处理结果保存路径
输出结果为:
切分和旋转后的身份证正反面图片。
对于图片A.jpg,... |
from app import db
from datetime import datetime, date, time
from sqlalchemy import func
class Offer(db.Model):
__tablename__ = "offer"
id = db.Column(db.Integer(), primary_key=True)
user_id = db.Column(db.Integer(), db.ForeignKey(
"app_user.id"), nullable=False)
event_id = db.Column(db.Int... |
import os
import stat
import tempfile
import unittest
from unittest.mock import MagicMock
import test_utils
from concourse.client.model import BuildStatus
from concourse.steps import step_def
from concourse.model.base import ScriptType
from concourse.model.job import JobVariant
from concourse.model.resources import ... |
import gym
import numpy as np
import matplotlib.pyplot as plt
from collections import defaultdict
def generate_session(policy, t_max=10 ** 4):
"""
Play game until end or for t_max ticks.
:param policy: an array of shape [n_states,n_actions] with action probabilities
:returns: list of states, list of a... |
import paddle.fluid as fluid
import paddle.fluid.dygraph.nn as nn
import paddle.fluid.layers as L
from utils import ConvModule, model_size
from models.resnet import ResNet, BasicBlock, make_res_layer
from models.triple_loss import TripletLoss
class DeCoder(fluid.dygraph.Layer):
def __init__(self,
... |
import sys
import numpy as np
import pandas as pd
import csv
import math
import operator
import os
import time
from feat_eng import *
from modeling import *
# Adding relative path to python path
#abs_path = os.path.abspath(__file__)
#file_dir = os.path.dirname(abs_path)
#sys.path.append(file_dir)
sys.path.append("/h... |
import torch.utils.data
import os
import rasterio
import torch
import numpy as np
import torch.nn.functional as F
import random
from utils.progressbar import ProgressBar
LABEL_FILENAME="y.tif"
def read(file):
with rasterio.open(file) as src:
return src.read(), src.profile
class RandomDataset(torch.utils.... |
# The MIT License (MIT)
#
# Copyright (c) 2018 <NAME>
# https://www.linkedin.com/in/federicosaldarini
# https://github.com/saldavonschwartz
# https://0xfede.io
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal... |
import numpy as np
from typing import Dict, Optional, Callable, Sequence
import dataclasses
from logging import getLogger
import math
import random
from nevergrad.optimization import optimizerlib
from nevergrad.instrumentation import InstrumentedFunction
from nevergrad.instrumentation.variables import Gaussian
from .... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2019 The FATE 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/lic... |
from PyQt5 import QtGui, QtCore, QtWidgets
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPen, QBrush, QColor, QGradient
from typing import Union
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .Canvas import Canvas
class VertexItem(QtWidgets.QGraphicsRectItem):
"""Represent future coordinates... |
#!/usr/bin/env python3
################ mylis: Tiny Scheme Environment in Python 3.10
## Additional runtime support by <NAME> for lis.py by
## <NAME> (c) 2010-18; See http://norvig.com/lispy.html
import functools as ft
import itertools as it
import operator as op
import math
import readline # "unused" import to ena... |
import json
import magic
import base64
from pppine.encoders.json import UniversalJSONEncoder
from bson.json_util import object_hook
from string import digits
def replace_at_index(string: str, new_char: str, index: int, no_fail: bool = False):
"""
Replace a string's character at the specified index.
:para... |
# Standard imports
import os
import socket
import json
import time
# Local imports
import processes.ggpPlayerProcess
import util.config_help
import networking.working as NET
# Setting up logging:
# https://docs.python.org/2/howto/logging.html#configuring-logging-for-a-library
import logging
LOG = logging.getLog... |
#-------------------------------------------------------------------------------
# Name: CONNECT 4 GAME
# Purpose: PROJECT FOR GAME DEVELOPMENT IN OOP
#
# Author: <NAME>, PASCUAL, LAURENT, VENERACION
#
# Created: 30/10/2019
# Copyright: (c) XENON_XEIN_XENLY 2019
# Licence: <your licence>
#----... |
#
# This file is part of LiteX.
#
# Copyright (c) 2019 <NAME> <<EMAIL>>
# Copyright (c) 2019-2020 <NAME> <<EMAIL>>
# SPDX-License-Identifier: BSD-2-Clause
from migen import *
from litex.soc.cores.clock.common import *
from litex.soc.cores.clock.xilinx_common import *
# Xilinx / Spartan6 -----------------------------... |
import pandas as pd
import numpy as np
import pickle
import os
import re
def pkl_to_df(model_dir):
''' Perform ETL on all models in a specified directory (that exist as .pkl files), transform into tidy formatted DataFrame. Training loss is averaged over chunks to a per-epoch level.'''
try:
os.chdir(os... |
# -*- coding: utf-8 -*-
"""
Created on Sun May 1 11:40:54 2016
@author: rahulkumar
"""
import numpy as np
import re
import itertools
from collections import Counter
from os import listdir
from os.path import isfile, join
def clean_str(string):
"""
Tokenization/string cleaning for all datasets except for ... |
import unittest
from collections import OrderedDict
from textwrap import dedent
from unittest.mock import Mock
from znake.setupgen import _render_entry_points, _render_install_requirements, \
_render_package_data, _render_setup_py_data
class TestRenderInstallRequires(unittest.TestCase):
def test_render_inst... |
import os.path as op
import numpy as np
from joblib import Parallel, delayed
import mne
import config as cfg
from library import preprocessing as pp
from library.preprocessing import (
_run_maxfilter, _get_global_reject_epochs, _get_global_reject_ssp)
def clean_raw(raw, subject, sss, ssp_er, ssp_eog, ssp_ecg, d... |
"""
Copyright 2016 Workiva, 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 or agreed to in writing, software
dist... |
#!/usr/bin/env python
# The MIT License (MIT)
#
# Copyright (c) 2016 <NAME>, National Institutes of Health / NINDS
#
# 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, incl... |
# 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... |
# Copyright (c) 2020-2022, NVIDIA CORPORATION & 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.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless ... |
from pypy.interpreter.mixedmodule import MixedModule
class PyPyModule(MixedModule):
interpleveldefs = {
'debug_repr': 'interp_extras.debug_repr',
'remove_invalidates': 'interp_extras.remove_invalidates',
'set_invalidation': 'interp_extras.set_invalidation',
}
appleveldefs = {}
cla... |
# date: 2018-09-27
# author: <NAME>.
from microbit import *
import random
import radio
BLINK_COUNT=10
N = 5
#####################################################################
# m = a nxn matrix with elements from {0,1}
#####################################################################
def blink_diag_major(n, ... |
# messy script for parsing metadata out of maps
import math
import os
from pathlib import Path
import sys
import textwrap
from xml.etree import ElementTree as ET
tracks = ['rainbow', 'desert']
src_dir = sys.argv[1]
build_dir = sys.argv[2]
def parse_points(points_str):
return [[int(x) for x in p.split(',')] for ... |
# -*- coding:utf-8 -*-
import logging
import itertools
from collections import deque
from typing import List, Dict, Union, Any, Optional, Deque
from aiostomp.frame import Frame
logger = logging.getLogger("aiostomp.protocol")
class Stomp:
V1_0 = '1.0'
V1_1 = '1.1'
V1_2 = '1.2'
class StompProtocol:
... |
import tensorflow as tf
from utils import *
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, recall_score
from numpy import argmax
from word2vec import *
from sklearn.metrics import confusion_matrix
CONTINUE_TRAIN = False
y_train_dir = './bins/y_train.npy'
x_... |
""" Methods for validate BioSimulations metadata
:Author: <NAME> <<EMAIL>>
:Date: 2021-06-23
:Copyright: 2021, Center for Reproducible Biomedical Modeling
:License: MIT
"""
from ..combine.data_model import CombineArchiveContentFormatPattern
from ..utils.identifiers_org import validate_identifiers_org_uri, InvalidIden... |
# 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 ... |
import threading
import datetime
import schedule
import asyncio
import logging
import time
from flask import Flask, json, request, Response
from werkzeug.wsgi import DispatcherMiddleware
from .utils import AttrDict, TaggedDict, mangle_name, join_url, _APIWrapper, IdioticEncoder
from .dispatch import Dispatcher
from .ve... |
from qiskit import QuantumCircuit
from qiskit import QuantumRegister
from qiskit import ClassicalRegister
try:
from qft import create_qft_circuit
except ModuleNotFoundError:
from core.algorithms.qft import create_qft_circuit
try:
from counting import build_diffuser
except ModuleNotFoundError:
from cor... |
# Copyright (C) 2018-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import logging as log
import numpy as np
from openvino.tools.mo.graph.graph import Node, Graph
from openvino.tools.mo.middle.passes.fusing.helpers import get_next_operation
# TODO: unit tests
def concat_convolutions(graph: Graph, sta... |
import mechanize
from bs4 import BeautifulSoup
import re,string
from collections import defaultdict
from bugger.util import levenshtein
from bugger.exceptions import *
class Mantis(object):
texts = {"access_denied": re.compile("Your account may be disabled or blocked or the username/password you entered is incorrect."... |
import copy
import uuid
from dataclasses import dataclass, field
from typing import (
Dict,
Optional,
TYPE_CHECKING,
Union,
List,
Iterable,
Any,
Mapping,
)
import numpy as np
from elasticsearch import Elasticsearch
from elasticsearch.helpers import bulk
from ..base.backend import BaseB... |
##############################################################################
#
# 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... |
# -*- coding: utf-8 -*-
# MIT License
#
# Copyright (c) 2017 <NAME>
#
# 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, mo... |
import pytest
from unittest.mock import Mock
from kombu import Connection, Exchange, Queue
from kombu.exceptions import ContentDisallowed
class SimpleBase:
def Queue(self, name, *args, **kwargs):
q = name
if not isinstance(q, Queue):
q = self.__class__.__name__
if name:
... |
'''
Dear nT analyser,
if you want to complain please contact: <EMAIL>, <EMAIL>, <EMAIL>
'''
import datetime
import strax
import numba
import numpy as np
# This makes sure shorthands for only the necessary functions
# are made available under straxen.[...]
export, __all__ = strax.exporter()
channel_list = [i for i in... |
from flask import (
Blueprint, flash, g, redirect, render_template, request, session, url_for
)
from datetime import datetime,timezone,timedelta
from . import models
from . import auth
bp = Blueprint('tournaments', __name__)
@bp.route('/')
def index():
tourn = models.Tournament.query.all()
tourn.sort(key... |
"""
This module takes care of the components of the design iteslf.
Author: <NAME> (<EMAIL>)
Date: 10.11.2014
"""
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from design_visual_guide import *
from util import *
class DesignScene(QGraphicsScene):
"""This class holds the dat... |
class Event:
'''A WebUI event that might be sent to the server.
Events should be created using the functions below instead of using the
constructor directly.
Attributes:
source: The component that fired the event.
listening: Whether the server actually wants the event. If false,
... |
import argparse
import os.path
import sys
import time
from binascii import hexlify, unhexlify
from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException
from bitcoinrpc.config import read_default_config
from pai.pouw.mining.blkmaker import blktemplate
from pai.pouw.mining.blkmaker.blkmaker import double_sha25... |
import json
from base64 import b64decode, b64encode
from typing import Optional
from django.conf import settings
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad as crypto_pad
from Crypto.Util.Padding import unpad as crypto_unpad
from Crypto.Util.py3compat import bord
AES_BLOCK_SIZE = 16
AES_KEY_MAX... |
import pytest
from buildpg import BuildError, MultipleValues, Renderer, SetValues, UnsafeError, Values, VarLiteral, render
args = 'template', 'ctx', 'expected_query', 'expected_params'
TESTS = [
{'template': 'simple: :v', 'ctx': lambda: dict(v=1), 'expected_query': 'simple: $1', 'expected_params': [1]},
{
... |
#!/usr/bin/python3
# BSD LICENSE
#
# Copyright(c) 2016-2017 Netronome.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above ... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import os
from lib.layers import *
class SSD(nn.Module):
"""Single Shot Multibox Architecture
See: https://arxiv.org/pdf/1512.02325.pdf for more details.
Args:
phase: (string) Can be "eval" or ... |
import sys
import getpass
import json
from prettytable import PrettyTable
import pandas
import logging
import os.path
import time
# 定义变量
RESULT = {}
# USERINFO = ("admin", "123456")
USERINFO = ("a", "a")
FIELDS = ['name', 'age', 'tel', 'email']
# RESULT.append(FIELDS)
FORMAT = """
==================================... |
# Written by Student 3 <NAME>
from flask import render_template, Blueprint, request, make_response, url_for, redirect, flash
from wtforms import ValidationError
from flask_login import current_user
from app.userstory.forms import UserstoryForm, UserstoryUpdateForm
from app import db
from app.models import... |
import tornado.ioloop
import tornado.web
import Settings
import tornado.httpserver
import tornado.httputil
from onelogin.saml2.auth import OneLogin_Saml2_Auth
from onelogin.saml2.utils import OneLogin_Saml2_Utils
# Global session info
session = {}
class Application(tornado.web.Application):
def __init__(self):
... |
import time
import logging
import multiprocessing
import pickle as pkl
import os
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
from sklearn.model_selection import StratifiedKFold
from alphaml.engine.components.models.classification import _classifiers
from alphaml.engin... |
import pandas as pd
import os
from clarifai.rest import ClarifaiApp
from clarifai.rest import Image as ClImage
import time
import logging
import warnings
from logging.handlers import RotatingFileHandler
logger_file_handler = RotatingFileHandler(u'working_data/logs/clarifai_custom_model.log')
logger_file_handler.se... |
# Copyright 2008-2018 pydicom authors. See LICENSE file for details.
"""Read a dicom media file"""
from pydicom.misc import size_in_bytes
from struct import Struct, unpack
extra_length_VRs_b = (b'OB', b'OW', b'OF', b'SQ', b'UN', b'UT')
ExplicitVRLittleEndian = b'1.2.840.10008.1.2.1'
ImplicitVRLittleEndian = b'1.2.840... |
#!/usr/bin/env python2
# coding=utf-8
import copy
import os
import json
import unicodecsv as csv
import codecs
from urllib2 import urlopen
from jinja2 import Environment, FileSystemLoader
CHINESE_WIKI_LANG = "zh"
SIMPLIFIED_CHINESE_LANG = "zh-hans"
TRADITIONAL_CHINESE_LANG = "zh-hant"
# Wikis that cause problems an... |
from flask import Flask, render_template, request, redirect
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.externals import joblib
from bokeh.e... |
import logging
import random
import shutil
import socket
from datetime import datetime
from pathlib import Path
import numpy as np
import torch
import torch.distributed as dist
import torch.optim as optim
from torch.backends import cudnn
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.ten... |
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, recall_score, precision_score, \
f1_score, confusion_matrix, classification_report
import torch
import json
from transformers import TrainingArguments, Trainer
from transfo... |
from typing import TYPE_CHECKING, List, Tuple, Optional, Iterator
from pkg_resources import DistributionNotFound, get_distribution
from . import errors, lfs
from .lfs import __LFS_DISK_VERSION__, __LFS_VERSION__
try:
__version__ = get_distribution('littlefs-python').version
except DistributionNotFound:
# Pac... |
"""Tests for tools.py"""
import warnings
from unittest.mock import patch
import pytest
from packaging import version
from ixdat.exceptions import DeprecationError
from ixdat.tools import deprecate
# Standard arguments for deprecate
DEPRECATE_STANDARD_ARGS = {
"last_supported_release": "1.2.3",
"update_messag... |
# https://en.wikipedia.org/wiki/Hill_climbing
import math
class SearchProblem:
"""
An interface to define search problems.
The interface will be illustrated using the example of mathematical function.
"""
def __init__(self, x: int, y: int, step_size: int, function_to_optimize):
"""
... |
"""
BSD 4-Clause License
Copyright (c) 2020, asaurusrex
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditi... |
import os
import torch
import torch.nn as nn
import shutil
import math
import torch.optim as optim
import matplotlib.pyplot as plt
def learning_rate_schedule(args, arguments):
"""Build learning rate schedule."""
num_examples = arguments['TADL'].shard_size
optimizer_params = arguments['optimizer'].state[ar... |
# How to use
#
# Train the model and save the model weights
# python lenet_mnist_keras.py --train-model 1 --save-trained 1
#
# Train the model and save the model weights to a give directory
# python lenet_mnist_keras.py --train-model 1 --save-trained 1 --weights data/lenet_weights.hdf5
#
# Evaluate the model from pre-t... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2017, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... |
import numpy
from fiducial import TopoTag
def save_plain_ppm(img, filename: str):
"""Save a matrix (floats) as a PPM image."""
with open(filename, 'wt') as fout:
fout.write("P3\n")
fout.write(f"{img.shape[1]} {img.shape[0]}\n")
fout.write("255\n")
idx = 0
for y in range(img.shape[0]):
for x in range(i... |
from __future__ import absolute_import
from __future__ import with_statement
import sys
import logging
from tempfile import mktemp
from celery import log
from celery.log import (setup_logger, setup_task_logger,
get_default_logger, get_task_logger,
redirect_stdouts_to_lo... |
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 10 16:45:42 2019
@author: ASUS PC
"""
from flask import Flask, render_template, Response
import time
from threading import Lock, Thread
import queue
import socket
from threading import Thread
# emulated camera
from camera3 import Camera
# Ras... |
from __future__ import absolute_import, print_function
import logging
from types import LambdaType
from sentry.models import Organization
from sentry.web.frontend.base import BaseView
from sentry.utils.session_store import RedisSessionStore
from sentry.utils.hashlib import md5_text
from sentry.web.helpers import ren... |
import torch
from mmcv.runner import force_fp32
from torch import nn as nn
from typing import List
from .furthest_point_sample import (furthest_point_sample,
furthest_point_sample_with_dist)
from .utils import calc_square_dist
def get_sampler_type(sampler_type):
"""Get the typ... |
from Tree import *
# create new list of random features in root original length
def generate_features(features_list):
new_random_features = features_list.to_numpy()
np.random.shuffle(new_random_features)
return new_random_features[0:int(np.sqrt(len(features_list)))]
# create a new sub data... |
import csv
import pandas as pd
import geopandas as gpd
import dash_html_components as html
def seismic_reporting_data(occurence):
'''
Seismic Reporting Function
Collects the additional features of the disaster like 'Tsunami Alerts', 'Danger Alerts'
Depends on the occurence type that is being chosen
Parameter : `... |
#!/usr/bin/env python
# encoding: utf-8
"""
An RFC 2821 smtp proxy server port from Python Standrad Library for Gevent usage
"""
# Overview:
#
# This file implements the minimal SMTP protocol as defined in RFC 821. It
# has a hierarchy of classes which implement the backend functionality for the
# smtpd. A number o... |
import asyncio
from libp2p.protocol_muxer.multiselect_client import MultiselectClient
from libp2p.protocol_muxer.multiselect import Multiselect
from libp2p.peer.id import id_b58_decode
from .network_interface import INetwork
from .notifee_interface import INotifee
from .stream.net_stream import NetStream
from .connec... |
# -*- coding: utf-8 -*-
""" Continuous temperature thermodynamic Monte Carlo algorithms. """
import numpy as np
import theano as th
import theano.tensor as tt
from thermomc.hmc import HamiltonianSampler
class GibbsContinuousTemperingSampler(HamiltonianSampler):
"""Gibbs updates continuous tempering sampler.
... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
@version: 0.1
@author: quantpy
@file: mplotly.py
@time: 2018/3/25 8:59
"""
import numpy as np
import pandas as pd
import plotly.figure_factory as ff
import cufflinks as cf
from . import tools
cf.go_offline()
def distplot1d(ss: pd.Series, bins=10, hist=True,... |
"""Testing bootstrap."""
import typing as t
import numpy as np
def bootstrap(
samples: np.ndarray,
num_resamples: int = 256,
random_state: t.Optional[int] = None,
) -> np.ndarray:
"""Generator of bootstraps ``samples``.
Arguments
---------
samples : :obj:`np.ndarray`
Population t... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
# soft accuracy:
# parts of the code are taken from https://github.com/wildltr/ptranking, specifically
# https://github.com/wildltr/ptranking/blob/master/ptranking/base/neural_utils.py
# soft binning:
# we have use... |
import numpy as np
import json, os, logging, pickle, argparse
from simpletransformers.question_answering import QuestionAnsweringModel
def lcs(S,T):
m = len(S)
n = len(T)
counter = [[0]*(n+1) for x in range(m+1)]
longest = 0
lcs_set = set()
for i in range(m):
for j in range(n):
... |
""" Model.py
This module provides class for store and process.
"""
import logging
import warnings
import pandas as pd
import numpy as np
from pandas import DataFrame
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)
sth = logging.StreamHandler()
sth.setLevel(logging.INFO)
stdoutformat = logging.Form... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import re
import bson
import pymongo
class cached_classmethod(object):
def __init__(self, f):
self.f = f
def __get__(self, instance, owner):
value = self.f(owner)
setattr(owner, self.f.__name__, value)
return value
class Cursor(pymon... |
# -*- coding: utf-8 -*-
# Copyright (c) 2015-2018, Exa Analytics Development Team
# Distributed under the terms of the Apache License 2.0
"""
Universe trait functions
#########################
"""
##########
# traits #
##########
import re
import numpy as np
import pandas as pd
from exatomic.base import sym2radius, sy... |
import argparse
import json
import os
import time
from typing import Callable, Generator, Tuple, Sequence, Union, Iterable
def has_ext(file_path: str, ext: str):
"""
Returns True if the extension of file_path is ext
:param file_path: file path to be examined
:param ext: extension
:return: boolea... |
import logging
import invitations.views
from allauth.account.views import EmailView, LoginView, LogoutView
from allauth.account.views import PasswordChangeView as BasePasswordChangeView
from allauth.account.views import SignupView as BaseSignupView
from allauth.socialaccount.views import ConnectionsView as BaseConnect... |
#!/usr/bin/env python
# wujian@2018
# xpavlu10@2020
"""
Compute SI-SDR as the evaluation metric
"""
import argparse
from tqdm import tqdm
from collections import defaultdict
from libs.metric import si_snr, permute_si_snr, permute_si_snr_mix_of_mix
from libs.audio import WaveReader, Reader
from glob import glob
im... |
"""Author: <NAME>"""
import os
from transformers import (BertConfig, BertForMaskedLM, BertTokenizer,
AlbertConfig, AlbertForMaskedLM, AlbertTokenizer)
import torch
from torch.utils.data import ConcatDataset, TensorDataset
import numpy as np
import random
import pickle
import logging
import re
... |
""""
File : message_pump.py
Author : ian
Created : 11-23-2016
Last Modified By : ian
Last Modified On : 11-23-2016
***********************************************************************
The MIT License (MIT)
Copyright © 2016 <NAME> <<EMAIL>>
Permission is hereby granted, free of charge... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import tests
import vcr as base_vcr
from tests.weibos import weibo2
from weibo_exporter import WeiboExporter, WeiboStatusTable
from datetime import datetime
import os
import tempfile
import shutil
vcr = base_vcr.VCR(
cassette_lib... |
#!/usr/bin/env python
"""Functions for finding modules so pynocle doesn't have to go
through python's import machinery.
Ideally it does not have to run any code in order to analyze.
"""
import imp
import os
import sys
_oabs = os.path.abspath
_ojoin = os.path.join
class _ModuleFinder(object):
def __... |
# Copyright (c) 2021 PaddlePaddle 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 appli... |
#!/bin/python
#coding:utf-8
import roomai
class Stage:
firstStage = 1
secondStage = 2
thirdStage = 3
fourthStage = 4
AllCardsPattern = dict()
#0 1 2 3 4 5 6
#name, isStraight, isPair, isSameSuit, [SizeOfPair1, SizeOfPair2,..](des... |
import pytest
import os
import tempfile
import numpy as np
import shutil
from edgel3.cli import positive_float, positive_int, get_file_list, parse_args, run, main
from argparse import ArgumentTypeError
from edgel3.edgel3_exceptions import EdgeL3Error
from unittest.mock import patch
TEST_DIR = os.path.dirname(__file__)... |
from flask import render_template, redirect, url_for, flash, request, \
session, jsonify, abort
from werkzeug.urls import url_parse
from flask_login import login_user, logout_user, current_user, login_required
from flask_babel import _
from app import db
from app.auth import bp
from app.auth.forms import LoginForm,... |
import pytest
from peewee import DoesNotExist
from app.logic.transcript import *
from app.models.user import User
from app.models.courseParticipant import CourseParticipant
from app.models.event import Event
from app.models.programEvent import ProgramEvent
from app.models.facilitator import Facilitator
from app.logic.... |
#!/usr/bin/python
from dis import opname, opmap
import marshal
import sys
import types
def disassemble(s):
i = 0
#r = ''
o = []
dupe_count = 1
while i < len(s.co_code):
op = ord(s.co_code[i])
r = opname[op] + ' '
if op >= 90: # these are the ones with args
oparg = ord(s.co_code[i+1]) | (ord(s.co_code[i+... |
# coding=utf-8
# Copyright 2022 Head2Toe 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 a... |
from __future__ import print_function
import collections
import math
import numpy as np
import random
import tensorflow as tf
from six.moves import range
from assignment5_word2vec.dataset import vocabulary_size, loadDataset
data, count, dictionary, reverse_dictionary = loadDataset()
class BatchGenerator():
def _... |
import wgpu # only for flags/enums
from . import register_wgpu_render_function
from ._shadercomposer import Binding, WorldObjectShader
from ._utils import to_texture_format
from ...objects import Background
from ...materials import BackgroundMaterial, BackgroundImageMaterial
from ...resources import Texture, TextureV... |
# coding=utf-8
# /usr/bin/env python
'''
Author: wenqiangw
Email: <EMAIL>
Date: 2020-07-10 13:16
Desc: 快速排序,冒泡排序,堆排序
'''
def quick_sort(_list,m=0,n=None):
''' “挖坑填数+分治法”
时间复杂度:
最坏情况: 每次基准都是最小值n*(n-1)=O(n^2) 冒泡排序
最优情况&平均情况:每次刚好一分为二,nlog(n)
T(n)=2T(n/2)+n -> T(n/2)=2T(n/4)+n/2 -> T(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.