text stringlengths 3.07k 22.1k |
|---|
import os
import shutil
import requests
import datetime
import glob
import time
import json
from codecs import encode, decode
import getopt, sys
import urllib.parse
# Command Line based globals
report_file = ""
data_folder = ""
wip_folder = ""
wip_remove_flag = False
kibanaEndpoint = ""
startDateGBL = ""
endDateGBL = ... |
from __future__ import print_function, absolute_import
import argparse
import os.path as osp
import random
import numpy as np
import sys
import collections
import copy
import time
from datetime import timedelta
import tabulate
from sklearn.cluster import DBSCAN, KMeans
from sklearn.preprocessing import normalize
impo... |
# (C) 2018-present <NAME>
# =============================[ Imports ]===========================
import codecs
import json
import math
import random
import numpy as np
from unidecode import unidecode
# ==========================[ Local Imports ]========================
from deepspell import featureset
# ==========... |
# -*- coding: utf-8 -*-
from copy import copy
from shapely.geometry import LineString, Point
import pandas as pd
from .trajectory import Trajectory
from .trajectory_collection import TrajectoryCollection
from .geometry_utils import measure_distance_geodesic, measure_distance_euclidean
class TrajectoryGeneralizer:
... |
'''Tests whether the functionality of the laboratory module is working properly.'''
import pytest
import lightlab.laboratory.state as labstate
from lightlab.laboratory.instruments import LocalHost, Host, Bench, Instrument, Keithley
from lightlab.laboratory.devices import Device
from lightlab.laboratory.experiments imp... |
# coding=utf-8
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available.
Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance ... |
"""
This module implements the logic to lazily load index files as
necessary. The classes in this module represent the indexes
provided by the main package API (e.g., :attr:`argopandas.prof`).
"""
import gzip
import io
from typing import Iterable, Union
import urllib.request
import numpy as np
import pandas as pd
impo... |
from exceptions import ConstraintViolationError
from solver_state import SolverState
from stats import StatsTracker
class Solver(object):
"""
Solves a Sudoku puzzle.
The algorithm is structured as follows:
1. Use the known cells to figure out what is possible in each row, column, 3x3 section, and... |
# The MIT License (MIT)
# Copyright (c) 2019 by the xcube development team and contributors
#
# 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... |
from uuid import uuid4
from django.db import models
from django.contrib.auth.models import AbstractUser
# from core_marketing.models import Rank
# from core_marketing.models import CoreLevelPlans
class CustomUser(AbstractUser):
user_id = models.UUIDField(default=uuid4, editable=False, primary_key=True)
phone ... |
""" This file is taken from https://github.com/aio-libs/aiohttp-session
for backward-compatibility, and then modified. It's going to be removed at some point.
"""
import json
import time
import uuid
from collections.abc import MutableMapping
from http.cookies import SimpleCookie
from typing import Optional, Awaitable... |
# taken from <NAME>'s amazing recharge model
# https://raw.githubusercontent.com/openforcefield/openff-recharge/5384eddb00e594c14c925b2d72956cfa3e51a874/openff/recharge/charges/bcc.py
# (ytz): we should just vendor this later.
import re
from openeye import oechem
from typing import Any, Dict, List, Callable, Type, Typ... |
import pytest
import pandas
import cellengine
from cellengine.utils.api_client.APIError import APIError
from cellengine.resources.attachment import Attachment
from cellengine.resources.compensation import Compensation
from cellengine.resources.experiment import Experiment
from cellengine.resources.fcs_file import FcsF... |
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
# Copyright 2017 <NAME>. 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/licen... |
"""TODO: generalize these functions to any ERC20"""
from __future__ import annotations
from typing_extensions import TypedDict
import typing
from ctc import directory
from ctc import evm
from ctc import spec
address_pools = {
'0xba12222222228d8ba445958a75a0704d566bf2c8': 'Balancer Vault',
'0xbaaa1f5dba42c... |
import asyncio
import re
from collections import namedtuple
from contextlib import suppress
import discord
from .message import Message
__all__ = [
'button',
'command',
'Session',
'EVERYONE',
]
class _EVERYONE:
"""Allows everyone to take part in a session"""
def __contains__(self, other):
... |
# -*- coding: utf-8 -*-
#
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights
# Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or i... |
from sys import stdin, argv
import unittest
track_previous = True
class weighted_digraph:
class __edge(object):
def __init__(self, to_node, weight):
self.to_node = to_node
self.weight = weight
class __node(object):
def __init__(self, value):
self.value = va... |
from collections import OrderedDict
from math import sqrt
from typing import List, Tuple
import cv2
import numpy as np
from coordinate.cameraCoordinate import CameraCoordinate
from vision.domain.iItemFinder import IItemFinder
from vision.domain.image import Image
from vision.domain.item.color import Color
from vision... |
'''
A module for the weighting methods.
'''
import sys
import numpy as np
import pandas as pd
from portfoliobuilder import api_utils
class Equal():
'''
A namespace for the equal weighting method.
'''
@staticmethod
def get_weights(symbols):
num_constituents = len(symbols)
stock_we... |
#!/usr/bin/python
import struct, array, fcntl
class struxx:
_fields = None
_format = None
_buffer = None
def __init__(self):
self.reset()
def __len__(self):
"""binary represntation length, for fields, use __dict__ or something"""
return struct.calcsize(self._format)
def __iter__(self):
re... |
import uuid
from django.db import models
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from django.conf import settings
from django.utils.html import mark_safe
from cuser.middleware import CuserMiddleware
COLORS_CHOICES = (
('info', _('Light blue')),
... |
# Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Convergence loop for a node-specific dataset agent.
In practice most of the code is generic, but a few bits assume this agent
is node-specific.
The convergence agent runs a loop that attempts to converge the local
state with the desired configuration a... |
'''
Generate serialized TF records
usage: python prepare_data.py
'''
import os
import argparse
import json
import numpy as np
import tensorflow as tf
import argparse
import logging
from model.utils import save_dict_to_json
# change RAW_RANK_DATA and TF_RANK_DATA accordingly
# for example the full path for '../../lea... |
'''
This module contains implementations of Scott's and Fleiss' Pi, adapted in
[FournierInkpen2012]_ for segmentation (in as similar a manner as [Hearst1997]_)
using the formulation of Kappa provided in [ArtsteinPoesio2008]_.
Pi's general form could be described, as it is in [ArtsteinPoesio2008]_, in
terms of actual ... |
from marshmallow import EXCLUDE, Schema, fields, validate
"""
This class consolidates schemas of bpm operations.
__author__ = "<EMAIL>"
"""
class FOIMinistryRequestWrapperSchema(Schema):
class Meta: # pylint: disable=too-few-public-methods
"""Exclude unknown fields in the deserialized output."""
... |
# Benchmark classifiers
import argparse
import logging
import matplotlib.pyplot as plt
import numpy as np
import os
import pandas as pd
import random
import tablib
from sklearn import metrics
from sklearn.ensemble import AdaBoostClassifier, BaggingClassifier, GradientBoostingClassifier, RandomForestClassifier
from sk... |
import argparse
import logging
import asyncio
import socket
import yaml
import sys
import re
import ssl
import pkgutil
import ipaddress
from datetime import datetime, timezone
# python3 -m pip dnspython
import dns.rcode
import dns.rdatatype
import dns.message
# wget https://raw.githubusercontent.com/dnstap/dnstap.pb... |
import argparse
import numpy as np
import pandas as pd
import torch
import torch.nn.functional as F
data_len = 470 #260
def get_common_args():
parser = argparse.ArgumentParser()
# learning params
parser.add_argument('--dev', action='store_true', help='dev')
parser.add_argument('--dev_size', type=int,... |
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------
# Distributed coordinated storage
# ----------------------------------------------------------------------
# Copyright (C) 2007-2017 The NOC Project
# See LICENSE for details
# ----------------------------------------------... |
import boto3
import zipfile
import os
from tqdm import tqdm
import copy
import json
import botocore.exceptions
import io
from botocore.exceptions import ClientError
from PyPDF2 import PdfFileReader
from .automl import AWS_ACC_KEY_ID, AWS_SEC_ACC_KEY, AWS_REGION_NAME
client_s3 = boto3.client('s3',
aws_access_key... |
import logging
import sys, json
base_dir = "/usr/local/fworch"
importer_base_dir = base_dir + '/importer'
sys.path.append(importer_base_dir)
import common, fwcommon, parse_rule
def create_section_header(section_name, layer_name, import_id, rule_uid, rule_num, section_header_uids, parent_uid):
# only do this once!... |
#!/usr/bin/python3
"""
# **********************************************************************************
# Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved.
# [openeuler-jenkins] is licensed under the Mulan PSL v1.
# You can use this software according to the terms and conditions of the Mul... |
import logging
import itertools
from pathlib import Path
import sys
from definitions import ROOT_DIR
from project_code.classes import Node, Branch, BranchTypeEnum
def remove_branches_with_loop_elements(branches, nodes):
for branch in branches:
if branch.name_from == branch.name_to:
branch.r... |
"""Perform GPR Active Learning where one threads continually re-prioritizes a list of
simulations to run and a second thread sebmits """
from colmena.thinker import BaseThinker, agent
from colmena.task_server import ParslTaskServer
from colmena.redis.queue import ClientQueues, make_queue_pairs
from sklearn.gaussian_p... |
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
import datetime
import sys
from django.http import HttpResponse
from django.test import signals, TestCase
from django.test.client import RequestFactory
from django.template import RequestContext
from django.core.urlresolvers import rever... |
import os
import sys
import copy
import shutil
import tarfile
import contextlib
import importlib
from collections import OrderedDict
from pylibimp import original_system, import_module
from pylibimport.utils import get_name_version
from pylibimport.run_pip import default_wait_func, pip_main
__all__ = ['InstallError'... |
import adventurelib_legacy.util as autil
from adventurelib_legacy.classes import PlayerCharacter, Entity
def tryNoticeAll(entities, enemies, player, isPlayerFriendly=False):
obliviousEntities = [entity for entity in entities if isinstance(entity, Entity) and not entity.IsDead and entity.Target is None]
validEn... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Floor creator. Orchestrates the creation of drillholes, blockmodels
# and geological shapes.
from collections import defaultdict
from src.geometry import *
from src.objects import *
import concurrent.futures
import numpy as np
import random
import math
import sys
clas... |
import numpy as np
from numpy.linalg import inv
import sys
# -- Solve your LP problems with this simple code!!! -----
# -- Your LP must be in the following format: ------------
# -- Maximize/Minimize c^T x -----------------------------
# -- subject to Ax <= b ----------------------------------
# -- Modify if you want ... |
import xml.etree.ElementTree as ET
# make sure to use a python implementation of ET.Element
if hasattr(ET, '_Element_Py'):
XMLElement = ET._Element_Py
else:
XMLElement = ET.Element
def _count(values):
if type(values) == list or type(values) == tuple:
return len(values)
elif values is None:
... |
"""
:Author: <NAME> <<EMAIL>>
This modules provides function for bootstrapping a regression method.
"""
import multiprocessing as mp
from collections import namedtuple
import numpy as np
from numpy.random import randint
import bootstrap_workers
import nonparam_regression
import sharedmem
from compat import irange, i... |
import os
from . import GlobalConstants as GC
from . import configuration as cf
from . import Action, Engine, Utility
class Affinity(object):
def __init__(self, icon_index, name, attack, defense, accuracy, avoid, crit, dodge, attackspeed):
self.icon = Engine.subsurface(GC.ITEMDICT['Affinity'], (0,... |
import argparse
import collections
import numpy as np
import pandas as pd
# from sklearn import metrics
# from sklearn.preprocessing import label_binarize
def get_y_true():
# """
# Read file to obtain y_true.
# All of five tasks of Sentihood use the test set of task-BERT-pair-NLI-M to get true... |
#/***********************************************************************
# * Licensed Materials - Property of IBM
# *
# * IBM SPSS Products: Statistics Common
# *
# * (C) Copyright IBM Corp. 1989, 2020
# *
# * US Government Users Restricted Rights - Use, duplication or disclosure
# * restricted by GSA ADP Schedule C... |
"""
This module contains functions and classes used to parse and
represent data stored in the C4.5 format.
An Example is a list of Features that complies to some
Schema, which describes feature types and values. An
ExampleSet is a list of Examples that all comply to the same
Schema.
ExampleSets, Examples, and Schemas... |
"""
<NAME>
Columbia University
Artificial Intelligence Course EDX
"""
import sys
import time
import copy
import numpy as np
import queue as Q
import pandas as pd
import itertools
from string import ascii_letters
class csp(object):
def __init__(self, sudoku, sudoku_board):
self.sudoku = sudoku
sel... |
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 2 20:33:55 2014
@author: isaac
"""
import numpy as np
from scipy.interpolate import interp1d
from scipy.optimize import newton
def calc_epsilon(m, L, S):
"""Non-dimensional gliding parameter, epsilon.
Parameters
----------
m : float
mass in kg... |
import xml.etree.ElementTree as ET
import re
from io import StringIO
from collecteur import debug as DBG
from collecteur import dico as DICO
from collecteur import utilities as UTIL
from collecteur import frequency as FREQ
from collecteur import precalcul as PC
from collecteur.automata import *
from xml.dom import mini... |
#!/usr/bin/env python
from generator.actions import Actions, Variable
import random
import string
import struct
import sys
from collections import OrderedDict
CURRENT_VER = 103
MAX_KEY_LEN = 128
MAX_TEXT_LEN = 1024
MAX_DATA_LEN = 512
OP_QUEUE = 0
OP_PROCESS = 1
OP_QUIT = 2
LMT_HELO = 0x4f4c4548
LMT_KEYX = 0x5859454... |
"""
The main training file
"""
import os
import argparse
from pathlib import Path
from datetime import datetime
import pandas as pd
import numpy as np
from tqdm.auto import tqdm
import shutil as sh
import fileinput
def parse_start_arguments():
parser = argparse.ArgumentParser(description='Wheat Det... |
import re
from typing import Optional
import discord
from discord.ext import commands
from utils import checks, converters, errors
async def user_can_edit_thread(bot, user, channel):
role = channel.guild.get_role((await bot.database.get_settings(channel.guild.id))["trustee_role"])
thread_author_id ... |
#!/usr/bin/env python
import os
from collections import defaultdict
import pandas as pd
import click
import numpy as np
from scipy.signal import argrelmax
from HotGauge.thermal.ICE import load_3DICE_grid_file
from HotGauge.utils.io import open_file_or_stdout
##########################################################... |
# -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
# File: axis.py
# Author: <NAME>
# Licence: GPL 3.0
# Description: Axis creation related classes and implementation
from enum import Enum
from mathutils import Vector
import bpy
import math
from data_vis.utils.data_utils import float_range
CATEGORICAL_AXIS_DEFAULT_TICKS = 10
class AxisDir(Enum):
X = 0
Y = ... |
import numpy as np
def coin_excange(money, coins):
dp = [0]*(money +10)
for i in range(1, money+3):
x = [dp[i-c] +1 for c in coins if i-c>=0]
dp[i] = min(x) if len(x)>0 else np.inf
return dp[money]
def manhaten_tourist(down, right, n, m):
dp = np.zeros((n+10,m+10))
for i i... |
from __future__ import unicode_literals
from django.contrib import messages
from django.db import models
from django.shortcuts import redirect, render
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from modelcluster.contrib.taggit import ClusterTaggableManager
from modelcluster.fields import... |
from matplotlib import pyplot
from modules.IterativeHistogram import IterativeHistogram
from modules.Fastx import *
import argparse
import mmap
import os
def plot_length_distribution(histogram, axes, label, weighted=False, normalize=False):
if normalize:
frequencies = histogram.get_normalized_histogram()... |
import string
formatter = string.Formatter()
class Dummy(object):
def __getattr__(self, attr):
return self
def __getitem__(self, item):
return self
dummy = Dummy()
class Template(object):
"""Abstract base class for lazy string templates.
A template is a symbolic string with inte... |
import os, sys
from flask import request, render_template
from werkzeug.utils import secure_filename
import joblib
import numpy as np
from PIL import Image
from torch import load
from torchvision import transforms
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
sys.path.append(os.path.abspath(os.path.jo... |
import bpy
from bpy.props import *
from ...nodes.BASE.node_base import RenderNodeBase
from collections import defaultdict
def update_node(self, context):
if self.engine == 'CYCLES':
self.create_input('RenderNodeSocketFloat', 'preview_adaptive_threshold', 'Viewport Noise Threshold',
... |
import time
import logging
import numpy as np
from core.decorator import config
from utility.utils import batch_dicts, moments, standardize
from replay.utils import init_buffer, print_buffer
logger = logging.getLogger(__name__)
def compute_nae(reward, discount, value, last_value,
gamma, mask=None,... |
import src.mapping.joy_mapping_orchestration
import src.mapping.composite.actions
import src.mapping.composite.axis
import src.mapping.composite.commands
import src.utils.filters
from src.utils.utilities import Bunch, tuple_it_if_needed
from src.helpers.freepie_helper import KeyExtended
from src.helpers.... |
# Copyright (c) Facebook, Inc. and its affiliates.
# Original code from SPIN: https://github.com/nkolot/SPIN
"""
This file contains functions that are used to perform data augmentation.
"""
import sys
import torch
import numpy as np
import scipy.misc
import cv2
from torchvision.transforms import Normalize
# For conv... |
import cv2
import mahotas
# from skimage import exposure
from skimage import feature
# from imutils import auto_canny
import numpy as np
import math
import wget
from scipy.spatial import distance
from ..DenseNet import densenet
# from DenseNet import densenet
from keras.models import Model, Sequential, load_model
from ... |
"""Processing of OpenStreetMap data.
The module provides functions to work with .osm.pbf files.
`Osmium <https://osmcode.org/osmium-tool/>`_ is required for most of them.
"""
import os
from subprocess import run, PIPE, DEVNULL
import tempfile
import functools
from loguru import logger
import numpy as np
import raste... |
import asyncio
import collections
import concurrent
import contextlib
import copy
import http.client
import json
import random
import sys
import time
import tornado.web
import tornado.httpclient
import tornado.httpserver
import tornado.netutil
import login
# Reply to wait proxies at least this often, even if we have ... |
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 16 13:41:31 2020
@author: <NAME>
"""
from tkinter import *
from tkinter.ttk import *
from tkinter.font import *
from data import *
from SysBase import *
from UIBase import *
from threading import Timer
import os
from FrmAbout import FrmAbout
import pkg_resources
class K... |
#Copyright (C) 2013 by <NAME>
#
#Released under the MIT license, see LICENSE.txt
'''Compute recombination probabilities
E.g: for each sample repertoire, compute P(V), P(J), P(D, J),
P(delV|V), P(delJ|J), P(del5, del3|D), P(insVD), P(x_i|x_i-1),
P(insDJ), P(y_j|y_j+1)
Compute the median of a subset of samples etc...
''... |
from .classes import *
import numpy as np
def _parseRelations(relations, network):
POI_relation_list = []
for osm_relation in relations:
relation = Relation()
relation.osm_relation_id = str(osm_relation.id)
for member_id, member_type, member_role in osm_relation.members:
... |
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 2 11:41:22 2018
@author: <NAME>
"""
from PIL import Image
import os
import shutil
import cv2
import csv
# ============================================================================
Model = "#6-NFS_4c_5000s1e"
# ======================================... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class Conv2D(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, same_padding=False, stride=1, relu=True, bn=False):
super(Conv2D, self).__init__()
padding = int((kernel_size - 1) / 2) if same_padding else 0
... |
# -*- coding: utf-8 -*-
"""
A pure implementation of the Monte Carlo Tree Search (MCTS)
@author: <NAME>
"""
import numpy as np
import copy
from operator import itemgetter
import logging, time, random
_logger = logging.getLogger(__name__) # 目的是得到当前文件名
def rollout_policy_fn(board):
"""a coarse, fast version... |
# #START_LICENSE###########################################################
#
#
# This file is part of the Environment for Tree Exploration program
# (ETE). http://etetoolkit.org
#
# ETE is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# t... |
# code inspired from: https://keras.io/examples/generative/vae/
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from keras.callbacks import EarlyStopping
from keras.callbacks import ModelCheckpoint
import os
import pandas as pd
from collections impo... |
# shadow - De <NAME>
import resource
try:
import gdb
except ImportError:
raise Exception('[shadow] gdb_engine is only usable from within gdb')
# cache
cache_dword_size = None
cache_page_size = None
cache_int_size = None
cache_offsets = {}
cache_values= {}
cache_sizes = {}
def to_int(val):
sval = str(v... |
# -*- coding: utf-8 -*-
from bstruct import *
#
# Structure definitions
#
class TicksRaw(BStruct):
_endianness = "<"
_fields = [
("symbol", "12s", pretty_print_string),
("time", "I", pretty_print_time),
("bid", "d"),
("ask", "d"),
("counter", "I"),
("unknown", "I... |
import sqlite3
import argparse
import utils
import shutil
import os
from output_validator import *
def print_local_table(filename):
conn = sqlite3.connect(filename)
c = conn.cursor()
results = c.execute("SELECT * FROM models ORDER BY input_file").fetchall()
optimal = c.execute("SELECT * FR... |
import sys
import itertools
import pygame
from pygame.locals import *
from pykinect import nui
import time
import threading
import thread
import pygame.color
from pykinect import nui
from pykinect.nui import JointId
from pykinect.nui import SkeletonTrackingState
from pykinect.nui import RuntimeOptions
from pykinect.nu... |
import json
import codecs
import logging
import tenet.settings as settings
from bitarray import bitarray
from Crypto.Cipher import PKCS1_v1_5, PKCS1_OAEP
from Crypto.Hash import SHA
from Crypto.Cipher import Blowfish
from Crypto import Random
from struct import pack
from tenet.hash import bloom_hash
from tenet.uti... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# File: sample_questions_mgn.py
# Author: anon
# Email: <EMAIL>
# Created on: 2020-05-19
#
# This file is part of MGN
# Distributed under terms of the MIT License
import os, sys, platform
import argparse
import h5py
import numpy as np
np.random.seed(42)
import random
ra... |
import hashlib
import re
import shutil
import sys
from datetime import datetime
from pathlib import Path
from tempfile import NamedTemporaryFile
from typing import Any, Dict, List, Optional
from fastapi import APIRouter, Body, Depends, File, HTTPException, UploadFile
from sqlalchemy import delete, update
from sqlalche... |
import re
pattern = re.compile(r'(\$\w+\$)')
operators = {
'>': lambda x, y: x > y,
'<': lambda x, y: x < y,
'>=': lambda x, y: x >= y,
'<=': lambda x, y: x <= y,
'==': lambda x, y: x == y,
'!=': lambda x, y: x != y
}
class AZMError(Exception):
def __init__(self, *args, **kwargs):
... |
import os
import cv2
import torch
import pydicom
import numpy as np
import pandas as pd
from PIL import Image
from torch.utils.data import Dataset
from albumentations import ShiftScaleRotate, Normalize, Resize, Compose
from albumentations.pytorch import ToTensor
from gloria.constants import *
class ImageBaseDataset(... |
"""
Defines ResourceSet objects that can be used to represent a set of resources.
"""
import operator
import functools
import itertools
from . import lookups, exceptions
class BaseResourceSet(object):
"""
Defines basic functionality for a ResourceSet object.
"""
def __init__(self, manager, resources... |
# encoding: utf-8
"""
@summary: this module contains classes for connecting model and view
@author: <NAME> <alsihad (at) zeropatience (dot) net>
Copyright (c) 2009, 2010 <NAME> alsihad (at) zeropatience (dot) net
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
ar... |
#!/usr/bin/python2.4
# encoding: utf-8
"""
help.py
Help functionality for the ddG database.
Created by <NAME> 2012.
Copyright (c) 2012 __UCSF__. All rights reserved.
"""
import sys
import re
from string import join
from kddg.api.dbi import StdCursor, ddGDatabase # FieldNames
from klab import colortext
import ddglib
fr... |
import os
os.system("python -m pip install -r requirements.txt")
import numpy as np
import pandas as pd
class ColorCodesGenerator:
"""
Generates rgb, hex and hsl color codes
"""
def __init__(self, n_colors):
"""
n_colors: an integer
The value should be <= 16777216 sinc... |
import subprocess
from os import system, remove
from tabulate import tabulate
def edges(n):
location = 0
edges = [[0,n-1]]
for i in range(n-1):
edges.append([location, location+1])
location += 1
return edges
def cut(state, edges):
cut = 0
for edge in edges:
cut += 1 if state[edge[0]] == state[edge[1]] el... |
import datetime
from django.conf import settings
from django.db import models
from django.db.models import Q
from django.utils.encoding import python_2_unicode_compatible
from colorful.fields import RGBColorField
@python_2_unicode_compatible
class Message(models.Model):
text = models.TextField(max_length=1000, ... |
# -*- coding: utf-8 -*-
# Copyright (c) 2021-2022 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... |
# Autoencoder examples
# Auther: ZWL
import torch
import torch.nn as nn
from torch.autograd import Variable
import torchvision.datasets as dataset
import time
import datetime
class Encoder(nn.Module):
def __init__(self, input_dim, layer_dims, bias=False,
activation='linear',
o... |
from .hic_exception import *
import numpy as np
from .utils import *
from abc import ABC, abstractmethod
from scipy.linalg import block_diag
from .interfaces import *
class BaseHicMatrix(ABC):
def __init__(self, the_array, res):
self._oe = False
self.mat = the_array
self.res = res
... |
# !/usr/bin/env python3
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
'''
Exclude operators that are unused/not required from build to reduce binary size.
'''
import argparse
import onnx
import op_registration_utils
import os
import shutil
import sys
import typing
from ... |
from collections import namedtuple
from django.core.exceptions import ImproperlyConfigured
from django.utils import six
import collections
from rest_framework.utils.serializer_helpers import BindingDict
from mongoengine.base.common import get_document
import mongoengine
from collections import OrderedDict
from rest_... |
from django.contrib.auth import login
from django.contrib.auth.decorators import login_required
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.template.loader import render_to_string
from weasyprint import HTML
from we... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# finpie - a simple library to download some financial data
# https://github.com/peterlacour/finpie
#
# Copyright (c) 2020 <NAME>
#
# Licensed under the MIT License
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and assoc... |
# ========================================================================
# Copyright (c) 2015 The University of Washington
#
# 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... |
# -*- coding: utf-8 -*-
import os
import xarray as xr
import numpy as np
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
import matplotlib.pyplot as plt
from ..utils import find_grid_spacing
def render_mask_as_3d_voxels(da_mask, ax=None, center_xy_pos=False, alpha=0.5):
if ax is None:
... |
# Copyright 2016, Ericsson AB
#
# 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 ag... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.