content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
import numpy as np import random letter_C = np.array([ [1, 1, 1, 1, 1], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 1, 1, 1, 1], ]) noisy_C = np.array([ [1, 1, 1, 1, 1], [0, 1, 0, 0, 1], [1, 0, 0, 0, 0], [1, 0, 0, 1, 0], [1, 0, 1, 1, 1], ]) letter_I = np.array([ [0, 1, 1, 1, 1], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [1, 1, 1, 1, 1], ]) noisy_I = np.array([ [1, 1, 1, 1, 1], [0, 0, 1, 0, 0], [0, 1, 1, 0, 0], [0, 0, 0, 0, 0], [0, 1, 0, 1, 1], ]) letter_T = np.array([ [1, 1, 1, 1, 1], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0], ]) noisy_T = np.array([ [1, 1, 0, 1, 0], [0, 0, 1, 0, 0], [0, 1, 1, 0, 0], [0, 0, 0, 0, 0], [0, 0, 1, 0, 0], ]) if __name__ == '__main__': test_w_less_101() test_w_more_100()
[ 11748, 299, 32152, 355, 45941, 198, 11748, 4738, 198, 198, 9291, 62, 34, 796, 45941, 13, 18747, 26933, 198, 220, 220, 220, 685, 16, 11, 352, 11, 352, 11, 352, 11, 352, 4357, 198, 220, 220, 220, 685, 16, 11, 657, 11, 657, 11, 657...
1.56239
569
from infoclientLib import InfoClient ic = InfoClient('localhost', 15002, 'localhost', 15003) ic.add('roi-weightedave', 'active') ic.start()
[ 198, 6738, 1167, 38679, 1153, 25835, 1330, 14151, 11792, 198, 291, 796, 14151, 11792, 10786, 36750, 3256, 20007, 17, 11, 705, 36750, 3256, 1315, 11245, 8, 198, 291, 13, 2860, 10786, 305, 72, 12, 6551, 276, 1015, 3256, 705, 5275, 11537, ...
3.021277
47
# (c) Copyright IBM Corporation 2020. # LICENSE: Apache License 2.0 (Apache-2.0) # http://www.apache.org/licenses/LICENSE-2.0 import abc import logging import time from collections import defaultdict from typing import List import numpy as np from dataclasses import dataclass logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s') import lrtc_lib.data_access.data_access_factory as data_access_factory import lrtc_lib.experiment_runners.experiments_results_handler as res_handler from lrtc_lib.oracle_data_access import oracle_data_access_api from lrtc_lib.active_learning.diversity_calculator import DiversityCalculator from lrtc_lib.active_learning.knn_outlier_calculator import KnnOutlierCalculator from lrtc_lib.active_learning.strategies import ActiveLearningStrategies from lrtc_lib.data_access.core.data_structs import TextElement from lrtc_lib.data_access.data_access_api import DataAccessApi from lrtc_lib.data_access.data_access_factory import get_data_access from lrtc_lib.orchestrator import orchestrator_api from lrtc_lib.orchestrator.orchestrator_api import DeleteModels from lrtc_lib.train_and_infer_service.model_type import ModelType from lrtc_lib.training_set_selector.train_and_dev_set_selector_api import TrainingSetSelectionStrategy
[ 2, 357, 66, 8, 15069, 19764, 10501, 12131, 13, 198, 198, 2, 38559, 24290, 25, 24843, 13789, 362, 13, 15, 357, 25189, 4891, 12, 17, 13, 15, 8, 198, 2, 2638, 1378, 2503, 13, 43073, 13, 2398, 14, 677, 4541, 14, 43, 2149, 24290, 12,...
2.955357
448
try: from tango import DeviceProxy, DevError except ModuleNotFoundError: pass
[ 28311, 25, 198, 220, 220, 220, 422, 13875, 78, 1330, 16232, 44148, 11, 6245, 12331, 198, 16341, 19937, 3673, 21077, 12331, 25, 198, 220, 220, 220, 1208, 628, 198 ]
3.034483
29
import json from django.contrib.auth.models import User from django.http import JsonResponse from django.shortcuts import redirect, render from .models import Game2048 # Create your views here. # test_user # 8!S#5RP!WVMACg
[ 11748, 33918, 198, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 11787, 198, 6738, 42625, 14208, 13, 4023, 1330, 449, 1559, 31077, 198, 6738, 42625, 14208, 13, 19509, 23779, 1330, 18941, 11, 8543, 198, 198, 6738, 7...
3.066667
75
from distdeepq import models # noqa from distdeepq.build_graph import build_act, build_train # noqa from distdeepq.simple import learn, load, make_session # noqa from distdeepq.replay_buffer import ReplayBuffer, PrioritizedReplayBuffer # noqa from distdeepq.static import * from distdeepq.plots import PlotMachine
[ 6738, 1233, 22089, 80, 1330, 4981, 220, 1303, 645, 20402, 198, 6738, 1233, 22089, 80, 13, 11249, 62, 34960, 1330, 1382, 62, 529, 11, 1382, 62, 27432, 220, 1303, 645, 20402, 198, 198, 6738, 1233, 22089, 80, 13, 36439, 1330, 2193, 11, ...
3.357895
95
# Authentication & API Keys # Many APIs require an API key. Just as a real-world key allows you to access something, an API key grants you access to a particular API. Moreover, an API key identifies you to the API, which helps the API provider keep track of how their service is used and prevent unauthorized or malicious activity. # # Some APIs require authentication using a protocol called OAuth. We won't get into the details, but if you've ever been redirected to a page asking for permission to link an application with your account, you've probably used OAuth. # # API keys are often long alphanumeric strings. We've made one up in the editor to the right! (It won't actually work on anything, but when you receive your own API keys in future projects, they'll look a lot like this.) api_key = "string"
[ 2, 48191, 1222, 7824, 26363, 198, 2, 4650, 23113, 2421, 281, 7824, 1994, 13, 2329, 355, 257, 1103, 12, 6894, 1994, 3578, 345, 284, 1895, 1223, 11, 281, 7824, 1994, 11455, 345, 1895, 284, 257, 1948, 7824, 13, 10968, 11, 281, 7824, 19...
4.389189
185
from .plucker import pluck, Path from .exceptions import PluckError __all__ = ["pluck", "Path", "PluckError"]
[ 6738, 764, 489, 12603, 1330, 458, 1347, 11, 10644, 198, 6738, 764, 1069, 11755, 1330, 1345, 1347, 12331, 198, 198, 834, 439, 834, 796, 14631, 489, 1347, 1600, 366, 15235, 1600, 366, 3646, 1347, 12331, 8973, 198 ]
3
37
"""Plot a scatter or hexbin of sampled parameters.""" import warnings import numpy as np from ..data import convert_to_dataset, convert_to_inference_data from .plot_utils import xarray_to_ndarray, get_coords, get_plotting_function from ..utils import _var_names def plot_pair( data, group="posterior", var_names=None, coords=None, figsize=None, textsize=None, kind="scatter", gridsize="auto", contour=True, fill_last=True, divergences=False, colorbar=False, ax=None, divergences_kwargs=None, plot_kwargs=None, backend=None, backend_kwargs=None, show=None, ): """ Plot a scatter or hexbin matrix of the sampled parameters. Parameters ---------- data : obj Any object that can be converted to an az.InferenceData object Refer to documentation of az.convert_to_dataset for details group : str, optional Specifies which InferenceData group should be plotted. Defaults to 'posterior'. var_names : list of variable names Variables to be plotted, if None all variable are plotted coords : mapping, optional Coordinates of var_names to be plotted. Passed to `Dataset.sel` figsize : figure size tuple If None, size is (8 + numvars, 8 + numvars) textsize: int Text size for labels. If None it will be autoscaled based on figsize. kind : str Type of plot to display (scatter, kde or hexbin) gridsize : int or (int, int), optional Only works for kind=hexbin. The number of hexagons in the x-direction. The corresponding number of hexagons in the y-direction is chosen such that the hexagons are approximately regular. Alternatively, gridsize can be a tuple with two elements specifying the number of hexagons in the x-direction and the y-direction. contour : bool If True plot the 2D KDE using contours, otherwise plot a smooth 2D KDE. Defaults to True. fill_last : bool If True fill the last contour of the 2D KDE plot. Defaults to True. divergences : Boolean If True divergences will be plotted in a different color, only if group is either 'prior' or 'posterior'. colorbar : bool If True a colorbar will be included as part of the plot (Defaults to False). Only works when kind=hexbin ax: axes, optional Matplotlib axes or bokeh figures. divergences_kwargs : dicts, optional Additional keywords passed to ax.scatter for divergences plot_kwargs : dicts, optional Additional keywords passed to ax.plot, az.plot_kde or ax.hexbin backend: str, optional Select plotting backend {"matplotlib","bokeh"}. Default "matplotlib". backend_kwargs: bool, optional These are kwargs specific to the backend being used. For additional documentation check the plotting method of the backend. show : bool, optional Call backend show function. Returns ------- axes : matplotlib axes or bokeh figures Examples -------- KDE Pair Plot .. plot:: :context: close-figs >>> import arviz as az >>> centered = az.load_arviz_data('centered_eight') >>> coords = {'school': ['Choate', 'Deerfield']} >>> az.plot_pair(centered, >>> var_names=['theta', 'mu', 'tau'], >>> kind='kde', >>> coords=coords, >>> divergences=True, >>> textsize=18) Hexbin pair plot .. plot:: :context: close-figs >>> az.plot_pair(centered, >>> var_names=['theta', 'mu'], >>> coords=coords, >>> textsize=18, >>> kind='hexbin') Pair plot showing divergences .. plot:: :context: close-figs >>> az.plot_pair(centered, ... var_names=['theta', 'mu', 'tau'], ... coords=coords, ... divergences=True, ... textsize=18) """ valid_kinds = ["scatter", "kde", "hexbin"] if kind not in valid_kinds: raise ValueError( ("Plot type {} not recognized." "Plot type must be in {}").format(kind, valid_kinds) ) if coords is None: coords = {} if plot_kwargs is None: plot_kwargs = {} if kind == "scatter": plot_kwargs.setdefault("marker", ".") plot_kwargs.setdefault("lw", 0) if divergences_kwargs is None: divergences_kwargs = {} divergences_kwargs.setdefault("marker", "o") divergences_kwargs.setdefault("markeredgecolor", "k") divergences_kwargs.setdefault("color", "C1") divergences_kwargs.setdefault("lw", 0) # Get posterior draws and combine chains data = convert_to_inference_data(data) grouped_data = convert_to_dataset(data, group=group) var_names = _var_names(var_names, grouped_data) flat_var_names, infdata_group = xarray_to_ndarray( get_coords(grouped_data, coords), var_names=var_names, combined=True ) divergent_data = None diverging_mask = None # Assigning divergence group based on group param if group == "posterior": divergent_group = "sample_stats" elif group == "prior": divergent_group = "sample_stats_prior" else: divergences = False # Get diverging draws and combine chains if divergences: if hasattr(data, divergent_group) and hasattr(getattr(data, divergent_group), "diverging"): divergent_data = convert_to_dataset(data, group=divergent_group) _, diverging_mask = xarray_to_ndarray( divergent_data, var_names=("diverging",), combined=True ) diverging_mask = np.squeeze(diverging_mask) else: divergences = False warnings.warn( "Divergences data not found, plotting without divergences. " "Make sure the sample method provides divergences data and " "that it is present in the `diverging` field of `sample_stats` " "or `sample_stats_prior` or set divergences=False", SyntaxWarning, ) if gridsize == "auto": gridsize = int(len(infdata_group[0]) ** 0.35) numvars = len(flat_var_names) if numvars < 2: raise Exception("Number of variables to be plotted must be 2 or greater.") pairplot_kwargs = dict( ax=ax, infdata_group=infdata_group, numvars=numvars, figsize=figsize, textsize=textsize, kind=kind, plot_kwargs=plot_kwargs, contour=contour, fill_last=fill_last, gridsize=gridsize, colorbar=colorbar, divergences=divergences, diverging_mask=diverging_mask, divergences_kwargs=divergences_kwargs, flat_var_names=flat_var_names, backend_kwargs=backend_kwargs, show=show, ) if backend == "bokeh": pairplot_kwargs.pop("gridsize", None) pairplot_kwargs.pop("colorbar", None) pairplot_kwargs.pop("divergences_kwargs", None) pairplot_kwargs.pop("hexbin_values", None) # TODO: Add backend kwargs plot = get_plotting_function("plot_pair", "pairplot", backend) ax = plot(**pairplot_kwargs) return ax
[ 37811, 43328, 257, 41058, 393, 17910, 8800, 286, 35846, 10007, 526, 15931, 198, 11748, 14601, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 11485, 7890, 1330, 10385, 62, 1462, 62, 19608, 292, 316, 11, 10385, 62, 1462, 62, 259, 428...
2.336799
3,174
from django.forms import ModelForm from .models import Cuestionario, Categoria from preguntas.models import Pregunta, Respuesta
[ 6738, 42625, 14208, 13, 23914, 1330, 9104, 8479, 198, 6738, 764, 27530, 1330, 14496, 395, 295, 4982, 11, 327, 2397, 7661, 198, 6738, 662, 70, 2797, 292, 13, 27530, 1330, 350, 2301, 44424, 11, 10328, 84, 18059, 628, 198 ]
3.333333
39
from django.views.generic import View from django.http import HttpResponse import os, json, datetime from django.shortcuts import redirect from django.shortcuts import render_to_response from vitcloud.models import File from django.views.decorators.csrf import csrf_exempt from listingapikeys import findResult import sys # sys.setdefaultencoding is cancelled by site.py reload(sys) # to re-enable sys.setdefaultencoding() sys.setdefaultencoding('utf-8') #Custom Functions: #**Not for Production** Views #Views:
[ 6738, 42625, 14208, 13, 33571, 13, 41357, 1330, 3582, 198, 6738, 42625, 14208, 13, 4023, 1330, 367, 29281, 31077, 198, 11748, 28686, 11, 33918, 11, 4818, 8079, 198, 6738, 42625, 14208, 13, 19509, 23779, 1330, 18941, 198, 6738, 42625, 1420...
2.876289
194
from abc import ABC import discord
[ 6738, 450, 66, 1330, 9738, 198, 11748, 36446, 628 ]
4
9
"""change admin to boolean Revision ID: e86dd3bc539c Revises: 6f63ef516cdc Create Date: 2020-11-11 22:32:00.707936 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'e86dd3bc539c' down_revision = '6f63ef516cdc' branch_labels = None depends_on = None
[ 37811, 3803, 13169, 284, 25131, 198, 198, 18009, 1166, 4522, 25, 304, 4521, 1860, 18, 15630, 20, 2670, 66, 198, 18009, 2696, 25, 718, 69, 5066, 891, 47493, 10210, 66, 198, 16447, 7536, 25, 12131, 12, 1157, 12, 1157, 2534, 25, 2624, ...
2.512195
123
# Generated by Django 4.0.3 on 2022-03-16 03:09 from django.db import migrations
[ 2, 2980, 515, 416, 37770, 604, 13, 15, 13, 18, 319, 33160, 12, 3070, 12, 1433, 7643, 25, 2931, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 628 ]
2.766667
30
""" Abstract training class """ from abc import ABC as AbstractBaseClass from abc import abstractmethod
[ 37811, 198, 23839, 3047, 1398, 198, 37811, 198, 6738, 450, 66, 1330, 9738, 355, 27741, 14881, 9487, 198, 6738, 450, 66, 1330, 12531, 24396, 628 ]
4.2
25
# -*- coding: utf-8 -*- # from mpmath import mp from .helpers import untangle2
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 6738, 285, 4426, 776, 1330, 29034, 198, 198, 6738, 764, 16794, 364, 1330, 1418, 9248, 17, 628 ]
2.454545
33
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from rest_framework.authtoken.models import Token from account.models import Profile admin.site.site_header = 'invoce' admin.site.unregister(Token) admin.site.register(Token, TokenAdmin) admin.site.unregister(User) admin.site.register(User, UserCustomAdmin)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, ...
3.137931
145
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jun 18 08:40:11 2020 @author: krishan """ for val in (0, "hello", 50.0, 13): print(f"Testing {val}:", funny_division3(val))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 26223, 7653, 1248, 8487, 25, 1821, 25, 1157, 12131, 198, 198, 31, 9800, 25, 479, 37518, 2...
2.142857
98
import os from datetime import datetime import torch from dataclasses import dataclass
[ 11748, 28686, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 11748, 28034, 198, 198, 6738, 4818, 330, 28958, 1330, 4818, 330, 31172, 628 ]
3.869565
23
# Copyright (c) 2014 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest from datetime import datetime import hashlib import os from os.path import join import time from mock import patch from swift.common import swob from swift.common.swob import Request from test.unit.common.middleware.s3api import S3ApiTestCase from test.unit.common.middleware.s3api.test_s3_acl import s3acl from swift.common.middleware.s3api.subresource import ACL, User, encode_acl, \ Owner, Grant from swift.common.middleware.s3api.etree import fromstring from swift.common.middleware.s3api.utils import mktime, S3Timestamp from test.unit.common.middleware.s3api.helpers import FakeSwift def test_object_PUT_copy_headers_with_match(self): etag = '7dfa07a8e59ddbcd1dc84d4c4f82aea1' last_modified_since = 'Fri, 01 Apr 2014 11:00:00 GMT' header = {'X-Amz-Copy-Source-If-Match': etag, 'X-Amz-Copy-Source-If-Modified-Since': last_modified_since, 'Date': self.get_date_header()} status, header, body = \ self._test_object_PUT_copy(swob.HTTPOk, header) self.assertEqual(status.split()[0], '200') self.assertEqual(len(self.swift.calls_with_headers), 2) _, _, headers = self.swift.calls_with_headers[-1] self.assertTrue(headers.get('If-Match') is None) self.assertTrue(headers.get('If-Modified-Since') is None) _, _, headers = self.swift.calls_with_headers[0] self.assertEqual(headers['If-Match'], etag) self.assertEqual(headers['If-Modified-Since'], last_modified_since) def _test_object_for_s3acl(self, method, account): req = Request.blank('/bucket/object', environ={'REQUEST_METHOD': method}, headers={'Authorization': 'AWS %s:hmac' % account, 'Date': self.get_date_header()}) return self.call_s3api(req) def _test_set_container_permission(self, account, permission): grants = [Grant(User(account), permission)] headers = \ encode_acl('container', ACL(Owner('test:tester', 'test:tester'), grants)) self.swift.register('HEAD', '/v1/AUTH_test/bucket', swob.HTTPNoContent, headers, None) def _test_object_copy_for_s3acl(self, account, src_permission=None, src_path='/src_bucket/src_obj'): owner = 'test:tester' grants = [Grant(User(account), src_permission)] \ if src_permission else [Grant(User(owner), 'FULL_CONTROL')] src_o_headers = \ encode_acl('object', ACL(Owner(owner, owner), grants)) src_o_headers.update({'last-modified': self.last_modified}) self.swift.register( 'HEAD', join('/v1/AUTH_test', src_path.lstrip('/')), swob.HTTPOk, src_o_headers, None) req = Request.blank( '/bucket/object', environ={'REQUEST_METHOD': 'PUT'}, headers={'Authorization': 'AWS %s:hmac' % account, 'X-Amz-Copy-Source': src_path, 'Date': self.get_date_header()}) return self.call_s3api(req) if __name__ == '__main__': unittest.main()
[ 2, 15069, 357, 66, 8, 1946, 4946, 25896, 5693, 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.300784
1,659
""" Eddsa Ed25519 key handling From https://github.com/n-y-z-o/nyzoVerifier/blob/b73bc25ba3094abe3470ec070ce306885ad9a18f/src/main/java/co/nyzo/verifier/KeyUtil.java plus https://github.com/n-y-z-o/nyzoVerifier/blob/17509f03a7f530c0431ce85377db9b35688c078e/src/main/java/co/nyzo/verifier/util/SignatureUtil.java """ # Uses https://github.com/warner/python-ed25519 , c binding, fast import ed25519 import hashlib from pynyzo.byteutil import ByteUtil if __name__ == "__main__": KeyUtil.main() # KeyUtil.private_to_public('nyzo-formatted-private-key'.replace('-', ''))
[ 37811, 198, 36, 1860, 11400, 1717, 13381, 1129, 1994, 9041, 198, 4863, 198, 5450, 1378, 12567, 13, 785, 14, 77, 12, 88, 12, 89, 12, 78, 14, 3281, 10872, 13414, 7483, 14, 2436, 672, 14, 65, 4790, 15630, 1495, 7012, 1270, 5824, 11231,...
2.313492
252
from argparse import ArgumentParser import os import numpy as np from joblib import dump from mldftdat.workflow_utils import SAVE_ROOT from mldftdat.models.gp import * from mldftdat.data import load_descriptors, filter_descriptors import yaml if __name__ == '__main__': main()
[ 6738, 1822, 29572, 1330, 45751, 46677, 198, 11748, 28686, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 1693, 8019, 1330, 10285, 198, 6738, 285, 335, 701, 19608, 13, 1818, 11125, 62, 26791, 1330, 14719, 6089, 62, 13252, 2394, 198, 6738, ...
3.032258
93
import api import bson from api.annotations import ( api_wrapper, log_action, require_admin, require_login, require_teacher ) from api.common import WebError, WebSuccess from flask import ( Blueprint, Flask, render_template, request, send_from_directory, session ) blueprint = Blueprint("admin_api", __name__)
[ 11748, 40391, 198, 11748, 275, 1559, 198, 6738, 40391, 13, 34574, 602, 1330, 357, 198, 220, 220, 220, 40391, 62, 48553, 11, 198, 220, 220, 220, 2604, 62, 2673, 11, 198, 220, 220, 220, 2421, 62, 28482, 11, 198, 220, 220, 220, 2421, ...
2.717557
131
#!/usr/bin/python import json import argparse from influxdb import InfluxDBClient parser = argparse.ArgumentParser(description = 'pull data for softlayer queue' ) parser.add_argument( 'measurement' , help = 'measurement001' ) args = parser.parse_args() client_influxdb = InfluxDBClient('50.23.117.76', '8086', 'cricket', 'cricket', 'cricket_data') query = 'SELECT "data_center", "device", "value" FROM "cricket_data"."cricket_retention".'+args.measurement+' WHERE time > now() - 10m order by time' result = client_influxdb.query(query) for r in result: i = 0 for data_center, device, value, time in r: print args.measurement,'\t',r[i][data_center],'\t',r[i][device],'\t',r[i][time],'\t',r[i][value] i += 1
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 198, 11748, 33918, 198, 11748, 1822, 29572, 198, 6738, 25065, 9945, 1330, 4806, 22564, 11012, 11792, 198, 198, 48610, 796, 1822, 29572, 13, 28100, 1713, 46677, 7, 11213, 796, 705, 31216, 1366, ...
2.594982
279
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations from typing import cast from pants.core.util_rules.config_files import ConfigFilesRequest from pants.core.util_rules.external_tool import TemplatedExternalTool from pants.option.custom_types import file_option, shell_str
[ 2, 15069, 33448, 41689, 1628, 20420, 357, 3826, 27342, 9865, 3843, 20673, 13, 9132, 737, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 3826, 38559, 24290, 737, 198, 198, 6738, 11593, 37443, 834, 1330, 37647, 198, ...
3.91
100
""" Handles functionality related to data storege. """ import sys, os, glob, re, gzip, json from biorun import const, utils, objects, ncbi from biorun.models import jsonrec import biorun.libs.placlib as plac # Module level logger. logger = utils.logger # A nicer error message on incorrect installation. try: from Bio import SeqIO except ImportError as exc: print(f"*** Error: {exc}", file=sys.stderr) print(f"*** This program requires biopython", file=sys.stderr) print(f"*** Install: conda install -y biopython>=1.78", file=sys.stderr) sys.exit(-1) def resolve_fname(name, format='json'): """ Resolve a file name given an accession number. """ ext = format.lower() fname = f"{name}.{ext}.gz" fname = os.path.join(utils.DATADIR, fname) return fname def delete_data(text): """ Deletes data under a filename. """ for name in text.split(","): fname = resolve_fname(name) if os.path.isfile(fname): os.remove(fname) logger.info(f"removed: {fname}") else: logger.info(f"file does not exist: {fname}") def read_json_file(fname): """ Returns the content of a JSON file. """ fp = utils.gz_read(fname) data = json.load(fp) fp.close() return data def save_json_file(fname, data): """ Returns the content of a JSON file. """ fp = utils.gz_write(fname) json.dump(data, fp) fp.close() logger.info(f"saved {fname}") return data def change_seqid(json_name, seqid): """ Changes the sequence id stored in a json file. """ if os.path.isfile(json_name): data = read_json_file(json_name) for item in data: item[const.SEQID] = seqid fp = utils.gz_write(json_name) json.dump(data, fp) fp.close() def fetch_data(data, param): """ Obtains data from NCBI. Fills each parameter with a json field. """ db = "protein" if param.protein else "nuccore" # Ensure json DB is built ncbi.build_db() genbank, taxon_acc, refseq = ncbi.get_data() for name in data: # Pretend no data if it is an update. json = None if param.update else get_json(name) # The data exists, nothing needs to be done. if json: continue # The JSON representation of the data. json_name = resolve_fname(name=name, format="json") # GenBank representation of the data. gbk_name = resolve_fname(name=name, format="gb") # Genome assembly data. if name.startswith("GCA") or name.startswith("GCF"): ncbi.genome(name=name, fname=gbk_name, update=param.update, genbank=genbank, refseq=refseq) else: # Genbank data. ncbi.genbank_save(name, db=db, fname=gbk_name) # Convert Genbank to JSON. data = jsonrec.parse_file(fname=gbk_name, seqid=param.seqid) # Save JSON file. save_json_file(fname=json_name, data=data) def get_json(name, seqid=None, inter=False, strict=False): """ Attempts to return a JSON formatted data based on a name. """ # Data is an existing path to a JSON file. if os.path.isfile(name): try: data = jsonrec.parse_file(name, seqid=seqid) except Exception as exc: logger.error(f"JSON parsing error for file {name}: {exc}") sys.exit(-1) return data # The JSON representation of the data. json_name = resolve_fname(name=name, format="json") # GenBank representation of the data. gbk_name = resolve_fname(name=name, format="gb") # Found the JSON representation of the file. if os.path.isfile(json_name): logger.info(f"found {json_name}") data = read_json_file(json_name) return data # There is no JSON file but there is a GenBank file. if os.path.isfile(gbk_name): logger.info(f"found {gbk_name}") data = jsonrec.parse_file(fname=gbk_name, seqid=seqid) data = save_json_file(fname=json_name, data=data) return data # Interactive input, make JSON from name if inter: data = jsonrec.make_jsonrec(name, seqid=seqid) return data # Raise error if in strict mode if strict: utils.error(f"data not found: {name}") return None def rename_data(data, param, newname=None): """ Rename data. """ # Will only rename a single data newnames = newname.split(",") for name1, name2 in zip(data, newnames): src_json = resolve_fname(name=name1, format="json") dest_json = resolve_fname(name=name2, format="json") src_gb = resolve_fname(name=name1, format="gb") dest_gb = resolve_fname(name=name2, format="gb") if os.path.isfile(src_json): logger.info(f"renamed {name1} as {name2}") os.rename(src_json, dest_json) if param.seqid: change_seqid(dest_json, seqid=param.seqid) else: logger.info(f"file not found: {src_json}") if os.path.isfile(src_gb): if not os.path.isfile(dest_gb): os.symlink(src_gb, dest_gb) else: logger.info(f"file not found: {src_gb}") def print_data_list(): """ Returns a list of the files in the data directory """ pattern = os.path.join(os.path.join(utils.DATADIR, '*.json.gz')) matched = glob.glob(pattern) # Extract the definition from the JSON without parsing it. patt = re.compile(r'(definition\":\s*)(?P<value>\".+?\")') collect = [] for path in matched: fsize = utils.human_size(os.path.getsize(path)) base, fname = os.path.split(path) fname = fname.rsplit(".", maxsplit=2)[0] # Parse the first N lines stream = gzip.open(path, 'rt') if path.endswith('gz') else open(path, 'rt') text = stream.read(1000) match = patt.search(text) title = match.group("value") if match else '' title = title.strip('", ') # Trim the title stitle = title[:100] stitle = stitle + "..." if len(title) != len(stitle) else stitle collect.append((str(fsize), f"{fname:10s}", stitle)) collect = sorted(collect, key=lambda x: x[2]) for row in collect: line = "\t".join(row) print(line)
[ 37811, 198, 12885, 829, 11244, 3519, 284, 1366, 3650, 469, 13, 198, 37811, 198, 11748, 25064, 11, 28686, 11, 15095, 11, 302, 11, 308, 13344, 11, 33918, 198, 6738, 275, 1504, 403, 1330, 1500, 11, 3384, 4487, 11, 5563, 11, 299, 66, 84...
2.242297
2,856
import numpy as np from random import randint from PyQt5.QtGui import QImage from PyQt5.QtCore import QPointF
[ 11748, 299, 32152, 355, 45941, 198, 6738, 4738, 1330, 43720, 600, 198, 198, 6738, 9485, 48, 83, 20, 13, 48, 83, 8205, 72, 1330, 1195, 5159, 198, 6738, 9485, 48, 83, 20, 13, 48, 83, 14055, 1330, 1195, 12727, 37, 198 ]
2.707317
41
# coding: utf-8 """ Trend Micro Deep Security API Copyright 2018 - 2020 Trend Micro Incorporated.<br/>Get protected, stay secured, and keep informed with Trend Micro Deep Security's new RESTful API. Access system data and manage security configurations to automate your security workflows and integrate Deep Security into your CI/CD pipeline. # noqa: E501 OpenAPI spec version: 12.5.841 Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, ApplicationTypeRights): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
[ 2, 19617, 25, 3384, 69, 12, 23, 201, 198, 201, 198, 37811, 201, 198, 220, 220, 220, 22836, 4527, 10766, 4765, 7824, 201, 198, 201, 198, 220, 220, 220, 15069, 2864, 532, 12131, 22836, 4527, 3457, 40132, 29847, 1671, 15913, 3855, 6861, ...
2.662736
424
from __future__ import print_function # Python 2/3 compatibility from gremlin_python import statics from gremlin_python.structure.graph import Graph from gremlin_python.process.graph_traversal import __ from gremlin_python.process.strategies import * from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection #initializing the graph object graph = Graph() #creating connection with the remote remoteConn = DriverRemoteConnection('wss://<endpoint>:8182/gremlin','g') g = graph.traversal().withRemote(DriverRemoteConnection('wss://<endpoint>:8182/gremlin','g')) print('Connection created.') #clearing out all the vertices to start fresh g.V().drop().iterate() print('Deleting everything and starting clean.') #Adding some vertices (nodes) gerald = g.addV('person').property('age','81').property('first_name','Gerald').property('stays_in','Portland').next() edith = g.addV('person').property('age','78').property('first_name','Edith').property('stays_in','Portland').next() peter = g.addV('person').property('age','52').property('first_name','Shane').property('stays_in','Seattle').next() mary = g.addV('person').property('age','50').property('first_name','Mary').property('stays_in','Seattle').next() betty = g.addV('person').property('age','19').property('first_name','Betty').property('stays_in','Chicago').next() print('Added some vertices (nodes).') #Adding relationships (edges) edge = g.V().has('first_name', 'Gerald').addE('husband_of').to(g.V().has('first_name', 'Edith')).property('married_since','1947').next() edge = g.V().has('first_name', 'Edith').addE('wife_of').to(g.V().has('first_name', 'Gerald')).property('married_since','1947').next() edge = g.V().has('first_name', 'Shane').addE('son_of').to(g.V().has('first_name', 'Gerald')).property('known_since','1964').next() edge = g.V().has('first_name', 'Gerald').addE('father_of').to(g.V().has('first_name', 'Shane')).property('known_since','1964').next() edge = g.V().has('first_name', 'Shane').addE('son_of').to(g.V().has('first_name', 'Edith')).property('known_since','1964').next() edge = g.V().has('first_name', 'Edith').addE('mother_of').to(g.V().has('first_name', 'Shane')).property('known_since','1964').next() edge = g.V().has('first_name', 'Shane').addE('husband_of').to(g.V().has('first_name', 'Mary')).property('known_since','1989').next() edge = g.V().has('first_name', 'Mary').addE('wife_of').to(g.V().has('first_name', 'Shane')).property('known_since','1989').next() edge = g.V().has('first_name', 'Shane').addE('father_of').to(g.V().has('first_name', 'Betty')).property('known_since','1991').next() edge = g.V().has('first_name', 'Betty').addE('daughter_of').to(g.V().has('first_name', 'Shane')).property('known_since','1991').next() edge = g.V().has('first_name', 'Mary').addE('mother_of').to(g.V().has('first_name', 'Betty')).property('known_since','1991').next() edge = g.V().has('first_name', 'Betty').addE('daughter_of').to(g.V().has('first_name', 'Mary')).property('known_since','1991').next() #print out all the node's first names print('\n Printing first name from all nodes:') print(g.V().first_name.toList()) #print out all the properties of person whose's first name is Shane print('\n Printing all properties of person whose first name is Shane:') print(g.V().has('person','first_name','Shane').valueMap().next()) #traversing the graph starting with Betty to then Shane to then Edith print('\n Finding Betty and then looking up her parents:') print(g.V().has('first_name', 'Betty').out('daughter_of').out('son_of').valueMap().toList()) #Print out all the nodes print('\n Printing out all the nodes:') people = g.V().valueMap().toList() print(people) #Print out all the connections (edges) print('\n Print out all the connections (edges):') connections = g.E().valueMap().toList() print(connections) #Closing the connection remoteConn.close() print('Connection closed!')
[ 6738, 11593, 37443, 834, 220, 1330, 3601, 62, 8818, 220, 1303, 11361, 362, 14, 18, 17764, 198, 198, 6738, 308, 17244, 62, 29412, 1330, 1185, 873, 198, 6738, 308, 17244, 62, 29412, 13, 301, 5620, 13, 34960, 1330, 29681, 198, 6738, 308,...
3.002309
1,299
import os from os.path import join, isdir from pathlib import Path from collections import defaultdict from tqdm import tqdm import nibabel as nib import numpy as np import json from .resample import resample_patient from .custom_augmentations import resize_data_and_seg, crop_to_bbox def standardize_per_image(image): """ Z-score standardization per image. """ mean, stddev = image.mean(), image.std() return (image - mean) / stddev def parse_slice_idx_to_str(slice_idx): """ Parse the slice index to a three digit string for saving and reading the 2D .npy files generated by io.preprocess.Preprocessor. Naming convention: {type of slice}_{case}_{slice_idx} * adding 0s to slice_idx until it reaches 3 digits, * so sorting files is easier when stacking """ return f"{slice_idx:03}"
[ 11748, 28686, 198, 6738, 28686, 13, 6978, 1330, 4654, 11, 318, 15908, 198, 6738, 3108, 8019, 1330, 10644, 198, 6738, 17268, 1330, 4277, 11600, 198, 6738, 256, 80, 36020, 1330, 256, 80, 36020, 198, 11748, 33272, 9608, 355, 33272, 198, 11...
2.877551
294
import sys import setuptools from setuptools.command.test import test as TestCommand setuptools.setup( name="calm.dsl", version="0.9.0-alpha", author="Nutanix", author_email="nucalm@nutanix.com", description="Calm DSL for blueprints", long_description=read_file("README.md"), long_description_content_type="text/markdown", url="https://github.com/nutanix/calm-dsl", packages=setuptools.find_namespace_packages(include=["calm.*"]), namespace_packages=["calm"], install_requires=read_file("requirements.txt"), tests_require=read_file("dev-requirements.txt"), cmdclass={"test": PyTest}, zip_safe=False, include_package_data=True, entry_points={"console_scripts": ["calm=calm.dsl.cli:main"]}, classifiers=[ "Development Status :: 3 - Alpha", "Environment :: Console", "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Natural Language :: English", "Operating System :: OS Independent", "Programming Language :: Python :: 3.7", ], )
[ 11748, 25064, 198, 11748, 900, 37623, 10141, 198, 6738, 900, 37623, 10141, 13, 21812, 13, 9288, 1330, 1332, 355, 6208, 21575, 628, 628, 198, 2617, 37623, 10141, 13, 40406, 7, 198, 220, 220, 220, 1438, 2625, 9948, 76, 13, 67, 6649, 160...
2.631579
418
# -*- coding:utf-8 -*- # Author: hankcs # Date: 2019-12-28 21:12 from hanlp_common.constant import HANLP_URL SIGHAN2005_PKU_CONVSEG = HANLP_URL + 'tok/sighan2005-pku-convseg_20200110_153722.zip' 'Conv model (:cite:`wang-xu-2017-convolutional`) trained on sighan2005 pku dataset.' SIGHAN2005_MSR_CONVSEG = HANLP_URL + 'tok/convseg-msr-nocrf-noembed_20200110_153524.zip' 'Conv model (:cite:`wang-xu-2017-convolutional`) trained on sighan2005 msr dataset.' CTB6_CONVSEG = HANLP_URL + 'tok/ctb6_convseg_nowe_nocrf_20200110_004046.zip' 'Conv model (:cite:`wang-xu-2017-convolutional`) trained on CTB6 dataset.' PKU_NAME_MERGED_SIX_MONTHS_CONVSEG = HANLP_URL + 'tok/pku98_6m_conv_ngram_20200110_134736.zip' 'Conv model (:cite:`wang-xu-2017-convolutional`) trained on pku98 six months dataset with familiy name and given name merged into one unit.' LARGE_ALBERT_BASE = HANLP_URL + 'tok/large_corpus_cws_albert_base_20211228_160926.zip' 'ALBERT model (:cite:`Lan2020ALBERT:`) trained on the largest CWS dataset in the world.' SIGHAN2005_PKU_BERT_BASE_ZH = HANLP_URL + 'tok/sighan2005_pku_bert_base_zh_20201231_141130.zip' 'BERT model (:cite:`devlin-etal-2019-bert`) trained on sighan2005 pku dataset.' COARSE_ELECTRA_SMALL_ZH = HANLP_URL + 'tok/coarse_electra_small_20220220_013548.zip' 'Electra (:cite:`clark2020electra`) small model trained on coarse-grained CWS corpora. Its performance is P=96.97% R=96.87% F1=96.92% which is ' \ 'much higher than that of MTL model ' FINE_ELECTRA_SMALL_ZH = HANLP_URL + 'tok/fine_electra_small_20220217_190117.zip' 'Electra (:cite:`clark2020electra`) small model trained on fine-grained CWS corpora. Its performance is P=97.44% R=97.40% F1=97.42% which is ' \ 'much higher than that of MTL model ' CTB9_TOK_ELECTRA_SMALL = HANLP_URL + 'tok/ctb9_electra_small_20220215_205427.zip' 'Electra (:cite:`clark2020electra`) small model trained on CTB9. Its performance is P=97.15% R=97.36% F1=97.26% which is ' \ 'much higher than that of MTL model ' # Will be filled up during runtime ALL = {}
[ 2, 532, 9, 12, 19617, 25, 40477, 12, 23, 532, 9, 12, 198, 2, 6434, 25, 289, 962, 6359, 198, 2, 7536, 25, 13130, 12, 1065, 12, 2078, 2310, 25, 1065, 198, 6738, 289, 272, 34431, 62, 11321, 13, 9979, 415, 1330, 367, 1565, 19930, ...
2.299544
878
#!/usr/bin/env python # Copyright 2015 The Swarming Authors. All rights reserved. # Use of this source code is governed under the Apache License, Version 2.0 that # can be found in the LICENSE file. import logging import os import subprocess import sys import tempfile import shutil import unittest import re THIS_FILE = os.path.abspath(__file__) sys.path.insert(0, os.path.dirname(os.path.dirname(THIS_FILE))) from utils import logging_utils # PID YYYY-MM-DD HH:MM:SS.MMM _LOG_HEADER = r'^%d \d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d\.\d\d\d' % os.getpid() _LOG_HEADER_PID = r'^\d+ \d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d\.\d\d\d' _PHASE = 'LOGGING_UTILS_TESTS_PHASE' def call(phase, cwd): """Calls itself back.""" env = os.environ.copy() env[_PHASE] = phase return subprocess.call([sys.executable, '-u', THIS_FILE], env=env, cwd=cwd) if __name__ == '__main__': sys.exit(main())
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 15069, 1853, 383, 2451, 18052, 46665, 13, 1439, 2489, 10395, 13, 198, 2, 5765, 286, 428, 2723, 2438, 318, 21825, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 326, 198, 2, 460, ...
2.357143
378
from featur_selection import df,race,occupation,workclass,country import pandas as pd from sklearn.preprocessing import StandardScaler from sklearn.model_selection import cross_val_score,KFold from sklearn.linear_model import LogisticRegression from imblearn.pipeline import Pipeline from sklearn.compose import ColumnTransformer from imblearn.combine import SMOTETomek from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier,AdaBoostClassifier from sklearn.neighbors import KNeighborsClassifier from catboost import CatBoostClassifier from xgboost import XGBClassifier from sklearn.svm import SVC from matplotlib import pyplot as plt import seaborn as sns df1=df.copy() salary=df1['salary'].reset_index(drop=True) df1=df1.drop(['salary'],axis=1) df1= concat_dataframes(df1) features=['age_logarthmic','hours_per_week'] scaler = ColumnTransformer(transformers = [('scale_num_features', StandardScaler(), features)], remainder='passthrough') models = [LogisticRegression(), SVC(), AdaBoostClassifier(), RandomForestClassifier(), XGBClassifier(),DecisionTreeClassifier(), KNeighborsClassifier(), CatBoostClassifier()] model_labels = ['LogisticReg.','SVC','AdaBoost','RandomForest','Xgboost','DecisionTree','KNN', 'CatBoost'] mean_validation_f1_scores = [] for model in models: data_pipeline = Pipeline(steps = [ ('scaler', scaler), ('resample', SMOTETomek()), ('model', model) ]) mean_validation_f1 = float(cross_val_score(data_pipeline, df1, salary, cv=KFold(n_splits=10), scoring='f1',n_jobs=-1).mean()) mean_validation_f1_scores.append(mean_validation_f1) print(mean_validation_f1_scores) fig, axes = plt.subplots(nrows = 2, ncols = 1, figsize = (15,8)) sns.set_style('dark') sns.barplot(y = model_labels ,x = mean_validation_f1_scores, ax=axes[0]) axes[0].grid(True, color='k') sns.set_style('whitegrid') sns.lineplot(x = model_labels, y = mean_validation_f1_scores) axes[1].grid(True, color='k') fig.show()
[ 6738, 220, 2218, 333, 62, 49283, 1330, 47764, 11, 16740, 11, 19596, 341, 11, 1818, 4871, 11, 19315, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 1341, 35720, 13, 3866, 36948, 1330, 8997, 3351, 36213, 198, 6738, 1341, 35720, 13, 19...
2.621212
792
from __future__ import print_function
[ 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 628 ]
4.333333
9
#!/usr/bin/env python3 import pytest import fileinput from os.path import splitext, abspath F_NAME = 'd8' #implement day8 using bits def find_ones(d): '''count number of ones in binary number''' ones = 0 while d > 0: ones += d & 1 d >>= 1 return ones # Assign each segment a 'wire'. lut = { 'a':0b0000001, 'b':0b0000010, 'c':0b0000100, 'd':0b0001000, 'e':0b0010000, 'f':0b0100000, 'g':0b1000000, } if __name__ == '__main__': import timeit start = timeit.default_timer() filename = fileinput.input(F_NAME + '.input') ans = answer(filename) print('Answer:', ans) duration = timeit.default_timer()-start print(f'Execution time: {duration:.3f} s')
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 11748, 12972, 9288, 198, 11748, 2393, 15414, 198, 6738, 28686, 13, 6978, 1330, 4328, 578, 742, 11, 2352, 6978, 198, 37, 62, 20608, 796, 705, 67, 23, 6, 198, 2, 320, 26908, 1110, ...
2.25
328
""" ******************************** * Created by mohammed-alaa * ******************************** Spatial Dataloader implementing sequence api from keras (defines how to load a single item) this loads batches of images for each iteration it returns [batch_size, height, width ,3] ndarrays """ import copy import random import cv2 import numpy as np import tensorflow.keras as keras from .UCF_splitting_kernel import * from .helpers import get_training_augmenter, get_validation_augmenter if __name__ == '__main__': data_loader = SpatialDataLoader(batch_size=64, use_multiprocessing=True, # data_root_path="data", ucf_split='01', testing_samples_per_video=19, width=224, height=224, num_workers=2) train_loader, test_loader, test_video_level_label = data_loader.run() print(len(train_loader)) print(len(test_loader)) print(train_loader.get_actual_length()) print(test_loader.get_actual_length()) print(train_loader.sequence[0][0].shape, train_loader.sequence[0][1].shape) print(train_loader[0][0].shape, train_loader[0][1].shape) # import tqdm # progress = tqdm.tqdm(train_loader.get_epoch_generator(), total=len(train_loader)) # for (sampled_frame, label) in progress: # pass import matplotlib.pyplot as plt # preview raw data print("train sample") for batch in train_loader.get_epoch_generator(): print(batch[0].shape, batch[1].shape) print(batch[1]) preview(batch[0], batch[1]) break print("test sample") # same name will be displayed testing_samples_per_video with no shuffling for batch in test_loader.get_epoch_generator(): print(batch[1].shape, batch[2].shape) print(batch[0], batch[2]) preview(batch[1], batch[2]) break
[ 37811, 198, 17174, 198, 9, 220, 220, 15622, 416, 285, 1219, 10573, 12, 6081, 64, 220, 220, 1635, 198, 17174, 198, 4561, 34961, 360, 10254, 1170, 263, 15427, 8379, 40391, 422, 41927, 292, 357, 4299, 1127, 703, 284, 3440, 257, 2060, 237...
2.552055
730
# -*- coding:utf-8 -*- """ @version: v1.0 @author: xuelong.liu @license: Apache Licence @contact: xuelong.liu@yulore.com @software: PyCharm @file: base_request_param.py @time: 12/21/16 6:48 PM """
[ 2, 532, 9, 12, 19617, 25, 40477, 12, 23, 532, 9, 12, 198, 198, 37811, 198, 31, 9641, 25, 410, 16, 13, 15, 198, 31, 9800, 25, 2124, 2731, 506, 13, 4528, 84, 198, 31, 43085, 25, 24843, 10483, 594, 220, 198, 31, 32057, 25, 2124, ...
2.197802
91
# stdlib imports import copy # vendor imports import click # Execute cli function on main if __name__ == "__main__": main()
[ 2, 14367, 8019, 17944, 198, 11748, 4866, 198, 198, 2, 18371, 17944, 198, 11748, 3904, 628, 198, 198, 2, 8393, 1133, 537, 72, 2163, 319, 1388, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1388, 34...
3
44
import os dirs = [ './PANDORA_files', './PANDORA_files/data', './PANDORA_files/data/csv_pkl_files', './PANDORA_files/data/csv_pkl_files/mhcseqs', './PANDORA_files/data/PDBs', './PANDORA_files/data/PDBs/pMHCI', './PANDORA_files/data/PDBs/pMHCII', './PANDORA_files/data/PDBs/Bad', './PANDORA_files/data/PDBs/Bad/pMHCI', './PANDORA_files/data/PDBs/Bad/pMHCII', './PANDORA_files/data/PDBs/IMGT_retrieved', './PANDORA_files/data/outputs', './test/test_data/PDBs/Bad','./test/test_data/PDBs/Bad/pMHCI', './test/test_data/PDBs/Bad/pMHCII', './test/test_data/csv_pkl_files' ] for D in dirs: try: os.mkdir(D) except OSError: print('Could not make directory: ' + D) # Install dependenciess # os.popen("alias KEY_MODELLER='XXXX'").read() # os.popen("conda install -y -c salilab modeller").read() # os.popen("conda install -y -c bioconda muscle").read() # os.popen("pip install -e ./").read()
[ 11748, 28686, 198, 198, 15908, 82, 796, 685, 198, 220, 220, 220, 220, 220, 220, 220, 705, 19571, 47, 6981, 1581, 32, 62, 16624, 3256, 705, 19571, 47, 6981, 1581, 32, 62, 16624, 14, 7890, 3256, 705, 19571, 47, 6981, 1581, 32, 62, 1...
1.975904
498
# app/auth/views.py import os from flask import flash, redirect, render_template, url_for, request from flask_login import login_required, login_user, logout_user, current_user from . import auth from .forms import (LoginForm, RegistrationForm, RequestResetForm, ResetPasswordForm) from .. import db, mail from ..models import User from flask_mail import Message from werkzeug.security import generate_password_hash def send_reset_email(user): try: token = user.get_reset_token() msg = Message('Password Reset Request', sender='activecodar@gmail.com', recipients=[user.email]) msg.body = f''' To reset your password visit the following link {url_for('auth.reset_password', token=token, _external=True)} If you did not make this request ignore this email ''' mail.send(msg) except Exception as e: print(e)
[ 2, 598, 14, 18439, 14, 33571, 13, 9078, 198, 11748, 28686, 198, 6738, 42903, 1330, 7644, 11, 18941, 11, 8543, 62, 28243, 11, 19016, 62, 1640, 11, 2581, 198, 6738, 42903, 62, 38235, 1330, 17594, 62, 35827, 11, 17594, 62, 7220, 11, 26...
2.581769
373
# Copyright 2015 Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import logging from oslo_messaging._drivers.zmq_driver.client.publishers\ import zmq_publisher_base from oslo_messaging._drivers.zmq_driver import zmq_async from oslo_messaging._drivers.zmq_driver import zmq_names from oslo_messaging._i18n import _LI, _LW LOG = logging.getLogger(__name__) zmq = zmq_async.import_zmq()
[ 2, 220, 220, 220, 15069, 1853, 7381, 20836, 11, 3457, 13, 198, 2, 198, 2, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 220, 220, 220, 407, 779, 428, 2393, ...
2.959119
318
import pickle import warnings import collections.abc from math import isnan from statistics import mean, median, stdev, mode from abc import abstractmethod, ABC from numbers import Number from collections import defaultdict from itertools import islice, chain from typing import Hashable, Optional, Sequence, Union, Iterable, Dict, Any, List, Tuple, Callable, Mapping from coba.backports import Literal from coba import pipes from coba.random import CobaRandom from coba.exceptions import CobaException from coba.statistics import iqr from coba.pipes import Flatten from coba.environments.primitives import Interaction from coba.environments.logged.primitives import LoggedInteraction from coba.environments.simulated.primitives import SimulatedInteraction
[ 11748, 2298, 293, 198, 11748, 14601, 198, 11748, 17268, 13, 39305, 198, 198, 6738, 10688, 1330, 2125, 272, 198, 6738, 7869, 1330, 1612, 11, 14288, 11, 336, 7959, 11, 4235, 198, 6738, 450, 66, 1330, 12531, 24396, 11, 9738, 198, 6738, 3...
3.529412
221
# # Copyright (c) 2019, NVIDIA CORPORATION. # # 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 cudf import nvcategory from librmm_cffi import librmm import numpy as np def _enforce_str(y: cudf.Series) -> cudf.Series: ''' Ensure that nvcategory is being given strings ''' if y.dtype != "object": return y.astype("str") return y
[ 2, 198, 2, 15069, 357, 66, 8, 13130, 11, 15127, 23929, 44680, 6234, 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, ...
3.185185
270
import re import difflib import pandas as pd import numpy as np from nameparser import HumanName from nameparser.config import CONSTANTS CONSTANTS.titles.remove("gen") CONSTANTS.titles.remove("prin") if __name__ == "__main__": import graph papers = pd.read_csv("cogsci_proceedings_raw.csv") papers['type'] = papers['section'].apply(parse_paper_type) papers = extract_authors(papers) G = graph.make_author_graph(papers) papers, G = fix_author_misspellings(papers, G) papers.to_csv("cogsci_proceedings.csv", encoding='utf-8')
[ 11748, 302, 198, 11748, 814, 8019, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 1438, 48610, 1330, 5524, 5376, 198, 6738, 1438, 48610, 13, 11250, 1330, 7102, 2257, 1565, 4694, 198, 10943, 225...
2.700483
207
# Generated by Django 3.1 on 2020-08-11 19:45 from django.db import migrations
[ 2, 2980, 515, 416, 37770, 513, 13, 16, 319, 12131, 12, 2919, 12, 1157, 678, 25, 2231, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 628 ]
2.892857
28
from pythonfuzz.main import PythonFuzz from tinytag import TinyTag import io if __name__ == '__main__': fuzz()
[ 6738, 21015, 69, 4715, 13, 12417, 1330, 11361, 37, 4715, 198, 6738, 7009, 12985, 1330, 20443, 24835, 198, 11748, 33245, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 197, 69, 4715, 3419, 628, 198 ]
2.948718
39
/home/runner/.cache/pip/pool/d1/fc/c7/6cbbdf9c58b6591d28ed792bbd7944946d3f56042698e822a2869787f6
[ 14, 11195, 14, 16737, 11757, 23870, 14, 79, 541, 14, 7742, 14, 67, 16, 14, 16072, 14, 66, 22, 14, 21, 66, 11848, 7568, 24, 66, 3365, 65, 2996, 6420, 67, 2078, 276, 48156, 11848, 67, 3720, 31911, 3510, 67, 18, 69, 20, 31916, 2075...
1.745455
55
# coding: utf-8 # pylint: disable = invalid-name, C0111 import gpboost as gpb import numpy as np from sklearn.metrics import mean_squared_error import matplotlib.pyplot as plt plt.style.use('ggplot') #--------------------Cross validation for tree-boosting without GP or random effects---------------- print('Simulating data...') # Simulate and create your dataset def f1d(x): """Non-linear function for simulation""" return (1.7 * (1 / (1 + np.exp(-(x - 0.5) * 20)) + 0.75 * x)) x = np.linspace(0, 1, 200, endpoint=True) plt.plot(x, f1d(x), linewidth=2, color="r") plt.title("Mean function") plt.show() def sim_data(n): """Function that simulates data. Two covariates of which only one has an effect""" X = np.random.rand(n, 2) # mean function plus noise y = f1d(X[:, 0]) + np.random.normal(scale=0.1, size=n) return ([X, y]) # Simulate data n = 1000 data = sim_data(2 * n) # create dataset for gpb.train data_train = gpb.Dataset(data[0][0:n, :], data[1][0:n]) # specify your configurations as a dict params = { 'objective': 'regression_l2', 'metric': {'l2', 'l1'}, 'learning_rate': 0.1, 'max_depth': 6, 'min_data_in_leaf': 5, 'verbose': 0 } print('Starting cross-validation...') # do cross-validation cvbst = gpb.cv(params=params, train_set=data_train, num_boost_round=100, early_stopping_rounds=5, nfold=2, verbose_eval=True, show_stdv=False, seed=1) print("Best number of iterations: " + str(np.argmin(cvbst['l2-mean']))) # --------------------Combine tree-boosting and grouped random effects model---------------- print('Simulating data...') # Simulate data def f1d(x): """Non-linear function for simulation""" return (1.7 * (1 / (1 + np.exp(-(x - 0.5) * 20)) + 0.75 * x)) x = np.linspace(0, 1, 200, endpoint=True) plt.figure("Mean function") plt.plot(x, f1d(x), linewidth=2, color="r") plt.title("Mean function") plt.show() n = 1000 # number of samples np.random.seed(1) X = np.random.rand(n, 2) F = f1d(X[:, 0]) # Simulate grouped random effects m = 25 # number of categories / levels for grouping variable group = np.arange(n) # grouping variable for i in range(m): group[int(i * n / m):int((i + 1) * n / m)] = i # incidence matrix relating grouped random effects to samples Z1 = np.zeros((n, m)) for i in range(m): Z1[np.where(group == i), i] = 1 sigma2_1 = 1 ** 2 # random effect variance sigma2 = 0.1 ** 2 # error variance b1 = np.sqrt(sigma2_1) * np.random.normal(size=m) # simulate random effects eps = Z1.dot(b1) xi = np.sqrt(sigma2) * np.random.normal(size=n) # simulate error term y = F + eps + xi # observed data # define GPModel gp_model = gpb.GPModel(group_data=group) gp_model.set_optim_params(params={"optimizer_cov": "fisher_scoring"}) # create dataset for gpb.train data_train = gpb.Dataset(X, y) # specify your configurations as a dict params = { 'objective': 'regression_l2', 'learning_rate': 0.05, 'max_depth': 6, 'min_data_in_leaf': 5, 'verbose': 0 } print('Starting cross-validation...') # do cross-validation cvbst = gpb.cv(params=params, train_set=data_train, gp_model=gp_model, use_gp_model_for_validation=False, num_boost_round=100, early_stopping_rounds=5, nfold=2, verbose_eval=True, show_stdv=False, seed=1) print("Best number of iterations: " + str(np.argmin(cvbst['l2-mean']))) # Include random effect predictions for validation (observe the lower test error) gp_model = gpb.GPModel(group_data=group) print("Running cross validation for GPBoost model and use_gp_model_for_validation = TRUE") cvbst = gpb.cv(params=params, train_set=data_train, gp_model=gp_model, use_gp_model_for_validation=True, num_boost_round=100, early_stopping_rounds=5, nfold=2, verbose_eval=True, show_stdv=Falsem, seed=1) print("Best number of iterations: " + str(np.argmin(cvbst['l2-mean']))) cvbst.best_iteration
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 2, 279, 2645, 600, 25, 15560, 796, 12515, 12, 3672, 11, 327, 486, 1157, 198, 11748, 27809, 39521, 355, 27809, 65, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 1341, 35720, 13, 4164, 10466, 1330...
2.481784
1,592
# Copyright 2022 The Matrix.org Foundation C.I.C. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from synapse.api.errors import StoreError from synapse.http.server import DirectServeHtmlResource, respond_with_html_bytes from synapse.http.servlet import parse_string from synapse.http.site import SynapseRequest if TYPE_CHECKING: from synapse.server import HomeServer
[ 2, 15069, 33160, 383, 24936, 13, 2398, 5693, 327, 13, 40, 13, 34, 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, ...
3.686992
246
import set_path import sys import torch set_path.append_sys_path() import rela import hanalearn import utils assert rela.__file__.endswith(".so") assert hanalearn.__file__.endswith(".so")
[ 11748, 900, 62, 6978, 198, 11748, 25064, 198, 11748, 28034, 198, 198, 2617, 62, 6978, 13, 33295, 62, 17597, 62, 6978, 3419, 198, 198, 11748, 823, 64, 198, 11748, 289, 272, 282, 451, 77, 198, 11748, 3384, 4487, 198, 198, 30493, 823, ...
2.56
75
# ****************************************************** ## Copyright 2019, PBL Netherlands Environmental Assessment Agency and Utrecht University. ## Reuse permitted under Gnu Public License, GPL v3. # ****************************************************** from netCDF4 import Dataset import numpy as np import general_path import accuflux import ascraster import get_surrounding_cells import make_np_grid
[ 2, 41906, 8412, 2466, 1174, 198, 2235, 15069, 13130, 11, 350, 9148, 12671, 13272, 25809, 7732, 290, 7273, 260, 21474, 2059, 13, 198, 2235, 797, 1904, 10431, 739, 18509, 84, 5094, 13789, 11, 38644, 410, 18, 13, 198, 2, 41906, 8412, 246...
4.408602
93
from io import TextIOWrapper import math from typing import TypeVar import random import os from Settings import Settings #pist = Pistachio(Dataset.LINUX_NL) # #for row in pist.Load()[0:10]: # print(row)
[ 6738, 33245, 1330, 8255, 40, 3913, 430, 2848, 201, 198, 11748, 10688, 201, 198, 6738, 19720, 1330, 5994, 19852, 201, 198, 11748, 4738, 201, 198, 11748, 28686, 201, 198, 6738, 16163, 1330, 16163, 201, 198, 201, 198, 201, 198, 201, 198, ...
2.395833
96
import datetime import decimal import json import traceback from django.conf import settings from django.core.mail import EmailMessage from django.db import models from django.utils import timezone from django.template.loader import render_to_string from django.contrib.sites.models import Site import stripe from jsonfield.fields import JSONField from .managers import CustomerManager, ChargeManager, TransferManager from .settings import ( DEFAULT_PLAN, INVOICE_FROM_EMAIL, PAYMENTS_PLANS, plan_from_stripe_id, SEND_EMAIL_RECEIPTS, TRIAL_PERIOD_FOR_USER_CALLBACK, PLAN_QUANTITY_CALLBACK ) from .signals import ( cancelled, card_changed, subscription_made, webhook_processing_error, WEBHOOK_SIGNALS, ) from .utils import convert_tstamp stripe.api_key = settings.STRIPE_SECRET_KEY stripe.api_version = getattr(settings, "STRIPE_API_VERSION", "2012-11-07")
[ 11748, 4818, 8079, 198, 11748, 32465, 198, 11748, 33918, 198, 11748, 12854, 1891, 198, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 7295, 13, 4529, 1330, 9570, 12837, 198, 6738, 42625, 14208, 13, 9945, 1330...
2.819572
327
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 1999-2020 Alibaba Group Holding Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..datasource import tensor as astensor def flip(m, axis): """ Reverse the order of elements in a tensor along the given axis. The shape of the array is preserved, but the elements are reordered. Parameters ---------- m : array_like Input tensor. axis : integer Axis in tensor, which entries are reversed. Returns ------- out : array_like A view of `m` with the entries of axis reversed. Since a view is returned, this operation is done in constant time. See Also -------- flipud : Flip a tensor vertically (axis=0). fliplr : Flip a tensor horizontally (axis=1). Notes ----- flip(m, 0) is equivalent to flipud(m). flip(m, 1) is equivalent to fliplr(m). flip(m, n) corresponds to ``m[...,::-1,...]`` with ``::-1`` at position n. Examples -------- >>> import mars.tensor as mt >>> A = mt.arange(8).reshape((2,2,2)) >>> A.execute() array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]]) >>> mt.flip(A, 0).execute() array([[[4, 5], [6, 7]], [[0, 1], [2, 3]]]) >>> mt.flip(A, 1).execute() array([[[2, 3], [0, 1]], [[6, 7], [4, 5]]]) >>> A = mt.random.randn(3,4,5) >>> mt.all(mt.flip(A,2) == A[:,:,::-1,...]).execute() True """ m = astensor(m) sl = [slice(None)] * m.ndim try: sl[axis] = slice(None, None, -1) except IndexError: raise ValueError("axis=%i is invalid for the %i-dimensional input tensor" % (axis, m.ndim)) return m[tuple(sl)]
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 15069, 7358, 12, 42334, 41992, 4912, 31703, 12052, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 3...
2.415193
961
# Copyright (c) OpenMMLab. All rights reserved. import pytest import torch _USING_PARROTS = True try: from parrots.autograd import gradcheck except ImportError: from torch.autograd import gradcheck, gradgradcheck _USING_PARROTS = False
[ 2, 15069, 357, 66, 8, 4946, 44, 5805, 397, 13, 1439, 2489, 10395, 13, 198, 11748, 12972, 9288, 198, 11748, 28034, 198, 198, 62, 2937, 2751, 62, 47, 26465, 33472, 796, 6407, 198, 28311, 25, 198, 220, 220, 220, 422, 1582, 24744, 13, ...
2.941176
85
import pandas as pd from tqdm import tqdm data_list = [] debug = False num_choices = 4 tqdm.pandas(desc="Progress") df = pd.read_pickle("data/augmented_datasets/pickle/label_description.pkl") if debug: df = df.iloc[:10] df = df.progress_apply(get_questions, axis=1) new_df = pd.DataFrame(data_list) if not debug: new_df.to_pickle("data/augmented_datasets/pickle/description_qa_knowledge.pkl") else: __import__("pudb").set_trace()
[ 11748, 19798, 292, 355, 279, 67, 198, 6738, 256, 80, 36020, 1330, 256, 80, 36020, 198, 198, 7890, 62, 4868, 796, 17635, 628, 198, 198, 24442, 796, 10352, 198, 22510, 62, 6679, 1063, 796, 604, 198, 198, 83, 80, 36020, 13, 79, 392, ...
2.326425
193
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 """ 'attach' command implementation''' """ from base64 import b64encode import argparse import magic from ..bugzilla import BugzillaError from ..context import bugzilla_instance from .. import ui from .base import Base
[ 2, 43907, 25, 7400, 11338, 28, 19, 4292, 8658, 6482, 10394, 28, 19, 2705, 8658, 11338, 28, 19, 198, 198, 37811, 198, 6, 47348, 6, 3141, 7822, 7061, 6, 198, 37811, 198, 198, 6738, 2779, 2414, 1330, 275, 2414, 268, 8189, 198, 11748, ...
3.419753
81
#!/usr/bin/env python # -*- coding: utf-8 -*- # import numpy import pygmsh from helpers import compute_volume if __name__ == '__main__': import meshio meshio.write('airfoil.vtu', *test())
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 11748, 299, 32152, 198, 11748, 12972, 70, 907, 71, 198, 198, 6738, 49385, 1330, 24061, 62, 29048, 628, 198, 1...
2.439024
82
import pytest
[ 11748, 12972, 9288, 198 ]
3.5
4
import json from threading import Semaphore import ee from flask import request from google.auth import crypt from google.oauth2 import service_account from google.oauth2.credentials import Credentials service_account_credentials = None import logging export_semaphore = Semaphore(5) get_info_semaphore = Semaphore(2)
[ 11748, 33918, 198, 6738, 4704, 278, 1330, 12449, 6570, 382, 198, 198, 11748, 304, 68, 198, 6738, 42903, 1330, 2581, 198, 6738, 23645, 13, 18439, 1330, 8194, 198, 6738, 23645, 13, 12162, 1071, 17, 1330, 2139, 62, 23317, 198, 6738, 23645,...
3.28
100
#https://microbit-micropython.readthedocs.io/en/latest/tutorials/images.html#animation from microbit import * boat1 = Image("05050:05050:05050:99999:09990") boat2 = Image("00000:05050:05050:05050:99999") boat3 = Image("00000:00000:05050:05050:05050") boat4 = Image("00000:00000:00000:05050:05050") boat5 = Image("00000:00000:00000:00000:05050") boat6 = Image("00000:00000:00000:00000:00000") all_boats = [boat1, boat2, boat3, boat4, boat5, boat6] display.show(all_boats, delay=200)
[ 2, 5450, 1378, 24055, 2545, 12, 9383, 1773, 7535, 13, 961, 83, 704, 420, 82, 13, 952, 14, 268, 14, 42861, 14, 83, 44917, 82, 14, 17566, 13, 6494, 2, 11227, 341, 198, 6738, 4580, 2545, 1330, 1635, 198, 24482, 16, 796, 7412, 7203, ...
2.572193
187
import os import json import shutil import time from pyramid.renderers import render_to_response from pyramid.response import Response from groupdocs.ApiClient import ApiClient from groupdocs.AsyncApi import AsyncApi from groupdocs.StorageApi import StorageApi from groupdocs.GroupDocsRequestSigner import GroupDocsRequestSigner # Checking value on null
[ 11748, 28686, 198, 11748, 33918, 198, 11748, 4423, 346, 198, 11748, 640, 198, 198, 6738, 27944, 13, 10920, 19288, 1330, 8543, 62, 1462, 62, 26209, 198, 6738, 27944, 13, 26209, 1330, 18261, 198, 198, 6738, 1448, 31628, 13, 32, 14415, 117...
3.71875
96
from __future__ import print_function import numpy as np import struct import solvers import pid from util import * MOTORSPEED = 0.9 MOTORMARGIN = 1 MOTORSLOPE = 30 ERRORLIM = 5.0 def getServoElevator(self): return 178.21 - degrees(self.shoulder_angle) def getServoActuator(self): return degrees(self.actuator_angle) + 204.78 def getServoSwing(self): return 150 - degrees(self.swing_angle) def getServoWristX(self): return 150 - degrees(self.wristXAngle) def getServoWristY(self): return 147 + degrees(self.wristYAngle) def armDiffAngle(self): return degrees(self.shoulder_angle - self.actuator_angle) def checkActuator(self): angle = self.getServoActuator() return angle >= 95 and angle <= 250 def checkDiff(self): angle = self.armDiffAngle() return angle >= 44 and angle <= 175 def checkElevator(self): angle = self.getServoElevator() return angle >= 60 and angle <= 210 def checkForearm(self): angle = degrees(self.elbow_angle + self.shoulder_angle) return angle < 200 and angle > 80 def checkSwing(self): angle = self.getServoSwing() return angle >= 60 and angle <= 240 def checkWristX(self): angle = self.getServoWristX() return angle >= 60 and angle <= 240 def checkWristY(self): angle = self.getServoWristY() return angle >= 60 and angle <= 160 def checkPositioning(self): # When Y>0 Forearm always faces outwards if self.wrist2D[1] > 0 and self.wrist2D[0] < self.elbow2D[0]: return False # No valid positions X<=0 if self.wrist2D[0] <= 0: return False # Effector height range if self.effector[1] > 180 or self.effector[1] < -200: return False return True def checkClearance(self): return (self.checkDiff() and self.checkActuator() and self.checkElevator() and self.checkSwing() and self.checkWristX() and self.checkWristY() and self.checkPositioning() and self.checkForearm()) def serialize(self): """Returns a packed struct holding the pose information""" return struct.pack( ArmPose.structFormat, self.swing_angle, self.shoulder_angle, self.elbow_angle, self.wristXAngle, self.wristYAngle ) class ArmController: def __init__(self, servo_swing, servo_shoulder, servo_elbow, servo_wrist_x, servo_wrist_y, arm_config, motion_enable = False): # Solvers are responsible for calculating the target servo positions to # reach a given goal position self.ik = solvers.IKSolver( arm_config.main_length, arm_config.forearm_length, arm_config.wrist_length, arm_config.shoulder_offset) self.physsolver = solvers.PhysicalSolver( arm_config.main_length, arm_config.linkage_length, arm_config.lower_actuator_length, arm_config.upper_actuator_length) # Servos self.servos = {} self.servos["swing"] = servo_swing self.servos["shoulder"] = servo_shoulder self.servos["elbow"] = servo_elbow self.servos["wrist_x"] = servo_wrist_x self.servos["wrist_y"] = servo_wrist_y for key, servo in self.servos.iteritems(): if servo is None: print ("Warning: {0} servo not connected".format(key)) else: # Initialise a PID controller for the servo if servo.protocol == 1: servo.setGoalSpeed(-MOTORSPEED) servo.data['pid'] = pid.PIDControl(2.4, 0, 0.4) else: servo.setGoalSpeed(0) servo.data['error'] = 0.0 # Make sure the goal speed is set servo.setTorqueEnable(1) if servo.protocol == 1: print("Setting slope") servo.setCWMargin(MOTORMARGIN) servo.setCCWMargin(MOTORMARGIN) servo.setCWSlope(MOTORSLOPE) servo.setCCWSlope(MOTORSLOPE) # Store parameters self.motion_enable = True self.enableMovement(False) self.cfg = arm_config # Dirty flags for stored poses self.ik_pose = None self.ik_dirty = True self.real_pose = None self.real_dirty = True # Current target pose self.target_pose = None def pollServos(self): """Poll the real-world servo positions""" for servo in self.servos.itervalues(): if servo is not None: newPos = servo.getPosition() if type(newPos) is float: servo.data['pos'] = newPos def clearPositionError(self): """Clears the servo's position-error accumulators""" for servo in self.servos.itervalues(): if servo is not None and servo.protocol == 1: servo.data['error'] = 0.0 def getRealPose(self): """Retrieve the real-world arm pose, or None if not all servos are connected. """ if any([servo is None for servo in self.servos.itervalues()]): return None # This whole function is essentially just FK based on the known servo # angles swing_servo = self.servos['swing'].data['pos'] elevator_servo = self.servos['shoulder'].data['pos'] actuator_servo = self.servos['elbow'].data['pos'] wrist_x_servo = self.servos['wrist_x'].data['pos'] wrist_y_servo = self.servos['wrist_y'].data['pos'] # Find the internal arm-pose angles for the given servo positions swing_angle = ArmPose.calcSwingAngle(swing_servo) elevator_angle = ArmPose.calcElevatorAngle(elevator_servo) actuator_angle = ArmPose.calcActuatorAngle(actuator_servo) wrist_x_angle = ArmPose.calcWristXAngle(wrist_x_servo) wrist_y_angle = ArmPose.calcWristYAngle(wrist_y_servo) # Solve elbow angle for given actuator and elevator angles # (this is the angle from the elevator arm's direction to the forearm's) elbow_angle = self.physsolver.solve_forearm(elevator_angle, actuator_angle) # FK positions from config and angles offset = self.cfg.shoulder_offset shoulder2D = np.array([offset[1], 0]) elbow2D = shoulder2D + rotate(vertical, elevator_angle)*self.cfg.main_length wrist2D = elbow2D + rotate(vertical, elevator_angle + elbow_angle)*self.cfg.forearm_length effector2D = wrist2D + [self.cfg.wrist_length, 0] # 3D Effector calculation is a little more involved td = rotate([offset[0], effector2D[0]], swing_angle) effector = np.array([td[0], effector2D[1], td[1]]) pose = ArmPose( self.cfg, swing_angle, elevator_angle, actuator_angle, elbow_angle, elbow2D, wrist2D, effector2D, effector, wrist_x_angle, wrist_y_angle) return pose
[ 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2878, 198, 198, 11748, 1540, 690, 198, 11748, 46514, 198, 6738, 7736, 1330, 1635, 198, 198, 44, 2394, 1581, 4303, 41841, 796, 657, 13, ...
2.095374
3,502
from pedalboard import Reverb, Compressor, Gain, LowpassFilter, Pedalboard import soundfile as sf if __name__ == '__main__': # replace by path of unprocessed piano file if necessar fn_wav_source = 'live_grand_piano.wav' # augmentation settings using Pedalboard library settings = {'rev-': [Reverb(room_size=.4)], 'rev+': [Reverb(room_size=.8)], 'comp+': [Compressor(threshold_db=-15, ratio=20)], 'comp-': [Compressor(threshold_db=-10, ratio=10)], 'gain+': [Gain(gain_db=15)], # clipping 'gain-': [Gain(gain_db=5)], 'lpf-': [LowpassFilter(cutoff_frequency_hz=50)], 'lpf+': [LowpassFilter(cutoff_frequency_hz=250)]} # create augmented versions for s in settings.keys(): # load unprocessed piano recording audio, sample_rate = sf.read(fn_wav_source) # create Pedalboard object board = Pedalboard(settings[s]) # create augmented audio effected = board(audio, sample_rate) # save it fn_target = fn_wav_source.replace('.wav', f'_{s}.wav') sf.write(fn_target, effected, sample_rate)
[ 6738, 26667, 3526, 1330, 797, 19011, 11, 3082, 44292, 11, 21686, 11, 7754, 6603, 22417, 11, 13457, 282, 3526, 198, 11748, 2128, 7753, 355, 264, 69, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 628, 220, 220, 220...
2.211111
540
"""add_request_system Revision: 9ba67b798fa Revises: 31b92bf6506d Created: 2013-07-23 02:49:09.342814 """ revision = '9ba67b798fa' down_revision = '31b92bf6506d' from alembic import op from spire.schema.fields import * from spire.mesh import SurrogateType from sqlalchemy import (Column, ForeignKey, ForeignKeyConstraint, PrimaryKeyConstraint, CheckConstraint, UniqueConstraint) from sqlalchemy.dialects import postgresql
[ 37811, 2860, 62, 25927, 62, 10057, 198, 198, 18009, 1166, 25, 860, 7012, 3134, 65, 43240, 13331, 198, 18009, 2696, 25, 3261, 65, 5892, 19881, 17544, 21, 67, 198, 41972, 25, 2211, 12, 2998, 12, 1954, 7816, 25, 2920, 25, 2931, 13, 268...
2.71519
158
# Copyright (C) 2021 Open Source Robotics Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import math from ignition.math import Vector2d from ignition.math import Vector2f if __name__ == '__main__': unittest.main()
[ 2, 15069, 357, 34, 8, 33448, 4946, 8090, 47061, 5693, 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, 1...
3.671569
204
import os import fsspec from fsspec.implementations.memory import MemoryFileSystem import pickle import pytest
[ 11748, 28686, 198, 11748, 277, 824, 43106, 198, 6738, 277, 824, 43106, 13, 320, 26908, 602, 13, 31673, 1330, 14059, 8979, 11964, 198, 11748, 2298, 293, 198, 11748, 12972, 9288, 628, 628, 198 ]
3.484848
33
""" A / | B C 'B, C' """ if __name__ == "__main__": c = CategoryTree() c.add_category('A', None) c.add_category('B', 'A') c.add_category('C', 'A') print(','.join(c.get_children('A') or [])) print(','.join(c.get_children('E') or []))
[ 37811, 198, 220, 220, 317, 198, 1220, 930, 198, 33, 220, 327, 198, 198, 6, 33, 11, 327, 6, 198, 37811, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 269, 796, 21743, 27660, 3419, 198, ...
2.046154
130
# -*- coding: UTF-8 -*- """ .. --------------------------------------------------------------------- ___ __ __ __ ___ / | \ | \ | \ / the automatic \__ |__/ |__/ |___| \__ annotation and \ | | | | \ analysis ___/ | | | | ___/ of speech http://www.sppas.org/ Use of this software is governed by the GNU Public License, version 3. SPPAS is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SPPAS 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 General Public License for more details. You should have received a copy of the GNU General Public License along with SPPAS. If not, see <http://www.gnu.org/licenses/>. This banner notice must not be removed. --------------------------------------------------------------------- anndata.aio ~~~~~~~~~~~ Readers and writers of annotated data. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2018 Brigitte Bigi """ from .annotationpro import sppasANT from .annotationpro import sppasANTX from .anvil import sppasAnvil from .audacity import sppasAudacity from .elan import sppasEAF from .htk import sppasLab from .phonedit import sppasMRK from .phonedit import sppasSignaix from .praat import sppasTextGrid from .praat import sppasIntensityTier from .praat import sppasPitchTier from .sclite import sppasCTM from .sclite import sppasSTM from .subtitle import sppasSubRip from .subtitle import sppasSubViewer from .text import sppasRawText from .text import sppasCSV from .weka import sppasARFF from .weka import sppasXRFF from .xtrans import sppasTDF from .xra import sppasXRA # ---------------------------------------------------------------------------- # Variables # ---------------------------------------------------------------------------- # TODO: get extension from the "default_extension" member of each class ext_sppas = ['.xra', '.[Xx][Rr][Aa]'] ext_praat = ['.TextGrid', '.PitchTier', '.[Tt][eE][xX][tT][Gg][Rr][Ii][dD]','.[Pp][Ii][tT][cC][hH][Tt][Ii][Ee][rR]'] ext_transcriber = ['.trs','.[tT][rR][sS]'] ext_elan = ['.eaf', '[eE][aA][fF]'] ext_ascii = ['.txt', '.csv', '.[cC][sS][vV]', '.[tT][xX][Tt]', '.info'] ext_phonedit = ['.mrk', '.[mM][rR][kK]'] ext_signaix = ['.hz', '.[Hh][zZ]'] ext_sclite = ['.stm', '.ctm', '.[sScC][tT][mM]'] ext_htk = ['.lab', '.mlf'] ext_subtitles = ['.sub', '.srt', '.[sS][uU][bB]', '.[sS][rR][tT]'] ext_anvil = ['.anvil', '.[aA][aN][vV][iI][lL]'] ext_annotationpro = ['.antx', '.[aA][aN][tT][xX]'] ext_xtrans = ['.tdf', '.[tT][dD][fF]'] ext_audacity = ['.aup'] ext_weka = ['.arff', '.xrff'] primary_in = ['.hz', '.PitchTier'] annotations_in = ['.xra', '.TextGrid', '.eaf', '.csv', '.mrk', '.txt', '.stm', '.ctm', '.lab', '.mlf', '.sub', '.srt', '.antx', '.anvil', '.aup', '.trs', '.tdf'] extensions = ['.xra', '.textgrid', '.pitchtier', '.hz', '.eaf', '.trs', '.csv', '.mrk', '.txt', '.mrk', '.stm', '.ctm', '.lab', '.mlf', '.sub', '.srt', 'anvil', '.antx', '.tdf', '.arff', '.xrff'] extensionsul = ext_sppas + ext_praat + ext_transcriber + ext_elan + ext_ascii + ext_phonedit + ext_signaix + ext_sclite + ext_htk + ext_subtitles + ext_anvil + ext_annotationpro + ext_xtrans + ext_audacity + ext_weka extensions_in = primary_in + annotations_in extensions_out = ['.xra', '.TextGrid', '.eaf', '.csv', '.mrk', '.txt', '.stm', '.ctm', '.lab', '.mlf', '.sub', '.srt', '.antx', '.arff', '.xrff'] extensions_out_multitiers = ['.xra', '.TextGrid', '.eaf', '.csv', '.mrk', '.antx', '.arff', '.xrff'] # ---------------------------------------------------------------------------- __all__ = ( "sppasANT", "sppasANTX", "sppasAnvil", "sppasAudacity", "sppasEAF", "sppasLab", "sppasMRK", "sppasSignaix", "sppasTextGrid", "sppasIntensityTier", "sppasPitchTier", "sppasCTM", "sppasSTM", "sppasSubRip", "sppasSubViewer", "sppasRawText", "sppasCSV", "sppasARFF", "sppasXRFF", "sppasTDF", "sppasXRA", "extensions", "extensions_in", "extensions_out" )
[ 2, 532, 9, 12, 19617, 25, 41002, 12, 23, 532, 9, 12, 198, 37811, 198, 220, 220, 220, 11485, 198, 220, 220, 220, 220, 220, 220, 220, 16529, 30934, 198, 220, 220, 220, 220, 220, 220, 220, 220, 46444, 220, 220, 11593, 220, 220, 220...
2.354628
1,988
from .resnet import * from .hynet import * from .classifier import Classifier, HFClassifier, HNSWClassifier from .ext_layers import ParameterClient samplerClassifier = { 'hf': HFClassifier, 'hnsw': HNSWClassifier, }
[ 6738, 764, 411, 3262, 1330, 1635, 198, 6738, 764, 71, 2047, 316, 1330, 1635, 198, 6738, 764, 4871, 7483, 1330, 5016, 7483, 11, 42253, 9487, 7483, 11, 367, 8035, 54, 9487, 7483, 198, 6738, 764, 2302, 62, 75, 6962, 1330, 25139, 2357, ...
2.825
80
import pickle import socket import _thread from scripts.multiplayer import game, board, tetriminos server = "192.168.29.144" port = 5555 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.bind((server, port)) except socket.error as e: print(e) s.listen() print("Waiting for connection") connected = set() games = {} idCount = 0 while True: conn, addr = s.accept() print("Connected to: ", addr) idCount += 1 p = 0 game_id = (idCount - 1) // 2 if idCount % 2 == 1: games[game_id] = game.Game((0, 0, 0), None, board) else: games[game_id].ready = True p = 1 _thread.start_new_thread(threaded_client, (conn, p, game_id))
[ 11748, 2298, 293, 198, 11748, 17802, 198, 11748, 4808, 16663, 198, 6738, 14750, 13, 41684, 7829, 1330, 983, 11, 3096, 11, 28408, 3036, 11996, 198, 198, 15388, 796, 366, 17477, 13, 14656, 13, 1959, 13, 18444, 1, 198, 634, 796, 642, 310...
2.400685
292
import os import re from collections import defaultdict CURRENT_DIR, _ = os.path.split(__file__) DATA_FLIE = os.path.join(CURRENT_DIR, 'data.txt') def part1(claims): """ This is basically a single-threaded collision detection method, implemented in pure python. Computation complexity is obviously not a consideration. """ # Determines how many times each locations was claimed claimed_space_registry = defaultdict(int) for claim in claims: for location in claim.all_locations(): claimed_space_registry[location] += 1 # Generates the set of all locations that were claimed more than once multi_claimed_spaces = { location for location,count in claimed_space_registry.items() if count > 1 } # Prints the number of locations that are claimed more than once # and returns the set of locations that were claimed more than once print('Multi-Claimed Spaces:', len(multi_claimed_spaces)) return multi_claimed_spaces def part2(claims, multi_claimed_spaces): """ Might not be the optimal solution, but it runs fast enough, and uses components that were already calculated in part 1. """ for claim in claims: all_locations_are_non_overlapping = all(map( lambda loc: loc not in multi_claimed_spaces, claim.all_locations() )) if all_locations_are_non_overlapping: print('Non-overlapping claim:', claim.id) return claim if __name__ == '__main__': claims = list(data_file_iter(DATA_FLIE)) mcs = part1(claims) santas_suit_material = part2(claims, mcs)
[ 11748, 28686, 198, 11748, 302, 198, 6738, 17268, 1330, 4277, 11600, 198, 198, 34, 39237, 62, 34720, 11, 4808, 796, 28686, 13, 6978, 13, 35312, 7, 834, 7753, 834, 8, 198, 26947, 62, 3697, 10008, 796, 28686, 13, 6978, 13, 22179, 7, 34...
2.682258
620
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) Philipp Wagner. All rights reserved. # Licensed under the BSD license. See LICENSE file in the project root for full license information. import numpy as np
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 15069, 357, 66, 8, 9844, 26451, 13, 1439, 2489, 10395, 13, 198, 2, 49962, 739, 262, 347, 10305, 5964, 13, 4...
3.348485
66
#!/usr/bin/python #coding=utf-8 import os import requests import time import re from datetime import datetime import urllib2 import json import mimetypes import smtplib from email.MIMEText import MIMEText from email.MIMEMultipart import MIMEMultipart # configuration for pgyer USER_KEY = "f605b7c7826690f796078e3dd23a60d5" API_KEY = "8bdd05df986d598f01456914e51fc889" PGYER_UPLOAD_URL = "https://www.pgyer.com/apiv1/app/upload" repo_path = 'C:/Users/Administrator/.jenkins/workspace/Demo/app' repo_url = 'https://github.com/r17171709/iite_test' ipa_path = "C:/Users/Administrator/.jenkins/workspace/Demo/app/build/outputs/apk/app-release.apk" update_description = "" # git # if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 201, 198, 2, 66, 7656, 28, 40477, 12, 23, 201, 198, 201, 198, 11748, 28686, 201, 198, 11748, 7007, 201, 198, 11748, 640, 201, 198, 11748, 302, 201, 198, 6738, 4818, 8079, 1330, 4818, 8079, 201, ...
2.297546
326
#!_PYTHONLOC # # (C) COPYRIGHT 2004-2021 Al von Ruff and Ahasuerus # ALL RIGHTS RESERVED # # The copyright notice above does not evidence any actual or # intended publication of such source code. # # Version: $Revision$ # Date: $Date$ from isfdblib import * from isfdblib_help import * from isfdblib_print import * from isfdb import * from SQLparsing import * from login import User if __name__ == '__main__': publisherID = SESSION.Parameter(0, 'int') record = SQLGetPublisher(publisherID) if not record: SESSION.DisplayError('Record Does Not Exist') PrintPreSearch('Publisher Editor') PrintNavBar('edit/editpublisher.cgi', publisherID) help = HelpPublisher() printHelpBox('publisher', 'EditPublisher') print '<form id="data" METHOD="POST" ACTION="/cgi-bin/edit/submitpublisher.cgi">' print '<table border="0">' print '<tbody id="tagBody">' # Limit the ability to edit publisher names to moderators user = User() user.load() display_only = 1 if SQLisUserModerator(user.id): display_only = 0 printfield("Publisher Name", "publisher_name", help, record[PUBLISHER_NAME], display_only) trans_publisher_names = SQLloadTransPublisherNames(record[PUBLISHER_ID]) printmultiple(trans_publisher_names, "Transliterated Name", "trans_publisher_names", help) webpages = SQLloadPublisherWebpages(record[PUBLISHER_ID]) printWebPages(webpages, 'publisher', help) printtextarea('Note', 'publisher_note', help, SQLgetNotes(record[PUBLISHER_NOTE])) printtextarea('Note to Moderator', 'mod_note', help, '') print '</tbody>' print '</table>' print '<p>' print '<input NAME="publisher_id" VALUE="%d" TYPE="HIDDEN">' % publisherID print '<input TYPE="SUBMIT" VALUE="Submit Data" tabindex="1">' print '</form>' print '<p>' PrintPostSearch(0, 0, 0, 0, 0, 0)
[ 2, 0, 62, 47, 56, 4221, 1340, 29701, 198, 2, 198, 2, 220, 220, 220, 220, 357, 34, 8, 27975, 38162, 9947, 5472, 12, 1238, 2481, 220, 220, 978, 18042, 42409, 290, 7900, 292, 15573, 385, 198, 2, 220, 220, 220, 220, 220, 220, 220, ...
2.547837
763
from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.orm import Session from dispatch.database.core import get_db from dispatch.database.service import common_parameters, search_filter_sort_paginate from dispatch.auth.permissions import SensitiveProjectActionPermission, PermissionsDependency from .models import ( IncidentCostCreate, IncidentCostPagination, IncidentCostRead, IncidentCostUpdate, ) from .service import create, delete, get, update router = APIRouter()
[ 6738, 3049, 15042, 1330, 3486, 4663, 39605, 11, 2129, 2412, 11, 14626, 16922, 198, 6738, 44161, 282, 26599, 13, 579, 1330, 23575, 198, 198, 6738, 27965, 13, 48806, 13, 7295, 1330, 651, 62, 9945, 198, 6738, 27965, 13, 48806, 13, 15271, ...
3.548611
144
import os from urllib.parse import urlparse, parse_qs from builtins import str from tests import PMGLiveServerTestCase from pmg.models import db, Committee, CommitteeQuestion from tests.fixtures import dbfixture, UserData, CommitteeData, MembershipData from flask import escape from io import BytesIO
[ 11748, 28686, 198, 6738, 2956, 297, 571, 13, 29572, 1330, 19016, 29572, 11, 21136, 62, 48382, 198, 6738, 3170, 1040, 1330, 965, 198, 6738, 5254, 1330, 3122, 8763, 425, 10697, 14402, 20448, 198, 6738, 9114, 70, 13, 27530, 1330, 20613, 11...
3.922078
77
import sys, wave import AudioAnalysis FILE_NAME = "snippet.wav" if __name__ == "__main__": main() #testAudioAnalysis() #testWavWrite()
[ 198, 198, 11748, 25064, 11, 6769, 198, 11748, 13491, 32750, 198, 198, 25664, 62, 20608, 796, 366, 16184, 3974, 316, 13, 45137, 1, 198, 220, 220, 220, 220, 628, 628, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, ...
2.295775
71
from syloga.core.map_expression_args import map_expression_args from syloga.utils.identity import identity from syloga.ast.BooleanNot import BooleanNot from syloga.ast.BooleanValue import BooleanValue from syloga.ast.BooleanOr import BooleanOr from syloga.ast.BooleanAnd import BooleanAnd from syloga.ast.BooleanNand import BooleanNand from syloga.ast.BooleanNor import BooleanNor from syloga.ast.BooleanXor import BooleanXor from syloga.ast.BreakOut import BreakOut # from syloga.core.assert_equality_by_table import assert_equality_by_table
[ 198, 6738, 827, 6404, 64, 13, 7295, 13, 8899, 62, 38011, 62, 22046, 1330, 3975, 62, 38011, 62, 22046, 198, 6738, 827, 6404, 64, 13, 26791, 13, 738, 414, 1330, 5369, 198, 198, 6738, 827, 6404, 64, 13, 459, 13, 46120, 13087, 3673, 1...
3.16185
173
from django.conf import settings from django.contrib.auth import authenticate, login as auth_login from django.contrib.sites.models import get_current_site from django.db.models import get_model from oscar.apps.customer.signals import user_registered from oscar.core.loading import get_class from oscar.core.compat import get_user_model User = get_user_model() CommunicationEventType = get_model('customer', 'CommunicationEventType') Dispatcher = get_class('customer.utils', 'Dispatcher')
[ 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 1330, 8323, 5344, 11, 17594, 355, 6284, 62, 38235, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 49315, 13, 27530, 1330, 651, 62, 14421, 62, 1...
3.346939
147
from parameters import * from library_time import * from paths import * import numpy as np import pylab as plt import matplotlib.pyplot as mplt mplt.rc('text', usetex=True) mplt.rcParams.update({'font.size': 16}) import logging, getopt, sys import time import os ########################################################################################## # C O N F I G U R A T I O N ########################################################################################## # activate ylim for w var1 = w1 var3 = w3 var5 = w5 var10 = w10 var25 = w25 mode = "w" # u or w ########################################################################################## # M A I N ########################################################################################## if __name__ == "__main__": if not os.path.exists('plots'): os.makedirs('plots') print('Created folder plots!') if not os.path.exists('plots/integral'): os.makedirs('plots/integral') print('Created folder plots/integral!') t = np.linspace(tmin, tmax, Nt) r = np.linspace(0,R,Nr) Ivar1 = np.zeros(Nt) Ivar3 = np.zeros(Nt) Ivar5 = np.zeros(Nt) Ivar10 = np.zeros(Nt) Ivar25 = np.zeros(Nt) for i in range(Nt): # /1000000 because of units Ivar1[i] = integrate(var1, i,r, Nt)/1000000 Ivar3[i] = integrate(var3, i,r, Nt)/1000000 Ivar5[i] = integrate(var5, i,r, Nt)/1000000 Ivar10[i] = integrate(var10, i,r, Nt)/1000000 Ivar25[i] = integrate(var25, i,r, Nt)/1000000 mplt.plot(t, Ivar1, label=r'$\alpha = 1$') mplt.plot(t, Ivar3, label=r'$\alpha = 3$') mplt.plot(t, Ivar5, label=r'$\alpha = 5$') mplt.plot(t, Ivar10, label=r'$\alpha = 10$') mplt.plot(t, Ivar25, label=r'$\alpha = 25$') mplt.xlim(tmin, tmax) mplt.yscale('log') mplt.xlabel(r'$t\quad [h]$') mplt.ylabel(r'$\bar{'+mode+'}\quad [\mu mol]$') ########################################################################################## # lim for w, because some values dont make sense mplt.ylim(1e-11, 3e2) # lim for w, because some values dont make sense ########################################################################################## mplt.legend(loc=1, bbox_to_anchor=(1, 0.9)) mplt.tight_layout() mplt.savefig('plots/integral/int'+mode+'.pdf', format='pdf') mplt.show()
[ 6738, 10007, 1330, 1635, 198, 6738, 5888, 62, 2435, 1330, 1635, 198, 6738, 13532, 1330, 1635, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 279, 2645, 397, 355, 458, 83, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 285, ...
2.442987
991
from helper import *
[ 6738, 31904, 1330, 1635, 198 ]
4.2
5
import sys, os sys.path.append("C:/Users/Delgado/Documents/Research/rheology-data-toolkit/rheodata/extractors") import h5py import pandas as pd from antonpaar import AntonPaarExtractor as APE from ARES_G2 import ARES_G2Extractor # %% sys.path.append("C:/Users/Delgado/Documents/Research/rheology-data-toolkit/rheodata") from data_converter import rheo_data_transformer import unittest extractor = APE() #converter = data_converter() if __name__ == '__main__': unittest.main()
[ 11748, 25064, 11, 28686, 198, 17597, 13, 6978, 13, 33295, 7203, 34, 14079, 14490, 14, 13856, 50054, 14, 38354, 14, 25104, 14, 81, 258, 1435, 12, 7890, 12, 25981, 15813, 14, 81, 258, 375, 1045, 14, 2302, 974, 669, 4943, 198, 198, 117...
2.606383
188
from ...models.models import Topic from ..default_schema import DefaultSchema from ..generics import DeleteAction from ..register import register_action
[ 6738, 2644, 27530, 13, 27530, 1330, 47373, 198, 6738, 11485, 12286, 62, 15952, 2611, 1330, 15161, 27054, 2611, 198, 6738, 11485, 8612, 873, 1330, 23520, 12502, 198, 6738, 11485, 30238, 1330, 7881, 62, 2673, 628 ]
4.4
35
from core import file_handling as file_h, driver_handling as driver_h from website_handling import website_check as wc from cookie_handling import cookie_compare websites = file_h.website_reader() driver = driver_h.webdriver_setup() try: wc.load_with_addon(driver, websites) except: print('ERROR: IN FIREFOX USAGE WITH ADDONS') finally: wc.close_driver_session(driver) # driver need to be reloaded because we need a new session without addons driver = driver_h.webdriver_setup() try: wc.load_without_addon(driver, websites) except: print('ERROR: IN VANILLA FIREFOX VERSION') finally: wc.close_driver_session(driver) cookie_compare.compare(websites)
[ 6738, 4755, 1330, 2393, 62, 4993, 1359, 355, 2393, 62, 71, 11, 4639, 62, 4993, 1359, 355, 4639, 62, 71, 198, 6738, 3052, 62, 4993, 1359, 1330, 3052, 62, 9122, 355, 266, 66, 198, 6738, 19751, 62, 4993, 1359, 1330, 19751, 62, 5589, ...
2.858333
240
import numpy as np from scipy import constants as sc from scipy.interpolate import interp1d from pathlib import Path from scipy.special import erf as Erf import pandas as pd import sys import os import csv
[ 11748, 299, 32152, 355, 45941, 198, 6738, 629, 541, 88, 1330, 38491, 355, 629, 198, 6738, 629, 541, 88, 13, 3849, 16104, 378, 1330, 987, 79, 16, 67, 198, 6738, 3108, 8019, 1330, 10644, 198, 6738, 629, 541, 88, 13, 20887, 1330, 1931,...
3.151515
66
from django.conf.urls.defaults import url, include, patterns from corehq.apps.appstore.dispatcher import AppstoreDispatcher store_urls = patterns('corehq.apps.appstore.views', url(r'^$', 'appstore_default', name="appstore_interfaces_default"), AppstoreDispatcher.url_pattern(), ) urlpatterns = patterns('corehq.apps.appstore.views', url(r'^$', 'appstore', name='appstore'), url(r'^api/', 'appstore_api', name='appstore_api'), url(r'^store/', include(store_urls)), url(r'^(?P<domain>[\w\.-]+)/info/$', 'project_info', name='project_info'), url(r'^deployments/$', 'deployments', name='deployments'), url(r'^deployments/api/$', 'deployments_api', name='deployments_api'), url(r'^deployments/(?P<domain>[\w\.-]+)/info/$', 'deployment_info', name='deployment_info'), url(r'^(?P<domain>[\w\.-]+)/approve/$', 'approve_app', name='approve_appstore_app'), url(r'^(?P<domain>[\w\.-]+)/copy/$', 'copy_snapshot', name='domain_copy_snapshot'), url(r'^(?P<domain>[\w\.-]+)/importapp/$', 'import_app', name='import_app_from_snapshot'), url(r'^(?P<domain>[\w\.-]+)/image/$', 'project_image', name='appstore_project_image'), url(r'^(?P<domain>[\w\.-]+)/multimedia/$', 'media_files', name='media_files'), )
[ 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 13, 12286, 82, 1330, 19016, 11, 2291, 11, 7572, 198, 6738, 4755, 71, 80, 13, 18211, 13, 1324, 8095, 13, 6381, 8071, 2044, 1330, 2034, 8095, 7279, 8071, 2044, 198, 198, 8095, 62, 6371, 82,...
2.433852
514
from __future__ import absolute_import import torch from torch.nn import functional def normal_init(m, mean, stddev, truncated=False): """ weight initalizer: truncated normal and random normal. """ # x is a parameter if truncated: m.weight.data.normal_().fmod_(2).mul_(stddev).add_(mean) # not a perfect approximation else: m.weight.data.normal_(mean, stddev) m.bias.data.zero_()
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 11748, 28034, 198, 6738, 28034, 13, 20471, 1330, 10345, 198, 198, 4299, 3487, 62, 15003, 7, 76, 11, 1612, 11, 336, 1860, 1990, 11, 40122, 515, 28, 25101, 2599, 198, 220, 220, 220, ...
2.584337
166
import unittest from biicode.common.settings.version import Version from mock import patch from biicode.client.setups.finders.finders import gnu_version from biicode.client.setups.rpi_cross_compiler import find_gnu_arm from biicode.client.workspace.bii_paths import get_biicode_env_folder_path GCC_VERSION_MAC = '''Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1 Apple LLVM version 5.1 (clang-503.0.38) (based on LLVM 3.4svn) Target: x86_64-apple-darwin13.1.0 Thread model: posix''' GCC_VERSION_UBUNTU = '''gcc (Ubuntu/Linaro 4.8.1-10ubuntu9) 4.8.1 Copyright (C) 2013 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ''' GCC_VERSION_WIN = '''gcc (GCC) 4.8.1 Copyright (C) 2013 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.'''
[ 11748, 555, 715, 395, 198, 6738, 3182, 291, 1098, 13, 11321, 13, 33692, 13, 9641, 1330, 10628, 198, 6738, 15290, 1330, 8529, 198, 6738, 3182, 291, 1098, 13, 16366, 13, 2617, 4739, 13, 19796, 364, 13, 19796, 364, 1330, 19967, 84, 62, ...
2.886792
371
from distutils.core import setup setup( name="arweave-python-client", packages = ['arweave'], # this must be the same as the name above version="1.0.15.dev0", description="Client interface for sending transactions on the Arweave permaweb", author="Mike Hibbert", author_email="mike@hibbertitsolutions.co.uk", url="https://github.com/MikeHibbert/arweave-python-client", download_url="https://github.com/MikeHibbert/arweave-python-client", keywords=['arweave', 'crypto'], classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], install_requires=[ 'arrow', 'python-jose', 'pynacl', 'pycryptodome', 'cryptography', 'requests', 'psutil' ], )
[ 6738, 1233, 26791, 13, 7295, 1330, 9058, 198, 198, 40406, 7, 198, 220, 1438, 2625, 283, 732, 1015, 12, 29412, 12, 16366, 1600, 198, 220, 10392, 796, 37250, 283, 732, 1015, 6, 4357, 1303, 428, 1276, 307, 262, 976, 355, 262, 1438, 202...
2.780142
282
""" Last update: 2018-10-26 """ from exchange_calendars.extensions.calendar_extension import ExtendedExchangeCalendar from pandas import ( Timestamp, ) from pandas.tseries.holiday import ( Holiday, previous_friday, ) from exchange_calendars.exchange_calendar import HolidayCalendar from datetime import time from itertools import chain from pytz import timezone KRNewYearsDay = Holiday( 'New Years Day', month=1, day=1) KRIndependenceDay = Holiday( 'Independence Day', month=3, day=1 ) KRArbourDay = Holiday( 'Arbour Day', month=4, day=5, end_date=Timestamp('2006-01-01'), ) KRLabourDay = Holiday( 'Labour Day', month=5, day=1 ) KRChildrensDay = Holiday( 'Labour Day', month=5, day=5 ) # KRMemorialDay = Holiday( 'Memorial Day', month=6, day=6 ) # KRConstitutionDay = Holiday( 'Constitution Day', month=7, day=17, end_date=Timestamp('2008-01-01') ) # KRLiberationDay = Holiday( 'Liberation Day', month=8, day=15 ) # KRNationalFoundationDay = Holiday( 'NationalFoundationDay', month=10, day=3 ) Christmas = Holiday( 'Christmas', month=12, day=25 ) # KRHangulProclamationDay = Holiday( 'Hangul Proclamation Day', month=10, day=9, start_date=Timestamp('2013-01-01') ) # KRX KRXEndOfYearClosing = Holiday( 'KRX Year-end Closing', month=12, day=31, observance=previous_friday, start_date=Timestamp('2001-01-01') ) KRXEndOfYearClosing2000 = [ Timestamp('2000-12-27', tz='UTC'), Timestamp('2000-12-28', tz='UTC'), Timestamp('2000-12-29', tz='UTC'), Timestamp('2000-12-30', tz='UTC'), ] # Lunar New Year KRLunarNewYear = [ # 2000 Timestamp('2000-02-04', tz='UTC'), # 2001 Timestamp('2001-01-23', tz='UTC'), Timestamp('2001-01-24', tz='UTC'), Timestamp('2001-01-25', tz='UTC'), # 2002 Timestamp('2002-02-11', tz='UTC'), Timestamp('2002-02-12', tz='UTC'), Timestamp('2002-02-13', tz='UTC'), # 2003 Timestamp('2003-01-31', tz='UTC'), # 2004 Timestamp('2004-01-21', tz='UTC'), Timestamp('2004-01-22', tz='UTC'), Timestamp('2004-01-23', tz='UTC'), # 2005 Timestamp('2005-02-08', tz='UTC'), Timestamp('2005-02-09', tz='UTC'), Timestamp('2005-02-10', tz='UTC'), # 2006 Timestamp('2006-01-28', tz='UTC'), Timestamp('2006-01-29', tz='UTC'), Timestamp('2006-01-30', tz='UTC'), # 2007 Timestamp('2007-02-19', tz='UTC'), # 2008 Timestamp('2008-02-06', tz='UTC'), Timestamp('2008-02-07', tz='UTC'), Timestamp('2008-02-08', tz='UTC'), # 2009 Timestamp('2009-01-25', tz='UTC'), Timestamp('2009-01-26', tz='UTC'), Timestamp('2009-01-27', tz='UTC'), # 2010 Timestamp('2010-02-13', tz='UTC'), Timestamp('2010-02-14', tz='UTC'), Timestamp('2010-02-15', tz='UTC'), # 2011 Timestamp('2011-02-02', tz='UTC'), Timestamp('2011-02-03', tz='UTC'), Timestamp('2011-02-04', tz='UTC'), # 2012 Timestamp('2012-01-23', tz='UTC'), Timestamp('2012-01-24', tz='UTC'), # 2013 Timestamp('2013-02-11', tz='UTC'), # 2014 Timestamp('2014-01-30', tz='UTC'), Timestamp('2014-01-31', tz='UTC'), # 2015 Timestamp('2015-02-18', tz='UTC'), Timestamp('2015-02-19', tz='UTC'), Timestamp('2015-02-20', tz='UTC'), # 2016 Timestamp('2016-02-07', tz='UTC'), Timestamp('2016-02-08', tz='UTC'), Timestamp('2016-02-09', tz='UTC'), Timestamp('2016-02-10', tz='UTC'), # 2017 Timestamp('2017-01-27', tz='UTC'), Timestamp('2017-01-28', tz='UTC'), Timestamp('2017-01-29', tz='UTC'), Timestamp('2017-01-30', tz='UTC'), # 2018 Timestamp('2018-02-15', tz='UTC'), Timestamp('2018-02-16', tz='UTC'), Timestamp('2018-02-17', tz='UTC'), # 2019 Timestamp('2019-02-04', tz='UTC'), Timestamp('2019-02-05', tz='UTC'), Timestamp('2019-02-06', tz='UTC'), # 2020 Timestamp('2020-01-24', tz='UTC'), Timestamp('2020-01-25', tz='UTC'), Timestamp('2020-01-26', tz='UTC'), Timestamp('2020-01-27', tz='UTC'), # 2021 Timestamp('2021-02-11', tz='UTC'), Timestamp('2021-02-12', tz='UTC'), # 2022 Timestamp('2022-01-31', tz='UTC'), Timestamp('2022-02-01', tz='UTC'), Timestamp('2022-02-02', tz='UTC'), ] # Election Days KRElectionDays = [ Timestamp('2000-04-13', tz='UTC'), # National Assembly Timestamp('2002-06-13', tz='UTC'), # Regional election Timestamp('2002-12-19', tz='UTC'), # Presidency Timestamp('2004-04-15', tz='UTC'), # National Assembly Timestamp('2006-05-31', tz='UTC'), # Regional election Timestamp('2007-12-19', tz='UTC'), # Presidency Timestamp('2008-04-09', tz='UTC'), # National Assembly Timestamp('2010-06-02', tz='UTC'), # Local election Timestamp('2012-04-11', tz='UTC'), # National Assembly Timestamp('2012-12-19', tz='UTC'), # Presidency Timestamp('2014-06-04', tz='UTC'), # Local election Timestamp('2016-04-13', tz='UTC'), # National Assembly Timestamp('2017-05-09', tz='UTC'), # Presidency Timestamp('2018-06-13', tz='UTC'), # Local election Timestamp('2020-04-15', tz='UTC'), # National Assembly Timestamp('2022-03-09', tz='UTC'), # Presidency Timestamp('2022-06-01', tz='UTC'), # Local election ] # Buddha's birthday KRBuddhasBirthday = [ Timestamp('2000-05-11', tz='UTC'), Timestamp('2001-05-01', tz='UTC'), Timestamp('2003-05-08', tz='UTC'), Timestamp('2004-05-26', tz='UTC'), Timestamp('2005-05-15', tz='UTC'), Timestamp('2006-05-05', tz='UTC'), Timestamp('2007-05-24', tz='UTC'), Timestamp('2008-05-12', tz='UTC'), Timestamp('2009-05-02', tz='UTC'), Timestamp('2010-05-21', tz='UTC'), Timestamp('2011-05-10', tz='UTC'), Timestamp('2012-05-28', tz='UTC'), Timestamp('2013-05-17', tz='UTC'), Timestamp('2014-05-06', tz='UTC'), Timestamp('2015-05-25', tz='UTC'), Timestamp('2016-05-14', tz='UTC'), Timestamp('2017-05-03', tz='UTC'), Timestamp('2018-05-22', tz='UTC'), Timestamp('2020-04-30', tz='UTC'), Timestamp('2021-05-19', tz='UTC'), ] # Harvest Moon Day KRHarvestMoonDay = [ # 2000 Timestamp('2000-09-11', tz='UTC'), Timestamp('2000-09-12', tz='UTC'), Timestamp('2000-09-13', tz='UTC'), # 2001 Timestamp('2001-10-01', tz='UTC'), Timestamp('2001-10-02', tz='UTC'), # 2002 Timestamp('2002-09-20', tz='UTC'), # 2003 Timestamp('2003-09-10', tz='UTC'), Timestamp('2003-09-11', tz='UTC'), Timestamp('2003-09-12', tz='UTC'), # 2004 Timestamp('2004-09-27', tz='UTC'), Timestamp('2004-09-28', tz='UTC'), Timestamp('2004-09-29', tz='UTC'), # 2005 Timestamp('2005-09-17', tz='UTC'), Timestamp('2005-09-18', tz='UTC'), Timestamp('2005-09-19', tz='UTC'), # 2006 Timestamp('2006-10-05', tz='UTC'), Timestamp('2006-10-06', tz='UTC'), Timestamp('2006-10-07', tz='UTC'), # 2007 Timestamp('2007-09-24', tz='UTC'), Timestamp('2007-09-25', tz='UTC'), Timestamp('2007-09-26', tz='UTC'), # 2008 Timestamp('2008-09-13', tz='UTC'), Timestamp('2008-09-14', tz='UTC'), Timestamp('2008-09-15', tz='UTC'), # 2009 Timestamp('2009-10-02', tz='UTC'), Timestamp('2009-10-03', tz='UTC'), Timestamp('2009-10-04', tz='UTC'), # 2010 Timestamp('2010-09-21', tz='UTC'), Timestamp('2010-09-22', tz='UTC'), Timestamp('2010-09-23', tz='UTC'), # 2011 Timestamp('2011-09-12', tz='UTC'), Timestamp('2011-09-13', tz='UTC'), # 2012 Timestamp('2012-10-01', tz='UTC'), # 2013 Timestamp('2013-09-18', tz='UTC'), Timestamp('2013-09-19', tz='UTC'), Timestamp('2013-09-20', tz='UTC'), # 2014 Timestamp('2014-09-08', tz='UTC'), Timestamp('2014-09-09', tz='UTC'), Timestamp('2014-09-10', tz='UTC'), # 2015 Timestamp('2015-09-28', tz='UTC'), Timestamp('2015-09-29', tz='UTC'), # 2016 Timestamp('2016-09-14', tz='UTC'), Timestamp('2016-09-15', tz='UTC'), Timestamp('2016-09-16', tz='UTC'), # 2017 Timestamp('2017-10-03', tz='UTC'), Timestamp('2017-10-04', tz='UTC'), Timestamp('2017-10-05', tz='UTC'), Timestamp('2017-10-06', tz='UTC'), # 2018 Timestamp('2018-09-23', tz='UTC'), Timestamp('2018-09-24', tz='UTC'), Timestamp('2018-09-25', tz='UTC'), Timestamp('2018-09-26', tz='UTC'), # 2019 Timestamp('2019-09-12', tz='UTC'), Timestamp('2019-09-13', tz='UTC'), # 2020 Timestamp('2020-09-30', tz='UTC'), Timestamp('2020-10-01', tz='UTC'), Timestamp('2020-10-02', tz='UTC'), # 2021 Timestamp('2021-09-20', tz='UTC'), Timestamp('2021-09-21', tz='UTC'), Timestamp('2021-09-22', tz='UTC'), # 2022 Timestamp('2022-09-09', tz='UTC'), Timestamp('2022-09-12', tz='UTC'), # ] # KRSubstitutionHolidayForChildrensDay2018 = [ Timestamp('2018-05-07', tz='UTC') ] # KRCelebrationForWorldCupHosting = [ Timestamp('2002-07-01', tz='UTC') ] KRSeventyYearsFromIndependenceDay = [ Timestamp('2015-08-14', tz='UTC') ] KRTemporaryHolidayForChildrensDay2016 = [ Timestamp('2016-05-06', tz='UTC') ] KRTemporaryHolidayForHarvestMoonDay2017 = [ Timestamp('2017-10-02', tz='UTC') ] KRTemporaryHolidayForChildrenDay2018 = [ Timestamp('2018-05-07', tz='UTC') ] KRTemporaryHolidayForChildrenDay2019 = [ Timestamp('2019-05-06', tz='UTC') ] KRTemporaryHolidayForLiberationDay2020 = [ Timestamp('2020-08-17', tz='UTC') ] KRTemporaryHoliday2021 = [ Timestamp('2021-08-16', tz='UTC'), # Timestamp('2021-10-04', tz='UTC'), # Timestamp('2021-10-11', tz='UTC'), # ] KRTemporaryHoliday2022 = [ Timestamp('2022-10-10', tz='UTC'), # ] # HolidaysNeedToCheck = [ Timestamp('2000-01-03', tz='UTC') ] HolidaysBefore1999 = [ Timestamp('1990-01-01', tz='UTC'), Timestamp('1990-01-02', tz='UTC'), Timestamp('1990-01-03', tz='UTC'), Timestamp('1990-01-29', tz='UTC'), Timestamp('1990-03-01', tz='UTC'), Timestamp('1990-04-05', tz='UTC'), Timestamp('1990-05-02', tz='UTC'), Timestamp('1990-06-06', tz='UTC'), Timestamp('1990-07-17', tz='UTC'), Timestamp('1990-08-15', tz='UTC'), Timestamp('1990-09-03', tz='UTC'), Timestamp('1990-10-01', tz='UTC'), Timestamp('1990-10-03', tz='UTC'), Timestamp('1990-10-09', tz='UTC'), Timestamp('1990-12-25', tz='UTC'), Timestamp('1991-01-01', tz='UTC'), Timestamp('1991-01-02', tz='UTC'), Timestamp('1991-02-14', tz='UTC'), Timestamp('1991-02-15', tz='UTC'), Timestamp('1991-03-01', tz='UTC'), Timestamp('1991-04-05', tz='UTC'), Timestamp('1991-05-21', tz='UTC'), Timestamp('1991-06-06', tz='UTC'), Timestamp('1991-07-17', tz='UTC'), Timestamp('1991-08-15', tz='UTC'), Timestamp('1991-09-23', tz='UTC'), Timestamp('1991-10-03', tz='UTC'), Timestamp('1991-12-25', tz='UTC'), Timestamp('1991-12-30', tz='UTC'), Timestamp('1992-01-01', tz='UTC'), Timestamp('1992-09-10', tz='UTC'), Timestamp('1992-09-11', tz='UTC'), Timestamp('1992-10-03', tz='UTC'), Timestamp('1992-12-25', tz='UTC'), Timestamp('1992-12-29', tz='UTC'), Timestamp('1992-12-30', tz='UTC'), Timestamp('1992-12-31', tz='UTC'), Timestamp('1993-01-01', tz='UTC'), Timestamp('1993-01-22', tz='UTC'), Timestamp('1993-03-01', tz='UTC'), Timestamp('1993-04-05', tz='UTC'), Timestamp('1993-05-05', tz='UTC'), Timestamp('1993-05-28', tz='UTC'), Timestamp('1993-07-17', tz='UTC'), Timestamp('1993-09-29', tz='UTC'), Timestamp('1993-09-30', tz='UTC'), Timestamp('1993-10-01', tz='UTC'), Timestamp('1993-12-29', tz='UTC'), Timestamp('1993-12-30', tz='UTC'), Timestamp('1993-12-31', tz='UTC'), Timestamp('1994-01-02', tz='UTC'), Timestamp('1994-02-09', tz='UTC'), Timestamp('1994-02-10', tz='UTC'), Timestamp('1994-02-11', tz='UTC'), Timestamp('1994-03-01', tz='UTC'), Timestamp('1994-04-05', tz='UTC'), Timestamp('1994-05-05', tz='UTC'), Timestamp('1994-06-06', tz='UTC'), Timestamp('1994-07-17', tz='UTC'), Timestamp('1994-08-15', tz='UTC'), Timestamp('1994-09-19', tz='UTC'), Timestamp('1994-09-20', tz='UTC'), Timestamp('1994-09-21', tz='UTC'), Timestamp('1994-10-03', tz='UTC'), Timestamp('1994-12-29', tz='UTC'), Timestamp('1994-12-30', tz='UTC'), Timestamp('1995-01-02', tz='UTC'), Timestamp('1995-01-30', tz='UTC'), Timestamp('1995-01-31', tz='UTC'), Timestamp('1995-02-01', tz='UTC'), Timestamp('1995-03-01', tz='UTC'), Timestamp('1995-05-01', tz='UTC'), Timestamp('1995-05-05', tz='UTC'), Timestamp('1995-06-06', tz='UTC'), Timestamp('1995-06-27', tz='UTC'), Timestamp('1995-07-17', tz='UTC'), Timestamp('1995-08-15', tz='UTC'), Timestamp('1995-09-08', tz='UTC'), Timestamp('1995-09-09', tz='UTC'), Timestamp('1995-10-03', tz='UTC'), Timestamp('1995-12-22', tz='UTC'), Timestamp('1995-12-25', tz='UTC'), Timestamp('1995-12-28', tz='UTC'), Timestamp('1995-12-29', tz='UTC'), Timestamp('1995-12-30', tz='UTC'), Timestamp('1995-12-31', tz='UTC'), Timestamp('1996-01-01', tz='UTC'), Timestamp('1996-01-02', tz='UTC'), Timestamp('1996-02-19', tz='UTC'), Timestamp('1996-02-20', tz='UTC'), Timestamp('1996-03-01', tz='UTC'), Timestamp('1996-04-05', tz='UTC'), Timestamp('1996-04-11', tz='UTC'), Timestamp('1996-05-01', tz='UTC'), Timestamp('1996-05-05', tz='UTC'), Timestamp('1996-05-24', tz='UTC'), Timestamp('1996-06-06', tz='UTC'), Timestamp('1996-07-17', tz='UTC'), Timestamp('1996-08-15', tz='UTC'), Timestamp('1996-09-26', tz='UTC'), Timestamp('1996-09-27', tz='UTC'), Timestamp('1996-09-28', tz='UTC'), Timestamp('1996-10-03', tz='UTC'), Timestamp('1996-12-25', tz='UTC'), Timestamp('1996-12-30', tz='UTC'), Timestamp('1996-12-31', tz='UTC'), Timestamp('1997-01-01', tz='UTC'), Timestamp('1997-01-02', tz='UTC'), Timestamp('1997-02-07', tz='UTC'), Timestamp('1997-02-08', tz='UTC'), Timestamp('1997-03-01', tz='UTC'), Timestamp('1997-04-05', tz='UTC'), Timestamp('1997-05-05', tz='UTC'), Timestamp('1997-05-14', tz='UTC'), Timestamp('1997-06-06', tz='UTC'), Timestamp('1997-07-17', tz='UTC'), Timestamp('1997-08-15', tz='UTC'), Timestamp('1997-09-16', tz='UTC'), Timestamp('1997-09-17', tz='UTC'), Timestamp('1997-10-03', tz='UTC'), Timestamp('1997-12-25', tz='UTC'), Timestamp('1998-01-01', tz='UTC'), Timestamp('1998-01-02', tz='UTC'), Timestamp('1998-01-27', tz='UTC'), Timestamp('1998-01-28', tz='UTC'), Timestamp('1998-01-29', tz='UTC'), Timestamp('1998-03-01', tz='UTC'), Timestamp('1998-04-05', tz='UTC'), Timestamp('1998-05-01', tz='UTC'), Timestamp('1998-05-03', tz='UTC'), Timestamp('1998-05-05', tz='UTC'), Timestamp('1998-06-04', tz='UTC'), Timestamp('1998-06-06', tz='UTC'), Timestamp('1998-07-17', tz='UTC'), Timestamp('1998-08-15', tz='UTC'), Timestamp('1998-10-03', tz='UTC'), Timestamp('1998-10-04', tz='UTC'), Timestamp('1998-10-05', tz='UTC'), Timestamp('1998-10-06', tz='UTC'), Timestamp('1998-12-25', tz='UTC'), Timestamp('1998-12-31', tz='UTC'), Timestamp('1999-01-01', tz='UTC'), Timestamp('1999-02-15', tz='UTC'), Timestamp('1999-02-16', tz='UTC'), Timestamp('1999-02-17', tz='UTC'), Timestamp('1999-03-01', tz='UTC'), Timestamp('1999-04-05', tz='UTC'), Timestamp('1999-05-05', tz='UTC'), Timestamp('1999-05-22', tz='UTC'), Timestamp('1999-06-06', tz='UTC'), Timestamp('1999-07-17', tz='UTC'), Timestamp('1999-09-23', tz='UTC'), Timestamp('1999-09-24', tz='UTC'), Timestamp('1999-09-25', tz='UTC'), Timestamp('1999-10-03', tz='UTC'), Timestamp('1999-12-29', tz='UTC'), Timestamp('1999-12-30', tz='UTC'), Timestamp('1999-12-31', tz='UTC'), ]
[ 37811, 198, 5956, 4296, 25, 2864, 12, 940, 12, 2075, 198, 37811, 198, 198, 6738, 5163, 62, 9948, 44942, 13, 2302, 5736, 13, 9948, 9239, 62, 2302, 3004, 1330, 24204, 3109, 3803, 9771, 9239, 198, 6738, 19798, 292, 1330, 357, 198, 220, ...
2.198798
7,319
import random import numpy #import tensorflow as tf #import torch from abc import abstractmethod from sklearn.decomposition import PCA from aggregators import FedAvg, MultiKrum, AlignedAvg, TrimmedMean, Median, StratifiedAggr # class StratifiedRandomSelection(SelectionStrategy): # #We first stratify: Each stratum will be a list of workers # #Then within each stratum, we randomly select # #We would need the list of workers and the information about their skews def select_aggregator(args, name, KWARGS={}): #Creates an Aggregator object as selected if name == "FedAvg": return FedAvg(args, name, KWARGS) elif name == "AlignedAvg": return AlignedAvg(args, name, KWARGS) elif name == "AlignedAvgImpute": KWARGS.update({"use_impute":"filter","align":"fusion"}) return AlignedAvg(args, name, **KWARGS) elif name == "MultiKrum": return MultiKrum(args, name, KWARGS) elif name == "TrimmedMean": return TrimmedMean(args, name, KWARGS) elif name == "Median": return Median(args, name, KWARGS) elif (name == "StratKrum") or (name == "StratTrimMean") or (name == "StratMedian") or (name == "StratFedAvg"): #We may have to change the class name to StratifiedAggregation return StratifiedAggr(args, name, KWARGS) else: raise NotImplementedError(f"Unrecognized Aggregator Name: {name}") def calculate_pca_of_gradients(logger, gradients, num_components): # Unchanged from original work pca = PCA(n_components=num_components) logger.info("Computing {}-component PCA of gradients".format(num_components)) return pca.fit_transform(gradients) #So this is here after all def calculate_model_gradient( model_1, model_2): # Minor change from original work """ Calculates the gradient (parameter difference) between two Torch models. :param logger: loguru.logger (NOW REMOVED) :param model_1: torch.nn :param model_2: torch.nn """ model_1_parameters = list(dict(model_1.state_dict())) model_2_parameters = list(dict(model_2.state_dict())) return calculate_parameter_gradients(model_1_parameters, model_2_parameters) def calculate_parameter_gradients(params_1, params_2): # Minor change from original work """ Calculates the gradient (parameter difference) between two sets of Torch parameters. :param logger: loguru.logger (NOW REMOVED) :param params_1: dict :param params_2: dict """ #logger.debug("Shape of model_1_parameters: {}".format(str(len(params_1)))) #logger.debug("Shape of model_2_parameters: {}".format(str(len(params_2)))) return numpy.array([x for x in numpy.subtract(params_1, params_2)]) # #Inserted # def convert2TF(torch_tensor): # # Converts a pytorch tensor into a Tensorflow. # # We first convert torch into numpy, then to tensorflow. # # Arg: torch_tensor - a Pytorch tensor object # np_tensor = torch_tensor.numpy().astype(float) # return tf.convert_to_tensor(np_tensor) # # def convert2Torch(tf_tensor): # #Converts a TF tensor to Torch # #Arg: tf_tensor - a TF tensor # np_tensor = tf.make_ndarray(tf_tensor) # return torch.from_numpy(np_tensor) def generate_uniform_weights(random_workers): """ This function generates uniform weights for each stratum in random_workers :param random_workers: :return: """ strata_weights = dict() weight = 1.0 / len(list(random_workers.keys())) for stratum in random_workers: strata_weights[stratum] = weight return strata_weights
[ 11748, 4738, 198, 11748, 299, 32152, 198, 2, 11748, 11192, 273, 11125, 355, 48700, 198, 2, 11748, 28034, 198, 6738, 450, 66, 1330, 12531, 24396, 198, 6738, 1341, 35720, 13, 12501, 296, 9150, 1330, 4217, 32, 198, 6738, 13262, 2024, 1330,...
2.665924
1,347
from sprites import PlayerSprite import time
[ 6738, 42866, 1330, 7853, 38454, 578, 198, 11748, 640 ]
4.888889
9
from typing import Sequence import torch from torch import nn
[ 6738, 19720, 1330, 45835, 198, 198, 11748, 28034, 198, 6738, 28034, 1330, 299, 77, 628 ]
4.266667
15
from gi.repository import Gtk from masterdata_abstract_window import MasterdataAbstractWindow from person_add_mask import PersonAddMask from person_list_mask import PersonListMask
[ 6738, 308, 72, 13, 260, 1930, 37765, 1330, 402, 30488, 198, 198, 6738, 4958, 7890, 62, 397, 8709, 62, 17497, 1330, 5599, 7890, 23839, 27703, 198, 198, 6738, 1048, 62, 2860, 62, 27932, 1330, 7755, 4550, 45195, 198, 6738, 1048, 62, 4868...
2.477778
90
import torch.nn as nn from .efficientnet import EfficientNet_B4, EfficientNet_B0 from .mobilenetv3 import MobileNetV3_Large, MobileNetV3_Small def get_trunk(trunk_name): """Retrieve the pretrained network trunk and channel counts""" if trunk_name == 'efficientnet_b4': backbone = EfficientNet_B4(pretrained=True) s2_ch = 24 s4_ch = 32 high_level_ch = 1792 elif trunk_name == 'efficientnet_b0': backbone = EfficientNet_B0(pretrained=True) s2_ch = 16 s4_ch = 24 high_level_ch = 1280 elif trunk_name == 'mobilenetv3_large': backbone = MobileNetV3_Large(pretrained=True) s2_ch = 16 s4_ch = 24 high_level_ch = 960 elif trunk_name == 'mobilenetv3_small': backbone = MobileNetV3_Small(pretrained=True) s2_ch = 16 s4_ch = 16 high_level_ch = 576 else: raise ValueError('unknown backbone {}'.format(trunk_name)) return backbone, s2_ch, s4_ch, high_level_ch
[ 11748, 28034, 13, 20471, 355, 299, 77, 198, 198, 6738, 764, 16814, 3262, 1330, 412, 5632, 7934, 62, 33, 19, 11, 412, 5632, 7934, 62, 33, 15, 198, 6738, 764, 76, 25898, 268, 316, 85, 18, 1330, 12173, 7934, 53, 18, 62, 21968, 11, ...
2.17382
466
import module from types import ModuleType foo(module) bar(module)
[ 11748, 8265, 198, 6738, 3858, 1330, 19937, 6030, 198, 198, 21943, 7, 21412, 8, 198, 5657, 7, 21412, 8 ]
3.526316
19
from unittest.mock import patch, MagicMock from pdchaosazure.webapp.actions import stop, restart, delete from tests.data import config_provider, secrets_provider, webapp_provider
[ 6738, 555, 715, 395, 13, 76, 735, 1330, 8529, 11, 6139, 44, 735, 198, 198, 6738, 279, 67, 354, 7495, 1031, 495, 13, 12384, 1324, 13, 4658, 1330, 2245, 11, 15765, 11, 12233, 198, 6738, 5254, 13, 7890, 1330, 4566, 62, 15234, 1304, 1...
3.267857
56
""" echopype data model that keeps tracks of echo data and its connection to data files. """ import os import warnings import datetime as dt from echopype.utils import uwa import numpy as np import xarray as xr def calc_seawater_absorption(self, src='file'): """Base method to be overridden for calculating seawater_absorption for different sonar models """ # issue warning when subclass methods not available print("Seawater absorption calculation has not been implemented for this sonar model!") def calc_sample_thickness(self): """Base method to be overridden for calculating sample_thickness for different sonar models. """ # issue warning when subclass methods not available print('Sample thickness calculation has not been implemented for this sonar model!') def calc_range(self): """Base method to be overridden for calculating range for different sonar models. """ # issue warning when subclass methods not available print('Range calculation has not been implemented for this sonar model!') def recalculate_environment(self, ss=True, sa=True, st=True, r=True): """ Recalculates sound speed, seawater absorption, sample thickness, and range using salinity, temperature, and pressure Parameters ---------- ss : bool Whether to calcualte sound speed. Defaults to `True` sa : bool Whether to calcualte seawater absorption. Defaults to `True` st : bool Whether to calcualte sample thickness. Defaults to `True` r : bool Whether to calcualte range. Defaults to `True` """ s, t, p = self.salinity, self.temperature, self.pressure if s is not None and t is not None and p is not None: if ss: self.sound_speed = self.calc_sound_speed(src='user') if sa: self.seawater_absorption = self.calc_seawater_absorption(src='user') if st: self.sample_thickness = self.calc_sample_thickness() if r: self.range = self.calc_range() elif s is None: print("Salinity was not provided. Environment was not recalculated") elif t is None: print("Temperature was not provided. Environment was not recalculated") else: print("Pressure was not provided. Environment was not recalculated") def calibrate(self): """Base method to be overridden for volume backscatter calibration and echo-integration for different sonar models. """ # issue warning when subclass methods not available print('Calibration has not been implemented for this sonar model!') def calibrate_TS(self): """Base method to be overridden for target strength calibration and echo-integration for different sonar models. """ # issue warning when subclass methods not available print('Target strength calibration has not been implemented for this sonar model!') def validate_path(self, save_path, save_postfix): """Creates a directory if it doesnt exist. Returns a valid save path. """ if save_path is None: save_dir = os.path.dirname(self.file_path) file_out = _assemble_path() else: path_ext = os.path.splitext(save_path)[1] # If given save_path is file, split into directory and file if path_ext != '': save_dir, file_out = os.path.split(save_path) if save_dir == '': # save_path is only a filename without directory save_dir = os.path.dirname(self.file_path) # use directory from input file # If given save_path is a directory, get a filename from input .nc file else: save_dir = save_path file_out = _assemble_path() # Create folder if not already exists if save_dir == '': # TODO: should we use '.' instead of os.getcwd()? save_dir = os.getcwd() # explicit about path to current directory if not os.path.exists(save_dir): os.mkdir(save_dir) return os.path.join(save_dir, file_out) def _get_proc_Sv(self, source_path=None, source_postfix='_Sv'): """Private method to return calibrated Sv either from memory or _Sv.nc file. This method is called by remove_noise(), noise_estimates() and get_MVBS(). """ if self.Sv is None: # calibration not yet performed Sv_path = self.validate_path(save_path=source_path, # wrangle _Sv path save_postfix=source_postfix) if os.path.exists(Sv_path): # _Sv exists self.Sv = xr.open_dataset(Sv_path) # load _Sv file else: # if path specification given but file do not exist: if (source_path is not None) or (source_postfix != '_Sv'): print('%s no calibrated data found in specified path: %s' % (dt.datetime.now().strftime('%H:%M:%S'), Sv_path)) else: print('%s data has not been calibrated. ' % dt.datetime.now().strftime('%H:%M:%S')) print(' performing calibration now and operate from Sv in memory.') self.calibrate() # calibrate, have Sv in memory return self.Sv def remove_noise(self, source_postfix='_Sv', source_path=None, noise_est_range_bin_size=None, noise_est_ping_size=None, SNR=0, Sv_threshold=None, save=False, save_postfix='_Sv_clean', save_path=None): """Remove noise by using noise estimates obtained from the minimum mean calibrated power level along each column of tiles. See method noise_estimates() for details of noise estimation. Reference: De Robertis & Higginbottom, 2017, ICES Journal of Marine Sciences Parameters ---------- source_postfix : str postfix of the Sv file used to remove noise from, default to '_Sv' source_path : str path of Sv file used to remove noise from, can be one of the following: - None (default): use Sv in RAWFILENAME_Sv.nc in the same folder as the raw data file, or when RAWFILENAME_Sv.nc doesn't exist, perform self.calibrate() and use the resulted self.Sv - path to a directory: RAWFILENAME_Sv.nc in the specified directory - path to a specific file: the specified file, e.g., ./another_directory/some_other_filename.nc noise_est_range_bin_size : float, optional Meters per tile for noise estimation [m] noise_est_ping_size : int, optional Number of pings per tile for noise estimation SNR : int, optional Minimum signal-to-noise ratio (remove values below this after general noise removal). Sv_threshold : int, optional Minimum Sv threshold [dB] (remove values below this after general noise removal) save : bool, optional Whether to save the denoised Sv (``Sv_clean``) into a new .nc file. Default to ``False``. save_postfix : str Filename postfix, default to '_Sv_clean' save_path : str Full filename to save to, overwriting the RAWFILENAME_Sv_clean.nc default """ # Check params if (noise_est_range_bin_size is not None) and (self.noise_est_range_bin_size != noise_est_range_bin_size): self.noise_est_range_bin_size = noise_est_range_bin_size if (noise_est_ping_size is not None) and (self.noise_est_ping_size != noise_est_ping_size): self.noise_est_ping_size = noise_est_ping_size # Get calibrated Sv if self.Sv is not None: print('%s Remove noise from Sv stored in memory.' % dt.datetime.now().strftime('%H:%M:%S')) print_src = False else: print_src = True proc_data = self._get_proc_Sv(source_path=source_path, source_postfix=source_postfix) if print_src: print('%s Remove noise from Sv stored in: %s' % (dt.datetime.now().strftime('%H:%M:%S'), self.Sv_path)) # Get tile indexing parameters self.noise_est_range_bin_size, range_bin_tile_bin_edge, ping_tile_bin_edge = \ self.get_tile_params(r_data_sz=proc_data.range_bin.size, p_data_sz=proc_data.ping_time.size, r_tile_sz=self.noise_est_range_bin_size, p_tile_sz=self.noise_est_ping_size, sample_thickness=self.sample_thickness) # Get TVG and ABS for compensating for transmission loss range_meter = self.range TVG = np.real(20 * np.log10(range_meter.where(range_meter >= 1, other=1))) ABS = 2 * self.seawater_absorption * range_meter # Function for use with apply # Groupby noise removal operation proc_data.coords['ping_idx'] = ('ping_time', np.arange(proc_data.Sv['ping_time'].size)) ABS.name = 'ABS' TVG.name = 'TVG' pp = xr.merge([proc_data, ABS]) pp = xr.merge([pp, TVG]) # check if number of range_bin per tile the same for all freq channels if np.unique([np.array(x).size for x in range_bin_tile_bin_edge]).size == 1: Sv_clean = pp.groupby_bins('ping_idx', ping_tile_bin_edge).\ map(remove_n, rr=range_bin_tile_bin_edge[0]) Sv_clean = Sv_clean.drop_vars(['ping_idx']) else: tmp_clean = [] cnt = 0 for key, val in pp.groupby('frequency'): # iterate over different frequency channel tmp = val.groupby_bins('ping_idx', ping_tile_bin_edge). \ map(remove_n, rr=range_bin_tile_bin_edge[cnt]) cnt += 1 tmp_clean.append(tmp) clean_val = np.array([zz.values for zz in xr.align(*tmp_clean, join='outer')]) Sv_clean = xr.DataArray(clean_val, coords={'frequency': proc_data['frequency'].values, 'ping_time': tmp_clean[0]['ping_time'].values, 'range_bin': tmp_clean[0]['range_bin'].values}, dims=['frequency', 'ping_time', 'range_bin']) # Set up DataSet Sv_clean.name = 'Sv' Sv_clean = Sv_clean.to_dataset() Sv_clean['noise_est_range_bin_size'] = ('frequency', self.noise_est_range_bin_size) Sv_clean.attrs['noise_est_ping_size'] = self.noise_est_ping_size # Attach calculated range into data set Sv_clean['range'] = (('frequency', 'range_bin'), self.range.T) # Save as object attributes as a netCDF file self.Sv_clean = Sv_clean # TODO: now adding the below so that MVBS can be calculated directly # from the cleaned Sv without saving and loading Sv_clean from disk. # However this is not explicit to the user. A better way to do this # is to change get_MVBS() to first check existence of self.Sv_clean # when `_Sv_clean` is specified as the source_postfix. if not print_src: # remove noise from Sv stored in memory self.Sv = Sv_clean.copy() if save: self.Sv_clean_path = self.validate_path(save_path=save_path, save_postfix=save_postfix) print('%s saving denoised Sv to %s' % (dt.datetime.now().strftime('%H:%M:%S'), self.Sv_clean_path)) Sv_clean.to_netcdf(self.Sv_clean_path) # Close opened resources proc_data.close() def noise_estimates(self, source_postfix='_Sv', source_path=None, noise_est_range_bin_size=None, noise_est_ping_size=None): """Obtain noise estimates from the minimum mean calibrated power level along each column of tiles. The tiles here are defined by class attributes noise_est_range_bin_size and noise_est_ping_size. This method contains redundant pieces of code that also appear in method remove_noise(), but this method can be used separately to determine the exact tile size for noise removal before noise removal is actually performed. Parameters ---------- source_postfix : str postfix of the Sv file used to calculate noise estimates from, default to '_Sv' source_path : str path of Sv file used to calculate noise estimates from, can be one of the following: - None (default): use Sv in RAWFILENAME_Sv.nc in the same folder as the raw data file, or when RAWFILENAME_Sv.nc doesn't exist, perform self.calibrate() and use the resulted self.Sv - path to a directory: RAWFILENAME_Sv.nc in the specified directory - path to a specific file: the specified file, e.g., ./another_directory/some_other_filename.nc noise_est_range_bin_size : float meters per tile for noise estimation [m] noise_est_ping_size : int number of pings per tile for noise estimation Returns ------- noise_est : xarray DataSet noise estimates as a DataArray with dimension [ping_time x range_bin] ping_time and range_bin are taken from the first element of each tile along each of the dimensions """ # Check params if (noise_est_range_bin_size is not None) and (self.noise_est_range_bin_size != noise_est_range_bin_size): self.noise_est_range_bin_size = noise_est_range_bin_size if (noise_est_ping_size is not None) and (self.noise_est_ping_size != noise_est_ping_size): self.noise_est_ping_size = noise_est_ping_size # Use calibrated data to calculate noise removal proc_data = self._get_proc_Sv() # Get tile indexing parameters self.noise_est_range_bin_size, range_bin_tile_bin_edge, ping_tile_bin_edge = \ self.get_tile_params(r_data_sz=proc_data.range_bin.size, p_data_sz=proc_data.ping_time.size, r_tile_sz=self.noise_est_range_bin_size, p_tile_sz=self.noise_est_ping_size, sample_thickness=self.sample_thickness) # Values for noise estimates range_meter = self.range TVG = np.real(20 * np.log10(range_meter.where(range_meter >= 1, other=1))) ABS = 2 * self.seawater_absorption * range_meter # Noise estimates proc_data['power_cal'] = 10 ** ((proc_data.Sv - ABS - TVG) / 10) # check if number of range_bin per tile the same for all freq channels if np.unique([np.array(x).size for x in range_bin_tile_bin_edge]).size == 1: noise_est = 10 * np.log10(proc_data['power_cal'].coarsen( ping_time=self.noise_est_ping_size, range_bin=int(np.unique(self.noise_est_range_bin_size / self.sample_thickness)), boundary='pad').mean().min(dim='range_bin')) else: range_bin_coarsen_idx = (self.noise_est_range_bin_size / self.sample_thickness).astype(int) tmp_noise = [] for r_bin in range_bin_coarsen_idx: freq = r_bin.frequency.values tmp_da = 10 * np.log10(proc_data['power_cal'].sel(frequency=freq).coarsen( ping_time=self.noise_est_ping_size, range_bin=r_bin.values, boundary='pad').mean().min(dim='range_bin')) tmp_da.name = 'noise_est' tmp_noise.append(tmp_da) # Construct a dataArray TODO: this can probably be done smarter using xarray native functions noise_val = np.array([zz.values for zz in xr.align(*tmp_noise, join='outer')]) noise_est = xr.DataArray(noise_val, coords={'frequency': proc_data['frequency'].values, 'ping_time': tmp_noise[0]['ping_time'].values}, dims=['frequency', 'ping_time']) noise_est = noise_est.to_dataset(name='noise_est') noise_est['noise_est_range_bin_size'] = ('frequency', self.noise_est_range_bin_size) noise_est.attrs['noise_est_ping_size'] = self.noise_est_ping_size # Close opened resources proc_data.close() return noise_est def get_MVBS(self, source_postfix='_Sv', source_path=None, MVBS_range_bin_size=None, MVBS_ping_size=None, save=False, save_postfix='_MVBS', save_path=None): """Calculate Mean Volume Backscattering Strength (MVBS). The calculation uses class attributes MVBS_ping_size and MVBS_range_bin_size to calculate and save MVBS as a new attribute to the calling EchoData instance. MVBS is an xarray DataArray with dimensions ``ping_time`` and ``range_bin`` that are from the first elements of each tile along the corresponding dimensions in the original Sv or Sv_clean DataArray. Parameters ---------- source_postfix : str postfix of the Sv file used to calculate MVBS, default to '_Sv' source_path : str path of Sv file used to calculate MVBS, can be one of the following: - None (default): use Sv in RAWFILENAME_Sv.nc in the same folder as the raw data file, or when RAWFILENAME_Sv.nc doesn't exist, perform self.calibrate() and use the resulted self.Sv - path to a directory: RAWFILENAME_Sv.nc in the specified directory - path to a specific file: the specified file, e.g., ./another_directory/some_other_filename.nc MVBS_range_bin_size : float, optional meters per tile for calculating MVBS [m] MVBS_ping_size : int, optional number of pings per tile for calculating MVBS save : bool, optional whether to save the calculated MVBS into a new .nc file, default to ``False`` save_postfix : str Filename postfix, default to '_MVBS' save_path : str Full filename to save to, overwriting the RAWFILENAME_MVBS.nc default """ # Check params if (MVBS_range_bin_size is not None) and (self.MVBS_range_bin_size != MVBS_range_bin_size): self.MVBS_range_bin_size = MVBS_range_bin_size if (MVBS_ping_size is not None) and (self.MVBS_ping_size != MVBS_ping_size): self.MVBS_ping_size = MVBS_ping_size # Get Sv by validating path and calibrate if not already done if self.Sv is not None: print('%s use Sv stored in memory to calculate MVBS' % dt.datetime.now().strftime('%H:%M:%S')) print_src = False else: print_src = True proc_data = self._get_proc_Sv(source_path=source_path, source_postfix=source_postfix) if print_src: if self.Sv_path is not None: print('%s Sv source used to calculate MVBS: %s' % (dt.datetime.now().strftime('%H:%M:%S'), self.Sv_path)) else: print('%s Sv source used to calculate MVBS: memory' % dt.datetime.now().strftime('%H:%M:%S')) # Get tile indexing parameters self.MVBS_range_bin_size, range_bin_tile_bin_edge, ping_tile_bin_edge = \ self.get_tile_params(r_data_sz=proc_data.range_bin.size, p_data_sz=proc_data.ping_time.size, r_tile_sz=self.MVBS_range_bin_size, p_tile_sz=self.MVBS_ping_size, sample_thickness=self.sample_thickness) # Calculate MVBS Sv_linear = 10 ** (proc_data.Sv / 10) # convert to linear domain before averaging # check if number of range_bin per tile the same for all freq channels if np.unique([np.array(x).size for x in range_bin_tile_bin_edge]).size == 1: MVBS = 10 * np.log10(Sv_linear.coarsen( ping_time=self.MVBS_ping_size, range_bin=int(np.unique(self.MVBS_range_bin_size / self.sample_thickness)), boundary='pad').mean()) MVBS.coords['range_bin'] = ('range_bin', np.arange(MVBS['range_bin'].size)) else: range_bin_coarsen_idx = (self.MVBS_range_bin_size / self.sample_thickness).astype(int) tmp_MVBS = [] for r_bin in range_bin_coarsen_idx: freq = r_bin.frequency.values tmp_da = 10 * np.log10(Sv_linear.sel(frequency=freq).coarsen( ping_time=self.MVBS_ping_size, range_bin=r_bin.values, boundary='pad').mean()) tmp_da.coords['range_bin'] = ('range_bin', np.arange(tmp_da['range_bin'].size)) tmp_da.name = 'MVBS' tmp_MVBS.append(tmp_da) # Construct a dataArray TODO: this can probably be done smarter using xarray native functions MVBS_val = np.array([zz.values for zz in xr.align(*tmp_MVBS, join='outer')]) MVBS = xr.DataArray(MVBS_val, coords={'frequency': Sv_linear['frequency'].values, 'ping_time': tmp_MVBS[0]['ping_time'].values, 'range_bin': np.arange(MVBS_val.shape[2])}, dims=['frequency', 'ping_time', 'range_bin']).dropna(dim='range_bin', how='all') # Set MVBS attributes MVBS.name = 'MVBS' MVBS = MVBS.to_dataset() MVBS['MVBS_range_bin_size'] = ('frequency', self.MVBS_range_bin_size) MVBS.attrs['MVBS_ping_size'] = self.MVBS_ping_size # Save results in object and as a netCDF file self.MVBS = MVBS if save: self.MVBS_path = self.validate_path(save_path=save_path, save_postfix=save_postfix) print('%s saving MVBS to %s' % (dt.datetime.now().strftime('%H:%M:%S'), self.MVBS_path)) MVBS.to_netcdf(self.MVBS_path) # Close opened resources proc_data.close()
[ 37811, 198, 3055, 404, 2981, 1366, 2746, 326, 7622, 8339, 286, 9809, 1366, 290, 198, 896, 4637, 284, 1366, 3696, 13, 198, 37811, 198, 198, 11748, 28686, 198, 11748, 14601, 198, 11748, 4818, 8079, 355, 288, 83, 198, 6738, 304, 354, 404...
2.165408
10,459