content
stringlengths
5
1.05M
class Solution: def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]: while i < len(firstList):
def Instagram(): from datetime import timedelta,date import pandas as pd from bs4 import BeautifulSoup import requests from selenium import webdriver from selenium.webdriver.common.by import By import time from joblib import Parallel, delayed print("Instagram 크롤링 시작\n") topic...
import tensorflow as tf import numpy as np from tensorflow.models.rnn import rnn, rnn_cell if __name__ == '__main__': X = np.random.randint(0,2,(50000,25,10)) Y = np.reshape(np.sum(X,axis=2),(50000,25,1)) X_test = np.random.randint(0,2,(1000,25,10)) Y_test = np.reshape(np.sum(X_test,axis=2),(1000,...
# Copyright 2015 OpenStack Foundation # Copyright 2016 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/LI...
# opencv 轉黑白 # pillow 套件 import pytesseract from PIL import Image import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = 'DejaVu Sans' # 用来正常显示中文标签 plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号 def get_bin_table(threshold=113): # 0表示黑色,1表示白色 binary # 闕值二值化 table = [] for i in r...
#!/usr/bin/python # # 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 DOCUMENTATION = ''' module: github_org_team short_description: Manage GitHub Organization Team extends_documentation...
from __future__ import print_function import numpy as np def IsPowerOfTwo(i): """Returns true if all entries of i are powers of two, False otherwise. """ return (i & (i - 1)) == 0 and i != 0 def Log2ofPowerof2(shape): """ Returns powers of two exponent for each element of shape """ res = ...
import numpy as np import pandas as pd # global variables from synthpop import NUM_COLS_DTYPES, CAT_COLS_DTYPES NAN_KEY = 'nan' NUMTOCAT_KEY = 'numtocat' class Processor: def __init__(self, spop): self.spop = spop self.processing_dict = {NUMTOCAT_KEY: {}, NAN_KEY:...
from django.shortcuts import render, get_object_or_404, redirect from .models import Post from .forms import CommentForm from django.views.generic import ( ListView, DetailView, CreateView, UpdateView, DeleteView, ) from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.contrib....
from eth2spec.test.helpers.keys import privkeys from eth2spec.utils import bls from eth2spec.utils.ssz.ssz_typing import Bitlist, ByteVector, Bitvector from eth2spec.utils.ssz.ssz_impl import hash_tree_root from eth2spec.utils.merkle_minimal import get_merkle_tree, get_merkle_proof from remerkleable.core import pack_bi...
import heapq from collections import defaultdict def dijkstra(start, N, branches): """ :param start: :param N: The number of nodes :param branches: dictionary, branches[src_node] = [(next_node, cost)] :return: """ distance_heap = [(float('inf'), i) for i in range(N)] distance_heap[star...
# -*- coding: utf-8 -*- # Copyright 2014, Digital Reasoning # # 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...
from flask import ( Flask, abort, request ) import json from api_server import authenticate # key for calling api, once we have database setup # use proper login/auth from model import search # TODO - add login/auth # Create the application instance app = Flask(__name__) @app.route('/search', methods...
# -*- coding: utf-8 -*- """ git-recipe is a small recipe that allows you to use git repositories [buildout] parts = data [data] recipe = gitrecipe repository = git://example.com/my-git-repo.git rev = origin/redevlop-branch as_egg = true """ import os from zc.buildout import buildout from zc.buildout import easy_in...
# Copyright (c) 2021 Leon Kuchenbecker <leon.kuchenbecker@uni-tuebingen.de> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to...
def majority_number(db): dic = {} maxcount = 0 for i in db: if i in dic: dic[i] += 1 else: dic[i] = 1 maxcount = max(dic, key=lambda i: dic[i]) return maxcount w = [2,2,3,7,5,7,7,7,4,7,2,7,4,5,6,7,7,8,6,7,7,8,10,12,29,30,19,10,7,7,7,7,7,7,7,7,7] majority_...
import sys import os _PATH = os.path.abspath(".") sys.path.append(_PATH) sys.path.append(os.path.join(_PATH, 'libcombine')) import libcombine def test_import(): test_file = os.path.join(_PATH, 'src/test/test-data/' 'Smith_2004.omex') assert os.path.exists(test_file) ...
""" Define handlers using decorators. Unhandled messages get passed up the inheritance hierarchy. Usage: @Actorize class Hello(Actor): @handle(SomeMessageClass) def somemethod(self, msg, sender): pass """ import inspect from thespian.actors import Actor def Actorize(cls): def receiveMessage...
import sqlite3 as sqlite from typing import Sequence, Mapping from CreatureRogue.data_layer.region import Region from CreatureRogue.data_layer.map_data_tile_type import MapDataTileType class MapDataTile: """ Represents a single tile in a map. """ def __init__(self, tile_type: MapDataTileType, row: in...
import os,sys import numpy as np def getNestedClasses(root,depth,max_depth,neighbor_length=0): new_depth=depth+1 classes={} total_cls=0 super_cls=0 for cls in os.listdir(root): if not os.path.isdir(os.path.join(root,cls)): continue if new_depth<max_depth: pac...
import functools import tensorflow as tf # ============================================================================== # = weight normalization = # ============================================================================== def weight_modulation(weights, ...
import json import os import pickle from sklearn.neural_network import MLPClassifier from tqdm import trange import argparse from usersim import UserSimulator from ft_tools import get_ft_id, get_ft_num fold = 1 parser = argparse.ArgumentParser() parser.add_argument('--path', '-p') args = parser.parse_args() user_sim...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('calendareshop', '0004_auto_20150918_1832'), ] operations = [ migrations.AddField( model_name='projecttype', ...
#!/usr/bin/env python # coding=utf-8 # Stan 2012-04-08 from __future__ import (division, absolute_import, print_function, unicode_literals) import logging from PySide import QtGui from ..core.backwardcompat import * from ..core.items import FileItem from ..core.dump import plain_type from .re...
#!/usr/bin/env python # -*- coding: UTF-8 -*- from pinpoint.common import PinpointCommonPlugin @PinpointCommonPlugin( __name__) def func1(a, b="Wool"): return a + b
def fx(requenst): return "hello world"
#!/usr/bin/env python import os import sys import time import subprocess ARTIFACT = "notify-hook" PROJDIR = os.path.dirname(os.path.realpath(__file__)) BINDIR = os.path.join(PROJDIR, 'bin') BINDIR_32 = os.path.join(BINDIR, '32') BINDIR_64 = os.path.join(BINDIR, '64') # Tweak targets as needed TARGETS = [ #(archi...
from django.http import JsonResponse from rest_framework.decorators import api_view import PyPDF2 from marking.marking_generator import generate_markings @api_view(['GET']) def ping(request): print('simply got pinged to trigger a start') return JsonResponse({}) @api_view(["POST"]) def marking(request): ...
# -*- coding: utf-8 -*- # Generated by Django 1.11.29 on 2021-03-16 07:02 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('mooring', '0156_remove_api_system_id'), ] operations = [ migrations.Create...
""" CSV file reporter function """ from ._report_zengine import _ReporterEngine class _SingleCsv(_ReporterEngine): """ Used to export findings to csv report. Allows alphabetical sorting or raw, write as given """ temp_report: any # TemporaryFile pointer. Assigned in report, used in _write_to_csv ...
from Sort.Example import Example class Merge(Example): def __init__(self) -> None: super().__init__() def sort(self, a): # create aux just once self.aux = [None for i in range(len(a))] self._sort(a, 0, len(a) - 1) def _sort(self, a, lo, hi): if lo >= hi: ...
''' Created on Apr 27, 2018 @author: rafferty ''' import pandas as pd import generate_contextual_data import sys import scipy, importlib, pprint, matplotlib.pyplot as plt, warnings from glmnet_python import glmnet from glmnet_python import glmnetPlot from glmnet_python import glmnetPrint from glmnet_python import glmn...
# 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 pulumi import pulumi.runtime class SecurityConfiguration(pulumi.CustomResource): """ Provides a resource to manage AWS ...
from setuptools import setup setup( name = 'timefn', version = '0.9.0', py_modules = ['timefn'], setup_requires=['setuptools-markdown'], long_description_markdown_filename = 'README.md' )
''' Created on Nov 12, 2016 @author: jeanl ''' import sys import os import sqlite3 as DBI class FlightDB(object): def __init__(self,folder_name): os.chdir( folder_name ) self.folder_name = folder_name self.dbFilename = 'Graph.db' # Delete database from previ...
class Similarity(): def __init__(self, lemma, synset, animal, person, location): self.lemma = lemma self.synset = synset self.animal = animal self.person = person self.location = location
from run_sentqa_f1_65 import * from tensorflow.keras.layers import Dense from os.path import join from tensorflow.keras.layers import Dense import tensorflow.keras.backend as K flags.DEFINE_bool("do_eval", default=False, help="whether to do eval") flags.DEFINE_bool("eval_all_ckpt", default=False, help="Eval all ...
from django.db import models from django.contrib.auth.models import User from course_app.models import Course import numpy as np from datetime import datetime # Create your models here. class Timeslot(models.Model): date_of_slot = models.DateTimeField(null=True); #time_of_slot = models.TimeField(null=True...
# Recursive algorithm def fibonacci_recursive(num): """ Calculate fibonacci number """ if num == 0: return 0 elif num in {1, 2}: return 1 else: return fibonacci_recursive(num-1) + fibonacci_recursive(num - 2) # Iterative algorithm def fibonacci(num): """ Calculate fibonacci ...
from .ProgressBar import ProgressBar from .Iterable import Iterable, iterate
#!/usr/bin/env python # encoding: utf-8 # ---------------------------------------------------------------------------- from django.conf import settings as django_settings from django.core import mail from django_mailer import models, constants, queue_email_message from base import MailerTestCase class TestBackend(Ma...
from celery import Celery import core.celeryconfig as celeryconfig app = Celery() app.config_from_object(celeryconfig)
#!/usr/bin/env python3 import crawler import json import argparse import colorama as co import copy import lzstring html = '''<!DOCTYPE html><html lang=zh_TW><head><title>JudgeGirl Scoreboard</title><meta charset=utf-8><meta name=viewport content="width=device-width,initial-scale=1"><link href=https://cdnjs.cloudflare...
# Generated by Django 3.1.8 on 2021-04-22 14:33 import hashid_field.field from django.db import migrations class Migration(migrations.Migration): dependencies = [("students", "0002_enrollment_uuid")] operations = [ migrations.AlterField( model_name="enrollment", name="id", ...
import numpy as np import matplotlib.pyplot as plt from scipy.stats import multivariate_normal class NaiveBayesFromScratch(): def __init__(self, X, y): self.num_examples, self.num_features = X.shape self.num_classes = len(np.unique(y)) def fit(self, X, y): self.classes_mean =...
# two types of and operator - Binary and Logical # Logical AND operator example x = int(input('Please enter a single digit integer:\n')) if x > 0 and x < 10: print('You entered positive single digit number') elif x < 0 and x > -10: print('You entered negative single digit number') else: print('You did not...
import tweepy from tweepy import Stream from tweepy import StreamListener from tweepy import OAuthHandler import json consumer_key = '' consumer_secret = '' access_token = '' access_secret = '' auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_secret) api = tweepy.API(aut...
# -*- coding: utf-8 -*- # Exercícios by Nick Parlante (CodingBat) # F. make_tags # make_tags('i', 'Yay'), '<i>Yay</i>' # make_tags('i', 'Hello'), '<i>Hello</i>' # make_tags('cite', 'Yay'), '<cite>Yay</cite>' def make_tags(tab, word): return '<%s>%s</%s>' % (tab, word, tab) def test_ex06(): print ('Make Tags') a...
from __future__ import print_function, unicode_literals def add_download_parser(subparsers): subparser = subparsers.add_parser( "download", help="Download the language resources required by the " "snips-nlu library") subparser.add_argument( "resource_name", type=str, ...
# -*- coding: utf-8 -*- # # K2HDKC DBaaS based on Trove # # Copyright 2020 Yahoo Japan Corporation # # K2HDKC DBaaS is a Database as a Service compatible with Trove which # is DBaaS for OpenStack. # Using K2HR3 as backend and incorporating it into Trove to provide # DBaaS functionality. K2HDKC, K2HR3, CHMPX and K2HASH ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' This script generates a map from a physical activity CSV file drawing a polyline of GPS trackpoints. The line colour depends of the chosen column. USAGE: ./map_padata.py [csv_file] [colum_name] If no csv_file is provided, the script opens a file dialog box. ''' __a...
import os # Define constants TODO: Set from commandline args inputFileName = "log.csv" outputFileName = "chart.csv" associationWindow = 100 #In ms # Global vars tsBuffer = list() ledNameBuffer = list() hitMatrix = {} # key is LED name, value is dictionary. # the subdictionary key is the other LED nam...
import cv2 import torch import numpy as np from annolid.segmentation.maskrcnn.model import predict_coco from annolid.annotation.keypoints import save_labels from annolid.annotation.masks import mask_to_polygons from labelme import label_file from labelme.shape import Shape import yaml from pathlib import Path here = Pa...
#!/usr/bin/env python3 import sys from solutionfamily.engine import Engine def main(args=[]): address = "http://192.168.0.9:8080" # address = "http://localhost:8080" engine = Engine.fromurl(address) print(f'Querying Engine Structure...') engine.refresh_structure() # query the data value...
"""Clients Views.""" # Django REST Framework from rest_framework import viewsets, mixins # Serializers from mock_api.clients.api.serializers import ClientModelSerializer, ClientSummarySerializer # Models from mock_api.clients.models import Client class ClientsViewSet(mixins.ListModelMixin, mix...
from __future__ import absolute_import, division, print_function from setuptools import setup, find_packages # Long description will go up on the pypi page with open('README.md') as file: LONG_DESCRIPTION = file.read() # Dependencies. with open('requirements.txt') as f: requirements = f.readlines() INSTALL_RE...
import falcon_kit.mains.calc_cutoff as mod import helpers import json import os.path import pytest def test_help(): try: mod.main(['prog', '--help']) except SystemExit: pass # Note: genome_size==1 makes math easy. def test_calc_cutoff(capsys): partial_capture_fn = os.path.join( ...
import sys from figdate.date import date if len(sys.argv) == 1: date() elif len(sys.argv) == 2: date(sys.argv[1]) elif len(sys.argv) == 3: date(sys.argv[1], sys.argv[2]) else: raise ValueError("ERROR! Wrong arguments count.")
ADDED = 0 UPDATED = 1 DELETED = 2
from django.forms import ModelForm from .models import Compartilhados class CompartilahadoForm(ModelForm): class Meta: model = Compartilhados fields = ['nome', 'email', 'telefone'] exclude = ['quemcompar']
""" * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * - Redistributions in bina...
import json import tempfile from httmock import urlmatch, HTTMock from mass_api_client.resources import DomainSample, IPSample, URISample, FileSample, ExecutableBinarySample from tests.httmock_test_case import HTTMockTestCase from tests.serialization_test_case import SerializationTestCase class DomainSampleTestCase...
import sys, os import pandas as pd from subprocess import call, run, DEVNULL, CalledProcessError, Popen from tqdm import tqdm_notebook, tqdm from glob import glob from joblib import Parallel, delayed import time, tempfile, argparse import programs MAX_ITER = 6000 def eval_file(program, infile, mode, label=True, opt=T...
from django.urls import path from product import views app_name = "product" urlpatterns = [ path("product-creation-page", views.productCreationView, name = "product-creation"), path("product-updation-page/<int:product_id>", views.productUpdationView, name = "product-updation"), path("product-deletion-page/...
#!/usr/bin/env python3 """ Fit a linear model A x = b """ import numpy as np from numpy.linalg import norm import scipy as sp import scipy.sparse try: from cssolve.bregman_func import bregman_func except ImportError: print("Failed to import bregman_func") pass try: from bcs_driver import bcs_driv...
import csv import json from io import StringIO from django.contrib.auth.decorators import login_required, permission_required from django.contrib.postgres.aggregates import StringAgg from django.db import transaction from django.db.models import Count, TextField, Max, Q, Subquery from django.db.models.functions import...
from typing import Any, Dict, List, Optional, Union def remove_empty_dict_values(dic: Dict[str, Any]) -> Dict[str, Any]: """Remove empty values inside a dict.""" return {k: v for k, v in dic.items() if v is not None} def clean_dict_values(dic: Dict[str, Any]) -> Dict[str, Any]: """Convert booleans and l...
from math import cos, sin, ceil peripheral_view = 114 def find_best_seat(width_of_screen, distance_between_screen_and_first_row): distance_from_screen = cot(peripheral_view) * width_of_screen/2 best_possible_seat = (distance_from_screen - distance_between_screen_and_first_row) ...
# example of pix2pix gan for satellite to map image-to-image translation import argparse import os import timeit from numpy import load from numpy import zeros from numpy import ones from numpy.random import randint from tensorflow.keras.optimizers import Adam from keras.initializers import RandomNormal from keras.mode...
from config.urls.configer import ParseConfig from config.urls.settings import ZGZW_CONFIG_FILE class ZgzwConfig(ParseConfig): PATH = ZGZW_CONFIG_FILE
# python-dotenv allows us to create an environment file to store secrets. If # there is no .env it will fail gracefully and fall back to the actual os # environment. try: from dotenv import load_dotenv # type:ignore from pathlib import Path env_path = Path(".") / ".env" load_dotenv(dotenv_path=env_pat...
''' date: 200115 objective: transmit video from rpi to computer general steps: 1. take a picture with webcam, make sure it's transmitting properly ''' import cv2 import numpy as np import sys,argparse,time,os import klib import rospy from std_msgs.msg import String from sensor_msgs.msg import Image from cv_bridge im...
import pandas as pd, os.path as path import numpy as np import os setting_folder=r'./results/' fns=os.listdir(setting_folder) transfer_type = '_gen_feat' #transfer_type = '_None' all_label = [] all_pred = [] for item in fns: if item != 'rd_idx': pred = np.load(setting_folder + item + '/...
# -*- coding: utf-8 -*- FEW_ARG = '''too few arguments, execute the following command for help: tccli help tccli configure help tccli service[cvm] help tccli service[cvm] action[RunInstances] help ''' INVALID_CMD = '''%s is invalid, execute the following command for help: tccli help tccli con...
"""empty message Revision ID: 93905e988491 Revises: 6c4f84fc263e Create Date: 2021-12-19 11:36:36.039856 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = "93905e988491" down_revision = "6c4f84fc263e" branch_labels = None depends_on = None def upgrade(): # #...
from psaw import PushshiftAPI def Download(subreddit="all", count=1000): api = PushshiftAPI() gen = api.search_comments(subreddit=subreddit) retCache = [] while len(retCache) < count: retCache.extend(list(next(gen))) return retCache def DownloadIter(subreddit="all", count=500): api = P...
#!/usr/bin/env python try: from urllib.request import urlopen, Request except ImportError: from urllib2 import urlopen, Request import json import os from bottle import route, run, template from bottle import get, request, response URL_JVB_METRICS="http://localhost:8080/colibri/stats" BIND_IP = '0.0.0.0' BIN...
from argparse import ArgumentParser import json import os import sys import shutil import tempfile from nbconvert.nbconvertapp import NbConvertApp from nbconvert.preprocessors import TagRemovePreprocessor from nbconvert.exporters import TemplateExporter import re PY_CODE_REGEX = re.compile(r'^#@slideshow\s+(.+)$') MAR...
# This configures the core prairiedog code # For pipeline work, the configurations are stored in the upper-level # config.yaml loaded by Snakemake import os K = 11 INPUT_DIRECTORY = 'samples/' MIC_CSV = 'samples/public_mic_class_dataframe.csv' def _input_files(): fls = [os.path.join(INPUT_DIRECTORY, f) ...
from heapq import heappop, heappush import sys input = sys.stdin.buffer.readline INF = 10 ** 9 n, m = map(int, input().split()) road = [tuple(map(int, input().split())) for _ in range(m)] edges = [[] for _ in range(n)] for a, b, c in road: edges[a - 1].append((b - 1, c)) def dijkstra(start): q = [(0, start)...
"""Generate JSON files with dbnames per project Just generates for wikipedias for now""" from urllib2 import urlopen import unicodecsv as csv import json def get_dbnames(wiki_class): """Return dbnames for all wikis in a particular wiki_class, such as 'wikipedias'""" URL = "https://wikistats.wmflabs.org/api.p...
#!/usr/bin/python # -*- coding: utf-8 -*- # vi: ts=4 sw=4 ''' :mod:`SciAnalysis.XSAnalysis.Data` - Base objects for XSAnalysis ================================================ .. module:: SciAnalysis.XSAnalysis :synopsis: Provides base classes for doing analysis of x-ray scattering data .. moduleauthor:: Dr. Kevin G...
from torch.utils.data import Dataset import numpy as np from torchvision.transforms import Pad from torchvision.transforms import Resize from torchvision.transforms import ToTensor from PIL import Image class MnistRotDataset(Dataset): def __init__(self, file, transform=None): self.transform = transform ...
# Miscellaneous items def null(*args, **kwargs): '''A function that takes arguments and does nothing. Useful for discarding a function call.''' pass
"""Setup settings variables to all modules.""" from pydantic import BaseSettings class Settings(BaseSettings): """Class to map directly all needed env variable.""" POSTGRES_USER: str POSTGRES_PASSWORD: str POSTGRES_DB: str DATABASE_URI: str settings = Settings()
from robust.robust import RobustModel from SimPleAC_setup import SimPleAC_setup from robust.signomial_simple_wing.models import simple_ac from robust.simulations.simulate import generate_model_properties from robust.robust_gp_tools import RobustGPTools model, subs = SimPleAC_setup() # the SimPleAC model model_solutio...
from .na_veigar_top import * from .na_veigar_jng import * from .na_veigar_mid import * from .na_veigar_bot import * from .na_veigar_sup import *
#!/usr/bin/python3 ### python script to interact with Complice ### giovanni, Wednesday, April 21, 2021, 5:48 AM ## Tuesday, March 15, 2022, 3:43 PM Python3 version, no dependencies import sys from config import POMOLENGTH, TIMERLENGTH, TOKEN from complice_post import complete_intention def main(): myInput = ...
# The MIT License (MIT) # # Copyright (c) 2018 Kattni Rembor for Adafruit Industries # # 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 ri...
N = input() if '3' in N or int(N) % 3 == 0: print('YES') else: print('NO')
# -*- coding: utf-8 -*- ''' Module for handling Heat stacks. :depends: - python-heatclient>=0.2.3 Python module :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file:: keystone.user: admin keystone.password: verybadpass ...
# -*- coding: utf-8 -*- def handler(event, context): return { 'status': 200, 'body': 'Hello DuEdge!' };
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-02-09 04:49 from __future__ import unicode_literals from django.db import migrations, models import geoposition.fields class Migration(migrations.Migration): dependencies = [ ('jobs', '0023_auto_20160208_2244'), ] operations = [ ...
import numpy as np import pandas as pd #import random import matplotlib.pyplot as plt import seaborn as sns import scipy as sc import scipy.stats as stats from scipy.special import factorial,digamma import numdifftools as nd from scipy.optimize import minimize from joblib import Parallel, delayed #######...
# Code to implement DIS algorithm from tarfile import FIFOTYPE import torch import numpy as np import os from torch.utils.data import Dataset from . import InferenceEngine, Model, TraceMode from .distributions import Empirical def effective_sample_size(w): """Effective sample size of weights `w` is a 1-dimens...
import torch import numpy as np from pathlib import Path from torch.utils.data import Dataset, DataLoader, Sampler from torch.nn.utils.rnn import pad_sequence import src.monitor.logger as logger import random #TODO: remove BUCKET_SIZE=1 ILEN_MIN = 2 ILEN_MAX = 10000 # def _seed_worker(worker_idx): # seed = torch...
# -*- coding: utf-8 -*- # # Copyright (c) 2021-2022, Geoffrey M. Poore # All rights reserved. # # Licensed under the BSD 3-Clause License: # http://opensource.org/licenses/BSD-3-Clause # from __future__ import annotations import base64 import queue import re import time import pathlib try: import jupyter_client...
import classes as cl import formulas as f import math import matplotlib.pyplot as plt import numpy as np import pandas as pd import sys def calculateElement(membrane, initial_draw, initial_feed, Jw_i): #Estimate Jw from inital data [d_h] = membrane.GetDimensions(["d_h"]) [dA] = membrane.GetDimensions(["dAm...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Oct 1 21:17:59 2019 @author: eddy """ from Bob_Alice import * from error_and_compare import * import time #################################################### ''' This will be the heart of the protocol. a function that takes in two keys, (one with a...
#!/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. from __future__ import annotations from dataclasses import dataclass from enum import IntEnum from typing impo...