content
stringlengths
1
1.04M
input_ids
listlengths
1
774k
ratio_char_token
float64
0.38
22.9
token_count
int64
1
774k
# -*- coding: utf-8 -*- # # ----------------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies (Shanghai) Co. Ltd. All rights reserved. # # The MIT License (MIT) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # ----------------------------------------------------------------------------------- import sys sys.path.append("../src/hackathon") import datetime from hackathon.hack import HackathonManager from hackathon.hackathon_response import bad_request, precondition_failed, not_found, ok import unittest from hackathon.database.models import UserHackathonRel, Hackathon, Experiment from hackathon import app, RequiredFeature from mock import Mock, ANY, patch import mock
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 16529, 1783, 6329, 198, 2, 15069, 357, 66, 8, 5413, 4946, 21852, 357, 2484, 272, 20380, 8, 1766, 13, 12052, 13, 220, 1439, 2489, 10395, 13, 198, 2, 198, ...
4.048611
432
# Copyright (c) 2010, 2011 Diogo Becker # Distributed under the MIT License # See accompanying file LICENSE """ Dude output for experiments """ import utils import os import core import sys HEAD = '~'*80 HEAD2 = '~'*80 LINE = '-'*80 class PBar: """ A simple progress bar. Based on example at http://snippets.dzone.com/posts/show/5432 """
[ 2, 15069, 357, 66, 8, 3050, 11, 2813, 6031, 24076, 40765, 198, 2, 4307, 6169, 739, 262, 17168, 13789, 198, 2, 4091, 19249, 2393, 38559, 24290, 198, 198, 37811, 198, 35, 2507, 5072, 329, 10256, 198, 37811, 198, 11748, 3384, 4487, 198, ...
2.834646
127
#! /usr/bin/python3.7 # soh cah toa main()
[ 2, 0, 1220, 14629, 14, 8800, 14, 29412, 18, 13, 22, 628, 198, 2, 523, 71, 269, 993, 284, 64, 198, 12417, 3419 ]
1.913043
23
import os import subprocess from setuptools import setup from distutils.command.install import install as _install setup( name='curig', version='0.1', author="LIU Honghao", author_email="stein.h.liu@gmail.com", description="GPU version of NUFFT and Radio astronomy gridder package", packages=['curig'], package_dir={'curig': 'python/curagridder'}, package_data={'curig': ['libcurafft.so']}, url="https://github.com/HLSUD/CURIG", install_requires=['numpy', 'pycuda', 'six'], python_requires='>=3.6', zip_safe=False, include_package_data=True, cmdclass={'install': install}, )
[ 198, 11748, 28686, 198, 11748, 850, 14681, 198, 6738, 900, 37623, 10141, 1330, 9058, 198, 6738, 1233, 26791, 13, 21812, 13, 17350, 1330, 2721, 355, 4808, 17350, 628, 628, 198, 40406, 7, 198, 220, 220, 220, 1438, 11639, 22019, 328, 3256,...
2.578947
247
from timeit import default_timer
[ 6738, 640, 270, 1330, 4277, 62, 45016, 628 ]
4.25
8
# # Define a custom noise model to be used during execution of Qiskit Aer simulator # # Note: this custom definition is the same as the default noise model provided # The code is provided here for users to copy to their own file and customize from qiskit.providers.aer.noise import NoiseModel, ReadoutError from qiskit.providers.aer.noise import depolarizing_error, reset_error
[ 2, 198, 2, 2896, 500, 257, 2183, 7838, 2746, 284, 307, 973, 1141, 9706, 286, 1195, 1984, 270, 15781, 35375, 198, 2, 198, 198, 2, 5740, 25, 428, 2183, 6770, 318, 262, 976, 355, 262, 4277, 7838, 2746, 2810, 198, 2, 383, 2438, 318, ...
3.762376
101
#!/usr/bin/env python 3 import pika from QUANTAXIS.QAPubSub.base import base_ps from QUANTAXIS.QAPubSub.setting import (qapubsub_ip, qapubsub_password, qapubsub_port, qapubsub_user) ######### 生产者 ######### if __name__ == '__main__': import datetime p = publisher(exchange='z3') while True: print(1) p.pub('{}'.format(datetime.datetime.now()))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 513, 198, 11748, 279, 9232, 628, 198, 6738, 19604, 1565, 5603, 55, 1797, 13, 48, 2969, 549, 7004, 13, 8692, 1330, 2779, 62, 862, 198, 6738, 19604, 1565, 5603, 55, 1797, 13, 48, 2969, 549,...
2.050251
199
"""Test doit_tasks/file_search.py.""" from calcipy.doit_tasks.doit_globals import DG from calcipy.doit_tasks.file_search import find_project_files_by_suffix def test_find_project_files_by_suffix(): """Test find_project_files_by_suffix.""" result = find_project_files_by_suffix(DG.meta.path_project, DG.meta.ignore_patterns) assert len(result) != 0, f'Error: see {DG.meta.path_project}/README.md for configuring the directory' assert [*result.keys()] == ['yml', 'toml', '', 'md', 'yaml', 'py', 'ini', 'lock', 'json'] assert result[''][0].name == '.flake8' assert result[''][2].name == 'LICENSE' assert result['md'][0].relative_to(DG.meta.path_project).as_posix() == '.github/ISSUE_TEMPLATE/bug_report.md'
[ 37811, 14402, 466, 270, 62, 83, 6791, 14, 7753, 62, 12947, 13, 9078, 526, 15931, 198, 198, 6738, 42302, 541, 88, 13, 4598, 270, 62, 83, 6791, 13, 4598, 270, 62, 4743, 672, 874, 1330, 46133, 198, 6738, 42302, 541, 88, 13, 4598, 270...
2.503401
294
import http import pathlib import pytest import requests from django.utils import timezone from jcasts.episodes.factories import EpisodeFactory from jcasts.episodes.models import Episode from jcasts.podcasts.factories import CategoryFactory, PodcastFactory from jcasts.podcasts.models import Podcast from jcasts.podcasts.parsers import feed_parser from jcasts.podcasts.parsers.date_parser import parse_date
[ 11748, 2638, 198, 11748, 3108, 8019, 198, 198, 11748, 12972, 9288, 198, 11748, 7007, 198, 198, 6738, 42625, 14208, 13, 26791, 1330, 640, 11340, 198, 198, 6738, 474, 40924, 13, 538, 8052, 13, 22584, 1749, 1330, 7922, 22810, 198, 6738, 47...
3.663717
113
# -*- coding: utf-8 -*- # # Copyright (C) 2020 Grzegorz Jacenków. # # 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. """Additional losses.""" import tensorflow as tf from tensorflow.keras import backend as K from tensorflow.keras.losses import Loss class DiceLoss(Loss): """Implements binary Dice loss function.""" @tf.function class MeanPrediction(Loss): """Implements mean of predictions as a loss function.""" @tf.function
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 15069, 357, 34, 8, 12131, 1902, 89, 1533, 273, 89, 8445, 268, 74, 10205, 86, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, ...
3.398551
276
from stable_baselines.common.cmd_util import make_atari_env from stable_baselines import SAC from stable_baselines.sac.policies import FeedForwardPolicy as SACPolicy from stable_baselines.common.policies import register_policy import tensorflow as tf import gym # There already exists an environment generator # that will make and wrap atari environments correctly env = gym.make("MountainCarContinuous-v0") register_policy('CustomSACPolicy', CustomSACPolicy) model = SAC('CustomSACPolicy', env, verbose=1) model.learn(total_timesteps=10000) obs = env.reset() for i in range(10000): action, _states = model.predict(obs) obs, rewards, dones, info = env.step(action) env.render() # Close the processes env.close()
[ 6738, 8245, 62, 12093, 20655, 13, 11321, 13, 28758, 62, 22602, 1330, 787, 62, 35554, 62, 24330, 198, 6738, 8245, 62, 12093, 20655, 1330, 311, 2246, 198, 6738, 8245, 62, 12093, 20655, 13, 30584, 13, 79, 4160, 444, 1330, 18272, 39746, 3...
3.231111
225
"""A selection of utilities to allow for fast scanning of a mol file""" from __future__ import generators import re def molSplitter(file): """(file) -> for m in molSplitter(file) ... do something with mol""" lines = [] for line in file: if line.find("$$$$") == 0: yield "\n".join(lines) lines = [] else: lines.append(line) FIELDPAT = re.compile(">\s+<([^>]+)>\s+\(*([^)]*)")
[ 37811, 32, 6356, 286, 20081, 284, 1249, 329, 3049, 21976, 286, 257, 18605, 198, 7753, 37811, 198, 6738, 11593, 37443, 834, 1330, 27298, 198, 11748, 302, 198, 198, 4299, 18605, 26568, 1967, 7, 7753, 2599, 198, 220, 220, 220, 13538, 18109...
2.338624
189
# Copyright (c) 2013, summayya and contributors # For license information, please see license.txt import frappe from frappe import _, _dict # def get_data(filters): # company = filters.company # data = frappe.db.sql(f"""SELECT account, balance from `tabGL Entry` where company = \'{company}\'""") # return data # def get_chart(): # chart = { # "data": { # 'labels': ["2020-21"], # "data": [22,45,67,456,23,46,23] # } # } # chart["type"] = "bar" # chart["fieldtype"] = "Currency"
[ 2, 15069, 357, 66, 8, 2211, 11, 2160, 11261, 3972, 290, 20420, 198, 2, 1114, 5964, 1321, 11, 3387, 766, 5964, 13, 14116, 198, 198, 11748, 5306, 27768, 198, 6738, 5306, 27768, 1330, 4808, 11, 4808, 11600, 628, 628, 198, 2, 825, 651, ...
2.49505
202
from coreapp.models import * from datetime import datetime, date, timedelta from django.contrib.auth.models import Group, User, Permission import pytz india_timezone = pytz.timezone('Asia/Kolkata') #india_timezone.localize(datetime.strptime('Sep 1 2017 12:01AM', '%b %d %Y %I:%M%p'))
[ 6738, 4755, 1324, 13, 27530, 1330, 1635, 198, 6738, 4818, 8079, 1330, 4818, 8079, 11, 3128, 11, 28805, 12514, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 4912, 11, 11787, 11, 2448, 3411, 198, 11748, 12972, 22877,...
2.733333
105
#!/usr/bin/env python3 import logging import csv
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 18931, 198, 11748, 269, 21370 ]
2.882353
17
#!/usr/bin/env python3 import asyncio import nemo import helper import config import discord from discord.ext.commands import has_permissions number_emojis = ["1⃣", "2⃣", "3⃣", "4⃣", "5⃣", "6⃣", "7⃣", "8⃣", "9⃣"] nemo = nemo.Nemo() @nemo.command("!") @has_permissions(administrator=True) @nemo.command("!help") @has_permissions(administrator=True) @helper.auto_delete @nemo.reaction(lambda reaction, member: reaction.message.author.bot and config.LIST_KEY in reaction.message.content) @nemo.reaction(lambda reaction, member: reaction.message.author.bot and config.CREATE_KEY in reaction.message.content) @nemo.command("!close") @nemo.command("!stop") @helper.event_command @helper.organizer_only @nemo.command("!open") @helper.event_command @helper.organizer_only @helper.auto_delete @nemo.command("!leave") @helper.event_command @helper.auto_delete @nemo.command("!private") @helper.event_command @helper.auto_delete @nemo.command("!name") @helper.event_command @helper.auto_delete @nemo.command("!invite") @helper.event_command @helper.auto_delete @nemo.command("!kick") @helper.event_command @helper.auto_delete @nemo.command("!colab") @helper.event_command @helper.auto_delete if __name__ == "__main__": nemo.run(config.TOKEN)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 11748, 30351, 952, 198, 198, 11748, 36945, 78, 198, 11748, 31904, 198, 11748, 4566, 198, 11748, 36446, 198, 6738, 36446, 13, 2302, 13, 9503, 1746, 1330, 468, 62, 525, 8481, 198, 19...
2.511905
504
import setuptools with open("README.md", "r") as fh: long_description = fh.read() requirements = ["beancount","pandas"] setuptools.setup( name="beancount2dataframe", version="0.0.1", author="Dmitri Kourbatsky", author_email="camel109@gmail.com", decription="pandas driver to load and read beancount records", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/dimonf/beancount2dataframe.git", # packages = setuptools.find_packages(), packages = ['beancount2dataframe'], package_dir={'beancount2dataframe':'src'}, classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], python_requires='>=3.6', install_requires=requirements, )
[ 11748, 900, 37623, 10141, 198, 198, 4480, 1280, 7203, 15675, 11682, 13, 9132, 1600, 366, 81, 4943, 355, 277, 71, 25, 198, 220, 220, 220, 890, 62, 11213, 796, 277, 71, 13, 961, 3419, 198, 198, 8897, 18883, 796, 14631, 1350, 1192, 608...
2.318296
399
#!/usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging from tempfile import NamedTemporaryFile from unittest.mock import patch from ax.utils.common.logger import build_file_handler, get_logger from ax.utils.common.testutils import TestCase BASE_LOGGER_NAME = f"ax.{__name__}"
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 15069, 357, 66, 8, 30277, 19193, 82, 11, 3457, 13, 290, 29116, 13, 198, 2, 198, 2, 770, 2723, 2438, 318, 11971, 739, 262, 17168, 5964, 1043, 287, 262, 198, 2, 38559, 24290, ...
3.356061
132
from enum import Enum
[ 6738, 33829, 1330, 2039, 388, 628 ]
3.833333
6
import re size = [] with open("allSize.txt") as inFile: for line in inFile: z = re.match(r'(.*)T ', line) if z: # print((z.groups())) # print z.group()[:-2] size.append(float(z.group()[:-2])) print sum(size)
[ 11748, 302, 198, 198, 7857, 796, 17635, 198, 4480, 1280, 7203, 439, 10699, 13, 14116, 4943, 355, 287, 8979, 25, 198, 220, 329, 1627, 287, 287, 8979, 25, 198, 220, 220, 220, 1976, 796, 302, 13, 15699, 7, 81, 6, 7, 15885, 8, 51, 4...
2.096491
114
# Lint as: python3 # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://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. """Tests for pyiree.tf.support.tf_utils.""" import os import tempfile from absl.testing import parameterized from pyiree.tf.support import tf_utils import tensorflow as tf if __name__ == '__main__': tf.test.main()
[ 2, 406, 600, 355, 25, 21015, 18, 198, 2, 15069, 12131, 3012, 11419, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351,...
3.480851
235
import json data = None with open('sparql_result.json', 'r') as f: data = json.load(f) print(data['head']) food_ids_list = data['results']['bindings'] ids = [] for doc in food_ids_list: current_id = doc['id']['value'] ids.append(current_id) print(len(ids)) f = open('article_ids.csv', 'w') with f: for i in range(len(ids) -1): f.write(ids[i] + ',\n') f.write(ids[len(ids) -1] + '\n')
[ 11748, 33918, 198, 198, 7890, 796, 6045, 198, 4480, 1280, 10786, 82, 1845, 13976, 62, 20274, 13, 17752, 3256, 705, 81, 11537, 355, 277, 25, 198, 220, 220, 220, 1366, 796, 33918, 13, 2220, 7, 69, 8, 198, 198, 4798, 7, 7890, 17816, ...
2.154639
194
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Mon Jun 4 19:25:01 2018 @author: francesco """ import numpy as np import time from izi.izi import izi import matplotlib.pyplot as plt plt.ion() timestart = time.process_time() #%% #THIS IS THE TEST data shown in Fig 1 of Blanc et al., 2015 #fluxes from HII region NGC0925 +087 -031 from Table 3 #of Van Zee et al. 1998, ApJ, 116, 2805 #TOP PANEL (ALL LINES) flux=[3.44,2.286, 1, 0.553, 0.698, 2.83] error=[0.17, 0.07,0.05, 0.023, 0.027, 0.15] id=['oii3726;oii3729','oiii4959;oiii5007', 'hbeta' , 'nii6548;nii6584', \ 'sii6717;sii6731', 'halpha'] out2=izi(flux, error, id,\ intergridfile='interpolgrid_50_50d13_kappa20', epsilon=0.1, quiet=False, plot=True) #%% #SECOND PANEL from top ([OIII], [OII], Hb) flux=[3.44,2.286, 1] error=[0.17, 0.07,0.05] id=['oii3726;oii3729','oiii4959;oiii5007', 'hbeta' ] out2=izi(flux, error, id,\ intergridfile='interpolgrid_50_50d13_kappa20', epsilon=0.1, quiet=False, plot=True) #%% #THIRD PANEL from top ([NII], [OII]) flux=[3.44,0.553] error=[0.17, 0.023] id=['oii3726;oii3729', 'nii6548;nii6584'] out2=izi(flux, error, id,\ intergridfile='interpolgrid_50_50d13_kappa20', epsilon=0.1, quiet=False, plot=True) #BOTTOM PANEL ([NII], Ha) flux=[0.553, 2.83] error=[0.023, 0.15] id=[ 'nii6548;nii6584', 'halpha'] out2=izi(flux, error, id,\ intergridfile='interpolgrid_50_50d13_kappa20', epsilon=0.1, quiet=False, plot=True) print('Elapsed time: {0} seconds'.format(time.process_time() - timestart))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 17, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 2892, 7653, 220, 604, 678, 25, 1495, 25, 486, 2864, 198, 198, 31, 9800, 25, 1216, 1817, ...
2.04047
766
""" Dynamic Edge-Conditioned Filters in Convolutional Neural Networks on Graphs https://github.com/mys007/ecc https://arxiv.org/abs/1704.02901 2017 Martin Simonovsky """ from __future__ import division from __future__ import print_function from builtins import range import torch import torch.nn as nn from torch.autograd import Variable, Function from .GraphConvInfo import GraphConvInfo from . import cuda_kernels from . import utils class GraphConvFunction(Function): """ Computes operations for each edge and averages the results over respective nodes. The operation is either matrix-vector multiplication (for 3D weight tensors) or element-wise vector-vector multiplication (for 2D weight tensors). The evaluation is computed in blocks of size `edge_mem_limit` to reduce peak memory load. See `GraphConvInfo` for info on `idxn, idxe, degs`. """ def _multiply(self, a, b, out, f_a=None, f_b=None): """ Performs operation on edge weights and node signal """ if self._full_weight_mat: # weights are full in_channels x out_channels matrices -> mm torch.bmm(f_a(a) if f_a else a, f_b(b) if f_b else b, out=out) else: # weights represent diagonal matrices -> mul torch.mul(a, b.expand_as(a), out=out) class GraphConvModule(nn.Module): """ Computes graph convolution using filter weights obtained from a filter generating network (`filter_net`). The input should be a 2D tensor of size (# nodes, `in_channels`). Multiple graphs can be concatenated in the same tensor (minibatch). Parameters: in_channels: number of input channels out_channels: number of output channels filter_net: filter-generating network transforming a 2D tensor (# edges, # edge features) to (# edges, in_channels*out_channels) or (# edges, in_channels) gc_info: GraphConvInfo object containing graph(s) structure information, can be also set with `set_info()` method. edge_mem_limit: block size (number of evaluated edges in parallel) for convolution evaluation, a low value reduces peak memory. """ class GraphConvModulePureAutograd(nn.Module): """ Autograd-only equivalent of `GraphConvModule` + `GraphConvFunction`. Unfortunately, autograd needs to store intermediate products, which makes the module work only for very small graphs. The module is kept for didactic purposes only. """
[ 37811, 201, 198, 220, 220, 220, 26977, 13113, 12, 48362, 276, 7066, 1010, 287, 34872, 2122, 282, 47986, 27862, 319, 29681, 82, 201, 198, 220, 220, 220, 3740, 1378, 12567, 13, 785, 14, 28744, 25816, 14, 68, 535, 201, 198, 220, 220, 2...
2.935294
850
""" Feature Store Dataclass ----------------------- This dataclass provides a unified interface to access Feast methods from within a feature store. """ import os from dataclasses import dataclass from datetime import datetime from typing import Any, Dict, List, Optional, Union import pandas as pd from dataclasses_json import dataclass_json from feast import FeatureStore as FeastFeatureStore from feast.entity import Entity from feast.feature_service import FeatureService from feast.feature_view import FeatureView from feast.infra.offline_stores.file import FileOfflineStoreConfig from feast.infra.online_stores.sqlite import SqliteOnlineStoreConfig from feast.repo_config import RepoConfig from flytekit import FlyteContext from flytekit.configuration import aws @dataclass_json @dataclass @dataclass_json @dataclass
[ 37811, 198, 38816, 9363, 16092, 330, 31172, 198, 19351, 6329, 198, 198, 1212, 4818, 330, 31172, 3769, 257, 22706, 7071, 284, 1895, 42936, 5050, 422, 1626, 257, 3895, 3650, 13, 220, 198, 37811, 198, 198, 11748, 28686, 198, 6738, 4818, 33...
3.743243
222
############### functions for borg # functions # by tatan ############### from termcolor import colored, cprint import colorama import random colorama.init() larrow = colored('>', 'green', attrs=['bold']) # for user input actmessages = colored('\nCurrently available actions:', 'green', attrs=['bold']) def plinput(): """Requests player input (for commands).""" print('\n{}'.format(larrow), end='\0') r = input() return r def dacts(m): """Displays available commands (given by the only parameter).""" if m == None: cprint('\nNo actions are available!', 'red', attrs=['bold']) else: print(actmessages, end='\0') print('{}.'.format(m)) def borg(mtrue, mfalse): """Function for various situations. The parameters are the returned messages for each case.""" chance = random.randint(1, 2) if chance == 1: cprint('\n{}'.format(mtrue), 'green', attrs=['bold']) return 1 elif chance == 2: cprint('\n{}'.format(mfalse), 'red', attrs=['bold']) return 2 if __name__ == "__main__": cprint('This file is for borg.py, if you\'re trying to run the game then run that script.', attrs=['bold']) exit()
[ 7804, 4242, 21017, 197, 197, 12543, 2733, 329, 275, 2398, 198, 2, 220, 5499, 220, 1303, 197, 197, 1525, 256, 39036, 198, 7804, 4242, 21017, 198, 6738, 3381, 8043, 1330, 16396, 11, 269, 4798, 198, 11748, 3124, 1689, 198, 11748, 4738, 1...
2.789604
404
import os import sys import logging import argparse import urllib import csv import utils import subprocess if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--name', required=True, dest='name', help='name package', default=None) parser.add_argument('--version', required=True, dest='version', help='version package fixed', default=None) parser.add_argument('--depends', required=True, dest='depends', help='json for save versions', default=None) parameters = parser.parse_args() depends_file = parameters.depends if os.path.exists(depends_file): data = utils.deserialize(depends_file) else: data = {} # serialize if is new data if parameters.name not in data: data[parameters.name] = parameters.version logging.info('serialize data = %s' % data) depends_file_tmp = depends_file + '.tmp' utils.serialize(data, depends_file_tmp) ret = subprocess.call('python -m json.tool %s > %s' % (depends_file_tmp, depends_file), shell=True) os.remove(depends_file_tmp) sys.exit(ret)
[ 11748, 28686, 198, 11748, 25064, 198, 11748, 18931, 198, 11748, 1822, 29572, 198, 11748, 2956, 297, 571, 198, 11748, 269, 21370, 198, 11748, 3384, 4487, 198, 11748, 850, 14681, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, ...
2.805128
390
import cv2 import numpy as np import glob file_array = [] img_array = [] for filename in glob.glob('./Diagnostics/local/Ratio/mass400/dist_function/IAT_E2_f1D_*.png'): file_array.append(filename) file_array.sort() for filename in file_array[:]: img = cv2.imread(filename) height, width, layers = img.shape size = (width,height) img_array.append(img) out = cv2.VideoWriter('./output_video_e2_1d.mp4',cv2.VideoWriter_fourcc(*'DIVX'), 5, size) for image in img_array: out.write(image) cv2.destroyAllWindows() out.release()
[ 11748, 269, 85, 17, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 15095, 198, 198, 7753, 62, 18747, 796, 17635, 198, 9600, 62, 18747, 796, 17635, 198, 1640, 29472, 287, 15095, 13, 4743, 672, 7, 4458, 14, 18683, 4660, 34558, 14, 1200...
2.427313
227
#!/usr/bin/env python # -*- coding: utf-8 -*- import scipy import scipy.linalg from pyss.mpi.util.operation import hv def rayleigh_ritz(p, a, b, cv, comm, left=False, right=True, check_finite=True, homogeneous_eigvals=False): """ Rayleigh-Ritz Procedure using MPI parallelism. Parameters ---------- p : (M, n) array_like Semi-unitary matrix. a : (M, M) array_like A complex or real matrix whose eigenvalues and eigenvectors will be computed. b : (M, M) array_like, optional Right-hand side matrix in a generalized eigenvalue problem. Default is None, identity matrix is assumed. cv : Callable object with type `cv(c: (M, M) array_like, v: ndarray, scomm: MPI_Comm) -> ndarray`. The function of multiplying of matrix `c` and matrix `v` on `scomm`, where `v` is ndarray with shape (M / rank, l) on each node of `scomm`. The return value of `cv` should be a ndarray, and with the same shape of `v`. left : bool, optional Whether to calculate and return left eigenvectors. Default is False. right : bool, optional Whether to calculate and return right eigenvectors. Default is True. check_finite : bool, optional Whether to check that the input matrices contain only finite numbers. Disabling may give a performance gain, but may result in problems (crashes, non-termination) if the inputs do contain infinities or NaNs. homogeneous_eigvals : bool, optional If True, return the eigenvalues in homogeneous coordinates. In this case w is a (2, M) array so that: `w[1,i] a vr[:,i] = w[0,i] b vr[:,i]` Default is False. Returns ------- w : (M,) or (2, M) double or complex ndarray The eigenvalues, each repeated according to its multiplicity. The shape is (M,) unless `homogeneous_eigvals=True`. vl : (M, M) double or complex ndarray The normalized left eigenvector corresponding to the eigenvalue `w[i]` is the column `vl[:,i]`. Only returned if `left=True`. vr : (M, M) double or complex ndarray The normalized right eigenvector corresponding to the eigenvalue `w[i]` is the column `vr[:,i]`. Only returned if `right=True`. Raises: ------- LinAlgError If eigenvalue computation does not converge. """ # Calculate (P^H A P) explicitly l = hv(p.T.conj(), cv(a, p, comm), comm) # Calculate (P^H B P) explicitly m = hv(p.T.conj(), cv(b, p, comm), comm) overwrite_a = False overwrite_b = False w, v = scipy.linalg.eig(l, m, left, right, overwrite_a, overwrite_b, check_finite, homogeneous_eigvals) return w, v
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 629, 541, 88, 198, 11748, 629, 541, 88, 13, 75, 1292, 70, 198, 6738, 12972, 824, 13, 3149, 72, 13, 2260...
2.43316
1,152
# Generated by Django 3.1 on 2021-02-19 14:05 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 16, 319, 33448, 12, 2999, 12, 1129, 1478, 25, 2713, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.966667
30
# -*- coding: utf-8 -*- # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # 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 os from lor import util, workspace from lor.generator import Generator
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13...
3.702857
175
''' Please Pass the Coded Messages ============================== You need to pass a message to the bunny prisoners, but to avoid detection, the code you agreed to use is... obscure, to say the least. The bunnies are given food on standard-issue prison plates that are stamped with the numbers 0-9 for easier sorting, and you need to combine sets of plates to create the numbers in the code. The signal that a number is part of the code is that it is divisible by 3. You can do smaller numbers like 15 and 45 easily, but bigger numbers like 144 and 414 are a little trickier. Write a program to help yourself quickly create large numbers for use in the code, given a limited number of plates to work with. You have L, a list containing some digits (0 to 9). Write a function solution(L) which finds the largest number that can be made from some or all of these digits and is divisible by 3. If it is not possible to make such a number, return 0 as the solution. L will contain anywhere from 1 to 9 digits. The same digit may appear multiple times in the list, but each element in the list may only be used once. Languages ========= To provide a Java solution, edit Solution.java To provide a Python solution, edit solution.py Test cases ========== Your code should pass the following test cases. Note that it may also be run against hidden test cases not shown here. -- Java cases -- Input: Solution.solution({3, 1, 4, 1}) Output: 4311 Input: Solution.solution({3, 1, 4, 1, 5, 9}) Output: 94311 -- Python cases -- Input: solution.solution([3, 1, 4, 1]) Output: 4311 Input: solution.solution([3, 1, 4, 1, 5, 9]) Output: 94311 Use verify [file] to test your solution and see how it does. When you are finished editing your code, use submit [file] to submit your answer. If your solution passes the test cases, it will be removed from your home folder. ''' from itertools import permutations #Input: print(solution([3, 1, 4, 1])) # Output: # 4311 # Input: print(solution([3, 1, 4, 1, 5, 9])) # Output: # 94311
[ 7061, 6, 198, 5492, 6251, 262, 327, 9043, 43534, 198, 4770, 25609, 855, 198, 198, 1639, 761, 284, 1208, 257, 3275, 284, 262, 44915, 10577, 11, 475, 284, 3368, 13326, 11, 262, 2438, 345, 4987, 284, 198, 779, 318, 986, 18611, 11, 284,...
3.423588
602
import os import shutil import tempfile from pathlib import Path try: from StringIO import StringIO except ImportError: from io import StringIO import dtoolcore from ruamel.yaml import YAML
[ 11748, 28686, 198, 11748, 4423, 346, 198, 11748, 20218, 7753, 198, 198, 6738, 3108, 8019, 1330, 10644, 198, 198, 28311, 25, 198, 220, 220, 220, 422, 10903, 9399, 1330, 10903, 9399, 198, 16341, 17267, 12331, 25, 198, 220, 220, 220, 422, ...
3.138462
65
from argparse import ArgumentParser import sys from jira import JIRA from jira_issue_recommender.util import get_comment, get_issues, get_issues_tfidf, get_most_similar
[ 6738, 1822, 29572, 1330, 45751, 46677, 198, 11748, 25064, 198, 198, 6738, 474, 8704, 1330, 449, 40, 3861, 198, 198, 6738, 474, 8704, 62, 21949, 62, 47335, 2194, 13, 22602, 1330, 651, 62, 23893, 11, 651, 62, 37165, 11, 651, 62, 37165, ...
3.245283
53
from trafpy.generator.src import builder from trafpy.generator.src.demand import Demand from trafpy.generator.src.tools import load_data_from_json, unpickle_data import glob import json import time from sqlitedict import SqliteDict import os if __name__ == '__main__': ''' Take path to previously generated json demand data file(s) and organise into slots_dict(s), then save as SQLite database in same path. ''' base_path = '/rdata/ong/trafpy/traces/jobcentric/' path_to_data = base_path + 'jobcentric_prototyping_k_4_L_2_n_16_chancap1250_numchans1_mldat3.2e5_bidirectional_benchmark_data' slot_size = 0.1 # 500.0 if glob.glob(path_to_data + '/*.json'): extension = '.json' elif glob.glob(path_to_data + '/*.pickle'): extension = '.pickle' else: raise Exception('Unrecognised or multiple file format in {}'.format(path_to_data)) _files = sorted(glob.glob(path_to_data + '/*{}'.format(extension))) if len(_files) == 0: raise Exception('No demand_data files found in {}.'.format(path_to_data)) for _file in _files: if os.path.exists(_file[:-(len(extension))]+'_slotsize_{}_slots_dict.sqlite'.format(slot_size)): print('\n{} already has an existing slots_dict database with slot_size {}. Skipping...'.format(_file, slot_size)) else: print('\nGenerating slots_dict database with slot_size {} for {}...'.format(slot_size, _file)) start = time.time() if extension == '.json': demand_data = json.loads(load_data_from_json(_file, print_times=False)) elif extension == '.pickle': demand_data = unpickle_data(_file, print_times=False) slots_dict = builder.construct_demand_slots_dict(demand_data=demand_data, include_empty_slots=True, slot_size=slot_size, print_info=True) with SqliteDict(_file[:-(len(extension))]+'_slotsize_{}_slots_dict.sqlite'.format(slot_size)) as _slots_dict: for key, val in slots_dict.items(): if type(key) is not str: _slots_dict[json.dumps(key)] = val else: _slots_dict[key] = val _slots_dict.commit() _slots_dict.close() end = time.time() print('Generated slots_dict database in {} s.'.format(end-start))
[ 6738, 1291, 69, 9078, 13, 8612, 1352, 13, 10677, 1330, 27098, 198, 6738, 1291, 69, 9078, 13, 8612, 1352, 13, 10677, 13, 28550, 1330, 34479, 198, 6738, 1291, 69, 9078, 13, 8612, 1352, 13, 10677, 13, 31391, 1330, 3440, 62, 7890, 62, 6...
2.065028
1,261
""" * 중복 문자 제거 중복된 문자를 제외하고 사전식 순서로 나열하라. 예제 1 - 입력 "bcabc" - 출력 "abc" 예제 2 - 입력 "cbacdcbc" - 출력 "acdb" """ if __name__ == '__main__': solution = Solution() param = "cbacdcb" print(solution.removeDuplicateLetters(param))
[ 37811, 198, 9, 23821, 97, 239, 167, 111, 113, 31619, 105, 116, 168, 252, 238, 23821, 254, 250, 166, 109, 108, 198, 168, 97, 239, 167, 111, 113, 167, 238, 250, 31619, 105, 116, 168, 252, 238, 167, 98, 120, 23821, 254, 250, 168, 2...
1.163366
202
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import click from punica.tool.tool import Tool from .main import main @main.group('tool', invoke_without_command=True) @click.pass_context def tool_cmd(ctx): """ Data format conversion tool """ if ctx.invoked_subcommand is None: print('Usage: punica tool [OPTIONS] COMMAND [ARGS]...') print('') print(' ', 'Data format conversion tool.') print() print('Options:') print(' ', '-h, --help Show this message and exit.') print() print('Commands:') print(' ', 'decryptprivatekey decrypt privatekey') print(' ', 'transform transform data') else: pass @tool_cmd.command('transform') @click.option('--addresstohex', nargs=1, type=str, default='', help='transform address to hex.') @click.option('--stringtohex', nargs=1, type=str, default='', help='transform string to hex.') @click.option('--hexreverse', nargs=1, type=str, default='', help='hex string reverse.') @click.option('--inttohex', nargs=1, type=int, default=0, help='transform int to hex.') def transform_cmd(addresstohex, stringtohex, hexreverse, inttohex): """ transform data """ if addresstohex != '': Tool.address_to_hex(addresstohex) elif stringtohex != '': Tool.str_to_hex(stringtohex) elif hexreverse != '': Tool.hex_reverse(hexreverse) elif inttohex != 0: Tool.num_to_hex(inttohex) else: print('Usage: punica tool transform [OPTIONS]') print('') print(' ', 'transform data.') print() print('Options:') print(' ', '--addresstohex TEXT transform address to hex.') print(' ', '--stringtohex TEXT transform string to hex.') print(' ', '--hexreverse TEXT hex string reverse.') print(' ', '--numtohex TEXT transform num to hex.') print(' ', '-h, --help Show this message and exit.') print() @tool_cmd.command('decryptprivatekey') @click.option('--key', nargs=1, type=str, default='', help='encrypted private key.') @click.option('--address', nargs=1, type=str, default='', help='address.') @click.option('--salt', nargs=1, type=str, default='', help='salt.') @click.option('--n', nargs=1, type=int, default=16384, help='n.') @click.option('--password', nargs=1, type=str, default='', help='password.') def decryptprivatekey_cmd(key, address, salt, n, password): """ decrypt privatekey """ if key == '' and address == '' and salt == '' or n == 0 and password == '': print('Usage: punica tool decryptprivatekey [OPTIONS]') print('') print(' ', 'decrypt privatekey') print() print('Options:') print(' ', '--key TEXT encrypted private key.') print(' ', '--address TEXT address.') print(' ', '--salt TEXT salt.') print(' ', '--n TEXT n.') print(' ', '--password TEXT password.') print(' ', '-h, --help Show this message and exit.') print() return if key == '': print('Error:') print('key should not be \'\'') return if address == '': print('Error:') print('address should not be \'\'') return if salt == '': print('Error:') print('salt should not be \'\'') return if password == '': print('Error:') print('password should not be \'\'') return Tool.decrypt_private_key(key, address, salt, n, password)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 3904, 198, 6738, 4000, 3970, 13, 25981, 13, 25981, 1330, 16984, 198, 198, 6738, 764, 12417, 1330, 1388,...
2.360105
1,519
"""Utilities to validate Galaxy xml tool wrappers and extract information from the XSD schema. """ from typing import List from lxml import etree from pygls.lsp.types import Diagnostic, MarkupContent, MarkupKind from ..context import XmlContext from ..xml.document import XmlDocument from .constants import MSG_NO_DOCUMENTATION_AVAILABLE, TOOL_XSD_FILE from .parser import GalaxyToolXsdParser from .validation import GalaxyToolValidationService NO_DOC_MARKUP = MarkupContent(kind=MarkupKind.Markdown, value=MSG_NO_DOCUMENTATION_AVAILABLE) class GalaxyToolXsdService: """Galaxy tool Xml Schema Definition service. This service provides functionality to extract information from the XSD schema and validate XML files against it. """ def __init__(self, server_name: str) -> None: """Initializes the validator by loading the XSD.""" self.server_name = server_name self.xsd_doc: etree._ElementTree = etree.parse(str(TOOL_XSD_FILE)) self.xsd_schema = etree.XMLSchema(self.xsd_doc) self.xsd_parser = GalaxyToolXsdParser(self.xsd_doc.getroot()) self.validator = GalaxyToolValidationService(server_name, self.xsd_schema) def validate_document(self, xml_document: XmlDocument) -> List[Diagnostic]: """Validates the Galaxy tool xml using the XSD schema and returns a list of diagnostics if there are any problems. """ return self.validator.validate_document(xml_document) def get_documentation_for(self, context: XmlContext) -> MarkupContent: """Gets the documentation annotated in the XSD about the given element name (node or attribute). """ if context.xsd_element: element = None if context.is_tag: element = context.xsd_element if context.is_attribute_key and context.node.name: element = context.xsd_element.attributes.get(context.node.name) if element: return element.get_doc() return NO_DOC_MARKUP
[ 37811, 18274, 2410, 284, 26571, 9252, 35555, 2891, 7917, 11799, 290, 7925, 198, 17018, 422, 262, 1395, 10305, 32815, 13, 198, 37811, 198, 198, 6738, 19720, 1330, 7343, 198, 198, 6738, 300, 19875, 1330, 2123, 631, 198, 6738, 12972, 4743, ...
2.663199
769
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Foss(BundlePackage): """GNU Compiler Collection (GCC) based compiler toolchain, including OpenMPI for MPI support, BLAS/LAPACK, ScaLAPACK, FFTW, ParMETIS, and PETSc. """ homepage = "https://hpcde.github.io/cluster-docs/" version('2020b') depends_on('gompi@2020b', type=('build', 'link', 'run')) depends_on('blas%gcc@10.2.0') depends_on('lapack%gcc@10.2.0') depends_on('scalapack%gcc@10.2.0') depends_on('fftw%gcc@10.2.0') depends_on('parmetis%gcc@10.2.0') depends_on('petsc%gcc@10.2.0')
[ 2, 15069, 2211, 12, 42334, 13914, 45036, 3549, 2351, 4765, 11, 11419, 290, 584, 198, 2, 1338, 441, 4935, 34152, 13, 4091, 262, 1353, 12, 5715, 27975, 38162, 9947, 2393, 329, 3307, 13, 198, 2, 198, 2, 30628, 55, 12, 34156, 12, 33234,...
2.395639
321
# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import (absolute_import, division, print_function, unicode_literals) import numpy as np from astropy.stats import sigma_clip __all__ = ['find_imgcuts', 'img_stats', 'rescale_img', 'scale_linear', 'scale_sqrt', 'scale_power', 'scale_log', 'scale_asinh',] # from scikit-image DTYPE_RANGE = {np.bool_: (False, True), np.bool8: (False, True), np.uint8: (0, 255), np.uint16: (0, 65535), np.int8: (-128, 127), np.int16: (-32768, 32767), np.float32: (-1, 1), np.float64: (-1, 1)} DTYPE_RANGE.update((d.__name__, limits) for d, limits in list(DTYPE_RANGE.items())) DTYPE_RANGE.update({'uint10': (0, 2**10 - 1), 'uint12': (0, 2**12 - 1), 'uint14': (0, 2**14 - 1), 'bool': DTYPE_RANGE[np.bool_], 'float': DTYPE_RANGE[np.float64]}) def find_imgcuts(image, min_cut=None, max_cut=None, min_percent=None, max_percent=None, percent=None): """ Find minimum and maximum image cut levels from percentiles of the image values. Parameters ---------- image : array_like The 2D array of the image. min_cut : float, optional The minimum cut level. Data values less than ``min_cut`` will set to ``min_cut`` before scaling the image. max_cut : float, optional The maximum cut level. Data values greater than ``max_cut`` will set to ``max_cut`` before scaling the image. min_percent : float, optional The minimum cut level as a percentile of the values in the image. If ``min_cut`` is input, then ``min_percent`` will be ignored. max_percent : float, optional The maximum cut level as a percentile of the values in the image. If ``max_cut`` is input, then ``max_percent`` will be ignored. percent : float, optional The percentage of the image values to scale. The lower cut level will set at the ``(100 - percent) / 2`` percentile, while the upper cut level will be set at the ``(100 + percent) / 2`` percentile. This value overrides the values of ``min_percent`` and ``max_percent``, but is ignored if ``min_cut`` and ``max_cut`` are both input. Returns ------- out : tuple Returns a tuple containing (``min_cut``, ``max_cut``) image cut levels. """ if min_cut is not None and max_cut is not None: return min_cut, max_cut if percent: assert (percent >= 0) and (percent <= 100.0), 'percent must be >= 0 and <= 100.0' if not min_percent and not max_percent: min_percent = (100.0 - float(percent)) / 2.0 max_percent = 100.0 - min_percent if min_cut is None: if min_percent is None: min_percent = 0.0 assert min_percent >= 0, 'min_percent must be >= 0' min_cut = np.percentile(image, min_percent) if max_cut is None: if max_percent is None: max_percent = 100.0 assert max_percent <= 100.0, 'max_percent must be <= 100.0' max_cut = np.percentile(image, max_percent) assert min_cut <= max_cut, 'min_cut must be <= max_cut' return min_cut, max_cut def img_stats(image, image_mask=None, mask_val=None, sig=3.0, iters=None): """ Perform sigma-clipped statistics on an image. Parameters ---------- image : array_like The 2D array of the image. image_mask : array_like, bool, optional A boolean mask with the same shape as ``image``, where a `True` value indicates the corresponding element of ``image`` is invalid. Masked pixels are ignored when computing the image statistics. mask_val : float, optional An image data value (e.g., ``0.0``) that is ignored when computing the image statistics. ``mask_val`` will be ignored if ``image_mask`` is input. sig : float, optional The number of standard deviations to use as the clipping limit. iters : float, optional The number of iterations to perform clipping, or `None` to clip until convergence is achieved (i.e. continue until the last iteration clips nothing). Returns ------- stats : tuple Returns a tuple of the (``mean``, ``median``, ``stddev``) of the sigma-clipped image. """ if image_mask: image = image[~image_mask] if mask_val and not image_mask: idx = (image != mask_val).nonzero() image = image[idx] image_clip = sigma_clip(image, sig=sig, iters=iters) goodvals = image_clip.data[~image_clip.mask] return np.mean(goodvals), np.median(goodvals), np.std(goodvals) def rescale_img(image, min_cut=None, max_cut=None, min_percent=None, max_percent=None, percent=None): """ Rescale image values between minimum and maximum cut levels to values between 0 and 1, inclusive. Parameters ---------- image : array_like The 2D array of the image. min_cut : float, optional The minimum cut level. Data values less than ``min_cut`` will set to ``min_cut`` before scaling the image. max_cut : float, optional The maximum cut level. Data values greater than ``max_cut`` will set to ``max_cut`` before scaling the image. min_percent : float, optional The minimum cut level as a percentile of the values in the image. If ``min_cut`` is input, then ``min_percent`` will be ignored. max_percent : float, optional The maximum cut level as a percentile of the values in the image. If ``max_cut`` is input, then ``max_percent`` will be ignored. percent : float, optional The percentage of the image values to scale. The lower cut level will set at the ``(100 - percent) / 2`` percentile, while the upper cut level will be set at the ``(100 + percent) / 2`` percentile. This value overrides the values of ``min_percent`` and ``max_percent``, but is ignored if ``min_cut`` and ``max_cut`` are both input. Returns ------- out : tuple Returns a tuple containing (``outimg``, ``min_cut``, ``max_cut``), which are the output scaled image and the minimum and maximum cut levels. """ image = image.astype(np.float64) min_cut, max_cut = find_imgcuts(image, min_cut=min_cut, max_cut=max_cut, min_percent=min_percent, max_percent=max_percent, percent=percent) outimg = rescale_intensity(image, in_range=(min_cut, max_cut), out_range=(0, 1)) return outimg, min_cut, max_cut def scale_linear(image, min_cut=None, max_cut=None, min_percent=None, max_percent=None, percent=None): """ Perform linear scaling of an image between minimum and maximum cut levels. Parameters ---------- image : array_like The 2D array of the image. min_cut : float, optional The minimum cut level. Data values less than ``min_cut`` will set to ``min_cut`` before scaling the image. max_cut : float, optional The maximum cut level. Data values greater than ``max_cut`` will set to ``max_cut`` before scaling the image. min_percent : float, optional The minimum cut level as a percentile of the values in the image. If ``min_cut`` is input, then ``min_percent`` will be ignored. max_percent : float, optional The maximum cut level as a percentile of the values in the image. If ``max_cut`` is input, then ``max_percent`` will be ignored. percent : float, optional The percentage of the image values to scale. The lower cut level will set at the ``(100 - percent) / 2`` percentile, while the upper cut level will be set at the ``(100 + percent) / 2`` percentile. This value overrides the values of ``min_percent`` and ``max_percent``, but is ignored if ``min_cut`` and ``max_cut`` are both input. Returns ------- scaled_image : array_like The 2D array of the scaled/stretched image. """ result = rescale_img(image, min_cut=min_cut, max_cut=max_cut, min_percent=min_percent, max_percent=max_percent, percent=percent) return result[0] def scale_sqrt(image, min_cut=None, max_cut=None, min_percent=None, max_percent=None, percent=None): """ Perform square-root scaling of an image between minimum and maximum cut levels. This is equivalent to using `scale_power` with a ``power`` of ``0.5``. Parameters ---------- image : array_like The 2D array of the image. min_cut : float, optional The minimum cut level. Data values less than ``min_cut`` will set to ``min_cut`` before scaling the image. max_cut : float, optional The maximum cut level. Data values greater than ``max_cut`` will set to ``max_cut`` before scaling the image. min_percent : float, optional The minimum cut level as a percentile of the values in the image. If ``min_cut`` is input, then ``min_percent`` will be ignored. max_percent : float, optional The maximum cut level as a percentile of the values in the image. If ``max_cut`` is input, then ``max_percent`` will be ignored. percent : float, optional The percentage of the image values to scale. The lower cut level will set at the ``(100 - percent) / 2`` percentile, while the upper cut level will be set at the ``(100 + percent) / 2`` percentile. This value overrides the values of ``min_percent`` and ``max_percent``. Returns ------- scaled_image : array_like The 2D array of the scaled/stretched image. """ result = rescale_img(image, min_cut=min_cut, max_cut=max_cut, min_percent=min_percent, max_percent=max_percent, percent=percent) return np.sqrt(result[0]) def scale_power(image, power, min_cut=None, max_cut=None, min_percent=None, max_percent=None, percent=None): """ Perform power scaling of an image between minimum and maximum cut levels. Parameters ---------- image : array_like The 2D array of the image. power : float The power index for the image scaling. min_cut : float, optional The minimum cut level. Data values less than ``min_cut`` will set to ``min_cut`` before scaling the image. max_cut : float, optional The maximum cut level. Data values greater than ``max_cut`` will set to ``max_cut`` before scaling the image. min_percent : float, optional The minimum cut level as a percentile of the values in the image. If ``min_cut`` is input, then ``min_percent`` will be ignored. max_percent : float, optional The maximum cut level as a percentile of the values in the image. If ``max_cut`` is input, then ``max_percent`` will be ignored. percent : float, optional The percentage of the image values to scale. The lower cut level will set at the ``(100 - percent) / 2`` percentile, while the upper cut level will be set at the ``(100 + percent) / 2`` percentile. This value overrides the values of ``min_percent`` and ``max_percent``, but is ignored if ``min_cut`` and ``max_cut`` are both input. Returns ------- scaled_image : array_like The 2D array of the scaled/stretched image. """ result = rescale_img(image, min_cut=min_cut, max_cut=max_cut, min_percent=min_percent, max_percent=max_percent, percent=percent) return (result[0])**power def scale_log(image, min_cut=None, max_cut=None, min_percent=None, max_percent=None, percent=None): """ Perform logarithmic (base 10) scaling of an image between minimum and maximum cut levels. Parameters ---------- image : array_like The 2D array of the image. min_cut : float, optional The minimum cut level. Data values less than ``min_cut`` will set to ``min_cut`` before scaling the image. max_cut : float, optional The maximum cut level. Data values greater than ``max_cut`` will set to ``max_cut`` before scaling the image. min_percent : float, optional The minimum cut level as a percentile of the values in the image. If ``min_cut`` is input, then ``min_percent`` will be ignored. max_percent : float, optional The maximum cut level as a percentile of the values in the image. If ``max_cut`` is input, then ``max_percent`` will be ignored. percent : float, optional The percentage of the image values to scale. The lower cut level will set at the ``(100 - percent) / 2`` percentile, while the upper cut level will be set at the ``(100 + percent) / 2`` percentile. This value overrides the values of ``min_percent`` and ``max_percent``, but is ignored if ``min_cut`` and ``max_cut`` are both input. Returns ------- scaled_image : array_like The 2D array of the scaled/stretched image. """ result = rescale_img(image, min_cut=min_cut, max_cut=max_cut, min_percent=min_percent, max_percent=max_percent, percent=percent) outimg = np.log10(result[0] + 1.0) / np.log10(2.0) return outimg def scale_asinh(image, noise_level=None, sigma=2.0, min_cut=None, max_cut=None, min_percent=None, max_percent=None, percent=None): """ Perform inverse hyperbolic sine (arcsinh) scaling of an image between minimum and maximum cut levels. Parameters ---------- image : array_like The 2D array of the image. noise_level: float, optional The noise level of the image. Levels less than noise_level will approximately be linearly scaled, while levels greater than noise_level will approximately be logarithmically scaled. sigma: float, optional The number of standard deviations of the background noise used to estimate the absolute noise level. This value is ignored if ``noise_level`` is input. min_cut : float, optional The minimum cut level. Data values less than ``min_cut`` will set to ``min_cut`` before scaling the image. max_cut : float, optional The maximum cut level. Data values greater than ``max_cut`` will set to ``max_cut`` before scaling the image. min_percent : float, optional The minimum cut level as a percentile of the values in the image. If ``min_cut`` is input, then ``min_percent`` will be ignored. max_percent : float, optional The maximum cut level as a percentile of the values in the image. If ``max_cut`` is input, then ``max_percent`` will be ignored. percent : float, optional The percentage of the image values to scale. The lower cut level will set at the ``(100 - percent) / 2`` percentile, while the upper cut level will be set at the ``(100 + percent) / 2`` percentile. This value overrides the values of ``min_percent`` and ``max_percent``, but is ignored if ``min_cut`` and ``max_cut`` are both input. Returns ------- scaled_image : array_like The 2D array of the scaled/stretched image. """ result = rescale_img(image, min_cut=min_cut, max_cut=max_cut, min_percent=min_percent, max_percent=max_percent, percent=percent) outimg, min_cut, max_cut = result if not noise_level: mean, median, stddev = img_stats(outimg) noise_level = mean + (sigma * stddev) z = (noise_level - min_cut) / (max_cut - min_cut) outimg = np.arcsinh(outimg / z) / np.arcsinh(1.0 / z) return outimg # from scikit-image def rescale_intensity(image, in_range=None, out_range=None): """Return image after stretching or shrinking its intensity levels. The image intensities are uniformly rescaled such that the minimum and maximum values given by `in_range` match those given by `out_range`. Parameters ---------- image : array Image array. in_range : 2-tuple (float, float) or str Min and max *allowed* intensity values of input image. If None, the *allowed* min/max values are set to the *actual* min/max values in the input image. Intensity values outside this range are clipped. If string, use data limits of dtype specified by the string. out_range : 2-tuple (float, float) or str Min and max intensity values of output image. If None, use the min/max intensities of the image data type. See `skimage.util.dtype` for details. If string, use data limits of dtype specified by the string. Returns ------- out : array Image array after rescaling its intensity. This image is the same dtype as the input image. Examples -------- By default, intensities are stretched to the limits allowed by the dtype: >>> image = np.array([51, 102, 153], dtype=np.uint8) >>> rescale_intensity(image) array([ 0, 127, 255], dtype=uint8) It's easy to accidentally convert an image dtype from uint8 to float: >>> 1.0 * image array([ 51., 102., 153.]) Use `rescale_intensity` to rescale to the proper range for float dtypes: >>> image_float = 1.0 * image >>> rescale_intensity(image_float) array([ 0. , 0.5, 1. ]) To maintain the low contrast of the original, use the `in_range` parameter: >>> rescale_intensity(image_float, in_range=(0, 255)) array([ 0.2, 0.4, 0.6]) If the min/max value of `in_range` is more/less than the min/max image intensity, then the intensity levels are clipped: >>> rescale_intensity(image_float, in_range=(0, 102)) array([ 0.5, 1. , 1. ]) If you have an image with signed integers but want to rescale the image to just the positive range, use the `out_range` parameter: >>> image = np.array([-10, 0, 10], dtype=np.int8) >>> rescale_intensity(image, out_range=(0, 127)) array([ 0, 63, 127], dtype=int8) """ dtype = image.dtype.type if in_range is None: imin = np.min(image) imax = np.max(image) elif in_range in DTYPE_RANGE: imin, imax = DTYPE_RANGE[in_range] else: imin, imax = in_range if out_range is None or out_range in DTYPE_RANGE: out_range = dtype if out_range is None else out_range omin, omax = DTYPE_RANGE[out_range] if imin >= 0: omin = 0 else: omin, omax = out_range image = np.clip(image, imin, imax) image = (image - imin) / float(imax - imin) return dtype(image * (omax - omin) + omin)
[ 2, 49962, 739, 257, 513, 12, 565, 682, 347, 10305, 3918, 5964, 532, 766, 38559, 24290, 13, 81, 301, 198, 6738, 11593, 37443, 834, 1330, 357, 48546, 62, 11748, 11, 7297, 11, 3601, 62, 8818, 11, 198, 220, 220, 220, 220, 220, 220, 22...
2.552348
7,622
#'!/usr/bin/env python #-*- coding:utf-8 -*- #!/usr/bin/python3 from chainer import Chain, functions, links from Encoder import Encoder from Decoder import Decoder import numpy as np from util.Common_function import CommonFunction
[ 2, 6, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 12, 9, 12, 19617, 25, 40477, 12, 23, 532, 9, 12, 198, 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 198, 6738, 6333, 263, 1330, 21853, 11, 5499, 11, 6117, 198, 6738, 14711...
3.28169
71
import sys script = sys.argv[0] filename = sys.argv[1] txt = open(filename) print(f"Here's your file {filename}:") print(txt.read()) print("Type the filename again:") file_again = input("> ") txt_again = open(file_again) print(txt_again.read())
[ 11748, 25064, 198, 198, 12048, 796, 25064, 13, 853, 85, 58, 15, 60, 198, 34345, 796, 25064, 13, 853, 85, 58, 16, 60, 198, 198, 14116, 796, 1280, 7, 34345, 8, 198, 198, 4798, 7, 69, 1, 4342, 338, 534, 2393, 1391, 34345, 38362, 49...
2.659574
94
"""Implements the COVID SEIR model as a TFP Joint Distribution""" import pandas as pd import geopandas as gp import numpy as np import xarray import tensorflow as tf import tensorflow_probability as tfp from gemlib.distributions import DiscreteTimeStateTransitionModel from covid19uk.util import impute_previous_cases from covid19uk.data import AreaCodeData from covid19uk.data import CasesData from covid19uk.data import read_mobility from covid19uk.data import read_population from covid19uk.data import read_traffic_flow tfd = tfp.distributions DTYPE = np.float64 STOICHIOMETRY = np.array([[-1, 1, 0, 0], [0, -1, 1, 0], [0, 0, -1, 1]]) TIME_DELTA = 1.0 NU = tf.constant(0.28, dtype=DTYPE) # E->I rate assumed known. def gather_data(config): """Loads covariate data :param paths: a dictionary of paths to data with keys {'mobility_matrix', 'population_size', 'commute_volume'} :returns: a dictionary of covariate information to be consumed by the model {'C': commute_matrix, 'W': traffic_flow, 'N': population_size} """ date_low = np.datetime64(config["date_range"][0]) date_high = np.datetime64(config["date_range"][1]) locations = AreaCodeData.process(config) mobility = read_mobility(config["mobility_matrix"], locations["lad19cd"]) popsize = read_population(config["population_size"], locations["lad19cd"]) commute_volume = read_traffic_flow( config["commute_volume"], date_low=date_low, date_high=date_high ) geo = gp.read_file(config["geopackage"], layer="UK2019mod_pop_xgen") geo = geo.sort_values("lad19cd") geo = geo[geo["lad19cd"].isin(locations["lad19cd"])] adjacency = _compute_adjacency_matrix(geo.geometry, geo["lad19cd"], 200) area = xarray.DataArray( geo.area, name="area", dims=["location"], coords=[geo["lad19cd"]], ) dates = pd.date_range(*config["date_range"], closed="left") weekday = xarray.DataArray( dates.weekday < 5, name="weekday", dims=["time"], coords=[dates.to_numpy()], ) cases = CasesData.process(config).to_xarray() return ( xarray.Dataset( dict( C=mobility.astype(DTYPE), W=commute_volume.astype(DTYPE), N=popsize.astype(DTYPE), adjacency=adjacency, weekday=weekday.astype(DTYPE), area=area.astype(DTYPE), locations=xarray.DataArray( locations["name"], dims=["location"], coords=[locations["lad19cd"]], ), ) ), xarray.Dataset(dict(cases=cases)), ) def impute_censored_events(cases): """Imputes censored S->E and E->I events using geometric sampling algorithm in `impute_previous_cases` There are application-specific magic numbers hard-coded below, which reflect experimentation to get the right lag between EI and IR events, and SE and EI events respectively. These were chosen by experimentation and examination of the resulting epidemic trajectories. :param cases: a MxT matrix of case numbers (I->R) :returns: a MxTx3 tensor of events where the first two indices of the right-most dimension contain the imputed event times. """ ei_events, lag_ei = impute_previous_cases(cases, 0.25) se_events, lag_se = impute_previous_cases(ei_events, 0.5) ir_events = np.pad(cases, ((0, 0), (lag_ei + lag_se - 2, 0))) ei_events = np.pad(ei_events, ((0, 0), (lag_se - 1, 0))) return tf.stack([se_events, ei_events, ir_events], axis=-1) def next_generation_matrix_fn(covar_data, param): """The next generation matrix calculates the force of infection from individuals in metapopulation i to all other metapopulations j during a typical infectious period (1/gamma). i.e. \[ A_{ij} = S_j * \beta_1 ( 1 + \beta_2 * w_t * C_{ij} / N_i) / N_j / gamma \] :param covar_data: a dictionary of covariate data :param param: a dictionary of parameters :returns: a function taking arguments `t` and `state` giving the time and epidemic state (SEIR) for which the NGM is to be calculated. This function in turn returns an MxM next generation matrix. """ return fn
[ 37811, 3546, 1154, 902, 262, 7375, 11008, 7946, 4663, 2746, 355, 257, 309, 5837, 16798, 27484, 37811, 198, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 30324, 392, 292, 355, 27809, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 21...
2.4228
1,807
from enum import Enum
[ 6738, 33829, 1330, 2039, 388, 628 ]
3.833333
6
# Auto-anchor utils
[ 2, 11160, 12, 3702, 273, 3384, 4487, 198 ]
2.5
8
#!/usr/bin/env python ''' Project: Geothon (https://github.com/MBoustani/Geothon) File: Vector/create_wkt_line.py Description: This code creates a wkt line from multi-points. Author: Maziyar Boustani (github.com/MBoustani) ''' try: import ogr except ImportError: from osgeo import ogr latitudes = [50, 51, 52, 53, 54] longitudes = [100, 110, 120, 130, 140] #to make it 2D point elevation = 0 #define a line geometry line = ogr.Geometry(ogr.wkbLineString) #add points into line geometry line.AddPoint(longitudes[0], latitudes[0], elevation) line.AddPoint(longitudes[1], latitudes[1], elevation) line.AddPoint(longitudes[2], latitudes[2], elevation) line.AddPoint(longitudes[3], latitudes[3], elevation) line.AddPoint(longitudes[4], latitudes[4], elevation) #convert line geometry into WKT format line.ExportToWkt() print line
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 7061, 6, 198, 16775, 25, 220, 220, 220, 220, 220, 220, 2269, 849, 261, 357, 5450, 1378, 12567, 13, 785, 14, 10744, 23968, 3216, 14, 10082, 849, 261, 8, 198, 8979, 25, 220, 220...
2.677019
322
from zeit.cms.interfaces import ICMSContent from zeit.content.article.interfaces import IArticle import argparse import logging import prometheus_client import zeit.cms.cli import zeit.find.interfaces import zeit.retresco.interfaces import zope.component REGISTRY = prometheus_client.CollectorRegistry() log = logging.getLogger(__name__) IMPORTERS = [ Gauge('vivi_recent_news_published_total', [ {'term': {'payload.workflow.product-id': 'News'}}, {'range': {'payload.document.date-last-modified': {'gt': 'now-1h'}}}, ], 'external'), Gauge('vivi_recent_videos_published_total', [ {'term': {'doc_type': 'video'}}, {'range': {'payload.document.date-last-modified': {'gt': 'now-1h'}}}, ], 'external'), Gauge('vivi_recent_vgwort_reported_total', [ {'range': {'payload.vgwort.reported_on': {'gt': 'now-1h'}}}, ], 'internal'), ] TOKEN_COUNT = Gauge('vivi_available_vgwort_tokens_total') BROKEN = Counter('vivi_articles_with_missing_tms_authors', { 'query': {'bool': {'filter': [ {'term': {'doc_type': 'article'}}, {'range': {'payload.document.date_first_released': {'gt': 'now-30m'}}} ]}}, '_source': ['url', 'payload.head.authors'], }, 'external') @zeit.cms.cli.runner() def collect(): """Collects all app-specific metrics that we have. Mostly these are based on ES queries, but not all of them. This is probably *not* the best factoring, but the overall amount is so little that putting in a larger architecture/mechanics is just not worth it at this point. """ parser = argparse.ArgumentParser() parser.add_argument('pushgateway') options = parser.parse_args() elastic = { 'external': zope.component.getUtility( zeit.retresco.interfaces.IElasticsearch), 'internal': zope.component.getUtility( zeit.find.interfaces.ICMSSearch), } for metric in IMPORTERS: query = {'query': {'bool': {'filter': metric.query}}} es = elastic[metric.es] metric.set(es.search(query, rows=0).hits) tokens = zope.component.getUtility(zeit.vgwort.interfaces.ITokens) TOKEN_COUNT.set(len(tokens)) for row in elastic[BROKEN.es].search(BROKEN.query, rows=100): content = ICMSContent('http://xml.zeit.de' + row['url'], None) if not IArticle.providedBy(content): log.info('Skip %s, not found', row['url']) continue tms = row.get('payload', {}).get('head', {}).get('authors', []) for ref in content.authorships: id = ref.target_unique_id if id and id not in tms: log.warn('%s: author %s not found in TMS', content, id) BROKEN.inc() prometheus_client.push_to_gateway( options.pushgateway, job=__name__, registry=REGISTRY)
[ 6738, 41271, 270, 13, 46406, 13, 3849, 32186, 1330, 12460, 5653, 19746, 198, 6738, 41271, 270, 13, 11299, 13, 20205, 13, 3849, 32186, 1330, 314, 14906, 198, 11748, 1822, 29572, 198, 11748, 18931, 198, 11748, 1552, 36916, 62, 16366, 198, ...
2.371548
1,195
import numpy as np from numba import jit # Assumptions: # The stock price volatility is equal to the implied volatility and remains constant. # Geometric Brownian Motion is used to model the stock price. # Risk-free interest rates remain constant. # The Black-Scholes Model is used to price options contracts. # Dividend yield is not considered. # Commissions are not considered. # Assignment risks are not considered. # Earnings date and stock splits are not considered.
[ 11748, 299, 32152, 355, 45941, 198, 6738, 997, 7012, 1330, 474, 270, 198, 198, 2, 2195, 388, 8544, 25, 198, 2, 383, 4283, 2756, 30772, 318, 4961, 284, 262, 17142, 30772, 290, 3793, 6937, 13, 198, 2, 2269, 16996, 4373, 666, 20843, 31...
4.157895
114
# Copyright (c) 2014 Rackspace, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in 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 uuid import mock from poppy.common import errors from poppy.manager.base import providers from poppy.model.helpers import provider_details from tests.unit import base
[ 2, 15069, 357, 66, 8, 1946, 37927, 13200, 11, 3457, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789,...
3.81
200
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, 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. """Unit tests for nrf52840 module.""" from unittest import mock from gazoo_device.auxiliary_devices import nrf52840 from gazoo_device.base_classes import nrf_connect_sdk_device from gazoo_device.tests.unit_tests.utils import fake_device_test_case import immutabledict _FAKE_DEVICE_ID = "nrf52840-detect" _FAKE_DEVICE_ADDRESS = "/dev/bus/usb/001/002" _NRF_CONNECT_PERSISTENT_PROPERTIES = immutabledict.immutabledict({ "os": "Zephyr RTOS", "platform": "nRF Connect", "serial_number": "FT2BSR6O", "name": "nrf52840_detect", "device_type": "nrf52840", }) class NRF52840DeviceTests(fake_device_test_case.FakeDeviceTestCase): """Test for base class NRF52840.""" def test_001_nrf52840_attributes(self): """Verifies nrf52840 attributes.""" self._test_get_detection_info(_FAKE_DEVICE_ADDRESS, nrf52840.NRF52840, _NRF_CONNECT_PERSISTENT_PROPERTIES) def test_003_jlink_flash_capability(self): """Verifies the initialization of j_link_flash capability.""" self.assertTrue(self.uut.flash_build) @mock.patch.object(nrf_connect_sdk_device.os.path, "exists") def test_004_is_connected_true(self, mock_exists): """Verifies is_connected works as expected.""" mock_exists.return_value = True self.assertTrue(nrf52840.NRF52840.is_connected(self.device_config)) if __name__ == "__main__": fake_device_test_case.main()
[ 2, 15069, 33448, 3012, 11419, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 2, 921, 743, 733...
2.663576
755
from django.conf.urls import patterns, url urlpatterns = patterns( 'wagtail.wagtailcore.views', # All front-end views are handled through Wagtail's core.views.serve mechanism. # Here we match a (possibly empty) list of path segments, each followed by # a '/'. If a trailing slash is not present, we leave CommonMiddleware to # handle it as usual (i.e. redirect it to the trailing slash version if # settings.APPEND_SLASH is True) url(r'^((?:[\w\-]+/)*)$', 'serve') )
[ 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 1330, 7572, 11, 19016, 198, 198, 6371, 33279, 82, 796, 7572, 7, 198, 220, 220, 220, 705, 86, 363, 13199, 13, 86, 363, 13199, 7295, 13, 33571, 3256, 198, 220, 220, 220, 1303, 1439, 2166, ...
2.952381
168
import csv import importlib import importlib.util import re __all__ = [ 'camel_case_to_underscore', 'import_type', 'import_module_from_file', 'read_teams_from_file', ] first_cap_re = re.compile('(.)([A-Z][a-z]+)') all_cap_re = re.compile('([a-z0-9])([A-Z])') def read_teams_from_file(file_name: str): """ Reads teams from CSV file. File should be in UTF-8 and has two columns: team name and vulnbox address. Common usage is `TEAMS = read_teams_from_file('teams.csv')` in `settings.py` :param file_name: name of CSV file :return: list of pairs """ from farm.logging import Logger logger = Logger('Configurator') logger.info('Reading teams list from %s' % file_name) result = [] with open(file_name, 'r', newline='', encoding='utf-8') as f: csv_reader = csv.reader(f) for line_index, row in enumerate(csv_reader): if len(row) != 2: raise ValueError('Invalid teams files %s: row #%d "%s" contains more or less than 2 items' % ( file_name, line_index, ','.join(row) )) result.append(tuple(row)) logger.info('Read %d teams from %s' % (len(result), file_name)) return result
[ 11748, 269, 21370, 198, 11748, 1330, 8019, 198, 11748, 1330, 8019, 13, 22602, 198, 11748, 302, 198, 198, 834, 439, 834, 796, 685, 198, 220, 220, 220, 705, 66, 17983, 62, 7442, 62, 1462, 62, 41116, 7295, 3256, 198, 220, 220, 220, 705...
2.229021
572
############################################################################## # # Copyright (c) 2006-2008 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## import copy import sys import zope.interface import zope.interface.interfaces import BTrees import BTrees.check import BTrees.Length import persistent import persistent.list import persistent.wref import six from zc.relation import interfaces ############################################################################## # constants # RELATION = None # uh, yeah. None. The story is, zc.relation.RELATION is more readable as # a search key, so I want a constant; but by the time I came to this decision, # ``None`` had already been advertised as the way to spell this. So, yeah... # hysterical raisins. ############################################################################## # helpers # ############################################################################## # Any and any # ############################################################################## # the marker that shows that a path is circular # @zope.interface.implementer(interfaces.ICircularRelationPath) ############################################################################## # the relation catalog @zope.interface.implementer(interfaces.ICatalog)
[ 29113, 29113, 7804, 4242, 2235, 198, 2, 198, 2, 15069, 357, 66, 8, 4793, 12, 11528, 1168, 3008, 5693, 290, 25767, 669, 13, 198, 2, 1439, 6923, 33876, 13, 198, 2, 198, 2, 770, 3788, 318, 2426, 284, 262, 8617, 286, 262, 1168, 3008, ...
4.354369
412
# Generated by Django 2.2.4 on 2019-09-07 14:22 import datetime from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 362, 13, 17, 13, 19, 319, 13130, 12, 2931, 12, 2998, 1478, 25, 1828, 198, 198, 11748, 4818, 8079, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.972222
36
from app.helpers.template_helpers import ( CENSUS_CY_BASE_URL, CENSUS_EN_BASE_URL, CENSUS_NIR_BASE_URL, ) from tests.integration.integration_test_case import IntegrationTestCase SIGN_OUT_URL_PATH = "/sign-out" SIGNED_OUT_URL_PATH = "/signed-out" ACCOUNT_SERVICE_LOG_OUT_URL = "http://localhost/logout" ACCOUNT_SERVICE_LOG_OUT_URL_PATH = "/logout" # Test the behaviour when using Hub/No Hub
[ 6738, 598, 13, 16794, 364, 13, 28243, 62, 16794, 364, 1330, 357, 198, 220, 220, 220, 327, 16938, 2937, 62, 34, 56, 62, 33, 11159, 62, 21886, 11, 198, 220, 220, 220, 327, 16938, 2937, 62, 1677, 62, 33, 11159, 62, 21886, 11, 198, ...
2.50303
165
#!/usr/bin/env python # -*- coding: utf-8 -*- """The definition of the base classes Host and VM which provide the necessary primitives to interact with a vm and test a submission bundle.""" from __future__ import with_statement # Use simplejson or Python 2.6 json, prefer simplejson. try: import simplejson as json except ImportError: import json import os import sys import time import logging import signal import shlex from threading import Thread from subprocess import Popen, PIPE, STDOUT from vmchecker.config import VirtualMachineConfig _logger = logging.getLogger('vm_executor')
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 464, 6770, 286, 262, 2779, 6097, 14504, 290, 16990, 543, 198, 15234, 485, 262, 3306, 2684, 20288, 284, 9427...
3.431818
176
import open3d as o3d import numpy as np import os import json import quaternion as quat import utils ################################################### ############### MAIN ################################################### do_white_background = False do_save = False dataset_name = 'easy' mesh_folder = '../results/volumetric_meshes' dataset_root_folder = '/home/poiesi/data/datasets/4dm/' if do_white_background: dest_folder = os.path.join('../results/volumetric_viz', dataset_name, 'white') else: dest_folder = os.path.join('../results/volumetric_viz', dataset_name, 'black') if not os.path.isdir(dest_folder): os.makedirs(dest_folder) mobiles = {1: '4846a8bc1c6f287a725111d3f60f2385', 2: 'cc74017ee8081c07917f03332f92ede6', 3: 'd7ec5aa63b32a4878ca037e2a7fec252', 4: '172673834746e6d591b4b00599c98ffa', 5: '378d43cea3872b0551900a15c92e0ec4', 6: '642a3152b339263852fffe527a9de347'} # corrections computed with https://github.com/fabiopoiesi/dip pose_corrections = [[[ 1., 0., 0., 0.], [ 0., 1., 0., 0.], [ 0., 0., 1., 0.], [ 0., 0., 0., 1.]], [[ 0.99905457, -0.02676729, -0.0342561, 0.15728716], [ 0.02700194, 0.99961486, 0.00640553, -0.01462191], [ 0.03407145, -0.00732446, 0.99939256, 0.00472023], [ 0., 0., 0., 1., ]], [[ 0.99960058, -0.00509856, 0.02779724, 0.14406139], [ 0.00464171, 0.9998535, 0.01647517, -0.00341851], [-0.02787717, -0.01633956, 0.9994778, -0.03475881], [ 0., 0., 0., 1., ]], [[ 9.98765432e-01, -4.96677155e-02, -8.54867548e-04, 1.72896007e-01], [ 4.96718223e-02, 9.98749038e-01, 5.75062066e-03, -6.17926371e-02], [ 5.68177950e-04, -5.78598396e-03, 9.99983100e-01, 1.00602630e-01], [ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 1.00000000e+00]], [[ 0.99998321, -0.00385142, -0.00432897, 0.19584433], [ 0.00391902, 0.99986879, 0.01571766, -0.0033018 ], [ 0.00426787, -0.01573436, 0.9998671, 0.0189917 ], [ 0., 0., 0., 1. ]], [[0.99847665, - 0.05491205, 0.00538861, 0.218133], [0.05486804, 0.99846156, 0.00800104, 0.00688609], [-0.00581968, - 0.00769319, 0.99995347, - 0.02124214], [0., 0., 0., 1.]] ] if not os.path.isdir(dest_folder): os.mkdir(dest_folder) mobile_viz_points = 0.4 * np.array([[-0.5, -0.5, 1], [0.5, -0.5, 1], [-0.5, 0.5, 1], [0.5, 0.5, 1], [0, 0, 0]]) mobile_viz_lines = [[0, 1], [2, 3], [2, 0], [1, 3], [4, 0], [4, 1], [4, 2], [4, 3]] mobile_viz_colors = [[1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 1, 0], [1, 1, 0], [1, 1, 0], [1, 1, 0]] if do_white_background: mobile_viz_colors = [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0]] vis = o3d.visualization.Visualizer() vis.create_window(visible=True, width=1920, height=1080-240) vis.get_render_option().background_color = [0, 0, 0] if do_white_background: vis.get_render_option().background_color = [1, 1, 1] flag_viz_camera_rotation = True vis.update_renderer() # init mobile captures mobile_captures = {} for mobile_number, mobile in mobiles.items(): mobile_captures[mobile_number] = {'im': [], 'position': [], 'rotation': [], 'principal_point': [], 'focal_length': [], 'K': [], 'frustum': [], 'person_pose': []} files = os.listdir(os.path.join(mesh_folder, dataset_name)) files.sort() local_frame = o3d.geometry.TriangleMesh.create_coordinate_frame(size=.2) vis.add_geometry(local_frame) mesh = o3d.geometry.TriangleMesh() c = np.asarray([1.00563633, 0, -1.10522775]) b = .9 h = 1.9 voxel_res = 220 X, Y, Z = np.meshgrid(np.linspace(c[0] - b, c[0] + b, voxel_res), np.linspace(0, -h, voxel_res), np.linspace(c[2] - b, c[2] + b, voxel_res)) c = 0 for mf in files: fr = int(mf.split('.')[0]) # CAMERAS for mobile_number, mobile in mobiles.items(): json_file = os.path.join(dataset_root_folder, dataset_name, mobile, '%04d.bin' % fr) # mobile pose with open(json_file, 'r') as jf: json_text = jf.read() meta = json.loads(json_text) pp = np.asarray([meta['principalPoint']['x'], meta['principalPoint']['y']]) fl = np.asarray([meta['focalLength']['x'], meta['focalLength']['y']]) rotation = quat.quaternion(meta['rotation']['w'], -meta['rotation']['x'], meta['rotation']['y'], -meta['rotation']['z']) C = np.asarray([meta['position']['x'], -meta['position']['y'], meta['position']['z']]) # http://ksimek.github.io/2012/08/22/extrinsic/ K = np.asarray([[fl[0], 0, pp[0]], [0, fl[1], pp[1]], [0, 0, 1]]) R = quat.as_rotation_matrix(rotation) T = np.zeros((4, 4)) T[:3,:3] = R T[:3, 3] = C T[3, 3] = 1 mpts = mobile_viz_points.T Tnew = pose_corrections[mobile_number-1] @ T mobile_pose_world = (Tnew @ np.r_[mpts, np.ones((1, mpts.shape[1]))])[:3].T if c > 0: [vis.remove_geometry(l) for l in mobile_captures[mobile_number]['frustum']] frustum_to_viz = [] line_mesh = utils.LineMesh(mobile_pose_world, mobile_viz_lines, mobile_viz_colors, radius=0.02) line_mesh_geoms = line_mesh.cylinder_segments mobile_captures[mobile_number]['frustum'] = line_mesh_geoms [vis.add_geometry(l) for l in mobile_captures[mobile_number]['frustum']] # MESH vis.remove_geometry(mesh) mesh = o3d.io.read_triangle_mesh(os.path.join(mesh_folder, dataset_name, mf)) triangles = np.asarray(mesh.vertices) mesh.compute_vertex_normals() vis.add_geometry(mesh) if flag_viz_camera_rotation: vis.run() camera_parameter = vis.get_view_control().convert_to_pinhole_camera_parameters() flag_viz_camera_rotation = 0 vis.get_view_control().convert_from_pinhole_camera_parameters(camera_parameter) vis.poll_events() vis.update_renderer() if do_save: vis.capture_screen_image(os.path.join(dest_folder, '{:04d}.png'.format(c))) c += 1 vis.destroy_window()
[ 11748, 1280, 18, 67, 355, 267, 18, 67, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28686, 198, 11748, 33918, 198, 11748, 627, 9205, 295, 355, 627, 265, 198, 11748, 3384, 4487, 198, 198, 29113, 14468, 21017, 198, 7804, 4242, 21017, ...
1.769076
3,984
# Generate table creation sql # # generate_table_sql.py schema parser_output_dir # Assumes that <schema>_hist exists # # Example: python generate_table_sql.py zte_cm_2g "data\cm\zte\gsm\parsed\in" # # Change log: # 23/11/2017 Make columns below text fields for Ericsson 2G cnaiv2 dumps # INTERNAL_CELL.UHPRIOTHR, # INTERNAL_CELL.UQRXLEVMIN # INTERNAL_CELL.ULPRIOTHR, # INTERNAL_CELL.UMFI_ACTIVE, # INTERNAL_CELL. COVERAGEU # INTERNAL_CELL.UMFI_IDLE, # MSC.LAI and # BSC.CAPACITYLOCKS # # Licence: Apache 2.0 # import os import sys import csv if len(sys.argv) != 3: print("Format: {0} {1} {2}".format( os.path.basename(__file__), "<schema>", "<input_directory>")) sys.exit() schema= sys.argv[1] folder_name=sys.argv[2] print( "-- psql -U bodastage -d bodastage -a -f {0}.sql".format(schema)) print( "-- \i {0}_tables.sql".format(schema)) print ("") text_fields = ["LAI","CAPACITYLOCKS","UMFI_IDLE","ULPRIOTHR","UQRXLEVMIN","COVERAGEU","UHPRIOTHR", "reservedBy", "certificateContent_publicKey", "sectorCarrierRef", "trustedCertificates", "consistsOf","consistsOf","listOfNe", "equipmentClockPriorityTable","rfBranchRef", "syncRiPortCandidate", "transceiverRef","vsdatamulticastantennabranch", "associatedRadioNodes","ethernetPortRef","staticRoutes_ipAddress", "staticRoutes_networkMask", "staticRoutes_nextHopIpAddr","staticRoutes_redistribute","ipInterfaceMoRef","ipAccessHostRef", "physicalPortList","additionalText","candNeighborRel_enbId", "vlanRef","trDeviceRef","port","iubLinkUtranCell", "manages","iubLinkUtranCell", "FREQLST"] for file in os.listdir(folder_name): columns = [] sample_row = [] mo_table_sql="" mo_table_sql_hist="" full_path = folder_name + os.path.sep + file if file == ".gitignore" : continue with open(full_path, 'r') as csvfile: reader = csv.reader(csvfile, quoting=csv.QUOTE_NONE) for row in reader: if len(columns) == 0: columns = row continue if len(sample_row) == 0: sample_row = row break filename = os.path.basename(file) mo_name = filename.replace(".csv","") mo_table_sql = "CREATE TABLE IF NOT EXISTS {0}.{1}".format(schema,mo_name) mo_table_sql += "(" mo_table_sql_hist = "CREATE TABLE IF NOT EXISTS {0}_hist.{1}".format(schema,mo_name) mo_table_sql_hist += "(" length = len(columns) for idx in range(length): column = columns[idx] value = sample_row[idx] comma = "," if idx == length-1 : comma = "" #print("column: {0} value: {1} len(value):".format(column,value, len(value))) #print(sample_row) try: #@TODO: Handle datetime fields separately if column == "varDateTime": mo_table_sql += " \"{0}\" TIMESTAMP {1}".format(column,comma) mo_table_sql_hist += " \"{0}\" TIMESTAMP {1}".format(column,comma) #LAI,UMFI_ACTIVE,and CAPACITYLOCKS are from Ericsson CNAIv2 dumps elif len(value) > 250 or column in text_fields or column[-3:].lower() == 'ref' : mo_table_sql += " \"{0}\" text {1}".format(column,comma) mo_table_sql_hist += " \"{0}\" text {1}".format(column,comma) elif "_BIT" in column: mo_table_sql += " \"{0}\" char(5) {1}".format(column,comma) mo_table_sql_hist += " \"{0}\" char(5) {1}".format(column,comma) else: mo_table_sql += " \"{0}\" char(250) {1}".format(column,comma) mo_table_sql_hist += " \"{0}\" char(250) {1}".format(column,comma) except Exception as ex: mo_table_sql += " \"{0}\" text {1}".format(column,comma) mo_table_sql_hist += " \"{0}\" text {1}".format(column,comma) mo_table_sql += ");" mo_table_sql += "\n" mo_table_sql_hist += ");" mo_table_sql_hist += "\n" print( mo_table_sql) print( mo_table_sql_hist)
[ 2, 2980, 378, 3084, 6282, 44161, 198, 2, 220, 198, 2, 7716, 62, 11487, 62, 25410, 13, 9078, 32815, 30751, 62, 22915, 62, 15908, 198, 2, 2195, 8139, 326, 1279, 15952, 2611, 29, 62, 10034, 7160, 198, 2, 198, 2, 17934, 25, 21015, 771...
2.283136
1,607
from pyramid.httpexceptions import HTTPBadRequest, HTTPConflict, HTTPForbidden, HTTPInternalServerError, HTTPOk from pyramid.settings import asbool from pyramid.view import view_config from magpie import models from magpie.api import exception as ax from magpie.api import requests as ar from magpie.api import schemas as s from magpie.api.management.resource import resource_formats as rf from magpie.api.management.resource import resource_utils as ru from magpie.api.management.service.service_formats import format_service_resources from magpie.api.management.service.service_utils import get_services_by_type from magpie.permissions import PermissionType, format_permissions from magpie.register import sync_services_phoenix from magpie.services import SERVICE_TYPE_DICT @s.ResourcesAPI.get(tags=[s.ResourcesTag], response_schemas=s.Resources_GET_responses) @view_config(route_name=s.ResourcesAPI.name, request_method="GET") def get_resources_view(request): """ List all registered resources. """ res_json = {} for svc_type in SERVICE_TYPE_DICT: services = get_services_by_type(svc_type, db_session=request.db) res_json[svc_type] = {} for svc in services: res_json[svc_type][svc.resource_name] = format_service_resources( svc, request.db, show_all_children=True, show_private_url=False) res_json = {"resources": res_json} return ax.valid_http(http_success=HTTPOk, detail=s.Resources_GET_OkResponseSchema.description, content=res_json) @s.ResourceAPI.get(schema=s.Resource_GET_RequestSchema, tags=[s.ResourcesTag], response_schemas=s.Resource_GET_responses) @view_config(route_name=s.ResourceAPI.name, request_method="GET") def get_resource_view(request): """ Get resource information. """ resource = ar.get_resource_matchdict_checked(request) res_json = ax.evaluate_call(lambda: rf.format_resource_with_children(resource, db_session=request.db), fallback=lambda: request.db.rollback(), http_error=HTTPInternalServerError, msg_on_fail=s.Resource_GET_InternalServerErrorResponseSchema.description, content={"resource": rf.format_resource(resource, basic_info=False)}) return ax.valid_http(http_success=HTTPOk, content={"resource": res_json}, detail=s.Resource_GET_OkResponseSchema.description) @s.ResourcesAPI.post(schema=s.Resources_POST_RequestSchema, tags=[s.ResourcesTag], response_schemas=s.Resources_POST_responses) @view_config(route_name=s.ResourcesAPI.name, request_method="POST") def create_resource_view(request): """ Register a new resource. """ resource_name = ar.get_value_multiformat_body_checked(request, "resource_name") resource_display_name = ar.get_multiformat_body(request, "resource_display_name", default=resource_name) resource_type = ar.get_value_multiformat_body_checked(request, "resource_type") parent_id = ar.get_value_multiformat_body_checked(request, "parent_id", check_type=int) return ru.create_resource(resource_name, resource_display_name, resource_type, parent_id, request.db) @s.ResourceAPI.delete(schema=s.Resource_DELETE_RequestSchema, tags=[s.ResourcesTag], response_schemas=s.Resources_DELETE_responses) @view_config(route_name=s.ResourceAPI.name, request_method="DELETE") def delete_resource_view(request): """ Unregister a resource. """ return ru.delete_resource(request) @s.ResourceAPI.patch(schema=s.Resource_PATCH_RequestSchema, tags=[s.ResourcesTag], response_schemas=s.Resource_PATCH_responses) @view_config(route_name=s.ResourceAPI.name, request_method="PATCH") def update_resource(request): """ Update a resource information. """ resource = ar.get_resource_matchdict_checked(request, "resource_id") service_push = asbool(ar.get_multiformat_body(request, "service_push", default=False)) res_old_name = resource.resource_name res_new_name = ar.get_value_multiformat_body_checked(request, "resource_name") ax.verify_param(res_new_name, not_equal=True, param_compare=res_old_name, param_name="resource_name", http_error=HTTPBadRequest, msg_on_fail=s.Resource_PATCH_BadRequestResponseSchema.description) db_session = request.db # check for conflicting name, either with services or children resources err_msg = s.Resource_PATCH_ConflictResponseSchema.description is_res_svc = resource.resource_type == models.Service.resource_type_name if is_res_svc: all_services = db_session.query(models.Service) all_svc_names = [svc.resource_name for svc in all_services] ax.verify_param(res_new_name, not_in=True, param_compare=all_svc_names, with_param=False, http_error=HTTPConflict, content={"resource_name": str(res_new_name)}, msg_on_fail=err_msg) else: ru.check_unique_child_resource_name(res_new_name, resource.parent_id, err_msg, db_session=db_session) ax.evaluate_call(lambda: rename_service_magpie_and_phoenix(), fallback=lambda: db_session.rollback(), http_error=HTTPForbidden, msg_on_fail=s.Resource_PATCH_ForbiddenResponseSchema.description, content={"resource_id": resource.resource_id, "resource_name": resource.resource_name, "old_resource_name": res_old_name, "new_resource_name": res_new_name}) return ax.valid_http(http_success=HTTPOk, detail=s.Resource_PATCH_OkResponseSchema.description, content={"resource_id": resource.resource_id, "resource_name": resource.resource_name, "old_resource_name": res_old_name, "new_resource_name": res_new_name}) @s.ResourcePermissionsAPI.get(schema=s.ResourcePermissions_GET_RequestSchema, tags=[s.ResourcesTag], response_schemas=s.ResourcePermissions_GET_responses) @view_config(route_name=s.ResourcePermissionsAPI.name, request_method="GET") def get_resource_permissions_view(request): """ List all applicable permissions for a resource. """ resource = ar.get_resource_matchdict_checked(request, "resource_id") res_perm = ax.evaluate_call(lambda: ru.get_resource_permissions(resource, db_session=request.db), fallback=lambda: request.db.rollback(), http_error=HTTPBadRequest, msg_on_fail=s.ResourcePermissions_GET_BadRequestResponseSchema.description, content={"resource": rf.format_resource(resource, basic_info=True)}) return ax.valid_http(http_success=HTTPOk, detail=s.ResourcePermissions_GET_OkResponseSchema.description, content=format_permissions(res_perm, PermissionType.ALLOWED))
[ 6738, 27944, 13, 2804, 24900, 11755, 1330, 14626, 22069, 18453, 11, 14626, 18546, 13758, 11, 14626, 1890, 37978, 11, 14626, 37693, 10697, 12331, 11, 14626, 18690, 198, 6738, 27944, 13, 33692, 1330, 355, 30388, 198, 6738, 27944, 13, 1177, ...
2.553137
2,710
from pprint import pprint from aim.engine.repo.repo import AimRepo from aim.ql.grammar.statement import Statement if __name__ == '__main__': repo = AimRepo.get_working_repo(mode='r') query = 'metric_2, metric ' \ ' if experiment in (test_metrics, test_metrics_2)' \ ' and context.foo == baz and params.default.baz > 1' parser = Statement() parsed_stmt = parser.parse(query) statement_select = parsed_stmt.node['select'] statement_expr = parsed_stmt.node['expression'] res = repo.select(statement_select, statement_expr) runs_list = [] for run in res.runs: runs_list.append(run.to_dict(include_only_selected_agg_metrics=True)) pprint(runs_list)
[ 6738, 279, 4798, 1330, 279, 4798, 198, 198, 6738, 4031, 13, 18392, 13, 260, 7501, 13, 260, 7501, 1330, 36223, 6207, 78, 198, 6738, 4031, 13, 13976, 13, 4546, 3876, 13, 26090, 1330, 21983, 628, 198, 361, 11593, 3672, 834, 6624, 705, ...
2.567376
282
import requests from EvaMap.Metrics.metric import metric
[ 11748, 7007, 198, 198, 6738, 32355, 13912, 13, 9171, 10466, 13, 4164, 1173, 1330, 18663, 198 ]
3.625
16
from volga.format import Format from volga.protocols import supportsDeserialization class Schema(supportsDeserialization): """[summary] :param supportsDeserialization: [description] :type supportsDeserialization: [type] """ def __init__(self) -> None: """[summary]""" ... def __deserialize__(self, format: Format) -> None: """[summary] :param format: [description] :type format: Format """ return
[ 6738, 2322, 4908, 13, 18982, 1330, 18980, 198, 6738, 2322, 4908, 13, 11235, 4668, 82, 1330, 6971, 5960, 48499, 1634, 628, 198, 4871, 10011, 2611, 7, 18608, 2096, 5960, 48499, 1634, 2599, 198, 220, 220, 220, 13538, 17912, 49736, 60, 628,...
2.569149
188
static = """ bumped = lhs; """ inc = """ bumped = lhs + 1; """ sum = """ bumped = lhs + i; """ vsids = """ if (i % 256 == 0) unbumped = lhs * 0.5; bumped = lhs + 1; """ nvsids = """ unbumped = 0.8 * lhs; bumped = lhs + (1 - 0.8); """ evsids = """ bumped = lhs + inc; ninc = lhs * (1 / 0.8); """ acids = """ bumped = (lhs + i) / 2; """ vmtf = """ bumped = i; """ gen1 = """ if (i == 512) unbumped = inc * 0.9 + 1 / 128; bumped = 2 * 0.4 + i; if (i >= i) ninc = lhs; """ hard_37 = """ if (128 + i % i == i * i) unbumped = lhs / i + i + i * i * lhs; bumped = lhs + inc; if (32 >= 6) ninc = lhs + lhs / 256; """ dsl_36 = """ bumped = inc / i + i / i / 0.9; ninc = i / 8 + inc; """ stgp_37 = """ if (512 == i) unbumped = i - lhs * i; bumped = i; if (4 == 512) ninc = i; """ stgp_hard_37 = """ if (i >= i) unbumped = lhs * 1024; bumped = lhs + inc; ninc = 64 + 16; """ monkeys = """ unbumped = (lhs + 2) * ((0.4 / 2) / 9); bumped = 0.9; ninc = inc; """ ratio = """ bumped = 32 - i + inc / 64 * inc; if ( i >= 5 ) ninc = lhs + 0 - 0.3 ; """ par_37 = """ bumped = i + i / 16 + lhs - 0.5 * lhs / 6; if ( i * 1024 == 0) ninc = inc / 256 / 0.9 - i; """
[ 12708, 796, 37227, 198, 220, 220, 220, 220, 220, 220, 220, 38034, 796, 300, 11994, 26, 198, 220, 220, 220, 37227, 198, 1939, 796, 37227, 198, 220, 220, 220, 220, 220, 220, 220, 38034, 796, 300, 11994, 1343, 352, 26, 198, 220, 220, ...
1.715859
908
#---------------------------------------------------------------------- # Copyright (c) 2011-2016 Raytheon BBN Technologies # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and/or hardware specification (the "Work") to # deal in the Work without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Work, and to permit persons to whom the Work # is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Work. # # THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS # IN THE WORK. #---------------------------------------------------------------------- import tools.pluginmanager as pm from chapi.Clearinghouse import CHv1Handler, CHv1DelegateBase from chapi.MemberAuthority import MAv1Handler, MAv1DelegateBase from chapi.SliceAuthority import SAv1Handler, SAv1DelegateBase from chapi.GuardBase import GuardBase from chapi.Parameters import set_parameters, configure_logging
[ 2, 10097, 23031, 198, 2, 15069, 357, 66, 8, 2813, 12, 5304, 7760, 1169, 261, 12597, 45, 21852, 198, 2, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 198, 2, 257, 4866, 286, 428, 3788, 290, ...
3.911168
394
from ipykernel.kernelapp import IPKernelApp from .kernel import CafKernel IPKernelApp.launch_instance(kernel_class=CafKernel)
[ 6738, 20966, 88, 33885, 13, 33885, 1324, 1330, 6101, 42, 7948, 4677, 198, 6738, 764, 33885, 1330, 35046, 42, 7948, 198, 4061, 42, 7948, 4677, 13, 35681, 62, 39098, 7, 33885, 62, 4871, 28, 34, 1878, 42, 7948, 8, 198 ]
3.15
40
from __future__ import print_function from __future__ import unicode_literals import pwd from .exceptions import ValidationError def validator(func): """ :param: none_if_invalid """ return inline @validator @validator
[ 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 11748, 279, 16993, 198, 198, 6738, 764, 1069, 11755, 1330, 3254, 24765, 12331, 628, 198, 4299, 4938, 1352, 7, 2078...
2.963415
82
""" Basic text-based table classes """ import texttab.const as const from texttab.const import FG_COLOURS, BG_COLOURS
[ 37811, 198, 26416, 2420, 12, 3106, 3084, 6097, 198, 37811, 198, 11748, 2420, 8658, 13, 9979, 355, 1500, 198, 6738, 2420, 8658, 13, 9979, 1330, 25503, 62, 25154, 2606, 6998, 11, 34839, 62, 25154, 2606, 6998, 628 ]
3.216216
37
import unittest from reamber.algorithms.generate.sv.SvSequence import SvSequence, SvObj if __name__ == '__main__': unittest.main()
[ 11748, 555, 715, 395, 198, 198, 6738, 302, 7789, 13, 282, 7727, 907, 13, 8612, 378, 13, 21370, 13, 50, 85, 44015, 594, 1330, 44343, 44015, 594, 11, 44343, 49201, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 1035...
2.574074
54
# Generated by Django 3.2.6 on 2021-08-22 07:57 from django.db import migrations
[ 2, 2980, 515, 416, 37770, 513, 13, 17, 13, 21, 319, 33448, 12, 2919, 12, 1828, 8753, 25, 3553, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 628 ]
2.766667
30
# jsb/socklib/xmpp/presence.py # # """ Presence. """ # jsb imports from jsb.lib.eventbase import EventBase from jsb.utils.trace import whichmodule from jsb.lib.gozerevent import GozerEvent ## basic imports import time import logging ## classes
[ 2, 474, 36299, 14, 82, 735, 8019, 14, 87, 76, 381, 14, 18302, 594, 13, 9078, 198, 2, 198, 2, 198, 198, 37811, 46523, 13, 37227, 198, 198, 2, 474, 36299, 17944, 198, 198, 6738, 474, 36299, 13, 8019, 13, 15596, 8692, 1330, 8558, 1...
2.820225
89
#! python3 from itertools import chain KING_CACHE = [king_moves(i) for i in range(64)] NIGHT_CACHE = [night_moves(i) for i in range(64)] VERTICAL_CACHE = [vertical_moves(i) for i in range(64)] DIAGONAL_CACHE = [diagonal_moves(i) for i in range(64)] if __name__ == "__main__": from main import run run()
[ 2, 0, 21015, 18, 198, 6738, 340, 861, 10141, 1330, 6333, 198, 198, 37286, 62, 34, 2246, 13909, 796, 685, 3364, 62, 76, 5241, 7, 72, 8, 329, 1312, 287, 2837, 7, 2414, 15437, 198, 198, 45, 9947, 62, 34, 2246, 13909, 796, 685, 3847...
2.29078
141
# proxy module from __future__ import absolute_import from chaco.scales.scales import *
[ 2, 15741, 8265, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 6738, 442, 10602, 13, 1416, 2040, 13, 1416, 2040, 1330, 1635, 198 ]
3.52
25
import construct as cs import construct_typed as cst import dataclasses import typing as t from . import GalleryItem @dataclasses.dataclass constr = "renamed_test" / cst.DataclassStruct(RenamedTest) gallery_item = GalleryItem( construct=constr, example_binarys={ "Zeros": bytes(constr.sizeof()), }, )
[ 11748, 5678, 355, 50115, 198, 11748, 5678, 62, 774, 9124, 355, 269, 301, 198, 11748, 4818, 330, 28958, 198, 11748, 19720, 355, 256, 198, 6738, 764, 1330, 12917, 7449, 628, 198, 31, 19608, 330, 28958, 13, 19608, 330, 31172, 628, 198, 1...
2.754237
118
version = (0, 5, 1)
[ 9641, 796, 357, 15, 11, 642, 11, 352, 8, 198 ]
2
10
# =========================================================================== # # SINGLETON METACLASS # # =========================================================================== # # =========================================================================== # # Project: ML Studio # # Version: 0.1.14 # # File: \singleton.py # # Python Version: 3.7.3 # # --------------- # # Author: John James # # Company: Decision Scients # # Email: jjames@decisionscients.com # # --------------- # # Create Date: Friday December 20th 2019, 8:29:22 am # # Last Modified: Friday December 20th 2019, 8:30:29 am # # Modified By: John James (jjames@decisionscients.com) # # --------------- # # License: Modified BSD # # Copyright (c) 2019 Decision Scients # # =========================================================================== # """Provides an alternative to the Singleton pattern, using the Borg superclass. More information about the Borg 'nonpattern' may be obtained from https://learning.oreilly.com/library/view/python-cookbook/0596001673/ch05s23.html To implement, simply subclass this class and call the __init__ method just as you always do for every base class's constructor. """
[ 2, 38093, 2559, 855, 1303, 198, 2, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 311, 2751, 2538, 11357, 31243, 2246, 43, 10705, 220, 220, 220, ...
1.84507
1,065
MODE_ARM = 0 MODE_THUMB = 1 MODE_JAZELLE = 2 #IFLAGS - keep bottom 8-bits for cross-platform flags like envi.IF_NOFALL and envi.IF_BRFALL IF_PSR_S = 1<<32 # This DP instruciton can update CPSR IF_B = 1<<33 # Byte IF_H = 1<<35 # HalfWord IF_S = 1<<36 # Signed IF_D = 1<<37 # Dword IF_L = 1<<38 # Long-store (eg. Dblword Precision) for STC IF_T = 1<<39 # Translate for strCCbt IF_W = 1<<40 # Write Back for STM/LDM (!) IF_UM = 1<<41 # User Mode Registers for STM/LDM (^) (obviously no R15) IF_DAIB_SHFT = 56 # shift-bits to get DAIB bits down to 0. this chops off the "is DAIB present" bit that the following store. IF_DAIB_MASK = 7<<(IF_DAIB_SHFT-1) IF_DA = 1<<(IF_DAIB_SHFT-1) # Decrement After IF_IA = 3<<(IF_DAIB_SHFT-1) # Increment After IF_DB = 5<<(IF_DAIB_SHFT-1) # Decrement Before IF_IB = 7<<(IF_DAIB_SHFT-1) # Increment Before IF_DAIB_B = 5<<(IF_DAIB_SHFT-1) # Before mask IF_DAIB_I = 3<<(IF_DAIB_SHFT-1) # Before mask IF_THUMB32 = 1<<50 # thumb32 IF_VQ = 1<<51 # Adv SIMD: operation uses saturating arithmetic IF_VR = 1<<52 # Adv SIMD: operation performs rounding IF_VD = 1<<53 # Adv SIMD: operation doubles the result IF_VH = 1<<54 # Adv SIMD: operation halves the result OF_W = 1<<8 # Write back to OF_UM = 1<<9 # Usermode, or if r15 included set current SPSR -> CPSR OSZFMT_BYTE = "B" OSZFMT_HWORD = "<H" # Introduced in ARMv4 OSZFMT_WORD = "<L" OSZ_BYTE = 1 OSZ_HWORD = 2 OSZ_WORD = 4 fmts = [None, OSZ_BYTE, OSZ_HWORD, None, OSZ_WORD] COND_EQ = 0x0 # z==1 (equal) COND_NE = 0x1 # z==0 (not equal) COND_CS = 0x2 # c==1 (carry set/unsigned higher or same) COND_CC = 0x3 # c==0 (carry clear/unsigned lower) COND_MI = 0x4 # n==1 (minus/negative) COND_PL = 0x5 # n==0 (plus/positive or zero) COND_VS = 0x6 # v==1 (overflow) COND_VC = 0x7 # v==0 (no overflow) COND_HI = 0x8 # c==1 and z==0 (unsigned higher) COND_LO = 0x9 # c==0 or z==1 (unsigned lower or same) COND_GE = 0xA # n==v (signed greater than or equal) (n==1 and v==1) or (n==0 and v==0) COND_LT = 0xB # n!=v (signed less than) (n==1 and v==0) or (n==0 and v==1) COND_GT = 0xC # z==0 and n==v (signed greater than) COND_LE = 0xD # z==1 and n!=v (signed less than or equal) COND_AL = 0xE # always COND_EXTENDED = 0xF # special case - see conditional 0b1111 cond_codes = { COND_EQ:"eq", # Equal Z set COND_NE:"ne", # Not equal Z clear COND_CS:"cs", #/HS Carry set/unsigned higher or same C set COND_CC:"cc", #/LO Carry clear/unsigned lower C clear COND_MI:"mi", # Minus/negative N set COND_PL:"pl", # Plus/positive or zero N clear COND_VS:"vs", # Overflow V set COND_VC:"vc", # No overflow V clear COND_HI:"hi", # Unsigned higher C set and Z clear COND_LO:"lo", # Unsigned lower or same C clear or Z set COND_GE:"ge", # Signed greater than or equal N set and V set, or N clear and V clear (N == V) COND_LT:"lt", # Signed less than N set and V clear, or N clear and V set (N!= V) COND_GT:"gt", # Signed greater than Z clear, and either N set and V set, or N clear and V clear (Z == 0,N == V) COND_LE:"le", # Signed less than or equal Z set, or N set and V clear, or N clear and V set (Z == 1 or N!= V) COND_AL:"", # Always (unconditional) - could be "al" but "" seems better... COND_EXTENDED:"2", # See extended opcode table } PM_usr = 0b10000 PM_fiq = 0b10001 PM_irq = 0b10010 PM_svc = 0b10011 PM_abt = 0b10111 PM_und = 0b11011 PM_sys = 0b11111 # reg stuff stolen from regs.py to support proc_modes REG_OFFSET_USR = 17 * (PM_usr&0xf) REG_OFFSET_FIQ = 17 * (PM_fiq&0xf) REG_OFFSET_IRQ = 17 * (PM_irq&0xf) REG_OFFSET_SVC = 17 * (PM_svc&0xf) REG_OFFSET_ABT = 17 * (PM_abt&0xf) REG_OFFSET_UND = 17 * (PM_und&0xf) REG_OFFSET_SYS = 17 * (PM_sys&0xf) #REG_OFFSET_CPSR = 17 * 16 REG_OFFSET_CPSR = 16 # CPSR is available in every mode, and PM_usr and PM_sys don't have an SPSR. REG_SPSR_usr = REG_OFFSET_USR + 16 REG_SPSR_fiq = REG_OFFSET_FIQ + 16 REG_SPSR_irq = REG_OFFSET_IRQ + 16 REG_SPSR_svc = REG_OFFSET_SVC + 16 REG_SPSR_abt = REG_OFFSET_ABT + 16 REG_SPSR_und = REG_OFFSET_UND + 16 REG_SPSR_sys = REG_OFFSET_SYS + 16 REG_PC = 0xf REG_SP = 0xd REG_BP = None REG_CPSR = REG_OFFSET_CPSR REG_FLAGS = REG_OFFSET_CPSR #same location, backward-compat name proc_modes = { # mode_name, short_name, description, offset, mode_reg_count, PSR_offset PM_usr: ("User Processor Mode", "usr", "Normal program execution mode", REG_OFFSET_USR, 15, REG_SPSR_usr), PM_fiq: ("FIQ Processor Mode", "fiq", "Supports a high-speed data transfer or channel process", REG_OFFSET_FIQ, 8, REG_SPSR_fiq), PM_irq: ("IRQ Processor Mode", "irq", "Used for general-purpose interrupt handling", REG_OFFSET_IRQ, 13, REG_SPSR_irq), PM_svc: ("Supervisor Processor Mode", "svc", "A protected mode for the operating system", REG_OFFSET_SVC, 13, REG_SPSR_svc), PM_abt: ("Abort Processor Mode", "abt", "Implements virtual memory and/or memory protection", REG_OFFSET_ABT, 13, REG_SPSR_abt), PM_und: ("Undefined Processor Mode", "und", "Supports software emulation of hardware coprocessor", REG_OFFSET_UND, 13, REG_SPSR_und), PM_sys: ("System Processor Mode", "sys", "Runs privileged operating system tasks (ARMv4 and above)", REG_OFFSET_SYS, 15, REG_SPSR_sys), } PM_LNAME = 0 PM_SNAME = 1 PM_DESC = 2 PM_REGOFF = 3 PM_BANKED = 4 PM_SPSR = 5 INST_ENC_DP_IMM = 0 # Data Processing Immediate Shift INST_ENC_MISC = 1 # Misc Instructions # Instruction encodings in arm v5 IENC_DP_IMM_SHIFT = 0 # Data processing immediate shift IENC_MISC = 1 # Miscellaneous instructions IENC_MISC1 = 2 # Miscellaneous instructions again IENC_DP_REG_SHIFT = 3 # Data processing register shift IENC_MULT = 4 # Multiplies & Extra load/stores IENC_UNDEF = 5 # Undefined instruction IENC_MOV_IMM_STAT = 6 # Move immediate to status register IENC_DP_IMM = 7 # Data processing immediate IENC_LOAD_IMM_OFF = 8 # Load/Store immediate offset IENC_LOAD_REG_OFF = 9 # Load/Store register offset IENC_ARCH_UNDEF = 10 # Architecturally undefined IENC_MEDIA = 11 # Media instructions IENC_LOAD_MULT = 12 # Load/Store Multiple IENC_BRANCH = 13 # Branch IENC_COPROC_RREG_XFER = 14 # mrrc/mcrr IENC_COPROC_LOAD = 15 # Coprocessor load/store and double reg xfers IENC_COPROC_DP = 16 # Coprocessor data processing IENC_COPROC_REG_XFER = 17 # Coprocessor register transfers IENC_SWINT = 18 # Sofware interrupts IENC_UNCOND = 19 # unconditional wacko instructions IENC_EXTRA_LOAD = 20 # extra load/store (swp) # offchutes IENC_MEDIA_PARALLEL = ((IENC_MEDIA << 8) + 1) << 8 IENC_MEDIA_SAT = ((IENC_MEDIA << 8) + 2) << 8 IENC_MEDIA_REV = ((IENC_MEDIA << 8) + 3) << 8 IENC_MEDIA_SEL = ((IENC_MEDIA << 8) + 4) << 8 IENC_MEDIA_USAD8 = ((IENC_MEDIA << 8) + 5) << 8 IENC_MEDIA_USADA8 = ((IENC_MEDIA << 8) + 6) << 8 IENC_MEDIA_EXTEND = ((IENC_MEDIA << 8) + 7) << 8 IENC_MEDIA_PACK = ((IENC_MEDIA << 8) + 8) << 8 IENC_UNCOND_CPS = ((IENC_UNCOND << 8) + 1) << 8 IENC_UNCOND_SETEND = ((IENC_UNCOND << 8) + 2) << 8 IENC_UNCOND_PLD = ((IENC_UNCOND << 8) + 3) << 8 IENC_UNCOND_BLX = ((IENC_UNCOND << 8) + 4) << 8 IENC_UNCOND_RFE = ((IENC_UNCOND << 8) + 5) << 8 # The supported types of operand shifts (by the 2 bit field) S_LSL = 0 S_LSR = 1 S_ASR = 2 S_ROR = 3 S_RRX = 4 # FIXME HACK XXX add this shift_names = ("lsl", "lsr", "asr", "ror", "rrx") SOT_REG = 0 SOT_IMM = 1 daib = ("da", "ia", "db", "ib") INS_AND = IENC_DP_IMM_SHIFT << 16 INS_EOR = (IENC_DP_IMM_SHIFT << 16) + 1 INS_SUB = (IENC_DP_IMM_SHIFT << 16) + 2 INS_RSB = (IENC_DP_IMM_SHIFT << 16) + 3 INS_ADD = (IENC_DP_IMM_SHIFT << 16) + 4 INS_ADC = (IENC_DP_IMM_SHIFT << 16) + 5 INS_SBC = (IENC_DP_IMM_SHIFT << 16) + 6 INS_RSC = (IENC_DP_IMM_SHIFT << 16) + 7 INS_TST = (IENC_DP_IMM_SHIFT << 16) + 8 INS_TEQ = (IENC_DP_IMM_SHIFT << 16) + 9 INS_CMP = (IENC_DP_IMM_SHIFT << 16) + 10 INS_CMN = (IENC_DP_IMM_SHIFT << 16) + 11 INS_ORR = (IENC_DP_IMM_SHIFT << 16) + 12 INS_MOV = (IENC_DP_IMM_SHIFT << 16) + 13 INS_BIC = (IENC_DP_IMM_SHIFT << 16) + 14 INS_MVN = (IENC_DP_IMM_SHIFT << 16) + 15 INS_ORN = (IENC_DP_IMM_SHIFT << 16) + 12 INS_ADR = (IENC_DP_IMM_SHIFT << 16) + 16 INS_B = instrenc(IENC_BRANCH, 0) INS_BL = instrenc(IENC_BRANCH, 1) INS_BCC = instrenc(IENC_BRANCH, 2) INS_BX = instrenc(IENC_MISC, 3) INS_BXJ = instrenc(IENC_MISC, 5) INS_BLX = IENC_UNCOND_BLX INS_SWI = IENC_SWINT # FIXME: must fit these into the numbering scheme INS_TB = 85 INS_LDREX = 85 INS_ORN = 85 INS_PKH = 85 INS_LSL = 85 INS_LSR = 85 INS_ASR = 85 INS_ROR = 85 INS_RRX = 85 INS_LDR = instrenc(IENC_LOAD_IMM_OFF, 0) INS_STR = instrenc(IENC_LOAD_IMM_OFF, 1) no_update_Rd = (INS_TST, INS_TEQ, INS_CMP, INS_CMN, )
[ 49058, 62, 33456, 220, 220, 220, 220, 220, 220, 220, 796, 657, 198, 49058, 62, 4221, 5883, 33, 220, 220, 220, 220, 220, 796, 352, 198, 49058, 62, 41, 22778, 3698, 2538, 220, 220, 220, 796, 362, 198, 198, 2, 40, 38948, 50, 532, 1...
2.115304
4,293
# Generated by Django 3.1.8 on 2021-10-08 11:32 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 16, 13, 23, 319, 33448, 12, 940, 12, 2919, 1367, 25, 2624, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.84375
32
from django.contrib import admin from grage.maintenance.models import Maintenance, MaintenanceItem admin.site.register([ Maintenance, MaintenanceItem, ])
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 198, 6738, 1036, 496, 13, 12417, 8219, 13, 27530, 1330, 34857, 11, 34857, 7449, 198, 198, 28482, 13, 15654, 13, 30238, 26933, 198, 220, 220, 220, 34857, 11, 34857, 7449, 11, 198, 12...
3.72093
43
# Copyright (c) 2015, Michael Boyle # See LICENSE file for details: <https://github.com/moble/scri/blob/master/LICENSE> import os import inspect import functools import warnings import socket import datetime import pprint import copy import numpy as np import quaternion import scipy.constants as spc from scipy.interpolate import CubicSpline from . import * @jit("void(c16[:,:], f8[:])") @jit("void(c16[:,:], f8[:])") def waveform_alterations(func): """Temporarily increment history depth safely This decorator stores the value of `self.__history_depth__`, then increments it by 1, calls the function, returns the history depth to its original value, and then returns the result of the function. This should be used on any member function that could alter the waveform on which it is called, or which could return a new altered version of the original. Typically, within the function itself, you will want to decrement the depth manually just before appending to the history -- which will presumably take place at the end of the function. You do not need to undo this, as the decorator will take care of that part. """ @functools.wraps(func) return func_wrapper def test_without_assertions(errs, val, msg=""): """Replacement for np.testing.assert_ This function should be able to replace `assert_`, but rather than raising an exception, this just adds a description of the problem to the `errors` variable. """ if not val: try: smsg = msg() except TypeError: smsg = msg errs += [smsg] class _object: """Useless class to allow multiple inheritance""" class WaveformBase(_object): """Object containing time, frame, and data, along with related information This object is just the base object from which these other classes are derived: * WaveformModes * WaveformGrid * WaveformInDetector * WaveformInDetectorFT For more specific information, see the documentation of those classes. Attributes ---------- t : float array Time steps corresponding to other data frame : quaternion array Rotors taking static basis onto decomposition basis data : 2-d array of complex or real numbers The nature of this data depends on the derived type. First index is time, second index depends on type. history : list of strings As far as possible, all functions applied to the object are recorded in the `history` variable. In fact, the object should almost be able to be recreated using the commands in the history list. Commands taking large arrays, however, are shortened -- so the data will not be entirely reconstructable. version_hist : list of pairs of strings Records the git hash and description for any change in the way SpEC outputs waveform data. frameType : int Index corresponding to `scri.FrameType` appropriate for `data`. dataType : int Index corresponding to `scri.DataType` appropriate for `data`. r_is_scaled_out : bool True if the `data` have been multiplied by the appropriate power of radius so that the asymptotic value can be finite and nonzero. m_is_scaled_out : bool True if the `data` have been scaled by the appropriate value of the total mass so that they are dimensionless. num : int (read only) Automatically assigned number of this object. The constructor of this type keeps count of the number of objects it has created, to assign each object a more-or-less unique ID for use in the history strings. This counter is reset at the beginning of each python session. Subclasses should automatically have a different counter. Indexing -------- WaveformBase objects can be indexed much like a numpy array, where the first dimension gives the time indices, and the second gives the data-set indices. This will return another WaveformBase object containing slices of the original data. It is important to note, however, that as with numpy array slices, slicing a WaveformBase will not typically copy the original data; the result will simply be a view into the data. This means that changing the data in the slice can change the data in the original. If you want to make a copy, you should probably use the copy constructor: `W2 = WaveformBase(W1)`. It is also possible to use the standard copy.deepcopy method. Also note that the first slice dimension corresponds to the indices of the time, but the second dimension may NOT correspond to indices for derived types. In particular, for `WaveformModes`, the second index corresponds to modes, because this type enforces completeness of each ell mode. For the `WaveformBase` type, however, the second index does correspond to the second dimension of the data. For example, >>> W = WaveformBase() >>> W[10:-20] will give all columns in the data, but only at times starting with the 10th time step, and ending one before the -20th time step. Meanwhile, >>> W[10:-20,2] will give the same range of times, but only the second column (unless the subclass overrides this behavior, as in `WaveformModes`). Similarly, >>> W[10:-20,2:5] will return the same range of times, along with the 2,3,4 columns. Note the lack of 5 column, for consistency with python's usual slice syntax. >>> W[:,:0] will return all time steps, along with all `frame` data, but `data` will be empty (because the `:0` term selects everything before the 0th element). Similarly, >>> W[:0,:0] is empty of all numerical data. """ __num = 0 # Used to count number of Waveforms created def __init__(self, *args, **kwargs): """Initializer for WaveformBase object WaveformBase objects may be created in two ways. First, by copying an existing WaveformBase object -- in which case the only parameter should be that object. Second, by passing any of the (writable) attributes as keywords. In both cases, the last step in initialization is to check the validity of the result. By default, this will raise an exception if the result is not valid. An additional keyword parameter `override_exception_from_invalidity` may be set if this is not desired. This may be necessary if only some of the data can be passed in to the initializer, for example. Keyword parameters ------------------ t: float array, empty default frame : quaternion array, empty default data : 2-d complex array, empty default history : list of strings, empty default This is the list of strings prepended to the history, an additional line is appended, showing the call to this initializer. version_hist : list of pairs of strings, empty default Remains empty if waveform data is on version 0. frameType : int, defaults to 0 (UnknownFrameType) See scri.FrameNames for possible values dataType : int, defaults to 0 (UnknownDataType) See scri.DataNames for possible values r_is_scaled_out : bool, defaults to False Set to True if the data represented could approach a nonzero value at Scri m_is_scaled_out : bool, defaults to False Set to True if the data represented are dimensionless and in units where the total mass is 1 override_exception_from_invalidity: bool, defaults to False If True, report any errors, but do not raise them. constructor_statement : str, optional If this is present, it will replace the default constructor statement added to the history. It is prepended with a string of the form `'{0} = '.format(self)`, which prints the ID of the resulting object (unique to this session only). """ original_kwargs = kwargs.copy() super().__init__(*args, **kwargs) # to ensure proper calling in multiple inheritance override_exception_from_invalidity = kwargs.pop("override_exception_from_invalidity", False) self.__num = type(self).__num self.__history_depth__ = 0 type(self).__num += 1 # Increment class's instance tracker if len(args) == 0: self.t = kwargs.pop("t", np.empty((0,), dtype=float)) self.frame = kwargs.pop("frame", np.empty((0,), dtype=np.quaternion)) self.data = kwargs.pop("data", np.empty((0, 0), dtype=complex)) # Information about this object self.history = kwargs.pop("history", []) self.version_hist = kwargs.pop("version_hist", []) self.frameType = kwargs.pop("frameType", UnknownFrameType) self.dataType = kwargs.pop("dataType", UnknownDataType) self.r_is_scaled_out = kwargs.pop("r_is_scaled_out", False) self.m_is_scaled_out = kwargs.pop("m_is_scaled_out", False) if "constructor_statement" in kwargs: self._append_history("{} = {}".format(self, kwargs.pop("constructor_statement"))) else: opts = np.get_printoptions() np.set_printoptions(threshold=6) self._append_history( "{} = {}(**{})".format(self, type(self).__name__, pprint.pformat(original_kwargs, indent=4)) ) np.set_printoptions(**opts) elif len(args) == 1 and isinstance(args[0], type(self)): other = args[0] self.t = np.copy(other.t) self.frame = np.copy(other.frame) self.data = np.copy(other.data) # Information about this object self.history = other.history[:] self.version_hist = other.version_hist[:] self.frameType = other.frameType self.dataType = other.dataType self.r_is_scaled_out = other.r_is_scaled_out self.m_is_scaled_out = other.m_is_scaled_out self._append_history(["", "{} = {}({})".format(self, type(self).__name__, other)]) else: raise ValueError( "Did not understand input arguments to `{}` constructor.\n".format(type(self).__name__) + "Note that explicit data values must be passed as keywords,\n" + "whereas objects to be copied must be passed as the sole argument." ) hostname = socket.gethostname() cwd = os.getcwd() time = datetime.datetime.now().isoformat() self.__history_depth__ = 1 self.ensure_validity(alter=True, assertions=(not override_exception_from_invalidity)) self.__history_depth__ = 0 self._append_history([f"hostname = {hostname}", f"cwd = {cwd}", f"datetime = {time}", version_info()], 1) if kwargs: warning = "\nIn `{}` initializer, unused keyword arguments:\n".format(type(self).__name__) warning += pprint.pformat(kwargs, indent=4) warnings.warn(warning) @waveform_alterations def ensure_validity(self, alter=True, assertions=False): """Try to ensure that the `WaveformBase` object is valid This tests various qualities of the WaveformBase's members that are frequently assumed throughout the code. If the optional argument `alter` is `True` (which is the default), this function tries to alter the WaveformBase in place to ensure validity. Note that this is not always possible. If that is the case, an exception may be raised. For example, if the `t` member is not a one-dimensional array of floats, it is not clear what that data should be. Similarly, if the `t` and `data` members have mismatched dimensions, there is no way to resolve that automatically. Also note that this is almost certainly not be an exhaustive test of all assumptions made in the code. If the optional `assertions` argument is `True` (default is `False`), the first test that fails will raise an assertion error. """ import numbers errors = [] alterations = [] if assertions: test = test_with_assertions else: test = test_without_assertions # Ensure that the various data are correct and compatible test( errors, isinstance(self.t, np.ndarray), "isinstance(self.t, np.ndarray) # type(self.t)={}".format(type(self.t)), ) test( errors, self.t.dtype == np.dtype(np.float), f"self.t.dtype == np.dtype(np.float) # self.t.dtype={self.t.dtype}", ) if alter and self.t.ndim == 2 and self.t.shape[1] == 1: self.t = self.t[:, 0] alterations += ["{0}.t = {0}.t[:,0]".format(self)] test( errors, not self.t.size or self.t.ndim == 1, f"not self.t.size or self.t.ndim==1 # self.t.size={self.t.size}; self.t.ndim={self.t.ndim}", ) test( errors, self.t.size <= 1 or np.all(np.diff(self.t) > 0.0), "self.t.size<=1 or np.all(np.diff(self.t)>0.0) " "# self.t.size={}; max(np.diff(self.t))={}".format( self.t.size, (max(np.diff(self.t)) if self.t.size > 1 else np.nan) ), ) test(errors, np.all(np.isfinite(self.t)), "np.all(np.isfinite(self.t))") if alter and self.frame is None: self.frame = np.empty((0,), dtype=np.quaternion) alterations += [f"{self}.frame = np.empty((0,), dtype=np.quaternion)"] test( errors, isinstance(self.frame, np.ndarray), "isinstance(self.frame, np.ndarray) # type(self.frame)={}".format(type(self.frame)), ) if alter and self.frame.dtype == np.dtype(np.float): try: # Might fail because of shape self.frame = quaternion.as_quat_array(self.frame) alterations += ["{0}.frame = quaternion.as_quat_array({0}.frame)".format(self)] except (AssertionError, ValueError): pass test( errors, self.frame.dtype == np.dtype(np.quaternion), f"self.frame.dtype == np.dtype(np.quaternion) # self.frame.dtype={self.frame.dtype}", ) test( errors, self.frame.size <= 1 or self.frame.size == self.t.size, "self.frame.size<=1 or self.frame.size==self.t.size " "# self.frame.size={}; self.t.size={}".format(self.frame.size, self.t.size), ) test(errors, np.all(np.isfinite(self.frame)), "np.all(np.isfinite(self.frame))") test( errors, isinstance(self.data, np.ndarray), "isinstance(self.data, np.ndarray) # type(self.data)={}".format(type(self.data)), ) test(errors, self.data.ndim >= 1, f"self.data.ndim >= 1 # self.data.ndim={self.data.ndim}") test( errors, self.data.shape[0] == self.t.shape[0], "self.data.shape[0]==self.t.shape[0] " "# self.data.shape[0]={}; self.t.shape[0]={}".format(self.data.shape[0], self.t.shape[0]), ) test(errors, np.all(np.isfinite(self.data)), "np.all(np.isfinite(self.data))") # Information about this object if alter and not self.history: self.history = [""] alterations += [f"{self}.history = ['']"] if alter and isinstance(self.history, str): self.history = self.history.split("\n") alterations += ["{0}.history = {0}.history.split('\n')".format(self)] test( errors, isinstance(self.history, list), "isinstance(self.history, list) # type(self.history)={}".format(type(self.history)), ) test( errors, isinstance(self.history[0], str), "isinstance(self.history[0], str) # type(self.history[0])={}".format(type(self.history[0])), ) test( errors, isinstance(self.frameType, numbers.Integral), "isinstance(self.frameType, numbers.Integral) # type(self.frameType)={}".format(type(self.frameType)), ) test(errors, self.frameType in FrameType, f"self.frameType in FrameType # self.frameType={self.frameType}") test( errors, isinstance(self.dataType, numbers.Integral), "isinstance(self.dataType, numbers.Integral) # type(self.dataType)={}".format(type(self.dataType)), ) test(errors, self.dataType in DataType, f"self.dataType in DataType # self.dataType={self.dataType}") test( errors, isinstance(self.r_is_scaled_out, bool), "isinstance(self.r_is_scaled_out, bool) # type(self.r_is_scaled_out)={}".format(type(self.r_is_scaled_out)), ) test( errors, isinstance(self.m_is_scaled_out, bool), "isinstance(self.m_is_scaled_out, bool) # type(self.m_is_scaled_out)={}".format(type(self.m_is_scaled_out)), ) test( errors, isinstance(self.num, numbers.Integral), "isinstance(self.num, numbers.Integral) # type(self.num)={}".format(type(self.num)), ) if alterations: self._append_history(alterations) warnings.warn("The following alterations were made:\n\t" + "\n\t".join(alterations)) if errors: warnings.warn("The following conditions were found to be incorrectly False:\n\t" + "\n\t".join(errors)) return False self.__history_depth__ -= 1 self._append_history("WaveformBase.ensure_validity" + f"({self}, alter={alter}, assertions={assertions})") return True @property # Data sizes @property @property # Calculate weights @property @property @property def gamma_weight(self): """Non-conformal effect of a boost. This factor allows for mass-scaling, for example. If the waveform describes `r*h/M`, for example, then `r` and `h` vary by the conformal weight, which depends on the direction; whereas `M` is a monopole, and thus cannot depend on the direction. Instead, `M` simply obeys the standard formula, scaling with gamma. """ return (MScaling[self.dataType] if self.m_is_scaled_out else 0) + ( -RScaling[self.dataType] if (self.r_is_scaled_out and self.m_is_scaled_out) else 0 ) @property @property # Text descriptions @property @property @property @property @property def descriptor_string(self): """Create a simple string describing the content of the waveform This string will be suitable for file names. For example, 'rMpsi4' or 'rhOverM'. It uses the waveform's knowledge of itself, so if this is incorrect, the result will be incorrect. """ if self.dataType == UnknownDataType: return self.data_type_string descriptor = "" if self.r_is_scaled_out: if RScaling[self.dataType] == 1: descriptor = "r" elif RScaling[self.dataType] > 1: descriptor = "r" + str(RScaling[self.dataType]) if self.m_is_scaled_out: Mexponent = MScaling[self.dataType] - (RScaling[self.dataType] if self.r_is_scaled_out else 0) if Mexponent < -1: descriptor = descriptor + self.data_type_string + "OverM" + str(-Mexponent) elif Mexponent == -1: descriptor = descriptor + self.data_type_string + "OverM" elif Mexponent == 0: descriptor = descriptor + self.data_type_string elif Mexponent == 1: descriptor = descriptor + "M" + self.data_type_string elif Mexponent > 1: descriptor = descriptor + "M" + str(Mexponent) + self.data_type_string else: descriptor = descriptor + self.data_type_string return descriptor # Data simplifications @property @property @property @property def norm(self, take_sqrt=False, indices=slice(None, None, None)): """L2 norm of the waveform The optional arguments say whether to take the square-root of the norm at each time, and allow restriction to a slice of the data, respectively. """ if indices == slice(None, None, None): n = np.empty((self.n_times,), dtype=float) else: n = np.empty((self.t[indices].shape[0],), dtype=float) if take_sqrt: complex_array_abs(self.data_2d[indices], n) else: complex_array_norm(self.data_2d[indices], n) return n def max_norm_index(self, skip_fraction_of_data=4): """Index of time step with largest norm The optional argument skips a fraction of the data. The default is 4, which means that it only searches the last three-fourths of the data for the max. If 0 or 1 is input, this is ignored, and all the data is searched. """ if skip_fraction_of_data == 0 or skip_fraction_of_data == 1: indices = slice(None, None, None) return np.argmax(self.norm(indices=indices)) else: indices = slice(self.n_times // skip_fraction_of_data, None, None) return np.argmax(self.norm(indices=indices)) + (self.n_times // skip_fraction_of_data) def max_norm_time(self, skip_fraction_of_data=4): """Return time at which largest norm occurs in data See `help(max_norm_index)` for explanation of the optional argument. """ return self.t[self.max_norm_index(skip_fraction_of_data=skip_fraction_of_data)] def compare(self, w_a, min_time_step=0.005, min_time=-3.0e300): """Return a waveform with differences between the two inputs This function simply subtracts the data in this waveform from the data in Waveform A, and finds the rotation needed to take this frame into frame A. Note that the waveform data are stored as complex numbers, rather than as modulus and phase. """ from quaternion.means import mean_rotor_in_chordal_metric from scri.extrapolation import intersection import scri.waveform_modes if self.frameType != w_a.frameType: warning = ( "\nWarning:" + "\n This Waveform is in the " + self.frame_type_string + " frame," + "\n The Waveform in the argument is in the " + w_a.frame_type_string + " frame." + "\n Comparing them probably does not make sense.\n" ) warnings.warn(warning) if self.n_modes != w_a.n_modes: raise Exception( "Trying to compare waveforms with mismatched LM data." + "\nA.n_modes=" + str(w_a.n_modes) + "\tB.n_modes()=" + str(self.n_modes) ) new_times = intersection(self.t, w_a.t) w_c = scri.waveform_modes.WaveformModes( t=new_times, data=np.zeros((new_times.shape[0], self.n_modes), dtype=self.data.dtype), history=[], version_hist=self.version_hist, frameType=self.frameType, dataType=self.dataType, r_is_scaled_out=self.r_is_scaled_out, m_is_scaled_out=self.m_is_scaled_out, ell_min=self.ell_min, ell_max=self.ell_max, ) w_c.history += ["B.compare(A)\n"] w_c.history += ["### A.history.str():\n" + "".join(w_a.history)] w_c.history += ["### B.history.str():\n" + "".join(self.history)] w_c.history += ["### End of old histories from `compare`"] # Process the frame, depending on the sizes of the input frames if w_a.frame.shape[0] > 1 and self.frame.shape[0] > 1: # Find the frames interpolated to the appropriate times Aframe = quaternion.squad(w_a.frame, w_a.t, w_c.t) Bframe = quaternion.squad(self.frame, self.t, w_c.t) # Assign the data w_c.frame = Aframe * np.array([np.quaternion.inverse(v) for v in Bframe]) elif w_a.frame.shape[0] == 1 and self.frame.shape[0] > 1: # Find the frames interpolated to the appropriate times Bframe = np.quaternion.squad(self.frame, self.t, w_c.t) # Assign the data w_c.frame.resize(w_c.n_times) w_c.frame = w_a.frame[0] * np.array([np.quaternion.inverse(v) for v in Bframe]) elif w_a.frame.shape[0] > 1 and self.frame.shape[0] == 1: # Find the frames interpolated to the appropriate times Aframe = np.quaternion.squad(w_a.frame, w_a.t, w_c.t) # Assign the data w_c.frame.resize(w_c.n_times) w_c.frame = Aframe * np.quaternion.inverse(self.frame[0]) elif w_a.frame.shape[0] == 1 and self.frame.shape[0] == 1: # Assign the data w_c.frame = np.array(w_a.frame[0] * np.quaternions.inverse(self.frame[0])) elif w_a.frame.shape[0] == 0 and self.frame.shape[0] == 1: # Assign the data w_c.frame = np.array(np.quaternions.inverse(self.frame[0])) elif w_a.frame.shape[0] == 1 and self.frame.shape[0] == 1: # Assign the data w_c.frame = np.array(w_a.frame[0]) # else, leave the frame data empty # If the average frame rotor is closer to -1 than to 1, flip the sign if w_c.frame.shape[0] == w_c.n_times: R_m = mean_rotor_in_chordal_metric(w_c.frame, w_c.t) if quaternion.rotor_chordal_distance(R_m, -quaternion.one) < quaternion.rotor_chordal_distance( R_m, quaternion.one ): w_c.frame = -w_c.frame elif w_c.frame.shape[0] == 1: if quaternion.rotor_chordal_distance(w_c.frame[0], -quaternion.one) < quaternion.rotor_chordal_distance( w_c.frame[0], quaternion.one ): w_c.frame[0] = -w_c.frame[0] # Now loop over each mode filling in the waveform data for AMode in range(w_a.n_modes): # Assume that all the ell,m data are the same, but not necessarily in the same order BMode = self.index(w_a.LM[AMode][0], w_a.LM[AMode][1]) # Initialize the interpolators for this data set # (Can't just re-view here because data are not contiguous) splineReA = CubicSpline(w_a.t, w_a.data[:, AMode].real) splineImA = CubicSpline(w_a.t, w_a.data[:, AMode].imag) splineReB = CubicSpline(self.t, self.data[:, BMode].real) splineImB = CubicSpline(self.t, self.data[:, BMode].imag) # Assign the data from the transition w_c.data[:, AMode] = (splineReA(w_c.t) - splineReB(w_c.t)) + 1j * (splineImA(w_c.t) - splineImB(w_c.t)) return w_c @property @property @property @property # Data representations def _append_history(self, hist, additional_depth=0): """Add to the object's history log Input may be a single string or list of strings. Any newlines will be split into separate strings. Each such string is then prepended with a number of `#`s, indicating that the content of that line was called from within a member function, or is simply a piece of information relevant to the waveform. The idea behind this is that the history should be -- as nearly as possible -- a script that could be run to reproduce the waveform, so the lines beginning with `#` would not be run. The number of `#`s is controlled by the object's `__history_depth__` field and the optional input to this function; their sum is the number prepended. The user should never have to deal with this issue, but all member functions should increment the `__history_depth__` before calling another member function, and decrement it again as necessary before recording itself in the history. Also, for any lines added just for informational purposes (e.g., the hostname, pwd, date, and versions added in `__init__`), this function should be called with `1` as the optional argument. """ if not isinstance(hist, list): hist = [hist] self.history += [ "# " * (self.__history_depth__ + additional_depth) + hist_line for hist_element in hist for hist_line in hist_element.split("\n") ] def __getstate__(self): """Get state of object for copying and pickling The only nontrivial operation is with quaternions, since they can't currently be pickled automatically. We just view the frame array as a float array, and pickle as usual. Also, we remove the `num` value, because this will get reset properly on creation. """ state = copy.deepcopy(self.__dict__) state["frame"] = quaternion.as_float_array(self.frame) return state def __setstate__(self, state): """Set state of object for copying and pickling The only nontrivial operation is with quaternions, since they can't currently be pickled automatically. We just view the frame array as a float array, and unpickle as usual, then convert the float array back to a quaternion array. """ new_num = self.__num old_num = state.get("_WaveformBase__num") self.__dict__.update(state) # Make sure to preserve auto-incremented num self.__num = new_num self.frame = quaternion.as_quat_array(self.frame) self._append_history(f"copied, deepcopied, or unpickled as {self}", 1) self._append_history("{} = {}".format(self, f"{self}".replace(str(self.num), str(old_num)))) @waveform_alterations def deepcopy(self): """Return a deep copy of the object This is just an alias for `copy`, which is deep anyway. """ W = self.copy() W.__history_depth__ -= 1 W._append_history(f"{W} = {self}.deepcopy()") return W @waveform_alterations def copy(self): """Return a (deep) copy of the object Note that this also copies all members if the object is a subclass. If you want a forgetful WaveformBase object, you can simply use the copy constructor. """ W = type(self)() state = copy.deepcopy(self.__dict__) state.pop("_WaveformBase__num") W.__dict__.update(state) W.__history_depth__ -= 1 W._append_history(f"{W} = {self}.copy()") return W @waveform_alterations def copy_without_data(self): """Return a copy of the object, with empty `t`, `frame`, and `data` fields Note that subclasses may override this to set some related data members. For example, `WaveformModes.copy_without_data` sets the `ell_min` and `ell_max` fields appropriately. If you wish to only skip `t`, `frame`, and `data`, you can simply use `WaveformBase.copy_without_data(W)`. The latter is useful if, for example, you will only be making changes to those three fields, and want everything else preserved. Also note that some slicing operations can achieve similar -- but different -- goals. For example, `w = w[:, :0]` will simply empty `data` and `ells`, without affecting the `time` and `frame`. """ W = type(self)() state = copy.deepcopy(self.__dict__) state.pop("_WaveformBase__num") state.pop("t") state.pop("frame") state.pop("data") W.__dict__.update(state) W.__history_depth__ -= 1 W._append_history(f"{W} = {self}.copy_without_data()") return W def _allclose( self, other, report_all=True, rtol=1e-10, atol=1e-10, compare_history_beginnings=False, exceptions=[] ): """Check that member data in two waveforms are the same For data sets (time, modes, etc.), the numpy function `np.allclose` is used, with the input tolerances. See that function's documentation for more details. The `*__num` datum is always ignored. By default, the `history` is ignored, though this can be partially overridden -- in which case, the shortest subset of the histories is compared for exact equality. This is probably only appropriate for the case where one waveform was created from the other. Parameters ---------- other : object Another object subclassing WaveformBase to compare report_all: bool, optional Wait until all attributes have been checked (and reported on) before returning the verdict rtol : float, optional Relative tolerance to which to compare arrays (see np.allclose), defaults to 1e-10 atol : float, optional Absolute tolerance to which to compare arrays (see np.allclose), defaults to 1e-10 compare_history_beginnings: bool, optional Compare the shortest common part of the `history` fields for equality, defaults to False exceptions : list, optional Don't compare elements in this list, corresponding to keys in the object's `__dict__`, defaults to [] """ equality = True if not type(self) == type(other): # not isinstance(other, self.__class__): warnings.warn("\n (type(self)={}) != (type(other)={})".format(type(self), type(other))) equality = False if not report_all and not equality: return False for key, val in self.__dict__.items(): if key.endswith("__num") or key in exceptions: continue elif key == "history": if compare_history_beginnings: min_length = min(len(self.history), len(other.history)) if self.history[:min_length] != other.history[:min_length]: warnings.warn("\n `history` fields differ") equality = False elif key == "version_hist": if self.version_hist != other.version_hist: warnings.warn("\n `version_hist` fields differ") equality = False elif isinstance(val, np.ndarray): if val.dtype == np.quaternion: if not np.allclose( quaternion.as_float_array(val), quaternion.as_float_array(other.__dict__[key]), rtol, atol ): warnings.warn(f"\n `{key}` fields differ") equality = False elif not np.allclose(val, other.__dict__[key], rtol, atol): warnings.warn(f"\n `{key}` fields differ") equality = False else: if not val == other.__dict__[key]: warnings.warn( "\n (self.{0}={1}) != (other.{0}={2}) fields differ".format(key, val, other.__dict__[key]) ) equality = False if not report_all and not equality: return False return equality # Slicing @waveform_alterations def __getitem__(self, key): """Extract subsets of the data efficiently See the docstring of the WaveformBase class for examples. """ W = WaveformBase.copy_without_data(self) # Remove trivial tuple structure first if isinstance(key, tuple) and len(key) == 1: key = key[0] # Now figure out which type of return is desired if isinstance(key, tuple) and 2 <= len(key) <= self.n_data_sets: # Return a subset of the data from a subset of times W.t = self.t[key[0]] W.frame = self.frame[key[0]] W.data = self.data[key] elif isinstance(key, slice) or isinstance(key, int): # Return complete data from a subset of times (key is slice), or # return complete data from a single instant in time (key is int) W.t = self.t[key] W.frame = self.frame[key] W.data = self.data[key] else: raise ValueError("Could not understand input `{}` (of type `{}`) ".format(key, type(key))) W.__history_depth__ -= 1 W._append_history(f"{W} = {self}[{key}]") return W @waveform_alterations def interpolate(self, tprime): """Interpolate the frame and data onto the new set of time steps Note that only `t`, `frame`, and `data` are changed in this function. If there is a corresponding data set in a subclass, for example, the subclass must override this function to set that data set -- though this function should probably be called to handle the ugly stuff. """ # Copy the information fields, but not the data W = WaveformBase.copy_without_data(self) W.t = np.copy(tprime) W.frame = quaternion.squad(self.frame, self.t, W.t) W.data = np.empty((W.n_times,) + self.data.shape[1:], dtype=self.data.dtype) W.data_2d[:] = CubicSpline(self.t, self.data_2d.view(float))(W.t).view(complex) W.__history_depth__ -= 1 W._append_history(f"{W} = {self}.interpolate({tprime})") return W @waveform_alterations def SI_units(self, current_unit_mass_in_solar_masses, distance_from_source_in_megaparsecs=100): """Assuming current quantities are in geometric units, convert to SI units This function assumes that the `dataType`, `r_is_scaled_out`, and `m_is_scaled_out` attributes are correct, then scales the amplitude and time data appropriately so that the data correspond to data that could be observed from a source with the given total mass at the given distance. Note that the curvature scalars will have units of s^-2, rather than the arguably more correct m^-2. This seems to be more standard in numerical relativity. The result can be divided by `scipy.constants.c**2` to give units of m^-2 if desired. Parameters ---------- current_unit_mass_in_solar_masses : float Mass of the system in the data converted to solar masses distance_from_source_in_megaparsecs : float, optional Output will be waveform as observed from this distance, default=100 (Mpc) """ if not self.r_is_scaled_out: warning = ( "\nTrying to convert to SI units, the radius is supposedly not scaled out.\n" + "This seems to suggest that the data may already be in some units..." ) warnings.warn(warning) if not self.m_is_scaled_out: warning = ( "\nTrying to convert to SI units, the mass is supposedly not scaled out.\n" + "This seems to suggest that the data may already be in some units..." ) warnings.warn(warning) M_in_meters = current_unit_mass_in_solar_masses * m_sun_in_meters # m M_in_seconds = M_in_meters / speed_of_light # s R_in_meters = distance_from_source_in_megaparsecs * (1e6 * parsec_in_meters) # m R_over_M = R_in_meters / M_in_meters # [dimensionless] # The radius scaling `r_scaling` is the number of factors of the dimensionless quantity `R_over_M` required # to keep the waveform asymptotically constant. So, for example, h and Psi4 both have `r_scaling=1`. The # mass scaling `m_scaling` is the number of factors of `M_in_meters` required to make the waveform # dimensionless, and does not account for the factors of mass in the radius scale. The Newman-Penrose # quantities are curvature quantities, so they have dimensions 1/m^2, and thus have `m_scaling=2`. if self.r_is_scaled_out: if self.m_is_scaled_out: amplitude_scaling = (R_over_M ** -self.r_scaling) * (M_in_meters ** -self.m_scaling) else: amplitude_scaling = R_over_M ** -self.r_scaling else: if self.m_is_scaled_out: amplitude_scaling = M_in_meters ** -self.m_scaling else: amplitude_scaling = 1.0 # Copy the information fields, but not the data W = WaveformBase.copy_without_data(self) if self.m_is_scaled_out: W.t = M_in_seconds * self.t # s else: W.t = np.copy(self.t) # supposedly already in the appropriate units... W.frame = np.copy(self.frame) W.data = amplitude_scaling * self.data W.m_is_scaled_out = False W.r_is_scaled_out = False W.__history_depth__ -= 1 W._append_history( "{} = {}.SI_units(current_unit_mass_in_solar_masses={}, " "distance_from_source_in_megaparsecs={})".format( W, self, current_unit_mass_in_solar_masses, distance_from_source_in_megaparsecs ) ) return W
[ 2, 15069, 357, 66, 8, 1853, 11, 3899, 37619, 198, 2, 4091, 38559, 24290, 2393, 329, 3307, 25, 1279, 5450, 1378, 12567, 13, 785, 14, 39949, 293, 14, 1416, 380, 14, 2436, 672, 14, 9866, 14, 43, 2149, 24290, 29, 198, 198, 11748, 2868...
2.353101
17,706
############################################################################ # This Python file is part of PyFEM, the code that accompanies the book: # # # # 'Non-Linear Finite Element Analysis of Solids and Structures' # # R. de Borst, M.A. Crisfield, J.J.C. Remmers and C.V. Verhoosel # # John Wiley and Sons, 2012, ISBN 978-0470666449 # # # # The code is written by J.J.C. Remmers, C.V. Verhoosel and R. de Borst. # # # # The latest stable version can be downloaded from the web-site: # # http://www.wiley.com/go/deborst # # # # A github repository, with the most up to date version of the code, # # can be found here: # # https://github.com/jjcremmers/PyFEM # # # # The code is open source and intended for educational and scientific # # purposes only. If you use PyFEM in your research, the developers would # # be grateful if you could cite the book. # # # # Disclaimer: # # The authors reserve all rights but do not guarantee that the code is # # free from errors. Furthermore, the authors shall not be liable in any # # event caused by the use of the program. # ############################################################################ from .Element import Element from pyfem.util.kinematics import Kinematics from pyfem.elements.SLSgeomdata import SLSgeomdata from pyfem.elements.SLSkinematic import SLSkinematic from pyfem.elements.SLSutils import LayerData,SLSparameters,StressContainer from pyfem.elements.CondensationManager import CondensationManager from numpy import zeros, dot, outer, ones #============================================================================== # #============================================================================== #------------------------------------------------------------------------------ # #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ # #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ # #------------------------------------------------------------------------------
[ 29113, 29113, 7804, 4242, 201, 198, 2, 220, 770, 11361, 2393, 318, 636, 286, 9485, 37, 3620, 11, 262, 2438, 326, 48159, 262, 1492, 25, 220, 1303, 201, 198, 2, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, ...
2.261065
1,333
# # PySNMP MIB module CISCO-XGCP-CAPABILITY (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-XGCP-CAPABILITY # Produced by pysmi-0.3.4 at Mon Apr 29 18:05:30 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ConstraintsIntersection, ValueRangeConstraint, ConstraintsUnion, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ConstraintsIntersection", "ValueRangeConstraint", "ConstraintsUnion", "ValueSizeConstraint") CCallControlProfileIndexOrZero, = mibBuilder.importSymbols("CISCO-MEDIA-GATEWAY-MIB", "CCallControlProfileIndexOrZero") CMgcGroupIndexOrZero, = mibBuilder.importSymbols("CISCO-MGC-MIB", "CMgcGroupIndexOrZero") ciscoAgentCapability, = mibBuilder.importSymbols("CISCO-SMI", "ciscoAgentCapability") CiscoPort, = mibBuilder.importSymbols("CISCO-TC", "CiscoPort") CXgcpRetryMethod, = mibBuilder.importSymbols("CISCO-XGCP-MIB", "CXgcpRetryMethod") InetAddressType, = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddressType") AgentCapabilities, ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "AgentCapabilities", "ModuleCompliance", "NotificationGroup") NotificationType, TimeTicks, Integer32, Bits, Counter64, IpAddress, ObjectIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, Gauge32, MibIdentifier, Unsigned32, iso, Counter32, ModuleIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "NotificationType", "TimeTicks", "Integer32", "Bits", "Counter64", "IpAddress", "ObjectIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Gauge32", "MibIdentifier", "Unsigned32", "iso", "Counter32", "ModuleIdentity") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") ciscoXgcpCapability = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 7, 408)) ciscoXgcpCapability.setRevisions(('2006-03-01 00:00', '2006-02-14 00:00', '2005-06-24 00:00', '2005-01-06 00:00', '2004-10-04 00:00', '2004-06-16 00:00', '2002-12-31 00:00',)) if mibBuilder.loadTexts: ciscoXgcpCapability.setLastUpdated('200603010000Z') if mibBuilder.loadTexts: ciscoXgcpCapability.setOrganization('Cisco Systems, Inc.') ciscoXgcpCapabilityV4R010 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 408, 1)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoXgcpCapabilityV4R010 = ciscoXgcpCapabilityV4R010.setProductRelease('MGX8850 Release 4.0') if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoXgcpCapabilityV4R010 = ciscoXgcpCapabilityV4R010.setStatus('current') ciscoXgcpCapabilityV12R03 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 408, 2)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoXgcpCapabilityV12R03 = ciscoXgcpCapabilityV12R03.setProductRelease('Cisco IOS 12.3') if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoXgcpCapabilityV12R03 = ciscoXgcpCapabilityV12R03.setStatus('deprecated') ciscoXgcpCapabilityV5R015 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 408, 3)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoXgcpCapabilityV5R015 = ciscoXgcpCapabilityV5R015.setProductRelease('MGX8850 release 5.0.15') if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoXgcpCapabilityV5R015 = ciscoXgcpCapabilityV5R015.setStatus('current') ciscoXgcpCapabilityV5R100 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 408, 4)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoXgcpCapabilityV5R100 = ciscoXgcpCapabilityV5R100.setProductRelease('MGX8880 release 5.1.00') if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoXgcpCapabilityV5R100 = ciscoXgcpCapabilityV5R100.setStatus('current') ciscoXgcpCapabilityV5R300 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 408, 5)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoXgcpCapabilityV5R300 = ciscoXgcpCapabilityV5R300.setProductRelease('MGX8880 release 5.3.00') if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoXgcpCapabilityV5R300 = ciscoXgcpCapabilityV5R300.setStatus('current') ciscoXgcpCapabilityV12R03AS5000 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 408, 6)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoXgcpCapabilityV12R03AS5000 = ciscoXgcpCapabilityV12R03AS5000.setProductRelease('Cisco IOS 12.3') if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoXgcpCapabilityV12R03AS5000 = ciscoXgcpCapabilityV12R03AS5000.setStatus('deprecated') ciscoXgcpCapabilityV12R04AS5000 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 408, 7)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoXgcpCapabilityV12R04AS5000 = ciscoXgcpCapabilityV12R04AS5000.setProductRelease('Cisco IOS 12.4') if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoXgcpCapabilityV12R04AS5000 = ciscoXgcpCapabilityV12R04AS5000.setStatus('current') mibBuilder.exportSymbols("CISCO-XGCP-CAPABILITY", ciscoXgcpCapability=ciscoXgcpCapability, ciscoXgcpCapabilityV12R03AS5000=ciscoXgcpCapabilityV12R03AS5000, ciscoXgcpCapabilityV12R03=ciscoXgcpCapabilityV12R03, ciscoXgcpCapabilityV4R010=ciscoXgcpCapabilityV4R010, PYSNMP_MODULE_ID=ciscoXgcpCapability, ciscoXgcpCapabilityV5R015=ciscoXgcpCapabilityV5R015, ciscoXgcpCapabilityV12R04AS5000=ciscoXgcpCapabilityV12R04AS5000, ciscoXgcpCapabilityV5R100=ciscoXgcpCapabilityV5R100, ciscoXgcpCapabilityV5R300=ciscoXgcpCapabilityV5R300)
[ 2, 198, 2, 9485, 15571, 7378, 337, 9865, 8265, 36159, 8220, 12, 55, 38, 8697, 12, 33177, 32, 25382, 357, 4023, 1378, 16184, 76, 489, 8937, 13, 785, 14, 79, 893, 11632, 8, 198, 2, 7054, 45, 13, 16, 2723, 2393, 1378, 14, 14490, 14...
2.434857
2,341
from typing import Optional import numpy as np import pandas as pd from temporis.transformation import TransformerStep from scipy.signal import savgol_filter from sklearn.cluster import MiniBatchKMeans class SavitzkyGolayTransformer(TransformerStep): """Filter each feature using LOESS Parameters ---------- window : int Window size of the filter order : int, optional Order of the filter, by default 2 name : Optional[str], optional Step name, by default None """ def transform(self, X:pd.DataFrame, y=None) -> pd.DataFrame: """Return a new dataframe with the features filtered Parameters ---------- X : pd.DataFrame Input life Returns ------- pd.DataFrame A new DatafFrame with the same index as the input with the features filtered """ if X.shape[0] > self.window: return pd.DataFrame(savgol_filter(X, self.window, self.order, axis=0), columns=X.columns, index=X.index) else: return X class MeanFilter(TransformerStep): """Filter each feature using a rolling mean filter Parameters ---------- window : int Size of the rolling window min_periods : int, optional Minimum number of points of the rolling window, by default 15 name : Optional[str], optional Name of the step, by default None """ class MedianFilter(TransformerStep): """Filter each feature using a rolling median filter Parameters ---------- window : int Size of the rolling window min_periods : int, optional Minimum number of points of the rolling window, by default 15 name : Optional[str], optional Name of the step, by default None """ class OneDimensionalKMeans(TransformerStep): """Clusterize each feature into a number of clusters Parameters ---------- n_clusters : int Number of clusters to obtain per cluster """ def transform(self, X:pd.DataFrame, y=None) -> pd.DataFrame: """Transform the input dataframe Parameters ---------- X : pd.DataFrame Input life Returns ------- pd.DataFrame A new DataFrame with the same index as the input. Each feature is replaced with the clusters of each point """ X = X.copy() for c in X.columns: X[c] = self.clusters[c].cluster_centers_[ self.clusters[c].predict(np.atleast_2d(X[c]).T) ] return X class MultiDimensionalKMeans(TransformerStep): """Clusterize data points and replace each feature with the centroid feature its belong Parameters ---------- n_clusters : int, optional Number of clusters to obtain by default 5 name : Optional[str], optional Name of the step, by default None """ def transform(self, X:pd.DataFrame, y=None) -> pd.DataFrame: """Transform the input life with the centroid information Parameters ---------- X : pd.DataFrame Input life Returns ------- pd.DataFrame A new DataFrame in which each point was replaced by the centroid its belong """ X = X.copy() X[:] = self.clusters.cluster_centers_[self.clusters.predict(X)] return X class EWMAFilter(TransformerStep): """Filter each feature using a rolling median filter Parameters ---------- window : int Size of the rolling window min_periods : int, optional Minimum number of points of the rolling window, by default 15 name : Optional[str], optional Name of the step, by default None """
[ 6738, 19720, 1330, 32233, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 10042, 271, 13, 7645, 1161, 1330, 3602, 16354, 8600, 198, 6738, 629, 541, 88, 13, 12683, 282, 1330, 6799, 70, 349, 62,...
2.451754
1,596
# coding: utf-8 # Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401 from oci.decorators import init_model_state_from_kwargs @init_model_state_from_kwargs class UpdateInstancePoolPlacementConfigurationDetails(object): """ The location for where an instance pool will place instances. """ def __init__(self, **kwargs): """ Initializes a new UpdateInstancePoolPlacementConfigurationDetails object with values from keyword arguments. The following keyword arguments are supported (corresponding to the getters/setters of this class): :param availability_domain: The value to assign to the availability_domain property of this UpdateInstancePoolPlacementConfigurationDetails. :type availability_domain: str :param fault_domains: The value to assign to the fault_domains property of this UpdateInstancePoolPlacementConfigurationDetails. :type fault_domains: list[str] :param primary_subnet_id: The value to assign to the primary_subnet_id property of this UpdateInstancePoolPlacementConfigurationDetails. :type primary_subnet_id: str :param secondary_vnic_subnets: The value to assign to the secondary_vnic_subnets property of this UpdateInstancePoolPlacementConfigurationDetails. :type secondary_vnic_subnets: list[oci.core.models.InstancePoolPlacementSecondaryVnicSubnet] """ self.swagger_types = { 'availability_domain': 'str', 'fault_domains': 'list[str]', 'primary_subnet_id': 'str', 'secondary_vnic_subnets': 'list[InstancePoolPlacementSecondaryVnicSubnet]' } self.attribute_map = { 'availability_domain': 'availabilityDomain', 'fault_domains': 'faultDomains', 'primary_subnet_id': 'primarySubnetId', 'secondary_vnic_subnets': 'secondaryVnicSubnets' } self._availability_domain = None self._fault_domains = None self._primary_subnet_id = None self._secondary_vnic_subnets = None @property def availability_domain(self): """ **[Required]** Gets the availability_domain of this UpdateInstancePoolPlacementConfigurationDetails. The availability domain to place instances. Example: `Uocm:PHX-AD-1` :return: The availability_domain of this UpdateInstancePoolPlacementConfigurationDetails. :rtype: str """ return self._availability_domain @availability_domain.setter def availability_domain(self, availability_domain): """ Sets the availability_domain of this UpdateInstancePoolPlacementConfigurationDetails. The availability domain to place instances. Example: `Uocm:PHX-AD-1` :param availability_domain: The availability_domain of this UpdateInstancePoolPlacementConfigurationDetails. :type: str """ self._availability_domain = availability_domain @property def fault_domains(self): """ Gets the fault_domains of this UpdateInstancePoolPlacementConfigurationDetails. The fault domains to place instances. If you don't provide any values, the system makes a best effort to distribute instances across all fault domains based on capacity. To distribute the instances evenly across selected fault domains, provide a set of fault domains. For example, you might want instances to be evenly distributed if your applications require high availability. To get a list of fault domains, use the :func:`list_fault_domains` operation in the Identity and Access Management Service API. Example: `[FAULT-DOMAIN-1, FAULT-DOMAIN-2, FAULT-DOMAIN-3]` :return: The fault_domains of this UpdateInstancePoolPlacementConfigurationDetails. :rtype: list[str] """ return self._fault_domains @fault_domains.setter def fault_domains(self, fault_domains): """ Sets the fault_domains of this UpdateInstancePoolPlacementConfigurationDetails. The fault domains to place instances. If you don't provide any values, the system makes a best effort to distribute instances across all fault domains based on capacity. To distribute the instances evenly across selected fault domains, provide a set of fault domains. For example, you might want instances to be evenly distributed if your applications require high availability. To get a list of fault domains, use the :func:`list_fault_domains` operation in the Identity and Access Management Service API. Example: `[FAULT-DOMAIN-1, FAULT-DOMAIN-2, FAULT-DOMAIN-3]` :param fault_domains: The fault_domains of this UpdateInstancePoolPlacementConfigurationDetails. :type: list[str] """ self._fault_domains = fault_domains @property def primary_subnet_id(self): """ **[Required]** Gets the primary_subnet_id of this UpdateInstancePoolPlacementConfigurationDetails. The OCID of the primary subnet to place instances. :return: The primary_subnet_id of this UpdateInstancePoolPlacementConfigurationDetails. :rtype: str """ return self._primary_subnet_id @primary_subnet_id.setter def primary_subnet_id(self, primary_subnet_id): """ Sets the primary_subnet_id of this UpdateInstancePoolPlacementConfigurationDetails. The OCID of the primary subnet to place instances. :param primary_subnet_id: The primary_subnet_id of this UpdateInstancePoolPlacementConfigurationDetails. :type: str """ self._primary_subnet_id = primary_subnet_id @property def secondary_vnic_subnets(self): """ Gets the secondary_vnic_subnets of this UpdateInstancePoolPlacementConfigurationDetails. The set of subnet OCIDs for secondary VNICs for instances in the pool. :return: The secondary_vnic_subnets of this UpdateInstancePoolPlacementConfigurationDetails. :rtype: list[oci.core.models.InstancePoolPlacementSecondaryVnicSubnet] """ return self._secondary_vnic_subnets @secondary_vnic_subnets.setter def secondary_vnic_subnets(self, secondary_vnic_subnets): """ Sets the secondary_vnic_subnets of this UpdateInstancePoolPlacementConfigurationDetails. The set of subnet OCIDs for secondary VNICs for instances in the pool. :param secondary_vnic_subnets: The secondary_vnic_subnets of this UpdateInstancePoolPlacementConfigurationDetails. :type: list[oci.core.models.InstancePoolPlacementSecondaryVnicSubnet] """ self._secondary_vnic_subnets = secondary_vnic_subnets
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 2, 15069, 357, 66, 8, 1584, 11, 33160, 11, 18650, 290, 14, 273, 663, 29116, 13, 220, 1439, 2489, 10395, 13, 198, 2, 770, 3788, 318, 10668, 12, 36612, 284, 345, 739, 262, 14499, 2448, 33532, 1...
2.804944
2,589
# -*- coding: utf-8 -*- """CLI debug commands.""" # system module import math import time from typing import TYPE_CHECKING from uuid import UUID # community module import click from dateutil import parser from circle_core.timed_db import TimedDBBundle if TYPE_CHECKING: from typing import List, Tuple @click.group('debug') def cli_debug() -> None: """`crcr debug`の起点.""" pass @cli_debug.command('build_whisper') @click.argument('dir') @click.argument('dburl') @click.argument('table') @click.argument('end_date') @cli_debug.command() @click.argument('dir') @click.argument('box_id') @click.argument('end_time', type=float) @click.argument('graph_range')
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 5097, 40, 14257, 9729, 526, 15931, 198, 198, 2, 1080, 8265, 198, 11748, 10688, 198, 11748, 640, 198, 6738, 19720, 1330, 41876, 62, 50084, 2751, 198, 6738, 334, 27...
2.763265
245
#!/usr/bin/python3 from urllib.request import urlopen from html.parser import HTMLParser from subprocess import call from functools import partial, wraps from typing import Any, List, Tuple import re import argparse import platform TEMPLATE = 'template.cc' LANGUAGE = 'C++17' SAMPLE_INPUT = 'input' SAMPLE_OUTPUT = 'output' MY_OUTPUT = 'my_output' VERSION = 'CodeForces Parser v1.5.1: Modified by Brandon' RED_F = '\033[31m' GREEN_F = '\033[32m' BOLD = '\033[1m' NORM = '\033[0m' if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 198, 6738, 2956, 297, 571, 13, 25927, 1330, 19016, 9654, 198, 6738, 27711, 13, 48610, 1330, 11532, 46677, 198, 198, 6738, 850, 14681, 1330, 869, 198, 6738, 1257, 310, 10141, 1330, 13027, ...
2.542857
210
from config.mysql import mysql_config_dev, mysql_config_prod
[ 6738, 4566, 13, 28744, 13976, 1330, 48761, 62, 11250, 62, 7959, 11, 48761, 62, 11250, 62, 1676, 67 ]
3.333333
18
""" Clean Keywords =============================================================================== Cleans the keywords columns using the file keywords.txt, located in the same directory as the documents.csv file. >>> from techminer2 import * >>> directory = "/workspaces/techminer2/data/" >>> clean_keywords(directory) - INFO - Applying thesaurus to 'raw_author_keywords' column ... - INFO - Applying thesaurus to 'raw_index_keywords' column... - INFO - Applying thesaurus to 'raw_nlp_document_title' column... - INFO - Applying thesaurus to 'raw_nlp_abstract' column... - INFO - Applying thesaurus to 'raw_nlp_phrases' column... - INFO - The thesaurus was applied to all keywords. """ # pylint: disable=no-member # pylint: disable=invalid-name from os.path import isfile, join import pandas as pd from . import logging from .map_ import map_ from .thesaurus import read_textfile def clean_keywords(directory="./"): """ Clean all keywords columns in the records using a thesaurus (keywrords.txt). """ # -------------------------------------------------------------------------- # Loads documents.csv filename = join(directory, "documents.csv") if not isfile(filename): raise FileNotFoundError(f"The file '{filename}' does not exist.") documents = pd.read_csv(filename, sep=",", encoding="utf-8") # -------------------------------------------------------------------------- thesaurus_file = join(directory, "keywords.txt") if isfile(thesaurus_file): th = read_textfile(thesaurus_file) th = th.compile_as_dict() else: raise FileNotFoundError("The file {} does not exist.".format(thesaurus_file)) # # Author keywords cleaning # if "raw_author_keywords" in documents.columns: logging.info("Applying thesaurus to 'raw_author_keywords' column ...") documents["author_keywords"] = map_( documents, "raw_author_keywords", th.apply_as_dict ) # # Index keywords cleaning # if "raw_index_keywords" in documents.columns: logging.info("Applying thesaurus to 'raw_index_keywords' column...") documents["index_keywords"] = map_( documents, "raw_index_keywords", th.apply_as_dict ) if "keywords" in documents.columns: logging.info("Applying thesaurus to 'raw_keywords' column...") documents["keywords"] = map_(documents, "raw_keywords", th.apply_as_dict) if "raw_nlp_document_title" in documents.columns: logging.info("Applying thesaurus to 'raw_nlp_document_title' column...") documents["nlp_document_title"] = map_( documents, "raw_nlp_document_title", th.apply_as_dict ) if "raw_nlp_abstract" in documents.columns: logging.info("Applying thesaurus to 'raw_nlp_abstract' column...") documents["nlp_abstract"] = map_( documents, "raw_nlp_abstract", th.apply_as_dict ) if "raw_nlp_phrases" in documents.columns: logging.info("Applying thesaurus to 'raw_nlp_phrases' column...") documents["nlp_phrases"] = map_(documents, "raw_nlp_phrases", th.apply_as_dict) # # Saves! # # datastore.to_csv(datastorefile, index=False) # -------------------------------------------------------------------------- documents.to_csv( join(directory, "documents.csv"), sep=",", encoding="utf-8", index=False, ) # -------------------------------------------------------------------------- logging.info("The thesaurus was applied to all keywords.")
[ 37811, 198, 32657, 7383, 10879, 198, 23926, 25609, 18604, 198, 198, 34, 11861, 262, 26286, 15180, 1262, 262, 2393, 26286, 13, 14116, 11, 5140, 287, 220, 198, 1169, 976, 8619, 355, 262, 4963, 13, 40664, 2393, 13, 198, 198, 33409, 422, ...
2.780695
1,295
import json from datetime import datetime, timedelta from django.urls import reverse import jwt from allauth.socialaccount.tests import OAuth2TestsMixin from allauth.tests import MockedResponse, TestCase from .provider import AppleProvider # Generated on https://mkjwk.org/, used to sign and verify the apple id_token TESTING_JWT_KEYSET = { "p": ( "4ADzS5jKx_kdQihyOocVS0Qwwo7m0f7Ow56EadySJ-cmnwoHHF3AxgRaq-h-KwybSphv" "dc-X7NbS79-b9dumHKyt1MeVLAsDZD1a-uQCEneY1g9LsQkscNr7OggcpvMg5UUFwv6A" "kavu8cB0iyhNdha5_AWX27K5lNebvpaXEJ8" ), "kty": "RSA", "q": ( "yy5UvMjrvZyO1Os_nxXIugCa3NyWOkC8oMppPvr1Bl5AnF_xwXN2n9ozPd9Nb3Q3n-om" "NgLayyUxhwIjWDlI67Vbx-ESuff8ZEBKuTK0Gdmr4C_QU_j0gvvNMNJweSPxDdRmIUgO" "njTVNWmdqFTZs43jXAT4J519rgveNLAkGNE" ), "d": ( "riPuGIDde88WS03CVbo_mZ9toFWPyTxvuz8VInJ9S1ZxULo-hQWDBohWGYwvg8cgfXck" "cqWt5OBqNvPYdLgwb84uVi2JeEHmhcQSc_x0zfRTau5HVE2KdR-gWxQjPWoaBHeDVqwo" "PKaU2XYxa-gYDXcuSJWHz3BX13oInDEFCXr6VwiLiwLBFsb63EEHwyWXJbTpoar7AARW" "kz76qtngDkk4t9gk_Q0L1y1qf1GeWiAL7xWb-bdptma4-1ui-R2219-1ONEZ41v_jsIS" "_z8ooXmVCbUsHV4Z1UDpRvpORVE3u57WK3qXUdAtZsXjaIwkdItbDmL1jFUgefwfO91Y" "YQ" ), "e": "AQAB", "use": "sig", "kid": "testkey", "qi": ( "R0Hu4YmpHzw3SKWGYuAcAo6B97-JlN2fXiTjZ2g8eHGQX7LSoKEu0Hmu5hcBZYSgOuor" "IPsPUu3mNtx3pjLMOaJRk34VwcYu7h23ogEKGcPUt1c4tTotFDdw8WFptDOw4ow31Tml" "BPExLqzzGjJeQSNULB1bExuuhYMWx6wBXo8" ), "dp": ( "WBaHlnbjZ3hDVTzqjrGIYizSr-_aPUJitPKlR6wBncd8nJYo7bLAmB4mOewXkX5HozIG" "wuF78RsZoFLi1fAmhqgxQ7eopcU-9DBcksUPO4vkgmlJbrkYzNiQauW9vrllekOGXIQQ" "szhVoqP4MLEMpR-Sy9S3PyItcKbJDE3T4ik" ), "alg": "RS256", "dq": ( "Ar5kbIw2CsBzeVKX8FkF9eUOMk9URAMdyPoSw8P1zRk2vCXbiOY7Qttad8ptLEUgfytV" "SsNtGvMsoQsZWRak8nHnhGJ4s0QzB1OK7sdNgU_cL1HV-VxSSPaHhdJBrJEcrzggDPEB" "KYfDHU6Iz34d1nvjBxoWE8rfqJsGbCW4xxE" ), "n": ( "sclLPioUv4VOcOZWAKoRhcvwIH2jOhoHhSI_Cj5c5zSp7qaK8jCU6T7-GObsgrhpty-k" "26ZuqRdgu9d-62WO8OBGt1e0wxbTh128-nTTrOESHUlV_K1wpJmXOxNpJiybcgzZNbAm" "ACmsHfxZvN9bt7gKPXxf3-_zFAf12PbYMrOionAJ1N_4HxL7fz3xkr5C87Av06QNilIC" "-mA-4n9Eqw_R2DYNpE3RYMdWtwKqBwJC8qs3677RpG9vcc-yZ_97pEiytd2FBJ8uoTwH" "d3DHJB8UVgBSh1kMUpSdoM7HxVzKx732nx6Kusln79LrsfOzrXF4enkfKJYI40-uwT95" "zw" ), } # Mocked version of the test data from https://appleid.apple.com/auth/keys KEY_SERVER_RESP_JSON = json.dumps({ "keys": [ { "kty": TESTING_JWT_KEYSET["kty"], "kid": TESTING_JWT_KEYSET["kid"], "use": TESTING_JWT_KEYSET["use"], "alg": TESTING_JWT_KEYSET["alg"], "n": TESTING_JWT_KEYSET["n"], "e": TESTING_JWT_KEYSET["e"], } ] }) def sign_id_token(payload): """ Sign a payload as apple normally would for the id_token. """ signing_key = jwt.algorithms.RSAAlgorithm.from_jwk( json.dumps(TESTING_JWT_KEYSET) ) return jwt.encode( payload, signing_key, algorithm='RS256', headers={'kid': TESTING_JWT_KEYSET["kid"]} ).decode("utf8")
[ 11748, 33918, 198, 6738, 4818, 8079, 1330, 4818, 8079, 11, 28805, 12514, 198, 198, 6738, 42625, 14208, 13, 6371, 82, 1330, 9575, 198, 198, 11748, 474, 46569, 198, 198, 6738, 477, 18439, 13, 14557, 23317, 13, 41989, 1330, 440, 30515, 17,...
1.522587
2,103
import webbrowser import sys import os import os.path import api def open_existing_link(search_key): """ Opens a link given particular key :param search_key: key to search in the quicklinks file :return: """ did_succeed = api.search_for_value(search_key, open_link) if not did_succeed: raise ValueError('''No quicklink found for this key! Please edit your ~/.quicklinks file or use ql --set <key> <url>''') def get_exception(): """Helper function to work with py2.4-py3 for getting the current exception in a try/except block """ return sys.exc_info()[1] if __name__ == '__main__': main()
[ 11748, 3992, 40259, 198, 11748, 25064, 198, 11748, 28686, 198, 11748, 28686, 13, 6978, 198, 11748, 40391, 628, 628, 198, 198, 4299, 1280, 62, 25687, 62, 8726, 7, 12947, 62, 2539, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 86...
2.700405
247
#!/usr/bin/env python3 from model_weights import * import argparse if __name__ == "__main__": parser = argparse.ArgumentParser(description='Export tensorflow variables from checkpoint to numpy file') parser.add_argument('logdir', metavar='TF_LOGDIR', type=str, help='the tensorflow log directory to import the latest checkpoint') parser.add_argument('save_to', metavar='SAVE_TO', type=str, help='the location to save the .npy file to') args = parser.parse_args() if args.save_to == "-": args.save_to = "/dev/stdout" export_model_weights(args.logdir, args.save_to)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 6738, 2746, 62, 43775, 1330, 1635, 198, 11748, 1822, 29572, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 30751, 796, 1822, 29572, 13,...
2.533333
255
from typing import Tuple, Union import pytest from nonebug import App from utils import make_fake_event, make_fake_message @pytest.mark.asyncio @pytest.mark.asyncio @pytest.mark.parametrize( "msg,ignorecase,type,text,expected", [ ("prefix", False, "message", "prefix_", True), ("prefix", False, "message", "Prefix_", False), ("prefix", True, "message", "prefix_", True), ("prefix", True, "message", "Prefix_", True), ("prefix", False, "message", "prefoo", False), ("prefix", False, "message", "fooprefix", False), (("prefix", "foo"), False, "message", "fooprefix", True), ("prefix", False, "notice", "foo", False), ], ) @pytest.mark.asyncio @pytest.mark.parametrize( "msg,ignorecase,type,text,expected", [ ("suffix", False, "message", "_suffix", True), ("suffix", False, "message", "_Suffix", False), ("suffix", True, "message", "_suffix", True), ("suffix", True, "message", "_Suffix", True), ("suffix", False, "message", "suffoo", False), ("suffix", False, "message", "suffixfoo", False), (("suffix", "foo"), False, "message", "suffixfoo", True), ("suffix", False, "notice", "foo", False), ], ) @pytest.mark.asyncio @pytest.mark.parametrize( "msg,ignorecase,type,text,expected", [ ("fullmatch", False, "message", "fullmatch", True), ("fullmatch", False, "message", "Fullmatch", False), ("fullmatch", True, "message", "fullmatch", True), ("fullmatch", True, "message", "Fullmatch", True), ("fullmatch", False, "message", "fullfoo", False), ("fullmatch", False, "message", "_fullmatch_", False), (("fullmatch", "foo"), False, "message", "fullmatchfoo", False), ("fullmatch", False, "notice", "foo", False), ], ) @pytest.mark.asyncio @pytest.mark.parametrize( "kws,type,text,expected", [ (("key",), "message", "_key_", True), (("key", "foo"), "message", "_foo_", True), (("key",), "notice", "foo", False), ], ) @pytest.mark.asyncio @pytest.mark.parametrize( "cmds", [(("help",),), (("help", "foo"),), (("help",), ("foo",))] ) # TODO: shell command # TODO: regex @pytest.mark.asyncio @pytest.mark.parametrize("expected", [True, False])
[ 6738, 19720, 1330, 309, 29291, 11, 4479, 198, 198, 11748, 12972, 9288, 198, 6738, 4844, 25456, 1330, 2034, 198, 198, 6738, 3384, 4487, 1330, 787, 62, 30706, 62, 15596, 11, 787, 62, 30706, 62, 20500, 628, 198, 31, 9078, 9288, 13, 4102,...
2.360122
983
print(@@calc1+2*@@python3+@@lua4@@@@@@@@@)
[ 198, 4798, 7, 12404, 9948, 66, 16, 10, 17, 9, 12404, 29412, 18, 10, 12404, 40211, 19, 37991, 31, 8, 628 ]
2.142857
21
import unittest import os import numpy as np from solar_data_pipeline.file.csv import CsvAccess
[ 11748, 555, 715, 395, 198, 11748, 28686, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 6591, 62, 7890, 62, 79, 541, 4470, 13, 7753, 13, 40664, 1330, 327, 21370, 15457, 198 ]
3.096774
31
import argparse from pathlib import Path import pandas as pd import numpy as np from progressbar import ProgressBar def save_filepath_label(usage, frame_dir, label_dir, out_dir): """ Save filepaths of all the frames and their respective output label as numpy array. Namely this numpy array's would be x_train, y_train, etc. This numpy array would be directly used in input pipeline for training and testing of model. Args: usage: Specify it as Train, Test, Validation or FinalTest. frame_dir: Path to directory which contains extracted frames. label_dir: Path to directory which contains labels csv files. out_dir: Path to directory which will be used to store numpy arrays of filepath and labels. """ frame_dir = frame_dir / usage if usage == "FinalTest": label_path = str(label_dir) + "/TestLabels.csv" else: label_path = str(label_dir) + f"/{usage}Labels.csv" labeldf = pd.read_csv(label_path) nrows = len(list(frame_dir.glob("*.jpeg"))) ncols = len(labeldf.columns) - 1 filepath = np.empty((nrows,), dtype=np.object) label = np.empty((nrows, ncols), dtype=np.float32) print(f"Getting filepath and labels for {usage}") with ProgressBar(max_value=nrows) as bar: for i, frame in enumerate(frame_dir.glob("*.jpeg")): filepath[i] = str(frame) framename = frame.parts[-1] frameid = framename[:framename.find("_")] video = frameid + ".avi" if labeldf['ClipID'].str.contains(video).any(): lidx = labeldf.index[labeldf['ClipID'].str.contains(video)] else: video = frameid + ".mp4" lidx = labeldf.index[labeldf['ClipID'].str.contains(video)] label[i] = labeldf.iloc[lidx, 1:] bar.update(i) np.random.seed(100) indices = np.random.permutation(nrows) filepath = filepath[indices] label = label[indices] np.save(f"{str(out_dir)}/x_{usage.lower()}", filepath, allow_pickle=True) np.save(f"{str(out_dir)}/y_{usage.lower()}", label) return filepath, label def main(frame_dir, label_dir, out_dir): """ Call the savefile_path_label function for Train, Test, Validatin and FinalTest. """ frame_dir = Path(frame_dir) label_dir = Path(label_dir) out_dir = Path(out_dir) out_dir.mkdir(parents=True, exist_ok=True) save_filepath_label("Train", frame_dir, label_dir, out_dir) save_filepath_label("Test", frame_dir, label_dir, out_dir) save_filepath_label("Validation", frame_dir, label_dir, out_dir) save_filepath_label("FinalTest", frame_dir, label_dir, out_dir) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Save filepath and labels.") grp = parser.add_argument_group("Required arguments") grp.add_argument("-i", "--frame_dir", type=str, required=True, help="Directory which contains all frames.") grp.add_argument("-l", "--label_dir", type=str, required=True, help="Directory which contains labels csv.") grp.add_argument("-o", "--out_dir", type=str, required=True, help="Directory to store frames and labels.") args = parser.parse_args() main(args.frame_dir, args.label_dir, args.out_dir)
[ 11748, 1822, 29572, 198, 6738, 3108, 8019, 1330, 10644, 198, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 4371, 5657, 1330, 18387, 10374, 628, 198, 4299, 3613, 62, 7753, 6978, 62, 18242, 7, 26060,...
2.372618
1,417
import os import collections ORIGINAL_TASK_ORDER = ('lemma', 'pos', 'morph') EMPTY = '_' if __name__ == '__main__': dirpath = 'datasets/capitula_classic/' all_tasks = get_all_tasks(dirpath) all_tasks = list(all_tasks) print(all_tasks) for f in os.listdir(dirpath): print("Processing file: ", f) to_normal_format(os.path.join(dirpath, f), f+'.csv', all_tasks)
[ 198, 11748, 28686, 198, 11748, 17268, 628, 198, 1581, 3528, 17961, 62, 51, 1921, 42, 62, 12532, 1137, 796, 19203, 10671, 2611, 3256, 705, 1930, 3256, 705, 24503, 11537, 198, 39494, 9936, 796, 705, 62, 6, 628, 628, 198, 361, 11593, 367...
2.197861
187
from scapy.all import DNS, DNSQR, IP, ICMP, RandShort, send, UDP import argparse import sys g_target_ip = "" g_name_servers = ["8.8.8.8"] # Default; can be overwritten using -n flag g_domain = "www.google.com" # Default; can be overwritten using -d flag """ This function creates and sends spoofed DNS queries to a list of DNS resolver. """ """ This function adds user defined DNS resolvers to the list of resolvers to be queried. """ if __name__ == "__main__": main()
[ 6738, 629, 12826, 13, 439, 1330, 18538, 11, 18538, 48, 49, 11, 6101, 11, 12460, 7378, 11, 8790, 16438, 11, 3758, 11, 36428, 198, 11748, 1822, 29572, 198, 11748, 25064, 198, 198, 70, 62, 16793, 62, 541, 796, 13538, 198, 70, 62, 3672,...
2.975155
161
#!/usr/bin/python # -*-encoding=utf8 -*- # @Author : imooc # @Email : imooc@foxmail.com # @Created at : 2018/11/30 # @Filename : myResponse.py # @Desc : # 状态码
[ 2, 48443, 14629, 14, 8800, 14, 29412, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, ...
1.345679
243
import unittest.mock as mock from django.contrib.auth.models import AnonymousUser, Group, User from django.test import TestCase from rest_access_policy import AccessPolicy, AccessPolicyException from rest_framework.decorators import api_view from rest_framework.viewsets import ModelViewSet
[ 11748, 555, 715, 395, 13, 76, 735, 355, 15290, 198, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 19200, 12982, 11, 4912, 11, 11787, 198, 6738, 42625, 14208, 13, 9288, 1330, 6208, 20448, 198, 6738, 1334, 62, 1552...
3.782051
78
#!/usr/bin/env python #coding: utf-8 import argparse import sys import inference import os ''' script for single image or batch predicition. Accepts folder or single file path''' if __name__ == '__main__': accept_arguments()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 66, 7656, 25, 3384, 69, 12, 23, 198, 11748, 1822, 29572, 198, 11748, 25064, 198, 11748, 32278, 198, 11748, 28686, 198, 7061, 6, 4226, 329, 2060, 2939, 393, 15458, 41219, 653, 13, ...
3.164384
73
import zmq from zmq import Socket, PULL, ZMQError, ENOTSOCK, RCVTIMEO, EAGAIN from logger.logger import log
[ 11748, 1976, 76, 80, 198, 6738, 1976, 76, 80, 1330, 47068, 11, 350, 9994, 11, 1168, 49215, 12331, 11, 412, 11929, 50, 11290, 11, 13987, 36392, 3955, 4720, 11, 412, 4760, 29833, 198, 198, 6738, 49706, 13, 6404, 1362, 1330, 2604, 628 ]
2.619048
42