text
stringlengths
3.07k
12.6k
import click import json import numpy as np import os from jina.executors import BaseExecutor from annoy_indexer import get_annoy_indexer from faiss_indexer import get_faiss_indexer from numpy_indexer import get_numpy_indexer from load_experiment import load_experiment from read_vectors_files import fvecs_read, ivecs...
""" Analyze the result of a hyperparameter sweep. Usage: ``` $ python analyze_hyperparameter_sweep.py path/to/exp_directory ``` """ import argparse import os.path as osp import subprocess import numpy as np from fanova import visualizer, CategoricalHyperparameter from rlkit.misc.fanova_util import get_fanova_info, ...
import warnings import autograd.numpy as np from scipy.fftpack import next_fast_len def autocov(samples, axis=-1): """Compute autocovariance estimates for every lag for the input array. Parameters ---------- samples : `numpy.ndarray(n_chains, n_iters)` An array containing samples Returns ...
# coding: utf-8 import os, sys fastplm_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../")) sys.path.append(fastplm_dir) import torch import argparse import time import numpy as np from tqdm import tqdm from fastplm import FastPLM, FastPLM_S2 from glue_utils import GLUE_TASKS, load_dataset_by_task_n...
import itertools from collections import deque from typing import Any, Iterable, Iterator, MutableSequence, NewType, Sequence from bitstream_iter import bitmasks Bit = NewType('Bit', int) def make_bit(value: Any) -> Bit: """Convert any value to 0 or 1 using truth value testing.""" if value: return ...
# Import Statements used. # Libraries used: Pandas, gensim, nltk, pprint. import pandas as pd import gensim from gensim.utils import simple_preprocess from gensim.parsing.preprocessing import STOPWORDS from nltk.stem import WordNetLemmatizer, SnowballStemmer from nltk.stem.porter import * import numpy as np np.random....
import fnmatch import glob import re import sys import os from optparse import make_option from django.core.management.base import NoArgsCommand, CommandError from django.core.management.commands.makemessages import handle_extensions, _popen, STATUS_OK, process_file, \ write_po_file, is_ignored, Command as Origin...
__version__ = '0.1.3' import logging import os import re import sys import socket from subprocess import check_output import smtplib as _smtp from emailahoy3.exceptions import UnableToVerifyException from emailahoy3.exceptions import HostSystemNotSupportedException DEBUG = False __all__ = ['VerifyEmail', 'verify_e...
''' Written by <NAME> - @sysopfb Free to use, attribute properly. ''' import pefile import sys import re import struct from Crypto.Cipher import DES3 def find_iv(pe): iv = -1 if type(pe) == pefile.PE: t = pe.get_memory_mapped_image() else: t = pe temp = re.findall(r'''\x68...\x00.{1,10}\x68...\x00\x68...\x00\...
#!/usr/bin/python3 # vim: set fileencoding=utf-8 : # Version 1.0.1 import os import sys import multiprocessing from re import sub, escape, match from subprocess import call, Popen, PIPE user = 'root' port = '22' # For sorting os.environ['LC_ALL'] = 'C' def rds(string): """Removes // from string""" return sub...
# transfer_request_finisher.py """Module to implement the TransferRequestFinisher component of the Long Term Archive.""" import asyncio import logging import sys from typing import Any, Dict, Optional, Union from rest_tools.client import RestClient from rest_tools.server import from_environment import wipac_telemetry...
import pandas as pd import arrow def zyzh(infile): data=infile data['org_id']=data['org_id'].str.replace('ZHEJIANG','浙江') data['org_id']=data['org_id'].str.replace('ANHUI','安徽') data['org_id']=data['org_id'].str.replace('BEIJING','北京') data['org_id']=data['org_id'].str.replace('CHONGQING','重庆...
from __future__ import print_function, division, absolute_import import os import pandas as pd from collections import defaultdict import numpy as np from matplotlib import pyplot as plt from scipy.stats import itemfreq import seaborn as sns try: from MulticoreTSNE import MulticoreTSNE as TSNE except ImportError: ...
from django.shortcuts import render import requests, os.path, collections from functools import reduce from datetime import datetime from math import ceil,floor ############################################################################### def round(x,val=10,up=True): if up: return int(ceil(x / float(val)...
# Imports: standard library import os import sys import logging from shutil import copy2 # Imports: third party import pandas as pd import pytest # Imports: first party from ml4c3.recipes import run from ml4c3.arguments import parse_args # pylint: disable=no-member def test_pre_tensorize_explorations(temp_dir): ...
'''Entry point script for the web scraper. Uses Selenium to scrape the UVic academic calendar for course relationships. ''' import logging from functools import partial from multiprocessing import Pool from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.we...
# vim:set et sts=4 sw=4: # # ibus - The Input Bus # # Copyright (c) 2007-2010 <NAME> <<EMAIL>> # Copyright (c) 2007-2010 Red Hat, Inc. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; ei...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # ============================================================================ # PaVal - Parameter validation module # Copyright (C) 2018 by <NAME> # Distributed under the MIT License (https://opensource.org/licenses/MIT) # # GitHub: https://github.com/urbanware-org/paval...
import numpy as np from bottleneck.codec import _DenseBlock, _Transition, FlattenImage, SplitModule, activation, module_size import torch import lamp.modules import torch.nn as nn import lamp.neuralnets class BaseEncoder(lamp.modules.BaseModule): def __init__(self): super(BaseEncoder, self).__init__() ...
# SPDX-License-Identifier: Apache-2.0 # Copyright (C) 2020 ifm electronic gmbh # # THE PROGRAM IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. # """ This viewer is a showcase to see how to write a viewer for nexxT. Note that there are multiple possibilities to view images, and this one might actually not be the best...
#!/usr/bin/env python import logging import argparse import shutil import os import rasterio import warnings import xarray as xr import numpy as np import subprocess import glob warnings.filterwarnings("ignore", category=rasterio.errors.NotGeoreferencedWarning) logging.basicConfig() logger = logging.getLogger(os.path...
import numpy as np from palpation import run_learning def generate_action(current_state, idx, min_vec, max_vec, number_of_actions): if min_vec.shape[0] <= idx: return current_state else: if min_vec[idx] != 0 or max_vec[idx] != 0: if max_vec[idx] - min_vec[idx] == 0: ...
#!/usr/bin/env python import sys import numpy as np from PIL import Image, ImageDraw SENSOR_WIDTH = 2592 SENSOR_HEIGHT = 1944 LENS_V_FOV = 6.8 SCALE_TABLE = [(454.393361, 476.91), (830.678717, 874.01), (620.699249, 653.95), (839.364112, 883.53), (93.786663, 99.7)] # pairs of data, predicted pixel distances vs m...
"""Console script for horcrux.""" import argparse import sys import os from pathlib import Path from . import split from . import combine from .sss import NotEnoughShares, IdMissMatch def required_length(nmin, nmax): class RequiredLength(argparse.Action): def __call__(self, parser, args, values, option_s...
# -*- coding: utf-8 -*- """ Created on Wed Aug 16 16:38:35 2017 @author: racuna """ import matplotlib.pyplot as plt import autograd.numpy as np from mayavi import mlab from numpy import random, cos, sin, sqrt, pi, linspace, deg2rad, meshgrid from mpl_toolkits.mplot3d import Axes3D from vision.camera import Camera fr...
#! /usr/local/bin/python2.7 import argparse import subprocess import os from azure.mgmt.resource import ResourceManagementClient from azure.common.credentials import ServicePrincipalCredentials api_version = "2018-10-01" subscription_holder = "{subscription}" resource_group_holder = "{resourceGroupName}" public_ip_hol...
import threading import time from queue import Queue, Empty import psutil as psutil from selenium import webdriver from selenium.webdriver.chrome.options import Options ''' * ------------------------------------------------- * * Browser_Pool * @discribe : Browser Pool * * @author : <NAME> * @date : 2018...
# Copyright 2020-2021 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agre...
""" libraries needed machine: for uart usage uio: packet buffer struct: serlization _TopicInfo: for topic negotiation already provided in rosserial_msgs """ import machine as m import uio import ustruct as struct from time import sleep, sleep_ms, sleep_us from rosserial_msgs import TopicInfo import sys import o...
#!/usr/bin/env python3 """ A Traveling Salesman Problem solver applied on shredded images. Part of the assignment for Combinatorial optimization class at FEE CTU. Sources: - https://cw.fel.cvut.cz/b192/_media/courses/ko/10_tsp.pdf Usage: main.py [input file] [output file] """ # imports ----------------------...
# Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import re from failure import Failure CHROMIUM_BUG_URL = "http://crbug.com/" def ExtractFirstValue(string, regex): m = re.search(regex, string)...
import numpy as np import tensorflow as tf import tensorflow.contrib.rnn as rnn import tensorflow.contrib.distributions as tfd import tensorflow.contrib.layers as tfl def gausspdf(x, mean, sigma): return tf.exp(-(x - mean)**2 / (2 * sigma**2)) / (tf.sqrt(2.0 * np.pi) * sigma) def _create_rnn_c...
import enum from typing import Any, AsyncGenerator import pytest from httpx import AsyncClient from sqlalchemy import ( Boolean, Column, DateTime, Enum, ForeignKey, Integer, Numeric, String, Text, ) from sqlalchemy.dialects.postgresql import INET, MACADDR, UUID from sqlalchemy.ext.a...
import unittest from collections import namedtuple import numpy as np import pandas as pd import pysubgroup as ps from pysubgroup.tests.DataSets import get_credit_data from pysubgroup.tests.algorithms_testing import TestAlgorithmsBase class TestGeneralisationAwareQf(unittest.TestCase): def setUp(self): sel...
import re from multiprocessing import Process, Queue from typing import Union import discord from discord.ext import commands from lib.connectX import Board as ConnectX from lib.discord_interface import add_choices_message, wait_for_choice, remove_choices from lib.emoji import extract_emoji from lib.emotes import bas...
import torch.nn as nn import torch import math from torchvision.models import * import torch.utils.model_zoo as model_zoo from torchvision.ops import nms, box_iou from retinanet.anchors import Anchors from retinanet import losses import timm import sys sys.path.append("..") from .block_utils import * from config imp...
import cv2 import numpy as np import os def blurflood1(img, imgpath): median = cv2.medianBlur(img, 5) # cv2.imwrite(path + name + '_blur2.jpg', median) h, w, chn = median.shape # h, w, chn = img.shape # seed = (20, 40) seed = (49,60) mask = np.zeros((h + 2, w + 2), np.uint8) floodfla...
"""Table is a storage class that can be used to store information, like one would in a database table, with indexes on the desired "columns.".""" from functools import reduce from typing import ( Dict, Generic, Iterator, Protocol, Sequence, Set, Tuple, Type, TypeVar, runtime_che...
# pins and serial library from machine import UART import utime # object to control de DHB-10 driver class ArloRobot(object): # com packet sending def com(self, packet): for i in packet: self.uart.write(i) self.uart.write(" ") self.uart.write("\r") tinit=utime.ticks_ms() resp='' while (utime.ticks...
import json import math INF = -1 def load_data(path): file = open(path) loaded_data = json.load(file) return loaded_data def all_inequalities_solved_min(point, ab_matrix, c_matrix): eps = 0.001 for i in range(0, len(ab_matrix)): if not ab_matrix[i][0] * point[0] + ab_matrix[i][1] * poin...
# Copyright 2016 Google 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 or ...
import subprocess import random import string import os import threading import time import logging import re import types def local_filename(filename=""): return os.path.join(os.getenv("CFUT_DIR", ".cfut"), filename) # Instantiate a dedicate generator to avoid being dependent on # the global seed which some ex...
""" Given two media conditions, one where we grow and one where we do not, and a set of reactions, test all the reactions to see which is required for growth """ import os import sys import argparse import copy import PyFBA from PyFBA import log_and_message model_data = PyFBA.model_seed.ModelData() __author__ = '<N...
# ---------------------------------------------------------------------------- # Copyright (c) 2020, <NAME>. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # -----------------------------------------------------------------------...
import configparser import random import time from os.path import abspath import requests import yagmail from bs4 import BeautifulSoup USER_AGENT_LIST = [ # Chrome "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36", "Mozilla/5.0 (Windows N...
""" --- Day 5: Hydrothermal Venture --- Part 1 ------ You come across a field of hydrothermal vents on the ocean floor! These vents constantly produce large, opaque clouds, so it would be best to avoid them if possible. They tend to form in lines; the submarine helpfully produces a list of nearby lines of vents (yo...
#coding: utf-8 from __future__ import absolute_import import logging import sys from datetime import datetime from collections import namedtuple import argparse import getpass import socket import functools import json from argparse import Namespace from six import iteritems # 自定义命令行配置参数元组 Arg = namedtuple( '...
from django.db import transaction from ..models import MediaType from ..models import Media from ..models import Project from ..schema import MediaTypeListSchema from ..schema import MediaTypeDetailSchema from ._base_views import BaseListView from ._base_views import BaseDetailView from ._permissions import ProjectFu...
from typing import Any, Dict, Optional, Sequence, Union import torch from pystiche.enc import Encoder, MultiLayerEncoder from pystiche.image import extract_batch_size from pystiche.loss import PerceptualLoss from pystiche.ops import GramOperator, MSEEncodingOperator, MultiLayerEncodingOperator from .utils import uly...
import os import json import boto3 import time import requests import datetime import sys sys.path.append(".") import input_validator LOGZIO_CUSTOM_LISTENER = os.environ["LOGZIO_CUSTOM_LISTENER"] LOGZIO_METRICS_TOKEN = os.environ["LOGZIO_METRICS_TOKEN"] LOGZIO_LOGS_TOKEN = os.environ["LOGZIO_LOGS_TOKEN"] LOGZIO_REGIO...
from collections import defaultdict, Counter, deque from functools import cache from itertools import product, pairwise from multiprocessing import Pool import math import re non_digits = re.compile('[^0-9]+') def sign(a, b, step=1): return int(math.copysign(step, b-a)) def autorange(a,b, step=1): if a == b:re...
""" File xrg.__init__.py This module contains code to help generate the code in pyopenxr. """ # TODO: # * generate docstrings import enum import os import pkg_resources import platform from typing import Generator, List import clang.cindex from clang.cindex import Cursor, CursorKind, Index, TranslationUnit, TypeKi...
""" The following is a modified (and modernized to deal with python3) version of ffprobe.py from https://pypi.org/project/ffprobe/. Unfortunately that project has not been maintained since 2013. It was/is distributed under an MIT license. The following code is based on release 0.5 / Oct 30, 2013 """ import subpr...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import app from absl import flags import os import os.path as osp import numpy as np import torch import torchvision import torch.nn as nn from torch.autograd import Variable import functools from . ...
import math from random import randint from flask import redirect, render_template, jsonify, request, session from bson.objectid import ObjectId from quiz import app from quiz import db #answering the quiz @app.route("/quiz/tests/<test_id>/answers/", methods=["POST"]) def send_answer(test_id): answers = request...
# -*- coding: utf-8 -*- # # rf documentation build configuration file, created by # sphinx-quickstart on Mon Nov 4 11:31:39 2013. # # This file is execfile()d with the current directory set to its containing dir. import sys, os, traceback # If extensions (or modules to document with autodoc) are in another director...
""" Purpose: Sample size Date created: 2020-11-19 Ref: https://www.qualtrics.com/experience-management/research/determine-sample-size/ https://github.com/shawnohare/samplesize/blob/master/samplesize.py Contributor(s): <NAME>. """ try: from secrets import SystemRandom except ModuleNotFoundError: ...
import time from contextlib import contextmanager from typing import ( TYPE_CHECKING, Any, Callable, Iterator, List, Optional, Sequence, Union, ) from django.http import HttpRequest from django.http.response import HttpResponse, HttpResponseBase from django.utils.encoding import force_s...
import json import torch import os from detectron2.structures import BoxMode, RotatedBoxes, pairwise_iou_rotated farea = lambda x: (x[:, 2] - x[:, 0]) * (x[:, 3] - x[:, 1]) def bbox_iou(box1, box2): area1 = farea(box1) area2 = farea(box2) lt = torch.max(box1[:, None, :2], box2[:, :2]) # [N,M,2] ...
from collections import Counter import numpy as np import pandas as pd import keras from keras.models import Sequential, load_model from keras.layers import Dense, Dropout from keras.utils import plot_model from sklearn import metrics from sklearn.preprocessing import MinMaxScaler from pipeline.util import * # Functio...
# Copyright (c) 2019 Western Digital Corporation or its affiliates. import torch import torch.nn as nn import torch.nn.functional as F from rflib.cnn import ConvModule from rfvision.models.builder import NECKS class DetectionBlock(nn.Module): """Detection block in YOLO neck. Let out_channels = n, the De...
""" This script comes from the RTRBM code by <NAME> from http://www.cs.utoronto.ca/~ilya/code/2008/RTRBM.tar """ from numpy import * from scipy import * import scipy.io import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt shape_std = shape def shape(A): if isinstance(A, ndarray): re...
import numpy as np from math import asin, atan, cos, radians, sin, sqrt, tan from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer from scipy.sparse import csr_matrix import pandas as pd import sparse_dot_topn.sparse_dot_topn as ct from typing import Union, Dict # ///////////////////////////////...
from math import atan2, pi from typing import Tuple import numpy as np import plotly.graph_objects as go import plotly.io as pio from plotly.subplots import make_subplots from IMLearn.learners.classifiers import Perceptron, LDA, GaussianNaiveBayes from IMLearn.metrics import accuracy pio.templates.default = "simple_...
"""Tools to interact with the inotify interface """ import array import fcntl import os import attr import trio from enum import Flag from pathlib import Path from typing import Callable, Dict, List, NamedTuple, Type from trio_inotify._inotify_bridge import ( ffi as inotify_ffi, lib as inotify_lib, inotify_...
import sys import pandas as pd import numpy as np import os import pickle from sqlalchemy import create_engine import re import nltk nltk.download(['punkt', 'wordnet', 'averaged_perceptron_tagger']) from sklearn.base import BaseEstimator, TransformerMixin from sklearn.model_selection import train_test_split, GridSear...
#! /usr/bin/python3 """An outline of PSIL's type system and other internal data objects. Author: <NAME> Date: 2015-03-19""" import parse class Namespace: """Represents the type of a namespace, the catchall type.""" def __init__(self, stack=None, parent=None, **kwdarg): if isinstance(stack, Namespace)...
# Tools from podrum.utils.Utils import Utils from podrum.plugin.Plugin import Plugin from podrum.command.CommandManager import CommandManager from podrum.lang.Base import Base from .CommandManagerEdit import CommandManager2 # External Modules from zipfile import ZipFile import json import traceback import time import P...
import numpy as np import acor import logging from .findpeaks import peakdetect def peaks_and_lphs(y, x=None, lookahead=5, return_heights=False): """Returns locations of peaks and corresponding "local peak heights" """ if x is None: x = np.arange(len(y)) maxes, mins = peakdetect(y, x, lookah...
import unit import filecmp, math, os, tempfile from nose.tools import assert_raises, assert_true, assert_greater_equal from synapseclient.multipart_upload import find_parts_to_upload, count_completed_parts, calculate_part_size, get_file_chunk, _upload_chunk from synapseclient.utils import MB, GB, make_bogus_binary_file...
from abc import ABC, abstractmethod from collections import OrderedDict from enum import Enum import cv2 import numpy as np from PIL import Image class Object(object): pass def copyStateDict(state_dict): if list(state_dict.keys())[0].startswith("module"): start_idx = 1 else: start_idx =...
# Generate random HW questions about what happens if you try to do various # strcat operations in the Python command line. Questions test knowledge of # syntax and semantics import random NUM_QUESTIONS = 15 # Bakersfield themed strings BAKO_STRINGS = [ "Bakersfield", "Kern", "Apple", "Camelot", "Carrot", "Ho...
"""Test LRUCache Implementation.""" from time import sleep from lrucache.lru_cache import LRUCache from lrucache.memoize_decorator import memoized_cache lru = LRUCache(maxSize=4) lru.insert_key_value("a", 99) lru["b"] = 202 lru["c"] = 203 lru["d"] = 204 lru["e"] = 205 lru.get_value("a") lru.get("a", None) print(...
#!/usr/bin/env python3 import sys import pysm import random import enum import heapq from heapdict import heapdict class Vertex: def __init__(self, note=-1, tick=None): self.note = note self.ticks = [] if tick is not None: self.ticks.append(tick) self._color = None ...
import menpo import menpo3d.io as mio import numpy as np from menpo.image import Image from menpo.shape import ColouredTriMesh, PointCloud, TexturedTriMesh, TriMesh from numpy.testing import assert_allclose # ground truth bunny landmarks from pytest import raises bunny_leye = np.array( [[-0.0907334573249135, 0.13...
import json import sys import h2o import forest_config import data_set_handler import scikit_wrapper import numpy as np import result_log import html_output from datetime import datetime BIN_FOLDER = 'bin/' DEPENDENCIES_FOLDER = 'dependencies/' IMPLEMENTATIONS = {'h2o': h2o.H2OWrapper, 'scikit': sc...
# coding= utf-8 import os import pandas as pd from datetime import datetime from pip._vendor import chardet from src.chart.draw import FmiChart from src.chart.draw import FmiChart from src.analysis.nmea import GNGGAFrame from src.report.PpWord import PPReporter from pandas.plotting import register_matplotlib_converters...
import csv from pyg2plot import Plot import urllib.request import urllib.parse import json import os tarCity = [["010", "Beijing"]] APIKEY = "44cdd042045af4570f95e47e4484b01a" KEYWORD = "自行车专卖店" KEYDEC = urllib.parse.quote(KEYWORD) CSVHEADERS = ["id", "pname", "cityname", "adname", "address", "category", "location"] B...
#!/usr/bin/python # -*- coding: utf-8 -*- try: from metal_python.api import NetworkApi from metal_python import models from metal_python import rest METAL_PYTHON_AVAILABLE = True except ImportError: METAL_PYTHON_AVAILABLE = False from ansible.module_utils.basic import AnsibleModule from ansible.m...
# voom_mode_inverseAtx.py # Last Modified: 2013-11-07 # VOoM -- Vim two-pane outliner, plugin for Python-enabled Vim 7.x # Website: http://www.vim.org/scripts/script.php?script_id=2657 # Author: <NAME> (<EMAIL> DOT <EMAIL> AT g<EMAIL> DOT <EMAIL>) # License: CC0, see http://creativecommons.org/publicdomain/zero/1.0/ "...
""" Test a Q Learner in a navigation problem. (c) 2015 <NAME> """ import numpy as np import random as rand import time from recommender.agent import Agent aleas = True # print out the map def printmap(data): print("-"*data.shape[1]*3) for row in range(0, data.shape[0]): line_str = "" for col...
""" Problem Class for a diffusion problem that populates and solves itself """ import numpy as np from . import node from . import matrices from . import plotting def _get_boundary_condition(bc_type): """Turn full boundary condition names into one boundary condition key Parameter: ---------- :type bc_type: st...
# # General-purpose Photovoltaic Device Model - a drift diffusion base/Shockley-Read-Hall # model for 1st, 2nd and 3rd generation solar cells. # Copyright (C) 2008-2022 <NAME> r.c.i.mackenzie at googlemail.com # # https://www.gpvdm.com # # This program is free software; you can redistribute it and/or m...
import torch from torch.nn import Sequential, Linear, ReLU, Sigmoid, Tanh, Dropout, Upsample import torch.nn.functional as F import torch.nn as nn from torch_geometric.nn import NNConv from torch_geometric.nn import GCNConv from torch_geometric.nn import BatchNorm import numpy as np from torch_geometric.data import Dat...
import io import traceback import shutil from typing import List, Dict import os import tempfile from loguru import logger from wand.image import Image def pdf_data_to_thumbnails( pdf_data: bytes, pages: List[int], width_max: int, height_max: int, *, use_last_resort: bool = True ) -> Dict[int...
# import tensorflow as tf import torch import torch.nn.functional as F class diag_offdiag_maxpool(torch.nn.Module): """diag_offdiag_maxpool""" def __init__(self): super(diag_offdiag_maxpool, self).__init__() # self.ones = torch.nn.Parameter(torch.ones(1)) def forward(self, inputs): # ...
"""MCMC utilities for the UC Irvine course on 'ML & Statistics for Physicists' """ import functools import inspect import numpy as np import pandas as pd import emcee def wrap(func, **kwargs): """Prepare an arbitrary function to use with emcee sampling. Emcee expects its parameters in a single list, but i...
# MIT License # # Copyright (c) 2021 Playtika Ltd. # # 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 use, copy, modify, mer...
#!/usr/bin/env python3 """ Takes a corpus of raw text as input and calculates comprehensive Markov probabilities. Which then feeds into a function that solicits a seed word and a 'sentence length' parameter in order to generate probabilistic text """ ####################################################################...
import numpy as np import matplotlib.pyplot as plt import pandas as pd from filterpy.kalman import KalmanFilter from filterpy.common import Q_discrete_white_noise # Saves figures to output folder def savefig(name): plt.xlabel('Vreme') plt.savefig('./out/' + name + '.png') # Region to watch REGION = 'Serbia' ...
""" """ # Full imports import json import os # Partial imports from datetime import datetime, timedelta from urllib.parse import urlparse, urljoin # Imports from modules from cornflow_client import CornFlow, CornFlowApiError # TODO: convert everything to an object that encapsulates everything # to make it clear ...
""" Facilities for registering and listing :term:`indexable sources <indexable source>`. Indexable sources are generic and don’t necessarily need to contain bibliographic data. """ import functools import hashlib from dataclasses import dataclass from typing import Callable, Union, List, Tuple, Dict, TypedDict from os...
import os import json import argparse import glob from sklearn.neighbors import KNeighborsClassifier import pandas as pd import numpy as np from utils.utils import read_features, get_vectors ACTOR_ID_PREFIX = "momaf:elonet_henkilo_" ACTORS_PATH = "./actors.csv" ACTOR_IMAGES_PATH = "./actor_images.csv" ACTOR_EMBEDDI...
import hashlib import socks import os import re import asyncio import aiohttp from telethon import TelegramClient from telethon.tl.functions.messages import GetBotCallbackAnswerRequest from aiohttp_socks import ProxyType, ProxyConnector, ChainProxyConnector REG_CODE_TOKEN = r'data-code=\"(?P<code>[^\"]+)\".+token=\"...
#!/usr/bin/env python # -*- coding: UTF-8 -*- ############################## # Create Time: 20170427 # Author: liuyang # Email: <EMAIL> # Content: Flow Object ############################## from uiautomator.adb import Adb import configparser import time import subprocess import os def OpenAPP(ap...
from collections import deque import sys class Node: def __init__(self,value): self.value = value self.left = None self.right = None def get_left_child(self): return self.left def get_right_child(self): return self.right def has_left_child(self): ...
"""Converts Sam's mevm state and json dict encoder into an MEVM class object and resaves the state into a single hdf5. """ import argparse import glob import json import os import exputils from hwr_novelty.models.mevm import MEVM def script_args(parser): parser.add_argument( 'mevm_state_path', h...
import numbers from src import lexer BINARY_OPERATORS = ["+", "-", "*", "/"] OPS_RANKING = {"(": 1, ")": 1, "/": 2, "*": 2, "+": 3, "-": 3} OPS_ASSOSIATIVITY = {"+": "l", "-": "l", "*": "l", "/": "l"} def is_function(string): return False def binary_operator(lhs, rhs, op): """ Evaluates and acts on d...
# -*- coding: utf-8 -*- """Functions to be called by workflow""" import os from datetime import datetime from .exceptions import CoincError, ConfigError from .query import Query from .utils import (init_workflow, load_currencies, refresh_rates, refresh_currencies, generate_list_items) __all__ = [ ...
# -*- coding: utf-8 -*- """ dialoguss.core ============== """ import logging import os import os.path import re import sys import yaml import random import requests from abc import ABCMeta, abstractmethod from argparse import ArgumentParser SID_MIN = 1000000 SID_MAX = 10000000 LOGGER = logging.getLogger(__name__) ...