text
stringlengths
3.07k
22.1k
import ray import copy import torch import random import argparse import numpy as np from tqdm import tqdm from simrl.utils import setup_seed, compute_gae from simrl.utils.modules import OnehotActor, ContinuousActor, Critic from simrl.utils.envs import make_env from simrl.utils.data import CollectorServer, ReplayBuffe...
import json import string from util.dirs import musicdata_dir composer_name_map = { 'bach': '<NAME>.', 'beethoven': '<NAME>', 'brahms': '<NAME>.', 'bruckner': '<NAME>.', 'holst': '<NAME>.', 'mahler': '<NAME>.', 'mozart': '<NAME>.', 'tchaikovsky': '<NAME>.', } def generate_table_heade...
#!/usr/bin/env python import argparse import logging import os import sys import uuid def read_header(header_line): header_split = header_line.strip().split('\t') header_key_dict = dict() for i, header_column in enumerate(header_split): header_key_dict[header_column] = i return header_key_dic...
###helper function for combining validation hyperparameters and fixed parameters import numpy as np def combine_dicts(dic1,dic2): ###start by combining dict elements of each res_repeat = {} repeated_keys = list(set(dic1.keys()).intersection(set(dic2.keys()))) non_repeat_1 = {key:dic1[key] for key in dic1.keys...
# vim:ts=4:sts=4:sw=4:expandtab from django.db.models import F from satori.core.models import Nonce, Association import logging import urlparse import urllib import urllib2 from xml.dom import minidom import base64 import hashlib import time from openid.consumer import consumer from openid.extensions import sreg as...
import argparse import datetime as dt import json import os import signal import stat import string import sys import mr.db import mr.net import mr.shell as shell today = dt.date.today() - dt.timedelta(days=2) tomorrow = dt.date.today() - dt.timedelta(days=1) class HckrnewsDatabase(mr.db.Database, metaclass=mr.db.D...
import unittest import os import mockpbs import sys import json os.environ["_UNITTEST_"] = "true" from submit_hook import QSELECT_EXE, QSTAT_EXE, QRLS_EXE, QALTER_EXE import submit_hook class Job: def __init__(self, job_id=1, Hold_Types=None, queue="workq", **resource_list): self.job_id = str(job_i...
from playhouse.shortcuts import dict_to_model from datetime import datetime import argparse import json import os from os import listdir from os.path import isfile from echr.utils.logger import getlogger from echr.utils.cli import TAB from rich.markdown import Markdown from rich.console import Console from rich.progres...
##Remember Me ## <NAME> <NAME> ## CIS 1051 Final Project 2021 ## Works cited ## https://eng.libretexts.org/Bookshelves/Computer_Science/Book%3A_Making_Games_with_Python_and_Pygame_(Sweigart)/04%3A_Memory_Puzzle/4.03%3A_Source_Code_of_Memory_Puzzle import random, pygame, sys from pygame.locals import * FPS = 30 ...
from typing import Union from collections import namedtuple import io import os import numpy as np from ..messages import MessageHeader, MessageType, Timestamp from ..parsers import FusionEngineDecoder FileIndexEntry = namedtuple('Element', ['time', 'type', 'offset']) class FileIndexIterator(object): def __i...
# Author: <NAME> at 08/03/2022 <<EMAIL>> # Licence: MIT License # Copyright: <NAME> (2018) <<EMAIL>> import numpy as np from ...mat_gen import zeros from ...utils.random import noise from ...utils.validation import is_array def reservoir_kernel(reservoir, u, r): """Reservoir base forward function. Computes:...
# coding=utf-8 import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import argparse import os import time from cp_dataset import CPDataset, CPDataLoader from networks import VGGLoss, load_checkpoint, save_checkpoint, WUTON, Discriminator, HumanParser ...
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### """ This file is a part of the VeRyPy classical vehicle routing problem heuristic library and provides an implementation of the (parametrized) sequential savings heuristic of Webb (1964). In con...
import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optm import sys import os import numpy as np dir_path = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, dir_path) import regression_idx as ridx from Tools.utils import QuantileLoss # class QuantileLoss(nn.Modul...
""" Utility functions for regenerating our test data starting from h5 files. """ import multiprocessing import subprocess from collections import defaultdict from functools import partial as P import tempfile import logging import shutil import random import time import re import os.path as op import os import sys i...
''' [Fixed] Having issue writing to video update display cfg ''' import os import cv2 import sys import yaml import time import argparse import numpy as np import matplotlib.pyplot as plt ##################### model stuff ##################### # System libs import os, csv, torch, numpy, scipy.io, PIL.Image, torchvis...
"""Definitions of frictional point contacts, contact maps, and basic wrench subroutines.""" import ik from robotsim import * try: import numpy except ImportError: pass def idToObject(world,ID): """Helper: takes a WorldModel ID and converts it into an object.""" assert(ID >= 0 and ID < world.numIDs()) if...
import copy import time import datetime import random from random import randint as rng import numpy as np from collections import deque from keras.models import Sequential from keras.layers import Dense from tensorflow.keras.optimizers import Adam import os screenwidth,screenheight = (300,300) ball...
import base64 import copy import hashlib import json import logging import math import os from typing import Union from lbt.datasets import build_dataset from lbt.metrics import get_experiment_metadata import globals import pandas as pd import yaml def get_gpu_list(): try: return os.environ["CUDA_VISIBLE...
""" 增强型奥拉II 搜索并统计character的数据 """ # MainForm.py中的一次完整的搜索流程应当是: # Step 1:通过ESI api获取角色ID(SearchName) # Step 2:通过zkb api获取角色统计信息 # Step 3:通过zkb api获取角色KM-hash表 # Step 4:对前n个km进行分析(SearchKM) # Step 5:得到的json只给出id,把characterID翻译为玩家角色名 # Step 6:返回 import requests as rq from time import sleep from json i...
from functools import partial import jax from typing import Any, Callable, Sequence, Optional, NewType from jax import lax, random, vmap, numpy as jnp from jax.experimental.ode import odeint import flax from flax.training import train_state from flax import traverse_util from flax.core import freeze, unfreeze from flax...
#!/usr/bin/env python3 import matplotlib.pyplot as plt import numpy as np from scipy.signal import periodogram from scipy.spatial import distance from scipy.stats import norm from sympy.combinatorics.graycode import GrayCode # Carrier signal f_c = 100.0 t_c = 1.0 / f_c # Sampling rate f_s = 10000.0 t_s = 1.0 / f_s ...
from pprint import pprint import itertools as it import random def datasets(dataset, percent): f = dataset.replace('\r\n','\n').split('\n') attr = {} # banyak fitur # id mengindekskan fitur # length menyimpan banyak id attr['id'] = [x.split(':')[0] for x in f[0].split(',')] attr['type'] ...
import re import textwrap import neovim from neovim.api import NvimError def mapl(f, x): return list(map(f, x)) def line_has_sep(line): """Line has a `-` before a `=` """ a = line.find('-') # not header b = line.find('=') # header if a == -1: # No `-` return False elif b == ...
from datetime import datetime, date, timedelta import OAuth2Util import praw import sqlite3 import sys import time try: import bot user = bot.hUser version = bot.hUserAgent userAgent = bot.hVersion subreddit = bot.hSubreddit admin = bot.hAdmin except Exception: pass footer = '\n\n---\n\n^(This post was generat...
import argparse import pandas as pd import numpy as np GENE = 'Hugo_Symbol' PROTEIN = 'Protein_Change' CHROMOSOME = 'Chromosome' ALT = 'Alteration' START_POSITION = 'Start_position' END_POSITION = 'End_position' REF_ALLELE = 'Reference_Allele' ALT_ALLELE = 'Tumor_Seq_Allele2' REF_COUNT = 't_ref_count' ALT_COUNT = 't_a...
import sys, os from PyQt4 import QtGui,QtCore from blocks.RenderableBlock import RenderableBlock from blocks.WorkspaceWidget import WorkspaceWidget from blocks.TrashCan import TrashCan from blocks.MiniMap import MiniMap class Canvas(QtGui.QWidget,WorkspaceWidget): def __init__(self, blockWorkspace): QtGui...
""" Examples of Merkle path verification """ import binascii # hexlify import struct # endianness conversions constants = [ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19b...
from dateutil.relativedelta import relativedelta import random import datetime import csv from numpy import number import pandas as pd def group_into_area(scrambled_soc_lists:tuple)->dict[str:list]: area_dict = { } for society in scrambled_soc_lists: if society[4].lower().strip() not in area_dict....
import asyncio from typing import Optional, List, Tuple, Callable, Awaitable import celery import torch import torch.nn.functional as F from rich.progress import Progress, TextColumn, BarColumn, TimeRemainingColumn, TimeElapsedColumn from torch import Tensor from config import log from zreader.model import ZReader fr...
# This file defines the 7 tetrominoes # I O J L S Z T # # Shapes: https://tetris.fandom.com/wiki/SRS import copy import abc import numpy as np _SHAPES_I = np.array([ [(1, 0), (1, 1), (1, 2), (1, 3)], [(0, 2), (1, 2), (2, 2), (3, 2)], [(2, 0), (2, 1), (2, 2), (2, 3)], [(0, 1), (1, 1), (2, 1), (3, 1)], ], dty...
#!/usr/bin/env python # encoding: utf-8 import logging import sys sys.path.append('.') from fastreid.config import get_cfg from fastreid.engine import DefaultPredictor, default_argument_parser, default_setup, launch from fastreid.utils import comm from collections import OrderedDict from fastreid.data import build_...
from operator import methodcaller from copy import deepcopy import six from django.forms.forms import NON_FIELD_ERRORS, Form from django.forms.formsets import formset_factory from django.forms.models import modelform_factory, _get_foreign_key, BaseInlineFormSet, BaseModelFormSet from django.forms.utils import pretty_...
import platform import csv import array import math from functools import partial # Check for the correct version version = platform.python_version() if float(version[:3]) < 2.7: try: from ordereddict import OrderedDict except: sys.stderr.write("Module ordereddict not found. Please install ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import xml.etree.cElementTree as ET import pprint import os import re # TODO: # 1. Combine same drug entities in the form of "drug_A (alias_for_A)" # find medications, and doses # also find sentence with location indices # # medications are in a list of: # {'beg': 4659,...
#!/bin/env python #all the reading stuff #import matplotlib #matplotlib.use('Agg') from plotting_tools import plotter_3d, movie_maker, plotter_fraction_colors import numpy as np from DeepJetCore.preprocessing import readListArray from DeepJetCore.TrainData import TrainData from datastructures import TrainData_NanoML ...
import json from itertools import chain import numpy as np import copy import utils.vocab_reader as vocab_reader dataroot = '/home/ubuntu/tools/slot_filling_and_intent_detection_of_SLU/data/atis-2' tag_vocab_dir = dataroot + '/vocab.slot2' class_vocab_dir = dataroot + '/vocab.intent' def write_to_dict(json_file1, mat...
from discord.ext import commands from discord.ext.commands import has_permissions import random import discord from discord.ext.commands.errors import MemberNotFound, MissingRequiredArgument import re bonk_gifs = [ 'https://c.tenor.com/GQVoTVtfLvoAAAAM/psyduck-farfetchd.gif', 'https://c.tenor.com/79SwW0QiqNAAA...
#!/usr/bin/env python """ Usage: sslscan [-v] [--threads=<n>] <host> sslscan info <type> sslscan (-h | --help) sslscan --version Options: -h --help Show this help screen --version Show the version -v Be more verbose --threads=<n> Use the given number of threa...
#!/usr/bin/python3 def getopts(argv): opts = {} # Empty dictionary to store key-value pairs. while argv: # While there are arguments left to parse... if argv[0][0] == '-' and argv[0][1] != 'h': # Found a "-name value" pair. opts[argv[0]] = argv[1] # Add key and value to the dictionary. ...
#from __future__ import absolute_import #from __future__ import division #from __future__ import print_function #ka liko padaryti: # pickle failiuke kolkas paveiksliukas issaugotas kaip 32ant32 , o ne 32*32 import pandas as pd import tensorflow as tf import numpy as np from sklearn.cross_validation import train_test_s...
# coding:utf-8 # Author: 阿财(<EMAIL>)(<EMAIL>) # Created date: 2020-02-27 # # The MIT License (MIT) # # Copyright (c) 2016-2019 yutiansut/QUANTAXIS # # 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 Sof...
import random import sys import string import time from rdflib import Graph, URIRef, BNode, Literal, Namespace from rdflib.namespace import RDF, RDFS, XSD # Namespaces scorvoc = Namespace('http://purl.org/eis/vocab/scor#') geo = Namespace('http://www.w3.org/2003/01/geo/wgs84_pos#') ngeo = Namespace('http://geovocab...
import os import logging from PIL import Image import numpy as np import sklearn.datasets import joblib from torch.utils.data import Dataset, DataLoader from torchvision import transforms, datasets import skorch.dataset from skorch.utils import to_numpy from utils.helpers import set_attributes from .helpers import t...
from math import ceil from typing import Any, Dict, Tuple import dash import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html from source.data import LABELS, GameData COLOR_STATWORX = "#013848" def count_score(data: GameData) -> Tuple[int, int]: """Calculat...
from typing import Tuple, Callable from torch import nn from torch.nn import functional as F import torch from torchvision.transforms import ToTensor, ToPILImage from torch.utils.data import DataLoader from statistics import mean from deepext.layers import * from deepext.utils import * class Generator(nn.Module): ...
""" Functions for manipulating `MESA`_ input and output files. .. _MESA: http://mesa.sourceforge.net/ """ import numpy as np import warnings from tomso.utils import tomso_open, load_mesa_gyre astero_table_dtype = [('n', int), ('chi2term', float), ('freq', float), ('corr', float), ('obs', float)...
import math import torch import torch.nn as nn import torch.nn.functional as F import torch_geometric.nn as PyG from nbeats import NBeatsEncoder class GCNConv(PyG.MessagePassing): def __init__(self, gcn_in_dim, config, **kwargs): super().__init__(aggr=config.gcn_aggr, node_dim=-2, **kwargs) self....
"""Dataloader for language generation""" import numpy as np from typing import List, Any, Tuple, Optional, Dict from collections import OrderedDict from .dataloader import LanguageProcessing from .context import FieldContext, VocabContext from .tokenizer import PretrainedTokenizer from .vocab import GeneralVocab, Pret...
# Class for IKEA 2D pose annotations # # <openpose root>/lib/datasets/ # # <NAME> <<EMAIL>> import os import sys import json import cv2 import shutil import argparse import itertools import numpy as np import copy import logging import torch import torchvision.transforms as transforms from glob import glob from PIL im...
# Goal is to annotate a vertex cover with dictionary representing various cluster metrics from igraph import Cover, VertexCover from scipy import nansum, nanmax import uuid import collections import time from circulo.metrics.omega import omega_index from circulo.utils.general import aggregate def __get_weight_attr(G, ...
import os import time import scipy.io as scio import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import dset as datasets from models import ImgNet, TxtNet from utils import compress, calculate_map, logger def save_hash_code(query_text, query_image, query_label, retrieval_text, ret...
import torch def L1(pred, got): """Goes to median.""" return (pred - got).abs().sum() def L2(pred, got): """Goes to mean.""" return .5*(pred - got).square().sum() class Split(torch.nn.Module): """ Splits an RNN (any `x→x` 1D function) into two RNNs, so that two goals can be optimized for without gradi...
# File: main.py # File Created: Saturday, 8th June 2019 9:38:18 am # Author: <NAME> (<EMAIL>) """ Main woker script for carrying out BO experiments Available systems: * Forrester functions * Toy system """ import os import sys import argparse from time import time from functools import partial import numpy as np im...
import os import cv2 import torch import numpy as np import torch.nn as nn import torch.nn.functional as func import matplotlib.pyplot as plt import utils import utils.torch_complex as tc import glob ##Basic Image processing # pad input field into target resolution def img_pad(u_in, target_res, padval=0, mode='cons...
"""Numba-compiled 1-dim and 2-dim functions. !!! note vectorbt treats matrices as first-class citizens and expects input arrays to be 2-dim, unless function has suffix `_1d` or is meant to be input to another function. Data is processed along index (axis 0). All functions passed as argument must be Nu...
"""Support library for OpenSearch templates This is an internal module to Akara. The API may change in the future. """ import re import urlparse import urllib __all__ = ["make_template", "apply_template"] # The OpenSearch format is documented at # http://www.opensearch.org/Specifications/OpenSearch/1.1/Draft_4 ...
# Import libraries import datetime import os import logging import pandas as pd import numpy as np from matplotlib import pyplot as plt from matplotlib.backends.backend_pdf import PdfPages import pickle import config SEED = config.SEED # Configure and create logger current_dir = os.getcwd() log_path = os.path.jo...
#!/usr/bin/python import sys import json from os import system import os def getFileBetween(filename,begin,end): try: f = open(filename,"r") res = "" start = False for line in f: if end in line : f.close() return res if start ...
import os import logging import shutil import PySimpleGUI as sg import riscv_config.checker as riscv_config import riscv_config.utils as utils from collections import OrderedDict import ruamel from ruamel.yaml import YAML import yaml as pyyaml import re yaml = YAML(typ="rt") yaml.default_flow_style = False yaml.allow_u...
# Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging import unittest from collections import namedtuple import torch import torch.nn as nn from classy_vision.generic.distributed_ut...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
import matplotlib.pyplot as plt from pylab import mpl import math import numpy as np from mpl_toolkits.axisartist.parasite_axes import HostAxes, ParasiteAxes import time import sys import base64 import json """完成拟合曲线参数计算前相应变量的计算""" def polynomial_fitting(data_x, data_y): size = len(data_x) i = 0 sum_x = ...
"""Chop and unchop https://github.com/tidyverse/tidyr/blob/master/R/chop.R """ from collections import defaultdict from typing import Iterable import numpy import pandas from ..core.backends.pandas import DataFrame, Series from ..core.backends.pandas.api.types import is_scalar from pipda import register_verb from .....
import tensorflow as tf import constants as const def _parse_layer_params(layer_desc_, num_expected): """Extracts parameters from network description layer and raises if there are issues.""" layer_type_, layer_params = layer_desc_[0], layer_desc_[1:] if len(layer_params) != num_expected: raise Valu...
import os, time import numpy as np import pandas as pd import seaborn as sns import tensorflow as tf import matplotlib.pyplot as plt # Auxiliary functions def seed_everything(seed=0): np.random.seed(seed) tf.random.set_seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) os.environ['TF_DETERMINISTI...
from tests.base import BaseTest from dataclasses import dataclass from typing import Any, Mapping, Optional from datetime import datetime import uuid from snuba.datasets.transactions_processor import TransactionsMessageProcessor from snuba.consumer import KafkaMessageMetadata from snuba.processor import ProcessorAc...
""" Declare and configure the models for the courses application """ from django.db import models from django.db.models import BooleanField, Case, Value, When from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from cms.extensions.extension_pool import extension_pool from cms.mode...
''' Issues some metadata to Bitcoin's blockchain via OP_RETURN. We currently store the hash of the index pdf certificate that holds all the hashes for the certificates. ''' import os import sys import hashlib import getpass import binascii import configargparse ''' Issues bytes to the Bitcoin's blockchain using OP_...
#!/usr/bin/env python3 # 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 require...
#!/usr/bin/env python3 """Defines the base class for schedulers.""" import itertools from schedsi import rcu from schedsi.cpu import context from schedsi.cpu.request import Request as CPURequest class SchedulerData: # pylint: disable=too-few-public-methods """Mutable data for the :class:`Scheduler`. Mutabl...
# -*- coding: utf-8 -*- """Tests the xonsh history.""" # pylint: disable=protected-access import io import os import sys import shlex from xonsh.lazyjson import LazyJSON from xonsh.history import History, _hist_create_parser, _hist_parse_args from xonsh import history import pytest @pytest.yield_fixture def hist():...
# -*- coding: utf-8 -*- """Dicom to nifti conversion for NAKO zipped imaging studies. Dicom to nifti conversion for NAKO zipped imaging studies. Example: Example usage:: $ python dcm2nii -h $ python dcm2nii /srcdir /destdir --dixon -v --id Todo: * ... """ import multiprocessing import os i...
import os from os.path import join as opj from shutil import copyfile, SameFileError import git # pip install gitpython from sqlalchemy import create_engine import numpy as np import subprocess from importlib.machinery import SourceFileLoader import warnings from sklearn.metrics import matthews_corrcoef def load_con...
# -*- coding: utf-8 -*- """ MIT License Copyright (c) 2022 cmla-psu/<NAME> 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, cop...
from __future__ import annotations import abc import dataclasses import uuid from types import TracebackType from typing import List, Tuple, Dict, Any, Optional, Sequence, Type, TypeVar, Generic from meadowrun.instance_selection import ( CloudInstance, Resources, remaining_resources_sort_key, ) from meado...
# Copyright 2022 <NAME> # # 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, softw...
import asyncio import logging import multiprocessing import os import signal import sys import time import requests from discord import AllowedMentions, Intents, RequestsWebhookAdapter, Webhook from dotenv import load_dotenv import config import ipc from app.cache import Cache from app.classes.bot import Bot from app...
#!/usr/bin/env python """ cli.py author: @mbiokyle29 """ from __future__ import print_function import logging import os import re import sys import warnings import click from onecodex.utils import (cli_resource_fetcher, download_file_helper, valid_api_key, OPTION_HELP, pprint, ...
''' Resnet for cifar dataset. Adapted from https://github.com/facebook/fb.resnet.torch and https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py (c) <NAME> ''' import torch import torch.nn as nn from torch.nn import functional as F from mixmo.augmentations import mixing_blocks from mixmo.utils im...
""" .. module: _map_getters_setters :synopsis: Getter and setter functions for the Map class. All of these functions are stored as methods of the map class in map.py. """ from . import cell import itertools import numpy as np # Dictionary that stores the RGB values corresponding to a given color. RGB_DIC...
# Copyright 2013-2020 Salesforce.com, inc. """ Unit tests for the krux.cli module. """ from __future__ import generator_stop import inspect import os import sys from argparse import ArgumentParser, Namespace from logging import Logger from unittest import TestCase from time import time from mock import MagicMock, patc...
#!/usr/bin/env python from __future__ import (absolute_import, division, print_function, unicode_literals) import matplotlib matplotlib.use('agg') import warnings with warnings.catch_warnings(): warnings.simplefilter('ignore') import matplotlib.pyplot as plt import matplotlib.patche...
from my_imports import * from tools import convert_to_gpu from generating_data import generate_z, generate_real_data, rank_by_discriminator def get_conf_int(data): if (np.amax(data)==np.amin(data)): return (data[0], data[0]) else: return norm.interval(0.95, loc=np.mean(np.array(data)), scale=np...
from random import randint class Individual: """ Classe que representa o individuo. """ def __init__(self, number_as_decimal): """ Construtor da classe que representa o individuo. Args: number_as_decimal (int): Valor x no sistema decimal. """ self.nu...
import numpy as np import healpy as hp from plancklens import utils as ut, utils_spin as uspin class qeleg: def __init__(self, spin_in, spin_out, cl): self.spin_in = spin_in self.spin_ou = spin_out self.cl = cl def __eq__(self, leg): if self.spin_in != leg.spin_in or self.spin_...
''' @author: shylent ''' from tftp.backend import FilesystemSynchronousBackend, IReader, IWriter from tftp.bootstrap import RemoteOriginWriteSession, RemoteOriginReadSession from tftp.datagram import (WRQDatagram, TFTPDatagramFactory, split_opcode, ERR_ILLEGAL_OP, RRQDatagram, ERR_ACCESS_VIOLATION, ERR_FILE_EXISTS,...
import os from cs50 import SQL from flask import Flask, flash, jsonify, redirect, render_template, request, session from flask_session import Session from tempfile import mkdtemp from werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError from werkzeug.security import check_password_hash, ge...
from django.db import models from dateutil.parser import parse as date_parse # Office365 User class User(models.Model): object_id = models.CharField(max_length=36) immutable_id = models.CharField(max_length=32, null=True) user_type = models.CharField(max_length=16, null=True) account_enabled = models....
import numpy as np import paddle import paddle.nn as nn import paddle.nn.functional as F import paddlenlp as nlp from functools import partial from paddlenlp.data import Stack, Tuple, Pad def predict(model, data, tokenizer, label_map, batch_size=1): """ Predicts the data labels. Args: model (obj...
import torch import time from torch.autograd import Variable import scipy.io as sio import pandas as pd import gzip import bz2 import csv from random import shuffle torch.set_default_tensor_type('torch.DoubleTensor') def loadSavedMatFile(x): data = sio.loadmat(x) # populate each column of array #convert from nump...
# aux.py # auxiliary functions # Copyright 2019 <NAME> import numpy as np import pandas as pd # for stat from scipy.sparse import coo_matrix from scipy import stats # for io import csv # for plot import matplotlib as mpl import matplotlib.pyplot as plt # === ds: custom data structure class Tray: ''' empty c...
#!/usr/bin/env python3 # coding: utf-8 # ---------- # # Data Tools # # ---------- # ### Modules # standard library import os from bisect import bisect_left from os.path import join, normpath import csv import json # dependencies import numpy as np from scipy.signal import savgol_filter # custom code from pupil_code...
import torch import torch.nn as nn import torch.nn.functional as F from transformers import BertTokenizer import random from dataset import wordVec_Table, sentencesVec class s2sencoder(nn.Module): """ # encoder without the embedding layer """ def __init__(self, input_dim=768, hidden_dim=768, decoder_h...
""" Run antibody characterization tool on the L110-CCK dataset Output an excel sheet of results """ import os import numpy as np import pandas as pd #also requires xlsxwriter from at_synapse_detection import dataAccess as da from at_synapse_detection import antibodyAnalysis as aa def NAME(): """ Run antibody cha...
#!/usr/bin/python3.6 -u import io import typing import asyncio import aiohttp from functions import * from discord.ext import commands """Unsure if we should import * here""" from datetime import datetime from datetime import timedelta bot = commands.Bot(command_prefix="!", case_insensitive=True, help_command=None) d...
from pathlib import Path import pandas as pd from tools import selection_methods import time import numpy as np from pathlib import Path from collections import OrderedDict from tools import eval_methods, selection_methods, resolution_methods from tqdm.auto import tqdm from dateutil import parser import pickle import ...
""" conftest that prepares fixtures with tests involving orm of aiida """ import tempfile import shutil from pathlib import Path import pytest from aiida.orm import Computer, Dict, Code, KpointsData, Node from aiida.plugins import DataFactory, ParserFactory from aiida.common.exceptions import NotExistent from aiida.c...
# -*- coding: UTF-8 -*- """ This module provides a compact trie (``CTrie``) implementation for Python. .. moduleauthor:: <NAME> <<EMAIL>> """ __version__ = '0.1.1' from io import StringIO def _cut_prefix(prefix, word): """ test if ``prefix`` is a prefix of ``word``. If so, return the trailing part of ...
# Module requests is used to collect html info from a url import requests # Module bs4 (or BeautifulSoup4) is used to easily pull data from html code # It also makes the code much easier to read if you plan on printing or writing # the code to a file to read through. from bs4 import BeautifulSoup import time ...