content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
# project/main/views.py ################# #### imports #### ################# import os import json import requests import pickle from flask import Blueprint, Flask, jsonify, request, g, url_for, abort, redirect, flash, render_template, current_app from flask_login import current_user from flask_login import login_required from .forms import UploadForm from werkzeug.utils import secure_filename from project.indexer_lib import get_metadata_from_file ################ #### config #### ################ main_blueprint = Blueprint('main', __name__,) ################ #### routes #### ################
[ 2, 1628, 14, 12417, 14, 33571, 13, 9078, 628, 198, 14468, 2, 198, 4242, 17944, 1303, 21017, 198, 14468, 2, 198, 11748, 28686, 198, 11748, 33918, 198, 11748, 7007, 198, 11748, 2298, 293, 198, 6738, 42903, 1330, 39932, 11, 46947, 11, 33...
3.941935
155
import string from django import forms from django.conf import settings from django.shortcuts import get_object_or_404 from accounts.models import User, Profile from .models import Blogs from .utils import get_limit_for_level, write_to_limit
[ 11748, 4731, 198, 198, 6738, 42625, 14208, 1330, 5107, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 19509, 23779, 1330, 651, 62, 15252, 62, 273, 62, 26429, 198, 198, 6738, 5504, 13, 27530, 1330, 11787, 11...
3.528571
70
a = [1, 2, 3, 5, 6] # print(recursive_search(a, 3)) a = [3,4,5,6,10,12,20] print(binary_search(a, 5)) print(recursive_fibonacci(0))
[ 64, 796, 685, 16, 11, 362, 11, 513, 11, 642, 11, 718, 60, 198, 198, 2, 3601, 7, 8344, 30753, 62, 12947, 7, 64, 11, 513, 4008, 628, 628, 198, 64, 796, 685, 18, 11, 19, 11, 20, 11, 21, 11, 940, 11, 1065, 11, 1238, 60, 198, ...
1.918919
74
from heap.max_binary_heap import MaxBinaryHeap
[ 6738, 24575, 13, 9806, 62, 39491, 62, 258, 499, 1330, 5436, 33, 3219, 1544, 499 ]
3.066667
15
# -*- coding: utf-8 -*-
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12 ]
1.769231
13
# -*- coding: utf-8 -*- """Mock Kwik files.""" #------------------------------------------------------------------------------ # Imports #------------------------------------------------------------------------------ import os.path as op import numpy as np import numpy.random as nr from .mea import staggered_positions from .h5 import open_h5 from .model import _create_clustering #------------------------------------------------------------------------------ # Mock functions #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ # Mock Kwik file #------------------------------------------------------------------------------ def create_mock_kwik(dir_path, n_clusters=None, n_spikes=None, n_channels=None, n_features_per_channel=None, n_samples_traces=None, with_kwx=True, with_kwd=True, add_original=True, ): """Create a test kwik file.""" filename = op.join(dir_path, '_test.kwik') kwx_filename = op.join(dir_path, '_test.kwx') kwd_filename = op.join(dir_path, '_test.raw.kwd') # Create the kwik file. with open_h5(filename, 'w') as f: f.write_attr('/', 'kwik_version', 2) _write_metadata('sample_rate', 20000.) # Filter parameters. _write_metadata('filter_low', 500.) _write_metadata('filter_high_factor', 0.95 * .5) _write_metadata('filter_butter_order', 3) _write_metadata('extract_s_before', 15) _write_metadata('extract_s_after', 25) _write_metadata('n_features_per_channel', n_features_per_channel) # Create spike times. spike_samples = artificial_spike_samples(n_spikes).astype(np.int64) spike_recordings = np.zeros(n_spikes, dtype=np.uint16) # Size of the first recording. recording_size = 2 * n_spikes // 3 if recording_size > 0: # Find the recording offset. recording_offset = spike_samples[recording_size] recording_offset += spike_samples[recording_size + 1] recording_offset //= 2 spike_recordings[recording_size:] = 1 # Make sure the spike samples of the second recording start over. spike_samples[recording_size:] -= spike_samples[recording_size] spike_samples[recording_size:] += 10 else: recording_offset = 1 if spike_samples.max() >= n_samples_traces: raise ValueError("There are too many spikes: decrease 'n_spikes'.") f.write('/channel_groups/1/spikes/time_samples', spike_samples) f.write('/channel_groups/1/spikes/recording', spike_recordings) f.write_attr('/channel_groups/1', 'channel_order', np.arange(1, n_channels - 1)[::-1]) graph = np.array([[1, 2], [2, 3]]) f.write_attr('/channel_groups/1', 'adjacency_graph', graph) # Create channels. positions = staggered_positions(n_channels) for channel in range(n_channels): group = '/channel_groups/1/channels/{0:d}'.format(channel) f.write_attr(group, 'name', str(channel)) f.write_attr(group, 'position', positions[channel]) # Create spike clusters. clusterings = [('main', n_clusters)] if add_original: clusterings += [('original', n_clusters * 2)] for clustering, n_clusters_rec in clusterings: spike_clusters = artificial_spike_clusters(n_spikes, n_clusters_rec) groups = {0: 0, 1: 1, 2: 2} _create_clustering(f, clustering, 1, spike_clusters, groups) # Create recordings. f.write_attr('/recordings/0', 'name', 'recording_0') f.write_attr('/recordings/1', 'name', 'recording_1') f.write_attr('/recordings/0/raw', 'hdf5_path', kwd_filename) f.write_attr('/recordings/1/raw', 'hdf5_path', kwd_filename) # Create the kwx file. if with_kwx: with open_h5(kwx_filename, 'w') as f: f.write_attr('/', 'kwik_version', 2) features = artificial_features(n_spikes, (n_channels - 2) * n_features_per_channel) masks = artificial_masks(n_spikes, (n_channels - 2) * n_features_per_channel) fm = np.dstack((features, masks)).astype(np.float32) f.write('/channel_groups/1/features_masks', fm) # Create the raw kwd file. if with_kwd: with open_h5(kwd_filename, 'w') as f: f.write_attr('/', 'kwik_version', 2) traces = artificial_traces(n_samples_traces, n_channels) # TODO: int16 traces f.write('/recordings/0/data', traces[:recording_offset, ...].astype(np.float32)) f.write('/recordings/1/data', traces[recording_offset:, ...].astype(np.float32)) return filename
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 44, 735, 509, 20763, 3696, 526, 15931, 198, 198, 2, 10097, 26171, 198, 2, 1846, 3742, 198, 2, 10097, 26171, 198, 198, 11748, 28686, 13, 6978, 355, 1034, 19...
2.194958
2,380
# Copyright 2020 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Code to compute the audio intensity for preprocessing. Code that stores incoming arbitrary audio data, and then yields fixed window sizes for processing (like computing the intensity.) After initializing the object, add a block of data to the object, and then pull fixed sized blocks of data with a given half_window_width, and separated by window_step samples. Data is always X x num_features, where X can change from add_data call to call, but num_features must not change. Do not reuse the object because it has internal state from previous calls. """ import numpy as np from telluride_decoding import result_store
[ 2, 15069, 12131, 3012, 3457, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 2, 921, 743, ...
4.199346
306
import logging from urllib.parse import urlsplit import asyncio as aio from functools import partial from .api.service import Service from .api.xsd import device as deviceParser from ..utils import requests_get log = logging.getLogger(__name__) def test(): device = Device("http://10.42.1.102:49152/setup.xml") print(device.get_service('basicevent').SetBinaryState(BinaryState=1)) if __name__ == "__main__": test()
[ 11748, 18931, 198, 6738, 2956, 297, 571, 13, 29572, 1330, 2956, 7278, 489, 270, 198, 198, 11748, 30351, 952, 355, 257, 952, 198, 198, 6738, 1257, 310, 10141, 1330, 13027, 198, 6738, 764, 15042, 13, 15271, 1330, 4809, 198, 6738, 764, 1...
2.939597
149
"""File providing localtime support.""" import time import network import ntptime from machine import RTC, reset from config import Config system_config = Config('system_config.json')
[ 37811, 8979, 4955, 1957, 2435, 1104, 526, 15931, 198, 11748, 640, 198, 11748, 3127, 198, 11748, 299, 83, 457, 524, 198, 6738, 4572, 1330, 371, 4825, 11, 13259, 198, 6738, 4566, 1330, 17056, 198, 198, 10057, 62, 11250, 796, 17056, 10786,...
3.854167
48
from django.urls import path from . import views urlpatterns = [ path('register/', views.registration_view, name='api_register'), path('login/', views.LoginView.as_view(), name='api_login'), path('complete_profile/', views.complete_profile_view, name='api_complete_profile'), path('logout/', views.LogoutView.as_view(), name='api_logout'), path('check_login_status/', views.check_login_status, name='api_check_login_status'), ]
[ 6738, 42625, 14208, 13, 6371, 82, 1330, 3108, 198, 6738, 764, 1330, 5009, 198, 198, 6371, 33279, 82, 796, 685, 198, 220, 220, 220, 3108, 10786, 30238, 14, 3256, 5009, 13, 2301, 33397, 62, 1177, 11, 1438, 11639, 15042, 62, 30238, 33809...
2.928105
153
"""A kernel manager for multiple kernels Authors: * Brian Granger """ #----------------------------------------------------------------------------- # Copyright (C) 2013 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- from __future__ import absolute_import import os import uuid import zmq from zmq.eventloop.zmqstream import ZMQStream from IPython.config.configurable import LoggingConfigurable from IPython.utils.importstring import import_item from IPython.utils.traitlets import ( Instance, Dict, Unicode, Any, DottedObjectName, ) #----------------------------------------------------------------------------- # Classes #-----------------------------------------------------------------------------
[ 37811, 32, 9720, 4706, 329, 3294, 50207, 198, 198, 30515, 669, 25, 198, 198, 9, 8403, 46236, 198, 37811, 198, 198, 2, 10097, 32501, 198, 2, 220, 15069, 357, 34, 8, 2211, 220, 383, 6101, 7535, 7712, 4816, 198, 2, 198, 2, 220, 4307,...
5.231884
207
#!/usr/bin/env python # -*- coding: UTF-8 -*- # 3 # # 2 2 4 6 10 ... # 20 f1 = 2 f2 = 2 for i in range(1, 20): print '%d\n%d' % (f1, f2) f1 = f1 + f2 f2 = f1 + f2
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 41002, 12, 23, 532, 9, 12, 198, 2, 513, 198, 2, 220, 198, 2, 362, 362, 604, 718, 838, 2644, 198, 198, 2, 1160, 198, 69, 16, 796, 362, 198, 69, 17, ...
1.695238
105
from random import randrange from time import time from __future__ import generators,division from Subs import * patch = { 'side l' : 45, 'side r' : 46, 'main 1' : 1, 'main 2' : 2, 'main 3' : 3, 'main 4' : 4, 'main 5' : 5, 'main 6' : 6, 'main 7' : 7, 'main 8' : 8, 'main 9' : 9, 'main 10' : 10, 'center sc' : 20, 'sr sky' : 43, 'blacklight' : 15, 'house':68, ('b0 1 r' ,'b01'):54, # left bank over house ('b0 2 p' ,'b02'):53, ('b0 3 o' ,'b03'):52, ('b0 4 b' ,'b04'):51, ('b0 5 r' ,'b05'):50, ('b0 6 lb','b06'):49, ('b1 1' ,'b11'):55, # mid bank ('b1 2' ,'b12'):56, ('b1 3' ,'b13'):57, ('b1 4' ,'b14'):58, ('b1 5' ,'b15'):59, ('b1 6' ,'b16'):60, ('b2 1 lb','b21'):61, # right bank ('b2 2 r' ,'b22'):62, ('b2 3 b' ,'b23'):63, ('b2 4 o' ,'b24'):64, ('b2 5 p' ,'b25'):65, ('b2 6 r' ,'b26'):66, } from util import maxes,scaledict FL=100 subs = { 'over pit sm' : levs(range(1, 13),(100,0,0,91,77,79,86,55,92,77,59,0)), 'over pit lg' : fulls(range(1, 13)), ('house', 'black') : { 68:100 }, ('cyc', 'lightBlue'):{42:FL,43:FL}, ('scp hot ctr', 'yellow'):{18:FL}, ('scp more', '#AAAA00'):{18:FL,14:FL}, ('scp all', '#AAAA00'):fulls((13,16,18,19,39)), ('col oran', '#EEEE99'):fulls((21,25,29,33)), ('col red', 'red'):fulls((24,28,32,36)), ('col red big', 'red'):fulls((24,28,32,36, 'b0 1 r','b0 5 r','b2 2 r','b2 6 r')), ('col blue', 'blue'):fulls((23,27,31,35,'b0 4 b','b2 3 b')), ('col gree', 'green'):fulls((22,26,30,34)), 'sidepost':fulls((45,46)), 'edges':fulls((55,60,49,54,61,66)), 'bank1ctr':fulls(('b12','b13','b14','b15')), ('blacklight', 'purple'):blacklight, 'over pit ctr' : fulls((6,)), ('strobe', 'grey'):strobe, # 'midstage' : dict([(r, 100) for r in range(11, 21)]), # 'backstage' : dict([(r, 100) for r in range(21, 31)]), # 'frontchase' : mr_effect, 'chase' : chase, 'chase2' : chase, # 'random' : randomdimmer, } subs["*10"] = { "14" : 46.000000, "18" : 46.000000, "22" : 88.000000, "23" : 95.000000, "24" : 19.000000, "26" : 88.000000, "27" : 95.000000, "28" : 19.000000, "30" : 88.000000, "31" : 95.000000, "32" : 19.000000, "34" : 88.000000, "35" : 95.000000, "36" : 19.000000, "b0 5 r" : 7.000000, "b0 4 b" : 95.000000, "b0 1 r" : 7.000000, "b2 2 r" : 7.000000, "b2 3 b" : 95.000000, "b2 6 r" : 7.000000, } subs["*13"] = { "main 1" : 51.0, "main 2" : 51.0, "main 3" : 51.0, "main 4" : 51.0, "main 5" : 51.0, "main 6" : 51.0, "main 7" : 51.0, "main 8" : 51.0, "main 9" : 51.0, "main 10" : 51.0, "11" : 51.0, "12" : 51.0, "blacklight" : 0.0, "21" : 56.0, "22" : 50.0, "24" : 51.0, "25" : 56.0, "26" : 50.0, "28" : 51.0, "29" : 56.0, "30" : 50.0, "32" : 51.0, "33" : 56.0, "34" : 50.0, "36" : 51.0, "b0 5 r" : 51.0, "b0 1 r" : 51.0, "b2 2 r" : 51.0, "b2 6 r" : 51.0, } subs["*16"] = { "main 1" : 54, "main 4" : 49, "main 5" : 41, "main 6" : 43, "main 7" : 46, "main 8" : 29, "main 9" : 50, "main 10" : 41, "11" : 32, "13" : 77, "16" : 77, "18" : 77, "19" : 77, "39" : 77, "42" : 30, "sr sky" : 30,} subs["*3"] = { "main 1" : 47, "main 2" : 47, "main 3" : 47, "main 4" : 47, "main 5" : 47, "main 6" : 47, "main 7" : 47, "main 8" : 47, "main 9" : 47, "main 10" : 47, "11" : 47, "12" : 47, "blacklight" : 0, "21" : 67, "22" : 69, "23" : 69, "24" : 78, "25" : 67, "26" : 69, "27" : 69, "28" : 78, "29" : 67, "30" : 69, "31" : 69, "32" : 78, "33" : 67, "34" : 69, "35" : 69, "36" : 78, "b0 4 b" : 69, "b1 2" : 61, "b1 3" : 61, "b1 4" : 61, "b1 5" : 61, "b2 3 b" : 69,} subs["*12"] = { "main 1" : 25, "main 4" : 23, "main 5" : 19, "main 6" : 20, "main 7" : 22, "main 8" : 14, "main 9" : 23, "main 10" : 19, "11" : 15, "13" : 36, "16" : 36, "18" : 36, "19" : 36, "22" : 65, "23" : 100, "24" : 23, "26" : 65, "27" : 100, "28" : 23, "30" : 65, "31" : 100, "32" : 23, "34" : 65, "35" : 100, "36" : 23, "39" : 36, "b0 4 b" : 100, "b1 2" : 62, "b1 3" : 62, "b1 4" : 62, "b1 5" : 62, "b2 3 b" : 100,} subs["*curtain"] = { "main 4" : 44, "main 5" : 37, "main 6" : 86, "main 7" : 42, "main 8" : 32, "main 9" : 45, "42" : 41, "sr sky" : 41, "b0 6 lb" : 27, "b0 1 r" : 27, "b1 1" : 27, "b1 2" : 100, "b1 3" : 100, "b1 4" : 100, "b1 5" : 100, "b1 6" : 27, "b2 1 lb" : 27, "b2 6 r" : 27, } subs["ba outrs"] = fulls("b01 b02 b03 b04 b05 b06 b21 b22 b23 b24 b25 b26".split()) subs["ba some"] = {'b02':40,'b03':FL,'b04':FL,'b05':40, 'b22':40,'b23':FL,'b24':FL,'b25':40,} subs['*curtain'].update(subs['ba some']) subs["*2"] = { "main 1" : 77, "main 4" : 70, "main 5" : 59, "main 6" : 61, "main 7" : 66, "main 8" : 42, "main 9" : 71, "main 10" : 59, "11" : 45, "24" : 77, "28" : 77, "32" : 77, "36" : 77, "b0 5 r" : 77, "b0 1 r" : 77, "b2 2 r" : 77, "b2 6 r" : 77,} subs["*6"] = { "main 1" : 37, "main 4" : 33, "main 5" : 28, "main 6" : 29, "main 7" : 32, "main 8" : 20, "main 9" : 34, "main 10" : 28, "11" : 22, "13" : 37, "blacklight" : 0, "16" : 37, "18" : 37, "19" : 37, "21" : 82, "22" : 82, "23" : 82, "24" : 82, "25" : 82, "26" : 82, "27" : 82, "28" : 82, "29" : 82, "30" : 82, "31" : 82, "32" : 82, "33" : 82, "34" : 82, "35" : 82, "36" : 82, "39" : 37, "b0 5 r" : 82, "b0 4 b" : 82, "b0 1 r" : 82, "b2 2 r" : 82, "b2 3 b" : 82, "b2 6 r" : 82,} subs["*8"] = { "13" : 60, "16" : 60, "18" : 60, "19" : 60, "22" : 14, "23" : 100, "26" : 14, "27" : 100, "30" : 14, "31" : 100, "34" : 14, "35" : 100, "39" : 60, "b0 6 lb" : 14, "b0 4 b" : 100, "b0 1 r" : 14, "b1 1" : 14, "b1 2" : 70, "b1 3" : 70, "b1 4" : 70, "b1 5" : 70, "b1 6" : 14, "b2 1 lb" : 14, "b2 3 b" : 100, "b2 6 r" : 14,} subs["*5"] = { "main 1" : 81, "main 4" : 74, "main 5" : 62, "main 6" : 64, "main 7" : 70, "main 8" : 44, "main 9" : 75, "main 10" : 62, "11" : 48, "21" : 29, "24" : 29, "25" : 29, "28" : 29, "29" : 29, "32" : 29, "33" : 29, "36" : 29, "42" : 37, "sr sky" : 37, "b0 5 r" : 29, "b0 4 b" : 72, "b0 3 o" : 72, "b0 2 p" : 29, "b2 2 r" : 29, "b2 3 b" : 72, "b2 4 o" : 72, "b2 5 p" : 29,}
[ 6738, 4738, 1330, 43720, 9521, 198, 6738, 640, 1330, 640, 198, 6738, 11593, 37443, 834, 1330, 27298, 11, 21426, 198, 6738, 3834, 82, 1330, 1635, 628, 198, 17147, 796, 1391, 198, 220, 220, 220, 705, 1589, 300, 6, 1058, 4153, 11, 198, ...
1.746741
3,759
# SPDX-License-Identifier: BSD-3-Clause # Copyright (c) 2021 Scipp contributors (https://github.com/scipp) # @file # @author Simon Heybrock # flake8: noqa from . import runtime_config user_configuration_filename = runtime_config.config_filename config = runtime_config.load() del runtime_config from ._scipp import _debug_ if _debug_: import warnings warnings.formatwarning = custom_formatwarning warnings.warn( 'You are running a "Debug" build of scipp. For optimal performance use a "Release" build.' ) from ._scipp import __version__ # Import classes from ._scipp.core import Variable, DataArray, Dataset, GroupByDataArray, \ GroupByDataset, Unit # Import errors from ._scipp.core import BinEdgeError, BinnedDataError, CoordError, \ DataArrayError, DatasetError, DimensionError, \ DTypeError, NotFoundError, SizeError, SliceError, \ UnitError, VariableError, VariancesError # Import submodules from ._scipp.core import units, dtype, buckets, geometry # Import functions from ._scipp.core import choose, divide, floor_divide, logical_and, \ logical_or, logical_xor, minus, mod, plus, times # Import python functions from .show import show, make_svg from .table import table from .plotting import plot from .extend_units import * from .html import to_html, make_html from .object_list import _repr_html_ from ._utils import collapse, slices from ._utils.typing import is_variable, is_dataset, is_data_array, \ is_dataset_or_array from .compat.dict import to_dict, from_dict from .sizes import _make_sizes # Wrappers for free functions from _scipp.core from ._bins import * from ._counts import * from ._comparison import * from ._cumulative import * from ._dataset import * from ._groupby import * from ._math import * from ._operations import * from ._unary import * from ._reduction import * from ._shape import * from ._trigonometry import * from ._variable import * setattr(Variable, '_repr_html_', make_html) setattr(DataArray, '_repr_html_', make_html) setattr(Dataset, '_repr_html_', make_html) from .io.hdf5 import to_hdf5 as _to_hdf5 setattr(Variable, 'to_hdf5', _to_hdf5) setattr(DataArray, 'to_hdf5', _to_hdf5) setattr(Dataset, 'to_hdf5', _to_hdf5) setattr(Variable, 'sizes', property(_make_sizes)) setattr(DataArray, 'sizes', property(_make_sizes)) setattr(Dataset, 'sizes', property(_make_sizes)) from ._bins import _bins, _set_bins, _events setattr(Variable, 'bins', property(_bins, _set_bins)) setattr(DataArray, 'bins', property(_bins, _set_bins)) setattr(Dataset, 'bins', property(_bins, _set_bins)) setattr(Variable, 'events', property(_events)) setattr(DataArray, 'events', property(_events)) from ._structured import _fields setattr( Variable, 'fields', property( _fields, doc= """Provides access to fields of structured types such as vectors or matrices.""" )) from ._bins import _groupby_bins setattr(GroupByDataArray, 'bins', property(_groupby_bins)) setattr(GroupByDataset, 'bins', property(_groupby_bins)) setattr(Variable, 'plot', plot) setattr(DataArray, 'plot', plot) setattr(Dataset, 'plot', plot) # Prevent unwanted conversion to numpy arrays by operations. Properly defining # __array_ufunc__ should be possible by converting non-scipp arguments to # variables. The most difficult part is probably mapping the ufunc to scipp # functions. for _obj in [Variable, DataArray, Dataset]: setattr(_obj, '__array_ufunc__', None)
[ 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 347, 10305, 12, 18, 12, 2601, 682, 198, 2, 15069, 357, 66, 8, 33448, 10286, 381, 20420, 357, 5450, 1378, 12567, 13, 785, 14, 36216, 381, 8, 198, 2, 2488, 7753, 198, 2, 2488, 9800, 11...
2.738931
1,310
# Import the required 'libraries' for pin definitions and PWM from machine import Pin, PWM # Also import a subset for sleep and millisecond sleep. If you just import # the utime you will have to prefix each call with "utime." from utime import sleep, sleep_ms # Define what the buzzer object is - a PWM output on pin 15 buzzer = PWM(Pin(15)) # A list of frequencies tones = (200, 250, 300, 350, 400, 450, 500, 550, 600, 650, 700, 750, 800, 850, 900, 950, 1000, 1100, 1200, 1400, 1500) # Define the function to play a single tone then stop # Define a similar functionm with no delay between tones # Now sound the tones, one after the other for tone in range(len(tones)): buzz(tones[tone]) # Small gap in SECONDS after the ascending tones sleep(1) # Don't do this, it puts the device to Seep Sleep but it reboots on wakeup just # like the ESP8266 #machine.deepsleep(1) # Now sound the tones IN REVERSE ORDER ie descending for tone in range(len(tones) -1, -1, -1): buzz(tones[tone]) # Another delay sleep(1) # Now sound ALL the frequencies from X to Y for tone in range(500, 2500): buzz2(tone) sleep_ms(5) buzzer.duty_u16(0); # And repeat in reverse order for tone in range(2500, 500, -1): buzz2(tone) sleep_ms(4) buzzer.duty_u16(0);
[ 2, 17267, 262, 2672, 705, 75, 11127, 6, 329, 6757, 17336, 290, 350, 22117, 201, 198, 6738, 4572, 1330, 13727, 11, 350, 22117, 201, 198, 201, 198, 2, 4418, 1330, 257, 24637, 329, 3993, 290, 33606, 623, 3993, 13, 1002, 345, 655, 1330,...
2.72541
488
from sqlalchemy.test.testing import assert_raises, assert_raises_message from sqlalchemy import MetaData, Integer from sqlalchemy.test.schema import Table from sqlalchemy.test.schema import Column from sqlalchemy.orm import mapper, create_session import sqlalchemy as sa from sqlalchemy.test import testing from test.orm import _base
[ 6738, 44161, 282, 26599, 13, 9288, 13, 33407, 1330, 6818, 62, 430, 2696, 11, 6818, 62, 430, 2696, 62, 20500, 198, 6738, 44161, 282, 26599, 1330, 30277, 6601, 11, 34142, 198, 6738, 44161, 282, 26599, 13, 9288, 13, 15952, 2611, 1330, 86...
3.585106
94
""" Backend abstraction for PDFDocuments """ import abc import os DEFAULT_BACKEND = "poppler" BACKEND = os.environ.get("PDFTABLES_BACKEND", DEFAULT_BACKEND).lower() # TODO(pwaller): Use abstract base class? # What does it buy us? Can we enforce that only methods specified in an ABC # are used by client code?
[ 37811, 198, 7282, 437, 34651, 329, 12960, 38354, 198, 37811, 198, 198, 11748, 450, 66, 198, 11748, 28686, 198, 198, 7206, 38865, 62, 31098, 10619, 796, 366, 7501, 381, 1754, 1, 198, 31098, 10619, 796, 28686, 13, 268, 2268, 13, 1136, 7...
3.118812
101
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import gym from class_ppo import * from gym_torcs import TorcsEnv #---------------------------------------------------------------------------------------- EP_MAX = 2000 EP_LEN = 1000 GAMMA = 0.95 A_LR = 1e-4 C_LR = 1e-4 BATCH = 128 A_UPDATE_STEPS = 10 C_UPDATE_STEPS = 10 S_DIM, A_DIM = 29, 3 METHOD = dict(name='clip', epsilon=0.1) # train_test = 0 for train; =1 for test train_test = 0 # irestart = 0 for fresh restart; =1 for restart from ckpt file irestart = 0 iter_num = 0 if (irestart == 0): iter_num = 0 #---------------------------------------------------------------------------------------- sess = tf.Session() ppo = PPO(sess, S_DIM, A_DIM, A_LR, C_LR, A_UPDATE_STEPS, C_UPDATE_STEPS, METHOD) saver = tf.train.Saver() env = TorcsEnv(vision=False, throttle=True, gear_change=False) #---------------------------------------------------------------------------------------- if (train_test == 0 and irestart == 0): sess.run(tf.global_variables_initializer()) else: saver.restore(sess, "ckpt/model") for ep in range(iter_num, EP_MAX): print("-"*50) print("episode: ", ep) if np.mod(ep, 100) == 0: ob = env.reset(relaunch=True) #relaunch TORCS every N episode because of the memory leak error else: ob = env.reset() s = np.hstack((ob.angle, ob.track, ob.trackPos, ob.speedX, ob.speedY, ob.speedZ, ob.wheelSpinVel/100.0, ob.rpm)) buffer_s, buffer_a, buffer_r = [], [], [] ep_r = 0 for t in range(EP_LEN): # in one episode a = ppo.choose_action(s) a[0] = np.clip(a[0],-1.0,1.0) a[1] = np.clip(a[1],0.0,1.0) a[2] = np.clip(a[2],0.0,1.0) #print("a: ", a) ob, r, done, _ = env.step(a) s_ = np.hstack((ob.angle, ob.track, ob.trackPos, ob.speedX, ob.speedY, ob.speedZ, ob.wheelSpinVel/100.0, ob.rpm)) if (train_test == 0): buffer_s.append(s) buffer_a.append(a) buffer_r.append(r) s = s_ ep_r += r if (train_test == 0): # update ppo if (t+1) % BATCH == 0 or t == EP_LEN-1 or done == True: #if t == EP_LEN-1 or done == True: v_s_ = ppo.get_v(s_) discounted_r = [] for r in buffer_r[::-1]: v_s_ = r + GAMMA * v_s_ discounted_r.append(v_s_) discounted_r.reverse() bs = np.array(np.vstack(buffer_s)) ba = np.array(np.vstack(buffer_a)) br = np.array(discounted_r)[:, np.newaxis] buffer_s, buffer_a, buffer_r = [], [], [] print("ppo update") ppo.update(bs, ba, br) #print("screen out: ") #ppo.screen_out(bs, ba, br) #print("-"*50) if (done == True): break print('Ep: %i' % ep,"|Ep_r: %i" % ep_r,("|Lam: %.4f" % METHOD['lam']) if METHOD['name'] == 'kl_pen' else '',) if (train_test == 0): with open("performance.txt", "a") as myfile: myfile.write(str(ep) + " " + str(t) + " " + str(round(ep_r,4)) + "\n") if (train_test == 0 and ep%25 == 0): saver.save(sess, "ckpt/model")
[ 11748, 11192, 273, 11125, 355, 48700, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 11550, 198, 6738, 1398, 62, 16634, 1330, 1635, 198, 6738, 11550, 62, 13165, 6359, 1330, ...
2.045651
1,621
""" Test case for the DocumentationWidget """ from tempfile import mkdtemp from pySUMOQt import MainWindow import pysumo import shutil """ Steps: 1. Open pySUMO 2. Open Merge.kif 3. Open DocumentationWidget 3a. Switch to the Ontology tab in the DocumentationWidget 4. Type subrelation into the search field 4a. Press Enter 5. Open TextEditor 5a. Select Merge.kif in TextEditor 6. Press one of the links listed under "Merge" 7. Switch to the WordNet tab in the DocumentationWidget 8. Search for 'Object' 9. Search for 'Table' """ if __name__ == "__main__": tmpdir = mkdtemp() pysumo.CONFIG_PATH = tmpdir MainWindow.main() shutil.rmtree(tmpdir, ignore_errors=True)
[ 37811, 6208, 1339, 329, 262, 43925, 38300, 37227, 198, 6738, 20218, 7753, 1330, 33480, 67, 29510, 198, 6738, 12972, 50, 5883, 46, 48, 83, 1330, 8774, 27703, 198, 11748, 279, 893, 43712, 198, 11748, 4423, 346, 198, 198, 37811, 198, 8600,...
3.026667
225
import unittest import threading from garage.threads import executors if __name__ == '__main__': unittest.main()
[ 11748, 555, 715, 395, 198, 198, 11748, 4704, 278, 198, 198, 6738, 15591, 13, 16663, 82, 1330, 3121, 669, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 555, 715, 395, 13, 12417, 3419, 19...
2.837209
43
import os import json from tqdm import tqdm from loader.Database import DBViewIndex, DBView, check_target_path from exporter.Shared import snakey from exporter.Adventurers import CharaData from exporter.Dragons import DragonData if __name__ == "__main__": index = DBViewIndex() view = BattleRoyalUnit(index) view.export_all_to_folder()
[ 11748, 28686, 198, 11748, 33918, 198, 6738, 256, 80, 36020, 1330, 256, 80, 36020, 198, 198, 6738, 40213, 13, 38105, 1330, 20137, 7680, 15732, 11, 20137, 7680, 11, 2198, 62, 16793, 62, 6978, 198, 6738, 1033, 4337, 13, 2484, 1144, 1330, ...
3.096491
114
from .user.queries import UserQuery # isort:skip from .user_group.queries import UserGroupQuery # isort:skip
[ 6738, 764, 7220, 13, 421, 10640, 1330, 11787, 20746, 220, 1303, 318, 419, 25, 48267, 198, 6738, 764, 7220, 62, 8094, 13, 421, 10640, 1330, 11787, 13247, 20746, 220, 1303, 318, 419, 25, 48267, 198 ]
3.171429
35
import matplotlib matplotlib.use('Agg') from statiskit import core from statiskit.data import core as data import unittest from nose.plugins.attrib import attr
[ 11748, 2603, 29487, 8019, 198, 6759, 29487, 8019, 13, 1904, 10786, 46384, 11537, 198, 198, 6738, 1185, 1984, 270, 1330, 4755, 198, 6738, 1185, 1984, 270, 13, 7890, 1330, 4755, 355, 1366, 198, 198, 11748, 555, 715, 395, 198, 6738, 9686, ...
3.285714
49
from scipy.io import loadmat import pickle mldinfo =loadmat('mldinfo.mat')["mldinfo"] out={} print(mldinfo) for i in mldinfo: line={} line["floatNumber"] = i[0] line["cycleNumber"] = i[26] line["tempMLTFIT"] = i[27] line["tempMLTFITIndex"] = i[28] line["densityMLTFIT"] = i[30] line["salinityMLTFIT"] = i[31] line["steepest"] = i[29] line["tempAlgo"] = i[4] line["salinityAlgo"] = i[8] line["densityAlgo"] = i[9] line["tempThreshold"] = i[13] line["densityThreshold"] = i[17] line["tempGradient"] = i[21] line["densityGradient"] = i[22] out[i[0],i[26]]=line with open("matOutput.pickle","wb") as f: pickle.dump(out,f)
[ 6738, 629, 541, 88, 13, 952, 1330, 3440, 6759, 198, 11748, 2298, 293, 198, 76, 335, 10951, 796, 2220, 6759, 10786, 76, 335, 10951, 13, 6759, 11537, 14692, 76, 335, 10951, 8973, 198, 448, 34758, 92, 198, 4798, 7, 76, 335, 10951, 8, ...
2.15674
319
#!/usr/bin/env python """ This is a special app instance that allows us to perform database operations without going through the app's migration_needed check. Running this script is functionally equivalent to what `flask db` normally does. The reason we can't continue to use that is that command is that it invokes the app instance from FLASK_APP env variable (natlas-server.py) which performs the migration check and exits during initialization. """ import argparse from app import create_app from config import Config from migrations import migrator parser_desc = """Perform database operations for Natlas.\ It is best practice to take a backup of your database before you upgrade or downgrade, just in case something goes wrong.\ """ if __name__ == "__main__": main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 37811, 198, 220, 220, 220, 770, 318, 257, 2041, 598, 4554, 326, 3578, 514, 284, 1620, 6831, 4560, 198, 220, 220, 220, 1231, 1016, 832, 262, 598, 338, 13472, 62, 27938, 2198, 13, 1816...
3.833333
210
# -*- coding: utf-8 -*- """Forms to process action related fields. ActionUpdateForm: Basic form to process the name/description of an action ActionForm: Inherits from Basic to process name, description and type ActionDescriptionForm: Inherits from basic but process only description (for surveys) FilterForm: Form to process filter elements ConditionForm: Form to process condition elements """ from builtins import str import json from typing import Dict from django import forms from django.utils.translation import ugettext_lazy as _ from ontask import models from ontask.core import RestrictedFileField import ontask.settings
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 8479, 82, 284, 1429, 2223, 3519, 7032, 13, 198, 198, 12502, 10260, 8479, 25, 14392, 1296, 284, 1429, 262, 1438, 14, 11213, 286, 281, 2223, 198, 198, 12502, ...
3.857143
168
#------------------------------------------------------------------------------ # # Copyright (c) 2006, Enthought, Inc. # All rights reserved. # # This software is provided without warranty under the terms of the BSD # license included in enthought/LICENSE.txt and may be redistributed only # under the conditions described in the aforementioned license. The license # is also available online at http://www.enthought.com/licenses/BSD.txt # # Thanks for using Enthought open source! # # Author: David C. Morrill # Date: 01/05/2006 # #------------------------------------------------------------------------------ """ Defines tree node classes and editors for various types of values. """ #------------------------------------------------------------------------- # Imports: #------------------------------------------------------------------------- from __future__ import absolute_import import inspect from operator import itemgetter from types import FunctionType, MethodType from traits.api import Any, Bool, HasPrivateTraits, HasTraits, Instance, List, Str from .tree_node import ObjectTreeNode, TreeNode, TreeNodeObject from .editors.tree_editor import TreeEditor import six #------------------------------------------------------------------------- # 'SingleValueTreeNodeObject' class: #------------------------------------------------------------------------- #------------------------------------------------------------------------- # 'MultiValueTreeNodeObject' class: #------------------------------------------------------------------------- #------------------------------------------------------------------------- # 'StringNode' class: #------------------------------------------------------------------------- #------------------------------------------------------------------------- # 'NoneNode' class: #------------------------------------------------------------------------- #------------------------------------------------------------------------- # 'BoolNode' class: #------------------------------------------------------------------------- #------------------------------------------------------------------------- # 'IntNode' class: #------------------------------------------------------------------------- #------------------------------------------------------------------------- # 'FloatNode' class: #------------------------------------------------------------------------- #------------------------------------------------------------------------- # 'ComplexNode' class: #------------------------------------------------------------------------- #------------------------------------------------------------------------- # 'OtherNode' class: #------------------------------------------------------------------------- #------------------------------------------------------------------------- # 'TupleNode' class: #------------------------------------------------------------------------- #------------------------------------------------------------------------- # 'ListNode' class: #------------------------------------------------------------------------- #------------------------------------------------------------------------- # 'SetNode' class: #------------------------------------------------------------------------- #------------------------------------------------------------------------- # 'ArrayNode' class: #------------------------------------------------------------------------- #------------------------------------------------------------------------- # 'DictNode' class: #------------------------------------------------------------------------- #------------------------------------------------------------------------- # 'FunctionNode' class: #------------------------------------------------------------------------- #--------------------------------------------------------------------------- # 'MethodNode' class: #--------------------------------------------------------------------------- #------------------------------------------------------------------------- # 'ObjectNode' class: #------------------------------------------------------------------------- #------------------------------------------------------------------------- # 'ClassNode' class: #------------------------------------------------------------------------- #------------------------------------------------------------------------- # 'TraitsNode' class: #------------------------------------------------------------------------- #------------------------------------------------------------------------- # 'RootNode' class: #------------------------------------------------------------------------- #------------------------------------------------------------------------- # Define the mapping of object types to nodes: #------------------------------------------------------------------------- _basic_types = None def basic_types(): global _basic_types if _basic_types is None: # Create the mapping of object types to nodes: _basic_types = [ (type(None), NoneNode), (str, StringNode), (six.text_type, StringNode), (bool, BoolNode), (int, IntNode), (float, FloatNode), (complex, ComplexNode), (tuple, TupleNode), (list, ListNode), (set, SetNode), (dict, DictNode), (FunctionType, FunctionNode), (MethodType, MethodNode), (HasTraits, TraitsNode) ] try: from numpy import array _basic_types.append((type(array([1])), ArrayNode)) except ImportError: pass return _basic_types #------------------------------------------------------------------------- # '_ValueTree' class: #------------------------------------------------------------------------- #------------------------------------------------------------------------- # Defines the value tree editor(s): #------------------------------------------------------------------------- # Nodes in a value tree: value_tree_nodes = [ ObjectTreeNode( node_for=[NoneNode, StringNode, BoolNode, IntNode, FloatNode, ComplexNode, OtherNode, TupleNode, ListNode, ArrayNode, DictNode, SetNode, FunctionNode, MethodNode, ObjectNode, TraitsNode, RootNode, ClassNode]) ] # Editor for a value tree: value_tree_editor = TreeEditor( auto_open=3, hide_root=True, editable=False, nodes=value_tree_nodes ) # Editor for a value tree with a root: value_tree_editor_with_root = TreeEditor( auto_open=3, editable=False, nodes=[ ObjectTreeNode( node_for=[NoneNode, StringNode, BoolNode, IntNode, FloatNode, ComplexNode, OtherNode, TupleNode, ListNode, ArrayNode, DictNode, SetNode, FunctionNode, MethodNode, ObjectNode, TraitsNode, RootNode, ClassNode] ), TreeNode(node_for=[_ValueTree], auto_open=True, children='values', move=[SingleValueTreeNodeObject], copy=False, label='=Values', icon_group='traits_node', icon_open='traits_node') ] ) #------------------------------------------------------------------------- # Defines a 'ValueTree' trait: #------------------------------------------------------------------------- # Trait for a value tree: ValueTree = Instance(_ValueTree, (), editor=value_tree_editor_with_root)
[ 2, 10097, 26171, 198, 2, 198, 2, 220, 15069, 357, 66, 8, 4793, 11, 2039, 28895, 11, 3457, 13, 198, 2, 220, 1439, 2489, 10395, 13, 198, 2, 198, 2, 220, 770, 3788, 318, 2810, 1231, 18215, 739, 262, 2846, 286, 262, 347, 10305, 198,...
4.23162
1,809
from django.contrib.auth.models import Group from django.test import TestCase from django.urls import reverse, reverse_lazy from django_dynamic_fixture import G from apps.authentication.models import OnlineUser from ..constants import EventType from ..models import Event from .utils import ( add_event_permissions, add_to_group, create_committee_group, generate_event, ) EVENTS_ADMIN_LIST_URL = reverse_lazy("admin:events_event_changelist") EVENTS_DASHBOARD_INDEX_URL = reverse_lazy("dashboard_events_index")
[ 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 4912, 198, 6738, 42625, 14208, 13, 9288, 1330, 6208, 20448, 198, 6738, 42625, 14208, 13, 6371, 82, 1330, 9575, 11, 9575, 62, 75, 12582, 198, 6738, 42625, 14208, 62, 67, 28...
3.016949
177
from pyuvs.files import DataFilenameCollection
[ 6738, 12972, 84, 14259, 13, 16624, 1330, 6060, 35063, 36307, 628 ]
4.363636
11
# coding: utf-8 import urllib2 import message_box from ast import literal_eval
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 11748, 2956, 297, 571, 17, 198, 11748, 3275, 62, 3524, 198, 6738, 6468, 1330, 18875, 62, 18206, 198 ]
2.962963
27
import sys import os import subprocess import pyautogui import time subprocess.run("C:/Windows/system32/cmd.exe") time.sleep(3) pyautogui.typewrite("python")
[ 11748, 25064, 201, 198, 11748, 28686, 201, 198, 11748, 850, 14681, 201, 198, 11748, 12972, 2306, 519, 9019, 201, 198, 11748, 640, 201, 198, 201, 198, 7266, 14681, 13, 5143, 7203, 34, 14079, 11209, 14, 10057, 2624, 14, 28758, 13, 13499, ...
2.119565
92
# import pip_test if __name__ == '__main__': pip_test.hello()
[ 2, 198, 11748, 7347, 62, 9288, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 7347, 62, 9288, 13, 31373, 3419 ]
2.407407
27
from .main import MainPort
[ 6738, 764, 12417, 1330, 8774, 13924 ]
4.333333
6
# -*- coding: utf-8 -*- # # Copyright (C) 2018, 2019 Esteban J. G. Gabancho. # # Invenio-S3 is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Module tests.""" from __future__ import absolute_import, print_function from invenio_s3 import InvenioS3 def test_version(): """Test version import.""" from invenio_s3 import __version__ assert __version__ def test_init(appctx): """Test extension initialization.""" assert 'invenio-s3' in appctx.extensions appctx.config['S3_ENDPOINT_URL'] = 'https://example.com:1234' appctx.config['S3_REGION_NAME'] = 'eu-west-1' s3_connection_info = appctx.extensions['invenio-s3'].init_s3fs_info assert s3_connection_info['client_kwargs'][ 'endpoint_url'] == 'https://example.com:1234' assert s3_connection_info['client_kwargs'][ 'region_name'] == 'eu-west-1' def test_access_key(appctx): """Test correct access key works together with flawed one.""" appctx.config['S3_ACCCESS_KEY_ID'] = 'secret' try: # Delete the cached value in case it's there already del appctx.extensions['invenio-s3'].__dict__['init_s3fs_info'] except KeyError: pass s3_connection_info = appctx.extensions['invenio-s3'].init_s3fs_info assert s3_connection_info['key'] == 'secret' def test_secret_key(appctx): """Test correct secret key works together with flawed one.""" appctx.config['S3_SECRECT_ACCESS_KEY'] = 'secret' try: # Delete the cached value in case it's there already del appctx.extensions['invenio-s3'].__dict__['init_s3fs_info'] except KeyError: pass s3_connection_info = appctx.extensions['invenio-s3'].init_s3fs_info assert s3_connection_info['secret'] == 'secret'
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 15069, 357, 34, 8, 2864, 11, 13130, 10062, 1765, 272, 449, 13, 402, 13, 12300, 3702, 78, 13, 198, 2, 198, 2, 554, 574, 952, 12, 50, 18, 318, 1479, 378...
2.545202
719
from textattack.constraints.pre_transformation import PreTransformationConstraint from textattack.shared.utils import default_class_repr
[ 6738, 2420, 20358, 13, 1102, 2536, 6003, 13, 3866, 62, 7645, 1161, 1330, 3771, 8291, 1161, 3103, 2536, 2913, 198, 6738, 2420, 20358, 13, 28710, 13, 26791, 1330, 4277, 62, 4871, 62, 260, 1050, 628 ]
3.942857
35
# TODO(jonathan): try to simplify this. def merge_kwargs(d1, d2, limit = 5): """Combine kwargs in a useful way. merge_kwargs combines dictionaries by inserting keys from d2 into d1. If the same key exists in both dictionaries: * if the value is a scalar, d2[key] overrides d1[key]. * if the value is a list, the contents of d2[key] not already in d1[key] are appended to d1[key]. * if the value is a dict, the sub-dictionaries are merged similarly (scalars are overriden, lists are appended). By default, this function limits recursion to 5 levels. The "limit" argument can be specified if deeper recursion is needed. """ merged = {} to_expand = [(merged, d1, k) for k in d1] + [(merged, d2, k) for k in d2] for _ in range(limit): expand_next = [] for m, d, k in to_expand: if k not in m: if type(d[k]) == "list": m[k] = list(d[k]) continue if type(d[k]) == "dict": m[k] = dict(d[k]) continue # type must be scalar: m[k] = d[k] continue if type(m[k]) == "dict": expand_next.extend([(m[k], d[k], k2) for k2 in d[k]]) continue if type(m[k]) == "list": # uniquify as we combine lists: for item in d[k]: if item not in m[k]: m[k].append(item) continue # type must be scalar: m[k] = d[k] to_expand = expand_next if not to_expand: break # If <limit> layers of recursion were not enough, explicitly fail. if to_expand: fail("merge_kwargs: exceeded maximum recursion limit.") return merged def add_tag(k, t): """Returns a kwargs dict that ensures tag `t` is present in kwargs["tags"].""" return merge_kwargs(k, {"tags": [t]})
[ 2, 16926, 46, 7, 46286, 6696, 2599, 1949, 284, 30276, 428, 13, 198, 4299, 20121, 62, 46265, 22046, 7, 67, 16, 11, 288, 17, 11, 4179, 796, 642, 2599, 198, 220, 220, 220, 37227, 20575, 500, 479, 86, 22046, 287, 257, 4465, 835, 13, ...
2.012
1,000
# import libraries import os, os.path import numpy as np import pandas as pd # import geopandas as gpd import sys from IPython.display import Image # from shapely.geometry import Point, Polygon from math import factorial import scipy from statsmodels.sandbox.regression.predstd import wls_prediction_std from sklearn.linear_model import LinearRegression from patsy import cr from datetime import date import datetime import time from pprint import pprint import matplotlib.pyplot as plt import seaborn as sb ################################################################ ##### ##### Function definitions ##### ################################################################ ######################################################################## def addToDF_SOS_EOS_White(pd_TS, VegIdx = "EVI", onset_thresh=0.15, offset_thresh=0.15): """ In this methods the NDVI_Ratio = (NDVI - NDVI_min) / (NDVI_Max - NDVI_min) is computed. SOS or onset is when NDVI_ratio exceeds onset-threshold and EOS is when NDVI_ratio drops below off-set-threshold. """ pandaFrame = pd_TS.copy() VegIdx_min = pandaFrame[VegIdx].min() VegIdx_max = pandaFrame[VegIdx].max() VegRange = VegIdx_max - VegIdx_min + sys.float_info.epsilon colName = VegIdx + "_ratio" pandaFrame[colName] = (pandaFrame[VegIdx] - VegIdx_min) / VegRange SOS_candidates = pandaFrame[colName] - onset_thresh EOS_candidates = offset_thresh - pandaFrame[colName] BOS, EOS = find_signChange_locs_DifferentOnOffset(SOS_candidates, EOS_candidates) pandaFrame['SOS'] = BOS * pandaFrame[VegIdx] pandaFrame['EOS'] = EOS * pandaFrame[VegIdx] return(pandaFrame) ######################################################################## def correct_big_jumps_1DaySeries(dataTMS_jumpie, give_col, maxjump_perDay = 0.015): """ in the function correct_big_jumps_preDefinedJumpDays(.) we have to define the jump_amount and the no_days_between_points. For example if we have a jump more than 0.4 in less than 20 dats, then that is an outlier detected. Here we modify the approach to be flexible in the following sense: if the amount of increase in NDVI is more than #_of_Days * 0.02 then an outlier is detected and we need interpolation. 0.015 came from the SG based paper that used 0.4 jump in NDVI for 20 days. That translates into 0.02 = 0.4 / 20 per day. But we did choose 0.015 as default """ dataTMS = dataTMS_jumpie.copy() dataTMS = initial_clean(df = dataTMS, column_to_be_cleaned = give_col) dataTMS.sort_values(by=['image_year', 'doy'], inplace=True) dataTMS.reset_index(drop=True, inplace=True) dataTMS['system_start_time'] = dataTMS['system_start_time'] / 1000 thyme_vec = dataTMS['system_start_time'].values.copy() Veg_indks = dataTMS[give_col].values.copy() time_diff = thyme_vec[1:] - thyme_vec[0:len(thyme_vec)-1] time_diff_in_days = time_diff / 86400 time_diff_in_days = time_diff_in_days.astype(int) Veg_indks_diff = Veg_indks[1:] - Veg_indks[0:len(thyme_vec)-1] jump_indexes = np.where(Veg_indks_diff > maxjump_perDay) jump_indexes = jump_indexes[0] jump_indexes = jump_indexes.tolist() # It is possible that the very first one has a big jump in it. # we cannot interpolate this. so, lets just skip it. if len(jump_indexes) > 0: if jump_indexes[0] == 0: jump_indexes.pop(0) if len(jump_indexes) > 0: for jp_idx in jump_indexes: if Veg_indks_diff[jp_idx] >= (time_diff_in_days[jp_idx] * maxjump_perDay): # # form a line using the adjacent points of the big jump: # x1, y1 = thyme_vec[jp_idx-1], Veg_indks[jp_idx-1] x2, y2 = thyme_vec[jp_idx+1], Veg_indks[jp_idx+1] # print (x1) # print (x2) m = np.float(y2 - y1) / np.float(x2 - x1) # slope b = y2 - (m*x2) # intercept # replace the big jump with linear interpolation Veg_indks[jp_idx] = m * thyme_vec[jp_idx] + b dataTMS[give_col] = Veg_indks return(dataTMS) ######################################################################## ######################################################################## ######################################################################## ######################################################################## def add_human_start_time_by_YearDoY(a_Reg_DF): """ This function is written for regularized data where we miss the Epoch time and therefore, cannot convert it to human_start_time using add_human_start_time() function Learn: x = pd.to_datetime(datetime.datetime(2016, 1, 1) + datetime.timedelta(213 - 1)) x year = 2020 DoY = 185 x = str(date.fromordinal(date(year, 1, 1).toordinal() + DoY - 1)) x datetime.datetime(2016, 1, 1) + datetime.timedelta(213 - 1) """ DF_C = a_Reg_DF.copy() # DF_C.image_year = DF_C.image_year.astype(float) DF_C.doy = DF_C.doy.astype(int) DF_C['human_system_start_time'] = pd.to_datetime(DF_C['image_year'].astype(int) * 1000 + DF_C['doy'], format='%Y%j') # DF_C.reset_index(drop=True, inplace=True) # DF_C['human_system_start_time'] = "1" # for row_no in np.arange(0, len(DF_C)): # year = DF_C.loc[row_no, 'image_year'] # DoY = DF_C.loc[row_no, 'doy'] # x = str(date.fromordinal(date(year, 1, 1).toordinal() + DoY - 1)) # DF_C.loc[row_no, 'human_system_start_time'] = x return(DF_C) ######################################################################## ######################################################################## ######################################################################## # # Kirti look here # # detect passing the threshod def extract_XValues_of_2Yrs_TS(regularized_TS, SF_yr): # old name extract_XValues_of_RegularizedTS_2Yrs(). # I do not know why I had Regularized in it. # new name extract_XValues_of_2Yrs_TS """ Jul 1. This function is being written since Kirti said we do not need to have parts of the next year. i.e. if we are looking at what is going on in a field in 2017, we only need data since Aug. 2016 till the end of 2017. We do not need anything in 2018. """ X_values_prev_year = regularized_TS[regularized_TS.image_year == (SF_yr - 1)]['doy'].copy().values X_values_full_year = regularized_TS[regularized_TS.image_year == (SF_yr)]['doy'].copy().values if check_leap_year(SF_yr - 1): X_values_full_year = X_values_full_year + 366 else: X_values_full_year = X_values_full_year + 365 return (np.concatenate([X_values_prev_year, X_values_full_year])) ######################################################################## ######################################################################## ######################################################################## # # These will not give what we want. It is a 10-days window # The days are actual days. i.e. between each 2 entry of our # time series there is already some gap. # ######################################################################## ######################################################################## ######################################################################## def save_matlab_matrix(filename, matDict): """ Write a MATLAB-formatted matrix file given a dictionary of variables. """ try: sio.savemat(filename, matDict) except: print("ERROR: could not write matrix file " + filename)
[ 2, 1330, 12782, 198, 11748, 28686, 11, 28686, 13, 6978, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 2, 1330, 30324, 392, 292, 355, 27809, 67, 198, 11748, 25064, 198, 6738, 6101, 7535, 13, 13812, 1330...
2.67056
2,911
from .AbstractFlaskTemplateFilter import AbstractFlaskTemplateFilter # # ... # #
[ 628, 198, 198, 6738, 764, 23839, 7414, 2093, 30800, 22417, 1330, 27741, 7414, 2093, 30800, 22417, 628, 628, 198, 198, 2, 198, 2, 2644, 198, 2, 198, 198, 2, 628, 628, 628, 628, 198 ]
2.911765
34
# Copyright (c) 2012-2018 SoftBank Robotics. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the COPYING file.
[ 2, 15069, 357, 66, 8, 2321, 12, 7908, 8297, 28650, 47061, 13, 1439, 2489, 10395, 13, 198, 2, 5765, 286, 428, 2723, 2438, 318, 21825, 416, 257, 347, 10305, 12, 7635, 5964, 326, 460, 307, 198, 2, 1043, 287, 262, 27975, 45761, 2393, ...
3.717391
46
# SPDX-License-Identifier: Apache-2.0 # To register converter for libsvm operators, import associated modules here. from . import SVMConverter
[ 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 24843, 12, 17, 13, 15, 198, 198, 2, 1675, 7881, 38394, 329, 9195, 82, 14761, 12879, 11, 1330, 3917, 13103, 994, 13, 198, 6738, 764, 1330, 311, 15996, 3103, 332, 353, 198 ]
3.512195
41
# for backwards compatibility with aspen-renderer modules from .simplates.renderers import Factory, Renderer Factory, Renderer # make pyflakes happy import warnings warnings.warn('aspen.renderers is deprecated and will be removed in a future version. ' 'Please use aspen.simplates.renderers instead.', FutureWarning)
[ 2, 329, 16196, 17764, 351, 355, 3617, 12, 10920, 11882, 13103, 198, 6738, 764, 14323, 17041, 13, 10920, 19288, 1330, 19239, 11, 28703, 11882, 198, 198, 22810, 11, 28703, 11882, 1303, 787, 12972, 2704, 1124, 3772, 198, 198, 11748, 14601, ...
3.505263
95
import pygame import sys import collections # for ordered dict import pickle # for saving and loading highscores from constants import (SCREEN_WIDTH, SCREEN_HEIGHT, RED, GREEN, GREY, BLACK, WHITE) # class that shows, saves and loads highscores
[ 11748, 12972, 6057, 198, 11748, 25064, 198, 11748, 17268, 1303, 329, 6149, 8633, 198, 11748, 2298, 293, 1303, 329, 8914, 290, 11046, 1029, 1416, 2850, 198, 6738, 38491, 1330, 357, 6173, 2200, 1677, 62, 54, 2389, 4221, 11, 6374, 2200, 16...
3.536232
69
#!/usr/bin/env python2 import glob as glob import os as os import re import shutil as shutil import signal as signal import subprocess as sp import sys as sys from lib import build from lib import scripts from lib import setup from lib import analysis ion_def = [] poses_list = [] poses_def = [] release_eq = [] translate_apr = [] attach_rest = [] lambdas = [] weights = [] components = [] aa1_poses = [] aa2_poses = [] # Read arguments that define input file and stage if len(sys.argv) < 5: scripts.help_message() sys.exit(0) for i in [1, 3]: if '-i' == sys.argv[i].lower(): input_file = sys.argv[i + 1] elif '-s' == sys.argv[i].lower(): stage = sys.argv[i + 1] else: scripts.help_message() sys.exit(1) # Open input file with open(input_file) as f_in: # Remove spaces and tabs lines = (line.strip(' \t\n\r') for line in f_in) lines = list(line for line in lines if line) # Non-blank lines in a list for i in range(0, len(lines)): # split line using the equal sign, and remove text after # if not lines[i][0] == '#': lines[i] = lines[i].split('#')[0].split('=') # Read parameters from input file for i in range(0, len(lines)): if not lines[i][0] == '#': lines[i][0] = lines[i][0].strip().lower() lines[i][1] = lines[i][1].strip() if lines[i][0] == 'pull_ligand': if lines[i][1].lower() == 'yes': pull_ligand = 'yes' elif lines[i][1].lower() == 'no': pull_ligand = 'no' else: print('Wrong input! Please use yes or no to indicate whether to pull out the ligand or not.') sys.exit(1) elif lines[i][0] == 'temperature': temperature = scripts.check_input('float', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'eq_steps1': eq_steps1 = scripts.check_input('int', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'eq_steps2': eq_steps2 = scripts.check_input('int', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'prep_steps1': prep_steps1 = scripts.check_input('int', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'prep_steps2': prep_steps2 = scripts.check_input('int', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'a_steps1': a_steps1 = scripts.check_input('int', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'a_steps2': a_steps2 = scripts.check_input('int', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'l_steps1': l_steps1 = scripts.check_input('int', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'l_steps2': l_steps2 = scripts.check_input('int', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 't_steps1': t_steps1 = scripts.check_input('int', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 't_steps2': t_steps2 = scripts.check_input('int', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'u_steps1': u_steps1 = scripts.check_input('int', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'u_steps2': u_steps2 = scripts.check_input('int', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'c_steps1': c_steps1 = scripts.check_input('int', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'c_steps2': c_steps2 = scripts.check_input('int', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'r_steps1': r_steps1 = scripts.check_input('int', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'r_steps2': r_steps2 = scripts.check_input('int', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'e_steps1': e_steps1 = scripts.check_input('int', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'e_steps2': e_steps2 = scripts.check_input('int', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'v_steps1': v_steps1 = scripts.check_input('int', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'v_steps2': v_steps2 = scripts.check_input('int', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'w_steps1': w_steps1 = scripts.check_input('int', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'w_steps2': w_steps2 = scripts.check_input('int', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'f_steps1': f_steps1 = scripts.check_input('int', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'f_steps2': f_steps2 = scripts.check_input('int', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'pull_spacing': pull_spacing = scripts.check_input('float', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'poses_list': newline = lines[i][1].strip('\'\"-,.:;#()][').split(',') for j in range(0, len(newline)): poses_list.append(scripts.check_input('int', newline[j], input_file, lines[i][0])) elif lines[i][0] == 'calc_type': calc_type = lines[i][1].lower() elif lines[i][0] == 'celpp_receptor': celp_st = lines[i][1] elif lines[i][0] == 'p1': H1 = lines[i][1] elif lines[i][0] == 'p2': H2 = lines[i][1] elif lines[i][0] == 'p3': H3 = lines[i][1] elif lines[i][0] == 'ligand_name': mol = lines[i][1] elif lines[i][0] == 'fe_type': if lines[i][1].lower() == 'rest': fe_type = lines[i][1].lower() elif lines[i][1].lower() == 'dd': fe_type = lines[i][1].lower() elif lines[i][1].lower() == 'pmf': fe_type = lines[i][1].lower() elif lines[i][1].lower() == 'all': fe_type = lines[i][1].lower() elif lines[i][1].lower() == 'pmf-rest': fe_type = lines[i][1].lower() elif lines[i][1].lower() == 'dd-rest': fe_type = lines[i][1].lower() elif lines[i][1].lower() == 'custom': fe_type = lines[i][1].lower() else: print('Free energy type not recognized, please choose all, rest (restraints), dd (double decoupling) or pmf (umbrella sampling), pmf-rest, dd-rest, or custom') sys.exit(1) elif lines[i][0] == 'dd_type': if lines[i][1].lower() == 'mbar': dd_type = lines[i][1].lower() elif lines[i][1].lower() == 'ti': dd_type = lines[i][1].lower() else: print('Double decoupling type not recognized, please choose ti or mbar') sys.exit(1) elif lines[i][0] == 'blocks': blocks = scripts.check_input('int', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'hmr': if lines[i][1].lower() == 'yes': hmr = 'yes' elif lines[i][1].lower() == 'no': hmr = 'no' else: print('Wrong input! Please use yes or no to indicate whether hydrogen mass repartitioning ' 'will be used.') sys.exit(1) elif lines[i][0] == 'water_model': if lines[i][1].lower() == 'tip3p': water_model = lines[i][1].upper() elif lines[i][1].lower() == 'tip4pew': water_model = lines[i][1].upper() elif lines[i][1].lower() == 'spce': water_model = lines[i][1].upper() else: print('Water model not supported. Please choose TIP3P, TIP4PEW or SPCE') sys.exit(1) elif lines[i][0] == 'num_waters': num_waters = scripts.check_input('int', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'neutralize_only': if lines[i][1].lower() == 'yes': neut = 'yes' elif lines[i][1].lower() == 'no': neut = 'no' else: print('Wrong input! Please choose neutralization only or add extra ions') sys.exit(1) elif lines[i][0] == 'cation': cation = lines[i][1] elif lines[i][0] == 'anion': anion = lines[i][1] elif lines[i][0] == 'num_cations': num_cations = scripts.check_input('int', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'num_cat_ligbox': num_cat_ligbox = scripts.check_input('int', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'buffer_x': buffer_x = scripts.check_input('float', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'buffer_y': buffer_y = scripts.check_input('float', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'lig_buffer': lig_buffer = scripts.check_input('float', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'rec_distance_force': rec_distance_force = scripts.check_input('float', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'rec_angle_force': rec_angle_force = scripts.check_input('float', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'rec_dihcf_force': rec_dihcf_force = scripts.check_input('float', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'rec_discf_force': rec_discf_force = scripts.check_input('float', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'lig_distance_force': lig_distance_force = scripts.check_input('float', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'lig_angle_force': lig_angle_force = scripts.check_input('float', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'lig_dihcf_force': lig_dihcf_force = scripts.check_input('float', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'lig_discf_force': lig_discf_force = scripts.check_input('float', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'l1_x': l1_x = scripts.check_input('float', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'l1_y': l1_y = scripts.check_input('float', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'l1_z': l1_z = scripts.check_input('float', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'l1_zm': l1_zm = scripts.check_input('float', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'l1_range': l1_range = scripts.check_input('float', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'min_adis': min_adis = scripts.check_input('float', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'max_adis': max_adis = scripts.check_input('float', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'rec_bb': if lines[i][1].lower() == 'yes': rec_bb = 'yes' elif lines[i][1].lower() == 'no': rec_bb = 'no' else: print('Wrong input! Please use yes or no to indicate whether protein backbone restraints' 'will be used.') sys.exit(1) elif lines[i][0] == 'bb_start': bb_start = scripts.check_input('int', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'bb_end': bb_end = scripts.check_input('int', lines[i][1], input_file, lines[i][0]) elif lines[i][0] == 'bb_equil': if lines[i][1].lower() == 'yes': bb_equil = lines[i][1].lower() else: bb_equil = 'no' elif lines[i][0] == 'release_eq': strip_line = lines[i][1].strip('\'\"-,.:;#()][').split() for j in range(0, len(strip_line)): release_eq.append(scripts.check_input('float', strip_line[j], input_file, lines[i][0])) elif lines[i][0] == 'translate_apr': strip_line = lines[i][1].strip('\'\"-,.:;#()][').split() for j in range(0, len(strip_line)): translate_apr.append(scripts.check_input('float', strip_line[j], input_file, lines[i][0])) elif lines[i][0] == 'attach_rest': strip_line = lines[i][1].strip('\'\"-,.:;#()][').split() for j in range(0, len(strip_line)): attach_rest.append(scripts.check_input('float', strip_line[j], input_file, lines[i][0])) elif lines[i][0] == 'lambdas': strip_line = lines[i][1].strip('\'\"-,.:;#()][').split() for j in range(0, len(strip_line)): lambdas.append(scripts.check_input('float', strip_line[j], input_file, lines[i][0])) elif lines[i][0] == 'weights': strip_line = lines[i][1].strip('\'\"-,.:;#()][').split() for j in range(0, len(strip_line)): weights.append(scripts.check_input('float', strip_line[j], input_file, lines[i][0])) elif lines[i][0] == 'components': strip_line = lines[i][1].strip('\'\"-,.:;#()][').split() for j in range(0, len(strip_line)): components.append(strip_line[j]) elif lines[i][0] == 'ntpr': ntpr = lines[i][1] elif lines[i][0] == 'ntwr': ntwr = lines[i][1] elif lines[i][0] == 'ntwe': ntwe = lines[i][1] elif lines[i][0] == 'ntwx': ntwx = lines[i][1] elif lines[i][0] == 'cut': cut = lines[i][1] elif lines[i][0] == 'gamma_ln': gamma_ln = lines[i][1] elif lines[i][0] == 'barostat': barostat = lines[i][1] elif lines[i][0] == 'receptor_ff': receptor_ff = lines[i][1] elif lines[i][0] == 'ligand_ff': if lines[i][1].lower() == 'gaff': ligand_ff = 'gaff' elif lines[i][1].lower() == 'gaff2': ligand_ff = 'gaff2' else: print('Wrong input! Available options for ligand force-field are gaff and gaff2') sys.exit(1) elif lines[i][0] == 'dt': dt = lines[i][1] # Number of simulations, 1 equilibrium and 1 production apr_sim = 2 # Define free energy components if fe_type == 'rest': components = ['c', 'a', 'l', 't', 'r'] elif fe_type == 'dd': components = ['e', 'v', 'f', 'w'] elif fe_type == 'pmf': components = ['u'] elif fe_type == 'all': components = ['c', 'a', 'l', 't', 'r', 'u', 'v', 'w', 'e', 'f'] elif fe_type == 'pmf-rest': components = ['c', 'a', 'l', 't', 'r', 'u'] elif fe_type == 'dd-rest': components = ['c', 'a', 'l', 't', 'r', 'e', 'v', 'w', 'f'] # Pull ligand out or not if pull_ligand == 'no': translate_apr = [ 0.00 ] pull_spacing = 1.0 prep_steps2 = 0 # Do not apply protein backbone restraints if rec_bb == 'no': bb_start = 1 bb_end = 0 bb_equil = 'no' # Create poses definitions if calc_type == 'dock': for i in range(0, len(poses_list)): poses_def.append('pose'+str(poses_list[i])) elif calc_type == 'crystal': poses_def = [celp_st] # Total distance apr_distance = translate_apr[-1] rng = 0 # Create restraint definitions rest = [rec_distance_force, rec_angle_force, rec_dihcf_force, rec_discf_force, lig_distance_force, lig_angle_force, lig_dihcf_force, lig_discf_force] # Create ion definitions ion_def = [cation, anion, num_cations] ion_lig = [cation, anion, num_cat_ligbox] # Define number of steps for all stages dic_steps1 = {} dic_steps2 = {} dic_steps1['a'] = a_steps1 dic_steps2['a'] = a_steps2 dic_steps1['l'] = l_steps1 dic_steps2['l'] = l_steps2 dic_steps1['t'] = t_steps1 dic_steps2['t'] = t_steps2 dic_steps1['c'] = c_steps1 dic_steps2['c'] = c_steps2 dic_steps1['r'] = r_steps1 dic_steps2['r'] = r_steps2 if stage == 'equil': comp = 'q' win = 0 trans_dist = 0 # Create equilibrium systems for all poses listed in the input file for i in range(0, len(poses_def)): rng = len(release_eq) - 1 pose = poses_def[i] if not os.path.exists('./all-poses/'+pose+'.pdb'): continue print('Setting up '+str(poses_def[i])) # Get number of simulations num_sim = len(release_eq) # Create aligned initial complex anch = build.build_equil(pose, celp_st, mol, H1, H2, H3, calc_type, l1_x, l1_y, l1_z, l1_zm, l1_range, min_adis, max_adis, ligand_ff) if anch == 'anch1': aa1_poses.append(pose) os.chdir('../') continue if anch == 'anch2': aa2_poses.append(pose) os.chdir('../') continue # Solvate system with ions print('Creating box...') build.create_box(hmr, pose, mol, num_waters, water_model, ion_def, neut, buffer_x, buffer_y, stage, ntpr, ntwr, ntwe, ntwx, cut, gamma_ln, barostat, receptor_ff, ligand_ff, dt) # Apply restraints and prepare simulation files print('Equil release weights:') for i in range(0, len(release_eq)): weight = release_eq[i] print('%s' %str(weight)) setup.restraints(pose, rest, bb_start, bb_end, weight, stage, mol, trans_dist, comp, bb_equil) shutil.copy('./'+pose+'/disang.rest', './'+pose+'/disang%02d.rest' %int(i)) shutil.copy('./'+pose+'/disang%02d.rest' %int(0), './'+pose+'/disang.rest') setup.sim_files(hmr, temperature, mol, num_sim, pose, comp, win, stage, eq_steps1, eq_steps2, rng) os.chdir('../') if len(aa1_poses) != 0: print('\n') print 'WARNING: Could not find the ligand first anchor L1 for', aa1_poses print 'The ligand is most likely not in the defined binding site in these systems.' if len(aa2_poses) != 0: print('\n') print 'WARNING: Could not find the ligand L2 or L3 anchors for', aa2_poses print 'Try reducing the min_adis parameter in the input file.' elif stage == 'prep': win = 0 weight = 100.0 comp = 's' # Prepare systems after equilibration for poses listed in the input file for i in range(0, len(poses_def)): pose = poses_def[i] if not os.path.exists('./equil/'+pose): continue print('Setting up '+str(poses_def[i])) # Get number of simulations num_sim = int(apr_distance/pull_spacing)+1 rng = num_sim - 1 # Create aligned initial complex fwin = len(release_eq) - 1 anch = build.build_prep(pose, mol, fwin, l1_x, l1_y, l1_z, l1_zm, l1_range, min_adis, max_adis) if anch == 'anch1': aa1_poses.append(pose) os.chdir('../') continue if anch == 'anch2': aa2_poses.append(pose) os.chdir('../') continue # Solvate system with ions print('Creating box...') build.create_box(hmr, pose, mol, num_waters, water_model, ion_def, neut, buffer_x, buffer_y, stage, ntpr, ntwr, ntwe, ntwx, cut, gamma_ln, barostat, receptor_ff, ligand_ff, dt) # Apply restraints and prepare simulation files print('Pulling distance interval: %s' %pull_spacing) print('Total pulling distance: %s' %apr_distance) print('Creating pulling steps...') for i in range(0, num_sim): trans_dist = float(i*pull_spacing) setup.restraints(pose, rest, bb_start, bb_end, weight, stage, mol, trans_dist, comp, bb_equil) shutil.copy('./'+pose+'/disang.rest', './'+pose+'/disang%03d.rest' %int(i)) shutil.copy('./'+pose+'/disang%03d.rest' %int(0), './'+pose+'/disang.rest') setup.sim_files(hmr, temperature, mol, num_sim, pose, comp, win, stage, prep_steps1, prep_steps2, rng) os.chdir('../') if len(aa1_poses) != 0: print('\n') print 'WARNING: Could not find the ligand first anchor L1 for', aa1_poses print 'The ligand most likely left the binding site during equilibration.' if len(aa2_poses) != 0: print('\n') print 'WARNING: Could not find the ligand L2 or L3 anchors for', aa2_poses print 'Try reducing the min_adis parameter in the input file.' elif stage == 'fe': # Create systems for all poses after preparation num_sim = apr_sim # Create and move to apr directory if not os.path.exists('fe'): os.makedirs('fe') os.chdir('fe') for i in range(0, len(poses_def)): pose = poses_def[i] if not os.path.exists('../prep/'+pose): continue print('Setting up '+str(poses_def[i])) # Create and move to pose directory if not os.path.exists(pose): os.makedirs(pose) os.chdir(pose) # Generate folder and restraints for all components and windows for j in range(0, len(components)): comp = components[j] # Translation (umbrella) if (comp == 'u'): if not os.path.exists('pmf'): os.makedirs('pmf') os.chdir('pmf') weight = 100.0 for k in range(0, len(translate_apr)): trans_dist = translate_apr[k] win = k print('window: %s%02d distance: %s' %(comp, int(win), str(trans_dist))) build.build_apr(hmr, mol, pose, comp, win, trans_dist, pull_spacing, ntpr, ntwr, ntwe, ntwx, cut, gamma_ln, barostat, receptor_ff, ligand_ff, dt) setup.sim_files(hmr, temperature, mol, num_sim, pose, comp, win, stage, u_steps1, u_steps2, rng) os.chdir('../') # Ligand conformational release in a small box elif (comp == 'c'): if not os.path.exists('rest'): os.makedirs('rest') os.chdir('rest') trans_dist = 0 for k in range(0, len(attach_rest)): weight = attach_rest[k] win = k if int(win) == 0: print('window: %s%02d weight: %s' %(comp, int(win), str(weight))) build.build_apr(hmr, mol, pose, comp, win, trans_dist, pull_spacing, ntpr, ntwr, ntwe, ntwx, cut, gamma_ln, barostat, receptor_ff, ligand_ff, dt) print('Creating box for ligand only...') build.ligand_box(mol, lig_buffer, water_model, neut, ion_lig, comp, ligand_ff) setup.restraints(pose, rest, bb_start, bb_end, weight, stage, mol, trans_dist, comp, bb_equil) setup.sim_files(hmr, temperature, mol, num_sim, pose, comp, win, stage, c_steps1, c_steps2, rng) else: print('window: %s%02d weight: %s' %(comp, int(win), str(weight))) build.build_apr(hmr, mol, pose, comp, win, trans_dist, pull_spacing, ntpr, ntwr, ntwe, ntwx, cut, gamma_ln, barostat, receptor_ff, ligand_ff, dt) setup.restraints(pose, rest, bb_start, bb_end, weight, stage, mol, trans_dist, comp, bb_equil) setup.sim_files(hmr, temperature, mol, num_sim, pose, comp, win, stage, c_steps1, c_steps2, rng) os.chdir('../') # Receptor conformational release in a separate box elif (comp == 'r'): if not os.path.exists('rest'): os.makedirs('rest') os.chdir('rest') trans_dist = translate_apr[-1] for k in range(0, len(attach_rest)): weight = attach_rest[k] win = k if int(win) == 0: print('window: %s%02d weight: %s' %(comp, int(win), str(weight))) build.build_apr(hmr, mol, pose, comp, win, trans_dist, pull_spacing, ntpr, ntwr, ntwe, ntwx, cut, gamma_ln, barostat, receptor_ff, ligand_ff, dt) print('Creating box for apo protein...') build.create_box(hmr, pose, mol, num_waters, water_model, ion_def, neut, buffer_x, buffer_y, stage, ntpr, ntwr, ntwe, ntwx, cut, gamma_ln, barostat, receptor_ff, ligand_ff, dt) setup.restraints(pose, rest, bb_start, bb_end, weight, stage, mol, trans_dist, comp, bb_equil) setup.sim_files(hmr, temperature, mol, num_sim, pose, comp, win, stage, r_steps1, r_steps2, rng) else: print('window: %s%02d weight: %s' %(comp, int(win), str(weight))) build.build_apr(hmr, mol, pose, comp, win, trans_dist, pull_spacing, ntpr, ntwr, ntwe, ntwx, cut, gamma_ln, barostat, receptor_ff, ligand_ff, dt) setup.restraints(pose, rest, bb_start, bb_end, weight, stage, mol, trans_dist, comp, bb_equil) setup.sim_files(hmr, temperature, mol, num_sim, pose, comp, win, stage, r_steps1, r_steps2, rng) os.chdir('../') # Van der Waals decoupling # site elif (comp == 'v'): if not os.path.exists('dd'): os.makedirs('dd') os.chdir('dd') trans_dist = 0 if not os.path.exists('site'): os.makedirs('site') os.chdir('site') for k in range(0, len(lambdas)): weight = lambdas[k] win = k print('window: %s%02d lambda: %s' %(comp, int(win), str(weight))) build.build_apr(hmr, mol, pose, comp, win, trans_dist, pull_spacing, ntpr, ntwr, ntwe, ntwx, cut, gamma_ln, barostat, receptor_ff, ligand_ff, dt) setup.dec_files(temperature, mol, num_sim, pose, comp, win, stage, v_steps1, v_steps2, weight, lambdas) os.chdir('../../') # bulk elif (comp == 'w'): if not os.path.exists('dd'): os.makedirs('dd') os.chdir('dd') trans_dist = 0 if not os.path.exists('bulk'): os.makedirs('bulk') os.chdir('bulk') for k in range(0, len(lambdas)): weight = lambdas[k] win = k if int(win) == 0: print('window: %s%02d lambda: %s' %(comp, int(win), str(weight))) build.build_apr(hmr, mol, pose, comp, win, trans_dist, pull_spacing, ntpr, ntwr, ntwe, ntwx, cut, gamma_ln, barostat, receptor_ff, ligand_ff, dt) print('Creating box for ligand only...') build.ligand_box(mol, lig_buffer, water_model, neut, ion_lig, comp, ligand_ff) setup.restraints(pose, rest, bb_start, bb_end, weight, stage, mol, trans_dist, comp, bb_equil) setup.dec_files(temperature, mol, num_sim, pose, comp, win, stage, w_steps1, w_steps2, weight, lambdas) else: print('window: %s%02d lambda: %s' %(comp, int(win), str(weight))) build.build_apr(hmr, mol, pose, comp, win, trans_dist, pull_spacing, ntpr, ntwr, ntwe, ntwx, cut, gamma_ln, barostat, receptor_ff, ligand_ff, dt) setup.dec_files(temperature, mol, num_sim, pose, comp, win, stage, w_steps1, w_steps2, weight, lambdas) os.chdir('../../') # Charge decoupling # site elif (comp == 'e'): if not os.path.exists('dd'): os.makedirs('dd') os.chdir('dd') trans_dist = 0 if not os.path.exists('site'): os.makedirs('site') os.chdir('site') for k in range(0, len(lambdas)): weight = lambdas[k] win = k print('window: %s%02d lambda: %s' %(comp, int(win), str(weight))) build.build_dec(hmr, mol, pose, comp, win, water_model, ntpr, ntwr, ntwe, ntwx, cut, gamma_ln, barostat, receptor_ff, ligand_ff, dt) setup.dec_files(temperature, mol, num_sim, pose, comp, win, stage, e_steps1, e_steps2, weight, lambdas) os.chdir('../../') # bulk elif (comp == 'f'): if not os.path.exists('dd'): os.makedirs('dd') os.chdir('dd') trans_dist = 0 if not os.path.exists('bulk'): os.makedirs('bulk') os.chdir('bulk') for k in range(0, len(lambdas)): weight = lambdas[k] win = k if int(win) == 0: print('window: %s%02d lambda: %s' %(comp, int(win), str(weight))) build.build_dec(hmr, mol, pose, comp, win, water_model, ntpr, ntwr, ntwe, ntwx, cut, gamma_ln, barostat, receptor_ff, ligand_ff, dt) print('Creating box for ligand decharging in bulk...') build.ligand_box(mol, lig_buffer, water_model, neut, ion_lig, comp, ligand_ff) setup.restraints(pose, rest, bb_start, bb_end, weight, stage, mol, trans_dist, comp, bb_equil) setup.dec_files(temperature, mol, num_sim, pose, comp, win, stage, f_steps1, f_steps2, weight, lambdas) else: print('window: %s%02d lambda: %s' %(comp, int(win), str(weight))) build.build_dec(hmr, mol, pose, comp, win, water_model, ntpr, ntwr, ntwe, ntwx, cut, gamma_ln, barostat, receptor_ff, ligand_ff, dt) setup.dec_files(temperature, mol, num_sim, pose, comp, win, stage, f_steps1, f_steps2, weight, lambdas) os.chdir('../../') # Attachments in the bound system else: if not os.path.exists('rest'): os.makedirs('rest') os.chdir('rest') trans_dist = 0 for k in range(0, len(attach_rest)): weight = attach_rest[k] win = k print('window: %s%02d weight: %s' %(comp, int(win), str(weight))) build.build_apr(hmr, mol, pose, comp, win, trans_dist, pull_spacing, ntpr, ntwr, ntwe, ntwx, cut, gamma_ln, barostat, receptor_ff, ligand_ff, dt) setup.restraints(pose, rest, bb_start, bb_end, weight, stage, mol, trans_dist, comp, bb_equil) steps1 = dic_steps1[comp] steps2 = dic_steps2[comp] setup.sim_files(hmr, temperature, mol, num_sim, pose, comp, win, stage, steps1, steps2, rng) os.chdir('../') os.chdir('../') elif stage == 'analysis': # Free energies MBAR/TI and analytical calculations for i in range(0, len(poses_def)): pose = poses_def[i] analysis.fe_values(blocks, components, temperature, pose, attach_rest, translate_apr, lambdas, weights, dd_type, rest) os.chdir('../../')
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 17, 198, 11748, 15095, 355, 15095, 198, 11748, 28686, 355, 28686, 198, 11748, 302, 198, 11748, 4423, 346, 355, 4423, 346, 198, 11748, 6737, 355, 6737, 198, 11748, 850, 14681, 355, 599, 198, ...
2.195324
12,661
# -*- coding: utf-8 -*- # Generated by Django 1.11.29 on 2021-06-30 06:22 from __future__ import unicode_literals from django.db import migrations, models
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 352, 13, 1157, 13, 1959, 319, 33448, 12, 3312, 12, 1270, 9130, 25, 1828, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198...
2.754386
57
from pathlib import Path from typing import Optional, Tuple import typer from onlinejudge import utils from pydantic.networks import HttpUrl from pydantic.types import DirectoryPath from judge.schema import JudgeConfig from judge.tools.download import DownloadArgs, LoginForm, SaveArgs from judge.tools.download import download as download_tool from judge.tools.download import save as save_tool def main( workdir: Path = typer.Argument(".", help="a directory path for working directory"), url: Optional[str] = typer.Option(None, help="a download URL"), directory: Path = typer.Option(None, help="a directory path for test cases"), no_store: bool = typer.Option(False, help="testcases is shown but not saved"), format: str = typer.Option("sample-%i.%e", help="custom filename format"), login: bool = typer.Option(False, help="login into target service"), cookie: Path = typer.Option(utils.default_cookie_path, help="directory for cookie"), ) -> None: """ Here is shortcut for download with `online-judge-tools`. At first, call `judge conf` for configuration. Pass `problem` at `contest` you want to test. Ex) the following leads to download test cases for Problem `C` at `ABC 051`: ```download``` """ typer.echo("Load configuration...") if not workdir.exists(): typer.secho(f"Not exists: {str(workdir.resolve())}", fg=typer.colors.BRIGHT_RED) raise typer.Abort() try: _config = JudgeConfig.from_toml(workdir) except KeyError as e: typer.secho(str(e), fg=typer.colors.BRIGHT_RED) raise typer.Abort() __config = _config.dict() if url or directory: # check arguments if url: __config["URL"] = url if directory: __config["testdir"] = directory.resolve() try: config = DownloadJudgeConfig(**__config) except KeyError as e: typer.secho(str(e), fg=typer.colors.BRIGHT_RED) raise typer.Abort() typer.echo(f"Download {config.URL}") try: login_form: Optional[LoginForm] = None if login: login_form = CLILoginForm() testcases = download_tool( DownloadArgs( url=config.URL, login_form=login_form, cookie=cookie, ) ) except Exception as e: typer.secho(str(e), fg=typer.colors.BRIGHT_RED) raise typer.Abort() if not no_store: try: save_tool( testcases, SaveArgs( format=format, directory=Path(config.testdir), ), ) except Exception as e: typer.secho(str(e), fg=typer.colors.BRIGHT_RED) raise typer.Abort() if __name__ == "__main__": typer.run(main)
[ 6738, 3108, 8019, 1330, 10644, 198, 6738, 19720, 1330, 32233, 11, 309, 29291, 198, 198, 11748, 1259, 525, 198, 6738, 2691, 10456, 469, 1330, 3384, 4487, 198, 6738, 279, 5173, 5109, 13, 3262, 5225, 1330, 367, 29281, 28165, 198, 6738, 279...
2.323841
1,229
import re import difflib from ansible import errors
[ 11748, 302, 198, 11748, 814, 8019, 198, 6738, 9093, 856, 1330, 8563, 628 ]
4.076923
13
from django.urls import path from .api.view import get_all_countries_view app_name = "core" urlpatterns = [ path('all-countries', get_all_countries_view) ]
[ 6738, 42625, 14208, 13, 6371, 82, 1330, 3108, 198, 6738, 764, 15042, 13, 1177, 1330, 651, 62, 439, 62, 9127, 1678, 62, 1177, 198, 198, 1324, 62, 3672, 796, 366, 7295, 1, 198, 6371, 33279, 82, 796, 685, 198, 220, 220, 220, 3108, 10...
2.639344
61
import atexit import os import re import shutil from enum import Enum from typing import List, Optional import collections from gitflow import cli, const, repotools, _, utils from gitflow.common import Result from gitflow.const import VersioningScheme from gitflow.properties import PropertyIO from gitflow.repotools import RepoContext from gitflow.version import VersionMatcher, VersionConfig
[ 11748, 379, 37023, 198, 11748, 28686, 198, 11748, 302, 198, 11748, 4423, 346, 198, 6738, 33829, 1330, 2039, 388, 198, 6738, 19720, 1330, 7343, 11, 32233, 198, 198, 11748, 17268, 198, 198, 6738, 17606, 11125, 1330, 537, 72, 11, 1500, 11,...
3.801887
106
from model.contact import Contact from random import randrange #def test_modify_first_contact_first_name(app): # if app.contact.count() == 0: # app.contact.create(Contact(first_name="test")) # old_contacts = app.contact.get_contact_list() # app.contact.modify_first_contact(Contact(first_name="zmodyfikuj imie")) # new_contacts = app.contact.get_contact_list() # assert len(old_contacts) == len(new_contacts) #def test_modify_first_contact_email(app): # if app.contact.count() == 0: # app.contact.create(Contact(first_name="test")) # old_contacts = app.contact.get_contact_list() # app.contact.modify_first_contact(Contact(last_name="Zmodyfikuj nazwisko")) # new_contacts = app.contact.get_contact_list() # assert len(old_contacts) == len(new_contacts)
[ 6738, 2746, 13, 32057, 1330, 14039, 198, 6738, 4738, 1330, 43720, 9521, 628, 198, 198, 2, 4299, 1332, 62, 4666, 1958, 62, 11085, 62, 32057, 62, 11085, 62, 3672, 7, 1324, 2599, 198, 2, 220, 220, 220, 611, 598, 13, 32057, 13, 9127, ...
2.567308
312
import webapp2 from webapp2_extras import sessions
[ 11748, 3992, 1324, 17, 198, 6738, 3992, 1324, 17, 62, 2302, 8847, 1330, 10991 ]
3.571429
14
import unittest try: from unittest.mock import Mock, call except ImportError: from mock import Mock, call from dbhelpers import cm_cursor, fetchiter, fetchone_nt, fetchmany_nt, fetchall_nt, fetchiter_nt
[ 11748, 555, 715, 395, 198, 28311, 25, 198, 220, 220, 220, 422, 555, 715, 395, 13, 76, 735, 1330, 44123, 11, 869, 198, 16341, 17267, 12331, 25, 198, 220, 220, 220, 422, 15290, 1330, 44123, 11, 869, 198, 198, 6738, 20613, 16794, 364, ...
2.958333
72
#!/usr/bin/env python # THIS SHEBANG IS REALLY REALLY IMPORTANT import rospy import roscpp import numpy as np from sensor_msgs.msg import Joy from std_msgs.msg import Int16MultiArray if __name__ == '__main__': try: # boiler plate to spin up a node. rospy.init_node('joystick_node') node = JoystickNode() except rospy.ROSInterruptException: rospy.logwarn('ERROR!!!')
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 220, 198, 2, 12680, 6006, 30195, 15567, 3180, 36413, 36413, 30023, 9863, 8643, 198, 11748, 686, 2777, 88, 198, 11748, 686, 1416, 381, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 12694, 62,...
2.475904
166
# -*- coding: utf-8 -*- # Copyright (c) 2015, Soldeva, SRL and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 15069, 357, 66, 8, 1853, 11, 12324, 48855, 11, 311, 7836, 290, 20420, 198, 2, 1114, 5964, 1321, 11, 3387, 766, 5964, 13, 14116, 198, 198, 6738, 11593, 37443, 834, ...
3.430769
65
import logging import typing from electrumsv_sdk.utils import get_directory_name COMPONENT_NAME = get_directory_name(__file__) logger = logging.getLogger(COMPONENT_NAME) if typing.TYPE_CHECKING: from .electrumsv_server import Plugin
[ 11748, 18931, 198, 198, 11748, 19720, 198, 198, 6738, 30880, 5700, 85, 62, 21282, 74, 13, 26791, 1330, 651, 62, 34945, 62, 3672, 628, 198, 9858, 47, 1340, 3525, 62, 20608, 796, 651, 62, 34945, 62, 3672, 7, 834, 7753, 834, 8, 198, ...
2.927711
83
# -*- coding: utf-8 -*- # pylint: disable=all import base64 import binascii import contextlib import math import os import textwrap import time import urllib.parse from const import LOGS_PATH from logparser import parse from utils import is_nan, print_file # from utils import IPAddressJSONEncoder, is_nan, print_file # today DATE = time.strftime('%Y-%m-%d') # log path LOGS = os.path.join(LOGS_PATH, 'http') os.makedirs(LOGS, exist_ok=True) # http log HTTP_LOG = os.path.join(LOGS_PATH, 'http', f'{DATE}.log') # macros SEPARATOR = '\t' SET_SEPARATOR = ',' EMPTY_FIELD = '(empty)' UNSET_FIELD = 'NoDef' FIELDS = ('scrip', 'ad', 'ts', 'url', 'ref', 'ua', 'dstip', 'cookie', 'src_port', 'json', 'method', 'body') TYPES = ('addr', 'string', 'time', 'string', 'string', 'string', 'addr', 'string', 'port', 'vector[string]', 'string', 'string')
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 279, 2645, 600, 25, 15560, 28, 439, 198, 198, 11748, 2779, 2414, 198, 11748, 9874, 292, 979, 72, 198, 11748, 4732, 8019, 198, 11748, 10688, 198, 11748, 28686, 198, ...
2.564565
333
import numpy as np from src.compute_corr_coef import compute_corr_coef from utils.plotting import plot_similarities def compute_trust_values(dsk, do_plot=False): """ Compute trust values following formula 6 k:= number of blendshapes n:= num_features (num_markers*3) :param dsk: delta_sk vector (k, n) :param do_plot: decide if we want to plot the between-correlation matrix :return: trust values vector (k,) """ if len(np.shape(dsk)) != 2: raise ValueError("[COMPUTE TRUST VALUE] dsk dimensions not supported ({}) instead of 2".format(len(np.shape(dsk)))) # compute between-blendshape correlation ckl = compute_corr_coef(dsk, dsk) ckl = np.maximum(ckl, np.zeros(np.shape(ckl))) if do_plot: plot_similarities(ckl, "Between blendshapes correlation", vmin=0, vmax=1) # compute lower triangle num_k = np.shape(ckl)[0] low_trig = np.zeros(num_k) for k in range(num_k): val = 0 for l in range(k): val += ckl[k, l] low_trig[k] = val max_low_trig = np.max(low_trig) # compute trust values (formula 6) tk = np.zeros(num_k) for k in range(len(tk)): tk[k] = 1 - low_trig[k]/max_low_trig return tk if __name__ == '__main__': """ test compute_trust_values function run: python -m src.compute_trust_values """ np.random.seed(0) from utils.re_order_delta import re_order_delta # test compute trust values sk = np.random.rand(6, 3) # (k, n) sorted_sk = re_order_delta(sk) tk = compute_trust_values(sorted_sk, do_plot=False) print("tk") print(tk)
[ 11748, 299, 32152, 355, 45941, 198, 6738, 12351, 13, 5589, 1133, 62, 10215, 81, 62, 1073, 891, 1330, 24061, 62, 10215, 81, 62, 1073, 891, 198, 6738, 3384, 4487, 13, 29487, 889, 1330, 7110, 62, 38610, 871, 628, 198, 4299, 24061, 62, ...
2.290682
719
import unittest from jaqalpaq.core.parameter import ParamType from jaqalpaq.core.constant import Constant from . import randomize from . import common if __name__ == "__main__": unittest.main()
[ 11748, 555, 715, 395, 198, 198, 6738, 474, 30188, 282, 8957, 80, 13, 7295, 13, 17143, 2357, 1330, 25139, 6030, 198, 6738, 474, 30188, 282, 8957, 80, 13, 7295, 13, 9979, 415, 1330, 20217, 198, 6738, 764, 1330, 4738, 1096, 198, 6738, ...
2.927536
69
# -*- coding: utf-8 -*- # richard -- video index system # Copyright (C) 2012, 2013, 2014, 2015 richard contributors. See AUTHORS. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from __future__ import unicode_literals from django.db import models, migrations
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 5527, 446, 1377, 2008, 6376, 1080, 198, 2, 15069, 357, 34, 8, 2321, 11, 2211, 11, 1946, 11, 1853, 5527, 446, 20420, 13, 220, 4091, 37195, 20673, 13, 198, 2, ...
3.679325
237
""" copy-paste from my (beckermr) personal code here https://github.com/beckermr/metadetect-coadding-sims """ import numpy as np import galsim from descwl_shear_sims.masking import get_bmask_and_set_image from descwl_shear_sims.artifacts import ( generate_bad_columns, generate_cosmic_rays, )
[ 37811, 198, 30073, 12, 34274, 422, 616, 357, 27343, 7780, 81, 8, 2614, 2438, 994, 198, 5450, 1378, 12567, 13, 785, 14, 27343, 7780, 81, 14, 4164, 324, 316, 478, 12, 1073, 26872, 12, 82, 12078, 198, 37811, 198, 11748, 299, 32152, 355...
2.669565
115
from getpass import getpass import os from .utils import Command from .db import DB
[ 6738, 651, 6603, 1330, 651, 6603, 198, 11748, 28686, 198, 198, 6738, 764, 26791, 1330, 9455, 198, 6738, 764, 9945, 1330, 20137, 628, 628, 628 ]
3.6
25
#!/usr/bin/env python # Reverse Integer https://oj.leetcode.com/problems/reverse-integer/ # Reverse digits of an integer. # Example1: x = 123, return 321 # Example2: x = -123, return -321 #Math # Xilin SUN # Dec 7 2014
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 201, 198, 2, 31849, 34142, 3740, 1378, 13210, 13, 293, 316, 8189, 13, 785, 14, 1676, 22143, 14, 50188, 12, 41433, 14, 201, 198, 2, 31849, 19561, 286, 281, 18253, 13, 201, 198, 2, 17934, ...
2.643678
87
############################################################################## # # Copyright (c) 2005 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################# """Configurator Test Setup""" import re import doctest from zope.component import testing from zope.testing.renormalizing import RENormalizing
[ 29113, 29113, 7804, 4242, 2235, 198, 2, 198, 2, 15069, 357, 66, 8, 5075, 1168, 3008, 5693, 290, 25767, 669, 13, 198, 2, 1439, 6923, 33876, 13, 198, 2, 198, 2, 770, 3788, 318, 2426, 284, 262, 8617, 286, 262, 1168, 3008, 5094, 13789...
4.078125
192
from skin_reaper import SkinReaper if __name__ == "__main__": r = SkinReaper() data = r.harvestLinks(5) r.setSkinPreview() r.collectRandom(data) r.kill()
[ 6738, 4168, 62, 260, 2136, 1330, 17847, 3041, 2136, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 374, 796, 17847, 3041, 2136, 3419, 198, 220, 220, 220, 1366, 796, 374, 13, 9869, 4223, 31815, ...
2.351351
74
# Credits go to <http://codereview.stackexchange.com/q/37522> import random import time def current_time(): '''Returns a tuple containing (hour, minute) for current local time.''' local_time = time.localtime(time.time()) return (local_time.tm_hour, local_time.tm_min) (hour, minute) = current_time() print(ishtime(hour, minute))
[ 2, 29501, 467, 284, 1279, 4023, 1378, 19815, 567, 1177, 13, 301, 330, 365, 87, 3803, 13, 785, 14, 80, 14, 22318, 1828, 29, 198, 11748, 4738, 198, 11748, 640, 628, 198, 4299, 1459, 62, 2435, 33529, 198, 220, 220, 220, 705, 7061, 35...
2.852459
122
from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='solar-viability-tester', version='1.0.0', description='Solar viability tester utilizing the AT&T IoT Starter Kit and PubNub.', long_description=long_description, url='https://github.com/ckuzma/solar-viability-tester', license='Apache-2.0' )
[ 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 201, 198, 6738, 40481, 82, 1330, 1280, 201, 198, 6738, 28686, 1330, 3108, 201, 198, 201, 198, 1456, 796, 3108, 13, 397, 2777, 776, 7, 6978, 13, 15908, 3672, 7, 834, 7753, 834...
2.674419
215
# -*- coding: utf-8 -*- # @Time : 2021/5/4 3:05 # @Author : godwaitup # @FileName: framework.py # original framework for joint extraction. import torch.optim as optim from torch import nn import os import data_loader import torch.nn.functional as F import numpy as np import json from functools import partial from data_loader import cmed_collate_fn import torch
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2488, 7575, 220, 220, 220, 1058, 33448, 14, 20, 14, 19, 513, 25, 2713, 198, 2, 2488, 13838, 220, 1058, 5770, 17077, 929, 198, 2, 2488, 8979, 5376, 25, 9355, 13, ...
3.065574
122
""" Settings for application when being run in the test suite. """ import os import sys # Add the directory containing this file to the search path sys.path.append(os.path.dirname(os.path.abspath(__file__))) # Import function to generate a self-signed cert dynamically from x509cert import gen_self_signed_cert DEBUG = True TESTING = True SECRET_KEY = 'bonjour, monde' # Configure the testing database. The database URI is specified by the # COMPONENTSDB_DATABASE_URI environment variable. SQLALCHEMY_DATABASE_URI = os.environ.get( 'COMPONENTSDB_DATABASE_URI', 'sqlite://' ) SQLALCHEMY_ECHO = True _cert, _key = gen_self_signed_cert() GOOGLE_OAUTH2_CERTS = {'selfsigned': _cert} GOOGLE_OAUTH2_ALLOWED_CLIENT_IDS = ['my-client'] TESTING_GOOGLE_OAUTH2_CERT_PRIV_KEYS = {'selfsigned': _key}
[ 37811, 198, 26232, 329, 3586, 618, 852, 1057, 287, 262, 1332, 18389, 13, 198, 198, 37811, 198, 11748, 28686, 198, 11748, 25064, 198, 198, 2, 3060, 262, 8619, 7268, 428, 2393, 284, 262, 2989, 3108, 198, 17597, 13, 6978, 13, 33295, 7, ...
2.690236
297
ips = [ '10.0.0.5', '10.5.3.1', '192.168.11.10', '2.2.2.2', '100.0.0.1', '20.3.2.4' ] print(sort_ips(ips))
[ 198, 220, 220, 220, 220, 220, 220, 220, 220, 198, 2419, 796, 685, 198, 197, 6, 940, 13, 15, 13, 15, 13, 20, 3256, 198, 197, 6, 940, 13, 20, 13, 18, 13, 16, 3256, 198, 197, 6, 17477, 13, 14656, 13, 1157, 13, 940, 3256, 198, ...
1.351064
94
#!/usr/bin/python import os import sys import glob import argparse import tempfile import numpy as np from scipy.io import * from scipy import stats from subprocess import Popen, PIPE from scai_utils import * from get_qdec_info import get_qdec_info from read_xml_labels import read_xml_labels atlas_label_fn = \ "/usr/share/fsl/5.0/data/atlases/JHU/JHU-ICBM-labels-1mm.nii.gz" atlas_label_xml = \ "/usr/share/fsl/5.0/data/atlases/JHU-labels.xml" P_THRESH_UNC = 0.05 if __name__ == "__main__": ap = argparse.ArgumentParser(description="Get stats (e.g., average FA) from in atlas-defined WM regions in TBSS-aligned diffusion-tensor images") ap.add_argument("tbssDir", help="Base TBSS directory (e.g., /users/cais/STUT/analysis/dt_tbss_dtiprep2)") if len(sys.argv) == 1: ap.print_help() sys.exit(0) # === Parse input arguments === # args = ap.parse_args() tbssDir = args.tbssDir # === Input sanity check === # check_dir(tbssDir) statsDir = os.path.join(tbssDir, "stats") check_dir(statsDir) origDir = os.path.join(tbssDir, "origdata") check_dir(origDir) check_file(atlas_label_fn) # === Read JHU-ICBM labels === # check_file(atlas_label_xml) labs = read_xml_labels(atlas_label_xml) # === Locate the all_FA image === # allFA = os.path.join(statsDir, "all_FA.nii.gz") check_file(allFA) # === Find out the subject IDs and their groups === # origDir = os.path.join(tbssDir, "origdata") check_dir(origDir) ds = glob.glob(os.path.join(origDir, "S??.nii.gz")) ds.sort() sIDs = [] idxPWS = [] idxPFS = [] for (i0, d) in enumerate(ds): [tpath, tfn] = os.path.split(d) sID = tfn.replace(".nii.gz", "") sIDs.append(sID) if get_qdec_info(sID, "diagnosis") == "PWS": idxPWS.append(i0) elif get_qdec_info(sID, "diagnosis") == "PFS": idxPFS.append(i0) else: raise Exception, "Unrecognized diagnosis for subject %s: %s" % \ (sID, get_qdec_info(sID, "diagnosis")) # === Split the all_FA image, for later use by fslstats === # splitBase = tempfile.mktemp() split_cmd = "fslsplit %s %s -t" % (allFA, splitBase) saydo(split_cmd) splitFNs = glob.glob(splitBase + "*.nii.gz") splitFNs.sort() if len(splitFNs) != len(sIDs): raise Exception, "Number of volumes in 4D series %s (%d) does not match the number of subjects in origdata (%d)" % \ (allFA, len(splitFNs), len(sIDs)) # === Iterate through the WM labels and get the stats info === # labRes = {"labels": [], "meanFA": [], "tt_t": [], "tt_p": []} for (i0, lab) in enumerate(labs['name']): ind = labs['ind'][i0] if ind == 0: continue print("\nProcessing label #%d: %s\n" % (i0, lab)) labRes["labels"].append(lab) labRes["meanFA"].append({"PWS": [], "PFS": []}) tmpfn = tempfile.mktemp() + ".nii.gz" # == Binarize, get label mask == # bin_cmd = "mri_binarize --i %s --match %d --o %s" % \ (atlas_label_fn, ind, tmpfn) saydo(bin_cmd) check_file(tmpfn) # == Use fslstats to get the masked mean == # t_vals = [-1] * len(sIDs) for (i1, splitFN) in enumerate(splitFNs): (sout, serr) = Popen(["fslstats", splitFN, "-k", tmpfn, "-m"], \ stdout=PIPE, stderr=PIPE).communicate() if len(serr) > 0: raise Exception, \ "ERROR occurred during fslstats on %s" % splitFN t_vals[i1] = float(sout.split(' ')[0]) t_vals = np.array(t_vals) labRes["meanFA"][-1]["PWS"] = t_vals[idxPWS] labRes["meanFA"][-1]["PFS"] = t_vals[idxPFS] (t, p) = stats.ttest_ind(labRes["meanFA"][-1]["PWS"], \ labRes["meanFA"][-1]["PFS"]) labRes["tt_t"].append(t) labRes["tt_p"].append(p) os.system("rm -f %s" % tmpfn) os.system("rm -f %s*" % splitBase) # === Save results to mat file === # resMatFN = "/users/cais/STUT/scripts/tbss_wm_atlas_stats.mat" os.system("rm -f %s" % resMatFN) savemat(resMatFN, labRes) check_file(resMatFN) print("\nINFO: Results saved to .mat file: %s" % resMatFN) # === Print results === # print("=== Significant results at P_THRESH_UNC = %f ===" % P_THRESH_UNC) for (i0, labName) in enumerate(labRes["labels"]): if labRes["tt_p"][i0] < P_THRESH_UNC: mean_PFS = np.mean(labRes["meanFA"][i0]["PFS"]) mean_PWS = np.mean(labRes["meanFA"][i0]["PWS"]) ste_PFS = np.std(labRes["meanFA"][i0]["PFS"]) / \ np.sqrt(len(idxPFS)) ste_PWS = np.std(labRes["meanFA"][i0]["PWS"]) / \ np.sqrt(len(idxPWS)) print("WM label [%s]:" % labName) print("\tPFS: mean = %f; SE = %f" % (mean_PFS, ste_PFS)) print("\tPWS: mean = %f; SE = %f" % (mean_PWS, ste_PWS)) print("\tt = %f; p = %f" % \ (labRes["tt_t"][i0], labRes["tt_p"][i0]))
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 15095, 198, 11748, 1822, 29572, 198, 11748, 20218, 7753, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 629, 541, 88, 13, 952, 1330, 1635, 198,...
1.929063
2,763
# Module to scrap all auction listings on the auction prices page from selenium import webdriver from bs4 import BeautifulSoup import csv import os # Utility to write as .csv file format # Selenium Driver Handler # Main handler controlling all auction listing parsing # Entry-point of the progran # Capability for stand-alone execution if __name__ == '__main__': main()
[ 2, 19937, 284, 15881, 477, 14389, 26890, 319, 262, 14389, 4536, 2443, 201, 198, 6738, 384, 11925, 1505, 1330, 3992, 26230, 201, 198, 6738, 275, 82, 19, 1330, 23762, 50, 10486, 201, 198, 11748, 269, 21370, 201, 198, 11748, 28686, 201, ...
3.327731
119
/home/runner/.cache/pip/pool/7d/da/46/b543433b18dcfd975ecc18a25baa2105812baf0edc0bdbfae3890e1df2
[ 14, 11195, 14, 16737, 11757, 23870, 14, 79, 541, 14, 7742, 14, 22, 67, 14, 6814, 14, 3510, 14, 65, 4051, 2682, 2091, 65, 1507, 67, 12993, 67, 42716, 68, 535, 1507, 64, 1495, 7012, 64, 21536, 3365, 1065, 65, 1878, 15, 276, 66, 15...
1.745455
55
"""Location cards.""" import logging from onirim.card._base import ColorCard from onirim import exception from onirim import util LOGGER = logging.getLogger(__name__) def _can_obtain_door(content): """ Check if the explored cards can obtain a door. """ last_card = content.explored[-1] same_count = 0 for card in reversed(content.explored): if last_card.color == card.color: same_count += 1 else: break return same_count % 3 == 0 def sun(color): """ Make a sun location card with specific color. Args: color (Color): The specific color. Returns: Card: A sun location card. """ return _Location(color, LocationKind.sun) def moon(color): """ Make a moon location card with specific color. Args: color (Color): The specific color. Returns: Card: A moon location card. """ return _Location(color, LocationKind.moon) def key(color): """ Make a key location card with specific color. Args: color (Color): The specific color. Returns: Card: A key location card. """ return _KeyLocation(color)
[ 37811, 14749, 4116, 526, 15931, 198, 198, 11748, 18931, 198, 198, 6738, 319, 343, 320, 13, 9517, 13557, 8692, 1330, 5315, 16962, 198, 6738, 319, 343, 320, 1330, 6631, 198, 6738, 319, 343, 320, 1330, 7736, 628, 198, 25294, 30373, 796, ...
2.569892
465
import pytest from gitlabform.gitlabform import GitLabForm from gitlabform.gitlabform.test import create_group, create_project_in_group, get_gitlab, create_readme_in_project, \ GROUP_NAME PROJECT_NAME = 'branches_project' GROUP_AND_PROJECT_NAME = GROUP_NAME + '/' + PROJECT_NAME protect_branch_but_allow_all = """ gitlab: api_version: 4 project_settings: gitlabform_tests_group/branches_project: branches: protect_branch_but_allow_all: protected: true developers_can_push: true developers_can_merge: true """ protect_branch_and_disallow_all = """ gitlab: api_version: 4 project_settings: gitlabform_tests_group/branches_project: branches: protect_branch_and_disallow_all: protected: true developers_can_push: false developers_can_merge: false """ mixed_config = """ gitlab: api_version: 4 project_settings: gitlabform_tests_group/branches_project: branches: protect_branch_and_allow_merges: protected: true developers_can_push: false developers_can_merge: true protect_branch_and_allow_pushes: protected: true developers_can_push: true developers_can_merge: false """ unprotect_branches = """ gitlab: api_version: 4 project_settings: gitlabform_tests_group/branches_project: branches: protect_branch_and_allow_merges: protected: false protect_branch_and_allow_pushes: protected: false """
[ 11748, 12972, 9288, 198, 198, 6738, 17606, 23912, 687, 13, 18300, 23912, 687, 1330, 15151, 17822, 8479, 198, 6738, 17606, 23912, 687, 13, 18300, 23912, 687, 13, 9288, 1330, 2251, 62, 8094, 11, 2251, 62, 16302, 62, 259, 62, 8094, 11, 6...
2.468439
602
from bespin.errors import StackDepCycle
[ 6738, 7284, 11635, 13, 48277, 1330, 23881, 12156, 20418, 2375, 628 ]
3.727273
11
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """events.py Pulse sequence events for the Arduino Due pulsebox. Radim Hok <hosak(at)optics.upol.cz> 2021 Quantum Optics Lab Olomouc """ from functools import reduce from pulsebox.codeblocks import state_change, loop, channel_states_to_odsr from pulsebox.config import calibration, pulsebox_pincount def read_time(time_string): """Calculate time from a string containing a number and a time unit. The unit is denoted by the last character of `time_string`. Time is calculated by multiplying the 'number part' of `time_string` by a factor corresponding to the unit. The following units are accepted: * n: nanoseconds (factor = 1e-9) * u: microseconds (1e-6) * m: milliseconds (1e-3) * s: seconds (1) * TODO: c: MCU clock cycles (12e-9) * TODO: i: delay loop iterations (see `calibration` in config.ini) Args: * time_string (str): The (number + unit) string, for example "1m" Returns: * float time: Time (in seconds). """ factors = { "n": 1e-9, "u": 1e-6, "m": 1e-3, "s": 1 } # Check that the time string is properly formatted, e. g. time part # is followed by the unit part. The string should contain at least two # character, otherwise splitting it into two parts will raise an IndexError. try: number, unit = time_string[:-1], time_string[-1] except (IndexError, TypeError): raise ValueError("Invalid time string given.") # If the 'time part' cannot be converted to float, this raises a ValueError. number = float(number) if number < 0: raise ValueError("Negative time values are not allowed.") # Check that a valid time unit was specified. If no unit was specified, # then what we call 'unit' will in fact be the last digit of the time value # and as we do not use numeric unit symbols, we still get an error. try: factor = factors[unit] except KeyError: raise ValueError("Invalid time unit given.") time = number * factor return time def time2iters(time): """Get the number of loop iterations required to achieve a given time delay. Args: * time (float): The time to convert to the number of delay loop iters. Returns: * int iters: The number of iterations through the ASM delay loop required to produce a delay of a given length. Notes: The possible delay times are discrete, with a step given by the structure of the ASM loop. This step is given by the `calibration` variable in the config. For example, if our delays for 1, 2, and 3 delay loop iterations are 50 ns, 100 ns, and 150 ns, respectively, and we want to convert 120 ns to delay loop iterations, we would see that 2.4 iterations are required. As this is impossible, we round this to the nearest integer amount of iterations. In this case, that's 2 iterations and instead of 120 ns delay we produced a 100 ns delay. """ if time < 0: raise ValueError("Negative time is not allowed.") iters = int(round(time / calibration)) return iters def parse_events(event_string, channel=None): """Convert a long string of events into an array of event instances. """ event_substrings = event_string.split(" ") events = [] for substring in event_substrings: try: event_type, event_params = substring[0], substring[1:] except (IndexError, ValueError): print(f"CH {channel} - Invalid event string: " \ f"{event_string.__repr__()}") return events if event_type.lower() == "p": # PulseEvent # Pulse event contains two timestrings - start and duration. # Separate them. timestamp, duration = None, None for n, ch in enumerate(event_params): if ch.isalpha(): timestamp = read_time(event_params[:n+1]) duration = read_time(event_params[n+1:]) break pe = PulseEvent(channel, timestamp, duration) new_events = pe.flips for event in new_events: events.append(event) return events
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 31534, 13, 9078, 198, 47, 9615, 8379, 2995, 329, 262, 27634, 14444, 19445, 3524, 13, 198, 198, 15546, ...
2.559906
1,711
def words_to_sentence(words: list) -> str: """ This function create a string from a list of strings, separated by space. """ return ' '.join(words)
[ 4299, 2456, 62, 1462, 62, 34086, 594, 7, 10879, 25, 1351, 8, 4613, 965, 25, 198, 220, 220, 220, 37227, 770, 2163, 2251, 257, 4731, 422, 257, 1351, 286, 13042, 11, 11266, 416, 2272, 13, 37227, 198, 220, 220, 220, 1441, 705, 45302, ...
3.076923
52
# Copyright 2020 The Johns Hopkins University Applied Physics Laboratory # # 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 numpy as np from skimage.measure import label, regionprops import argparse if __name__ == "__main__": main()
[ 2, 15069, 12131, 383, 25824, 21183, 2059, 27684, 23123, 18643, 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, 1...
3.795918
196
import pytest import os from tests import test_analyzer from spectra_analyzer import analyzer def file_ref(name): """Helper function for getting paths to testing spectra.""" file = os.path.join(os.path.dirname(test_analyzer.__file__), "test_analyzer", name) return file def normalized(spectrum): """Test if passed spectrum is truly normalized.""" for i in range(spectrum.shape[0]): if spectrum[i] < 0.0 or spectrum[i] > 1.0: return False return True def test_trans_parameters(spectrum_inst): """Test modification of transformation parameters inside spectrum instance.""" # test initial parameters assert spectrum_inst.freq0 == 0 assert spectrum_inst.wSize == 5 scales = len(spectrum_inst.scales) assert scales == 48 # set for the specific spectrum mod = spectrum_inst.modify_parameters mod(48, 0) assert spectrum_inst.freq0 == 47 assert spectrum_inst.wSize == 0 mod(48, 10) assert spectrum_inst.freq0 == 47 assert spectrum_inst.wSize == 0 mod(48, 1) assert spectrum_inst.freq0 == 47 assert spectrum_inst.wSize == 0 mod(47, 1) assert spectrum_inst.freq0 == 47 assert spectrum_inst.wSize == 0 mod(46, 2) assert spectrum_inst.freq0 == 46 assert spectrum_inst.wSize == 1 mod(0, 48) assert spectrum_inst.freq0 == 0 assert spectrum_inst.wSize == 47 mod(0, 47) assert spectrum_inst.freq0 == 0 assert spectrum_inst.wSize == 47 mod(1, 47) assert spectrum_inst.freq0 == 1 assert spectrum_inst.wSize == 46 def test_spectrum_plotting(spectrum_inst): """Test that spectrum plotting returns some output.""" plot = spectrum_inst.plot_spectrum() assert type(plot) == str assert len(plot) > 0 def test_cwt_plotting(spectrum_inst): """Test that cwt plotting returns some output.""" plot = spectrum_inst.plot_cwt() assert type(plot) == str assert len(plot) > 0 def test_transformation_plotting(spectrum_inst): """Test that transformation plotting returns some output.""" plot = spectrum_inst.plot_reduced_spectrum() assert type(plot) == str assert len(plot) > 0 plot = spectrum_inst.plot_reduced_spectrum(only_transformation=True) assert type(plot) == str assert len(plot) > 0 def test_rec_invalidation(spectrum_inst): """Test that _rec variable is properly invalidated after parameter modification.""" assert spectrum_inst._rec is None spectrum_inst.plot_reduced_spectrum() assert spectrum_inst._rec is not None spectrum_inst.modify_parameters(5, 4) assert spectrum_inst._rec is None
[ 11748, 12972, 9288, 198, 11748, 28686, 198, 6738, 5254, 1330, 1332, 62, 38200, 9107, 198, 6738, 5444, 430, 62, 38200, 9107, 1330, 4284, 9107, 628, 198, 4299, 2393, 62, 5420, 7, 3672, 2599, 198, 220, 220, 220, 37227, 47429, 2163, 329, ...
2.746901
968
from django.shortcuts import render from .models import User from . import forms # Create your views here.
[ 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 198, 6738, 764, 27530, 1330, 11787, 198, 6738, 764, 1330, 5107, 198, 2, 13610, 534, 5009, 994, 13 ]
4.076923
26
import unittest from submitty_utils import string_utils if __name__ == '__main__': unittest.main()
[ 11748, 555, 715, 395, 198, 198, 6738, 850, 76, 9760, 62, 26791, 1330, 4731, 62, 26791, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 555, 715, 395, 13, 12417, 3419, 198 ]
2.717949
39
import os
[ 11748, 28686, 198 ]
3.333333
3
import os import argparse import logging import numpy as np import SimpleITK as sitk logging.basicConfig(level=logging.INFO) from tqdm import tqdm import cv2 import sys from PIL import Image from sklearn import metrics def Dice(y_true, y_pred): """Returns Dice Similarity Coefficient for ground truth and predicted masks.""" #print(y_true.dtype) #print(y_pred.dtype) y_true = np.squeeze(y_true)/255 y_pred = np.squeeze(y_pred)/255 y_true.astype('bool') y_pred.astype('bool') intersection = np.logical_and(y_true, y_pred).sum() return ((2. * intersection.sum()) + 1.) / (y_true.sum() + y_pred.sum() + 1.) if __name__ == '__main__': main()
[ 11748, 28686, 198, 11748, 1822, 29572, 198, 11748, 18931, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 17427, 2043, 42, 355, 1650, 74, 198, 6404, 2667, 13, 35487, 16934, 7, 5715, 28, 6404, 2667, 13, 10778, 8, 198, 6738, 256, 80, 36...
2.558052
267
from app.models.enums.station import Station
[ 6738, 598, 13, 27530, 13, 268, 5700, 13, 17529, 1330, 9327, 198 ]
3.75
12
import os import sys import copy import asyncio import logging import argparse import synapse.exc as s_exc import synapse.common as s_common import synapse.telepath as s_telepath import synapse.lib.cli as s_cli import synapse.lib.cmd as s_cmd import synapse.lib.node as s_node import synapse.lib.time as s_time import synapse.lib.output as s_output import synapse.lib.parser as s_parser import synapse.lib.msgpack as s_msgpack logger = logging.getLogger(__name__) ERROR_COLOR = '#ff0066' WARNING_COLOR = '#f4e842' NODEEDIT_COLOR = "lightblue" welcome = ''' Welcome to the Storm interpreter! Local interpreter (non-storm) commands may be executed with a ! prefix: Use !quit to exit. Use !help to see local interpreter commands. ''' def getArgParser(): pars = argparse.ArgumentParser(prog='synapse.tools.storm') pars.add_argument('cortex', help='A telepath URL for the Cortex.') pars.add_argument('onecmd', nargs='?', help='A single storm command to run and exit.') return pars if __name__ == '__main__': # pragma: no cover sys.exit(asyncio.run(main(sys.argv[1:])))
[ 11748, 28686, 198, 11748, 25064, 198, 11748, 4866, 198, 11748, 30351, 952, 198, 11748, 18931, 198, 11748, 1822, 29572, 198, 198, 11748, 6171, 7512, 13, 41194, 355, 264, 62, 41194, 198, 11748, 6171, 7512, 13, 11321, 355, 264, 62, 11321, ...
2.887139
381
from sklearn.feature_selection import VarianceThreshold # Create feature matrix with: # Feature 0: 80% class 0 # Feature 1: 80% class 1 # Feature 2: 60% class 0, 40% class 1 X = [[0, 1, 0], [0, 1, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0]] # Run threshold by variance thresholder = VarianceThreshold(threshold=(.75 * (1 - .75))) thresholder.fit_transform(X)
[ 6738, 1341, 35720, 13, 30053, 62, 49283, 1330, 15965, 590, 817, 10126, 198, 198, 2, 13610, 3895, 17593, 351, 25, 198, 2, 27018, 657, 25, 4019, 4, 1398, 657, 198, 2, 27018, 352, 25, 4019, 4, 1398, 352, 198, 2, 27018, 362, 25, 3126,...
2.476821
151
#!/usr/bin/python3 import sys sys.path.insert(0, '../..') # make '..' first in the lib search path import gzip import numpy from lemminflect.kmodels.ModelLemma import ModelLemma from lemminflect.kmodels.ModelLemmaInData import ModelLemmaInData from lemminflect.kmodels.ModelLemmaClasses import ModelLemmaClasses from lemminflect import config if __name__ == '__main__': # Load the lemmatization data print('Loading ', config.lemma_tcorp_fn) indata = ModelLemmaInData(config.lemma_tcorp_fn) print('Loaded {:,} entries'.format(len(indata.entries))) # Load the lemmatization rules print('Loading ', config.model_lemma_cl_fn) rules = ModelLemmaClasses(config.model_lemma_cl_fn) # Convert data into training format X = [] Y = [] input_len = ModelLemmaInData.WVEC_LEN input_letters = ModelLemmaInData.getLetterClasses() output_rules = rules.rules for entry in indata.entries: rule = ModelLemmaClasses.computeSuffixRule(entry.infl, entry.lemma) idx = rules.getRuleIndex(rule) vec = ModelLemmaInData.wordToVec(entry.infl, entry.category) X.append( vec ) Y.append( idx ) X = numpy.asarray(X, dtype='float32') Y = numpy.asarray(Y, dtype='int32') print('X.shape= ', X.shape) print('Y.shape= ', Y.shape) print() # Create the model batch_size = 32 nepochs = 50 model = ModelLemma() model.create(input_len, input_letters, output_rules) model.model.summary() model.train(X, Y, batch_size, nepochs) print() print('Saving model to ', config.model_lemma_fn) model.save(config.model_lemma_fn) print('done')
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 11748, 25064, 198, 17597, 13, 6978, 13, 28463, 7, 15, 11, 705, 40720, 492, 11537, 220, 220, 220, 1303, 787, 705, 492, 6, 717, 287, 262, 9195, 2989, 3108, 198, 11748, 308, 13344, 198, ...
2.378723
705
# coding=utf-8 from __future__ import (absolute_import, division, print_function, unicode_literals) import json from _ctypes import byref, pointer from builtins import range, str from ctypes import c_char_p, string_at from snips_nlu_parsers.utils import (CStringArray, check_ffi_error, lib, string_array_pointer, string_pointer) _ALL_LANGUAGES = None _SUPPORTED_ENTITIES = dict() _SUPPORTED_GAZETTEER_ENTITIES = dict() _SUPPORTED_GRAMMAR_ENTITIES = dict() _ENTITIES_EXAMPLES = dict() _ALL_BUILTIN_ENTITIES = None _ALL_GAZETTEER_ENTITIES = None _ALL_GRAMMAR_ENTITIES = None _BUILTIN_ENTITIES_SHORTNAMES = dict() _COMPLETE_ENTITY_ONTOLOGY = None _LANGUAGE_ENTITY_ONTOLOGY = dict() def get_all_languages(): """Lists all the supported languages""" global _ALL_LANGUAGES if _ALL_LANGUAGES is None: lib.snips_nlu_ontology_supported_languages.restype = CStringArray array = lib.snips_nlu_ontology_supported_languages() _ALL_LANGUAGES = set( array.data[i].decode("utf8") for i in range(array.size)) return _ALL_LANGUAGES def get_all_builtin_entities(): """Lists the builtin entities that are supported in at least one language""" global _ALL_BUILTIN_ENTITIES if _ALL_BUILTIN_ENTITIES is None: lib.snips_nlu_ontology_all_builtin_entities.restype = CStringArray array = lib.snips_nlu_ontology_all_builtin_entities() _ALL_BUILTIN_ENTITIES = set( array.data[i].decode("utf8") for i in range(array.size)) return _ALL_BUILTIN_ENTITIES def get_all_gazetteer_entities(): """Lists the gazetteer entities that are supported in at least one language""" global _ALL_GAZETTEER_ENTITIES if _ALL_GAZETTEER_ENTITIES is None: lib.snips_nlu_ontology_all_gazetteer_entities.restype = CStringArray array = lib.snips_nlu_ontology_all_gazetteer_entities() _ALL_GAZETTEER_ENTITIES = set( array.data[i].decode("utf8") for i in range(array.size)) return _ALL_GAZETTEER_ENTITIES def get_all_grammar_entities(): """Lists the grammar entities that are supported in at least one language""" global _ALL_GRAMMAR_ENTITIES if _ALL_GRAMMAR_ENTITIES is None: lib.snips_nlu_ontology_all_grammar_entities.restype = CStringArray array = lib.snips_nlu_ontology_all_grammar_entities() _ALL_GRAMMAR_ENTITIES = set( array.data[i].decode("utf8") for i in range(array.size)) return _ALL_GRAMMAR_ENTITIES def get_builtin_entity_shortname(entity): """Get the short name of the entity Examples: >>> get_builtin_entity_shortname(u"snips/amountOfMoney") 'AmountOfMoney' """ global _BUILTIN_ENTITIES_SHORTNAMES if entity not in _BUILTIN_ENTITIES_SHORTNAMES: with string_pointer(c_char_p()) as ptr: exit_code = lib.snips_nlu_ontology_entity_shortname( entity.encode("utf8"), byref(ptr)) check_ffi_error(exit_code, "Something went wrong when retrieving " "builtin entity shortname") result = string_at(ptr) _BUILTIN_ENTITIES_SHORTNAMES[entity] = result.decode("utf8") return _BUILTIN_ENTITIES_SHORTNAMES[entity] def get_supported_entities(language): """Lists the builtin entities supported in the specified *language* Returns: list of str: the list of entity labels """ global _SUPPORTED_ENTITIES if not isinstance(language, str): raise TypeError("Expected language to be of type 'str' but found: %s" % type(language)) if language not in _SUPPORTED_ENTITIES: with string_array_pointer(pointer(CStringArray())) as ptr: exit_code = lib.snips_nlu_parsers_supported_builtin_entities( language.encode("utf8"), byref(ptr)) check_ffi_error(exit_code, "Something went wrong when retrieving " "supported entities") array = ptr.contents _SUPPORTED_ENTITIES[language] = set( array.data[i].decode("utf8") for i in range(array.size)) return _SUPPORTED_ENTITIES[language] def get_supported_gazetteer_entities(language): """Lists the gazetteer entities supported in the specified *language* Returns: list of str: the list of entity labels """ global _SUPPORTED_GAZETTEER_ENTITIES if not isinstance(language, str): raise TypeError("Expected language to be of type 'str' but found: %s" % type(language)) if language not in _SUPPORTED_GAZETTEER_ENTITIES: with string_array_pointer(pointer(CStringArray())) as ptr: exit_code = \ lib.snips_nlu_parsers_supported_builtin_gazetteer_entities( language.encode("utf8"), byref(ptr)) check_ffi_error(exit_code, "Something went wrong when retrieving " "supported gazetteer entities") array = ptr.contents _SUPPORTED_GAZETTEER_ENTITIES[language] = set( array.data[i].decode("utf8") for i in range(array.size)) return _SUPPORTED_GAZETTEER_ENTITIES[language] def get_supported_grammar_entities(language): """Lists the grammar entities supported in the specified *language* Returns: list of str: the list of entity labels """ global _SUPPORTED_GRAMMAR_ENTITIES if not isinstance(language, str): raise TypeError("Expected language to be of type 'str' but found: %s" % type(language)) if language not in _SUPPORTED_GRAMMAR_ENTITIES: with string_array_pointer(pointer(CStringArray())) as ptr: exit_code = lib.snips_nlu_parsers_supported_grammar_entities( language.encode("utf8"), byref(ptr)) check_ffi_error(exit_code, "Something went wrong when retrieving " "supported grammar entities") array = ptr.contents _SUPPORTED_GRAMMAR_ENTITIES[language] = set( array.data[i].decode("utf8") for i in range(array.size)) return _SUPPORTED_GRAMMAR_ENTITIES[language] def get_builtin_entity_examples(builtin_entity_kind, language): """Provides some examples of the builtin entity in the specified language """ global _ENTITIES_EXAMPLES if not isinstance(builtin_entity_kind, str): raise TypeError("Expected `builtin_entity_kind` to be of type 'str' " "but found: %s" % type(builtin_entity_kind)) if not isinstance(language, str): raise TypeError("Expected `language` to be of type 'str' but found: %s" % type(language)) if builtin_entity_kind not in _ENTITIES_EXAMPLES: _ENTITIES_EXAMPLES[builtin_entity_kind] = dict() if language not in _ENTITIES_EXAMPLES[builtin_entity_kind]: with string_array_pointer(pointer(CStringArray())) as ptr: exit_code = lib.snips_nlu_parsers_builtin_entity_examples( builtin_entity_kind.encode("utf8"), language.encode("utf8"), byref(ptr)) check_ffi_error(exit_code, "Something went wrong when retrieving " "builtin entity examples") array = ptr.contents _ENTITIES_EXAMPLES[builtin_entity_kind][language] = list( array.data[i].decode("utf8") for i in range(array.size)) return _ENTITIES_EXAMPLES[builtin_entity_kind][language] def get_complete_entity_ontology(): """Lists the complete entity ontology for all languages in JSON format """ global _COMPLETE_ENTITY_ONTOLOGY if _COMPLETE_ENTITY_ONTOLOGY is None: with string_pointer(c_char_p()) as ptr: exit_code = lib.snips_nlu_parsers_complete_entity_ontology_json(byref(ptr)) check_ffi_error(exit_code, "Something went wrong when retrieving " "complete entity ontology") json_str = string_at(ptr).decode("utf8") _COMPLETE_ENTITY_ONTOLOGY = json.loads(json_str, encoding="utf8") return _COMPLETE_ENTITY_ONTOLOGY def get_language_entity_ontology(language): """Lists the complete entity ontology for the specified language in JSON format """ global _LANGUAGE_ENTITY_ONTOLOGY if language not in _LANGUAGE_ENTITY_ONTOLOGY: with string_pointer(c_char_p()) as ptr: exit_code = lib.snips_nlu_parsers_language_entity_ontology_json( language.encode("utf8"), byref(ptr)) check_ffi_error(exit_code, "Something went wrong when retrieving " "language entity ontology") json_str = string_at(ptr).decode("utf8") _LANGUAGE_ENTITY_ONTOLOGY[language] = json.loads(json_str, encoding="utf8") return _LANGUAGE_ENTITY_ONTOLOGY[language]
[ 2, 19617, 28, 40477, 12, 23, 198, 6738, 11593, 37443, 834, 1330, 357, 48546, 62, 11748, 11, 7297, 11, 3601, 62, 8818, 11, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 2...
2.267372
3,972
import os;os.environ['TMPDIR'] = os.path.join(os.environ['HOME'], 'tmp') import pwn remote_binary = "/problems/got_5_c5119617c90aa544a639812dbc41e24e/vuln" segfault()
[ 11748, 28686, 26, 418, 13, 268, 2268, 17816, 15972, 5760, 4663, 20520, 796, 28686, 13, 6978, 13, 22179, 7, 418, 13, 268, 2268, 17816, 39069, 6, 4357, 705, 22065, 11537, 198, 11748, 279, 675, 198, 198, 47960, 62, 39491, 796, 12813, 167...
2.139241
79
#!/usr/bin/env python # coding: utf-8 # *Author: Dezso Ribli* """ Util functions for training CNN on weak lesnsing maps. Mostly data loaders and data generators with some additional functionality. """ import numpy as np # https://github.com/IntelPython/mkl_fft/issues/11 #np.fft.restore_all() import cv2 import math import os def step_decay(epoch, base_lr, epochs_drop, drop=0.1): """Helper for step learning rate decay.""" lrate = base_lr for epoch_drop in epochs_drop: lrate *= math.pow(drop,math.floor(epoch/epoch_drop)) return lrate def load_training_data(mapsize=512, grfized=False, exclude_fid=False, dense_grid=False, random_split=False, from_files=False): """Load data for different training scenarios.""" if not grfized and (not dense_grid) and (not random_split): # the default data to loas X_train, X_test, y_train, y_test = load_sparse_grid(imsize=mapsize, from_files=from_files) elif grfized: # equivalent gaussian random filed maps assert not from_files X_train, X_test, y_train, y_test = load_grf_sparse_grid() elif dense_grid: assert not from_files # data with additional points around a cosmology X_train, X_test, y_train, y_test = load_dense_grid(imsize=mapsize) elif random_split: # random train and test split X_train, X_test, y_train, y_test = load_randomsplit_grid( imsize=mapsize, from_files=from_files) # aleays predict newidf, why not, it takes not time # anyway we will not use it with the experiemnts fn = '../../data/columbia_data_fiducial_new_idf_pix'+str(mapsize)+'.npy' X_new_idf = np.load(fn) y_new_idf = np.ones((len(y_test),2)) y_new_idf[:,0], y_new_idf[:,1] = 0.309, 0.816 if exclude_fid: # exclude fiducial cosmo params if asked for idx = (y_train[:,0] == 0.309) & (y_train[:,1] == 0.816) X_train, y_train = X_train[~idx], y_train[~idx] return X_train, X_test, X_new_idf, y_train, y_test, y_new_idf """Loaders for various experiments.""" def predict_on_generator(model, datagen, augment): """Predict on data generator with augmentation.""" datagen.reset_indices_and_reshuffle(force=True) y_true, y_pred = [],[] for i in range(datagen.n_data): xi,yi = datagen.next() y_true.append(yi) y_pred_tmp = np.zeros(yi.shape) if augment: for ai in [0,1]: for aj in [0,1]: for ak in [0,1]: y_pred_tmp += model.predict_on_batch( aug_ims(xi,ai,aj,ak)) y_pred.append(y_pred_tmp/8.) else: y_pred.append(model.predict_on_batch(xi)) y_true = np.vstack(y_true) y_pred = np.vstack(y_pred) return y_true, y_pred def aug_ims(ims, fliplr=0, flipud=0, T=0): """Augment images with flips and transposition.""" ims_aug = np.array(ims, copy=True) for i in range(len(ims_aug)): if fliplr: # flip left right ims_aug[i] = np.fliplr(ims_aug[i]) if flipud: # flip up down ims_aug[i] = np.flipud(ims_aug[i]) if T: # transpose ims_aug[i,:,:,0] = ims_aug[i,:,:,0].T return ims_aug def add_shape_noise(x, A, ng, rng=None, sige=0.4): """Add shape noise""" sigpix = sige / (2 * A * ng)**0.5 # final pixel noise scatter # add shape noise to map if rng: # use given random generator return x + rng.normal(loc=0, scale=sigpix, size=x.shape) else: # or just a random noise return x + np.random.normal(loc=0, scale=sigpix, size=x.shape) def smooth(x, smoothing_scale_arcmin, map_size_arcmin): """Smooth by Gaussian kernel.""" # smoothing kernel width in pixels instead of arcmins map_size_pix = x.shape[0] s = (smoothing_scale_arcmin * map_size_pix) / map_size_arcmin # cut off at: 6 sigma + 1 pixel # for large smooothing area and odd pixel number cutoff = 6 * int(s+1) + 1 return cv2.GaussianBlur(x, ksize=(cutoff, cutoff), sigmaX=s, sigmaY=s)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 19617, 25, 3384, 69, 12, 23, 198, 2, 1635, 13838, 25, 1024, 89, 568, 23133, 4528, 9, 198, 198, 37811, 198, 198, 18274, 346, 5499, 329, 3047, 8100, 319, 4939, 10287, 5907, 278, 8...
2.110944
1,992
import hashlib import io import json import os import re import struct
[ 198, 11748, 12234, 8019, 198, 11748, 33245, 198, 11748, 33918, 198, 11748, 28686, 198, 11748, 302, 198, 11748, 2878, 198 ]
3.6
20
table = _Table()
[ 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 628, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 198, 11487, 796, 4808, 10962, 3419, 198, 220, 220, 220, 220, 198, 220, 220, 220, 22...
1.244898
49
# Copyright 2021 VMware, Inc. # SPDX-License-Identifier: Apache-2.0 import logging import unittest from unittest import mock from vdk.plugin.control_api_auth.authentication import Authentication from vdk_provider.hooks.vdk import VDKHook log = logging.getLogger(__name__) # Monkey-patch the authentication logic to allow for more granular testing # of the VDKHook
[ 2, 15069, 33448, 37754, 11, 3457, 13, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 24843, 12, 17, 13, 15, 198, 11748, 18931, 198, 11748, 555, 715, 395, 198, 6738, 555, 715, 395, 1330, 15290, 198, 198, 6738, 410, 34388, 13, 3...
3.294643
112
"""Funcs for logging""" import logging _CRITICAL = logging.CRITICAL _ERROR = logging.ERROR _WARNING = logging.WARNING _INFO = logging.INFO _DEBUG = logging.DEBUG _NOTSET = logging.NOTSET
[ 37811, 24629, 6359, 329, 18931, 37811, 198, 11748, 18931, 628, 198, 62, 9419, 2043, 20151, 796, 18931, 13, 9419, 2043, 20151, 198, 62, 24908, 796, 18931, 13, 24908, 198, 62, 31502, 796, 18931, 13, 31502, 198, 62, 10778, 796, 18931, 13, ...
3.220339
59
#!/usr/bin/env python3 # https://leetcode.com/problems/contains-duplicate/ import unittest from typing import List
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 3740, 1378, 293, 316, 8189, 13, 785, 14, 1676, 22143, 14, 3642, 1299, 12, 646, 489, 5344, 14, 198, 198, 11748, 555, 715, 395, 198, 198, 6738, 19720, 1330, 7343, 628, 198 ]
2.767442
43
from __future__ import division import numpy as np np.seterr(divide='ignore') # these warnings are usually harmless for this code from matplotlib import pyplot as plt import copy, os import pyhsmm from pyhsmm.util.text import progprint_xrange ################### # generate data # ################### T = 1000 obs_dim = 2 N = 4 obs_hypparams = {'mu_0':np.zeros(obs_dim), 'sigma_0':np.eye(obs_dim), 'kappa_0':0.25, 'nu_0':obs_dim+2} dur_hypparams = {'alpha_0':10*1, 'beta_0':10*100} true_obs_distns = [pyhsmm.distributions.Gaussian(**obs_hypparams) for state in range(N)] true_dur_distns = [pyhsmm.distributions.GeometricDuration(**dur_hypparams) for state in range(N)] truemodel = pyhsmm.models.GeoHSMM( alpha=6., init_state_concentration=6., obs_distns=true_obs_distns, dur_distns=true_dur_distns) data, labels = truemodel.generate(T) plt.figure() truemodel.plot() temp = np.concatenate(((0,),truemodel.states_list[0].durations.cumsum())) changepoints = zip(temp[:-1],temp[1:]) changepoints[-1] = (changepoints[-1][0],T) # because last duration might be censored ######################### # posterior inference # ######################### Nmax = 25 obs_distns = [pyhsmm.distributions.Gaussian(**obs_hypparams) for state in range(Nmax)] dur_distns = [pyhsmm.distributions.GeometricDuration(**dur_hypparams) for state in range(Nmax)] posteriormodel = pyhsmm.models.GeoHSMMPossibleChangepoints( alpha=6., init_state_concentration=6., obs_distns=obs_distns, dur_distns=dur_distns) posteriormodel.add_data(data,changepoints=changepoints) for idx in progprint_xrange(50): posteriormodel.resample_model() plt.figure() posteriormodel.plot() plt.show()
[ 6738, 11593, 37443, 834, 1330, 7297, 198, 11748, 299, 32152, 355, 45941, 198, 37659, 13, 82, 2357, 81, 7, 7146, 485, 11639, 46430, 11537, 1303, 777, 14601, 389, 3221, 23585, 329, 428, 2438, 198, 6738, 2603, 29487, 8019, 1330, 12972, 294...
2.269663
801
from django.db import transaction from rest_framework.exceptions import ValidationError from .base_nested_mixin import BaseNestedMixin
[ 6738, 42625, 14208, 13, 9945, 1330, 8611, 198, 6738, 1334, 62, 30604, 13, 1069, 11755, 1330, 3254, 24765, 12331, 198, 198, 6738, 764, 8692, 62, 77, 7287, 62, 19816, 259, 1330, 7308, 45, 7287, 35608, 259, 628 ]
3.702703
37
__version__ = "2021.10.07"
[ 834, 9641, 834, 796, 366, 1238, 2481, 13, 940, 13, 2998, 1, 198 ]
2.076923
13
"""Make datasets available.""" from forayer.datasets.oaei_kg import OAEIKGDataset from forayer.datasets.open_ea import OpenEADataset __all__ = ["OpenEADataset", "OAEIKGDataset"]
[ 37811, 12050, 40522, 1695, 526, 15931, 198, 6738, 329, 2794, 13, 19608, 292, 1039, 13, 78, 3609, 72, 62, 10025, 1330, 440, 14242, 18694, 38, 27354, 292, 316, 198, 6738, 329, 2794, 13, 19608, 292, 1039, 13, 9654, 62, 18213, 1330, 4946,...
2.521127
71
from django.contrib import admin from challenge.models import Goal, GoalInstance, SignificantOther # Register your models here. admin.site.register(Goal) admin.site.register(GoalInstance) admin.site.register(SignificantOther)
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 6738, 4427, 13, 27530, 1330, 25376, 11, 25376, 33384, 11, 49631, 6395, 198, 198, 2, 17296, 534, 4981, 994, 13, 198, 28482, 13, 15654, 13, 30238, 7, 49045, 8, 198, 28482, 13, 15654, ...
3.783333
60
import library import random import re
[ 11748, 5888, 201, 198, 11748, 4738, 201, 198, 11748, 302, 201, 198, 201, 198, 201 ]
3
15