content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
import logging ## Logging Configuration ## logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) ch = logging.StreamHandler() # console handler ch.setLevel(logging.INFO) fh = logging.FileHandler('logfile.txt') fh.setLevel(logging.INFO) fmtr = logging.Formatter('%(asctime)s | [%(levelname)s] | (%(name)s) | %(message)s') fh.setFormatter(fmtr) logger.addHandler(fh) logger.addHandler(ch) #disable this to stop console output. This better than print statements as you can disable all console output in 1 spot instead of every print statement. logger.critical(f'testing a critical message from {__name__}')
[ 11748, 18931, 198, 198, 2235, 5972, 2667, 28373, 22492, 198, 198, 6404, 1362, 796, 18931, 13, 1136, 11187, 1362, 7, 834, 3672, 834, 8, 198, 6404, 1362, 13, 2617, 4971, 7, 6404, 2667, 13, 10778, 8, 198, 198, 354, 796, 18931, 13, 1212...
3.024272
206
#!/bin/python3 import os if __name__ == "__main__": f = open(os.environ["OUTPUT_PATH"], "w") nm = input().split() n = int(nm[0]) m = int(nm[1]) a = list(map(int, input().rstrip().split())) b = list(map(int, input().rstrip().split())) total = getTotalX(a, b) f.write(str(total) + "\n") f.close()
[ 2, 48443, 8800, 14, 29412, 18, 201, 198, 201, 198, 11748, 28686, 201, 198, 201, 198, 201, 198, 201, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 201, 198, 220, 220, 220, 277, 796, 1280, 7, 418, 13, 268, 2268, 1469...
1.941176
187
import h5py import numpy as np import os, pdb import tensorflow as tf from rllab.envs.base import EnvSpec from rllab.envs.normalized_env import normalize as normalize_env import rllab.misc.logger as logger from sandbox.rocky.tf.algos.trpo import TRPO from sandbox.rocky.tf.policies.gaussian_mlp_policy import GaussianMLPPolicy from sandbox.rocky.tf.policies.gaussian_gru_policy import GaussianGRUPolicy from sandbox.rocky.tf.envs.base import TfEnv from sandbox.rocky.tf.spaces.discrete import Discrete from hgail.algos.hgail_impl import Level from hgail.baselines.gaussian_mlp_baseline import GaussianMLPBaseline from hgail.critic.critic import WassersteinCritic from hgail.envs.spec_wrapper_env import SpecWrapperEnv from hgail.envs.vectorized_normalized_env import vectorized_normalized_env from hgail.misc.datasets import CriticDataset, RecognitionDataset from hgail.policies.categorical_latent_sampler import CategoricalLatentSampler from hgail.policies.gaussian_latent_var_gru_policy import GaussianLatentVarGRUPolicy from hgail.policies.gaussian_latent_var_mlp_policy import GaussianLatentVarMLPPolicy from hgail.policies.latent_sampler import UniformlyRandomLatentSampler from hgail.core.models import ObservationActionMLP from hgail.policies.scheduling import ConstantIntervalScheduler from hgail.recognition.recognition_model import RecognitionModel from hgail.samplers.hierarchy_sampler import HierarchySampler import hgail.misc.utils from julia_env.julia_env import JuliaEnv ''' Const NGSIM_FILENAME_TO_ID = { 'trajdata_i101_trajectories-0750am-0805am.txt': 1, 'trajdata_i101_trajectories-0805am-0820am.txt': 2, 'trajdata_i101_trajectories-0820am-0835am.txt': 3, 'trajdata_i80_trajectories-0400-0415.txt': 4, 'trajdata_i80_trajectories-0500-0515.txt': 5, 'trajdata_i80_trajectories-0515-0530.txt': 6 }''' NGSIM_FILENAME_TO_ID = { 'trajdata_i101_trajectories-0750am-0805am.txt': 1, 'trajdata_i101-22agents-0750am-0805am.txt' : 1 } ''' Common ''' ''' Component build functions ''' ''' This is about as hacky as it gets, but I want to avoid editing the rllab source code as much as possible, so it will have to do for now. Add a reset(self, kwargs**) function to the normalizing environment https://stackoverflow.com/questions/972/adding-a-method-to-an-existing-object-instance ''' '''end of hack, back to our regularly scheduled programming''' # Raunak adding an input argument for multiagent video making ''' setup ''' ''' data utilities '''
[ 198, 11748, 289, 20, 9078, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28686, 11, 279, 9945, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 198, 6738, 374, 297, 397, 13, 268, 14259, 13, 8692, 1330, 2039, 85, 22882, 198, 6738, 374...
2.683476
932
import argparse import ast import configparser import io import os.path from typing import Any from typing import Dict from typing import Optional from typing import Sequence METADATA_KEYS = frozenset(( 'name', 'version', 'url', 'download_url', 'project_urls', 'author', 'author_email', 'maintainer', 'maintainer_email', 'classifiers', 'license', 'license_file', 'description', 'long_description', 'long_description_content_type', 'keywords', 'platforms', 'provides', 'requires', 'obsoletes', )) OPTIONS_AS_SECTIONS = ( 'entry_points', 'extras_require', 'package_data', 'exclude_package_data', ) OPTIONS_KEYS = frozenset(( 'zip_safe', 'setup_requires', 'install_requires', 'python_requires', 'use_2to3', 'use_2to3_fixers', 'use_2to3_exclude_fixers', 'convert_2to3_doctests', 'scripts', 'eager_resources', 'dependency_links', 'tests_require', 'include_package_data', 'packages', 'package_dir', 'namespace_packages', 'py_modules', 'data_files', # need special processing (as sections) *OPTIONS_AS_SECTIONS, )) FIND_PACKAGES_ARGS = ('where', 'exclude', 'include') if __name__ == '__main__': raise SystemExit(main())
[ 11748, 1822, 29572, 198, 11748, 6468, 198, 11748, 4566, 48610, 198, 11748, 33245, 198, 11748, 28686, 13, 6978, 198, 6738, 19720, 1330, 4377, 198, 6738, 19720, 1330, 360, 713, 198, 6738, 19720, 1330, 32233, 198, 6738, 19720, 1330, 45835, 1...
2.767606
426
from .user import User, MultiUserUpload from .problem import Problem, TestData from .submit import Submit
[ 6738, 764, 7220, 1330, 11787, 11, 15237, 12982, 41592, 198, 6738, 764, 45573, 1330, 20647, 11, 6208, 6601, 198, 6738, 764, 46002, 1330, 39900, 198 ]
4.24
25
# pytest tests import numpy as np from Advent2019_10 import Day10
[ 2, 12972, 9288, 5254, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 33732, 23344, 62, 940, 1330, 3596, 940, 628, 198 ]
3.136364
22
import pytest from tests.test_application import app def test_hello_resource(client): """ Test if it is possible to access to /hello resource :param client: Test client object :return: """ response = client.get('/hello').get_json() assert response['hello'] == 'world' def test_asset_found(client): """ Test if Swagger assets are accessible from the new path :param client: Test client object :return: """ response = client.get('/this_is_a_new/path_for_swagger_internal_documentation/swaggerui/swagger-ui-bundle.js') assert response.status_code is 200
[ 11748, 12972, 9288, 198, 6738, 5254, 13, 9288, 62, 31438, 1330, 598, 628, 198, 198, 4299, 1332, 62, 31373, 62, 31092, 7, 16366, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 6208, 611, 340, 318, 1744, 284, 1895, 284, 1220, 31...
2.914286
210
''' 03 - Multiple arguments In the previous exercise, the square brackets around imag in the documentation showed us that the imag argument is optional. But Python also uses a different way to tell users about arguments being optional. Have a look at the documentation of sorted() by typing help(sorted) in the IPython Shell. You'll see that sorted() takes three arguments: iterable, key and reverse. key=None means that if you don't specify the key argument, it will be None. reverse=False means that if you don't specify the reverse argument, it will be False. In this exercise, you'll only have to specify iterable and reverse, not key. The first input you pass to sorted() will be matched to the iterable argument, but what about the second input? To tell Python you want to specify reverse without changing anything about key, you can use =: sorted(___, reverse = ___) Two lists have been created for you on the right. Can you paste them together and sort them in descending order? Note: For now, we can understand an iterable as being any collection of objects, e.g. a List. Instructions: - Use + to merge the contents of first and second into a new list: full. - Call sorted() on full and specify the reverse argument to be True. Save the sorted list as full_sorted. - Finish off by printing out full_sorted. ''' # Create lists first and second first = [11.25, 18.0, 20.0] second = [10.75, 9.50] # Paste together first and second: full full = first + second # Sort full in descending order: full_sorted full_sorted = sorted(full, reverse=True) # Print out full_sorted print(full_sorted)
[ 7061, 6, 198, 3070, 532, 20401, 7159, 198, 198, 818, 262, 2180, 5517, 11, 262, 6616, 28103, 1088, 3590, 287, 262, 10314, 3751, 514, 326, 262, 198, 48466, 4578, 318, 11902, 13, 887, 11361, 635, 3544, 257, 1180, 835, 284, 1560, 2985, ...
3.797647
425
""" Entradas: 3 Valores flotantes que son el valor de diferentes monedas Chelines autriacos --> float --> x Dramas griegos --> float --> z Pesetas --> float --> w Salidas 4 valores flotantes que es la conversin de las anteriores monedas Pesetas --> float --> x Francos franceses --> float --> z Dolares --> float --> a Liras italianas --> float --> b """ # Entradas x1 = float(input("Dime los chelines autracos\n")) z1 = float(input("Dime los dracmas griegos\n")) w = float(input("Dime las pesetas\n")) # Caja negra x = (x1 * 956871)/100 z = z1/22.64572381 a = w/122499 b = (w*100)/9289 # Salidas print(f"\n{x1} Chelines austracos en pesetas son {x}\n{z1} Dracmas griegos en Francos franceses son {z}\n{w} Pesetas en Dolares son {a}\n{w} Pesetas en Liras italianas son {b}\n")
[ 37811, 198, 14539, 6335, 292, 25, 513, 3254, 2850, 781, 313, 39781, 8358, 3367, 1288, 1188, 273, 390, 288, 361, 9100, 274, 937, 276, 292, 220, 198, 198, 38292, 1127, 1960, 380, 330, 418, 14610, 12178, 14610, 2124, 220, 198, 35, 859, ...
2.451713
321
import argparse import os from glob import glob import imageio from tqdm import tqdm from csbdeep.utils import normalize from stardist.models import StarDist3D # could be done more efficiently, see # https://github.com/hci-unihd/batchlib/blob/master/batchlib/segmentation/stardist_prediction.py if __name__ == '__main__': main()
[ 11748, 1822, 29572, 198, 11748, 28686, 198, 6738, 15095, 1330, 15095, 198, 198, 11748, 2939, 952, 198, 6738, 256, 80, 36020, 1330, 256, 80, 36020, 198, 198, 6738, 269, 36299, 22089, 13, 26791, 1330, 3487, 1096, 198, 6738, 336, 446, 396,...
2.923077
117
#!/usr/bin/env python # -*- coding: utf-8 -*- from django import forms from estacionamientos.models import Estacionamiento, Reserva, Pago
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 42625, 14208, 1330, 5107, 198, 6738, 1556, 49443, 321, 1153, 418, 13, 27530, 1330, 10062, 49443, 321, 1153, 78, 1...
2.483333
60
""" Y. Saad, M. Schultz, GMRES: a generalized minimal residual algorithm for solving nonsymmetric linear systems, SIAM J. Sci. and Stat. Comput., 7(3), 856869, 1986, <https://doi.org/10.1137/0907058>. Other implementations: <https://petsc.org/release/docs/manualpages/KSP/KSPGMRES.html> """ from __future__ import annotations from typing import Callable import numpy as np import scipy.linalg from numpy.typing import ArrayLike from ._helpers import ( Identity, Info, LinearOperator, Product, assert_correct_shapes, clip_imag, get_default_inner, wrap_inner, ) from .arnoldi import ArnoldiHouseholder, ArnoldiMGS from .givens import givens def multi_matmul(A, b): """A @ b for many A, b (i.e., A.shape == (m,n,...), y.shape == (n,...))""" return np.einsum("ij...,j...->i...", A, b) def multi_solve_triangular(A, B): """This function calls scipy.linalg.solve_triangular for every single A. A vectorized version would be much better here. """ A_shape = A.shape a = A.reshape(A.shape[0], A.shape[1], -1) b = B.reshape(B.shape[0], -1) y = [] for k in range(a.shape[2]): if np.all(b[:, k] == 0.0): y.append(np.zeros(b[:, k].shape)) else: y.append(scipy.linalg.solve_triangular(a[:, :, k], b[:, k])) y = np.array(y).T.reshape([A_shape[0]] + list(A_shape[2:])) return y
[ 37811, 198, 56, 13, 10318, 324, 11, 337, 13, 26530, 11, 198, 38, 13599, 1546, 25, 257, 38284, 10926, 29598, 11862, 329, 18120, 14011, 26621, 19482, 14174, 3341, 11, 198, 11584, 2390, 449, 13, 10286, 13, 290, 5133, 13, 22476, 1539, 767...
2.312292
602
# Copyright 2020 Northern.tech AS # # 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. import pytest import random import time from testutils.api.client import ApiClient import testutils.api.useradm as useradm import testutils.api.deviceauth as deviceauth import testutils.api.tenantadm as tenantadm import testutils.api.deployments as deployments from testutils.infra.cli import CliTenantadm, CliUseradm import testutils.util.crypto from testutils.common import ( User, Device, Tenant, mongo, clean_mongo, create_org, create_random_authset, get_device_by_id_data, change_authset_status, ) class TestAccountSuspensionEnterprise: def test_user_cannot_log_in(self, tenants): tc = ApiClient(tenantadm.URL_INTERNAL) uc = ApiClient(useradm.URL_MGMT) for u in tenants[0].users: r = uc.call("POST", useradm.URL_LOGIN, auth=(u.name, u.pwd)) assert r.status_code == 200 # tenant's users can log in for u in tenants[0].users: r = uc.call("POST", useradm.URL_LOGIN, auth=(u.name, u.pwd)) assert r.status_code == 200 assert r.status_code == 200 # suspend tenant r = tc.call( "PUT", tenantadm.URL_INTERNAL_SUSPEND, tenantadm.req_status("suspended"), path_params={"tid": tenants[0].id}, ) assert r.status_code == 200 time.sleep(10) # none of tenant's users can log in for u in tenants[0].users: r = uc.call("POST", useradm.URL_LOGIN, auth=(u.name, u.pwd)) assert r.status_code == 401 # but other users still can for u in tenants[1].users: r = uc.call("POST", useradm.URL_LOGIN, auth=(u.name, u.pwd)) assert r.status_code == 200
[ 2, 15069, 12131, 8342, 13, 13670, 7054, 198, 2, 198, 2, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 220, 220, 220, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 35...
2.392675
983
import os, sys sys.path.append(os.path.dirname(os.path.abspath(__file__))) import json import logging import yaml import requests import time from actions.migrate_job_action import MigrateJobAction from actions.send_alert_action import SendAlertAction from actions.reboot_node_action import RebootNodeAction from actions.uncordon_action import UncordonAction from datetime import datetime, timedelta, timezone from rules_abc import Rule from utils import prometheus_util, k8s_util from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText activity_log = logging.getLogger('activity')
[ 11748, 28686, 11, 25064, 198, 17597, 13, 6978, 13, 33295, 7, 418, 13, 6978, 13, 15908, 3672, 7, 418, 13, 6978, 13, 397, 2777, 776, 7, 834, 7753, 834, 22305, 198, 198, 11748, 33918, 198, 11748, 18931, 198, 11748, 331, 43695, 198, 117...
3.373626
182
# Copyright 2019 Nokia # # 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 ironic_python_agent import hardware from ironic_python_agent import utils from oslo_log import log from oslo_concurrency import processutils LOG = log.getLogger()
[ 2, 15069, 13130, 26182, 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, 7330, 257...
3.724138
203
from django.core.cache import cache from datetime import datetime from museum_site.models.detail import Detail from museum_site.models.file import File from museum_site.constants import TERMS_DATE from museum_site.common import ( DEBUG, EMAIL_ADDRESS, BOOT_TS, CSS_INCLUDES, UPLOAD_CAP, env_from_host, qs_sans ) from museum_site.core.detail_identifiers import *
[ 6738, 42625, 14208, 13, 7295, 13, 23870, 1330, 12940, 198, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 198, 6738, 13257, 62, 15654, 13, 27530, 13, 49170, 1330, 42585, 198, 6738, 13257, 62, 15654, 13, 27530, 13, 7753, 1330, 9220, 198, ...
2.952381
126
from django.contrib.auth import get_user_model from django.contrib.staticfiles.templatetags.staticfiles import static from django.shortcuts import redirect from misago.conf import settings UserModel = get_user_model()
[ 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 1330, 651, 62, 7220, 62, 19849, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 12708, 16624, 13, 11498, 489, 265, 316, 3775, 13, 12708, 16624, 1330, 9037, 198, 6738, 42625, 14208, 13, 19509, ...
3.378788
66
from __future__ import print_function, unicode_literals, absolute_import, division from six.moves import range, zip, map, reduce, filter from keras.layers import Input, Conv2D, Conv3D, Activation, Lambda from keras.models import Model from keras.layers.merge import Add, Concatenate import tensorflow as tf from keras import backend as K from .blocks import unet_block, unet_blocks, gaussian_2d import re from ..utils import _raise, backend_channels_last import numpy as np def custom_unet(input_shape, last_activation, n_depth=2, n_filter_base=16, kernel_size=(3,3,3), n_conv_per_depth=2, activation="relu", batch_norm=False, dropout=0.0, pool_size=(2,2,2), n_channel_out=1, residual=False, prob_out=False, long_skip=True, eps_scale=1e-3): """ TODO """ if last_activation is None: raise ValueError("last activation has to be given (e.g. 'sigmoid', 'relu')!") all((s % 2 == 1 for s in kernel_size)) or _raise(ValueError('kernel size should be odd in all dimensions.')) channel_axis = -1 if backend_channels_last() else 1 n_dim = len(kernel_size) # TODO: rewrite with conv_block conv = Conv2D if n_dim == 2 else Conv3D input = Input(input_shape, name="input") unet = unet_block(n_depth, n_filter_base, kernel_size, input_planes=input_shape[-1], activation=activation, dropout=dropout, batch_norm=batch_norm, n_conv_per_depth=n_conv_per_depth, pool=pool_size, long_skip=long_skip)(input) final = conv(n_channel_out, (1,)*n_dim, activation='linear')(unet) if residual: if not (n_channel_out == input_shape[-1] if backend_channels_last() else n_channel_out == input_shape[0]): raise ValueError("number of input and output channels must be the same for a residual net.") final = Add()([final, input]) final = Activation(activation=last_activation)(final) if prob_out: scale = conv(n_channel_out, (1,)*n_dim, activation='softplus')(unet) scale = Lambda(lambda x: x+np.float32(eps_scale))(scale) final = Concatenate(axis=channel_axis)([final, scale]) return Model(inputs=input, outputs=final) def uxnet(input_shape, n_depth=2, n_filter_base=16, kernel_size=(3, 3), n_conv_per_depth=2, activation="relu", last_activation='linear', batch_norm=False, dropout=0.0, pool_size=(2, 2), residual=True, odd_to_even=False, shortcut=None, shared_idx=[], prob_out=False, eps_scale=1e-3): """ Multi-body U-Net which learns identity by leaving one plane out in each branch :param input_shape: :param n_depth: :param n_filter_base: :param kernel_size: :param n_conv_per_depth: :param activation: :param last_activation: :param batch_norm: :param dropout: :param pool_size: :param prob_out: :param eps_scale: :return: Model """ # TODO: fill params # TODO: add odd-to-even mode # Define vars channel_axis = -1 if backend_channels_last() else 1 n_planes = input_shape[channel_axis] if n_planes % 2 != 0 and odd_to_even: raise ValueError('Odd-to-even mode does not support uneven number of planes') n_dim = len(kernel_size) conv = Conv2D if n_dim == 2 else Conv3D # Define functional model input = Input(shape=input_shape, name='input_main') # TODO test new implementation and remove old # Split planes (preserve channel) input_x = [Lambda(lambda x: x[..., i:i+1], output_shape=(None, None, 1))(input) for i in range(n_planes)] # We can train either in odd-to-even mode or in LOO mode if odd_to_even: # In this mode we stack together odd and even planes, train the net to predict even from odd and vice versa # input_x_out = [Concatenate(axis=-1)(input_x[j::2]) for j in range(2)] input_x_out = [Concatenate(axis=-1)(input_x[j::2]) for j in range(1, -1, -1)] else: # Concatenate planes back in leave-one-out way input_x_out = [Concatenate(axis=-1)([plane for i, plane in enumerate(input_x) if i != j]) for j in range(n_planes)] # if odd_to_even: # input_x_out = [Lambda(lambda x: x[..., j::2], # output_shape=(None, None, n_planes // 2), # name='{}_planes'.format('even' if j == 0 else 'odd'))(input) # for j in range(1, -1, -1)] # else: # # input_x_out = [Lambda(lambda x: x[..., tf.convert_to_tensor([i for i in range(n_planes) if i != j], dtype=tf.int32)], # # output_shape=(None, None, n_planes-1), # # name='leave_{}_plane_out'.format(j))(input) # # for j in range(n_planes)] # # input_x_out = [Lambda(lambda x: K.concatenate([x[..., :j], x[..., (j+1):]], axis=-1), # output_shape=(None, None, n_planes - 1), # name='leave_{}_plane_out'.format(j))(input) # for j in range(n_planes)] # U-Net parameters depend on mode (odd-to-even or LOO) n_blocks = 2 if odd_to_even else n_planes input_planes = n_planes // 2 if odd_to_even else n_planes-1 output_planes = n_planes // 2 if odd_to_even else 1 # Create U-Net blocks (by number of planes) unet_x = unet_blocks(n_blocks=n_blocks, input_planes=input_planes, output_planes=output_planes, n_depth=n_depth, n_filter_base=n_filter_base, kernel_size=kernel_size, activation=activation, dropout=dropout, batch_norm=batch_norm, n_conv_per_depth=n_conv_per_depth, pool=pool_size, shared_idx=shared_idx) unet_x = [unet(inp_out) for unet, inp_out in zip(unet_x, input_x_out)] # Version without weight sharing: # unet_x = [unet_block(n_depth, n_filter_base, kernel_size, # activation=activation, dropout=dropout, batch_norm=batch_norm, # n_conv_per_depth=n_conv_per_depth, pool=pool_size, # prefix='out_{}_'.format(i))(inp_out) for i, inp_out in enumerate(input_x_out)] # TODO: rewritten for sharing -- remove commented below # Convolve n_filter_base to 1 as each U-Net predicts a single plane # unet_x = [conv(1, (1,) * n_dim, activation=activation)(unet) for unet in unet_x] if residual: if odd_to_even: # For residual U-Net sum up output for odd planes with even planes and vice versa unet_x = [Add()([unet, inp]) for unet, inp in zip(unet_x, input_x[::-1])] else: # For residual U-Net sum up output with its neighbor (next for the first plane, previous for the rest unet_x = [Add()([unet, inp]) for unet, inp in zip(unet_x, [input_x[1]]+input_x[:-1])] # Concatenate outputs of blocks, should receive (None, None, None, n_planes) # TODO assert to check shape? if odd_to_even: # Split even and odd, assemble them together in the correct order # TODO tests unet_even = [Lambda(lambda x: x[..., i:i+1], output_shape=(None, None, 1), name='even_{}'.format(i))(unet_x[0]) for i in range(n_planes // 2)] unet_odd = [Lambda(lambda x: x[..., i:i+1], output_shape=(None, None, 1), name='odd_{}'.format(i))(unet_x[1]) for i in range(n_planes // 2)] unet_x = list(np.array(list(zip(unet_even, unet_odd))).flatten()) unet = Concatenate(axis=-1)(unet_x) if shortcut is not None: # We can create a shortcut without long skip connection to prevent noise memorization if shortcut == 'unet': shortcut_block = unet_block(long_skip=False, input_planes=n_planes, n_depth=n_depth, n_filter_base=n_filter_base, kernel_size=kernel_size, activation=activation, dropout=dropout, batch_norm=batch_norm, n_conv_per_depth=n_conv_per_depth, pool=pool_size)(input) shortcut_block = conv(n_planes, (1,) * n_dim, activation='linear', name='shortcut_final_conv')(shortcut_block) # Or a simple gaussian blur block elif shortcut == 'gaussian': shortcut_block = gaussian_2d(n_planes, k=13, s=7)(input) else: raise ValueError('Shortcut should be either unet or gaussian') # TODO add or concatenate? unet = Add()([unet, shortcut_block]) # unet = Concatenate(axis=-1)([unet, shortcut_unet]) # Final activation layer final = Activation(activation=last_activation)(unet) if prob_out: scale = conv(n_planes, (1,)*n_dim, activation='softplus')(unet) scale = Lambda(lambda x: x+np.float32(eps_scale))(scale) final = Concatenate(axis=channel_axis)([final, scale]) return Model(inputs=input, outputs=final) def common_unet(n_dim=2, n_depth=1, kern_size=3, n_first=16, n_channel_out=1, residual=True, prob_out=False, long_skip=True, last_activation='linear'): """ Construct a common CARE neural net based on U-Net [1]_ and residual learning [2]_ to be used for image restoration/enhancement. Parameters ---------- n_dim : int number of image dimensions (2 or 3) n_depth : int number of resolution levels of U-Net architecture kern_size : int size of convolution filter in all image dimensions n_first : int number of convolution filters for first U-Net resolution level (value is doubled after each downsampling operation) n_channel_out : int number of channels of the predicted output image residual : bool if True, model will internally predict the residual w.r.t. the input (typically better) requires number of input and output image channels to be equal prob_out : bool standard regression (False) or probabilistic prediction (True) if True, model will predict two values for each input pixel (mean and positive scale value) last_activation : str name of activation function for the final output layer Returns ------- function Function to construct the network, which takes as argument the shape of the input image Example ------- >>> model = common_unet(2, 1,3,16, 1, True, False)(input_shape) References ---------- .. [1] Olaf Ronneberger, Philipp Fischer, Thomas Brox, *U-Net: Convolutional Networks for Biomedical Image Segmentation*, MICCAI 2015 .. [2] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun. *Deep Residual Learning for Image Recognition*, CVPR 2016 """ return _build_this modelname = re.compile("^(?P<model>resunet|unet)(?P<n_dim>\d)(?P<prob_out>p)?_(?P<n_depth>\d+)_(?P<kern_size>\d+)_(?P<n_first>\d+)(_(?P<n_channel_out>\d+)out)?(_(?P<last_activation>.+)-last)?$") def common_unet_by_name(model): r"""Shorthand notation for equivalent use of :func:`common_unet`. Parameters ---------- model : str define model to be created via string, which is parsed as a regular expression: `^(?P<model>resunet|unet)(?P<n_dim>\d)(?P<prob_out>p)?_(?P<n_depth>\d+)_(?P<kern_size>\d+)_(?P<n_first>\d+)(_(?P<n_channel_out>\d+)out)?(_(?P<last_activation>.+)-last)?$` Returns ------- function Calls :func:`common_unet` with the respective parameters. Raises ------ ValueError If argument `model` is not a valid string according to the regular expression. Example ------- >>> model = common_unet_by_name('resunet2_1_3_16_1out')(input_shape) >>> # equivalent to: model = common_unet(2, 1,3,16, 1, True, False)(input_shape) Todo ---- Backslashes in docstring for regexp not rendered correctly. """ m = modelname.fullmatch(model) if m is None: raise ValueError("model name '%s' unknown, must follow pattern '%s'" % (model, modelname.pattern)) # from pprint import pprint # pprint(m.groupdict()) options = {k:int(m.group(k)) for k in ['n_depth','n_first','kern_size']} options['prob_out'] = m.group('prob_out') is not None options['residual'] = {'unet': False, 'resunet': True}[m.group('model')] options['n_dim'] = int(m.group('n_dim')) options['n_channel_out'] = 1 if m.group('n_channel_out') is None else int(m.group('n_channel_out')) if m.group('last_activation') is not None: options['last_activation'] = m.group('last_activation') return common_unet(**options) def receptive_field_unet(n_depth, kern_size, pool_size=2, n_dim=2, img_size=1024): """Receptive field for U-Net model (pre/post for each dimension).""" x = np.zeros((1,)+(img_size,)*n_dim+(1,)) mid = tuple([s//2 for s in x.shape[1:-1]]) x[(slice(None),) + mid + (slice(None),)] = 1 model = custom_unet ( x.shape[1:], n_depth=n_depth, kernel_size=[kern_size]*n_dim, pool_size=[pool_size]*n_dim, n_filter_base=8, activation='linear', last_activation='linear', ) y = model.predict(x)[0,...,0] y0 = model.predict(0*x)[0,...,0] ind = np.where(np.abs(y-y0)>0) return [(m-np.min(i), np.max(i)-m) for (m, i) in zip(mid, ind)]
[ 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 11, 28000, 1098, 62, 17201, 874, 11, 4112, 62, 11748, 11, 7297, 198, 6738, 2237, 13, 76, 5241, 1330, 2837, 11, 19974, 11, 3975, 11, 4646, 11, 8106, 198, 198, 6738, 41927, 292, 13, 75, ...
2.255625
6,044
parameters = {} genome = {} genome_stats = {} genome_test_stats = [] brain = {} cortical_list = [] cortical_map = {} intercortical_mapping = [] block_dic = {} upstream_neurons = {} memory_list = {} activity_stats = {} temp_neuron_list = [] original_genome_id = [] fire_list = [] termination_flag = False variation_counter_actual = 0 exposure_counter_actual = 0 mnist_training = {} mnist_testing = {} top_10_utf_memory_neurons = {} top_10_utf_neurons = {} v1_members = [] prunning_candidates = set() genome_id = "" event_id = '_' blueprint = "" comprehension_queue = '' working_directory = '' connectome_path = '' paths = {} watchdog_queue = '' exit_condition = False fcl_queue = '' proximity_queue = '' last_ipu_activity = '' last_alertness_trigger = '' influxdb = '' mongodb = '' running_in_container = False hardware = '' gazebo = False stimulation_data = {} hw_controller_path = '' hw_controller = None opu_pub = None router_address = None burst_timer = 1 # rules = "" brain_is_running = False # live_mode_status can have modes of idle, learning, testing, tbd live_mode_status = 'idle' fcl_history = {} brain_run_id = "" burst_detection_list = {} burst_count = 0 fire_candidate_list = {} previous_fcl = {} future_fcl = {} labeled_image = [] training_neuron_list_utf = {} training_neuron_list_img = {} empty_fcl_counter = 0 neuron_mp_list = [] pain_flag = False cumulative_neighbor_count = 0 time_neuron_update = '' time_apply_plasticity_ext = '' plasticity_time_total = None plasticity_time_total_p1 = None plasticity_dict = {} tester_test_stats = {} # Flags flag_ready_to_inject_image = False
[ 17143, 7307, 796, 23884, 198, 5235, 462, 796, 23884, 198, 5235, 462, 62, 34242, 796, 23884, 198, 5235, 462, 62, 9288, 62, 34242, 796, 17635, 198, 27825, 796, 23884, 198, 66, 419, 605, 62, 4868, 796, 17635, 198, 66, 419, 605, 62, 889...
2.687919
596
#!/usr/bin/env python # -*- coding: utf-8 -*- import subprocess from geonamescache import GeonamesCache gc = GeonamesCache() toposrc = '../data/states-provinces.json' for iso2, country in gc.get_countries().items(): iso3 = country['iso3'] topojson = 'mapshaper -i {0} -filter \'"{1}" == adm0_a3\' -filter-fields fips,name -o format=topojson {1}.json' subprocess.call(topojson.format(toposrc, iso3), shell=True) subprocess.call('mv *.json ../src/topojson/countries/', shell=True)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 850, 14681, 198, 6738, 4903, 261, 1047, 23870, 1330, 2269, 261, 1047, 30562, 198, 198, 36484, 796, 2269, 261, 10...
2.507614
197
""" This module contains all information for pushing a NordicEvent object into the database. Functions and Classes --------------------- """ import psycopg2 import os import re import datetime from nordb.core import usernameUtilities from nordb.database import creationInfo INSERT_COMMANDS = { 1: ( "INSERT INTO " "nordic_header_main " "(origin_time, origin_date, location_model, " "distance_indicator, event_desc_id, epicenter_latitude, " "epicenter_longitude, depth, depth_control, " "locating_indicator, epicenter_reporting_agency, " "stations_used, rms_time_residuals, magnitude_1, " "type_of_magnitude_1, magnitude_reporting_agency_1, " "magnitude_2, type_of_magnitude_2, magnitude_reporting_agency_2, " "magnitude_3, type_of_magnitude_3, magnitude_reporting_agency_3, " "event_id) " "VALUES " "(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, " "%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) " "RETURNING " "id;" ), 2: ( "INSERT INTO " "nordic_header_macroseismic " "(description, diastrophism_code, tsunami_code, seiche_code, " "cultural_effects, unusual_effects, maximum_observed_intensity, " "maximum_intensity_qualifier, intensity_scale, macroseismic_latitude, " "macroseismic_longitude, macroseismic_magnitude, type_of_magnitude, " "logarithm_of_radius, logarithm_of_area_1, bordering_intensity_1, " "logarithm_of_area_2, bordering_intensity_2, quality_rank, " "reporting_agency, event_id) " "VALUES " "(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, " " %s, %s, %s, %s, %s, %s) " "RETURNING " "id" ), 3: ( "INSERT INTO " "nordic_header_comment " "(h_comment, event_id) " "VALUES " "(%s, %s) " "RETURNING " "id " ), 5: ( "INSERT INTO " "nordic_header_error " "(gap, second_error, epicenter_latitude_error, " "epicenter_longitude_error, depth_error, " "magnitude_error, header_id) " "VALUES " "(%s, %s, %s, %s, %s, %s, %s)" "RETURNING " "id" ), 6: ( "INSERT INTO " "nordic_header_waveform " "(waveform_info, event_id) " "VALUES " "(%s, %s) " "RETURNING " "id " ), 7: ( "INSERT INTO " "nordic_phase_data " "(station_code, sp_instrument_type, sp_component, quality_indicator, " "phase_type, weight, first_motion, observation_time, " "signal_duration, max_amplitude, max_amplitude_period, back_azimuth, " "apparent_velocity, signal_to_noise, azimuth_residual, " "travel_time_residual, location_weight, epicenter_distance, " "epicenter_to_station_azimuth, event_id) " "VALUES " "(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, " "%s, %s, %s, %s, %s, %s, %s, %s, %s) " "RETURNING " "id " ), } def event2Database(nordic_event, solution_type = "O", nordic_filename = None, f_creation_id = None, e_id = -1, privacy_level='public', db_conn = None): """ Function that pushes a NordicEvent object to the database :param NordicEvent nordic_event: Event that will be pushed to the database :param int solution_type: event type id :param str nordic_filename: name of the file from which the nordic is read from :param int f_creation_id: id of the creation_info entry in the database :param int e_id: id of the event to which this event will be attached to by event_root. If -1 then this event will not be attached to aything. :param string privacy_level: privacy level of the event in the database """ if db_conn is None: conn = usernameUtilities.log2nordb() else: conn = db_conn if f_creation_id is None: creation_id = creationInfo.createCreationInfo(privacy_level, conn) else: creation_id = f_creation_id author_id = None for header in nordic_event.comment_h: search = re.search(r'\((\w{3})\)', header.h_comment) if search is not None: author_id = search.group(0)[1:-1] if author_id is None: author_id = '---' cur = conn.cursor() try: cur.execute("SELECT allow_multiple FROM solution_type WHERE type_id = %s", (solution_type,)) ans = cur.fetchone() if ans is None: raise Exception("{0} is not a valid solution_type! Either add the event type to the database or use another solution_type".format(solution_type)) allow_multiple = ans[0] filename_id = -1 cur.execute("SELECT id FROM nordic_file WHERE file_location = %s", (nordic_filename,)) filenameids = cur.fetchone() if filenameids is not None: filename_id = filenameids[0] root_id = -1 if nordic_event.root_id != -1: root_id = nordic_event.root_id if e_id >= 0: cur.execute("SELECT root_id, solution_type FROM nordic_event WHERE id = %s", (e_id,)) try: root_id, old_solution_type = cur.fetchone() except: raise Exception("Given linking even_id does not exist in the database!") if e_id == -1 and nordic_event.root_id == -1: cur.execute("INSERT INTO nordic_event_root DEFAULT VALUES RETURNING id;") root_id = cur.fetchone()[0] if filename_id == -1: cur.execute("INSERT INTO nordic_file (file_location) VALUES (%s) RETURNING id", (nordic_filename,)) filename_id = cur.fetchone()[0] cur.execute("INSERT INTO " + "nordic_event " + "(solution_type, root_id, nordic_file_id, author_id, creation_id) " + "VALUES " + "(%s, %s, %s, %s, %s) " + "RETURNING " + "id", (solution_type, root_id, filename_id, author_id, creation_id) ) event_id = cur.fetchone()[0] nordic_event.event_id = event_id if e_id != -1 and solution_type == old_solution_type and not allow_multiple: cur.execute("UPDATE nordic_event SET solution_type = 'O' WHERE id = %s", (e_id,)) main_header_id = -1 for main in nordic_event.main_h: main.event_id = event_id main.h_id = executeCommand( cur, INSERT_COMMANDS[1], main.getAsList(), True)[0][0] if main.error_h is not None: main.error_h.header_id = main.h_id main.error_h.h_id = executeCommand( cur, INSERT_COMMANDS[5], main.error_h.getAsList(), True)[0][0] for macro in nordic_event.macro_h: macro.event_id = event_id macro.h_id = executeCommand(cur, INSERT_COMMANDS[2], macro.getAsList(), True)[0][0] for comment in nordic_event.comment_h: comment.event_id = event_id comment.h_id = executeCommand( cur, INSERT_COMMANDS[3], comment.getAsList(), True)[0][0] for waveform in nordic_event.waveform_h: waveform.event_id = event_id waveform.h_id = executeCommand( cur, INSERT_COMMANDS[6], waveform.getAsList(), True)[0][0] for phase_data in nordic_event.data: phase_data.event_id = event_id d_id = executeCommand( cur, INSERT_COMMANDS[7], phase_data.getAsList(), True)[0][0] phase_data.d_id = d_id conn.commit() except Exception as e: raise e finally: if f_creation_id is None: creationInfo.deleteCreationInfoIfUnnecessary(creation_id, db_conn=conn) if db_conn is None: conn.close() def executeCommand(cur, command, vals, returnValue): """ Function for for executing a command with values and handling exceptions :param Psycopg.Cursor cur: cursor object from psycopg2 library :param str command: the sql command string :param list vals: list of values for the command :param bool returnValue: boolean values for if the command returns a value :returns: Values returned by the query or None if returnValue is False """ cur.execute(command, vals) if returnValue: return cur.fetchall() else: return None
[ 37811, 198, 1212, 8265, 4909, 477, 1321, 329, 7796, 257, 35834, 9237, 2134, 656, 262, 6831, 13, 198, 198, 24629, 2733, 290, 38884, 198, 19351, 12, 198, 37811, 198, 198, 11748, 17331, 22163, 70, 17, 198, 11748, 28686, 198, 11748, 302, ...
1.710564
6,295
"""This module contains class definitions for storing media files""" import webbrowser
[ 37811, 1212, 8265, 4909, 1398, 17336, 329, 23069, 2056, 3696, 37811, 198, 198, 11748, 3992, 40259, 198 ]
5.176471
17
# workserver.py - simple HTTP server with a do_work / stop_work API # GET /do_work activates a worker thread which uses CPU # GET /stop_work signals worker thread to stop import math import socket import threading import time from bottle import route, run hostname = socket.gethostname() hostport = 9000 keepworking = False # boolean to switch worker thread on or off # thread which maximizes CPU usage while the keepWorking global is True # start the worker thread worker_thread = threading.Thread(target=workerthread, args=()) worker_thread.start() run(host=hostname, port=hostport)
[ 2, 2499, 18497, 13, 9078, 532, 2829, 14626, 4382, 351, 257, 466, 62, 1818, 1220, 2245, 62, 1818, 7824, 198, 2, 17151, 1220, 4598, 62, 1818, 36206, 257, 8383, 4704, 543, 3544, 9135, 198, 2, 17151, 1220, 11338, 62, 1818, 10425, 8383, ...
3.691358
162
from maxdb import DB def _open(self): """Create DB instance and preload default models.""" self._db = DB(self._path) products = self._db.table( 'Products', columns={'name': 'str', 'price': 'int'} ) orders = self._db.table( 'Orders', columns={'product': 'fk', 'client': 'str', 'destination': 'addr'} ) try: products.insert_multiple([ {"name": ("product1", "str"), "price": ("50", "int")}, {"name": ("product2", "str"), "price": ("100", "int")}, {"name": ("product3", "str"), "price": ("200", "int")}, ]) except: pass try: orders.insert_multiple([ { "product": ({'table': 'Products', 'fkid': '1'}, 'fk'), "client": ("honchar", "str"), "destination": ("Kyiv", "addr") }, { "product": ({'table': 'Products', 'fkid': '2'}, 'fk'), "client": ("honchar2", "str"), "destination": ("Kyiv2", "addr") }, { "product": ({'table': 'Products', 'fkid': '3'}, 'fk'), "client": ("honchar3", "str"), "destination": ("Kyiv3", "addr") }, ]) except: pass self.run('help', *()) def _close(self, _): """Close DB instance routine.""" self._db.close() def __enter__(self): self._open() return self def __exit__(self, exc_type, exc_val, exc_tb): self._close(None)
[ 6738, 3509, 9945, 1330, 20137, 628, 628, 220, 220, 220, 825, 4808, 9654, 7, 944, 2599, 198, 220, 220, 220, 220, 220, 220, 220, 37227, 16447, 20137, 4554, 290, 662, 2220, 4277, 4981, 526, 15931, 198, 220, 220, 220, 220, 220, 220, 220...
1.823144
916
import easygui as g # judge=1 # def judge_null(tmp): # if tmp.isspace()or len(tmp)==0: # return judge==0 # # while 1: # user_info=g.multenterbox(title='', # msg='*\t*\t*\t*E-mail', # fields=['*','*','','*','QQ','*E-mail'] # ) # # if judge_null(user_info[0])==0: # g.msgbox(title='',msg='') # elif judge_null(user_info[1])==0: # g.msgbox(title='',msg='') # elif judge_null(user_info[3])==0: # g.msgbox(title='',msg='') # elif judge_null(user_info[5])==0: # g.msgbox(title='',msg='E-mail') # else: # g.msgbox(title='',msg='') # break #2 title='' msg='' field_list=['*','*','','*','QQ','*E-mail'] field_value=[] field_value = g.multenterbox(msg,title,field_list) while 1: if field_value==None: break err_msg='' for i in range(len(field_list)): option=field_list[i].strip() if field_value[i].strip()==''and option[0]=='*': err_msg+='%s\n\n'%(field_list[i]) if err_msg=='': break field_value = g.multenterbox(err_msg, title, field_list,field_value) print(''+str(field_value))
[ 11748, 2562, 48317, 355, 308, 198, 198, 2, 5052, 28, 16, 198, 2, 825, 5052, 62, 8423, 7, 22065, 2599, 198, 2, 220, 220, 220, 220, 611, 45218, 13, 747, 10223, 3419, 273, 18896, 7, 22065, 8, 855, 15, 25, 198, 2, 220, 220, 220, 2...
1.835913
646
from cognibench.models import CNBModel from cognibench.capabilities import ContinuousAction, ContinuousObservation from cognibench.continuous import ContinuousSpace from cognibench.models.wrappers import MatlabWrapperMixin
[ 6738, 8866, 571, 24421, 13, 27530, 1330, 31171, 33, 17633, 198, 6738, 8866, 571, 24421, 13, 11128, 5738, 1330, 45012, 12502, 11, 45012, 31310, 13208, 198, 6738, 8866, 571, 24421, 13, 18487, 5623, 1330, 45012, 14106, 198, 6738, 8866, 571, ...
4.148148
54
from layout import Layout
[ 6738, 12461, 1330, 47639, 198 ]
5.2
5
import unittest from programy.config.file.yaml_file import YamlConfigurationFile from programy.clients.restful.config import RestConfiguration from programy.clients.events.console.config import ConsoleConfiguration
[ 11748, 555, 715, 395, 198, 198, 6738, 1430, 88, 13, 11250, 13, 7753, 13, 88, 43695, 62, 7753, 1330, 14063, 75, 38149, 8979, 198, 6738, 1430, 88, 13, 565, 2334, 13, 2118, 913, 13, 11250, 1330, 8324, 38149, 198, 6738, 1430, 88, 13, ...
3.927273
55
# Write a recursive function to count the number of nodes in a Tree. (first do your self then see code) Q # 2: '''The height of a tree is the maximum number of levels in the tree. So, a tree with just one node has a height of 1. If the root has children which are leaves, the height of the tree is 2. The height of a TreeNode can be computed recursively using a simple algorithm: The height Of a TreeNode With no children is 1. If it has children the height is: max of height of its two sub-trees + 1. Write a clean, recursive function for the TreeNode class that calculates the height based on the above statement(first do your self then see code) ''' print(self.val) if self.left.val > self.val or self.right.val < self.val return False
[ 2, 19430, 257, 45115, 2163, 284, 954, 262, 1271, 286, 13760, 287, 257, 12200, 13, 357, 11085, 466, 534, 2116, 788, 766, 2438, 8, 198, 197, 198, 197, 198, 1195, 1303, 362, 25, 197, 198, 7061, 6, 464, 6001, 286, 257, 5509, 318, 262,...
3.673171
205
#! /usr/bin/env python3 # from datetime import datetime # from random import choices # from string import ascii_lowercase from flask import Flask, request, render_template, Response, send_file from flaskext.markdown import Markdown from D47crunch import D47data, pretty_table, make_csv, smart_type from D47crunch import __version__ as vD47crunch import zipfile, io, time from pylab import * from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas import base64 from werkzeug.wsgi import FileWrapper from matplotlib import rcParams # rcParams['backend'] = 'Agg' # rcParams['interactive'] = False rcParams['font.family'] = 'Helvetica' rcParams['font.sans-serif'] = 'Helvetica' rcParams['font.size'] = 10 rcParams['mathtext.fontset'] = 'custom' rcParams['mathtext.rm'] = 'sans' rcParams['mathtext.bf'] = 'sans:bold' rcParams['mathtext.it'] = 'sans:italic' rcParams['mathtext.cal'] = 'sans:italic' rcParams['mathtext.default'] = 'rm' rcParams['xtick.major.size'] = 4 rcParams['xtick.major.width'] = 1 rcParams['ytick.major.size'] = 4 rcParams['ytick.major.width'] = 1 rcParams['axes.grid'] = False rcParams['axes.linewidth'] = 1 rcParams['grid.linewidth'] = .75 rcParams['grid.linestyle'] = '-' rcParams['grid.alpha'] = .15 rcParams['savefig.dpi'] = 150 __author__ = 'Mathieu Daron' __contact__ = 'daeron@lsce.ipsl.fr' __copyright__ = 'Copyright (c) 2020 Mathieu Daron' __license__ = 'Modified BSD License - https://opensource.org/licenses/BSD-3-Clause' __date__ = '2020-04-22' __version__ = '2.1.dev2' rawdata_input_str = '''UID\tSession\tSample\td45\td46\td47\tNominal_d13C_VPDB\tNominal_d18O_VPDB A01\tSession01\tETH-1\t5.795017\t11.627668\t16.893512\t2.02\t-2.19 A02\tSession01\tIAEA-C1\t6.219070\t11.491072\t17.277490 A03\tSession01\tETH-2\t-6.058681\t-4.817179\t-11.635064\t-10.17\t-18.69 A04\tSession01\tIAEA-C2\t-3.861839\t4.941839\t0.606117 A05\tSession01\tETH-3\t5.543654\t12.052277\t17.405548\t1.71\t-1.78 A06\tSession01\tMERCK\t-35.929352\t-2.087501\t-39.548484 A07\tSession01\tETH-4\t-6.222218\t-5.194170\t-11.944111 A08\tSession01\tETH-2\t-6.067055\t-4.877104\t-11.699265\t-10.17\t-18.69 A09\tSession01\tMERCK\t-35.930739\t-2.080798\t-39.545632 A10\tSession01\tETH-1\t5.788207\t11.559104\t16.801908\t2.02\t-2.19 A11\tSession01\tETH-4\t-6.217508\t-5.221407\t-11.987503 A12\tSession01\tIAEA-C2\t-3.876921\t4.868892\t0.521845 A13\tSession01\tETH-3\t5.539840\t12.013444\t17.368631\t1.71\t-1.78 A14\tSession01\tIAEA-C1\t6.219046\t11.447846\t17.234280 A15\tSession01\tMERCK\t-35.932060\t-2.088659\t-39.531627 A16\tSession01\tETH-3\t5.516658\t11.978320\t17.295740\t1.71\t-1.78 A17\tSession01\tETH-4\t-6.223370\t-5.253980\t-12.025298 A18\tSession01\tETH-2\t-6.069734\t-4.868368\t-11.688559\t-10.17\t-18.69 A19\tSession01\tIAEA-C1\t6.213642\t11.465109\t17.244547 A20\tSession01\tETH-1\t5.789982\t11.535603\t16.789811\t2.02\t-2.19 A21\tSession01\tETH-4\t-6.205703\t-5.144529\t-11.909160 A22\tSession01\tIAEA-C1\t6.212646\t11.406548\t17.187214 A23\tSession01\tETH-3\t5.531413\t11.976697\t17.332700\t1.71\t-1.78 A24\tSession01\tMERCK\t-35.926347\t-2.124579\t-39.582201 A25\tSession01\tETH-1\t5.786979\t11.527864\t16.775547\t2.02\t-2.19 A26\tSession01\tIAEA-C2\t-3.866505\t4.874630\t0.525332 A27\tSession01\tETH-2\t-6.076302\t-4.922424\t-11.753283\t-10.17\t-18.69 A28\tSession01\tIAEA-C2\t-3.878438\t4.818588\t0.467595 A29\tSession01\tETH-3\t5.546458\t12.133931\t17.501646\t1.71\t-1.78 A30\tSession01\tETH-1\t5.802916\t11.642685\t16.904286\t2.02\t-2.19 A31\tSession01\tETH-2\t-6.069274\t-4.847919\t-11.677722\t-10.17\t-18.69 A32\tSession01\tETH-3\t5.523018\t12.007363\t17.362080\t1.71\t-1.78 A33\tSession01\tETH-1\t5.802333\t11.616032\t16.884255\t2.02\t-2.19 A34\tSession01\tETH-3\t5.537375\t12.000263\t17.350856\t1.71\t-1.78 A35\tSession01\tETH-2\t-6.060713\t-4.893088\t-11.728465\t-10.17\t-18.69 A36\tSession01\tETH-3\t5.532342\t11.990022\t17.342273\t1.71\t-1.78 A37\tSession01\tETH-3\t5.533622\t11.980853\t17.342245\t1.71\t-1.78 A38\tSession01\tIAEA-C2\t-3.867587\t4.893554\t0.540404 A39\tSession01\tIAEA-C1\t6.201760\t11.406628\t17.189625 A40\tSession01\tETH-1\t5.802150\t11.563414\t16.836189\t2.02\t-2.19 A41\tSession01\tETH-2\t-6.068598\t-4.897545\t-11.722343\t-10.17\t-18.69 A42\tSession01\tMERCK\t-35.928359\t-2.098440\t-39.577150 A43\tSession01\tETH-4\t-6.219175\t-5.168031\t-11.936923 A44\tSession01\tIAEA-C2\t-3.871671\t4.871517\t0.518290 B01\tSession02\tETH-1\t5.800180\t11.640916\t16.939044\t2.02\t-2.19 B02\tSession02\tETH-1\t5.799584\t11.631297\t16.917656\t2.02\t-2.19 B03\tSession02\tIAEA-C1\t6.225135\t11.512637\t17.335876 B04\tSession02\tETH-2\t-6.030415\t-4.746444\t-11.525506\t-10.17\t-18.69 B05\tSession02\tIAEA-C2\t-3.837017\t4.992780\t0.675292 B06\tSession02\tETH-3\t5.536997\t12.048918\t17.420228\t1.71\t-1.78 B07\tSession02\tMERCK\t-35.928379\t-2.105615\t-39.594573 B08\tSession02\tETH-4\t-6.218801\t-5.185168\t-11.964407 B09\tSession02\tETH-2\t-6.068197\t-4.840037\t-11.686296\t-10.17\t-18.69 B10\tSession02\tMERCK\t-35.926951\t-2.071047\t-39.546767 B11\tSession02\tETH-1\t5.782634\t11.571818\t16.835185\t2.02\t-2.19 B12\tSession02\tETH-2\t-6.070168\t-4.877700\t-11.703876\t-10.17\t-18.69 B13\tSession02\tETH-4\t-6.214873\t-5.190550\t-11.967040 B14\tSession02\tIAEA-C2\t-3.853550\t4.919425\t0.584634 B15\tSession02\tETH-3\t5.522265\t12.011737\t17.368407\t1.71\t-1.78 B16\tSession02\tIAEA-C1\t6.219374\t11.447014\t17.264258 B17\tSession02\tMERCK\t-35.927733\t-2.103033\t-39.603494 B18\tSession02\tETH-3\t5.527002\t11.984062\t17.332660\t1.71\t-1.78 B19\tSession02\tIAEA-C2\t-3.850358\t4.889230\t0.562794 B20\tSession02\tETH-4\t-6.222398\t-5.263817\t-12.033650 B21\tSession02\tETH-3\t5.525478\t11.970096\t17.340498\t1.71\t-1.78 B22\tSession02\tETH-2\t-6.070129\t-4.941487\t-11.773824\t-10.17\t-18.69 B23\tSession02\tIAEA-C1\t6.217001\t11.434152\t17.232308 B24\tSession02\tETH-1\t5.793421\t11.533191\t16.810838\t2.02\t-2.19 B25\tSession02\tETH-4\t-6.217740\t-5.198048\t-11.977179 B26\tSession02\tIAEA-C1\t6.216912\t11.425200\t17.234224 B27\tSession02\tETH-3\t5.522238\t11.932174\t17.286903\t1.71\t-1.78 B28\tSession02\tMERCK\t-35.914404\t-2.133955\t-39.614612 B29\tSession02\tETH-1\t5.784156\t11.517244\t16.786548\t2.02\t-2.19 B30\tSession02\tIAEA-C2\t-3.852750\t4.884339\t0.551587 B31\tSession02\tETH-2\t-6.068631\t-4.924103\t-11.764507\t-10.17\t-18.69 B32\tSession02\tETH-4\t-6.220238\t-5.231375\t-12.009300 B33\tSession02\tIAEA-C2\t-3.855245\t4.866571\t0.534914 B34\tSession02\tETH-1\t5.788790\t11.544306\t16.809117\t2.02\t-2.19 B35\tSession02\tMERCK\t-35.935017\t-2.173682\t-39.664046 B36\tSession02\tETH-3\t5.518320\t11.955048\t17.300668\t1.71\t-1.78 B37\tSession02\tETH-1\t5.790564\t11.521174\t16.781304\t2.02\t-2.19 B38\tSession02\tETH-4\t-6.218809\t-5.205256\t-11.979998 B39\tSession02\tIAEA-C1\t6.204774\t11.391335\t17.181310 B40\tSession02\tETH-2\t-6.076424\t-4.967973\t-11.815466\t-10.17\t-18.69 C01\tSession03\tETH-3\t5.541868\t12.129615\t17.503738\t1.71\t-1.78 C02\tSession03\tETH-3\t5.534395\t12.034601\t17.391274\t1.71\t-1.78 C03\tSession03\tETH-1\t5.797568\t11.563575\t16.857871\t2.02\t-2.19 C04\tSession03\tETH-3\t5.529415\t11.969512\t17.342673\t1.71\t-1.78 C05\tSession03\tETH-1\t5.794026\t11.526540\t16.806934\t2.02\t-2.19 C06\tSession03\tETH-3\t5.527210\t11.937462\t17.294015\t1.71\t-1.78 C07\tSession03\tIAEA-C1\t6.220521\t11.430197\t17.242458 C08\tSession03\tETH-2\t-6.064061\t-4.900852\t-11.732976\t-10.17\t-18.69 C09\tSession03\tIAEA-C2\t-3.846482\t4.889242\t0.558395 C10\tSession03\tETH-1\t5.789644\t11.520663\t16.795837\t2.02\t-2.19 C11\tSession03\tETH-4\t-6.219385\t-5.258604\t-12.036476 C12\tSession03\tMERCK\t-35.936631\t-2.161769\t-39.693775 C13\tSession03\tETH-2\t-6.076357\t-4.939912\t-11.803553\t-10.17\t-18.69 C14\tSession03\tIAEA-C2\t-3.862518\t4.850015\t0.499777 C15\tSession03\tETH-3\t5.515822\t11.928316\t17.287739\t1.71\t-1.78 C16\tSession03\tETH-4\t-6.216625\t-5.252914\t-12.033781 C17\tSession03\tETH-1\t5.792540\t11.537788\t16.801906\t2.02\t-2.19 C18\tSession03\tIAEA-C1\t6.218853\t11.447394\t17.270859 C19\tSession03\tETH-2\t-6.070107\t-4.944520\t-11.806885\t-10.17\t-18.69 C20\tSession03\tMERCK\t-35.935001\t-2.155577\t-39.675070 C21\tSession03\tETH-3\t5.542309\t12.082338\t17.471951\t1.71\t-1.78 C22\tSession03\tETH-4\t-6.209017\t-5.137393\t-11.920935 C23\tSession03\tETH-1\t5.796781\t11.621197\t16.905496\t2.02\t-2.19 C24\tSession03\tMERCK\t-35.926449\t-2.053921\t-39.576918 C25\tSession03\tETH-2\t-6.057158\t-4.797641\t-11.644824\t-10.17\t-18.69 C26\tSession03\tIAEA-C1\t6.221982\t11.501725\t17.321709 C27\tSession03\tETH-3\t5.535162\t12.023486\t17.396560\t1.71\t-1.78 C28\tSession03\tIAEA-C2\t-3.836934\t4.984196\t0.665651 C29\tSession03\tETH-3\t5.531331\t11.991300\t17.353622\t1.71\t-1.78 C30\tSession03\tIAEA-C2\t-3.844008\t4.926554\t0.601156 C31\tSession03\tETH-2\t-6.063163\t-4.907454\t-11.765065\t-10.17\t-18.69 C32\tSession03\tMERCK\t-35.941566\t-2.163022\t-39.704731 C33\tSession03\tETH-3\t5.523894\t11.992718\t17.363902\t1.71\t-1.78 C34\tSession03\tIAEA-C1\t6.220801\t11.462090\t17.282153 C35\tSession03\tETH-1\t5.794369\t11.563017\t16.845673\t2.02\t-2.19 C36\tSession03\tETH-4\t-6.221257\t-5.272969\t-12.055444 C37\tSession03\tETH-3\t5.517832\t11.957180\t17.312487\t1.71\t-1.78 C38\tSession03\tETH-2\t-6.053330\t-4.909476\t-11.740852\t-10.17\t-18.69 C39\tSession03\tIAEA-C1\t6.217139\t11.440085\t17.244787 C40\tSession03\tETH-1\t5.794091\t11.541948\t16.826158\t2.02\t-2.19 C41\tSession03\tIAEA-C2\t-3.803466\t4.894953\t0.624184 C42\tSession03\tETH-3\t5.513788\t11.933062\t17.286883\t1.71\t-1.78 C43\tSession03\tETH-1\t5.793334\t11.569668\t16.844535\t2.02\t-2.19 C44\tSession03\tETH-2\t-6.064928\t-4.935031\t-11.786336\t-10.17\t-18.69 C45\tSession03\tETH-4\t-6.216796\t-5.300373\t-12.075033 C46\tSession03\tETH-3\t5.521772\t11.933713\t17.283775\t1.71\t-1.78 C47\tSession03\tMERCK\t-35.937762\t-2.181553\t-39.739636 D01\tSession04\tETH-4\t-6.218867\t-5.242334\t-12.032129 D02\tSession04\tIAEA-C1\t6.218458\t11.435622\t17.238776 D03\tSession04\tETH-3\t5.522006\t11.946540\t17.300601\t1.71\t-1.78 D04\tSession04\tMERCK\t-35.931765\t-2.175265\t-39.716152 D05\tSession04\tETH-1\t5.786884\t11.560397\t16.823187\t2.02\t-2.19 D06\tSession04\tIAEA-C2\t-3.846071\t4.861980\t0.534465 D07\tSession04\tETH-2\t-6.072653\t-4.917987\t-11.786215\t-10.17\t-18.69 D08\tSession04\tETH-3\t5.516592\t11.923729\t17.275641\t1.71\t-1.78 D09\tSession04\tETH-1\t5.789889\t11.531354\t16.804221\t2.02\t-2.19 D10\tSession04\tIAEA-C2\t-3.845074\t4.865635\t0.546284 D11\tSession04\tETH-1\t5.795006\t11.507829\t16.772751\t2.02\t-2.19 D12\tSession04\tETH-1\t5.791371\t11.540606\t16.822704\t2.02\t-2.19 D13\tSession04\tETH-2\t-6.074029\t-4.937379\t-11.786614\t-10.17\t-18.69 D14\tSession04\tETH-4\t-6.216977\t-5.273352\t-12.057294 D15\tSession04\tIAEA-C1\t6.214304\t11.412869\t17.227005 D16\tSession04\tETH-2\t-6.071021\t-4.966406\t-11.812116\t-10.17\t-18.69 D17\tSession04\tETH-3\t5.543181\t12.065648\t17.455042\t1.71\t-1.78 D18\tSession04\tETH-1\t5.805793\t11.632212\t16.937561\t2.02\t-2.19 D19\tSession04\tIAEA-C1\t6.230425\t11.518038\t17.342943 D20\tSession04\tETH-2\t-6.049292\t-4.811109\t-11.639895\t-10.17\t-18.69 D21\tSession04\tIAEA-C2\t-3.829436\t4.967992\t0.665451 D22\tSession04\tETH-3\t5.538827\t12.064780\t17.438156\t1.71\t-1.78 D23\tSession04\tMERCK\t-35.935604\t-2.092229\t-39.632228 D24\tSession04\tETH-4\t-6.215430\t-5.166894\t-11.939419 D25\tSession04\tETH-2\t-6.068214\t-4.868420\t-11.716099\t-10.17\t-18.69 D26\tSession04\tMERCK\t-35.918898\t-2.041585\t-39.566777 D27\tSession04\tETH-1\t5.786924\t11.584138\t16.861248\t2.02\t-2.19 D28\tSession04\tETH-2\t-6.062115\t-4.820423\t-11.664703\t-10.17\t-18.69 D29\tSession04\tETH-4\t-6.210819\t-5.160997\t-11.943417 D30\tSession04\tIAEA-C2\t-3.842542\t4.937635\t0.603831 D31\tSession04\tETH-3\t5.527648\t11.985083\t17.353603\t1.71\t-1.78 D32\tSession04\tIAEA-C1\t6.221429\t11.481788\t17.284825 D33\tSession04\tMERCK\t-35.922066\t-2.113682\t-39.642962 D34\tSession04\tETH-3\t5.521955\t11.989323\t17.345179\t1.71\t-1.78 D35\tSession04\tIAEA-C2\t-3.838229\t4.937180\t0.617586 D36\tSession04\tETH-4\t-6.215638\t-5.221584\t-11.999819 D37\tSession04\tETH-2\t-6.067508\t-4.893477\t-11.754488\t-10.17\t-18.69 D38\tSession04\tIAEA-C1\t6.214580\t11.440629\t17.254051''' app = Flask(__name__) Markdown(app, extensions = [ 'markdown.extensions.tables', # 'pymdownx.magiclink', # 'pymdownx.betterem', 'pymdownx.highlight', 'pymdownx.tilde', 'pymdownx.caret', # 'pymdownx.emoji', # 'pymdownx.tasklist', 'pymdownx.superfences' ]) default_payload = { 'display_results': False, 'error_msg': '', 'rawdata_input_str': rawdata_input_str, 'o17_R13_VPDB': 0.01118, 'o17_R18_VSMOW': 0.0020052, 'o17_R17_VSMOW': 0.00038475, 'o17_lambda': 0.528, 'd13C_stdz_setting': 'd13C_stdz_setting_2pt', 'd18O_stdz_setting': 'd18O_stdz_setting_2pt', 'wg_setting': 'wg_setting_fromsamples', # 'wg_setting_fromsample_samplename': 'ETH-3', # 'wg_setting_fromsample_d13C': 1.71, # 'wg_setting_fromsample_d18O': -1.78, 'acidfrac_setting': 1.008129, 'rf_input_str': '0.258\tETH-1\n0.256\tETH-2\n0.691\tETH-3', 'stdz_method_setting': 'stdz_method_setting_pooled', } def start(): payload = default_payload.copy() # payload['token'] = datetime.now().strftime('%y%m%d') + ''.join(choices(ascii_lowercase, k=5)) return render_template('main.html', payload = payload, vD47crunch = vD47crunch) def proceed(): payload = dict(request.form) data = D47data() if payload['d13C_stdz_setting'] == 'd13C_stdz_setting_2pt': data.d13C_STANDARDIZATION_METHOD = '2pt' elif payload['d13C_stdz_setting'] == 'd13C_stdz_setting_1pt': data.d13C_STANDARDIZATION_METHOD = '1pt' elif payload['d13C_stdz_setting'] == 'd13C_stdz_setting_none': data.d13C_STANDARDIZATION_METHOD = 'none' if payload['d18O_stdz_setting'] == 'd18O_stdz_setting_2pt': data.d18O_STANDARDIZATION_METHOD = '2pt' elif payload['d18O_stdz_setting'] == 'd18O_stdz_setting_1pt': data.d18O_STANDARDIZATION_METHOD = '1pt' elif payload['d18O_stdz_setting'] == 'd18O_stdz_setting_none': data.d18O_STANDARDIZATION_METHOD = 'none' anchors = [l.split('\t') for l in payload['rf_input_str'].splitlines() if '\t' in l] data.Nominal_D47 = {l[1]: float(l[0]) for l in anchors} try: data.R13_VPDB = float(payload['o17_R13_VPDB']) except: payload['error_msg'] = 'Check the value of R13_VPDB in oxygen-17 correction settings.' return render_template('main.html', payload = payload, vD47crunch = vD47crunch) try: data.R18_VSMOW = float(payload['o17_R18_VSMOW']) except: payload['error_msg'] = 'Check the value of R18_VSMOW in oxygen-17 correction settings.' return render_template('main.html', payload = payload, vD47crunch = vD47crunch) try: data.R17_VSMOW = float(payload['o17_R17_VSMOW']) except: payload['error_msg'] = 'Check the value of R17_VSMOW in oxygen-17 correction settings.' return render_template('main.html', payload = payload, vD47crunch = vD47crunch) try: data.lambda_17 = float(payload['o17_lambda']) except: payload['error_msg'] = 'Check the value of in oxygen-17 correction settings.' return render_template('main.html', payload = payload, vD47crunch = vD47crunch) data.input(payload['rawdata_input_str']) # try: # data.input(payload['rawdata_input_str'], '\t') # except: # payload['error_msg'] = 'Raw data input failed for some reason.' # return render_template('main.html', payload = payload, vD47crunch = vD47crunch) for r in data: for k in ['UID', 'Sample', 'Session', 'd45', 'd46', 'd47']: if k not in r or r[k] == '': payload['error_msg'] = f'Analysis "{r["UID"]}" is missing field "{k}".' return render_template('main.html', payload = payload, vD47crunch = vD47crunch) for k in ['d45', 'd46', 'd47']: if not isinstance(r[k], (int, float)): payload['error_msg'] = f'Analysis "{r["UID"]}" should have a valid number for field "{k}".' return render_template('main.html', payload = payload, vD47crunch = vD47crunch) if payload['wg_setting'] == 'wg_setting_fromsamples': # if payload['wg_setting_fromsample_samplename'] == '': # payload['error_msg'] = 'Empty sample name in WG settings.' # return render_template('main.html', payload = payload, vD47crunch = vD47crunch) # # wg_setting_fromsample_samplename = payload['wg_setting_fromsample_samplename'] # # for s in data.sessions: # if wg_setting_fromsample_samplename not in [r['Sample'] for r in data.sessions[s]['data']]: # payload['error_msg'] = f'Sample name from WG settings ("{wg_setting_fromsample_samplename}") not found in session "{s}".' # return render_template('main.html', payload = payload, vD47crunch = vD47crunch) # # try: # wg_setting_fromsample_d13C = float(payload['wg_setting_fromsample_d13C']) # except: # payload['error_msg'] = 'Check the 13C value in WG settings.' # return render_template('main.html', payload = payload, vD47crunch = vD47crunch) # # try: # wg_setting_fromsample_d18O = float(payload['wg_setting_fromsample_d18O']) # except: # payload['error_msg'] = 'Check the 18O value in WG settings.' # return render_template('main.html', payload = payload, vD47crunch = vD47crunch) try: acidfrac = float(payload['acidfrac_setting']) except: payload['error_msg'] = 'Check the acid fractionation value.' return render_template('main.html', payload = payload, vD47crunch = vD47crunch) if acidfrac == 0: payload['error_msg'] = 'Acid fractionation value should be greater than zero.' return render_template('main.html', payload = payload, vD47crunch = vD47crunch) if payload['wg_setting'] == 'wg_setting_fromsamples': data.Nominal_d13C_VPDB = {} data.Nominal_d18O_VPDB = {} for r in data: if 'Nominal_d13C_VPDB' in r: if r['Sample'] in data.Nominal_d13C_VPDB: if data.Nominal_d13C_VPDB[r['Sample']] != r['Nominal_d13C_VPDB']: payload['error_msg'] = f"Inconsistent <span class='field'>Nominal_d13C_VPDB</span> value for {r['Sample']} (analysis: {r['UID']})." return render_template('main.html', payload = payload, vD47crunch = vD47crunch) else: data.Nominal_d13C_VPDB[r['Sample']] = r['Nominal_d13C_VPDB'] if 'Nominal_d18O_VPDB' in r: if r['Sample'] in data.Nominal_d18O_VPDB: if data.Nominal_d18O_VPDB[r['Sample']] != r['Nominal_d18O_VPDB']: payload['error_msg'] = f"Inconsistent <span class='field'>Nominal_d18O_VPDB</span> value for {r['Sample']} (analysis {r['UID']})." return render_template('main.html', payload = payload, vD47crunch = vD47crunch) else: data.Nominal_d18O_VPDB[r['Sample']] = r['Nominal_d18O_VPDB'] try: data.wg(a18_acid = acidfrac) except: payload['error_msg'] = 'WG computation failed for some reason.' return render_template('main.html', payload = payload, vD47crunch = vD47crunch) if payload['wg_setting'] == 'wg_setting_explicit': for r in data: for k in ['d13Cwg_VPDB', 'd18Owg_VSMOW']: if k not in r: payload['error_msg'] = f'Analysis "{r["UID"]}" is missing field "{k}".' return render_template('main.html', payload = payload, vD47crunch = vD47crunch) try: data.crunch() except: payload['error_msg'] = 'Crunching step failed for some reason.' return render_template('main.html', payload = payload, vD47crunch = vD47crunch) method = { 'stdz_method_setting_pooled': 'pooled', 'stdz_method_setting_indep_sessions': 'indep_sessions', }[payload['stdz_method_setting']] data.standardize( consolidate_tables = False, consolidate_plots = False, method = method) csv = 'Session,a,b,c,va,vb,vc,covab,covac,covbc,Xa,Ya,Xu,Yu' for session in data.sessions: s = data.sessions[session] Ga = [r for r in s['data'] if r['Sample'] in data.anchors] Gu = [r for r in s['data'] if r['Sample'] in data.unknowns] csv += f"\n{session},{s['a']},{s['b']},{s['c']},{s['CM'][0,0]},{s['CM'][1,1]},{s['CM'][2,2]},{s['CM'][0,1]},{s['CM'][0,2]},{s['CM'][1,2]},{';'.join([str(r['d47']) for r in Ga])},{';'.join([str(r['D47']) for r in Ga])},{';'.join([str(r['d47']) for r in Gu])},{';'.join([str(r['D47']) for r in Gu])}" # payload['error_msg'] = 'Foo bar.' # return str(payload).replace(', ','\n') payload['display_results'] = True payload['csv_of_sessions'] = csv summary = data.summary(save_to_file = False, print_out = False) tosessions = data.table_of_sessions(save_to_file = False, print_out = False) payload['summary'] = pretty_table(summary, header = 0) payload['summary_rows'] = len(payload['summary'].splitlines())+2 payload['summary_cols'] = len(payload['summary'].splitlines()[0]) payload['table_of_sessions'] = pretty_table(tosessions) payload['table_of_sessions_rows'] = len(payload['table_of_sessions'].splitlines())+1 payload['table_of_sessions_cols'] = len(payload['table_of_sessions'].splitlines()[0]) payload['table_of_sessions_csv'] = make_csv(tosessions) tosamples = data.table_of_samples(save_to_file = False, print_out = False) payload['table_of_samples'] = pretty_table(tosamples) payload['table_of_samples'] = payload['table_of_samples'][:] + 'NB: d18O_VSMOW is the composition of the analyzed CO2.' payload['table_of_samples_rows'] = len(payload['table_of_samples'].splitlines()) payload['table_of_samples_cols'] = len(payload['table_of_samples'].splitlines()[0])+1 payload['table_of_samples_csv'] = make_csv(tosamples) toanalyses = data.table_of_analyses(save_to_file = False, print_out = False) payload['table_of_analyses'] = pretty_table(toanalyses) payload['table_of_analyses_rows'] = len(payload['table_of_analyses'].splitlines())+1 payload['table_of_analyses_cols'] = len(payload['table_of_analyses'].splitlines()[0]) payload['table_of_analyses_csv'] = make_csv(toanalyses) covars = "\n\nCOVARIANCE BETWEEN SAMPLE 47 VALUES:\n\n" txt = [['Sample #1', 'Sample #2', 'Covariance', 'Correlation']] unknowns = [k for k in data.unknowns] for k, s1 in enumerate(unknowns): for s2 in unknowns[k+1:]: txt += [[ s1, s2, f"{data.sample_D47_covar(s1,s2):.4e}", f"{data.sample_D47_covar(s1,s2)/data.samples[s1]['SE_D47']/data.samples[s2]['SE_D47']:.6f}", ]] covars += pretty_table(txt, align = '<<>>') payload['report'] = f"Report generated on {time.asctime()}\nClumpyCrunch v{__version__} using D47crunch v{vD47crunch}" payload['report'] += "\n\nOXYGEN-17 CORRECTION PARAMETERS:\n" + pretty_table([['R13_VPDB', 'R18_VSMOW', 'R17_VSMOW', 'lambda_17'], [payload['o17_R13_VPDB'], payload['o17_R18_VSMOW'], payload['o17_R17_VSMOW'], payload['o17_lambda']]], align = '<<<<') if payload['wg_setting'] == 'wg_setting_fromsample': payload['report'] += f"\n\nWG compositions constrained by sample {wg_setting_fromsample_samplename} with:" payload['report'] += f"\n 13C_VPDB = {wg_setting_fromsample_d13C}" payload['report'] += f"\n 18O_VPDB = {wg_setting_fromsample_d18O}" payload['report'] += f"\n(18O/16O) AFF = {wg_setting_fromsample_acidfrac}\n" elif payload['wg_setting'] == 'wg_setting_explicit': payload['report'] += f"\n\nWG compositions specified by user.\n" payload['report'] += f"\n\nSUMMARY:\n{payload['summary']}" payload['report'] += f"\n\nSAMPLES:\n{payload['table_of_samples']}\n" payload['report'] += f"\n\nSESSIONS:\n{payload['table_of_sessions']}" payload['report'] += f"\n\nANALYSES:\n{payload['table_of_analyses']}" payload['report'] += covars txt = payload['csv_of_sessions'] txt = [[x.strip() for x in l.split(',')] for l in txt.splitlines() if l.strip()] sessions = [{k: smart_type(v) for k,v in zip(txt[0], l)} for l in txt[1:]] payload['plots'] = [] for s in sessions: s['Xa'] = [float(x) for x in s['Xa'].split(';')] s['Ya'] = [float(x) for x in s['Ya'].split(';')] s['Xu'] = [float(x) for x in s['Xu'].split(';')] s['Yu'] = [float(x) for x in s['Yu'].split(';')] for s in sessions: fig = figure(figsize = (3,3)) subplots_adjust(.2,.15,.95,.9) plot_session(s) pngImage = io.BytesIO() FigureCanvas(fig).print_png(pngImage) pngImageB64String = "data:image/png;base64," pngImageB64String += base64.b64encode(pngImage.getvalue()).decode('utf8') payload['plots'] += [pngImageB64String] close(fig) return(render_template('main.html', payload = payload, vD47crunch = vD47crunch)) # @app.route("/csv/<foo>/<filename>", methods = ['POST']) # def get_file(foo, filename): # payload = dict(request.form) # return Response( # payload[foo], # mimetype='text/plain', # headers={'Content-Disposition': f'attachment;filename="{filename}"'} # )
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 2, 422, 4818, 8079, 1330, 4818, 8079, 198, 2, 422, 4738, 1330, 7747, 198, 2, 422, 4731, 1330, 355, 979, 72, 62, 21037, 7442, 198, 6738, 42903, 1330, 46947, 11, 2581, 11,...
1.926733
12,666
r"""Train a neural network to predict feedback for a program string.""" from __future__ import division from __future__ import print_function from __future__ import absolute_import import os import sys import random import numpy as np from tqdm import tqdm import torch import torch.optim as optim import torch.utils.data as data import torch.nn.functional as F from .models import ProgramRNN from .utils import AverageMeter, save_checkpoint, merge_args_with_dict from .datasets import load_dataset from .config import default_hyperparams from .rubric_utils.load_params import get_label_params, get_max_seq_len if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument('dataset', type=str, help='annotated|synthetic') parser.add_argument('problem_id', type=int, help='1|2|3|4|5|6|7|8') parser.add_argument('out_dir', type=str, help='where to save outputs') parser.add_argument('--cuda', action='store_true', default=False, help='enables CUDA training [default: False]') args = parser.parse_args() args.cuda = args.cuda and torch.cuda.is_available() merge_args_with_dict(args, default_hyperparams) device = torch.device('cuda' if args.cuda else 'cpu') args.max_seq_len = get_max_seq_len(args.problem_id) label_dim, _, _, _, _ = get_label_params(args.problem_id) # reproducibility torch.manual_seed(args.seed) np.random.seed(args.seed) if not os.path.isdir(args.out_dir): os.makedirs(args.out_dir) train_dataset = load_dataset( args.dataset, args.problem_id, 'train', vocab=None, max_seq_len=args.max_seq_len, min_occ=args.min_occ) val_dataset = load_dataset( args.dataset, args.problem_id, 'val', vocab=train_dataset.vocab, max_seq_len=args.max_seq_len, min_occ=args.min_occ) test_dataset = load_dataset(args.dataset, args.problem_id, 'test', vocab=train_dataset.vocab, max_seq_len=args.max_seq_len, min_occ=args.min_occ) train_loader = data.DataLoader(train_dataset, batch_size=args.batch_size, shuffle=True) val_loader = data.DataLoader(val_dataset, batch_size=args.batch_size, shuffle=False) test_loader = data.DataLoader(test_dataset, batch_size=args.batch_size, shuffle=False) model = ProgramRNN( args.z_dim, label_dim, train_dataset.vocab_size, embedding_dim=args.embedding_dim, hidden_dim=args.hidden_dim, num_layers=args.num_layers) model = model.to(device) optimizer = optim.Adam(model.parameters(), lr=args.lr) best_loss = sys.maxint track_train_loss = np.zeros(args.epochs) track_val_loss = np.zeros(args.epochs) track_test_loss = np.zeros(args.epochs) track_train_acc = np.zeros(args.epochs) track_val_acc = np.zeros(args.epochs) track_test_acc = np.zeros(args.epochs) for epoch in xrange(1, args.epochs + 1): train_loss, train_acc = train(epoch) val_loss, val_acc = test(epoch, val_loader, name='Val') test_loss, test_acc = test(epoch, test_loader, name='Test') track_train_loss[epoch - 1] = train_loss track_val_loss[epoch - 1] = val_loss track_test_loss[epoch - 1] = test_loss track_train_acc[epoch - 1] = train_acc track_val_acc[epoch - 1] = val_acc track_test_acc[epoch - 1] = test_acc is_best = val_loss < best_loss best_loss = min(val_loss, best_loss) save_checkpoint({ 'state_dict': model.state_dict(), 'cmd_line_args': args, 'vocab': train_dataset.vocab, }, is_best, folder=args.out_dir) np.save(os.path.join(args.out_dir, 'train_loss.npy'), track_train_loss) np.save(os.path.join(args.out_dir, 'val_loss.npy'), track_val_loss) np.save(os.path.join(args.out_dir, 'test_loss.npy'), track_test_loss) np.save(os.path.join(args.out_dir, 'train_acc.npy'), track_train_acc) np.save(os.path.join(args.out_dir, 'val_acc.npy'), track_val_acc) np.save(os.path.join(args.out_dir, 'test_acc.npy'), track_test_acc)
[ 81, 37811, 44077, 257, 17019, 3127, 284, 4331, 7538, 329, 257, 1430, 4731, 526, 15931, 198, 198, 6738, 11593, 37443, 834, 1330, 7297, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 1174...
2.261222
1,849
# -------------- # Code starts here class_1 = ['Geoffrey Hinton' , 'Andrew Ng' , 'Sebastian Raschka' , 'Yoshua Bengio'] class_2 = ['Hilary Mason' , 'Carla Gentry' , 'Corinna Cortes'] new_class = class_1 + class_2 print(new_class) new_class.append('Peter Warden') print(new_class) del new_class[5] print(new_class) # Code ends here # -------------- # Code starts here courses = {'Math': 65 , 'English': 70 , 'History': 80 , 'French': 70 , 'Science': 60} total = sum(courses.values()) print(total) percentage = total/500*100 print(percentage) # Code ends here # -------------- # Code starts here mathematics = { 'Geoffrey Hinton' : 78, 'Andrew Ng' : 95, 'Sebastian Raschka' : 65 , 'Yoshua Benjio' : 50 , 'Hilary Mason' : 70 , 'Corinna Cortes' : 66 , 'Peter Warden' : 75} max_marks_scored = max(mathematics, key=mathematics.get) print(max_marks_scored) topper = max_marks_scored print(topper) # Code ends here # -------------- # Given string topper = ' andrew ng' # Code starts here first_name = topper.split()[0] print(first_name) last_name = topper.split()[1] print(last_name) full_name = last_name +' '+ first_name print(full_name) certificate_name = full_name.upper() print(certificate_name) # Code ends here
[ 2, 220, 26171, 198, 2, 6127, 4940, 994, 198, 4871, 62, 16, 796, 37250, 10082, 2364, 4364, 367, 2371, 6, 837, 705, 20508, 34786, 6, 837, 705, 50, 1765, 459, 666, 28513, 354, 4914, 6, 837, 705, 56, 3768, 6413, 14964, 952, 20520, 198...
2.678261
460
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' NAME: checklog.py DESCRIPTION: This script checks the tail of the log file and lists the disk space CREATED: Sun Mar 15 22:53:54 2015 VERSION: 1.0 AUTHOR: Mark Tibbett AUTHOR_EMAIL: mtibbett67@gmail.com URL: N/A DOWNLOAD_URL: N/A INSTALL_REQUIRES: [] PACKAGES: [] SCRIPTS: [] ''' # Standard library imports import os import sys import subprocess # Related third party imports # Local application/library specific imports # Console colors W = '\033[0m' # white (normal) R = '\033[31m' # red G = '\033[32m' # green O = '\033[33m' # orange B = '\033[34m' # blue P = '\033[35m' # purple C = '\033[36m' # cyan GR = '\033[37m' # gray # Section formats SEPARATOR = B + '=' * 80 + W NL = '\n' # Clear the terminal os.system('clear') # Check for root or sudo. Remove if not needed. UID = os.getuid() if UID != 0: print R + ' [!]' + O + ' ERROR:' + G + ' sysupdate' + O + \ ' must be run as ' + R + 'root' + W # print R + ' [!]' + O + ' login as root (' + W + 'su root' + O + ') \ # or try ' + W + 'sudo ./wifite.py' + W os.execvp('sudo', ['sudo'] + sys.argv) else: print NL print G + 'You are running this script as ' + R + 'root' + W print NL + SEPARATOR + NL LOG = ['tail', '/var/log/messages'] DISK = ['df', '-h'] def check(arg1, arg2): '''Call subprocess to check logs''' print G + arg1 + W + NL item = subprocess.check_output(arg2) #subprocess.call(arg2) print item + NL + SEPARATOR + NL check('Runing tail on messages', LOG) check('Disk usage', DISK)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 7061, 6, 198, 20608, 25, 198, 9122, 6404, 13, 9078, 198, 198, 30910, 40165, 25, 198, 1212, 4226, 8794, 262, 7894...
2.327143
700
n = int(input().strip()) items = [ int(A_temp) for A_temp in input().strip().split(' ') ] items_map = {} result = None for i, item in enumerate(items): if item not in items_map: items_map[item] = [i] else: items_map[item].append(i) for _, item_indexes in items_map.items(): items_indexes_length = len(item_indexes) if items_indexes_length > 1: for i in range(items_indexes_length): for j in range(i + 1, items_indexes_length): diff = item_indexes[j] - item_indexes[i] if result is None: result = diff elif diff < result: result = diff print(result if result else -1)
[ 77, 796, 493, 7, 15414, 22446, 36311, 28955, 198, 198, 23814, 796, 685, 198, 220, 220, 220, 493, 7, 32, 62, 29510, 8, 198, 220, 220, 220, 329, 317, 62, 29510, 198, 220, 220, 220, 287, 5128, 22446, 36311, 22446, 35312, 10786, 705, ...
2.056657
353
""" Sparse Poisson Recovery (SPoRe) module for solving Multiple Measurement Vector problem with Poisson signals (MMVP) by batch stochastic gradient ascent and Monte Carlo integration Authors: Pavan Kota, Daniel LeJeune Reference: [1] P. K. Kota, D. LeJeune, R. A. Drezek, and R. G. Baraniuk, "Extreme Compressed Sensing of Poisson Rates from Multiple Measurements," Mar. 2021. arXiv ID: """ from abc import ABC, abstractmethod import numpy as np import time import pdb from .mmv_models import FwdModelGroup, SPoReFwdModelGroup
[ 37811, 198, 50, 29572, 7695, 30927, 21007, 357, 4303, 78, 3041, 8, 8265, 329, 18120, 20401, 24291, 434, 20650, 220, 198, 45573, 351, 7695, 30927, 10425, 357, 12038, 8859, 8, 416, 15458, 3995, 354, 3477, 31312, 37137, 290, 220, 198, 9069...
3.005495
182
"""Use translation table to translate coding sequence to protein.""" from Bio.Data import CodonTable # type: ignore from Bio.Seq import Seq # type: ignore def translate_cds(cds: str, translation_table: str) -> str: """Translate coding sequence to protein. :param cds: str: DNA coding sequence (CDS) :param translation_table: str: translation table as defined in Bio.Seq.Seq.CodonTable.ambiguous_generic_by_name :return: str: Protein sequence """ table = CodonTable.ambiguous_dna_by_name[translation_table] cds = "".join(cds.split()) # clean out whitespace coding_dna = Seq(cds) protein = coding_dna.translate(table, cds=True, to_stop=True) return str(protein)
[ 37811, 11041, 11059, 3084, 284, 15772, 19617, 8379, 284, 7532, 526, 15931, 201, 198, 201, 198, 6738, 16024, 13, 6601, 1330, 18720, 261, 10962, 220, 1303, 2099, 25, 8856, 201, 198, 6738, 16024, 13, 4653, 80, 1330, 1001, 80, 220, 1303, ...
2.688645
273
from pycodimd import CodiMD cmd = CodiMD('https://md.noemis.me') #cmd.login('user@example.com','CorrectHorseBatteryStaple') cmd.load_cookies() print(cmd.history()[-1]['text']) # Print Name of latest Note
[ 6738, 12972, 19815, 320, 67, 1330, 18720, 72, 12740, 198, 198, 28758, 796, 18720, 72, 12740, 10786, 5450, 1378, 9132, 13, 3919, 30561, 13, 1326, 11537, 198, 2, 28758, 13, 38235, 10786, 7220, 31, 20688, 13, 785, 41707, 42779, 39, 7615, ...
2.710526
76
import os print('echoenv...', end=' ') print('Hello,', os.environ['USER'])
[ 11748, 28686, 198, 4798, 10786, 3055, 6571, 85, 986, 3256, 886, 11639, 705, 8, 198, 4798, 10786, 15496, 11, 3256, 28686, 13, 268, 2268, 17816, 29904, 6, 12962, 198 ]
2.586207
29
""" Display command results. """ from __future__ import unicode_literals from contextlib import contextmanager from argparse import Namespace from io import BytesIO from colorama import AnsiToWin32 from chromalog.stream import stream_has_color_support from chromalog.colorizer import Colorizer from chromalog.mark.helpers.simple import ( warning, important, success, error, )
[ 37811, 198, 23114, 3141, 2482, 13, 198, 37811, 198, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 6738, 4732, 8019, 1330, 4732, 37153, 198, 6738, 1822, 29572, 1330, 28531, 10223, 198, 6738, 33245, 1330, 2750, ...
3.344538
119
### # Copyright (c) 2020-2021, The Limnoria Contributors # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions, and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions, and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the author of this software nor the name of # contributors to this software may be used to endorse or promote products # derived from this software without specific prior written consent. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. ### from supybot import conf, ircutils, ircmsgs, callbacks from supybot.i18n import PluginInternationalization _ = PluginInternationalization("Autocomplete") REQUEST_TAG = "+draft/autocomplete-request" RESPONSE_TAG = "+draft/autocomplete-response" def _commonPrefix(L): """Takes a list of lists, and returns their longest common prefix.""" assert L if len(L) == 1: return L[0] for n in range(1, max(map(len, L)) + 1): prefix = L[0][:n] for item in L[1:]: if prefix != item[:n]: return prefix[0:-1] assert False def _getAutocompleteResponse(irc, msg, payload): """Returns the value of the +draft/autocomplete-response tag for the given +draft/autocomplete-request payload.""" tokens = callbacks.tokenize( payload, channel=msg.channel, network=irc.network ) normalized_payload = " ".join(tokens) candidate_commands = _getCandidates(irc, normalized_payload) if len(candidate_commands) == 0: # No result return None elif len(candidate_commands) == 1: # One result, return it directly commands = candidate_commands else: # Multiple results, return only the longest common prefix + one word tokenized_candidates = [ callbacks.tokenize(c, channel=msg.channel, network=irc.network) for c in candidate_commands ] common_prefix = _commonPrefix(tokenized_candidates) words_after_prefix = { candidate[len(common_prefix)] for candidate in tokenized_candidates } commands = [ " ".join(common_prefix + [word]) for word in words_after_prefix ] # strip what the user already typed assert all(command.startswith(normalized_payload) for command in commands) normalized_payload_length = len(normalized_payload) response_items = [ command[normalized_payload_length:] for command in commands ] return "\t".join(sorted(response_items)) def _getCandidates(irc, normalized_payload): """Returns a list of commands starting with the normalized_payload.""" candidates = set() for cb in irc.callbacks: cb_commands = cb.listCommands() # copy them with the plugin name (optional when calling a command) # at the beginning plugin_name = cb.canonicalName() cb_commands += [plugin_name + " " + command for command in cb_commands] candidates |= { command for command in cb_commands if command.startswith(normalized_payload) } return candidates Class = Autocomplete # vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:
[ 21017, 198, 2, 15069, 357, 66, 8, 12131, 12, 1238, 2481, 11, 383, 7576, 77, 7661, 25767, 669, 198, 2, 1439, 2489, 10395, 13, 198, 2, 198, 2, 2297, 396, 3890, 290, 779, 287, 2723, 290, 13934, 5107, 11, 351, 393, 1231, 198, 2, 176...
2.831911
1,523
""" preprocess-twitter.py python preprocess-twitter.py "Some random text with #hashtags, @mentions and http://t.co/kdjfkdjf (links). :)" Script for preprocessing tweets by Romain Paulus with small modifications by Jeffrey Pennington with translation to Python by Motoki Wu Translation of Ruby script to create features for GloVe vectors for Twitter data. http://nlp.stanford.edu/projects/glove/preprocess-twitter.rb """ import sys import regex as re FLAGS = re.MULTILINE | re.DOTALL if __name__ == '__main__': _, text = sys.argv if text == "test": text = "I TEST alllll kinds of #hashtags and #HASHTAGS, @mentions and 3000 (http://t.co/dkfjkdf). w/ <3 :) haha!!!!!" tokens = tokenize(text) print(tokens)
[ 37811, 198, 3866, 14681, 12, 6956, 13, 9078, 198, 29412, 662, 14681, 12, 6956, 13, 9078, 366, 4366, 4738, 2420, 351, 1303, 17831, 31499, 11, 2488, 434, 507, 290, 2638, 1378, 83, 13, 1073, 14, 74, 28241, 69, 74, 28241, 69, 357, 28751...
2.897233
253
#! /usr/bin/env python # -*- coding:utf8 -*- # # pw_classes.py # # This file is part of pyplanes, a software distributed under the MIT license. # For any question, please contact one of the authors cited below. # # Copyright (c) 2020 # Olivier Dazel <olivier.dazel@univ-lemans.fr> # Mathieu Gaborit <gaborit@kth.se> # Peter Gransson <pege@kth.se> # # 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. # import numpy as np import numpy.linalg as LA import matplotlib.pyplot as plt from mediapack import from_yaml from mediapack import Air, PEM, EqFluidJCA from pyPLANES.utils.io import initialisation_out_files_plain from pyPLANES.core.calculus import PwCalculus from pyPLANES.core.multilayer import MultiLayer from pyPLANES.pw.pw_layers import FluidLayer from pyPLANES.pw.pw_interfaces import FluidFluidInterface, RigidBacking Air = Air() # def initialise_PW_solver(L, b): # nb_PW = 0 # dofs = [] # for _layer in L: # if _layer.medium.MODEL == "fluid": # dofs.append(nb_PW+np.arange(2)) # nb_PW += 2 # elif _layer.medium.MODEL == "pem": # dofs.append(nb_PW+np.arange(6)) # nb_PW += 6 # elif _layer.medium.MODEL == "elastic": # dofs.append(nb_PW+np.arange(4)) # nb_PW += 4 # interface = [] # for i_l, _layer in enumerate(L[:-1]): # interface.append((L[i_l].medium.MODEL, L[i_l+1].medium.MODEL)) # return nb_PW, interface, dofs # class Solver_PW(PwCalculus): # def __init__(self, **kwargs): # PwCalculus.__init__(self, **kwargs) # ml = kwargs.get("ml") # termination = kwargs.get("termination") # self.layers = [] # for _l in ml: # if _l[0] == "Air": # mat = Air # else: # mat = from_yaml(_l[0]+".yaml") # d = _l[1] # self.layers.append(Layer(mat,d)) # if termination in ["trans", "transmission","Transmission"]: # self.backing = "Transmission" # else: # self.backing = backing.rigid # self.kx, self.ky, self.k = None, None, None # self.shift_plot = kwargs.get("shift_pw", 0.) # self.plot = kwargs.get("plot_results", [False]*6) # self.result = {} # self.outfiles_directory = False # initialisation_out_files_plain(self) # def write_out_files(self, out): # self.out_file.write("{:.12e}\t".format(self.current_frequency)) # abs = 1-np.abs(out["R"])**2 # self.out_file.write("{:.12e}\t".format(abs)) # self.out_file.write("\n") # def interface_fluid_fluid(self, ieq, iinter, L, d, M): # SV_1, k_y_1 = fluid_SV(self.kx, self.k, L[iinter].medium.K) # SV_2, k_y_2 = fluid_SV(self.kx, self.k, L[iinter+1].medium.K) # M[ieq, d[iinter+0][0]] = SV_1[0, 0]*np.exp(-1j*k_y_1*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = SV_1[0, 1] # M[ieq, d[iinter+1][0]] = -SV_2[0, 0] # M[ieq, d[iinter+1][1]] = -SV_2[0, 1]*np.exp(-1j*k_y_2*L[iinter+1].thickness) # ieq += 1 # M[ieq, d[iinter+0][0]] = SV_1[1, 0]*np.exp(-1j*k_y_1*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = SV_1[1, 1] # M[ieq, d[iinter+1][0]] = -SV_2[1, 0] # M[ieq, d[iinter+1][1]] = -SV_2[1, 1]*np.exp(-1j*k_y_2*L[iinter+1].thickness) # ieq += 1 # return ieq # def interface_fluid_rigid(self, M, ieq, L, d): # SV, k_y = fluid_SV(self.kx, self.k, L.medium.K) # M[ieq, d[0]] = SV[0, 0]*np.exp(-1j*k_y*L.thickness) # M[ieq, d[1]] = SV[0, 1] # ieq += 1 # return ieq # def semi_infinite_medium(self, M, ieq, L, d): # M[ieq, d[1]] = 1. # ieq += 1 # return ieq # def interface_pem_pem(self, ieq, iinter, L, d, M): # SV_1, k_y_1 = PEM_SV(L[iinter].medium, self.kx) # SV_2, k_y_2 = PEM_SV(L[iinter+1].medium, self.kx) # for _i in range(6): # M[ieq, d[iinter+0][0]] = SV_1[_i, 0]*np.exp(-1j*k_y_1[0]*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = SV_1[_i, 1]*np.exp(-1j*k_y_1[1]*L[iinter].thickness) # M[ieq, d[iinter+0][2]] = SV_1[_i, 2]*np.exp(-1j*k_y_1[2]*L[iinter].thickness) # M[ieq, d[iinter+0][3]] = SV_1[_i, 3] # M[ieq, d[iinter+0][4]] = SV_1[_i, 4] # M[ieq, d[iinter+0][5]] = SV_1[_i, 5] # M[ieq, d[iinter+1][0]] = -SV_2[_i, 0] # M[ieq, d[iinter+1][1]] = -SV_2[_i, 1] # M[ieq, d[iinter+1][2]] = -SV_2[_i, 2] # M[ieq, d[iinter+1][3]] = -SV_2[_i, 3]*np.exp(-1j*k_y_2[0]*L[iinter+1].thickness) # M[ieq, d[iinter+1][4]] = -SV_2[_i, 4]*np.exp(-1j*k_y_2[1]*L[iinter+1].thickness) # M[ieq, d[iinter+1][5]] = -SV_2[_i, 5]*np.exp(-1j*k_y_2[2]*L[iinter+1].thickness) # ieq += 1 # return ieq # def interface_fluid_pem(self, ieq, iinter, L, d, M): # SV_1, k_y_1 = fluid_SV(self.kx, self.k, L[iinter].medium.K) # SV_2, k_y_2 = PEM_SV(L[iinter+1].medium,self.kx) # # print(k_y_2) # M[ieq, d[iinter+0][0]] = SV_1[0, 0]*np.exp(-1j*k_y_1*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = SV_1[0, 1] # M[ieq, d[iinter+1][0]] = -SV_2[2, 0] # M[ieq, d[iinter+1][1]] = -SV_2[2, 1] # M[ieq, d[iinter+1][2]] = -SV_2[2, 2] # M[ieq, d[iinter+1][3]] = -SV_2[2, 3]*np.exp(-1j*k_y_2[0]*L[iinter+1].thickness) # M[ieq, d[iinter+1][4]] = -SV_2[2, 4]*np.exp(-1j*k_y_2[1]*L[iinter+1].thickness) # M[ieq, d[iinter+1][5]] = -SV_2[2, 5]*np.exp(-1j*k_y_2[2]*L[iinter+1].thickness) # ieq += 1 # M[ieq, d[iinter+0][0]] = SV_1[1, 0]*np.exp(-1j*k_y_1*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = SV_1[1, 1] # M[ieq, d[iinter+1][0]] = -SV_2[4, 0] # M[ieq, d[iinter+1][1]] = -SV_2[4, 1] # M[ieq, d[iinter+1][2]] = -SV_2[4, 2] # M[ieq, d[iinter+1][3]] = -SV_2[4, 3]*np.exp(-1j*k_y_2[0]*L[iinter+1].thickness) # M[ieq, d[iinter+1][4]] = -SV_2[4, 4]*np.exp(-1j*k_y_2[1]*L[iinter+1].thickness) # M[ieq, d[iinter+1][5]] = -SV_2[4, 5]*np.exp(-1j*k_y_2[2]*L[iinter+1].thickness) # ieq += 1 # M[ieq, d[iinter+1][0]] = SV_2[0, 0] # M[ieq, d[iinter+1][1]] = SV_2[0, 1] # M[ieq, d[iinter+1][2]] = SV_2[0, 2] # M[ieq, d[iinter+1][3]] = SV_2[0, 3]*np.exp(-1j*k_y_2[0]*L[iinter+1].thickness) # M[ieq, d[iinter+1][4]] = SV_2[0, 4]*np.exp(-1j*k_y_2[1]*L[iinter+1].thickness) # M[ieq, d[iinter+1][5]] = SV_2[0, 5]*np.exp(-1j*k_y_2[2]*L[iinter+1].thickness) # ieq += 1 # M[ieq, d[iinter+1][0]] = SV_2[3, 0] # M[ieq, d[iinter+1][1]] = SV_2[3, 1] # M[ieq, d[iinter+1][2]] = SV_2[3, 2] # M[ieq, d[iinter+1][3]] = SV_2[3, 3]*np.exp(-1j*k_y_2[0]*L[iinter+1].thickness) # M[ieq, d[iinter+1][4]] = SV_2[3, 4]*np.exp(-1j*k_y_2[1]*L[iinter+1].thickness) # M[ieq, d[iinter+1][5]] = SV_2[3, 5]*np.exp(-1j*k_y_2[2]*L[iinter+1].thickness) # ieq += 1 # return ieq # def interface_elastic_pem(self, ieq, iinter, L, d, M): # SV_1, k_y_1 = elastic_SV(L[iinter].medium,self.kx, self.omega) # SV_2, k_y_2 = PEM_SV(L[iinter+1].medium,self.kx) # # print(k_y_2) # M[ieq, d[iinter+0][0]] = -SV_1[0, 0]*np.exp(-1j*k_y_1[0]*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = -SV_1[0, 1]*np.exp(-1j*k_y_1[1]*L[iinter].thickness) # M[ieq, d[iinter+0][2]] = -SV_1[0, 2] # M[ieq, d[iinter+0][3]] = -SV_1[0, 3] # M[ieq, d[iinter+1][0]] = SV_2[0, 0] # M[ieq, d[iinter+1][1]] = SV_2[0, 1] # M[ieq, d[iinter+1][2]] = SV_2[0, 2] # M[ieq, d[iinter+1][3]] = SV_2[0, 3]*np.exp(-1j*k_y_2[0]*L[iinter+1].thickness) # M[ieq, d[iinter+1][4]] = SV_2[0, 4]*np.exp(-1j*k_y_2[1]*L[iinter+1].thickness) # M[ieq, d[iinter+1][5]] = SV_2[0, 5]*np.exp(-1j*k_y_2[2]*L[iinter+1].thickness) # ieq += 1 # M[ieq, d[iinter+0][0]] = -SV_1[1, 0]*np.exp(-1j*k_y_1[0]*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = -SV_1[1, 1]*np.exp(-1j*k_y_1[1]*L[iinter].thickness) # M[ieq, d[iinter+0][2]] = -SV_1[1, 2] # M[ieq, d[iinter+0][3]] = -SV_1[1, 3] # M[ieq, d[iinter+1][0]] = SV_2[1, 0] # M[ieq, d[iinter+1][1]] = SV_2[1, 1] # M[ieq, d[iinter+1][2]] = SV_2[1, 2] # M[ieq, d[iinter+1][3]] = SV_2[1, 3]*np.exp(-1j*k_y_2[0]*L[iinter+1].thickness) # M[ieq, d[iinter+1][4]] = SV_2[1, 4]*np.exp(-1j*k_y_2[1]*L[iinter+1].thickness) # M[ieq, d[iinter+1][5]] = SV_2[1, 5]*np.exp(-1j*k_y_2[2]*L[iinter+1].thickness) # ieq += 1 # M[ieq, d[iinter+0][0]] = -SV_1[1, 0]*np.exp(-1j*k_y_1[0]*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = -SV_1[1, 1]*np.exp(-1j*k_y_1[1]*L[iinter].thickness) # M[ieq, d[iinter+0][2]] = -SV_1[1, 2] # M[ieq, d[iinter+0][3]] = -SV_1[1, 3] # M[ieq, d[iinter+1][0]] = SV_2[2, 0] # M[ieq, d[iinter+1][1]] = SV_2[2, 1] # M[ieq, d[iinter+1][2]] = SV_2[2, 2] # M[ieq, d[iinter+1][3]] = SV_2[2, 3]*np.exp(-1j*k_y_2[0]*L[iinter+1].thickness) # M[ieq, d[iinter+1][4]] = SV_2[2, 4]*np.exp(-1j*k_y_2[1]*L[iinter+1].thickness) # M[ieq, d[iinter+1][5]] = SV_2[2, 5]*np.exp(-1j*k_y_2[2]*L[iinter+1].thickness) # ieq += 1 # M[ieq, d[iinter+0][0]] = -SV_1[2, 0]*np.exp(-1j*k_y_1[0]*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = -SV_1[2, 1]*np.exp(-1j*k_y_1[1]*L[iinter].thickness) # M[ieq, d[iinter+0][2]] = -SV_1[2, 2] # M[ieq, d[iinter+0][3]] = -SV_1[2, 3] # M[ieq, d[iinter+1][0]] = (SV_2[3, 0]-SV_2[4, 0]) # M[ieq, d[iinter+1][1]] = (SV_2[3, 1]-SV_2[4, 1]) # M[ieq, d[iinter+1][2]] = (SV_2[3, 2]-SV_2[4, 2]) # M[ieq, d[iinter+1][3]] = (SV_2[3, 3]-SV_2[4, 3])*np.exp(-1j*k_y_2[0]*L[iinter+1].thickness) # M[ieq, d[iinter+1][4]] = (SV_2[3, 4]-SV_2[4, 4])*np.exp(-1j*k_y_2[1]*L[iinter+1].thickness) # M[ieq, d[iinter+1][5]] = (SV_2[3, 5]-SV_2[4, 5])*np.exp(-1j*k_y_2[2]*L[iinter+1].thickness) # ieq += 1 # M[ieq, d[iinter+0][0]] = -SV_1[3, 0]*np.exp(-1j*k_y_1[0]*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = -SV_1[3, 1]*np.exp(-1j*k_y_1[1]*L[iinter].thickness) # M[ieq, d[iinter+0][2]] = -SV_1[3, 2] # M[ieq, d[iinter+0][3]] = -SV_1[3, 3] # M[ieq, d[iinter+1][0]] = SV_2[5, 0] # M[ieq, d[iinter+1][1]] = SV_2[5, 1] # M[ieq, d[iinter+1][2]] = SV_2[5, 2] # M[ieq, d[iinter+1][3]] = SV_2[5, 3]*np.exp(-1j*k_y_2[0]*L[iinter+1].thickness) # M[ieq, d[iinter+1][4]] = SV_2[5, 4]*np.exp(-1j*k_y_2[1]*L[iinter+1].thickness) # M[ieq, d[iinter+1][5]] = SV_2[5, 5]*np.exp(-1j*k_y_2[2]*L[iinter+1].thickness) # ieq += 1 # return ieq # def interface_pem_elastic(self, ieq, iinter, L, d, M): # SV_1, k_y_1 = PEM_SV(L[iinter].medium,self.kx) # SV_2, k_y_2 = elastic_SV(L[iinter+1].medium,self.kx, self.omega) # # print(k_y_2) # M[ieq, d[iinter+0][0]] = SV_1[0, 0]*np.exp(-1j*k_y_1[0]*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = SV_1[0, 1]*np.exp(-1j*k_y_1[1]*L[iinter].thickness) # M[ieq, d[iinter+0][2]] = SV_1[0, 2]*np.exp(-1j*k_y_1[2]*L[iinter].thickness) # M[ieq, d[iinter+0][3]] = SV_1[0, 3] # M[ieq, d[iinter+0][4]] = SV_1[0, 4] # M[ieq, d[iinter+0][5]] = SV_1[0, 5] # M[ieq, d[iinter+1][0]] = -SV_2[0, 0] # M[ieq, d[iinter+1][1]] = -SV_2[0, 1] # M[ieq, d[iinter+1][2]] = -SV_2[0, 2]*np.exp(-1j*k_y_2[0]*L[iinter+1].thickness) # M[ieq, d[iinter+1][3]] = -SV_2[0, 3]*np.exp(-1j*k_y_2[1]*L[iinter+1].thickness) # ieq += 1 # M[ieq, d[iinter+0][0]] = SV_1[1, 0]*np.exp(-1j*k_y_1[0]*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = SV_1[1, 1]*np.exp(-1j*k_y_1[1]*L[iinter].thickness) # M[ieq, d[iinter+0][2]] = SV_1[1, 2]*np.exp(-1j*k_y_1[2]*L[iinter].thickness) # M[ieq, d[iinter+0][3]] = SV_1[1, 3] # M[ieq, d[iinter+0][4]] = SV_1[1, 4] # M[ieq, d[iinter+0][5]] = SV_1[1, 5] # M[ieq, d[iinter+1][0]] = -SV_2[1, 0] # M[ieq, d[iinter+1][1]] = -SV_2[1, 1] # M[ieq, d[iinter+1][2]] = -SV_2[1, 2]*np.exp(-1j*k_y_2[0]*L[iinter+1].thickness) # M[ieq, d[iinter+1][3]] = -SV_2[1, 3]*np.exp(-1j*k_y_2[1]*L[iinter+1].thickness) # ieq += 1 # M[ieq, d[iinter+0][0]] = SV_1[2, 0]*np.exp(-1j*k_y_1[0]*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = SV_1[2, 1]*np.exp(-1j*k_y_1[1]*L[iinter].thickness) # M[ieq, d[iinter+0][2]] = SV_1[2, 2]*np.exp(-1j*k_y_1[2]*L[iinter].thickness) # M[ieq, d[iinter+0][3]] = SV_1[2, 3] # M[ieq, d[iinter+0][4]] = SV_1[2, 4] # M[ieq, d[iinter+0][5]] = SV_1[2, 5] # M[ieq, d[iinter+1][0]] = -SV_2[1, 0] # M[ieq, d[iinter+1][1]] = -SV_2[1, 1] # M[ieq, d[iinter+1][2]] = -SV_2[1, 2]*np.exp(-1j*k_y_2[0]*L[iinter+1].thickness) # M[ieq, d[iinter+1][3]] = -SV_2[1, 3]*np.exp(-1j*k_y_2[1]*L[iinter+1].thickness) # ieq += 1 # M[ieq, d[iinter+0][0]] = (SV_1[3, 0]-SV_1[4, 0])*np.exp(-1j*k_y_1[0]*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = (SV_1[3, 1]-SV_1[4, 1])*np.exp(-1j*k_y_1[1]*L[iinter].thickness) # M[ieq, d[iinter+0][2]] = (SV_1[3, 2]-SV_1[4, 2])*np.exp(-1j*k_y_1[2]*L[iinter].thickness) # M[ieq, d[iinter+0][3]] = (SV_1[3, 3]-SV_1[4, 3]) # M[ieq, d[iinter+0][4]] = (SV_1[3, 4]-SV_1[4, 4]) # M[ieq, d[iinter+0][5]] = (SV_1[3, 5]-SV_1[4, 5]) # M[ieq, d[iinter+1][0]] = -SV_2[2, 0] # M[ieq, d[iinter+1][1]] = -SV_2[2, 1] # M[ieq, d[iinter+1][2]] = -SV_2[2, 2]*np.exp(-1j*k_y_2[0]*L[iinter+1].thickness) # M[ieq, d[iinter+1][3]] = -SV_2[2, 3]*np.exp(-1j*k_y_2[1]*L[iinter+1].thickness) # ieq += 1 # M[ieq, d[iinter+0][0]] = SV_1[5, 0]*np.exp(-1j*k_y_1[0]*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = SV_1[5, 1]*np.exp(-1j*k_y_1[1]*L[iinter].thickness) # M[ieq, d[iinter+0][2]] = SV_1[5, 2]*np.exp(-1j*k_y_1[2]*L[iinter].thickness) # M[ieq, d[iinter+0][3]] = SV_1[5, 3] # M[ieq, d[iinter+0][4]] = SV_1[5, 4] # M[ieq, d[iinter+0][5]] = SV_1[5, 5] # M[ieq, d[iinter+1][0]] = -SV_2[3, 0] # M[ieq, d[iinter+1][1]] = -SV_2[3, 1] # M[ieq, d[iinter+1][2]] = -SV_2[3, 2]*np.exp(-1j*k_y_2[0]*L[iinter+1].thickness) # M[ieq, d[iinter+1][3]] = -SV_2[3, 3]*np.exp(-1j*k_y_2[1]*L[iinter+1].thickness) # ieq += 1 # return ieq # def interface_elastic_elastic(self, ieq, iinter, L, d, M): # SV_1, k_y_1 = elastic_SV(L[iinter].medium,self.kx, self.omega) # SV_2, k_y_2 = elastic_SV(L[iinter+1].medium,self.kx, self.omega) # for _i in range(4): # M[ieq, d[iinter+0][0]] = SV_1[_i, 0]*np.exp(-1j*k_y_1[0]*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = SV_1[_i, 1]*np.exp(-1j*k_y_1[1]*L[iinter].thickness) # M[ieq, d[iinter+0][2]] = SV_1[_i, 2] # M[ieq, d[iinter+0][3]] = SV_1[_i, 3] # M[ieq, d[iinter+1][0]] = -SV_2[_i, 0] # M[ieq, d[iinter+1][1]] = -SV_2[_i, 1] # M[ieq, d[iinter+1][2]] = -SV_2[_i, 2]*np.exp(-1j*k_y_2[0]*L[iinter+1].thickness) # M[ieq, d[iinter+1][3]] = -SV_2[_i, 3]*np.exp(-1j*k_y_2[1]*L[iinter+1].thickness) # ieq += 1 # return ieq # def interface_fluid_elastic(self, ieq, iinter, L, d, M): # SV_1, k_y_1 = fluid_SV(self.kx, self.k, L[iinter].medium.K) # SV_2, k_y_2 = elastic_SV(L[iinter+1].medium, self.kx, self.omega) # # Continuity of u_y # M[ieq, d[iinter+0][0]] = SV_1[0, 0]*np.exp(-1j*k_y_1*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = SV_1[0, 1] # M[ieq, d[iinter+1][0]] = -SV_2[1, 0] # M[ieq, d[iinter+1][1]] = -SV_2[1, 1] # M[ieq, d[iinter+1][2]] = -SV_2[1, 2]*np.exp(-1j*k_y_2[0]*L[iinter+1].thickness) # M[ieq, d[iinter+1][3]] = -SV_2[1, 3]*np.exp(-1j*k_y_2[1]*L[iinter+1].thickness) # ieq += 1 # # sigma_yy = -p # M[ieq, d[iinter+0][0]] = SV_1[1, 0]*np.exp(-1j*k_y_1*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = SV_1[1, 1] # M[ieq, d[iinter+1][0]] = SV_2[2, 0] # M[ieq, d[iinter+1][1]] = SV_2[2, 1] # M[ieq, d[iinter+1][2]] = SV_2[2, 2]*np.exp(-1j*k_y_2[0]*L[iinter+1].thickness) # M[ieq, d[iinter+1][3]] = SV_2[2, 3]*np.exp(-1j*k_y_2[1]*L[iinter+1].thickness) # ieq += 1 # # sigma_xy = 0 # M[ieq, d[iinter+1][0]] = SV_2[0, 0] # M[ieq, d[iinter+1][1]] = SV_2[0, 1] # M[ieq, d[iinter+1][2]] = SV_2[0, 2]*np.exp(-1j*k_y_2[0]*L[iinter+1].thickness) # M[ieq, d[iinter+1][3]] = SV_2[0, 3]*np.exp(-1j*k_y_2[1]*L[iinter+1].thickness) # ieq += 1 # return ieq # def interface_pem_fluid(self, ieq, iinter, L, d, M): # SV_1, k_y_1 = PEM_SV(L[iinter].medium, self.kx) # SV_2, k_y_2 = fluid_SV(self.kx, self.k, L[iinter+1].medium.K) # # print(k_y_2) # M[ieq, d[iinter+0][0]] = -SV_1[2, 0]*np.exp(-1j*k_y_1[0]*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = -SV_1[2, 1]*np.exp(-1j*k_y_1[1]*L[iinter].thickness) # M[ieq, d[iinter+0][2]] = -SV_1[2, 2]*np.exp(-1j*k_y_1[2]*L[iinter].thickness) # M[ieq, d[iinter+0][3]] = -SV_1[2, 3] # M[ieq, d[iinter+0][4]] = -SV_1[2, 4] # M[ieq, d[iinter+0][5]] = -SV_1[2, 5] # M[ieq, d[iinter+1][0]] = SV_2[0, 0] # M[ieq, d[iinter+1][1]] = SV_2[0, 1]*np.exp(-1j*k_y_2*L[iinter+1].thickness) # ieq += 1 # M[ieq, d[iinter+0][0]] = -SV_1[4, 0]*np.exp(-1j*k_y_1[0]*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = -SV_1[4, 1]*np.exp(-1j*k_y_1[1]*L[iinter].thickness) # M[ieq, d[iinter+0][2]] = -SV_1[4, 2]*np.exp(-1j*k_y_1[2]*L[iinter].thickness) # M[ieq, d[iinter+0][3]] = -SV_1[4, 3] # M[ieq, d[iinter+0][4]] = -SV_1[4, 4] # M[ieq, d[iinter+0][5]] = -SV_1[4, 5] # M[ieq, d[iinter+1][0]] = SV_2[1, 0] # M[ieq, d[iinter+1][1]] = SV_2[1, 1]*np.exp(-1j*k_y_2*L[iinter+1].thickness) # ieq += 1 # M[ieq, d[iinter+0][0]] = SV_1[0, 0]*np.exp(-1j*k_y_1[0]*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = SV_1[0, 1]*np.exp(-1j*k_y_1[1]*L[iinter].thickness) # M[ieq, d[iinter+0][2]] = SV_1[0, 2]*np.exp(-1j*k_y_1[2]*L[iinter].thickness) # M[ieq, d[iinter+0][3]] = SV_1[0, 3] # M[ieq, d[iinter+0][4]] = SV_1[0, 4] # M[ieq, d[iinter+0][5]] = SV_1[0, 5] # ieq += 1 # M[ieq, d[iinter+0][0]] = SV_1[3, 0]*np.exp(-1j*k_y_1[0]*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = SV_1[3, 1]*np.exp(-1j*k_y_1[1]*L[iinter].thickness) # M[ieq, d[iinter+0][2]] = SV_1[3, 2]*np.exp(-1j*k_y_1[2]*L[iinter].thickness) # M[ieq, d[iinter+0][3]] = SV_1[3, 3] # M[ieq, d[iinter+0][4]] = SV_1[3, 4] # M[ieq, d[iinter+0][5]] = SV_1[3, 5] # ieq += 1 # return ieq # def interface_elastic_fluid(self, ieq, iinter, L, d, M): # SV_1, k_y_1 = elastic_SV(L[iinter].medium, self.kx, self.omega) # SV_2, k_y_2 = fluid_SV(self.kx, self.k, L[iinter+1].medium.K) # # Continuity of u_y # M[ieq, d[iinter+0][0]] = -SV_1[1, 0]*np.exp(-1j*k_y_1[0]*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = -SV_1[1, 1]*np.exp(-1j*k_y_1[1]*L[iinter].thickness) # M[ieq, d[iinter+0][2]] = -SV_1[1, 2] # M[ieq, d[iinter+0][3]] = -SV_1[1, 3] # M[ieq, d[iinter+1][0]] = SV_2[0, 0] # M[ieq, d[iinter+1][1]] = SV_2[0, 1]*np.exp(-1j*k_y_2*L[iinter+1].thickness) # ieq += 1 # # sigma_yy = -p # M[ieq, d[iinter+0][0]] = SV_1[2, 0]*np.exp(-1j*k_y_1[0]*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = SV_1[2, 1]*np.exp(-1j*k_y_1[1]*L[iinter].thickness) # M[ieq, d[iinter+0][2]] = SV_1[2, 2] # M[ieq, d[iinter+0][3]] = SV_1[2, 3] # M[ieq, d[iinter+1][0]] = SV_2[1, 0] # M[ieq, d[iinter+1][1]] = SV_2[1, 1]*np.exp(-1j*k_y_2*L[iinter+1].thickness) # ieq += 1 # # sigma_xy = 0 # M[ieq, d[iinter+0][0]] = SV_1[0, 0]*np.exp(-1j*k_y_1[0]*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = SV_1[0, 1]*np.exp(-1j*k_y_1[1]*L[iinter].thickness) # M[ieq, d[iinter+0][2]] = SV_1[0, 2] # M[ieq, d[iinter+0][3]] = SV_1[0, 3] # ieq += 1 # return ieq # def interface_elastic_rigid(self, M, ieq, L, d): # SV, k_y = elastic_SV(L.medium,self.kx, self.omega) # M[ieq, d[0]] = SV[1, 0]*np.exp(-1j*k_y[0]*L.thickness) # M[ieq, d[1]] = SV[1, 1]*np.exp(-1j*k_y[1]*L.thickness) # M[ieq, d[2]] = SV[1, 2] # M[ieq, d[3]] = SV[1, 3] # ieq += 1 # M[ieq, d[0]] = SV[3, 0]*np.exp(-1j*k_y[0]*L.thickness) # M[ieq, d[1]] = SV[3, 1]*np.exp(-1j*k_y[1]*L.thickness) # M[ieq, d[2]] = SV[3, 2] # M[ieq, d[3]] = SV[3, 3] # ieq += 1 # return ieq # def interface_pem_rigid(self, M, ieq, L, d): # SV, k_y = PEM_SV(L.medium, self.kx) # M[ieq, d[0]] = SV[1, 0]*np.exp(-1j*k_y[0]*L.thickness) # M[ieq, d[1]] = SV[1, 1]*np.exp(-1j*k_y[1]*L.thickness) # M[ieq, d[2]] = SV[1, 2]*np.exp(-1j*k_y[2]*L.thickness) # M[ieq, d[3]] = SV[1, 3] # M[ieq, d[4]] = SV[1, 4] # M[ieq, d[5]] = SV[1, 5] # ieq += 1 # M[ieq, d[0]] = SV[2, 0]*np.exp(-1j*k_y[0]*L.thickness) # M[ieq, d[1]] = SV[2, 1]*np.exp(-1j*k_y[1]*L.thickness) # M[ieq, d[2]] = SV[2, 2]*np.exp(-1j*k_y[2]*L.thickness) # M[ieq, d[3]] = SV[2, 3] # M[ieq, d[4]] = SV[2, 4] # M[ieq, d[5]] = SV[2, 5] # ieq += 1 # M[ieq, d[0]] = SV[5, 0]*np.exp(-1j*k_y[0]*L.thickness) # M[ieq, d[1]] = SV[5, 1]*np.exp(-1j*k_y[1]*L.thickness) # M[ieq, d[2]] = SV[5, 2]*np.exp(-1j*k_y[2]*L.thickness) # M[ieq, d[3]] = SV[5, 3] # M[ieq, d[4]] = SV[5, 4] # M[ieq, d[5]] = SV[5, 5] # ieq += 1 # return ieq # def plot_sol_PW(self, X, dofs): # x_start = self.shift_plot # for _l, _layer in enumerate(self.layers): # x_f = np.linspace(0, _layer.thickness,200) # x_b = x_f-_layer.thickness # if _layer.medium.MODEL == "fluid": # SV, k_y = fluid_SV(self.kx, self.k, _layer.medium.K) # pr = SV[1, 0]*np.exp(-1j*k_y*x_f)*X[dofs[_l][0]] # pr += SV[1, 1]*np.exp( 1j*k_y*x_b)*X[dofs[_l][1]] # ut = SV[0, 0]*np.exp(-1j*k_y*x_f)*X[dofs[_l][0]] # ut += SV[0, 1]*np.exp( 1j*k_y*x_b)*X[dofs[_l][1]] # if self.plot[2]: # plt.figure(2) # plt.plot(x_start+x_f, np.abs(pr), 'r') # plt.plot(x_start+x_f, np.imag(pr), 'm') # plt.title("Pressure") # # plt.figure(5) # # plt.plot(x_start+x_f,np.abs(ut),'b') # # plt.plot(x_start+x_f,np.imag(ut),'k') # if _layer.medium.MODEL == "pem": # SV, k_y = PEM_SV(_layer.medium, self.kx) # ux, uy, pr, ut = 0*1j*x_f, 0*1j*x_f, 0*1j*x_f, 0*1j*x_f # for i_dim in range(3): # ux += SV[1, i_dim ]*np.exp(-1j*k_y[i_dim]*x_f)*X[dofs[_l][i_dim]] # ux += SV[1, i_dim+3]*np.exp( 1j*k_y[i_dim]*x_b)*X[dofs[_l][i_dim+3]] # uy += SV[5, i_dim ]*np.exp(-1j*k_y[i_dim]*x_f)*X[dofs[_l][i_dim]] # uy += SV[5, i_dim+3]*np.exp( 1j*k_y[i_dim]*x_b)*X[dofs[_l][i_dim+3]] # pr += SV[4, i_dim ]*np.exp(-1j*k_y[i_dim]*x_f)*X[dofs[_l][i_dim]] # pr += SV[4, i_dim+3]*np.exp( 1j*k_y[i_dim]*x_b)*X[dofs[_l][i_dim+3]] # ut += SV[2, i_dim ]*np.exp(-1j*k_y[i_dim]*x_f)*X[dofs[_l][i_dim]] # ut += SV[2, i_dim+3]*np.exp( 1j*k_y[i_dim]*x_b)*X[dofs[_l][i_dim+3]] # if self.plot[0]: # plt.figure(0) # plt.plot(x_start+x_f, np.abs(uy), 'r') # plt.plot(x_start+x_f, np.imag(uy), 'm') # plt.title("Solid displacement along x") # if self.plot[1]: # plt.figure(1) # plt.plot(x_start+x_f, np.abs(ux), 'r') # plt.plot(x_start+x_f, np.imag(ux), 'm') # plt.title("Solid displacement along y") # if self.plot[2]: # plt.figure(2) # plt.plot(x_start+x_f, np.abs(pr), 'r') # plt.plot(x_start+x_f, np.imag(pr), 'm') # plt.title("Pressure") # if _layer.medium.MODEL == "elastic": # SV, k_y = elastic_SV(_layer.medium, self.kx, self.omega) # ux, uy, pr, sig = 0*1j*x_f, 0*1j*x_f, 0*1j*x_f, 0*1j*x_f # for i_dim in range(2): # ux += SV[1, i_dim ]*np.exp(-1j*k_y[i_dim]*x_f)*X[dofs[_l][i_dim]] # ux += SV[1, i_dim+2]*np.exp( 1j*k_y[i_dim]*x_b)*X[dofs[_l][i_dim+2]] # uy += SV[3, i_dim ]*np.exp(-1j*k_y[i_dim]*x_f)*X[dofs[_l][i_dim]] # uy += SV[3, i_dim+2]*np.exp( 1j*k_y[i_dim]*x_b)*X[dofs[_l][i_dim+2]] # pr -= SV[2, i_dim ]*np.exp(-1j*k_y[i_dim]*x_f)*X[dofs[_l][i_dim]] # pr -= SV[2, i_dim+2]*np.exp( 1j*k_y[i_dim]*x_b)*X[dofs[_l][i_dim+2]] # sig -= SV[0, i_dim ]*np.exp(-1j*k_y[i_dim]*x_f)*X[dofs[_l][i_dim]] # sig -= SV[0, i_dim+2]*np.exp( 1j*k_y[i_dim]*x_b)*X[dofs[_l][i_dim+2]] # if self.plot[0]: # plt.figure(0) # plt.plot(x_start+x_f, np.abs(uy), 'r') # plt.plot(x_start+x_f, np.imag(uy), 'm') # plt.title("Solid displacement along x") # if self.plot[1]: # plt.figure(1) # plt.plot(x_start+x_f, np.abs(ux), 'r') # plt.plot(x_start+x_f, np.imag(ux), 'm') # plt.title("Solid displacement along y") # # if self.plot[2]: # # plt.figure(2) # # plt.plot(x_start+x_f, np.abs(pr), 'r') # # plt.plot(x_start+x_f, np.imag(pr), 'm') # # plt.title("Sigma_yy") # # if self.plot[2]: # # plt.figure(3) # # plt.plot(x_start+x_f, np.abs(sig), 'r') # # plt.plot(x_start+x_f, np.imag(sig), 'm') # # plt.title("Sigma_xy") # x_start += _layer.thickness # def PEM_SV(mat,ky): # ''' S={0:\hat{\sigma}_{xy}, 1:u_y^s, 2:u_y^t, 3:\hat{\sigma}_{yy}, 4:p, 5:u_x^s}''' # kx_1 = np.sqrt(mat.delta_1**2-ky**2) # kx_2 = np.sqrt(mat.delta_2**2-ky**2) # kx_3 = np.sqrt(mat.delta_3**2-ky**2) # kx = np.array([kx_1, kx_2, kx_3]) # delta = np.array([mat.delta_1, mat.delta_2, mat.delta_3]) # alpha_1 = -1j*mat.A_hat*mat.delta_1**2-1j*2*mat.N*kx[0]**2 # alpha_2 = -1j*mat.A_hat*mat.delta_2**2-1j*2*mat.N*kx[1]**2 # alpha_3 = -2*1j*mat.N*kx[2]*ky # SV = np.zeros((6,6), dtype=complex) # SV[0:6, 0] = np.array([-2*1j*mat.N*kx[0]*ky, kx[0], mat.mu_1*kx[0], alpha_1, 1j*delta[0]**2*mat.K_eq_til*mat.mu_1, ky]) # SV[0:6, 3] = np.array([ 2*1j*mat.N*kx[0]*ky,-kx[0],-mat.mu_1*kx[0], alpha_1, 1j*delta[0]**2*mat.K_eq_til*mat.mu_1, ky]) # SV[0:6, 1] = np.array([-2*1j*mat.N*kx[1]*ky, kx[1], mat.mu_2*kx[1],alpha_2, 1j*delta[1]**2*mat.K_eq_til*mat.mu_2, ky]) # SV[0:6, 4] = np.array([ 2*1j*mat.N*kx[1]*ky,-kx[1],-mat.mu_2*kx[1],alpha_2, 1j*delta[1]**2*mat.K_eq_til*mat.mu_2, ky]) # SV[0:6, 2] = np.array([1j*mat.N*(kx[2]**2-ky**2), ky, mat.mu_3*ky, alpha_3, 0., -kx[2]]) # SV[0:6, 5] = np.array([1j*mat.N*(kx[2]**2-ky**2), ky, mat.mu_3*ky, -alpha_3, 0., kx[2]]) # return SV, kx # def elastic_SV(mat,ky, omega): # ''' S={0:\sigma_{xy}, 1: u_y, 2 \sigma_{yy}, 3 u_x}''' # P_mat = mat.lambda_ + 2.*mat.mu # delta_p = omega*np.sqrt(mat.rho/P_mat) # delta_s = omega*np.sqrt(mat.rho/mat.mu) # kx_p = np.sqrt(delta_p**2-ky**2) # kx_s = np.sqrt(delta_s**2-ky**2) # kx = np.array([kx_p, kx_s]) # alpha_p = -1j*mat.lambda_*delta_p**2 - 2j*mat.mu*kx[0]**2 # alpha_s = 2j*mat.mu*kx[1]*ky # SV = np.zeros((4, 4), dtype=np.complex) # SV[0:4, 0] = np.array([-2.*1j*mat.mu*kx[0]*ky, kx[0], alpha_p, ky]) # SV[0:4, 2] = np.array([ 2.*1j*mat.mu*kx[0]*ky, -kx[0], alpha_p, ky]) # SV[0:4, 1] = np.array([1j*mat.mu*(kx[1]**2-ky**2), ky,-alpha_s, -kx[1]]) # SV[0:4, 3] = np.array([1j*mat.mu*(kx[1]**2-ky**2), ky, alpha_s, kx[1]]) # return SV, kx # def fluid_SV(kx, k, K): # ''' S={0:u_y , 1:p}''' # ky = np.sqrt(k**2-kx**2) # SV = np.zeros((2, 2), dtype=complex) # SV[0, 0:2] = np.array([ky/(1j*K*k**2), -ky/(1j*K*k**2)]) # SV[1, 0:2] = np.array([1, 1]) # return SV, ky # def resolution_PW_imposed_displacement(S, p): # # print("k={}".format(p.k)) # Layers = S.layers.copy() # n, interfaces, dofs = initialise_PW_solver(Layers, S.backing) # M = np.zeros((n, n), dtype=complex) # i_eq = 0 # # Loop on the layers # for i_inter, _inter in enumerate(interfaces): # if _inter[0] == "fluid": # if _inter[1] == "fluid": # i_eq = interface_fluid_fluid(i_eq, i_inter, Layers, dofs, M, p) # if _inter[1] == "pem": # i_eq = interface_fluid_pem(i_eq, i_inter, Layers, dofs, M, p) # elif _inter[0] == "pem": # if _inter[1] == "fluid": # i_eq = interface_pem_fluid(i_eq, i_inter, Layers, dofs, M, p) # if _inter[1] == "pem": # i_eq = interface_pem_pem(i_eq, i_inter, Layers, dofs, M, p) # if S.backing == backing.rigid: # if Layers[-1].medium.MODEL == "fluid": # i_eq = interface_fluid_rigid(M, i_eq, Layers[-1], dofs[-1], p) # elif Layers[-1].medium.MODEL == "pem": # i_eq = interface_pem_rigid(M, i_eq, Layers[-1], dofs[-1], p) # if Layers[0].medium.MODEL == "fluid": # F = np.zeros(n, dtype=complex) # SV, k_y = fluid_SV(p.kx, p.k, Layers[0].medium.K) # M[i_eq, dofs[0][0]] = SV[0, 0] # M[i_eq, dofs[0][1]] = SV[0, 1]*np.exp(-1j*k_y*Layers[0].thickness) # F[i_eq] = 1. # elif Layers[0].medium.MODEL == "pem": # SV, k_y = PEM_SV(Layers[0].medium, p.kx) # M[i_eq, dofs[0][0]] = SV[2, 0] # M[i_eq, dofs[0][1]] = SV[2, 1] # M[i_eq, dofs[0][2]] = SV[2, 2] # M[i_eq, dofs[0][3]] = SV[2, 3]*np.exp(-1j*k_y[0]*Layers[0].thickness) # M[i_eq, dofs[0][4]] = SV[2, 4]*np.exp(-1j*k_y[1]*Layers[0].thickness) # M[i_eq, dofs[0][5]] = SV[2, 5]*np.exp(-1j*k_y[2]*Layers[0].thickness) # F = np.zeros(n, dtype=complex) # F[i_eq] = 1. # i_eq +=1 # M[i_eq, dofs[0][0]] = SV[0, 0] # M[i_eq, dofs[0][1]] = SV[0, 1] # M[i_eq, dofs[0][2]] = SV[0, 2] # M[i_eq, dofs[0][3]] = SV[0, 3]*np.exp(-1j*k_y[0]*Layers[0].thickness) # M[i_eq, dofs[0][4]] = SV[0, 4]*np.exp(-1j*k_y[1]*Layers[0].thickness) # M[i_eq, dofs[0][5]] = SV[0, 5]*np.exp(-1j*k_y[2]*Layers[0].thickness) # i_eq += 1 # M[i_eq, dofs[0][0]] = SV[3, 0] # M[i_eq, dofs[0][1]] = SV[3, 1] # M[i_eq, dofs[0][2]] = SV[3, 2] # M[i_eq, dofs[0][3]] = SV[3, 3]*np.exp(-1j*k_y[0]*Layers[0].thickness) # M[i_eq, dofs[0][4]] = SV[3, 4]*np.exp(-1j*k_y[1]*Layers[0].thickness) # M[i_eq, dofs[0][5]] = SV[3, 5]*np.exp(-1j*k_y[2]*Layers[0].thickness) # X = LA.solve(M, F) # # print("|R pyPLANES_PW| = {}".format(np.abs(X[0]))) # print("R pyPLANES_PW = {}".format(X[0])) # plot_sol_PW(S, X, dofs, p)
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 40477, 23, 532, 9, 12, 198, 2, 198, 2, 279, 86, 62, 37724, 13, 9078, 198, 2, 198, 2, 770, 2393, 318, 636, 286, 12972, 22587, 11, 257, 3788, 9387, ...
1.510267
21,671
from __future__ import absolute_import, division, print_function import sys import time from cctbx.array_family import flex from scitbx.math import superpose from mmtbx.conformation_dependent_library import mcl_sf4_coordination from six.moves import range from mmtbx.conformation_dependent_library import metal_coordination_library def superpose_ideal_ligand_on_poor_ligand(ideal_hierarchy, poor_hierarchy, ): """Function superpose an ideal ligand onto the mangled ligand from a ligand fitting procedure Args: ideal_hierarchy (pdb_hierarchy): Ideal ligand poor_hierarchy (pdb_hierarchy): Poor ligand with correct c.o.m. and same atom names in order. Could become more sophisticated. """ sites_moving = flex.vec3_double() sites_fixed = flex.vec3_double() for atom1, atom2 in zip(ideal_hierarchy.atoms(), poor_hierarchy.atoms()): assert atom1.name==atom2.name, '%s!=%s' % (atom1.quote(),atom2.quote()) sites_moving.append(atom1.xyz) sites_fixed.append(atom2.xyz) lsq_fit = superpose.least_squares_fit( reference_sites = sites_fixed, other_sites = sites_moving) sites_new = ideal_hierarchy.atoms().extract_xyz() sites_new = lsq_fit.r.elems * sites_new + lsq_fit.t.elems # rmsd = sites_fixed.rms_difference(lsq_fit.other_sites_best_fit()) ideal_hierarchy.atoms().set_xyz(sites_new) return ideal_hierarchy if __name__=="__main__": from iotbx import pdb ideal_inp=pdb.pdb_input(sys.argv[1]) ideal_hierarchy = ideal_inp.construct_hierarchy() poor_inp=pdb.pdb_input(sys.argv[2]) poor_hierarchy = poor_inp.construct_hierarchy() ideal_hierarchy = superpose_ideal_ligand_on_poor_ligand(ideal_hierarchy, poor_hierarchy) ideal_hierarchy.write_pdb_file('new.pdb')
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 11, 7297, 11, 3601, 62, 8818, 198, 11748, 25064, 198, 11748, 640, 198, 198, 6738, 269, 310, 65, 87, 13, 18747, 62, 17989, 1330, 7059, 198, 6738, 629, 270, 65, 87, 13, 11018, 1330, 2208...
2.39295
766
from contextlib import contextmanager import random import shutil import stat import tempfile import unittest from os.path import join from conda import install from conda.install import (PaddingError, binary_replace, update_prefix, warn_failed_remove, duplicates_to_remove) from .decorators import skip_if_no_mock from .helpers import mock patch = mock.patch if mock else None def generate_all_false_mocks(self): return self.generate_mocks(False, False, False) class duplicates_to_remove_TestCase(unittest.TestCase): if __name__ == '__main__': unittest.main()
[ 6738, 4732, 8019, 1330, 4732, 37153, 198, 11748, 4738, 198, 11748, 4423, 346, 198, 11748, 1185, 198, 11748, 20218, 7753, 198, 11748, 555, 715, 395, 198, 6738, 28686, 13, 6978, 1330, 4654, 628, 198, 6738, 1779, 64, 1330, 2721, 198, 6738,...
2.834862
218
"""A Queryset slicer for Django."""
[ 37811, 32, 2264, 263, 893, 316, 14369, 263, 329, 37770, 526, 15931, 628 ]
2.846154
13
from django.urls import path from . import views urlpatterns = [ path('', views.news_home, name='news_home'), path('create', views.create, name='create'), path('<int:pk>', views.NewsDetailView.as_view(), name='news-detail'), path('<int:pk>/update', views.NewsUpdateView.as_view(), name='news-update'), path('<int:pk>/delete', views.NewsDeleteView.as_view(), name='news-delete'), ]
[ 6738, 42625, 14208, 13, 6371, 82, 1330, 3108, 198, 198, 6738, 764, 1330, 5009, 198, 198, 6371, 33279, 82, 796, 685, 198, 220, 220, 220, 3108, 10786, 3256, 5009, 13, 10827, 62, 11195, 11, 1438, 11639, 10827, 62, 11195, 33809, 198, 220,...
2.68
150
import requests import lib.common MODULE_NAME = 'headers'
[ 11748, 7007, 198, 198, 11748, 9195, 13, 11321, 198, 198, 33365, 24212, 62, 20608, 796, 705, 50145, 6, 628 ]
3.210526
19
import os import requests from bs4 import BeautifulSoup from ekorpkit import eKonf from ekorpkit.io.download.web import web_download, web_download_unzip
[ 11748, 28686, 198, 11748, 7007, 198, 6738, 275, 82, 19, 1330, 23762, 50, 10486, 198, 6738, 304, 74, 16300, 15813, 1330, 304, 42, 261, 69, 198, 6738, 304, 74, 16300, 15813, 13, 952, 13, 15002, 13, 12384, 1330, 3992, 62, 15002, 11, 39...
3.142857
49
from HARK.ConsumptionSaving.ConsIndShockModel import PerfForesightConsumerType import numpy as np import unittest
[ 6738, 367, 14175, 13, 9444, 24098, 50, 2703, 13, 9444, 5497, 31646, 17633, 1330, 2448, 69, 37, 2850, 432, 49106, 6030, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 555, 715, 395, 198 ]
3.454545
33
# coding: utf-8 from __future__ import absolute_import from datetime import date, datetime # noqa: F401 from typing import List, Dict # noqa: F401 from openapi_server.models.base_model_ import Model from openapi_server.models.component import Component from openapi_server import util from openapi_server.models.component import Component # noqa: E501
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 6738, 4818, 8079, 1330, 3128, 11, 4818, 8079, 220, 1303, 645, 20402, 25, 376, 21844, 198, 198, 6738, 19720, 1330, 7343, 11, 360, 713, 220...
3.386792
106
import os from os import getcwd #---------------------------------------------# # classes # model_datatxt #---------------------------------------------# classes = ["cat", "dog"] sets = ["train", "test"] wd = getcwd() for se in sets: list_file = open('cls_' + se + '.txt', 'w') datasets_path = "datasets/" + se types_name = os.listdir(datasets_path) for type_name in types_name: if type_name not in classes: continue cls_id = classes.index(type_name) photos_path = os.path.join(datasets_path, type_name) photos_name = os.listdir(photos_path) for photo_name in photos_name: _, postfix = os.path.splitext(photo_name) if postfix not in ['.jpg', '.png', '.jpeg']: continue list_file.write(str(cls_id) + ";" + '%s/%s'%(wd, os.path.join(photos_path, photo_name))) list_file.write('\n') list_file.close()
[ 11748, 28686, 201, 198, 6738, 28686, 1330, 651, 66, 16993, 201, 198, 201, 198, 2, 3880, 32501, 2, 201, 198, 2, 220, 220, 6097, 201, 198, 2, 220, 220, 2746, 62, 19608, 265, 742, 201, 198, 2, 3880, 32501, 2, 201, 198, 37724, 796, ...
2.158242
455
from protocolbuffers import SimObjectAttributes_pb2 as protocols from careers.career_unemployment import CareerUnemployment import services import sims4 logger = sims4.log.Logger('Relationship', default_owner='jjacobson')
[ 6738, 8435, 36873, 364, 1330, 3184, 10267, 29021, 62, 40842, 17, 355, 19565, 198, 6738, 16179, 13, 6651, 263, 62, 403, 28812, 1330, 32619, 3118, 28812, 198, 11748, 2594, 198, 11748, 985, 82, 19, 198, 6404, 1362, 796, 985, 82, 19, 13, ...
3.7
60
# Given an integer n, count the total number of digit 1 appearing # in all non-negative integers less than or equal to n. # # For example: # Given n = 13, # Return 6, because digit 1 occurred in the following numbers: # 1, 10, 11, 12, 13. # if __name__ == "__main__": print Solution().countDigitOne(13)
[ 2, 11259, 281, 18253, 299, 11, 954, 262, 2472, 1271, 286, 16839, 352, 12655, 198, 2, 287, 477, 1729, 12, 31591, 37014, 1342, 621, 393, 4961, 284, 299, 13, 198, 2, 198, 2, 1114, 1672, 25, 198, 2, 11259, 299, 796, 1511, 11, 198, 2...
3.131313
99
from PIL import Image from math import sqrt import numpy as np import time import matplotlib.backends.backend_tkagg import matplotlib.pyplot as plt def distance(point, x, y): return sqrt((point.x - x)**2 + (point.y - y)**2) def insert_in_heap(heap, top, point): heap.append(point) i = top parent = (i - 1)/2 while i >= 1 and heap[int(i)].f < heap[int(parent)].f: heap[int(i)], heap[int(parent)] = heap[int(parent)], heap[int(i)] # swap i = parent parent = (i - 1) / 2 return def calculate_weight(x, y, liste, top, point, visited, index1, index2): if visited[int(x)][int(y)] == 0: r, g, b = image.getpixel((x, y)) if x == end.x and y == end.y: print("Path found.") if r is 0: r = 1 new_point = Point(x, y, 0) new_point.parent = point new_point.h = distance(end, x, y) * (256 - r) new_point.g = 0 if index1 == 1: # a_star new_point.g = new_point.parent.g + 256 - r new_point.f = new_point.h + new_point.g # bfs'de g = 0 if index2 == 0: # stack liste.append(new_point) else: # heap insert_in_heap(liste, top, new_point) top += 1 visited[int(x)][int(y)] = 1 return top def add_neighbours(point, liste, top, visited, index1, index2): # print(point.x, point.y) if (point.x == width - 1 and point.y == height - 1) or (point.x == 0 and point.y == 0) or \ (point.x == 0 and point.y == height - 1) or (point.x == width - 1 and point.y == 0): # print("first if") if point.x == width - 1 and point.y == height - 1: constx = -1 consty = -1 elif point.x == 0 and point.y == 0: constx = 1 consty = 1 elif point.x == width - 1 and point.y == 0: constx = 1 consty = -1 else: constx = -1 consty = 1 top = calculate_weight(point.x + constx, point.y, liste, top, point, visited, index1, index2) top = calculate_weight(point.x, point.y + consty, liste, top, point, visited, index1, index2) top = calculate_weight(point.x + constx, point.y + consty, liste, top, point, visited, index1, index2) elif point.x == 0 or point.x == width - 1: # print("nd if") top = calculate_weight(point.x, point.y - 1, liste, top, point, visited, index1, index2) top = calculate_weight(point.x, point.y + 1, liste, top, point, visited, index1, index2) if point.x == 0: const = 1 else: const = -1 top = calculate_weight(point.x + const, point.y - 1, liste, top, point, visited, index1, index2) top = calculate_weight(point.x + const, point.y + 1, liste, top, point, visited, index1, index2) top = calculate_weight(point.x + const, point.y, liste, top, point, visited, index1, index2) elif point.y == 0 or point.y == height - 1: # print("3rd if") top = calculate_weight(point.x - 1, point.y, liste, top, point, visited, index1, index2) top = calculate_weight(point.x + 1, point.y, liste, top, point, visited, index1, index2) if point.y == 0: const = 1 else: const = -1 top = calculate_weight(point.x - 1, point.y + const, liste, top, point, visited, index1, index2) top = calculate_weight(point.x + 1, point.y + const, liste, top, point, visited, index1, index2) top = calculate_weight(point.x, point.y + const, liste, top, point, visited, index1, index2) else: # print("4th if") top = calculate_weight(point.x - 1, point.y, liste, top, point, visited, index1, index2) top = calculate_weight(point.x - 1, point.y - 1, liste, top, point, visited, index1, index2) top = calculate_weight(point.x - 1, point.y + 1, liste, top, point, visited, index1, index2) top = calculate_weight(point.x + 1, point.y - 1, liste, top, point, visited, index1, index2) top = calculate_weight(point.x + 1, point.y, liste, top, point, visited, index1, index2) top = calculate_weight(point.x + 1, point.y + 1, liste, top, point, visited, index1, index2) top = calculate_weight(point.x, point.y + 1, liste, top, point, visited, index1, index2) top = calculate_weight(point.x, point.y - 1, liste, top, point, visited, index1, index2) return top def paint(point): yol = [] while not point.equal(start): yol.append(point) image.putpixel((int(point.x), int(point.y)), (60, 255, 0)) point = point.parent end_time = time.time() # image.show() '''print("--------------YOL------------------") for i in range(len(yol)): print("x: {}, y:{}, distance:{}".format(yol[i].x, yol[i].y, yol[i].f)) print("------------------------------------")''' return image, (end_time - start_time) def bfs_and_a_star_with_stack(index): stack = [] top = 0 found = False point = None stack.append(start) visited = np.zeros((width, height)) visited[int(start.x)][int(start.y)] = 1 j = 0 max_element = 0 while stack and not found: point = stack.pop(top) # print("x: {}, y:{}, f:{}".format(point.x, point.y, point.f)) top -= 1 if point.equal(end): found = True else: top = add_neighbours(point, stack, top, visited, index, 0) stack.sort(key=lambda point: point.f, reverse=True) if len(stack) > max_element: max_element = len(stack) j += 1 if found: result_image, total_time = paint(point) # print("Stackten ekilen eleman says: ", j) # print("Stackteki maksimum eleman says: ", max_element) return result_image, total_time, j, max_element def find_smallest_child(heap, i, top): if 2 * i + 2 < top: # has two child if heap[2*i + 1].f < heap[2*i + 2].f: return 2*i + 1 else: return 2*i + 2 elif 2*i + 1 < top: # has one child return 2*i + 1 else: # has no child return 0 def remove_min(heap, top): if top == 0: return None min_point = heap[0] top -= 1 heap[0] = heap[top] del heap[top] i = 0 index = find_smallest_child(heap, i, top) while index != 0 and heap[i].f > heap[index].f: heap[i], heap[index] = heap[index], heap[i] i = index index = find_smallest_child(heap, i, top) return min_point, top def bfs_and_a_star_with_heap(index): heap = [] found = False yol = [] point = None heap.append(start) visited = np.zeros((width, height)) visited[int(start.x)][int(start.y)] = 1 j = 0 top = 1 max_element = 0 while heap and not found: point, top = remove_min(heap, top) # print("x: {}, y:{}, f:{}".format(point.x, point.y, point.f)) if point.equal(end): found = True else: top = add_neighbours(point, heap, top, visited, index, 1) if len(heap) > max_element: max_element = len(heap) j += 1 if found: result_image, total_time = paint(point) else: return return result_image, total_time, j, max_element if __name__ == "__main__": print("UYARI: Seilecek grnt exe dosyas ile ayn klasrde olmaldr.") image_name = input("Algoritmann zerinde alaca grntnn ismini giriniz (rnek input: image.png): ") print(image_name) print("-------------------Algoritmalar------------------") print("1- Best First Search with Stack") print("2- Best First Search with Heap") print("3- A* with Stack") print("4- A* with Heap") print("5- Analiz (tm algoritmalarn almalarn ve kyaslamalarn gr)") alg = input("Algoritmay ve veri yapsnn numarasn seiniz (rnek input: 1): ") image = Image.open(image_name) width, height = image.size image = image.convert('RGB') print("Grntnn genilii: {}, ykseklii: {}".format(width, height)) print("NOT: Balang ve biti noktasnn koordinatlar genilik ve uzunluktan kk olmaldr.") sx, sy = input("Balang noktasnn x ve y piksel koordinatlarn srasyla giriniz (rnek input: 350 100): ").split() ex, ey = input("Biti noktasnn x ve y piksel koordinatlarn srasyla giriniz (rnek input: 200 700): ").split() start = Point(int(sx), int(sy), -1) start.parent = -1 end = Point(int(ex), int(ey), -1) start_time = time.time() if int(alg) == 1: result_image, total_time, n_elements, max_elements = bfs_and_a_star_with_stack(0) elif int(alg) == 2: result_image, total_time, n_elements, max_elements = bfs_and_a_star_with_heap(0) elif int(alg) == 3: result_image, total_time, n_elements, max_elements = bfs_and_a_star_with_stack(1) elif int(alg) == 4: result_image, total_time, n_elements, max_elements = bfs_and_a_star_with_heap(1) elif int(alg) == 5: result_image, total_time, n_elements, max_elements = bfs_and_a_star_with_stack(0) output1 = Output(result_image, total_time, n_elements, max_elements) print(n_elements, total_time, max_elements) output1.name = "BFS with Stack" print("1/4") image = Image.open(image_name) width, height = image.size image = image.convert('RGB') start_time = time.time() result_image, total_time, n_elements, max_elements = bfs_and_a_star_with_heap(0) output2 = Output(result_image, total_time, n_elements, max_elements) print(n_elements, total_time, max_elements) output2.name = "BFS with Heap" print("2/4") image = Image.open(image_name) width, height = image.size image = image.convert('RGB') start_time = time.time() result_image, total_time, n_elements, max_elements = bfs_and_a_star_with_stack(1) output3 = Output(result_image, total_time, n_elements, max_elements) output3.name = "A* with Stack" print(n_elements, total_time, max_elements) print("3/4") image = Image.open(image_name) width, height = image.size image = image.convert('RGB') start_time = time.time() result_image, total_time, n_elements, max_elements = bfs_and_a_star_with_heap(1) output4 = Output(result_image, total_time, n_elements, max_elements) output4.name = "A* with Heap" print("4/4") output1.plot_times(output2, output3, output4) output1.plot_max_elements(output2, output3, output4) output1.plot_n_elements(output2, output3, output4) print("Bastrlan grntler srasyla BFS stack, BFS heap, A* stack ve A* heap eklindedir.") fname = image_name.split('.') output1.result_image.show() output1.result_image.save(fname[0] + "BFS_stack.png") output2.result_image.show() output2.result_image.save(fname[0] + "BFS_heap.png") output3.result_image.show() output3.result_image.save(fname[0] + "A_star_stack.png") output4.result_image.show() output4.result_image.save(fname[0] + "A_star_heap.png") exit(0) else: print("Algoritma numaras hatal girildi, tekrar deneyin.") exit(0) print("Stackten ekilen eleman says: ", n_elements) print("Stackteki maksimum eleman says: ", max_elements) print("Toplam sre: ", total_time) result_image.show()
[ 6738, 350, 4146, 1330, 7412, 201, 198, 6738, 10688, 1330, 19862, 17034, 201, 198, 11748, 299, 32152, 355, 45941, 201, 198, 11748, 640, 201, 198, 11748, 2603, 29487, 8019, 13, 1891, 2412, 13, 1891, 437, 62, 30488, 9460, 201, 198, 11748, ...
2.08578
5,689
#Author Shoaib Omar import time import rnnoise import numpy as np time_rnnoise()
[ 2, 13838, 911, 12162, 571, 24980, 198, 11748, 640, 198, 11748, 374, 77, 3919, 786, 198, 11748, 299, 32152, 355, 45941, 198, 2435, 62, 35906, 3919, 786, 3419 ]
2.857143
28
""" shell sort tests module """ import unittest import random from sort import shell from tests import helper
[ 198, 37811, 7582, 3297, 5254, 8265, 37227, 198, 198, 11748, 555, 715, 395, 198, 11748, 4738, 198, 198, 6738, 3297, 1330, 7582, 198, 6738, 5254, 1330, 31904, 198 ]
4.035714
28
import h5pyd from datetime import datetime import tzlocal BUCKET="firefly-hsds" inventory_domain = "/FIREfly/inventory.h5" f = h5pyd.File(inventory_domain, "r", bucket=BUCKET) table = f["inventory"] for row in table: filename = row[0].decode('utf-8') if row[1]: start = formatTime(row[1]) else: start = 0 if row[2]: stop = formatTime(row[2]) else: stop = 0 print(f"{filename}\t{start}\t{stop}") print(f"{table.nrows} rows")
[ 11748, 289, 20, 79, 5173, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 11748, 256, 89, 12001, 198, 198, 33, 16696, 2767, 2625, 6495, 12254, 12, 11994, 9310, 1, 198, 24807, 62, 27830, 796, 12813, 11674, 2200, 12254, 14, 24807, 13, 71,...
2.210046
219
#------------------------------------------------------------------------------ # Copyright (c) 2013-2017, Nucleic Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. #------------------------------------------------------------------------------ from atom.api import Typed from enaml.widgets.timer import ProxyTimer from .QtCore import QTimer from .qt_toolkit_object import QtToolkitObject
[ 2, 10097, 26171, 198, 2, 15069, 357, 66, 8, 2211, 12, 5539, 11, 399, 14913, 291, 7712, 4816, 13, 198, 2, 198, 2, 4307, 6169, 739, 262, 2846, 286, 262, 40499, 347, 10305, 13789, 13, 198, 2, 198, 2, 383, 1336, 5964, 318, 287, 262,...
4.752381
105
# -*- coding: utf-8 -*- # Copyright (c) 2020, Frappe Technologies Pvt. Ltd. and Contributors # See license.txt from __future__ import unicode_literals from json import dumps import frappe import unittest from erpnext.erpnext_integrations.doctype.mpesa_settings.mpesa_settings import process_balance_info, verify_transaction from erpnext.accounts.doctype.pos_invoice.test_pos_invoice import create_pos_invoice def get_test_account_balance_response(): """Response received after calling the account balance API.""" return { "ResultType":0, "ResultCode":0, "ResultDesc":"The service request has been accepted successfully.", "OriginatorConversationID":"10816-694520-2", "ConversationID":"AG_20200927_00007cdb1f9fb6494315", "TransactionID":"LGR0000000", "ResultParameters":{ "ResultParameter":[ { "Key":"ReceiptNo", "Value":"LGR919G2AV" }, { "Key":"Conversation ID", "Value":"AG_20170727_00004492b1b6d0078fbe" }, { "Key":"FinalisedTime", "Value":20170727101415 }, { "Key":"Amount", "Value":10 }, { "Key":"TransactionStatus", "Value":"Completed" }, { "Key":"ReasonType", "Value":"Salary Payment via API" }, { "Key":"TransactionReason" }, { "Key":"DebitPartyCharges", "Value":"Fee For B2C Payment|KES|33.00" }, { "Key":"DebitAccountType", "Value":"Utility Account" }, { "Key":"InitiatedTime", "Value":20170727101415 }, { "Key":"Originator Conversation ID", "Value":"19455-773836-1" }, { "Key":"CreditPartyName", "Value":"254708374149 - John Doe" }, { "Key":"DebitPartyName", "Value":"600134 - Safaricom157" } ] }, "ReferenceData":{ "ReferenceItem":{ "Key":"Occasion", "Value":"aaaa" } } } def get_payment_request_response_payload(Amount=500): """Response received after successfully calling the stk push process request API.""" CheckoutRequestID = frappe.utils.random_string(10) return { "MerchantRequestID": "8071-27184008-1", "CheckoutRequestID": CheckoutRequestID, "ResultCode": 0, "ResultDesc": "The service request is processed successfully.", "CallbackMetadata": { "Item": [ { "Name": "Amount", "Value": Amount }, { "Name": "MpesaReceiptNumber", "Value": "LGR7OWQX0R" }, { "Name": "TransactionDate", "Value": 20201006113336 }, { "Name": "PhoneNumber", "Value": 254723575670 } ] } } def get_payment_callback_payload(Amount=500, CheckoutRequestID="ws_CO_061020201133231972", MpesaReceiptNumber="LGR7OWQX0R"): """Response received from the server as callback after calling the stkpush process request API.""" return { "Body":{ "stkCallback":{ "MerchantRequestID":"19465-780693-1", "CheckoutRequestID":CheckoutRequestID, "ResultCode":0, "ResultDesc":"The service request is processed successfully.", "CallbackMetadata":{ "Item":[ { "Name":"Amount", "Value":Amount }, { "Name":"MpesaReceiptNumber", "Value":MpesaReceiptNumber }, { "Name":"Balance" }, { "Name":"TransactionDate", "Value":20170727154800 }, { "Name":"PhoneNumber", "Value":254721566839 } ] } } } } def get_account_balance_callback_payload(): """Response received from the server as callback after calling the account balance API.""" return { "Result":{ "ResultType": 0, "ResultCode": 0, "ResultDesc": "The service request is processed successfully.", "OriginatorConversationID": "16470-170099139-1", "ConversationID": "AG_20200927_00007cdb1f9fb6494315", "TransactionID": "OIR0000000", "ResultParameters": { "ResultParameter": [ { "Key": "AccountBalance", "Value": "Working Account|KES|481000.00|481000.00|0.00|0.00" }, { "Key": "BOCompletedTime", "Value": 20200927234123 } ] }, "ReferenceData": { "ReferenceItem": { "Key": "QueueTimeoutURL", "Value": "https://internalsandbox.safaricom.co.ke/mpesa/abresults/v1/submit" } } } }
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 15069, 357, 66, 8, 12131, 11, 39313, 27768, 21852, 18367, 83, 13, 12052, 13, 290, 25767, 669, 198, 2, 4091, 5964, 13, 14116, 198, 6738, 11593, 37443, 834, 1330, 280...
2.396147
1,661
from __future__ import absolute_import import yaml with open("config.yml", "r") as f: config = yaml.load(f)
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 198, 11748, 331, 43695, 198, 198, 4480, 1280, 7203, 11250, 13, 88, 4029, 1600, 366, 81, 4943, 355, 277, 25, 198, 220, 220, 220, 4566, 796, 331, 43695, 13, 2220, 7, 69, 8, 198 ]
2.651163
43
""" XVM (c) www.modxvm.com 2013-2017 """ # PUBLIC # PRIVATE from logger import * from gui.shared.utils.requesters import REQ_CRITERIA from helpers import dependency from skeletons.gui.shared import IItemsCache _special = { # Data from http://forum.worldoftanks.ru/index.php?/topic/41221- # Last update: 23.05.2017 # level 2 'germany:G53_PzI': [ 2, 2 ], 'uk:GB76_Mk_VIC': [ 2, 2 ], 'usa:A19_T2_lt': [ 2, 4 ], 'usa:A93_T7_Combat_Car': [ 2, 2 ], # level 3 'germany:G36_PzII_J': [ 3, 4 ], 'japan:J05_Ke_Ni_B': [ 3, 4 ], 'ussr:R34_BT-SV': [ 3, 4 ], 'ussr:R50_SU76I': [ 3, 4 ], 'ussr:R56_T-127': [ 3, 4 ], 'ussr:R67_M3_LL': [ 3, 4 ], 'ussr:R86_LTP': [ 3, 4 ], # level 4 'france:F14_AMX40': [ 4, 6 ], 'germany:G35_B-1bis_captured': [ 4, 4 ], 'japan:J06_Ke_Ho': [ 4, 6 ], 'uk:GB04_Valentine': [ 4, 6 ], 'uk:GB60_Covenanter': [ 4, 6 ], 'ussr:R12_A-20': [ 4, 6 ], 'ussr:R31_Valentine_LL': [ 4, 4 ], 'ussr:R44_T80': [ 4, 6 ], 'ussr:R68_A-32': [ 4, 5 ], # level 5 'germany:G104_Stug_IV': [ 5, 6 ], 'germany:G32_PzV_PzIV': [ 5, 6 ], 'germany:G32_PzV_PzIV_ausf_Alfa': [ 5, 6 ], 'germany:G70_PzIV_Hydro': [ 5, 6 ], 'uk:GB20_Crusader': [ 5, 7 ], 'uk:GB51_Excelsior': [ 5, 6 ], 'uk:GB68_Matilda_Black_Prince': [ 5, 6 ], 'usa:A21_T14': [ 5, 6 ], 'usa:A44_M4A2E4': [ 5, 6 ], 'ussr:R32_Matilda_II_LL': [ 5, 6 ], 'ussr:R33_Churchill_LL': [ 5, 6 ], 'ussr:R38_KV-220': [ 5, 6 ], 'ussr:R38_KV-220_beta': [ 5, 6 ], 'ussr:R78_SU_85I': [ 5, 6 ], # level 6 'germany:G32_PzV_PzIV_CN': [ 6, 7 ], 'germany:G32_PzV_PzIV_ausf_Alfa_CN': [ 6, 7 ], 'uk:GB63_TOG_II': [ 6, 7 ], # level 7 'germany:G48_E-25': [ 7, 8 ], 'germany:G78_Panther_M10': [ 7, 8 ], 'uk:GB71_AT_15A': [ 7, 8 ], 'usa:A86_T23E3': [ 7, 8 ], 'ussr:R98_T44_85': [ 7, 8 ], 'ussr:R99_T44_122': [ 7, 8 ], # level 8 'china:Ch01_Type59': [ 8, 9 ], 'china:Ch03_WZ-111': [ 8, 9 ], 'china:Ch14_T34_3': [ 8, 9 ], 'china:Ch23_112': [ 8, 9 ], 'france:F65_FCM_50t': [ 8, 9 ], 'germany:G65_JagdTiger_SdKfz_185': [ 8, 9 ], 'usa:A45_M6A2E1': [ 8, 9 ], 'usa:A80_T26_E4_SuperPershing': [ 8, 9 ], 'ussr:R54_KV-5': [ 8, 9 ], 'ussr:R61_Object252': [ 8, 9 ], 'ussr:R61_Object252_BF': [ 8, 9 ], }
[ 37811, 1395, 15996, 357, 66, 8, 7324, 13, 4666, 87, 14761, 13, 785, 2211, 12, 5539, 37227, 198, 198, 2, 44731, 628, 198, 2, 4810, 3824, 6158, 198, 198, 6738, 49706, 1330, 1635, 198, 6738, 11774, 13, 28710, 13, 26791, 13, 8897, 8586,...
1.484171
2,148
import math from pypy.module.cpyext import pystrtod from pypy.module.cpyext.test.test_api import BaseApiTest, raises_w from rpython.rtyper.lltypesystem import rffi from rpython.rtyper.lltypesystem import lltype from pypy.module.cpyext.pystrtod import PyOS_string_to_double
[ 11748, 10688, 198, 198, 6738, 279, 4464, 88, 13, 21412, 13, 66, 9078, 2302, 1330, 12972, 2536, 83, 375, 198, 6738, 279, 4464, 88, 13, 21412, 13, 66, 9078, 2302, 13, 9288, 13, 9288, 62, 15042, 1330, 7308, 32, 14415, 14402, 11, 12073,...
2.679612
103
# -*- coding: utf-8 -*- from mathics.core.symbols import Symbol # Some other common Symbols. This list is sorted in alphabetic order. SymbolAssumptions = Symbol("$Assumptions") SymbolAborted = Symbol("$Aborted") SymbolAll = Symbol("All") SymbolAlternatives = Symbol("Alternatives") SymbolAnd = Symbol("And") SymbolAppend = Symbol("Append") SymbolApply = Symbol("Apply") SymbolAssociation = Symbol("Association") SymbolAutomatic = Symbol("Automatic") SymbolBlank = Symbol("Blank") SymbolBlend = Symbol("Blend") SymbolByteArray = Symbol("ByteArray") SymbolCatalan = Symbol("Catalan") SymbolColorData = Symbol("ColorData") SymbolComplex = Symbol("Complex") SymbolComplexInfinity = Symbol("ComplexInfinity") SymbolCondition = Symbol("Condition") SymbolConditionalExpression = Symbol("ConditionalExpression") Symbol_Context = Symbol("$Context") Symbol_ContextPath = Symbol("$ContextPath") SymbolCos = Symbol("Cos") SymbolD = Symbol("D") SymbolDerivative = Symbol("Derivative") SymbolDirectedInfinity = Symbol("DirectedInfinity") SymbolDispatch = Symbol("Dispatch") SymbolE = Symbol("E") SymbolEdgeForm = Symbol("EdgeForm") SymbolEqual = Symbol("Equal") SymbolExpandAll = Symbol("ExpandAll") SymbolEulerGamma = Symbol("EulerGamma") SymbolFailed = Symbol("$Failed") SymbolFunction = Symbol("Function") SymbolGamma = Symbol("Gamma") SymbolGet = Symbol("Get") SymbolGoldenRatio = Symbol("GoldenRatio") SymbolGraphics = Symbol("Graphics") SymbolGreater = Symbol("Greater") SymbolGreaterEqual = Symbol("GreaterEqual") SymbolGrid = Symbol("Grid") SymbolHoldForm = Symbol("HoldForm") SymbolIndeterminate = Symbol("Indeterminate") SymbolImplies = Symbol("Implies") SymbolInfinity = Symbol("Infinity") SymbolInfix = Symbol("Infix") SymbolInteger = Symbol("Integer") SymbolIntegrate = Symbol("Integrate") SymbolLeft = Symbol("Left") SymbolLess = Symbol("Less") SymbolLessEqual = Symbol("LessEqual") SymbolLog = Symbol("Log") SymbolMachinePrecision = Symbol("MachinePrecision") SymbolMakeBoxes = Symbol("MakeBoxes") SymbolMessageName = Symbol("MessageName") SymbolMinus = Symbol("Minus") SymbolMap = Symbol("Map") SymbolMatrixPower = Symbol("MatrixPower") SymbolMaxPrecision = Symbol("$MaxPrecision") SymbolMemberQ = Symbol("MemberQ") SymbolMinus = Symbol("Minus") SymbolN = Symbol("N") SymbolNeeds = Symbol("Needs") SymbolNIntegrate = Symbol("NIntegrate") SymbolNone = Symbol("None") SymbolNot = Symbol("Not") SymbolNull = Symbol("Null") SymbolNumberQ = Symbol("NumberQ") SymbolNumericQ = Symbol("NumericQ") SymbolOptionValue = Symbol("OptionValue") SymbolOr = Symbol("Or") SymbolOverflow = Symbol("Overflow") SymbolPackages = Symbol("$Packages") SymbolPattern = Symbol("Pattern") SymbolPi = Symbol("Pi") SymbolPiecewise = Symbol("Piecewise") SymbolPoint = Symbol("Point") SymbolPossibleZeroQ = Symbol("PossibleZeroQ") SymbolQuiet = Symbol("Quiet") SymbolRational = Symbol("Rational") SymbolReal = Symbol("Real") SymbolRow = Symbol("Row") SymbolRowBox = Symbol("RowBox") SymbolRGBColor = Symbol("RGBColor") SymbolSuperscriptBox = Symbol("SuperscriptBox") SymbolRule = Symbol("Rule") SymbolRuleDelayed = Symbol("RuleDelayed") SymbolSequence = Symbol("Sequence") SymbolSeries = Symbol("Series") SymbolSeriesData = Symbol("SeriesData") SymbolSet = Symbol("Set") SymbolSimplify = Symbol("Simplify") SymbolSin = Symbol("Sin") SymbolSlot = Symbol("Slot") SymbolStringQ = Symbol("StringQ") SymbolStyle = Symbol("Style") SymbolTable = Symbol("Table") SymbolToString = Symbol("ToString") SymbolUndefined = Symbol("Undefined") SymbolXor = Symbol("Xor")
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 10688, 873, 13, 7295, 13, 1837, 2022, 10220, 1330, 38357, 198, 198, 2, 2773, 584, 2219, 41327, 10220, 13, 770, 1351, 318, 23243, 287, 435, 746, 33312, 1502, ...
3.148082
1,121
# from https://github.com/kvwoerden/mcts-cartpole # ---------------------------------------------------------------------------- # # Imports # # ---------------------------------------------------------------------------- # import os import time import random import argparse <<<<<<< HEAD ======= from types import SimpleNamespace >>>>>>> MCTS import gym from gym import logger from gym.wrappers.monitoring.video_recorder import VideoRecorder from Simple_mcts import MCTSAgent <<<<<<< HEAD # ---------------------------------------------------------------------------- # # Constants # # ---------------------------------------------------------------------------- # SEED = 28 EPISODES = 1 ENVIRONMENT = 'CartPole-v0' LOGGER_LEVEL = logger.WARN ITERATION_BUDGET = 80 LOOKAHEAD_TARGET = 100 MAX_EPISODE_STEPS = 1500 VIDEO_BASEPATH = '.\\video' # './video' START_CP = 20 ======= from Agent import dqn_agent # ---------------------------------------------------------------------------- # # Constants # # ---------------------------------------------------------------------------- # LOGGER_LEVEL = logger.WARN args = dict() args['env_name'] = 'CartPole-v0' args['episodes'] = 10 args['seed'] = 28 args['iteration_budget'] = 8000 # The number of iterations for each search step. Increasing this should lead to better performance.') args['lookahead_target'] = 10000 # The target number of steps the agent aims to look forward.' args['max_episode_steps'] = 1500 # The maximum number of steps to play. args['video_basepath'] = '.\\video' # './video' args['start_cp'] = 20 # The start value of C_p, the value that the agent changes to try to achieve the lookahead target. Decreasing this makes the search tree deeper, increasing this makes the search tree wider. args = SimpleNamespace(**args) >>>>>>> MCTS # ---------------------------------------------------------------------------- # # Main loop # # ---------------------------------------------------------------------------- # if __name__ == '__main__': <<<<<<< HEAD random.seed(SEED) parser = argparse.ArgumentParser( description='Run a Monte Carlo Tree Search agent on the Cartpole environment', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--env_id', nargs='?', default=ENVIRONMENT, help='The environment to run (only CartPole-v0 is supperted)') parser.add_argument('--episodes', nargs='?', default=EPISODES, type=int, help='The number of episodes to run.') parser.add_argument('--iteration_budget', nargs='?', default=ITERATION_BUDGET, type=int, help='The number of iterations for each search step. Increasing this should lead to better performance.') parser.add_argument('--lookahead_target', nargs='?', default=LOOKAHEAD_TARGET, type=int, help='The target number of steps the agent aims to look forward.') parser.add_argument('--max_episode_steps', nargs='?', default=MAX_EPISODE_STEPS, type=int, help='The maximum number of steps to play.') parser.add_argument('--video_basepath', nargs='?', default=VIDEO_BASEPATH, help='The basepath where the videos will be stored.') parser.add_argument('--start_cp', nargs='?', default=START_CP, type=int, help='The start value of C_p, the value that the agent changes to try to achieve the lookahead target. Decreasing this makes the search tree deeper, increasing this makes the search tree wider.') parser.add_argument('--seed', nargs='?', default=SEED, type=int, help='The random seed.') args = parser.parse_args() logger.set_level(LOGGER_LEVEL) env = gym.make(args.env_id) env.seed(args.seed) agent = MCTSAgent(args.iteration_budget, args.env_id) ======= logger.set_level(LOGGER_LEVEL) random.seed(args.seed) env = gym.make(args.env_name) env.seed(args.seed) Q_net = dqn_agent() agent = MCTSAgent(args.iteration_budget, env, Q_net) >>>>>>> MCTS timestr = time.strftime("%Y%m%d-%H%M%S") reward = 0 done = False for i in range(args.episodes): ob = env.reset() env._max_episode_steps = args.max_episode_steps video_path = os.path.join( args.video_basepath, f"output_{timestr}_{i}.mp4") <<<<<<< HEAD rec = VideoRecorder(env, path=video_path) ======= # rec = VideoRecorder(env, path=video_path) >>>>>>> MCTS try: sum_reward = 0 node = None all_nodes = [] C_p = args.start_cp while True: print("################") env.render() <<<<<<< HEAD rec.capture_frame() ======= # rec.capture_frame() >>>>>>> MCTS action, node, C_p = agent.act(env.state, n_actions=env.action_space.n, node=node, C_p=C_p, lookahead_target=args.lookahead_target) ob, reward, done, _ = env.step(action) print("### observed state: ", ob) sum_reward += reward print("### sum_reward: ", sum_reward) if done: <<<<<<< HEAD rec.close() break except KeyboardInterrupt as e: rec.close() ======= # rec.close() break except KeyboardInterrupt as e: # rec.close() >>>>>>> MCTS env.close() raise e env.close()
[ 2, 422, 3740, 1378, 12567, 13, 785, 14, 74, 85, 21638, 263, 6559, 14, 76, 310, 82, 12, 26674, 36869, 198, 2, 16529, 10541, 1303, 198, 2, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, ...
2.416355
2,409
from django_cron import CronJobBase, Schedule
[ 6738, 42625, 14208, 62, 66, 1313, 1330, 31683, 33308, 14881, 11, 19281, 628 ]
3.615385
13
import ASV from simpletal import simpleTAL, simpleTALES try: import logging except: import InfoLogging as logging import codecs
[ 11748, 7054, 53, 198, 198, 6738, 2829, 39240, 1330, 2829, 51, 1847, 11, 2829, 51, 1847, 1546, 198, 198, 28311, 25, 198, 197, 11748, 18931, 198, 16341, 25, 198, 197, 11748, 14151, 11187, 2667, 355, 18931, 198, 198, 11748, 40481, 82, 19...
3.022222
45
from django.forms import BooleanField, ValidationError from django.utils.timezone import now from django.utils.translation import gettext as _ from .models import WagtailAdminModelForm
[ 6738, 42625, 14208, 13, 23914, 1330, 41146, 15878, 11, 3254, 24765, 12331, 198, 6738, 42625, 14208, 13, 26791, 13, 2435, 11340, 1330, 783, 198, 6738, 42625, 14208, 13, 26791, 13, 41519, 1330, 651, 5239, 355, 4808, 198, 198, 6738, 764, 2...
3.836735
49
import os from sqlalchemy.orm import Session from db.database import SessionLocal
[ 11748, 28686, 198, 198, 6738, 44161, 282, 26599, 13, 579, 1330, 23575, 198, 198, 6738, 20613, 13, 48806, 1330, 23575, 14565, 628, 628, 628 ]
3.708333
24
#!/usr/bin/python # -*- coding:utf-8 -*- print("hello world") f = None try: f = open("./hello.txt","r",encoding="utf8") print(f.read(5),end='') print(f.read(5),end='') print(f.read(5)) except IOError as e: print(e) finally: if f: f.close() # with auto call the methods' close with open("./hello.txt","r",encoding="utf8") as f: print(f.read()) # readlines() with open("./hello.txt","r",encoding="utf8") as f: for line in f.readlines(): print(line.strip()) # with open("./hello_1.txt","w",encoding="utf8") as f: f.write("!") with open("./hello.txt","a",encoding="utf8") as f: f.write(" 70!") # StringIO / BytesIO from io import StringIO # str = StringIO('init') # while True: s = str.readline() if s == '': break print(s.strip()) # str.write("!") str.write(" ") # print(str.getvalue()) ''' while True: s = str.readline() if s == '': break print(s.strip()) ''' # from io import BytesIO bi = BytesIO() bi.write("".encode("utf-8")) print(bi.getvalue()) by = BytesIO(b'\xe4\xbd\xa0\xe5\xa5\xbd') print(by.read()) # OS import os # nt print(os.name) # python <module 'ntpath' from 'G:\\python-3.7\\lib\\ntpath.py'> print(os.path) # print(os.environ) # 'bobol' print(os.getlogin()) # os.mkdir("./foo/") # os.rmdir("./foo/") ''' os.path ''' # 'G:\\pythonDemo\\python-demo\\five' print(os.path.abspath("./")) # False print(os.path.exists("./foo")) # 4096 print(os.path.getsize("../")) # False print(os.path.isabs("../"))
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 532, 9, 12, 19617, 25, 40477, 12, 23, 532, 9, 12, 198, 198, 4798, 7203, 31373, 995, 4943, 198, 198, 69, 796, 6045, 198, 28311, 25, 198, 220, 220, 220, 277, 796, 1280, 7, 1911, 14, ...
2.030928
776
# Copyright (c) 2009-2020, quasardb SAS. All rights reserved. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of quasardb nor the names of its contributors may # be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY QUASARDB AND CONTRIBUTORS ``AS IS'' AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # from __future__ import print_function from builtins import range as xrange, int import os from socket import gethostname import sys import inspect import traceback import random import time import datetime import locale import numpy as np import quasardb STOCK_COLUMN = "stock_id" OPEN_COLUMN = "open" CLOSE_COLUMN = "close" HIGH_COLUMN = "high" LOW_COLUMN = "low" VOLUME_COLUMN = "volume" if __name__ == "__main__": try: if len(sys.argv) != 3: print("usage: ", sys.argv[0], " quasardb_uri points_count") sys.exit(1) main(sys.argv[1], int(sys.argv[2])) except Exception as ex: # pylint: disable=W0703 print("An error ocurred:", str(ex)) traceback.print_exc()
[ 2, 15069, 357, 66, 8, 3717, 12, 42334, 11, 627, 292, 446, 65, 35516, 13, 1439, 2489, 10395, 13, 198, 2, 1439, 2489, 10395, 13, 198, 2, 198, 2, 2297, 396, 3890, 290, 779, 287, 2723, 290, 13934, 5107, 11, 351, 393, 1231, 198, 2, ...
3.01581
759
from nerwhal.backends.flashtext_backend import FlashtextBackend from nerwhal.recognizer_bases import FlashtextRecognizer
[ 6738, 17156, 1929, 282, 13, 1891, 2412, 13, 34167, 5239, 62, 1891, 437, 1330, 9973, 5239, 7282, 437, 198, 6738, 17156, 1929, 282, 13, 26243, 7509, 62, 65, 1386, 1330, 9973, 5239, 6690, 2360, 7509, 628, 628 ]
3.351351
37
import boto3 import sys import time import logging import getpass dbname = sys.argv[1] instanceID = sys.argv[2] storage = sys.argv[3] dbInstancetype = sys.argv[4] dbusername = sys.argv[5] new_rdsmysql(dbname, instanceID, storage, dbInstancetype, dbusername)
[ 11748, 275, 2069, 18, 198, 11748, 25064, 198, 11748, 640, 198, 11748, 18931, 198, 11748, 651, 6603, 198, 198, 9945, 3672, 796, 25064, 13, 853, 85, 58, 16, 60, 198, 39098, 2389, 796, 25064, 13, 853, 85, 58, 17, 60, 198, 35350, 796, ...
2.539216
102
import random import requests from api.block_api import BlockApi from exception.tzscan import TzScanException from log_config import main_logger logger = main_logger HEAD_API = {'MAINNET': {'HEAD_API_URL': 'https://api%MIRROR%.tzscan.io/v2/head'}, 'ALPHANET': {'HEAD_API_URL': 'http://api.alphanet.tzscan.io/v2/head'}, 'ZERONET': {'HEAD_API_URL': 'http://api.zeronet.tzscan.io/v2/head'} } REVELATION_API = {'MAINNET': {'HEAD_API_URL': 'https://api%MIRROR%.tzscan.io/v1/operations/%PKH%?type=Reveal'}, 'ALPHANET': {'HEAD_API_URL': 'https://api.alphanet.tzscan.io/v1/operations/%PKH%?type=Reveal'}, 'ZERONET': {'HEAD_API_URL': 'https://api.zeronet.tzscan.io/v1/operations/%PKH%?type=Reveal'} } if __name__ == '__main__': test_get_revelation()
[ 11748, 4738, 198, 198, 11748, 7007, 198, 6738, 40391, 13, 9967, 62, 15042, 1330, 9726, 32, 14415, 198, 6738, 6631, 13, 22877, 35836, 1330, 309, 89, 33351, 16922, 198, 198, 6738, 2604, 62, 11250, 1330, 1388, 62, 6404, 1362, 198, 198, 6...
2.021635
416
import pytest import cudf import mock from cuxfilter.charts.core.non_aggregate.core_non_aggregate import ( BaseNonAggregate, ) from cuxfilter.dashboard import DashBoard from cuxfilter import DataFrame from cuxfilter.layouts import chart_view
[ 11748, 12972, 9288, 198, 11748, 269, 463, 69, 198, 11748, 15290, 198, 198, 6738, 269, 2821, 24455, 13, 354, 5889, 13, 7295, 13, 13159, 62, 9460, 49373, 13, 7295, 62, 13159, 62, 9460, 49373, 1330, 357, 198, 220, 220, 220, 7308, 15419, ...
3.139241
79
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 5366, 13, 26791, 1330, 4818, 8079, 62, 26791, 355, 4818, 8079, 198, 6738, 5366, 13, 9945, 1330, 20613, 198, 6738, 5366, 13, 85, 17, 1330, 10011, 2611, 44, 4254, ...
3.113208
53
#!/usr/bin/env python # Copyright (C) 2013-2016 by Yu-Jie Lin # # 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. """ ============ b.py command ============ Commands ======== ============= ======================= command supported services ============= ======================= ``blogs`` ``b`` ``post`` ``b``, ``wp`` ``generate`` ``base``, ``b``, ``wp`` ``checklink`` ``base``, ``b``, ``wp`` ``search`` ``b`` ============= ======================= Descriptions: ``blogs`` list blogs. This can be used for blog IDs lookup. ``post`` post or update a blog post. ``generate`` generate HTML file at ``<TEMP>/draft.html``, where ``<TEMP>`` is the system's temporary directory. The generation can output a preview html at ``<TEMP>/preview.html`` if there is ``tmpl.html``. It will replace ``%%Title%%`` with post title and ``%%Content%%`` with generated HTML. ``checklink`` check links in generated HTML using lnkckr_. ``search`` search blog .. _lnkckr: https://pypi.python.org/pypi/lnkckr """ from __future__ import print_function import argparse as ap import codecs import imp import logging import os import sys import traceback from bpy.handlers import handlers from bpy.services import find_service, services __program__ = 'b.py' __description__ = 'Post to Blogger or WordPress in markup language seamlessly' __copyright__ = 'Copyright 2013-2016, Yu Jie Lin' __license__ = 'MIT License' __version__ = '0.11.0' __website__ = 'http://bitbucket.org/livibetter/b.py' __author__ = 'Yu-Jie Lin' __author_email__ = 'livibetter@gmail.com' # b.py stuff ############ # filename of local configuration without '.py' suffix. BRC = 'brc' if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 15069, 357, 34, 8, 2211, 12, 5304, 416, 10605, 12, 41, 494, 5164, 198, 2, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 257, 4866, 198, ...
3.288299
829
# -*- coding: utf-8 -*- # # Copyright Spyder Project Contributors # Licensed under the terms of the MIT License # (see spyder/__init__.py for details) """Outline explorer API. You need to declare a OutlineExplorerProxy, and a function for handle the edit_goto Signal. class OutlineExplorerProxyCustom(OutlineExplorerProxy): ... def handle_go_to(name, line, text): ... outlineexplorer = OutlineExplorerWidget(None) oe_proxy = OutlineExplorerProxyCustom(name) outlineexplorer.set_current_editor(oe_proxy, update=True, clear=False) outlineexplorer.edit_goto.connect(handle_go_to) """ import re from qtpy.QtCore import Signal, QObject from qtpy.QtGui import QTextBlock from spyder.config.base import _ from spyder.config.base import running_under_pytest def is_cell_header(block): """Check if the given block is a cell header.""" if not block.isValid(): return False data = block.userData() return (data and data.oedata and data.oedata.def_type == OutlineExplorerData.CELL) def cell_index(block): """Get the cell index of the given block.""" index = len(list(document_cells(block, forward=False))) if is_cell_header(block): return index + 1 return index def cell_name(block): """ Get the cell name the block is in. If the cell is unnamed, return the cell index instead. """ if is_cell_header(block): header = block.userData().oedata else: try: header = next(document_cells(block, forward=False)) except StopIteration: # This cell has no header, so it is the first cell. return 0 if header.has_name(): return header.def_name else: # No name, return the index return cell_index(block) def is_valid(self): """Check if the oedata has a valid block attached.""" block = self.block return (block and block.isValid() and block.userData() and hasattr(block.userData(), 'oedata') and block.userData().oedata == self ) def has_name(self): """Check if cell has a name.""" if self._def_name: return True else: return False def get_block_number(self): """Get the block number.""" if not self.is_valid(): # Avoid calling blockNumber if not a valid block return None return self.block.blockNumber()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 15069, 220, 23688, 1082, 4935, 25767, 669, 198, 2, 49962, 739, 262, 2846, 286, 262, 17168, 13789, 198, 2, 357, 3826, 13997, 1082, 14, 834, 15003, 834, 13, ...
2.420444
1,037
import weakref from .mount import mountmanager from .macro_mode import get_macro_mode, macro_mode_on from . import cell as cell_module from .cell import Cell, cell from . import context as context_module from .context import Context, context from .worker import Worker from .transformer import Transformer, transformer from .structured_cell import StructuredCell, Inchannel, Outchannel from .macro import Macro, macro, path from .reactor import Reactor, reactor from .unilink import unilink
[ 11748, 4939, 5420, 198, 198, 6738, 764, 14948, 1330, 3817, 37153, 198, 6738, 764, 20285, 305, 62, 14171, 1330, 651, 62, 20285, 305, 62, 14171, 11, 15021, 62, 14171, 62, 261, 198, 6738, 764, 1330, 2685, 355, 2685, 62, 21412, 198, 6738,...
3.806202
129
import os import re import sys from oguilem.configuration.fitness import OGUILEMFitnessFunctionConfiguration from oguilem.configuration.ga import OGUILEMGlobOptConfig from oguilem.configuration.geometry import OGUILEMGeometryConfig from oguilem.configuration.utils import ConnectedValue, ConfigFileManager from oguilem.resources import options
[ 11748, 28686, 198, 11748, 302, 198, 11748, 25064, 198, 198, 6738, 267, 5162, 576, 76, 13, 11250, 3924, 13, 69, 3659, 1330, 34498, 10080, 2538, 49800, 3659, 22203, 38149, 198, 6738, 267, 5162, 576, 76, 13, 11250, 3924, 13, 4908, 1330, ...
3.465347
101
from __future__ import (division, print_function) import matplotlib.cm as cmx import matplotlib.colors as colors from matplotlib import gridspec from metadatastore.api import db_connect as mds_db_connect from filestore.api import db_connect as fs_db_connect fs_db_connect( **{'database': 'data-processing-dev', 'host': 'localhost', 'port': 27017}) mds_db_connect( **{'database': 'data-processing-dev', 'host': 'localhost', 'port': 27017}) from databroker import db, get_events from datamuxer import DataMuxer from sidewinder_spec.utils.handlers import * import logging from xpd_workflow.parsers import parse_xrd_standard logger = logging.getLogger(__name__) if __name__ == '__main__': import os import numpy as np import matplotlib.pyplot as plt save = True lam = 1.54059 # Standard reflections for sample components niox_hkl = ['111', '200', '220', '311', '222', '400', '331', '420', '422', '511'] niox_tth = np.asarray( [37.44, 43.47, 63.20, 75.37, 79.87, 95.58, 106.72, 111.84, 129.98, 148.68]) pr3_hkl = ['100', '001', '110', '101', '111', '200', '002', '210', '211', '112', '202'] pr3_tth = np.asarray( [22.96, 24.33, 32.70, 33.70, 41.18, 46.92, 49.86, 52.86, 59.00, 60.91, 70.87] ) pr4_hkl = ['111', '113', '008', '117', '200', '119', '028', '0014', '220', '131', '1115', '0214', '317', '31Na', '2214', '040', '400'] pr4_tth = np.asarray( [23.43, 25.16, 25.86, 32.62, 33.36, 37.67, 42.19, 46.11, 47.44, 53.18, 55.55, 57.72, 59.10, 59.27, 68.25, 68.71, 70.00] ) pr2_tth, pr2int, pr2_hkl = parse_xrd_standard( '/mnt/bulk-data/research_data/Pr2NiO4orthorhombicPDF#97-008-1577.txt') pr2_tth = pr2_tth[pr2int > 5.] prox_hkl = ['111', '200', '220', '311', '222', '400', '331', '420', '422', '511', '440', '531', '600'] prox_tth = np.asarray( [28.25, 32.74, 46.99, 55.71, 58.43, 68.59, 75.73, 78.08, 87.27, 94.12, 105.63, 112.90, 115.42] ) standard_names = [ # 'NiO', 'Pr3Ni2O7', 'Pr2NiO4', # 'Pr4' 'Pr6O11' ] master_hkl = [ # niox_hkl, pr3_hkl, pr2_hkl, # pr4_hkl prox_hkl ] master_tth = [ # niox_tth, pr3_tth, pr2_tth, # pr4_tth prox_tth ] color_map = [ # 'red', 'blue', 'black', 'red' ] line_style = ['--', '-.', ':', ] ns = [1, 2, 3, 4, 5, # 18, 20, 22, 16, 28, 29, 27, 26 ] # ns = [26] ns.sort() # for i in ns: legended_hkl = [] print(i) folder = '/mnt/bulk-data/research_data/USC_beamtime/APS_March_2016/S' + str( i) + '/temp_exp' hdr = db(run_folder=folder)[0] dm = DataMuxer() dm.append_events(get_events(hdr)) df = dm.to_sparse_dataframe() print(df.keys()) binned = dm.bin_on('img', interpolation={'T': 'linear'}) # key_list = [f for f in os.listdir(folder) if # f.endswith('.gr') and not f.startswith('d')] key_list = [f for f in os.listdir(folder) if f.endswith('.chi') and not f.startswith('d') and f.strip( '0.chi') != '' and int( f.lstrip('0').strip('.chi')) % 2 == 1] key_list.sort() key_list = key_list[:-1] # key_list2.sort() idxs = [int(os.path.splitext(f)[0]) for f in key_list] Ts = binned['T'].values[idxs] output = os.path.splitext(key_list[0])[-1][1:] if key_list[0].endswith('.gr'): offset = .1 skr = 0 else: skr = 8 offset = .001 data_list = [(np.loadtxt(os.path.join(folder, f), skiprows=skr )[:, 0], np.loadtxt(os.path.join(folder, f), skiprows=skr )[:, 1]) for f in key_list] ylim_min = None for xmax, length in zip( [len(data_list[0][0]) - 1, len(data_list[0][0]) - 1], ['short', 'full']): fig = plt.figure(figsize=(26, 12)) gs = gridspec.GridSpec(1, 2, width_ratios=[5, 1]) ax1 = plt.subplot(gs[0]) if length == 'short': ax1.set_xlim(1.5, 4.5) ax2 = plt.subplot(gs[1], sharey=ax1) plt.setp(ax2.get_yticklabels(), visible=False) cm = plt.get_cmap('viridis') cNorm = colors.Normalize(vmin=0, vmax=len(key_list)) scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=cm) for idx in range(len(key_list)): xnm, y = data_list[idx] colorVal = scalarMap.to_rgba(idx) if output == 'chi': x = xnm / 10. ax1.plot(x[:xmax], y[:xmax] + idx * offset, color=colorVal) ax2.plot(Ts[idx], y[-1] + idx * offset, marker='o', color=colorVal) if ylim_min is None or ylim_min > np.min( y[:xmax + idx * offset]): ylim_min = np.min(y[:xmax + idx * offset]) ax2.set_xticklabels([str(f) for f in ax2.get_xticks()], rotation=90) if output == 'gr': bnds = ['O-Pr', 'O-Ni', 'Ni-Ni', 'Pr-Pr', 'Ni-Pr', 'O-Pr', 'O-Ni', 'Ni-Ni-Ni', 'Pr-Ni', 'Pr-Pr', 'Pr-Ni-O', 'Ni-Pr-Ni', 'Pr-Pr', 'Rs:Pr-Pr', 'Rs:Pr_Pr'] bnd_lens = [2.320, 1.955, 3.883, 3.765, 3.186, 2.771, 2.231, 7.767, 4.426, 6.649, 4.989, 5.404, 3.374, 3.910, 8.801] # ax1.grid(True) # ax2.grid(True) for bnd, bnd_len in zip(bnds, bnd_lens): ax1.axvline(bnd_len, color='grey', linestyle='--') ax3 = ax1.twiny() ax3.set_xticks(np.asarray(bnd_lens) / x[xmax]) ax3.set_xticklabels(bnds, rotation=90) else: std_axis = [] for n, hkls, tths, color, ls in zip(standard_names, master_hkl, master_tth, color_map, line_style): std_axis.append(ax1.twiny()) ax3 = std_axis[-1] hkl_q = np.pi * 4 * np.sin(np.deg2rad(tths / 2)) / lam for k, (hkl, q) in enumerate(zip(hkls, hkl_q)): if n not in legended_hkl: ax1.axvline(q, color=color, linestyle=ls, lw=2, label=n ) legended_hkl.append(n) else: ax1.axvline(q, color=color, linestyle=ls, lw=2, ) a = hkl_q > ax1.get_xlim()[0] b = hkl_q < ax1.get_xlim()[1] c = a & b ax3.set_xticks(list((hkl_q[c] - ax1.get_xlim()[0]) / ( ax1.get_xlim()[1] - ax1.get_xlim()[0]) )) ax3.set_xticklabels(hkls, rotation=90, color=color) ax2.set_xlabel('Temperature C') if output == 'gr': fig.suptitle('S{} PDF'.format(i)) ax1.set_xlabel(r"$r (\AA)$") ax1.set_ylabel(r"$G (\AA^{-2})$") elif output == 'chi': fig.suptitle('S{} I(Q)'.format(i)) ax1.set_xlabel(r"$Q (\AA^{-1})$") ax1.set_ylabel(r"$I (Q) $") ax1.set_ylim(ylim_min) ax1.legend() gs.tight_layout(fig, rect=[0, 0, 1, .98], w_pad=1e-6) if save: fig.savefig(os.path.join('/mnt/bulk-data/Dropbox/', 'S{}_{}_output_{}.png'.format( i, length, output))) fig.savefig(os.path.join('/mnt/bulk-data/Dropbox/', 'S{}_{}_output_{}.eps'.format( i, length, output))) else: plt.show()
[ 6738, 11593, 37443, 834, 1330, 357, 21426, 11, 3601, 62, 8818, 8, 198, 198, 11748, 2603, 29487, 8019, 13, 11215, 355, 12067, 87, 198, 11748, 2603, 29487, 8019, 13, 4033, 669, 355, 7577, 198, 6738, 2603, 29487, 8019, 1330, 50000, 43106, ...
1.596955
5,451
from __future__ import unicode_literals import copy import json from six import string_types from . import default_operators from . import sql_prepare from . import values from .error import WinnowError from .templating import SqlFragment from .templating import WinnowSql
[ 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 11748, 4866, 198, 11748, 33918, 198, 198, 6738, 2237, 1330, 4731, 62, 19199, 198, 198, 6738, 764, 1330, 4277, 62, 3575, 2024, 198, 6738, 764, 1330, 44161, 62, 46012, ...
3.538462
78
import regex as re import time import collections import datetime import six import pandas as pd import google.cloud.bigquery as bq from multipledispatch import Dispatcher import ibis import ibis.common as com import ibis.expr.operations as ops import ibis.expr.types as ir import ibis.expr.schema as sch import ibis.expr.datatypes as dt import ibis.expr.lineage as lin from ibis.compat import parse_version from ibis.client import Database, Query, SQLClient from ibis.bigquery import compiler as comp from google.api.core.exceptions import BadRequest NATIVE_PARTITION_COL = '_PARTITIONTIME' _IBIS_TYPE_TO_DTYPE = { 'string': 'STRING', 'int64': 'INT64', 'double': 'FLOAT64', 'boolean': 'BOOL', 'timestamp': 'TIMESTAMP', 'date': 'DATE', } _DTYPE_TO_IBIS_TYPE = { 'INT64': dt.int64, 'FLOAT64': dt.double, 'BOOL': dt.boolean, 'STRING': dt.string, 'DATE': dt.date, # FIXME: enforce no tz info 'DATETIME': dt.timestamp, 'TIME': dt.time, 'TIMESTAMP': dt.timestamp, 'BYTES': dt.binary, } _LEGACY_TO_STANDARD = { 'INTEGER': 'INT64', 'FLOAT': 'FLOAT64', 'BOOLEAN': 'BOOL', } class BigQueryCursor(object): """Cursor to allow the BigQuery client to reuse machinery in ibis/client.py """ def _find_scalar_parameter(expr): """:func:`~ibis.expr.lineage.traverse` function to find all :class:`~ibis.expr.types.ScalarParameter` instances and yield the operation and the parent expresssion's resolved name. Parameters ---------- expr : ibis.expr.types.Expr Returns ------- Tuple[bool, object] """ op = expr.op() if isinstance(op, ops.ScalarParameter): result = op, expr.get_name() else: result = None return lin.proceed, result class BigQueryQuery(Query): class BigQueryAPIProxy(object): def get_datasets(self): return list(self.client.list_datasets()) def get_dataset(self, dataset_id): return self.client.dataset(dataset_id) def get_table(self, table_id, dataset_id, reload=True): (table_id, dataset_id) = _ensure_split(table_id, dataset_id) table = self.client.dataset(dataset_id).table(table_id) if reload: table.reload() return table def get_schema(self, table_id, dataset_id): return self.get_table(table_id, dataset_id).schema def run_sync_query(self, stmt): query = self.client.run_sync_query(stmt) query.use_legacy_sql = False query.run() # run_sync_query is not really synchronous: there's a timeout while not query.job.done(): query.job.reload() time.sleep(0.1) return query class BigQueryDatabase(Database): pass bigquery_param = Dispatcher('bigquery_param') class BigQueryClient(SQLClient): sync_query = BigQueryQuery database_class = BigQueryDatabase proxy_class = BigQueryAPIProxy dialect = comp.BigQueryDialect def table(self, *args, **kwargs): t = super(BigQueryClient, self).table(*args, **kwargs) if NATIVE_PARTITION_COL in t.columns: col = ibis.options.bigquery.partition_col assert col not in t return (t .mutate(**{col: t[NATIVE_PARTITION_COL]}) .drop([NATIVE_PARTITION_COL])) return t def _build_ast(self, expr, context): result = comp.build_ast(expr, context) return result def _execute_query(self, dml, async=False): klass = self.async_query if async else self.sync_query inst = klass(self, dml, query_parameters=dml.context.params) df = inst.execute() return df def _fully_qualified_name(self, name, database): dataset_id = database or self.dataset_id return dataset_id + '.' + name def _get_table_schema(self, qualified_name): return self.get_schema(qualified_name) def _execute(self, stmt, results=True, query_parameters=None): # TODO(phillipc): Allow **kwargs in calls to execute query = self._proxy.client.run_sync_query(stmt) query.use_legacy_sql = False query.query_parameters = query_parameters or [] query.run() # run_sync_query is not really synchronous: there's a timeout while not query.job.done(): query.job.reload() time.sleep(0.1) return BigQueryCursor(query) def database(self, name=None): if name is None: name = self.dataset_id return self.database_class(name, self) _DTYPE_TO_IBIS_TYPE = { 'INT64': dt.int64, 'FLOAT64': dt.double, 'BOOL': dt.boolean, 'STRING': dt.string, 'DATE': dt.date, # FIXME: enforce no tz info 'DATETIME': dt.timestamp, 'TIME': dt.time, 'TIMESTAMP': dt.timestamp, 'BYTES': dt.binary, } _LEGACY_TO_STANDARD = { 'INTEGER': 'INT64', 'FLOAT': 'FLOAT64', 'BOOLEAN': 'BOOL', }
[ 11748, 40364, 355, 302, 198, 11748, 640, 198, 11748, 17268, 198, 11748, 4818, 8079, 198, 198, 11748, 2237, 198, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 23645, 13, 17721, 13, 14261, 22766, 355, 275, 80, 198, 198, 6738, 5021, ...
2.283295
2,185
from math import log, ceil
[ 6738, 10688, 1330, 2604, 11, 2906, 346 ]
3.714286
7
import numpy as np import ROOT from dummy_distributions import dummy_pt_eta counts, test_in1, test_in2 = dummy_pt_eta() f = ROOT.TFile.Open("samples/testSF2d.root") sf = f.Get("scalefactors_Tight_Electron") xmin, xmax = sf.GetXaxis().GetXmin(), sf.GetXaxis().GetXmax() ymin, ymax = sf.GetYaxis().GetXmin(), sf.GetYaxis().GetXmax() test_out = np.empty_like(test_in1) for i, (eta, pt) in enumerate(zip(test_in1, test_in2)): if xmax <= eta: eta = xmax - 1.0e-5 elif eta < xmin: eta = xmin if ymax <= pt: pt = ymax - 1.0e-5 elif pt < ymin: pt = ymin ib = sf.FindBin(eta, pt) test_out[i] = sf.GetBinContent(ib) print(repr(test_out))
[ 11748, 299, 32152, 355, 45941, 198, 11748, 15107, 2394, 198, 198, 6738, 31548, 62, 17080, 2455, 507, 1330, 31548, 62, 457, 62, 17167, 198, 198, 9127, 82, 11, 1332, 62, 259, 16, 11, 1332, 62, 259, 17, 796, 31548, 62, 457, 62, 17167, ...
2
345
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Mar 14 17:42:27 2018 @author: zgeorg03 """ import re import json # Used for converting json to dictionary import datetime # Used for date conversions import matplotlib.pyplot as plt import numpy as np from sentiment import Sentiment import json if __name__ == '__main__': file_name = "./log" #max_articles = 1000 p = Parser(file_name,file_out='data-26-04.json') p.parse() p.write() print('Finished')
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 3300, 1526, 1478, 1596, 25, 3682, 25, 1983, 2864, 198, 198, 31, 9800, 25, 1976, 469, 2398...
2.442922
219
"""Recursive implementations.""" def find_max(A): """invoke recursive function to find maximum value in A.""" def rmax(lo, hi): """Use recursion to find maximum value in A[lo:hi+1].""" if lo == hi: return A[lo] mid = (lo+hi) // 2 L = rmax(lo, mid) R = rmax(mid+1, hi) return max(L, R) return rmax(0, len(A)-1) def find_max_with_count(A): """Count number of comparisons.""" def frmax(lo, hi): """Use recursion to find maximum value in A[lo:hi+1] incl. count""" if lo == hi: return (0, A[lo]) mid = (lo+hi)//2 ctleft,left = frmax(lo, mid) ctright,right = frmax(mid+1, hi) return (1+ctleft+ctright, max(left, right)) return frmax(0, len(A)-1) def count(A,target): """invoke recursive function to return number of times target appears in A.""" def rcount(lo, hi, target): """Use recursion to find maximum value in A[lo:hi+1].""" if lo == hi: return 1 if A[lo] == target else 0 mid = (lo+hi)//2 left = rcount(lo, mid, target) right = rcount(mid+1, hi, target) return left + right return rcount(0, len(A)-1, target)
[ 37811, 6690, 30753, 25504, 526, 15931, 198, 198, 4299, 1064, 62, 9806, 7, 32, 2599, 198, 220, 220, 220, 37227, 37669, 45115, 2163, 284, 1064, 5415, 1988, 287, 317, 526, 15931, 628, 220, 220, 220, 825, 374, 9806, 7, 5439, 11, 23105, ...
2.207273
550
#from distutils.core import setup from setuptools import setup, find_packages from distutils.extension import Extension import re import os import codecs here = os.path.abspath(os.path.dirname(__file__)) try: from Cython.Distutils import build_ext except ImportError: use_cython = False else: use_cython = True cmdclass = { } ext_modules = [ ] if use_cython: ext_modules += [ Extension("deepgmap.data_preprocessing_tools.seq_to_binary2", [ "deepgmap/data_preprocessing_tools/seq_to_binary2.pyx" ]), #Extension("data_preprocessing_tools.queue", [ "deepgmap/data_preprocessing_tools/queue.pyx" ],libraries=["calg"]), Extension("deepgmap.post_train_tools.cython_util", [ "deepgmap/post_train_tools/cython_util.pyx" ]), ] cmdclass.update({ 'build_ext': build_ext }) else: ext_modules += [ Extension("deepgmap.data_preprocessing_tools.seq_to_binary2", [ "deepgmap/data_preprocessing_tools/seq_to_binary2.c" ]), Extension("deepgmap.post_train_tools.cython_util", [ "deepgmap/post_train_tools/cython_util.c" ]), ] #print(find_version("deepgmap", "__init__.py")) setup( name='DeepGMAP', #version=VERSION, version=find_version("deepgmap", "__init__.py"), description='Learning and predicting gene regulatory sequences in genomes', author='Koh Onimaru', author_email='koh.onimaru@gmail.com', url='', packages=['deepgmap','deepgmap.train','deepgmap.network_constructors','deepgmap.post_train_tools','deepgmap.data_preprocessing_tools','deepgmap.misc'], #packages=find_packages('deepgmap'), #packages=['deepgmap.'], package_dir={'DeepGMAP':'deepgmap'}, #package_data = { # '': ['enhancer_prediction/*', '*.pyx', '*.pxd', '*.c', '*.h'], #}, scripts=['bin/deepgmap', ], #packages=find_packages(), cmdclass = cmdclass, ext_modules=ext_modules, classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Intended Audience :: Developers', 'Programming Language :: Python :: 3.6', 'License :: OSI Approved :: Apache Software License ', 'Operating System :: POSIX :: Linux', 'Topic :: Scientific/Engineering :: Bio-Informatics', 'Topic :: Scientific/Engineering :: Artificial Intelligence', ], install_requires=['tensorflow>=1.15', 'numpy', 'matplotlib', 'sklearn', 'tornado', 'natsort', 'psutil', 'pyBigWig'], long_description=open('README.rst').read(), )
[ 2, 6738, 1233, 26791, 13, 7295, 1330, 9058, 198, 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 198, 6738, 1233, 26791, 13, 2302, 3004, 1330, 27995, 198, 11748, 302, 198, 11748, 28686, 198, 11748, 40481, 82, 198, 1456, 796, ...
2.493596
1,015
import logging from flask import Flask from flask_sqlalchemy import SQLAlchemy as _BaseSQLAlchemy from flask_migrate import Migrate from flask_cors import CORS from flask_talisman import Talisman from flask_ipban import IpBan from config import Config, get_logger_handler # database db = SQLAlchemy() migrate = Migrate() cors = CORS() talisman = Talisman() global_config = Config() ip_ban = IpBan(ban_seconds=200, ban_count=global_config.IP_BAN_LIST_COUNT) # logging logger = logging.getLogger('frontend') from api import models
[ 198, 11748, 18931, 198, 6738, 42903, 1330, 46947, 198, 6738, 42903, 62, 25410, 282, 26599, 1330, 16363, 2348, 26599, 355, 4808, 14881, 17861, 2348, 26599, 198, 6738, 42903, 62, 76, 42175, 1330, 337, 42175, 198, 6738, 42903, 62, 66, 669, ...
3.159763
169
# -*- coding: utf-8 -*- import os import csv import pymongo from pymongo.errors import DuplicateKeyError from settings import MONGO_HOST, MONGO_PORT, SAVE_ROOT
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 28686, 198, 11748, 269, 21370, 198, 11748, 279, 4948, 25162, 198, 6738, 279, 4948, 25162, 13, 48277, 1330, 49821, 5344, 9218, 12331, 198, 6738, 6460, 1330, 25000, 1...
2.745763
59
from pathlib import Path from requests.auth import _basic_auth_str import pytest from bravado_core.formatter import SwaggerFormat, NO_OP from gc3_query.lib.gc3_config import GC3Config, IDMCredential TEST_BASE_DIR: Path = Path(__file__).parent.joinpath("GC3Config") config_dir = TEST_BASE_DIR.joinpath("config") # @pytest.fixture() # def get_bravado_config_setup(): # gc3_config = GC3Config() # assert 'iaas_classic' in gc3_config # yield (gc3_config) # # def test_bravado_client_config(get_bravado_config_setup): # gc3_config = get_bravado_config_setup # assert 'iaas_classic' in gc3_config # bravado_client_config = gc3_config.bravado_client_config # assert bravado_client_config # assert 'formats' not in bravado_client_config # assert not 'include_missing_properties' in bravado_client_config # assert 'also_return_response' in bravado_client_config # bravado_client_config_2 = gc3_config.bravado_client_config # assert bravado_client_config==bravado_client_config_2 # assert bravado_client_config is not bravado_client_config_2 # assert isinstance(bravado_client_config, dict) # # def test_bravado_core_config(get_bravado_config_setup): # gc3_config = get_bravado_config_setup # assert 'iaas_classic' in gc3_config # bravado_core_config = gc3_config.bravado_core_config # assert bravado_core_config # assert 'formats' in bravado_core_config # assert 'include_missing_properties' in bravado_core_config # assert not 'also_return_response' in bravado_core_config # bravado_core_config_2 = gc3_config.bravado_core_config # assert bravado_core_config==bravado_core_config_2 # assert bravado_core_config is not bravado_core_config_2 # assert isinstance(bravado_core_config, dict) # assert isinstance(bravado_core_config['formats'], list) # # # # def test_bravado_config(get_bravado_config_setup): # gc3_config = get_bravado_config_setup # assert 'iaas_classic' in gc3_config # bravado_config = gc3_config.bravado_config # assert bravado_config # assert 'formats' in bravado_config # assert 'include_missing_properties' in bravado_config # assert 'also_return_response' in bravado_config # bravado_config_2 = gc3_config.bravado_config # assert bravado_config==bravado_config_2 # assert bravado_config is not bravado_config_2 # assert isinstance(bravado_config, dict) # assert isinstance(bravado_config['formats'], list) # # def test_BRAVADO_CONFIG(get_constants_setup): # gc3_config = get_constants_setup # bravado_config = gc3_config.BRAVADO_CONFIG # assert bravado_config # assert 'formats' in bravado_config # assert 'include_missing_properties' in bravado_config # assert 'also_return_response' in bravado_config # assert isinstance(bravado_config, dict) # assert isinstance(bravado_config['formats'], list) # assert bravado_config['formats'] # formats = [f.format for f in bravado_config['formats']] # assert 'json-bool' in formats # assert all([isinstance(i , SwaggerFormat) for i in bravado_config['formats']])
[ 6738, 3108, 8019, 1330, 10644, 198, 6738, 7007, 13, 18439, 1330, 4808, 35487, 62, 18439, 62, 2536, 198, 198, 11748, 12972, 9288, 198, 6738, 49025, 4533, 62, 7295, 13, 687, 1436, 1330, 2451, 7928, 26227, 11, 8005, 62, 3185, 198, 6738, ...
2.528698
1,237
import machine from machine import * import ssd1306 import time import socket import urequests as requests import json word = {'body':8} labels = ['c', 'o', 'l', 'u', 'm', 'b', 'i', 'a','null'] HOST = '18.218.158.249' PORT = 8080 flag = 0 stop = False data = {} xdata = [] ydata = [] n = 0 do_connect() switchA = machine.Pin(0, machine.Pin.IN, machine.Pin.PULL_UP) switchA.irq(trigger=machine.Pin.IRQ_RISING, handler=switchAcallback) switchC = machine.Pin(2, machine.Pin.IN, machine.Pin.PULL_UP) switchC.irq(trigger=machine.Pin.IRQ_RISING, handler=switchCcallback) spi = machine.SPI(1, baudrate=2000000, polarity=1, phase=1) cs = machine.Pin(15, machine.Pin.OUT) cs.value(0) spi.write(b'\x2d') spi.write(b'\x2b') cs.value(1) cs.value(0) spi.write(b'\x31') spi.write(b'\x0f') cs.value(1) i2c = machine.I2C(-1, machine.Pin(5), machine.Pin(4)) oled = ssd1306.SSD1306_I2C(128, 32, i2c) while True: x = 0 y = 0 sendstatus = "null" if (flag): cs.value(0) test1 = spi.read(5, 0xf2) cs.value(1) cs.value(0) test2 = spi.read(5, 0xf3) cs.value(1) cs.value(0) test3 = spi.read(5, 0xf4) cs.value(1) cs.value(0) test4 = spi.read(5, 0xf5) cs.value(1) x = dp(test2[1]) y = dp(test4[1]) xdata.append(x) ydata.append(y) sendstatus = "collect" + str(len(xdata)) + ' '+ ' ' + str(x) + ' ' + str(y) if send: word = sendData() sendstatus = "send success" flag = 0 send = False oled.fill(0) oled.text(labels[word['body']], 0, 0) oled.text(sendstatus, 0,10) oled.show()
[ 11748, 4572, 198, 6738, 4572, 1330, 1635, 198, 11748, 264, 21282, 12952, 21, 198, 11748, 640, 198, 11748, 17802, 198, 11748, 334, 8897, 3558, 355, 7007, 198, 11748, 33918, 198, 198, 4775, 796, 1391, 6, 2618, 10354, 23, 92, 198, 23912, ...
1.921412
878
from Geometry.VeryForwardGeometry.dd4hep.v5.geometryRPFromDD_2021_cfi import *
[ 6738, 2269, 15748, 13, 16371, 39746, 10082, 15748, 13, 1860, 19, 258, 79, 13, 85, 20, 13, 469, 15748, 20031, 4863, 16458, 62, 1238, 2481, 62, 66, 12463, 1330, 1635, 198 ]
2.548387
31
import argparse import matplotlib.pyplot as plt import torch from pytorch_warmup import * parser = argparse.ArgumentParser(description='Warmup schedule') parser.add_argument('--output', type=str, default='none', choices=['none', 'png', 'pdf'], help='Output file type (default: none)') args = parser.parse_args() beta2 = 0.999 max_step = 3000 plt.plot(range(1, max_step+1), get_rates(RAdamWarmup, beta2, max_step), label='RAdam') plt.plot(range(1, max_step+1), get_rates(UntunedExponentialWarmup, beta2, max_step), label='Untuned Exponential') plt.plot(range(1, max_step+1), get_rates(UntunedLinearWarmup, beta2, max_step), label='Untuned Linear') plt.legend() plt.title('Warmup Schedule') plt.xlabel('Iteration') plt.ylabel(r'Warmup factor $(\omega_t)$') if args.output == 'none': plt.show() else: plt.savefig(f'warmup_schedule.{args.output}')
[ 11748, 1822, 29572, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 28034, 198, 6738, 12972, 13165, 354, 62, 31975, 929, 1330, 1635, 628, 198, 198, 48610, 796, 1822, 29572, 13, 28100, 1713, 46677, 7, 11213, 116...
2.4375
368
"""\ This plugin merely enables other plugins to accept data over HTTP. If a plugin defines a module level function named "httpev" it will be invoked for POST requests to the url http://$hostname/event/$pluginname. The function is invoked from the thread in the web.py request context and as such has access to the full web.py API. """ import base64 import json import web web.config.debug = False def load(): s = Server() s.start() return s def unload(s): s.stop()
[ 37811, 59, 198, 1212, 13877, 6974, 13536, 584, 20652, 284, 2453, 1366, 625, 14626, 13, 1002, 198, 64, 13877, 15738, 257, 8265, 1241, 2163, 3706, 366, 2804, 431, 85, 1, 340, 481, 307, 198, 16340, 6545, 329, 24582, 7007, 284, 262, 19016...
3.286667
150
somaIdade = 0 maiorIdade = 0 nomeVelho = '' totmulher20 = 0 for p in range(1, 3): print('---- {} PESSOA ----'.format(p)) nome = str(input('Nome: ')).strip() idade = int(input('Idade: ')) sexo = str(input('Sexo [M/F]: ')) somaIdade += idade if p == 1 and sexo in 'Mm': maiorIdade = idade nomeVelho = nome if sexo in 'Mm' and idade > maiorIdade: maiorIdade = idade nomeVelho = nome if sexo in 'Ff' and idade < 20: totmulher20 += 1 mediaIdade = int(somaIdade / 4) print('A mdia de idade do grupo de pessoas de {} anos.'.format(mediaIdade)) print('O homem mais velho tem {} anos e se chama {}.'.format(maiorIdade, nomeVelho)) print('Ao todo so {} mulher com menos de 20 anos.'.format(totmulher20))
[ 82, 6086, 7390, 671, 796, 657, 198, 2611, 1504, 7390, 671, 796, 657, 198, 77, 462, 46261, 8873, 796, 10148, 198, 83, 313, 76, 377, 372, 1238, 796, 657, 198, 1640, 279, 287, 2837, 7, 16, 11, 513, 2599, 198, 220, 220, 220, 3601, 1...
2.142061
359
"""\ PROMORT example. """ import argparse import random import sys import pyecvl.ecvl as ecvl import pyeddl.eddl as eddl from pyeddl.tensor import Tensor import models if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("in_ds", metavar="INPUT_DATASET") parser.add_argument("--epochs", type=int, metavar="INT", default=50) parser.add_argument("--batch-size", type=int, metavar="INT", default=32) parser.add_argument("--gpu", action="store_true") parser.add_argument("--out-dir", metavar="DIR", help="if set, save images in this directory") main(parser.parse_args())
[ 37811, 59, 198, 4805, 2662, 9863, 1672, 13, 198, 37811, 198, 198, 11748, 1822, 29572, 198, 11748, 4738, 198, 11748, 25064, 198, 198, 11748, 12972, 721, 19279, 13, 721, 19279, 355, 9940, 19279, 198, 11748, 12972, 6048, 75, 13, 6048, 75, ...
2.55303
264
from src.view.services_page import ServicesPage from src.view.services_add_page import ServicesAddPage
[ 6738, 12351, 13, 1177, 13, 30416, 62, 7700, 1330, 6168, 9876, 198, 6738, 12351, 13, 1177, 13, 30416, 62, 2860, 62, 7700, 1330, 6168, 4550, 9876, 628, 220, 220, 220, 220, 220, 220, 220, 220 ]
3.2
35
import os import gettext import bisect from locale import getdefaultlocale from collections.abc import MutableMapping from copy import copy, deepcopy import six _trans = Trans() if six.PY2: else:
[ 11748, 28686, 198, 11748, 651, 5239, 198, 11748, 47457, 478, 198, 6738, 36693, 1330, 651, 12286, 17946, 1000, 198, 6738, 17268, 13, 39305, 1330, 13859, 540, 44, 5912, 198, 6738, 4866, 1330, 4866, 11, 2769, 30073, 198, 198, 11748, 2237, ...
3.215385
65
import socket s = socket.socket() s.bind(("localhost", 9999)) s.listen(1) sc, addr = s.accept() while True: recibido = sc.recv(1024) if recibido == "quit": break print "Recibido:", recibido sc.send(recibido) print "adios" sc.close() s.close()
[ 11748, 17802, 198, 198, 82, 796, 17802, 13, 44971, 3419, 198, 82, 13, 21653, 7, 7203, 36750, 1600, 860, 17032, 4008, 198, 82, 13, 4868, 268, 7, 16, 8, 198, 198, 1416, 11, 37817, 796, 264, 13, 13635, 3419, 198, 198, 4514, 6407, 25,...
2.176
125
import numpy import matplotlib.pyplot as plt import geojsoncontour # Create lat and lon vectors and grid data grid_size = 1.0 latrange = numpy.arange(-90.0, 90.0, grid_size) lonrange = numpy.arange(-180.0, 180.0, grid_size) X, Y = numpy.meshgrid(lonrange, latrange) Z = numpy.sqrt(X * X + Y * Y) n_contours = 10 levels = numpy.linspace(start=0, stop=100, num=n_contours) # Create a contour plot plot from grid (lat, lon) data figure = plt.figure() ax = figure.add_subplot(111) contour = ax.contour(lonrange, latrange, Z, levels=levels, cmap=plt.cm.jet) # Convert matplotlib contour to geojson geojsoncontour.contour_to_geojson( contour=contour, geojson_filepath='out.geojson', min_angle_deg=10.0, ndigits=3, unit='m' )
[ 11748, 299, 32152, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 4903, 13210, 1559, 3642, 454, 198, 198, 2, 13610, 3042, 290, 300, 261, 30104, 290, 10706, 1366, 198, 25928, 62, 7857, 796, 352, 13, 15, 198, ...
2.38141
312