content
stringlengths
5
1.05M
def main(): a, b = map(int, input().strip() .split()) nums_high = [3]*a nums_low = [-3]*a for i in range(b): t = int(input()) nums_high[i] = t nums_low[i] = t ans1 = sum(nums_low) / a ans2 = sum(nums_high) / a print(ans1, ans2) if __name__ == "__main__": main() ...
# -*- coding:utf-8 -*- import torch from allennlp.training.metrics.metric import Metric class SentenceAccuracy(Metric): def __init__(self): self.correct_count = 0.0 self.total_count = 0.0 def __call__(self, domain_pred=None, domain_gold=None, intent_pred=None, intent_gold=No...
import unittest import subprocess import semantic_version from package_version import PackageVersion from future import standard_library standard_library.install_aliases() from flexmock import flexmock class VersionsTestCase(unittest.TestCase): def setUp(self): output = 'pip 1.5.3 from /virtualenv/lib/py...
from __future__ import print_function, division # import sys,os quspin_path = os.path.join(os.getcwd(),"../../") sys.path.insert(0,quspin_path) # from quspin.operators import hamiltonian # Hamiltonians and operators from quspin.basis import spinless_fermion_basis_1d # Hilbert space spinless fermion basis import numpy a...
class Cell: def __init__(self, num): self.num = num def __setattr__(self, attr, value): if attr == "num": self.__dict__[attr] = value else: print(f"Атрибут {attr} недопустим") def __str__(self): return str(self.num) def __add__(self, other): ...
from Ab_data_loader import loader """ Import the following files from the import folder. + Assumptions + Population forecast + Acute Hospital activity + Community activity """ class assumptions_data(loader): """Assumptions driving the model. Inherits from base class loader Attributes: data (pd...
import argparse import numpy as np def argument_parser(): """Parse input arguments.""" parser = argparse.ArgumentParser(description="Modify fk tables to swap x-grid.") parser.add_argument("fk_file", help="A file to modify.") args = parser.parse_args() return args def load_fk(fk_file: str): "...
from .connection import Connection from .skills import Skills from .utils import Utils class Amsel(Connection, Skills, Utils): # Constructor def __init__(self, local_ip="192.168.0.100", speed=100): Connection.__init__(self, local_ip) Skills.__init__(self, speed) # Standard return method def __str__...
import requests from django.conf import settings from django.core.cache import cache from django.views.generic import TemplateView from rest_framework import status from rest_framework.response import Response from rest_framework.views import APIView from api.serializers import IngredientsSerializer from core.ingredie...
import pandas as pd import matplotlib.pyplot as plt min_heap_times = pd.read_csv("benchmark.txt", sep="\t") ax = plt.gca() #gca = get current axis min_heap_times.plot(kind='line', x='n', y='On Heaps', ax=ax) min_heap_times.plot(kind='line', x='n', y='On Arrays', ax=ax) plt.xlabel('Input size') plt.ylabel('Elapsed ti...
import sqlite3 conn = sqlite3.connect('crawl.sqlite') cur = conn.cursor() cur.execute('SELECT DISTINCT from_id FROM Links') #store distinct from ids into a list from_ids=list() for row in cur: from_ids.append(row[0]) #store to_ids into a list which are in from ids also to_ids=list() links=list() cur.execute('SEL...
import os import sys import warnings BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(BASE_DIR) warnings.filterwarnings('ignore') import argparse import functools import time import torch from torch.utils.data import DataLoader from simpleAICV.detection.common import DetectionC...
import platform import os cmd = "git clone https://github.com/emscripten-core/emsdk.git" returned_value = os.system(cmd) # returns the exit code in unix print('returned value:', returned_value) if platform.system() == 'Linux': cmd = "./emsdk/emsdk install latest" else: cmd = ".\\emsdk\\emsdk.bat install ...
# -*- coding: utf-8 -*- class Setting(object): @classmethod def db_name(cls): return 'NK225FTicks' @classmethod def db_port(cls): return '5432' @classmethod def db_user(cls): return 'postgres' @classmethod def db_password(cls): return 'ba'
""" Commands available """ from .api_as_source import ApiAsSourceCommand from .bonobo_etl import BonoboEtlCommand from .pandas_etl import PandasEtlCommand COMMANDS = { "api_as_source": ApiAsSourceCommand, "bonobo_etl": BonoboEtlCommand, "pandas_etl": PandasEtlCommand } __all__ = ['get_command'] def get...
"""empty message Revision ID: b7dca6de930b Revises: Create Date: 2017-11-18 18:42:26.022147 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'b7dca6de930b' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto gene...
from util.combinatorics.amounts import lattice_paths def problem_0015(grid_height: int, grid_width: int) -> int: return lattice_paths(grid_height, grid_width) if __name__ == '__main__': GRID_HEIGHT = 20 GRID_WIDTH = 20 print(problem_0015(GRID_HEIGHT, GRID_WIDTH)) # Expected: 137846528820
import pytest import pandas as pd from castjeeves.sourcehooks import County @pytest.fixture(scope='module') def resource_a(request, source_resource): return County(sourcedata=source_resource) def test_countyid_query_from_LIST_of_countystatestrs(resource_a): test_values = ['Adams, PA', 'Anne Arundel, MD'] ...
import scipy from SloppyCell.ReactionNetworks import * from Nets import * net1.resetDynamicVariables() traj1 = Dynamics.integrate(net1, (10**-5, 10**2)) net2.resetDynamicVariables() traj2 = Dynamics.integrate(net2, (10**-3, 10**4)) Plotting.figure(1, figsize=(8,10)) Plotting.subplot(3,1,1) Plotting.semilogx(traj1....
"""Create custom logger.""" from sys import stdout from loguru import logger as loguru_logger def create_logger(): """Create custom logger.""" loguru_logger.remove() loguru_logger.add( stdout, colorize=True, level="INFO", catch=True, format="<green>{time:MM-DD-YYYY ...
import json import codecs import tldextract import pickle import random import copy import matplotlib.pyplot as plt # One of 'city', 'name', 'phone' VARIABLE = 'phone' with open('backpage.com/nebraska.json', "rb") as fp: urls = pickle.load(fp) count = 0 def preprocess(urls): ad_to_extraction = dict() ex...
from com.arm.debug.dtsl.configurations import DTSLv1 from com.arm.debug.dtsl.components import FormatterMode from com.arm.debug.dtsl.components import CSDAP from com.arm.debug.dtsl.components import MemoryRouter from com.arm.debug.dtsl.components import DapMemoryAccessor from com.arm.debug.dtsl.components import D...
from __future__ import annotations from enum import Enum from random import randint from tic_tac_toe.core.board import DEFAULT_BOARD from tic_tac_toe.errors import InvalidMoveError, NoMovesAvailableError class Player(Enum): PLAYER_X = "X" PLAYER_O = "O" class GameController: def __init__( self...
# (c) 2019 Open Risk (https://www.openriskmanagement.com) # # This code is licensed under the Apache 2.0 license a copy of which is included # in the source distribution of the course. This is notwithstanding any licenses of # third-party software included in this distribution. You may not use this file except in # com...
# -*- coding: utf-8 -*- import numpy as np import timeit from random import randint from pylab import * from PIL import Image, ImagePath from scipy.ndimage import measurements from os import listdir, path # Taken from # https://stackoverflow.com/questions/25664682/ # how-to-find-cluster-sizes-in-2d-numpy-array def ge...
import sys V = int(input()) n = int(input()) i = 0 for cur in input().split(): if (V == int(cur)): print(i) i += 1
import tkinter as tk from tkinter import filedialog from generator.word_gen import DependenciesMatrix, WordGenerator from generator.utils import split_text class App(tk.Tk): DEF_GRID = { "sticky": tk.NSEW, "padx": 5, "pady": 5, } def __init__(self, *args, **kwargs): super...
from .wrapper import model_ihc, model_synapse, seed_rng, get_matlab from .cache import get_spiketrain
"""test_device_m2m.py""" import unittest import time from py_connect.hw_devices.power_connections import * from py_connect.hw_devices.hw_connections import * from py_connect.hw_devices.exceptions import * from py_connect import DeviceHandler class TestHwConnections(unittest.TestCase): def devices(self): ...
#Design-space sweep for the Joby S2 import os import sys sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/../..')) import math import numpy as np from gpkit import Variable, VectorVariable, Model, Vectorize, ureg from rotor_test import rotors_analysis_function from standard_atmosphere import stdatmo from...
import pymunk, sys from pymunk.pygame_util import * from pymunk.vec2d import Vec2d import pygame from pygame.locals import * import numpy as np from PIL import Image from pymunk.pygame_util import DrawOptions from ActorCritic import Agent import matplotlib.pyplot as plt def convert_coordinates(point): ...
# # # import sys, os import tensorflow as tf from mynet.mynet_training import train_and_validate from mynet.mynet_testing import test_cnn_net # cwd = os.getcwd() sys.path.append(os.path.realpath(cwd)) tf.logging.set_verbosity(tf.logging.INFO) flags = tf.app.flags # # parameter setting with flags flags.DEFINE_bool('tra...
from typing import Dict, List import torchvision import torch from .build import TRANSFORM_REGISTRY import torchvision.transforms.functional as F from .functional import hflip, one_hot_semantic, vertx2semantic @TRANSFORM_REGISTRY.register_module class RandomHorizontalFlip(torch.nn.Module): def __init__(self, ...
#!/usr/bin/env python # -*- coding: UTF-8 -*- """ find and PRINT on screen only the top positive and negative sentiment per topic CHECK HERE DO WE NEED A DIFFERENT SORTING of the sentiment """ import codecs from collections import defaultdict, OrderedDict import json import re import glob, os import math ...
import os wtg_path = os.path.dirname(__file__) + "/" example_data_path = os.path.dirname(__file__) + "/"
import argparse import os from .logger import * from .orchestra import play __version__ = '0.0.6' def parse_args(): parser = argparse.ArgumentParser() parser.add_argument( "--swagger", required=True, help="Location of swagger document. Could be HTTP endpoint or local file system", ...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack, LLC # 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/...
import scrapy import re from novel_scrapy.common.font_num import FontToNum from novel_scrapy.items import NovelBookItem from novel_scrapy.common.LogHandler import Loghandler log = Loghandler('QdSpider') class QdSpider(scrapy.Spider): name = 'qd' allowed_domains = ["www.qidian.com"] start_urls = ['https:/...
import os def update_bounding_box(file_name, box = None): ''' Looks for a line of the form %%BoundingBox: xmin ymin xmax ymax in file_name Adjusts current box to take the largest available box ''' file = open(file_name,'r') found = False for line in file: if line.startswith('%%BoundingBox:'): ...
from pypkgtemp.hello import HelloWorld, fizzbuzz def test_example(): assert 1 == 1 def test_helloworld_hello(): helloworld = HelloWorld('Chris', 'Ostrouchov') assert helloworld.hello == 'Hello Chris Ostrouchov' def test_helloworld_helloworld(): assert HelloWorld.helloworld('Chris') == 'Hello World...
import numpy as np import matplotlib.pyplot as plt import helper_salary as helper def create_mean_salary_barchart(uc_schools): """ This function takes a list of uc schools and it returns mean salary barchart. : param uc_schools: (list), uc schools """ assert len(uc_schools) > 0 y_pos = np....
# Crie um programa que leia quanto dinheiro uma pessoa tem na carteira e mostre quanto ela pode comprar em dolar din = float(input('Digite quantos reais você tem na carteira: R$')) dol = din / 3.27 print('Com R${:.2f} você pode comprar ${:0.2f} '.format(din, dol))
import json import time import os import threading from datetime import datetime, timedelta from re import sub from decimal import Decimal import PyInquirer ## from .colorize import colorize from .driver import Driver from .settings import Settings class User: def __init__(self, data): data = json.loads(j...
''' this is really a classic problem 1. DP O(n*sqrt(n)) you have to use static array, otherwise TLE 2. BFS ''' class Solution: _dp = [0] def numSquares(self, n: int) -> int: dp = self._dp while len(dp)<=n: cur = len(dp) temp = float('inf') for i in range(1,...
#!/usr/bin/env python # -*- coding: utf-8 -*- from datetime import datetime, date import cerberus import unittest import pickle class SanheUnittest(unittest.TestCase): def setUp(self): schema = { "a_date": { "type": "date", "after": date(2000, 1, 1), "before": ...
#-*- coding:utf-8 -*- from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # url(r'^grappelli/',include('grappelli.urls')), #放admin前面优先加载 url(r'^admin/', include(admin.site.urls)), url(r'^',include('blog.urls')), url(r'^se...
# 循环便利 # Python叫迭代器 d = {'a': 'qq', 'b': 'bb', 'c': '3'} for e in d : print(e + ',') # 字符串也可以迭代 for c in 'ABCDEFG': print(c) # 判断一个对象是否可以被迭代 from collections import Iterable print(isinstance('abc', Iterable)) # 如何取下标 for i, value in enumerate(['A', 'B', 'C']): print(i, value) for key, value in enum...
import asyncio import json import click from kubernetes import client, config async def run(cmd): proc = await asyncio.create_subprocess_shell( cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE ) stdout, stderr = await proc.communicate() result = proc.return...
from .utils import * from .rgbd import * from .pose import * import open3d as o3d import numpy as np import matplotlib.pyplot as plt import cv2 import os from collections import Iterable class TSDFContainer: ''' 对数据集和重建流程的封装 ''' default={ "datasetBase":"./datasets/", "dataset"...
################################################ # # # Institute: University of Sussex # # Project Type: Assignment # # # # G6019: Knowledge & Reasoning # # Minimax With Alpha...
# -*- coding: utf-8 -*- """ Identification of spectral properties in analog signals (e.g., the power spectrum) :copyright: Copyright 2015 by the Elephant team, see AUTHORS.txt. :license: Modified BSD, see LICENSE.txt for details. """ import warnings import numpy as np import scipy.signal import scipy.fftpack as fftp...
def repl_at(string: str, _idx: int, _new: str) -> str: return string[:_idx] + _new + string[_idx + 1:] def repl_last(string: str, _old: str, _new: str): return repl_at(string, string.rindex(_old), _new)
# -*- coding: utf-8 -*- ''' TopQuant-TQ极宽智能量化回溯分析系统2019版 Top极宽量化(原zw量化),Python量化第一品牌 by Top极宽·量化开源团队 2019.01.011 首发 网站: www.TopQuant.vip www.ziwang.com QQ群: Top极宽量化总群,124134140 文件名:toolkit.py 默认缩写:import topquant2019 as tk 简介:Top极宽量化·常用量化系统参数模块 ''' # import sys, os, re import arrow, bs4, rando...
import json from flask import Flask, jsonify, request from greentastic.api_requests import get_autocomplete, get_directions from greentastic.compute_scores import compute_score app = Flask(__name__) @app.route('/query_directions', methods=['GET', 'POST']) def query_directions(): """ Receives a query to com...
"""Example package for URL dependencies."""
import utilities.languages_utilities as lu from django.test import TestCase class TestUtilities(TestCase): def test_get_languages_and_levels_pairs(self): self.assertEqual(lu.get_languages_and_levels_pairs('Se requiere inglés fluido y básico de francés'), [('inglés', 'C1'), ('francés', 'B1')]) self...
# # Filter.py # # Herein lies all the ugliness needed to convert GFF3 files as downloaded from their # respective sources into GFF3 as needed for import. # A filter implements a set of transformations on a gene model. # In genomes.json, each stanza specifies (by name) zero or more filters to apply during import. # The...
""" Created on Jun 15, 2013 :author: andrei """ import pickle from bioflow.utils.log_behavior import get_logger from bioflow.configs.main_configs import Dumps, reactome_biopax_path from bioflow.configs.main_configs import reactome_forbidden_nodes from bioflow.neo4j_db.GraphDeclarator import DatabaseGraph from bioflow.b...
import turtle wn = turtle.Screen() colors = ["orange", "forest green", "deep sky blue", "gold", "red", "sienna"] t = turtle.Turtle() t.color("red") i = 0 t.speed(0) # 3 ist die Default-Geschwindigkeit der Turtle, 0 ist die schnellste for angle in range(0, 360, 5): t. color(colors[i % 6]) t.seth(angle) t...
from cartoframes.auth import set_default_credentials from cartoframes import read_carto, to_carto import geopandas as gpd import pandas as pd import os import logging from shapely import geometry # set up logging # get top-level logger object logger = logging.getLogger() for handler in logger.handlers: logger.remov...
# https://www.django-rest-framework.org/api-guide/testing/ from django.test import TestCase from rest_framework.decorators import api_view, action from rest_framework.response import Response from rest_framework import mixins, viewsets from artifacts.models import Artifact from people.models import Person from vehicle...
def resolve(): ''' code here ''' N = int(input()) X = [item for item in input()] cnt_1_x = X.count('1') def cal(i, X): cnt = 0 if X[i] == '1': X[i] = '0' cnt_1 = cnt_1_x - 1 else: X[i] = '1' cnt_1 = cnt_1_x + 1 ...
# cli build # cli run # cli gen # cli version # cli gen build run from genericpath import exists import os, sys import subprocess from typing import Pattern TOOLS_DIR = "tools" def RunCommand(cmd): ret = 0 script = "{}/{}/{}.py".format(os.getcwd(), TOOLS_DIR, cmd) if os.path.exists(script): print("Executing:...
""" Stochastic Model Gender Diversity 5 Year Forecasts --------------------- This is the second generation of the gender diversity model with 5 year forecasts. Notes: 09/14/2017 - This is the first version of the second generate model. """ __author__ = 'krishnab' __version__ = '0.1.0' import numpy as np import pan...
""" MIT License Copyright (c) 2016 Zeke Barge 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, di...
import ftplib import logging import os import platform import socket import time """ Atomic synchronous download/upload jobs to be executed either on main or background thread """ FTP_RETRY_COUNT = 10 # attempts to execute failed FTP operation FTP_RETRY_DELAY = 3 # seconds between another FTP attempt FTP_OPERATION_...
import os import time import random from eval import * from flask import Flask, jsonify, request, abort from miscc.config import cfg from flask_cors import CORS # from werkzeug.contrib.profiler import ProfilerMiddleware app = Flask(__name__) CORS(app) @app.route('/api/v1.0/coco', methods=['POST']) def create_coco()...
import json import os import pathlib import git import jsonschema from django.conf import settings from git.exc import GitError """ Given a repo, crawl its subdirectories and return paths to directories with valid config.json """ def find_valid_dirs(repo): with open(pathlib.Path(__file__).parent.joinpath("exper...
""" Tool contract wrappers for miscellaneous quick functions involving filtration """ import logging import sys import re from pbcoretools.DataSetEntryPoints import parse_filter_list from pbcore.io import openDataSet from pbcommand.cli import registry_builder, registry_runner, QuickOpt from pbcommand.models import Fi...
# Copyright 2017 AT&T Corporation. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless require...
"""SKINNY-128-128. TK1 version, where the tweakey size is equal to the block size. A `WeakModel` is used to model the XOR and linear models of the S-box. """ from cascada.bitvector.core import Constant from cascada.bitvector.operation import BvIdentity from cascada.bitvector.secondaryop import LutOperation from casca...
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import absolute_import, division, print_function, unicode_literals import os from builtins import object from pants.base.specs import DescendantAddresses, ...
from __future__ import print_function import random import tweepy from spacenamer.generator import spacename from words import WORDS def generate_status(word=None): at_reply = False if word is None: word = random.choice(WORDS) if word[0] == '@': word = word[1:] at_reply = True...
from . import iter, matrix, predicates from .core import * from .parsing import * from .syntax_tree import SyntaxTree
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the Apache License. import json import os from azurelinuxagent.common.future import httpclient from azurelinuxagent.common import conf from azurelinuxagent.common.exception import IncompleteGoalStateError from azurelinuxagent.common.protocol...
# 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 use ...
import cPickle as pickle import os import numpy as np def load_CIFAR_batch(filename): with open(filename, 'r') as f: datadict = pickle.load(f) X = datadict['data'] Y = datadict['labels'] X = X.reshape(10000, 3, 32, 32).transpose(0, 2, 3, 1).astype('float') Y = np.array(Y) ...
import os from typing import Callable, Optional, Tuple, List, Dict, Collection, Any from torch.utils.data import Dataset class DatasetFolderOfFolder(Dataset): """ root/class_x/id1/ root/class_x/id2/ ... root/class_y/id10/ ... """ def __init__( self, root: str, ...
#! /usr/bin/env python from gazebo_msgs.srv import GetModelState import rospy class Block: def __init__(self, name, relative_entity_name): self._name = name self._relative_entity_name = relative_entity_name class State: _blockListDict = { 'block_a': Block('person_walking_0', 'link'),...
from typing import Union, Iterable, Coroutine from inspect import getmembers import asyncio import discord from . import Listener, listener, Command, command, CommandAdmin, CommandSuperAdmin from ..utils import list_to_str, Logs class CommandSet: """Base class to create a group of commands and listeners""" def ...
# TestSwiftStructChangeRerun.py # # This source file is part of the Swift.org open source project # # Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors # Licensed under Apache License v2.0 with Runtime Library Exception # # See https://swift.org/LICENSE.txt for license information # See https://swift.o...
from django import forms #from eve_db.models import InvBlueprintType from apps.api.models import Character, CharSkill, Skill class SelectBlueprintForm(forms.Form): """ Form to select the blueprint the user wants to manufacture. """ blueprint = forms.CharField(max_length=100, widget=forms.TextInput(att...
from .get import get from .path import path
#DESAFIO 034: Escreva um programa que pergunte o salário de um funcionário e calcule o valor do seu aumento. #Considere: Para salários superiores a R$ 1250,00 calcule um aumento de 10%. Para salários inferiores ou iguais, o aumento é de 15%. salario = float(input('Qual é o salário do funcionário? R$ ')) if salario <=...
import math import os import time import tempfile from termcolor import colored import matplotlib.pyplot as plt import numpy as np import tensorflow as tf import config from function_classifier_gru_estimator import lstmnet import gen_data # Implementation with tfrecords and compliance with tf estimator API GENERATE...
import h1st as h1 import pandas as pd import os import sklearn import sklearn.metrics import subprocess import pathlib from sklearn.ensemble import RandomForestRegressor from sklearn.pipeline import Pipeline from sklearn.compose import make_column_transformer from sklearn.preprocessing import OneHotEncoder from Forecas...
import pytest from functools import partial import numpy as np import numpy.testing as npt import astropy.units as u import astropy.constants as cst from astropy.wcs import WCS from astropy.nddata import StdDevUncertainty from kidsdata.ftsdata import FTSData def empty_ds(n_itg=1024, n_pix=1): """Double sided"...
class IdLoader: @staticmethod def process_identifiers(identifier, dataProvider): dataProviderDict = { 'DRSC' : 'DRSC:' } # Remove the prefix of the identifier based on the dataProvider. prefix = dataProviderDict[dataProvider] if identifier.startswith(prefix): return identifier[len(prefix):] @s...
from time import time from django.db import models from django.urls import reverse from django.utils.text import slugify from django.contrib.auth.models import User class UsersRatedRecord(models.Model): user_pk = models.IntegerField() rating = models.IntegerField() def __str__(self): usernam...
# this script is designed to be run via the IPython %run magic import matplotlib.pyplot as plt import numpy as np import sys import pdplot as p import qualtrics_api.Qv3_helpers as qh import settings import util as u try: __IPYTHON__ pass except NameError: raise RuntimeError("This script is for IPython mag...
# Run as script using 'python -m test.synth' import cPickle import os import matplotlib.pyplot as plt from pyglm.models.model_factory import * from pyglm.inference.gibbs import initialize_updates from population import Population def geweke_test(population, data, N_samples=1000): ...
#!python """ Lizard extension to count occurences and span of tokens within a function. :seealso: https://www.fluentcpp.com/2018/10/23/word-counting-span/ https://github.com/terryyin/lizard/tree/master/lizard_ext Note the style of this module is consistent with the lizard project as we may move it there if it adds v...
from modules.featrep import FeatureRep from commons import Feature from transformers.modeling_bert import BertModel, BertPreTrainedModel, BertConfig from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence import torch import torch.nn as nn """ Xây dựng class con lấy BertPreTrainedModel làm class cha...
from Tkinter import * root = Tk() label1 = Label( root, text="Month(MM)") E1 = Entry(root, bd =5) label2 = Label( root, text="Day(DD)") E2 = Entry(root, bd =5) label3 = Label( root, text="Year(YYYY)") E3 = Entry(root, bd =5) def getDate(): print E1.get() print E2.get() print E3.get() submit = Button(...
import torch from evaluation import evalFcn from utils import myUtils from ..Model import Model import collections class Stereo(Model): # dataset: only used for suffix of saveFolderName # maxdisp: disparity range of self.model. # ( # Note: the definition of maxdisp was changed from commit:d46b96. ...
# script for replace placeholders from string import Template from datetime import datetime from data_email import my_email, my_password from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.image import MIMEImage import smtplib with open('template.html', 'r') as html: ...
#!/usr/bin/env python """ Wikipedia: part of the brainbehavior python package BrainBehavior: This module will work with three databases that combined can make inferences about disorders and behaviors. SAMPLE USAGE: Please see README included with package """ from wikipedia import search, page import re __author_...
import re import numpy as np import pandas as pd from six import StringIO from ..definitions import ( PART_OF_PRNFILE, convert_magicc6_to_magicc7_variables, convert_magicc7_to_openscm_variables, convert_magicc_to_openscm_regions, ) from .base import _Writer from .scen import _NonStandardEmisInReader ...
"""Command-line programs using :pypi:`click`.""" import abc import asyncio import inspect import io import os import sys from functools import wraps from pathlib import Path from textwrap import wrap from types import ModuleType from typing import ( Any, Awaitable, Callable, ClassVar, Dict, IO, ...
__version__ = "1.6.3" __author__ = "Jean-Sebastien Dieu"