text stringlengths 3.07k 12.6k |
|---|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""blast.py
Module that interacts with BLAST+ for diagnostic primer prediction.
The module provides functions that generate BLASTN command lines,
tuned for screening primer sequences. This module does NOT run the
commands - that is handled by one of the schedulers (multi... |
import json
import logging
import os
import pickle
import sys
from typing import Optional, List, Tuple
import ase.formula
import ase.atoms
import numpy as np
import scipy.signal
import torch
from ase.formula import Formula
from ase import io
from ase.atoms import Atoms
from molgym.agents.base import AbstractActorCriti... |
# Copyright 2015 gRPC 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 writing... |
import re
from typing import List, Dict
import gensim
import gensim.corpora as corpora
import numpy as np
import pandas as pd
from gensim.models import CoherenceModel
from tqdm import tqdm
def topic_dictionary_2_dataframe(review_topic_dictionary):
"""
This method takes a topic dictionary as an input and outp... |
"""
Some basic tests for SEAWAT Henry create and run.
"""
import os
import numpy as np
import flopy
workspace = os.path.join('temp', 't026')
# make the directory if it does not exist
if not os.path.isdir(workspace):
os.makedirs(workspace)
seawat_exe = 'swt_v4'
isseawat = flopy.which(seawat_exe)
# Setup problem... |
import sys
import os
import math
import numpy as np
import pickle
import CellModeller
import subprocess
import string
import shutil
from CellModeller.Simulator import Simulator
import networkx
from reportlab.pdfgen.canvas import Canvas
from reportlab.lib import units
from reportlab.lib.colors import Color
from reportla... |
"""
Copyright (c) 2018 iCyP
Released under the MIT license
https://opensource.org/licenses/mit-license.php
"""
from .. import vrm_types
def bone(node) -> vrm_types.Node:
v_node = vrm_types.Node()
if "name" in node:
v_node.name = node["name"]
else:
v_node.name = "tmp"
v_node.position ... |
"""
Load centrality.
"""
# Copyright (C) 2004-2010 by
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# All rights reserved.
# BSD license.
__author__ = "\n".join(['<NAME> (<EMAIL>)',
'<NAME> (<EMAIL>)',
'<NAME> (<EMAIL>)'])
__... |
"""PyLabware driver for IDEX MX II series six-port sample injection valve."""
from typing import Optional, Union
import time
import serial
# Core imports
from ..controllers import AbstractDistributionValve, in_simulation_device_returns
from ..exceptions import (PLConnectionError,
PLDeviceCom... |
# 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)
import weakref
import numpy as np
from pymor.discretizers.builtin.grids.boundaryinfos import G... |
import logging
log = logging.getLogger(__name__)
import threading
import numpy as np
from atom.api import (Str, Float, Bool, observe, Property, Int, Typed,
Value)
from enaml.core.api import Declarative, d_
from psi.core.enaml.api import PSIContribution
from ..util import copy_declarative
from ... |
from django.shortcuts import render, redirect
from django.views.generic.list import ListView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.views.generic.detail import DetailView
from django.views.generic import TemplateView, View
from django.contrib.auth.mixins import LoginRequire... |
from enum import IntEnum
class Status:
"""
:attribute code: int (optional) default as ok
:attribute message: str (optional) current status message
"""
SUCCESS = 0
UNEXPECTED_ERROR = 1
CONNECT_FAILED = 2
PERMISSION_DENIED = 3
COLLECTION_NOT_EXISTS = 4
ILLEGAL_ARGUMENT = 5
... |
# -*- coding: utf-8 -*-
"""
Created on Tue May 17 15:50:25 2016
@author: hossam
"""
from pathlib import Path
import optimizers.PSO as pso
import optimizers.MVO as mvo
import optimizers.GWO as gwo
import optimizers.MFO as mfo
import optimizers.CS as cs
import optimizers.BAT as bat
import optimizers.WOA as woa
import op... |
# Stencil Benchmarks
#
# Copyright (c) 2017-2020, ETH Zurich and MeteoSwiss
# 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 no... |
import os
import sys
import ssl
import pprint
import socket
import urllib.parse
# Rename HTTPServer to _HTTPServer so as to avoid confusion with HTTPSServer.
from http.server import (HTTPServer as _HTTPServer,
SimpleHTTPRequestHandler, BaseHTTPRequestHandler)
from test import support
threading = support.import_mod... |
from salesforceSoapApi import SalesforceSoapAPI
from salesforceRestApi import SalesforceRestAPI
from version import Version
from httpClient import HTTPConnection
from httpClient import Requests
from urlResources import RestUrlResources, SoapUrlResources
import utils
class Salesforce(object):
def __init__(self, **... |
import pandas as pd
import numpy as np
import random
def one_hot(df):
"""
@param df pandas DataFrame
@param cols a list of columns to encode
@return a DataFrame with one-hot encoding
"""
dummies = pd.get_dummies(data['iso'], prefix='Continent', drop_first=False)
df = pd.concat([df, dummies... |
# LIBTBX_PRE_DISPATCHER_INCLUDE_SH export PHENIX_GUI_ENVIRONMENT=1
import pickle
import sys
import iotbx.phil
import dials.util.log
from dials.util.image_viewer.spotfinder_wrap import spot_wrapper
from dials.util.options import OptionParser, flatten_experiments, flatten_reflections
help_message = """
This program... |
from functools import partial
from fn.op import identity
default_cmp = (lambda a, b: -1 if (a < b) else 1)
class _MergeBased(object):
def __nonzero__(self):
return self.root is not None
def __bool__(self):
return self.__nonzero__()
def __iter__(self):
"""Extract elements one-... |
import pandas as pd
import numpy as np
# Loading libraries for modeling
from sklearn.naive_bayes import MultinomialNB
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics import confusion_matrix, recall_score
import time
import pickle
import argparse
import sys
import os
import cProfile,... |
# coding=utf-8
# Copyright 2022 The Google Research 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 applicab... |
#coding:utf-8
import pytest
import tempfile
import pathlib
from operator import le, itemgetter, methodcaller
import pandas as pd
import numpy as np
from bourbaki.iterutils import batched, filltail, check_empty_iter, peek, zipcall, do_all
from bourbaki.iterutils.classes import EqualChunks, EqualSlices
n = 10
test_arr =... |
import pika_wrapper
import trapum_pipeline_wrapper
from trapum_pipeline_wrapper import TrapumPipelineWrapper
import optparse
from sqlalchemy.pool import NullPool
import subprocess
import logging
import parseheader
import lxml
from pymongo import MongoClient
from xmljson import parker
import os
log = logging.getLogg... |
import sys
import numpy as np
import pandas as pd
import re
import pickle
import nltk
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
from nltk.corpus import stopwords
nltk.download(['punkt', 'wordnet', 'stopwords'])
from sklearn.model_selection import train_test_split, GridSearchCV
fr... |
# -*- coding: utf-8 -*-
from django import forms
from django.core.exceptions import ImproperlyConfigured
from django.forms.models import ModelForm
from django.utils.encoding import smart_text
from django.utils.translation import ugettext as _
from cms.api import create_page
from cms.constants import TEMPLATE_INHERITA... |
import sys
import os
import subprocess
import json
from collections import OrderedDict
class Aigents():
def __init__(self, study_path='study.json', opened_config= False):
if opened_config:
config = study_path
else:
with open(study_path) as json_file:
config... |
"""Module: barcode.ean
:Provided barcodes: EAN-14, EAN-13, EAN-8, JAN
"""
__docformat__ = "restructuredtext en"
from functools import reduce
from barcode.base import Barcode
from barcode.charsets import ean as _ean
from barcode.errors import (
IllegalCharacterError,
NumberOfDigitsError,
WrongCountryCodeE... |
# pylint: disable=W0613
import logging
from pyramid.path import DottedNameResolver
from sandglass.time.resource.utils import allow_request_methods
from .registry import register_resource
from .registry import RESOURCE_REGISTRY
from .utils import REQUEST_METHODS
LOG = logging.getLogger(__name__)
# Permission suffix... |
import base64
import hashlib
import importlib
import json
import logging
from urllib.parse import parse_qs
from urllib.parse import urlparse
from urllib.parse import urlsplit
from urllib.parse import urlunsplit
import uuid
from cryptography.fernet import Fernet
from cryptojwt import as_unicode
from cryptojwt.utils imp... |
import pika
import multiprocessing
import threading
import os
import signal
import sys
import json
import socket
from init_client import handle_config,rabbitmq_detail
key = '<KEY>'
handle_config(key)
from time import sleep
from connection import manage_connection
from database_management import manage_... |
# coding: utf-8
"""
This module implements utility functions to compute several geometric
properties.
"""
import numpy as np
__author__ = "<NAME>"
__copyright__ = "University of Pau and Pays Adour"
__email__ = "<EMAIL>"
__all__ = ["center_of_mass", "circum_center", "get_plane", "get_dihedral"]
def center_of_mass... |
import pandas as pd
import yaml
class Dict2Class(object):
def __init__(self, dvar, def_topvar):
if not isinstance(dvar, dict) or not dvar:
setattr(self, def_topvar, None)
return
for key in dvar:
if isinstance(dvar[key], list):
nested_dclass = []... |
import pytest
from tests.communication.test_CommBase import TestComm as base_class
class TestForkComm(base_class):
r"""Tests for ForkComm communication class."""
test_error_send = None
test_error_recv = None
test_work_comm = None
test_send_recv_raw = None
@pytest.fixture(scope="class", autou... |
# Copyright 2011 VMware, 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 a... |
"""
This is a hacky little attempt using the tools from the trigger creation script to identify a
good set of label strings. The idea is to train a linear classifier over the predict token and
then look at the most similar tokens.
"""
import argparse
import json
import logging
from pathlib import Path
import os
import ... |
# Copyright (c) 2020, NVIDIA CORPORATION.
import os
from glob import glob
from warnings import warn
from fsspec.utils import infer_compression
from dask import dataframe as dd
from dask.base import tokenize
from dask.dataframe.io.csv import make_reader
from dask.utils import apply, parse_bytes
import cudf
def rea... |
import os
import cv2
import time
import argparse
import torch
import numpy as np
from predict import InferYOLOv3
from utils.utils import xyxy2xywh
from deep_sort import DeepSort
from utils.utils_sort import COLORS_10, draw_bboxes
from sort.sort import *
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
class Detector(object... |
# Copyright 2019 Yelp 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, so... |
import json
import pathlib
import numpy as np
import pytest
from set_matching.datasets.iqon3000_dataset import FINBsDataset, FITBDataset, PopOneDataset, SplitDataset
def test_popone_dataset(data_dir):
if data_dir is None:
pytest.skip("there is no testdata.")
root = pathlib.Path(data_dir)
data = ... |
from hathor.graphviz import GraphvizVisualizer
from tests import unittest
from tests.simulation.base import SimulatorTestCase
from tests.utils import add_custom_tx, gen_new_tx
class BaseConsensusSimulatorTestCase(SimulatorTestCase):
def checkConflict(self, tx1, tx2):
meta1 = tx1.get_metadata()
met... |
from sqlalchemy import Column, SmallInteger, String, LargeBinary, Table, ForeignKey, Date, Float, Integer
from sqlalchemy.orm import relationship
from northwind_db_api.database import Base
class Category(Base):
__tablename__ = "categories"
category_id = Column(SmallInteger, primary_key=True, index=True)
... |
# Copyright 2016 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Allow creation of uart/console interface via stm32 usb endpoint."""
import errno
import exceptions
import os
import pty
import select
import sys
import ... |
"""
[Calculation of lower bound for the KL-divergence]
Created on Wd Jul 03 2019
Copyright (c) [2019] [<NAME>]
This software is released under the MIT License.
http://opensource.org/licenses/mit-license.php
"""
"""
URL of the preprint
https://arxiv.org/abs/1907.00288
"""
import numpy as np
impo... |
#!/usr/bin/env python3
"""
Remove those pesky AWS default VPCs.
Python Version: 3.7.3
Boto3 Version: 1.9.143
Botocore version: 1.12.154
"""
import sys
import boto3
from botocore.exceptions import ClientError
from multiprocessing.dummy import Pool as ThreadPool
import itertools
def delete_igw(ec2, vpc_id, dryrun=True)... |
# pylint: disable=unused-import
"""Loads a CWL document."""
import os
import uuid
import logging
import re
import urlparse
from schema_salad.ref_resolver import Loader
import schema_salad.validate as validate
from schema_salad.validate import ValidationException
import schema_salad.schema as schema
from avro.schema im... |
import os
import sys
import time
import six
import numpy as np
import math
import argparse
import paddle.fluid as fluid
import paddle
import time
import utils
import net
SEED = 102
def parse_args():
parser = argparse.ArgumentParser("gru4rec benchmark.")
parser.add_argument(
'--train_dir', type=str, de... |
#!/usr/bin/env python
usage = """
Usage:
$0 REPO-DIR FSFS-ID-WITH-BAD-OFFSET
-- Find the correct FSFS node-rev id, given one that is correct except for
its byte-offset part.
$0 REPO-DIR REV SIZE
-- Find a rep header that matches REV and SIZE.
Example:
Result of running 'svnadmin verify':
svnad... |
import numpy as np
import torch as th
import torch.nn as nn
import torch.nn.functional as F
Vis_REGISTER = {}
class SimpleConvNetwork(nn.Module):
def __init__(self, visual_dim):
super().__init__()
self.net = nn.Sequential(
nn.Conv2d(visual_dim[-1], 16, kernel_size=8, stride=4),
... |
import math
import numpy as np
import scipy
pi = math.pi
def int2bitarray(N,k):
"""
Changes array's base from int (base 10) to binary (base 2)
Parameters:
N: int N
k: Width of the binary array you would like to change N into. N must not be greater than 2^k - 1.
>> Examples: in... |
import inspect
import os
import re
import pylons
import paste.deploy.converters as converters
import webhelpers.html.tags
__all__ = ['toolkit']
class CkanVersionException(Exception):
''' Exception raised if required ckan version is not available. '''
pass
class _Toolkit(object):
'''This class is inten... |
#!/usr/bin/env python
#
# Copyright 2017, <NAME> <<EMAIL>>
#
# This file is part of HISAT 2.
#
# HISAT 2 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) ... |
# -*- coding: utf-8 -*-
# Copyright: (c) 2021, 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
from contextlib import contextmanager
from ansible_collections.community.... |
# See https://zulip.readthedocs.io/en/latest/subsystems/caching.html for docs
import datetime
import logging
from typing import Any, Callable, Dict, Iterable, List, Tuple
from django.conf import settings
from django.contrib.sessions.models import Session
from django.utils.timezone import now as timezone_now
# This fi... |
from argparse import ArgumentParser
import pytorch_lightning as pl
from transformers import (
AutoModelForTokenClassification,
AutoTokenizer,
AutoConfig,
)
from transformers.optimization import AdamW
from data import LMDataModule
from uuid import uuid4
import torch
import logging
from pathlib import P... |
#Credits code taken from here:
#https://github.com/scipy/scipy/blob/master/scipy/spatial/transform/rotation.pyx
import re
import numpy as np
import scipy.linalg
_AXIS_TO_IND = {'x': 0, 'y': 1, 'z': 2}
def _compose_quat(p, q):
product = np.empty((max(p.shape[0], q.shape[0]), 4))
product[:, 3] = p[:, 3] * q[:... |
#!/usr/bin/env python3
import os
import numpy as np
import cv2
import freenect
def pretty_depth(depth):
"""Converts depth into a 'nicer' format for display
This is abstracted to allow for experimentation with normalization
Args:
depth: A numpy array with 2 bytes per pixel
Returns:
A ... |
# _*_ coding: utf-8 _*_
import json
from fastrunner import models
from fastrunner.utils.parser import Format
from djcelery import models as celery_models
def get_counter(model, pk=None):
"""
统计相关表长度
"""
if pk:
return model.objects.filter(project__id=pk).count()
else:
return model.o... |
#!/usr/bin/env python
#############################################################################
##
# This file is part of Taurus
##
# http://taurus-scada.org
##
# Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain
##
# Taurus is free software: you can redistribute it and/or modify
# it under the terms of t... |
from get_java_methods import ChangedMethodsFinder
import json
import pandas as pd
from git import Repo, db
import tqdm
import os
class GitFeaturesExtractor:
def __init__(self, path_to_repo, path_to_reports):
self.commit_time = []
self.modified_time_diff = []
self.authors = []
self.... |
import json
import requests
from typing import Union
import uuid
from urllib.parse import urljoin
from .exceptions import SiteConfigurationError
STATUS_LIVE = 'live'
def get_cache_key_for_site(site_uuid: Union[str, uuid.UUID]):
"""
Get the cache key for a site.
"""
return 'site_config_client.backe... |
#!/usr/bin/env python
from datetime import datetime
import json
import os.path
import click
import markdown
from nltk.corpus import wordnet
from nltk.tokenize import word_tokenize
from nltk.stem import PorterStemmer
stemmer = PorterStemmer()
# http://www.nltk.org/howto/stem.html
STOP_WORDS = [
'the',
'a',
... |
import torch
from torch import nn
from torch.nn import functional as F
from ..util import mask_upper_triangular
class LatentEncoder(nn.Module):
def __init__(
self,
input_dim,
hidden_size=32,
latent_dim=32,
min_std=0.01,
dropout=0,
nhead=8,
num_laye... |
# -*- coding:utf-8 -*-
"""
Author:
<NAME>, <EMAIL>
Reference:
[1] <NAME>, <NAME>, <NAME>, et al. Operation-aware Neural Networks for User Response Prediction[J]. arXiv preprint arXiv:1904.12579, 2019. (https://arxiv.org/pdf/1904.12579)
"""
import itertools
import tensorflow as tf
from tensorflow.python.ker... |
import numpy as np
import pandas as pd
import gc
import time
import lightgbm as lgb
from sklearn.metrics import roc_auc_score, roc_curve
from sklearn.model_selection import KFold, StratifiedKFold
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
import base64
import os
from sklearn.preprocessing imp... |
from functools import partial
from keras.layers import Input, LeakyReLU, Add, UpSampling2D, Activation, SpatialDropout2D, Conv2D
from keras.engine import Model
from keras.optimizers import Adam
from unet3d.metrics import minh_dice_coef_metric
from unet3d.utils.model_utils import compile_model
from unet2d.model.blocks ... |
"""Abstract classes to be inherited by prototorch models."""
import pytorch_lightning as pl
import torch
import torchmetrics
from ..core.competitions import WTAC
from ..core.components import Components, LabeledComponents
from ..core.distances import euclidean_distance
from ..core.initializers import LabelsInitialize... |
"""Test support for already-defined UDFs in Postgres"""
import functools
import pytest
import ibis
import ibis.expr.datatypes as dt
from ibis.sql.postgres import existing_udf, udf
from ibis.sql.postgres.udf.api import PostgresUDFError
# mark test module as postgresql (for ability to easily exclude,
# e.g. in conda ... |
import torch as t
import torch.nn as nn
from torch.optim import SGD
from torch.nn.init import normal_
import numpy as np
import random as rd
import math
import matplotlib.pyplot as plt
from sklearn.neighbors import KNeighborsClassifier as KNN
def get_datas(c, R, num):
datas = []
for i in range(num):
ra... |
#!/usr/bin/python3
"""EnviroPhat and DisplayTron class to show various environment values.
This script when run will activate the Diplay-A-Tron with its
associated buttons which will enable it to show different
environment variables from the Envirophat itself and other attached
sensors. Such as MQ sensors and a CCS811... |
"""
This program scores the mutations of the contact residues of an aa sequence based on the prediction of Evolutron.
"""
from __future__ import print_function
import os
import random
import corebio
import lasagne
import numpy as np
import theano
import theano.tensor as ten
from weblogolib import *
import prep_v031 ... |
#!/usr/bin/env python
# Copyright (c) 2017, The MITRE Corporation
# For license information, see the LICENSE.txt file
from libtaxii.scripts import TaxiiScript
import libtaxii.messages_11 as tm11
from libtaxii.constants import *
class InboxClient11Script(TaxiiScript):
parser_description = 'The TAXII 1.1 Inbox Cli... |
from django.db import transaction
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect, Http404
from django.utils import timezone
from django.urls import reverse
from django.views.decorators.http import require_POST
from .algorithms import generate_matches_montecarlo, get_... |
# -*- coding: utf-8 -*-
import sys
import os
curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(curPath)[0]
sys.path.append(rootPath)
import itchat
import time
from itchat.content import *
from app import dataprocess
from app import gvariable as gl
from apscheduler.schedulers.background impor... |
# /usr/bin/env python3.5
# -*- mode: python -*-
# =============================================================================
# @@-COPYRIGHT-START-@@
#
# Copyright (c) 2019, Qualcomm Innovation Center, Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification,... |
#!/usr/bin/python
# 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
# di... |
import numpy as np
from numpy.random import randint
from tensorflow.keras import backend as K
from tensorflow.keras.datasets import fashion_mnist as fmnist
from tensorflow.keras.layers import *
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import Adam
from tqdm import tqdm
def pick_superv... |
import numpy as np
import tensorflow as tf
from keras.layers import Lambda,Input
import keras.backend as K
from decorator import decorator
class keras_Objective(object):
def __init__(self, objective_func, name="", description="",batch_n=1):
self.objective_func = objective_func
self.name = name
... |
from enum import Enum
import tensorflow as tf
from tensorflow.contrib import rnn
class Phase(Enum):
Train = 0
Validation = 1
Predict = 2
def rnn_hidden_layers(
config,
inputs,
seq_lens=None,
phase=Phase.Predict):
if config.BIDIRECTIONAL:
fcells = [rnn.GRUCell(... |
import pytest
import os.path
import numpy as np
from astropy.utils import find_current_module
from astropy.nddata import NDDataArray
from ..io import NDMapIO
from ..data import FileName, DataFile, DataFileList, NDLater
# Determine path to data in common to some of the tests below:
# Using get_pkg_data_filename() from ... |
"""end-of-year read books stats"""
from datetime import date
from uuid import uuid4
from django.contrib.auth.decorators import login_required
from django.db.models import Avg, Sum, Min, Case, When
from django.http import Http404
from django.shortcuts import redirect
from django.template.response import TemplateRespons... |
# MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
#
# Copyright (c) 2014-2020 Megvii Inc. All rights reserved.
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY ... |
import os
from time import strftime
from time import localtime
import mxnet as mx
from mxnet import ndarray as nd
import numpy as np
from lib.dataset.hm36 import JntName, HM_act_idx
def try_gpu():
"""If GPU is available, return mx.gpu(0); else return mx.cpu()"""
try:
ctx = mx.gpu()
_ = nd.arr... |
# Matrix, a simple programming language
# (c) 2022 <NAME>
# License: MIT, see License.md
# Version: 20220319110310
from re import compile, match, search
from sly import Lexer
from sly.lex import Token
class MatrixToken(Token):
def __init__(self) -> None:
super().__init__()
self.line = ""
... |
from __future__ import annotations
import abc
import enum
import typing
def add(mod: int, lhs: int, rhs: int) -> int:
assert 0 <= lhs < mod and 0 <= rhs < mod
res = lhs + rhs
if res >= mod:
res -= mod
return res
def neg(mod: int, x: int) -> int:
assert 0 <= x < mod
return mod - x
... |
# 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 ... |
import gym
import random
import numpy as np
import tensorflow as tf
from collections import deque
from utils.action import e_greedy, noisy_action
class DQN:
def __init__(self, input_size, output_size, l_rate=1e-1, name='main'):
self.input_size = input_size
self.output_size = output_size
se... |
import logging
import os
import re
from typing import Callable, Any, Union
import yaml
from .configurations import Configurations
logging.basicConfig(level='INFO')
logger = logging.getLogger(__name__)
class GetConfig(object):
"""
GetConfig decorator
"""
def __init__(self, cls_name: str, category: ... |
#
# query seasonal data:
# Input paramters: ObjectTypeCV,InstanceNameCV,AttributeNameCV
# return: df_Seasonal
import pandas as pd
from collections import OrderedDict
import csv
import os
def Seasonal_query(conn,multi_Seasonal):
total_df_Seasonal = []
for input_param in multi_Seasonal:
Seasonal_query=... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import argparse
import os
import sys
py3 = sys.version_info.major == 3
def warn(msg):
print('[powerline-bash] ', msg)
if py3:
def unicode(x):
return x
class Powerline:
symbols = {
'compatible': {
... |
import datetime
from flask import current_app, request, url_for
from itsdangerous import TimedSerializer
from werkzeug.security import generate_password_hash, check_password_hash
from beedare import db, login_manager
class Friend(db.Model):
__tablename__ = 'friends'
follower_id = db.Column(db.Integer, db.For... |
# 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.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
# Copyright 2021 magohole
#
# 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, so... |
import json
import matplotlib.pyplot as plt
import sys
import numpy as np
import copy
sys.path.append('../')
# importing
import helper
# Ignore NONE in list
import warnings
warnings.filterwarnings("ignore", category=RuntimeWarning)
FILE = "out.json"
PRINT_MATCHES = False
NOMINAL_S = 300
TOLERANCE_S = 1
HIST_BINS = ... |
#!/usr/bin/env python3
#
# Copyright (C) 2020 <NAME>
#
# MIT License details found under LICENSE
#
# Cross Platform and Multi Architecture Advanced Binary Emulation Framework
# Built on top of Unicorn emulator (www.unicorn-engine.org)
# After mapping /proc there will be a /dev/mtdblock11 missing and crash
# To fi... |
#!/usr/bin/env python3
import argparse
import datetime
import os
import pprint
import gym
import numpy as np
import torch
from torch.utils.tensorboard import SummaryWriter
from examples.offline.utils import load_buffer_d4rl
from tianshou.data import Collector
from tianshou.env import SubprocVectorEnv
from tianshou.p... |
#!/usr/bin/env python3
import os
import sys
import re
import errno
import urllib.request
import shutil
from glob import glob
from pathlib import Path
from shutil import copyfile
from setuptools import setup, find_packages
from os import path
from os.path import basename, dirname, join
from setuptools.command.develop i... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 8 15:13:22 2018
@author: Morteza
"""
import sys
import os
import subprocess
import re
def get_xref(pdf_file_path, mutool_path='D:\\afl\\mupdf-1.11-windows\\mutool.exe',
mutool_command=' show -e ', mutool_object_number=' x'):
# command line to get xref... |
from PyQt5.QtGui import qRgb, QColor
from idacyber import ColorFilter
from PyQt5.QtCore import Qt
from ida_idd import regval_t
from ida_dbg import (get_reg_val, get_ip_val, get_sp_val,
DBG_Hooks, is_step_trace_enabled, is_debugger_on,
get_process_state)
from ida_bytes import get_item_size
from ida_kern... |
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import torch
from torch.optim.optimizer import Optimizer
class LARS(Optimizer):
r"""Implements LARS algor... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.