text
stringlengths
3.07k
22.1k
#! /usr/bin/env python # -*- coding: utf-8 -*- """ Module that contains implementation for DCC tools """ from __future__ import print_function, division, absolute_import import os import re import logging from tpDcc import dcc from tpDcc.core import tool from tpDcc.managers import resources, configs from tpDcc.libs...
# -*- coding: utf-8 -*- ''' rosaceae.scorecard ~~~~~~~~~~~~~~~~~~ This module provides functions for credit risk scorecard. ''' from __future__ import print_function import re import pandas as pd import numpy as np from math import log, e from .bins import bin_tree, bin_custom # raw value transfer to woe value acc...
#!/usr/bin/env python3 # Copyright (c) 2019 Advanced Micro Devices, 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 # #...
from card import Card #TODO - restructure Hand vs PokerHand so Hand can be used as a generic class class Hand(object): """In general, Hand object has two sets of cards - public cards (self.cards) which are shared by a group, and hole cards (__hole_cards) which belong to the Hand and are not shared or expo...
from api_emulator.redfish.EventService_api import EventServiceAPI, CreateEventService from api_emulator.redfish.Chassis_api import ChassisCollectionAPI, ChassisAPI, CreateChassis from api_emulator.redfish.ComputerSystem_api import ComputerSystemCollectionAPI, ComputerSystemAPI, CreateComputerSystem from api_emulator.re...
import torch import numpy as np from transformers import BertModel from sentence_transformers import SentenceTransformer, util from relevance_model import text_preprocessing, preprocessing_for_bert, bert_predict, BertClassifier from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSample...
# Copyright 2008-2010 Nokia Siemens Networks Oyj # # 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...
# !/usr/bin/env python # title :Train.py # description :Main script to TRAIN the gaze estimation network # author :<NAME> # date :30092018 # version :2.0 # usage :Example (see more @init_main): # python3 Train.py -t FT_SM_NFEL5836GRU_fold3 -exp NFEL5...
# -*- coding: utf-8 -*- import argparse psr = argparse.ArgumentParser() psr.add_argument('ipt', help='input file') psr.add_argument('-o', dest='opt', help='output') psr.add_argument('-N', dest='NetDir', help='Network directory') psr.add_argument('--mod', type=str, help='mode of weight', choices=['PEnum', 'Charge']) ps...
import pymongo import datetime from pprint import pprint def create(): def add_member(n): member_collection.update_one( {"name": n}, { "$setOnInsert": {"name": n}, }, upsert=True) name = "*" print("Enter names of the members...") ...
#!/usr/bin/env python #-*- coding: utf-8 -*- # Created by lhao at 2019-04-21 import cobra from cobra import Model, Reaction, Metabolite import os import pandas as pd import re import imp import My_def def gpr2log( gpr_i, othergeneset,inset = True, notinset = False, emptyset = '' ): torf = '' if not gpr_i : ...
''' NMF optimization for dynamic brain networks Uses cross-validation to find the optimal parameter set for a collection of network adjacency matrices. Created by: <NAME> Change Log ---------- 2016/12/25 - Implemented consensus detection ''' import numpy as np from . import Utils nnls = Utils.nnls matrix_utils = Ut...
from iminuit._core import ( FCN, MnUserParameterState, MnUserTransformation, MnMigrad, MnStrategy, MnScan, FunctionMinimum, MnSimplex, MnPrint, MnUserCovariance, MinimumState, ) from pytest import approx import pytest import pickle @pytest.fixture def debug(): prev = Mn...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/11/20 15:05 # @Author : bxf # @File : API_IMP_OPT.py # @Software: PyCharm from model.util.PUB_LOG import * from openpyxl import load_workbook from model.util.newID import * from model.util.PUB_RESP import * from model.util.PUB_DATABASEOPT i...
import os import click import numpy as np import json import copy from mpi4py import MPI from baselines import logger from baselines.common import set_global_seeds, tf_util from baselines.common.mpi_moments import mpi_moments import baselines.her.experiment.config as config from baselines.her.rollout import RolloutWo...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from . import ...
from django.db.models import Q from django.contrib import messages from django.contrib.auth.decorators import login_required from django.core.urlresolvers import reverse from django.shortcuts import get_object_or_404, redirect from django.utils.decorators import method_decorator from django.views.generic import DetailV...
#!/usr/bin/python3 import os import sys import argparse import subprocess import datetime import perfscrape import responsetimescrape from htmconfig import ConfigureHTM from cycconfig import ConfigureCycles ############################################################################### # Initialization #############...
import shutil import os from django.core.files.uploadedfile import SimpleUploadedFile from django.core.management import call_command from django.urls import reverse from django.conf import settings import pytest from geocontrib.models.project import Project from geocontrib.models.user import UserLevelPermission from...
# This file is part of rinohtype, the Python document preparation system. # # Copyright (c) <NAME>. # # Use of this source code is subject to the terms of the GNU Affero General # Public License v3. See the LICENSE file or http://www.gnu.org/licenses/. from io import BytesIO from itertools import islice from pathlib i...
from sys import platform from shutil import rmtree, copyfile from random import randint from os import system, getcwd, path, curdir, chdir, mkdir from time import sleep, time from multiprocessing import Process as p mswin = (platform == "win32") if mswin: from subprocess import Popen, REALTIME_PRIORITY_CLASS else:...
""" Script to search for similiar files on github """ import os import requests import math import logging import tempfile import time from collections import OrderedDict import arrow from server.models import Assignment from server.extensions import cache from server import jobs GITHUB_PAGE_MAX = 6 # Stop after 6 ...
# -*- coding: utf-8 -*- import difflib import numpy as np import os import SimpleITK as sitk import scipy.spatial # Set the path to the source data (e.g. the training data for self-testing) # and the output directory of that subject testDir = '' # For example: '/data/Utrecht/0' participantDir = '' # For exam...
import logging logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) import pygame from camera import * WALL = 0 FLOOR = 1 START = 2 END = 3 cell_types = ["Wall", "Floor", "Start", "End"] class Cell: def __init__(self, x, y, size, c_type=FLOOR): self.x = x self.y = y ...
import argparse from utils import get_logger logger = get_logger() arg_lists = [] parser = argparse.ArgumentParser() def str2bool(v): return v.lower() in ('true') def add_argument_group(name): arg = parser.add_argument_group(name) arg_lists.append(arg) return arg # Network net_arg = add_argument_g...
import numpy as np import sys import csv import copy import matplotlib import matplotlib.pyplot as plt matplotlib.use("pgf") matplotlib.rcParams.update({ "pgf.texsystem": "pdflatex", 'font.family': 'serif', 'text.usetex': True, 'pgf.rcfonts': False, }) k=1 def print_optimal_rows(file_name, a,b): te...
import json import os from os import listdir import os.path as osp import pickle import time from collections import OrderedDict, Counter import argparse import numpy as np import pathlib import joblib from gym.wrappers.monitoring.video_recorder import VideoRecorder from TeachMyAgent.run_utils.environment_args_handle...
import warnings warnings.simplefilter(action='ignore', category=FutureWarning) import os import os.path as osp import numpy as np import json import provider from sklearn.model_selection import train_test_split BASE_DIR = os.path.dirname(os.path.abspath(__file__)) TRAIN_FILES_MODELNET = provider.getDataFiles( \ ...
import os import subprocess as sp from pathlib import Path import parmed as pmd systems = """./a-bam-p ./a-bam-s ./a-but-p ./a-but-s ./a-cbu-p ./a-chp-p ./a-cbu-s ./a-chp-s ./a-cpe-p ./a-coc-p ./a-coc-s ./a-cpe-s ./a-hep-p ./a-ham-s ./a-ham-p ./a-hep-s ./a-hp6-p ./a-hex-p ./a-hex-s ./a-hp6-s ./a-hx2-p ./a-hpa-s ./a-h...
from __future__ import print_function import torch # Quantization related import from aimet_torch.quantsim import QuantizationSimModel from aimet_common.utils import AimetLogger import logging from aimet_torch.cross_layer_equalization import equalize_model import sys import os import argparse import num...
#!/usr/bin/env python3 from WellKnownHandler import WellKnownHandler from WellKnownHandler import TYPE_UMA_V2, KEY_UMA_V2_RESOURCE_REGISTRATION_ENDPOINT, KEY_UMA_V2_PERMISSION_ENDPOINT, KEY_UMA_V2_INTROSPECTION_ENDPOINT from flask import Flask, request, Response from werkzeug.datastructures import Headers from random...
# -- # Copyright (c) 2008-2021 Net-ng. # All rights reserved. # # This software is licensed under the BSD License, as described in # the file LICENSE.txt, which you should have received as part of # this distribution. # -- from __future__ import absolute_import import logging import logging.config import traceback fr...
""" This file was used to manually but quickly label all the source csv files. It shows a schema, asks if you actually want to use this schema (you can discard it if it is not usable). It then asks per column if you want to use/discard the column, and what the new column name should be. All csv files are then ...
# Processing to create the sentence dictionary, which has the form: # 'text': 'narrative_text', # 'LOCS': ['location1', ...], 'TIMES': ['dates_or_times1', ...], 'EVENTS': ['event1', ...], # 'subjects': [{'subject_text': 'subject_text', 'subject_type': 'type_such_as_SINGNOUN'}, # {'subject_text'...
from ..deps import * router = APIRouter( prefix = "/admin", tags = ["Admin"], include_in_schema = False ) @router.get("/console") async def admin_dashboard(request:Request, stats: Optional[int] = 0): if "userid" in request.session.keys() or stats == 1: if "userid" in request.session.keys() and...
"""Multiprocessing utilities around Queues. Note this could potentially be simplified by using a multiprocess.Pool, but the ability to debug specific cases and error messages is less straightforward. These utilities are structured to be compatible with the multiprocessing implementation in Assignment.py, but ha...
import math as maths from datetime import datetime, timedelta from operator import attrgetter from random import randrange from time import time from flask import current_app from app.extensions import db from app.default.models import Activity, Machine, ScheduledActivity from config import Config def complete_last...
import os, sys import os.path as osp import argparse import warnings import time import numpy as np from utils import paired_transforms_tv04 as p_tr from PIL import Image from skimage.io import imsave from skimage.util import img_as_ubyte from skimage.transform import resize import torch from models.get_model import g...
# / ┌─────────────┐ \ # # |==│ By BitExpo3 │==| # # \ └─────────────┘ / # import socket import threading import sys import json import curses from curses import wrapper import yaml import os wmain = None wside = None wbar = None winy, winx = None, None state = "" # Official server IP & PORT coming soon! SERVER =...
from __future__ import print_function import xml.etree.ElementTree as Tree import sys def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) AMQP_TO_ZIG = { 'longstr': "[]const u8", 'bit': "bool", 'longlong': "u64", 'short': "u16", 'table': "Table", 'l...
"""Deep Q learning graph The functions in this file can are used to create the following functions: ======= act ======== Function to chose an action given an observation Parameters ---------- observation: object Observation that can be feed into the output of make_obs_ph stochastic: bool...
""" Custom multihead attention. We overwrite torch.nn.MultiHeadAttention's forward to use custom_multi_head_attention_forward instead of torch.nn.functional.multi_head_attention_forward. Code is taken and adapted from https://github.com/pytorch. """ from torch import Tensor from torch.nn import MultiheadAttention impo...
""" Copyright (c) 2015 Red Hat, Inc All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. """ from flexmock import flexmock from textwrap import dedent import pycurl import six import time import json from osbs.http import HttpResponse...
#!/usr/bin/python3 # coding: utf-8 # In[1]: RunActualDB = True from Private_Pkgs.DataRecordingUtils import drutils import sys import json import datetime import time import random import statistics import pprint import math print("Current Python version: ", sys.version_info[0],".",sys.version_info[1],".",sys.version...
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
# Standard library imports import argparse import os import sys from multiprocessing.dummy import Pool # Third party imports import redis # Local imports from parsers.city import CityParser from parsers.hotel import HotelParser from parsers.overall import overall_review_numbers from parsers.restaurant import Restaura...
"""This module contains plotly visualizations.""" import plotly.graph_objs as go import plotly.io as pio OPACITY = 0.7 COLORS = ['rgba(0,0,51,{})', 'rgba(94,12,35,{})', 'rgba(4,103,103,{})', 'rgba(128,128,128,{})'] FILL_COLORS = [color.format(OPACITY) for color in COLORS] HISTOGRAM_COLORS = ['rgba(94,12,35,{...
""" The Config container is a typed dict-like class to store application's config. """ from collections import ChainMap, UserDict, OrderedDict import copy import inspect import logging from typing import Any, Callable, ClassVar, Dict, Generic, GenericMeta, Iterable, Hashable, Optional, Type, TypeVar, Union, get_type_hi...
import turtle import time import random from random import randint from pygame import mixer mixer.init() sound1 = "sounds/impact_snowball_hit_wall.mp3" sound2 = "sounds/zapsplat_sport_squash_ball" \ "_catch_in_hand_001_17896.mp3" impact = mixer.Sound(sound1) impact_2 = mixer.Sound(sound2) mixer.music.load("os...
import pathlib from typing import Any, Callable, Dict, Optional, Tuple, Union from pydantic import BaseModel module_path = pathlib.Path(__file__).parent.absolute() Layer = Tuple[int, int] LayerSpec = Union[int, Layer, str, None] def make_empty_dict() -> Dict[str, Callable]: return {} class LayerMap(BaseModel)...
# Goal: # Make a junction temperature measurement on an LED using the Electrical Test Method specified by the Joint Electron Device Engineering Council # # Expectation: # 1.) A K-factor will be measured by comparing voltages at two controlled temperatures # 2.) The LED will be heated using its operational current unti...
#!/usr/bin/python3 # -*- coding: utf8 -*- # Copyright (c) 2020 Baidu, 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...
from typing import Union, List, Dict, Any, Sequence, Iterable, Optional import re reCommaWhitespacePotentiallyBreaks = re.compile(r",\s+") def dictString(d: Dict, brackets: Optional[str] = None): s = ', '.join([f'{k}={toString(v)}' for k, v in d.items()]) if brackets is not None: return brackets[:1]...
import re import struct import typing from typing import List from hashlib import sha256 from decimal import Decimal from hub.schema.base58 import Base58 from hub.schema.bip32 import PublicKey from hub.common import hash160, hash_to_hex_str, double_sha256 from hub.scribe.transaction import TxOutput, TxInput, Block from...
import warnings import os import gc import numpy as np import scipy.ndimage.morphology as scipy_morph import scipy.ndimage.measurements as scipy_meas from skimage.filters import gaussian, threshold_otsu from skimage.morphology import remove_small_objects from skimage.exposure import adjust_gamma from glob import glo...
from functools import partial import tkinter as tk import tkinter.ttk as ttk from typing import Callable, List, Tuple, Type, Union from threading import Thread from src.pages.BasePage import BasePage from src.utils.utils import ensureOnScreen from src.models.dummy import Model from src.utils.State import State from sr...
''' These functions generate combinations and permutations in lexical order. ****************************************************** * * * WARNING: These functions are not reentrant! * * * **...
# coding: utf-8 from __future__ import unicode_literals, absolute_import import json from collections import namedtuple from itertools import chain import csv import re from datetime import datetime from django.http import HttpResponse, JsonResponse from django.utils.module_loading import import_string try: from...
# The 6.00 Word Game import random import string VOWELS = 'aeiou' CONSONANTS = 'bcdfghjklmnpqrstvwxyz' # Do not assume that there are always 7 letters in a hand! # The parameter n is the number of letters required for a bonus score # (the maximum number of letters in the hand). Our goal is to keep the code modular. H...
#!/usr/bin/env python import datetime import json import logging import os import traceback from functools import partial from pathlib import Path from typing import Any, Callable, Dict, Iterable, List import yaml from pandas import DataFrame, Int32Dtype, concat, isna, read_csv # ROOT directory ROOT = Path(os.path.d...
""" Metrics for determining the quality of generated and reconstructed images. Author: <NAME> Date: 28-07-2020 Updated: 10-11-2020 """ import numpy as np import os import tensorflow as tf from StyleALAE.data import * # FID # from tensorflow.keras.applications.inception_v3 import InceptionV3 from tensorflow.keras.ap...
from ctypes import * import math import random import os import cv2 import numpy as np import time def sample(probs): s = sum(probs) probs = [a/s for a in probs] r = random.uniform(0, 1) for i in range(len(probs)): r = r - probs[i] if r <= 0: return i return len(probs)-...
import PySimpleGUI as sg """ PySimpleGUI is designed & authored in Python to take full advantage the awesome Python constructs & capabilities. Layouts are represented as lists to PySimpleGUI. Lists are fundamental in Python and have a number of powerful capabilities that PySimpleGUI exploits. M...
import numpy as np import torch import torch.nn as nn from .distributions import Bernoulli, Categorical, DiagGaussian from .utils import init class Flatten(nn.Module): def forward(self, x): return x.view(x.size(0), -1) class Policy(nn.Module): def __init__(self, obs_shape, action_space, base=None, ...
import scann from argparse import ArgumentParser from pl_bolts.models.self_supervised import SimCLR from pl_bolts.models.self_supervised.resnets import resnet18 from pl_bolts.models.self_supervised.simclr.transforms import SimCLREvalDataTransform, SimCLRTrainDataTransform from pathlib import Path import torch import os...
# ------------------------------------------------------------------------------ # CodeHawk Java Analyzer # Author: <NAME> # ------------------------------------------------------------------------------ # The MIT License (MIT) # # Copyright (c) 2016-2020 Kestrel Technology LLC # # Permission is hereby granted, free of...
from enum import Enum, auto, unique import datetime as dt import math from .calculations import time_zenith, time_altitude, time_shadow_factor @unique class CalculationMethod(Enum): ISNA = auto() MWL = auto() EGYPT = auto() TEHRAN = auto() JAFARI = auto() MAKKAH = auto() KARACHI = auto() ...
## Script written by <NAME>. ## Last edited on 18/02/2020. ## BOSS-V algorithm. # Copyright (c) 2020, the BOSS-V author (see AUTHORS.txt). # Licensed under the BSD 3-clause license (see LICENSE) import numpy as np from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler, MinMaxScaler # ...
import unittest import inspect import os from random import randint, uniform from nwlattice import planes, base class PlaneObjectsTest(unittest.TestCase): """convenient base class for every other test in this module""" def setUp(self) -> None: self.plane_types = self.get_all_plane_objects() s...
import itertools import os import enum import pickle import logging import numpy as np import pandas as pd import sklearn.metrics as metrics from util import read_geotiff, Image from feature import Feature from groundtruth import create_mask, create_groundtruth, reshape_image from matplotlib import pyplot as plt from...
from __future__ import absolute_import, print_function import numpy as np import pandas as pd import unittest import os import os.path import logging import src.lib.OptimizationAlgo as OA import src.lib.NeuralNetwork as NN import src.lib.Layer as Layer import src.lib.Activation as AC import src.lib.LossFun...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = "<NAME>" __doc__ = r""" Created on 09-12-2020 """ from pathlib import Path from typing import Iterable import numpy import torchaudio from draugr.random_utilities.seeding import numpy_seed from draugr.numpy_utilities import zero_pad_...
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2018 <NAME> <<EMAIL>> # # Distributed under terms of the MIT license. """ """ from __future__ import print_function, division import sys, os, time import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import matplotl...
#/usr/bin/env python3 import socket import sys import os import select import pickle import signal import datetime import math import time #Note: We declare here the server descriptor and the log file to be "global variables" # and that these can be accessed by the CTRL + C handler and the connection...
# -*- coding: utf-8 -*- """ Copyright © 2018 Approximator. All rights reserverd. Author: Approximator (<EMAIL>) 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/L...
#!/usr/bin/env python # -*- coding:utf-8 -*- """================================================================= @Project : Algorithm_YuweiYin/LeetCode-All-Solution/Python3 @File : LC-0279-Perfect-Squares.py @Author : [YuweiYin](https://github.com/YuweiYin) @Date : 2022-02-24 ===================================...
import numpy as np import pandas as pd import warnings ## Plotting libraries import seaborn as sns import matplotlib.pyplot as plt ## Sklearn Libraries from sklearn.utils import shuffle from sklearn.preprocessing import StandardScaler from sklearn.preprocessing import label_binarize from sklearn.model_selection impor...
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distrib...
from tensorflow.keras import layers import tensorflow_addons as tfa from tensorflow import keras import tensorflow as tf from datetime import datetime import matplotlib.pyplot as plt import numpy as np import random # Setting seeds for reproducibility. SEED = 100 tf.random.set_seed(SEED) np.random.seed(SEED) random.s...
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
""" GIF picture parser. Author: <NAME> """ from lib.hachoir_parser import Parser from lib.hachoir_core.field import (FieldSet, ParserError, Enum, UInt8, UInt16, Bit, Bits, NullBytes, String, PascalString8, Character, NullBits, RawBytes) from lib.hachoir_parser.image.common import PaletteRGB from lib.h...
import numpy as np import matplotlib.pyplot as plt from scipy.stats import gaussian_kde as kde from mpl_toolkits.axes_grid1 import make_axes_locatable import pylab as pl from scipy.interpolate import LSQUnivariateSpline as interpolate from .statistic import PDF, PowerSpectrum, Moments def plot_powerspectrum(cmb_mapse...
#!/usr/bin/python3.6 # -*- coding: utf-8 -*- """ <NAME> Optical Flow and Dense Optical Flow You can select both of them from command line. """ # Idea from: https://docs.opencv.org/3.4/d4/dee/tutorial_optical_flow.html # http://www.inf.fu-berlin.de/inst/ag-ki/rojas_home/documents/tutorials/Lucas-Kanade2.p...
from __future__ import division from collections import OrderedDict import numpy as np from io import BytesIO import scipy as sp import scipy.stats import copy import sys #names and data. #after cpy. del dct[key] #dct.keys().index('keyval') #name_dict structure : OrderedDict( [ ('result', ['p', 'e']), ('cap-shape', ['...
"""" This is a saved model run from natcap.invest.carbon.carbon_combined. Generated: 07/05/16 15:08:53 InVEST version: 3.3.0 """ import arcpy import natcap.invest.carbon.carbon_combined import os import shutil import sys arcpy.env.overwriteOutput = True workspace_dir = arcpy.env.scratchFolder def GetArgs(): do...
from __future__ import print_function import os import time from datetime import datetime import math import argparse import logging import pickle import yaml import cv2 as cv import numpy as np # from skimage.measure.simple_metrics import compare_psnr import torch import torch.nn as nn import torch.optim as optim im...
# Copyright 2017 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 a...
import functools import time from collections import Counter from math import ceil from os.path import abspath, dirname, join import numpy as np from matplotlib import pylab as pyl from matplotlib import pyplot as plt N = 5 M = 20 K = 5 DICT_LIMIT = 10000000 # M * N * K * number_of_increasing_partitions(N, M) PRINT_...
# coding: utf-8 from __future__ import unicode_literals from .common import InfoExtractor from ..utils import ( compat_str, ExtractorError, int_or_none, str_or_none, url_or_none, ) import re class EurozetArticleIE(InfoExtractor): IE_NAME = 'eurozet:article' _VALID_URL = r'https?://(?:[a-z...
import ipaddress import os import sys import subprocess from collections import OrderedDict import datetime import json other_proto = set() def parse_packet_head(line): ''' Parses the head of the packet to get the key tuple which contains the flow level data Args: line: Header line from tcpd...
import numpy from btypes.big_endian import * import gx import logging logger = logging.getLogger(__name__) class Header(Struct): magic = ByteString(4) section_size = uint32 shape_count = uint16 __padding__ = Padding(2) shape_offset = uint32 index_offset = uint32 unknown0_offset = uint32 ...
#!/usr/bin/python import argparse import os import sys import pdf2image # from PIL import Image import PyPDF2 import pytesseract import logman Args = None def print_help_and_exit(code=1): if Args is not None: Args.print_help(sys.stderr) else: logman.error('Args was None, exiting ..') s...
# -*- coding: utf-8 -*- """ Unit tests for the Open Babel methods """ import os import pybel import unittest from mdstudio_structures.cheminfo_pkgmanager import CinfonyPackageManager from mdstudio_structures.cheminfo_molhandle import mol_addh, mol_make3D, mol_read, mol_removeh, mol_write toolkits = CinfonyPackageMa...
import argparse import datetime import os import time import uuid import numpy as np import pandas as pd import torch import torch.nn as nn from sklearn.model_selection import train_test_split from torch.utils.tensorboard import SummaryWriter from torch.utils.data import DataLoader, Dataset from torch.utils.data.datas...
import sys import os, os.path from io import open import glob, time from lark import Lark from lark.indenter import Indenter from lark import tree import json import tokenize from tokenize import tok_name import keyword functionDefDict = {} allCalls = [] # __path__ = os.path.dirname(__file__) class PythonIndenter(Ind...
""" This file is part of YAOS and is licenced under the MIT licence. Common utilities used by multiple submodules. """ import gettext gettext.bindtextdomain('yaosapp', '/lang') gettext.textdomain('yaosapp') _ = gettext.gettext import gi gi.require_version('Gtk', '3.0') from gi.repository import GdkPixbu...
"""Bot events""" import re import sys import traceback from datetime import datetime import discord import tldextract from discord.ext import commands from mergedeep import merge from koabot.cogs.botstatus import BotStatus from koabot.cogs.imageboard import ImageBoard from koabot.cogs.reactionroles import ReactionRol...
from rlf.algos.il.gail import GailDiscrim import torch import torch.nn as nn from functools import partial import rlf.il.utils as iutils from rlf.algos.nested_algo import NestedAlgo from rlf.algos.on_policy.ppo import PPO from rlf.il.transition_dataset import TransitionDataset import rlf.rl.utils as rutils from torch.u...
import asyncio import logging import os import sys from argparse import SUPPRESS, ArgumentParser from typing import Callable, Dict, Mapping import yaml from aioregistry import ( AsyncRegistryClient, ChainedCredentialStore, DockerCredentialStore, default_credential_store, ) from tplbuild.cmd.base_build...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2018 theloop 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 requ...