content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np import copy from core_tools.utility.plotting.plot_settings import plot_layout, graph_settings_1D, _1D_raw_plot_data from core_tools.utility.plotting.plot_general import _data_plotter # TODO add log scale support !!! if __name__ == '__main__': from colors import MATERIAL_COLOR, Red # global settings g = graph_settings_1D() g.color = Red[::-1] g.linewidth = 1 a = plotter_1D(graph_setings=g) a[0].set_labels('x_label', 'y_label') a[0].add_data(np.linspace(0,50,200), np.sin(np.linspace(10,50,200)), w = 'p', alpha = 1, c=Red[5]) a[0].add_data(np.linspace(0,50,200), np.sin(np.linspace(10,50,200)), w = 'l', alpha = 0.3, c=Red[5]) # a.plot() a.save('test1D_single.svg') a = plotter_1D(plot_layout(n_plots_x = 1,n_plots_y = 2)) a[0].set_labels('x_label', 'y_label') a[0].add_data(np.linspace(10,50,50), np.random.random([50])) a[0,1].set_labels('x_label', 'y_label') a[0,1].add_data(np.linspace(10,50,50), np.random.random([50])) a.save('test1D_12.svg') # a.plot() a = plotter_1D(plot_layout(n_plots_x = 2,n_plots_y = 2, share_x=True, share_y=True)) a[0].set_labels('x_label', 'y_label') a[0].add_data(np.linspace(10,50,50), np.random.random([50]), label='test 1') a[0,1].set_labels('x_label', 'y_label') a[0,1].add_data(np.linspace(10,50,50), np.random.random([50]), label='test 2') a[0,1].add_data(np.linspace(10,50,50), np.random.random([50])) a[1,0].set_labels('x_label', 'y_label') a[1,0].add_data(np.linspace(10,50,50), np.random.random([50])) a[1,1].set_labels('x_label', 'y_label') a[1,1].add_data(np.linspace(10,50,50), np.sin(np.linspace(10,50,50))) a.save('test1D_22.svg') # a.plot() a = plotter_1D(plot_layout((300, 70), n_plots_x = 6,n_plots_y = 1, share_x=False, share_y=True)) a[0].set_labels('time (ns)', 'Spin up probably (%)') a[0].add_data(np.linspace(0,500,50), np.sin(np.linspace(10,50,50))) a[1].set_labels('time (ns)', 'Spin up probably (%)') a[1].add_data(np.linspace(0,500,50), np.sin(np.linspace(10,50,50))) a[2].set_labels('time (ns)', 'Spin up probably (%)') a[2].add_data(np.linspace(0,500,50), np.sin(np.linspace(10,50,50))) a[3].set_labels('time (ns)', 'Spin up probably (%)') a[3].add_data(np.linspace(0,500,50), np.sin(np.linspace(10,50,50))) a[4].set_labels('time (ns)', 'Spin up probably (%)') a[4].add_data(np.linspace(0,500,50), np.sin(np.linspace(10,50,50))) a[5].set_labels('time (ns)', 'Spin up probably (%)') a[5].add_data(np.linspace(0,500,50), np.sin(np.linspace(10,50,50))) print(a) a.save('test1D_61.svg') a.plot()
[ 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 2603, 29487, 8019, 355, 285, 489, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 4866, 198, 198, 6738, 4755, 62, 31391, 13, 315, 879, 13, 29487, 889, 13, 29487, 62,...
2.112642
1,234
# last edit date: 2016/11/2 # author: Forec # LICENSE # Copyright (c) 2015-2017, Forec <forec@bupt.edu.cn> # Permission to use, copy, modify, and/or distribute this code for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. from socket import * import threading import pyaudio import wave import sys import zlib import struct import pickle import time import numpy as np CHUNK = 1024 FORMAT = pyaudio.paInt16 CHANNELS = 2 RATE = 44100 RECORD_SECONDS = 0.5
[ 2, 938, 4370, 3128, 25, 1584, 14, 1157, 14, 17, 198, 2, 1772, 25, 4558, 66, 198, 2, 38559, 24290, 198, 2, 15069, 357, 66, 8, 1853, 12, 5539, 11, 4558, 66, 1279, 754, 66, 31, 11110, 457, 13, 15532, 13, 31522, 29, 198, 198, 2, ...
3.263158
323
from gdb.models import *
[ 6738, 308, 9945, 13, 27530, 1330, 1635, 198 ]
3.125
8
from .base import ArticleView, ArticlePreviewView, ArticleListView, SearchView, LandingView, \ CategoryView, TagView, SubscribeForUpdates, UnsubscribeFromUpdates from .ajax import GetArticleSlugAjax, TagsAutocompleteAjax from .errors import page_not_found, server_error
[ 6738, 764, 8692, 1330, 10172, 7680, 11, 10172, 48835, 7680, 11, 10172, 8053, 7680, 11, 11140, 7680, 11, 29689, 7680, 11, 3467, 198, 220, 220, 220, 21743, 7680, 11, 17467, 7680, 11, 19808, 1890, 4933, 19581, 11, 791, 7266, 12522, 4863, ...
3.468354
79
# by MrSteyk & Dogecore # TODO: extraction instructions & testing import json import os.path from typing import List import bpy loaded_materials = {} MATERIAL_LOAD_PATH = "" # put your path here # normal has special logic MATERIAL_INPUT_LINKING = { "color": "Base Color", "rough": "Roughness", "spec": "Specular", "illumm": "Emission", }
[ 2, 416, 1770, 7447, 48361, 1222, 2141, 469, 7295, 198, 2, 16926, 46, 25, 22236, 7729, 1222, 4856, 198, 11748, 33918, 198, 11748, 28686, 13, 6978, 198, 6738, 19720, 1330, 7343, 198, 198, 11748, 275, 9078, 628, 198, 14578, 62, 33665, 82...
2.770992
131
from django.db import models TASK_STATUS = ( ("c", "created"), ("p", "progress"), ("s", "success"), ("f", "failed") )
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 628, 198, 51, 1921, 42, 62, 35744, 2937, 796, 357, 198, 220, 220, 220, 5855, 66, 1600, 366, 25598, 12340, 220, 198, 220, 220, 220, 5855, 79, 1600, 366, 33723, 12340, 220, 198, 220, 220, 220,...
2.225806
62
# Copyright (c) 2018 European Organization for Nuclear Research. # 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 agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_config import cfg reaper_group = cfg.OptGroup( 'reaper', title='Aardvark Service Options', help="Configuration options for Aardvark service") reaper_opts = [ cfg.StrOpt('reaper_driver', default='chance_driver', help=""" The driver that the reaper will use Possible choices: * strict_driver: The purpose of the preemptibles existence is to eliminate the idling resources. This driver gets all the possible offers from the relevant hosts and tries to find the best matching for the requested resources. The best matching offer is the combination of preemptible servers that leave the least possible resources unused. * chance_driver: A valid host is selected randomly and in a number of preconfigured retries, the driver tries to find the instances that have to be culled in order to have the requested resources available. """ ), cfg.IntOpt('alternatives', default=1, help=""" The number of alternative slots that the the reaper will try to free up for each requested slot. """ ), cfg.IntOpt('max_attempts', default=5, help=""" The number of alternative slots that the the reaper will try to free up for each requested slot. """ ), cfg.ListOpt('watched_aggregates', default=[], help=""" The list of aggregate names that the reaper will try to make space to Each element of the list can be an aggregate or a combination of aggregates. Combination of aggregates is a single string with a vertical-line-separated aggregate names. e.g. watched_aggregates={agg_name1},{agg_name2}|{agg_name3}',.... For each element in the list, a reaper thread will be spawned and the request will be forwarded to the responsible worker. If the provided list is empty, only one worker will be spawned, responsible for the whole system. """ ), cfg.StrOpt('job_backend', default='redis', choices=('redis', 'zookeeper'), help=""" The backend to use for distributed task management. For this purpose the Reaper uses OpenStack Taskflow. The two supported backends are redis and zookeper. """ ), cfg.StrOpt('backend_host', default='localhost', help=""" Specifies the host where the job board backend can be found. """ ), ]
[ 2, 15069, 357, 66, 8, 2864, 3427, 12275, 329, 19229, 4992, 13, 198, 2, 1439, 6923, 33876, 13, 198, 2, 198, 2, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, ...
2.786467
1,138
import glob import numpy as np
[ 11748, 15095, 201, 198, 11748, 299, 32152, 355, 45941, 201, 198 ]
3
11
import csv vat_filenames = set() train_csv_filename = 'train_annotations.csv' val_csv_filename = 'val_annotations.csv' for csv_filename in [train_csv_filename, val_csv_filename]: for line in csv.reader(open(csv_filename)): vat_filename = line[0].split('/')[-1] vat_filenames.add(vat_filename) print(len(vat_filenames)) vat_filenames.clear()
[ 11748, 269, 21370, 198, 198, 85, 265, 62, 10379, 268, 1047, 796, 900, 3419, 198, 27432, 62, 40664, 62, 34345, 796, 705, 27432, 62, 34574, 602, 13, 40664, 6, 198, 2100, 62, 40664, 62, 34345, 796, 705, 2100, 62, 34574, 602, 13, 40664,...
2.327044
159
""" This file is part of LiberaForms. # SPDX-FileCopyrightText: 2020 LiberaForms.org # SPDX-License-Identifier: AGPL-3.0-or-later """ import os, json from flask import g, request, render_template, redirect from flask import session, flash, Blueprint from flask import send_file, after_this_request from flask_babel import gettext as _ from liberaforms.models.user import User from liberaforms.models.form import Form from liberaforms.models.site import Site from liberaforms.models.invite import Invite from liberaforms.utils.wraps import * from liberaforms.utils import utils from liberaforms.utils.utils import make_url_for, JsonResponse from liberaforms.utils.dispatcher import Dispatcher from liberaforms.utils import wtf from pprint import pprint admin_bp = Blueprint('admin_bp', __name__, template_folder='../templates/admin') """ User management """ """ Form management """ """ Invitations """ """ Personal Admin preferences """ """ ROOT_USERS functions """
[ 37811, 198, 1212, 2393, 318, 636, 286, 5261, 64, 8479, 82, 13, 198, 198, 2, 30628, 55, 12, 8979, 15269, 8206, 25, 12131, 5261, 64, 8479, 82, 13, 2398, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 13077, 6489, 12, 18, 13, 1...
3.227564
312
import os, copy import cv2 from functools import partial import numpy as np import torch import torchvision from torch.utils.data import Dataset from zephyr.data_util import to_np, vectorize, img2uint8 from zephyr.utils import torch_norm_fast from zephyr.utils.mask_edge import getRendEdgeScore from zephyr.utils.edges import generate_distance_image from zephyr.normals import compute_normals from zephyr.utils.timer import TorchTimer try: from zephyr.datasets.bop_raw_dataset import BopRawDataset except ImportError: pass from zephyr.datasets.prep_dataset import PrepDataset IMPORTANCE_ORDER = [ 28, 27, 32, 33, 36, 35, 29, 16, 26, 22, 13, 4, 26, 21, 22 ]
[ 11748, 28686, 11, 4866, 201, 198, 11748, 269, 85, 17, 201, 198, 6738, 1257, 310, 10141, 1330, 13027, 201, 198, 201, 198, 11748, 299, 32152, 355, 45941, 201, 198, 11748, 28034, 201, 198, 11748, 28034, 10178, 201, 198, 6738, 28034, 13, ...
2.614232
267
from Roteiro7.Roteiro7__funcoes import GrafoComPesos # .:: Arquivo de Testes do Algoritmo de Dijkstra ::. # # --------------------------------------------------------------------------- # grafo_aula = GrafoComPesos( ['E', 'A', 'B', 'C', 'D'], { 'E-A': 1, 'E-C': 10, 'A-B': 2, 'B-C': 4, 'C-D': 3 } ) print(grafo_aula) print('Menor caminho por Dijkstra: ', grafo_aula.dijkstra('E', 'D')) print("-------------------------") grafo_aula2 = GrafoComPesos( ['A', 'B', 'C', 'D', 'E', 'F', 'G'], { 'A-B': 1, 'A-F': 3, 'A-G': 2, 'B-F': 1, 'C-B': 2, 'C-D': 5, 'D-E': 2, 'F-D': 4, 'F-G': 2, 'G-E': 7, } ) print(grafo_aula2) print('Menor caminho por Dijkstra: ', grafo_aula2.dijkstra('A', 'E'))
[ 6738, 371, 1258, 7058, 22, 13, 49, 1258, 7058, 22, 834, 12543, 1073, 274, 1330, 7037, 6513, 5377, 47, 274, 418, 628, 198, 2, 764, 3712, 943, 421, 23593, 390, 6208, 274, 466, 978, 7053, 270, 5908, 390, 360, 45961, 12044, 7904, 13, ...
1.829213
445
# -*- coding: utf-8 -*- # ---------------------------------------------------------------------------- # Copyright Tom Hren # Licensed under the terms of the MIT License # ---------------------------------------------------------------------------- """ Python QtScreenCaster Spyder API. """
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 16529, 10541, 198, 2, 15069, 220, 4186, 367, 918, 198, 198, 2, 49962, 739, 262, 2846, 286, 262, 17168, 13789, 198, 2, 16529, 10541, 198, 37811, 198, 37906, 33734, 2...
5.444444
54
import os, os.path import subprocess from distutils.core import setup from py2exe.build_exe import py2exe PROGRAM_NAME = 'icom_app' PROGRAM_DESC = 'simple icom app' NSIS_SCRIPT_TEMPLATE = r""" !define py2exeOutputDirectory '{output_dir}\' !define exe '{program_name}.exe' ; Uses solid LZMA compression. Can be slow, use discretion. SetCompressor /SOLID lzma ; Sets the title bar text (although NSIS seems to append "Installer") Caption "{program_desc}" Name '{program_name}' OutFile ${{exe}} Icon '{icon_location}' ; Use XPs styles where appropriate XPStyle on ; You can opt for a silent install, but if your packaged app takes a long time ; to extract, users might get confused. The method used here is to show a dialog ; box with a progress bar as the installer unpacks the data. ;SilentInstall silent AutoCloseWindow true ShowInstDetails nevershow Section DetailPrint "Extracting application..." SetDetailsPrint none InitPluginsDir SetOutPath '$PLUGINSDIR' File /r '${{py2exeOutputDirectory}}\*' GetTempFileName $0 ;DetailPrint $0 Delete $0 StrCpy $0 '$0.bat' FileOpen $1 $0 'w' FileWrite $1 '@echo off$\r$\n' StrCpy $2 $TEMP 2 FileWrite $1 '$2$\r$\n' FileWrite $1 'cd $PLUGINSDIR$\r$\n' FileWrite $1 '${{exe}}$\r$\n' FileClose $1 ; Hide the window just before the real app launches. Otherwise you have two ; programs with the same icon hanging around, and it's confusing. HideWindow nsExec::Exec $0 Delete $0 SectionEnd """ zipfile = r"lib\shardlib" setup( name = 'MyApp', description = 'My Application', version = '1.0', window = [ { 'script': os.path.join('.','ICOM.py'), 'icon_resources': [(1, os.path.join('.', 'icom.ico'))], 'dest_base': PROGRAM_NAME, }, ], options = { 'py2exe': { # Py2exe options... "optimize": 2 } }, zipfile = zipfile, data_files = [],# etc... cmdclass = {"py2exe": build_installer}, )
[ 11748, 28686, 11, 28686, 13, 6978, 201, 198, 11748, 850, 14681, 201, 198, 201, 198, 6738, 1233, 26791, 13, 7295, 1330, 9058, 201, 198, 6738, 12972, 17, 13499, 13, 11249, 62, 13499, 1330, 12972, 17, 13499, 201, 198, 4805, 7730, 24115, ...
2.183953
1,022
import torch from farm.data_handler.samples import Sample from farm.modeling.prediction_head import RegressionHead
[ 11748, 28034, 198, 6738, 5318, 13, 7890, 62, 30281, 13, 82, 12629, 1330, 27565, 198, 6738, 5318, 13, 4666, 10809, 13, 28764, 2867, 62, 2256, 1330, 3310, 2234, 13847, 628, 198 ]
3.774194
31
import pytest from rest_framework import status from rest_framework.test import APIClient def returns_status_code_http_200_ok(response): assert response.status_code == status.HTTP_200_OK def returns_status_code_http_401_unauthorized(response): assert response.status_code == status.HTTP_401_UNAUTHORIZED def returns_status_code_http_201_created(response): assert response.status_code == status.HTTP_201_CREATED def returns_status_code_http_204_no_content(response): assert response.status_code == status.HTTP_204_NO_CONTENT def returns_status_code_http_405_not_allowed(response): assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED def response_has_etag(response): assert response.get("ETag")
[ 11748, 12972, 9288, 198, 6738, 1334, 62, 30604, 1330, 3722, 198, 6738, 1334, 62, 30604, 13, 9288, 1330, 3486, 2149, 75, 1153, 628, 628, 628, 628, 628, 198, 198, 4299, 5860, 62, 13376, 62, 8189, 62, 4023, 62, 2167, 62, 482, 7, 26209,...
3.032258
248
from collections import defaultdict import discord from redbot.core import Config, checks, commands from redbot.core.bot import Red from redbot.core.utils.chat_formatting import box, humanize_list, inline from abc import ABC # ABC Mixins from dashboard.abc.abc import MixinMeta from dashboard.abc.mixin import DBMixin, dashboard # Command Mixins from dashboard.abc.roles import DashboardRolesMixin from dashboard.abc.webserver import DashboardWebserverMixin from dashboard.abc.settings import DashboardSettingsMixin # RPC Mixins from dashboard.baserpc import HUMANIZED_PERMISSIONS, DashboardRPC from dashboard.menus import ClientList, ClientMenu THEME_COLORS = ["red", "primary", "blue", "green", "greener", "yellow"] # Thanks to Flare for showing how to use group commands across multiple files. If this breaks, its his fault
[ 6738, 17268, 1330, 4277, 11600, 201, 198, 201, 198, 11748, 36446, 201, 198, 6738, 2266, 13645, 13, 7295, 1330, 17056, 11, 8794, 11, 9729, 201, 198, 6738, 2266, 13645, 13, 7295, 13, 13645, 1330, 2297, 201, 198, 6738, 2266, 13645, 13, 7...
3.265152
264
""" https://leetcode.com/problems/find-peak-element/submissions/ """ from typing import List
[ 37811, 198, 5450, 1378, 293, 316, 8189, 13, 785, 14, 1676, 22143, 14, 19796, 12, 36729, 12, 30854, 14, 7266, 8481, 14, 198, 37811, 198, 6738, 19720, 1330, 7343, 628 ]
3.133333
30
from torchvision.datasets import ImageFolder from torchvision import transforms import random import os import torch from torch.utils.data.dataloader import DataLoader from utils import constants, get_default_device from image_folder_with_path import ImageFolderWithPaths def to_device(data, device): """Move tensor(s) to chosen device""" if isinstance(data, (list, tuple)): return [to_device(x, device) for x in data] return data.to(device, non_blocking=True) default_device = get_default_device.default_device train_transforms = transforms.Compose([ transforms.RandomHorizontalFlip(p=0.5), transforms.RandomRotation(degrees=random.uniform(5, 10)), transforms.Resize((512, 512)), transforms.ToTensor(), ]) test_transforms = transforms.Compose([ transforms.Resize((512, 512)), transforms.ToTensor(), ]) classes = os.listdir(constants.DATA_PATH + constants.TRAIN_PATH) training_dataset = ImageFolder(constants.DATA_PATH + constants.TRAIN_PATH, transform=train_transforms) valid_dataset = ImageFolder(constants.DATA_PATH + constants.VAL_PATH, transform=test_transforms) # testing_dataset = ImageFolder(constants.DATA_PATH + constants.TEST_PATH, transform=test_transforms) # training_dataset = ImageFolderWithPaths(constants.DATA_PATH + constants.TRAIN_PATH, transform=train_transforms) # valid_dataset = ImageFolderWithPaths(constants.DATA_PATH + constants.VAL_PATH, transform=test_transforms) testing_dataset = ImageFolderWithPaths(constants.DATA_PATH + constants.TEST_PATH, transform=test_transforms) torch.manual_seed(constants.RANDOM_SEED) train_dl = DataLoader(training_dataset, constants.BATCH_SIZE, shuffle=True, num_workers=8, pin_memory=True) val_dl = DataLoader(valid_dataset, constants.BATCH_SIZE, num_workers=8, pin_memory=True) test_dl = DataLoader(testing_dataset, constants.BATCH_SIZE, num_workers=8, pin_memory=True) """ Now we can wrap our training and validation data loaders using DeviceDataLoader for automatically transferring batches of data to GPU (if available), and use to_device to move our model to GPU (if available) """ train_dl = DeviceDataLoader(train_dl, default_device) val_dl = DeviceDataLoader(val_dl, default_device) test_dl = DeviceDataLoader(test_dl, default_device)
[ 6738, 28034, 10178, 13, 19608, 292, 1039, 1330, 7412, 41092, 198, 6738, 28034, 10178, 1330, 31408, 198, 11748, 4738, 198, 11748, 28686, 198, 11748, 28034, 198, 6738, 28034, 13, 26791, 13, 7890, 13, 67, 10254, 1170, 263, 1330, 6060, 17401,...
3.110041
727
# import matplotlib # matplotlib.use('Qt5Agg') # Prevents `Invalid DISPLAY variable` errors import pytest import tempfile from calliope import Model from calliope.utils import AttrDict from calliope import analysis from . import common from .common import assert_almost_equal, solver, solver_io import matplotlib.pyplot as plt plt.switch_backend('agg') # Prevents `Invalid DISPLAY variable` errors
[ 2, 1330, 2603, 29487, 8019, 198, 2, 2603, 29487, 8019, 13, 1904, 10786, 48, 83, 20, 46384, 11537, 220, 1303, 43280, 658, 4600, 44651, 13954, 31519, 7885, 63, 8563, 198, 198, 11748, 12972, 9288, 198, 11748, 20218, 7753, 198, 198, 6738, ...
3.248
125
import os from mol.util import read_xyz dirname = os.path.dirname(os.path.abspath(__file__)) filename = os.path.join(dirname, 'look_and_say.dat') with open(filename, 'r') as handle: look_and_say = handle.read()
[ 11748, 28686, 198, 6738, 18605, 13, 22602, 1330, 1100, 62, 5431, 89, 198, 198, 15908, 3672, 796, 28686, 13, 6978, 13, 15908, 3672, 7, 418, 13, 6978, 13, 397, 2777, 776, 7, 834, 7753, 834, 4008, 198, 34345, 796, 28686, 13, 6978, 13, ...
2.578313
83
# 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 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import copy import json from unittest import mock from cinder import test from cinder.volume import configuration as conf from cinder.volume.targets import spdknvmf as spdknvmf_driver BDEVS = [{ "num_blocks": 4096000, "name": "Nvme0n1", "driver_specific": { "nvme": { "trid": { "trtype": "PCIe", "traddr": "0000:00:04.0" }, "ns_data": { "id": 1 }, "pci_address": "0000:00:04.0", "vs": { "nvme_version": "1.1" }, "ctrlr_data": { "firmware_revision": "1.0", "serial_number": "deadbeef", "oacs": { "ns_manage": 0, "security": 0, "firmware": 0, "format": 0 }, "vendor_id": "0x8086", "model_number": "QEMU NVMe Ctrl" }, "csts": { "rdy": 1, "cfs": 0 } } }, "supported_io_types": { "reset": True, "nvme_admin": True, "unmap": False, "read": True, "write_zeroes": False, "write": True, "flush": True, "nvme_io": True }, "claimed": False, "block_size": 512, "product_name": "NVMe disk", "aliases": ["Nvme0n1"] }, { "num_blocks": 8192, "uuid": "70efd305-4e66-49bd-99ff-faeda5c3052d", "aliases": [ "Nvme0n1p0" ], "driver_specific": { "lvol": { "base_bdev": "Nvme0n1", "lvol_store_uuid": "58b17014-d4a1-4f85-9761-093643ed18f1", "thin_provision": False } }, "supported_io_types": { "reset": True, "nvme_admin": False, "unmap": True, "read": True, "write_zeroes": True, "write": True, "flush": False, "nvme_io": False }, "claimed": False, "block_size": 4096, "product_name": "Split Disk", "name": "Nvme0n1p0" }, { "num_blocks": 8192, "uuid": "70efd305-4e66-49bd-99ff-faeda5c3052d", "aliases": [ "Nvme0n1p1" ], "driver_specific": { "lvol": { "base_bdev": "Nvme0n1", "lvol_store_uuid": "58b17014-d4a1-4f85-9761-093643ed18f1", "thin_provision": False } }, "supported_io_types": { "reset": True, "nvme_admin": False, "unmap": True, "read": True, "write_zeroes": True, "write": True, "flush": False, "nvme_io": False }, "claimed": False, "block_size": 4096, "product_name": "Split Disk", "name": "Nvme0n1p1" }, { "num_blocks": 8192, "uuid": "70efd305-4e66-49bd-99ff-faeda5c3052d", "aliases": [ "lvs_test/lvol0" ], "driver_specific": { "lvol": { "base_bdev": "Malloc0", "lvol_store_uuid": "58b17014-d4a1-4f85-9761-093643ed18f1", "thin_provision": False } }, "supported_io_types": { "reset": True, "nvme_admin": False, "unmap": True, "read": True, "write_zeroes": True, "write": True, "flush": False, "nvme_io": False }, "claimed": False, "block_size": 4096, "product_name": "Logical Volume", "name": "58b17014-d4a1-4f85-9761-093643ed18f1_4294967297" }, { "num_blocks": 8192, "uuid": "8dec1964-d533-41df-bea7-40520efdb416", "aliases": [ "lvs_test/lvol1" ], "driver_specific": { "lvol": { "base_bdev": "Malloc0", "lvol_store_uuid": "58b17014-d4a1-4f85-9761-093643ed18f1", "thin_provision": True } }, "supported_io_types": { "reset": True, "nvme_admin": False, "unmap": True, "read": True, "write_zeroes": True, "write": True, "flush": False, "nvme_io": False }, "claimed": False, "block_size": 4096, "product_name": "Logical Volume", "name": "58b17014-d4a1-4f85-9761-093643ed18f1_4294967298" }] NVMF_SUBSYSTEMS = [{ "listen_addresses": [], "subtype": "Discovery", "nqn": "nqn.2014-08.org.nvmexpress.discovery", "hosts": [], "allow_any_host": True }, { "listen_addresses": [], "subtype": "NVMe", "hosts": [{ "nqn": "nqn.2016-06.io.spdk:init" }], "namespaces": [{ "bdev_name": "Nvme0n1p0", "nsid": 1, "name": "Nvme0n1p0" }], "allow_any_host": False, "serial_number": "SPDK00000000000001", "nqn": "nqn.2016-06.io.spdk:cnode1" }, { "listen_addresses": [], "subtype": "NVMe", "hosts": [], "namespaces": [{ "bdev_name": "Nvme1n1p0", "nsid": 1, "name": "Nvme1n1p0" }], "allow_any_host": True, "serial_number": "SPDK00000000000002", "nqn": "nqn.2016-06.io.spdk:cnode2" }]
[ 2, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 220, 220, 220, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 921, 743, 7330, 198, 2, 220, 220, ...
1.791908
3,114
""" This is algos.euler.transformer module. This module is responsible for transforming raw candle data into training samples usable to the Euler algorithm. """ import datetime import decimal from algos.euler.models import training_samples as ts from core.models import instruments from datasource.models import candles TWO_PLACES = decimal.Decimal('0.01') def extract_features(day_candle): """ Extract the features for the learning algorithm from a daily candle. The Features are: high_bid, low_bid, close_bid, open_ask, high_ask, low_ask, and close_ask (all relative to open_bid) in pips. Args: day_candle: candles.Candle object representing a daily candle. Returns: features: List of Decimals. The features described above, all in two decimal places. """ multiplier = day_candle.instrument.multiplier features = [ day_candle.high_bid, day_candle.low_bid, day_candle.close_bid, day_candle.open_ask, day_candle.high_ask, day_candle.low_ask, day_candle.close_ask, ] features = [multiplier * (x - day_candle.open_bid) for x in features] features = [decimal.Decimal(x).quantize(TWO_PLACES) for x in features] return features def get_profitable_change(day_candle): """ Get the potential daily profitable price change in pips. If prices rise enough, we have: close_bid - open_ask (> 0), buy. If prices fall enough, we have: close_ask - open_bid (< 0), sell. if prices stay relatively still, we don't buy or sell. It's 0. Args: day_candle: candles.Candle object representing a daily candle. Returns: profitable_change: Decimal. The profitable rate change described above, in two decimal places. """ multiplier = day_candle.instrument.multiplier change = 0 if day_candle.close_bid > day_candle.open_ask: change = multiplier * (day_candle.close_bid - day_candle.open_ask) elif day_candle.close_ask < day_candle.open_bid: change = multiplier * (day_candle.close_ask - day_candle.open_bid) return decimal.Decimal(change).quantize(TWO_PLACES) def build_sample_row(candle_previous, candle_next): """ Build one training sample from two consecutive days of candles. Args: candle_previous: candles.Candle object. Candle of first day. candle_next: candles.Candle object. Candle of second day. Returns: sample: TrainingSample object. One training sample for learning. """ return ts.create_one( instrument=candle_next.instrument, date=candle_next.start_time.date() + datetime.timedelta(1), features=extract_features(candle_previous), target=get_profitable_change(candle_next)) def get_start_time(instrument): """ Get the start time for retrieving candles of the given instrument. This is determined by the last training sample in the database. Args: instrument: Instrument object. The given instrument. Returns: start_time: Datetime object. The datetime from which to query candles from to fill the rest of the training samples. """ last_sample = ts.get_last(instrument) if last_sample is not None: start_date = last_sample.date - datetime.timedelta(1) return datetime.datetime.combine(start_date, datetime.time()) return datetime.datetime(2005, 1, 1) def run(): """ Update the training samples in the database from the latest candles. This should be run daily to ensure the training set is up-to-date. Args: None. """ all_new_samples = [] for instrument in instruments.get_all(): start_time = get_start_time(instrument) new_candles = candles.get_candles( instrument=instrument, start=start_time, order_by='start_time') for i in range(len(new_candles) - 1): all_new_samples.append( build_sample_row(new_candles[i], new_candles[i + 1])) ts.insert_many(all_new_samples)
[ 37811, 770, 318, 435, 70, 418, 13, 68, 18173, 13, 7645, 16354, 8265, 13, 198, 220, 220, 220, 770, 8265, 318, 4497, 329, 25449, 8246, 26839, 1366, 656, 3047, 198, 220, 220, 220, 8405, 24284, 284, 262, 412, 18173, 11862, 13, 198, 3781...
2.529483
1,662
from diagrams import Node
[ 6738, 37067, 1330, 19081, 628 ]
5.4
5
__doc__ = \ """ ======================================================================================= Main-driver :obj:`LogStream` variables (:mod:`mango.application.main_driver.logstream`) ======================================================================================= .. currentmodule:: mango.application.main_driver.logstream Logging objects/attributes for :obj:`mango.application.main_driver.MainDriverFilter` filters. Classes ======= .. autosummary:: :toctree: generated/ LogStream - Message logging for :obj:`mango.application.main_driver.MainDriverFilter` filters. Attributes ========== .. autodata:: log .. autodata:: mstLog .. autodata:: mstOut .. autodata:: warnLog .. autodata:: errLog """ import mango import mango.mpi as mpi import os import os.path import sys if sys.platform.startswith('linux'): import DLFCN as dl _flags = sys.getdlopenflags() sys.setdlopenflags(dl.RTLD_NOW|dl.RTLD_GLOBAL) from . import _mango_main_driver as _mango_main_driver_so sys.setdlopenflags(_flags) else: from . import _mango_main_driver as _mango_main_driver_so from mango.core import LogStream #: Messages sent to stdout, prefixed with :samp:`'P<RANK>'`, where :samp:`<RANK>` is MPI process world rank. log = _mango_main_driver_so._log #: Messages sent to stdout, prefixed with :samp:`'MST'`, and messages also saved to history-meta-data. mstLog = _mango_main_driver_so._mstLog #: Messages sent to stdout, prefixed with :samp:`'OUT'`. mstOut = _mango_main_driver_so._mstOut #: Messages sent to stderr, prefixed with :samp:`'WARNING'`. warnLog = _mango_main_driver_so._warnLog #: Messages sent to stderr, prefixed with :samp:`'ERROR'`. errLog = _mango_main_driver_so._errLog __all__ = [s for s in dir() if not s.startswith('_')]
[ 834, 15390, 834, 796, 3467, 198, 37811, 198, 23926, 4770, 1421, 18604, 198, 13383, 12, 26230, 1058, 26801, 25, 63, 11187, 12124, 63, 9633, 357, 25, 4666, 25, 63, 76, 14208, 13, 31438, 13, 12417, 62, 26230, 13, 6404, 5532, 63, 8, 198...
2.882637
622
# -*- coding: utf-8-unix -*- import platform ###################################################################### # Platform specific headers ###################################################################### if platform.system() == 'Linux': src = """ typedef bool BOOL; """ ###################################################################### # Common headers ###################################################################### src += """ #define CY_STRING_DESCRIPTOR_SIZE 256 #define CY_MAX_DEVICE_INTERFACE 5 #define CY_US_VERSION_MAJOR 1 #define CY_US_VERSION_MINOR 0 #define CY_US_VERSION_PATCH 0 #define CY_US_VERSION 1 #define CY_US_VERSION_BUILD 74 typedef unsigned int UINT32; typedef unsigned char UINT8; typedef unsigned short UINT16; typedef char CHAR; typedef unsigned char UCHAR; typedef void* CY_HANDLE; typedef void (*CY_EVENT_NOTIFICATION_CB_FN)(UINT16 eventsNotified); typedef struct _CY_VID_PID { UINT16 vid; UINT16 pid; } CY_VID_PID, *PCY_VID_PID; typedef struct _CY_LIBRARY_VERSION { UINT8 majorVersion; UINT8 minorVersion; UINT16 patch; UINT8 buildNumber; } CY_LIBRARY_VERSION, *PCY_LIBRARY_VERSION; typedef struct _CY_FIRMWARE_VERSION { UINT8 majorVersion; UINT8 minorVersion; UINT16 patchNumber; UINT32 buildNumber; } CY_FIRMWARE_VERSION, *PCY_FIRMWARE_VERSION; typedef enum _CY_DEVICE_CLASS{ CY_CLASS_DISABLED = 0, CY_CLASS_CDC = 0x02, CY_CLASS_PHDC = 0x0F, CY_CLASS_VENDOR = 0xFF } CY_DEVICE_CLASS; typedef enum _CY_DEVICE_TYPE { CY_TYPE_DISABLED = 0, CY_TYPE_UART, CY_TYPE_SPI, CY_TYPE_I2C, CY_TYPE_JTAG, CY_TYPE_MFG } CY_DEVICE_TYPE; typedef enum _CY_DEVICE_SERIAL_BLOCK { SerialBlock_SCB0 = 0, SerialBlock_SCB1, SerialBlock_MFG } CY_DEVICE_SERIAL_BLOCK; typedef struct _CY_DEVICE_INFO { CY_VID_PID vidPid; UCHAR numInterfaces; UCHAR manufacturerName [256]; UCHAR productName [256]; UCHAR serialNum [256]; UCHAR deviceFriendlyName [256]; CY_DEVICE_TYPE deviceType [5]; CY_DEVICE_CLASS deviceClass [5]; CY_DEVICE_SERIAL_BLOCK deviceBlock; } CY_DEVICE_INFO,*PCY_DEVICE_INFO; typedef struct _CY_DATA_BUFFER { UCHAR *buffer; UINT32 length; UINT32 transferCount; } CY_DATA_BUFFER,*PCY_DATA_BUFFER; typedef enum _CY_RETURN_STATUS{ CY_SUCCESS = 0, CY_ERROR_ACCESS_DENIED, CY_ERROR_DRIVER_INIT_FAILED, CY_ERROR_DEVICE_INFO_FETCH_FAILED, CY_ERROR_DRIVER_OPEN_FAILED, CY_ERROR_INVALID_PARAMETER, CY_ERROR_REQUEST_FAILED, CY_ERROR_DOWNLOAD_FAILED, CY_ERROR_FIRMWARE_INVALID_SIGNATURE, CY_ERROR_INVALID_FIRMWARE, CY_ERROR_DEVICE_NOT_FOUND, CY_ERROR_IO_TIMEOUT, CY_ERROR_PIPE_HALTED, CY_ERROR_BUFFER_OVERFLOW, CY_ERROR_INVALID_HANDLE, CY_ERROR_ALLOCATION_FAILED, CY_ERROR_I2C_DEVICE_BUSY, CY_ERROR_I2C_NAK_ERROR, CY_ERROR_I2C_ARBITRATION_ERROR, CY_ERROR_I2C_BUS_ERROR, CY_ERROR_I2C_BUS_BUSY, CY_ERROR_I2C_STOP_BIT_SET, CY_ERROR_STATUS_MONITOR_EXIST } CY_RETURN_STATUS; typedef struct _CY_I2C_CONFIG{ UINT32 frequency; UINT8 slaveAddress; BOOL isMaster; BOOL isClockStretch; } CY_I2C_CONFIG,*PCY_I2C_CONFIG; typedef struct _CY_I2C_DATA_CONFIG { UCHAR slaveAddress; BOOL isStopBit; BOOL isNakBit; } CY_I2C_DATA_CONFIG, *PCY_I2C_DATA_CONFIG; typedef enum _CY_SPI_PROTOCOL { CY_SPI_MOTOROLA = 0, CY_SPI_TI, CY_SPI_NS } CY_SPI_PROTOCOL; typedef struct _CY_SPI_CONFIG { UINT32 frequency; UCHAR dataWidth; CY_SPI_PROTOCOL protocol ; BOOL isMsbFirst; BOOL isMaster; BOOL isContinuousMode; BOOL isSelectPrecede; BOOL isCpha; BOOL isCpol; }CY_SPI_CONFIG,*PCY_SPI_CONFIG; typedef enum _CY_UART_BAUD_RATE { CY_UART_BAUD_300 = 300, CY_UART_BAUD_600 = 600, CY_UART_BAUD_1200 = 1200, CY_UART_BAUD_2400 = 2400, CY_UART_BAUD_4800 = 4800, CY_UART_BAUD_9600 = 9600, CY_UART_BAUD_14400 = 14400, CY_UART_BAUD_19200 = 19200, CY_UART_BAUD_38400 = 38400, CY_UART_BAUD_56000 = 56000, CY_UART_BAUD_57600 = 57600, CY_UART_BAUD_115200 = 115200, CY_UART_BAUD_230400 = 230400, CY_UART_BAUD_460800 = 460800, CY_UART_BAUD_921600 = 921600, CY_UART_BAUD_1000000 = 1000000, CY_UART_BAUD_3000000 = 3000000, }CY_UART_BAUD_RATE; typedef enum _CY_UART_PARITY_MODE { CY_DATA_PARITY_DISABLE = 0, CY_DATA_PARITY_ODD, CY_DATA_PARITY_EVEN, CY_DATA_PARITY_MARK, CY_DATA_PARITY_SPACE } CY_UART_PARITY_MODE; typedef enum _CY_UART_STOP_BIT { CY_UART_ONE_STOP_BIT = 1, CY_UART_TWO_STOP_BIT } CY_UART_STOP_BIT; typedef enum _CY_FLOW_CONTROL_MODES { CY_UART_FLOW_CONTROL_DISABLE = 0, CY_UART_FLOW_CONTROL_DSR, CY_UART_FLOW_CONTROL_RTS_CTS, CY_UART_FLOW_CONTROL_ALL } CY_FLOW_CONTROL_MODES; typedef struct _CY_UART_CONFIG { CY_UART_BAUD_RATE baudRate; UINT8 dataWidth; CY_UART_STOP_BIT stopBits; CY_UART_PARITY_MODE parityMode; BOOL isDropOnRxErrors; } CY_UART_CONFIG,*PCY_UART_CONFIG; typedef enum _CY_CALLBACK_EVENTS { CY_UART_CTS_BIT = 0x01, CY_UART_DSR_BIT = 0x02, CY_UART_BREAK_BIT = 0x04, CY_UART_RING_SIGNAL_BIT = 0x08, CY_UART_FRAME_ERROR_BIT = 0x10, CY_UART_PARITY_ERROR_BIT = 0x20, CY_UART_DATA_OVERRUN_BIT = 0x40, CY_UART_DCD_BIT = 0x100, CY_SPI_TX_UNDERFLOW_BIT = 0x200, CY_SPI_BUS_ERROR_BIT = 0x400, CY_ERROR_EVENT_FAILED_BIT = 0x800 } CY_CALLBACK_EVENTS; CY_RETURN_STATUS CyLibraryInit (); CY_RETURN_STATUS CyLibraryExit (); CY_RETURN_STATUS CyGetListofDevices ( UINT8* numDevices ); CY_RETURN_STATUS CyGetDeviceInfo( UINT8 deviceNumber, CY_DEVICE_INFO *deviceInfo ); CY_RETURN_STATUS CyGetDeviceInfoVidPid ( CY_VID_PID vidPid, UINT8 *deviceIdList, CY_DEVICE_INFO *deviceInfoList, UINT8 *deviceCount, UINT8 infoListLength ); CY_RETURN_STATUS CyOpen ( UINT8 deviceNumber, UINT8 interfaceNum, CY_HANDLE *handle ); CY_RETURN_STATUS CyClose ( CY_HANDLE handle ); CY_RETURN_STATUS CyCyclePort ( CY_HANDLE handle ); CY_RETURN_STATUS CySetGpioValue ( CY_HANDLE handle, UINT8 gpioNumber, UINT8 value ); CY_RETURN_STATUS CyGetGpioValue ( CY_HANDLE handle, UINT8 gpioNumber, UINT8 *value ); CY_RETURN_STATUS CySetEventNotification( CY_HANDLE handle, CY_EVENT_NOTIFICATION_CB_FN notificationCbFn ); CY_RETURN_STATUS CyAbortEventNotification( CY_HANDLE handle ); CY_RETURN_STATUS CyGetLibraryVersion ( CY_HANDLE handle, PCY_LIBRARY_VERSION version ); CY_RETURN_STATUS CyGetFirmwareVersion ( CY_HANDLE handle, PCY_FIRMWARE_VERSION firmwareVersion ); CY_RETURN_STATUS CyResetDevice ( CY_HANDLE handle ); CY_RETURN_STATUS CyProgUserFlash ( CY_HANDLE handle, CY_DATA_BUFFER *progBuffer, UINT32 flashAddress, UINT32 timeout ); CY_RETURN_STATUS CyReadUserFlash ( CY_HANDLE handle, CY_DATA_BUFFER *readBuffer, UINT32 flashAddress, UINT32 timeout ); CY_RETURN_STATUS CyGetSignature ( CY_HANDLE handle, UCHAR *pSignature ); CY_RETURN_STATUS CyGetUartConfig ( CY_HANDLE handle, CY_UART_CONFIG *uartConfig ); CY_RETURN_STATUS CySetUartConfig ( CY_HANDLE handle, CY_UART_CONFIG *uartConfig ); CY_RETURN_STATUS CyUartRead ( CY_HANDLE handle, CY_DATA_BUFFER* readBuffer, UINT32 timeout ); CY_RETURN_STATUS CyUartWrite ( CY_HANDLE handle, CY_DATA_BUFFER* writeBuffer, UINT32 timeout ); CY_RETURN_STATUS CyUartSetHwFlowControl( CY_HANDLE handle, CY_FLOW_CONTROL_MODES mode ); CY_RETURN_STATUS CyUartGetHwFlowControl( CY_HANDLE handle, CY_FLOW_CONTROL_MODES *mode ); CY_RETURN_STATUS CyUartSetRts( CY_HANDLE handle ); CY_RETURN_STATUS CyUartClearRts( CY_HANDLE handle ); CY_RETURN_STATUS CyUartSetDtr( CY_HANDLE handle ); CY_RETURN_STATUS CyUartClearDtr( CY_HANDLE handle ); CY_RETURN_STATUS CyUartSetBreak( CY_HANDLE handle, UINT16 timeout ); CY_RETURN_STATUS CyGetI2cConfig ( CY_HANDLE handle, CY_I2C_CONFIG *i2cConfig ); CY_RETURN_STATUS CySetI2cConfig ( CY_HANDLE handle, CY_I2C_CONFIG *i2cConfig ); CY_RETURN_STATUS CyI2cRead ( CY_HANDLE handle, CY_I2C_DATA_CONFIG *dataConfig, CY_DATA_BUFFER *readBuffer, UINT32 timeout ); CY_RETURN_STATUS CyI2cWrite ( CY_HANDLE handle, CY_I2C_DATA_CONFIG *dataConfig, CY_DATA_BUFFER *writeBuffer, UINT32 timeout ); CY_RETURN_STATUS CyI2cReset( CY_HANDLE handle, BOOL resetMode ); CY_RETURN_STATUS CyGetSpiConfig ( CY_HANDLE handle, CY_SPI_CONFIG *spiConfig ); CY_RETURN_STATUS CySetSpiConfig ( CY_HANDLE handle, CY_SPI_CONFIG *spiConfig ); CY_RETURN_STATUS CySpiReadWrite ( CY_HANDLE handle, CY_DATA_BUFFER* readBuffer, CY_DATA_BUFFER* writeBuffer, UINT32 timeout ); CY_RETURN_STATUS CyJtagEnable ( CY_HANDLE handle ); CY_RETURN_STATUS CyJtagDisable ( CY_HANDLE handle ); CY_RETURN_STATUS CyJtagWrite ( CY_HANDLE handle, CY_DATA_BUFFER *writeBuffer, UINT32 timeout ); CY_RETURN_STATUS CyJtagRead ( CY_HANDLE handle, CY_DATA_BUFFER *readBuffer, UINT32 timeout ); CY_RETURN_STATUS CyPhdcClrFeature ( CY_HANDLE handle ); CY_RETURN_STATUS CyPhdcSetFeature ( CY_HANDLE handle ); CY_RETURN_STATUS CyPhdcGetStatus ( CY_HANDLE handle, UINT16 *dataStatus ); """
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 12, 403, 844, 532, 9, 12, 198, 198, 11748, 3859, 198, 198, 29113, 29113, 4242, 2235, 198, 2, 19193, 2176, 24697, 198, 29113, 29113, 4242, 2235, 198, 198, 361, 3859, 13, 10057, 3419, 6624...
2.083961
4,645
from overrides import overrides from ..masked_layer import MaskedLayer
[ 6738, 23170, 1460, 1330, 23170, 1460, 198, 198, 6738, 11485, 27932, 276, 62, 29289, 1330, 18007, 276, 49925, 628 ]
3.842105
19
""" energy.py function that computes the inter particle energy It uses truncated 12-6 Lennard Jones potential All the variables are in reduced units. """ def distance(atom1, atom2): """ Computes the square of inter particle distance Minimum image convention is applied for distance calculation for periodic boundary conditions """ dx = atom1.x - atom2.x dy = atom1.y - atom2.y dz = atom1.z - atom2.z if dx > halfLx dx -= Lx elif dx < -halfLx: dx += Lx if dy > halfLy: dy -= Ly elif dy < -halfLy: dy += Ly if dz > halfLz: dz -= Lz elif dz < -halfLz: dz += Lz return dx**2 + dy**2 + dz**2 def energy(atom1, atom2, rc): ''' calculates the energy of the system ''' ## Arithmatic mixing rules - Lorentz Berthlot mixing eps = (atom1.eps + atom2.eps)/2 sig = (atom1.sigma * atom2.sigma)**0.5 rcsq = rc**2 rsq = distance(atom1, atom2) if rsq <= rcsq: energy = 4.0*eps*( (sig/rsq)**6.0 - (sig/rsq)**3.0) else: energy = 0.0 def writeEnergy(step, energy): ''' Writes the energy to a file. ''' with open('energy.dat', 'a') as f: f.write('{0} {1}\n'.format(step, energy))
[ 37811, 198, 22554, 13, 9078, 198, 198, 8818, 326, 552, 1769, 262, 987, 18758, 2568, 198, 1026, 3544, 40122, 515, 1105, 12, 21, 28423, 446, 5437, 2785, 198, 3237, 262, 9633, 389, 287, 5322, 4991, 13, 198, 198, 37811, 198, 198, 4299, ...
2.098884
627
import numpy as np import math from scipy.optimize import curve_fit
[ 11748, 299, 32152, 355, 45941, 198, 11748, 10688, 198, 6738, 629, 541, 88, 13, 40085, 1096, 1330, 12133, 62, 11147, 628, 628 ]
3.227273
22
#!/usr/bin/env python3 # -*- coding:utf-8 -*- ############################################################# # File: network_models_LSTU.py # Created Date: Tuesday February 25th 2020 # Author: Chen Xuanhong # Email: chenxuanhongzju@outlook.com # Last Modified: Tuesday, 25th February 2020 9:57:06 pm # Modified By: Chen Xuanhong # Copyright (c) 2020 Shanghai Jiao Tong University ############################################################# from __future__ import absolute_import from __future__ import division from __future__ import print_function from functools import partial import tensorflow as tf import tensorflow.contrib.slim as slim import tflib as tl conv = partial(slim.conv2d, activation_fn=None) dconv = partial(slim.conv2d_transpose, activation_fn=None) fc = partial(tl.flatten_fully_connected, activation_fn=None) relu = tf.nn.relu lrelu = tf.nn.leaky_relu sigmoid = tf.nn.sigmoid tanh = tf.nn.tanh batch_norm = partial(slim.batch_norm, scale=True, updates_collections=None) instance_norm = slim.instance_norm MAX_DIM = 64 * 16
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 40477, 12, 23, 532, 9, 12, 198, 29113, 14468, 7804, 4242, 2, 198, 2, 9220, 25, 3127, 62, 27530, 62, 43, 2257, 52, 13, 9078, 198, 2, 15622, 7536, 2...
3.121302
338
from unittest import TestCase from expects import expect, equal, raise_error from slender import List
[ 198, 6738, 555, 715, 395, 1330, 6208, 20448, 198, 6738, 13423, 1330, 1607, 11, 4961, 11, 5298, 62, 18224, 220, 198, 198, 6738, 36808, 1330, 7343, 628, 628 ]
3.857143
28
#!/usr/bin/env python3 # Copyright (c) 2020 The Bitcoin Cash Node developers # Author matricz # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """ Test that inv messages are sent according to an exponential distribution with scale -txbroadcastinterval The outbound interval should be half of the inbound """ import time from test_framework.mininode import P2PInterface, mininode_lock from test_framework.test_framework import BitcoinTestFramework from test_framework.util import wait_until, connect_nodes, disconnect_nodes from scipy import stats if __name__ == '__main__': TxBroadcastIntervalTest().main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 15069, 357, 66, 8, 12131, 383, 6185, 16210, 19081, 6505, 198, 2, 6434, 2603, 1173, 89, 198, 2, 4307, 6169, 739, 262, 17168, 3788, 5964, 11, 766, 262, 19249, 198, 2, 2393, 27...
3.610256
195
import backend as F import numpy as np import scipy as sp import dgl from dgl import utils import unittest from numpy.testing import assert_array_equal np.random.seed(42) if __name__ == '__main__': test_create_full() test_1neighbor_sampler_all() test_10neighbor_sampler_all() test_1neighbor_sampler() test_10neighbor_sampler() test_layer_sampler() test_nonuniform_neighbor_sampler() test_setseed() test_negative_sampler()
[ 11748, 30203, 355, 376, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 629, 541, 88, 355, 599, 198, 11748, 288, 4743, 198, 6738, 288, 4743, 1330, 3384, 4487, 198, 11748, 555, 715, 395, 198, 6738, 299, 32152, 13, 33407, 1330, 6818, 62...
2.475936
187
# Copyright Amazon.com, Inc. or its affiliates. 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 agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import os from typing import TYPE_CHECKING, Any, Dict, Optional import aws_orbit from aws_orbit.plugins import hooks from aws_orbit.remote_files import helm if TYPE_CHECKING: from aws_orbit.models.context import Context, TeamContext _logger: logging.Logger = logging.getLogger("aws_orbit") CHART_PATH = os.path.join(os.path.dirname(__file__))
[ 2, 220, 15069, 6186, 13, 785, 11, 3457, 13, 393, 663, 29116, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 11074, 198, 2, 220, 220, 220, 9...
3.279221
308
#! /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 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Generate list of cinder drivers""" import argparse import os from cinder.interface import util parser = argparse.ArgumentParser(prog="generate_driver_list") parser.add_argument("--format", default='str', choices=['str', 'dict'], help="Output format type") # Keep backwards compatibilty with the gate-docs test # The tests pass ['docs'] on the cmdln, but it's never been used. parser.add_argument("output_list", default=None, nargs='?') CI_WIKI_ROOT = "https://wiki.openstack.org/wiki/ThirdPartySystems/" def collect_driver_info(driver): """Build the dictionary that describes this driver.""" info = {'name': driver.class_name, 'version': driver.version, 'fqn': driver.class_fqn, 'description': driver.desc, 'ci_wiki_name': driver.ci_wiki_name} return info if __name__ == '__main__': main()
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 198, 2, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 220, 220, 220, 407, 779, 428, 2393, 2845, 287, ...
2.876686
519
import sys f = open("/home/vader/Desktop/test.py", "r") #read all file python_script = f.read() print(python_script)
[ 11748, 25064, 198, 69, 796, 1280, 7203, 14, 11195, 14, 85, 5067, 14, 36881, 14, 9288, 13, 9078, 1600, 366, 81, 4943, 198, 1303, 961, 477, 2393, 198, 29412, 62, 12048, 796, 220, 277, 13, 961, 3419, 220, 220, 220, 220, 220, 198, 479...
2.470588
51
import smtplib import argparse from os.path import basename from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.utils import COMMASPACE, formatdate import configparser import json parser = argparse.ArgumentParser() parser.add_argument('attachment') args = parser.parse_args() attachpath = args.attachment config = configparser.ConfigParser() config.read('email_file.ini') email_from = config['DEFAULT']['From'] email_to_list = json.loads(config['DEFAULT']['To']) email_subject = config['DEFAULT']['Subject'] email_body = config['DEFAULT']['Body'] email_server = config['DEFAULT']['Server'] email_server_ssl = bool(config['DEFAULT']['Server_SSL']) email_server_username = config['DEFAULT']['Server_Username'] email_server_password = config['DEFAULT']['Server_Password'] send_mail(email_from, email_to_list, email_subject, email_body, [attachpath], email_server, email_server_ssl, email_server_username, email_server_password)
[ 11748, 895, 83, 489, 571, 198, 11748, 1822, 29572, 198, 6738, 28686, 13, 6978, 1330, 1615, 12453, 198, 6738, 3053, 13, 76, 524, 13, 31438, 1330, 337, 12789, 23416, 198, 6738, 3053, 13, 76, 524, 13, 16680, 541, 433, 1330, 337, 3955, ...
3.154321
324
import logging TRACE_LVL = int( (logging.DEBUG + logging.INFO) / 2 )
[ 11748, 18931, 198, 198, 5446, 11598, 62, 30976, 43, 796, 493, 7, 357, 6404, 2667, 13, 30531, 1343, 18931, 13, 10778, 8, 1220, 362, 1267, 198 ]
2.692308
26
from dagster import repository from simple_lakehouse.pipelines import simple_lakehouse_pipeline
[ 6738, 48924, 1706, 1330, 16099, 198, 6738, 2829, 62, 27180, 4803, 13, 79, 541, 20655, 1330, 2829, 62, 27180, 4803, 62, 79, 541, 4470, 628 ]
3.88
25
#Copyright ReportLab Europe Ltd. 2000-2017 #see license.txt for license details __version__='3.3.0' __doc__='' #REPORTLAB_TEST_SCRIPT import sys, copy, os from reportlab.platypus import * _NEW_PARA=os.environ.get('NEW_PARA','0')[0] in ('y','Y','1') _REDCAP=int(os.environ.get('REDCAP','0')) _CALLBACK=os.environ.get('CALLBACK','0')[0] in ('y','Y','1') if _NEW_PARA: from reportlab.lib.units import inch from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.enums import TA_LEFT, TA_RIGHT, TA_CENTER, TA_JUSTIFY import reportlab.rl_config reportlab.rl_config.invariant = 1 styles = getSampleStyleSheet() Title = "The Odyssey" Author = "Homer" Elements = [] ChapterStyle = copy.deepcopy(styles["Heading1"]) ChapterStyle.alignment = TA_CENTER ChapterStyle.fontsize = 14 InitialStyle = copy.deepcopy(ChapterStyle) InitialStyle.fontsize = 16 InitialStyle.leading = 20 PreStyle = styles["Code"] chNum = 0 ParaStyle = copy.deepcopy(styles["Normal"]) ParaStyle.spaceBefore = 0.1*inch if 'right' in sys.argv: ParaStyle.alignment = TA_RIGHT elif 'left' in sys.argv: ParaStyle.alignment = TA_LEFT elif 'justify' in sys.argv: ParaStyle.alignment = TA_JUSTIFY elif 'center' in sys.argv or 'centre' in sys.argv: ParaStyle.alignment = TA_CENTER else: ParaStyle.alignment = TA_JUSTIFY useTwoCol = 'notwocol' not in sys.argv firstPre = 1 if __name__=='__main__': if '--prof' in sys.argv: doProf('dodyssey.prof',run) else: run()
[ 2, 15269, 6358, 17822, 2031, 12052, 13, 4751, 12, 5539, 198, 2, 3826, 5964, 13, 14116, 329, 5964, 3307, 198, 834, 9641, 834, 11639, 18, 13, 18, 13, 15, 6, 198, 834, 15390, 834, 28, 7061, 198, 198, 2, 2200, 15490, 48780, 62, 51, ...
2.5
594
""" econ/fred_view.py tests """ import unittest from unittest import mock from io import StringIO import pandas as pd # pylint: disable=unused-import from gamestonk_terminal.econ.fred_view import get_fred_data # noqa: F401 fred_data_mock = """ ,GDP 2019-01-01,21115.309 2019-04-01,21329.877 2019-07-01,21540.325 2019-10-01,21747.394 2020-01-01,21561.139 2020-04-01,19520.114 2020-07-01,21170.252 2020-10-01,21494.731 """
[ 37811, 304, 1102, 14, 39193, 62, 1177, 13, 9078, 5254, 37227, 198, 11748, 555, 715, 395, 198, 6738, 555, 715, 395, 1330, 15290, 198, 6738, 33245, 1330, 10903, 9399, 198, 11748, 19798, 292, 355, 279, 67, 198, 198, 2, 279, 2645, 600, ...
2.322404
183
# Copyright (c) 2009-2010 Denis Bilenko. See LICENSE for details. """Managing greenlets in a group. The :class:`Group` class in this module abstracts a group of running greenlets. When a greenlet dies, it's automatically removed from the group. The :class:`Pool` which a subclass of :class:`Group` provides a way to limit concurrency: its :meth:`spawn <Pool.spawn>` method blocks if the number of greenlets in the pool has already reached the limit, until there is a free slot. """ from gevent.hub import GreenletExit, getcurrent from gevent.greenlet import joinall, Greenlet from gevent.timeout import Timeout from gevent.event import Event from gevent.coros import Semaphore, DummySemaphore __all__ = ['Group', 'Pool'] def GreenletSet(*args, **kwargs): import warnings warnings.warn("gevent.pool.GreenletSet was renamed to gevent.pool.Group since version 0.13.0", DeprecationWarning, stacklevel=2) return Group(*args, **kwargs)
[ 2, 15069, 357, 66, 8, 3717, 12, 10333, 33089, 24207, 32720, 13, 4091, 38559, 24290, 329, 3307, 13, 198, 37811, 5124, 3039, 4077, 5289, 287, 257, 1448, 13, 198, 198, 464, 1058, 4871, 25, 63, 13247, 63, 1398, 287, 428, 8265, 12531, 82...
3.355634
284
import time import logging from typing import Dict, Any, Tuple import pickle import numpy as np import xgboost as xgb from .common import load_lw_dataset, encode_query, decode_label from ..postgres import Postgres from ..estimator import Estimator from ..utils import evaluate, run_test from ...dataset.dataset import load_table from ...workload.workload import Query from ...constants import MODEL_ROOT, NUM_THREADS, PKL_PROTO L = logging.getLogger(__name__) def test_lw_tree(dataset: str, version: str, workload: str, params: Dict[str, Any], overwrite: bool) -> None: """ params: model: model file name use_cache: load processed vectors directly instead of build from queries """ # uniform thread number model_file = MODEL_ROOT / dataset / f"{params['model']}.pkl" L.info(f"Load model from {model_file} ...") with open(model_file, 'rb') as f: state = pickle.load(f) # load corresonding version of table table = load_table(dataset, state['version']) # load model args = state['args'] model = state['model'] pg_est = Postgres(table, args.bins, state['seed']) estimator = LWTree(model, params['model'], pg_est, table) L.info(f"Load and built lw(tree) estimator: {estimator}") if params['use_cache']: # test table might has different version with train test_table = load_table(dataset, version) lw_dataset = load_lw_dataset(test_table, workload, state['seed'], args.bins) X, _, gt = lw_dataset['test'] run_test(dataset, version, workload, estimator, overwrite, lw_vec=(X, gt)) else: run_test(dataset, version, workload, estimator, overwrite)
[ 11748, 640, 198, 11748, 18931, 198, 6738, 19720, 1330, 360, 713, 11, 4377, 11, 309, 29291, 198, 11748, 2298, 293, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2124, 70, 39521, 355, 2124, 22296, 198, 198, 6738, 764, 11321, 1330, ...
2.644757
639
import os import configparser from warnings import warn def write_info_to_file(file_handle, separator, *args, **kw_args): """ Write arguments or keyword arguments to a file. Values will be separated by a given separator. """ output_lines = [] if len(args) > 0: output_lines.append(separator.join(args)) if len(kw_args) > 0: for k, v in kw_args.items(): output_lines.append(f'{k}{separator}{v}') print('\n'.join(output_lines), file=file_handle)
[ 198, 11748, 28686, 198, 11748, 4566, 48610, 198, 6738, 14601, 1330, 9828, 198, 198, 4299, 3551, 62, 10951, 62, 1462, 62, 7753, 7, 7753, 62, 28144, 11, 2880, 1352, 11, 1635, 22046, 11, 12429, 46265, 62, 22046, 2599, 198, 220, 220, 220,...
2.535
200
# This file is part of the pyMOR project (http://www.pymor.org). # Copyright 2013-2017 pyMOR developers and contributors. All rights reserved. # License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) import numpy as np import pytest from pymor.core.pickle import dumps, loads from pymor.functions.basic import ConstantFunction, GenericFunction from pymortests.fixtures.function import function, picklable_function, function_argument from pymortests.fixtures.parameter import parameters_of_type from pymortests.pickling import assert_picklable, assert_picklable_without_dumps_function # monkey np.testing.assert_allclose to behave the same as np.allclose # for some reason, the default atol of np.testing.assert_allclose is 0 # while it is 1e-8 for np.allclose real_assert_allclose = np.testing.assert_allclose np.testing.assert_allclose = monkey_allclose
[ 2, 770, 2393, 318, 636, 286, 262, 12972, 44, 1581, 1628, 357, 4023, 1378, 2503, 13, 9078, 4491, 13, 2398, 737, 198, 2, 15069, 2211, 12, 5539, 12972, 44, 1581, 6505, 290, 20420, 13, 1439, 2489, 10395, 13, 198, 2, 13789, 25, 347, 10...
3.322097
267
''' step 1 get the userID and their locations put them all into a database ''' from bs4 import BeautifulSoup import urllib import sqlite3 from selenium import webdriver import time import re from urllib import request import random import pickle import os import pytesseract url_dog = "https://www.douban.com/group/lovelydog/members?start=" url_cat = "https://www.douban.com/group/cat/members?start=" ''' cat = 1 ~ 336770 dog = 1 ~ 156240 ''' # info_dog = getInfo("dog") # info_dog.crawler() info_cat = getInfo("cat") info_cat.crawler() ''' create table CatPeople as select distinct * from CatPeople_backup WHERE not location GLOB '*[A-Za-z]*'; pre-processing to delete locations out of China '''
[ 201, 198, 7061, 6, 201, 198, 9662, 352, 201, 198, 1136, 262, 2836, 2389, 290, 511, 7064, 201, 198, 1996, 606, 477, 656, 257, 6831, 201, 198, 7061, 6, 201, 198, 201, 198, 6738, 275, 82, 19, 1330, 23762, 50, 10486, 201, 198, 11748, ...
2.407407
324
from .structure import Structure
[ 6738, 764, 301, 5620, 1330, 32522, 198 ]
4.714286
7
import unittest import numpy as np from tbase.common.cmd_util import set_global_seeds from tbase.network.polices import RandomPolicy if __name__ == '__main__': unittest.main()
[ 11748, 555, 715, 395, 198, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 256, 8692, 13, 11321, 13, 28758, 62, 22602, 1330, 900, 62, 20541, 62, 325, 5379, 198, 6738, 256, 8692, 13, 27349, 13, 16104, 1063, 1330, 14534, 36727, 628,...
2.846154
65
# Copyright 2012 OpenStack Foundation # # 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 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import atexit import base64 import contextlib import datetime import functools import hashlib import json import ldap import os import shutil import socket import sys import uuid import warnings import fixtures import flask from flask import testing as flask_testing import http.client from oslo_config import fixture as config_fixture from oslo_context import context as oslo_context from oslo_context import fixture as oslo_ctx_fixture from oslo_log import fixture as log_fixture from oslo_log import log from oslo_utils import timeutils from sqlalchemy import exc import testtools from testtools import testcase import keystone.api from keystone.common import context from keystone.common import json_home from keystone.common import provider_api from keystone.common import sql import keystone.conf from keystone import exception from keystone.identity.backends.ldap import common as ks_ldap from keystone import notifications from keystone.resource.backends import base as resource_base from keystone.server.flask import application as flask_app from keystone.server.flask import core as keystone_flask from keystone.tests.unit import ksfixtures keystone.conf.configure() keystone.conf.set_config_defaults() PID = str(os.getpid()) TESTSDIR = os.path.dirname(os.path.abspath(__file__)) TESTCONF = os.path.join(TESTSDIR, 'config_files') ROOTDIR = os.path.normpath(os.path.join(TESTSDIR, '..', '..', '..')) VENDOR = os.path.join(ROOTDIR, 'vendor') ETCDIR = os.path.join(ROOTDIR, 'etc') TMPDIR = _calc_tmpdir() CONF = keystone.conf.CONF PROVIDERS = provider_api.ProviderAPIs log.register_options(CONF) IN_MEM_DB_CONN_STRING = 'sqlite://' # Strictly matches ISO 8601 timestamps with subsecond precision like: # 2016-06-28T20:48:56.000000Z TIME_FORMAT = '%Y-%m-%dT%H:%M:%S.%fZ' TIME_FORMAT_REGEX = r'^\d{4}-[0-1]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d{6}Z$' exception._FATAL_EXCEPTION_FORMAT_ERRORS = True os.makedirs(TMPDIR) atexit.register(shutil.rmtree, TMPDIR) def skip_if_cache_disabled(*sections): """Skip a test if caching is disabled, this is a decorator. Caching can be disabled either globally or for a specific section. In the code fragment:: @skip_if_cache_is_disabled('assignment', 'token') def test_method(*args): ... The method test_method would be skipped if caching is disabled globally via the `enabled` option in the `cache` section of the configuration or if the `caching` option is set to false in either `assignment` or `token` sections of the configuration. This decorator can be used with no arguments to only check global caching. If a specified configuration section does not define the `caching` option, this decorator makes the caching enabled if `enabled` option in the `cache` section of the configuration is true. """ return wrapper def skip_if_cache_is_enabled(*sections): return wrapper def skip_if_no_multiple_domains_support(f): """Decorator to skip tests for identity drivers limited to one domain.""" return wrapper NEEDS_REGION_ID = object() def new_endpoint_ref_with_region(service_id, region, interface='public', **kwargs): """Define an endpoint_ref having a pre-3.2 form. Contains the deprecated 'region' instead of 'region_id'. """ ref = new_endpoint_ref(service_id, interface, region=region, region_id='invalid', **kwargs) del ref['region_id'] return ref def create_user(api, domain_id, **kwargs): """Create a user via the API. Keep the created password. The password is saved and restored when api.create_user() is called. Only use this routine if there is a requirement for the user object to have a valid password after api.create_user() is called. """ user = new_user_ref(domain_id=domain_id, **kwargs) password = user['password'] user = api.create_user(user) user['password'] = password return user def _assert_expected_status(f): """Add `expected_status_code` as an argument to the test_client methods. `expected_status_code` must be passed as a kwarg. """ TEAPOT_HTTP_STATUS = 418 _default_expected_responses = { 'get': http.client.OK, 'head': http.client.OK, 'post': http.client.CREATED, 'put': http.client.NO_CONTENT, 'patch': http.client.OK, 'delete': http.client.NO_CONTENT, } return inner
[ 2, 15069, 2321, 4946, 25896, 5693, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 921, 743, 7330, ...
2.898575
1,755
from .group import Group from .node import (Node, parse_xml_properties, ATTR_ID) from time import sleep from xml.dom import minidom
[ 198, 6738, 764, 8094, 1330, 4912, 198, 6738, 764, 17440, 1330, 357, 19667, 11, 21136, 62, 19875, 62, 48310, 11, 5161, 5446, 62, 2389, 8, 198, 6738, 640, 1330, 3993, 198, 6738, 35555, 13, 3438, 1330, 949, 312, 296, 628 ]
3.35
40
# SPDX-FileCopyrightText: 2021 easyCore contributors <core@easyscience.software> # SPDX-License-Identifier: BSD-3-Clause # 2021 Contributors to the easyCore project <https://github.com/easyScience/easyCore> __author__ = 'github.com/wardsimon' __version__ = '0.1.0' import logging
[ 2, 220, 30628, 55, 12, 8979, 15269, 8206, 25, 33448, 2562, 14055, 20420, 220, 1279, 7295, 31, 30412, 893, 4234, 13, 43776, 29, 198, 2, 220, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 347, 10305, 12, 18, 12, 2601, 682, 198, 2, 220,...
2.969072
97
"""Module for IQ option billing resource.""" from iqoptionapi.http.resource import Resource
[ 37811, 26796, 329, 18248, 3038, 26297, 8271, 526, 15931, 198, 198, 6738, 1312, 80, 18076, 15042, 13, 4023, 13, 31092, 1330, 20857, 628 ]
4.086957
23
# -*- coding: utf-8 -*- def ordered_set(iter): """Creates an ordered set @param iter: list or tuple @return: list with unique values """ final = [] for i in iter: if i not in final: final.append(i) return final def class_slots(ob): """Get object attributes from child class attributes @param ob: Defaults object @type ob: Defaults @return: Tuple of slots """ current_class = type(ob).__mro__[0] if not getattr(current_class, 'allslots', None) \ and current_class != object: _allslots = [list(getattr(cls, '__slots__', [])) for cls in type(ob).__mro__] _fslots = [] for slot in _allslots: _fslots = _fslots + slot current_class.allslots = tuple(ordered_set(_fslots)) return current_class.allslots def usef(attr): """Use another value as default @param attr: the name of the attribute to use as alternative value @return: value of alternative attribute """ return use_if_none_cls(attr) use_name_if_none = usef('Name') def choose_alt(attr, ob, kwargs): """If the declared class attribute of ob is callable then use that callable to get a default ob instance value if a value is not available in kwargs. @param attr: ob class attribute name @param ob: the object instance whose default value needs to be set @param kwargs: the kwargs values passed to the ob __init__ method @return: value to be used to set ob instance """ result = ob.__class__.__dict__.get(attr, None) if type(result).__name__ == "member_descriptor": result = None elif callable(result): result = result(attr, ob, kwargs) return result
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 628, 198, 4299, 6149, 62, 2617, 7, 2676, 2599, 198, 220, 220, 220, 37227, 16719, 274, 281, 6149, 900, 628, 220, 220, 220, 2488, 17143, 11629, 25, 1351, 393, 46545, 198, 220...
2.490196
714
import asyncio from collections import defaultdict from datetime import timedelta import pytest from yui.api import SlackAPI from yui.bot import Bot from yui.box import Box from yui.types.slack.response import APIResponse from yui.utils import json from .util import FakeImportLib
[ 11748, 30351, 952, 198, 6738, 17268, 1330, 4277, 11600, 198, 6738, 4818, 8079, 1330, 28805, 12514, 198, 198, 11748, 12972, 9288, 198, 198, 6738, 331, 9019, 13, 15042, 1330, 36256, 17614, 198, 6738, 331, 9019, 13, 13645, 1330, 18579, 198, ...
3.487805
82
#!/usr/bin/env python import numpy as np import rospy import geometry_msgs.msg import tf2_ros from tf.transformations import quaternion_slerp if __name__ == '__main__': rospy.init_node('marker_filter') alpha = rospy.get_param('~alpha', 0.9) parent_frame_id = rospy.get_param('~parent_frame_id', 'kinect2_link') marker_id = rospy.get_param('~marker_id', 'marker_id0') marker_filtered_id = rospy.get_param( '~marker_filtered_id', 'marker_id0_filtered') rate_value = rospy.get_param('~rate_value', 125) tfBuffer = tf2_ros.Buffer() listener = tf2_ros.TransformListener(tfBuffer) br = tf2_ros.TransformBroadcaster() marker_pose = None marker_pose0 = None rate = rospy.Rate(rate_value) while not rospy.is_shutdown(): marker_pose0 = marker_pose # Lookup the transform try: marker_pose_new = tfBuffer.lookup_transform( parent_frame_id, marker_id, rospy.Time()) if not marker_pose_new is None: marker_pose = marker_pose_new except (tf2_ros.LookupException, tf2_ros.ConnectivityException, tf2_ros.ExtrapolationException) as e: rospy.logwarn(e) if marker_pose is None: rate.sleep() continue # Apply running average filter to translation and rotation if not marker_pose0 is None: rotation0 = quaternion_to_numpy(marker_pose0.transform.rotation) rotation = quaternion_to_numpy(marker_pose.transform.rotation) rotation_interpolated = quaternion_slerp( rotation0, rotation, 1 - alpha) translation0 = translation_to_numpy( marker_pose0.transform.translation) translation = translation_to_numpy( marker_pose.transform.translation) translation = alpha * translation0 + (1 - alpha) * translation # Update pose of the marker marker_pose.transform.rotation.x = rotation_interpolated[0] marker_pose.transform.rotation.y = rotation_interpolated[1] marker_pose.transform.rotation.z = rotation_interpolated[2] marker_pose.transform.rotation.w = rotation_interpolated[3] marker_pose.transform.translation.x = translation[0] marker_pose.transform.translation.y = translation[1] marker_pose.transform.translation.z = translation[2] # Create new transform and broadcast it t = geometry_msgs.msg.TransformStamped() t.header.stamp = rospy.Time.now() t.header.frame_id = parent_frame_id t.child_frame_id = marker_filtered_id t.transform = marker_pose.transform br.sendTransform(t) rate.sleep()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 686, 2777, 88, 198, 11748, 22939, 62, 907, 14542, 13, 19662, 198, 11748, 48700, 17, 62, 4951, 198, 6738, 48700, 13, 35636, 602, 1330, 62...
2.275947
1,214
import os import subprocess from pathlib import Path from torch.hub import load_state_dict_from_url import numpy as np model_urls = { # ResNet 'resnet18': 'https://download.pytorch.org/models/resnet18-f37072fd.pth', 'resnet34': 'https://download.pytorch.org/models/resnet34-b627a593.pth', 'resnet50': 'https://download.pytorch.org/models/resnet50-0676ba61.pth', 'resnet101': 'https://download.pytorch.org/models/resnet101-63fe2227.pth', 'resnet152': 'https://download.pytorch.org/models/resnet152-394f9c45.pth', 'resnext50_32x4d': 'https://download.pytorch.org/models/resnext50_32x4d-7cdf4587.pth', 'resnext101_32x8d': 'https://download.pytorch.org/models/resnext101_32x8d-8ba56ff5.pth', 'wide_resnet50_2': 'https://download.pytorch.org/models/wide_resnet50_2-95faca4d.pth', 'wide_resnet101_2': 'https://download.pytorch.org/models/wide_resnet101_2-32ee1156.pth', # MobileNetV2 'mobilenet_v2': 'https://download.pytorch.org/models/mobilenet_v2-b0353104.pth', # Se ResNet 'seresnet18': 'https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/seresnet18-4bb0ce65.pth', 'seresnet34': 'https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/seresnet34-a4004e63.pth', 'seresnet50': 'https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-cadene/se_resnet50-ce0d4300.pth', 'seresnet101': 'https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-cadene/se_resnet101-7e38fcc6.pth', 'seresnet152': 'https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-cadene/se_resnet152-d17c99b7.pth', 'seresnext50_32x4d': 'http://data.lip6.fr/cadene/pretrainedmodels/se_resnext50_32x4d-a260b3a4.pth', # ViT 'vit_base_patch16_224': 'https://storage.googleapis.com/vit_models/imagenet21k/ViT-B_16.npz', 'vit_base_patch32_224': 'https://storage.googleapis.com/vit_models/imagenet21k/ViT-B_32.npz', 'vit_large_patch16_224': 'https://storage.googleapis.com/vit_models/imagenet21k/ViT-L_16.npz', 'vit_large_patch32_224': 'https://storage.googleapis.com/vit_models/imagenet21k/ViT-L_32.npz', # Hybrid (resnet50 + ViT) 'r50_vit_base_patch16_224': 'https://storage.googleapis.com/vit_models/imagenet21k/R50+ViT-B_16.npz', 'r50_vit_large_patch32_224': 'https://storage.googleapis.com/vit_models/imagenet21k/R50+ViT-L_32.npz', }
[ 11748, 28686, 198, 11748, 850, 14681, 198, 6738, 3108, 8019, 1330, 10644, 198, 198, 6738, 28034, 13, 40140, 1330, 3440, 62, 5219, 62, 11600, 62, 6738, 62, 6371, 198, 198, 11748, 299, 32152, 355, 45941, 628, 198, 19849, 62, 6371, 82, 7...
2.172197
1,115
import requests from bs4 import BeautifulSoup links = getLinks("http://www.reddit.com/") print(links)
[ 11748, 7007, 198, 6738, 275, 82, 19, 1330, 23762, 50, 10486, 198, 198, 28751, 796, 651, 31815, 7203, 4023, 1378, 2503, 13, 10748, 13, 785, 14, 4943, 198, 4798, 7, 28751, 8 ]
3.1875
32
"""Tests for SEIR model in this repo * Compares conserved quantities * Compares model against SEIR wo social policies in limit to SIR """ from pandas import Series from pandas.testing import assert_frame_equal, assert_series_equal from bayes_chime.normal.models import SEIRModel, SIRModel from pytest import fixture from tests.normal.models.sir_test import ( # pylint: disable=W0611 fixture_penn_chime_raw_df_no_policy, fixture_penn_chime_setup, fixture_sir_data_wo_policy, ) COLS_TO_COMPARE = [ "susceptible", "infected", "recovered", # Does not compare census as this repo uses the exponential distribution ] PENN_CHIME_COMMIT = "188c35be9561164bedded4a8071a320cbde0d2bc" def test_conserved_n(seir_data): """Checks if S + E + I + R is conserved for SEIR """ x, pars = seir_data n_total = 0 for key in SEIRModel.compartments: n_total += pars[f"initial_{key}"] seir_model = SEIRModel() predictions = seir_model.propagate_uncertainties(x, pars) n_computed = predictions[SEIRModel.compartments].sum(axis=1) n_expected = Series(data=[n_total] * len(n_computed), index=n_computed.index) assert_series_equal(n_expected, n_computed) def test_compare_sir_vs_seir(sir_data_wo_policy, seir_data, monkeypatch): """Checks if SEIR and SIR return same results if the code enforces * alpha = gamma * E = 0 * dI = dE """ x_sir, pars_sir = sir_data_wo_policy x_seir, pars_seir = seir_data pars_seir["alpha"] = pars_sir["gamma"] # will be done by hand seir_model = SEIRModel() monkeypatch.setattr(seir_model, "simulation_step", mocked_seir_step) sir_model = SIRModel() predictions_sir = sir_model.propagate_uncertainties(x_sir, pars_sir) predictions_seir = seir_model.propagate_uncertainties(x_seir, pars_seir) assert_frame_equal( predictions_sir[COLS_TO_COMPARE], predictions_seir[COLS_TO_COMPARE], )
[ 37811, 51, 3558, 329, 7946, 4663, 2746, 287, 428, 29924, 198, 9, 3082, 3565, 4055, 276, 17794, 198, 9, 3082, 3565, 2746, 1028, 7946, 4663, 24486, 1919, 4788, 287, 4179, 284, 311, 4663, 198, 37811, 198, 6738, 19798, 292, 1330, 7171, 19...
2.500642
779
import numpy as np from scipy.interpolate import interp1d from pyTools import * ################################################################################ #~~~~~~~~~Log ops ################################################################################ ################################################################################ #~~~~~~~~~Symmeterize data ################################################################################ ################################################################################ #~~~~~~~~~3D Shapes ################################################################################ ################################################################################ #~~~~~~~~~2D Shapes ################################################################################ ################################################################################ #~~~~~~~~~Rotations ################################################################################
[ 11748, 299, 32152, 355, 45941, 198, 6738, 629, 541, 88, 13, 3849, 16104, 378, 1330, 987, 79, 16, 67, 198, 6738, 12972, 33637, 1330, 1635, 198, 198, 29113, 29113, 14468, 198, 2, 15116, 93, 11187, 39628, 198, 29113, 29113, 14468, 198, 1...
9.268519
108
from setuptools import setup setup( name="ambient_api", version="1.5.6", packages=["ambient_api"], url="https://github.com/avryhof/ambient_api", license="MIT", author="Amos Vryhof", author_email="amos@vryhofresearch.com", description="A Python class for accessing the Ambient Weather API.", classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3", ], install_requires=["requests", "urllib3"], )
[ 6738, 900, 37623, 10141, 1330, 9058, 198, 198, 40406, 7, 198, 220, 220, 220, 1438, 2625, 4131, 1153, 62, 15042, 1600, 198, 220, 220, 220, 2196, 2625, 16, 13, 20, 13, 21, 1600, 198, 220, 220, 220, 10392, 28, 14692, 4131, 1153, 62, ...
2.631111
225
#!/usr/bin/env python import subprocess import os
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 850, 14681, 198, 11748, 28686, 628, 198 ]
2.944444
18
from collections import deque
[ 6738, 17268, 1330, 390, 4188, 628 ]
5.166667
6
from flask import Blueprint, render_template from gateways.models import getWeatherData web = Blueprint("web", __name__, template_folder='templates') #@web.route("/profile", methods=['GET']) #def profile(): # items = getWeatherData.get_last_item() # return render_template("profile.html", # celcius=items["temperature"], # humidity=items["humidity"], # pressure=items["pressure"]) #@web.route("/about", methods=['GET']) #def about(): # return render_template("about.html")
[ 6738, 42903, 1330, 39932, 11, 8543, 62, 28243, 198, 6738, 8946, 1322, 13, 27530, 1330, 651, 41865, 6601, 628, 198, 12384, 796, 39932, 7203, 12384, 1600, 11593, 3672, 834, 11, 11055, 62, 43551, 11639, 11498, 17041, 11537, 198, 198, 2, 31...
2.40678
236
from __future__ import absolute_import from changes.buildsteps.default import DefaultBuildStep
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 198, 6738, 2458, 13, 11249, 20214, 13, 12286, 1330, 15161, 15580, 8600, 628 ]
4.409091
22
#!/usr/bin/env python3 """Star Wars API HTTP response parsing""" # requests is used to send HTTP requests (get it?) import requests URL= "https://swapi.dev/api/people/1" def main(): """sending GET request, checking response""" # SWAPI response is stored in "resp" object resp= requests.get(URL) # what kind of python object is "resp"? print("This object class is:", type(resp), "\n") # what can we do with it? print("Methods/Attributes include:", dir(resp)) if __name__ == "__main__": main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 37811, 8248, 6176, 7824, 14626, 2882, 32096, 37811, 198, 198, 2, 7007, 318, 973, 284, 3758, 14626, 7007, 357, 1136, 340, 10091, 198, 11748, 7007, 198, 198, 21886, 28, 366, 5450, 13...
2.988764
178
import json schema = { "Spartina": { "ColStart": "2000-04-01", "ColEnd": "2000-05-31", "random": 7, "mud_colonization": [0.0, 0.0], "fl_dr": 0.005, "Maximum age": 20, "Number LifeStages": 2, "initial root length": 0.05, "initial shoot length": 0.015, "initial diameter": 0.003, "start growth period": "2000-04-01", "end growth period": "2000-10-31", "start winter period": "2000-11-30", "maximum plant height": [0.8, 1.3], "maximum diameter": [0.003, 0.005], "maximum root length": [0.2, 1], "maximum years in LifeStage": [1, 19], "numStem": [700, 700], # 3.5. number of stems per m2 "iniCol_frac": 0.6, # 3.6. initial colonization fraction (0-1) "Cd": [1.1, 1.15], # 3.7. drag coefficient "desMort_thres": [400, 400], # 3.9. dessication mortality threshold "desMort_slope": [0.75, 0.75], # 3.10. dessication mortality slope "floMort_thres": [0.4, 0.4], # 3.11. flooding mortality threshold "floMort_slope": [0.25, 0.25], # 3.12. flooding mortality slope "vel_thres": [0.15, 0.25], # 3.13. flow velocity threshold "vel_slope": [3, 3], # 3.14. flow velocity slope "maxH_winter": [0.4, 0.4], # 3.15 max height during winter time }, "Salicornia": { "ColStart": "2000-02-15", "ColEnd": "2000-04-30", "random": 20, "mud_colonization": [0.0, 0.0], "fl_dr": 0.005, "Maximum age": 1, "Number LifeStages": 1, "initial root length": 0.15, "initial shoot length": 0.05, "initial diameter": 0.01, "start growth period": "2000-02-15", "end growth period": "2000-10-15", "start winter period": "2000-11-01", "maximum plant height": [0.4, 0], "maximum diameter": [0.015, 0], "maximum root length": [0.05, 0], "maximum years in LifeStage": [1, 0], "numStem": [190, 0], # 3.5. number of stems per m2 "iniCol_frac": 0.2, # 3.6. initial colonization fraction (0-1) "Cd": [0.7, 0], # 3.7. drag coefficient "desMort_thres": [400, 1], # 3.9. dessication mortality threshold "desMort_slope": [0.75, 1], # 3.10. dessication mortality slope "floMort_thres": [0.5, 1], # 3.11. flooding mortality threshold "floMort_slope": [0.12, 1], # 3.12. flooding mortality slope "vel_thres": [0.15, 1], # 3.13. flow velocity threshold "vel_slope": [3, 1], # 3.14. flow velocity slope "maxH_winter": [0.0, 0.0], # 3.15 max height during winter time }, "Puccinellia": { "ColStart": "2000-03-01", "ColEnd": "2000-04-30", "random": 7, "mud_colonization": [0.0, 0.0], "fl_dr": 0.005, "Maximum age": 20, "Number LifeStages": 2, "initial root length": 0.02, "initial shoot length": 0.05, "initial diameter": 0.004, "start growth period": "2000-03-01", "end growth period": "2000-11-15", "start winter period": "2000-11-30", "maximum plant height": [0.2, 0.35], "maximum diameter": [0.004, 0.005], "maximum root length": [0.15, 0.15], "maximum years in LifeStage": [1, 19], "numStem": [6500, 6500], # 3.5. number of stems per m2 "iniCol_frac": 0.3, # 3.6. initial colonization fraction (0-1) "Cd": [0.7, 0.7], # 3.7. drag coefficient "desMort_thres": [400, 400], # 3.9. dessication mortality threshold "desMort_slope": [0.75, 0.75], # 3.10. dessication mortality slope "floMort_thres": [0.35, 0.35], # 3.11. flooding mortality threshold "floMort_slope": [0.4, 0.4], # 3.12. flooding mortality slope "vel_thres": [0.25, 0.5], # 3.13. flow velocity threshold "vel_slope": [3, 3], # 3.14. flow velocity slope "maxH_winter": [0.2, 0.2], # 3.15 max height during winter time }, } with open("constants_veg.json", "w") as write_file: json.dump(schema, write_file, indent=4)
[ 11748, 33918, 198, 198, 15952, 2611, 796, 1391, 198, 220, 220, 220, 366, 50, 3911, 1437, 1298, 1391, 198, 220, 220, 220, 220, 220, 220, 220, 366, 5216, 10434, 1298, 366, 11024, 12, 3023, 12, 486, 1600, 198, 220, 220, 220, 220, 220, ...
2.07014
1,996
format_py = rule( implementation = _format_py_impl, executable = True, attrs = { "srcs": attr.label_list( allow_files = [".py"], mandatory = True, ), "_fmt": attr.label( cfg = "host", default = "//format:format_py", executable = True, ), "_style": attr.label( allow_single_file = True, default = ":setup.cfg", ), }, )
[ 198, 18982, 62, 9078, 796, 3896, 7, 198, 220, 220, 220, 7822, 796, 4808, 18982, 62, 9078, 62, 23928, 11, 198, 220, 220, 220, 28883, 796, 6407, 11, 198, 220, 220, 220, 708, 3808, 796, 1391, 198, 220, 220, 220, 220, 220, 220, 220, ...
1.831373
255
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib.auth.models import AbstractUser, UserManager from django.db import models from django.utils import timezone # Create your models here. # Create our new user class
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 27741, 12982, 11, 11787, 13511, 198, 6738, ...
3.378378
74
""" If you find this code useful, please cite our paper: Mahmoud Afifi, Marcus A. Brubaker, and Michael S. Brown. "HistoGAN: Controlling Colors of GAN-Generated and Real Images via Color Histograms." In CVPR, 2021. @inproceedings{afifi2021histogan, title={Histo{GAN}: Controlling Colors of {GAN}-Generated and Real Images via Color Histograms}, author={Afifi, Mahmoud and Brubaker, Marcus A. and Brown, Michael S.}, booktitle={CVPR}, year={2021} } """ from tqdm import tqdm from histoGAN import Trainer, NanException from histogram_classes.RGBuvHistBlock import RGBuvHistBlock from datetime import datetime import torch import argparse from retry.api import retry_call import os from PIL import Image from torchvision import transforms import numpy as np SCALE = 1 / np.sqrt(2.0) if __name__ == "__main__": args = get_args() torch.cuda.set_device(args.gpu) train_from_folder( data=args.data, results_dir=args.results_dir, models_dir=args.models_dir, name=args.name, new=args.new, load_from=args.load_from, image_size=args.image_size, network_capacity=args.network_capacity, transparent=args.transparent, batch_size=args.batch_size, gradient_accumulate_every=args.gradient_accumulate_every, num_train_steps=args.num_train_steps, learning_rate=args.learning_rate, num_workers=args.num_workers, save_every=args.save_every, generate=args.generate, save_noise_latent=args.save_n_l, target_noise_file=args.target_n, target_latent_file=args.target_l, num_image_tiles=args.num_image_tiles, trunc_psi=args.trunc_psi, fp16=args.fp16, fq_layers=args.fq_layers, fq_dict_size=args.fq_dict_size, attn_layers=args.attn_layers, hist_method=args.hist_method, hist_resizing=args.hist_resizing, hist_sigma=args.hist_sigma, hist_bin=args.hist_bin, hist_insz=args.hist_insz, target_hist=args.target_hist, alpha=args.alpha, aug_prob=args.aug_prob, dataset_aug_prob=args.dataset_aug_prob, aug_types=args.aug_types )
[ 37811, 198, 1002, 345, 1064, 428, 2438, 4465, 11, 3387, 21729, 674, 3348, 25, 628, 38554, 2483, 22238, 11, 17068, 317, 13, 1709, 549, 3110, 11, 290, 3899, 311, 13, 4373, 13, 366, 13749, 78, 45028, 25, 198, 2345, 18886, 29792, 286, 4...
2.512165
822
# -*- coding: utf-8 -*- # Generated by Django 1.9.10 on 2016-10-05 18:52 from __future__ import unicode_literals from django.db import migrations, models
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 352, 13, 24, 13, 940, 319, 1584, 12, 940, 12, 2713, 1248, 25, 4309, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 1...
2.736842
57
# 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 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 distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import timeit import itertools import argparse import os if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('ffi_type') parsed = parser.parse_args() if parsed.ffi_type == "cython": os.environ['MXNET_ENABLE_CYTHON'] = '1' os.environ['MXNET_ENFORCE_CYTHON'] = '1' elif parsed.ffi_type == "ctypes": os.environ['MXNET_ENABLE_CYTHON'] = '0' else: raise ValueError("unknown ffi_type {}",format(parsed.ffi_type)) os.environ["MXNET_ENGINE_TYPE"] = "NaiveEngine" import mxnet as mx import numpy as onp from mxnet import np as dnp mx.npx.set_np(dtype=False) packages = { "onp": { "module": onp, "data": lambda arr: arr.asnumpy() if isinstance(arr, dnp.ndarray) else arr }, "dnp": { "module": dnp, "data": lambda arr: arr } } prepare_workloads() results = run_benchmark(packages) show_results(results)
[ 2, 49962, 284, 262, 24843, 10442, 5693, 357, 1921, 37, 8, 739, 530, 198, 2, 393, 517, 18920, 5964, 11704, 13, 220, 4091, 262, 28536, 2393, 198, 2, 9387, 351, 428, 670, 329, 3224, 1321, 198, 2, 5115, 6634, 9238, 13, 220, 383, 7054,...
2.654815
675
#!/usr/bin/env python3 import json import argparse import re import datetime import paramiko import requests # cmd ['ssh', 'smart', # 'mkdir -p /home/levabd/smart-home-temp-humidity-monitor; # cat - > /home/levabd/smart-home-temp-humidity-monitor/lr.json'] from miio import chuangmi_plug from btlewrap import available_backends, BluepyBackend from mitemp_bt.mitemp_bt_poller import MiTempBtPoller, \ MI_TEMPERATURE, MI_HUMIDITY, MI_BATTERY state = {} f = open('/home/pi/smart-climat-daemon/ac_state.json') state = json.load(f) plug_type = 'chuangmi.plug.m1' def valid_mitemp_mac(mac, pat=re.compile(r"[0-9A-F]{2}:[0-9A-F]{2}:[0-9A-F]{2}:[0-9A-F]{2}:[0-9A-F]{2}:[0-9A-F]{2}")): """Check for valid mac addresses.""" if not pat.match(mac.upper()): raise argparse.ArgumentTypeError( 'The MAC address "{}" seems to be in the wrong format'.format(mac)) return mac def turn_on_humidifier(): """Turn on humidifier on a first floor.""" hummidifier_plug = chuangmi_plug.ChuangmiPlug( ip='192.168.19.59', token='14f5b868a58ef4ffaef6fece61c65b16', start_id=0, debug=1, lazy_discover=True, model=plug_type) hummidifier_plug.on() def turn_off_humidifier(): """Turn off humidifier on a first floor.""" hummidifier_plug = chuangmi_plug.ChuangmiPlug( ip='192.168.19.59', token='14f5b868a58ef4ffaef6fece61c65b16', start_id=0, debug=1, lazy_discover=True, model=plug_type) hummidifier_plug.off() def check_if_ac_off(): """Check if AC is turned off.""" status_url = 'http://smart.levabd.pp.ua:2002/status-bedroom?key=27fbc501b51b47663e77c46816a' response = requests.get(status_url, timeout=(20, 30)) if ('address' not in response.json()) and ('name' not in response.json()): return None if ((response.json()['name'] == "08bc20043df8") and (response.json()['address'] == "192.168.19.54")): if response.json()['props']['boot'] == 0: return True return False return None def check_if_ac_cool(): """Check if AC is turned for a automate cooling.""" status_url = 'http://smart.levabd.pp.ua:2002/status-bedroom?key=27fbc501b51b47663e77c46816a' response = requests.get(status_url, timeout=(20, 30)) if ('address' not in response.json()) or ('name' not in response.json()): return None if ((response.json()['name'] == "08bc20043df8") and (response.json()['address'] == "192.168.19.54")): if not response.json()['props']['boot'] == 1: return False if not response.json()['props']['runMode'] == '001': return False if not response.json()['props']['wdNumber'] == 25: return False if not response.json()['props']['windLevel'] == '001': return False return True return None def check_if_ac_heat(): """Check if AC is turned for a automate heating.""" status_url = 'http://smart.levabd.pp.ua:2003/status/key/27fbc501b51b47663e77c46816a' response = requests.get(status_url, timeout=(20, 30)) if ('address' not in response.json()) and ('name' not in response.json()): return None if ((response.json()['name'] == "08bc20043df8") and (response.json()['address'] == "192.168.19.54")): if not response.json()['props']['boot'] == 1: return False if not response.json()['props']['runMode'] == '100': return False if not response.json()['props']['wdNumber'] == 23: return False if not response.json()['props']['windLevel'] == '001': return False return True return None def turn_on_heat_ac(): """Turn on AC on a first floor for a heating if it was not.""" if (state['wasTurnedHeat'] == 1) and not state['triedTurnedHeat'] == 1: return heat_url = 'http://smart.levabd.pp.ua:2003/heat/key/27fbc501b51b47663e77c46816a' ac_heat = check_if_ac_heat() if ac_heat is not None: if not ac_heat: state['triedTurnedHeat'] = 1 state['wasTurnedHeat'] = 0 with open('/home/pi/smart-climat-daemon/ac_state.json', 'w') as file: json.dump(state, file) response = requests.get(heat_url) print(response.json()) else: if state['triedTurnedHeat'] == 1: state['triedTurnedOff'] = 0 state['wasTurnedOff'] = 0 state['triedTurnedCool'] = 0 state['wasTurnedCool'] = 0 state['triedTurnedHeat'] = 0 state['wasTurnedHeat'] = 1 with open('/home/pi/smart-climat-daemon/ac_state.json', 'w') as file: json.dump(state, file) def turn_on_cool_ac(): """Turn on AC on a first floor for a cooling if it was not.""" if (state['wasTurnedCool'] == 1) and not state['triedTurnedCool'] == 1: return cool_url = 'http://smart.levabd.pp.ua:2003/cool/key/27fbc501b51b47663e77c46816a' ac_cool = check_if_ac_cool() if ac_cool is not None: if not ac_cool: state['triedTurnedCool'] = 1 state['wasTurnedCool'] = 0 with open('/home/pi/smart-climat-daemon/ac_state.json', 'w') as file: json.dump(state, file) response = requests.get(cool_url) print(response.json()) else: if state['triedTurnedCool'] == 1: state['triedTurnedOff'] = 0 state['wasTurnedOff'] = 0 state['triedTurnedCool'] = 0 state['wasTurnedCool'] = 1 state['triedTurnedHeat'] = 0 state['wasTurnedHeat'] = 0 with open('/home/pi/smart-climat-daemon/ac_state.json', 'w') as file: json.dump(state, file) def turn_off_ac(): """Turn off AC on a first floor.""" if (state['wasTurnedOff'] == 1) and not state['triedTurnedOff'] == 1: return turn_url = 'http://smart.levabd.pp.ua:2003/power-off/key/27fbc501b51b47663e77c46816a' ac_off = check_if_ac_off() if ac_off is not None: if not ac_off: state['triedTurnedOff'] = 1 state['wasTurnedOff'] = 0 with open('/home/pi/smart-climat-daemon/ac_state.json', 'w') as file: json.dump(state, file) response = requests.get(turn_url) print(response.json()) else: if state['triedTurnedOff'] == 1: state['triedTurnedOff'] = 0 state['wasTurnedOff'] = 1 state['triedTurnedCool'] = 0 state['wasTurnedCool'] = 0 state['triedTurnedHeat'] = 0 state['wasTurnedHeat'] = 0 with open('/home/pi/smart-climat-daemon/ac_state.json', 'w') as file: json.dump(state, file) def record_temp_humid(temperature, humidity): """Record temperature and humidity data for web interface monitor""" dicty = { "temperature": temperature, "humidity": humidity } ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect('smart.levabd.pp.ua', port = 2001, username='levabd', password='vapipu280.') sftp = ssh.open_sftp() with sftp.open('smart-home-temp-humidity-monitor/lr.json', 'w') as outfile: json.dump(dicty, outfile) ssh.close() def poll_temp_humidity(): """Poll data frstate['triedTurnedOff']om the sensor.""" today = datetime.datetime.today() backend = BluepyBackend poller = MiTempBtPoller('58:2d:34:38:c0:91', backend) temperature = poller.parameter_value(MI_TEMPERATURE) humidity = poller.parameter_value(MI_HUMIDITY) print("Month: {}".format(today.month)) print("Getting data from Mi Temperature and Humidity Sensor") print("FW: {}".format(poller.firmware_version())) print("Name: {}".format(poller.name())) print("Battery: {}".format(poller.parameter_value(MI_BATTERY))) print("Temperature: {}".format(poller.parameter_value(MI_TEMPERATURE))) print("Humidity: {}".format(poller.parameter_value(MI_HUMIDITY))) return (today, temperature, humidity) # scan(args): # """Scan for sensors.""" # backend = _get_backend(args) # print('Scanning for 10 seconds...') # devices = mitemp_scanner.scan(backend, 10) # devices = [] # print('Found {} devices:'.format(len(devices))) # for device in devices: # print(' {}'.format(device)) def list_backends(_): """List all available backends.""" backends = [b.__name__ for b in available_backends()] print('\n'.join(backends)) def main(): """Main function.""" # check_if_ac_cool() (today, temperature, humidity) = poll_temp_humidity() # Record temperature and humidity for monitor record_temp_humid(temperature, humidity) try: if (humidity > 49) and (today.month < 10) and (today.month > 4): turn_off_humidifier() if (humidity < 31) and (today.month < 10) and (today.month > 4): turn_on_humidifier() if (humidity < 31) and ((today.month > 9) or (today.month < 5)): turn_on_humidifier() if (humidity > 49) and ((today.month > 9) or (today.month < 5)): turn_off_humidifier() # Prevent Sleep of Xiaomi Smart Plug hummidifier_plug = chuangmi_plug.ChuangmiPlug( ip='192.168.19.59', token='14f5b868a58ef4ffaef6fece61c65b16', start_id=0, debug=0, lazy_discover=True, model='chuangmi.plug.m1') print(hummidifier_plug.status()) except Exception: print("Can not connect to humidifier") # clear env at night if today.hour == 4: state['triedTurnedOff'] = 0 state['wasTurnedOff'] = 0 state['triedTurnedCool'] = 0 state['wasTurnedCool'] = 0 state['triedTurnedHeat'] = 0 state['wasTurnedHeat'] = 0 with open('/home/pi/smart-climat-daemon/ac_state.json', 'w') as file: json.dump(state, file) if (today.hour > -1) and (today.hour < 7): turn_off_ac() if (temperature > 26.4) and (today.month < 6) and (today.month > 4) and (today.hour < 24) and (today.hour > 10): turn_on_cool_ac() if (temperature > 26.4) and (today.month < 10) and (today.month > 8) and (today.hour < 24) and (today.hour > 10): turn_on_cool_ac() if (temperature > 27.3) and (today.month < 9) and (today.month > 5) and (today.hour < 24) and (today.hour > 10): turn_on_cool_ac() if (temperature < 23.5) and (today.month < 10) and (today.month > 4): turn_off_ac() # _if (temperature < 20) and ((today.month > 9) or (today.month < 5)) and (today.hour < 24) and (today.hour > 9): # turn_on_heat_ac() if (temperature > 22) and ((today.month > 9) or (today.month < 5)): turn_off_ac() if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 33918, 198, 11748, 1822, 29572, 198, 11748, 302, 198, 11748, 4818, 8079, 198, 11748, 5772, 12125, 198, 11748, 7007, 198, 198, 2, 23991, 37250, 45824, 3256, 705, 27004, 32...
2.171552
5,083
import pickle from sklearn.neural_network import MLPClassifier train = pickle.load(open('train_pca_reservoir_output_200samples.pickle','rb')) test = pickle.load(open('test_pca_reservoir_output_50samples.pickle','rb')) train_num = 200 test_num = 50 mlp = MLPClassifier(hidden_layer_sizes=(2000,), max_iter=100, alpha=1e-5, solver='sgd', verbose=10, tol=1e-4, random_state=1, learning_rate_init=.1, batch_size= 20) mlp.fit(train[0], train[1][:train_num]) print("Training set score: %f" % mlp.score(train[0], train[1][:train_num])) print("Test set score: %f" % mlp.score(test[0], test[1][:test_num]))
[ 11748, 2298, 293, 198, 6738, 1341, 35720, 13, 710, 1523, 62, 27349, 1330, 10373, 47, 9487, 7483, 198, 198, 27432, 796, 2298, 293, 13, 2220, 7, 9654, 10786, 27432, 62, 79, 6888, 62, 411, 712, 10840, 62, 22915, 62, 2167, 82, 12629, 13...
2.236934
287
import numpy as np import pandas as pd from skimage import io import skimage.measure as measure import os from lpg_pca_impl import denoise
[ 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 1341, 9060, 1330, 33245, 198, 11748, 1341, 9060, 13, 1326, 5015, 355, 3953, 198, 11748, 28686, 198, 6738, 300, 6024, 62, 79, 6888, 62, 23928, 1330, 2853, ...
3.148936
47
import redis from rq import Queue, Connection from flask import Flask, render_template, Blueprint, jsonify, request import tasks import rq_dashboard from wingnut import Wingnut app = Flask( __name__, template_folder="./templates", static_folder="./static", ) app.config.from_object(rq_dashboard.default_settings) app.register_blueprint(rq_dashboard.blueprint, url_prefix="/rq") if __name__ == "__main__": app.run(host="0.0.0.0",debug=1)
[ 11748, 2266, 271, 198, 6738, 374, 80, 1330, 4670, 518, 11, 26923, 198, 6738, 42903, 1330, 46947, 11, 8543, 62, 28243, 11, 39932, 11, 33918, 1958, 11, 2581, 198, 11748, 8861, 198, 11748, 374, 80, 62, 42460, 3526, 198, 6738, 8539, 14930...
2.580645
186
from pytaboola.client import TaboolaClient
[ 6738, 12972, 10658, 13, 16366, 1330, 16904, 10513, 11792 ]
4.666667
9
# -------------- # Importing header files import numpy as np import warnings warnings.filterwarnings('ignore') new_record=[[50, 9, 4, 1, 0, 0, 40, 0]] #New record #Reading file data = np.genfromtxt(path, delimiter=",", skip_header=1) data.shape cenus=np.concatenate((new_record,data),axis=0) cenus.shape print(cenus) age=cenus[:,0] max_age=age.max() print(max_age) min_age=age.min() mean_age=np.mean(age) age_std=np.std(age) race=cenus[:,2] print(race) race_0=(race==0) len_0=len(race[race_0]) print(len_0) race_1=(race==1) len_1=len(race[race_1]) race_2=(race==2) race_3=(race==3) race_4=(race==4) len_2=len(race[race_2]) len_3=len(race[race_3]) len_4=len(race[race_4]) minority_race=3 print(minority_race) senior_citizen=(age>60) working_hour_sum=sum(cenus[:,6][senior_citizen]) print(working_hour_sum) senior_citizen_len=len(age[senior_citizen]) avg_working_hours=working_hour_sum/senior_citizen_len avg_working_hours=round(avg_working_hours,2) education_num=cenus[:,1] print(education_num) high=education_num>10 #high=education_num[high] print(high) low=education_num<=10 #low=education_num[low] print(low) INCOME=cenus[:,7][high] print(INCOME) print(np.mean(INCOME)) avg_pay_high=round(np.mean(INCOME),2) print(avg_pay_high) LOW_AVG=cenus[:,7][low] avg_pay_low=round(np.mean(LOW_AVG),2) print(avg_pay_low) #Code starts here
[ 2, 220, 26171, 198, 2, 17267, 278, 13639, 3696, 201, 198, 11748, 299, 32152, 355, 45941, 201, 198, 11748, 14601, 201, 198, 201, 198, 40539, 654, 13, 24455, 40539, 654, 10786, 46430, 11537, 201, 198, 3605, 62, 22105, 28, 30109, 1120, 1...
2.058394
685
#! /usr/bin/env python # # Presents the results of an Autobahn TestSuite run in TAP format. # # Copyright 2015 Jacob Champion # # 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 # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from distutils.version import StrictVersion import json import os.path import sys import textwrap import yamlish def filter_report(report): """Filters a test report dict down to only the interesting keys.""" INTERESTING_KEYS = [ 'behavior', 'behaviorClose', 'expected', 'received', 'expectedClose', 'remoteCloseCode' ] return { key: report[key] for key in INTERESTING_KEYS } def prepare_description(report): """Constructs a description from a test report.""" raw = report['description'] # Wrap to at most 80 characters. wrapped = textwrap.wrap(raw, 80) description = wrapped[0] if len(wrapped) > 1: # If the text is longer than one line, add an ellipsis. description += '...' return description # # MAIN # # Read the index. results_dir = 'test-results' with open(os.path.join(results_dir, 'index.json'), 'r') as index_file: index = json.load(index_file)['AutobahnPython'] # Sort the tests by numeric ID so we print them in a sane order. test_ids = list(index.keys()) test_ids.sort(key=StrictVersion) # Print the TAP header. print('TAP version 13') print('1..{0!s}'.format(len(test_ids))) count = 0 skipped_count = 0 failed_count = 0 for test_id in test_ids: count += 1 passed = True skipped = False report = None result = index[test_id] # Try to get additional information from this test's report file. try: path = os.path.join(results_dir, result['reportfile']) with open(path, 'r') as f: report = json.load(f) description = prepare_description(report) except Exception as e: description = '[could not load report file: {0!s}]'.format(e) test_result = result['behavior'] close_result = result['behaviorClose'] # Interpret the result for this test. if test_result != 'OK' and test_result != 'INFORMATIONAL': if test_result == 'UNIMPLEMENTED': skipped = True else: passed = False elif close_result != 'OK' and close_result != 'INFORMATIONAL': passed = False # Print the TAP result. print(u'{0} {1} - [{2}] {3}{4}'.format('ok' if passed else 'not ok', count, test_id, description, ' # SKIP unimplemented' if skipped else '')) # Print a YAMLish diagnostic for failed tests. if report and not passed: output = filter_report(report) diagnostic = yamlish.dumps(output) for line in diagnostic.splitlines(): print(' ' + line) if not passed: failed_count += 1 if skipped: skipped_count += 1 # Print a final result. print('# Autobahn|TestSuite {0}'.format('PASSED' if not failed_count else 'FAILED')) print('# total {0}'.format(count)) print('# passed {0}'.format(count - failed_count - skipped_count)) print('# skipped {0}'.format(skipped_count)) print('# failed {0}'.format(failed_count)) exit(0 if not failed_count else 1)
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 198, 2, 47102, 262, 2482, 286, 281, 41735, 15386, 6208, 5606, 578, 1057, 287, 309, 2969, 5794, 13, 198, 2, 198, 2, 15069, 1853, 12806, 15869, 198, 2, 198, 2, 49962, 739, 262, ...
2.502898
1,553
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.891892
37
import openpyxl wb = openpyxl.load_workbook('example.xlsx') sheet = wb.get_sheet_by_name('Sheet1') rows = sheet.get_highest_row() cols = sheet.get_highest_column() for i in range(1, rows + 1): for j in range(1, cols + 1): print('%s: %s' % (sheet.cell(row=i, column=j).coordinate, sheet.cell(row=i, column=j).value)) print('---------------------------------------------')
[ 11748, 1280, 9078, 87, 75, 201, 198, 201, 198, 39346, 796, 1280, 9078, 87, 75, 13, 2220, 62, 1818, 2070, 10786, 20688, 13, 87, 7278, 87, 11537, 201, 198, 21760, 796, 266, 65, 13, 1136, 62, 21760, 62, 1525, 62, 3672, 10786, 3347, 3...
2.509677
155
# Generated by Django 3.1.13 on 2021-10-04 11:44 from django.db import migrations, models import django.db.models.deletion
[ 2, 2980, 515, 416, 37770, 513, 13, 16, 13, 1485, 319, 33448, 12, 940, 12, 3023, 1367, 25, 2598, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 11748, 42625, 14208, 13, 9945, 13, 27530, 13, 2934, 1616, 295, ...
2.840909
44
#import external libraries used in code import requests, json import pycountry print('Currency Exchange') currencies = [] if __name__ == "__main__": findCurrency() help() currencyAmount, fromCurrency, toCurrency = userData() rate = realTimeRate(fromCurrency, toCurrency) completeExchange(rate, currencyAmount, fromCurrency, toCurrency)
[ 2, 11748, 7097, 12782, 973, 287, 2438, 201, 198, 11748, 7007, 11, 33918, 201, 198, 11748, 12972, 19315, 201, 198, 201, 198, 4798, 10786, 34, 13382, 12516, 11537, 201, 198, 201, 198, 22019, 14038, 796, 17635, 201, 198, 220, 220, 220, 2...
2.775362
138
r, c, m = map(int, input().split()) n = int(input()) op = [list(map(lambda x: int(x) - 1, input().split())) for _ in range(n)] board = [[0 for _ in range(c)] for _ in range(r)] for ra, rb, ca, cb in op: for j in range(ra, rb + 1): for k in range(ca, cb + 1): board[j][k] += 1 cnt = 0 for i in range(r): for j in range(c): board[i][j] %= 4 if board[i][j] == 0: cnt += 1 for i in range(n): ra, rb, ca, cb = op[i] cnti = cnt for j in range(ra, rb + 1): for k in range(ca, cb + 1): if board[j][k] == 0: cnti -= 1 elif board[j][k] == 1: cnti += 1 if cnti == m: print(i + 1)
[ 81, 11, 269, 11, 285, 796, 3975, 7, 600, 11, 5128, 22446, 35312, 28955, 198, 77, 796, 493, 7, 15414, 28955, 198, 404, 796, 685, 4868, 7, 8899, 7, 50033, 2124, 25, 493, 7, 87, 8, 532, 352, 11, 5128, 22446, 35312, 3419, 4008, 329,...
1.778607
402
# Copyright (C) 2018 Alexandre Morlet, Henrique Pereira Coutada Miranda # All rights reserved. # # This file is part of yambopy # from __future__ import print_function from builtins import range from yambopy import * from qepy import * import json import matplotlib.pyplot as plt import numpy as np import sys import argparse import operator def analyse_bse( folder, var, exc_n, exc_int, exc_degen, exc_max_E, pack ): """ Using ypp, you can study the convergence of BSE calculations in 2 ways: Create a .png of all absorption spectra relevant to the variable you study Look at the eigenvalues of the first n "bright" excitons (given a threshold intensity) The script reads from <folder> all results from <variable> calculations for processing. The resulting pictures and data files are saved in the ./analyse_bse/ folder. By default, the graphical interface is deactivated (assuming you run on a cluster because of ypp calls). See line 2 inside the script. """ # Packing results (o-* files) from the calculations into yambopy-friendly .json files if pack: # True by default, False if -np used print('Packing ...') pack_files_in_folder(folder,mask=var) pack_files_in_folder(folder,mask='reference') print('Packing done.') else: print('Packing skipped.') # importing data from .json files in <folder> print('Importing...') data = YamboAnalyser(folder) # extract data according to relevant var invars = data.get_inputfiles_tag(var) # Get only files related to the convergence study of the variable, # ordered to have a smooth plot keys=[] sorted_invars = sorted(list(invars.items()), key=operator.itemgetter(1)) for i in range(0,len(sorted_invars)): key=sorted_invars[i][0] if key.startswith(var) or key=='reference.json': keys.append(key) print('Files detected: ',keys) # unit of the input value unit = invars[keys[0]]['variables'][var][1] ###################### # Output-file filename ###################### os.system('mkdir -p analyse_bse') outname = './analyse_%s/%s_%s'%(folder,folder,var) # Array that will contain the output excitons = [] # Loop over all calculations for key in keys: jobname=key.replace('.json','') print(jobname) # input value # BndsRn__ is a special case if var.startswith('BndsRnX'): # format : [1, nband, ...] inp = invars[key]['variables'][var][0][1] else: inp = invars[key]['variables'][var][0] print('Preparing JSON file. Calling ypp if necessary.') ### Creating the 'absorptionspectra.json' file # It will contain the exciton energies y = YamboOut(folder=folder,save_folder=folder) # Args : name of job, SAVE folder path, folder where job was run path a = YamboBSEAbsorptionSpectra(jobname,path=folder) # Get excitons values (runs ypp once) a.get_excitons(min_intensity=exc_int,max_energy=exc_max_E,Degen_Step=exc_degen) # Write .json file with spectra and eigenenergies a.write_json(filename=outname) ### Loading data from .json file f = open(outname+'.json') data = json.load(f) f.close() print('JSON file prepared and loaded.') ### Plotting the absorption spectra # BSE spectra plt.plot(data['E/ev[1]'], data['EPS-Im[2]'],label=jobname,lw=2) # # Axes : lines for exciton energies (disabled, would make a mess) # for n,exciton in enumerate(data['excitons']): # plt.axvline(exciton['energy']) ### Creating array with exciton values (according to settings) l = [inp] for n,exciton in enumerate(data['excitons']): if n <= exc_n-1: l.append(exciton['energy']) excitons.append(l) if text: header = 'Columns : '+var+' (in '+unit+') and "bright" excitons eigenenergies in order.' print(excitons) np.savetxt(outname+'.dat',excitons,header=header) #np.savetxt(outname,excitons,header=header,fmt='%1f') print(outname+'.dat') else: print('-nt flag : no text produced.') if draw: plt.xlabel('$\omega$ (eV)') plt.gca().yaxis.set_major_locator(plt.NullLocator()) plt.legend() #plt.draw() #plt.show() plt.savefig(outname+'.png', bbox_inches='tight') print(outname+'.png') else: print('-nd flag : no plot produced.') print('Done.') if __name__ == "__main__": parser = argparse.ArgumentParser(description='Study convergence on BS calculations using ypp calls.') pa = parser.add_argument pa('folder', help='Folder containing SAVE and convergence runs.' ) pa('variable', help='Variable tested (e.g. FFTGvecs)' ) pa('-ne','--numbexc', help='Number of excitons to read beyond threshold', default=2,type=int) pa('-ie','--intexc', help='Minimum intensity for excitons to be considered bright', default=0.05,type=float) pa('-de','--degenexc', help='Energy threshold under which different peaks are merged (eV)', default=0.01,type=float) pa('-me','--maxexc', help='Energy threshold after which excitons are not read anymore (eV)', default=8.0,type=float) pa('-np','--nopack', help='Skips packing o- files into .json files', action='store_false') pa('-nt','--notext', help='Skips writing the .dat file', action='store_false') pa('-nd','--nodraw', help='Skips drawing (plotting) the abs spectra', action='store_false') if len(sys.argv)==1: parser.print_help() sys.exit(1) args = parser.parse_args() folder = args.folder var = args.variable exc_n = args.numbexc exc_int = args.intexc exc_degen = args.degenexc exc_max_E = args.maxexc pack = args.nopack text = args.text draw = args.draw analyse_bse( folder, var, exc_n, exc_int, exc_degen, exc_max_E, pack=pack, text=text, draw=draw )
[ 2, 15069, 357, 34, 8, 2864, 21000, 260, 3461, 1616, 11, 6752, 33865, 17229, 8704, 40253, 4763, 29575, 198, 2, 1439, 2489, 10395, 13, 198, 2, 198, 2, 770, 2393, 318, 636, 286, 331, 4131, 11081, 198, 2, 198, 6738, 11593, 37443, 834, ...
2.44994
2,507
from module import XMPPModule import halutils import pyfatafl # Commented to avoid loading before its ready
[ 6738, 8265, 1330, 1395, 7378, 47, 26796, 198, 11748, 10284, 26791, 198, 11748, 12972, 69, 1045, 2704, 198, 197, 197, 628, 198, 2, 955, 12061, 284, 3368, 11046, 878, 663, 3492, 198 ]
3.53125
32
from typing import cast, Optional from datetime import datetime, tzinfo, timedelta from zonedbpy import zone_infos from zone_processor.zone_specifier import ZoneSpecifier from zone_processor.inline_zone_info import ZoneInfo __version__ = '1.1'
[ 6738, 19720, 1330, 3350, 11, 32233, 198, 6738, 4818, 8079, 1330, 4818, 8079, 11, 256, 89, 10951, 11, 28805, 12514, 198, 6738, 1976, 12004, 65, 9078, 1330, 6516, 62, 10745, 418, 198, 6738, 6516, 62, 41341, 13, 11340, 62, 16684, 7483, 1...
3.430556
72
from part1 import ( gamma_board, gamma_busy_fields, gamma_delete, gamma_free_fields, gamma_golden_move, gamma_golden_possible, gamma_move, gamma_new, ) """ scenario: test_random_actions uuid: 554539540 """ """ random actions, total chaos """ board = gamma_new(6, 8, 3, 17) assert board is not None assert gamma_move(board, 1, 7, 4) == 0 assert gamma_move(board, 1, 4, 3) == 1 assert gamma_busy_fields(board, 1) == 1 assert gamma_move(board, 2, 5, 1) == 1 assert gamma_move(board, 2, 1, 7) == 1 assert gamma_busy_fields(board, 2) == 2 assert gamma_golden_possible(board, 2) == 1 assert gamma_move(board, 3, 1, 0) == 1 assert gamma_golden_move(board, 3, 3, 4) == 0 assert gamma_busy_fields(board, 2) == 2 assert gamma_move(board, 3, 1, 3) == 1 assert gamma_move(board, 1, 3, 5) == 1 assert gamma_move(board, 1, 2, 3) == 1 assert gamma_golden_possible(board, 1) == 1 assert gamma_move(board, 2, 1, 0) == 0 assert gamma_move(board, 3, 2, 2) == 1 assert gamma_golden_possible(board, 3) == 1 assert gamma_move(board, 1, 0, 2) == 1 assert gamma_move(board, 1, 1, 1) == 1 assert gamma_move(board, 2, 5, 4) == 1 assert gamma_move(board, 3, 0, 4) == 1 assert gamma_golden_possible(board, 3) == 1 assert gamma_move(board, 1, 1, 2) == 1 assert gamma_move(board, 2, 1, 4) == 1 assert gamma_move(board, 2, 1, 6) == 1 assert gamma_move(board, 3, 1, 2) == 0 assert gamma_move(board, 1, 0, 3) == 1 assert gamma_move(board, 1, 4, 2) == 1 board251673140 = gamma_board(board) assert board251673140 is not None assert board251673140 == (".2....\n" ".2....\n" "...1..\n" "32...2\n" "131.1.\n" "113.1.\n" ".1...2\n" ".3....\n") del board251673140 board251673140 = None assert gamma_move(board, 2, 4, 3) == 0 assert gamma_move(board, 2, 5, 1) == 0 assert gamma_move(board, 3, 4, 5) == 1 assert gamma_move(board, 3, 3, 0) == 1 assert gamma_free_fields(board, 3) == 29 assert gamma_move(board, 2, 1, 7) == 0 assert gamma_move(board, 2, 3, 5) == 0 assert gamma_move(board, 3, 0, 5) == 1 assert gamma_move(board, 3, 0, 1) == 1 assert gamma_golden_possible(board, 3) == 1 assert gamma_move(board, 1, 3, 0) == 0 assert gamma_move(board, 1, 0, 7) == 1 board281476409 = gamma_board(board) assert board281476409 is not None assert board281476409 == ("12....\n" ".2....\n" "3..13.\n" "32...2\n" "131.1.\n" "113.1.\n" "31...2\n" ".3.3..\n") del board281476409 board281476409 = None assert gamma_move(board, 2, 5, 1) == 0 assert gamma_move(board, 2, 5, 4) == 0 assert gamma_golden_possible(board, 2) == 1 assert gamma_move(board, 3, 7, 3) == 0 assert gamma_move(board, 3, 5, 1) == 0 assert gamma_busy_fields(board, 3) == 8 assert gamma_move(board, 1, 5, 4) == 0 assert gamma_move(board, 1, 0, 0) == 1 assert gamma_move(board, 2, 6, 3) == 0 assert gamma_move(board, 2, 4, 4) == 1 assert gamma_move(board, 3, 0, 5) == 0 assert gamma_move(board, 3, 0, 1) == 0 assert gamma_free_fields(board, 3) == 24 assert gamma_move(board, 1, 1, 7) == 0 assert gamma_move(board, 1, 2, 1) == 1 board412285252 = gamma_board(board) assert board412285252 is not None assert board412285252 == ("12....\n" ".2....\n" "3..13.\n" "32..22\n" "131.1.\n" "113.1.\n" "311..2\n" "13.3..\n") del board412285252 board412285252 = None assert gamma_move(board, 2, 1, 6) == 0 assert gamma_move(board, 2, 2, 1) == 0 assert gamma_move(board, 3, 1, 2) == 0 assert gamma_free_fields(board, 3) == 23 assert gamma_golden_move(board, 3, 4, 4) == 1 assert gamma_move(board, 1, 0, 2) == 0 assert gamma_move(board, 1, 3, 6) == 1 assert gamma_golden_possible(board, 1) == 1 assert gamma_move(board, 2, 7, 4) == 0 assert gamma_free_fields(board, 2) == 22 assert gamma_move(board, 3, 5, 5) == 1 assert gamma_move(board, 3, 5, 5) == 0 assert gamma_free_fields(board, 3) == 21 assert gamma_move(board, 1, 0, 5) == 0 assert gamma_move(board, 1, 5, 7) == 1 assert gamma_move(board, 2, 0, 6) == 1 assert gamma_move(board, 2, 5, 6) == 1 assert gamma_move(board, 3, 2, 2) == 0 assert gamma_move(board, 1, 5, 2) == 1 assert gamma_move(board, 2, 7, 4) == 0 assert gamma_move(board, 3, 2, 3) == 0 assert gamma_move(board, 3, 3, 1) == 1 assert gamma_move(board, 1, 5, 1) == 0 assert gamma_free_fields(board, 1) == 16 assert gamma_move(board, 2, 4, 2) == 0 assert gamma_move(board, 3, 4, 1) == 1 assert gamma_move(board, 3, 5, 2) == 0 assert gamma_move(board, 1, 7, 4) == 0 assert gamma_move(board, 1, 4, 1) == 0 assert gamma_move(board, 2, 0, 2) == 0 assert gamma_move(board, 2, 0, 5) == 0 assert gamma_busy_fields(board, 2) == 7 assert gamma_move(board, 3, 5, 2) == 0 assert gamma_move(board, 1, 1, 5) == 1 assert gamma_move(board, 2, 3, 5) == 0 assert gamma_move(board, 2, 4, 1) == 0 assert gamma_move(board, 3, 0, 3) == 0 assert gamma_move(board, 3, 1, 5) == 0 assert gamma_move(board, 1, 2, 4) == 1 assert gamma_move(board, 1, 3, 0) == 0 assert gamma_busy_fields(board, 1) == 16 assert gamma_move(board, 2, 3, 5) == 0 assert gamma_move(board, 2, 3, 1) == 0 assert gamma_move(board, 3, 5, 2) == 0 assert gamma_move(board, 1, 0, 4) == 0 assert gamma_move(board, 1, 0, 6) == 0 assert gamma_move(board, 2, 5, 5) == 0 assert gamma_golden_move(board, 2, 2, 2) == 1 assert gamma_move(board, 1, 5, 5) == 0 assert gamma_free_fields(board, 1) == 13 assert gamma_move(board, 2, 2, 6) == 1 assert gamma_move(board, 2, 5, 6) == 0 assert gamma_move(board, 3, 4, 3) == 0 assert gamma_move(board, 1, 4, 3) == 0 assert gamma_move(board, 1, 3, 5) == 0 assert gamma_move(board, 2, 2, 0) == 1 assert gamma_move(board, 3, 0, 4) == 0 assert gamma_move(board, 1, 7, 3) == 0 assert gamma_move(board, 2, 7, 3) == 0 assert gamma_move(board, 2, 3, 1) == 0 assert gamma_move(board, 3, 7, 3) == 0 assert gamma_move(board, 3, 0, 2) == 0 assert gamma_move(board, 1, 3, 3) == 1 assert gamma_move(board, 2, 7, 2) == 0 assert gamma_move(board, 2, 2, 3) == 0 assert gamma_free_fields(board, 2) == 10 assert gamma_move(board, 3, 7, 3) == 0 assert gamma_move(board, 3, 5, 1) == 0 assert gamma_move(board, 1, 7, 2) == 0 board481507094 = gamma_board(board) assert board481507094 is not None assert board481507094 == ("12...1\n" "2221.2\n" "31.133\n" "321.32\n" "13111.\n" "112.11\n" "311332\n" "1323..\n") del board481507094 board481507094 = None assert gamma_move(board, 2, 2, 4) == 0 assert gamma_move(board, 2, 5, 4) == 0 assert gamma_busy_fields(board, 2) == 10 assert gamma_move(board, 1, 7, 2) == 0 assert gamma_move(board, 2, 7, 4) == 0 assert gamma_move(board, 3, 0, 4) == 0 assert gamma_busy_fields(board, 3) == 11 assert gamma_golden_possible(board, 3) == 0 assert gamma_move(board, 2, 7, 2) == 0 assert gamma_move(board, 2, 1, 4) == 0 assert gamma_free_fields(board, 2) == 10 assert gamma_move(board, 3, 0, 5) == 0 assert gamma_busy_fields(board, 3) == 11 assert gamma_move(board, 1, 7, 2) == 0 assert gamma_move(board, 1, 1, 6) == 0 assert gamma_move(board, 2, 2, 0) == 0 assert gamma_move(board, 2, 1, 7) == 0 assert gamma_move(board, 3, 3, 1) == 0 assert gamma_move(board, 1, 6, 4) == 0 assert gamma_move(board, 2, 0, 4) == 0 assert gamma_move(board, 2, 2, 7) == 1 board984249076 = gamma_board(board) assert board984249076 is not None assert board984249076 == ("122..1\n" "2221.2\n" "31.133\n" "321.32\n" "13111.\n" "112.11\n" "311332\n" "1323..\n") del board984249076 board984249076 = None assert gamma_move(board, 1, 4, 1) == 0 assert gamma_golden_possible(board, 1) == 1 board492321582 = gamma_board(board) assert board492321582 is not None assert board492321582 == ("122..1\n" "2221.2\n" "31.133\n" "321.32\n" "13111.\n" "112.11\n" "311332\n" "1323..\n") del board492321582 board492321582 = None assert gamma_move(board, 2, 2, 3) == 0 assert gamma_move(board, 2, 2, 4) == 0 assert gamma_golden_possible(board, 2) == 0 assert gamma_move(board, 3, 2, 3) == 0 assert gamma_move(board, 1, 7, 3) == 0 assert gamma_move(board, 1, 4, 3) == 0 assert gamma_move(board, 2, 2, 4) == 0 assert gamma_move(board, 1, 0, 4) == 0 assert gamma_move(board, 2, 0, 4) == 0 assert gamma_move(board, 2, 2, 6) == 0 assert gamma_move(board, 3, 5, 2) == 0 assert gamma_move(board, 1, 0, 5) == 0 assert gamma_move(board, 2, 3, 2) == 1 assert gamma_move(board, 3, 0, 5) == 0 assert gamma_move(board, 1, 0, 5) == 0 assert gamma_move(board, 1, 2, 3) == 0 assert gamma_golden_possible(board, 1) == 1 assert gamma_move(board, 2, 2, 0) == 0 assert gamma_move(board, 3, 5, 6) == 0 assert gamma_move(board, 3, 2, 1) == 0 gamma_delete(board)
[ 6738, 636, 16, 1330, 357, 198, 220, 220, 220, 34236, 62, 3526, 11, 198, 220, 220, 220, 34236, 62, 10885, 88, 62, 25747, 11, 198, 220, 220, 220, 34236, 62, 33678, 11, 198, 220, 220, 220, 34236, 62, 5787, 62, 25747, 11, 198, 220, ...
2.343707
3,631
# coding=utf-8 # Copyright 2019 The HuggingFace Inc. team. # Copyright (c) 2019 The HuggingFace Inc. 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 agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Finetuning seq2seq models for sequence generation.""" import argparse import functools import logging import os import random import sys sys.path.append(r'../') import numpy as np from tqdm import tqdm, trange import torch from torch.optim import Adam from torch.utils.data import DataLoader, RandomSampler, SequentialSampler from transformers import ( AutoTokenizer, BertForMaskedLM, BertConfig, PreTrainedEncoderDecoder, Model2Models, ) from utils_summarization import ( CNNDailyMailDataset, encode_for_summarization, fit_to_block_size, build_lm_labels, build_mask, compute_token_type_ids, ) from utils_chemistry import (ChemistryDataset,) ''' class InputExample(object): def __init__(self,example_id,question_input,question_varible_output=None,condition_output=None): self.example_id=example_id self.question_input=question_input self.question_varible_output=question_varible_output self.condition_output=condition_output ''' logger = logging.getLogger(__name__) logging.basicConfig(stream=sys.stdout, level=logging.INFO) # ------------ # Load dataset # ------------ def collate(data, tokenizer, input_block_size,output_block_size): """ List of tuple as an input. """ question_inputs=[] question_varible_outputs=[] condition_outputs=[] for i,example in enumerate(data): question_input=tokenizer.encode(example.question_input) question_input=fit_to_block_size(question_input, input_block_size, tokenizer.pad_token_id) question_inputs.append(question_input) if example.question_varible_output is not None: question_varible_output=tokenizer.encode(example.question_varible_output) else: question_varible_output=tokenizer.build_inputs_with_special_tokens([]) question_varible_output=fit_to_block_size(question_varible_output, output_block_size, tokenizer.pad_token_id) question_varible_outputs.append(question_varible_output) if example.condition_output is not None: condition_output=tokenizer.encode(example.condition_output) else: condition_output=tokenizer.build_inputs_with_special_tokens([]) condition_output=fit_to_block_size(condition_output, output_block_size, tokenizer.pad_token_id) condition_outputs.append(condition_output) question_inputs = torch.tensor(question_inputs) question_varible_outputs = torch.tensor(question_varible_outputs) condition_outputs = torch.tensor(condition_outputs) question_inputs_mask = build_mask(question_inputs, tokenizer.pad_token_id) question_varible_outputs_mask = build_mask(question_varible_outputs, tokenizer.pad_token_id) condition_outputs_mask = build_mask(condition_outputs, tokenizer.pad_token_id) question_varible_outputs_mask_lm_labels = build_lm_labels(question_varible_outputs, tokenizer.pad_token_id) condition_outputs_mask_lm_labels = build_lm_labels(condition_outputs, tokenizer.pad_token_id) return ( question_inputs, [question_varible_outputs,condition_outputs], question_inputs_mask, [question_varible_outputs_mask,condition_outputs_mask], [question_varible_outputs_mask_lm_labels,condition_outputs_mask_lm_labels], ) # ---------- # Optimizers # ---------- # ------------ # Train # ------------ def train(args, model, tokenizer): """ Fine-tune the pretrained model on the corpus. """ set_seed(args) # Load the data args.train_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu) train_dataset = load_and_cache_examples(args, tokenizer, "train") train_sampler = RandomSampler(train_dataset) model_collate_fn = functools.partial(collate, tokenizer=tokenizer, input_block_size=args.input_block_size,output_block_size=args.output_block_size) train_dataloader = DataLoader( train_dataset, sampler=train_sampler, batch_size=args.train_batch_size, collate_fn=model_collate_fn, ) # Training schedule if args.max_steps > 0: t_total = args.max_steps args.num_train_epochs = t_total // ( len(train_dataloader) // args.gradient_accumulation_steps + 1 ) else: t_total = ( len(train_dataloader) // args.gradient_accumulation_steps * args.num_train_epochs ) # Prepare the optimizer #lr = {"encoder": 0.002, "decoder": 0.2} lr = {"encoder": args.encoder_lr, "decoder": args.decoder_lr} #warmup_steps = {"encoder": 20000, "decoder": 10000} warmup_steps = {"encoder": args.encoder_warmup, "decoder": args.decoder_warmup} optimizer = BertSumOptimizer(model, lr, warmup_steps) # Train logger.info("***** Running training *****") logger.info(" Num examples = %d", len(train_dataset)) logger.info(" Num Epochs = %d", args.num_train_epochs) logger.info( " Instantaneous batch size per GPU = %d", args.per_gpu_train_batch_size ) logger.info( " Total train batch size (w. parallel, distributed & accumulation) = %d", args.train_batch_size * args.gradient_accumulation_steps # * (torch.distributed.get_world_size() if args.local_rank != -1 else 1), ) logger.info(" Gradient Accumulation steps = %d", args.gradient_accumulation_steps) logger.info(" Total optimization steps = %d", t_total) model.zero_grad() train_iterator = trange(args.num_train_epochs, desc="Epoch", disable=False) global_step = 0 tr_loss = 0.0 for _ in train_iterator: epoch_iterator = tqdm(train_dataloader, desc="Iteration", disable=False) for step, batch in enumerate(epoch_iterator): source, target, encoder_mask, decoder_mask, lm_labels = batch #print('source: {}'.format(source)) #print('target: {}'.format(target)) feed_source=None feed_targets=[None]*len(target) feed_encoder_mask=None feed_decoder_masks=[None]*len(decoder_mask) feed_lm_labels=[None]*len(lm_labels) feed_source = source.to(args.device) for i in range(len(target)): feed_targets[i] = target[i].to(args.device) feed_encoder_mask = encoder_mask.to(args.device) for i in range(len(decoder_mask)): feed_decoder_masks[i] = decoder_mask[i].to(args.device) for i in range(len(lm_labels)): feed_lm_labels[i] = lm_labels[i].to(args.device) model.train() #print('debug by zhuoyu: source = {}'.format(source)) #print('debug by zhuoyu: target = {}'.format(target)) #print('debug by zhuoyu, device:') #print('feed source {}'.format(feed_source.device)) #print('feed target {}'.format([str(feed_target.device) for feed_target in feed_targets])) #print('feed encoder mask {}'.format(feed_encoder_mask.device)) #print('feed decoder masks {}'.format([str(feed_decoder_mask.device) for feed_decoder_mask in feed_decoder_masks])) #print('feed lm labels {}'.format([str(feed_lm_label.device) for feed_lm_label in feed_lm_labels])) outputs = model( feed_source, feed_targets, encoder_attention_mask=feed_encoder_mask, decoder_attention_mask=feed_decoder_masks, decoder_lm_labels=feed_lm_labels, ) loss=0 for i in range(len(model.decoders)): #print('outputs[{}][0] type: {}'.format(i,type(outputs[i][0]))) loss += outputs[i][0] #print(loss) if args.gradient_accumulation_steps > 1: loss /= args.gradient_accumulation_steps loss.backward() tr_loss += loss.item() if (step + 1) % args.gradient_accumulation_steps == 0: torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm) optimizer.step() model.zero_grad() global_step += 1 if args.max_steps > 0 and global_step > args.max_steps: epoch_iterator.close() break if args.max_steps > 0 and global_step > args.max_steps: train_iterator.close() break return global_step, tr_loss / global_step # ------------ # Train # ------------ if __name__ == "__main__": main()
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 15069, 13130, 383, 12905, 2667, 32388, 3457, 13, 1074, 13, 198, 2, 15069, 357, 66, 8, 13130, 383, 12905, 2667, 32388, 3457, 13, 220, 1439, 2489, 10395, 13, 198, 2, 198, 2, 49962, 739, 262, 2484...
2.348189
3,949
from django.contrib.gis.gdal import DataSource from django.contrib.gis.utils import LayerMapping from django.core.management.base import BaseCommand from envergo.geodata.models import Zone
[ 6738, 42625, 14208, 13, 3642, 822, 13, 70, 271, 13, 21287, 282, 1330, 6060, 7416, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 70, 271, 13, 26791, 1330, 34398, 44, 5912, 198, 6738, 42625, 14208, 13, 7295, 13, 27604, 13, 8692, 1330, 7...
3.237288
59
from test.vim_test_case import VimTestCase as _VimTest from test.constant import * # Anonymous Expansion {{{# # End: Anonymous Expansion #}}}
[ 6738, 1332, 13, 31124, 62, 9288, 62, 7442, 1330, 36645, 14402, 20448, 355, 4808, 53, 320, 14402, 198, 6738, 1332, 13, 9979, 415, 1330, 1635, 198, 198, 2, 19200, 25042, 220, 22935, 90, 2, 628, 628, 628, 628, 628, 198, 2, 5268, 25, ...
3.163265
49
import discord from jshbot import utilities, data, configurations, plugins, logger from jshbot.exceptions import BotException, ConfiguredBotException from jshbot.commands import ( Command, SubCommand, Shortcut, ArgTypes, Attachment, Arg, Opt, MessageTypes, Response) __version__ = '0.1.0' CBException = ConfiguredBotException('0.3 to 0.4 plugin')
[ 11748, 36446, 198, 198, 6738, 474, 1477, 13645, 1330, 20081, 11, 1366, 11, 25412, 11, 20652, 11, 49706, 198, 6738, 474, 1477, 13645, 13, 1069, 11755, 1330, 18579, 16922, 11, 17056, 1522, 20630, 16922, 198, 6738, 474, 1477, 13645, 13, 95...
3.413462
104
from tkinter import * from PIL import Image, ImageTk #python image library #imagetk supports jpg image a1 = Tk() a1.geometry("455x244") #for png image #photo = PhotoImage(file="filename.png") #a2 = Label(image = photo) #a2.pack() image = Image.open("PJXlVd.jpg") photo = ImageTk.PhotoImage(image) a2 = Label(image = photo) a2.pack() a1.mainloop()
[ 6738, 256, 74, 3849, 1330, 1635, 201, 198, 6738, 350, 4146, 1330, 7412, 11, 7412, 51, 74, 201, 198, 2, 29412, 2939, 5888, 201, 198, 2, 48466, 316, 74, 6971, 474, 6024, 2939, 201, 198, 201, 198, 64, 16, 796, 309, 74, 3419, 201, 1...
2.280488
164
import os import torch from PIL import Image from read_csv import csv_to_label_and_bbx import numpy as np from torch.utils.data import Subset, random_split, ConcatDataset def split_index(K=5, len=100): idx = list(range(len)) final_list = [] for i in range(K): final_list.append(idx[(i*len)//K:((i+1)*len)//K]) return final_list def k_fold_index(K=5, len=100, fold=0): split = split_index(K, len) val = split[fold] train = [] for i in range(K): if i != fold: train = train + split[i] return train, val def stat_dataset(dataset): class_ids = {1: "A", 2: "B1", 3: "B2", 4: "B3"} stats = {"A": 0, "B1": 0, "B2": 0, "B3": 0} for img, target in dataset: for k in target['labels']: stats[class_ids[int(k)]] += 1 print(stats) def NBIFiveFoldDataset(transforms): ds = NBIFullDataset(root="./NBI_full_dataset/", transforms=transforms) # n = len(ds) # for i in range(5): # train_idx, val_idx = k_fold_index(5, n, i) # train_subset = Subset(ds, train_idx) # val_subset = Subset(ds, val_idx) # print("Fold: %d" % i, len(train_subset), len(val_subset)) # stat_dataset(train_subset) # stat_dataset(val_subset) torch.manual_seed(13) all_subsets = random_split(ds, [46, 46, 46, 45, 45]) fold_i_subsets = [] for i in range(5): val_subset = all_subsets[i] train_subset = ConcatDataset([all_subsets[j] for j in range(5) if j != i]) fold_i_subsets.append({"train": train_subset, "val": val_subset}) # print("Fold: %d" % i, len(train_subset), len(val_subset)) # stat_dataset(train_subset) # stat_dataset(val_subset) return fold_i_subsets if __name__ == '__main__': # ds = NBIFiveFoldDataset(None) di = "aaa".encode("UTF-8") result = eval(di) print(result)
[ 11748, 28686, 198, 11748, 28034, 198, 6738, 350, 4146, 1330, 7412, 198, 6738, 1100, 62, 40664, 1330, 269, 21370, 62, 1462, 62, 18242, 62, 392, 62, 11848, 87, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 28034, 13, 26791, 13, 7890, 1...
2.067686
916
# coding: utf-8 import functools if __name__ == '__main__': from timeit import Timer measure = [{'exec': 'fibonacci(100)', 'import': 'fibonacci', 'func': fibonacci}, {'exec': 'nsum(200)', 'import': 'nsum', 'func': nsum}] for m in measure: t = Timer('{}'.format(m['exec']), 'from __main__ import \ {}'.format(m['import'])) print('name: {}, doc: {}, executing: {}, time: \ {}'.format(m['func'].__name__, m['func'].__doc__, m['exec'], t.timeit()))
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 11748, 1257, 310, 10141, 628, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 422, 640, 270, 1330, 5045, 263, 198, 220, 220, 220, 3953, 796, 685, 90...
1.901316
304
from .transforms import *
[ 198, 6738, 764, 7645, 23914, 1330, 1635, 198 ]
3.375
8
# !\usr\bin\python import numpy as np from mpl_toolkits import mplot3d import matplotlib.pyplot as plt import scipy.optimize from matplotlib import animation from scipy.integrate import ode import pdb # Material parameters rho = 7800. E = 2.e11 nu = 0.3 mu = 0.5*E/(1.+nu) kappa = E/(3.*(1.-2.*nu)) lamb = kappa-2.*mu/3. sigy = 100.0e6 H = 100.08e6 beta=(6.*mu**2)/(3.*mu+H) from mpl_toolkits.mplot3d import proj3d proj3d.persp_transformation = orthogonal_proj Samples=5 # Sample constant stress component sig22 sig22=np.linspace(0.,sigy,Samples) #sig22=np.linspace(-sigy/np.sqrt(1-nu+nu**2),sigy/np.sqrt(1-nu+nu**2),Samples) Samples*=10 sig=np.zeros((Samples,Samples)) tau=np.zeros((Samples,Samples)) frames=[10,20,40] frames=[5,10,15,20] col=["r","g","b","y","c","m","k","p"] tauM=1.5*sigy/np.sqrt(3.) sigM=1.5*sigy/np.sqrt(1-nu+nu**2) tauM=sigM Niter=1000 TAU=np.zeros((Niter,len(frames),len(sig22))) SIG11=np.zeros((Niter,len(frames),len(sig22))) SIG22=np.zeros((Niter,len(frames),len(sig22))) eigsigS=np.zeros((Niter,len(frames),len(sig22),3)) criterionS=np.zeros((Niter,len(frames))) PsiS=np.zeros((Samples,len(sig22))) plast_S=np.zeros((Niter,len(frames))) LodeAngle_S=np.zeros((Niter,len(frames))) # Boolean to plot the upadted yield surface updated_criterion=False for k in range(len(sig22)-1): s22=sig22[k] Delta=(4.*sigy**2- 3.*s22**2) sigMax=(s22+np.sqrt(Delta))/2. sigMin=(s22-np.sqrt(Delta))/2. # Sample stress component sig11 sig[:,k]=np.linspace(sigMin,sigMax,Samples) sig[:,k]=np.linspace(0.,sigMax,Samples) # Compute shear stress satisfying the criterion given sig11 and sig22 for i in range(Samples): s11=sig[i,k] delta=(s11*s22 -s11**2-s22**2 + sigy**2)/3. if np.abs(delta)<10. : delta=np.abs(delta) tauMax=np.sqrt(delta) f_vm=lambda x:computeCriterion(s11,s22,x,0.,sigy) tau[i,k]=np.sqrt(delta) ## LOADING PATHS PLOTS for k in range(len(sig22)-1)[1:]: s22=sig22[k] sigM=1.25*np.max(sig[:,k]) tauM=1.25*np.max(tau[:,k]) ## For each value of sig22 trace the loading paths given by psis from yield surface to an arbitrary shear stress level approx=np.zeros((len(frames),2)) ordonnees=np.zeros((len(frames),Samples)) abscisses=np.zeros((len(frames),Samples)) radius_S=np.zeros(len(frames)) for s,i in enumerate(frames): if i==0: continue sig0=sig[-1-i,k] tau0=tau[-1-i,k] dsig=(sigM-sig0)/Niter SIG11[:,s,k]=np.linspace(sig0,sigM,Niter) TAU[0,s,k]=tau0 SIG22[0,s,k]=s22 #rSlow = ode(computePsiSlow).set_integrator('vode',method='bdf') rSlow = ode(computePsiSlow).set_integrator('vode',method='adams',order=12) rSlow.set_initial_value(np.array([TAU[0,s,k],SIG22[0,s,k]]),SIG11[0,s,k]).set_f_params(0.,lamb,mu,beta,'planeStress',rho) sigma = np.matrix([[SIG11[0,s,k],TAU[0,s,k],0.],[TAU[0,s,k],SIG22[0,s,k],0.],[0.,0.,0.]]) eigsig=np.linalg.eig(sigma)[0] eigsigS[0,s,k,:]=eigsig LodeAngle_S[0,s]=computeLodeAngle(sigma[0,0],SIG22[0,s,k],sigma[0,1],0.) p=0. epsp33=0. for j in range(Niter-1): rSlow.set_f_params(np.array([TAU[j,s,k],SIG22[j,s,k]]),0.,lamb,mu,beta,'planeStress',rho) if not rSlow.successful(): print "Integration issues in slow wave path" break rSlow.integrate(rSlow.t+dsig) TAU[j+1,s,k],SIG22[j+1,s,k]=rSlow.y sigma = np.array([SIG11[j,s,k],np.sqrt(2.)*TAU[j,s,k],SIG22[j,s,k],0.]) sigman = np.array([SIG11[j+1,s,k],np.sqrt(2.)*TAU[j+1,s,k],SIG22[j+1,s,k],0.]) f_vm=computeCriterion(SIG11[j+1,s,k],SIG22[j+1,s,k],TAU[j+1,s,k],0.,sigy+H*p) #if f_vm>0. : #p+=updateEquivalentPlasticStrain(sigma,sigman,H) #residual=lambda x: plasticResidual(sigma,sigman,p,x,H) residual=lambda x: computeCriterion(SIG11[j+1,s,k],SIG22[j+1,s,k],TAU[j+1,s,k],0.,sigy+H*x) p=scipy.optimize.root(residual,p,method='hybr',options={'xtol':1.e-12}).x[0] criterionS[j+1,s]=computeCriterion(SIG11[j+1,s,k],SIG22[j+1,s,k],TAU[j+1,s,k],0.,sigy+H*p) plast_S[j+1,s]=p LodeAngle_S[j+1,s]=computeLodeAngle(sigman[0],sigman[2],sigman[1]/np.sqrt(2.),0.) # Eigenvalues of sigma (for deviatoric plane plots) sigma = np.matrix([[SIG11[j+1,s,k],TAU[j+1,s,k],0.],[TAU[j+1,s,k],SIG22[j+1,s,k],0.],[0.,0.,0.]]) eigsigS[j+1,s,k,:]=computeEigenStresses(sigma) print "Final equivalent plastic strain after slow wave : ",p radius_S[s]=sigy+H*p TAU_MAX_S=np.max(ordonnees) SIG_MAX_S=np.max(abscisses) ### SUBPLOTS SETTINGS fig = plt.figure() ax2=plt.subplot2grid((1,2),(0,1),projection='3d') ax1d1=plt.subplot2grid((1,2),(0,0)) ax1d1.grid() ax1d1.set_xlabel(r'$\Theta$', fontsize=24) ax1d1.set_ylabel('p', fontsize=24) fvm1=ax1d1.twinx() fvm1.set_ylabel('f',fontsize=18.) fvm1.ticklabel_format(style='sci', axis='y', scilimits=(0,0)) cylindre=vonMisesYieldSurface(sigy) ax2.plot_wireframe(cylindre[0,:],cylindre[1,:],cylindre[2,:], color="k") elevation_Angle_radian=np.arctan(1./np.sqrt(2.0)) angle_degree= 180.*elevation_Angle_radian/np.pi radius=1.*np.sqrt((2./3.)*sigy**2) ax2.set_xlim(-1.*radius,1.*radius) ax2.set_ylim(-1.*radius,1.*radius) ax2.set_zlim(-1.*radius,1.*radius) ax2.view_init(angle_degree,45.) ax2.plot([0.,sigy],[0.,sigy],[0.,sigy],color="k") ax2.set_xlabel(r'$\sigma_1$',size=24.) ax2.set_ylabel(r'$\sigma_2$',size=24.) ax2.set_zlabel(r'$\sigma_3$',size=24.) for p in range(len(frames)): if updated_criterion : cylindre=vonMisesYieldSurface(radius_S[p]) ax2.plot_wireframe(cylindre[0,:],cylindre[1,:],cylindre[2,:], color=col[p],linestyle='--') ## 2D plot of equivalent plastic strain evolution ax1d1.plot(LodeAngle_S[:Niter/5,p],plast_S[:Niter/5,p],col[p]) #ax1d1_2.plot(LodeAngle_S[:Niter/5,p],SIG33_S[:Niter/5,p,k],col[p],marker='o') fvm1.plot(LodeAngle_S[:,p],criterionS[:,p],col[p],linestyle='--') ## 3D plots of loading paths (deviatoric plane) ax2.plot(eigsigS[:,p,k,0],eigsigS[:,p,k,1],eigsigS[:,p,k,2],color=col[p],marker="o") ax2.plot([-sigy,sigy],[0.,0.],[0.,0.],color="k",linestyle="--",lw=1.) ax2.plot([0.,0.],[-sigy,sigy],[0.,0.],color="k",linestyle="--",lw=1.) ax2.plot([-radius,radius],[radius,-radius],[0.,0.],color="k",linestyle="--",lw=1.) #plt.show() fig = plt.figure() ax1=plt.subplot2grid((1,2),(0,0)) ax2=plt.subplot2grid((1,2),(0,1)) ax1.set_xlabel(r'$\sigma_{11}$',size=28.) ax1.set_ylabel(r'$\sigma_{12}$',size=28.) #ax1.set_zlabel(r'$\sigma_{22}$',size=28.) ax2.set_xlabel(r'$\sigma_{22}$',size=28.) ax2.set_ylabel(r'$\sigma_{12}$',size=28.) #ax2.set_zlabel(r'$\sigma_{11}$',size=28.) ax1.grid() ax2.grid() #ax2.view_init(-90.,-0.) #ax1.view_init(-90.,0.) for s,i in enumerate(frames): sig0=sig[-1-i,k] s22max=(sig0+np.sqrt(4*sigy**2-3.*sig0**2))/2. s22min=(sig0-np.sqrt(4*sigy**2-3.*sig0**2))/2. s22=np.linspace(s22min,s22max,Samples) s12=np.sqrt((sigy**2- sig0**2-s22**2+sig0*s22)/3.) ax2.plot(s22,s12,color=col[s]) ax1.plot(sig[:,k],tau[:,k],'k') #ax2.plot(sig[:,k],tau[:,k],sig22[k],'k') for p in range(len(frames)): ax1.plot(SIG11[:,p,k],TAU[:,p,k],color=col[p]) ax2.plot(SIG22[:,p,k],TAU[:,p,k],color=col[p]) plt.show()
[ 2, 5145, 59, 14629, 59, 8800, 59, 29412, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 285, 489, 62, 25981, 74, 896, 1330, 285, 29487, 18, 67, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 629, 541, 88, ...
1.756866
4,442
# _*_ coding: utf-8 _*_ #@Time : 2020/7/29 09:49 #@Author : cherish_peng #@Email : 1058386071@qq.com #@File : connectionstate.py #@Software : PyCharm from enum import Enum
[ 2, 4808, 9, 62, 19617, 25, 3384, 69, 12, 23, 4808, 9, 62, 198, 2, 31, 7575, 220, 220, 220, 220, 220, 1058, 12131, 14, 22, 14, 1959, 220, 7769, 25, 2920, 198, 2, 31, 13838, 220, 220, 220, 1058, 48303, 62, 79, 1516, 198, 2, 31...
2.087912
91
# -*- coding: utf-8 -*- import time from datetime import datetime import warnings from textwrap import dedent, fill import numpy as np import pandas as pd from numpy.linalg import norm, inv from scipy.linalg import solve as spsolve, LinAlgError from scipy.integrate import trapz from scipy import stats from lifelines.fitters import BaseFitter, Printer from lifelines.plotting import set_kwargs_drawstyle from lifelines.statistics import chisq_test, proportional_hazard_test, TimeTransformers, StatisticalResult from lifelines.utils.lowess import lowess from lifelines.utils.concordance import _concordance_summary_statistics, _concordance_ratio from lifelines.utils import ( _get_index, _to_list, _to_tuple, _to_1d_array, inv_normal_cdf, normalize, qth_survival_times, coalesce, check_for_numeric_dtypes_or_raise, check_low_var, check_complete_separation, check_nans_or_infs, StatError, ConvergenceWarning, StatisticalWarning, StepSizer, ConvergenceError, string_justify, interpolate_at_times_and_return_pandas, CensoringType, interpolate_at_times, format_p_value, ) __all__ = ["CoxPHFitter"] def _partition_by_strata(self, X, T, E, weights, as_dataframes=False): for stratum, stratified_X in X.groupby(self.strata): stratified_E, stratified_T, stratified_W = (E.loc[[stratum]], T.loc[[stratum]], weights.loc[[stratum]]) if not as_dataframes: yield (stratified_X.values, stratified_T.values, stratified_E.values, stratified_W.values), stratum else: yield (stratified_X, stratified_T, stratified_E, stratified_W), stratum def _compute_scaled_schoenfeld(self, X, T, E, weights, index=None): r""" Let s_k be the kth schoenfeld residuals. Then E[s_k] = 0. For tests of proportionality, we want to test if \beta_i(t) is \beta_i (constant) or not. Let V_k be the contribution to the information matrix at time t_k. A main result from Grambsch and Therneau is that \beta(t) = E[s_k*V_k^{-1} + \hat{beta}] so define s_k^* = s_k*V_k^{-1} + \hat{beta} as the scaled schoenfeld residuals. We can approximate V_k with Hessian/d, so the inverse of Hessian/d is (d * variance_matrix_) Notes ------- lifelines does not add the coefficients to the final results, but R does when you call residuals(c, "scaledsch") """ n_deaths = self.event_observed.sum() scaled_schoenfeld_resids = n_deaths * self._compute_schoenfeld(X, T, E, weights, index).dot( self.variance_matrix_ ) scaled_schoenfeld_resids.columns = self.params_.index return scaled_schoenfeld_resids def _compute_schoenfeld_within_strata(self, X, T, E, weights): """ A positive value of the residual shows an X value that is higher than expected at that death time. """ # TODO: the diff_against is gross # This uses Efron ties. n, d = X.shape if not np.any(E): # sometimes strata have no deaths. This means nothing is returned # in the below code. return np.zeros((n, d)) # Init risk and tie sums to zero risk_phi, tie_phi = 0, 0 risk_phi_x, tie_phi_x = np.zeros((1, d)), np.zeros((1, d)) # Init number of ties and weights weight_count = 0.0 tie_count = 0 scores = weights * np.exp(np.dot(X, self.params_)) diff_against = [] schoenfeld_residuals = np.empty((0, d)) # Iterate backwards to utilize recursive relationship for i in range(n - 1, -1, -1): # Doing it like this to preserve shape ti = T[i] ei = E[i] xi = X[i : i + 1] score = scores[i : i + 1] w = weights[i] # Calculate phi values phi_i = score phi_x_i = phi_i * xi # Calculate sums of Risk set risk_phi = risk_phi + phi_i risk_phi_x = risk_phi_x + phi_x_i # Calculate sums of Ties, if this is an event diff_against.append((xi, ei)) if ei: tie_phi = tie_phi + phi_i tie_phi_x = tie_phi_x + phi_x_i # Keep track of count tie_count += 1 # aka death counts weight_count += w if i > 0 and T[i - 1] == ti: # There are more ties/members of the risk set continue elif tie_count == 0: for _ in diff_against: schoenfeld_residuals = np.append(schoenfeld_residuals, np.zeros((1, d)), axis=0) diff_against = [] continue # There was atleast one event and no more ties remain. Time to sum. weighted_mean = np.zeros((1, d)) for l in range(tie_count): numer = risk_phi_x - l * tie_phi_x / tie_count denom = risk_phi - l * tie_phi / tie_count weighted_mean += numer / (denom * tie_count) for xi, ei in diff_against: schoenfeld_residuals = np.append(schoenfeld_residuals, ei * (xi - weighted_mean), axis=0) # reset tie values tie_count = 0 weight_count = 0.0 tie_phi = 0 tie_phi_x = np.zeros((1, d)) diff_against = [] return schoenfeld_residuals[::-1] def _compute_delta_beta(self, X, T, E, weights, index=None): """ approximate change in betas as a result of excluding ith row. Good for finding outliers / specific subjects that influence the model disproportionately. Good advice: don't drop these outliers, model them. """ score_residuals = self._compute_score(X, T, E, weights, index=index) d = X.shape[1] scaled_variance_matrix = self.variance_matrix_ * np.tile(self._norm_std.values, (d, 1)).T delta_betas = score_residuals.dot(scaled_variance_matrix) delta_betas.columns = self.params_.index return delta_betas def compute_residuals(self, training_dataframe, kind): """ Parameters ---------- training_dataframe : pandas DataFrame the same training DataFrame given in `fit` kind : string {'schoenfeld', 'score', 'delta_beta', 'deviance', 'martingale', 'scaled_schoenfeld'} """ ALLOWED_RESIDUALS = {"schoenfeld", "score", "delta_beta", "deviance", "martingale", "scaled_schoenfeld"} assert kind in ALLOWED_RESIDUALS, "kind must be in %s" % ALLOWED_RESIDUALS warnings.filterwarnings("ignore", category=ConvergenceWarning) X, T, E, weights, shuffled_original_index, _ = self._preprocess_dataframe(training_dataframe) resids = getattr(self, "_compute_%s" % kind)(X, T, E, weights, index=shuffled_original_index) return resids def print_summary(self, decimals=2, **kwargs): """ Print summary statistics describing the fit, the coefficients, and the error bounds. Parameters ----------- decimals: int, optional (default=2) specify the number of decimal places to show kwargs: print additional metadata in the output (useful to provide model names, dataset names, etc.) when comparing multiple outputs. """ # Print information about data first justify = string_justify(25) headers = [] headers.append(("duration col", "'%s'" % self.duration_col)) if self.event_col: headers.append(("event col", "'%s'" % self.event_col)) if self.weights_col: headers.append(("weights col", "'%s'" % self.weights_col)) if self.cluster_col: headers.append(("cluster col", "'%s'" % self.cluster_col)) if self.penalizer > 0: headers.append(("penalizer", self.penalizer)) if self.robust or self.cluster_col: headers.append(("robust variance", True)) if self.strata: headers.append(("strata", self.strata)) headers.extend( [ ("number of observations", "{:g}".format(self.weights.sum())), ("number of events observed", "{:g}".format(self.weights[self.event_observed > 0].sum())), ("partial log-likelihood", "{:.{prec}f}".format(self.log_likelihood_, prec=decimals)), ("time fit was run", self._time_fit_was_called), ] ) p = Printer(headers, self, justify, decimals, kwargs) p.print() def log_likelihood_ratio_test(self): """ This function computes the likelihood ratio test for the Cox model. We compare the existing model (with all the covariates) to the trivial model of no covariates. """ if hasattr(self, "_ll_null_"): ll_null = self._ll_null_ else: if self._batch_mode: ll_null = self._trivial_log_likelihood_batch( self.durations.values, self.event_observed.values, self.weights.values ) else: ll_null = self._trivial_log_likelihood_single( self.durations.values, self.event_observed.values, self.weights.values ) ll_alt = self.log_likelihood_ test_stat = 2 * ll_alt - 2 * ll_null degrees_freedom = self.params_.shape[0] p_value = chisq_test(test_stat, degrees_freedom=degrees_freedom) return StatisticalResult( p_value, test_stat, name="log-likelihood ratio test", null_distribution="chi squared", degrees_freedom=degrees_freedom, ) def predict_partial_hazard(self, X): r""" Parameters ---------- X: numpy array or DataFrame a (n,d) covariate numpy array or DataFrame. If a DataFrame, columns can be in any order. If a numpy array, columns must be in the same order as the training data. Returns ------- partial_hazard: DataFrame Returns the partial hazard for the individuals, partial since the baseline hazard is not included. Equal to :math:`\exp{(x - mean(x_{train}))'\beta}` Notes ----- If X is a DataFrame, the order of the columns do not matter. But if X is an array, then the column ordering is assumed to be the same as the training dataset. """ return np.exp(self.predict_log_partial_hazard(X)) def predict_log_partial_hazard(self, X): r""" This is equivalent to R's linear.predictors. Returns the log of the partial hazard for the individuals, partial since the baseline hazard is not included. Equal to :math:`(x - \text{mean}(x_{\text{train}})) \beta` Parameters ---------- X: numpy array or DataFrame a (n,d) covariate numpy array or DataFrame. If a DataFrame, columns can be in any order. If a numpy array, columns must be in the same order as the training data. Returns ------- log_partial_hazard: DataFrame Notes ----- If X is a DataFrame, the order of the columns do not matter. But if X is an array, then the column ordering is assumed to be the same as the training dataset. """ hazard_names = self.params_.index if isinstance(X, pd.Series) and ((X.shape[0] == len(hazard_names) + 2) or (X.shape[0] == len(hazard_names))): X = X.to_frame().T return self.predict_log_partial_hazard(X) elif isinstance(X, pd.Series): assert len(hazard_names) == 1, "Series not the correct argument" X = X.to_frame().T return self.predict_log_partial_hazard(X) index = _get_index(X) if isinstance(X, pd.DataFrame): order = hazard_names X = X.reindex(order, axis="columns") X = X.astype(float) X = X.values X = X.astype(float) X = normalize(X, self._norm_mean.values, 1) return pd.DataFrame(np.dot(X, self.params_), index=index) def predict_cumulative_hazard(self, X, times=None, conditional_after=None): """ Parameters ---------- X: numpy array or DataFrame a (n,d) covariate numpy array or DataFrame. If a DataFrame, columns can be in any order. If a numpy array, columns must be in the same order as the training data. times: iterable, optional an iterable of increasing times to predict the cumulative hazard at. Default is the set of all durations (observed and unobserved). Uses a linear interpolation if points in time are not in the index. conditional_after: iterable, optional Must be equal is size to X.shape[0] (denoted `n` above). An iterable (array, list, series) of possibly non-zero values that represent how long the subject has already lived for. Ex: if :math:`T` is the unknown event time, then this represents :math`T | T > s`. This is useful for knowing the *remaining* hazard/survival of censored subjects. The new timeline is the remaining duration of the subject, i.e. reset back to starting at 0. Returns ------- cumulative_hazard_ : DataFrame the cumulative hazard of individuals over the timeline """ if isinstance(X, pd.Series): return self.predict_cumulative_hazard(X.to_frame().T, times=times, conditional_after=conditional_after) n = X.shape[0] if times is not None: times = np.atleast_1d(times).astype(float) if conditional_after is not None: conditional_after = _to_1d_array(conditional_after).reshape(n, 1) if self.strata: cumulative_hazard_ = pd.DataFrame() for stratum, stratified_X in X.groupby(self.strata): try: strata_c_0 = self.baseline_cumulative_hazard_[[stratum]] except KeyError: raise StatError( dedent( """The stratum %s was not found in the original training data. For example, try the following on the original dataset, df: `df.groupby(%s).size()`. Expected is that %s is not present in the output.""" % (stratum, self.strata, stratum) ) ) col = _get_index(stratified_X) v = self.predict_partial_hazard(stratified_X) times_ = coalesce(times, self.baseline_cumulative_hazard_.index) n_ = stratified_X.shape[0] if conditional_after is not None: times_to_evaluate_at = np.tile(times_, (n_, 1)) + conditional_after c_0_ = interpolate_at_times(strata_c_0, times_to_evaluate_at) c_0_conditional_after = interpolate_at_times(strata_c_0, conditional_after) c_0_ = np.clip((c_0_ - c_0_conditional_after).T, 0, np.inf) else: times_to_evaluate_at = np.tile(times_, (n_, 1)) c_0_ = interpolate_at_times(strata_c_0, times_to_evaluate_at).T cumulative_hazard_ = cumulative_hazard_.merge( pd.DataFrame(c_0_ * v.values[:, 0], columns=col, index=times_), how="outer", right_index=True, left_index=True, ) else: v = self.predict_partial_hazard(X) col = _get_index(v) times_ = coalesce(times, self.baseline_cumulative_hazard_.index) if conditional_after is not None: times_to_evaluate_at = np.tile(times_, (n, 1)) + conditional_after c_0 = interpolate_at_times(self.baseline_cumulative_hazard_, times_to_evaluate_at) c_0_conditional_after = interpolate_at_times(self.baseline_cumulative_hazard_, conditional_after) c_0 = np.clip((c_0 - c_0_conditional_after).T, 0, np.inf) else: times_to_evaluate_at = np.tile(times_, (n, 1)) c_0 = interpolate_at_times(self.baseline_cumulative_hazard_, times_to_evaluate_at).T cumulative_hazard_ = pd.DataFrame(c_0 * v.values[:, 0], columns=col, index=times_) return cumulative_hazard_ def predict_survival_function(self, X, times=None, conditional_after=None): """ Predict the survival function for individuals, given their covariates. This assumes that the individual just entered the study (that is, we do not condition on how long they have already lived for.) Parameters ---------- X: numpy array or DataFrame a (n,d) covariate numpy array or DataFrame. If a DataFrame, columns can be in any order. If a numpy array, columns must be in the same order as the training data. times: iterable, optional an iterable of increasing times to predict the cumulative hazard at. Default is the set of all durations (observed and unobserved). Uses a linear interpolation if points in time are not in the index. conditional_after: iterable, optional Must be equal is size to X.shape[0] (denoted `n` above). An iterable (array, list, series) of possibly non-zero values that represent how long the subject has already lived for. Ex: if :math:`T` is the unknown event time, then this represents :math`T | T > s`. This is useful for knowing the *remaining* hazard/survival of censored subjects. The new timeline is the remaining duration of the subject, i.e. normalized back to starting at 0. Returns ------- survival_function : DataFrame the survival probabilities of individuals over the timeline """ return np.exp(-self.predict_cumulative_hazard(X, times=times, conditional_after=conditional_after)) def predict_percentile(self, X, p=0.5, conditional_after=None): """ Returns the median lifetimes for the individuals, by default. If the survival curve of an individual does not cross 0.5, then the result is infinity. http://stats.stackexchange.com/questions/102986/percentile-loss-functions Parameters ---------- X: numpy array or DataFrame a (n,d) covariate numpy array or DataFrame. If a DataFrame, columns can be in any order. If a numpy array, columns must be in the same order as the training data. p: float, optional (default=0.5) the percentile, must be between 0 and 1. conditional_after: iterable, optional Must be equal is size to X.shape[0] (denoted `n` above). An iterable (array, list, series) of possibly non-zero values that represent how long the subject has already lived for. Ex: if :math:`T` is the unknown event time, then this represents :math`T | T > s`. This is useful for knowing the *remaining* hazard/survival of censored subjects. The new timeline is the remaining duration of the subject, i.e. normalized back to starting at 0. Returns ------- percentiles: DataFrame See Also -------- predict_median """ subjects = _get_index(X) return qth_survival_times(p, self.predict_survival_function(X, conditional_after=conditional_after)[subjects]).T def predict_median(self, X, conditional_after=None): """ Predict the median lifetimes for the individuals. If the survival curve of an individual does not cross 0.5, then the result is infinity. Parameters ---------- X: numpy array or DataFrame a (n,d) covariate numpy array or DataFrame. If a DataFrame, columns can be in any order. If a numpy array, columns must be in the same order as the training data. Returns ------- percentiles: DataFrame the median lifetimes for the individuals. If the survival curve of an individual does not cross 0.5, then the result is infinity. See Also -------- predict_percentile """ return self.predict_percentile(X, 0.5, conditional_after=conditional_after) def predict_expectation(self, X): r""" Compute the expected lifetime, :math:`E[T]`, using covariates X. This algorithm to compute the expectation is to use the fact that :math:`E[T] = \int_0^\inf P(T > t) dt = \int_0^\inf S(t) dt`. To compute the integral, we use the trapizoidal rule to approximate the integral. Caution -------- However, if the survival function doesn't converge to 0, the the expectation is really infinity and the returned values are meaningless/too large. In that case, using ``predict_median`` or ``predict_percentile`` would be better. Parameters ---------- X: numpy array or DataFrame a (n,d) covariate numpy array or DataFrame. If a DataFrame, columns can be in any order. If a numpy array, columns must be in the same order as the training data. Returns ------- expectations : DataFrame Notes ----- If X is a DataFrame, the order of the columns do not matter. But if X is an array, then the column ordering is assumed to be the same as the training dataset. See Also -------- predict_median predict_percentile """ subjects = _get_index(X) v = self.predict_survival_function(X)[subjects] return pd.DataFrame(trapz(v.values.T, v.index), index=subjects) def _compute_baseline_survival(self): """ Importantly, this agrees with what the KaplanMeierFitter produces. Ex: Example ------- >>> from lifelines.datasets import load_rossi >>> from lifelines import CoxPHFitter, KaplanMeierFitter >>> rossi = load_rossi() >>> kmf = KaplanMeierFitter() >>> kmf.fit(rossi['week'], rossi['arrest']) >>> rossi2 = rossi[['week', 'arrest']].copy() >>> rossi2['var1'] = np.random.randn(432) >>> cph = CoxPHFitter() >>> cph.fit(rossi2, 'week', 'arrest') >>> ax = cph.baseline_survival_.plot() >>> kmf.plot(ax=ax) """ survival_df = np.exp(-self.baseline_cumulative_hazard_) if not self.strata: survival_df = survival_df.rename(columns={"baseline cumulative hazard": "baseline survival"}) return survival_df def plot(self, columns=None, hazard_ratios=False, ax=None, **errorbar_kwargs): """ Produces a visual representation of the coefficients (i.e. log hazard ratios), including their standard errors and magnitudes. Parameters ---------- columns : list, optional specify a subset of the columns to plot hazard_ratios: bool, optional by default, `plot` will present the log-hazard ratios (the coefficients). However, by turning this flag to True, the hazard ratios are presented instead. errorbar_kwargs: pass in additional plotting commands to matplotlib errorbar command Examples --------- >>> from lifelines import datasets, CoxPHFitter >>> rossi = datasets.load_rossi() >>> cph = CoxPHFitter().fit(rossi, 'week', 'arrest') >>> cph.plot(hazard_ratios=True) Returns ------- ax: matplotlib axis the matplotlib axis that be edited. """ from matplotlib import pyplot as plt if ax is None: ax = plt.gca() errorbar_kwargs.setdefault("c", "k") errorbar_kwargs.setdefault("fmt", "s") errorbar_kwargs.setdefault("markerfacecolor", "white") errorbar_kwargs.setdefault("markeredgewidth", 1.25) errorbar_kwargs.setdefault("elinewidth", 1.25) errorbar_kwargs.setdefault("capsize", 3) z = inv_normal_cdf(1 - self.alpha / 2) user_supplied_columns = True if columns is None: user_supplied_columns = False columns = self.params_.index yaxis_locations = list(range(len(columns))) log_hazards = self.params_.loc[columns].values.copy() order = list(range(len(columns) - 1, -1, -1)) if user_supplied_columns else np.argsort(log_hazards) if hazard_ratios: exp_log_hazards = np.exp(log_hazards) upper_errors = exp_log_hazards * (np.exp(z * self.standard_errors_[columns].values) - 1) lower_errors = exp_log_hazards * (1 - np.exp(-z * self.standard_errors_[columns].values)) ax.errorbar( exp_log_hazards[order], yaxis_locations, xerr=np.vstack([lower_errors[order], upper_errors[order]]), **errorbar_kwargs ) ax.set_xlabel("HR (%g%% CI)" % ((1 - self.alpha) * 100)) else: symmetric_errors = z * self.standard_errors_[columns].values ax.errorbar(log_hazards[order], yaxis_locations, xerr=symmetric_errors[order], **errorbar_kwargs) ax.set_xlabel("log(HR) (%g%% CI)" % ((1 - self.alpha) * 100)) best_ylim = ax.get_ylim() ax.vlines(1 if hazard_ratios else 0, -2, len(columns) + 1, linestyles="dashed", linewidths=1, alpha=0.65) ax.set_ylim(best_ylim) tick_labels = [columns[i] for i in order] ax.set_yticks(yaxis_locations) ax.set_yticklabels(tick_labels) return ax def plot_covariate_groups(self, covariates, values, plot_baseline=True, **kwargs): """ Produces a plot comparing the baseline survival curve of the model versus what happens when a covariate(s) is varied over values in a group. This is useful to compare subjects' survival as we vary covariate(s), all else being held equal. The baseline survival curve is equal to the predicted survival curve at all average values in the original dataset. Parameters ---------- covariates: string or list a string (or list of strings) of the covariate(s) in the original dataset that we wish to vary. values: 1d or 2d iterable an iterable of the specific values we wish the covariate(s) to take on. plot_baseline: bool also display the baseline survival, defined as the survival at the mean of the original dataset. kwargs: pass in additional plotting commands. Returns ------- ax: matplotlib axis, or list of axis' the matplotlib axis that be edited. Examples --------- >>> from lifelines import datasets, CoxPHFitter >>> rossi = datasets.load_rossi() >>> cph = CoxPHFitter().fit(rossi, 'week', 'arrest') >>> cph.plot_covariate_groups('prio', values=np.arange(0, 15, 3), cmap='coolwarm') .. image:: images/plot_covariate_example1.png >>> # multiple variables at once >>> cph.plot_covariate_groups(['prio', 'paro'], values=[ >>> [0, 0], >>> [5, 0], >>> [10, 0], >>> [0, 1], >>> [5, 1], >>> [10, 1] >>> ], cmap='coolwarm') .. image:: images/plot_covariate_example2.png >>> # if you have categorical variables, you can do the following to see the >>> # effect of all the categories on one plot. >>> cph.plot_covariate_groups(['dummy1', 'dummy2', 'dummy3'], values=[[1, 0, 0], [0, 1, 0], [0, 0, 1]]) >>> # same as: >>> cph.plot_covariate_groups(['dummy1', 'dummy2', 'dummy3'], values=np.eye(3)) """ from matplotlib import pyplot as plt covariates = _to_list(covariates) n_covariates = len(covariates) values = np.asarray(values) if len(values.shape) == 1: values = values[None, :].T if n_covariates != values.shape[1]: raise ValueError("The number of covariates must equal to second dimension of the values array.") for covariate in covariates: if covariate not in self.params_.index: raise KeyError("covariate `%s` is not present in the original dataset" % covariate) set_kwargs_drawstyle(kwargs, "steps-post") if self.strata is None: axes = kwargs.pop("ax", None) or plt.figure().add_subplot(111) x_bar = self._norm_mean.to_frame().T X = pd.concat([x_bar] * values.shape[0]) if np.array_equal(np.eye(n_covariates), values): X.index = ["%s=1" % c for c in covariates] else: X.index = [", ".join("%s=%g" % (c, v) for (c, v) in zip(covariates, row)) for row in values] for covariate, value in zip(covariates, values.T): X[covariate] = value self.predict_survival_function(X).plot(ax=axes, **kwargs) if plot_baseline: self.baseline_survival_.plot(ax=axes, ls=":", color="k", drawstyle="steps-post") else: axes = [] for stratum, baseline_survival_ in self.baseline_survival_.iteritems(): ax = plt.figure().add_subplot(1, 1, 1) x_bar = self._norm_mean.to_frame().T for name, value in zip(_to_list(self.strata), _to_tuple(stratum)): x_bar[name] = value X = pd.concat([x_bar] * values.shape[0]) if np.array_equal(np.eye(len(covariates)), values): X.index = ["%s=1" % c for c in covariates] else: X.index = [", ".join("%s=%g" % (c, v) for (c, v) in zip(covariates, row)) for row in values] for covariate, value in zip(covariates, values.T): X[covariate] = value self.predict_survival_function(X).plot(ax=ax, **kwargs) if plot_baseline: baseline_survival_.plot( ax=ax, ls=":", label="stratum %s baseline survival" % str(stratum), drawstyle="steps-post" ) plt.legend() axes.append(ax) return axes def check_assumptions( self, training_df, advice=True, show_plots=False, p_value_threshold=0.01, plot_n_bootstraps=10, columns=None ): """ Use this function to test the proportional hazards assumption. See usage example at https://lifelines.readthedocs.io/en/latest/jupyter_notebooks/Proportional%20hazard%20assumption.html Parameters ----------- training_df: DataFrame the original DataFrame used in the call to ``fit(...)`` or a sub-sampled version. advice: boolean, optional display advice as output to the user's screen show_plots: boolean, optional display plots of the scaled schoenfeld residuals and loess curves. This is an eyeball test for violations. This will slow down the function significantly. p_value_threshold: float, optional the threshold to use to alert the user of violations. See note below. plot_n_bootstraps: in the plots displayed, also display plot_n_bootstraps bootstrapped loess curves. This will slow down the function significantly. columns: list, optional specify a subset of columns to test. Examples ---------- >>> from lifelines.datasets import load_rossi >>> from lifelines import CoxPHFitter >>> >>> rossi = load_rossi() >>> cph = CoxPHFitter().fit(rossi, 'week', 'arrest') >>> >>> cph.check_assumptions(rossi) Notes ------- The ``p_value_threshold`` is arbitrarily set at 0.01. Under the null, some covariates will be below the threshold (i.e. by chance). This is compounded when there are many covariates. Similarly, when there are lots of observations, even minor deviances from the proportional hazard assumption will be flagged. With that in mind, it's best to use a combination of statistical tests and eyeball tests to determine the most serious violations. References ----------- section 5 in https://socialsciences.mcmaster.ca/jfox/Books/Companion/appendices/Appendix-Cox-Regression.pdf, http://www.mwsug.org/proceedings/2006/stats/MWSUG-2006-SD08.pdf, http://eprints.lse.ac.uk/84988/1/06_ParkHendry2015-ReassessingSchoenfeldTests_Final.pdf """ if not training_df.index.is_unique: raise IndexError( "`training_df` index should be unique for this exercise. Please make it unique or use `.reset_index(drop=True)` to force a unique index" ) residuals = self.compute_residuals(training_df, kind="scaled_schoenfeld") test_results = proportional_hazard_test( self, training_df, time_transform=["rank", "km"], precomputed_residuals=residuals ) residuals_and_duration = residuals.join(training_df[self.duration_col]) counter = 0 n = residuals_and_duration.shape[0] for variable in self.params_.index.intersection(columns or self.params_.index): minumum_observed_p_value = test_results.summary.loc[variable, "p"].min() if np.round(minumum_observed_p_value, 2) > p_value_threshold: continue counter += 1 if counter == 1: if advice: print( fill( """The ``p_value_threshold`` is set at %g. Even under the null hypothesis of no violations, some covariates will be below the threshold by chance. This is compounded when there are many covariates. Similarly, when there are lots of observations, even minor deviances from the proportional hazard assumption will be flagged.""" % p_value_threshold, width=100, ) ) print() print( fill( """With that in mind, it's best to use a combination of statistical tests and visual tests to determine the most serious violations. Produce visual plots using ``check_assumptions(..., show_plots=True)`` and looking for non-constant lines. See link [A] below for a full example.""", width=100, ) ) print() test_results.print_summary() print() print() print( "%d. Variable '%s' failed the non-proportional test: p-value is %s." % (counter, variable, format_p_value(4)(minumum_observed_p_value)), end="\n\n", ) if advice: values = training_df[variable] value_counts = values.value_counts() n_uniques = value_counts.shape[0] # Arbitrary chosen 10 and 4 to check for ability to use strata col. # This should capture dichotomous / low cardinality values. if n_uniques <= 10 and value_counts.min() >= 5: print( fill( " Advice: with so few unique values (only {0}), you can include `strata=['{1}', ...]` in the call in `.fit`. See documentation in link [E] below.".format( n_uniques, variable ), width=100, ) ) else: print( fill( """ Advice 1: the functional form of the variable '{var}' might be incorrect. That is, there may be non-linear terms missing. The proportional hazard test used is very sensitive to incorrect functional forms. See documentation in link [D] below on how to specify a functional form.""".format( var=variable ), width=100, ), end="\n\n", ) print( fill( """ Advice 2: try binning the variable '{var}' using pd.cut, and then specify it in `strata=['{var}', ...]` in the call in `.fit`. See documentation in link [B] below.""".format( var=variable ), width=100, ), end="\n\n", ) print( fill( """ Advice 3: try adding an interaction term with your time variable. See documentation in link [C] below.""", width=100, ), end="\n\n", ) if show_plots: from matplotlib import pyplot as plt fig = plt.figure() # plot variable against all time transformations. for i, (transform_name, transformer) in enumerate(TimeTransformers().iter(["rank", "km"]), start=1): p_value = test_results.summary.loc[(variable, transform_name), "p"] ax = fig.add_subplot(1, 2, i) y = residuals_and_duration[variable] tt = transformer(self.durations, self.event_observed, self.weights)[self.event_observed.values] ax.scatter(tt, y, alpha=0.75) y_lowess = lowess(tt.values, y.values) ax.plot(tt, y_lowess, color="k", alpha=1.0, linewidth=2) # bootstrap some possible other lowess lines. This is an approximation of the 100% confidence intervals for _ in range(plot_n_bootstraps): ix = sorted(np.random.choice(n, n)) tt_ = tt.values[ix] y_lowess = lowess(tt_, y.values[ix]) ax.plot(tt_, y_lowess, color="k", alpha=0.30) best_xlim = ax.get_xlim() ax.hlines(0, 0, tt.max(), linestyles="dashed", linewidths=1) ax.set_xlim(best_xlim) ax.set_xlabel("%s-transformed time\n(p=%.4f)" % (transform_name, p_value), fontsize=10) fig.suptitle("Scaled Schoenfeld residuals of '%s'" % variable, fontsize=14) plt.tight_layout() plt.subplots_adjust(top=0.90) if advice and counter > 0: print( dedent( r""" --- [A] https://lifelines.readthedocs.io/en/latest/jupyter_notebooks/Proportional%20hazard%20assumption.html [B] https://lifelines.readthedocs.io/en/latest/jupyter_notebooks/Proportional%20hazard%20assumption.html#Bin-variable-and-stratify-on-it [C] https://lifelines.readthedocs.io/en/latest/jupyter_notebooks/Proportional%20hazard%20assumption.html#Introduce-time-varying-covariates [D] https://lifelines.readthedocs.io/en/latest/jupyter_notebooks/Proportional%20hazard%20assumption.html#Modify-the-functional-form [E] https://lifelines.readthedocs.io/en/latest/jupyter_notebooks/Proportional%20hazard%20assumption.html#Stratification """ ) ) if counter == 0: print("Proportional hazard assumption looks okay.")
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 640, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 11748, 14601, 198, 6738, 2420, 37150, 1330, 4648, 298, 11, 6070, 198, 11748, 299, 32152, 355, 45941, 198, 11748, ...
2.170056
18,688
""" Test configuration loading @author aevans """ import os from nlp_server.config import load_config def test_load_config(): """ Test loading a configuration """ current_dir = os.path.curdir test_path = os.path.sep.join([current_dir, 'data', 'test_config.json']) cfg = load_config.load_config(test_path) assert cfg is not None assert cfg.use_gpu is False
[ 37811, 198, 14402, 8398, 11046, 198, 198, 31, 9800, 257, 1990, 504, 198, 37811, 198, 198, 11748, 28686, 198, 198, 6738, 299, 34431, 62, 15388, 13, 11250, 1330, 3440, 62, 11250, 628, 198, 4299, 1332, 62, 2220, 62, 11250, 33529, 198, 22...
2.655405
148
import os, json, inspect import mimetypes from html2text import html2text from RestrictedPython import compile_restricted, safe_globals import RestrictedPython.Guards import frappe import frappe.utils import frappe.utils.data from frappe.website.utils import (get_shade, get_toc, get_next_link) from frappe.modules import scrub from frappe.www.printview import get_visible_columns import frappe.exceptions
[ 198, 11748, 28686, 11, 33918, 11, 10104, 198, 11748, 17007, 2963, 12272, 198, 6738, 27711, 17, 5239, 1330, 27711, 17, 5239, 198, 6738, 8324, 20941, 37906, 1330, 17632, 62, 49343, 11, 3338, 62, 4743, 672, 874, 198, 11748, 8324, 20941, 37...
3.411765
119