content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
DEFAULT_MIRRORS = { "bitbucket": [ "https://bitbucket.org/{repository}/get/{commit}.tar.gz", ], "buildifier": [ "https://github.com/bazelbuild/buildtools/releases/download/{version}/{filename}", ], "github": [ "https://github.com/{repository}/archive/{commit}.tar.gz", ], "pypi": [ "https://files.pythonhosted.org/packages/source/{p}/{package}/{package}-{version}.tar.gz", ], }
[ 7206, 38865, 62, 44, 4663, 16411, 50, 796, 1391, 198, 220, 220, 220, 366, 2545, 27041, 316, 1298, 685, 198, 220, 220, 220, 220, 220, 220, 220, 366, 5450, 1378, 2545, 27041, 316, 13, 2398, 14, 90, 260, 1930, 37765, 92, 14, 1136, 14...
2.125
208
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Tue Jun 6 21:15:23 2017 @author: yolandatiao """ import csv import glob import os from astropy.io import ascii # For using ascii table to open csv from astropy.table import Table, Column # For using astropy table functions os.chdir("/Volumes/Huitian/GSE88987/codes") import fc_basic_astropy_subprocess as fc os.chdir("/Volumes/Huitian/Genombrower/codes/txt") flist=[] for fname in glob.glob("*.txt"): flist.append(fname) nlist=[] fnflist=[] print len(flist) for i in flist: fnflist.append(i[:-4]) with open(i, "r") as fin: rfin=csv.reader(fin, delimiter=",") nlist.append(int(next(rfin)[0])) #print nlist outab=Table() outab["filename_nf"]=fnflist outab["bdgaccu"]=nlist ascii.write(outab, "meta.csv", format="csv", overwrite=True) metab=ascii.read("meta_write_bash.csv") metab=fc.setcolnames(metab) with open("bdgnorm.sh","r") as fin: rfin=csv.reader(fin, delimiter=",") inrow=next(rfin)[0] print inrow for x in xrange(0, len(metab)): xshname="%s.sh"%x with open(xshname, "w") as fout: wfout=csv.writer(fout, delimiter="\t") wfout.writerow(["cd /gpfs/home/hdiao/Geombrowser"]) outrow=inrow osfactor=str(metab["1000000000_scalingfactor"][x]) ofname=str(metab["filename_nf"][x]) outrow=outrow.replace("sfactor", osfactor) outrow=outrow.replace("inputfile", ofname) fout.writelines(outrow) with open("qsub.sh", "w") as fout: for x in xrange(0, 66): fout.writelines("qsub %s.sh"%x) fout.writelines("\n") os.chdir("/Volumes/Huitian/Genombrower/codes/rename") meta=ascii.read("rename_meta.csv") with open("rename.sh", "w") as fout: for x in xrange(0, len(meta)): fout.writelines("mv ") fout.writelines(meta["oldname"][x]) fout.writelines(" ") fout.writelines(meta["newnamenf"][x]) fout.writelines(".bdg") fout.writelines("\n")
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 17, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 30030, 7653, 220, 718, 2310, 25, 1314, 25, 1954, 2177, 198, 198, 31, 9800, 25, 331, 23573...
2.069347
995
import unittest from vendcrawler.scripts.vendcrawler import VendCrawler if __name__ == '__main__': unittest.main()
[ 11748, 555, 715, 395, 198, 198, 6738, 10817, 66, 39464, 13, 46521, 13, 85, 437, 66, 39464, 1330, 44220, 34, 39464, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 555, 715, 395, 13, 12417, 341...
2.75
44
#!/usr/bin/python3 # -*- coding: utf-8 -*- import time import json import os import sys import time import urllib import socket import argparse import requests import lib.common as common base_url = 'http://localhost:24879/player/' #------------------------------------------------------------------------------# # do something on startup # #------------------------------------------------------------------------------# #------------------------------------------------------------------------------# # check if librespot-java is running # #------------------------------------------------------------------------------# #------------------------------------------------------------------------------# # get metadata from spotify # #------------------------------------------------------------------------------# #------------------------------------------------------------------------------# # get play status # #------------------------------------------------------------------------------# #------------------------------------------------------------------------------# # get whats currently playing # #------------------------------------------------------------------------------# #------------------------------------------------------------------------------# # get player data from API # #------------------------------------------------------------------------------# #------------------------------------------------------------------------------# # read cover image fom spotify connect web # #------------------------------------------------------------------------------# #------------------------------------------------------------------------------# # play next song # #------------------------------------------------------------------------------# #------------------------------------------------------------------------------# # play previuous song # #------------------------------------------------------------------------------# #------------------------------------------------------------------------------# # start playing # #------------------------------------------------------------------------------# #------------------------------------------------------------------------------# # stop playing # #------------------------------------------------------------------------------# #------------------------------------------------------------------------------# # handle http get request # #------------------------------------------------------------------------------# #------------------------------------------------------------------------------# # main program # #------------------------------------------------------------------------------# init() common.http_get_handler = respond_to_get_request common.run_http(port) while True: time.sleep(2000)
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 640, 198, 11748, 33918, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 640, 198, 11748, 2956, 297, 571, 198, 117...
3.301408
1,065
# from tensorflow.keras import Model, Input # from tensorflow.keras.applications import vgg16, resnet50 # from tensorflow.keras.layers import (Conv2D, Conv2DTranspose, Cropping2D, add, Dropout, Reshape, Activation) # from tensorflow.keras import layers # import tensorflow as tf # # """ # FCN-8: # 1(fc)(fully conv) # 2(deconv) # 3(skip) # 4 skip 3 pixels # lower-resolution layers padding crop, # spatially aligned concat # # FCN-8FCN-16FCN-32: # 1: FCN: [b, 16, 16, filters], 32 [b, 16*32, 16*32, n_classes], # 32 FCN-32 # FCN-16 FCN-8 168 # """ # # # def fcn8_helper(input_shape, num_classes, backbone): # assert input_shape[0] % 32 == 0 # assert input_shape[1] % 32 == 0 # # inputs = Input(input_shape) # if backbone == 'vgg16': # base_model = vgg16.VGG16(input_tensor=inputs, # include_top=False, # weights='imagenet', # pooling=None, # classes=100) # elif backbone == 'resnet50': # base_model = resnet50.ResNet50(input_tensor=inputs, # include_top=False, # weights='imagenet', # pooling=None, # classes=1000) # assert isinstance(base_model, Model) # base_model.trainable = False # # # out = Conv2D( # filters=1024, kernel_size=7, padding="same", activation="relu", name="fc6")(base_model.output) # out = Dropout(rate=0.5)(out) # out = Conv2D( # filters=1024, kernel_size=1, padding="same", activation="relu", name="fc7")(out) # out = Dropout(rate=0.5)(out) # out = Conv2D( # filters=num_classes, kernel_size=(1, 1), padding="same", activation="relu", # kernel_initializer="he_normal", name="score_fr")(out) # # # [B, 8, 8, filters] * 2 --> [None, 16, 16, n_classes] # out = Conv2DTranspose( # filters=num_classes, kernel_size=(2, 2), strides=(2, 2), padding="valid", activation=None, name="score2")(out) # # fcn8 = Model(inputs=inputs, outputs=out) # return fcn8 # # # def fcn8_model(input_shape, num_classes): # fcn8 = fcn8_helper(input_shape, num_classes, backbone='vgg16') # # # "block4_pool" shape: [B, 16, 16, 512] : # skip_con1 = Conv2D( # num_classes, kernel_size=(1, 1), padding="same", activation=None, # kernel_initializer="he_normal", name="score_pool4")(fcn8.get_layer("block4_pool").output) # Summed = add(inputs=[skip_con1, fcn8.output]) # # # [B, 32, 32, num_classes] # x = Conv2DTranspose( # num_classes, kernel_size=(2, 2), strides=(2, 2), padding="valid", activation=None, name="score4")(Summed) # # # block3_pool: [B, 32, 32, filters] # skip_con2 = Conv2D( # num_classes, kernel_size=(1, 1), padding="same", activation=None, # kernel_initializer="he_normal", name="score_pool3")(fcn8.get_layer("block3_pool").output) # Summed2 = add(inputs=[skip_con2, x]) # # # 8, [B, 32, 32, filters] --> [B, 32*8, 32*8, n_classes] # outputs = Conv2DTranspose( # num_classes, kernel_size=(8, 8), strides=(8, 8), padding="valid", # activation='sigmoid', name="upsample")(Summed2) # # if num_classes == 1: # outputs = layers.Activation('sigmoid')(outputs) # else: # outputs = layers.Softmax()(outputs) # # fcn_model = Model(inputs=fcn8.input, outputs=outputs, name='FCN8s') # return fcn_model # # # def fcn8_model_resnet50(input_shape, num_classes): # fcn8 = fcn8_helper(input_shape, num_classes, backbone='resnet50') # # # "block4_pool" shape: [B, 16, 16, 1024] : # skip_con1 = Conv2D( # num_classes, kernel_size=(1, 1), padding="same", activation=None, # kernel_initializer="he_normal", name="score_pool4")(fcn8.get_layer("conv4_block6_out").output) # Summed = add(inputs=[skip_con1, fcn8.output]) # # # [B, 32, 32, num_classes] # x = Conv2DTranspose( # num_classes, kernel_size=(2, 2), strides=(2, 2), padding="valid", activation=None, name="score4")(Summed) # # # block3_pool: [B, 32, 32, 512] # skip_con2 = Conv2D( # num_classes, kernel_size=(1, 1), padding="same", activation=None, # kernel_initializer="he_normal", name="score_pool3")(fcn8.get_layer("conv3_block4_out").output) # Summed2 = add(inputs=[skip_con2, x]) # # # 8, [B, 32, 32, filters] --> [B, 32*8, 32*8, n_classes] # outputs = Conv2DTranspose( # num_classes, kernel_size=(8, 8), strides=(8, 8), padding="valid", # activation='sigmoid', name="upsample")(Summed2) # # if num_classes == 1: # outputs = layers.Activation('sigmoid')(outputs) # else: # outputs = layers.Softmax()(outputs) # # fcn_model = Model(inputs=fcn8.input, outputs=outputs, name='FCN8s') # return fcn_model # # # if __name__ == '__main__': # # m = FCN8(15, 320, 320) # # from keras.utils import plot_model # # # # plot_model(m, show_shapes=True, to_file='model_fcn8.png') # # print(len(m.layers)) # model_1 = fcn8_model_resnet50(input_shape=(256, 256, 3), num_classes=1) # model_1.summary() # # inputs = tf.keras.Input((256, 256, 3)) # # base_model = resnet50.ResNet50(input_tensor=inputs, # # include_top=False, # # weights='imagenet', # # pooling=None, # # classes=1000) # # base_model.summary() from tensorflow.keras.layers import (Conv2D, Conv2DTranspose, Cropping2D, add, Dropout, Reshape, Activation) from tensorflow.keras.applications import vgg16, resnet50 from tensorflow.keras import Model, Input from tensorflow.keras import layers """ FCN-8: 1(fc)(fully conv) 2(deconv) 3(skip) 4 skip 3 pixels lower-resolution layers padding crop, spatially aligned concat FCN-8FCN-16FCN-32: 1: FCN: [b, 16, 16, filters], 32 [b, 16*32, 16*32, n_classes], 32 FCN-32 FCN-16 FCN-8 168 """ if __name__ == '__main__': # m = FCN8(15, 320, 320) # from keras.utils import plot_model # # plot_model(m, show_shapes=True, to_file='model_fcn8.png') # print(len(m.layers)) model_1 = fcn8_model(input_shape=(256, 256, 3), num_classes=1) model_1.summary()
[ 2, 422, 11192, 273, 11125, 13, 6122, 292, 1330, 9104, 11, 23412, 201, 198, 2, 422, 11192, 273, 11125, 13, 6122, 292, 13, 1324, 677, 602, 1330, 410, 1130, 1433, 11, 581, 3262, 1120, 201, 198, 2, 422, 11192, 273, 11125, 13, 6122, 29...
1.978022
3,367
def binom(n, k): """Quickly adapted from https://stackoverflow.com/questions/26560726/python-binomial-coefficient""" if k < 0 or k > n: return 0 if k == 0 or k == n: return 1 total_ways = 1 for i in range(min(k, n - k)): total_ways = total_ways * (n - i) // (i + 1) return total_ways def max_confs_cnt(formula=""): """Get the maximal number of configurations for a given chemical formula.""" from IsoSpecPy import IsoParamsFromFormula f = IsoParamsFromFormula(formula) if f.atomCount: N = 1 for n, p in zip(f.atomCount, f.prob): N *= binom(n+len(p)-1, n) return N else: return 0 test_formulas = [ 'O100', 'O100N10S6', 'C100H202', 'S10H20' ] def test_all_configs_output_cnt(): """Test if IsoSpecPy output correctly all configurations.""" from IsoSpecPy import IsoThreshold global test_formulas for f in test_formulas: I = IsoThreshold(formula=f, threshold=0.0, absolute=True) assert len(I) == max_confs_cnt(f) print("Seems OK!") if __name__ == "__main__": test_all_configs_output_cnt()
[ 4299, 9874, 296, 7, 77, 11, 479, 2599, 198, 220, 220, 220, 37227, 21063, 306, 16573, 422, 3740, 1378, 25558, 2502, 11125, 13, 785, 14, 6138, 507, 14, 22980, 31980, 2075, 14, 29412, 12, 8800, 49070, 12, 1073, 16814, 37811, 198, 220, ...
2.093103
580
# Copyright 2017 Division of Medical Image Computing, German Cancer Research Center (DKFZ) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import glob from os.path import join import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.optim import Adamax import torch.optim.lr_scheduler as lr_scheduler from torch.autograd import Variable from tractseg.libs.PytorchUtils import PytorchUtils from tractseg.libs.ExpUtils import ExpUtils from tractseg.models.BaseModel import BaseModel from tractseg.libs.MetricUtils import MetricUtils from tractseg.libs.PytorchUtils import conv2d from tractseg.libs.PytorchUtils import deconv2d
[ 2, 15069, 2177, 7458, 286, 8366, 7412, 38589, 11, 2679, 15523, 4992, 3337, 357, 48510, 37, 57, 8, 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...
3.44868
341
import argparse import time from kubernetes.client.rest import ApiException from polyaxon_client.client import PolyaxonClient from polyaxon_k8s.manager import K8SManager from sidecar import settings from sidecar.monitor import is_pod_running if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( '--app_label', type=str ) parser.add_argument( '--container_id', type=str ) parser.add_argument( '--sleep_interval', default=2, type=int ) parser.add_argument( '--max_restarts', default=0, type=int ) args = parser.parse_args() arguments = args.__dict__ container_id = arguments.pop('container_id') app_label = arguments.pop('app_label') sleep_interval = arguments.pop('sleep_interval') max_restarts = arguments.pop('max_restarts') k8s_manager = K8SManager(namespace=settings.K8S_NAMESPACE, in_cluster=True) client = PolyaxonClient() client.set_internal_health_check() retry = 0 is_running = True status = None while is_running and retry < 3: time.sleep(sleep_interval) try: is_running, status = is_pod_running(k8s_manager, settings.POD_ID, container_id, max_restarts) except ApiException: retry += 1 time.sleep(sleep_interval) # We wait a bit more before try if status: client.reconcile(status=status)
[ 11748, 1822, 29572, 198, 11748, 640, 198, 198, 6738, 479, 18478, 3262, 274, 13, 16366, 13, 2118, 1330, 5949, 72, 16922, 198, 198, 6738, 7514, 897, 261, 62, 16366, 13, 16366, 1330, 12280, 897, 261, 11792, 198, 6738, 7514, 897, 261, 62,...
2.091731
774
#! /usr/bin/env python import rospy from nav_msgs.msg import Odometry if __name__ == "__main__": rospy.init_node('odom_topic_subscriber') odom_reader_object = OdomTopicReader() rate = rospy.Rate(10) while not rospy.is_shutdown(): rate.sleep()
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 686, 2777, 88, 198, 6738, 6812, 62, 907, 14542, 13, 19662, 1330, 10529, 15748, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 68...
2.245902
122
"""Tests for quantization""" import numpy as np import unittest import os import shutil import yaml import tensorflow as tf if __name__ == "__main__": unittest.main()
[ 37811, 51, 3558, 329, 5554, 1634, 37811, 201, 198, 11748, 299, 32152, 355, 45941, 201, 198, 11748, 555, 715, 395, 201, 198, 11748, 28686, 201, 198, 11748, 4423, 346, 201, 198, 11748, 331, 43695, 201, 198, 11748, 11192, 273, 11125, 355, ...
2.43038
79
# Copyright 2020 The Cirq Developers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for EngineClient.""" import datetime from unittest import mock import pytest from google.api_core import exceptions from google.protobuf.field_mask_pb2 import FieldMask from google.protobuf.timestamp_pb2 import Timestamp from cirq.google.engine.engine_client import EngineClient, EngineException from cirq.google.engine.client import quantum from cirq.google.engine.client.quantum_v1alpha1 import enums as qenums from cirq.google.engine.client.quantum_v1alpha1 import types as qtypes # yapf: disable # yapf: disable
[ 2, 15069, 12131, 383, 21239, 80, 34152, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 2, 921...
3.50152
329
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! import grpc from google.ads.google_ads.v0.proto.resources import media_file_pb2 as google_dot_ads_dot_googleads__v0_dot_proto_dot_resources_dot_media__file__pb2 from google.ads.google_ads.v0.proto.services import media_file_service_pb2 as google_dot_ads_dot_googleads__v0_dot_proto_dot_services_dot_media__file__service__pb2 def add_MediaFileServiceServicer_to_server(servicer, server): rpc_method_handlers = { 'GetMediaFile': grpc.unary_unary_rpc_method_handler( servicer.GetMediaFile, request_deserializer=google_dot_ads_dot_googleads__v0_dot_proto_dot_services_dot_media__file__service__pb2.GetMediaFileRequest.FromString, response_serializer=google_dot_ads_dot_googleads__v0_dot_proto_dot_resources_dot_media__file__pb2.MediaFile.SerializeToString, ), 'MutateMediaFiles': grpc.unary_unary_rpc_method_handler( servicer.MutateMediaFiles, request_deserializer=google_dot_ads_dot_googleads__v0_dot_proto_dot_services_dot_media__file__service__pb2.MutateMediaFilesRequest.FromString, response_serializer=google_dot_ads_dot_googleads__v0_dot_proto_dot_services_dot_media__file__service__pb2.MutateMediaFilesResponse.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler( 'google.ads.googleads.v0.services.MediaFileService', rpc_method_handlers) server.add_generic_rpc_handlers((generic_handler,))
[ 2, 2980, 515, 416, 262, 308, 49, 5662, 11361, 8435, 17050, 13877, 13, 8410, 5626, 48483, 0, 198, 11748, 1036, 14751, 198, 198, 6738, 23645, 13, 5643, 13, 13297, 62, 5643, 13, 85, 15, 13, 1676, 1462, 13, 37540, 1330, 2056, 62, 7753, ...
2.583045
578
import importlib import math import os from pathlib import Path from typing import Optional, Tuple import cv2 import numpy as np import requests import torch import kornia as K if __name__ == "__main__": main()
[ 11748, 1330, 8019, 198, 11748, 10688, 198, 11748, 28686, 198, 6738, 3108, 8019, 1330, 10644, 198, 6738, 19720, 1330, 32233, 11, 309, 29291, 198, 198, 11748, 269, 85, 17, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 7007, 198, 11748, ...
3.25
68
# Copyright 2020 The Forte Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import random from typing import Tuple import numpy as np from texar.torch.data import Vocab, Embedding from ft.onto.base_ontology import Annotation from forte.common.configuration import Config from forte.processors.data_augment.algorithms.text_replacement_op import ( TextReplacementOp, ) __all__ = [ "EmbeddingSimilarityReplacementOp", ]
[ 2, 15069, 12131, 383, 6401, 68, 46665, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 2...
3.509158
273
from __future__ import print_function, absolute_import from sentry import analytics from sentry.signals import join_request_created, join_request_link_viewed
[ 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 11, 4112, 62, 11748, 198, 198, 6738, 1908, 563, 1330, 23696, 198, 6738, 1908, 563, 13, 12683, 874, 1330, 4654, 62, 25927, 62, 25598, 11, 4654, 62, 25927, 62, 8726, 62, 1177, 276, 628, 1...
3.744186
43
from django.conf.urls import url, include from django.contrib import admin from django.views.generic import RedirectView from django.views.generic import TemplateView from django.contrib.sitemaps.views import sitemap from django.conf import settings from blog.sitemaps import ArticleSitemap urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^robots\.txt$', TemplateView.as_view(template_name='robots.txt', content_type='text/plain')), url(r'^sitemap\.xml$', sitemap, {'sitemaps': {'blog': ArticleSitemap}}, name='sitemap'), url(r'^', include('blog.urls')), ] if settings.DEBUG: import debug_toolbar urlpatterns += [ url(r'^__debug__/', include(debug_toolbar.urls)), ]
[ 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 1330, 19016, 11, 2291, 198, 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 6738, 42625, 14208, 13, 33571, 13, 41357, 1330, 2297, 1060, 7680, 198, 6738, 42625, 14208, 13, 33571, 13, 4135...
2.657993
269
#!/usr/bin/env python """ @package ion_functions.qc_functions @file ion_functions/qc_functions.py @author Christopher Mueller @brief Module containing QC functions ported from matlab samples in DPS documents """ from ion_functions.qc.qc_extensions import stuckvalues, spikevalues, gradientvalues, ntp_to_month import time import numpy as np import numexpr as ne from scipy.interpolate import LinearNDInterpolator from ion_functions import utils from ion_functions.utils import fill_value # try to load the OOI logging module, using default Python logging module if # unavailable try: from ooi.logging import log except ImportError: import logging log = logging.getLogger('ion-functions') def dataqc_globalrangetest_minmax(dat, dat_min, dat_max, strict_validation=False): ''' Python wrapper for dataqc_globalrangetest Combines the min/max arguments into list for dataqc_globalrangetest ''' if is_none(dat_min) or is_none(dat_max) or is_fill(dat_min) or is_fill(dat_max): out = np.empty(dat.shape, dtype=np.int8) out.fill(-99) return out return dataqc_globalrangetest(dat, [np.atleast_1d(dat_min)[-1], np.atleast_1d(dat_max)[-1]], strict_validation=strict_validation) def dataqc_globalrangetest(dat, datlim, strict_validation=False): """ Description: Data quality control algorithm testing if measurements fall into a user-defined valid range. Returns 1 for presumably good data and 0 for data presumed bad. Implemented by: 2010-07-28: DPS authored by Mathias Lankhorst. Example code provided for Matlab. 2013-04-06: Christopher Wingard. Initial python implementation. 2013-05-30: Christopher Mueller. Performance improvements by adding strict_validation flag. Usage: qcflag = dataqc_globalrangetest(dat, datlim, strict_validation) where qcflag = Boolean, 0 if value is outside range, else = 1. dat = Input dataset, any scalar or vector. Must be numeric and real. datlim = Two-element vector with the minimum and maximum values considered to be valid. strict_validation = Flag (default is False) to assert testing of input types (e.g. isreal, isnumeric) References: OOI (2012). Data Product Specification for Global Range Test. Document Control Number 1341-10004. https://alfresco.oceanobservatories.org (See: Company Home >> OOI >> Controlled >> 1000 System Level >> 1341-10004_Data_Product_SPEC_GLBLRNG_OOI.pdf) """ dat = np.atleast_1d(dat) datlim = np.atleast_1d(datlim) if strict_validation: if not utils.isnumeric(dat).all(): raise ValueError('\'dat\' must be numeric') if not utils.isreal(dat).all(): raise ValueError('\'dat\' must be real') if not utils.isnumeric(datlim).all(): raise ValueError('\'datlim\' must be numeric') if not utils.isreal(datlim).all(): raise ValueError('\'datlim\' must be real') if len(datlim) < 2: # Must have at least 2 elements raise ValueError('\'datlim\' must have at least 2 elements') return (datlim.min() <= dat) & (dat <= datlim.max()).astype('int8') def dataqc_localrangetest(dat, z, datlim, datlimz, strict_validation=False): """ Description: Data quality control algorithm testing if measurements fall into a user-defined valid range. This range is not constant but varies with measurement location. Returns 1 for presumably good data and 0 for data presumed bad. Implemented by: 2012-07-17: DPS authored by Mathias Lankhorst. Example code provided for Matlab. 2013-04-06: Christopher Wingard. Initial python implementation. Usage: qcflag = dataqc_localrangetest(dat, z, datlim, datlimz) where qcflag = Boolean, 0 if value is outside range, else = 1. dat = input data set, a numeric real scalar or column vector. z = location of measurement dat. must have same # of rows as dat and same # of columns as datlimz datlim = two column array with the minimum (column 1) and maximum (column 2) values considered valid. datlimz = array with the locations where datlim is given. must have same # of rows as datlim and same # of columns as z. References: OOI (2012). Data Product Specification for Local Range Test. Document Control Number 1341-10005. https://alfresco.oceanobservatories.org/ (See: Company Home >> OOI >> Controlled >> 1000 System Level >> 1341-10005_Data_Product_SPEC_LOCLRNG_OOI.pdf) """ if strict_validation: # check if dat and datlim are matrices if not utils.isvector(dat): raise ValueError('\'dat\' must be a matrix') if not utils.ismatrix(datlim): raise ValueError('\'datlim\' must be a matrix') # check if all inputs are numeric and real for k, arg in {'dat': dat, 'z': z, 'datlim': datlim, 'datlimz': datlimz}.iteritems(): if not utils.isnumeric(arg).all(): raise ValueError('\'{0}\' must be numeric'.format(k)) if not utils.isreal(arg).all(): raise ValueError('\'{0}\' must be real'.format(k)) if len(datlim.shape) == 3 and datlim.shape[0] == 1: datlim = datlim.reshape(datlim.shape[1:]) if len(datlimz.shape) == 3 and datlimz.shape[0] == 1: datlimz = datlimz.reshape(datlimz.shape[1:]) # test size and shape of the input arrays datlimz and datlim, setting test # variables. array_size = datlimz.shape if len(array_size) == 1: numlim = array_size[0] ndim = 1 else: numlim = array_size[0] ndim = array_size[1] array_size = datlim.shape tmp1 = array_size[0] tmp2 = array_size[1] if tmp1 != numlim: raise ValueError('\'datlim\' and \'datlimz\' must ' 'have the same number of rows.') if tmp2 != 2: raise ValueError('\'datlim\' must be structured as 2-D array ' 'with exactly 2 columns and 1 through N rows.') # test the size and shape of the z input array array_size = z.shape if len(array_size) == 1: num = array_size[0] tmp2 = 1 else: num = array_size[0] tmp2 = array_size[1] if tmp2 != ndim: raise ValueError('\'z\' must have the same number of columns ' 'as \'datlimz\'.') if num != dat.size: raise ValueError('Len of \'dat\' must match number of ' 'rows in \'z\'') # test datlim, values in column 2 must be greater than those in column 1 if not all(datlim[:, 1] > datlim[:, 0]): raise ValueError('Second column values of \'datlim\' should be ' 'greater than first column values.') # calculate the upper and lower limits for the data set if ndim == 1: # determine the lower limits using linear interpolation lim1 = np.interp(z, datlimz, datlim[:, 0], left=np.nan, right=np.nan) # determine the upper limits using linear interpolation lim2 = np.interp(z, datlimz, datlim[:, 1], left=np.nan, right=np.nan) else: # Compute Delaunay Triangulation and use linear interpolation to # determine the N-dimensional lower limits F = LinearNDInterpolator(datlimz, datlim[:, 0].reshape(numlim, 1)) lim1 = F(z).reshape(dat.size) # Compute Delaunay Triangulation and use linear interpolation to # determine the N-dimensional upper limits F = LinearNDInterpolator(datlimz, datlim[:, 1].reshape(numlim, 1)) lim2 = F(z).reshape(dat.size) # replace NaNs from above interpolations ff = (np.isnan(lim1)) | (np.isnan(lim2)) lim1[ff] = np.max(datlim[:, 1]) lim2[ff] = np.min(datlim[:, 0]) # compute the qcflags qcflag = (dat >= lim1) & (dat <= lim2) return qcflag.astype('int8') def dataqc_spiketest(dat, acc, N=5, L=5, strict_validation=False): """ Description: Data quality control algorithm testing a time series for spikes. Returns 1 for presumably good data and 0 for data presumed bad. The time series is divided into windows of len L (an odd integer number). Then, window by window, each value is compared to its (L-1) neighboring values: a range R of these (L-1) values is computed (max. minus min.), and replaced with the measurement accuracy ACC if ACC>R. A value is presumed to be good, i.e. no spike, if it deviates from the mean of the (L-1) peers by less than a multiple of the range, N*max(R,ACC). Further than (L-1)/2 values from the start or end points, the peer values are symmetrically before and after the test value. Within that range of the start and end, the peers are the first/last L values (without the test value itself). The purpose of ACC is to restrict spike detection to deviations exceeding a minimum threshold value (N*ACC) even if the data have little variability. Use ACC=0 to disable this behavior. Implemented by: 2012-07-28: DPS authored by Mathias Lankhorst. Example code provided for Matlab. 2013-04-06: Christopher Wingard. Initial python implementation. 2013-05-30: Christopher Mueller. Performance optimizations. Usage: qcflag = dataqc_spiketest(dat, acc, N, L) where qcflag = Boolean, 0 if value is outside range, else = 1. dat = input data set, a numeric, real vector. acc = Accuracy of any input measurement. N = (optional, defaults to 5) Range multiplier, cf. above L = (optional, defaults to 5) Window len, cf. above References: OOI (2012). Data Product Specification for Spike Test. Document Control Number 1341-10006. https://alfresco.oceanobservatories.org/ (See: Company Home >> OOI >> Controlled >> 1000 System Level >> 1341-10006_Data_Product_SPEC_SPKETST_OOI.pdf) """ dat = np.atleast_1d(dat) if strict_validation: if not utils.isnumeric(dat).all(): raise ValueError('\'dat\' must be numeric') if not utils.isreal(dat).all(): raise ValueError('\'dat\' must be real') if not utils.isvector(dat): raise ValueError('\'dat\' must be a vector') for k, arg in {'acc': acc, 'N': N, 'L': L}.iteritems(): if not utils.isnumeric(arg).all(): raise ValueError('\'{0}\' must be numeric'.format(k)) if not utils.isreal(arg).all(): raise ValueError('\'{0}\' must be real'.format(k)) dat = np.asanyarray(dat, dtype=np.float) out = spikevalues(dat, L, N, acc) return out def dataqc_polytrendtest(dat, t, ord_n=1, nstd=3, strict_validation=False): """ Description: Data quality control algorithm testing if measurements contain a significant portion of a polynomial. Returns 1 if this is not the case, else 0. The purpose of this test is to check if a significant fraction of the variability in a time series can be explained by a drift, possibly interpreted as a sensor drift. This drift is assumed to be a polynomial of order ORD. Use ORD=1 to consider a linear drift The time series dat is passed to MatLab's POLYFIT routine to obtain a polynomial fit PP to dat, and the difference dat-PP is compared to the original dat. If the standard deviation of (dat-PP) is less than that of dat by a factor of NSTD, the time series is assumed to contain a significant trend (output will be 0), else not (output will be 1). Implemented by: 2012-10-29: DPS authored by Mathias Lankhorst. Example code provided for Matlab. 2013-04-06: Christopher Wingard. Initial python implementation. 2013-05-30: Christopher Mueller. Performance optimizations. Usage: qcflag = dataqc_polytrendtest(dat, t, ord_n, nstd, strict_validation) where qcflag = Boolean, 0 a trend is detected, 1 elsewhere. dat = Input dataset, a numeric real vector. t = time record associated with dat ord_n (optional, defaults to 1) = Polynomial order. nstd (optional, defaults to 3) = Factor by how much the standard deviation must be reduced before qcflag switches from 1 to 0 strict_validation (optional, defaults to False) = Flag asserting testing of inputs. References: OOI (2012). Data Product Specification for Trend Test. Document Control Number 1341-10007. https://alfresco.oceanobservatories.org/ (See: Company Home >> OOI >> Controlled >> 1000 System Level >> 1341-10007_Data_Product_SPEC_TRNDTST_OOI.pdf) """ dat = np.atleast_1d(dat) t = np.atleast_1d(t) if strict_validation: for k, arg in {'dat': dat, 't': t, 'ord_n': ord_n, 'nstd': nstd}.iteritems(): if not utils.isnumeric(arg).all(): raise ValueError('\'{0}\' must be numeric'.format(k)) if not utils.isreal(arg).all(): raise ValueError('\'{0}\' must be real'.format(k)) for k, arg in {'dat': dat, 't': t}.iteritems(): if not utils.isvector(arg): raise ValueError('\'{0}\' must be a vector'.format(k)) for k, arg in {'ord_n': ord_n, 'nstd': nstd}.iteritems(): if not utils.isscalar(arg): raise ValueError('\'{0}\' must be a scalar'.format(k)) ord_n = int(round(abs(ord_n))) nstd = int(abs(nstd)) ll = len(dat) # Not needed because time is incorporated as 't' # t = range(ll) pp = np.polyfit(t, dat, ord_n) datpp = np.polyval(pp, t) # test for a trend if np.atleast_1d((np.std(dat - datpp) * nstd) < np.std(dat)).all(): trndtst = 0 else: trndtst = 1 # insure output size equals input, even though test yields a single value. qcflag = np.ones(dat.shape).astype('int8') * trndtst return qcflag def dataqc_stuckvaluetest(x, reso, num=10, strict_validation=False): """ Description: Data quality control algorithm testing a time series for "stuck values", i.e. repeated occurences of one value. Returns 1 for presumably good data and 0 for data presumed bad. Implemented by: 2012-10-29: DPS authored by Mathias Lankhorst. Example code provided for Matlab. 2013-04-06: Christopher Wingard. Initial python implementation. Usage: qcflag = =dataqc_stuckvaluetest(x, RESO, NUM); where qcflag = Boolean output: 0 where stuck values are found, 1 elsewhere. x = Input time series (vector, numeric). reso = Resolution; repeat values less than reso apart will be considered "stuck values". num = Minimum number of successive values within reso of each other that will trigger the "stuck value". num is optional and defaults to 10 if omitted or empty. References: OOI (2012). Data Product Specification for Stuck Value Test. Document Control Number 1341-10008. https://alfresco.oceanobservatories.org/ (See: Company Home >> OOI >> Controlled >> 1000 System Level >> 1341-10008_Data_Product_SPEC_STUCKVL_OOI.pdf) """ dat = np.atleast_1d(x) if strict_validation: if not utils.isnumeric(dat).all(): raise ValueError('\'x\' must be numeric') if not utils.isvector(dat): raise ValueError('\'x\' must be a vector') if not utils.isreal(dat).all(): raise ValueError('\'x\' must be real') for k, arg in {'reso': reso, 'num': num}.iteritems(): if not utils.isnumeric(arg).all(): raise ValueError('\'{0}\' must be numeric'.format(k)) if not utils.isscalar(arg): raise ValueError('\'{0}\' must be a scalar'.format(k)) if not utils.isreal(arg).all(): raise ValueError('\'{0}\' must be real'.format(k)) num = np.abs(num) dat = np.asanyarray(dat, dtype=np.float) ll = len(x) if ll < num: # Warn - 'num' is greater than len(x), returning zeros out = np.zeros(dat.size, dtype='int8') else: out = stuckvalues(dat, reso, num) return out def dataqc_gradienttest(dat, x, ddatdx, mindx, startdat, toldat, strict_validation=False): """ Description Data quality control algorithm testing if changes between successive data points fall within a certain range. Input data dat are given as a function of coordinate x. The algorithm will flag dat values as bad if the change deltaDAT/deltaX between successive dat values exceeds thresholds given in ddatdx. Once the threshold is exceeded, following dat are considered bad until a dat value returns to within toldat of the last known good value. It is possible to remove data points that are too close together in x coordinates (use mindx). By default, the first value of dat is considered good. To change this, use startdat and toldat to set as the first good data point the first one that comes within toldat of startdat. Implemented by: 2012-07-17: DPS authored by Mathias Lankhorst. Example code provided for Matlab. 2013-04-06: Christopher Wingard. Initial python implementation. Usage: outdat, outx, outqc = dataqc_gradienttest(dat, x, ddatdx, mindx, startdat, toldat); where outdat = same as dat except that NaNs and values not meeting mindx are removed. outx = same as x except that NaNs and values not meeting mindx are removed. outqc = output quality control flags for outdat. 0 means bad data, 1 means good data. dat = input dataset, a numeric real vector. x = coordinate (e.g. time, distance) along which dat is given. Must be of the same size as dat and strictly increasing. ddatdx = two-element vector defining the valid range of ddat/dx from one point to the next. mindx = scalar. minimum dx for which this test will be applied (data that are less than mindx apart will be deleted). defaults to zero if NaN/empty. startdat = start value (scalar) of dat that is presumed good. defaults to first non-NaN value of dat if NaN/empty. toldat = tolerance value (scalar) for dat; threshold to within which dat must return to be counted as good, after exceeding a ddatdx threshold detected bad data. References: OOI (2012). Data Product Specification for Gradient Test. Document Control Number 1341-100010. https://alfresco.oceanobservatories.org/ (See: Company Home >> OOI >> Controlled >> 1000 System Level >> 1341-10010_Data_Product_SPEC_GRDTEST_OOI.pdf) """ if strict_validation: if not utils.isvector(dat) or not utils.isvector(x): raise ValueError('\'dat\' and \'x\' must be vectors') if len(dat) != len(x): raise ValueError('\'dat\' and \'x\' must be of equal len') if not all(np.diff(x) > 0): raise ValueError('\'x\' must be montonically increasing') dat = np.asanyarray(dat, dtype=np.float).flatten() x = np.asanyarray(x, dtype=np.float).flatten() if np.isnan(mindx): mindx = 0 mindx = mindx or 0 if np.isnan(startdat): startdat = 0 startdat = startdat or 0 # No strict validation here, they are scalards and they must be validated # before going into the C-layer if not utils.isscalar(mindx): raise ValueError("'mindx' must be scalar, NaN, or empty.") if not utils.isscalar(startdat): raise ValueError("'startdat' must be scalar, NaN, or empty.") # Confirm that there are still data points left, else abort: if np.abs(x[0] - x[-1]) < mindx: out = np.zeros(x.shape) out.fill(1) log.warn('Too few values to inspect') return out grad_min = ddatdx[0] grad_max = ddatdx[1] out = gradientvalues(dat, x, grad_min, grad_max, mindx, startdat, toldat) return out def dataqc_solarelevation(lon, lat, dt): """ Description Computes instantaneous no-sky solar radiation and altitude from date and time stamp and position data. It is put together from expressions taken from Appendix E in the 1978 edition of Almanac for Computers, Nautical Almanac Office, U.S. Naval Observatory. They are reduced accuracy expressions valid for the years 1800-2100. Solar declination computed from these expressions is accurate to at least 1'. The solar constant (1368.0 W/m^2) represents a mean of satellite measurements made over the last sunspot cycle (1979-1995) taken from Coffey et al (1995), Earth System Monitor, 6, 6-10. This code is a python implementation of soradna1.m available in Air-Sea Toolbox. Implemented by: 1997-03-08: Version 1.0 (author unknown) of soradna1.m. 1998-08-28: Version 1.1 (author unknown) of soradna1.m. 1999-08-05: Version 2.0 (author unknown) of soradna1.m. 2013-04-07: Christopher Wingard. Initial python implementation. Note, this function is derived from old, unmaintained code. More robust implementations exist (e.g. PyEphem and PySolar) that will probably calculate these values more accurately. Usage: z, sorad = dataqc_solarelevation(lon, lat, dt) where z = solar altitude [degrees] sorad = no atmosphere solar radiation [W m^-2] lon = longitude (east is positive) [decimal degress] lat = latitude [decimal degrees] dt = date and time stamp in UTC [seconds since 1970-01-01] Examples dt = 1329177600 # 2012-02-14 00:00:00 z, sorad = dataqc_solarelevation(120, 30, dt) z = 15.1566, sorad = 366.8129 OOI (2012). Data Product Specification for Solar Elevation. Document Control Number 1341-100011. https://alfresco.oceanobservatories.org/ (See: Company Home >> OOI >> Controlled >> 1000 System Level >> 1341-10011_Data_Product_SPEC_SOLRELV_OOI.pdf) """ # Test lengths and types of inputs. Latitude and longitude must be the same # size and can either be a scalar or a vecotr. The date and time stamp # can also be either a scalar or a vector. If all three inputs are vectors, # they must be of the same length. if len(lon) != len(lat): raise ValueError('\'lon\' and \'lat\' must be the same size') if utils.isvector(lon) and utils.isvector(lat) and utils.isvector(dt): # test their lengths if not len(lon) == len(lat) == len(dt): raise ValueError('If all inputs are vectors, these must all ' 'be of the same length') # set constants (using values from as_consts.m) # ------ short-wave flux calculations # the solar constant [W m^-2] represents a mean of satellite measurements # made over the last sunspot cycle (1979-1995), taken from Coffey et al. # (1995), Earth System Monitor, 6, 6-10. solar_const = 1368.0 # Create a time tuple in UTC from the Epoch time input, and then create # scalars or numpy arrays of time elements for subsequent calculations. ldt = len(dt) yy = np.zeros(ldt, dtype=np.int) mn = np.zeros(ldt, dtype=np.int) dd = np.zeros(ldt, dtype=np.int) hh = np.zeros(ldt, dtype=np.int) mm = np.zeros(ldt, dtype=np.int) ss = np.zeros(ldt, dtype=np.int) for i in range(ldt): # create time tuple in UTC gtime = time.gmtime(dt[i]) # create scalar elements yy[i] = gtime[0] mn[i] = gtime[1] dd[i] = gtime[2] hh[i] = gtime[3] mm[i] = gtime[4] ss[i] = gtime[5] #constants used in function deg2rad = np.pi / 180.0 rad2deg = 1 / deg2rad # compute Universal Time in hours utime = hh + (mm + ss / 60.0) / 60.0 # compute Julian ephemeris date in days (Day 1 is 1 Jan 4713 B.C. which # equals -4712 Jan 1) jed = (367.0 * yy - np.fix(7.0*(yy+np.fix((mn+9)/12.0))/4.0) + np.fix(275.0*mn/9.0) + dd + 1721013 + utime / 24.0) # compute interval in Julian centuries since 1900 jc_int = (jed - 2415020.0) / 36525.0 # compute mean anomaly of the sun ma_sun = 358.475833 + 35999.049750 * jc_int - 0.000150 * jc_int**2 ma_sun = (ma_sun - np.fix(ma_sun/360.0) * 360.0) * deg2rad # compute mean longitude of sun ml_sun = 279.696678 + 36000.768920 * jc_int + 0.000303 * jc_int**2 ml_sun = (ml_sun - np.fix(ml_sun/360.0) * 360.0) * deg2rad # compute mean anomaly of Jupiter ma_jup = 225.444651 + 2880.0 * jc_int + 154.906654 * jc_int ma_jup = (ma_jup - np.fix(ma_jup/360.0) * 360.0) * deg2rad # compute longitude of the ascending node of the moon's orbit an_moon = (259.183275 - 1800 * jc_int - 134.142008 * jc_int + 0.002078 * jc_int**2) an_moon = (an_moon - np.fix(an_moon/360.0) * 360.0 + 360.0) * deg2rad # compute mean anomaly of Venus ma_ven = (212.603219 + 58320 * jc_int + 197.803875 * jc_int + 0.001286 * jc_int**2) ma_ven = (ma_ven - np.fix(ma_ven/360.0) * 360.0) * deg2rad # compute sun theta theta = (0.397930 * np.sin(ml_sun) + 0.009999 * np.sin(ma_sun-ml_sun) + 0.003334 * np.sin(ma_sun+ml_sun) - 0.000208 * jc_int * np.sin(ml_sun) + 0.000042 * np.sin(2*ma_sun+ml_sun) - 0.000040 * np.cos(ml_sun) - 0.000039 * np.sin(an_moon-ml_sun) - 0.000030 * jc_int * np.sin(ma_sun-ml_sun) - 0.000014 * np.sin(2*ma_sun-ml_sun) - 0.000010 * np.cos(ma_sun-ml_sun-ma_jup) - 0.000010 * jc_int * np.sin(ma_sun+ml_sun)) # compute sun rho rho = (1.000421 - 0.033503 * np.cos(ma_sun) - 0.000140 * np.cos(2*ma_sun) + 0.000084 * jc_int * np.cos(ma_sun) - 0.000033 * np.sin(ma_sun-ma_jup) + 0.000027 * np.sin(2.*ma_sun-2.*ma_ven)) # compute declination decln = np.arcsin(theta/np.sqrt(rho)) # compute equation of time (in seconds of time) l = 276.697 + 0.98564734 * (jed-2415020.0) l = (l - 360.0 * np.fix(l/360.0)) * deg2rad eqt = (-97.8 * np.sin(l) - 431.3 * np.cos(l) + 596.6 * np.sin(2*l) - 1.9 * np.cos(2*l) + 4.0 * np.sin(3*l) + 19.3 * np.cos(3*l) - 12.7 * np.sin(4*l)) eqt = eqt / 60.0 # compute local hour angle from global hour angle gha = 15.0 * (utime-12) + 15.0 * eqt / 60.0 lha = gha - lon # compute radius vector rv = np.sqrt(rho) # compute solar altitude sz = (np.sin(deg2rad*lat) * np.sin(decln) + np.cos(deg2rad*lat) * np.cos(decln) * np.cos(deg2rad*lha)) z = rad2deg * np.arcsin(sz) # compute solar radiation outside atmosphere (defaults to 0 when solar # altitude is below the horizon) sorad = (solar_const / rv**2) * np.sin(deg2rad * z) sorad[z < 0] = 0 return (z, sorad) def dataqc_propagateflags_wrapper(strict_validation=False, *args): ''' This is a function that wraps dataqc_propagateflags for use in ION It accepts a variable number of vector arguments (of the same shape) and calls dataqc_propagateflags ''' if not strict_validation: shapes = np.array([i.shape[0] for i in args]) if not (shapes == shapes[0]).all(): raise ValueError('Input vectors are not the same shape') return dataqc_propagateflags(np.array(args), strict_validation=strict_validation) def dataqc_propagateflags(inflags, strict_validation=False): """ Description: Propagate "bad" qc flags (from an arbitrary number of source datasets) to another (derived) dataset. Consider data from an oceanographic CTD (conductivity, temperature, and pressure) instrument. From these three time series, you want to compute salinity. If any of the three source data (conductivity, temperature, pressure) is of bad quality, the salinity will be bad as well. You can feed your QC assessment of the former three into this routine, which will then give you the combined assessment for the derived (here: salinity) property. Implemented by: 2012-07-17: DPS authored by Mathias Lankhorst. Example code provided for Matlab. 2013-04-06: Christopher Wingard. Initial python implementation. Usage: outflag = dataqc_propagateflags(inflags) where outflag = a 1-by-N boolean vector that contains 1 where all of the inflags are 1, and 0 otherwise. inflags = an M-by-N boolean matrix, where each of the M rows contains flags of an independent data set such that "0" means bad data and "1" means good data. References: OOI (2012). Data Product Specification for Combined QC Flags. Document Control Number 1341-100012. https://alfresco.oceanobservatories.org/ (See: Company Home >> OOI >> Controlled >> 1000 System Level >> 1341-10012_Data_Product_SPEC_CMBNFLG_OOI.pdf) """ if strict_validation: if not utils.islogical(inflags): raise ValueError('\'inflags\' must be \'0\' or \'1\' ' 'integer flag array') array_size = inflags.shape nrows = array_size[0] if nrows < 2: error('\'inflags\' must be at least a two-dimensional array') outflag = np.all(inflags, 0) return outflag.astype('int8') def dataqc_condcompress(p_orig, p_new, c_orig, cpcor=-9.57e-8): """ Description: Implementation of the Sea-Bird conductivity compressibility correction, scaling the input conductivity based on ratio of the original pressure and the updated pressure. Implemented by: 2013-04-07: Christopher Wingard. Initial python implementation. Usage: c_new = dataqc_condcompress(p_orig, p_new, c_orig, cpcor) where c_new = updated conductivity record [S/m] p_orig = original pressure used to calculate original conductivity, this typically the L1a PRESWAT [dbar] p_new = updated pressure, typically L1b PRESWAT [dbar] c_orig = original conductivty record, typically L1a CONDWAT [S/m] cpcor = pressure correction coefficient used to calculate original conductivity, default is -9.57e-8 References: OOI (2012). Data Product Specification for Conductivity Compressibility Correction. Document Control Number 1341-10030. https://alfresco.oceanobservatories.org/ (See: Company Home >> OOI >> Controlled >> 1000 System Level >> 1341-10030_Data_Product_SPEC_CNDCMPR_OOI.pdf) """ c_new = c_orig * (1 + cpcor * p_orig) / (1 + cpcor * p_new) return c_new
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 37811, 198, 31, 26495, 22088, 62, 12543, 2733, 13, 80, 66, 62, 12543, 2733, 198, 31, 7753, 22088, 62, 12543, 2733, 14, 80, 66, 62, 12543, 2733, 13, 9078, 198, 31, 9800, 12803, ...
2.424337
13,091
"""Backward compatibility for version 0.8 API.""" from __future__ import absolute_import import inspect import datatest from datatest._compatibility import itertools from datatest._compatibility.collections.abc import Sequence from datatest._load.get_reader import get_reader from datatest._load.load_csv import load_csv from datatest._load.temptable import load_data from datatest._load.temptable import new_table_name from datatest._load.temptable import savepoint from datatest._load.temptable import table_exists from datatest._query.query import DEFAULT_CONNECTION from datatest._query.query import BaseElement from datatest._utils import file_types from datatest._utils import string_types from datatest._utils import iterpeek from datatest.allowance import BaseAllowance from datatest import Invalid from datatest.difference import NOTFOUND datatest.DataResult = datatest.Result datatest.DataQuery = DataQuery datatest.DataSource = DataSource datatest.allowed_key = allowed_key datatest.allowed_args = allowed_args datatest.DataTestCase.subject = property(get_subject, set_subject) datatest.DataTestCase.reference = property(get_reference, set_reference) datatest.DataTestCase._find_data_source = staticmethod(_find_data_source) def allowedKey(self, function, msg=None): """Allows differences in a mapping where *function* returns True. For each difference, function will receive the associated mapping **key** unpacked into one or more arguments. """ return allowed_key(function, msg) datatest.DataTestCase.allowedKey = allowedKey def allowedArgs(self, function, msg=None): """Allows differences where *function* returns True. For the 'args' attribute of each difference (a tuple), *function* must accept the number of arguments unpacked from 'args'. """ return allowed_args(function, msg) datatest.DataTestCase.allowedArgs = allowedArgs def _require_sequence(data, sequence): # New behavior in datatest 0.8.3 """Compare *data* against a *sequence* of values. Stops at the first difference found and returns an AssertionError. If no differences are found, returns None. """ if isinstance(data, str): raise ValueError("uncomparable types: 'str' and sequence type") data_type = getattr(data, 'evaluation_type', data.__class__) if not issubclass(data_type, Sequence): type_name = data_type.__name__ msg = "expected sequence type, but got " + repr(type_name) raise ValueError(msg) message_prefix = None previous_element = NOTFOUND zipped = itertools.zip_longest(data, sequence, fillvalue=NOTFOUND) for index, (actual, expected) in enumerate(zipped): if actual == expected: previous_element = actual continue if actual == NOTFOUND: message_prefix = ('Data sequence is missing ' 'elements starting with index {0}').format(index) message_suffix = 'Expected {0!r}'.format(expected) elif expected == NOTFOUND: message_prefix = ('Data sequence contains extra ' 'elements starting with index {0}').format(index) message_suffix = 'Found {0!r}'.format(actual) else: message_prefix = \ 'Data sequence differs starting at index {0}'.format(index) message_suffix = \ 'Found {0!r}, expected {1!r}'.format(actual, expected) break else: # <- NOBREAK! return None # <- EXIT! leading_elements = [] if index > 1: leading_elements.append('...') if previous_element != NOTFOUND: leading_elements.append(repr(previous_element)) actual_repr = repr(actual) if actual != NOTFOUND else '?????' caret_underline = '^' * len(actual_repr) trailing_elements = [] next_tuple = next(zipped, NOTFOUND) if next_tuple != NOTFOUND: trailing_elements.append(repr(next_tuple[0])) if next(zipped, NOTFOUND) != NOTFOUND: trailing_elements.append('...') if leading_elements: leading_string = ', '.join(leading_elements) + ', ' else: leading_string = '' leading_whitespace = ' ' * len(leading_string) if trailing_elements: trailing_string = ', ' + ', '.join(trailing_elements) else: trailing_string = '' sequence_string = leading_string + actual_repr + trailing_string message = '{0}:\n\n {1}\n {2}{3}\n{4}'.format(message_prefix, sequence_string, leading_whitespace, caret_underline, message_suffix) return AssertionError(message) datatest.validation._require_sequence = _require_sequence
[ 37811, 7282, 904, 17764, 329, 2196, 657, 13, 23, 7824, 526, 15931, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 11748, 10104, 198, 198, 11748, 4818, 265, 395, 198, 6738, 4818, 265, 395, 13557, 5589, 25901, 1330, 340, 861, ...
2.544508
1,921
# Copyright 2008 Owen Taylor # # This file is part of Reinteract and distributed under the terms # of the BSD license. See the file COPYING in the Reinteract # distribution for full details. # ######################################################################## import os import gobject import gtk import pango from application import application from format_escaped import format_escaped from notebook import NotebookFile from shell_buffer import ShellBuffer from shell_view import ShellView from save_file import SaveFileBuilder
[ 2, 15069, 3648, 22605, 8121, 198, 2, 198, 2, 770, 2393, 318, 636, 286, 797, 3849, 529, 290, 9387, 739, 262, 2846, 198, 2, 286, 262, 347, 10305, 5964, 13, 4091, 262, 2393, 27975, 45761, 287, 262, 797, 3849, 529, 198, 2, 6082, 329, ...
4.483333
120
""" This script compares events from two ETLs to highlight differences in elapsed times or row counts. * Pre-requisites You need to have a list of events for each ETL. Arthur can provide this using the "query_events" command. For example: ``` arthur.py query_events -p development 37ACEC7440AB4620 -q > 37ACEC7440AB4620.events arthur.py query_events -p development 96BE11B234F84F39 -q > 96BE11B234F84F39.events ``` * Usage Once you have the files, you use this script: ``` compare_events.py 37ACEC7440AB4620.events 96BE11B234F84F39.events ``` The order of those two files is: "older ETL" => "newer ETL". """ import csv import re import sys from collections import defaultdict, namedtuple from math import isclose from tabulate import tabulate def extract_values(filename): """Find elapsed time and rowcount for each target relation.""" # The "lambda: None" trick allows us to use 'd[]' instead of 'd.get()' later. elapsed = defaultdict(lambda: None) rowcount = defaultdict(lambda: None) for row in parse_file(filename): elapsed[row.step, row.target] = float(row.elapsed) if row.elapsed != "---" else None rowcount[row.step, row.target] = int(row.rowcount) if row.rowcount != "---" else None return elapsed, rowcount def delta(a, b): """ Return change in percent (or None if undefined). The delta in percent is rounded to one decimal. """ if a is None or b is None: return None if a == 0.0 and b == 0.0: return 0.0 assert a != 0.0 and b != 0.0 return round((b - a) * 1000.0 / a) / 10.0 def show_delta(previous_value, current_value, column): """ Return whether the change from previous event to current event is "significant". If the values appear to be equal or almost equal, there's no need to report a delta. Also, if the values are really small and any change is inflated, skip reporting the delta. Note that for row count, a decrease in rows is always shown. """ if previous_value is None or current_value is None: return False if previous_value == current_value: return False if column == "elapsed": # Decrease trigger-happiness for quick loads: if previous_value < 10.0 and current_value < 10.0: return False if previous_value < 30.0 or current_value < 30.0: return not isclose(previous_value, current_value, abs_tol=20.0) if previous_value < 60.0 or current_value < 60.0: return not isclose(previous_value, current_value, rel_tol=0.5) if previous_value < 300.0 or current_value < 300.0: return not isclose(previous_value, current_value, rel_tol=0.2) if column == "rowcount": # We expect to move forward with growing tables so smaller row counts are suspect. if previous_value > current_value: return True # Increase trigger-happiness for small (dimensional) tables: if previous_value < 1000 or current_value < 1000: return not isclose(previous_value, current_value, abs_tol=10) return not isclose(previous_value, current_value, rel_tol=0.1) def print_comparison_table(previous_values, current_values, column): """Print differences between runs, sorted by relation.""" all_events = frozenset(previous_values).union(current_values) has_large_diff = frozenset( event for event in all_events if show_delta(previous_values[event], current_values[event], column) ) table = sorted( ( ( event[1], # target event[0], # step previous_values[event], current_values[event], delta(previous_values[event], current_values[event]), ) for event in has_large_diff ), key=lambda row: row[:2], # Avoid comparison with None values in the columns ) print("Differences for '{}':\n".format(column)) print( tabulate( table, headers=("target", "step", "prev. " + column, "cur. " + column, "delta %"), tablefmt="presto", ) ) def main(): if len(sys.argv) >= 2 and sys.argv[1] in ("-h", "--help"): print(__doc__) sys.exit(0) if len(sys.argv) != 3: print( "Usage: {prog} previous_events current_events".format(prog=sys.argv[0]), file=sys.stderr, ) sys.exit(1) previous_events_file, current_events_file = sys.argv[1:3] previous_elapsed, previous_rowcount = extract_values(previous_events_file) current_elapsed, current_rowcount = extract_values(current_events_file) print_comparison_table(previous_elapsed, current_elapsed, "elapsed") print() print_comparison_table(previous_rowcount, current_rowcount, "rowcount") if __name__ == "__main__": main()
[ 37811, 198, 1212, 4226, 23008, 2995, 422, 734, 12152, 43, 82, 284, 7238, 5400, 287, 42118, 1661, 393, 5752, 9853, 13, 198, 198, 9, 3771, 12, 34075, 198, 198, 1639, 761, 284, 423, 257, 1351, 286, 2995, 329, 1123, 12152, 43, 13, 13514...
2.51928
1,945
# Augur: A Step Towards Realistic Drift Detection in Production MLSystems - Code # Copyright 2022 Carnegie Mellon University. # # NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. # # Released under a MIT (SEI)-style license, please see license.txt or contact permission@sei.cmu.edu for full terms. # # [DISTRIBUTION STATEMENT A] This material has been approved for public release and unlimited distribution. Please see Copyright notice for non-US Government use and distribution. # # Carnegie Mellon is registered in the U.S. Patent and Trademark Office by Carnegie Mellon University. # # This Software includes and/or makes use of the following Third-Party Software subject to its own license: # 1. Tensorflow (https://github.com/tensorflow/tensorflow/blob/master/LICENSE) Copyright 2014 The Regents of the University of California. # 2. Pandas (https://github.com/pandas-dev/pandas/blob/main/LICENSE) Copyright 2021 AQR Capital Management, LLC, Lambda Foundry, Inc. and PyData Development Team, and open source contributors. # 3. scikit-learn (https://github.com/scikit-learn/scikit-learn/blob/main/COPYING) Copyright 2021 The scikit-learn developers. # 4. numpy (https://github.com/numpy/numpy/blob/main/LICENSE.txt) Copyright 2021 NumPy Developers. # 5. scipy (https://github.com/scipy/scipy/blob/main/LICENSE.txt) Copyright 2021 SciPy Developers. # 6. statsmodels (https://github.com/statsmodels/statsmodels/blob/main/LICENSE.txt) Copyright 2018 Jonathan E. Taylor, Scipy developers, statsmodels Developers. # 7. matplotlib (https://github.com/matplotlib/matplotlib/blob/main/LICENSE/LICENSE) Copyright 2016 Matplotlib development team. # # DM22-0044 import shutil from drift import drift_generator from utils import arguments from utils.config import Config from utils import logging from datasets import dataset LOG_FILE_NAME = "drifter.log" DEFAULT_CONFIG_FILENAME = "./drifter_config.json" DRIFT_EXP_CONFIG_FOLDER = "../experiments/drifter" def load_dataset(dataset_filename, dataset_class_name): """Load dataset to drift.""" dataset_class = dataset.load_dataset_class(dataset_class_name) base_dataset = dataset_class() base_dataset.load_from_file(dataset_filename) return base_dataset if __name__ == '__main__': main()
[ 2, 2447, 333, 25, 317, 5012, 49953, 6416, 2569, 39819, 46254, 287, 19174, 13981, 6781, 82, 532, 6127, 201, 198, 2, 15069, 33160, 33976, 49808, 2059, 13, 198, 2, 220, 201, 198, 2, 8005, 34764, 56, 13, 12680, 17368, 45, 7156, 10008, 1...
3.149083
872
SURVEY_POST = { 'tags': [' '], 'description': ' ', 'parameters': [ { 'name': 'Authorization', 'description': 'JWT Token', 'in': 'header', 'type': 'str', 'required': True }, { 'name': 'title', 'description': ' ', 'in': 'formData', 'type': 'str', 'required': True }, { 'name': 'start_date', 'description': ' (YYYY-MM-DD)', 'in': 'formData', 'type': 'str', 'required': True }, { 'name': 'end_date', 'description': ' (YYYY-MM-DD)', 'in': 'formData', 'type': 'str', 'required': True }, { 'name': 'target', 'description': ' ', 'in': 'formData', 'type': 'list', 'required': True } ], 'responses': { '201': { 'description': ' ' }, '403': { 'description': ' ' } } } QUESTION_POST = { 'tags': [' '], 'description': ' ', 'parameters': [ { 'name': 'Authorization', 'description': 'JWT Token', 'in': 'header', 'type': 'str', 'required': True }, { 'name': 'id', 'description': ' ID', 'in': 'formData', 'type': 'str', 'required': True }, { 'name': 'title', 'description': ' ', 'in': 'formData', 'type': 'str', 'required': True }, { 'name': 'is_objective', 'description': ' ', 'in': 'formData', 'type': 'bool', 'required': True }, { 'name': 'choice_paper', 'description': ' ', 'in': 'formData', 'type': 'list', 'required': False } ], 'responses': { '201': { 'description': ' ' }, '403': { 'description': ' ' } } }
[ 50, 4261, 6089, 56, 62, 32782, 796, 1391, 198, 220, 220, 220, 705, 31499, 10354, 37250, 705, 4357, 198, 220, 220, 220, 705, 11213, 10354, 705, 46083, 198, 220, 220, 220, 705, 17143, 7307, 10354, 685, 198, 220, 220, 220, 220, 220, 22...
1.630499
1,364
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import math from functools import partial import logging import os try: from . import initializer from .utils import load_state except: import initializer from utils import load_state __all__ = ['ResNeXt', 'resnet50', 'resnet101'] def get_fine_tuning_parameters(model, ft_begin_index): if ft_begin_index == 0: return model.parameters() ft_module_names = [] for i in range(ft_begin_index, 5): ft_module_names.append('layer{}'.format(i)) ft_module_names.append('fc') parameters = [] for k, v in model.named_parameters(): for ft_module in ft_module_names: if ft_module in k: parameters.append({'params': v}) break else: parameters.append({'params': v, 'lr': 0.0}) return parameters def RESNET101(**kwargs): """Constructs a ResNet-50 model. """ model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs) return model if __name__ == "__main__": import torch logging.getLogger().setLevel(logging.DEBUG) # --------- net1 = RESNET101(num_classes=11, pretrained=True) data = torch.randn(1,3,16,224,224) output1 = net1(data) print (output1.shape)
[ 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 198, 6738, 28034, 13, 2306, 519, 6335, 1330, 35748, 198, 11748, 10688, 198, 6738, 1257, 310, 10141, 1330, 13027, 198, 11748, 18...
2.424908
546
import pytest from inference_logic import Rule, Variable, search from inference_logic.data_structures import Assert, Assign
[ 11748, 12972, 9288, 198, 198, 6738, 32278, 62, 6404, 291, 1330, 14330, 11, 35748, 11, 2989, 198, 6738, 32278, 62, 6404, 291, 13, 7890, 62, 7249, 942, 1330, 2195, 861, 11, 2195, 570, 628 ]
3.705882
34
#!/usr/bin/env python # # Copyright 2015 Airbus # Copyright 2017 Fraunhofer Institute for Manufacturing Engineering and Automation (IPA) # # 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 rospy import os import sys import threading from roslib.packages import get_pkg_dir from python_qt_binding.QtGui import * from python_qt_binding.QtCore import * from python_qt_binding import loadUi from airbus_cobot_gui.res import R from diagnostic_msgs.msg import DiagnosticArray, DiagnosticStatus from airbus_pyqt_extend.QtAgiGui import QAgiPopup from rqt_robot_monitor.status_item import StatusItem import rqt_robot_monitor.util_robot_monitor as util ## @class DiagnosticsStatus ## @brief Class for difine different control status. #OK = 0 #WARN = 1 #ERROR = 2 #STALE = 3 if __name__ == "__main__": from airbus_cobot_gui.context import Context app = QApplication(sys.argv) main = QMainWindow() main.setCentralWidget(TranslatorUi(Context(main))) main.show() app.exec_() #End of file
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 198, 2, 15069, 1853, 39173, 198, 2, 15069, 2177, 39313, 403, 71, 30288, 5136, 329, 32760, 14044, 290, 17406, 341, 357, 4061, 32, 8, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, ...
3.181053
475
from flask_wtf import FlaskForm from wtforms import SubmitField, TextAreaField from wtforms.validators import DataRequired
[ 6738, 42903, 62, 86, 27110, 1330, 46947, 8479, 198, 6738, 266, 83, 23914, 1330, 39900, 15878, 11, 8255, 30547, 15878, 198, 6738, 266, 83, 23914, 13, 12102, 2024, 1330, 6060, 37374, 628 ]
3.875
32
import numpy as np from ..transform import DenseTransform from ..decorators import multiple from ..transform import Transform __all__ = ['onehot', 'Onehot']
[ 11748, 299, 32152, 355, 45941, 201, 198, 201, 198, 6738, 11485, 35636, 1330, 360, 1072, 41762, 201, 198, 6738, 11485, 12501, 273, 2024, 1330, 3294, 201, 198, 6738, 11485, 35636, 1330, 26981, 201, 198, 201, 198, 834, 439, 834, 796, 37250...
3.148148
54
"""Handles data storage for Users, rides and requests """ # pylint: disable=E1101 import datetime from flask import make_response, jsonify, current_app from werkzeug.security import generate_password_hash import psycopg2 import config from databasesetup import db
[ 37811, 12885, 829, 1366, 6143, 329, 18987, 11, 17445, 290, 7007, 198, 37811, 198, 2, 279, 2645, 600, 25, 15560, 28, 36, 1157, 486, 198, 11748, 4818, 8079, 198, 198, 6738, 42903, 1330, 787, 62, 26209, 11, 33918, 1958, 11, 1459, 62, 1...
3.573333
75
import configparser ''' config = configparser.ConfigParser() config.read('db.ini') print(config.sections()) print(dict(config['mysqld'])['symbolic-links']) ''' result, ok = ReadConfig('db.ini', 'mysqld', 'socket') print(ok) print(result) if __name__ == '__main__': ReadConfig('db.ini','mysqld','socket')
[ 11748, 4566, 48610, 198, 7061, 6, 198, 11250, 796, 4566, 48610, 13, 16934, 46677, 3419, 628, 198, 11250, 13, 961, 10786, 9945, 13, 5362, 11537, 198, 4798, 7, 11250, 13, 23946, 28955, 198, 198, 4798, 7, 11600, 7, 11250, 17816, 28744, 8...
2.698276
116
# -*- coding: utf-8 -*- # --------------------------------------------------------------------- # Forms wrapper # --------------------------------------------------------------------- # Copyright (C) 2007-2019 The NOC Project # See LICENSE for details # --------------------------------------------------------------------- # Third-party modules import six from django import forms from django.utils.encoding import force_unicode from django.utils.html import escape
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 16529, 30934, 198, 2, 39196, 29908, 198, 2, 16529, 30934, 198, 2, 15069, 357, 34, 8, 4343, 12, 23344, 383, 399, 4503, 4935, 198, 2, 4091, 38559, 24290, 329, 3307, ...
5.164835
91
import json from django.shortcuts import get_object_or_404 from django.core import serializers from django.http import HttpResponse from .models import Unit from .utils import UNIT_LIST_FIELD BAD_REQUEST = HttpResponse(json.dumps({'error': 'Bad Request'}), status=400, content_type='application/json') def unit_json_list(request): ''' List Json View for local available units ''' if request.is_ajax(): units = Unit.objects.available_units() data = serializers.serialize('json', list(units), fields=UNIT_LIST_FIELD) _raw_data = json.loads(data) for unit in _raw_data: if unit['fields']['is_alliance']: unit['fields'].update({'identifier': '{}{}'.format(unit['fields']['identifier'],' (Alianza)')}) else: continue return HttpResponse(json.dumps(_raw_data), content_type='application/json', status=200) else: return BAD_REQUEST def detail_unit_json(request, id_unit): ''' Detail view of unit ''' if request.is_ajax(): unit = Unit.objects.filter(pk=id_unit) if len(unit) == 0: return HttpResponse(json.dumps({'error': 'Unidad no encontrada'}), status=404, content_type='application/json') data = serializers.serialize('json', unit, fields=UNIT_LIST_FIELD) # Add crew list _raw_data = json.loads(data) _raw_data[0]['fields'].update({ 'crew_list' : unit.first().get_crew_list }) return HttpResponse(json.dumps(_raw_data), content_type='application/json', status=200) else: return BAD_REQUEST def alliance_unit_json_list(request): ''' List Json View for alliance available units ''' if request.is_ajax(): units = Unit.objects.available_alliance_units() data = serializers.serialize('json', list(units), fields=UNIT_LIST_FIELD) return HttpResponse(data, content_type='application/json', status=200) else: return BAD_REQUEST
[ 11748, 33918, 198, 6738, 42625, 14208, 13, 19509, 23779, 1330, 651, 62, 15252, 62, 273, 62, 26429, 198, 6738, 42625, 14208, 13, 7295, 1330, 11389, 11341, 198, 6738, 42625, 14208, 13, 4023, 1330, 367, 29281, 31077, 198, 6738, 764, 27530, ...
2.45679
810
''' ex029: Escreva um programa que leia a velocidade de uma carro. Se ele ultrapassar 80 km/h, mostre uma mensagem dizendo que ele foi multado. A multa vai custar R$ 7,00 por cada Km acima do limite. ''' from colorise import set_color, reset_color cor = { 'limpa':'\033[m', 'white':'\033[1;97m' } set_color(fg='green') velocidade_carro = int(input('Informe a velocidade do carro KM/H: ')) if velocidade_carro > 80: multa = (velocidade_carro - 80) * 7.00 print('\nMULTADO! VOC ULTRAPASSOU O LIMITE PERMITIDO. LOGO TER QUE PAGAR ', end='') reset_color() print('{}R${:.2f}{}'.format(cor['white'], multa, cor['limpa'])) else: set_color(fg='green') print('\nCONTINUE ASSIM. DIRIGINDO COM SEGURANA!')
[ 7061, 6, 198, 1069, 48891, 25, 16319, 260, 6862, 23781, 1430, 64, 8358, 443, 544, 257, 11555, 420, 312, 671, 390, 334, 2611, 1097, 305, 13, 1001, 9766, 3789, 2416, 562, 283, 4019, 10571, 14, 71, 11, 749, 260, 334, 2611, 285, 641, ...
2.2263
327
#!/usr/bin/env python3.4 # coding: utf-8
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 13, 19, 198, 2, 19617, 25, 3384, 69, 12, 23, 628 ]
2.1
20
# -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function import os from django.conf import settings from django.shortcuts import reverse from django.core.management import call_command import test from dataops import pandas_db from workflow.models import Workflow
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 11, 3601, 62, 8818, 198, 198, 11748, 28686, 198, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 4...
3.464286
84
from attrdict import AttrDefault import asyncio def current_distance(self): return self.current_step / self.milli_meter_step_count def _get_step_instructions(self): return self._step_instructions[self._step_type]
[ 6738, 708, 4372, 713, 1330, 3460, 81, 19463, 198, 198, 11748, 30351, 952, 628, 220, 220, 220, 825, 1459, 62, 30246, 7, 944, 2599, 198, 220, 220, 220, 220, 220, 220, 220, 1441, 2116, 13, 14421, 62, 9662, 1220, 2116, 13, 17805, 72, ...
2.715909
88
input_num = raw_input() print(str(eval(input_num)))
[ 15414, 62, 22510, 796, 8246, 62, 15414, 3419, 198, 4798, 7, 2536, 7, 18206, 7, 15414, 62, 22510, 22305, 198 ]
2.6
20
from django.contrib import admin from django.db.models import Count from reversion.admin import VersionAdmin from website.apps.lexicon.models import Lexicon from website.apps.entry.models import Task, TaskLog, Wordlist, WordlistMember from website.apps.core.admin import TrackedModelAdmin admin.site.register(Task, TaskAdmin) admin.site.register(TaskLog, TaskLogAdmin) admin.site.register(Wordlist, TaskWordlistAdmin)
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 6738, 42625, 14208, 13, 9945, 13, 27530, 1330, 2764, 198, 6738, 302, 9641, 13, 28482, 1330, 10628, 46787, 198, 6738, 3052, 13, 18211, 13, 2588, 4749, 13, 27530, 1330, 17210, 4749, 198...
3.202899
138
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import re import sys sys.dont_write_bytecode = True from pprint import pprint from base import BaseFest2Bash
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 28686, 198, 11748, 302, 198, 11748, 25064, 198, 17597, 13, 67, 756, 62, 13564, 62, 26327, 8189, 796, ...
2.640625
64
#!/usr/bin/env python """ Srapyd control methods """ import logging from typing import Any, Dict, List from urllib.parse import urljoin from opennem.settings import settings from opennem.utils.http import http from opennem.utils.scrapy import get_spiders logger = logging.getLogger("scrapyd.client")
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 37811, 198, 50, 2416, 5173, 1630, 5050, 198, 198, 37811, 198, 11748, 18931, 198, 6738, 19720, 1330, 4377, 11, 360, 713, 11, 7343, 198, 6738, 2956, 297, 571, 13, 29572, 1330, 19016, 221...
3.111111
99
from abaqusConstants import * from .FailStrain import FailStrain from .FailStress import FailStress
[ 6738, 450, 30188, 385, 34184, 1187, 1330, 1635, 198, 6738, 764, 39044, 1273, 3201, 1330, 18448, 1273, 3201, 198, 6738, 764, 39044, 1273, 601, 1330, 18448, 1273, 601, 628 ]
3.482759
29
# setup.py for pyscrabble from distutils.core import setup try: import py2exe HAS_PY2EXE = True except ImportError: HAS_PY2EXE = False import glob import os import pkg_resources import sys from pyscrabble.constants import VERSION from pyscrabble import util from pyscrabble import dist kwargs = { 'name': 'pyscrabble', 'version': VERSION, 'author': 'Kevin Conaway', 'author_email': 'kevin.a.conaway@gmail.com', 'url': 'http://pyscrabble.sourceforge.net', 'data_files': dist.getDataFiles(), 'packages': ['pyscrabble', 'pyscrabble.command', 'pyscrabble.game', 'pyscrabble.gui', 'pyscrabble.net'] } if HAS_PY2EXE and 'py2exe' in sys.argv: #eggpacks = pkg_resources.require("nevow") #for egg in eggpacks: # if os.path.isdir(egg.location): # sys.path.insert(0, egg.location) try: import modulefinder import win32com for p in win32com.__path__[1:]: modulefinder.AddPackagePath("win32com",p) for extra in ["win32com.shell"]: __import__(extra) m = sys.modules[extra] for p in m.__path__[1:]: modulefinder.addPackagePath(extra, p) except ImportError: print 'import error' kwargs['py_modules'] = ['pyscrabble-main', 'server_console', 'db_upgrade'] kwargs['options'] = { "py2exe": { "packages": "encodings, nevow", "includes": "pango,atk,gobject,decimal,dumbdbm,dbhash,xml.sax.expatreader", "dll_excludes": ["iconv.dll","intl.dll","libatk-1.0-0.dll", "libgdk_pixbuf-2.0-0.dll","libgdk-win32-2.0-0.dll", "libglib-2.0-0.dll","libgmodule-2.0-0.dll", "libgobject-2.0-0.dll","libgthread-2.0-0.dll", "libgtk-win32-2.0-0.dll","libpango-1.0-0.dll", "libpangowin32-1.0-0.dll"], } } kwargs['windows'] = [{ "script": "pyscrabble-main.py", "icon_resources" : [(1, "resources/images/py.ico")] }] kwargs['console'] = [{ "script": "server_service.py", "icon_resources" : [(1, "resources/images/py.ico")] }, { "script": "server_console.py", "icon_resources" : [(1, "resources/images/py.ico")] }] kwargs['service'] = ['server_service'] kwargs['data_files'] += [('.', ['CHANGELOG.txt'])] kwargs['data_files'] += [('.', ['LICENSE.txt'])] #for egg in eggpacks: # kwargs['data_files'] += dist.getResourceDirs(egg.location, ensureLower=False, basePath=None, outdir='extra') else: kwargs['scripts'] = ['pyscrabble-main.py', 'server_console.py', 'db_upgrade.py'] kwargs['data_files'] = [fix_path(x) for x in kwargs['data_files']] kwargs['cmdclass'] = {'install_lib': dist.InstallLib, 'install_scripts' : dist.InstallScripts} setup(**kwargs)
[ 2, 9058, 13, 9078, 329, 279, 893, 6098, 397, 903, 201, 198, 6738, 1233, 26791, 13, 7295, 1330, 9058, 201, 198, 28311, 25, 201, 198, 220, 220, 220, 1330, 12972, 17, 13499, 201, 198, 220, 220, 220, 33930, 62, 47, 56, 17, 6369, 36, ...
1.984533
1,487
def integrate_exponential(a, x0, dt, T): """Compute solution of the differential equation xdot=a*x with initial condition x0 for a duration T. Use time step dt for numerical solution. Args: a (scalar): parameter of xdot (xdot=a*x) x0 (scalar): initial condition (x at time 0) dt (scalar): timestep of the simulation T (scalar): total duration of the simulation Returns: ndarray, ndarray: `x` for all simulation steps and the time `t` at each step """ # Initialize variables t = np.arange(0, T, dt) x = np.zeros_like(t, dtype=complex) x[0] = x0 # Step through system and integrate in time for k in range(1, len(t)): # for each point in time, compute xdot = a*x xdot = (a*x[k-1]) # update x by adding xdot scaled by dt x[k] = x[k-1] + xdot * dt return x, t # choose parameters a = -0.5 # parameter in f(x) T = 10 # total Time duration dt = 0.001 # timestep of our simulation x0 = 1. # initial condition of x at time 0 x, t = integrate_exponential(a, x0, dt, T) with plt.xkcd(): fig = plt.figure(figsize=(8, 6)) plt.plot(t, x.real) plt.xlabel('Time (s)') plt.ylabel('x')
[ 4299, 19386, 62, 11201, 35470, 7, 64, 11, 2124, 15, 11, 288, 83, 11, 309, 2599, 198, 220, 37227, 7293, 1133, 4610, 286, 262, 22577, 16022, 2124, 26518, 28, 64, 9, 87, 351, 220, 198, 220, 4238, 4006, 2124, 15, 329, 257, 9478, 309, ...
2.460888
473
import json import geojson import geopandas as gpd
[ 11748, 33918, 198, 11748, 4903, 13210, 1559, 198, 11748, 30324, 392, 292, 355, 27809, 67, 198, 220, 220, 220, 220, 220, 220, 220, 220 ]
2.458333
24
import requests import ssbio.utils import os.path as op # #### PDB stats # Request flexibility data about one particular PDB. # # http://pdbflex.org/php/api/PDBStats.php?pdbID=1a50&chainID=A # # pdbID of structure you are interested in # chainID of chain you are interested in # # [{"pdbID":"1a50", # "chainID":"A", # "parentClusterID":"4hn4A", # "avgRMSD":"0.538", # "maxRMSD":"2.616", # "flexibilityLabel":"Low", # "otherClusterMembers":["4hn4A","4hpjA","4hpxA","4kkxA",...], # "PDBFlexLink":"http:\/\/pdbflex.org\/cluster.html#!\/4hn4A\/20987\/1a50A"}] # # Note: you can omit the chainID and PDBFlex will return information for all chains. # # #### RMSD profile # Request RMSD array used for local flexibility plots # # http://pdbflex.org/php/api/rmsdProfile.php?pdbID=1a50&chainID=A # # pdbID PDB ID of structure you are interested in # chainID Chain ID of chain you are interested in # # {"queryPDB":"1a50A", # "clusterName":"4hn4A", # "profile":"[0.616,0.624,0.624,0.624,0.624,0.624,0.029,0.013,0.016,0.023,0.025,0.028,0.030,0.034,0.035,0.035,0.035,0.035,0.036,0.033,0.027,0.023,0.017...]"} # # #### PDB representatives # Request representatives for a PDB's own cluster. Returns a list of chains that represent the most distinct structures in the cluster. # # http://pdbflex.org/php/api/representatives.php?pdbID=1a50&chainID=A # # pdbID PDB ID of structure you are interested in # chainID Chain ID of chain you are interested in # # ["2trsA","3pr2A","1kfjA"]
[ 11748, 7007, 198, 11748, 264, 36299, 952, 13, 26791, 198, 11748, 28686, 13, 6978, 355, 1034, 628, 198, 2, 1303, 21017, 350, 11012, 9756, 198, 2, 19390, 13688, 1366, 546, 530, 1948, 350, 11012, 13, 198, 2, 198, 2, 2638, 1378, 79, 994...
2.324812
665
""" Modify Notes """ # pylint: disable=too-few-public-methods from ...mysql.mysql_connection import MySqlConnection from ...mysql.orm.autogen_entities import Task
[ 37811, 198, 3401, 1958, 11822, 198, 37811, 198, 2, 279, 2645, 600, 25, 15560, 28, 18820, 12, 32146, 12, 11377, 12, 24396, 82, 198, 6738, 2644, 28744, 13976, 13, 28744, 13976, 62, 38659, 1330, 2011, 50, 13976, 32048, 198, 6738, 2644, 2...
3.055556
54
# # This file is part of pyasn1 software. # # Copyright (c) 2005-2019, Ilya Etingof <etingof@gmail.com> # License: http://snmplabs.com/pyasn1/license.html # import sys try: import unittest2 as unittest except ImportError: import unittest from tests.base import BaseTestCase from pyasn1.type import namedval suite = unittest.TestLoader().loadTestsFromModule(sys.modules[__name__]) if __name__ == '__main__': unittest.TextTestRunner(verbosity=2).run(suite)
[ 2, 198, 2, 770, 2393, 318, 636, 286, 12972, 292, 77, 16, 3788, 13, 198, 2, 198, 2, 15069, 357, 66, 8, 5075, 12, 23344, 11, 49804, 64, 412, 889, 1659, 1279, 13629, 1659, 31, 14816, 13, 785, 29, 198, 2, 13789, 25, 2638, 1378, 16...
2.638889
180
#!/usr/bin/env python from setuptools import setup, find_packages from pymemcache import __version__ setup( name = 'pymemcache', version = __version__, author = 'Charles Gordon', author_email = 'charles@pinterest.com', packages = find_packages(), tests_require = ['nose>=1.0'], install_requires = ['six'], description = 'A comprehensive, fast, pure Python memcached client', long_description = open('README.md').read(), license = 'Apache License 2.0', url = 'https://github.com/Pinterest/pymemcache', classifiers = [ 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'License :: OSI Approved :: Apache Software License', 'Topic :: Database', ], )
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 198, 198, 6738, 279, 4948, 368, 23870, 1330, 11593, 9641, 834, 198, 198, 40406, 7, 198, 220, 220, 220, 1438, 796, 705, ...
2.72381
315
import torch from plyfile import PlyData from torch_geometric.data import Data
[ 11748, 28034, 198, 6738, 35960, 7753, 1330, 36526, 6601, 198, 6738, 28034, 62, 469, 16996, 13, 7890, 1330, 6060, 628 ]
4
20
from mlagents.trainers.brain import BrainInfo, BrainParameters, CameraResolution from mlagents.envs.base_env import BatchedStepResult, AgentGroupSpec from mlagents.envs.exception import UnityEnvironmentException import numpy as np from typing import List
[ 6738, 25962, 49638, 13, 27432, 364, 13, 27825, 1330, 14842, 12360, 11, 14842, 48944, 11, 20432, 4965, 2122, 198, 6738, 25962, 49638, 13, 268, 14259, 13, 8692, 62, 24330, 1330, 6577, 1740, 8600, 23004, 11, 15906, 13247, 22882, 198, 6738, ...
3.953846
65
from setuptools import find_packages, setup from glob import glob import os package_name = 'mrdc_serial' setup( name=package_name, version='1.0.0', packages=find_packages(), data_files=[ ('share/ament_index/resource_index/packages', ['resource/' + package_name]), ('share/' + package_name, ['package.xml']), (os.path.join('share', package_name, 'launch'), glob(os.path.join('launch', '*.xml'))) ], install_requires=['setuptools'], maintainer='Dylan Zemlin', maintainer_email='dylan.zemlin@gmail.com', description='The MRDC Serial package that controls communication to the arduino', license='MIT License', entry_points={ 'console_scripts': [ 'remote = mrdc_serial.remote:main', 'serial = mrdc_serial.serial:main' ], }, )
[ 6738, 900, 37623, 10141, 1330, 1064, 62, 43789, 11, 9058, 198, 6738, 15095, 1330, 15095, 198, 11748, 28686, 198, 198, 26495, 62, 3672, 796, 705, 76, 4372, 66, 62, 46911, 6, 198, 198, 40406, 7, 198, 220, 220, 220, 1438, 28, 26495, 62...
2.409605
354
from django.core.urlresolvers import reverse_lazy from django.views import generic from django.shortcuts import redirect, render from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from . import forms from . import models from custommixins import mixins
[ 6738, 42625, 14208, 13, 7295, 13, 6371, 411, 349, 690, 1330, 9575, 62, 75, 12582, 198, 6738, 42625, 14208, 13, 33571, 1330, 14276, 198, 6738, 42625, 14208, 13, 19509, 23779, 1330, 18941, 11, 8543, 198, 6738, 42625, 14208, 13, 4023, 1330...
3.666667
81
""" This file defines some simple experiments to illustrate how Pytorch-Routing functions. """ import numpy as np import tqdm import torch from PytorchRouting.DecisionLayers import REINFORCE, QLearning, SARSA, ActorCritic, GumbelSoftmax, PerTaskAssignment, \ WPL, AAC, AdvantageLearning, RELAX, EGreedyREINFORCE, EGreedyAAC from PytorchRouting.Examples.Models import PerTask_all_fc, RoutedAllFC, PerTask_1_fc, PerDecisionSingleAgent, \ Dispatched from PytorchRouting.Examples.Datasets import CIFAR100MTL if __name__ == '__main__': # MNIST # dataset = MNIST_MTL(64, data_files=['./Datasets/mnist.pkl.gz']) # model = PerTask_all_fc(1, 288, 2, dataset.num_tasks, dataset.num_tasks) # model = WPL_routed_all_fc(1, 288, 2, dataset.num_tasks, dataset.num_tasks) cuda = False # cuda = True # CIFAR dataset = CIFAR100MTL(10, data_files=['./Datasets/cifar-100-py/train', './Datasets/cifar-100-py/test'], cuda=cuda) model = RoutedAllFC(WPL, 3, 128, 5, dataset.num_tasks, dataset.num_tasks) # model = RoutedAllFC(RELAX, 3, 128, 5, dataset.num_tasks, dataset.num_tasks) # model = RoutedAllFC(EGreedyREINFORCE, 3, 128, 5, dataset.num_tasks, dataset.num_tasks) # model = RoutedAllFC(AdvantageLearning, 3, 128, 5, dataset.num_tasks, dataset.num_tasks) # model = PerDecisionSingleAgent(AdvantageLearning, 3, 128, 5, dataset.num_tasks, dataset.num_tasks) # model = Dispatched(AdvantageLearning, 3, 128, 5, dataset.num_tasks, dataset.num_tasks) learning_rates = {0: 3e-3, 5: 1e-3, 10: 3e-4} routing_module_learning_rate_ratio = 0.3 if cuda: model.cuda() run_experiment(model, dataset, learning_rates, routing_module_learning_rate_ratio) ''' WPL_routed_all_fc(3, 512, 5, dataset.num_tasks, dataset.num_tasks) Training averages: Model loss: 0.427, Routing loss: 8.864, Accuracy: 0.711 Testing averages: Model loss: 0.459, Routing loss: 9.446, Accuracy: 0.674 '''
[ 37811, 198, 1212, 2393, 15738, 617, 2829, 10256, 284, 19418, 703, 9485, 13165, 354, 12, 49, 13660, 5499, 13, 198, 37811, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 256, 80, 36020, 198, 11748, 28034, 198, 6738, 9485, 13165, 354, 49,...
2.473952
787
from output.models.ms_data.regex.re_g22_xsd.re_g22 import ( Regex, Doc, ) __all__ = [ "Regex", "Doc", ]
[ 6738, 5072, 13, 27530, 13, 907, 62, 7890, 13, 260, 25636, 13, 260, 62, 70, 1828, 62, 87, 21282, 13, 260, 62, 70, 1828, 1330, 357, 198, 220, 220, 220, 797, 25636, 11, 198, 220, 220, 220, 14432, 11, 198, 8, 198, 198, 834, 439, 8...
1.833333
66
#!/usr/bin/env python from skimage.color import rgb2gray from skimage.io import imread, imsave from scipy.misc import toimage import numpy as np import wrapper as wr ########################################################### # IMAGE IO ########################################################### def imload_rgb(path): """Load and return an RGB image in the range [0, 1].""" return imread(path) / 255.0 def save_img(image, imgname, use_JPEG=False): """Save image as either .jpeg or .png""" if use_JPEG: imsave(imgname+".JPEG", image) else: toimage(image, cmin=0.0, cmax=1.0).save(imgname+".png") ########################################################### # IMAGE MANIPULATION ########################################################### def adjust_contrast(image, contrast_level): """Return the image scaled to a certain contrast level in [0, 1]. parameters: - image: a numpy.ndarray - contrast_level: a scalar in [0, 1]; with 1 -> full contrast """ assert(contrast_level >= 0.0), "contrast_level too low." assert(contrast_level <= 1.0), "contrast_level too high." return (1-contrast_level)/2.0 + image.dot(contrast_level) def grayscale_contrast(image, contrast_level): """Convert to grayscale. Adjust contrast. parameters: - image: a numpy.ndarray - contrast_level: a scalar in [0, 1]; with 1 -> full contrast """ return adjust_contrast(rgb2gray(image), contrast_level) def uniform_noise(image, width, contrast_level, rng): """Convert to grayscale. Adjust contrast. Apply uniform noise. parameters: - image: a numpy.ndarray - width: a scalar indicating width of additive uniform noise -> then noise will be in range [-width, width] - contrast_level: a scalar in [0, 1]; with 1 -> full contrast - rng: a np.random.RandomState(seed=XYZ) to make it reproducible """ image = grayscale_contrast(image, contrast_level) return apply_uniform_noise(image, -width, width, rng) ########################################################### # HELPER FUNCTIONS ########################################################### def apply_uniform_noise(image, low, high, rng=None): """Apply uniform noise to an image, clip outside values to 0 and 1. parameters: - image: a numpy.ndarray - low: lower bound of noise within [low, high) - high: upper bound of noise within [low, high) - rng: a np.random.RandomState(seed=XYZ) to make it reproducible """ nrow = image.shape[0] ncol = image.shape[1] image = image + get_uniform_noise(low, high, nrow, ncol, rng) #clip values image = np.where(image < 0, 0, image) image = np.where(image > 1, 1, image) assert is_in_bounds(image, 0, 1), "values <0 or >1 occurred" return image def get_uniform_noise(low, high, nrow, ncol, rng=None): """Return uniform noise within [low, high) of size (nrow, ncol). parameters: - low: lower bound of noise within [low, high) - high: upper bound of noise within [low, high) - nrow: number of rows of desired noise - ncol: number of columns of desired noise - rng: a np.random.RandomState(seed=XYZ) to make it reproducible """ if rng is None: return np.random.uniform(low=low, high=high, size=(nrow, ncol)) else: return rng.uniform(low=low, high=high, size=(nrow, ncol)) def is_in_bounds(mat, low, high): """Return wether all values in 'mat' fall between low and high. parameters: - mat: a numpy.ndarray - low: lower bound (inclusive) - high: upper bound (inclusive) """ return np.all(np.logical_and(mat >= 0, mat <= 1)) def eidolon_partially_coherent_disarray(image, reach, coherence, grain): """Return parametrically distorted images (produced by Eidolon factory. For more information on the effect of different distortions, please have a look at the paper: Koenderink et al., JoV 2017, Eidolons: Novel stimuli for vision research). - image: a numpy.ndarray - reach: float, controlling the strength of the manipulation - coherence: a float within [0, 1] with 1 = full coherence - grain: float, controlling how fine-grained the distortion is """ return wr.partially_coherent_disarray(wr.data_to_pic(image), reach, coherence, grain) ########################################################### # MAIN METHOD FOR TESTING & DEMONSTRATION PURPOSES ########################################################### if __name__ == "__main__": print("""This main method should generate manipulated images in the directory where it was executed.""") use_JPEG = False # either JPEG or PNG img = imload_rgb("test_image.JPEG") ################################################### # A) Example for color-experiment: # - convert to grayscale ################################################### img_grayscale = rgb2gray(img) save_img(img_grayscale, "test_image_grayscale", use_JPEG) ################################################### # B) Example for contrast-experiment: # - convert to grayscale and # - reduce contrast to nominal contrast of 10% ################################################### contrast_level_1 = 0.1 img_low_contrast = grayscale_contrast(image=img, contrast_level=contrast_level_1) save_img(img_low_contrast, "test_image_low_contrast", use_JPEG) ################################################### # C) Example for noise-experiment: # - convert to graycale and # - reduce contrast to 30% and # - apply uniform noise with width 0.1 ################################################### noise_width = 0.1 contrast_level_2 = 0.3 rng = np.random.RandomState(seed=42) img_noisy = uniform_noise(image=img, width=noise_width, contrast_level=contrast_level_2, rng=rng) save_img(img_noisy, "test_image_noisy", use_JPEG) ################################################### # D) Example for eidolon-experiment: # - use partially_coherent_disarray ################################################### grain = 10.0 coherence = 1.0 reach = 8.0 img_eidolon = eidolon_partially_coherent_disarray(img, reach, coherence, grain) save_img(img_eidolon, "test_image_eidolon", use_JPEG)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 6738, 1341, 9060, 13, 8043, 1330, 46140, 17, 44605, 198, 6738, 1341, 9060, 13, 952, 1330, 545, 961, 11, 545, 21928, 198, 6738, 629, 541, 88, 13, 44374, 1330, 284, 9060, 198, 117...
2.728016
2,445
from django.db.models import fields from main.models import RoomReservation, UserRoom from django import forms from django.core.exceptions import ValidationError from django.contrib.auth import authenticate, login from django.contrib.auth import get_user_model
[ 6738, 42625, 14208, 13, 9945, 13, 27530, 1330, 7032, 198, 6738, 1388, 13, 27530, 1330, 10096, 4965, 13208, 11, 11787, 41178, 198, 6738, 42625, 14208, 1330, 5107, 198, 6738, 42625, 14208, 13, 7295, 13, 1069, 11755, 1330, 3254, 24765, 12331...
3.742857
70
""" Module to define various calculation types as Enums for VASP """ import datetime from itertools import groupby, product from pathlib import Path from typing import Dict, Iterator, List import bson import numpy as np from monty.json import MSONable from monty.serialization import loadfn from pydantic import BaseModel from pymatgen.analysis.structure_matcher import ElementComparator, StructureMatcher from pymatgen.core.structure import Structure from typing_extensions import Literal from emmet.core import SETTINGS from emmet.core.utils import ValueEnum _RUN_TYPE_DATA = loadfn(str(Path(__file__).parent.joinpath("run_types.yaml").resolve())) _TASK_TYPES = [ "NSCF Line", "NSCF Uniform", "Dielectric", "DFPT", "DFPT Dielectric", "NMR Nuclear Shielding", "NMR Electric Field Gradient", "Static", "Structure Optimization", "Deformation", ] _RUN_TYPES = ( [ rt for functional_class in _RUN_TYPE_DATA for rt in _RUN_TYPE_DATA[functional_class] ] + [ f"{rt}+U" for functional_class in _RUN_TYPE_DATA for rt in _RUN_TYPE_DATA[functional_class] ] + ["LDA", "LDA+U"] ) RunType = ValueEnum( # type: ignore "RunType", dict({"_".join(rt.split()).replace("+", "_"): rt for rt in _RUN_TYPES}) ) RunType.__doc__ = "VASP calculation run types" TaskType = ValueEnum("TaskType", {"_".join(tt.split()): tt for tt in _TASK_TYPES}) # type: ignore TaskType.__doc__ = "VASP calculation task types" CalcType = ValueEnum( # type: ignore "CalcType", { f"{'_'.join(rt.split()).replace('+','_')}_{'_'.join(tt.split())}": f"{rt} {tt}" for rt, tt in product(_RUN_TYPES, _TASK_TYPES) }, ) CalcType.__doc__ = "VASP calculation types" def run_type(parameters: Dict) -> RunType: """ Determines the run_type from the VASP parameters dict This is adapted from pymatgen to be far less unstable Args: parameters: Dictionary of VASP parameters from Vasprun.xml """ if parameters.get("LDAU", False): is_hubbard = "+U" else: is_hubbard = "" def _variant_equal(v1, v2) -> bool: """ helper function to deal with strings """ if isinstance(v1, str) and isinstance(v2, str): return v1.strip().upper() == v2.strip().upper() else: return v1 == v2 # This is to force an order of evaluation for functional_class in ["HF", "VDW", "METAGGA", "GGA"]: for special_type, params in _RUN_TYPE_DATA[functional_class].items(): if all( [ _variant_equal(parameters.get(param, None), value) for param, value in params.items() ] ): return RunType(f"{special_type}{is_hubbard}") return RunType(f"LDA{is_hubbard}") def task_type( inputs: Dict[Literal["incar", "poscar", "kpoints", "potcar"], Dict] ) -> TaskType: """ Determines the task type Args: inputs: inputs dict with an incar, kpoints, potcar, and poscar dictionaries """ calc_type = [] incar = inputs.get("incar", {}) if incar.get("ICHARG", 0) > 10: try: kpts = inputs.get("kpoints") or {} kpt_labels = kpts.get("labels") or [] num_kpt_labels = len(list(filter(None.__ne__, kpt_labels))) except Exception as e: raise Exception( "Couldn't identify total number of kpt labels: {}".format(e) ) if num_kpt_labels > 0: calc_type.append("NSCF Line") else: calc_type.append("NSCF Uniform") elif incar.get("LEPSILON", False): if incar.get("IBRION", 0) > 6: calc_type.append("DFPT") calc_type.append("Dielectric") elif incar.get("IBRION", 0) > 6: calc_type.append("DFPT") elif incar.get("LCHIMAG", False): calc_type.append("NMR Nuclear Shielding") elif incar.get("LEFG", False): calc_type.append("NMR Electric Field Gradient") elif incar.get("NSW", 1) == 0: calc_type.append("Static") elif incar.get("ISIF", 2) == 3 and incar.get("IBRION", 0) > 0: calc_type.append("Structure Optimization") elif incar.get("ISIF", 3) == 2 and incar.get("IBRION", 0) > 0: calc_type.append("Deformation") return TaskType(" ".join(calc_type)) def calc_type( inputs: Dict[Literal["incar", "poscar", "kpoints", "potcar"], Dict], parameters: Dict, ) -> CalcType: """ Determines the calc type Args: inputs: inputs dict with an incar, kpoints, potcar, and poscar dictionaries parameters: Dictionary of VASP parameters from Vasprun.xml """ rt = run_type(parameters).value tt = task_type(inputs).value return CalcType(f"{rt} {tt}")
[ 37811, 19937, 284, 8160, 2972, 17952, 3858, 355, 2039, 5700, 329, 569, 1921, 47, 37227, 198, 11748, 4818, 8079, 198, 6738, 340, 861, 10141, 1330, 1448, 1525, 11, 1720, 198, 6738, 3108, 8019, 1330, 10644, 198, 6738, 19720, 1330, 360, 713...
2.234238
2,173
from mono_left import MonoLeft from mono_right import MonoRight from mono_rear import MonoRear from stereo_left import StereoLeft from stereo_right import StereoRight from stereo_centre import StereoCentre
[ 198, 6738, 33361, 62, 9464, 1330, 34879, 18819, 198, 6738, 33361, 62, 3506, 1330, 34879, 11028, 198, 6738, 33361, 62, 260, 283, 1330, 34879, 49, 451, 198, 6738, 24820, 62, 9464, 1330, 520, 32934, 18819, 198, 6738, 24820, 62, 3506, 1330,...
3.696429
56
import sys import pandas as pd from sqlalchemy import create_engine import nltk nltk.download(['punkt', 'wordnet', 'averaged_perceptron_tagger']) import re from nltk.tokenize import word_tokenize from nltk.stem import WordNetLemmatizer from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import train_test_split from sklearn.pipeline import Pipeline, FeatureUnion from sklearn.base import BaseEstimator, TransformerMixin from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer import pickle from sklearn.model_selection import GridSearchCV def load_data(database_filepath): """ load data from sql db :param database_filepath: sql db path :return: pandas dataframe """ engine = create_engine("sqlite:///"+database_filepath) df = pd.read_sql_table('modeling_data', engine) yvar = [item for item in list(df) if item not in ['message', 'original', 'genre', 'id']] X = df['message'] Y = df[yvar] return X.values, Y.values, list(Y) def tokenize(text): """ processing the text input :param text: text inputs :return: """ url_regex = 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+' detected_urls = re.findall(url_regex, text) for url in detected_urls: text = text.replace(url, "urlplaceholder") tokens = word_tokenize(text) lemmatizer = WordNetLemmatizer() clean_tokens = [] for tok in tokens: clean_tok = lemmatizer.lemmatize(tok).lower().strip() clean_tokens.append(clean_tok) return clean_tokens def build_model(): """ build model pipeline :return: model pipeline """ model_pipeline = Pipeline([ ('features', Pipeline([ ('vect', CountVectorizer(tokenizer=tokenize)), ('tfidf', TfidfTransformer()) ])), ('clf', RandomForestClassifier()) ]) return model_pipeline def evaluate_model(model, X_test, Y_test, category_names): """ evaluate model performances :param model: model obj :param X_test: test x :param Y_test: test y :param category_names: y names :return: """ y_pred = model.predict(X_test) print(classification_report(Y_test, y_pred, target_names=category_names)) def save_model(model, model_filepath): """ save model to local path :param model: model obj :param model_filepath: saving path :return: """ with open(model_filepath, 'wb') as f: pickle.dump(model, f) def main(): """ CLI to fit the model :return: """ if len(sys.argv) == 3: database_filepath, model_filepath = sys.argv[1:] print('Loading data...\n DATABASE: {}'.format(database_filepath)) X, Y, category_names = load_data(database_filepath) X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2) print('Building model...') model = build_model() print('Training model...') # model.fit(X_train, Y_train) parameters = { 'clf__n_estimators': [100, 400, 800], # 'clf__criterion':["gini", "entropy"] } cv = model_gridsearch(model, parameters) best_model_pipeline = cv.best_estimator_ print('Evaluating model...') evaluate_model(best_model_pipeline, X_test, Y_test, category_names) print('Saving model...\n MODEL: {}'.format(model_filepath)) save_model(best_model_pipeline, model_filepath) print('Trained model saved!') else: print('Please provide the filepath of the disaster messages database '\ 'as the first argument and the filepath of the pickle file to '\ 'save the model to as the second argument. \n\nExample: python '\ 'train_classifier.py ../data/DisasterResponse.db classifier.pkl') if __name__ == '__main__': main()
[ 11748, 25064, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 44161, 282, 26599, 1330, 2251, 62, 18392, 198, 11748, 299, 2528, 74, 198, 77, 2528, 74, 13, 15002, 7, 17816, 30354, 83, 3256, 705, 4775, 3262, 3256, 705, 8770, 1886, 62, ...
2.40404
1,683
import os from datetime import date from django.conf import settings from django.core.mail import send_mail from django.template.loader import render_to_string from django.utils import translation from django.utils.translation import ugettext as _ from mailchimp3 import MailChimp def notify(subject, body='.'): send_mail(subject, body, 'damian@dymaxionlabs.com', ['monitor@dymaxionlabs.com'])
[ 11748, 28686, 198, 6738, 4818, 8079, 1330, 3128, 198, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 7295, 13, 4529, 1330, 3758, 62, 4529, 198, 6738, 42625, 14208, 13, 28243, 13, 29356, 1330, 8543, 62, 1462...
2.957746
142
# coding=utf-8 # Copyright 2019 The Edward2 Authors. # # 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. """Parses real and synthetic datasets. """ from __future__ import absolute_import from __future__ import division from __future__ import google_type_annotations from __future__ import print_function import collections import tensorflow as tf NPRegressionDescription = collections.namedtuple( "NPRegressionDescription", ("context_x", "context_y", "target_x", "target_y"))
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 15069, 13130, 383, 10443, 17, 46665, 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, ...
3.681648
267
from flask import Blueprint, render_template from flask_babel import format_number import critiquebrainz.db.users as db_users import critiquebrainz.db.review as db_review from bs4 import BeautifulSoup from markdown import markdown DEFAULT_CACHE_EXPIRATION = 10 * 60 # seconds frontend_bp = Blueprint('frontend', __name__)
[ 6738, 42903, 1330, 39932, 11, 8543, 62, 28243, 198, 6738, 42903, 62, 65, 9608, 1330, 5794, 62, 17618, 198, 11748, 19976, 27825, 89, 13, 9945, 13, 18417, 355, 20613, 62, 18417, 198, 11748, 19976, 27825, 89, 13, 9945, 13, 19023, 355, 20...
3.381443
97
import strawberryfields as sf from strawberryfields import ops from strawberryfields.utils import random_interferometer from strawberryfields.apps import data, sample, subgraph, plot import plotly import networkx as nx import numpy as np
[ 11748, 41236, 25747, 355, 264, 69, 198, 6738, 41236, 25747, 1330, 39628, 198, 6738, 41236, 25747, 13, 26791, 1330, 4738, 62, 3849, 2232, 15635, 198, 6738, 41236, 25747, 13, 18211, 1330, 1366, 11, 6291, 11, 850, 34960, 11, 7110, 198, 117...
4.175439
57
#!/usr/bin/env python # # Copyright (c) 2015-2017 Nest Labs, Inc. # All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ## # @file # Implements HappyNodeJoin class through which a virtual node join a network. # # When a node joins a network, an TAP interface is created in the node and in # the network. Then TUN is setup on the node. # import os import sys from happy.ReturnMsg import ReturnMsg from happy.Utils import * from happy.utils.IP import IP from happy.HappyLink import HappyLink from happy.HappyNetwork import HappyNetwork from happy.HappyNode import HappyNode import happy.HappyLinkAdd import happy.HappyNodeAddress import happy.HappyNodeRoute options = {} options["quiet"] = False options["node_id"] = None options["tap"] = False options["network_id"] = None options["fix_hw_addr"] = None options["customized_eui64"] = None
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 2, 198, 2, 220, 220, 220, 15069, 357, 66, 8, 1853, 12, 5539, 21420, 23500, 11, 3457, 13, 198, 2, 220, 220, 220, 1439, 2489, 10395, 13, 198, 2, 198, 2, 220, 220, 220, 49962, ...
3.245413
436
# -*- coding: utf-8 -*- """ Modules to support data reduction in Python. The main purpose of the base module ``Data_Reduction`` is to provide a suplerclass with a good set of attributes and methods to cover all common needs. The base module is also able to read data from a text file as a ``numpy`` structured array. This is done with a class called ``DataGetterMixin`` which must be invoked after the base class has been initiated. The module function ``examine_text_data_file()`` reveals the structure of the file(s) that provide the data.. Examples ======== Here we initiate a base class after mixing in the data getter. The first line o the file has column names but the first three columns are all under one name ``UTC`` so we specify column widths to consider the first three columns to be one column. We use the names from the first line of the file, which could have been done with an ``open()``, ``readline()``, and ``close()``:: mixIn(Observation, DataGetterMixin) obs = Observation(dss=28, date="2012/127", project="SolarPatrol") obs.open_datafile('t12127.10', delimiter=[17,16,3,11,7,9,8,2,6], skip_header=1, names="UTC Epoch Chan Tsys Int Az El Diode Level".split()) Now the data getter is already mixed in to Observation so we don't need to do it again. In this case we specify the names of the columns, changing ``Int`` to ``Integr``:: obs2 = Observation(dss=28, date="2012/127", project="SolarPatrol") obs2.open_datafile('t12127.10', skip_header=1, names="Year DOY UTC Epoch Chan Tsys Integr Az El Diode Level".split()) The class Map inherits from DataGetterMixin, so no explicit mixin required:: obsmap = Map(dss=84, date="2020/163", project="SolarPatrol") obsmap.initialize('sim-venus.dat', source="Venus") Let's examine ``obsmap``. We have only one signal column:: In [3]: obsmap.channel.keys() Out[3]: dict_keys(['xl']) In [4]: obsmap.channel['xl'].keys() Out[4]: dict_keys(['freq', 'bw', 'pol', 'ifmode', 'atten', 'power']) """ # standard Python modules import datetime import glob import h5py import logging import math import matplotlib.dates as MPLd import numpy as NP import os import re import readline import scipy.interpolate import scipy.fftpack import Astronomy as A import Astronomy.DSN_coordinates as coords import Astronomy.Ephem as AE import DatesTimes as DT import local_dirs import Math.clusters as VQ # vector quantization import support # enable raw_input Tab completion readline.parse_and_bind("tab: complete") logger = logging.getLogger(__name__) # module logger # ------------------------ module functions ------------------------------- def examine_text_data_file(filename): """ Examine a file to guide ``genfromtxt()`` Things to look for:: * Is there a header line with column names? If not, use argument ``names``. * Is the number of names equal to the number of columns? If not:: - use argument ``names`` and ``skip_header=1``, or - use argument ``delimiter`` with a list of column widths and ``skip_header=1``. """ print(examine_text_data_file.__doc__) fd = open(filename, "r") lines = fd.readlines() fd.close() topline = lines[0].strip().split() print(" 1 2 3 4 5 6 7") print("01234567890123456789012345678901234567890123456789012345678901234567890123456789") print(lines[0].strip()) print(lines[1].strip()) print(" ...") print(lines[-1].strip()) data = NP.genfromtxt(filename, dtype=None, names=None, skip_header=1, encoding=None) print("%d datatypes:" % len(data.dtype.fields)) for item in data.dtype.fields: print(item, data.dtype.fields[item]) def get_obs_dirs(project, station, year, DOY, datafmt=None): """ Returns the directories where data and working files are kept @param project : project code string, e.g., RRL @type project : str @param station : DSN station number @type station : int @param year : year of observation @type year : int @param DOY : day of year of observations @type DOY : int @param datafmt : raw data format @type datafmt : str """ #logger.debug("get_obs_dirs: type %s for %s, DSS%d, %4d/%03d", # datafmt, project, station, year, DOY) obspath = "dss%2d/%4d/%03d/" % (station,year,DOY) if project: projdatapath = "/usr/local/project_data/"+project+"/"+obspath projworkpath = "/usr/local/projects/"+project+"/Observations/"+obspath else: projdatapath = "" projworkpath = "" if datafmt: rawdatapath = "/usr/local/RA_data/"+datafmt+"/"+obspath else: rawdatapath = "" return projdatapath, projworkpath, rawdatapath # --------- old stuff to be discarded still needed for now --------------- def old_get_obs_session(project=None, dss=None, date=None, path='proj'): """ Provides project, station, year and DOY, asking as needed. It follows one of several possible paths to get to the session:: proj - path through /usr/local/projects/<project> hdf5 - path through /usr/local/RA_data/HDF5 fits - path through /usr/local/RA_data/FITS wvsr - path through /data @param project : optional name as defined in /usr/local/projects @type project : str @param dss : optional station number @type dss : int @param date : optional YYYY/DDD @type date : str @return: project, DSS, year, DOY. """ def get_directory(path): """ """ # only one trailing / path = path.rstrip('/')+"/*" logger.debug("get_obs_session:get_directory: from %s", path) names = glob.glob(path) if names: dirs = [] for name in names: if os.path.isdir(name): dirs.append(os.path.basename(name)) dirs.sort() for name in dirs: print((name), end=' ') return input('\n>') else: return [] def from_wvsr_dir(): """ this needs to be completed and tested on crab14 or an auto host """ session = get_directory(local_dirs.wvsr_dir) return session cwd = os.getcwd() # get the project if project: pass else: os.chdir(local_dirs.projects_dir) project = get_directory(local_dirs.projects_dir) logger.debug("from_wvsr_dir: project is %s", project) projectpath = local_dirs.projects_dir+project # get the station if path[:4].lower() == 'wvsr': # special call print("from_wvsr_dir()") if path[:4].lower() == 'proj': os.chdir(projectpath+"/Observations/") elif path[:4].lower() == 'hdf5': os.chdir(local_dirs.hdf5_dir) elif path[:4].lower() == 'fits': os.chdir(local_dirs.fits_dir) # get the station if dss: pass else: # This seems odd but get_directory() needs '/' and int does not station = get_directory(os.getcwd()+"/").rstrip('/') dss = int(station[-2:]) stationpath = os.getcwd()+"/dss"+str(dss) # get the date if date: items = date.split('/') year = int(items[0]) DOY = int(items[1]) else: year = int(get_directory(stationpath)) yearpath = stationpath+"/"+str(year) DOY = int(get_directory(yearpath)) os.chdir(cwd) return project, dss, year, DOY
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 5841, 5028, 284, 1104, 1366, 7741, 287, 11361, 13, 198, 198, 464, 1388, 4007, 286, 262, 2779, 8265, 7559, 6601, 62, 7738, 8110, 15506, 318, 284, 2148, 257, ...
2.575362
2,833
""" PyGRB. A GRB light-curve analysis package. """ __version__ = "0.0.5" __author__ = 'James Paynter' from . import backend from . import fetch from . import main from . import postprocess from . import preprocess
[ 37811, 198, 20519, 10761, 33, 13, 198, 198, 32, 10863, 33, 1657, 12, 22019, 303, 3781, 5301, 13, 198, 37811, 198, 198, 834, 9641, 834, 796, 366, 15, 13, 15, 13, 20, 1, 198, 834, 9800, 834, 220, 197, 28, 705, 14731, 7119, 77, 353...
2.92
75
import os from dotenv import load_dotenv load_dotenv()
[ 11748, 28686, 198, 6738, 16605, 24330, 1330, 3440, 62, 26518, 24330, 198, 2220, 62, 26518, 24330, 3419, 628 ]
3.111111
18
import numpy as np from wordreps import WordReps from algebra import cosine, normalize import tensorflow as tf import random from dataset import DataSet import CGRE_Model from Eval import eval_SemEval import sklearn.preprocessing # ============ End Imports ============ # ============ End of the Evaluation class ============ def next_batch(batchSize,data): # loop over our dataset in mini-batches of size `batchSize` for i in np.arange(0, len(data), batchSize): # yield the current batched data yield data[i:i + batchSize] # ------------------------------------------------------- # ------------------------------------------------------- # ----------------------------------------------------------- if __name__=="__main__": ''' Word Embeddings ''' pretrained_glove_300=("../glove.6B.300d.zip","glove",300) WR=WordReps() norm=1 standardise=0 WR.Read_Embeddings_zip_file(pretrained_glove_300,norm,standardise) WR.vects['<PAD>']=np.zeros(WR.dim) # WR.vects['X']=np.random.rand(WR.dim) # WR.vects['Y']=np.random.rand(WR.dim) WR.vects['X']=np.random.normal(size=(WR.dim)).astype('float32') WR.vects['Y']=np.random.normal(size=(WR.dim)).astype('float32') ''' Dataset ''' corpus='Wikipedia_English' Train_dataset=('DiffVec',"DiffVec_Pairs") Test_dataset=('SemEval',"SemEval_Pairs.txt") labels_type='proxy' Reverse_pairs=True DS=DataSet(corpus,Train_dataset,Test_dataset,labels_type,Reverse_pairs) id2Patterns="../Relational_Patterns/Patterns_Xmid5Y" Patterns_per_pair="../Relational_Patterns/Patterns_Xmid5Y_PerPair" DS.Retrieve_Patterns(id2Patterns,Patterns_per_pair) Ea=DS.Generate_Embedding_Matrix(WR) ''' Training & Evaluation ''' Eval=Training() Eval.Train_Model()
[ 11748, 299, 32152, 355, 45941, 220, 198, 6738, 1573, 260, 862, 1330, 9678, 6207, 82, 198, 6738, 37139, 1330, 8615, 500, 11, 3487, 1096, 198, 11748, 11192, 273, 11125, 355, 48700, 220, 198, 11748, 4738, 198, 6738, 27039, 1330, 6060, 7248...
2.656878
647
from radtrans_integrate import radtrans_integrate from polsynchemis import polsynchemis import numpy as np import scipy.integrate # calculate synchrotron emissivity for given coefficients
[ 6738, 2511, 7645, 62, 18908, 4873, 1330, 2511, 7645, 62, 18908, 4873, 198, 6738, 755, 28869, 15245, 271, 1330, 755, 28869, 15245, 271, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 629, 541, 88, 13, 18908, 4873, 198, 198, 2, 15284, ...
3.634615
52
""" Copyright 2016 Brocade Communications Systems, 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. """ from jinja2 import Template, Environment, StrictUndefined, UndefinedError, meta
[ 37811, 198, 15269, 1584, 2806, 46395, 14620, 11998, 11, 3457, 13, 198, 26656, 15385, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 5832, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, ...
3.976048
167
import os __all__ = ['DATA_FOLDER', 'load_data'] DATA_FOLDER = os.path.dirname(os.path.abspath(__file__)) def load_data(name): """ Loads an Excel form from the data folder with the specified name. Parameters ---------- name : str The name of the form without file extension. """ from ..lca_writer import LCAWriter # to prevent recursive import p = os.path.join(DATA_FOLDER, name + '.xlsx') return LCAWriter(p)
[ 11748, 28686, 198, 198, 834, 439, 834, 796, 37250, 26947, 62, 37, 3535, 14418, 3256, 705, 2220, 62, 7890, 20520, 628, 198, 26947, 62, 37, 3535, 14418, 796, 28686, 13, 6978, 13, 15908, 3672, 7, 418, 13, 6978, 13, 397, 2777, 776, 7, ...
2.634286
175
var = "Docker" print(f"Hello {var} world!")
[ 7785, 796, 366, 35, 12721, 1, 198, 198, 4798, 7, 69, 1, 15496, 1391, 7785, 92, 995, 2474, 8, 198 ]
2.25
20
""" Model mixin classes for auth, category and recipe modules """ from app import db # pylint: disable=C0103 # pylint: disable=E1101
[ 37811, 9104, 5022, 259, 6097, 329, 6284, 11, 6536, 290, 8364, 13103, 37227, 198, 198, 6738, 598, 1330, 20613, 198, 198, 2, 279, 2645, 600, 25, 15560, 28, 34, 486, 3070, 198, 2, 279, 2645, 600, 25, 15560, 28, 36, 1157, 486, 198 ]
3.139535
43
import dash_core_components as dcc import dash_html_components as html from config import strings def make_tab_port_map_controls( port_arr: list, port_val: str, vessel_types_arr: list, vessel_type_val: str, year_arr: list, year_val: int, month_arr: list, month_val: int, ) -> html.Div: """ Returns a HTML div of user controls found on top of the map tab. :param port_arr: list, all possible ports :param port_val: str, current port value :param vessel_types_arr: list, all possible vessel types :param vessel_type_val: str, current vessel type value :param year_arr: list, all possible years :param year_val: str, current year value :param month_arr: list, all possible months :param month_val: str, current month value :return: HTML div """ return html.Div( className="tab-port-map-controls", children=[ html.Div( className="tab-port-map-single-control-container area-a", children=[ html.Label( className="control-label", children=[strings.LABEL_PORT] ), dcc.Dropdown( id="port-map-dropdown-port", clearable=False, options=[{"label": port, "value": port} for port in port_arr], value=port_val, ), ], ), html.Div(className="tab-port-map-single-control-separator area-b"), html.Div( className="tab-port-map-single-control-container area-c", children=[ html.Label( className="control-label", children=[strings.LABEL_VESSEL] ), dcc.Dropdown( id="port-map-dropdown-vessel-type", clearable=False, options=[ {"label": vessel_type, "value": vessel_type} for vessel_type in vessel_types_arr ], value=vessel_type_val, ), ], ), html.Div(className="tab-port-map-single-control-separator area-d"), html.Div( className="tab-port-map-single-control-container date-grid area-e", children=[ html.Div( className="tab-port-map-single-control-container-date", children=[ html.Label( className="control-label", children=[strings.LABEL_YEAR] ), dcc.Dropdown( id="port-map-dropdown-year", clearable=False, options=[ {"label": year, "value": year} for year in year_arr ], value=year_val, ), ], ), html.Div( className="tab-port-map-single-control-separator smaller-line" ), html.Div( className="tab-port-map-single-control-container-date", children=[ html.Label( className="control-label", children=[strings.LABEL_MONTH], ), dcc.Dropdown( id="port-map-dropdown-month", clearable=False, options=[ {"label": month, "value": month} for month in month_arr ], value=month_val, ), ], ), ], ), ], )
[ 11748, 14470, 62, 7295, 62, 5589, 3906, 355, 288, 535, 198, 11748, 14470, 62, 6494, 62, 5589, 3906, 355, 27711, 198, 6738, 4566, 1330, 13042, 628, 198, 4299, 787, 62, 8658, 62, 634, 62, 8899, 62, 13716, 82, 7, 198, 220, 220, 220, ...
1.631012
2,599
from typing import List from subs2srs.core.preview_item import PreviewItem
[ 6738, 19720, 1330, 7343, 198, 6738, 6352, 17, 82, 3808, 13, 7295, 13, 3866, 1177, 62, 9186, 1330, 22217, 7449, 628, 198 ]
3.5
22
import sys sys.path.append("..") from src.sync_ends_service import SyncEnd from src.parser import Parser if __name__ == "__main__": main()
[ 11748, 25064, 198, 198, 17597, 13, 6978, 13, 33295, 7203, 492, 4943, 198, 198, 6738, 12351, 13, 27261, 62, 2412, 62, 15271, 1330, 35908, 12915, 198, 6738, 12351, 13, 48610, 1330, 23042, 263, 628, 198, 198, 361, 11593, 3672, 834, 6624, ...
2.792453
53
# Copyright 2018-present Kensho Technologies, LLC. """Workarounds for OrientDB scheduler issue that causes poor query planning for certain queries. For purposes of query planning, the OrientDB query planner ignores "where:" clauses that hit indexes but do not use the "=" operator. For example, "CONTAINS" can be used to check that a field covered by an index is in a specified list of values, and can therefore be covered by an index, but OrientDB will ignore this. When no equality ("=") checks on indexed columns are present, OrientDB will generate a query plan that starts execution at the class with lowest cardinality, which can lead to excessive numbers of scanned and discarded records. Assuming the query planner creates a query plan where a location with CONTAINS is the first in the execution order, the execution system will apply indexes to speed up this operation. Therefore, it's sufficient to trick the query planner into always creating such a query plan, even though it thinks indexes cannot be used in the query. Valid query execution start points for the OrientDB query planner must satisfy the following: - Must not be "optional: true". - Must not have a "while:" clause nor follow a location that has one. - Must have a "class:" defined. This class is used for cardinality estimation, and to look for available indexes that may cover any "where:" clause that may be present. The optimizations in this file improve performance by enabling execution start points according to the following assumptions: 1. Start points with "where:" clauses that reference only local fields (i.e. not tagged values from other query locations) are always better than start points without a "where:". This is because the filter will have to be applied one way or the other, so we might as well apply it early. 2. If no such start points are available, we'd like to make available as many start points as possible, since we'd like OrientDB to start at the start point whose class has the lowest possible cardinality. The process of applying the optimizations is as follows: - Exclude and ignore all query steps that are inside a fold, optional, or recursion scope, or have a "where:" clause that references a non-local (i.e. tagged) field. - Find all remaining query steps with "where:" clauses that reference only local fields. - If any are found, we guide our actions from assumption 1 above: - Ensure they have a defined "class:" -- i.e. the OrientDB scheduler will consider them valid start points. - Then, prune all other query steps (ones without such "where:" clauses) by removing their "class:" clause, making them invalid as query start points for OrientDB's scheduler. - If none are found, we guide our actions from assumption 2 above: - Ensure that all query points not inside fold, optional, or recursion scope contain a "class:" clause. That increases the number of available query start points, so OrientDB can choose the start point of lowest cardinality. """ from ..blocks import CoerceType, QueryRoot, Recurse, Traverse from ..expressions import ContextField, ContextFieldExistence from ..helpers import get_only_element_from_collection from ..ir_lowering_match.utils import convert_coerce_type_and_add_to_where_block def _is_local_filter(filter_block): """Return True if the Filter block references no non-local fields, and False otherwise.""" # We need the "result" value of this function to be mutated within the "visitor_fn". # Since we support both Python 2 and Python 3, we can't use the "nonlocal" keyword here: # https://www.python.org/dev/peps/pep-3104/ # Instead, we use a dict to store the value we need mutated, since the "visitor_fn" # can mutate state in the parent scope, but not rebind variables in it without "nonlocal". # TODO(predrag): Revisit this if we drop support for Python 2. result = { 'is_local_filter': True } filter_predicate = filter_block.predicate def visitor_fn(expression): """Expression visitor function that looks for uses of non-local fields.""" non_local_expression_types = (ContextField, ContextFieldExistence) if isinstance(expression, non_local_expression_types): result['is_local_filter'] = False # Don't change the expression. return expression filter_predicate.visit_and_update(visitor_fn) return result['is_local_filter'] def _classify_query_locations(match_query): """Classify query locations into three groups: preferred, eligible, ineligible. - Ineligible locations are ones that cannot be the starting point of query execution. These include locations within recursions, locations that are the target of an optional traversal, and locations with an associated "where:" clause with non-local filter. - Preferred locations are ones that are eligible to be the starting point, and also have an associated "where:" clause that references no non-local fields -- only local fields, literals, and variables. - Eligible locations are all locations that do not fall into either of these two categories. Args: match_query: MatchQuery object describing the query being analyzed for optimization Returns: tuple (preferred, eligible, ineligible) where each element is a set of Location objects. The three sets are disjoint. """ preferred_locations = set() eligible_locations = set() ineligible_locations = set() # Any query must have at least one traversal with at least one step. # The first step in this traversal must be a QueryRoot. first_match_step = match_query.match_traversals[0][0] if not isinstance(first_match_step.root_block, QueryRoot): raise AssertionError(u'First step of first traversal unexpectedly was not QueryRoot: ' u'{} {}'.format(first_match_step, match_query)) # The first step in the first traversal cannot possibly be inside an optional, recursion, # or fold. Its location is always an eligible start location for a query. # We need to determine whether it is merely eligible, or actually a preferred location. if first_match_step.where_block is not None: if _is_local_filter(first_match_step.where_block): preferred_locations.add(first_match_step.as_block.location) else: # TODO(predrag): Fix once we have a proper fix for tag-and-filter in the same scope. # Either the locally-scoped tag will have to generate a LocalField # instead of a ContextField, or we'll have to rework the local filter # detection code in this module. raise AssertionError(u'The first step of the first traversal somehow had a non-local ' u'filter. This should not be possible, since there is nowhere ' u'for the tagged value to have come from. Values: {} {}' .format(first_match_step, match_query)) else: eligible_locations.add(first_match_step.as_block.location) # This loop will repeat the analysis of the first step of the first traversal. # QueryRoots other than the first are required to always be at a location whose status # (preferred / eligible / ineligible) is already known. Since we already processed # the first QueryRoot above, the rest of the loop can assume all QueryRoots are like that. for current_traversal in match_query.match_traversals: for match_step in current_traversal: current_step_location = match_step.as_block.location if isinstance(match_step.root_block, QueryRoot): already_encountered_location = any(( current_step_location in preferred_locations, current_step_location in eligible_locations, current_step_location in ineligible_locations, )) if not already_encountered_location: raise AssertionError(u'Unexpectedly encountered a location in QueryRoot whose ' u'status has not been determined: {} {} {}' .format(current_step_location, match_step, match_query)) at_eligible_or_preferred_location = ( current_step_location in preferred_locations or current_step_location in eligible_locations) # This location has already been encountered and processed. # Other than setting the "at_eligible_or_preferred_location" state for the sake of # the following MATCH steps, there is nothing further to be done. continue elif isinstance(match_step.root_block, Recurse): # All Recurse blocks cause locations within to be ineligible. at_eligible_or_preferred_location = False elif isinstance(match_step.root_block, Traverse): # Optional Traverse blocks cause locations within to be ineligible. # Non-optional Traverse blocks do not change the eligibility of locations within: # if the pre-Traverse location was eligible, so will the location within, # and if it was not eligible, neither will the location within. if match_step.root_block.optional: at_eligible_or_preferred_location = False else: raise AssertionError(u'Unreachable condition reached: {} {} {}' .format(match_step.root_block, match_step, match_query)) if not at_eligible_or_preferred_location: ineligible_locations.add(current_step_location) elif match_step.where_block is not None: if _is_local_filter(match_step.where_block): # This location has a local filter, and is not otherwise ineligible (it's not # in a recursion etc.). Therefore, it's a preferred query start location. preferred_locations.add(current_step_location) else: # Locations with non-local filters are never eligible locations, since they # depend on another location being executed before them. ineligible_locations.add(current_step_location) else: # No local filtering (i.e. not preferred), but also not ineligible. Eligible it is. eligible_locations.add(current_step_location) return preferred_locations, eligible_locations, ineligible_locations def _calculate_type_bound_at_step(match_step): """Return the GraphQL type bound at the given step, or None if no bound is given.""" current_type_bounds = [] if isinstance(match_step.root_block, QueryRoot): # The QueryRoot start class is a type bound. current_type_bounds.extend(match_step.root_block.start_class) if match_step.coerce_type_block is not None: # The CoerceType target class is also a type bound. current_type_bounds.extend(match_step.coerce_type_block.target_class) if current_type_bounds: # A type bound exists. Assert that there is exactly one bound, defined in precisely one way. return get_only_element_from_collection(current_type_bounds) else: # No type bound exists at this MATCH step. return None def _assert_type_bounds_are_not_conflicting(current_type_bound, previous_type_bound, location, match_query): """Ensure that the two bounds either are an exact match, or one of them is None.""" if all((current_type_bound is not None, previous_type_bound is not None, current_type_bound != previous_type_bound)): raise AssertionError( u'Conflicting type bounds calculated at location {}: {} vs {} ' u'for query {}'.format(location, previous_type_bound, current_type_bound, match_query)) def _expose_only_preferred_locations(match_query, location_types, coerced_locations, preferred_locations, eligible_locations): """Return a MATCH query where only preferred locations are valid as query start locations.""" preferred_location_types = dict() eligible_location_types = dict() new_match_traversals = [] for current_traversal in match_query.match_traversals: new_traversal = [] for match_step in current_traversal: new_step = match_step current_step_location = match_step.as_block.location if current_step_location in preferred_locations: # This location is preferred. We have to make sure that at least one occurrence # of this location in the MATCH query has an associated "class:" clause, # which would be generated by a type bound at the corresponding MATCH step. current_type_bound = _calculate_type_bound_at_step(match_step) previous_type_bound = preferred_location_types.get(current_step_location, None) if previous_type_bound is not None: # The location is already valid. If so, make sure that this step either does # not have any type bounds (e.g. via QueryRoot or CoerceType blocks), # or has type bounds that match the previously-decided type bound. _assert_type_bounds_are_not_conflicting( current_type_bound, previous_type_bound, current_step_location, match_query) else: # The location is not yet known to be valid. If it does not have # a type bound in this MATCH step, add a type coercion to the type # registered in "location_types". if current_type_bound is None: current_type_bound = location_types[current_step_location].name new_step = match_step._replace( coerce_type_block=CoerceType({current_type_bound})) preferred_location_types[current_step_location] = current_type_bound elif current_step_location in eligible_locations: # This location is eligible, but not preferred. We have not make sure # none of the MATCH steps with this location have type bounds, and therefore # will not produce a corresponding "class:" clause in the resulting MATCH query. current_type_bound = _calculate_type_bound_at_step(match_step) previous_type_bound = eligible_location_types.get(current_step_location, None) if current_type_bound is not None: # There is a type bound here that we need to neutralize. _assert_type_bounds_are_not_conflicting( current_type_bound, previous_type_bound, current_step_location, match_query) # Record the deduced type bound, so that if we encounter this location again, # we ensure that we again infer the same type bound. eligible_location_types[current_step_location] = current_type_bound if (current_step_location not in coerced_locations or previous_type_bound is not None): # The type bound here is already implied by the GraphQL query structure, # or has already been applied at a previous occurrence of this location. # We can simply delete the QueryRoot / CoerceType blocks that impart it. if isinstance(match_step.root_block, QueryRoot): new_root_block = None else: new_root_block = match_step.root_block new_step = match_step._replace( root_block=new_root_block, coerce_type_block=None) else: # The type bound here is not already implied by the GraphQL query structure. # This should only be possible via a CoerceType block. Lower this CoerceType # block into a Filter with INSTANCEOF to ensure the resulting query has the # same semantics, while making the location invalid as a query start point. if (isinstance(match_step.root_block, QueryRoot) or match_step.coerce_type_block is None): raise AssertionError(u'Unexpected MATCH step applying a type bound not ' u'already implied by the GraphQL query structure: ' u'{} {}'.format(match_step, match_query)) new_where_block = convert_coerce_type_and_add_to_where_block( match_step.coerce_type_block, match_step.where_block) new_step = match_step._replace( coerce_type_block=None, where_block=new_where_block) else: # There is no type bound that OrientDB can find defined at this location. # No action is necessary. pass else: # This location is neither preferred nor eligible. # No action is necessary at this location. pass new_traversal.append(new_step) new_match_traversals.append(new_traversal) return match_query._replace(match_traversals=new_match_traversals) def _expose_all_eligible_locations(match_query, location_types, eligible_locations): """Return a MATCH query where all eligible locations are valid as query start locations.""" eligible_location_types = dict() new_match_traversals = [] for current_traversal in match_query.match_traversals: new_traversal = [] for match_step in current_traversal: new_step = match_step current_step_location = match_step.as_block.location if current_step_location in eligible_locations: # This location is eligible. We need to make sure it has an associated type bound, # so that it produces a "class:" clause that will make it a valid query start # location. It either already has such a type bound, or we can use the type # implied by the GraphQL query structure to add one. current_type_bound = _calculate_type_bound_at_step(match_step) previous_type_bound = eligible_location_types.get(current_step_location, None) if current_type_bound is None: current_type_bound = location_types[current_step_location].name new_coerce_type_block = CoerceType({current_type_bound}) new_step = match_step._replace(coerce_type_block=new_coerce_type_block) else: # There is a type bound here. We simply ensure that the bound is not conflicting # with any other type bound at a different MATCH step with the same location. _assert_type_bounds_are_not_conflicting( current_type_bound, previous_type_bound, current_step_location, match_query) # Record the deduced type bound, so that if we encounter this location again, # we ensure that we again infer the same type bound. eligible_location_types[current_step_location] = current_type_bound else: # This function may only be called if there are no preferred locations. Since this # location cannot be preferred, and is not eligible, it must be ineligible. # No action is necessary in this case. pass new_traversal.append(new_step) new_match_traversals.append(new_traversal) return match_query._replace(match_traversals=new_match_traversals) def expose_ideal_query_execution_start_points(compound_match_query, location_types, coerced_locations): """Ensure that OrientDB only considers desirable query start points in query planning.""" new_queries = [] for match_query in compound_match_query.match_queries: location_classification = _classify_query_locations(match_query) preferred_locations, eligible_locations, _ = location_classification if preferred_locations: # Convert all eligible locations into non-eligible ones, by removing # their "class:" clause. The "class:" clause is provided either by having # a QueryRoot block or a CoerceType block in the MatchStep corresponding # to the location. We remove it by converting the class check into # an "INSTANCEOF" Filter block, which OrientDB is unable to optimize away. new_query = _expose_only_preferred_locations( match_query, location_types, coerced_locations, preferred_locations, eligible_locations) elif eligible_locations: # Make sure that all eligible locations have a "class:" clause by adding # a CoerceType block that is a no-op as guaranteed by the schema. This merely # ensures that OrientDB is able to use each of these locations as a query start point, # and will choose the one whose class is of lowest cardinality. new_query = _expose_all_eligible_locations( match_query, location_types, eligible_locations) else: raise AssertionError(u'This query has no preferred or eligible query start locations. ' u'This is almost certainly a bug: {}'.format(match_query)) new_queries.append(new_query) return compound_match_query._replace(match_queries=new_queries)
[ 2, 15069, 2864, 12, 25579, 29018, 8873, 21852, 11, 11419, 13, 198, 37811, 12468, 283, 3733, 329, 35275, 11012, 6038, 18173, 2071, 326, 5640, 3595, 12405, 5410, 329, 1728, 20743, 13, 198, 198, 1890, 4959, 286, 12405, 5410, 11, 262, 35275...
2.554265
8,781
from enum import IntEnum import functools import usb.core import usb.util from traffic_light.error import TrafficLightError, MultipleTrafficLightsError BM_REQUEST_TYPE = 0x21 B_REQUEST = 0x09 W_VALUE = 0x200 W_INDEX = 0x00 ID_VENDOR = 0x0d50 ID_PRODUCT = 0x0008 INTERFACE = 0 def __getattr__(self, name): """Parses attribut calls in function""" args = name.split('_') try: color = Color[args[0].upper()] state = State[args[1].upper()] except Exception as exc: raise TrafficLightError("Either the given color or state could not be parsed! Exc: {}" .format(exc)) return functools.partial(self.set_led, color, state) def __str__(self): """Converts instance into string with important imformations""" return ("== Cleware Traffic Light ==\n" "Address: {} \n" "IdVendor: {} \n" "IdProduct: {}".format(self.address, ID_VENDOR, ID_PRODUCT))
[ 6738, 33829, 1330, 2558, 4834, 388, 198, 198, 11748, 1257, 310, 10141, 198, 11748, 38551, 13, 7295, 198, 11748, 38551, 13, 22602, 198, 198, 6738, 4979, 62, 2971, 13, 18224, 1330, 23624, 15047, 12331, 11, 20401, 15721, 2108, 43, 2337, 12...
2.228261
460
# coding=utf-8 # ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ """ FILE: sample_analyze_orchestration_app_luis_response_async.py DESCRIPTION: This sample demonstrates how to analyze user query using an orchestration project. In this sample, orchestration project's top intent will map to a LUIS project. For more info about how to setup a CLU orchestration project, see the README. USAGE: python sample_analyze_orchestration_app_luis_response_async.py Set the environment variables with your own values before running the sample: 1) AZURE_CONVERSATIONS_ENDPOINT - endpoint for your CLU resource. 2) AZURE_CONVERSATIONS_KEY - API key for your CLU resource. 3) AZURE_CONVERSATIONS_WORKFLOW_PROJECT_NAME - project name for your CLU orchestration project. 4) AZURE_CONVERSATIONS_WORKFLOW_DEPLOYMENT_NAME - deployment name for your CLU orchestration project. """ import asyncio if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(main())
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 20368, 650, 198, 2, 15069, 357, 66, 8, 5413, 10501, 13, 198, 2, 49962, 739, 262, 17168, 13789, 13, 198, 2, 20368, 650, 198, 198, 37811, 198, 25664, 25, 6291, 62, 38200, 2736, 62, 273, 2395, 1...
3.018041
388
# flake8: noqa from schemas.client_credentials import * from schemas.message import * from schemas.token import * from schemas.user import *
[ 2, 781, 539, 23, 25, 645, 20402, 198, 6738, 3897, 5356, 13, 16366, 62, 66, 445, 14817, 1330, 1635, 198, 6738, 3897, 5356, 13, 20500, 1330, 1635, 198, 6738, 3897, 5356, 13, 30001, 1330, 1635, 198, 6738, 3897, 5356, 13, 7220, 1330, 16...
3.204545
44
import json from web3 import Web3 from solcx import compile_standard, install_solc with open("./SimpleStorage.sol", "r") as file: simple_storage_src = file.read() # install solcx install_solc("0.8.0") # compile the source compiled_sol = compile_standard( { "language": "Solidity", "sources": {"SimpleStorage.sol": {"content": simple_storage_src}}, "settings": { "outputSelection": { "*": { "*": ["abi", "metadata", "evm.bytecode", "evm.sourceMap"] } } }, }, solc_version = "0.8.0" ) with open("./out.json", "w") as file: json.dump(compiled_sol, file) # getting the bytecode bytecode = compiled_sol["contracts"]["SimpleStorage.sol"]["SimpleStorage"]["evm"]["bytecode"]["object"] # getting the abi abi = compiled_sol["contracts"]["SimpleStorage.sol"]["SimpleStorage"]["abi"] # connecting to ganache w3 = Web3(Web3.HTTPProvider("HTTP://127.0.0.1:7545")) chain_id = 1337 my_address = "0x02ECDdb09504C4d4B2ba2c7Ec80d77d44f6e631c" private_key = "0xa9ddbecce894fdad11cd9864d9c58f794d23bd5f0d78d1c2eea204b284edfefc" # Create the contract in python SimpleStorage = w3.eth.contract(abi=abi, bytecode=bytecode) # Get the latest test transaction nonce = w3.eth.getTransactionCount(my_address) # 1. Build a transaction # 2. Sing the transaction # 3. Send the transaction transaction = SimpleStorage.constructor().buildTransaction({"gasPrice": w3.eth.gas_price, "chainId": chain_id, "from": my_address, "nonce": nonce}) signed_txn = w3.eth.account.sign_transaction(transaction, private_key) tx_hash = w3.eth.send_raw_transaction(signed_txn.rawTransaction) # confirm transaction is received tx_receipt = w3.eth.wait_for_transaction_receipt(tx_hash) print("tx_hash=", tx_hash) print("receipt=", tx_receipt) # working on-chain simple_storage = w3.eth.contract(address=tx_receipt.contractAddress, abi=abi) print(simple_storage.functions.retrieve().call()) store_transaction = simple_storage.functions.store(15).buildTransaction({ "gasPrice": w3.eth.gas_price, "chainId": chain_id, "from": my_address, "nonce": nonce + 1 } ) singed_store_transaction = w3.eth.account.sign_transaction(store_transaction, private_key) store_transaction_hash = w3.eth.send_raw_transaction(singed_store_transaction.rawTransaction) store_transaction_receipt = w3.eth.wait_for_transaction_receipt(store_transaction_hash)
[ 11748, 33918, 198, 6738, 3992, 18, 1330, 5313, 18, 198, 6738, 1540, 66, 87, 1330, 17632, 62, 20307, 11, 2721, 62, 34453, 66, 628, 198, 4480, 1280, 7, 1911, 14, 26437, 31425, 13, 34453, 1600, 366, 81, 4943, 355, 2393, 25, 198, 220, ...
2.393678
1,044
from noise.dh.dh import DH from noise.cipher.cipher import Cipher from noise.hash.hash import Hash from noise.processing.handshakepatterns.handshakepattern import HandshakePattern from noise.processing.impl.handshakestate import HandshakeState from noise.processing.impl.symmetricstate import SymmetricState from noise.processing.impl.cipherstate import CipherState def create_symmetricstate(self, cipherstate=None, hash=None): """ :param cipherstate: :type cipherstate: CipherState :param hash: :type hash: Hash :return: :rtype: SymmetricState """ return SymmetricState(cipherstate or self.create_cipherstate(), hash or self._hash) def create_handshakestate(self, symmetricstate=None, dh=None): """ :param symmetricstate: :type symmetricstate: SymmetricState :param dh: :type dh: DH :return: :rtype: HandshakeState """ return HandshakeState(symmetricstate or self.create_symmetricstate(), dh or self._dh)
[ 6738, 7838, 13, 34985, 13, 34985, 1330, 23809, 198, 6738, 7838, 13, 66, 10803, 13, 66, 10803, 1330, 44334, 198, 6738, 7838, 13, 17831, 13, 17831, 1330, 21059, 198, 6738, 7838, 13, 36948, 13, 4993, 32431, 33279, 82, 13, 4993, 32431, 33...
2.609337
407
import urllib.parse import webbrowser import json from xml.etree import ElementTree import sublime import SublimeHaskell.sublime_haskell_common as Common import SublimeHaskell.internals.utils as Utils import SublimeHaskell.internals.unicode_opers as UnicodeOpers import SublimeHaskell.symbols as symbols import SublimeHaskell.internals.backend_mgr as BackendManager import SublimeHaskell.parseoutput as ParseOutput import SublimeHaskell.types as types # Unused module variable: # style_header = "<style>" \ # "a { text-decoration: underline; }" \ # ".type { color: red; }" \ # ".tyvar { color: blue; }" \ # ".operator { color: green; }" \ # ".comment { color: gray; font-style: italic; }" \ # ".docs { color: gray; }" \ # "</style>"
[ 11748, 2956, 297, 571, 13, 29572, 198, 198, 11748, 3992, 40259, 198, 11748, 33918, 198, 6738, 35555, 13, 316, 631, 1330, 11703, 27660, 198, 198, 11748, 41674, 198, 198, 11748, 3834, 27299, 19242, 17164, 13, 7266, 27299, 62, 10134, 17164, ...
2.865672
268
#!/usr/bin/env python # Copyright (C) 2017 Seeed Technology Limited # # 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 modules.pixel_ring import pixel_ring import numpy import time import threading try: import queue as Queue except ImportError: import Queue as Queue lights = GoogleHomeLights() if __name__ == '__main__': while True: try: lights.wakeup() time.sleep(3) lights.think() time.sleep(3) lights.speak() time.sleep(3) lights.off() time.sleep(3) except KeyboardInterrupt: break pixel_ring.off()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 2, 15069, 357, 34, 8, 2177, 1001, 2308, 8987, 15302, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407...
2.712941
425
""" Nonnegative CP decomposition by Hierarchical alternating least squares (HALS). With support for missing data. """ import numpy as np import scipy as sci from scipy import linalg from tensortools.operations import unfold, khatri_rao from tensortools.tensors import KTensor from tensortools.optimize import FitResult, optim_utils from .._hals_update import _hals_update def mncp_hals(X, rank, mask, random_state=None, init='rand', **options): """ Fits nonnegtaive CP Decomposition using the Hierarcial Alternating Least Squares (HALS) Method. Supports missing data. Parameters ---------- X : (I_1, ..., I_N) array_like A real array with nonnegative entries and ``X.ndim >= 3``. rank : integer The `rank` sets the number of components to be computed. mask : (I_1, ..., I_N) array_like A binary tensor with the same shape as ``X``. All entries equal to zero correspond to held out or missing data in ``X``. All entries equal to one correspond to observed entries in ``X`` and the decomposition is fit to these datapoints. random_state : integer, RandomState instance or None, optional (default ``None``) If integer, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by np.random. init : str, or KTensor, optional (default ``'rand'``). Specifies initial guess for KTensor factor matrices. If ``'randn'``, Gaussian random numbers are used to initialize. If ``'rand'``, uniform random numbers are used to initialize. If KTensor instance, a copy is made to initialize the optimization. options : dict, specifying fitting options. tol : float, optional (default ``tol=1E-5``) Stopping tolerance for reconstruction error. max_iter : integer, optional (default ``max_iter = 500``) Maximum number of iterations to perform before exiting. min_iter : integer, optional (default ``min_iter = 1``) Minimum number of iterations to perform before exiting. max_time : integer, optional (default ``max_time = np.inf``) Maximum computational time before exiting. verbose : bool ``{'True', 'False'}``, optional (default ``verbose=True``) Display progress. Returns ------- result : FitResult instance Object which holds the fitted results. It provides the factor matrices in form of a KTensor, ``result.factors``. Notes ----- This implemenation is using the Hierarcial Alternating Least Squares Method. References ---------- Cichocki, Andrzej, and P. H. A. N. Anh-Huy. "Fast local algorithms for large scale nonnegative matrix and tensor factorizations." IEICE transactions on fundamentals of electronics, communications and computer sciences 92.3: 708-721, 2009. Examples -------- """ # Mask missing elements. X = np.copy(X) X[~mask] = np.linalg.norm(X[mask]) # Check inputs. optim_utils._check_cpd_inputs(X, rank) # Initialize problem. U, normX = optim_utils._get_initial_ktensor(init, X, rank, random_state) result = FitResult(U, 'NCP_HALS', **options) # Store problem dimensions. normX = linalg.norm(X[mask].ravel()) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Iterate the HALS algorithm until convergence or maxiter is reached # i) compute the N gram matrices and multiply # ii) Compute Khatri-Rao product # iii) Update component U_1, U_2, ... U_N # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ while result.still_optimizing: # First, HALS update. for n in range(X.ndim): # Select all components, but U_n components = [U[j] for j in range(X.ndim) if j != n] # i) compute the N-1 gram matrices grams = sci.multiply.reduce([arr.T.dot(arr) for arr in components]) # ii) Compute Khatri-Rao product kr = khatri_rao(components) p = unfold(X, n).dot(kr) # iii) Update component U_n _hals_update(U[n], grams, p) # Then, update masked elements. pred = U.full() X[~mask] = pred[~mask] # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Update the optimization result, checks for convergence. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Compute objective function # grams *= U[X.ndim - 1].T.dot(U[X.ndim - 1]) # obj = np.sqrt( (sci.sum(grams) - 2 * sci.sum(U[X.ndim - 1] * p) + normX**2)) / normX resid = X - pred result.update(linalg.norm(resid.ravel()) / normX) # end optimization loop, return result. return result.finalize()
[ 37811, 198, 15419, 31591, 16932, 26969, 9150, 416, 36496, 998, 605, 39623, 1551, 24438, 357, 39, 23333, 737, 198, 3152, 1104, 329, 4814, 1366, 13, 198, 37811, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 629, 541, 88, 355, 20681...
2.740984
1,830
""" @author: Jonas Eschle "Mayou36" DEPRECEATED! USE OTHER MODULES LIKE rd.data, rd.ml, rd.reweight, rd.score and rd.stat DEPRECEATED!DEPRECEATED!DEPRECEATED!DEPRECEATED!DEPRECEATED! Contains several tools to convert, load, save and plot data """ import warnings import os import copy import pandas as pd import numpy as np import uproot import pickle from . import dev_tool # both produce error (27.07.2016) when importing them if run from main.py. # No problem when run as main... # from raredecay.tools import dev_tool from .. import meta_config as meta_cfg def apply_cuts(signal_data, bkg_data, percent_sig_to_keep=100, bkg_length=None): """Search for best cut on value to still keep percent_sig_to_keep of signal Parameters ---------- signal_data : 1-D numpy array The signal bkg_data : 1-D numpy array The background data percent_sig_to_keep : 0 < float <= 100 What percentage of the data to keep in order to apply the cuts. """ # if percent_sig_to_keep < 100: # raise NotImplementedError("percentage of < 100 not yet imlemented") percentile = [0, percent_sig_to_keep] # TODO: modify for percent_sig_to_keep bkg_length_before = len(bkg_data) bkg_length = len(bkg_data) if bkg_length in (None, 0) else bkg_length lower_cut, upper_cut = np.percentile(signal_data, percentile) cut_bkg = np.count_nonzero( np.logical_or(bkg_data < lower_cut, bkg_data > upper_cut) ) rejected_bkg = (bkg_length_before - cut_bkg) / bkg_length return [lower_cut, upper_cut], rejected_bkg def make_root_dict(path_to_rootfile, tree_name, branches): """Returns a root_numpy compatible "root-dict" of a root-tree. Parameters ---------- path_to_rootfile : str The exact path to the root-tree including the filename. Example: /home/user1/data/myRootTree1.root tree_name : str The name of the tree branches : str or list[str, str, str,... ] The branches of the tree to use """ output = dict(filenames=path_to_rootfile, treename=tree_name, branches=branches) output = dev_tool.entries_to_str(output) return output def add_to_rootfile(rootfile, new_branch, branch_name=None, overwrite=True): """Adds a new branch to a given root file. .. warning:: Overwrite not working currently! Parameters ---------- rootfile : root-dict The ROOT-file where the data should be added new_branch : numpy.array 1-D, list, root-dict A one-dimensional numpy array that contains the data. branch_name : str The name of the branche resp. the name in the dtype of the array. """ from root_numpy import array2root from rootpy.io import root_open rootfile = dev_tool.entries_to_str(rootfile) new_branch = dev_tool.entries_to_str(new_branch) branch_name = dev_tool.entries_to_str(branch_name) # get the right parameters # TODO: what does that if there? an assertion maybe? write_mode = "update" branch_name = "new_branch1" if branch_name is None else branch_name if isinstance(rootfile, dict): filename = rootfile.get("filenames") treename = rootfile.get("treename") new_branch = to_ndarray(new_branch) # new_branch.dtype = [(branch_name, 'f8')] # write to ROOT-file write_to_root = False if os.path.isfile(filename): with root_open(filename, mode="a") as root_file: tree = getattr(root_file, treename) # test if not tree.has_branch(branch_name): write_to_root = True # array2tree(new_branch, tree=tree) # f.write("", TObject.kOverwrite) # overwrite, does not create friends else: write_mode = "recreate" write_to_root = True if write_to_root: arr = np.core.records.fromarrays([new_branch], names=branch_name) array2root(arr=arr, filename=filename, treename=treename, mode=write_mode) return 0 else: return 1 # TODO: remove? outdated def format_data_weights(data_to_shape, weights): """Format the data and the weights perfectly. Same length and more. Change the data to pandas.DataFrame and fill the weights with ones where nothing or None is specified. Returns both in lists. Very useful to loop over several data and weights. Parameters ---------- data_to_shape : (root_dict, numpy.array, pandas.DataFrame) The data for which we apply the weights. Usual 2-D shape. weights : (list, numpy.array, pandas.DataFrame, None) The weights to be reshaped *Best format* : [array(weights),array(weights), None, array(weights),...] *None* can be used if no special weights are specified. If weights contains less "weight-containing array-like objects" then data_to_shape does, the difference will be filled with *1* Return ------ out : list(pandas.DataFrame(data), pandas.DataFrame(data),...) Return a list containing data out : list(numpy.array(weight), numpy.array(weight),...) Return a list with the weights, converted and filled. """ # conver the data if not isinstance(data_to_shape, list): data_to_shape = [data_to_shape] data_to_shape = list(map(to_pandas, data_to_shape)) # convert the weights if not isinstance(weights, list): weights = [weights] if weights[0] is not None: if len(weights[0]) == 1: weights = [weights] # convert to pandas assert isinstance(weights, list), "weights could not be converted to list" for data_id, data in enumerate(data_to_shape): if data_id >= len(weights): weights.append(None) if weights[data_id] is None: weights[data_id] = np.array([1] * len(data)) weights[data_id] = to_pandas(weights[data_id]).squeeze().values return data_to_shape, weights def obj_to_string(objects, separator=None): """Return a string containing all objects as strings, separated by the separator. Useful for automatic conversion for different types. The following objects will automatically be converted: - None will be omitted Parameters ---------- objects : any object or list(obj, obj, ...) with a string representation The objects will be converted to a string and concatenated, separated by the separator. separator : str The separator between the objects. Default is " - ". """ objects = dev_tool.entries_to_str(objects) if isinstance(objects, str): # no need to change things return objects separator = " - " if separator is None else separator assert isinstance(separator, str), "Separator not a str" objects = to_list(objects) objects = [str(obj) for obj in objects if obj not in (None, "")] # remove Nones string_out = "" for word in objects: string_out += word + separator if word != objects[-1] else word return string_out def is_root(data_to_check): """Check whether a given data is a root file. Needs dicts to be True.""" flag = False data_to_check = dev_tool.entries_to_str(data_to_check) if isinstance(data_to_check, dict): path_name = data_to_check.get("filenames") # assert isinstance(path_name, str), ("'filenames' of the dictionary " + # str(data_to_check) + "is not a string") if path_name.endswith(meta_cfg.ROOT_DATATYPE): flag = True return flag def is_list(data_to_check): """Check whether the given data is a list.""" flag = False if isinstance(data_to_check, list): flag = True return flag def is_ndarray(data_to_check): """Check whether a given data is an ndarray.""" flag = False if isinstance(data_to_check, np.ndarray): flag = True return flag def is_pickle(data_to_check): """Check if the file is a pickled file (checks the ending).""" flag = False data_to_check = dev_tool.entries_to_str(data_to_check) if isinstance(data_to_check, str): if data_to_check.endswith(meta_cfg.PICKLE_DATATYPE): flag = True return flag def to_list(data_in): """Convert the data into a list. Does not pack lists into a new one. If your input is, for example, a string or a list of strings, or a tuple filled with strings, you have, in general, a problem: - just iterate through the object will fail because it iterates through the characters of the string. - using list(obj) converts the tuple, leaves the list but splits the strings characters into single elements of a new list. - using [obj] creates a list containing a string, but also a list containing a list or a tuple, which you did not want to. Solution: use to_list(obj), which creates a new list in case the object is a single object (a string is a single object in this sence) or converts to a list if the object is already a container for several objects. Parameters ---------- data_in : any obj So far, any object can be entered. Returns ------- out : list Return a list containing the object or the object converted to a list. """ if isinstance(data_in, (str, int, float)): data_in = [data_in] data_in = list(data_in) return data_in def to_ndarray(data_in, float_array=False): """Convert data to numpy array (containing only floats). Parameters ---------- data_in : any reasonable data The data to be converted """ import uproot if is_root(data_in): with uproot.open(data_in["filenames"]) as file: tree = file[data_in["treename"]] branches = to_list(data_in["branches"]) loaded = tree.arrays(branches, library="np") loaded = np.stack([loaded[branch] for branch in branches]) if len(branches) == 1: loaded = loaded[0] data_in = loaded # change numpy.void to normal floats if isinstance(data_in, (pd.Series, pd.DataFrame)): test_sample = data_in.iloc[0] else: test_sample = data_in[0] if isinstance(test_sample, np.void): data_in = np.array([val[0] for val in data_in]) if isinstance(data_in, (np.recarray, np.ndarray)): data_in = data_in.tolist() if is_list(data_in) or isinstance(data_in, pd.Series): data_in = np.array(data_in) if not isinstance(data_in[0], (int, float, str, bool)): if float_array: iter_data = copy.deepcopy(data_in) # HACK data_in = np.ndarray(shape=len(data_in), dtype=data_in.dtype) # HACK END for i, element in enumerate(iter_data): if not isinstance(element, (int, float, str, bool)): # does that work or should we iterate over copy? try: element_len = len(element) except TypeError: element_len = 1 if element_len > 1: data_in[i] = to_ndarray(element) float_array = False elif element_len == 1: data_in[i] = float(element) warnings.warn("Could not force float array") if float_array: data_in = np.asfarray(data_in) assert is_ndarray(data_in), "Error, could not convert data to numpy array" return data_in def to_pandas_old(data_in, index=None, columns=None): """Convert data from numpy or root to pandas dataframe. Convert data safely to pandas, whatever the format is. Parameters ---------- data_in : any reasonable data The data to be converted """ # TODO: generalize root_index_name = "__index__" data_in = dev_tool.entries_to_str(data_in) if is_root(data_in): root_index = None import root_numpy if root_index_name in root_numpy.list_branches( filename=data_in["filenames"], treename=data_in.get("treename") ): root_index = root_numpy.root2array( filenames=data_in["filenames"], treename=data_in.get("treename"), selection=data_in.get("selection"), branches=root_index_name, ) data_in = root_numpy.root2array(**data_in) # why **? it's a root dict if is_list(data_in): data_in = np.array(data_in) if is_ndarray(data_in): if (isinstance(columns, (list, tuple)) and len(columns) == 1) or isinstance( columns, str ): data_in = to_ndarray(data_in) data_in = pd.DataFrame(data_in, columns=columns, index=root_index) if index is not None: data_in = data_in.loc[index] elif isinstance(data_in, pd.DataFrame): pass else: raise TypeError("Could not convert data to pandas. Data: " + data_in) return data_in def to_pandas(data_in, index=None, columns=None): """Convert data from numpy or root to pandas dataframe. Convert data safely to pandas, whatever the format is. Parameters ---------- data_in : any reasonable data The data to be converted """ data_in = dev_tool.entries_to_str(data_in) if is_root(data_in): if columns is None: columns = data_in["branches"] with uproot.open(data_in["filenames"]) as file: tree = file[data_in["treename"]] if "__index__" in tree.keys(): # legacy, we can also convert this return to_pandas_old(data_in=data_in, index=index, columns=columns) branches = to_list(columns) loaded = tree.arrays(branches, library="pd") if index is not None: loaded = loaded.loc[index] return loaded else: # HACK START return to_pandas_old(data_in=data_in, index=index, columns=columns) # HACK END # from root_pandas import read_root # # root_pandas_numpy_map = dict(filenames='paths', treename='key', branches='columns', # selection='where') # # if is_root(data_in): # is_root2array = False # for key, val in copy.deepcopy(list(data_in.items())): # if key in root_pandas_numpy_map: # is_root2array = True # del data_in[key] # data_in[root_pandas_numpy_map[key]] = val # data_in['columns'] = to_list(data_in['columns']) # if is_root2array: # data_in['columns'] = ['noexpand:'+col for col in data_in['columns'] if not col.startswith('noexpand:')] # remove the noexpand: # data_in = read_root(**data_in) # why **? it's a root dict # if is_list(data_in): # data_in = np.array(data_in) # if is_ndarray(data_in): # if ((isinstance(columns, (list, tuple)) and len(columns) == 1) or # isinstance(columns, string)): # # data_in = to_ndarray(data_in) # data_in = pd.DataFrame(data_in, columns=columns) # if index is not None: # data_in = data_in.loc[index] # elif isinstance(data_in, pd.DataFrame): # pass # else: # raise TypeError("Could not convert data to pandas. Data: " + data_in) # return data_in def adv_return(return_value, save_name=None): """Save the value if save_name specified, otherwise just return input. Can be wrapped around the return value. Without any arguments, the return of your function will be exactly the same. With arguments, the value can be saved (**pickled**) before it is returned. Parameters ---------- return_value : any python object The python object which should be pickled. save_name : str, None | The (file-)name for the pickled file. File-extension will be added \ automatically if specified in *raredecay.meta_config*. | If *None* is passed, the object won't be pickled. Return ------ out : python object Return return_value without changes. **Usage**: Instead of a simple return statement >>> return my_variable/my_object one can use the **completely equivalent** statement >>> return adv_return(my_variable/my_object) If the return value should be saved in addition to be returned, use >>> return adv_return(my_variable/my_object, save_name='my_object.pickle') (*the .pickle ending is not required but added automatically if omitted*) which returns the value and saves it. """ save_name = dev_tool.entries_to_str(save_name) if save_name not in (None, False): if isinstance(save_name, str): save_name = meta_cfg.PICKLE_PATH + save_name if not is_pickle(save_name): save_name += "." + meta_cfg.PICKLE_DATATYPE with open(str(save_name), "wb") as f: pickle.dump(return_value, f, meta_cfg.PICKLE_PROTOCOL) print(str(return_value) + " pickled to " + save_name) else: pass # HACK how to solve logger problem? # logger.error("Could not pickle data, name for file (" + # str(save_name) + ") is not a string!" + # "\n Therefore, the following data was only returned" + # " but not saved! \n Data:" + str(return_value)) return return_value def try_unpickle(file_to_unpickle, use_metapath_bkwcomp=False): """Try to unpickle a file and return, otherwise just return input.""" file_to_unpickle = dev_tool.entries_to_str(file_to_unpickle) if is_pickle(file_to_unpickle): extra_path = meta_cfg.PICKLE_PATH if use_metapath_bkwcomp else "" with open(extra_path + file_to_unpickle, "rb") as f: file_to_unpickle = pickle.load(f) return file_to_unpickle
[ 37811, 198, 198, 31, 9800, 25, 40458, 8678, 354, 293, 366, 6747, 280, 2623, 1, 628, 198, 46162, 2200, 5222, 11617, 0, 23210, 25401, 19164, 6239, 1546, 34178, 374, 67, 13, 7890, 11, 374, 67, 13, 4029, 11, 374, 67, 13, 260, 6551, 11...
2.379442
7,598
from direct.directnotify import DirectNotifyGlobal import DistributedBoardOfficeAI from toontown.toonbase import ToontownGlobals from toontown.coghq.boardbothq import BoardOfficeLayout from direct.showbase import DirectObject import random
[ 6738, 1277, 13, 12942, 1662, 1958, 1330, 4128, 3673, 1958, 22289, 198, 11748, 4307, 6169, 29828, 27743, 20185, 198, 6738, 284, 756, 593, 13, 1462, 261, 8692, 1330, 1675, 756, 593, 9861, 672, 874, 198, 6738, 284, 756, 593, 13, 1073, 45...
3.75
64
from typing import Union def key_value_list(d: Union[dict, list], key=None) -> list: """ This function iterates over all the key-value pairs of a dictionary and returns a list of tuple (key, value) where the key contain only primitive value (i.e., no list or dict), e.g., string, number etc. d -- a dictionary to iterate through """ if not d: return [] if not isinstance(d, dict) and not isinstance(d, list): return [] key_values = [] if isinstance(d, list): for entry in d: if isinstance(entry, dict): key_values.extend(key_value_list(entry)) else: key_values.append((key, entry)) else: for k, v in d.items(): if k is None or v is None: continue if not isinstance(v, dict) and type(v) != list: key_values.append((k, v)) elif isinstance(v, list): key_values.extend(key_value_list(v, k)) else: key_values.extend(key_value_list(v)) return key_values def all_keys(d: Union[dict, list]) -> list: """ Returns a list of all the keys of a dictionary (duplicates included) d -- a dictionary to iterate through """ if not d: return [] if d is None or not isinstance(d, dict) and not isinstance(d, list): return [] keys = [] if isinstance(d, list): for entry in d: keys.extend(all_keys(entry)) else: for k, v in d.items(): keys.append(k) keys.extend(all_keys(v)) return keys def all_values(d: Union[dict, list]) -> list: """ Returns a list of all the primitive values of a dictionary (duplicates included) d -- a dictionary to iterate through """ if not d: return [] if not isinstance(d, dict) and not isinstance(d, list): return [d] values = [] if isinstance(d, list): for entry in d: values.extend(all_values(entry)) else: for k, v in d.items(): values.extend(all_values(v)) return values
[ 6738, 19720, 1330, 4479, 628, 198, 4299, 1994, 62, 8367, 62, 4868, 7, 67, 25, 4479, 58, 11600, 11, 1351, 4357, 1994, 28, 14202, 8, 4613, 1351, 25, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 770, 2163, 11629, 689, 625, 477, 262...
2.226376
963
from yampy.apis.utils import ArgumentConverter, none_filter, stringify_booleans from yampy.models import extract_id
[ 6738, 331, 696, 88, 13, 499, 271, 13, 26791, 1330, 45751, 3103, 332, 353, 11, 4844, 62, 24455, 11, 4731, 1958, 62, 2127, 2305, 504, 198, 6738, 331, 696, 88, 13, 27530, 1330, 7925, 62, 312, 628 ]
3.162162
37
# -*- coding: utf-8 -*- """Actions and snippets.""" # ----------------------------------------------------------------------------- # Imports # ----------------------------------------------------------------------------- import inspect from functools import partial, wraps import logging import re import sys import traceback from .qt import QKeySequence, QAction, require_qt, input_dialog, busy_cursor, _get_icon from phylib.utils import Bunch logger = logging.getLogger(__name__) # ----------------------------------------------------------------------------- # Snippet parsing utilities # ----------------------------------------------------------------------------- def _parse_arg(s): """Parse a number or string.""" try: return int(s) except ValueError: pass try: return float(s) except ValueError: pass return s def _parse_list(s): """Parse a comma-separated list of values (strings or numbers).""" # Range: 'x-y' if '-' in s: m, M = map(_parse_arg, s.split('-')) return list(range(m, M + 1)) # List of ids: 'x,y,z' elif ',' in s: return list(map(_parse_arg, s.split(','))) else: return _parse_arg(s) def _parse_snippet(s): """Parse an entire snippet command.""" return tuple(map(_parse_list, s.split(' '))) def _prompt_args(title, docstring, default=None): """Display a prompt dialog requesting function arguments. 'default' is a function returning the default value for the proposed input dialog. """ # There are args, need to display the dialog. # Extract Example: `...` in the docstring to put a predefined text # in the input dialog. logger.debug("Prompting arguments for %s", title) r = re.search('Example: `([^`]+)`', docstring) docstring_ = docstring[:r.start()].strip() if r else docstring try: text = str(default()) if default else (r.group(1) if r else None) except Exception as e: # pragma: no cover logger.error("Error while handling user input: %s", str(e)) return s, ok = input_dialog(title, docstring_, text) if not ok or not s: return # Parse user-supplied arguments and call the function. args = _parse_snippet(s) return args # ----------------------------------------------------------------------------- # Show shortcut utility functions # ----------------------------------------------------------------------------- def _get_shortcut_string(shortcut): """Return a string representation of a shortcut.""" if not shortcut: return '' if isinstance(shortcut, (tuple, list)): return ', '.join([_get_shortcut_string(s) for s in shortcut]) if isinstance(shortcut, str): if hasattr(QKeySequence, shortcut): shortcut = QKeySequence(getattr(QKeySequence, shortcut)) else: return shortcut.lower() assert isinstance(shortcut, QKeySequence) s = shortcut.toString() or '' return str(s).lower() def _get_qkeysequence(shortcut): """Return a QKeySequence or list of QKeySequence from a shortcut string.""" if shortcut is None: return [] if isinstance(shortcut, (tuple, list)): return [_get_qkeysequence(s) for s in shortcut] assert isinstance(shortcut, str) if hasattr(QKeySequence, shortcut): return QKeySequence(getattr(QKeySequence, shortcut)) sequence = QKeySequence.fromString(shortcut) assert not sequence.isEmpty() return sequence def _show_shortcuts(shortcuts): """Display shortcuts.""" out = [] for n in sorted(shortcuts): shortcut = _get_shortcut_string(shortcuts[n]) if not n.startswith('_') and not shortcut.startswith('-'): out.append('- {0:<40} {1:s}'.format(n, shortcut)) if out: print('Keyboard shortcuts') print('\n'.join(out)) print('') def _show_snippets(snippets): """Display snippets.""" out = [] for n in sorted(snippets): snippet = snippets[n] if not n.startswith('_'): out.append('- {0:<40} :{1:s}'.format(n, snippet)) if out: print('Snippets') print('\n'.join(out)) print('') def show_shortcuts_snippets(actions): """Show the shortcuts and snippets of an Actions instance.""" print(actions.name) print('-' * len(actions.name)) print() _show_shortcuts(actions.shortcuts) _show_snippets(actions._default_snippets) # ----------------------------------------------------------------------------- # Actions # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # Snippets # ----------------------------------------------------------------------------- def _enter(self): """Disable the snippet mode and execute the command.""" command = self.command logger.log(5, "Snippet keystroke `Enter`.") # NOTE: we need to set back the actions (mode_off) before running # the command. self.mode_off() self.run(command) def _create_snippet_actions(self): """Add mock Qt actions for snippet keystrokes. Used to enable snippet mode. """ # One action per allowed character. for i, char in enumerate(self._snippet_chars): # Lowercase letters. self.actions.add( name='_snippet_{}'.format(i), shortcut=char, callback=_make_func(char)) # Uppercase letters. if char in self._snippet_chars[:26]: self.actions.add( name='_snippet_{}_upper'.format(i), shortcut='shift+' + char, callback=_make_func(char.upper())) self.actions.add( name='_snippet_backspace', shortcut='backspace', callback=self._backspace) self.actions.add( name='_snippet_activate', shortcut=('enter', 'return'), callback=self._enter) self.actions.add( name='_snippet_disable', shortcut='escape', callback=self.mode_off) def run(self, snippet): """Execute a snippet command. May be overridden. """ assert snippet[0] == ':' snippet = snippet[1:] snippet_args = _parse_snippet(snippet) name = snippet_args[0] logger.debug("Processing snippet `%s`.", snippet) try: # Try to run the snippet on all attached Actions instances. for actions in self.gui.actions: try: actions.run(name, *snippet_args[1:]) return except ValueError: # This Actions instance doesn't contain the requested # snippet, trying the next attached Actions instance. pass logger.warning("Couldn't find action `%s`.", name) except Exception as e: logger.warning("Error when executing snippet: \"%s\".", str(e)) logger.debug(''.join(traceback.format_exception(*sys.exc_info()))) def is_mode_on(self): """Whether the snippet mode is enabled.""" return self.command.startswith(':') def mode_on(self): """Enable the snippet mode.""" logger.debug("Snippet mode enabled, press `escape` to leave this mode.") # Save the current status message. self._status_message = self.gui.status_message self.gui.lock_status() # Silent all actions except the Snippets actions. for actions in self.gui.actions: if actions != self.actions: actions.disable() self.actions.enable() self.command = ':' def mode_off(self): """Disable the snippet mode.""" self.gui.unlock_status() # Reset the GUI status message that was set before the mode was # activated. self.gui.status_message = self._status_message # Re-enable all actions except the Snippets actions. self.actions.disable() for actions in self.gui.actions: if actions != self.actions: actions.enable() # The `:` shortcut should always be enabled. self.actions.enable('enable_snippet_mode')
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 32, 2733, 290, 45114, 526, 15931, 628, 198, 2, 16529, 32501, 198, 2, 1846, 3742, 198, 2, 16529, 32501, 198, 198, 11748, 10104, 198, 6738, 1257, 310, 10141, ...
2.570377
3,261
""" delete all .pyc bytecode files in a directory tree: use the command line arg as root if given, else current working dir """ import os, sys findonly = False rootdir = os.getcwd() if len(sys.argv) == 1 else sys.argv[1] found = removed = 0 for (thisDirLevel, subsHere, filesHere) in os.walk(rootdir): for filename in filesHere: if filename.endswith('.pyc'): fullname = os.path.join(thisDirLevel, filename) print('=>', fullname) if not findonly: try: os.remove(fullname) removed += 1 except: type, inst = sys.exc_info()[:2] print('*'*4, 'Failed:', filename, type, inst) found += 1 print('Found', found, 'files, removed', removed)
[ 37811, 198, 33678, 477, 764, 9078, 66, 18022, 8189, 3696, 287, 257, 8619, 5509, 25, 779, 262, 198, 21812, 1627, 1822, 355, 6808, 611, 1813, 11, 2073, 1459, 1762, 26672, 198, 37811, 198, 198, 11748, 28686, 11, 25064, 198, 19796, 8807, ...
2.10705
383
from django.apps import AppConfig
[ 6738, 42625, 14208, 13, 18211, 1330, 2034, 16934, 628 ]
3.888889
9
import boto3 from logger import logger
[ 11748, 275, 2069, 18, 198, 198, 6738, 49706, 1330, 49706, 628 ]
3.727273
11
from typing import Any, Dict, Optional, Type, Union from cx_const import Light, PredefinedActionsMapping from cx_core.color_helper import get_color_wheel from cx_core.controller import action from cx_core.feature_support.light import LightSupport from cx_core.integration import EventData from cx_core.integration.deconz import DeCONZIntegration from cx_core.integration.z2m import Z2MIntegration from cx_core.release_hold_controller import ReleaseHoldController from cx_core.stepper import Stepper from cx_core.stepper.circular_stepper import CircularStepper from cx_core.stepper.minmax_stepper import MinMaxStepper from cx_core.type_controller import Entity, TypeController DEFAULT_MANUAL_STEPS = 10 DEFAULT_AUTOMATIC_STEPS = 10 DEFAULT_MIN_BRIGHTNESS = 1 DEFAULT_MAX_BRIGHTNESS = 255 DEFAULT_MIN_WHITE_VALUE = 1 DEFAULT_MAX_WHITE_VALUE = 255 DEFAULT_MIN_COLOR_TEMP = 153 DEFAULT_MAX_COLOR_TEMP = 500 DEFAULT_TRANSITION = 300 DEFAULT_ADD_TRANSITION = True DEFAULT_TRANSITION_TURN_TOGGLE = False ColorMode = str # Once the minimum supported version of Python is 3.8, # we can declare the ColorMode as a Literal # ColorMode = Literal["auto", "xy_color", "color_temp"]
[ 6738, 19720, 1330, 4377, 11, 360, 713, 11, 32233, 11, 5994, 11, 4479, 198, 198, 6738, 43213, 62, 9979, 1330, 4401, 11, 14322, 18156, 32, 2733, 44, 5912, 198, 6738, 43213, 62, 7295, 13, 8043, 62, 2978, 525, 1330, 651, 62, 8043, 62, ...
3.111406
377
from typing import Union import pandas as pd from kts.core.frame import KTSFrame AnyFrame = Union[pd.DataFrame, KTSFrame]
[ 6738, 19720, 1330, 4479, 198, 198, 11748, 19798, 292, 355, 279, 67, 198, 198, 6738, 479, 912, 13, 7295, 13, 14535, 1330, 509, 4694, 19778, 198, 198, 7149, 19778, 796, 4479, 58, 30094, 13, 6601, 19778, 11, 509, 4694, 19778, 60, 198 ]
2.97619
42
from app import db from flask.ext.login import UserMixin
[ 6738, 598, 1330, 20613, 198, 6738, 42903, 13, 2302, 13, 38235, 1330, 11787, 35608, 259, 628, 198 ]
3.470588
17
import markdown from comments.forms import CommentForm,BookCommentForm,MovieCommentForm from django.shortcuts import render, get_object_or_404 from.models import Post,Category,Tag, Book,Movie #from django.http import HttpResponse from django.views.generic import ListView, DetailView from django.utils.text import slugify from markdown.extensions.toc import TocExtension from django.db.models import Q """ def index(request): #post_list = Post.objects.all().order_by('-created_time') post_list = Post.objects.all() return render(request, 'blog/index.html', context={'post_list': post_list}) """ # """ def detail(request, pk): post = get_object_or_404(Post, pk=pk) # +1 post.increase_views() post.body = markdown.markdown(post.body, extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', 'markdown.extensions.toc', 'markdown.extensions.tables', ]) form = CommentForm() # post comment_list = post.comment_set.all() # detail.html context = {'post': post, 'form': form, 'comment_list': comment_list } return render(request, 'blog/detail.html', context=context) """ # """ def archives(request, year, month): post_list = Post.objects.filter(created_time__year=year, created_time__month=month ).order_by('-created_time') return render(request, 'blog/index.html', context={'post_list': post_list}) """ # """ def category(request, pk): cate = get_object_or_404(Category, pk=pk) post_list = Post.objects.filter(category=cate).order_by('-created_time') return render(request, 'blog/index.html', context={'post_list': post_list}) """ # # def search(request): q = request.GET.get('q') error_msg = '' if not q: error_msg = "" return render(request, 'blog/index.html', {'error_msg': error_msg}) post_list = Post.objects.filter(Q(title__icontains=q) | Q(body__icontains=q)) return render(request, 'blog/index.html', {'error_msg': error_msg, 'post_list': post_list}) # # ### # def about(request): return render(request, 'blog/about.html')
[ 11748, 1317, 2902, 198, 6738, 3651, 13, 23914, 1330, 18957, 8479, 11, 10482, 21357, 8479, 11, 25097, 21357, 8479, 198, 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 11, 651, 62, 15252, 62, 273, 62, 26429, 198, 6738, 13, 27530, 1330,...
2.152632
1,140
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- # pylint: disable=line-too-long from azure.cli.core.commands.parameters import resource_group_name_type from knack.arguments import CLIArgumentType from ._validators import (validate_alert_status, validate_auto_provisioning_toggle, validate_pricing_tier) name_arg_type = CLIArgumentType(options_list=('--name', '-n'), metavar='NAME', help='name of the resource to be fetched') home_region_arg_type = CLIArgumentType(options_list=('--home-region', '-hr'), metavar='HOMEREGION', help='home region that was selected for the subscription') location_arg_type = CLIArgumentType(options_list=('--location', '-l'), metavar='LOCATION', help='location of the resource') # Alerts alert_status_arg_type = CLIArgumentType(options_list=('--status'), metavar='STATUS', help='target status of the alert. possible values are "dismiss" and "activate"') # Auto Provisioning auto_provisioning_auto_provision_arg_type = CLIArgumentType(options_list=('--auto-provision'), metavar='AUTOPROVISION', help='Automatic provisioning toggle. possible values are "on" or "off"') # Contacts contact_email_arg_type = CLIArgumentType(options_list=('--email'), metavar='EMAIL', help='E-mail of the security contact') contact_phone_arg_type = CLIArgumentType(options_list=('--phone'), metavar='PHONE', help='Phone of the security contact') contact_alert_notifications_arg_type = CLIArgumentType(options_list=('--alert-notifications'), metavar='ALERTNOTIFICATIONS', help='Whether to send mail notifications to the security contacts') contact_alerts_admins_arg_type = CLIArgumentType(options_list=('--alerts-admins'), metavar='ALERTADMINS', help='Whether to send mail notifications to the subscription administrators') # Pricing pricing_tier_arg_type = CLIArgumentType(options_list=('--tier'), metavar='TIER', help='pricing tier type') # Workspace settings workspace_setting_target_workspace_arg_type = CLIArgumentType(options_list=('--target-workspace'), metavar='TARGETWORKSPACE', help='An ID of the workspace resource that will hold the security data')
[ 2, 16529, 1783, 10541, 198, 2, 15069, 357, 66, 8, 5413, 10501, 13, 1439, 2489, 10395, 13, 198, 2, 49962, 739, 262, 17168, 13789, 13, 4091, 13789, 13, 14116, 287, 262, 1628, 6808, 329, 5964, 1321, 13, 198, 2, 16529, 1783, 10541, 198,...
3.409283
711
import sys IMAGES_PATH = sys.path[1] + "/Images" BACKGROUND_IMAGES_PATH = IMAGES_PATH + '/background' USER_INFO_BACKGROUND_PATH = BACKGROUND_IMAGES_PATH+"/blue_background.jpg" SPRINT_IMAGE_PATH = IMAGES_PATH + '/sprite' PROFILE_IMAGES_PATH = IMAGES_PATH + '/profile' CONFIGURATION_FILES_PATH = sys.path[1] + "/configuration_files"
[ 11748, 25064, 628, 198, 3955, 25552, 62, 34219, 796, 25064, 13, 6978, 58, 16, 60, 1343, 12813, 29398, 1, 198, 31098, 46025, 62, 3955, 25552, 62, 34219, 796, 45325, 62, 34219, 1343, 31051, 25249, 6, 198, 29904, 62, 10778, 62, 31098, 46...
2.789916
119
import unittest import torch from parameterized import parameterized from src.constructor import create_backbone from src.models.backbones.utils import list_models from .test_segmentation import example_backbones
[ 11748, 555, 715, 395, 198, 198, 11748, 28034, 198, 6738, 11507, 1143, 1330, 11507, 1143, 198, 198, 6738, 12351, 13, 41571, 273, 1330, 2251, 62, 1891, 15992, 198, 6738, 12351, 13, 27530, 13, 1891, 35095, 13, 26791, 1330, 1351, 62, 27530,...
3.875
56
import typing from . import base from . import fields from .inline_query_result import InlineQueryResult from .location import Location from .user import User
[ 11748, 19720, 198, 198, 6738, 764, 1330, 2779, 198, 6738, 764, 1330, 7032, 198, 6738, 764, 45145, 62, 22766, 62, 20274, 1330, 554, 1370, 20746, 23004, 198, 6738, 764, 24886, 1330, 13397, 198, 6738, 764, 7220, 1330, 11787, 628 ]
4.128205
39