content
stringlengths
5
1.05M
file_name = input("Digite o nome do arquivo: ") with open(file_name, 'r') as file: k = int(file.readline().split('=')[1].replace("\n", '')) sequence = file.readlines()[0].replace("\n", '') kmers = [] for i in range(len(sequence)): kmer = sequence[i:i+k] if (len(kmer) < k): break kmers.app...
import tensorflow as tf from .utils import anchor_generator_builder, box_list_ops, shape_utils, \ box_list, post_processing, target_assigner, post_processing_builder, ops from ..processor import model_config as config from .utils import standard_fields as fields BOX_ENCODINGS = 'box_encodings' CLASS_PREDICT...
# -*- coding: utf-8 -*- # # Copyright 2011 Google Inc. All Rights Reserved. # """Tools for recording and reporting timeline of abstract events. You can store any events provided that they can be stringified. """ __author__ = 'kbaclawski@google.com (Krystian Baclawski)' import collections import datetime import time ...
""" Add a "featured" field to objects so admins can better direct top content. """ from __future__ import absolute_import, unicode_literals from django.db import models from django.utils.translation import ugettext_lazy as _ from feincms import extensions class Extension(extensions.Extension): def handle_model...
import numpy as np import matplotlib.pyplot as plt import datetime import glob2 import xarray as xr import pandas as pd #plt.close("all") pd.options.display.max_columns = None pd.options.display.max_rows = None dircInput1 = 'C:/Users/Chenxi/OneDrive/phd/age_and_fire/data/02_semi_raw/09_ENVISAT_MIPAS_with_AGEparams/' ...
# # Copyright 2020 EPAM Systems # # 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...
from setuptools import setup setup(name='Dis_Probability', version='0.2', description='This is a fundamental package that helps compute both binomial and Gaussain probability', packages=['Dist_Probability'], author = "Oluwaseun Adeyo", author_email = "johnadeyo@hotmail.com", zip_sa...
# coding: utf-8 # # Copyright 2014 The Oppia 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 requi...
import random eat_reactions = ['''_{0}_, you try to eat _{1}_, but you can\'t do it. So you leave, with the taste of failure hanging in your mouth.''', '_{0}_, you try to gobble up _{1}_. They prove to be a tight fit, but you manage to eat them.', '_{0}_, you advance toward _{1}_, but...
def outer(): def inner(): print(outervar) outervar = "Hello World!!" inner() def main(): outer() if __name__ == '__main__': main()
import discord from discord.app.commands import slash_command, Option from discord.ext import commands, menus from discord.member import VoiceState from discord.utils import escape_mentions from mysqldb import * from external_cons import the_drive from PIL import Image, ImageDraw, ImageFont import os import shutil imp...
#!/usr/bin/env python # -*- coding: iso-8859-2 -*- from ez_setup import use_setuptools use_setuptools() import codecs import os import sys import cassango as cngo from setuptools import setup, find_packages readme_file = os.path.join(os.path.dirname(__file__), 'README.rst') try: long_description = open(readme_file)...
from traitlets import Tuple, Dict class DefaultDict(Dict): def __init__(self, traits, **kwargs): """Create a dict trait type from a Python dict. Parameters ---------- traits : Dictionary of trait types [ optional ] A Python dictionary containing the types that are va...
# Copyright (c) 2021 AccelByte Inc. All Rights Reserved. # This is licensed software from AccelByte Inc, for limitations # and restrictions contact your company contract manager. # # Code generated. DO NOT EDIT! # template file: justice_py_sdk_codegen/__main__.py # pylint: disable=duplicate-code # pylint: disable=li...
N = int(input()) L = list(map(int, input().split())) max_len = max(L) sum = 0 for i in L: sum += i sum -= max_len print("Yes" if sum > max_len else "No")
from __future__ import division, print_function, absolute_import from warnings import warn import celerite from . import numbers as nb import numpy as np from . import ranges from scipy.optimize import minimize class QuiescenceModel(celerite.GP): """ An extension of the `celerite` Gassian Process model obje...
from __future__ import absolute_import, print_function import pytest from moment_polytopes import * # prior work def test_borland_dennis(algorithm): R = weyl_module(6, [1, 1, 1]) C = ressayre_tester(R, algorithm=algorithm) assert C.is_ressayre(((0, 0, 0, -1, 1, 1), 0)) def test_8_qubits(algorithm): ...
""" **************************************************************************************************** :copyright (c) 2019-2021 URBANopt, Alliance for Sustainable Energy, LLC, and other contributors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted ...
from django.utils.translation import ugettext_lazy from openslides.config.api import config from openslides.utils.personal_info import PersonalInfo from .models import Motion class MotionSubmitterPersonalInfo(PersonalInfo): """ Class for personal info block for motion submitters. """ headline = uget...
import os import io from contextlib import contextmanager import boto3 import botocore from lib.storage import Storage from lib.package import Package class S3Storage(Storage): def __init__(self, bucket_loc=None): s3 = boto3.resource('s3') self._bucket_loc = bucket_loc or os.getenv('DEFAULT_BUCK...
from util.Match import Tail,force class unpack(object): def __init__(self,v): self.v = v def __enter__(self): return _f(self.v) def __exit__(self,*args): pass @Tail def f(lst,acc): if lst == []: return acc return f(lst[1:],[lst[0],acc]) def _f(lst): lst = list(rev...
def countdown(number): while number >= 0: print number number -= 1 def count(num): if num > 0: while num >= 0: print num num -= 1 elif num < 0: while num < 1: print num num += 1 else: print num #count(5) #count(-3) def countfrom(num1, num2): if num1 > num2: while num1 >= num2: print n...
""" Predict flower name from an image with predict.py along with the probability of that name. That is, you'll pass in a single image /path/to/image and return the flower name and class probability. Basic usage: python predict.py /path/to/image checkpoint Options: Return top KKK most likely classes: pyt...
# @Author: Narsi Reddy <narsi> # @Date: 2019-12-18T20:15:32-06:00 # @Last modified by: cibitaw1 # @Last modified time: 2020-02-11T19:02:04-06:00 import os from PIL import Image import torch torch.manual_seed(29) from torch.utils.data import Dataset from torch.utils.data.sampler import Sampler from torchvision impor...
from django.test import TestCase from django.contrib.auth import get_user_model from .models import Blog, Category, Comment, Subscriber from django.urls import reverse class BlogTests(TestCase): @classmethod def setUpTestData(cls): # create a user testuser1 = get_user_model().objects.create_us...
# -*- coding: utf-8 -*- """ Microsoft-Windows-Dwm-Api GUID : 292a52c4-fa27-4461-b526-54a46430bd54 """ from construct import Int8sl, Int8ul, Int16ul, Int16sl, Int32sl, Int32ul, Int64sl, Int64ul, Bytes, Double, Float32l, Struct from etl.utils import WString, CString, SystemTime, Guid from etl.dtyp import Sid from etl.par...
import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets, transforms from torch.utils.data import DataLoader import torch.optim.lr_scheduler as lr_scheduler from CenterLoss import CenterLoss import matplotlib.pyplot as plt class Net(nn.Module): ...
# Generated by Django 3.1.5 on 2021-01-09 06:50 import cloudinary.models from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Image', fields=[ (...
""" @author: Gabriele Girelli @contact: gigi.ga90@gmail.com """ import logging from rich.logging import RichHandler # type: ignore from kmermaid.scripts import arguments, kmer, kmer_batch, kmer_count, kmer_uniq logging.basicConfig( level=logging.INFO, format="%(message)s", handlers=[RichHandler(markup=...
from django.contrib.admin.widgets import ForeignKeyRawIdWidget, ManyToManyRawIdWidget from django.forms import widgets __all__ = ["AdminIPInput", "AdminUUIDInput", "AdminSwitchInput", "AdminTextarea", "AdminForeignKeyRawIdWidget", "AdminManyToManyRawIdWidget", "AdminCheckboxInput", "AdminRadioSe...
import copy import logging from .batch_provider import BatchProvider from gunpowder.batch_request import BatchRequest from gunpowder.profiling import Timing logger = logging.getLogger(__name__) class BatchFilterError(Exception): def __init__(self, batch_filter, msg): self.batch_filter = batch_filter ...
from myspiders.ruia import JsonField, AttrField, Item, Spider from urllib.parse import urlencode, urlparse from config import CONFIG, Target, Job import random import demjson import re import os ''' AIResumeCount: 0 ActivityGID: null ActivityTitle: "" ApprovedBy: "" ApprovedComment: "请明确数字的包含关系,重新提交审批" ApprovedOn: "20...
# -*- coding: utf-8 -*- # # Copyright (c) 2017, the cclib development team # # This file is part of cclib (http://cclib.github.io) and is distributed under # the terms of the BSD 3-Clause License. """Test the Nuclear method in cclib""" import sys import os import re import logging import unittest import numpy as np ...
import logging import os import psutil from qtoggleserver.conf import settings from . import battery from . import conf from . import date from . import dns from . import fwupdate from . import net from . import storage from . import temperature logger = logging.getLogger(__name__) def reboot() -> None: log...
import numpy as np class DigitUtils: def countPrimeDigits(heftyNum,digits)->"[counts per digit]": if type(digits) is not list: digits = [digits] cntDict = dict.fromkeys(digits,0) for i in np.nditer(heftyNum.baseCoef): if i in digits: cntDict[int(i)]...
from pylabnet.utils.decorators.gui_decorators import handle_gui_errors class GUIHandler(): """Generic GUI handler class providing an error-tolerant GUI client - script Interface. Member variables of this class keep track of connection parameters (is_running, is_connected, etc.), and global error handling...
import pygame pygame.mixer.init() pygame.mixer.music.load('morena.mp3') pygame.mixer.music.play() input("Escuta o som")
from ..Base import Base from . import u_logger as log import random import math from scipy.special import erf, erfinv # noinspection SpellCheckingInspection class Gacha(Base): def __init__(self, *args): super().__init__(*args) @staticmethod async def random_album_popularity(): """Returns ...
def lexNext(s, n): for i in range(n - 1, -1, -1): if s[i] != 'z': k = ord(s[i]) s[i] = chr(k + 1) return ''.join(s) s[i] = 'a' S = "abcdeg" n = len(S) S = list(S) res = lexNext(S, n) print(s)
from serif.theory.serif_syn_node_theory import SerifSynNodeTheory from serif.theory.token import Token from serif.xmlio import _SimpleAttribute, _ReferenceAttribute, _ChildTheoryElementList class SynNode(SerifSynNodeTheory): tag = _SimpleAttribute(is_required=True) start_token = _ReferenceAttribute('start_tok...
# Simple python program to display current date and time. # Author: Adrian Sypos # Date: 21/09/2017 # Imports import time; # Creating variable localtime that returns a time-tuple with all nine items valid localtime = time.localtime(time.time()) # Printing localtime unformatted print ("Local current time :", localtim...
import inspect import pkg_resources from datetime import timedelta from moksha.api.hub import Consumer from moksha.pastetemplate import MokshaConsumerTemplate from base import QuickstartTester, setup_quickstart, teardown_quickstart app = None def setup(): template = MokshaConsumerTemplate templates = ['mok...
#!/usr/bin/env python import os import sys import getpass try: import Environment from Executor import * except ImportError, e: print "Couldn't find project-utils modules." sys.exit(1) network_config = [ { 'NAME' : 'QSFP_TOP_10G_PORT1', 'DFE': '172.16.50.1', 'TAP': '172.16.50.10', 'NETMASK' : '255.255.255....
# vim: ai ts=4 sts=4 et sw=4 encoding=utf-8 from django.conf.urls.defaults import patterns, url from datawinners.alldata.views import index from datawinners.dashboard.views import dashboard, get_submission_breakup, get_submissions_about_project, geo_json_for_project, render_map from datawinners.dashboard.views import ...
import os import sys import time from torch import save,load, device import pickle LIMIT_4G = 3.8 * 1024 ** 3 def timeFormated() -> str: return time.strftime("%H-%M_%d-%b-%y", time.gmtime()) def timeFormatedS() -> str: return time.strftime("%H-%M-%S_%d-%b-%y", time.gmtime()) def timeDiffFormated(start): ...
# -*- coding: utf-8 -*- # Copyright 2014 Fanficdownloader team, 2018 FanFicFare team # # 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 # # U...
#!/usr/bin/env python3 from instaloader.__main__ import main if __name__ == '__main__': main()
#!/usr/bin/env python3 #https://codeforces.com/problemset/problem/1020/B #寻找环. def who(al,i): vl = [False]*len(al) while vl[i] is False: vl[i] = True i = al[i] return i n = int(input()) #1000 al = [0] + list(map(int,input().split())) #al print(*[who(al,i) for i in range(1,n+...
""" Interactions with other mF2C components This is being developed for the MF2C Project: http://www.mf2c-project.eu/ Copyright: Roi Sucasas Font, Atos Research and Innovation, 2017. This code is licensed under an Apache 2.0 license. Please, refer to the LICENSE.TXT file for more information Created on 09 may. 2019 ...
import argparse import csv import datetime import gpxpy import gpxpy.gpx import pyproj from dateutil import parser def jps2gpx(args): ecef = pyproj.Proj(proj='geocent', ellps='WGS84', datum='WGS84') lla = pyproj.Proj(proj='latlong', ellps='WGS84', datum='WGS84') gpx = gpxpy.gpx.GPX() # Create first ...
#!/usr/bin/env python3 """Default values and configuration.""" # Possible word delimiters for synonyms. MULTIWORD_DELIMITERS = (' ', '-', '_', '/') # Default output format if not explicitly stated. DEFAULT_OUTPUT_FORMAT = 'yaml' # Stemmer to be used by default. DEFAULT_STEMMER = None # DEFAULT_STEMMER = Stemmer.get...
from .lr0itemset import LR0ItemSet from .lr0node import LR0Node from .lr0path import LR0PathItem from .lr0dominancenode import LR0DominanceSet from .merge_tree import MergeTree from motor_typing import TYPE_CHECKING import sys class LALRTable(object): def __init__(self, action_table, goto_table): # type: ...
import tkinter from tkinter import * win = Tk() c = Canvas(win, height=250, width=300, bg="blue") coord = 20, 50, 250, 200 arc = c.create_arc(coord, start=0, extent=180, fill="red") line = c.create_line(10, 10, 200, 200, fill="white") c.pack() win.mainloop()
from src.switchbox import * from src.point import * from src.netcrackerformat import * # ============================== Analysis results ============================== FILTER_GLOBAL_RES = "global pjs" # Type: [PIPJunction] FILTER_LOCAL_RES = "local pjs" # Type: [PIPJunction] FILTER_INTERNAL_RES = "inte...
# -*- coding: utf-8 -*- import threading import json from typing import Optional from dataclasses import dataclass, asdict import inject import template_logging import template_exception from flask import Request, Response from werkzeug.exceptions import NotFound, BadRequest from pymysql.constants import ER from sql...
from typing import List from dataclasses import dataclass from injector import inject from domain.customer import Customer from domain.repository.customer_repository import CustomerRepository from domain.repository.menu_repository import MenuRepository from domain.repository.store_repository import StoreRepository fro...
# pylint: disable=unused-wildcard-import from typing import Callable import functools import traceback # Local from .common import * from .executor import NoRemoteException # External from py_derive_cmd import Settings, CommandInfo, UsageException class MySettings(Settings): def handle_exceptions(self, command: 'C...
# Plexiglass box generating marginal value maps # Concept design by Ben Bryant # code by Ginger Kowal # 5.15.15 import os import sys if 'C:/Python27/Lib/site-packages' not in sys.path: sys.path.append('C:/Python27/Lib/site-packages') sys.path.append('C:/Users/Ginger/Documents/Python/csopt_Ginger_working/csopt') fr...
# -*- coding: utf-8 -*- from troposphere import Base64, Select, FindInMap, GetAtt, GetAZs, Join, Output from troposphere import Parameter, Ref, Tags, Template import troposphere.efs as efs import troposphere.ec2 as ec2 from constants import * from base import CloudformationAbstractBaseClass class SecurityGroup(Cloud...
import graphene from graphene_django.types import DjangoObjectType from .models import User class UserType(DjangoObjectType): class Meta: model = User class Query(object): users = graphene.List(UserType) user = graphene.Field(UserType, user_id=graphene.NonNull(graphene.I...
import sys import time for i in range(5): print("Python:", i, end =' ') sys.stdout.flush() time.sleep(0.5) # m = 0/0 #uncomment to test error handling
"""Binary (Protobuf) formatting utilities.""" import binascii import numbers import logging import google.protobuf.message from google.protobuf.internal.decoder import _DecodeVarint from google.protobuf.internal import encoder from openxc.formats.base import VehicleMessageStreamer from openxc import openxc_pb2 LOG...
""" This is an implementation of the Lex Code Hook Interface in order to serve the ShaykhBot to get the ayah requested. """ import math import dateutil.parser import datetime import time import os import logging import requests logger = logging.getLogger() logger.setLevel(logging.DEBUG) """ --- Helpers to build re...
#!/usr/bin/env python # Copyright 2020 Arm Limited. # SPDX-License-Identifier: Apache-2.0 # # 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 #...
import tensorflow as tf import tensorflow.keras.backend as K import abc from typing import Optional, Callable, List from functools import reduce from common import common class WordsSubtokenMetricBase(tf.metrics.Metric): FilterType = Callable[[tf.Tensor, tf.Tensor], tf.Tensor] def __init__(self, ...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- # # MIT License # # Copyright (c) 2018 Miha Purg <miha.purg@gmail.com> # # 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,...
# Copyright 2020 Google LLC # # 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, ...
#!/usr/bin/env python3 import numpy as np from calc11 import almacalc nant = 1 ntimes = 60 refx = 1000.0 refy = 1299.0 refz = 700.0 antx = np.array([-3101.52]) anty = np.array([-11245.77]) antz = np.array([8916.26]) temp = np.array([30.0]) pressure = np.array([1000.0]) humidity = np.array([0.7]) mjd = np.array([58...
import torch import torch.nn as nn from collections import defaultdict from tqdm import tqdm def train_model(model, train_dl, valid_dl, lr, epochs, verbose=True): device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model.to(device) optimizer = torch.optim.Adam(model.parameters(), lr=lr) ...
p = int(raw_input('Price of lemonade')) c = int(raw_input('Cost of lemonade')) w = int(raw_input('Wage of wokers')) a = int(raw_input('utility function of lemonades U = a*Q + b, a = ')) b = int(raw_input('utility function of lemonades U = a*Q + b, b = ')) ul = int(raw_input('how much you hate work')) fq = int(raw_input...
from django.test import TestCase from bug_tracker_v2.users.models import User # testing coverage: coverage run manage.py test --settings=config.settings.test # coverage html --omit="admin.py" class TrivialTest(TestCase): def setUp(self): self.user = User.objects.create_user(username='name', password='pas...
''' Linking records of various aac affiliated museums against ULAN museum. Record blocking using birth year and record linkage string comparison algorithms ''' import sys, os, re, json, time from unidecode import unidecode from pprint import pprint import pkg_resources from optparse import OptionParser class recordLi...
# Intel® Single Event API # # This file is provided under the BSD 3-Clause license. # Copyright (c) 2021, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: # Redistri...
from click import ClickException from .ui import format_full_image_name from .types import DockerImage class PieroneException(ClickException): '''Thrown when something does not go as expected''' class APIException(PieroneException): """ Exception when accessing the API. ``action`` is a format stri...
""" Pipeline helper functions. """ import os from pipeline_config import * import traceback import time def vbPrint(s): """print only if verbose is enabled Args: s ([type]): [description] """ if(config['verbose']==1): print(s) def setConfig(argv): """ * Takes the termina...
class NavigationHelper: def __init__(self, app): self.app = app def open_home_page(self): wd = self.app.wd if not (wd.current_url.endswith("/") and len(wd.find_elements_by_name("Select all")) > 0): wd.get(self.app.base_url)
############################################################################### # url.py # # Copyright Human # Author ASC_8384 # Mail ASC_8384@foxmail.com # Website http://ASC8384.top # FileName url.py # Description 编码转换: 把某些网站上的乱码转为我的人所可理解的文字 #...
#Source code with the blog post at http://monik.in/a-noobs-guide-to-implementing-rnn-lstm-using-tensorflow/ import numpy as np import random from random import shuffle import tensorflow as tf # from tensorflow.models.rnn import rnn_cell # from tensorflow.models.rnn import rnn NUM_EXAMPLES = 10000 train_input = ['{0:...
from flask import Blueprint, request, jsonify from models.models import ( RelUserFavProject, RelUserInProject, db, UserModel, RelUserLanguage, RelUserTopic, ) user_api = Blueprint("user_api", __name__) @user_api.route("/getUserData", methods=("GET",)) def getUserData(): username = reques...
# File: daterangepicker/forms.py from django.forms import ModelForm from daterangepicker import utils from daterangepicker.utils import DATETIME_INPUT_FORMAT, time_range_generator from daterangepicker.fields import DateTimeRangeField __all__ = [ "TimeRangedModelForm", "utils", "DATETIME_INPUT_FORMAT", ...
#! /usr/bin/env python import base64 import os import sys import subprocess import StringIO if len(sys.argv)<3: print >> sys.stderr, "syntax: copy-opencloud <srcfn> <desthost:destfn>" sys.exit(-1) srcfn = sys.argv[1] dest = sys.argv[2] if not ":" in dest: print >> sys.stderr, "malformed desthost:destfn"...
from django.views.generic import TemplateView from .calc_modules.minimum_blank_size import MBSCalculate from .calc_modules.back_vertex_power import BVPCalculate from .calc_modules.cylinder_transpose import CTCalculate from .calc_modules.mean_ocular_perfusion_pressure import MOPPCalculate class IndexView(TemplateView...
# -*- coding: utf-8 -*- __author__ = ["chrisholder"] from typing import Any import numpy as np from numba import njit from sktime.distances.base import DistanceCallable, NumbaDistance class _SquaredDistance(NumbaDistance): """Squared distance between two time series.""" def _distance_factory( self...
#!/usr/bin/env python import argparse from flask import Flask, jsonify, request, abort from dispatch import Dispatcher app = Flask(__name__) PROFILE = None @app.route('/') def ok(): """ Verify the system is running. """ return jsonify({"response": "200 OK"}), 200 @app.errorhandler(400) def bad_r...
from inferelator import utils from inferelator import workflow from inferelator.distributed.inferelator_mp import MPControl from inferelator.preprocessing import single_cell from inferelator.regression.bbsr_multitask import BBSRByTaskRegressionWorkflow N_CORES = 100 INPUT_DIR = '/mnt/ceph/users/cjackson/inferelator/da...
#! /usr/bin/env python # run this scritp along with _06Briding_openCV_ROS.py from this package import rospy, cv2, time from cv_bridge import CvBridge, CvBridgeError from sensor_msgs.msg import Image # CONSTANTS NODE_NAME = "image_publisher" IMAGE_TOPIC = "image" # GLOBALS image_pub = None bridge = CvBridge() def m...
# Generated by Django 3.0.2 on 2020-02-13 14:44 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('shortcode', '0024_auto_20200213_0846'), ] operations = [ migrations.RenameField( model_name='ad...
import numpy as np import tensorflow as tf from ..common.utils import logger """ Simple time-series modeling with custom RNN Some code motivated by: Hands-On Machine Learning with Scikit-Learn and TensorFlow by Aurelien Geron https://machinelearningmastery.com/time-train_series-forecasting-long-short-term-me...
""" .. Copyright (c) 2014-2017, Magni developers. All rights reserved. See LICENSE.rst for further information. Module providing the public function of the magni.cs.phase_transition subpackage. """ from __future__ import division import os import re import types from magni.cs.phase_transition import _an...
import weakref from pyqtgraph import ROI, PolyLineROI, Point from pyqtgraph.graphicsItems.ROI import Handle, RectROI, LineROI from qtpy.QtCore import QRectF, QPointF, Qt, Signal, QSize from qtpy.QtGui import QColor, QPainter, QPainterPath, QBrush, QPainterPathStroker, QCursor from qtpy.QtWidgets import QAction, QVBoxLa...
import os # scenario name for log file scenario_name = "20mus" # material parameters # -------------------- Conductivity = 3.828 # [mS/cm] sigma, conductivity Am = 500.0 # [cm^-1] surface area to volume ratio Cm = 0.58 # [uF/cm^2] membrane capacitance, (1 = fast twitch, 0.58 = ...
from .boilerplates import * from .geometry import * from .graphics import * from .uitools import * from .util import * from .tile import * from .sprite import Sprite
## Haralambi Todorov (harrytodorov@gmail.com) ## University of Freiburg, Germany ## November 2018 # The Expectation Maximization algorithm # Input: Observed data X=(X_1, ..., X_N), # number of iterations, # initial values for theta_A, theta_B # parameter m # Output: theta_A, theta_B ...
import logging import matplotlib as mpl import matplotlib.pyplot as plt logger = logging.getLogger(__name__) logging.getLogger('matplotlib').setLevel(logging.INFO) def plotPxx(Pxx, freqs, out=None, title=None): ''' Function to plot PSD and save ''' fig, ax = plt.subplots(1) ax.loglog(freqs, Pxx) a...
#!/bin/python3 import sys def twinArrays(ar1, ar2): a1 = min(ar1) a2 = min(ar2) if ar1.index(a1) != ar2.index(a2): return a1+a2 else: a = sorted(ar1) b = sorted(ar2) if a[1] < b[1]: return a[1] + a2 else: return a1 + b[1] n = int(input(...
"""""" # -*- coding: utf-8 -*- # date: 2021 # author: AllChooseC import numpy as np import scipy as sc from scipy import signal from sklearn.preprocessing import normalize import torch class ToSpectrogram(object): """""" def __init__(self, nperseg=32, noverlap=16): assert isinstance(nperseg, int) ...
import logging from django.db import connections # project from ...ext import sql as sqlx from ...ext import AppTypes from .conf import settings log = logging.getLogger(__name__) CURSOR_ATTR = '_datadog_original_cursor' def patch_db(tracer): for c in connections.all(): patch_conn(tracer, c) def un...
import json from os.path import abspath, dirname, isfile, join CURRENT_DIR = dirname(abspath(__file__)) TEST_DATA_DIR = join(dirname(dirname(dirname(CURRENT_DIR))), 'test_data') from opendp_apps.analysis.testing.base_stat_spec_test import StatSpecTestCase from opendp_apps.analysis.tools.dp_count_spec import DPCountSp...
from PIL import Image import numpy as np import matplotlib.pyplot as plt import networkx as nx import torch.nn.functional as F label_colours = [(178, 45, 45), (153, 115, 115), (64, 36, 32), (255, 68, 0), (89, 24, 0), (191, 121, 96), (191, 102, 0), (76, 41, 0), (153, 115, 38), (102, 94, 77), (242, 194...
#!/usr/bin/env python # Copyright 2017 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. """Downloads cloud_sql_proxy for Linux and Mac, and packages it as cipd. See https://cloud.google.com/sql/docs/mysql/sql-proxy#install...