text
stringlengths
3.07k
12.6k
#!/usr/bin/env python from __future__ import print_function try: # If possible, use setuptools from setuptools import setup from setuptools.extension import Extension from setuptools.command.build_ext import build_ext as distutils_build_ext except ImportError: from distutils.core import setup ...
''' Created on 2009-08-30 @author: beaudoin Allows creation of a vertical collection of collapsible tool sets ''' import wx class ToolSet(wx.Panel): """A simple class that maintain tools and that can be hidden or showed.""" _triUp = None _triDown = None def __init__(self, parent, id =...
# coding=utf-8 from g2p_aligner import load_transcription def load_process_rules(process_rules_file_name): """ Load process rules file to rule list. :param process_rules_file_name: :return: a list containing rules like: [ (grapheme:string, phones:list, modified_phone:string),...
""" get scores for F1 Threshold(rho) experiments for competitive approaches """ # requires: # - json file with predicted answers # - json data file from __future__ import print_function from collections import Counter import string import re import argparse import json import sys import numpy as np from collect...
# -*- coding: utf-8 -*- """ Created on Fri May 14 14:11:23 2021 @author: freeridingeo """ import numpy as np import xarray as xr import pandas as pd from eolearn.core import FeatureParser import sys sys.path.append("D:/Code/eotopia/metadata") from metadata_geographical import (get_eopatch_coordinates) from metadata...
#!/usr/bin/env python3 import ast from itertools import islice import os from pprint import pprint import sys import traceback from arpeggio import Optional, ZeroOrMore, OneOrMore, EOF from arpeggio import ParserPython, PTNodeVisitor, visit_parse_tree, ArpeggioError from arpeggio import RegExMatch as _ from stdlib im...
from decimal import * import os import random import datetime # Define Global Variables Hopper = int(500) InCred = int(0) OutCred = int(0) Balance = int(0) SpinCount = int(0) ToPay = int(0) ReelDisplay = str("0 0 0") InfoStrip = "See your host to begin!" UseConfig = "N" # Set Reels (This does determine odds and payou...
#!/usr/bin/env python3 # Copyright 2015 Intel Corporation # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modif...
import os import requests import json import traceback import src.parsers.variant_xml_parser as v_xml_parser from src.helpers.variant_helpers.primary_transcript import get_primary_transcript from src.helpers.variant_helpers.hgvs_notation import get_hgvs_notation def find(hgvs_notation: str, grouping=True): """Q...
import numpy as np import torch import torch.nn as nn import numpy as np from PIL import Image ## NeRFmm Import import thirdparty.ATE as ATE def make_rand_axis(batch_size): vec = (np.random.rand(batch_size, 3) - 0.5) mag = np.linalg.norm(vec, 2, 1, keepdims=True) vec = vec/mag return vec def R_axis_...
# -*- coding: utf-8 -*- ################################################################################ # _____ _ _____ _ # # / ____(_) / ____| | | # # | | _ ___ ___ ___ | (___ _ _ ___...
from dataclasses import dataclass from typing import Callable, Tuple, List import numpy as np import torch import torch.nn as nn from devices.light_curtain import LCReturn from policies.actors import Pi from policies.actors.actor import Actor from policies.critics.critic import Critic import utils @utils.register_c...
# -*- coding: utf-8 -*- """ Created on Fri Feb 7 13:53:58 2020 @author: malot """ from __future__ import division from PyQt5 import QtWidgets #from PIL import Image import os import numpy as np #import glob #import pylab import tomopy from os import mkdir from os.path import join, isdir from imageio import imread, ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Queries the commercetools API, transforms data into pandas DataFrame, and exports data to csv (purchases/orders) and xml (product catalog) files. @author: amagrabi """ import pandas as pd from lxml import etree import config import nr import make_df_full import a...
from __future__ import print_function, division import torch import torch.nn as nn from torch.autograd.gradcheck import zero_gradients import numpy as np from . import utils as ut from . import base_attack from collections import namedtuple Deepfool_Return_Payload = namedtuple("Deepfool_Return_Payload", ["delta", ...
# Compute dN/dt, using the formalism in Lamers et al. (2005, L05), # assuming a truncated power-law cluster IMF # # Author: <NAME>, with additions by <NAME> (ICCUB) # Last modified: 27.11.2020 # # Reference: https://ui.adsabs.harvard.edu/abs/2020arXiv200601690A/abstract from __future__ import division import numpy fr...
import argparse from mmcv import Config from mmcv.cnn import get_model_complexity_info from mmcv.cnn.utils.flops_counter import flops_to_string, params_to_string #from mmseg.models import build_segmentor import torch from isegm.model.modeling.segformer.segformer_model import SegFormer from isegm.model.is_segformer_mo...
# -*- coding: utf-8 -*- """ test_utils ~~~~~~~~~~ Tests for helper functions. :copyright: 2015 by <NAME>, see AUTHORS :license: United States Geological Survey (USGS), see LICENSE file """ import pytest import numpy as np from gagepy import utils from datetime import datetime import os def test...
import backbone.support.classes_and_adjustments as ca import backbone.support.configurations_variables as confv import numpy as np import backbone.support.directory_file_checking as dfc import os from tqdm import tqdm import backbone.support.data_loading as dl import librosa import backbone.support.calculations as calc...
from math import ceil import pandas as pd import numpy as np import torch import torch.utils.data as tud import os import sys sys.path.append('..') from utils import config as cfg class HarmonixDataset(tud.Dataset): '''Harmonix dataset object. To follow the idea of the original paper, each chunk is aligned w...
# Burning Flame simulation and Tetris-like game # BBC Micro:bit # <NAME>, 2019 from microbit import display, button_a, button_b, sleep import random class Particle: __max_x_pos = 4 __max_intensity = 9 __min_intensity = 1 __max_fading = 3 __min_fading = 1 def reset( self ): self.ypos =...
import caffe import yaml import json import numpy as np import os import random import gzip def proto_load(file_path): # load .gz version if exists # AD_HOC implementation if os.path.isfile(file_path + '.gz'): file_path += '.gz' if os.path.splitext(file_path)[1] == '.gz': with gzip.Gzip...
from torch import optim from torch.utils.data import DataLoader from tqdm import tqdm, trange from emb_modeling import ContextStaticModel from emb_dataset import Mydataset import torch from torch.nn import functional as F import json import time import numpy as np from emb_config import model_config,train_config,data_c...
from PIL import Image from matplotlib import pyplot as plt import matplotlib.patches as patches from collections import Counter from pathlib import Path import numpy as np import tensorflow as tf import os from dataset import HandsegDataset from dataset_bboxes import HandsegDatasetBboxes from src.utils.paths import HAN...
# Copyright 2020 Open Reaction Database Project 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 applicable l...
#!/usr/bin/python # -*- coding: utf-8 -*- __author__ = '<NAME>' __version__ = '0.1' from os.path import dirname, abspath from argparse import ArgumentParser import re parser = ArgumentParser(description='Update ChibiOS halconf and mcuconf from STM32CubeMX project files.') parser.add_argument('cube', type=str, help='S...
import pygame SCREEN_WIDTH = 800 SCREEN_HEIGHT = 576 # Define some colors BLACK = (0,0,0) WHITE = (255,255,255) class Player(pygame.sprite.Sprite): change_x = 0 change_y = 0 explosion = False game_over = False def __init__(self,x,y,filename): # Call the parent class (sprite...
#%% [markdown] # # Flow ranking and hypothesis testing # TODO: explain the goal of finding a latent ordering, comparing between graphs #%% [markdown] # TODO: explain some of the math behind spring rank/signal flow #%% import os import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as ...
from tkinter import * # Defining region codes INSIDE = 0 # 0000 LEFT = 1 # 0001 RIGHT = 2 # 0010 BOTTOM = 4 # 0100 TOP = 8 # 1000 x_max = 350 y_max = 350 x_min = 50 y_min = 50 def computeCode(x, y): code = INSIDE if x < x_min: # to the left of rectangle code |= LEFT elif...
#!/usr/bin/env python3 """ A script to run on your phone (running in Termux under Android). """ # TODO local sync with SFTP to an isolated location on the computer? Some watcher would pick up the files. # TODO sync to cloud # - get last filename from scaleaway # - send encrypted chunks (contain entire photos) # - enc...
# -*- coding: utf-8 -*- # @Time : 2018/5/8 下午7:24 # @Author : yidxue # MLP 是一种前向结构的人工神经网络。一个MLP至少由三层节点组成。除输入节点外,每个节点都是使用非线性激活函数的神经元。 # MLP使用称为“反向传播”的监督学习技术进行训练。其多层和非线性激活将MLP与线性感知器区分开来。 # 它可以区分不能线性分离的数据。 # https://www.toutiao.com/a6552804995442409991/?tt_from=weixin&utm_campaign=client_share&timestamp=1525776941&ap...
# -*- coding: utf-8 -*- ''' @author: <NAME> @contact: <EMAIL> @description: ranking comparison-related method tests. ''' # DEPENDENCIES ================================================================= import numpy as np import pandas as pd from scipy.stats import norm from gpseqc.compare import * # PARAMS =======...
import json from unittest.mock import call, patch, sentinel import pytest import scaraplate.automation.gitlab from scaraplate.automation.gitlab import ( GitLabCloneTemplateVCS, GitLabMRProjectVCS, gitlab_available, gitlab_clone_url, gitlab_project_url, ) from scaraplate.template import TemplateMet...
# -*- coding: latin-1 -*- import copy from . import conditions from . import effects from . import pddl_types class Action(object): def __init__(self, name, parameters, precondition, effects, cost): self.name = name self.parameters = parameters self.precondition = precondition sel...
"""Mouse bindings.""" from copy import copy import numpy as np from ._region_constants import Orientation from ._region_utils import preprocess_region def highlight(layer, event): """Highlight hovered regions.""" layer._set_highlight() def add(layer, event): """Add new infinite region.""" # on pre...
from c0101_retrieve_ref import retrieve_ref from c0101_retrieve_ref import retrieve_ref_color from c0101_retrieve_ref import retrieve_ref_color_wearable_segment from c0101_retrieve_ref import retrieve_sensor_unit from c0102_build_path import build_path from c0104_retrieve_meta import retrieve_meta from c0402_retrieve_...
from collections import Counter from sarge import run, Capture from dependency_management.Helper import is_executable_exists from dependency_management.requirements.AnyOneOfRequirements import ( AnyOneOfRequirements) from dependency_management.requirements.ExecutableRequirement import ( ExecutableRequirement)...
""" #Dashboard_Bokeh v1.0 #Autor: <NAME> #Date: 1/Enero/2019 #Description: Make a dashboard with Bokeh library """ #Import modules import pandas as pd import numpy as np from bokeh.io import curdoc from bokeh.models import ColumnDataSource,Select from bokeh.plotting import figure from bokeh.palettes impor...
"""Crystal Orbital Overlap Population calculation. Index ----- .. currentmodule:: nanoqm.workflows.workflow_coop .. autosummary:: workflow_crystal_orbital_overlap_population """ from __future__ import annotations __all__ = ['workflow_crystal_orbital_overlap_population'] from typing import Tuple, TYPE_CHECKING ...
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.distributions.categorical import Categorical import sys sys.path.insert(0, '../') from networks.quant_layer import Linear_Q, Conv2d_Q def batch_conv(x, weight, bias=None, stride=1, padding=0, dilation=1, groups=1): if...
# # SPDX-FileCopyrightText: 2021 <NAME> <<EMAIL>> # # SPDX-License-Identifier: Apache-2.0 # from os import path,makedirs,getcwd,mkdir import errno import logging import argparse import re from subprocess import run import tarfile import yaml from diadmin.utils.utils import add_defaultsuffix, toggle_mockapi from di...
# A streamline do searchlight analysis across participants # Streamline included several steps below. # 1. Seperate cifti t map from each subject into metrics in left/right hemispheres # 2. Do searchlight analysis, and save it. # 3. Merge correlations in left/right hemispheres together. # 4. Extract the averaged correl...
import torch import torch.nn as nn import torch.nn.functional as F import math import numpy as np from .Util import * import torch.distributed as dist class ConvBlock_ablation(nn.Module): def __init__( self, inputSize, outputSize, hiddenSize, kernelSize...
import time import uuid from botocore.stub import Stubber from dagster import check class ECSError(Exception): pass class ECSTimeout(ECSError): pass class ECSClient: def __init__(self, client, cluster, subnets, polling_interval=5, max_polls=120): check.invariant( polling_interval ...
from enum import Enum class op(Enum): GAP_A = 1 GAP_B = 2 MA_MM = 3 def parseNucleotide(nucleotide): switcher = { 'A': 0, 'T': 1, 'G': 2, 'C': 3, 'N': 4 } return switcher.get(nucleotide,"Invalid nucleotide") def get_score(score_mtx,characterA,characterB...
import locate from pathlib import Path import os import tempfile import shutil import subprocess import uuid _compile_vbs = locate.this_dir().joinpath("bin", "compile.vbs") _decompile_vbs = locate.this_dir().joinpath("bin", "decompile.vbs") _runmacro_vbs = locate.this_dir().joinpath("bin", "runmacro.vbs") _saveasxlsx_...
from treelib import Node, Tree import numpy as np import math import copy from matplotlib import pyplot as plt import time import config from car import Car from optim_steer import optimSteer, ackermann_to_differential from probability_map import generateMap, sample def diff_kinematic(state,u): newState...
import config import matplotlib.pyplot as plt import matplotlib.patches as patches import numpy as np import os import random import torch from nms import nms from collections import Counter from torch.utils.data import DataLoader from tqdm import tqdm def plot_particles(image, boxes, scores=True, pixels=F...
import pandas as pd from sklearn import linear_model from sklearn.exceptions import ConvergenceWarning import logging import warnings def logistic_regression( data=None, dependent=None, predictors=None, regressions='available', inplace=False): """Performs logistic regression imputation on the data...
from builtins import object import logging import os from pynamodb.models import Model from pynamodb.attributes import UnicodeAttribute, BooleanAttribute from pynamodb.indexes import GlobalSecondaryIndex, AllProjection """ DbTrust handles all db operations for a trust Google datastore for google is used as a b...
""" MIT License Copyright (c) 2020-2022 thatsOven Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish...
"""Definition and setup of the Satellite Tracker Sensors for Home Assistant.""" import logging import time import datetime from homeassistant.util.dt import as_local, utc_from_timestamp from homeassistant.components.sensor import ENTITY_ID_FORMAT from homeassistant.const import TIME_SECONDS, ATTR_NAME from homeassist...
""" Binary tree. """ class Node: """Binary tree node.""" def __init__(self, key, left=None, right=None, p=None): self._key = key self._left = left self._right = right self._p = p @property def key(self): """The key of the node.""" return self._key ...
# -*- coding: utf-8 -*- import math import logging logger = logging.getLogger(__name__) class NoPruning: @classmethod def filter(cls, Pe, Le, Te, *args): for i in range(1, len(Pe)+1): for j in range(i+1, len(Pe)+1): yield i, j class LazyCountPruning: @cla...
from django.shortcuts import render, get_object_or_404, redirect from django.contrib.auth import get_user_model, decorators from django.core.paginator import Paginator from django.db.models import Count from .models import Post, Group, Comment, Follow from .forms import PostForm, CommentForm User = get_user_model() ...
#!/usr/bin/env python """ This module runs the performance tests to compare the ``re`` module with the ``re2`` module. You can just run it from the command line, assuming you have re2 installed, and it will output a table in ReST format comparing everything. To add a test, you can add a function to the bottom of this ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2021 <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 ...
from pprint import pprint from math import floor from math import sqrt from uuid import uuid4 ### CHANGE THESE VARIABLES TO CHANGE GRID GENERATION # digits = each point is placed in a box generated from the lat/lon coordinates, # by rounding down to the nearest digit specified by digits. # If ...
""" This program compares two snapshots generated with methodmap and outputs a report showing the differences difference reports follow this form: REL=<relnumber>;VER=<vernumber>;MISSING|MOVED|DEL|ADD;<msg> The message following MISSING|MOVED|DEL|ADD will have the following interpretation and form: MISSING: means e...
import simpy def main(tijd): env = simpy.Environment() wachtrij = simpy.Resource(env, capacity=4) TL = TrafficLight(env, groen_duur=30, geel_duur=7, rood_duur=22, grens=2) car0 = Car(env, TL, wachtrij, "Thijs", duurOp=10) car1 = Car(env, TL, wachtrij, "Freek", duurOp=9) car1 = Car(env, TL, w...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # @Author: <NAME> (<EMAIL>) # @Date: 2019-10-05 # @Filename: testing.py # @License: BSD 3-clause (http://www.opensource.org/licenses/BSD-3-Clause) from __future__ import annotations import asyncio import json import re import sys import types import unittest.mock from ...
from time import time from numba import njit import re from typing import Any, Callable, Collection, Dict, Hashable, List, Mapping, Optional, Set, Tuple import numpy as np import matplotlib.pyplot as plt from enum import Enum, auto import random from itertools import count, product from functools import partial class...
import csv import random import numpy as np import math import matplotlib.pyplot as plt import time from tqdm import tqdm # setting city_num = 48 # total number of cities city_loc = np.loadtxt('city_location.txt') # list of city coordinates neigh_max = 50 # neighbor max number iter_num = 20000 # iterat...
import pandas as pd import plotly from plotly import offline as py from augustus.system.metabase_env import augustusEnvBase class PlotBase(augustusEnvBase): def __init__(self): super().__init__() self.positions_df = self.env.recorder.position.dataframe() self.holding_pnl_df = self.env.r...
import json from unittest.mock import MagicMock, patch import pytest import requests from airflow.models.connection import Connection from ideafast_etl.hooks.jwt import JwtHook def test_find_jwt_token(haystack): """Test that a deep token can be found""" path = "haystack1.haystack2.haystack4" jwt_hook = ...
# Copyright 2021 UW-IT, University of Washington # SPDX-License-Identifier: Apache-2.0 from django.utils import timezone from django.conf import settings from endorsement.dao.uwnetid_categories import ( set_active_category, set_former_category) from endorsement.dao.uwnetid_subscriptions import ( activate_subscr...
import numpy as np from PyQt5 import QtGui, QtCore from pyqtgraph import PlotWidget, mkPen, LegendItem class PLWidget(PlotWidget): def __init__(self, engine, lines): super(PLWidget, self).__init__() self.styles = {'color':'b', 'font-size':'18px'} self.setBackground('w') self.showGri...
#!/usr/bin/env python3 # File: sudoku.py # Author: <NAME> # Contains a class which has a 9x9 grid, including all things necessary about a sudoku "backend" # This class is made to not mix up with the Qt UI. import random import sys def eprint(*args, **kwargs): print(*args, **kwargs, file=sys.stderr) class Sudo...
import events from entities import Deck, Player, Match, GameOverException, Effect class IllegalOperation(Exception): def __init__(self, message): super(IllegalOperation, self).__init__(message) def assert_get_resource_by_index(index, container, entity_name): if index < 0 or index >= len(container):...
from __future__ import absolute_import, print_function, unicode_literals from validator.constants import BUGZILLA_BUG from ..regex.generic import FILE_REGEXPS from .jstypes import Global, Hook, Interfaces # SQL. SYNCHRONOUS_SQL_DESCRIPTION = ( 'The use of synchronous SQL via the storage system leads to severe ...
# # File: FIXReader.py # Author: blee4 # Date: 25 April 2018 # Purpose: Create a FIX parser and answer the following questions: # 1. How many instruments of each security type (tag 167) exist? # 2. How many futures (tag 167) instruments exist in each product complex (tag 462)? # 3. ...
#!/usr/bin/python3 # -*- coding: utf-8 -*- import re import string import nltk import wordninja from nltk import word_tokenize from nltk.corpus import wordnet from nltk.stem import WordNetLemmatizer from nltk.stem.porter import PorterStemmer from nltk.stem.snowball import SnowballStemmer from sklearn.base import Bas...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # Adapted from https://github.com/facebookresearch/SlowFast/blob/master/slowfast/visualization/gradcam_utils.py from operator import attrgetter import matplotlib.pyplot as plt import torch import torch.nn.functional as F d...
from itertools import combinations from collections import Counter import numpy as np import pandas as pd import networkx as nx from networkx.algorithms import bipartite def generate_edge_list(df: pd.DataFrame) -> pd.DataFrame: df['pairs'] = df['author'].map(lambda x: list(combinations(x, 2))) edge_list = pd...
import numpy as np from sklearn.pipeline import Pipeline from sklearn.feature_extraction.text import CountVectorizer from sklearn.svm import LinearSVC, SVC from sklearn.feature_extraction.text import TfidfTransformer from sklearn.multiclass import OneVsRestClassifier from sklearn.metrics import zero_one_loss import sk...
from __future__ import print_function import json import os from collections import OrderedDict from fhirclient.models import fhirdate, observation, patient, familymemberhistory, quantity, relatedperson from observation_commons import * from db_references import * from dateutil.relativedelta import relativedelta def ...
from discord import Embed, Interaction, ButtonStyle from discord.ui import button, View from discord.ext import commands from datetime import datetime from typing import Optional from ..echoes.echoes_cogs import EchoesCog from ..db.db import Playlist class PaginatorView(View): def __init__(self, pages: list[Embed...
""" Example of how to trace a Fresnel Zone Plate by <NAME> and <NAME>. 1) The source is from get_beam(), is a collimated source of squared cross section (800 microns), monochromatic (1.54 A) 2) fresnel_zone_plane() calculates a fzp, centered at (0,0). It returns a new shadow3 beam containing the beam after the...
from typing import Optional, List import numpy as np from my_collection import suls from PIL import Image from matplotlib import pyplot as plt from pathos.multiprocessing import ProcessPool import basis from basis.laplacian import create_grid_adj_matrix """ this example recovers an image with missing pixels by trans...
#all nine mole conversion functions #Grams to Moles def gramToMole(gram,molarMass): return gram / molarMass #Grams to Molels to Particles def gramToMoleToParticle(gram,molarMass): return (gram / molarMass) * (6.022*(10**23)) #Grams to Moles to Particles to Atoms def gramToMoleToParticleToAtom(gram,molarMass,...
# -*- coding: utf-8 -*- """ Created on Wed May 20 12:10:29 2020 @author: Nick # *********************************************************************** # read the 6-n params file. Format: atnum, rep, rmin,emin # here is an example file for MM3 params # 0 0.205 1.53 0.026 # 1 12.0 1.62 0.02 # 6 12.0 2.04 0....
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np class CausalConv1d(torch.nn.Conv1d): def __init__(self, in_channels, out_channels, kernel_size, stride=1, dilation=1, groups=1...
#!/usr/bin/env python3 import re import logging import argparse import os import subprocess import time import signal logging.basicConfig( level=logging.INFO, format='%(asctime)-15s %(levelname)-8s %(name)-20s %(message)s' ) logger = logging.getLogger('waveroam') parser = argparse.ArgumentParser(description='w...
import glob import json import math import os import shutil import tarfile import time import typing import pyrogram config = None with open(file="config.json", encoding="utf-8") as f: config = json.load(fp=f) def PrintUser(user: typing.Union[pyrogram.types.Chat, pyrogram.types.User]) -> str: ...
import numpy as np import tensorflow as tf from functools import * from tensorflow.keras import Model from tensorflow.keras.layers import * import matplotlib.pyplot as plt import pandas as pd def load_data(): data = np.load("data/batt_processed_min.npz", allow_pickle=True) x_train = data['x_train'] y_trai...
from contextlib import contextmanager import filecmp import mock import os import shutil import tempfile import pytest from six.moves import shlex_quote import yaml import mlflow from mlflow.projects import Project, ExecutionException TEST_DIR = "tests" TEST_PROJECT_DIR = os.path.join(TEST_DIR, "resources", "example...
import shlex import shutil import subprocess import json, os from pathlib import Path from collections import defaultdict, OrderedDict def fairseq_preprocess(src, tgt, destdir, trainpref=None, validpref=None, testpref=None, srcdict=None, **kwargs): additional_cmds = ''.join([f"--{k.replace('_', '-')} {v} " for k, ...
import numpy as np from scipy.special import hyp2f1 def from_nfw(rhos_NFW,rs_NFW): ''' Convert from NFW profile to postencounter density profile. See arXiv:1907.13133 for the profile and arXiv:xxxx.xxxxx for a refinement. Parameters: rhos_NFW, rs_NFW: scale parameters associated with th...
# pylint:disable=unused-argument import typing from typing import List, Optional, Tuple, TYPE_CHECKING import threading import asyncio from tornado.platform.asyncio import AnyThreadEventLoopPolicy import PySide2 from PySide2.QtWidgets import QDialog, QPushButton, QHBoxLayout, QVBoxLayout, QMessageBox, QTableView, \ ...
""" ################################################################################################## # Copyright Info : Copyright (c) <NAME> @ Hikvision Research Institute. All rights reserved. # Filename : affine_transformation.py # Abstract : Implementations of the affine transformation # Curr...
#!/usr/bin/python3 # from https://raw.githubusercontent.com/Klabbedi/ev3/master/Line_follow_2.py # coding: utf-8 from time import sleep from ev3dev.auto import * # ------Input-------- print('Setting input values') power = 60 power = 20 power = 40 target = 55 kp = float(0.65) # Proportional gain. Start value 1 kp = f...
# -*- coding: utf-8 -*- # @Author : gwentmaster(<EMAIL>) # I regret in my life """代理管理""" import ctypes import logging import random import time import winreg from dataclasses import dataclass from math import inf as INF from queue import Empty, Queue from threading import Event from typing import Any, Dict, Optio...
from ..optimize import cull, fuse from ..core import flatten from ..optimize import dealias, inline_functions from .core import getarray from operator import getitem from dask.rewrite import RuleSet, RewriteRule from toolz import valmap, partial import numpy as np def optimize(dsk, keys, **kwargs): """ Optimize d...
#!/usr/bin/python # # Copyright 2010 Google 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 ag...
#!/usr/bin/python3 # Demonstrates using Quadric Objects # <NAME> # <EMAIL> # # Based heavily on: sphereworld.cpp # OpenGL SuperBible # Program by <NAME>. from OpenGL.GL import * from OpenGL.GLUT import * from OpenGL.GLU import * from PIL import Image import time ESCAPE = b'\033' from random imp...
import os import sys import copy import difflib import click from .vagga import Config as Vagga from . import lithos from . import metadata from .main import main as cli from .human import panic from .vagga_command import extract_command_info def _careful_update(old_config, old_info, new_info, *, verbose): new...
from .jsobject import JSObject import json import IPython # Store tool manager state window = None cache_time = None tools = None _py_funcs = {} class NBTool: """ Tool class, used to register new tools with the manager """ origin = None id = None name = None description = None attrib...
# -*- coding: utf-8 -*- #------------------------------------------------------------------------------ # Importes das bibliotecas utilizadas import logging import time import pandas as pd import pickle from utils.log_factory import Log from os.path import dirname, abspath, join import w...
import numpy as np from toolkitJ import cell2dmatlab_jsp import GVal def fScore(beta, P, R): F = (1 + beta**2) * (P * R) / ((beta**2) * P + R) return F def dataSetPreparation(feature_index, X_train_raw, Y_train_raw, X_valid_raw, Y_valid_raw): X = X_train_raw[:, feature_index] y = Y_t...
import time import warnings from itertools import count from typing import Sequence, Tuple, Iterator import gym import numpy as np import torch from more_itertools import consume from torch import Tensor from learner.LSGAN import LSGAN from learner.utils import print_message, display_goals ''' PARAMETERS ''' Rmin = ...