text
stringlengths
3.07k
12.6k
""" """ import numpy as np from robot_localisation.grid import Heading from numpy.random import random_sample from robot_localisation.grid import * from enum import IntEnum class Robot: """ Representation of the actual robot. """ def __init__(self, grid, transition_matrix): """ The ...
import pandas as pd def subset_grm(grm, grm_indiv, target_indiv): set_target_indiv = set(target_indiv) isin = np.array([ g in set_target_indiv for g in grm_indiv ]) grm = grm[:, isin][isin, :] grm_indiv = list(np.array(grm_indiv)[isin]) return grm, grm_indiv def subset_y(df, indiv): df_indiv =...
################################################################################ # atd.py - The Unix at scheduler in Python ################## py2k version 0.1 # ################################################################################ # `at` is a command line utility, like cron, that schedules commands to be ru...
import xlrd import datetime import math from .base import TableParser class WorkbookParser(TableParser): workbook = None worksheet = None sheet_name = 0 start_row = None column_count = None no_pickle_parser = ['workbook', 'worksheet'] binary = True date_format = 'yyyy-mm-dd' time_...
'''Visualization of the filters of VGG16, via gradient ascent in input space. This script can run on CPU in a few minutes (with the TensorFlow backend). Results example: http://i.imgur.com/4nj4KjN.jpg ''' from __future__ import print_function from scipy.misc import imsave import numpy as np import time from keras.appl...
# Original work Copyright 2017 Palantir Technologies, Inc. (MIT) # Original work Copyright 2020 Open Law Library. (Apache 2) # See ThirdPartyNotices.txt in the project root for license information. # All modifications Copyright (c) Robocorp Technologies Inc. # All rights reserved. # # Licensed under the Apache License,...
import netket as nk import networkx as nx import numpy as np import pytest operators = {} # Ising 1D g = nk.graph.Hypercube(length=20, n_dim=1, pbc=True) hi = nk.hilbert.Spin(s=0.5, graph=g) operators["Ising 1D"] = nk.operator.Ising(h=1.321, hilbert=hi) # Heisenberg 1D g = nk.graph.Hypercube(length=20, n_dim=1, pbc...
"""TODO(DAGW): Add a description here.""" import os import datasets from datasets.utils import metadata import ndjson from .licenses import * _CITATION = """\ @inproceedings{dagw, title = {{The Danish Gigaword Corpus}}, author = {<NAME> and <NAME> and <NAME> and <NAME> and <NAME> and <NAME> and <NAME> and <NAME>...
import numpy as np import tensorflow as tf from tqdm import trange import tensorflow.contrib.slim as slim from flearn.utils.model_utils import batch_data, gen_batch from flearn.utils.tf_utils import graph_size from flearn.utils.tf_utils import process_grad trunc_normal = lambda stddev: tf.truncated_normal_initializer...
import pandas as pd import numpy as np from _datetime import datetime class AttendanceSystem: def __init__(self, path_to_internal_employees_file, path_to_attendance_log): self.clock = Clock(path_to_internal_employees_file, path_to_attendance_log) # add method - read csv, write csv self.rep...
from typing import * import os import json import torch from torch.utils.data import Dataset, DataLoader from torch.nn.utils.rnn import pad_sequence, pack_padded_sequence, pad_packed_sequence import tqdm def load_data(folder: str, fname: str) -> List[Dict]: """ Loads the data in a suitable format. Args: ...
# -*- coding: utf-8 -*- """ Copyright (c) 2020 MeteoSwiss, contributors of the original matlab version of the code listed in ORIGINAL_AUTHORS. Copyright (c) 2020 MeteoSwiss, contributors of the Python version of the code listed in AUTHORS. Distributed under the terms of the BSD 3-Clause License. SPDX-License-Identifi...
# -*- coding: utf-8 -* import unittest from bianalyzer.abstracts import download_abstracts, IEEEKeywordDownloader, DLTermType from bianalyzer import BianalyzerText from bianalyzer.keywords import extract_keywords_via_textrank, extract_keywords_via_frequency from bianalyzer.relevance import construct_similarity_matrix,...
#!/usr/bin/env python # coding=utf-8 """ @author: <NAME> @create time: 1970-01-01 08:00 @edit time: 2020-05-10 10:29 @FilePath: /expdf/tests/test_pdfnode.py @desc: 测试Graph模块是否正常工作 """ from expdf.pdfnode import PDFNode, LocalPDFNode import json class TestPDFNode: def setup(self): PDFNode.clear_nodes() ...
from dateutil.relativedelta import relativedelta from django.db import models from django.db.models import Func, F from django.db.models.functions import Substr, Lower from django.utils import timezone from lib import fields from accounts.models import User from mailer.signals import allocation_created_from_request c...
import math def f_to_s(v): return'{0:.5f}'.format(float(v)) def list_to_array(vals): return '{}'.format(','.join([f_to_s(v) for v in vals])) class URScript(object): def __init__(self): self.text = '' # Starts inside of a function self.indent_level = 0 def add_line(self, text): #print('add_l...
from __future__ import print_function import numpy as np import tensorflow as tf from tensorflow.contrib import rnn import random import collections import time start_time = time.time() def elapsed(sec): if sec<60: return str(sec) + " sec" elif sec<(60*60): return str(sec/60) + " min" else: return str(sec/(6...
# -*- coding: utf-8 -*- """ This software is licensed under the License (MIT) located at https://github.com/ephreal/rollbot/Licence Please see the license for any restrictions or rights granted to you by the License. """ import asyncio import unittest from classes.dice_rolling import shadowrun_rolling as sr from cla...
import random from config.board_config import BoardConfig import logging logging.basicConfig( level=logging.INFO, format='%(asctime)s | %(name)s | %(levelname)s | %(message)s') logger = logging.getLogger(__name__) def generate_new_shape() -> tuple[int, list[int], list[int]]: """Generate new shape ...
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 import sys from datetime import datetime import boto3 from pyspark.context import SparkContext def get_catalog_table(glue_client, db_name, table_name): try: return glue_client.get_table(DatabaseName=db_...
# -*- coding: utf-8 -*- import os import sys import types import errno from shutil import copy2 from future.utils import raise_from from django.utils import (six, translation) from django.conf import settings from django.conf.urls import include as include_urls from django.http import HttpResponse from django.tem...
import json import datetime import os import time from threading import Lock from multiprocessing.pool import ThreadPool from collections import defaultdict import requests from pyhmy.util import ( json_load, datetime_format ) from .common import ( Loggers, get_config, ) def live_info(accounts, inte...
__source__ = 'https://leetcode.com/problems/self-crossing/' # https://github.com/kamyu104/LeetCode/blob/master/Python/self-crossing.py # Time: O(n) # Space: O(1) # # Description: Leetcode # 335. Self Crossing # # You are given an array x of n positive numbers. # You start at point (0,0) and moves x[0] metres to the no...
import sys import os if sys.platform != "win32": raise OSError("movefile-restart module is only supported on Windows systems!") import winreg _registry = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) def __get_current_values(): """Get Values. Internal function to get the current values stored...
import torch.utils.data as data import numpy as np import os import pickle import h5py import json from PIL import Image from utils.directory import check_exists from scipy.misc import imread, imresize import datasets.preprocess as preprocess class Namespace: def __init__(self, **kwargs): self.__dict__.upd...
""" This module contains utils for manipulating target configurations such as compiler flags. """ from types import MappingProxyType from numba.core import utils class Option: """An option to be used in ``TargetConfig``. """ __slots__ = "_type", "_default", "_doc" def __init__(self, type, *, default...
#!/usr/bin/env python import argparse import inspect import pprint import sys import time import unittest from idpmodem.atcommand_thread import get_modem_thread, IdpModemBusy, AtException, AtCrcConfigError, AtCrcError, AtTimeout DEFAULT_PORT = '/dev/ttyUSB1' class IdpModemTestCase(unittest.TestCase): @classme...
import numpy as np import os from scratchai.DataLoader.ImageLoader import ImageLoader from . import color_code as colors from PIL import Image import glob import torchvision from torch.utils.data import DataLoader import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec import torchvision.transforms as tr...
# -*- coding: utf-8 -*- # @Time : 2019-12-23 15:24 # @Author : yingyuankai # @Email : <EMAIL> # @File : glue_zh.py """DuReader.""" __all__ = [ "Ccfbdci2020" ] import os import six import logging import json import tensorflow as tf import tensorflow_datasets as tfds from aispace.datasets import BaseData...
# Copyright 2020 Adap GmbH. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
#!/usr/bin/env python # # June 2 2021, <NAME> <<EMAIL>> # # Copyright (c) 2021, LabN Consulting, L.L.C. # Copyright (c) 2019-2020 by # <NAME> <<EMAIL>> # # Permission to use, copy, modify, and/or distribute this software # for any purpose with or without fee is hereby granted, provided # that the above copyright notice...
import datetime import logging from time import sleep from ceph.parallel import parallel from tests.iscsi.iscsi_utils import IscsiUtils log = logging def run(**kw): log.info("Running test") ceph_nodes = kw.get('ceph_nodes') test_data = kw.get('test_data') iscsi_util = IscsiUtils(ceph_nodes) iscs...
__all__ = ["CBProMarketBBO", "timer"] __author__ = "<NAME>" import websocket import time import logging import urllib.request import json import math import functools from typing import Dict, List, Callable URL_WS = "wss://ws-feed.pro.coinbase.com/" URL_PRODUCTS = "https://api.pro.coinbase.com/products" URL_USER_AGE...
# Copyright 2017 FUJITSU LIMITED # # 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 writ...
# Copyright 2021 The NPLinker 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...
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import pandas as pd class TwitterData_Initialize(): data = [] processed_data = [] wordlist = [] data_model = None data_labels = None is_testing = False def initialize(self, csv_file, is_testing_set=False, from_cached=None):...
#!/usr/bin/env python import sys START_ADDR_SEG = 2 # converts ld65 map file to da65 info file if len(sys.argv) < 2: print("USAGE: map2info.py <map file> [vice label file [debug info]]") sys.exit(1) items = open(sys.argv[1], "r").readlines() def read_chunk(items): chunk = [] while len(items) > 0: ...
#!usr/bin/python import assign_window def match_window(g_dic, left, right, strand): genes= g_dic.keys() proximity=[] for g in genes: left_g = int(g_dic[g][0]) right_g = int(g_dic[g][1]) if( right-left < right_g-left_g ): ##window is smaller than gene if( (left_g-200 < left) and (right_g+200 > right) an...
# Import the Runway SDK. Please install it first with # `pip install runway-python`. import runway from runway.data_types import category, image, number, boolean import numpy as np import tensorflow as tf from PIL import Image # from example_model import ExampleModel import lucid.modelzoo.vision_models as models from ...
# Copyright 2021 The SmallPebble 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 applic...
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # File : cs.py # Author : <NAME> # Email : <EMAIL> # Date : 01/22/2018 # # This file is part of Jacinle. # Distributed under terms of the MIT license. import collections import contextlib import queue import threading import zmq from jacinle.concurrency.packing im...
import logging from datetime import datetime from flask import Flask, render_template, request from DAL import user_dal import math import re import pytz def manage_user(): try: action = request.form['action'] if not action: return list_user() if action == 'delete': ...
# Keyboard Synchronization import arachnoid as ara #import win32api, win32con from pynput import keyboard import os, sys print('PID: {}'.format(ara.get_pid())) IP_ADDR = '192.168.1.94'#'43.33' PORT_NUMBER = 5555 #KB_LAYOUT = win32api.GetKeyboardLayout() ''' def get_key_strokes(from_=0, to=250): return l...
#!/usr/bin/env python ''' Synthesizes a logic proposition using a user-specified set of opcodes. TODO: Integrate a SAT/SMT solver to perform synthesis, rather then using brute-force. ''' from typing import List, Callable, Dict, Optional, Tuple from itertools import product class Opcode: def __init__(self, num_...
from multiprocessing import Process, Queue, Event import os import baselines.common.tf_util as U import time from mpi4py import MPI from baselines.common import set_global_seeds import tensorflow as tf import numpy as np def traj_segment_function(env, pol, gamma, task_horizon, feature_fun, batch_size): ''' Col...
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
import numpy as np import math, os, cv2 def get_bg_from_image(dimensions, image_path): WIDTH, HEIGHT = dimensions img = cv2.imread(image_path, cv2.IMREAD_COLOR) # Convert the image from RGB2RGBA if len(img.shape) > 2 and img.shape[2] == 3: img = cv2.cvtColor(img, cv2.COLOR_BGR2BGRA) retur...
r""":mod:`mirgecom.thermochemistry` provides a wrapper class for :mod:`pyrometheus`.. .. autofunction:: make_pyrometheus_mechanism_class .. autofunction:: make_pyrometheus_mechanism """ __copyright__ = """ Copyright (C) 2021 University of Illinois Board of Trustees """ __license__ = """ Permission is hereby granted,...
from datetime import datetime from django.conf import settings from mongoengine.queryset import transform, Q from rest_framework import fields from happ.utils import date_to_string from .fields import DateTime000Field, ListField, RangeField, GeoPointField, ObjectIdField COMPARISION_OPERATORS = ('ne', 'gt', 'gte', ...
import pathlib import sys import re import time import threading from PyQt5.QtCore import Qt import main_func from PyQt5 import QtWidgets, QtCore, QtGui from PyQt5.QtWidgets import QTableWidgetItem, QFileDialog, QDialog, QPushButton, QLabel from qt_view import Ui_MainWindow class MainWindow(QtWidgets.QMainWindow): ...
# -*- coding: utf-8 -*- """ Created on Fri Nov 8 16:10:22 2019 @author: a.sijaria """ from selenium import webdriver from bs4 import BeautifulSoup import pandas as pd import time import chromedriver_binary import sys,os def get_reviews(app_id,language = 'en',country= 'IN'): chrome_options = webdriver.ChromeO...
# @singleton from abc import abstractmethod from collections import Counter import numpy as np from mlib.boot import log from mlib.boot.stream import concat, listmap, make2d, objarray from mlib.fig.makefigslib import MakeFigsBackend from mlib.math import isreal from mlib.wolf.bar import bar from mlib.wolf.line import...
import re import tiles # REGEXs for global/clock signals # Globals global_entry_re = re.compile(r'R\d+C\d+_VPRX(\d){2}00') global_left_right_re = re.compile(r'R\d+C\d+_HPSX(\d){2}00') global_up_down_re = re.compile(r'R\d+C\d+_VPTX(\d){2}00') global_branch_re = re.compile(r'R\d+C\d+_HPBX(\d){2}00') # High Fanout Seco...
#!/usr/bin/python3 # <NAME>: import json import sys TERM = 'jmp', 'br', 'ret' # From Lesson 2 def form_blocks(body): cur_block = [] for inst in body: if 'op' in inst: cur_block.append(inst) # check for term if inst['op'] in TERM: yield cur_block ...
# -*- coding: utf-8 -*- # # 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 ...
"""Calculate repeater fraction over time for various rate distributions.""" from copy import deepcopy from matplotlib.lines import Line2D import matplotlib.pyplot as plt import numpy as np from frbpoppy import CosmicPopulation, Survey, SurveyPopulation, merge_pop from frbpoppy import log10normal, hist, clustered from...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import os import shutil import datetime from subprocess import Popen, PIPE import trackmac.config def generate_plist(install_base_dir): """ generate a plist file under current folder """ cur_dir = os.path.abspath(os.path.dirname(__file__...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import timedelta from odoo import api, fields, models from odoo.tools.safe_eval import safe_eval class ProjectTaskType(models.Model): _inherit = 'project.task.type' def _default_domain_rating_t...
""" OpenWRT/luci Telnet-based tracker. Tested on a Zyxel NBG6604 which has luci but lacks the RPC module or a possibility to install it in order to use https://www.home-assistant.io/integrations/luci/ """ import logging import re from collections import namedtuple from datetime import timedelta import telnetlib impor...
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import logging from google.appengine.ext import ndb from components import metrics from components import utils import gae_ts_mon import config import mod...
from sklearn.datasets import load_boston from sklearn.model_selection import train_test_split import random import numpy as np import torch import torch.autograd as py class DataLoader(): def __init__(self, data_file): super(DataLoader, self).__init__() self.data_file = data_file self.load_...
""" An encoder sequence is used to produce a sequence of ratios with respect to the original input length consisting of a_0, a_1, a_2, etc, where a_0 is equal to different lengths, and a_f is global """ from typing import List import torch from torch import nn from Utility.Torch import Learnables from Utility.Torch...
import logging import argparse import json import os from evaluation.hotpotqa_evaluate_v1 import normalize_answer from util.args_help import file_list logger = logging.getLogger(__name__) logging.basicConfig(format='%(filename)s:%(lineno)d - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', ...
# -*- coding: utf-8 -*- ############################################################################ # # Copyright © 2015 OnlineGroups.net and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this dis...
# -*- coding: utf-8 -*- # @Time : 6/21/2020 2:55 PM # @Author : <NAME> # @FileName: crawl_xinloupan.py # @Software: PyCharm # @Github : https://github.com/w4356y/House_price.git from bs4 import BeautifulSoup import re import requests from parsel import Selector import pandas as pd import time from datetime import...
#!/usr/bin/env python3 import asyncio import base64 import json import os from typing import Any, Dict, List, Union import numpy as np from fastapi import APIRouter, Body, FastAPI, Request, WebSocket from fastapi.encoders import jsonable_encoder from fastapi.responses import HTMLResponse, JSONResponse from fastapi.sta...
import cv2 import numpy as np from skimage.measure import compare_ssim as ssim def get_mse_psnr(x, y): if x.ndim == 4: mse_list = [] psnr_list = [] data_len = len(x) for k in range(data_len): img = x[k] ref = y[k] mse = np.mean((img - ref) ** 2) ...
#! usr/bin/env/ python3 """Parser for CLI user options""" import argparse import getpass import os import sys from choppy.version import VERSION # ------------------------------------------------------------------------------ def confirm_directory(subdir): if os.path.exists(subdir): if not os.path.isdir...
import multiprocessing import os import subprocess # This is a helper function that allows to run a bash command in a separate process def execute_command(cmd): return subprocess.call(cmd, shell=True) def TestDimensions(problem_dim,space_dim=2,element_dim=2): # cast dimensions if not already strings prob...
import torch import torch.nn as nn import torch.nn.functional as F from scvi.dataloaders import DataSplitter from scvi.model._utils import parse_use_gpu_arg from scvi.dataloaders._ann_dataloader import AnnDataLoader from scvi import settings from typing import Optional, Union from anndata import AnnData from scvi.n...
from functools import partial import torch import gym.spaces as spaces from torch.nn import functional as F from rlberry.agents.utils.memories import ReplayMemory from rlberry.exploration_tools.uncertainty_estimator import UncertaintyEstimator from rlberry.exploration_tools.typing import preprocess_args from rlberry....
import argparse import random from typing import List, Tuple from skimage.draw import polygon from skimage.metrics import normalized_root_mse from deap import base, creator, tools, algorithms from PIL import Image import numpy as np import multiprocessing import pickle from pathlib import Path from tqdm.auto import ...
#! $PATH/python # -*- coding: utf-8 -*- # file name: nfexample.py # author: lianghy # time: 2019/8/30 17:37:14 """本文件使用暖风工具描述一个电路模块。""" import sys import numpy as np import logging as lg sys.path.append("C:\\Users\\l110084\\lhy\\work\\nuanfeng\\project_nf") from nuanfeng.nffunc import * from nuanfeng.util import * ...
from ml.optimizer import GradientDescentOptimizer from ml.graph import graph_function_and_data from ml.error import Error import matplotlib.pyplot as plt from math import * from inspect import signature import pickle class Regression: def __init__(self, func, loss_function='MSE'): """ Creates a ne...
# -*- coding: utf-8 -*- from macros import export_macros from macros import import_macros from discovery_rules import export_discovery_rules from discovery_rules import import_discovery_rules from actions import export_actions from actions import import_actions import logging, json EXPORT_KEYS = [ 'templates', ...
import os import random import cv2 import numpy as np import torch import torch.nn as nn import torchvision.transforms as transforms from torch.utils.data import Dataset from .data_argument import custom_aug import matplotlib.pyplot as plt def random_random(v=0.5): if random.random() > 0.5: return Tr...
from datetime import timedelta, time from itertools import groupby import time as _time from dateutil.relativedelta import relativedelta, MO import pytz import itertools class Period(object): @property def delta(self): return self._delta @property def start_at_key(self): return "_%s_...
# -*- coding: utf-8 -*- """ flask_raven.resource ~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2014 <NAME> :license: Artistic 2.0 """ from datetime import datetime from flask import request from Crypto.Hash.SHA import SHA1Hash from Crypto.PublicKey import RSA from Crypto.Signature import PKCS1_v1_5 from .er...
# coding=utf-8 """Parser for ClassScript""" from typing import cast, Union import os from modelscript.base.grammars import ( ASTNodeSourceIssue) from modelscript.base.issues import ( Levels) from modelscript.base.exceptions import ( UnexpectedCase) from modelscript.metamodels.demo import ( DemoModel, ...
from __future__ import print_function import sys sys.path.insert( 1, 'C:/Users/seand/OneDrive/Documents/University/Autonomous Drone Navigation/Implementation/AirSimAPI') import time import numpy as np import cv2 from tensorflow import keras import tensorflow as tf from numpy.lib.function_base import average import ...
"""Lambda Function Source Code Adheres to Smart Home Skill V3 API Responds to discovery and control requests """ # Import AWS SDK and set up client import uuid import time import boto3 import json client = boto3.client('iot') client_data = boto3.client('iot-data') # Main Lambda handler # First function invoked when...
# This file is a part of the AnyBlok / Postgres api project # # Copyright (C) 2018 <NAME> <<EMAIL>> # Copyright (C) 2018 <NAME> <<EMAIL>> # # This Source Code Form is subject to the terms of the Mozilla Public License, # v. 2.0. If a copy of the MPL was not distributed with this file,You can # obtain one at http:...
import argparse import configparser import os from configparser import ConfigParser from google.oauth2.credentials import Credentials from model.events import GoogleCalendarEvents class Configurations: def __init__(self, config: ConfigParser): self._owm_token = config.get('API_KEYS', 'OWM', fallback='')...
#!/usr/bin/python # -*- coding: utf-8 -*- # 圆周避障 import RPi.GPIO as GPIO import time PWMA = 18 AIN1 = 22 AIN2 = 27 PWMB = 23 BIN1 = 25 BIN2 = 24 trigger = 20 echo = 21 def init(): GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(AIN2, GPIO.OUT) GPIO.setup(AIN1, GPIO.OUT) GPIO.setup(PW...
import random as aleas import matplotlib.pyplot as plt from scipy.signal import freqz import numpy as np """ random : pour generer des nombres aleatoires matplotlib.pyplot : pour generer des graphiques et gerer leur construction scipy.signal : pour avoir le TF de l'autocorrelation numpy : pour im...
import io import os import re from torchtext.data import Field, NestedField import torchtext.data as data from torchtext.data.dataset import Dataset from torchtext.data.example import Example from typing import Iterable from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence PAD_TOKEN = '<pad>' START...
from discord import Embed, Member, Color from discord.ext import commands from requests import get from datetime import datetime from sqlite3 import connect from os import environ class Chat(commands.Cog, name='Chat'): """ Utilisable par tout le monde et rassemble toutes les commandes un peu random. """ ...
import time from abc import ABCMeta from datetime import datetime from typing import Sequence, Mapping import torch import torch.nn as nn from torch.utils.tensorboard import SummaryWriter from hhutil.io import fmt_path, time_now from horch.common import CUDA, convert_tensor as c_convert_tensor from horch.train.base ...
#!/usr/bin/env python3 #title : model_selection.py #description : Contains methods that perform the actual model selection. #author : <NAME> #date : 2015.06.21 #version : 0.1 #usage : python model_selection.py #===============================================================...
#!/usr/bin/env python2.5 # encoding: utf-8 """ cleaneval.py v1.0 Simple and fast evaluation of CleanEval-1 tasks (precision, recall, F-score). """ import sys import os import string import re from math import * from difflib import SequenceMatcher from getopt import getopt, GetoptError help_message = ''' This is clean...
import virtualbox import os import time import threading import logging logging.basicConfig(level=logging.DEBUG, format='(%(threadName)-10s) %(message)s',) class Sandbox(object): def __init__(self, name): vbox = virtualbox.VirtualBox() self.vm = vbox.find_machine(name) ...
# 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, software #...
import wx from wx import aui from wx.aui import EVT_AUITOOLBAR_TOOL_DROPDOWN from meerk40t.kernel import lookup_listener ID_ADD_FILE = wx.NewId() ID_OPEN = wx.NewId() ID_SAVE = wx.NewId() ID_JOB = wx.NewId() ID_SIM = wx.NewId() ID_NOTES = wx.NewId() ID_CONSOLE = wx.NewId() ID_RASTER = wx.NewId() _ = wx.GetTranslatio...
from twisted.protocols.basic import LineReceiver from twisted.internet import reactor, protocol from twisted.internet.task import LoopingCall from xsbs.settings import PluginConfig from xsbs.events import triggerServerEvent, eventHandler from xsbs.net import ipLongToString import sbserver import time import logging ...
import torch.nn as nn import torch.nn.functional as F from torch.optim import SGD import torch as t from scipy import constants import numpy as np import pandas as pd from pyhdx.models import Protein class DeltaGFit(nn.Module): def __init__(self, deltaG): super(DeltaGFit, self).__init__() self.del...
import numpy import pytest from numpy import cos, pi, sin import quadpy def test_simple(): val, _ = quadpy.line_segment.integrate_adaptive(sin, [0.0, pi], 1.0e-10) exact = 2.0 assert abs(exact - val) < 1.0e-10 val, _ = quadpy.line_segment.integrate_adaptive( lambda x: x * sin(x), [0.0, pi], ...
import logging import pathlib import json import sys from converterpy.adapter import ConverterTextAdapter from converterpy.converter import Converter from converterpy.cli import Cli from converterpy.exception import SuitableConverterNotFoundException, MultipleSuitableConverterException from converterpy.provider.built...
import os import numpy as np import matplotlib.pyplot as plt from cellsync.detect_peaks import * import itertools import matplotlib.colors as colors import matplotlib.cm as cmx from mpl_toolkits.axes_grid1 import make_axes_locatable def find_sync(d, metadata, corr,regions_ch2, labels, cell_position, sync_time=1, ...
# -*- coding: utf-8 -*- """ @author: <NAME> @contact: <EMAIL> @description: IO management library. """ # DEPENDENCIES ================================================================= from datetime import datetime import numpy as np import os, sys, tempfile from time import time import warnings from pygpseq import ...
from vrepdemo.vrep_env import vrep_env import os import gym from gym import spaces from gym.utils import seeding import numpy as np vrep_scenes_path = '/home/ubuntu/pytorch-a2c-ppo-acktr/vrepdemo/scenes' RAD2DEG = 180/np.pi class TwoLinkBall2VrepEnv(vrep_env.VrepEnv): metadata = {'render.modes': [],} def _...