text
stringlengths
3.07k
12.6k
# encoding: utf-8 # 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 # "Licens...
""" <NAME> Section AF CSE 163 Final Project This file includes functions to construct a new data frame from multiple files, build a regression decision tree, optimize the tree/max tree depth based on the mean squared errors of training and testing data vs. the max tree depth. This file answers my 3rd research problem. ...
import ctypes as ctypes from ctypes import wintypes as wintypes import os import sys kernel32 = ctypes.WinDLL('kernel32', use_last_error=True) advapi32 = ctypes.WinDLL('advapi32', use_last_error=True) ERROR_INVALID_FUNCTION = 0x0001 ERROR_FILE_NOT_FOUND = 0x0002 ERROR_PATH_NOT_FOUND = 0x0003 ERROR_ACCESS_DENI...
# Copyright 2016 Euclidean Technologies Management LLC 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 requi...
from django.conf import settings from django.core.cache import cache from django.db import models from django.utils import timezone from django.utils.encoding import python_2_unicode_compatible, force_text from django.utils.translation import ugettext_lazy as _ from operator import attrgetter from .enums import (ZONE...
import math import numpy as np # https://stackoverflow.com/questions/37674306/what-is-the-difference-between-same-and-valid-padding-in-tf-nn-max-pool-of-t def pad_inputs(X, pad): print(pad) print("int(pad[0] // 2): ", int(pad[0] // 2)) return np.pad(X, ((0, 0), (int(pad[0] // 2), pad[0] - int(pad[0] // 2...
#!/usr/bin/env python3 #-*-coding:utf-8-*- import sqlite3 import sys from findarray30code import ui, ui2 import re from PyQt4 import QtGui, QtCore import signal signal.signal(signal.SIGINT, signal.SIG_DFL) def table2list(table_tsv): with open(table_tsv,'r',encoding='utf-16') as tsv: code_list = [] ...
import config import ccxt import multiprocessing from multiprocessing import Process, Pipe, Manager import threading import logging import logging.handlers import json from copy import copy, deepcopy import numpy as np import schedule from message import * import os import time rootLogger = logging.getLogger('') root...
import torch import numpy as np import cv2 from pytorch_msssim import ssim def torchPSNR(tar_img, prd_img): imdff = torch.clamp(prd_img, 0, 1) - torch.clamp(tar_img, 0, 1) rmse = (imdff**2).mean().sqrt() ps = 20*torch.log10(1/rmse) return ps def torchSSIM(tar_img, prd_img): return ssim(tar_img, pr...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import...
"""Commander for interacting with Google Drive""" import sys import os import csv import argparse import re from .drive.drive import Drive from .drive.drive_api import DRIVE_READONLY, DRIVE_PER_FILE from .sheets.sheets import Sheets from .sheets.sheets_api import SHEET_FULL, SHEET_READONLY BLUE = "\033[94m" NOCOLOR =...
from itertools import combinations from django.db import models from django.db.models import Q from django.utils.translation import gettext_lazy as _ from embed_video.fields import EmbedVideoField from unidecode import unidecode from thiamsu.utils import get_youtube_id_from_url, translate_hanzi_to_hanlo def _to_ali...
# ann_train.py # # Trains a neural net on a toy problem to generate a grid of zeros and # ones. Training data is located in the tdata.txt file and is arranged # as a 50x50 grid. For training, inputs are normalized on the interval # [-1.0, 1.0]. The number of training pairs is 50 * 50 = 2500. There is # a single output ...
import time , http.client , re , sys class url_lib: def __init__(self,url="url str"): if url[:4] == "http": self.url=url else: self.url="" self.Headers={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.10...
import logging from hashlib import md5 from .bam_io import BamAlignmentReader as Reader from .cluster import BaseCluster from .cluster_base import ( SampleNameMixin, ToGffMixin ) from .dumb_consensus import dumb_consensus from .tag_softclip import get_softclipped_portion logger = logging.getLogger(__name__) ...
""" adapted from original CREPE and FCN-f0 repositories at: https://github.com/marl/crepe https://github.com/ardaillon/FCN-f0/ original articles: "CREPE: A Convolutional Representation for Pitch Estimation", 2018, (Kim, <NAME>; <NAME>; <NAME>; Bello, <NAME>) "Fully-Convolutional Network for Pitch Estimation of Speech ...
import os import subprocess import sys import time import PIL.Image as Im import pyocr import pyocr.builders from PIL import Image as Im from wand.image import Image VALIDITY = [".jpg",".gif",".png",".tga",".tif",".bmp", ".pdf"] FNULL = open(os.devnull, 'w') #Open file in write mode to The file path of the null devi...
# coding=utf-8 # Copyright 2021 TF-Transformers Authors and The TensorFlow Authors. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licens...
from django.http import HttpResponse, Http404, HttpResponseRedirect from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated from ..models import GradingProcess, GradingAssignment, GradingContainer, Assignment, AssignmentItem, Assignme...
import time import argparse import caffe2 from caffe2.python import ( dyndep, brew, core, model_helper, net_drawer, optimizer, workspace, ) from caffe2.python.modeling import initializers import os import sys import numpy as np parser = argparse.ArgumentParser(description='FC Example') ...
""" Handy utility functions for various fMRI procedures""" import json import os from datetime import datetime import re import pandas as pd import subprocess import sys sys.path.append('../') from ..utils import convert_file def is_motion_corrected(fn): with open(fn) as f: metadata = json.load(f) ...
import io import sys from pathlib import Path from typing import Dict, Optional, List, Iterable import yaml from labml import logger from labml.logger import Text from labml_remote.configs import Configs from labml_remote.execute import UIMode from labml_remote.server import Server, SERVERS class Job: def __ini...
# Copyright 2018, Oath Inc # Licensed under the terms of the Apache 2.0 license. See LICENSE file in # https://github.com/yahoo/ironic-secureboot-driver import base64 import json import os from oslo_utils import fileutils import requests from ironic.common import boot_devices from ironic.common import exception as i...
from pyorbit.classes.common import np, dummy_import_4args from pyorbit.models.abstract_model import AbstractModel try: import celerite import autograd.numpy as np from celerite.terms import Term except: import numpy as np Term = dummy_import_4args # This class was written by <NAME> for his paper: ...
# -*- coding: utf-8 -*- """ hog ~~~ Sending multiple HTTP requests ON GREEN thread. :copyright: (c) 2014-2019 by <NAME>. :license: MIT, see LICENSE for more details. """ from six import itervalues, iteritems from six.moves import xrange import eventlet eventlet.monkey_patch() import click import re import request...
# -*- coding:utf-8 -*- """ :author: <NAME> :copyright: © 2019 <NAME> :time: 2020/3/29 15:39 """ import os from pathlib import Path from typing import List import arrow from flask import current_app, Response from lxml import html from app.response.maker import make_response_ok, make_response_error from ap...
from django.db import models from django.conf import settings from django.contrib.auth.models import ( AbstractBaseUser, PermissionsMixin, UserManager, Group, ) from django.contrib.auth.validators import ( ASCIIUsernameValidator, UnicodeUsernameValidator ) from django.contrib.staticfiles.templat...
import numpy as np class Board: def __init__(self): """A list of lists with dicts inside is the model being used for the playing grid. This model allows us to use [row] and [col] when iterating through the playing grid. Player hands are a list of dict, no list has been nested inside the li...
import os import time import requests import io import hashlib from PIL import Image from selenium import webdriver import signal from glob import glob ############## # Parameters ############## number_of_images = 400 GET_IMAGE_TIMEOUT = 2 SLEEP_BETWEEN_INTERACTIONS = 0.1 SLEEP_BEFORE_MORE = 5 IMAGE_QUALITY = 85 ...
""" Classes for reading/writing and other functions on haplotypes TODO: * transform * deal with LA and STRs * writephenotypes * documentation and type hinting * tests * Compare simulation output to GCTA * fail gracefully on assertions - we need ERROR utility """ import re import gzip from pathlib import Path imp...
# written by kylesim import re import pickle from sklearn.preprocessing import StandardScaler, RobustScaler, QuantileTransformer from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer from sklearn.metrics import classification_report, confusion_matrix, accuracy_score, precision_score, recall_score...
#!python3 import numpy as np import matplotlib.pyplot as plt import yaml ####################################################################### # Import yaml fit parameters to analyse ####################################################################### # Define filenames via timestamp name10kHz = '20181004T124047...
from django.db import models from systems.models import OperatingSystem, ServerModel from datetime import datetime, timedelta, date from django.db.models.query import QuerySet from settings import USER_SYSTEM_ALLOWED_DELETE, FROM_EMAIL_ADDRESS, UNAUTHORIZED_EMAIL_ADDRESS, BUG_URL from django.core.exceptions import Perm...
import os import numpy as np import pybullet as p from utils.text import TextFlag, log YAML_CONFIG_PATH = os.path.join(os.path.dirname(__file__), '..', '..', 'config', 'objects.yaml') class Haptic: MASS_FRICTION = "mass_friction" RESTITUTION = "restitution" SPRING_DAMPING_STIFFNESS = "spring_damping_st...
import pymysql import socket import time import numpy as np from Cryptodome.Cipher import AES from Cryptodome import Random import rsa import pymysql def sendData(serversocket, stringData,key=None,delay=None): print('ssssssssssssssssss') if key!=None: iv = Random.new().read(AES.block_size) mycip...
import json import os import datetime from menu import Requests from menu import Utility as Util from datetime import timedelta import logging def foods_to_json(food_array, day): foods = [] for food_name in food_array: food = { "name": food_name, "rating": 0, "amou...
#!/usr/bin/env python import requests from config import * from models import Task, User import os @app.route('/api/post_task', methods=['POST']) @auth.login_required def post_task(): # записывать исполнителям и принимать исполнителей ? strtask = request.json.get('task') username = request.json.get('user...
import webapp2 import os from google.appengine.ext.webapp import template import jinja2 class MainPage(webapp2.RequestHandler): def get(self): self.response.write(open("mainpage.html").read()) class LevelOne(webapp2.RequestHandler): page_header = """ <!doctype html> <html> <head> ...
# -*- coding: utf-8 -*- # # Copyright (c) 2020~2999 - Cologler <<EMAIL>> # ---------- # # ---------- from typing import * from collections.abc import MutableMapping, ItemsView, ValuesView from sqlite3 import Connection, connect, Cursor from contextlib import closing import json from tinydb.storages import Storage fr...
################ # # Deep Flow Prediction - <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME> (TUM) # # CNN setup and data normalization # ################ import torch import torch.nn as nn import torch.nn.functional as F def weights_init(m): classname = m.__class__.__name__ if classname.find('Conv') != -1: ...
# -*- coding: utf-8 -*- """ @Time: 2021/1/14 12:28 @Author: LizzieDeng @File: design_KF.py @Description: """ import matplotlib.pyplot as plt from plotGraph import plotgraph import plotly.graph_objects as go import numpy as np # ### 水箱实例代码实现 def plot_result(t, y_list, y_label): fig = go.Figure(layout=dict(width=60...
#!/usr/bin/env python """Secondary mirror focus control. History: 2004-01-09 ROwen first draft 2004-02-23 ROwen Modified to play cmdDone/cmdFailed for commands. 2004-03-11 ROwen Bug fix: assumed the secondary mirror would start moving within 10 seconds (a poor assumption if others are movi...
import re from typing import Dict, Text, Any, List, Union, Optional import logging from rasa_sdk import Tracker, Action from rasa_sdk.executor import CollectingDispatcher from rasa_sdk.forms import FormAction, REQUESTED_SLOT from rasa_sdk.events import ( SlotSet, EventType, ActionExecuted, SessionStarte...
from discord.ext import commands import discord alias = { "upgrade": ["upg", "up", "u", "upgrade"], "challenge": ["ch", "c", "challenge"], "research": ["r", "res", "research"], "lineage": ["lineage", "line", "l"], "artifact": ["artifact", "art", "a"], "bloodline": ["bloodline", "bl", "b"], ...
#!/usr/bin/python from __future__ import division import math import os import sys import plotly import numpy as np from mpl_toolkits.mplot3d import Axes3D import matplotlib.tri as tri import matplotlib.pyplot as plt import plotly.figure_factory as ff def cart2bary(arg=None,wd=None): X,Y,Z,E,I = [],[],[],[],[] ...
# coding=utf-8 # Copyright 2021 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...
#!/usr/bin/env python # pip3 install csv """refreshdata.py: Refresh Data in a system from any given source (database, csv, xml file).""" from gi.types import nothing from orca import input_event from zim import datetimetz __author__ = "<NAME>" __copyright_ = "Copyright 2020" __credits__ = ["<NAME>"] __lice...
#!/usr/bin/env python3 # Copyright 2021 <NAME>, <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 applica...
import os, cv2, random import numpy as np from keras.layers import Input, Dense from keras.optimizers import RMSprop from keras.callbacks import Callback, EarlyStopping, TensorBoard from keras.applications.vgg16 import VGG16 from keras.models import Model from keras.utils import np_utils import tensorflow as tf from ...
import pytest import numpy as np from easydict import EasyDict from dizoo.smac.envs import SMACEnv MOVE_EAST = 4 MOVE_WEST = 5 def automation(env, n_agents): actions = {"me": [], "opponent": []} for agent_id in range(n_agents): avail_actions = env.get_avail_agent_actions(agent_id, is_opponent=False)...
from utils.torch_utils import * # bins = (8.0, 15.0) bins = (4.5, 8.0, 15.0) # bins = tuple(np.arange(4.5, 15.5, 0.5).tolist()) t_bins = torch.tensor((0,) + bins, dtype=torch.float, device=device) weight_bins = (8.0, 15.0) weights = (20.5, 5.4, 1.0) def quantize_distance_matrix(dmat, bins=bins, use_ordinal=False): ...
# standard from urllib.request import urlopen from tempfile import NamedTemporaryFile import copy import sys import unittest import xml.etree.ElementTree as et # internal from encyclopedia.templates import Unindexed class XML(Unindexed): ''' Forest syntax combined with an elementTree XML implementation. To...
from crianza.errors import CompileError from crianza.interpreter import Machine, isconstant, isstring, isbool, isnumber from crianza import instructions from crianza import optimizer EMBEDDED_PUSH_TAG = "embedded_push" def make_embedded_push(value): """Returns a closure that pushed the given value onto a Machine'...
""" Example script for data preparation. If you use this code, please cite the following paper. <NAME> and <NAME> SPHARM-Net: Spherical Harmonics-based Convolution for Cortical Parcellation. IEEE Transactions on Medical Imaging. 2022 Copyright 2022 <NAME> Licensed under the Apache License, Version 2.0 (...
import sys import random import time from datetime import datetime, timedelta from pymongo import MongoClient, ASCENDING from sample import * QUERY_NUM = 20 LOG = "PLAN" # DEBUG | PLAN | INFO INSERT_DOC = True TEST_QUERY_NAME = True TEST_QUERY_FILE_EXTENSTION = True TEST_QUERY_TAG...
import os import tempfile from contextlib import contextmanager from urllib.parse import urlparse from google.cloud import storage _GOOGLE_STORAGE_SCHEMA = "gs" ## Things that can go here ## class GoogleStorageEnvironmentError(EnvironmentError): pass class GoogleStorageValueError(ValueError): pass class GoogleStora...
import numpy as np from typing import Tuple, Union # Rotation routines are heavily based on <NAME>'s transformations.py # axis sequences for Euler angles _NEXT_AXIS = [1, 2, 0, 1] # map axes strings to/from tuples of inner axis, parity, repetition, frame _AXES2TUPLE = { 'sxyz': (0, 0, 0, 0), 'sxyx': (0, 0, 1, 0), ...
import json from ..util.serialization import remove_dict_prefix from ..util.hash import sha256 from . import transaction from database import Database class Block(object): """ Class representing a Block instance This class will serve as an interphase to handle blocks. Whenever we need to deal ...
variables = {'pi':'fart','why':'yes'} keywords = ['print','exit','var','atom','help','all','import'] imports = [] def lexer(text): tokens = ['SOF'] tok = "" string = "" name = '' iS = False digits = '0123456789' literals = "= '#()" operands = '+-*/' jENM = False iN = False n...
# -*- coding: utf-8 -*- from metrics.mobilenetv2 import mobilenetv2 import torch import torch.nn as nn import torch.nn.functional as F import torchvision.transforms as transforms import torchvision from misc.utils import denorm def load_model(model, model_path): pretrained_dict = torch.load(model_path, ...
import numpy as np from collections import namedtuple import random QTransition = namedtuple("QTransition", "state action reward next_state terminal") SarsaTransition = namedtuple("QTransition", "state action reward next_state next_action terminal") class AbstractApproximateAgent(): r""" Base class for the approx...
import numpy as __np__ import matplotlib.pyplot as __plt__ from matplotlib import cm as __cm__ def __apershow__(obj, extent): if extent != 0: obj = -abs(obj) __plt__.imshow(obj, extent=[-extent / 2, extent / 2, -extent / 2, extent / 2]) __plt__.set_cmap('Greys') __plt__.show() ...
import torch import torch.nn as nn from torch.nn import functional as F def conv3x3_relu(in_ch, out_ch, rate=1): conv3x3_relu = nn.Sequential(nn.Conv2d(in_ch, out_ch, kernel_size=3, s...
# ref: https://github.com/ndrplz/ConvLSTM_pytorch/blob/master/convlstm.py import torch import torch.nn as nn class ConvLSTMCell(nn.Module): def __init__(self, input_size, input_dim, hidden_dim, kernel_size, bias): """ Initialize ConvLSTM cell. Parameters ---------- input_si...
""" Copyright 2021 Objectiv B.V. """ import pytest # Any import from modelhub initializes all the types, do not remove from modelhub import __version__ from tests_modelhub.data_and_utils.utils import get_objectiv_dataframe_test from tests.functional.bach.test_data_and_utils import assert_equals_data from uuid import U...
"""models.py - This file contains the class definitions for the Datastore entities used by the Game. Because these classes are also regular Python classes they can include methods (such as 'to_form' and 'new_game').""" from protorpc import messages from google.appengine.ext import ndb COMMANDS = ['rock', 'paper', 'sci...
import torch from torch import nn, optim from torchvision import models import numpy as np from collections import OrderedDict def create_model(arch, hidden_units , prob_dropout): # Create model model = eval("models." + arch + "(pretrained=True)") model.epochs = 0 # To prevent backprop through p...
import requests import json from rantlib.core_application.storage import read_data_file from os import walk from pathlib import Path from PyQt5.QtCore import Qt from PyQt5.QtGui import QFont from PyQt5.QtWidgets import QWidgetItem from pathlib import Path class Theme: def __init__(self): self.title = None...
from __future__ import division, print_function import os import gc import cv2 import pandas as pd import numpy as np import tensorflow as tf # Flask libraries # Flask utils from flask import Flask, redirect, url_for, request, render_template from werkzeug.utils import secure_filename from tqdm import tqdm from PIL ...
"""Food101データセット.""" # default packages import json import logging import tarfile import urllib.request as request import typing as t # third party packages import pandas as pd import pytorch_lightning as pl import sklearn.model_selection as model_selection import sklearn.preprocessing as preprocessing import torch im...
import pyodbc from loguru import logger from neo4j import GraphDatabase from pathlib import Path import configparser def create_object_nodes(session, cursor, database): logger.info("Creating object nodes and relationships to schema") query = read_sql_file('Objects') dependencies = cursor.execute(query) ...
import multiprocessing import os import sys import logging from functools import partial logger = logging.getLogger(__name__) import click import pandas as pd import numpy as np sys.path.append("..") from utils.sequence_utils import SequenceCollectingUtils, SequenceType from utils.parallelization_service import Para...
"""Iterative sampler framework. The framework is designed in two layers. 1. A driver class `IterativeSampler` that has an internal state `SamplerState` 2. Worker classes based on `SamplerStep` The sampler steps (subclasses of `SamplerStep`) implement a `_step` method that receives a `SamplerState` and returns a modif...
from typing import List, Tuple import torch from torch import nn from models.ssd_mobilenet_v1 import SSD, MobileNetV1Base, Block from models.anchor_generator import create_ssd_anchors from models.utils import decode_boxes class PredictionHead(nn.Module): def __init__(self, in_channels, num_classes, num_anchors)...
# Copyright 2014-2016 MongoDB, 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 writin...
import numpy as np import pandas as pd from bs4 import BeautifulSoup import nltk from nltk import wordpunct_tokenize from nltk.stem.snowball import EnglishStemmer from nltk.corpus import stopwords from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.decomposition import TruncatedSVD from sklearn.pip...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 1999-2018 Alibaba Group Holding 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-...
""" Credit for demo setup: Gusto development team """ from gusto import * from firedrake import IcosahedralSphereMesh, cos, sin, SpatialCoordinate, \ FunctionSpace, parameters from firedrake.petsc import PETSc from argparse import ArgumentParser from hybridization import HybridizedShallowWaterSolver import sys day...
import os import pickle import re import torch import torch.nn as nn from hyperbox.mutables.spaces import OperationSpace # from .rep_ops import * from hyperbox.networks.repnas.rep_ops import * from hyperbox.networks.repnas.utils import * from hyperbox.networks.base_nas_network import BaseNASNetwork from hyperbox.util...
import pytest from qualg.toolbox import simplify from qualg.scalars import DeltaFunction from qualg.fock_state import FockOp, FockOpProduct, BaseFockState def test_fock_op_product(): aw = FockOp('a', 'w') av = FockOp('a', 'v') print(FockOpProduct([aw, av])) print(FockOpProduct([aw, av, aw])) as...
""" Main script for xfcsdashboard. plot_data -> entry point for xfcs metadata plot_csv -> cli entry point """ import os import pandas as pd import plotly.graph_objs as go from plotly.offline import plot from xfcsdashboard import csv_data # ---------------------------------------------------------------------------...
import re import numpy as np import pandas as pd import ops.filenames from ops.constants import * def parse_czi_export(f): pat = '.*_s(\d+)c(\d+)m(\d+)_ORG.tif' scene, channel, m = re.findall(pat, f)[0] return {WELL: int(scene), CHANNEL: int(channel), SITE: int(m) - 1} def make_czi_file_table(f...
#!/usr/bin/env python # encoding=utf-8 #codeby 道长且阻 #email @ydhcui/QQ664284092 from lib import requests import re import socket import urllib.parse as urlparse import settings from core.cmsfind import CmsFind CMS = CmsFind(settings.DATAPATH + '/cmsdata.json') #################################### class BaseWe...
from typing import Dict, Tuple op_rules = { '+': (int,int), '-': (int,int), '*': (int,int), '/': (int,int), '+.': (float,float), '-.': (float,float), '*.': (float,float), '/.': (float,float), '>': (int,bool), '=': (int,bool), '>.': (float,bool), '=.': (float,bool), ...
""" Global dataset information functions : - explore (func): Identify variables types and gives global information about the dataset (NA, low variance features) - low variance features (func): identify features with low variance - get_features_type (func): get all features per type """ from sklearn.preprocessing im...
import pandas as pd import numpy as np import scipy.stats as sci import seaborn as sns import matplotlib import matplotlib.pyplot as plt def sum_sq_and_dof_factors(df, target_col, column): ss = 0 grand_mean = np.mean(df[target_col]) dof = len(list(df[column].unique())) - 1 for item in list(df[column]....
#!/usr/bin/env python # -*- coding: utf-8 -*- #https://qiita.com/ReoNagai/items/4c5c2c2b1175f898c0d6 import numpy as np import gym import random from collections import deque from keras.layers import Input, Activation, Dense, Flatten, RepeatVector, Reshape from keras.layers.convolutional import Conv2D from keras.mod...
import os import re import math from random import choice, randint, choices from backstage.models import College, Major, AdmClass, Student,\ Teacher, ClassRoom, MajorPlan from scoreManagement.models import Course, Teaching from django.db.utils import IntegrityError from .make_encoding import make_encode class Coll...
import Open import json import copy import os from progress.bar import Bar import numpy as np os.chdir('..') class SPS(object): def __init__(self): self.per = 0 self.perCopy = 0 self.Load() self.subjectList = Open.GetSubject().Names() def Load(self): with open(os.getcw...
#!/usr/bin/env python # encoding: utf-8 # ---------------------------------------------------------------------------- from __future__ import absolute_import, unicode_literals import logging import time from io import StringIO from django.conf import settings as django_settings from django.core import mail from djang...
import typing as ty import numpy as np from scipy import stats import tensorflow as tf import tensorflow_probability as tfp import flamedisx as fd export, __all__ = fd.exporter() o = tf.newaxis class DetectPhotonsOrElectrons(fd.Block): """Common code for DetectPhotons and DetectElectrons""" model_attribute...
from django.contrib.auth import get_user_model from djoser.serializers import UserCreateSerializer, UserSerializer from drf_extra_fields.fields import Base64ImageField from recipes.models import Ingredient, IngredientRecipe, Recipe, Tag from rest_framework import serializers from rest_framework.validators import Unique...
from typing import Optional import torch import torch.nn as nn from torch import Tensor import numpy as np ''' Modules are basically follow the desing of the original repo, but also with some modifications. https://github.com/lioryariv/volsdf/blob/main/code/model/network.py ''' class SDFNet(nn.Module): def __init...
import os import sys import glob import json from flask import Flask, render_template, request, redirect, url_for, \ jsonify, send_file, send_from_directory, abort # import psycopg2 from PIL import Image from io import BytesIO from base64 import b64encode, b64decode import time import random from tempfile import ...
import numpy as np import os import tensorflow as tf from glob import glob from object_detection.builders import model_builder from object_detection.core.model import DetectionModel from object_detection.core import standard_fields as fields from object_detection.utils import config_util, label_map_util from typing im...
import random import numpy as np import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import copy DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") def soft_update(target, source, tau): for target_param, param in zip(target.parameters(), source.par...
import pygame import random import os pygame.mixer.init() pygame.init() # COLOURS white = (255, 255, 255 ) red = (255, 0, 0) black = (0, 0, 0) aqua = (26, 198, 217) yellow = (252, 186, 3) # CREATING WINDOW screen_width = 900 screen_height = 600 gameWindow = pygame.display.set_mode((screen_width,scre...
class Ann(object): def __init__(self, name, padding = 0): self.value = False self.name = name self.width = len(name) + padding self.empty = " " * self.width def set(self): self.value = True def reset(self): self.value = False def text(self): if se...
import vcf import argparse from record import Record, PhaseSet, ChromosomoHaplotype from stats import PhaseSetStats, HapStats def get_phase_set_stats(template_phase_set:PhaseSet, phase_set:PhaseSet): prev_record: Record record: Record t_record: Record t_prev_record: Record record_count = 0 s...
import numpy as np import cv2 from PIL import Image from sklearn.metrics.pairwise import cosine_similarity import torchvision.transforms as transforms from torchvision import models from torch.autograd import Variable import matplotlib.image as mpimg import ov_utils.imgproc as imgproc model = models.resnet18(pretraine...