text stringlengths 3.07k 22.1k |
|---|
from __future__ import print_function, division
import argparse
import torch
import torch.nn as nn
import torch.optim as optim
import math
import pickle
import matplotlib.pyplot as plt
from teacher_student import *
from teacher_dataset import *
def get_Q(path_to_mask_list, path_to_teacher, input_dim):
unpruned_MLP... |
#!/usr/bin/env python3
"""
coloromo.color
MIT License
Copyright (c) 2021 <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 u... |
import time
import datetime
import re
import argparse
from mylogging import logger
from selenium import webdriver
import pandas as pd
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from urllib3.exceptions import MaxRetryError
from selenium.common.exceptions import WebDriverException
#... |
"""Tools for partitioning sets."""
# http://codereview.stackexchange.com/questions/1526/finding-all-k-subset-partitions
# http://stackoverflow.com/questions/18353280/iterator-over-all-partitions-into-k-groups
# https://docs.python.org/3/library/itertools.html
# http://stackoverflow.com/questions/9316436/how-many-diffe... |
import json
from excepciones import *
import re
import nltk
from nltk.corpus import stopwords
from string import punctuation
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import pandas as pd
import logging
#Descargar las stopwords, necesario para la ... |
#!/usr/bin/env python
"""
TODO:
- allow plotting single component, cpt_min would have to be calculated
- optimise land crop: download lower res, make template with it (png still slower)
"""
from argparse import ArgumentParser
from multiprocessing import Pool
import os
from shutil import rmtree
from tempfile import mkd... |
from abc import ABC, abstractmethod
import torch
from data_utils import helper
from data_utils import pose_features
# A normalizer provides an interface to normalize and denormalize a batch of poses.
# The normalization/denormalization is always a deterministic process.
class BaseNormalizer(ABC):
@classmethod
... |
import os
from typing import List, Union
from werkzeug.wrappers import Request, Response
from werkzeug.serving import run_simple
from jsonrpc import Dispatcher, JSONRPCResponseManager as JRPCRespMgr
from jsonrpc.exceptions import JSONRPCDispatchException, JSONRPCServerError, JSONRPCInternalError
import log
from API... |
import sys, os
import numpy as np
import scipy
import itertools
import time
from math import factorial
import copy as cp
import sys
import tools
from fermicluster import *
from pyscf_helper import *
import pyscf
from pyscf import gto, scf, ao2mo, molden, lo, mo_mapping, mcscf
pyscf.lib.num_threads(1) #with degenerat... |
import pycurl
import os
import sys
import StringIO
import urllib2
import lib_TheardPool2
import lib_func
import shutil
import gzip
import urlparse
import re
import math
flock=lib_TheardPool2.getlock()
curlopts={pycurl.USERAGENT:"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0",\
pycu... |
from pathlib import Path
import multiprocessing as mp
from torch.optim import Adam
from torch.optim.lr_scheduler import ReduceLROnPlateau
from tqdm import tqdm
from transformers import AutoTokenizer, BertForMaskedLM, BertForSequenceClassification, AutoConfig, BertModel
import torch
import torch.utils.data as tud
from... |
'''
Copyright 2014 Hewlett-Packard
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, softwar... |
import unittest
import requests
use_production = False
URL = 'https://sharecipe-backend.herokuapp.com' if use_production else 'http://127.0.0.1:5000'
class Account:
def __init__(self, username, password, user_id, access_token, refresh_token):
self.username = username
self.password = password
... |
#!/usr/bin/env python
#
# screenshot.py - The ScreenshotAction class.
#
# Author: <NAME> <<EMAIL>>
#
"""This module provides the :class:`ScreenshotAction` class, an
:class:`.Action` which can take screenshots of :class:`.CanvasPanel` and
:class:`.PlotPanel` views.
A few stand-alone functions are defined in this modul... |
import numpy as np
# import matplotlib.pyplot as plt
from scipy.optimize import minimize, brute
from functools import partial
from ktr_shuttle_ode import main_ode, ParamHolder
from kinase_estimation_inh import calc_rep_profile_at_steady_state
from scipy.integrate import odeint
def trapezoid_func(t, t1, t2, t3, t4, c1... |
#!/usr/bin/env python
# http://multivax.com/last_question.html
"""Unit and functional tests for getmac."""
import unittest
import getmac
import io
import re
from os import path
try:
from unittest import mock
except ImportError:
import mock
getmac.DEBUG = True
class MockHelper(object):
@classmethod
... |
# -*- coding: utf-8 -*-
"""
.. codeauthor:: <NAME> <<EMAIL>>
.. codeauthor:: <NAME> <<EMAIL>>
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
BN_EPS = 1e-05
BN_MOMENTUM = 0.9 # too large?
class DONetMultiscaleClassificationOrientationPose(nn.Module):
def __init__(self):
super(DONe... |
from custom_dataset import Multimodal_Data_Generator
from sentence_cnn import SentenceCNN
from tensorflow.keras.applications.vgg16 import VGG16
from tensorflow.keras.applications.resnet import ResNet50
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, TensorBoard, ReduceLROnPlateau
from tensorflow.... |
# -*- coding: utf-8 -*-
"""
Polygon data structure with preprocessor-related attributes and converters
"""
from schimpy import schism_yaml
from shapely.geometry.polygon import orient
from shapely.geometry import Polygon, Point
from osgeo.osr import SpatialReference
from osgeo.ogr import Open, CreateGeometryFromWkb, OFT... |
import os
import time
import json
import torch
import dill
import random
import pathlib
import evaluation
import numpy as np
import visualization as vis
from argument_parser import args
from model.online.online_trajectron import OnlineTrajectron
from model.model_registrar import ModelRegistrar
from environment import E... |
'''
python script to train a decoder
'''
import os, sys
import numpy as np
import torch
from torch import nn
from torch import optim
from torch.nn import functional as F
#-------------------------------------------------------
# params
#-------------------------------------------------------
name = sys.argv[1]
i... |
'''
Copyright (c) 2021, Oracle and/or its affiliates.
Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl.
'''
import json
import pprint
import requests
import idcsUtils
accessToken = ''
continueOnError = False
logger = None
pp = pprint.PrettyPrinter(inde... |
# Copyright 2015 Google 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 applicable law or a... |
from __future__ import annotations
import difflib
import re
from collections import Counter
from collections.abc import Callable
from dataclasses import dataclass
from pathlib import Path
from textwrap import indent
import uharfbuzz as hb
import yaml
from fontTools import unicodedata
from data import mongolian
from ... |
#!/usr/bin/env python
import os
import logging
import time
log = logging.getLogger(__name__)
def batch_dl2_to_sensitivity(
dl2_directory,
offset_gammas,
job_ids_from_dl1_dl2,
log_from_dl1_dl2,
source_env,
prod_id,
):
"""
Batches the dl2_to_sensitivity stage (`stages.script_dl2_to_se... |
import numpy as np
from scipy.optimize import linear_sum_assignment
from collections import defaultdict
from utils.utils import parse_camera_param
def global2pixel(person_coords, camera_id, camera_param_dict):
# det : X Y Z
world_coord = person_coords / camera_param_dict['discretization_factor'] + camera_param... |
import random
import pickle
import os
def print_board(slots, board_size):
st = " "
for i in range(board_size):
st = st + " " + str(i + 1)
print(st)
for row in range(board_size):
st = " "
if row == 0:
for col in range(board_size):
... |
"""
Convert plain text to format accepted by model (token idxs + special tokens).
"""
import warnings
import functools
from collections import namedtuple, Counter, OrderedDict
import spacy
import numpy as np
NLP = None
def get_spacy():
global NLP
if NLP is None:
NLP = spacy.load("en_core_web_sm", di... |
import pandas as pd
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import os
import re
SAMPLE_FILE = snakemake.input[0]
EXTRACTION_PROFILE = snakemake.input[1]
POPCLUSTERING_FILE = snakemake.input[2]
TARGETS_FILE = snakemake.input[3]
OUT_DIR = snak... |
import platform
import time
from uuid import uuid4
from django.conf import settings
from django.db import models
from django.db.models import F
from django.db.models import QuerySet
from morango.models import UUIDField
from morango.models.core import SyncSession
from .utils import LANDING_PAGE_LEARN
from .utils impor... |
import logging
import shutil
from copy import deepcopy
from typing import Dict, Any
import h5py
from Bio import SeqIO
from pandas import read_csv, DataFrame
from tqdm import tqdm
from bio_embeddings.embed import (
ProtTransAlbertBFDEmbedder,
ProtTransBertBFDEmbedder,
EmbedderInterface,
SeqVecEmbedder,... |
"""
core application module
initializes the Flask application, sets up the database, and provides access
to a few non-blueprinted routes.
"""
# ----------------------------------------------------------------------------
# IMPORTS
# standard library
import os
import json
import uuid
import logging
# depedencies
fro... |
import gzip
import shutil
import subprocess
from dataclasses import dataclass, field
from pathlib import Path
from typing import Dict, Iterator, List, Union, Tuple
import numpy as np
from Bio import SeqIO
from dataclasses_json import config, dataclass_json
@dataclass_json
@dataclass(frozen=True)
class PrimerMatch:
... |
#!/usr/bin/python
# -*- encoding: utf-8 -*-
'''
@Time : 2021/06/11 11:37:46
@Author : Camille
@Version : 1.0
'''
import os
import sys
sys.path.append(os.getcwd())
import pandas
import numpy
import json
import time
from scripts.windows.windows import BaseWindowsControl, ProcessMonitoring
from scripts.windows.... |
import graphene
from graphene_django.types import DjangoObjectType
from django.contrib.auth.models import User
from ..models import TaskManager, Task, Note, Release
from .types import TaskManagerType, TaskType, NoteType, ReleaseType
from .inputs import TaskManagerInput, TaskInput, NoteInput, ReleaseInput
from apps.core... |
from enum import Enum
import copy
from abc import ABC, abstractmethod
import numbers
from itertools import count
import numpy as np
import scipy
class Type(Enum):
Continuous = 'c'
Discrete = 'o'
class DuplicateHyperparameterError(Exception):
pass
class MissingHyperparameterError(Exception):
pass... |
import pandas as pd
from datetime import datetime
import math
import pathlib
import sys
import os
# Read data downloaded from the crawler
def read_data(path):
try:
data = pd.read_excel(path, engine="odf")
return data
except Exception as excep:
sys.stderr.write(
"'Não foi p... |
from __future__ import annotations
import numpy as np
import pandas as pd
from sklearn import datasets
from IMLearn.metrics import mean_square_error
from IMLearn.utils import split_train_test
from IMLearn.model_selection import cross_validate
from IMLearn.learners.regressors import PolynomialFitting, LinearRegression, ... |
import logging
import aiogram.utils.markdown as md
from aiogram import Bot, Dispatcher, executor, types
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters import Text
from aiogram.dispatcher.filters.state import State, StatesGroup
impor... |
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
import keras
from keras.preprocessing.sequence import pad_sequences
from keras.models import Sequential
from keras.layers import Dense, BatchNormalization, Flatten, Dropout
from keras.layers import LSTM, MaxPooling1D, Conv1D
from keras import re... |
import os
import sys
import tempfile
from glob import glob
from copy import deepcopy
from collections import defaultdict
from typing import List, NamedTuple, Union, Dict, Any, Set, Tuple
import click
import pandas as pd
import numpy as np
from tabulate import tabulate
from pycocotools.coco import COCO
from pycocotools... |
from __future__ import division
import torch
from torch import nn
import torch.nn.functional as F
from inverse_warp import inverse_warp2
import math
device = torch.device(
"cuda") if torch.cuda.is_available() else torch.device("cpu")
# compute photometric loss (with ssim) and geometry consistency loss
def comput... |
# pylint: skip-file
# type: ignore
# -*- coding: utf-8 -*-
#
# tests.analyses.milhdbk217f.models.test_connection.py is part of The
# RAMSTK Project
#
# All rights reserved.
# Copyright 2007 - 2017 <NAME> doyle.rowland <AT> reliaqual <DOT> com
"""Test class for the connection module."""
# Third Party Import... |
#Curve Fit Program
#This program creates trendlines from data points
#By: <NAME>
#
#########################################
# #
# Table of Contents #
# #
# Main Program............26 - 70 #
# Check Program............. |
#!/usr/bin/python
import json
import re
import traceback
from functools import wraps
from flask import request
from flask_login import current_user
from flask_socketio import disconnect
from flask_socketio import emit
from flask_socketio import join_room
import flask_together.models as models
import flas... |
##########################################################################################
# Copyright (c) MemSQL. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root for license information.
##########################################################################################
"... |
import asyncio
import itertools
import os
import random
import re
import subprocess
from collections import UserDict
from typing import Any, Iterable, List, Optional
HASH_BYTES = 32
def get_package_path():
"""
Returns ROOT_PATH s.t. $ROOT_PATH/starkware is the package folder.
"""
import starkware.pyt... |
import re
import yaml
import random
import logging
import mist.api.shell
from StringIO import StringIO
from mist.api.exceptions import BadRequestError
from mist.api.exceptions import ScriptFormatError
from mist.api.scripts.base import BaseScriptController
from yaml.parser import ParserError as YamlParserError
from yaml... |
# Copyright(c) 2016, The f-scLVM developers (<NAME>, <NAME>)
#
#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 la... |
import os.path
import torch
import numpy as np
import xlsxwriter
import torch.nn.functional as F
from torch.utils.data import DataLoader
import json
from action_labels import action_labels
# import sophisticated optimizer (loaded from GitHub)
from Ranger.ranger.ranger import Ranger
from network_model import *
import ... |
#!/usr/bin/env python
# Copyright 2017 <NAME> <EMAIL>
# Copyright 2017 <NAME> <EMAIL>
# Copyright 2017 <NAME> <EMAIL>
import sys
def _input():
#a1 = []
b1 = []
if len(sys.argv) == 1:
exit(2)
try:
for i in range(1,len(sys.argv)):
k = float(sys.argv[i])
if k < 0 :
exit(2)
except:
exit(2)
for li... |
import torch.nn as nn
import numpy as np
FAIRFACE_AE_N_UPSAMPLING_EXTRA = {1: 1, 2: 1, 3: 2, 4: 2, 5: 3, 6: 5, 7: 5}
class ResnetBlock(nn.Module):
"""Define a Resnet block"""
def __init__(self, dim, padding_type, norm_layer, use_dropout, use_bias):
"""Initialize the Resnet block
A r... |
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from models import *
from slack import WebClient
from flask import request
from datetime import datetime
from sqlalchemy import create_engine
app = Flask(__name__)
db_url = os.environ.get('DB_URL')
app.config['SQLALCHEMY_DATABASE_URI'] = db_url
... |
""" Callbacks that modify properties of the cytoscape graph.
"""
import datetime as dt
from typing import Any, Dict, List, Tuple
import dash
import google.protobuf.json_format as json_format
from dash.dependencies import ALL, Input, Output, State
from dash.exceptions import PreventUpdate
from graph_structures_pb2 im... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.core.exceptions import ValidationError
from django.db.models import Q
from django.forms import widgets
from django.forms.fields import ChoiceField
from django.forms.models import ModelForm
from django.utils.html import format_html
from django.... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import keras
from keras import backend as K
from keras.models import Input, Model
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Conv2DTranspose, concatenate
K.set_image_data_format('channels_first')
# From https://github.com/... |
import hashlib
import hmac
from secrets import token_bytes
from typing import Any, Union
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.asymmetric.ec import (
EllipticCurvePrivateKey,
EllipticCurvePublicKey,
)
from ... |
"""
<NAME>
orientation.py
Implement the keypoint gradient direction estimation technique based on the
Lecture 9 notes
/\
/**\
/****\ /\
/ \ /**\
/ /\ / \ /\ /\ /\ /\ /\/\/\ /\
/ / \ / \ / \/\/... |
import pdb
from datetime import datetime
import pytz
import pandas as pd
from shapely.geometry import LineString, Point
from shapely import wkb
import psycopg2
from psycopg2.extras import execute_values
from geoalchemy2.shape import from_shape
class PostgresInterface(object):
def __init__(self, dbname, table_name... |
import argparse
import ast
import itertools
import sys
import tokenize
from typing import Tuple, Iterable, Union, List, cast
import flake8.options.manager
ComprehensionType = Union[
ast.ListComp, ast.SetComp, ast.DictComp, ast.GeneratorExp
]
DEFAULT_SELECT = [
"C2000",
"C2001",
"C2002",
"C2020",
... |
# Exercise - 5
from emoji import emojize # pip install emoji
import random
from time import sleep
import shutil
from simple_colors import * # pip install simple_colors
def intro():
"""
Function to print the basic introduction about te game
"""
columns = shutil.get_terminal_size().columns
print... |
from collections import defaultdict
import glob
import os
import pickle
import re
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
from common.utils import METHOD_NAME, get_latest_folder, load_compressed_pickle, mysavefig
from games.maze.maze_game import MazeGame
from games.maze.maze_level i... |
from nerblackbox.modules.ner_training.data_preprocessing.tools.bert_dataset import (
BertDataset,
)
from nerblackbox.modules.ner_training.data_preprocessing.tools.csv_reader import (
CsvReader,
)
from nerblackbox.modules.ner_training.data_preprocessing.tools.input_example import (
InputExample,
)
from nerbl... |
"""
Convert COARDS time specification to a datetime object.
"""
from datetime import datetime, timedelta
import re
import warnings
EPOCH = datetime(1970, 1, 1)
# constants in seconds
SECOND = 1.0
MINUTE = 60.0
HOUR = 3.6e3
DAY = 8.64e4
SHAKE = 1e-8
SIDEREAL_DAY = 8.616409e4
SIDEREAL_HOUR = 3.590170e3
SIDEREAL_MIN... |
import numpy as np
def binary_repr(x):
return list(reversed([int(e) for e in np.binary_repr(x)]))
class Reduction1:
def __init__(self, modulus):
self.p = modulus
# Next power of 2
self.k = p.bit_length()
self.table = {}
for l in range(self.k, self.k*2):
sel... |
# pylint: disable=superfluous-parens, misplaced-comparison-constant
import math
import operator
import pytest
from capacity import MiB, byte, GiB, KiB, Capacity, bit, from_string, MB, GB, PiB, __version__
from numbers import Integral
from operator import truediv
from .utils import assert_value_error
def test_version... |
# EMACS settings: -*- tab-width: 2; indent-tabs-mode: t; python-indent-offset: 2 -*-
# vim: tabstop=2:shiftwidth=2:noexpandtab
# kate: tab-width 2; replace-tabs off; indent-width 2;
#
# ==============================================================================
# Authors: <NAME>
#
# Python Class: Base c... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""InriaAerialImageLabeling datamodule."""
from typing import Any, Dict, List, Optional, Tuple, Union, cast
import kornia.augmentation as K
import pytorch_lightning as pl
import torch
import torchvision.transforms as T
from... |
#!/usr/bin/env python3
#
# add-orcid-identifiers-csv.py 1.0.2
#
# Copyright 2021 <NAME>.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Author: <NAME> <<EMAIL>>
import json
import base64
import pathlib
import requests
import dataclasses
from datetime import datetime
from typing import Optional, Iterator, Iterable, Any, Dict, Callable, Type, Set
#######################################################... |
"""json_validation.py - provides validation functions and decorators
for those types that can occur in a
JSON-dataset, in particular TypedDicts.
Copyright 2021 by <NAME> (<EMAIL>)
Bavarian Academy of Sciences an Humanities (badw.de)
Licensed under the A... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
A library to get index of refraction (delta) or attenuation length.
Author: <NAME> (BNL)
2016
"""
import json
import math
import os
from bnlcrl import visualize as vis
from bnlcrl.utils import convert_types, defaults_file, read_json
parms = defaults_file(suffix='delta')... |
from shutil import copytree, move
from tempfile import TemporaryDirectory
from pathlib import Path
from unittest import skip
from capanno_utils.repo_config import tools_dir_name
from tests.test_base import TestBase
from capanno_utils.add_content import main as add_content_main
from capanno_utils.helpers.get_paths impo... |
""" Class for emission line systems
"""
from __future__ import print_function, absolute_import, division, unicode_literals
# Python 2 & 3 compatibility
try:
basestring
except NameError:
basestring = str
import numpy as np
import pdb
import warnings
from abc import ABCMeta
from astropy import units as u
from... |
"""
AUTHOR: <NAME>
CONTACT: <EMAIL>
NOTE:
This library implements the convolutional classifier described in the paper
"Seq2Seq RNN based Gait Anomaly Detection".
Please refer to the paper for further details.
WARNING:
If this is the first time you run this bundle, this file MUST be run after running
bidirectio... |
# Copyright (c) 2013 Rackspace, 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 wr... |
import os
import sys
sys.path[0] = os.path.join(
os.path.dirname("__file__"), os.path.pardir, os.path.pardir)
import argparse
import functools
from functools import partial
import numpy as np
import paddle
import paddle.nn as nn
from paddle.io import Dataset, BatchSampler, DataLoader
from paddle.metric import Metr... |
# coding: utf-8
# In[13]:
import helper
import numpy as np
from distutils.version import LooseVersion
import warnings
import tensorflow as tf
from tensorflow.contrib import seq2seq
# In[14]:
int_text, vocab_to_int, int_to_vocab, token_dict = helper.load_preprocess()
# 建立NN网络
# In[15]:
# Check TensorFlo... |
import numpy as np
import matplotlib
import os
import re
import matplotlib.pyplot as plt
import argparse
from preprocessing.util import lidar_to_topview, get_max_elevation, world_to_relative
parser = argparse.ArgumentParser(description='Save a topview/plot with past, predicted, and future ground-truth path.')
parser.a... |
import numpy as np
from heapq import nlargest
def heuralign(alphabet, substitution_matrix, seq1, seq2):
# defining parameters
ktup = 2 # length of matches
cutoff_score = -3 # cutoff score when scoring diagonals
width = 29 # width of band for banded DP
n = 3 # number of diagonals to run banded DP on
# get t... |
import constants
from error import Error
import properties
import utilities
ArgCounter = 0
OptCounter = 0
StartDefinition = constants.DefaultStartDefinition
EndDefinition = constants.DefaultEndDefinition
DefinitionSeparator = constants.DefaultDefinitionSeparator
class ParserResult:
def __init__(self, text, args, ... |
#! /usr/bin/env python
"""
Look for compositional + taxonomic oddities in an LCA database.
"""
import sourmash
import sys
from collections import defaultdict
import argparse
import csv
from sourmash.logging import error, debug, set_quiet, notify
from sourmash.lca import lca_utils
def make_lca_counts(dblist, lowest_r... |
import session
import neurotolge
import enginespecs
import memsource
import html
from datetime import datetime
from flask import request
langDesc = { 'et': 'eesti', 'lv': 'läti', 'lt': 'leedu', 'ru_ru': 'vene', 'ru': 'vene', 'de': 'saksa', 'fi': 'soome', 'en': 'inglise' }
shortenLang = { 'est': 'et', 'eng': 'en', 'l... |
"""
采用 BERT + BILSTM + CRF 网络进行处理
"""
import json
import jieba
from django.db.models import Q
from algo.model.model import CustomModel
from algo.model.model_config import BertBilstmCrfConfig
from keras.models import Model
from keras.layers import Bidirectional, LSTM, Dense, Dropout
from keras.optimizers import Adam
f... |
import gc
import math
import multiprocessing
import tempfile
from importlib.util import find_spec
from os.path import join
from typing import Optional
import lightgbm
import numpy
from lightgbm import Booster, record_evaluation
from aydin.regression.base import RegressorBase
from aydin.regression.gbm_utils.callbacks ... |
import typing
from dataclasses import dataclass
from aiothornode.types import ThorConstants, ThorMimir
from services.lib.texts import split_by_camel_case
from services.models.base import BaseModelMixin
@dataclass
class MimirEntry:
name: str
pretty_name: str
real_value: str
hard_coded_value: str
... |
#!/usr/bin/env python
"""
Copyright 2018 by <NAME> (alohawild) and <NAME>
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
Unle... |
"""
.. currentmodule:: feinsum.einsum
.. autoclass:: FusedEinsum
.. autoclass:: VeryLongAxis
.. autoclass:: EinsumAxisAccess
.. autoclass:: FreeAxis
.. autoclass:: SummationAxis
.. autoclass:: Argument
.. autoclass:: EinsumOperand
.. autoclass:: IntermediateResult
.. autoclass:: ContractionSchedule
.. autoclass:: Size... |
from functools import partial
import time
import os
import sys
import threading
import resotolib.proc
from typing import List, Dict
from .config import add_config
from resotolib.config import Config
from resotolib.logger import log, setup_logger, add_args as logging_add_args
from resotolib.jwt import add_args as jwt_ad... |
import time
import os
import psycopg2
import csv
import pandas as pd
import re
import tweepy
import json
from datetime import timedelta
from datetime import datetime
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
from collections import defaultdict
def twitter_str_to_dt(dt_str):
retur... |
#! /usr/bin/env python3
"""
Restore sites from xxLINK tape
Author: <NAME>
Example command line:
sudo python3 ~/kb/xxLINK-resources/scripts/restore-sites.py /home/johan/kb/xxLINK/tapes-DDS/2/file000001 /home/johan/kb/xxLINK/siteData-DDS/2
NOTE: running as sudo is needed bc of permissions set in source data.
"""
i... |
#!/usr/bin/env python
"""
===========
%(PROG)s
===========
----------------------------------------------------
Filter input values based upon user-defined function
----------------------------------------------------
:Author: <EMAIL>
:Date: 2013-03-15
:Copyright: TradeLink LLC 2013
:Version: 0.1
:Manual section: 1
... |
##########################################################
# detect_lanes.py
#
# SPDX-FileCopyrightText: Copyright 2021 <NAME>
#
# SPDX-License-Identifier: MIT
#
# Lane detection on video files
#
# ########################################################
#
# Import libraries
import cv2
#
import numpy as np
import os
... |
#!/usr/bin/python2.5
# -*- coding: utf-8 -*-
#
# Copyright 2009 Google 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 requir... |
"""
This script checks a scenario for v2.29.0 format and migrates the input tables it to the v2.31.1 format.
NOTE: You'll still need to run the archetypes-mapper after this script has run.
"""
import os
import cea
import pandas as pd
import collections
import cea.config
import cea.inputlocator
from cea.utilities... |
#
# Functions to manage the secrets in AWS Secrets Manager
#
from botocore.exceptions import ClientError
import cgi
import boto3
import settings
import json
import datetime
import miscFunctions
import logFunctions
import slackFunctions
import urllib
import s3Functions
requestContext = {}
#
# AWS Functions
#
session... |
import pickle
import pandas as pd
import re
import nltk
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
import numpy as np
import bcolz
import unicodedata
import torch
import torch.nn as nn
import torch.nn.functional as F
import time
import torch.optim as optim
import matplotlib.pyplot as plt
... |
import json
import os
from os.path import join, isdir
from os import mkdir, makedirs
import cv2
import numpy as np
import re
def tryint(s):
try:
return int(s)
except:
return s
def alphanum_key(s):
""" Turn a string into a list of string and number chunks.
"z23a" -> ["z", 23, "a"] ... |
"""
@brief PyTorch training code.
@author <NAME> (<EMAIL>)
@date July 2021
"""
import argparse
from decimal import Decimal
import json
from tqdm import tqdm
import numpy as np
import torch
from torch.optim import Adam
import torchnet as tnt
from src.network_architectures.custom_3dunet.unet import UNet3D
from src.e... |
"""Django views, mostly JSON APIs.
"""
from functools import wraps
from django.http import HttpResponse, JsonResponse, FileResponse, Http404
from django.shortcuts import get_object_or_404
from django.conf import settings
from rest_framework import viewsets
from . import models
from . import digests
from . import ocr
fr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.