text
stringlengths
3.07k
22.1k
import torch import random import numpy as np import os import pandas as pd import config import cv2 import matplotlib.pyplot as plt from dataset import ImageFolder from torch.utils.data import DataLoader from sklearn.model_selection import train_test_split import albumentations as A from albumentations.py...
import os import sys import gc from collections import defaultdict from numpy.lib.function_base import _DIMENSION_NAME from src.api import target_class_lib as tc project_directory = '/srv/target' if os.path.join(project_directory, 'checkout') not in sys.path: sys.path.append(os.path.join(project_directory, 'che...
from flask import Flask, render_template, request, Response import json import void_scribe import os from Void_Logger import Void_Log_Info, Void_Log_Debug app = Flask(__name__) pathNameTypes = "Enviorment/data/nametypes" pathPromptTypes = "Enviorment/data/PromptTemplates" dataFilesPath = os.path.abspath(pathNameTypes)...
""" Functions for reading and writing data. """ import re as _re import json as _json from .fixation import FixationSequence as _FixationSequence from .text import TextBlock as _TextBlock def read(file_path): """ Read in a JSON file. `eyekit.fixation.FixationSequence` and `eyekit.text.TextBlock` obje...
import argparse import itertools import os import pickle import sys import datetime import string import math import random import json import shutil import numpy as np import tensorflow as tf from paragraph_batch_utils import batch_data_generator, pad_paragraphs_to_seq_length def randomword(length): """ ...
import abc import dataclasses import enum import importlib import pkg_resources import types import typing as t import typing_extensions as te import weakref import nr.preconditions as preconditions from nr.stream import Stream from nr.pylang.utils.funcdef import except_format from databind.core.annotations.base imp...
# Copyright (c) 2021 <NAME>. All Rights Reserved. from maya.app.general.mayaMixin import MayaQWidgetDockableMixin import maya.OpenMaya as om import pymel.core as pm import piper_config as pcfg import piper.core.util as pcu from piper.ui.widget import manager from piper.ui.switcher import Switcher from piper.mayapy.p...
from errors import * from nodes import * from ifelse import * from loop import * from func import * from trycatch import * from strquot import unquote STATEMENTS = set('func labda local if elseif else while for try catch repeat'.split()) STATEMENT_CLASS = {'func': FuncStatement, 'labda': LabdaStatement, 'local': Lo...
# import os # import sys # sys.path.append(os.getcwd()) from ltp import LTP import json from math import log2 from operator import itemgetter from algorithm.config import * class IterateComments: def __init__(self, raw_comments): self.iter_raw = iter(raw_comments.items()) def iter_loads_comments(sel...
"""NLU audio module""" import asyncio from binascii import unhexlify import os import wave import audioop import speex import pyaudio from pocketsphinx.pocketsphinx import Decoder from tuxeatpi.nlu.common import Recorder, WebsocketConnection, NLUBase # SILENT DETECTION # TODO adjust it FS_NB_CHUNK = 100 NB_CHUNK =...
import pytest from mapreader import classifier from mapreader import loadAnnotations from mapreader import patchTorchDataset import numpy as np import torch from torch import nn import torchvision from torchvision import transforms from torchvision import models PATH2IMAGES = "./examples/non-geospatial/classificati...
# name='sopel_modules.idlerpg', # version='0.1.0', # description='A rewrite of the original IdleRPG to work as a module for Sopel. It incorporates some of the features of Shocky\'s IdleRPG system, though is much more in-depth.', # long_description=readme + '\n\n' + history, # author='<NAME>', # ...
# This is a anti-pattern to disable warnings # I'm using just for a simplification import warnings warnings.filterwarnings("ignore") import matplotlib.pyplot as plt import numpy as np import os import pandas as pd import pyLDAvis.sklearn import re import seaborn as sns import spacy import string from collections impor...
#!/usr/bin/env python3 from pathlib import Path import argparse import re import shutil import subprocess import oyaml as yaml def get_template_config_dict(config_yaml_path): with open(config_yaml_path) as config_yaml_file: return yaml.safe_load(config_yaml_file) def launch(mutation, wt_str, queue, num_...
from dateutil.parser import isoparse from flask import Blueprint, jsonify, abort, make_response, request from flask_cors import cross_origin from config import Config from app import db from app.models.webnews import WebNewsCategory, WebNews, WebNewsKeyword from app.models.auth import Auth from datetime import datetime...
# -*- coding: utf-8 -*- # # ensemble.py # # This module is part of dstools. # """ Tools for combining base estimators to build a learning algorithm with improved robustness over a single estimator. """ __author__ = '<NAME>' __email__ = '<EMAIL>' import numpy as np from scipy import sparse from dstools.base import ...
# -*- coding: utf-8 -*- """ Copyright 2016 <NAME>. This file is part of BicingBot. 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 ...
import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt # for overlaying images: from matplotlib import offsetbox from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.axes_grid1 import make_axes_locatable ## Plotting functions ------------------------------------------------------ def plot2...
import glob import os.path import random import numpy as np import tensorflow as tf from tensorflow.python.platform import gfile BOTTLENECK_TENSOR_SIZE = 2048 BOTTLENECK_TENSOR_NAME = 'pool_3/_reshape:0' JPEG_DATA_TENSOR_NAME = 'DecodeJpeg/contents:0' MODEL_DIR = './inception_dec_2015' MODEL_FIL...
import sys sys.path.extend(["../../", "../", "./"]) import warnings warnings.filterwarnings("ignore") from sklearn.preprocessing import MinMaxScaler import gensim from sklearn.metrics import classification_report from sklearn.svm import SVC from sklearn.model_selection import GridSearchCV from sklearn import...
#!/usr/bin/python # -*- coding: UTF-8 -*- # Introduction: codonPY main script # Created by galaxy on 17-3-7 10:08 pm import logging.handlers import os import sys import time import traceback from argparse import ArgumentParser from Bio import SeqIO from src.calculate_relative_adaptiveness import calculate_wi from src....
from __future__ import print_function from __future__ import division from builtins import range from past.utils import old_div import random import json import sys import os import enchant import pyocr import pyocr.builders from PIL import Image, ImageDraw, ImageFont path = "images/img8.jpg" # characters to recogni...
#! python3 from tkinter import * from tkinter import ttk import tkinter as tk from tkinter.font import Font import tkinter.scrolledtext as tkst ########## # Window # ########## win = tk.Tk() win.title("Cuttings Description BETA") # Icon win.wm_iconbitmap("CDicon.ico") # String Varaible for ra...
# -*- coding: utf-8 -*- # Copyright 2017-2019 ControlScan, Inc. # # This file is part of Cyphon Engine. # # Cyphon Engine 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, version 3 of the License. # # Cyphon En...
import os os.environ['TF_CPP_MIN_LOG_LEVEL']='1' from os import listdir import sys import time import argparse import tools.ops import subprocess import numpy as np import tensorflow as tf import scipy.misc as sm from models.mfb_net_cross import * from tools.utilities import * from tools.ops import * parser = argpa...
import os, io, gzip, types, re import boto3, botocore from collections import OrderedDict from io import TextIOWrapper from gzip import GzipFile from datetime import datetime __DATE_COL = 0 __TIME_COL = 1 __REQID_COL = 14 def __version(fd): line = next(iter(fd)) split = line.rstrip().split(' ') if len(s...
import argparse from pathlib import Path from PIL import Image import cv2 import numpy as np import pandas as pd import torch import torch.optim as optim import matplotlib.pyplot as plt from utils import Options, overlap_ratio from models.mdnet import MDNet, BCELoss from models.extractor import SampleGenerator, Regio...
from collections import OrderedDict as ODict from typing import IO, Sequence, Tuple, Union, List, Dict from itertools import repeat import librosa import numpy as np import matplotlib.pyplot as plt import matplotlib.ticker as tckr from numpy import ndarray import scipy.signal as scsig from hparams import hp import ge...
#python3 ###### imports import sqlite3 as sql import os import pandas as pd import numpy as np from datetime import date ###### Define functions def crshmidt_nodes(): """Prepares stats for crshmidt user """ d1 = date(2017, 4, 1) # when OSM was founded d0 = date(2004, 8, 9) delta = d1 - d0 nodes = 1201241 node...
#! /usr/bin/env python """Run a YOLO_v2 style detection model on test images.""" import argparse import colorsys import imghdr import os import random import time,cv2 import numpy as np from keras import backend as K from keras.models import load_model from PIL import Image, ImageDraw, ImageFont from yad2k.models.kera...
import argparse from heapq import nlargest from pprint import pformat from igraph import Graph, VertexClustering from scripts.utils.utils import init_logger, load_communities, load_titles, save_data_to_json from scripts.utils.graph import log_igraph logger = init_logger() def degree(comm_subgraph): retur...
#%% #%matplotlib inline #%% import tensorflow as tf #%% sess = tf.InteractiveSession() #%% import keras.backend as K K.set_image_data_format("channels_first") import keras import numpy as np from keras.layers import Dense, Dropout, Conv2D, MaxPooling2D from keras.layers import Flatten, Lambda, BatchNormalization ...
""" """ import os import re import csv import ssl from tornado import web, ioloop, httpserver, websocket MOD_ROOT, _ = os.path.split(os.path.abspath(__file__)) STATIC_ROOT = MOD_ROOT + "/static" # users can change this module value SECURITY_ROOT = MOD_ROOT + "/security" # user can change this module value ...
# Copyright (c) 2019, <NAME> # # All rights reserved. # # The MIT License (MIT) # # 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 right...
""" eval_attachment.py ====================== This modest python script will evaluate the attachment of software attributes to the right software names, creating complete software entities. The software-mentions service must first be started, the config.json file being updated accordingly if neces...
# coding=utf-8 # Copyright 2022 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...
import collections def inv(n, q): """div on PN modulo a/b mod q as a * inv(b, q) mod q >>> assert n * inv(n, q) % q == 1 """ # n*inv % q = 1 => n*inv = q*m + 1 => n*inv + q*-m = 1 # => egcd(n, q) = (inv, -m, 1) => inv = egcd(n, q)[0] (mod q) return egcd(n, q)[0] % q #[ref] naive implementa...
from .Wavefunction import Wavefunction from .LinAlg import expm, get_basis import numba import numpy as np from scipy.fft import ifft2, fft2 class Nucleus(Wavefunction): # Upon calling wilsonLine() or adjointWilsonLine(), these are properly defined _wilsonLine = None _adjointWilsonLine = None # Som...
import os, torch import numpy as np from torch import nn from torch import functional as F import tifffile from tqdm import tqdm class BCEFocalLoss(torch.nn.Module): def __init__(self, gamma=2, alpha=0.25, reduction='elementwise_mean'): super().__init__() self.gamma = gamma self....
import argparse import json import sys import traceback from camundatools.definition import Definition from camundatools.instance import Instance from camundatools.task import Task class InstanceCommand: args: argparse.Namespace instance: Instance definition: Definition task: Task def __init__(...
# coding=utf-8 """apyfal.__main__ tests""" from collections import namedtuple import pytest def test_cached_accelerator(tmpdir): """Tests _cached_accelerator""" from apyfal.__main__ import _cached_accelerator import apyfal.__main__ as main name = 'accelerator' parameters = {'param1': 1, 'param2'...
import re import itertools from .dict_changed import DictChanged class UnicodeMap(DictChanged): '''Represents PDF "ToUnicode" optional data structure that controls character encoding''' NotParsed = object() #: for internal use def __init__(self, text): self._text = text super().__init__(...
# Main file of Babylon Tower Solver # # Tecnológico de Costa Rica # Computing Engineering School # Course # Artificial Intelligence # Teacher <NAME> # Programmers # <NAME> @ediloaz # <NAME> # September, 2018 # import os # For center the window import ctypes # For center the win...
import os file_directory = os.getcwd() def root_run(file_directory): pathway_list = [] for root, dirs, csv_files in os.walk("%s"%(file_directory)): for csv_file in csv_files: if csv_file.endswith(".txt"): #print(os.path.join(root, csv_file)) active_csv_file = csv_file ...
from flask_sqlalchemy import SQLAlchemy from sqlalchemy import Integer, ForeignKey db = SQLAlchemy() class Article(db.Model): __tablename__ = "articles" id = db.Column(db.Integer, primary_key=True) article_id = db.Column(db.Integer()) published_date = db.Column(db.DateTime()) title = db.Column(d...
import glob from hail.expr.functions import log from pyspark.sql import SQLContext from functools import reduce from pyspark.sql.functions import lit, overlay from hail import Table import subprocess from .decorators import * from .common import * from .logutil import * from .shared import Shared import hail as hl im...
from gym_torcs import TorcsEnv import numpy as np import random import argparse from keras.models import model_from_json, Model from keras.models import Sequential from keras.layers.core import Dense, Dropout, Activation, Flatten from keras.optimizers import Adam import tensorflow as tf from keras.engine.training impor...
import aio_pika import asyncio import logging import json import os from tornado.httpclient import AsyncHTTPClient from tornado.iostream import StreamClosedError from tornado.web import HTTPError, RequestHandler from urllib.parse import urlencode import zipfile from datamart_core.common import log_future from datamart...
from abc import ABC, abstractmethod from pydeation.constants import WHITE import c4d class KeyFrame: """a keyframe object is responsible for creating a keyframe in c4d for a single target for a single description id with a specific value and time""" def __init__(self, target, desc_id, value=None, time=No...
import torch import torch.nn.functional as F import numpy as np import matplotlib.pyplot as plt from sklearn.pipeline import Pipeline from SVC_Utils import * from sklearn.metrics import roc_curve, auc # determine device to run network on (runs on gpu if available) device = torch.device("cuda:0" if torch.cuda.is_avail...
# -*- coding: utf-8 -*- # vim: set ft=python ts=4 sw=4 expandtab: """ Run a simulation to see how well different character input sources behave. """ from __future__ import annotations # so we can return a type from one of its own methods import csv import statistics from itertools import combinations_with_replaceme...
import sys from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, QLabel from PyQt5.QtGui import QPainter, QColor, QPen, QPixmap from PyQt5.QtGui import QIcon from PyQt5.QtCore import Qt, QObject, QRunnable, QMetaObject, QSocketNotifier, \ pyqtSlot, pyqtSignal, QSettings from . import bagl from .display ...
import numpy as np import consts import utils from models import BertFromMiddle import torch from tqdm import tqdm as progressbar from dataHandler import DataHandler from torch.utils.data.dataloader import DataLoader from pathlib import Path from transformers import BertTokenizer, BertForMaskedLM import time from argp...
import numpy as np WALL = '%' START = 'P' DOT = '.' SPACE = ' ' PATHCHAR = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' class MazeSearchNode: def __init__(self, state, parent=None, cost=0): self.state = state self.parent = parent self.cost = cost self.ate = No...
from collections import namedtuple from xml.dom import minidom BOOKMARK_COLOR_NONE = "-1" BOOKMARK_COLOR_BLUE = "0" BOOKMARK_COLOR_GREEN = "1" BOOKMARK_COLOR_YELLOW = "2" BOOKMARK_COLOR_ORANGE = "3" BOOKMARK_COLOR_RED = "4" LINK_STYLE_NORMAL = "0" LINK_STYLE_DASHED = "1" LINK_STYLE_DOTTED = "2" LINK_STYLE_DASHDOT = "...
import os import sys import tarfile from shutil import rmtree from tempfile import mkdtemp from galaxy import model from galaxy.exceptions import MalformedContents from galaxy.tools.imp_exp import JobImportHistoryArchiveWrapper, unpack_tar_gz_archive unit_root = os.path.abspath( os.path.join( os.path.dirname( __file_...
"""This module contains everything related to debugging.""" import functools import pdb import sys import click from _pytask.config import hookimpl from _pytask.console import console from _pytask.nodes import PythonFunctionTask from _pytask.outcomes import Exit from _pytask.shared import convert_truthy_or_falsy_to_bo...
import json import logging from functools import wraps from urllib.parse import parse_qs, urlparse from oauthlib.oauth2 import OAuth2Error from pyramid.httpexceptions import HTTPFound, exception_response from pyramid.view import view_config, view_defaults from h import models from h.services.oauth import DEFAULT_SCOP...
"""Helper for listing upcoming (and past) projectum milestones. Projecta are small bite-sized project quanta that typically will result in one manuscript. """ import datetime as dt import dateutil.parser as date_parser from dateutil.relativedelta import relativedelta import sys from regolith.dates import get_du...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Setup script for IPython. Under Posix environments it works like a typical setup.py script. Under Windows, the command sdist is not supported, since IPython requires utilities which are not available under Windows.""" #--------------------------------------------------...
""" Contains the parent classes Device and DeviceCollection""" # devices.py # Mission Pinball Framework # Written by <NAME> & <NAME> # Released under the MIT License. (See license info at the end of this file.) # Documentation and more info at http://missionpinball.com/framework import logging import time from collec...
""" #Trains a ResNet on the CIFAR10 dataset. """ from __future__ import print_function from tensorflow import keras from keras.layers import Dense, Conv2D, BatchNormalization, Activation from keras.layers import AveragePooling2D, Input, Flatten from tensorflow.keras.optimizers import Adam from keras.callbacks import ...
# Copyright (c) 2011, <NAME>, Inc. # All rights reserved. # # 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 ...
from baseline_data import IMDB_Dataset, SST2_Dataset, AGNEWS_Dataset import torch from torch.utils.data import DataLoader from torch import nn, optim from baseline_model import Baseline_Bert, Baseline_LSTM, Baseline_TextCNN from baseline_tools import logging, get_time from baseline_config import Baseline_Config, config...
from os import path from sys import modules from fabric.context_managers import cd from fabric.contrib.files import append, exists, upload_template from fabric.operations import run, sudo from offregister_fab_utils.apt import apt_depends from offregister_fab_utils.fs import cmd_avail from pkg_resources import resource...
#!/usr/bin/env python3 import os import re import sys import subprocess TAB = " " * 4 ##==================== REFERENCE ===========================================## # # https://github.com/grpc/grpc/blob/master/bazel/test/python_test_repo/BUILD # ##==================== HEADER TEMPLATE ================================...
#!/usr/bin/env python3 import time from matrix_client.client import MatrixClient from matrix_client.api import MatrixRequestError from requests.exceptions import ConnectionError, Timeout import argparse import random from configparser import ConfigParser import re import traceback import urllib.parse import logging imp...
""" get_spatial_meshgrid and warp functions are extracted from https://github.com/NVlabs/PWC-Net/blob/master/PyTorch/models/PWCNet.py#L139 """ import torch def get_spatial_meshgrid(x: torch.Tensor, scale=False): """ Get grid which contains spatial coordinates at each pixel location Args: x: image...
# Copyright 2019 Xanadu Quantum Technologies 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 agre...
#!/usr/bin/env python """md2po command line interface. See :ref:`md2po CLI<cli:md2po>`. """ import argparse import sys from mdpo.cli import ( CLOSE_QUOTE_CHAR, OPEN_QUOTE_CHAR, add_command_alias_argument, add_common_cli_first_arguments, add_debug_option, add_encoding_arguments, add_exten...
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
import zlib from hazelcast.serialization import ( BYTE_SIZE_IN_BYTES, CHAR_SIZE_IN_BYTES, BE_UINT16, DOUBLE_SIZE_IN_BYTES, BE_DOUBLE, INT_SIZE_IN_BYTES, BE_INT, LONG_SIZE_IN_BYTES, BE_LONG, BE_UINT8, ) _MASK_PREFIX = 1 _MASK_METRIC = 1 << 1 _MASK_DISCRIMINATOR = 1 << 2 _MASK_DI...
import gym from ray.rllib.models.modelv2 import ModelV2 from ray.rllib.models.torch.torch_modelv2 import TorchModelV2 from ray.rllib.utils import try_import_torch from ray.rllib.utils.annotations import override torch, nn = try_import_torch() class OnlineLinearRegression(nn.Module): def __init__(self, feature_d...
import matplotlib.pyplot as plt import numpy import seaborn import tensorflow as tf import muzero.models as models from muzero.self_play import MCTS, Node, SelfPlay class DiagnoseModel: """ Tools to understand the learned model. Args: weights: weights for the model to diagnose. config: ...
from env_common import get_screen from common import select_action_policy import torch import torch.nn as nn import torch.nn.functional as F from torch.optim import RMSprop from itertools import count import numpy as np import gym import visdom device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # ...
""" Brief ===== This module is not part of the public API. It contains encoding and decoding functionality which is exclusively used by `io.write` and `io.read`. It enables storing and transmitting Pyfar- and Numpy-objects without using the unsafe pickle protocoll. Design and Function =================== The `_encod...
import logging from typing import Dict, Type, Union import pytorch_lightning as pl import torch import torch.nn.functional as F from torch.tensor import Tensor from transformers import PreTrainedModel, PreTrainedTokenizer from transformers.tokenization_utils_base import BatchEncoding from melbe.collections.pipelines....
#!/usr/bin/python3 # Additionally format C++ code for further entropy reduction # Assumes clang-format already run # Does not work for all possible C++ programs # Test carefully before reusing in other projects! import argparse import os import re parser = argparse.ArgumentParser(description="Additionally format C++ ...
# alias to keep the 'bytecode' variable free import bytecode as _bytecode from bytecode.concrete import ConcreteInstr from bytecode.instr import Label, SetLineno, Instr class BasicBlock(_bytecode._InstrList): def __init__(self, instructions=None): # a BasicBlock object, or None self.next_block = N...
from app import app from flask import abort, \ redirect, \ render_template, \ request, \ session, \ url_for from flask.ext.login import current_user, \ login_user, \ login_re...
#pylint: disable=import-error from six.moves import queue import os, time, threading, socket, signal, shutil, glob #pylint: disable=import-error from distutils.spawn import find_executable import logging import xml.etree.ElementTree as xmlet import CIME.utils from CIME.utils import expect, Timeout, run_cmd_no_fail fro...
""" .. module: lemur.certificates.models :platform: Unix :copyright: (c) 2018 by Netflix Inc., see AUTHORS for more :license: Apache, see LICENSE for more details. .. moduleauthor:: <NAME> <<EMAIL>> """ from datetime import timedelta import arrow from cryptography import x509 from cryptography.hazmat.primi...
import logging from django.db.models import Exists, OuterRef, Q from django.db.models.functions import Coalesce from django.utils.timezone import now from rest_framework import serializers, status from rest_framework.exceptions import ValidationError from rest_framework.response import Response from rest_framework.vie...
#by <NAME>, www.bitpilot.de, 19.2.2021 from machine import LCD from machine import Pin, Map, ADC import random from time import sleep BLACK = (0, 0, 0) WHITE = (255, 255, 255) GRAY = (128, 128, 128) colors = [ (0, 0, 0), (20, 255, 62), (255, 0, 0), (10, 48, 255), (10, 246, 255), ...
import argparse import tqdm import random import math import os import pandas as pd import sklearn import timeit import numpy as np import struct import torch import torch.nn as nn import torch.optim as optim from torch.autograd import Variable import pickle import torch import pandas as pd import torchvision import ...
import pytest import shutil from common.version import DigitDotVersion from indy_common.constants import APP_NAME from indy_common.version import src_version_cls from indy_node.utils.node_control_utils import ( NodeControlUtil, ShellError, DebianVersion ) # TODO # - conditionally skip all tests for non-debian sy...
#%% import argparse import torch import numpy as np from dataloader import * from model import Model from loss import * import os import random from pathlib import Path import wandb import time from utils.pyart import bnum2ls # fix random seeds for reproducibility SEED = 1 torch.manual_seed(SEED) torch.cuda.manual_see...
# Script use to collect incumbents_v5.pkl # Uses incumbents_v4.pkl and reorders the list in a semi-deterministic manner import pickle import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy.spatial import distance_matrix # from scipy.spatial.distance import euclidean from scipy.spatial import...
"""Useful functions for working with dicts.""" from collections import defaultdict ## clojure def merge(*dicts): """Returns a dict that consists of the rest of the dicts merged with the first. If a key occurs in more than one map, the value from the latter (left-to-right) will be the value in the result."...
from __future__ import print_function, unicode_literals import tensorflow as tf import numpy as np import scipy.misc import matplotlib.pyplot as plt import matplotlib.image as mpimg import os from mpl_toolkits.mplot3d import Axes3D import argparse import cv2 import operator import pickle from nets.ColorHandPose3DNetw...
import copy import logging, os import gettext as _gettext from gettext import NullTranslations, GNUTranslations import warnings import tg from tg.util import lazify from tg._compat import PY3, string_type log = logging.getLogger(__name__) class LanguageError(Exception): """Exception raised when a problem occurs ...
import inspect import pytest from prefect.core import Flow, Task from prefect.engine.flow_runner import FlowRunner from prefect.engine.signals import PAUSE from prefect.engine.state import Paused, Resume from prefect.utilities import tasks class TestTaskDecorator: def test_task_decorator_can_be_used_without_cal...
# coding=utf-8 import json from uuid import uuid4 import falcon import requests from ..config import COINBASE_ADDRESS from ..config import DECIMALS from ..config import REFERRAL_DUMMY from ..db import db from ..eth import vpn_service_manager from ..helpers import eth_helper def get_vpns_list(vpn_type): _list = ...
from xnat_dashboards.data_cleaning import data_formatter from xnat_dashboards.bbrc import data_formatter as data_formatter_b formatter_object_connected = data_formatter.Formatter() formatter_object_connected_b = data_formatter_b.Formatter() def test_get_projects_details(): projects = 1 project_details = for...
""" Example using sksym with a two-dimensional landmap. """ import functools import glob import os import numpy import lightgbm import matplotlib from matplotlib import pyplot from mpl_toolkits.axes_grid1.inset_locator import inset_axes from PIL import Image import sksym RNG = numpy.random.Generator(numpy.random.Ph...
import torch from torch import nn from torch.nn import CrossEntropyLoss from transformers.modeling_bert import BertPreTrainedModel, BertLayerNorm, BertEncoder, BertPooler class CustomBertEmbeddings(nn.Module): def __init__(self, config): super().__init__() self.word_embeddings = nn.Embedding(config...
#!/usr/bin/python # # Copyright (c) 2017-2019 Forcepoint ANSIBLE_METADATA = { 'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community' } DOCUMENTATION = ''' --- module: firewall_nat_rule_facts short_description: Facts about firewall rules based on specified policy description: - R...
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import os import sys import torch ...
# -*- coding: utf-8 -*- # this file is released under public domain and you can use without limitations ######################################################################### ## This is a sample controller ## - index is the default action of any application ## - user is required for authentication and authorization...
# Copyright 2016, FBPIC contributors # Authors: <NAME>, <NAME> # License: 3-Clause-BSD-LBNL """ This file is part of the Fourier-Bessel Particle-In-Cell code (FB-PIC) It defines a set of common longitudinal laser profiles. """ import numpy as np from scipy.constants import c from scipy.interpolate import interp1d from ...