content
stringlengths
5
1.05M
# *-* encoding: utf-8 *-* from django_tables2 import tables, Column from vmtory.models import VM from django.utils.safestring import mark_safe from django.utils.translation import gettext_lazy as _ class Top10Table(tables.Table): assignee__username = Column(_('User')) total = Column(_('Quantity')) class Gen...
import datetime import uuid from auth.domain.activation import Activation from auth.domain.user import User from auth.settings import ACTIVATION_EXPIRE_TIME def test_user_id(): email = 'foo.bar@email.com' user = User(id=uuid.uuid4(), full_name='Foo Bar', email=email, password='a-secret') activation = Ac...
from utils import startTestMsg from tests.test_FA_Determinization import tFA_Determinization from tests.test_FA_Minimization import tFA_Minimization from tests.test_FA_Recognition import tFA_Recognition from tests.test_FA_Operations import tFA_Renaming_States, tFA_Union from tests.test_CFG_disk import testCFGReading, ...
# v3 API endpoints of HackerEarth Code Checker API COMPILE_API_ENDPOINT = "https://api.hackerearth.com/v3/code/compile/" RUN_API_ENDPOINT = "https://api.hackerearth.com/v3/code/run/" # Max run time of a program in seconds RUN_TIME_UPPER_LIMIT = 5 # Max memory consumption allowed for a program MEMORY_UPPER_LIMIT = 1...
__author__ = "Tomasz Rybotycki" from copy import deepcopy from typing import List, Iterable from numpy import ndarray from scipy import special from ..boson_sampling_utilities.boson_sampling_utilities import generate_possible_outputs from ..distribution_calculators.bs_distribution_calculator_interface import \ B...
from setuptools import setup setup( name="batch-file-renamer", scripts = [ 'BatchFileRenamer/batch-file-renamer' ], version="1.0", description="Simple batch file renaming application", author="JJ Style", author_email="style.jj@pm.me", license="MIT", url="https://github.com/j...
# -*- coding: utf-8 -*- import os import pickle from autobahn.twisted.util import sleep from mdstudio.deferred.chainable import chainable from mdstudio.component.session import ComponentSession from mdstudio.runner import main from mdstudio_workflow import Workflow class LIEPredictionWorkflow(ComponentSession): ...
# https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/ class Solution: def minRemoveToMakeValid(self, s: str) -> str: indexes_to_remove = set() unclosed_open_parentheses_indexes = list() for idx, char in enumerate(s): if char == '(': unclosed_o...
# nxt.motcont module -- Interface to Linus Atorf's MotorControl NXC # Copyright (C) 2011 Marcus Wanner # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (a...
import torch as th import torch.nn as nn import torch.nn.functional as functional import torch.nn.init as INIT class TransEScore(nn.Module): def __init__(self, gamma): super(TransEScore, self).__init__() self.gamma = gamma def edge_func(self, edges): head = edges.src['emb'] tai...
__title__ = 'pycimvp' __description__ = 'A Python library project for TDD + CI.' __url__ = 'https://pycimvp.readthedocs.io/' __version__ = '1.0.3' # __build__ = 0x022501 __author__ = 'Lee Shiueh' __author_email__ = 'lee.shiueh@gmail.com' __license__ = 'Apache 2.0' # __copyright__ = 'Copyright 2021'
import os print(""" /* Uses Testcases from https://github.com/nst/JSONTestSuite/ MIT License Copyright (c) 2016 Nicolas Seriot 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 restricti...
from typing import List, Optional import torch import torch.distributed as dist from colossalai.zero.shard_utils import BaseShardStrategy from colossalai.zero.sharded_model._zero3_utils import get_shard from colossalai.zero.sharded_param.sharded_tensor import ShardedTensor from colossalai.utils import get_current_devi...
# Generated by Django 2.1.7 on 2019-03-02 22:06 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('torrents', '0014_auto_20190302_2121'), ] operations = [ migrations.AddField( model_name='torrentinfo', name='is_dele...
__version__ = "0.16.5" __author__ = "Tulir Asokan <tulir@maunium.net>" __all__ = [ "api", "appservice", "bridge", "client", "crypto", "errors", "util", "types", "__optional_imports__", ] from typing import TYPE_CHECKING __optional_imports__ = TYPE_CHECKING
import numpy as np from satellipy.analysis import audio as Audio from satellipy.analysis import emotions as Emotions def analyse_and_get_personality_features( username, emotions_collection, audio_features_collection): audio_analysis = Audio.analyse_audio_for_user( username, audio_...
# coding: utf-8 import re import numpy as np from scipy.ndimage import imread from scipy.misc import toimage class ImageProcessor(object): BLACK = 0 WHITE = 254 LIMIT = 0.45 @classmethod def _maximizer(cls, x, maximum): val = x / maximum ret_val = cls.WHITE if val < cls.L...
import sys import os import copy import traceback import simplejson as json import matplotlib.pyplot as plt from matplotlib.collections import PatchCollection from matplotlib.patches import Rectangle import numpy as np from typing import List from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer...
from textblob import TextBlob import sys import tweepy from dotenv import load_dotenv import os load_dotenv() api_key = os.getenv('PUBLIC_API') api_key_secret = os.getenv('PRIVATE_API') access_token = os.getenv('ACCESS_TOKEN') access_token_secret = os.getenv('ACCESS_TOKEN_SECRET') auth_handler = tweepy.OAuthHandler(c...
import numpy as np import popsynth from dask.distributed import Client, LocalCluster from popsynth.aux_samplers.lognormal_aux_sampler import Log10NormalAuxSampler from popsynth.aux_samplers.normal_aux_sampler import NormalAuxSampler from popsynth.aux_samplers.trunc_normal_aux_sampler import \ TruncatedNormalAuxSamp...
import os from setuptools import setup VERSION = "0.4" def get_long_description(): with open( os.path.join(os.path.dirname(os.path.abspath(__file__)), "README.md"), encoding="utf8", ) as fp: return fp.read() setup( name="stepmania-to-sqlite", description="Save data about yo...
"""Test the skip_celltags option.""" import os from typing import TYPE_CHECKING from nbqa.__main__ import main if TYPE_CHECKING: from _pytest.capture import CaptureFixture def test_skip_celltags_cli(capsys: "CaptureFixture") -> None: """ Check flake8 works. Shouldn't alter the notebook content. Par...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import re import pandas as pd from scipy import interpolate class Function: """Esta clase carga una función a partir de una disperción de datos ordenados. Posee el método 'eval', que evalúa la función en cualquier número mientras esté en el dominio...
from django.apps import AppConfig class App2CvVideosConfig(AppConfig): name = 'App_2_CV_Videos'
# -*- coding: utf-8 -*- # # Copyright (C) 2020 CERN. # # invenio-app-ils is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Test ILL borrowing requests.""" import json from flask import url_for from invenio_search import current_sear...
# - * - encoding : utf - 8 - * - """ :copyright: 2017-2018 H2O.ai, Inc. :license: Apache License Version 2.0 (see LICENSE for details) """ #import abc import os import numpy as np import pandas as pd from daal.data_management import (AOSNumericTable, FileDataSource, DataSource, Homo...
""" Plotting class for FVCOM results. """ from __future__ import print_function import copy from datetime import datetime from pathlib import Path from warnings import warn import collections import cartopy.crs as ccrs import cartopy.feature as cfeature import matplotlib.widgets import mpl_toolkits.axes_grid1 import...
# from lib.core.mscgnet import * # score 0.547, no TTA import datetime import logging import os import numpy as np import torch from PIL import Image # from core.net import * from core.net import get_model from utils.data.augmentation import img_load from utils.data.preprocess import IDS, GT, IMG from utils import P...
import discord from discord.ext import commands import asyncio from asyncio import sleep class Embeds(commands.Cog): def __init__(self, client): self.client = client @commands.command() async def id(self, ctx, member : discord.Member): embed = discord.Embed(title = member.name, descripti...
from rest_framework import serializers from .models import CoronaCaseRaw class CoronaCaseRawSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = CoronaCaseRaw fields = [ 'case_type', 'name', 'description', 'latitude', '...
import numpy as np import math import matplotlib.pyplot as plt import time from control_utilities.chrono_utilities import calcAngle class MatplotlibWrapper: def __init__(self, step_size, vehicle, opponents=None, obstacles=None, render_step_size=1.0/60): self.step_size = step_size self.time = 0 ...
#!/bin/python3 """dbreversepivot takes an input file with time/value columns, and pivots the table into a narrow table with one line per old column. For example, if the input was this: #fsdb -F s time foo bar 1 10 0 2 30 20 3 0 40 It would convert this to: #fsdb -F s ti...
class Card: """Card class for representing and manipulating one playing card""" def __init__(self, rank, suit): """A constructor method that sets the suit and rank""" self.suit = suit self.rank = rank def __str__(self): """Overrides the information used by the prin...
from django.conf.urls import url from django.contrib.auth.decorators import login_required, permission_required from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^$', permission_required('sale.view_table', login_url='account_login') ...
import cPickle def convert_to_csv(): ''' Convert ques_id, user_id to user int id, ques int id stores a mapping of id to int id ''' mahout_file = open("../bytecup2016data/invited_info_train_mahout.csv","w") mahout_test_file = open("../bytecup2016data/test_nolabel_mahout.csv","w") # vari...
# -*- coding: utf-8 -*- ''' This is a PyTorch implementation of CURL: Neural Curve Layers for Global Image Enhancement https://arxiv.org/pdf/1911.13175.pdf Please cite paper if you use this code. Tested with Pytorch 1.7.1, Python 3.7.9 Authors: Sean Moran (sean.j.moran@gmail.com), 2020 Instructions: T...
from pydantic import BaseModel class AlertType(BaseModel): id: int name: str description: str photo: str class Config: orm_mode = True class Animal(BaseModel): id: int name: str photo: str type: int class Config: orm_mode = True class AnimalType(BaseModel)...
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 """ Register new Pipes. Requires the API to be running. """ from __future__ import annotations from meerschaum.utils.typing import SuccessTuple, Any, List, Optional def register( action : Optional[List[str]] = None, **kw : Any ) -> S...
""" This example will access the twitter follow button API, grab a number like the number of followers... and display it on a screen! if you can find something that spits out JSON data, we can display it """ import sys import time import board from adafruit_pyportal import PyPortal cwd = ("/"+__file__).rsplit('/', 1)[0...
import struct import re from err import Warning, Error, InterfaceError, DataError, \ DatabaseError, OperationalError, IntegrityError, InternalError, \ NotSupportedError, ProgrammingError insert_values = re.compile(r'\svalues\s*(\(.+\))', re.IGNORECASE) class Cursor(object): ''' This ...
from django.conf import settings from datetime import datetime from kazoo.client import KazooClient PERM_READ = 1 PERM_WRITE = 2 PERM_CREATE = 4 PERM_DELETE = 8 PERM_ADMIN = 16 PERM_ALL = PERM_READ | PERM_WRITE | PERM_CREATE | PERM_DELETE | PERM_ADMIN TIMEOUT = 10.0 ZOOKEEPER_SERVERS = getattr(settings, 'ZOOKEEPER_...
#!/usr/bin/env python3.6 x = 123456789 x = 123456 x = .1 x = 1. x = 1E+1 x = 1E-1 x = 1.00000001 x = 123456789.123456789 x = 123456789.123456789E123456789 x = 123456789E123456789 x = 123456789J x = 123456789.123456789J x = 0XB1ACC x = 0B1011 x = 0O777 x = 0.000000006 # output #!/usr/bin/env python3.6 x = 123_456_7...
#!/usr/bin/env python3 # the TweetStreamer is a subclass of TwythonStreamer from twython import TwythonStreamer # errors! import error_messenger # the TweetStreamer class will use the streaming api to check for new tweets. # It will be used for filtering all tweets containing the trigger word specified in setup.py # ...
# Copyright 2017 Zhongyi Han. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
#import pyARC from pyARC_dev import pyARC import numpy as np import matplotlib import matplotlib.ticker import matplotlib.pyplot as plt import glob import pdb, sys, os """ Module containing a routine for installing the namelist parameters in an ATMO object. """ # Fiducial values for HAT-P-18: LOGG = 2.69 TEQ = 850 ...
import abc as ABC from abc import ABC, abstractmethod, abstractproperty class Analyzer(ABC): @abstractmethod def analyze(self): pass
# Run inference on batches of data # uses default configuration from detectron2 # # Fatemeh Saleh <fatemehsadat.saleh@anu.edu.au> import numpy as np import cv2 import os from detectron2 import model_zoo from detectron2.modeling import build_model from detectron2.config import get_cfg import torch import detectron2.dat...
import os def getRootPath(): return os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")) def getProjectAbsPath(*path): return os.path.join(getRootPath(), *path) def getCachePath(*path): return getProjectAbsPath(".cache", *path) def getTemplatePath(*path): return getProjectAbsPath...
def aumentar(preço, pc): aum = preço + (preço * pc / 100) return aum def diminuir(preço, pc): dim = preço - (preço * pc / 100) return dim def dobro(preço): dob = preço * 2 return dob def metade(preço): met = preço / 2 return met
from api.db import db_users from api.services.custom_mapper import map_json_to_object from api.services.view_models import ErrorModel, PostModelReturn def worker_for_post(posted_user): mongo_object = map_json_to_object(posted_user) if mongo_object.user == 'frontpage': error_object = ErrorModel(mongo_o...
# NOTE: this file is not an actual test though, but could be helpful to debug the new replayer import os from pathlib import Path from simod.readers.log_reader import LogReader from simod.replayer_datatypes import BPMNGraph, ElementInfo from simod.configuration import Configuration bpmn_schema_url = 'http://www.omg....
# Copyright 2021 - Guillaume Charbonnier # Licensed under the Apache License, Version 2.0 (the "License"); # http://www.apache.org/licenses/LICENSE-2.0 from typing import Optional from _nats.aio.client import Client as NC from .mixins.consumers import ConsumersMixin from .mixins.infos import AccountInfosMixin from .m...
import tensorflow as tf from tensorflow import keras from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense import numpy as np import pandas as pd import matplotlib.pyplot as plt class MultiLayerPerceptron(object): def __init__(self,hidden_neurons,feature_dim): self.model = keras....
from .method import Method from .scheme import Scheme from .status_code import StatusCode
import asyncio async def foo(data): """"sleep and return an increment""" print('foo', data) await asyncio.sleep(0.1) print('done foo') return data + 1 async def bar(): """"sleep and return nothing""" print('bar') await asyncio.sleep(0.2) return 'done bar' async def quit_it(loop...
#!/usr/bin/python # -*- coding: utf-8 -*- import sys import os def resource_path(relative): ''' resolve the path(PyInstaller) ''' if hasattr(sys, "_MEIPASS"): # noinspection PyProtectedMember return os.path.join(sys._MEIPASS, relative) return os.path.join(relative) class Saveloa...
"""Parse a grammar written in ECMArkup.""" from __future__ import annotations # mypy: no-implicit-optional import os import collections from typing import Dict, Iterable, Optional, Tuple from jsparagus import parse_pgen, gen, grammar, extension, types from jsparagus.lexer import LexicalGrammar from jsparagus.ordered...
n = int(input()) s = [] for i in range(n): s.append(input()) s[i] = s[i][::-1] s.sort() for i in range(n): s[i] = s[i][::-1] print(s[i])
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.11.3 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # %% [raw] raw_mimetype="tex...
# Copyright (C) 2015 Yahoo! Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law...
import re def fun(email): #pattern = '[^@]+@[^@]+\.[^@]{1,3}' pattern = '^[a-zA-Z][\w-]*@[a-zA-Z0-9]+\.[a-zA-Z]{1,3}$' return re.match(pattern, email)
# -*- coding: utf-8 -*- from django.db import models from .mixins import SeasonsMixin from .time_base import TimeMixin from . import fields class PartManager(models.Manager): def get_by_natural_key(self, name): return self.get(name=name) class Part(SeasonsMixin, TimeMixin, models.Model): objects ...
# -*- coding: UTF-8 -*- """ .. --------------------------------------------------------------------- ___ __ __ __ ___ / | \ | \ | \ / the automatic \__ |__/ |__/ |___| \__ annotation and \ | | | | \ ...
from delphi.translators.for2py.format import * from delphi.translators.for2py.arrays import * def main(): A = Array([(-3,1),(-4,0)]) for i in range(-3,1+1): for j in range(-4,0+1): A.set_((i,j), i+j) fmt_obj = Format(['5(I5,X)']) for i in range(-3,1+1): sys.stdout.write(f...
"""The data models and enums returned and accepted by the api.""" __all__ = ["cards", "embeds", "events", "fundings", "merchants", "transactions"]
#!/usr/bin/env python # -*- coding: UTF-8 -*- # (c) 2020 Mike Lewis import setuptools import foursquare version = str(foursquare.__version__) setuptools.setup( name="foursquare", version=version, author="Mike Lewis", author_email="mlewis.mail@gmail.com", url="http://github.com/mLewisLogic/foursq...
from subprocess import call class Telescope: MAX_SPEED = 10000.0 MIN_DURATION = 20.0 MAX_DURATION = 20000.0 DURATION_CONST= MAX_SPEED * MIN_DURATION def __init__(self, device='/dev/ttyACM0'): call(("stty -F %s -imaxbel -opost -isig -icanon -echo -echoe -ixoff -ixon 9600" % device).sp...
#!/usr/bin/env python # -*- coding: utf8 -*- """ This script check that only whitelisted headers are included (transitivly) by including chemfiles.h or chemfiles.hpp. """ import os import sys import re ROOT = os.path.join(os.path.dirname(__file__), "..", "..") GENERATED_HEADERS = ["chemfiles/config.hpp", "chemfiles/ex...
import torch from torch.utils.data import DataLoader import torch.nn.functional as F import math import numpy as np import os, argparse import time import shutil import subprocess from s3dg import S3D from dataset import VideoClipDataset, RandomSequenceSampler from preprocessing import Preprocessing parser = argparse...
from io import BytesIO from pathlib import Path from typing import ( Any, List, Mapping, Optional, Union, ) import numpy as np from hamcrest.core.base_matcher import BaseMatcher from hamcrest.core.string_description import StringDescription from sklearn.externals import joblib from microcosm_sagem...
import argparse import logging import sys from requests.exceptions import RequestException from dothttp.log_utils import setup_logging from .exceptions import DotHttpException from .request_base import CurlCompiler, RequestCompiler, HttpFileFormatter, Config, eprint logger = logging.getLogger('dothttp') def apply(...
# coding:utf-8 import sys import csv import json import os import FuelSDK import et_objects from getpass import getpass CONFIG_PATH = '~/.fuelsdk/config.python' class Commands(object): def authenticate(self, client_id=None, client_secret=None, debug=False): if client_id is None or client_secret is None:...
import os import argparse import json import numpy as np from PIL import Image import torch import torchvision import torch.nn as nn from torch.autograd import Variable from torchvision import models, transforms def main(): args = get_arguments() model = load_checkpoint(args.checkpoint) model.idx_to_clas...
# encoding: utf-8 """ capability/__init__.py Created by Thomas Mangin on 2012-07-17. Copyright (c) 2009-2015 Exa Networks. All rights reserved. """ from exabgp.bgp.message.open.capability.capability import Capability from exabgp.bgp.message.open.capability.addpath import AddPath from exabgp.bgp.message.open.capabili...
from . import requests from .stats import box_plots, date_bins, date_histograms, counts async def visualizations(startDate, endDate, requestTypes=[], ncList=[]): bins, start, end = date_bins(startDate, endDate) fields = [ 're...
from django.core.mail import send_mail, BadHeaderError from django.http import HttpResponse, HttpResponseRedirect from django.conf import settings from django.shortcuts import render, redirect from .forms import ContactForm, ReplyForm import requests from django.contrib.auth.decorators import login_required from django...
#!/usr/bin/env python2 import re #Author: Stefan Toman if __name__ == '__main__': #read input n = int(raw_input()) s = "" for _ in range(n): s += raw_input() #print output for r in re.finditer("<a ([^<>]*)href=['\"](\S*)['\"]([^<>]*)>(.*?)</a>", s): print "%s,%s" % (r.groups(...
import os import time from functools import wraps class LazyProperty: """ 延迟调用、结果保存 """ def __init__(self, func): self.func = func def __get__(self, instance, cls): if instance is None: return self else: value = self.func(instance) setattr(inst...
import tensorflow as tf if False: from typing import List def isolate_rectangle(tensor, # type: tf.Tensor corner_1, # type: List[int] corner_2 # type: List[int] ): shape_to_subtract = [a + (tensor.shape[b] - corner_2[b]) for a, b in zip(cor...
from typing import Optional, Sequence from git import Repo from flexlate.branch_update import get_flexlate_branch_name_for_feature_branch from flexlate.constants import DEFAULT_TEMPLATE_BRANCH_NAME, DEFAULT_MERGED_BRANCH_NAME from flexlate.ext_git import branch_exists, push_to_remote from flexlate.styles import print...
from django.conf.urls import patterns, include, url from django.contrib import admin from msgvis.apps.base import views urlpatterns = patterns('', url(r'^$', views.HomeView.as_view(), name='home'), # url(r'^explorer/$', views.ExplorerView.as_view(), name='explorer'), ...
from urllib import urlencode import json import os from geomancer.app_config import MANCER_KEYS from geomancer.helpers import encoded_dict from geomancer.mancers.geotype import State, StateFIPS from geomancer.mancers.base import BaseMancer, MancerError from string import punctuation import re from urlparse import urlpa...
from adafruit_si7021 import SI7021 from ._i2c_utils import get_busio_i2c class Si7021(SI7021): address = 0x40 def __init__(self): super().__init__(get_busio_i2c()) @property def data(self): return { "temperature": self.temperature, "humidity": self.relative_humidity } @property ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class BusinessHoursDesc(object): def __init__(self): self._days_in_week = None self._hours = None @property def days_in_week(self): return self._days_in_week @days...
import falcon, json, rethinkdb as r ''' Set HTTP access control (CORS) headers https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS https://github.com/falconry/falcon/issues/303 ''' def corsMiddleware(request, response, params): response.set_header('Access-Control-Allow-Origin', '*') response...
import random import string from model.user import User import jsonpickle import os.path import getopt import sys # default params n = 1 # quantity iterations f = "data/users.json" # path to file file = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", f) # get option from cmd try: ...
import io import os import sys from decorator import decorator def wrap_cli_test(output, save_output=False): """ This decorator captures the stdout and stder and compare it with the contacts of the specified files. Instead of save_output you can set the env variable BRG_TOOLS_TESTS_SAVE_OUTPUT ...
from fastapi import status from fastapi.exceptions import HTTPException from sqlalchemy.orm import Session from sqlalchemy.orm.exc import NoResultFound from app.db.queries import memos from app.models import models def check_owner_is_collect( memo_id: int, db: Session, owner: models.User ) -> bool: memo = ge...
# written by David Sommer (david.sommer at inf.ethz.ch) in 2019 import numpy as np import scipy.stats from core.probabilitybuckets_light import ProbabilityBuckets from matplotlib import pyplot as plt #### # Privacy Buckets is based on the following publication #### # [*] S. Meiser, E. Mohammadi, # [*] "Tight on Budg...
""" A script used to display the cross-correlation matrix and the the whole time seriesxX """ import numpy as np import matplotlib.pyplot as plt import statsmodels.api as sm from signals.time_series_class import MixAr, AR from signals.aux_functions import sidekick from visualization import distance import os plot2 = ...
# Copyright 2017 The TensorFlow Authors All Rights Reserved. # Copyright 2018 Xu Chen 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...
import cv2 as cv import numpy as np from numpy.linalg import norm from math import sqrt class CameraSensor: SIDE_ORDER = ["L", "R", "B", "U", "D", "F"] def __init__(self): capture = cv.VideoCapture(0) ret, frame = capture.read() self.camHeight, self.camWidth, self.camColors = fra...
from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings from django.views.generic.base import RedirectView from .views import signup urlpatterns = [ path('', RedirectView.as_view(pattern_name='researcher:view'), name='home...
# The MIT License (MIT) # # Copyright (c) 2015, Nicolas Sebrecht & 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 the rights ...
from .cspdarknet import * # noqa F401
#!/usr/bin/python ######################################################################################################################## # # Copyright (c) 2014, Regents of the University of California # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, are permi...
import torch.nn as nn import torch import torch.nn.functional as F class SelfAttention(nn.Module): def __init__(self, input_size): super().__init__() self.input_linear = nn.Linear(input_size, 1, bias=False) self.dot_scale = nn.Parameter(torch.Tensor(input_size).uniform_(1.0 / (input_size *...
import os import numpy as np from matplotlib.colors import rgb_to_hsv, hsv_to_rgb from PIL import Image def norm(img): """ Normalize an image down to a 'unit vector' """ n = np.linalg.norm(img) if n == 0: return img return img.astype(np.float32) / n def rgb2gray(img): """ Convert RGB im...
class LazyLoadProxy(object): # Taken from http://code.activestate.com/recipes/496741-object-proxying/ __slots__ = ["_obj_fn", "__weakref__", "__proxy_storage"] def __init__(self, fn, storage=None): object.__setattr__(self, "_obj_fn", fn) object.__setattr__(self, "__proxy_storage", storage) ...
from django.shortcuts import render from django.http import HttpResponse # Create your views here. def tools_list(request): #return HttpResponse('tools') return render(request, 'tools/tools_list.html')