text
stringlengths
3.07k
12.6k
import csv def printContents(): with open ('DataSet.csv',"r",newline="") as f: print("Contents of file") ReadObj= csv.reader(f) for line in ReadObj: print(line) def CountEach(): with open ('DataSet.csv',"r",newline="") as f: global AdsCount g...
""" This module contains small scripts for managing the database entries for NorLyst application. """ import sys from os.path import realpath from datetime import datetime from nordb.core.usernameUtilities import log2nordb from nordb.database.nordicSearch import searchSameEvents from nordb.nordic.nordicEvent import No...
#!/pygame_snake_oop/bin python import pygame from random import randint from time import sleep class Snake(): def __init__(self, screen_width, screen_height): self.snake_ate = 0 self.snake_life = 'alive' self.snake_direction = 'rigth' self.snake_body = [[10, 30], [10, 20], [10, 10]] self.snake_color = (...
# Copyright ClusterHQ Inc. See LICENSE file for details. """ Tests for :module:`admin.merge_pr`. """ import os import subprocess from hypothesis import given from hypothesis.strategies import ( booleans, dictionaries, fixed_dictionaries, just, lists, one_of, sampled_from, text, ) ...
from __future__ import print_function import sys import os import re def getColumnNameAndType(s): d = '' index = 0 index2 = s.find(' ', index+1 ) s2 = s[index2 + 1:].strip() index3 = s2.find(' ') n = s[index:index2] t = s2[:index3] index_default = s.find(...
# -*- coding: utf-8 -*- from __future__ import division, print_function __all__ = ["Parameter", "UnitVector", "Model"] import numpy as np import tensorflow as tf def get_param_for_value(value, min_value, max_value): if ((min_value is not None and np.any(value <= min_value)) or (max_value is not Non...
# -*- coding: utf-8 -*- """ Created on Thu Mar 28 09:29:03 2019 @author: Philip """ from GNewsAnalysis.utils import editionMap, topicMap, langMap, orderMap import requests from tqdm import tqdm from bs4 import BeautifulSoup import pandas as pd from newspaper import Article import matplotlib.pyplot as plt ...
from subprocess import call import os PAIRWISE_THRESHOLD = 1.e-1 FEATURE_DIFF_THRESHOLD = 1.e-6 class LibSvmFormatter: def processQueryDocFeatureVector(self,docClickInfo,trainingFile): '''Expects as input a sorted by queries list or generator that provides the context for each query in a...
import asyncio from pyppeteer import launch import aiohttp import pymongo import jieba import jieba.analyse as analyse import collections import time from textrank4zh import TextRank4Keyword, TextRank4Sentence import re search_url = 'https://www.zhihu.com/search?range=1w&type=content&q=' get_answers_by_id_url = 'https...
""" Auxiliarry functions for the pointwise gravity spherical harmonics expansion. """ import warnings import numpy as np from joblib import Parallel, delayed from .legendre import lplm, lplm_d1 np.seterr(over='raise') def expand_parallel(x, q, *args): nlat = x.shape[0] # parallel only if there are more than...
""" This cpawd.taskRunner module implements the running of all watch-do tasks. ---- The following description is illustrated in the interaction diagram below. The top level `runTasks` method initiates an `asyncio.Tasks` running the `watchDo` method for each watch-do task. The `watchDo` method `reStart`s an `asyncio....
"""Upload CSMR data to t3 table so EpiViz can access it for plotting.""" import pandas as pd from cascade.core import getLoggers from cascade.core.db import cursor, db_queries from cascade.input_data.db import METRIC_IDS, MEASURE_IDS, GBDDataError CODELOG, MATHLOG = getLoggers(__name__) def _csmr_in_t3(execution_c...
from tkinter import * import random import PA_func as pf import sqlite3 import datetime import Expressions as xp sqlite_file = 'assistant.sqlite' conn = sqlite3.connect(sqlite_file) c = conn.cursor() now = datetime.datetime.now() def start_gui(): master = Tk() master.geometry('450x400') m...
"""Tests for `fake_data_for_learning` package.""" import pytest import numpy as np from sklearn.preprocessing import LabelEncoder from fake_data_for_learning.fake_data_for_learning import ( BayesianNodeRV, SampleValue ) # (Conditional) probability distributions @pytest.fixture def binary_pt(): return np.arr...
""" Base classes used to setup testing fixtures """ import itertools from django.core.files.uploadedfile import SimpleUploadedFile from django.contrib.auth.models import AnonymousUser, User, Permission from django.utils.text import slugify from assessment.builder import models, choices from assessment.assess impo...
# Copyright (c) 2015 SONATA-NFV, 2017 5GTANGO # 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 ...
# coding: utf-8 import sys import os from operate_file import abstractReadFile import re import error_check def make_HydrogenBond(line, extracted_data, d_p_dict): dssp_ID = int(line[:5]) pdb_ID = int(line[5:10]) chain = line[11] d_p_dict.setdefault(dssp_ID, [pdb_ID, chain]) axes_CA = [float(line[1...
""" Settings """ from importlib import import_module import six import json from collections import MutableMapping from . import default_settings TORNADO_APP_SETTINGS_PREFIX = "TORNADO_APP_SETTINGS_" TORNADO_SERVER_SETTINGS_PREFIX = "TORNADO_SERVER_SETTINGS_" class Settings(MutableMapping): def __init__(self, ...
''' Send email module of the LS CI/CD Integration toolkit, implements the necessary methods to notify of the results of the CI/CD process''' import os import smtplib import sys from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from string import Template import traceback from ...
import copy import numpy as np import imageio import torch import torch.nn.functional as F from models.rendering import get_rays_tourism, sample_points, volume_render def test_time_optimize(args, model, meta_state_dict, tto_view): """ quicky optimize the meta trained model to a target appearance and retur...
# -*- coding: utf-8 -*- import pandas as pd import re from urllib.parse import quote_plus from vespid import setup_logger import gzip import os import shutil from vespid import setup_logger, set_global_log_level logger = setup_logger(module_name=__name__) def replace_special_solr_characters(data, columns=None): ...
# This is a sample Python script. # Press ⌃R to execute it or replace it with your code. # Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings. import nltk from nltk import punkt from nltk.corpus import stopwords import matplotlib.pyplot as plt LINES = ['-', ':', '--'] # Line s...
import gc import os import pickle from skopt import gp_minimize from skopt.callbacks import CheckpointSaver from skopt import load import pandas as pd from EEG_Model.EEG_gpt2 import EEG_GPT2 from EEG_Model.EventDataset import EventDataset """" Global variables are necessary due to the Bayesian Optimization used """ t...
""" Scripts to parse the gender data for the PhD recipients. genderize.io gender-api.com """ import urllib import json import yaml import glob import numpy as np import astropy from astropy.io import ascii import requests import os ### gender-api.com GENDER_API_KEY = os.getenv(GENDER_API_KEY) ### genederize.io GEND...
import functools import numpy as np from estimagic.batch_evaluators import joblib_batch_evaluator from src.manfred.minimize_manfred import minimize_manfred def minimize_manfred_estimagic( internal_criterion_and_derivative, x, lower_bounds, upper_bounds, convergence_relative_params_tolerance=0.00...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import division from __future__ import print_function import os import io import time import numpy as np import scipy.io as sio from scipy import sparse as sp from scipy import spatial import cPickle as pkl import networkx as nx import rando...
#!/usr/bin/env python import functools import math import numpy import hypothesis import hypothesis.extra.numpy from hypothesis.strategies import complex_numbers, floats import libnu.array from test import eq arrays = functools.partial( hypothesis.extra.numpy.arrays, shape=10, unique=True, ) numpy.ones...
# Copyright (c) <NAME> # See LICENSE for details. """ Implementations to some of the abstract classes used by this module. """ import os import time from uuid import uuid4 try: from ConfigParser import RawConfigParser except ImportError: # noinspection PyUnresolvedReferences from configparser import RawCo...
import pandas as pd import sklearn as sk import scipy import numpy as np import matplotlib.pyplot as plt import seaborn as sns def plot_general_statistics(df): means = df.mean(axis=1) medians = df.median(axis=1) std = df.std(axis=1) maxval = df.max(axis=1) minval = df.min(axis=1) skew = df.ske...
# data.world-py # Copyright 2017 data.world, 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 agr...
#! /usr/bin/env python3 # Copyright(c) 2019 Intel Corporation. # License: MIT See LICENSE file in root directory. from argparse import ArgumentParser, SUPPRESS from openvino.inference_engine import IENetwork, IEPlugin, IECore import cv2 import logging as log import numpy as np import os import sys import time # Spec...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Sep 30 19:29:51 2018 @author: pi """ import logging from radiostate import RadioState from wifiscanner import WifiScanner from radioevents import StationButtonEvent, PowerButtonEvent from encoder import EncoderEvent from powerbutton import PowerEvent ...
from __future__ import annotations from dataclasses import dataclass from typing import Sequence, Tuple, Optional, List, Dict, Any, Iterable import logging from pathlib import Path import os from concurrent.futures import ThreadPoolExecutor from requests import HTTPError from catpy.applications import CatmaidClientApp...
"""Code used to create the examples in the overflow paper. This module contains the code used to create the examples in the paper at https://arxiv.org/pdf/2001.09611v1, referred to as the overflow paper. Execute this module as a script to reproduce the examples. The code has been tested using Python 3.5.2, NumPy ...
from dataclasses import astuple, dataclass import numpy as np import torch from copy import deepcopy class Binarizer: def __init__(self, binarization): self.bin = binarization def __call__(self, tens): if self.bin is None: return tens elif self.bin[0] == "neq": ...
import argparse import os import sys from pathlib import Path import datetime, pytz import cv2 import numpy as np import torch import torch.backends.cudnn as cudnn from models.experimental import attempt_load from utils.datasets import LoadImages, LoadStreams from utils.general import apply_classifier, check_img_size...
"""analog to itertools from standard library""" import operator from functools import partial from sicp_streams import Stream def smap(func, *streams): def resolve(): tails = [s.tail for s in streams] if not all(tails): return None else: return smap(func, *tails) ...
"""Contains specialization functions for dense_cupy. These are the functions that are defined outside of qutip/core/data/dense.pyx.""" import cupy as cp from .dense import CuPyDense def tidyup_dense(matrix, tol, inplace=True): return matrix def reshape_cupydense(cp_arr, n_rows_out, n_cols_out): return Cu...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Sep 8 13:43:52 2021 @author: renaud https://stackoverflow.com/questions/29211794/how-to-bind-a-click-event-to-a-canvas-in-tkinter """ import tkinter as tk import random import time haut = 10 # table heigth larg = 10 # table width cote = 40 # cell...
import numpy as np import matplotlib import matplotlib.pyplot as plt import matplotlib.lines as lines import matplotlib.text as text import matplotlib.patches as patches import argparse import sys from matplotlib.backends.backend_pdf import PdfPages from emma.processing.dsp import butter_filter from common import * d...
import torch from torch.backends import cudnn cudnn.enabled = True from torch.utils.data import DataLoader import torch.nn.functional as F import importlib import voc12.dataloader from misc import pyutils, torchutils def validate(model, data_loader): print('validating ... ', flush=True, end='') val_loss_m...
""" All functions that take input (other than the game mainloop). interface.poll() returns (libtcod.Key, libtcod.Mouse) with key *presses* and mouse events, but not key *releases*. interface.parse_move(key) translates a libtcod.Key into directional movement. interface.log_display(width=60) interface.target_tile(acto...
from __future__ import division, print_function, absolute_import import os import numpy as np from dipy.direction.peaks import (PeaksAndMetrics, reshape_peaks_for_visualization) from dipy.core.sphere import Sphere from dipy.io.image import save_nifti import h5py def _safe_save(grou...
# -*- coding: utf-8 -*- """ Created on Mon May 14 16:50:33 2018 @author: ADay """ import os import pandas as pd import numpy as np import requests import time import json def get_earliest_date(item): """ Given a crossref works record, find the earliest date. """ tags = ['issued','created','indexed',...
import os import StringIO from PIL import Image import base64 from spriter.image import FileImage, URLImage, class_name_function as cnf class DefaultImageDoesNotExist(Exception): message = "The default image path must be exist. Not found in: " def __init__(self, path): super(DefaultImageDoesNotExist,...
# Copyright 2020 The MiNLP 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 applicable l...
import ast import collections import itertools import logging import os import sys from argparse import ArgumentParser from enum import Enum from pprint import pformat from typing import Dict, Iterator, List, Optional, Set, Tuple class DuplicateEnumClassError(Exception): pass class DuplicateEnumItemError(Except...
# -*- coding: utf-8 -*- """OSIRIS custom regions.""" import os import argparse import six import glob import subprocess import astropy.units as u from astropy.coordinates import SkyCoord, BaseCoordinateFrame, ICRS from ...regions import Box, Circle, Region, Ruler, RegionFile from .coords import OsirisInstrumentFrame ...
# Copyright 2017 Workonline Communications (Pty) Ltd. All rights reserved. # # The contents of this file are 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/LIC...
# pylint: disable=no-self-use,protected-access from unittest import TestCase, skip from testfixtures import compare, StringComparison from service.ws_re.register.authors import Authors from service.ws_re.register.register_types.volume import VolumeRegister from service.ws_re.register.test_base import BaseTestRegister...
import itertools class SeatMatrix: OCCUPIED = '#' EMPTY = 'L' FLOOR = '.' def __init__(self, arr): self.matrix = arr self.num_rows = len(self.matrix) self.num_cols = len(self.matrix[0]) def get_seat_val(self, r, c): return self.matrix[r][c] def count_immediate...
import sys, re, os from enum import Enum class ElseLanguage: def __init__(self, output, language: str, punctuation: str, valid_identifier: str, indentation: int, version: str, copyright: str, start_rule: str) -> None: self.output: str = output self.language: str = language self.punctuation:...
import arcpy import os import sys import math from arcpy import env surface1 = arcpy.GetParameterAsText(0) surface2 = arcpy.GetParameterAsText(1) new_first_surface = arcpy.GetParameterAsText(2) new_second_surface = arcpy.GetParameterAsText(3) tolerance = arcpy.GetParameter(4) def search_intersect(surf...
"""Checks whether Control Plane logging is enabled for an EKS cluster""" import os import boto3 from botocore.exceptions import ClientError from datetime import datetime, timedelta import traceback import logging import json from dateutil.tz import tzlocal sqs_queue_url = os.environ["sqs_queue_url"] logger = logging...
import argparse from numpy.core.fromnumeric import shape from tool.torch_utils import do_detect import torch import torch.backends.cudnn as cudnn from tool.darknet2pytorch import Darknet import timeit, time import os import numpy as np import cv2 import json import random FRAME_SIZES = [64, 96, 128, 160, 192, 224, ...
import torch import torch.nn as nn from torch.nn import functional as F import torch.distributions as distributions import numpy as np import math from ptbaselines.algos.common.torch_utils import init_weight class Pd(object): """ A particular probability distribution """ def flatparam(self): ra...
import numpy as np from .lanczos import lanczos_resample_three, lanczos_resample_one def invert_affine_transform_wcs(u, v, wcs): """Invert a galsim.AffineTransform WCS. The AffineTransform WCS forward model is [u, v] = Jac * ([x, y] - origin) + world_origin where the `*` is a matrix multiplica...
from os import path import requests import json from requests.exceptions import HTTPError from tkinter import messagebox from tkinter.constants import BOTTOM, CENTER, E, RIGHT, W, Y, X from tkinter.ttk import Treeview, Scrollbar from ibuki import Ibuki from utils import fetch_local_data, get_config, messages tv = Non...
""" Implementation of Total Variation Loss (https://en.wikipedia.org/wiki/Total_variation_denoising) copied and slightly modified from the original Apache License 2.0 traiNNer Authors https://github.com/victorca25/traiNNer/tree/master # Copyright 2021 traiNNer Authors # # Licensed under the Apache License, Version 2....
import threading import time import traceback import os import sys from six import iteritems def get_current_thread_object_dict(): """ Get a dictionary of all 'Thread' objects created via the threading module keyed by thread_id. Note that not all interpreter threads have a thread objects, only the ma...
import pandas as pd import plotly.graph_objs as go # TODO: Scroll down to line 157 and set up a fifth visualization for the data dashboard def cleandata(dataset, keepcolumns = ['Country Name', '1990', '2015'], value_variables = ['1990', '2015']): """Clean world bank data for a visualizaiton dashboard Keeps d...
import datetime import json DATE_FORMAT = "%Y-%m-%d" def date_to_string(date): return date.strftime(DATE_FORMAT) def string_to_date(string): return datetime.datetime.strptime(string, DATE_FORMAT) def segment_month_date(start, end): """ start : YYYY-MM-DD end : YYYY-MM-DD """ start_dat...
from sympy.core.numbers import (Float, pi) from sympy.core.symbol import symbols from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.matrices.immutable import ImmutableDenseMatrix as Matrix from sympy.physics.vector import ReferenceFrame, Vector, dynamicsymbols, outer from sympy.physics.vect...
# -*- coding: utf-8 -*- # pip install pycryptodome from datetime import datetime from Crypto.PublicKey import RSA from Crypto.Signature import PKCS1_v1_5 from Crypto.Hash import SHA256 from urllib.parse import quote_plus from base64 import decodebytes, encodebytes import json class AliPay(object): """ 支付宝支...
#!/usr/bin/env python # 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 #...
import torch import torch.nn as nn import torch.optim import torch.cuda.amp import torch.backends.cudnn from torch.utils.data import DataLoader from torchvision.transforms import Compose, Normalize, ToTensor, Resize, RandomCrop, RandomHorizontalFlip, RandomApply, RandomGrayscale, ColorJitter, GaussianBlur from tqdm imp...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright (C) 2020 The Project U-Ray Authors. # # Use of this source code is governed by a ISC-style # license that can be found in the LICENSE file or at # https://opensource.org/licenses/ISC # # SPDX-License-Identifier: ISC import re import fasm import bitstream ...
"""datenerfassung URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-base...
# -*- coding: utf-8 -*- # Copyright (c) 2016-2020 by University of Kassel and Fraunhofer Institute for Energy Economics # and Energy System Technology (IEE), Kassel. All rights reserved. import numpy as np import pytest import pandapower as pp import pandapower.shortcircuit as sc @pytest.fixture def w...
# Copyright 2020 Cortex Labs, 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 agreed to in wri...
from flask import Flask, render_template, redirect, url_for, request, send_from_directory, make_response, session, \ jsonify import pymysql, io, os, time, json app = Flask(__name__) app.secret_key = "tracking system" def graph_data(): db = pymysql.connect("localhost", "pmauser", "aritraroot", "tracker") ...
# coding: utf-8 from datetime import datetime from pyspark import SparkContext, SparkConf from collections import defaultdict, Counter from itertools import count from operator import add import string import math import json import re import sys def timer(start_time=None): """Counting processing time :parame...
import pgzrun import random TITLE = "Stella Rossa" FONT_COLOR = (255,255,255) WIDTH = 800 HEIGHT = 600 CENTRO_X = WIDTH / 2 CENTRO_Y = HEIGHT / 2 CENTRO = (CENTRO_X, CENTRO_Y) LIVELLO_FINALE = 8 VEL_INIZIALE = 10 COLORI_STELLA = ["blu","verde","arancione","porpora","gialla"] game_over = False game_completato = False...
#!/usr/bin/env python from __future__ import division, print_function, unicode_literals import sys import string try: from tkinter import * except ImportError: # Fall back to Python 2 name for module from Tkinter import * import subprocess tkroot = Tk() class Container: pass cont = Container(...
"""Core authentication logic.""" from enum import Enum from importlib import import_module from typing import List, Tuple from gino.declarative import Model from jwcrypto.jwe import JWE, InvalidJWEData from jwcrypto.jwk import JWK from jwcrypto.jws import InvalidJWSObject, InvalidJWSSignature from passlib.context imp...
import os import posixpath from pystac.errors import RequiredPropertyMissing from typing import Any, Callable, Dict, List, Optional, TypeVar, Union from urllib.parse import urlparse, ParseResult as URLParseResult from datetime import datetime, timezone import dateutil.parser # Allow for modifying the path library for ...
#! python3 import re import collections import xml.etree.ElementTree as ET class Device(): def __init__(self, name): self.name = name self.cpu = Cpu() self.peripherals = {} @property def children(self): return self.peripherals def __str__(self): ...
# 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...
"""Base module for generating javascript Angular application.""" import datetime import re from textx import generator from textxjinja import textx_jinja_generator from os import mkdir, getcwd from os.path import dirname, exists, join from sbag.language import Entity, BaseType from sbag.generators.java import get_type ...
"""Pathname and path-related operations for the Macintosh.""" # strings representing various path-related bits and pieces # These are primarily for export; internally, they are hardcoded. # Should be set before imports for resolving cyclic dependency. curdir = ':' pardir = '::' extsep = '.' sep = ':' pathsep ...
""" mairo_soundboard.py This is a sample on how to use mario.py. It shows how to register event hook functions and how to let the script run as an endless loop. ################################################################################### MIT License Copyright (c) 2022 <NAME>, <NAME> Permission is hereby granted...
# Copyright 2020 The Magenta 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 law or agreed to in ...
""" Benchmark processing in Dask This mimics the overall structure and workload of our processing. <NAME> 8 November 2017 <EMAIL> """ import csv import numpy from dask import delayed from distributed import Client, wait, LocalCluster # Make some randomly located points on 2D plane def sparse(n, margin=0.1): num...
# pylint:disable=unused-variable # pylint:disable=unused-argument # pylint:disable=redefined-outer-name import asyncio import logging from typing import AsyncIterator, Dict, Iterator, List import aiopg.sa import pytest import sqlalchemy as sa import tenacity from sqlalchemy.orm import sessionmaker from ten...
# (c) Copyright 2014-2016 Hewlett-Packard Development Company, L.P. # # 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 ap...
import github3 from github3 import gists from tests.utils import (BaseCase, load) class TestGist(BaseCase): def __init__(self, methodName='runTest'): super(TestGist, self).__init__(methodName) self.gist = gists.Gist(load('gist')) self.api = 'https://api.github.com/gists/3813862' def s...
import numpy as np from src.maths import rotationMatrix R = rotationMatrix(0, 0, 0) R1 = rotationMatrix(0, 0, np.pi / 2) R2 = rotationMatrix(0, 0, np.pi) R3 = rotationMatrix(0, 0, 3 * np.pi / 2) R4 = rotationMatrix(0, 0, 2 * np.pi) R5 = rotationMatrix(0, np.pi / 2, 0) R6 = rotationMatrix(0, np.pi, 0) R7 = rotationM...
# coding:utf-8 #!/usr/bin/python # # Copyright (c) Contributors to the Open 3D Engine Project. # For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # # # ------------------------------------------------------------------------...
import os import shutil import subprocess import tempfile from contextlib import contextmanager from packaging import version from pathlib import Path @contextmanager def working_directory(path): prev_cwd = os.getcwd() os.chdir(path) try: yield finally: os.chdir(prev_cw...
# Copyright 2014 # The Cloudscaling Group, 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 agreed to...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue May 12 20:10:00 2020 @author: thorius """ import os import sys from queue import Queue import numpy as np import logging import pyaudio import time from tflite_runtime.interpreter import Interpreter import collections from scipy import signal class S...
#!/usr/bin/env python # # Author: <NAME> # License: BSD 2-clause # Last Change: Thu Jul 29, 2021 at 03:51 PM +0200 import uproot import sys import os sys.path.insert(0, os.path.dirname(os.path.realpath(__file__))) from argparse import ArgumentParser from pyTuplingUtils.utils import extract_uid from pyTuplingUtils.cu...
from __future__ import annotations import io import os import subprocess import textwrap import unittest from typing import Sequence from unittest import mock from dconf_manager import HierarchicalSet from dconf_manager import main EXPECTED_OUTPUT = """\ \033[32m> add/AddedKey=1 \033[31m< clear/foo/bar/blah=50 \033[...
"""Utilities to validate Galaxy xml tool wrappers. """ from typing import List, Optional from lxml import etree from galaxy.util import xml_macros from pygls.workspace import Document from pygls.types import ( Diagnostic, Position, Range, ) MACROS_TAG = "<macros>" class GalaxyToolValidationService: ...
""" this is a program use Class to handle two Fractions plus, minus, mutiply, divide and check-out if they equals to each other upgraded with unittest module to build a test suite Written by <NAME> """ import unittest as ut class TestFraction(ut.TestCase): """ Test class of fraction which includes testing '+-*/...
import fisher import numpy as np def print_2x2_table(table, row_labels, col_labels, fmt="%d"): """ Prints a table used for Fisher's exact test. Adds row, column, and grand totals. :param table: The four cells of a 2x2 table: [r1c1, r1c2, r2c1, r2c2] :param row_labels: A length-2 list of row names ...
""" The idea of late parallelization is that we don't have to slice our tensor network in the beginning of the contraction. """ import psutil import numpy as np from functools import partial from loguru import logger as log import qtree import qtensor as qtn from qtensor.optimisation import Optimizer, RGreedyOptimize...
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals from datetime import datetime from inspect import getmodulename import logging import os import re import socket import ssl from urllib.error import HTTPError, URLError from urllib.request import urlopen, Request from ..co...
#!/usr/bin/env python3 """ This reads a log file and verifies that all the 'action' entries are corrent. And action entry looks like: act: key value up-card action """ act_line = '' def main(): global act_line with open('trace.txt', 'rt') as fd: for line in fd: line = line.rstrip() ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # standard modules import math import re # third party modules import luigi import unicodecsv as csv # local modules from alleletraj import utils from alleletraj.const import OUTGROUP_POP from alleletraj.db.load import CreateDatabase from alleletraj.sra import entrez_dir...