content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
import io import os import re import zipfile import flask import markdown import blueprints.example import blueprints.home import blueprints.presentation import blueprints.transformations if __name__ == '__main__': main()
[ 11748, 33245, 198, 11748, 28686, 198, 11748, 302, 198, 11748, 19974, 7753, 198, 198, 11748, 42903, 198, 11748, 1317, 2902, 198, 198, 11748, 4171, 17190, 13, 20688, 198, 11748, 4171, 17190, 13, 11195, 198, 11748, 4171, 17190, 13, 25579, 34...
3.42029
69
import os, time import numpy as np import logging import fire import torch import torch.optim as optim import torch.nn as nn from torch.utils.data import DataLoader from model import * from dataset import * if __name__ == '__main__': fire.Fire({ 'train': main, 'test': score, })
[ 11748, 28686, 11, 640, 201, 198, 11748, 299, 32152, 355, 45941, 201, 198, 11748, 18931, 201, 198, 11748, 2046, 201, 198, 201, 198, 11748, 28034, 201, 198, 11748, 28034, 13, 40085, 355, 6436, 201, 198, 11748, 28034, 13, 20471, 355, 299, ...
2.477612
134
# -*- coding: utf-8 -*- """ download file using requests Created on Fri Jul 3 09:13:04 2015 @author: poldrack """ import requests import os from requests.packages.urllib3.util import Retry from requests.adapters import HTTPAdapter from requests import Session, exceptions # from http://stackoverflow.com/questions/16694907/how-to-download-large-file-in-python-with-requests-py
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 15002, 2393, 1262, 7007, 198, 198, 41972, 319, 19480, 5979, 220, 513, 7769, 25, 1485, 25, 3023, 1853, 198, 198, 31, 9800, 25, 279, 727, 39638, 198, 37811, ...
3.122951
122
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2011 Fourth Paradigm Development, 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 django import template from django import http from django.conf import settings from django.contrib.auth.decorators import login_required from django.shortcuts import render_to_response from django.utils.translation import ugettext as _ import datetime import logging from django.contrib import messages from django_openstack import api from django_openstack import forms from django_openstack.dash.views import instances as dash_instances from openstackx.api import exceptions as api_exceptions TerminateInstance = dash_instances.TerminateInstance RebootInstance = dash_instances.RebootInstance LOG = logging.getLogger('django_openstack.syspanel.views.instances')
[ 2, 43907, 25, 7400, 11338, 28, 19, 6482, 10394, 28, 19, 2705, 8658, 11338, 28, 19, 198, 198, 2, 15069, 2813, 1578, 1829, 5070, 355, 7997, 416, 262, 198, 2, 22998, 286, 262, 2351, 15781, 261, 2306, 873, 290, 4687, 8694, 13, 198, 2,...
3.6
420
from datetime import datetime as dt from bitmap import Bitmap, PilBitmap h = 500 w = 500 image = Bitmap(w, h, alpha=True) pil_image = PilBitmap(w, h, alpha=True) color_red = 0 for i in range(h): for j in range(w): image.set_rgba_pixel(j, i, color_red, 0, 0, 150) pil_image.set_rgba_pixel(j, i, color_red, 0, 0, 150) color_red += 1 path = "images/im1_" + dt.now().strftime("%Y-%m-%d_%H:%M:%S") + ".png" print("Image saved: " + path) image.save_as_png(path) path = "images/im2_" + dt.now().strftime("%Y-%m-%d_%H:%M:%S") + ".png" print("Image saved: " + path) pil_image.save_as_png(path)
[ 6738, 4818, 8079, 1330, 4818, 8079, 355, 288, 83, 198, 6738, 1643, 8899, 1330, 4722, 8899, 11, 12693, 13128, 8899, 198, 198, 71, 796, 5323, 198, 86, 796, 5323, 198, 9060, 796, 4722, 8899, 7, 86, 11, 289, 11, 17130, 28, 17821, 8, 1...
2.117647
289
# Copyright AllSeen Alliance. All rights reserved. # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import validate import common def get_indirection_level(signature): """Get the number of dimensions in the array or 0 if not an array.""" return len(signature) - len(signature.lstrip('a')) def get_base_signature(signature, index = 0): """Return the base signature i.e. 'i', 'ai', and 'aai' all return 'i'.""" return signature[index:len(signature)].lstrip('a') def is_array(signature): """Return True if this argument is an array. A dictionary is considered an array.""" return signature[0] == "a" def is_structure(signature): """Return True if the base argument type is a structure.""" sig = get_base_signature(signature) return sig[0] == '(' def is_dictionary(signature): """Return True if the base argument type is a dictionary.""" sig = get_base_signature(signature) return signature[0] == 'a' and sig[0] == '{' def is_dictionary_array(signature): """Return True if the base argument type is an array of dictionaries.""" return is_dictionary(signature) and get_indirection_level(signature) > 1 def __find_end_of_type(signature, index = 0): """Returns the index of the start of the next type starting at 'index'. If there are no more types then return the end of the type signature. For example: ("ab", 0) returns 1 ("ab", 1) returns 2 ("aab", 0) returns 1 ("aab", 1) returns 1 ("aab", 2) returns 3 ("abb", 1) returns 2 ("abb", 2) returns 3 ("bqd", 0) returns 1 ("bqd", 1) returns 2 ("bqd", 2) returns 3 ("(bqd)", 0) returns 4 ("(bqd)", 1) returns 2 ("(bqd)", 2) returns 3 ("(bqd)", 3) returns 4 ("(bqd)", 4) returns 5 ("(bqd(bad))", 0) returns 9 ("(bqd(bad))", 1) returns 2 ("(bqd(bad))", 2) returns 3 ("(bqd(bad))", 3) returns 4 ("(bqd(bad))", 4) returns 8 ("(bqd(bad))", 5) returns 6""" assert(index < len(signature)) c = signature[index] if c == '(': end_index = __find_container_end(signature, index, ')') elif c == '{': end_index = __find_container_end(signature, index, '}') elif c == 'a': base = get_base_signature(signature, index) end_index = __find_end_of_type(base) end_index += index + get_indirection_level(signature, index) else: end_index = index + 1 return end_index def is_basic_type(signature): """Returns True if the signature is a basic type 'a', '(', '{', and 'v' are not considered basic types because they usually cannot be handled the same as other types.""" basic_types = ('b','d', 'g', 'i','n','o','q','s','t','u','x','y') return signature in basic_types def get_max_array_dimension(signature): """Gets the number of array dimensions in this signature.""" return_value = 0 while signature.find((return_value + 1) * 'a') != -1: return_value += 1 return return_value def split_signature(sig): """splits a container signature into individual fields.""" components = [] index = 1 while index < len(sig)-1: part = sig[index:] startindex = get_indirection_level(part) endindex = __find_end_of_type(part, startindex) components.append(part[:endindex]) index = index + endindex return components
[ 2, 15069, 1439, 4653, 268, 10302, 13, 1439, 2489, 10395, 13, 198, 2, 198, 2, 2448, 3411, 284, 779, 11, 4866, 11, 13096, 11, 290, 14, 273, 14983, 428, 3788, 329, 597, 198, 2, 4007, 351, 393, 1231, 6838, 318, 29376, 7520, 11, 2810, ...
2.725676
1,480
# Generated by Django 2.0.2 on 2018-06-13 22:10 from django.conf import settings from django.db import migrations, models import django.db.models.deletion
[ 2, 2980, 515, 416, 37770, 362, 13, 15, 13, 17, 319, 2864, 12, 3312, 12, 1485, 2534, 25, 940, 198, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 11748, 42625, 1420...
3.019231
52
# coding=utf-8 # Copyright 2020 The Learning-to-Prompt 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 Learning-to-Prompt governing permissions and # limitations under the License. # ============================================================================== """Input preprocesses.""" from typing import Any, Callable, Dict, Optional import ml_collections from augment import augment_utils import tensorflow as tf IMAGENET_DEFAULT_MEAN = (0.485, 0.456, 0.406) IMAGENET_DEFAULT_STD = (0.229, 0.224, 0.225) CIFAR10_MEAN = (0.4914, 0.4822, 0.4465) CIFAR10_STD = (0.2471, 0.2435, 0.2616) CIFAR100_MEAN = (0.5071, 0.4867, 0.4408) CIFAR100_STD = (0.2675, 0.2565, 0.2761) # Constants for configuring config.<name> RANDOM_ERASING = "randerasing" AUGMENT = "augment" MIX = "mix" COLORJITTER = "colorjitter" create_mix_augment = augment_utils.create_mix_augment def resize_small(image: tf.Tensor, size: int, *, antialias: bool = False) -> tf.Tensor: """Resizes the smaller side to `size` keeping aspect ratio. Args: image: Single image as a float32 tensor. size: an integer, that represents a new size of the smaller side of an input image. antialias: Whether to use an anti-aliasing filter when downsampling an image. Returns: A function, that resizes an image and preserves its aspect ratio. """ h, w = tf.shape(image)[0], tf.shape(image)[1] # Figure out the necessary h/w. ratio = (tf.cast(size, tf.float32) / tf.cast(tf.minimum(h, w), tf.float32)) h = tf.cast(tf.round(tf.cast(h, tf.float32) * ratio), tf.int32) w = tf.cast(tf.round(tf.cast(w, tf.float32) * ratio), tf.int32) image = tf.image.resize(image, [h, w], antialias=antialias) return image def central_crop(image: tf.Tensor, size: int) -> tf.Tensor: """Makes central crop of a given size.""" h, w = size, size top = (tf.shape(image)[0] - h) // 2 left = (tf.shape(image)[1] - w) // 2 image = tf.image.crop_to_bounding_box(image, top, left, h, w) return image def decode_and_random_resized_crop(image: tf.Tensor, rng, resize_size: int) -> tf.Tensor: """Decodes the images and extracts a random crop.""" shape = tf.io.extract_jpeg_shape(image) begin, size, _ = tf.image.stateless_sample_distorted_bounding_box( shape, tf.zeros([0, 0, 4], tf.float32), seed=rng, area_range=(0.05, 1.0), min_object_covered=0, # Don't enforce a minimum area. use_image_if_no_bounding_boxes=True) top, left, _ = tf.unstack(begin) h, w, _ = tf.unstack(size) image = tf.image.decode_and_crop_jpeg(image, [top, left, h, w], channels=3) image = tf.cast(image, tf.float32) / 255.0 image = tf.image.resize(image, (resize_size, resize_size)) return image def train_preprocess(features: Dict[str, tf.Tensor], crop_size: int = 224) -> Dict[str, tf.Tensor]: """Processes a single example for training.""" image = features["image"] # This PRNGKey is unique to this example. We can use it with the stateless # random ops in TF. rng = features.pop("rng") rng, rng_crop, rng_flip = tf.unstack( tf.random.experimental.stateless_split(rng, 3)) image = decode_and_random_resized_crop(image, rng_crop, resize_size=crop_size) image = tf.image.stateless_random_flip_left_right(image, rng_flip) return {"image": image, "label": features["label"]} def train_cifar_preprocess(features: Dict[str, tf.Tensor]): """Augmentation function for cifar dataset.""" image = tf.io.decode_jpeg(features["image"]) image = tf.image.resize_with_crop_or_pad(image, 32 + 4, 32 + 4) rng = features.pop("rng") rng, rng_crop, rng_flip = tf.unstack( tf.random.experimental.stateless_split(rng, 3)) # Randomly crop a [HEIGHT, WIDTH] section of the image. image = tf.image.stateless_random_crop(image, [32, 32, 3], rng_crop) # Randomly flip the image horizontally image = tf.image.stateless_random_flip_left_right(image, rng_flip) image = tf.cast(image, tf.float32) / 255.0 return {"image": image, "label": features["label"]} def get_augment_preprocess( augment_params: ml_collections.ConfigDict, *, colorjitter_params: Optional[ml_collections.ConfigDict] = None, randerasing_params: Optional[ml_collections.ConfigDict] = None, mean: Optional[tf.Tensor] = None, std: Optional[tf.Tensor] = None, basic_process: Callable[[Dict[str, tf.Tensor]], Dict[str, tf.Tensor]] = train_preprocess, ) -> Callable[[Dict[str, tf.Tensor]], Dict[str, tf.Tensor]]: """Creates a custom augmented image preprocess.""" augmentor = None # If augment_params.type is noop/default, we skip. if augment_params and augment_params.get( "type") and augment_params.type not in ("default", "noop"): augmentor = augment_utils.create_augmenter(**augment_params.to_dict()) jitter = None if colorjitter_params and colorjitter_params.type not in ("default", "noop"): jitter = augment_utils.create_augmenter(**colorjitter_params.to_dict()) return train_custom_augment_preprocess def eval_preprocess(features: Dict[str, tf.Tensor], mean: Optional[tf.Tensor] = None, std: Optional[tf.Tensor] = None, input_size: int = 256, crop_size: int = 224) -> Dict[str, tf.Tensor]: """Process a single example for evaluation.""" image = features["image"] assert image.dtype == tf.uint8 image = tf.cast(image, tf.float32) / 255.0 # image = resize_small(image, size=int(256 / 224 * input_size)) # image = central_crop(image, size=input_size) image = resize_small(image, size=input_size) # e.g. 256, 448 image = central_crop(image, size=crop_size) # e.g. 224, 384 if mean is not None: _check_valid_mean_std(mean, std) image = (image - mean) / std return {"image": image, "label": features["label"]} def cifar_eval_preprocess( features: Dict[str, tf.Tensor], mean: Optional[tf.Tensor] = None, std: Optional[tf.Tensor] = None) -> Dict[str, tf.Tensor]: """Processes a single example for evaluation for cifar.""" image = features["image"] assert image.dtype == tf.uint8 image = tf.cast(image, tf.float32) / 255.0 if mean is not None: _check_valid_mean_std(mean, std) image = (image - mean) / std return {"image": image, "label": features["label"]}
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 15069, 12131, 383, 18252, 12, 1462, 12, 24129, 457, 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, ...
2.570999
2,662
from __future__ import absolute_import, division, print_function from matplotlib.backends.backend_qt5 import NavigationToolbar2QT from glue.config import viewer_tool from glue.viewers.common.tool import CheckableTool, Tool __all__ = ['MatplotlibTool', 'MatplotlibCheckableTool', 'HomeTool', 'SaveTool', 'PanTool', 'ZoomTool']
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 11, 7297, 11, 3601, 62, 8818, 198, 198, 6738, 2603, 29487, 8019, 13, 1891, 2412, 13, 1891, 437, 62, 39568, 20, 1330, 42115, 25391, 5657, 17, 48, 51, 198, 198, 6738, 22749, 13, 11250, 1...
3.034783
115
import matplotlib.pyplot as plt import numpy as np from ipywidgets import interactive, interactive_output, fixed, HBox, VBox import ipywidgets as widgets
[ 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 20966, 88, 28029, 11407, 1330, 14333, 11, 14333, 62, 22915, 11, 5969, 11, 367, 14253, 11, 569, 14253, 198, 11748, 20966, 88, 28029, ...
3.333333
48
#!/usr/bin/env python import os import sys import jieba import numpy as np jieba.setLogLevel(60) # quiet fname = sys.argv[1] with open(fname) as f: text = f.read() tokenizer = jieba.Tokenizer() tokens = list(tokenizer.cut(text)) occurences = np.array([tokenizer.FREQ[w] for w in tokens if w in tokenizer.FREQ]) difficulties = 1 / (occurences + 1) max_occurence = np.max(list(tokenizer.FREQ.values())) min_score = 1 / (max_occurence + 1) max_score = 1 perc = 75 mean = np.mean(difficulties) median = np.percentile(difficulties, perc) normalized_mean = norm(mean) normalized_median = norm(median) print( f"{os.path.basename(fname)}: " f"mean: {normalized_mean:.6f}, {perc}th percentile: {normalized_median:.6f} " f"in [0: trivial, 1: hardest]" ) import matplotlib.pyplot as plt clipped = difficulties[(difficulties <= 0.01) & (difficulties >= 0.0001)] plt.hist(clipped, bins=20, density=True) ax = plt.gca() ax.set_title(fname) plt.show()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 11748, 28686, 198, 11748, 25064, 198, 198, 11748, 474, 494, 7012, 198, 11748, 299, 32152, 355, 45941, 198, 198, 73, 494, 7012, 13, 2617, 11187, 4971, 7, 1899, 8, 220, 1303, 5897, 198, ...
2.375
408
from itertools import tee from typing import Dict, Iterator, List, Sequence, Tuple from brown_clustering.defaultvaluedict import DefaultValueDict Corpus = Sequence[Sequence[str]]
[ 6738, 340, 861, 10141, 1330, 30479, 198, 6738, 19720, 1330, 360, 713, 11, 40806, 1352, 11, 7343, 11, 45835, 11, 309, 29291, 198, 198, 6738, 7586, 62, 565, 436, 1586, 13, 12286, 39728, 713, 1330, 15161, 11395, 35, 713, 198, 198, 45680,...
3.45283
53
from .base import *
[ 6738, 764, 8692, 1330, 1635, 628, 628, 198 ]
3
8
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2018 JiNong, Inc. # All right reserved. # """ Utility Functions . """ import time import math import logging import logging.handlers if __name__ == '__main__': st = SunTime(128.856632, 37.798953) print("rise", st.getsunrise(), "set", st.getsunset())
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 15069, 357, 66, 8, 2864, 29380, 45, 506, 11, 3457, 13, 198, 2, 1439, 826, 10395, 13, 198, 2, 198, 198,...
2.550388
129
# -*- encoding:utf-8 -*- # @Time : 2019/10/23 15:45 # @Author : gfjiang # @Site : # @File : __init__.py # @Software: PyCharm
[ 2, 532, 9, 12, 21004, 25, 40477, 12, 23, 532, 9, 12, 201, 198, 2, 2488, 7575, 220, 220, 220, 1058, 13130, 14, 940, 14, 1954, 1315, 25, 2231, 201, 198, 2, 2488, 13838, 220, 1058, 308, 69, 39598, 201, 198, 2, 2488, 29123, 220, 2...
1.894737
76
import sys # for development sys.path.append('../../src') from screencastscript import ScreencastScript # noqa: E402 screencast = ScreencastScript() screencast.sleep(1) screencast.i3wm_focus_left() screencast.sleep(1) screencast.i3wm_zoom_in() screencast.sleep(1) screencast.i3wm_zoom_out() screencast.sleep(1) screencast.i3wm_focus_right() screencast.sleep(1) screencast.i3wm_focus_up() screencast.sleep(1) screencast.i3wm_focus_down() screencast.sleep(1) screencast.i3wm_toggle_fullscreen() screencast.sleep(1) screencast.i3wm_ws_2() screencast.sleep(1) screencast.i3wm_ws_1() screencast.sleep(1)
[ 11748, 25064, 198, 2, 329, 2478, 198, 17597, 13, 6978, 13, 33295, 10786, 40720, 40720, 10677, 11537, 198, 198, 6738, 3159, 2701, 12048, 1330, 15216, 2701, 7391, 220, 1303, 645, 20402, 25, 412, 32531, 198, 198, 9612, 2701, 796, 15216, 27...
2.504098
244
""" computes the mean hippocampal-cortical functional connectivity (fc) matrix, for the left hemisphere subfields """ import os import h5py import numpy as np # data dirs ddir = '../data/' conndir = '../data/tout_hippoc/' odir = '../data/tout_group/' # get HCP - S900 subject list subjlist = '../data/subjectListS900_QC_gr.txt' f = open(subjlist); mylist = f.read().split("\n"); f.close() subjlist = joinedlist = mylist[:-1] print('We have now %i subjects... ' % (len(subjlist))) # 709 fc_left = np.zeros((4096, 360)) j = 0 for subjID in subjlist: fname = os.path.join(conndir, 'HCP_' + subjID + '_left.h5') f = h5py.File(fname, 'r') f = np.array(f['HCP_' + subjID]) fc_left = fc_left + f j += 1 fc_left = fc_left / j h = h5py.File('../data/tout_group/Hmean709_FC_left.h5', 'w') h.create_dataset('data', data = fc_left) h.close() print(fc_left.min(), fc_left.max(), fc_left.shape, j) # -0.005300521852874321, 0.39153784016161197, (4096, 360), 709
[ 37811, 198, 5589, 1769, 262, 1612, 28253, 282, 12, 66, 419, 605, 10345, 19843, 357, 16072, 8, 17593, 11, 198, 1640, 262, 1364, 33169, 850, 25747, 198, 37811, 198, 11748, 28686, 198, 11748, 289, 20, 9078, 198, 11748, 299, 32152, 355, 4...
2.180435
460
"""A setuptools based setup module. See: https://packaging.python.org/en/latest/distributing.html https://github.com/pypa/sampleproject """ #To install: # py -3 setup.py sdist # pip3 install . # Always prefer setuptools over distutils from setuptools import setup, find_packages from os import path from io import open #from reptools import __version__ here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() #Get the version # Arguments marked as "Required" below must be included for upload to PyPI. # Fields marked as "Optional" may be commented out. setup( name='reptools', version=open("reptools/version.py").readlines()[-1].split()[-1].strip("\"'"), # https://packagiATR01400 ng.python.org/specifications/core-metadata/#summary description='Tools for processing Rep-seq data', # https://packaging.python.org/specifications/core-metadata/#description-optional long_description=long_description, # https://packaging.python.org/specifications/core-metadata/#description-content-type-optional long_description_content_type='text/markdown', # https://packaging.python.org/specifications/core-metadata/#home-page-optional #url='', # Optional author='Stephen Preston', author_email='stephen.preston@zoo.ox.ac.uk', # For a list of valid classifiers, see https://pypi.org/classifiers/ classifiers=[ # How mature is this project? Common values are # 3 - Alpha # 4 - Beta # 5 - Production/Stable 'Development Status :: 3 - Alpha', 'Intended Audience :: Immunologists', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', ], # Note that this is a string of words separated by whitespace, not a list. #keywords='sample setuptools development', # Optional # packages=find_packages(exclude=['contrib', 'docs', 'tests']), # Required # For an analysis of "install_requires" vs pip's requirements files see: # https://packaging.python.org/en/latest/requirements.html install_requires=['numpy','numba'], python_requires='>=3.7', #extras_require={ # Optional # 'dev': ['check-manifest'], # 'test': ['coverage'], #}, #package_data={ # Optional # 'sample': ['package_data.dat'], #}, # Although 'package_data' is the preferred approach, in some case you may # need to place data files outside of your packages. See: # http://docs.python.org/3.4/distutils/setupscript.html#installing-additional-files # # In this case, 'data_file' will be installed into '<sys.prefix>/my_data' #data_files=[('my_data', ['data/data_file'])], # Optional # The following provides a command called `reptools` which # executes the function `main` from the reptools.cli package when invoked: entry_points={ 'console_scripts': [ 'reptools=reptools.cli:main', ], }, # List additional URLs that are relevant to your project as a dict. # https://packaging.python.org/specifications/core-metadata/#project-url-multiple-use #project_urls={ # Optional # 'Bug Reports': 'https://github.com/pypa/sampleproject/issues', # 'Funding': 'https://donate.pypi.org', # 'Say Thanks!': 'http://saythanks.io/to/example', # 'Source': 'https://github.com/pypa/sampleproject/', #}, )
[ 37811, 32, 900, 37623, 10141, 1912, 9058, 8265, 13, 198, 198, 6214, 25, 198, 5450, 1378, 8002, 3039, 13, 29412, 13, 2398, 14, 268, 14, 42861, 14, 17080, 2455, 278, 13, 6494, 198, 5450, 1378, 12567, 13, 785, 14, 79, 4464, 64, 14, 3...
2.659527
1,354
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-10-18 14:23 from __future__ import unicode_literals from django.db import migrations, models
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 352, 13, 1157, 13, 17, 319, 2177, 12, 940, 12, 1507, 1478, 25, 1954, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, ...
2.736842
57
from wpc.report.issue import issue import xml.etree.cElementTree as etree from lxml import etree as letree from operator import itemgetter, attrgetter, methodcaller # TODO should this class contain info about the scan? or define a new class called report? # Version of script # Date, time of audit # Who the audit ran as (username, groups, privs) # ...
[ 6738, 266, 14751, 13, 13116, 13, 21949, 1330, 2071, 198, 11748, 35555, 13, 316, 631, 13, 66, 20180, 27660, 355, 2123, 631, 198, 6738, 300, 19875, 1330, 2123, 631, 355, 1309, 631, 198, 6738, 10088, 1330, 2378, 1136, 353, 11, 708, 81, ...
3.490196
102
#!/usr/bin/python """ From Mininet 2.2.1: convert simple documentation to epydoc/pydoctor-compatible markup """ from sys import stdin, stdout, argv import os from tempfile import mkstemp from subprocess import call import re spaces = re.compile(r'\s+') singleLineExp = re.compile(r'\s+"([^"]+)"') commentStartExp = re.compile(r'\s+"""') commentEndExp = re.compile(r'"""$') returnExp = re.compile(r'\s+(returns:.*)') lastindent = '' comment = False def fixParam(line): "Change foo: bar to @foo bar" result = re.sub(r'(\w+):', r'@param \1', line) result = re.sub(r' @', r'@', result) return result def fixReturns(line): "Change returns: foo to @return foo" return re.sub('returns:', r'@returns', line) if __name__ == '__main__': infile = open(argv[1]) outfid, outname = mkstemp() fixLines(infile.readlines(), outfid) infile.close() os.close(outfid) call([ 'doxypy', outname ])
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 198, 37811, 198, 4863, 1855, 42504, 362, 13, 17, 13, 16, 25, 10385, 2829, 10314, 284, 2462, 5173, 420, 14, 9078, 35580, 12, 38532, 41485, 198, 37811, 198, 198, 6738, 25064, 1330, 14367, 259, ...
2.423377
385
from django.views.generic import ListView, DetailView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.urls import reverse_lazy, reverse from django.shortcuts import redirect from .models import StockEntry, StockEntryLine from .forms import StockEntryForm, StockEntryLineForm, StockEntryLineIF from main.views import BaseView
[ 6738, 42625, 14208, 13, 33571, 13, 41357, 1330, 7343, 7680, 11, 42585, 7680, 198, 6738, 42625, 14208, 13, 33571, 13, 41357, 13, 19312, 1330, 13610, 7680, 11, 10133, 7680, 11, 23520, 7680, 198, 6738, 42625, 14208, 13, 6371, 82, 1330, 957...
3.615385
104
""" sentry.web.frontend.generic ~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from django.utils.translation import ugettext as _ from sentry.models import Team from sentry.permissions import can_create_teams from sentry.plugins import plugins from sentry.plugins.base import Response from sentry.web.decorators import login_required from sentry.web.helpers import render_to_response def static_media(request, **kwargs): """ Serve static files below a given point in the directory structure. """ from django.contrib.staticfiles.views import serve module = kwargs.get('module') path = kwargs.get('path', '') if module: path = '%s/%s' % (module, path) return serve(request, path, insecure=True) def missing_perm(request, perm, **kwargs): """ Returns a generic response if you're missing permission to perform an action. Plugins may overwrite this with the ``missing_perm_response`` hook. """ response = plugins.first('missing_perm_response', request, perm, **kwargs) if response: if isinstance(response, HttpResponseRedirect): return response if not isinstance(response, Response): raise NotImplementedError('Use self.render() when returning responses.') return response.respond(request, { 'perm': perm, }) if perm.label: return render_to_response('sentry/generic_error.html', { 'title': _('Missing Permission'), 'message': _('You do not have the required permissions to %s.') % (perm.label,) }, request) return HttpResponseRedirect(reverse('sentry'))
[ 37811, 198, 82, 13000, 13, 12384, 13, 8534, 437, 13, 41357, 198, 27156, 15116, 4907, 93, 198, 198, 25, 22163, 4766, 25, 357, 66, 8, 3050, 12, 4967, 416, 262, 11352, 563, 4816, 11, 766, 37195, 20673, 329, 517, 3307, 13, 198, 25, 43...
2.914992
647
import setuptools setuptools.setup( name="synmetric", version="0.2.dev1", license='MIT', author="Harsh Soni", author_email="author@example.com", description="Metric to evaluate data quality for synthetic data.", url="https://github.com/harsh020/synthetic_metric", download_url = 'https://github.com/harsh020/synthetic_metric/archive/v_02dev1.tar.gz', project_urls={ "Bug Tracker": "https://github.com/harsh020/synthetic_metric/issues", }, classifiers=[ "Development Status :: 3 - Alpha", "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], packages=setuptools.find_packages(), python_requires=">=3.6", install_requires = [ 'numpy', 'pandas', 'scikit-learn', 'scipy' ] )
[ 11748, 900, 37623, 10141, 628, 198, 2617, 37623, 10141, 13, 40406, 7, 198, 220, 220, 220, 1438, 2625, 28869, 4164, 1173, 1600, 198, 220, 220, 220, 2196, 2625, 15, 13, 17, 13, 7959, 16, 1600, 198, 220, 220, 220, 5964, 11639, 36393, 3...
2.38587
368
"""Submodule for NeuroKit.""" from .microstates_clean import microstates_clean from .microstates_peaks import microstates_peaks from .microstates_static import microstates_static from .microstates_dynamic import microstates_dynamic from .microstates_complexity import microstates_complexity from .microstates_segment import microstates_segment from .microstates_classify import microstates_classify from .microstates_plot import microstates_plot from .microstates_findnumber import microstates_findnumber __all__ = ["microstates_clean", "microstates_peaks", "microstates_static", "microstates_dynamic", "microstates_complexity", "microstates_segment", "microstates_classify", "microstates_plot", "microstates_findnumber"]
[ 37811, 7004, 21412, 329, 13782, 20827, 526, 15931, 198, 198, 6738, 764, 24055, 27219, 62, 27773, 1330, 4580, 27219, 62, 27773, 198, 6738, 764, 24055, 27219, 62, 431, 4730, 1330, 4580, 27219, 62, 431, 4730, 198, 6738, 764, 24055, 27219, ...
2.862676
284
from pytest import raises from notario.validators import Hybrid from notario.exceptions import Invalid from notario.decorators import optional from notario import validate
[ 6738, 12972, 9288, 1330, 12073, 198, 6738, 407, 4982, 13, 12102, 2024, 1330, 29481, 198, 6738, 407, 4982, 13, 1069, 11755, 1330, 17665, 198, 6738, 407, 4982, 13, 12501, 273, 2024, 1330, 11902, 198, 6738, 407, 4982, 1330, 26571, 628, 628...
4.268293
41
from django.urls import path, include from . import views from rest_framework import routers router = routers.SimpleRouter() router.register(r'players', views.PlayerView, basename='players') router.register(r'teams', views.TeamView, basename='teams') urlpatterns = [ path('', views.APIWelcomeView), path('', include((router.urls))), ]
[ 6738, 42625, 14208, 13, 6371, 82, 1330, 3108, 11, 2291, 198, 6738, 764, 1330, 5009, 198, 6738, 1334, 62, 30604, 1330, 41144, 198, 198, 472, 353, 796, 41144, 13, 26437, 49, 39605, 3419, 198, 472, 353, 13, 30238, 7, 81, 6, 32399, 3256...
3.008696
115
# Generated by Django 2.0.2 on 2020-11-01 20:04 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 362, 13, 15, 13, 17, 319, 12131, 12, 1157, 12, 486, 1160, 25, 3023, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.84375
32
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. import torchx.examples.apps.lightning_classy_vision.component as lightning_classy_vision from torchx.components.component_test_base import ComponentTestCase
[ 2, 15069, 357, 66, 8, 30277, 19193, 82, 11, 3457, 13, 290, 29116, 13, 198, 2, 1439, 2489, 10395, 13, 198, 2, 198, 2, 770, 2723, 2438, 318, 11971, 739, 262, 347, 10305, 12, 7635, 5964, 1043, 287, 262, 198, 2, 38559, 24290, 2393, ...
3.744898
98
import requests from sanic import Sanic from sanic.response import json from sanic_limiter import Limiter, get_remote_address from bs4 import BeautifulSoup app = Sanic() app.error_handler.add(Exception, ratelimit_handler) limiter = Limiter(app, global_limits=["1 per 3 seconds", "50 per hour"], key_func=get_remote_address) if __name__ == "__main__": app.run(host="0.0.0.0", port=9500)
[ 11748, 7007, 198, 198, 6738, 5336, 291, 1330, 2986, 291, 198, 6738, 5336, 291, 13, 26209, 1330, 33918, 198, 198, 6738, 5336, 291, 62, 2475, 2676, 1330, 7576, 2676, 11, 651, 62, 47960, 62, 21975, 198, 6738, 275, 82, 19, 1330, 23762, ...
2.875912
137
from os.path import join, dirname import numpy as np from .text import put_text from .. import const from ..os import makedirs from ..imprt import preset_import from ..log import get_logger logger = get_logger() def make_video( imgs, fps=24, outpath=None, method='matplotlib', dpi=96, bitrate=-1): """Writes a list of images into a grayscale or color video. Args: imgs (list(numpy.ndarray)): Each image should be of type ``uint8`` or ``uint16`` and of shape H-by-W (grayscale) or H-by-W-by-3 (RGB). fps (int, optional): Frame rate. outpath (str, optional): Where to write the video to (a .mp4 file). ``None`` means ``os.path.join(const.Dir.tmp, 'make_video.mp4')``. method (str, optional): Method to use: ``'matplotlib'``, ``'opencv'``, ``'video_api'``. dpi (int, optional): Dots per inch when using ``matplotlib``. bitrate (int, optional): Bit rate in kilobits per second when using ``matplotlib``; reasonable values include 7200. Writes - A video of the images. """ if outpath is None: outpath = join(const.Dir.tmp, 'make_video.mp4') makedirs(dirname(outpath)) assert imgs, "Frame list is empty" for frame in imgs: assert np.issubdtype(frame.dtype, np.unsignedinteger), \ "Image type must be unsigned integer" h, w = imgs[0].shape[:2] for frame in imgs[1:]: assert frame.shape[:2] == (h, w), \ "All frames must have the same shape" if method == 'matplotlib': import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from matplotlib import animation w_in, h_in = w / dpi, h / dpi fig = plt.figure(figsize=(w_in, h_in)) Writer = animation.writers['ffmpeg'] # may require you to specify path writer = Writer(fps=fps, bitrate=bitrate) anim = animation.ArtistAnimation(fig, [(img_plt(x),) for x in imgs]) anim.save(outpath, writer=writer) # If obscure error like "ValueError: Invalid file object: <_io.Buff..." # occurs, consider upgrading matplotlib so that it prints out the real, # underlying ffmpeg error plt.close('all') elif method == 'opencv': cv2 = preset_import('cv2', assert_success=True) # TODO: debug codecs (see http://www.fourcc.org/codecs.php) if outpath.endswith('.mp4'): # fourcc = cv2.VideoWriter_fourcc(*'MJPG') # fourcc = cv2.VideoWriter_fourcc(*'X264') fourcc = cv2.VideoWriter_fourcc(*'H264') # fourcc = 0x00000021 elif outpath.endswith('.avi'): fourcc = cv2.VideoWriter_fourcc(*'XVID') else: raise NotImplementedError("Video type of\n\t%s" % outpath) vw = cv2.VideoWriter(outpath, fourcc, fps, (w, h)) for frame in imgs: if frame.ndim == 3: frame = frame[:, :, ::-1] # cv2 uses BGR vw.write(frame) vw.release() elif method == 'video_api': video_api = preset_import('video_api', assert_success=True) assert outpath.endswith('.webm'), "`video_api` requires .webm" with video_api.write(outpath, fps=fps) as h: for frame in imgs: if frame.ndim == 3 and frame.shape[2] == 4: frame = frame[:, :, :3] #frame = frame.astype(np.ubyte) h.add_frame(frame) else: raise ValueError(method) logger.debug("Images written as a video to:\n%s", outpath) def make_comparison_video( imgs1, imgs2, bar_width=4, bar_color=(1, 0, 0), sweep_vertically=False, sweeps=1, label1='', label2='', font_size=None, font_ttf=None, label1_top_left_xy=None, label2_top_left_xy=None, **make_video_kwargs): """Writes two lists of images into a comparison video that toggles between two videos with a sweeping bar. Args: imgs? (list(numpy.ndarray)): Each image should be of type ``uint8`` or ``uint16`` and of shape H-by-W (grayscale) or H-by-W-by-3 (RGB). bar_width (int, optional): Width of the sweeping bar. bar_color (tuple(float), optional): Bar and label RGB, normalized to :math:`[0,1]`. Defaults to red. sweep_vertically (bool, optional): Whether to sweep vertically or horizontally. sweeps (int, optional): Number of sweeps. label? (str, optional): Label for each video. font_size (int, optional): Font size. font_ttf (str, optional): Path to the .ttf font file. Defaults to Arial. label?_top_left_xy (tuple(int), optional): The XY coordinate of the label's top left corner. make_video_kwargs (dict, optional): Keyword arguments for :func:`make_video`. Writes - A comparison video. """ # Bar is perpendicular to sweep-along sweep_along = 0 if sweep_vertically else 1 bar_along = 1 if sweep_vertically else 0 # Number of frames n_frames = len(imgs1) assert n_frames == len(imgs2), \ "Videos to be compared have different numbers of frames" img_shape = imgs1[0].shape # Bar color according to image dtype img_dtype = imgs1[0].dtype bar_color = np.array(bar_color, dtype=img_dtype) if np.issubdtype(img_dtype, np.integer): bar_color *= np.iinfo(img_dtype).max # Map from frame index to bar location, considering possibly multiple trips bar_locs = [] for i in range(sweeps): ind = np.arange(0, img_shape[sweep_along]) if i % 2 == 1: # reverse every other trip ind = ind[::-1] bar_locs.append(ind) bar_locs = np.hstack(bar_locs) # all possible locations ind = np.linspace(0, len(bar_locs) - 1, num=n_frames, endpoint=True) bar_locs = [bar_locs[int(x)] for x in ind] # uniformly sampled # Label locations if label1_top_left_xy is None: # Label 1 at top left corner label1_top_left_xy = (int(0.1 * img_shape[1]), int(0.05 * img_shape[0])) if label2_top_left_xy is None: if sweep_vertically: # Label 2 at bottom left corner label2_top_left_xy = ( int(0.1 * img_shape[1]), int(0.75 * img_shape[0])) else: # Label 2 at top right corner label2_top_left_xy = ( int(0.7 * img_shape[1]), int(0.05 * img_shape[0])) frames = [] for i, (img1, img2) in enumerate(zip(imgs1, imgs2)): assert img1.shape == img_shape, f"`imgs1[{i}]` has a differnet shape" assert img2.shape == img_shape, f"`imgs2[{i}]` has a differnet shape" assert img1.dtype == img_dtype, f"`imgs1[{i}]` has a differnet dtype" assert img2.dtype == img_dtype, f"`imgs2[{i}]` has a differnet dtype" # Label the two images img1 = put_text( img1, label1, label_top_left_xy=label1_top_left_xy, font_size=font_size, font_color=bar_color, font_ttf=font_ttf) img2 = put_text( img2, label2, label_top_left_xy=label2_top_left_xy, font_size=font_size, font_color=bar_color, font_ttf=font_ttf) # Bar start and end bar_loc = bar_locs[i] bar_width_half = bar_width // 2 bar_start = max(0, bar_loc - bar_width_half) bar_end = min(bar_loc + bar_width_half, img_shape[sweep_along]) # Up to bar start, we show Image 1; bar end onwards, Image 2 img1 = np.take(img1, range(bar_start), axis=sweep_along) img2 = np.take( img2, range(bar_end, img_shape[sweep_along]), axis=sweep_along) # Between the two images, we show the bar actual_bar_width = img_shape[ sweep_along] - img1.shape[sweep_along] - img2.shape[sweep_along] reps = [1, 1, 1] reps[sweep_along] = actual_bar_width reps[bar_along] = img_shape[bar_along] bar_img = np.tile(bar_color, reps) frame = np.concatenate((img1, bar_img, img2), axis=sweep_along) frames.append(frame) make_video(frames, **make_video_kwargs)
[ 6738, 28686, 13, 6978, 1330, 4654, 11, 26672, 3672, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 764, 5239, 1330, 1234, 62, 5239, 198, 6738, 11485, 1330, 1500, 198, 6738, 11485, 418, 1330, 285, 4335, 17062, 198, 6738, 11485, 320,...
2.197153
3,723
# -*- coding: utf-8 -*- """Top-level package for Shipfunk.""" __author__ = """Jaana Sarajrvi""" __email__ = 'jaana.sarajarvi@vilkas.fi' __version__ = '0.1.1'
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 9126, 12, 5715, 5301, 329, 16656, 69, 2954, 526, 15931, 198, 198, 834, 9800, 834, 796, 37227, 33186, 2271, 6866, 1228, 81, 8903, 37811, 198, 834, 12888, 834,...
2.191781
73
#! python3 # coding: utf-8 from vpc.nos import NetworkElement,NetworkElementEvent,event_t,EventChain if __name__ == "__main__": pass
[ 2, 0, 21015, 18, 198, 2, 19617, 25, 3384, 69, 12, 23, 198, 6738, 410, 14751, 13, 39369, 1330, 7311, 20180, 11, 26245, 20180, 9237, 11, 15596, 62, 83, 11, 9237, 35491, 628, 628, 628, 198, 361, 11593, 3672, 834, 6624, 366, 834, 1241...
2.784314
51
import logging
[ 11748, 18931, 628 ]
5.333333
3
""" Created on Tue Feb 24 16:08:39 2015 @author: mukherjee """ import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn import preprocessing, metrics from sklearn.learning_curve import learning_curve # read Form data DATA_FORM_FILE = 'all-merged-cat.csv' #rawdata = pd.read_csv(DATA_FORM_FILE, usecols=np.r_[3,5:12,13:28,81:87,108]) rawdata = pd.read_csv(DATA_FORM_FILE) #select features posfeat = pd.DataFrame.as_matrix(rawdata)[:,np.r_[3:12]].astype(float) posfeat_name = rawdata.columns.values[3:12] lextypefeat = pd.DataFrame.as_matrix(rawdata)[:,np.r_[12:14]] lextypefeat_name = rawdata.columns.values[12:14] lexfeat = pd.DataFrame.as_matrix(rawdata)[:,np.r_[14:29]].astype(float) lexfeat_name = rawdata.columns.values[14:29] phonfeat = pd.DataFrame.as_matrix(rawdata)[:,np.r_[29:47]] accoufeat = pd.DataFrame.as_matrix(rawdata)[:,np.r_[47:81]].astype(float) accoufeat_name = rawdata.columns.values[47:81] phonfeat = pd.DataFrame.as_matrix(rawdata)[:,np.r_[29]].astype(float) lextypefeat = pd.DataFrame.as_matrix(rawdata)[:,np.r_[13]] lextypefeat_name = rawdata.columns.values[13:14].astype(object) # feature name feat_name = np.concatenate((posfeat_name,accoufeat_name,lexfeat_name),axis=0) # Transforming categorical feature le = preprocessing.LabelBinarizer() le.fit(lextypefeat) list(le.classes_) lextypefeat = le.transform(lextypefeat) #---------------------------------------------------------------------------------------------------- # select feature combination featN = np.column_stack((posfeat,accoufeat)) #featB = np.column_stack((lexfeat,lextypefeat)) featB = lexfeat ###------------------------------------------- PCA #from sklearn.decomposition import PCA #pca = PCA(n_components=4) #####------------------------------------------- Randomized PCA ##from sklearn.decomposition import RandomizedPCA ##pca = RandomizedPCA(n_components=30, whiten=True) ### #scale = pca.fit(feat1) #feat1 = scale.fit_transform(feat1) feat = np.column_stack((featN,featB)) feat[np.isnan(feat)] = 0 feat[np.isinf(feat)] = 0 # select test labels #Ytest = pd.DataFrame.as_matrix(rawdata)[:,20:26].astype(float) label = pd.DataFrame.as_matrix(rawdata)[:,108] #remove bad features as there is no label scale = np.where(label == 'None') label = np.delete(label,scale) feat = np.delete(feat,scale,0) #---------------------------------------------------------------------------------------------------- # Transforming categorical feature le = preprocessing.LabelEncoder() le.fit(label) list(le.classes_) label = le.transform(label) # create traning and test data by partioning nSamples = len(feat) XtrainPos = feat[:.7 * nSamples,:] YtrainPos = label[:.7 * nSamples] XtestPos = feat[.7 * nSamples:,:] YtestPos = label[.7 * nSamples:] XtrainAll = feat #---------------------------------------------------------------------------------------------------- #normalization of features scale = preprocessing.StandardScaler().fit(XtrainPos) XtrainPos = scale.transform(XtrainPos) XtestPos = scale.transform(XtestPos) # for whole data set scaleAll = preprocessing.StandardScaler().fit(XtrainAll) XtrainAll = scaleAll.transform(XtrainAll) #scale = preprocessing.MinMaxScaler() #XtrainPos = scale.fit_transform(XtrainPos) #XtestPos = scale.transform(XtestPos) #scaleAll = preprocessing.MinMaxScaler() #XtrainAll = scaleAll.fit_transform(XtrainAll) #scale = preprocessing.Normalizer().fit(XtrainPos) #XtrainPos = scale.transform(XtrainPos) #XtestPos = scale.transform(XtestPos) #scaleAll = preprocessing.Normalizer().fit(XtrainAll) #XtrainAll = scaleAll.transform(XtrainAll) ###------------------------------------------- RandomizedLogisticRegression #from sklearn.linear_model import RandomizedLogisticRegression #scale = RandomizedLogisticRegression() #XtrainPos = scale.fit_transform(XtrainPos,YtrainPos) #XtestPos = scale.transform(XtestPos) #XtrainAll = scale.fit_transform(XtrainAll,label) ###------------------------------------------- PCA #from sklearn.decomposition import PCA #pca = PCA(n_components=30) ####------------------------------------------- Randomized PCA #from sklearn.decomposition import RandomizedPCA #pca = RandomizedPCA(n_components=30, whiten=True) ## ## #scale = pca.fit(XtrainPos) #XtrainPos = scale.fit_transform(XtrainPos) #XtestPos = scale.fit_transform(XtestPos) #scaleAll = pca.fit(XtrainAll) #XtrainAll = scaleAll.transform(XtrainAll) ###------------------------------------------- LDA #from sklearn.lda import LDA #lda = LDA(n_components=4) #scale = lda.fit(XtrainPos,YtrainPos) #XtrainPos = scale.transform(XtrainPos) #XtestPos = scale.transform(XtestPos) #scaleAll = lda.fit(XtrainAll,label) #XtrainAll = scaleAll.transform(XtrainAll) #--------------------------------------------classification------------------------------------------- ##GradientBoost #from sklearn.ensemble import GradientBoostingClassifier #clf = GradientBoostingClassifier(n_estimators=100, learning_rate=0.1, # max_depth=1, random_state=0) ## SVM #from sklearn import svm #clf = svm.SVC() #from sklearn.multiclass import OneVsOneClassifier #from sklearn.multiclass import OutputCodeClassifier #clf = OutputCodeClassifier(svm.SVC()) ## RandomForest from sklearn.ensemble import RandomForestClassifier clf = RandomForestClassifier(min_samples_leaf=10) ## SGD #from sklearn.linear_model import SGDClassifier #clf = SGDClassifier(loss="log", penalty="l2") # CART #from sklearn import tree #clf = tree.DecisionTreeClassifier() # ### AdaBoostClassifier #from sklearn.ensemble import AdaBoostClassifier #clf = AdaBoostClassifier(n_estimators=100) # Gaussian Naive Bayes #from sklearn.naive_bayes import GaussianNB #clf = GaussianNB() # KNN #from sklearn import neighbors ##clf = neighbors.KNeighborsClassifier(n_neighbors=10,weights='distance') #clf = neighbors.KNeighborsClassifier(n_neighbors=10) ##-------------------------------------------------Traning------------------ clf = clf.fit(XtrainPos, YtrainPos) print(metrics.classification_report(YtestPos, clf.predict(XtestPos))) ##--------------------------Crossvalidation 5 times using different split------------------------------ #from sklearn import cross_validation #scores = cross_validation.cross_val_score(clf, XtrainAll, label, cv=3, scoring='f1') #print("Accuracy: %0.2f (+/- %0.2f)" % (scores.mean(), scores.std() * 2)) ####---------------------------------Check for overfeat------------------------------------- train_sample_size, train_scores, test_scores = learning_curve(clf, XtrainAll, label, train_sizes=np.arange(0.1,1,0.1), cv=10) #----------------------------------------Visualization--------------------------------------------- plt.xlabel("# Training sample") plt.ylabel("Accuracy") plt.grid(); mean_train_scores = np.mean(train_scores, axis=1) mean_test_scores = np.mean(test_scores, axis=1) std_train_scores = np.std(train_scores, axis=1) std_test_scores = np.std(test_scores, axis=1) gap = np.abs(mean_test_scores - mean_train_scores) g = plt.figure(1) plt.title("Learning curves for %r\n" "Best test score: %0.2f - Gap: %0.2f" % (clf, mean_test_scores.max(), gap[-1])) plt.plot(train_sample_size, mean_train_scores, label="Training", color="b") plt.fill_between(train_sample_size, mean_train_scores - std_train_scores, mean_train_scores + std_train_scores, alpha=0.1, color="b") plt.plot(train_sample_size, mean_test_scores, label="Cross-validation", color="g") plt.fill_between(train_sample_size, mean_test_scores - std_test_scores, mean_test_scores + std_test_scores, alpha=0.1, color="g") plt.legend(loc="lower right") g.show() ## confusion matrix #from sklearn.metrics import confusion_matrix #cm = confusion_matrix(YtestPos,clf.predict(XtestPos)) ## Show confusion matrix in a separate window #plt.matshow(cm) #plt.title('Confusion matrix') #plt.colorbar() #plt.ylabel('True label') #plt.xlabel('Predicted label') #plt.show() ############################################################################### # Plot feature importance feature_importance = clf.feature_importances_ # make importances relative to max importance feature_importance = 100.0 * (feature_importance / feature_importance.max()) sorted_idx = np.argsort(feature_importance) pos = np.arange(sorted_idx.shape[0]) + .5 f = plt.figure(2,figsize=(18, 18)) plt.barh(pos, feature_importance[sorted_idx], align='center') plt.yticks(pos, feat_name[sorted_idx]) plt.xlabel('Relative Importance') plt.title('Variable Importance') plt.savefig('feature_importance') f.show()
[ 37811, 201, 198, 41972, 319, 30030, 3158, 1987, 1467, 25, 2919, 25, 2670, 1853, 201, 198, 201, 198, 31, 9800, 25, 285, 2724, 372, 34589, 201, 198, 37811, 201, 198, 11748, 299, 32152, 355, 45941, 201, 198, 11748, 19798, 292, 355, 279, ...
2.639378
3,408
from httpcore import TimeoutException from httpcore._exceptions import ConnectError from httpx import Timeout, Client, ConnectTimeout from unittest.mock import patch from pytest import raises from googletrans import Translator
[ 6738, 2638, 7295, 1330, 3862, 448, 16922, 198, 6738, 2638, 7295, 13557, 1069, 11755, 1330, 8113, 12331, 198, 6738, 2638, 87, 1330, 3862, 448, 11, 20985, 11, 8113, 48031, 198, 6738, 555, 715, 395, 13, 76, 735, 1330, 8529, 198, 6738, 12...
3.772727
66
# -*- coding: utf-8 -*- import torch import torch.nn as nn import torch.nn.functional as F import numpy as np # Func1: change density map into count map # density map: batch size * 1 * w * h # Func2: convert count to class (0->c-1) # Func3: convert class (0->c-1) to count number def Class2Count(pre_cls,label_indice): ''' # --Input: # 1.pre_cls is class label range in [0,1,2,...,C-1] # 2.label_indice not include 0 but the other points # --Output: # 1.count value, the same size as pre_cls ''' if isinstance(label_indice,np.ndarray): label_indice = torch.from_numpy(label_indice) label_indice = label_indice.squeeze() IF_gpu = torch.cuda.is_available() IF_ret_gpu = (pre_cls.device.type == 'cuda') # tranform interval to count value map label2count = [0.0] for (i,item) in enumerate(label_indice): if i<label_indice.size()[0]-1: tmp_count = (label_indice[i]+label_indice[i+1])/2 else: tmp_count = label_indice[i] label2count.append(tmp_count) label2count = torch.tensor(label2count) label2count = label2count.type(torch.FloatTensor) #outputs = outputs.max(dim=1)[1].cpu().data ORI_SIZE = pre_cls.size() pre_cls = pre_cls.reshape(-1).cpu() pre_counts = torch.index_select(label2count,0,pre_cls.cpu().type(torch.LongTensor)) pre_counts = pre_counts.reshape(ORI_SIZE) if IF_ret_gpu: pre_counts = pre_counts.cuda() return pre_counts if __name__ == '__main__': pre_cls = torch.Tensor([[0,1,2],[3,4,4]]) label_indice =torch.Tensor([0.5,1,1.5,2]) pre_counts = Class2Count(pre_cls,label_indice) print(pre_cls) print(label_indice) print(pre_counts) pre_cls = Count2Class(pre_counts,label_indice) print(pre_cls)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 201, 198, 201, 198, 11748, 28034, 201, 198, 11748, 28034, 13, 20471, 355, 299, 77, 201, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 201, 198, 11748, 299, 32152, 355, ...
2.08204
902
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations from pants.option.option_types import BoolOption from pants.option.subsystem import Subsystem
[ 2, 15069, 33160, 41689, 1628, 20420, 357, 3826, 27342, 9865, 3843, 20673, 13, 9132, 737, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 3826, 38559, 24290, 737, 198, 198, 6738, 11593, 37443, 834, 1330, 37647, 198, ...
3.984848
66
# 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 mock import uuid import testtools import shade from shade import _utils from shade import exc from shade.tests import fakes from shade.tests.unit import base RANGE_DATA = [ dict(id=1, key1=1, key2=5), dict(id=2, key1=1, key2=20), dict(id=3, key1=2, key2=10), dict(id=4, key1=2, key2=30), dict(id=5, key1=3, key2=40), dict(id=6, key1=3, key2=40), ] def test_list_servers_all_projects(self): '''This test verifies that when list_servers is called with `all_projects=True` that it passes `all_tenants=True` to nova.''' self.register_uris([ dict(method='GET', uri=self.get_mock_url( 'compute', 'public', append=['servers', 'detail'], qs_elements=['all_tenants=True']), complete_qs=True, json={'servers': []}), ]) self.cloud.list_servers(all_projects=True) self.assert_calls() def test__nova_extensions(self): body = [ { "updated": "2014-12-03T00:00:00Z", "name": "Multinic", "links": [], "namespace": "http://openstack.org/compute/ext/fake_xml", "alias": "NMN", "description": "Multiple network support." }, { "updated": "2014-12-03T00:00:00Z", "name": "DiskConfig", "links": [], "namespace": "http://openstack.org/compute/ext/fake_xml", "alias": "OS-DCF", "description": "Disk Management Extension." }, ] self.register_uris([ dict(method='GET', uri='{endpoint}/extensions'.format( endpoint=fakes.COMPUTE_ENDPOINT), json=dict(extensions=body)) ]) extensions = self.cloud._nova_extensions() self.assertEqual(set(['NMN', 'OS-DCF']), extensions) self.assert_calls() def test__nova_extensions_fails(self): self.register_uris([ dict(method='GET', uri='{endpoint}/extensions'.format( endpoint=fakes.COMPUTE_ENDPOINT), status_code=404), ]) with testtools.ExpectedException( exc.OpenStackCloudURINotFound, "Error fetching extension list for nova" ): self.cloud._nova_extensions() self.assert_calls() def test__has_nova_extension(self): body = [ { "updated": "2014-12-03T00:00:00Z", "name": "Multinic", "links": [], "namespace": "http://openstack.org/compute/ext/fake_xml", "alias": "NMN", "description": "Multiple network support." }, { "updated": "2014-12-03T00:00:00Z", "name": "DiskConfig", "links": [], "namespace": "http://openstack.org/compute/ext/fake_xml", "alias": "OS-DCF", "description": "Disk Management Extension." }, ] self.register_uris([ dict(method='GET', uri='{endpoint}/extensions'.format( endpoint=fakes.COMPUTE_ENDPOINT), json=dict(extensions=body)) ]) self.assertTrue(self.cloud._has_nova_extension('NMN')) self.assert_calls() def test__has_nova_extension_missing(self): body = [ { "updated": "2014-12-03T00:00:00Z", "name": "Multinic", "links": [], "namespace": "http://openstack.org/compute/ext/fake_xml", "alias": "NMN", "description": "Multiple network support." }, { "updated": "2014-12-03T00:00:00Z", "name": "DiskConfig", "links": [], "namespace": "http://openstack.org/compute/ext/fake_xml", "alias": "OS-DCF", "description": "Disk Management Extension." }, ] self.register_uris([ dict(method='GET', uri='{endpoint}/extensions'.format( endpoint=fakes.COMPUTE_ENDPOINT), json=dict(extensions=body)) ]) self.assertFalse(self.cloud._has_nova_extension('invalid')) self.assert_calls() def test_range_search(self): filters = {"key1": "min", "key2": "20"} retval = self.cloud.range_search(RANGE_DATA, filters) self.assertIsInstance(retval, list) self.assertEqual(1, len(retval)) self.assertEqual([RANGE_DATA[1]], retval) def test_range_search_2(self): filters = {"key1": "<=2", "key2": ">10"} retval = self.cloud.range_search(RANGE_DATA, filters) self.assertIsInstance(retval, list) self.assertEqual(2, len(retval)) self.assertEqual([RANGE_DATA[1], RANGE_DATA[3]], retval) def test_range_search_3(self): filters = {"key1": "2", "key2": "min"} retval = self.cloud.range_search(RANGE_DATA, filters) self.assertIsInstance(retval, list) self.assertEqual(0, len(retval)) def test_range_search_4(self): filters = {"key1": "max", "key2": "min"} retval = self.cloud.range_search(RANGE_DATA, filters) self.assertIsInstance(retval, list) self.assertEqual(0, len(retval)) def test_range_search_5(self): filters = {"key1": "min", "key2": "min"} retval = self.cloud.range_search(RANGE_DATA, filters) self.assertIsInstance(retval, list) self.assertEqual(1, len(retval)) self.assertEqual([RANGE_DATA[0]], retval)
[ 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 921, 743, 7330, 198, 2, 257, 4866, 286, 262, 13789, 379, 198, 2,...
1.961091
3,264
import matplotlib import pandas as pd matplotlib.rcParams['pdf.fonttype'] = 42 matplotlib.rcParams['ps.fonttype'] = 42 import matplotlib.pyplot as plt import seaborn as sns from utils.utils import mkdir_p sns.set() sns.despine() sns.set_context("paper", rc={"font.size": 18, "axes.labelsize": 18, "xtick.labelsize": 15, "ytick.labelsize": 15, "legend.fontsize": 16}) sns.set_style('white', {'axes.edgecolor': "0.5", "pdf.fonttype": 42}) plt.gcf().subplots_adjust(bottom=0.15, left=0.14) if __name__ == "__main__": experiment = ['Q', 'Q'] info = '0M' l1 = 1 l2 = 1 episodes = 5000 moocs = ['SER'] games = ['iag', 'iagR', 'iagM', 'iagRNE', 'iagNE'] # ['iagRNE'] # ['iag']['iagM']'iagNE', for l1 in range(1, 2): for l2 in range(1, 2): for mooc in moocs: for game in games: path_data = f'results/tour_{experiment}_{game}_l{l1}_{l2}' plot_results(game, mooc, path_data, experiment)
[ 11748, 2603, 29487, 8019, 198, 11748, 19798, 292, 355, 279, 67, 198, 198, 6759, 29487, 8019, 13, 6015, 10044, 4105, 17816, 12315, 13, 10331, 4906, 20520, 796, 5433, 198, 6759, 29487, 8019, 13, 6015, 10044, 4105, 17816, 862, 13, 10331, 4...
1.994141
512
import os, sys import shutil from unittest import TestCase, main from ocrd.resolver import Resolver from ocrd_models.ocrd_page import to_xml from ocrd_modelfactory import page_from_file from ocrd_utils import MIMETYPE_PAGE from ocrd_tesserocr.recognize import TesserocrRecognize from ocrd_keraslm.wrapper import KerasRate WORKSPACE_DIR = '/tmp/pyocrd-test-ocrd_keraslm' PWD = os.path.dirname(os.path.realpath(__file__)) if __name__ == '__main__': main()
[ 11748, 28686, 11, 25064, 198, 11748, 4423, 346, 198, 6738, 555, 715, 395, 1330, 6208, 20448, 11, 1388, 198, 198, 6738, 267, 66, 4372, 13, 411, 14375, 1330, 1874, 14375, 198, 6738, 267, 66, 4372, 62, 27530, 13, 1696, 67, 62, 7700, 13...
2.575419
179
# Copyright 2020 DeepMind Technologies 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 # # 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. """Configuration for Territory: Rooms. Example video: https://youtu.be/u0YOiShqzA4 See _Territory: Open_ for the general description of the mechanics at play in this substrate. In this substrate, _Territory: Rooms_, individuals start in segregated rooms that strongly suggest a partition individuals could adhere to. They can break down the walls of these regions and invade each other's "natural territory", but the destroyed resources are lost forever. A peaceful partition is possible at the start of the episode, and the policy to achieve it is easy to implement. But if any agent gets too greedy and invades, it buys itself a chance of large rewards, but also chances inflicting significant chaos and deadweight loss on everyone if its actions spark wider conflict. The reason it can spiral out of control is that once an agent's neighbor has left their natural territory then it becomes rational to invade the space, leaving one's own territory undefended, creating more opportunity for mischief by others. """ from typing import Any, Dict from ml_collections import config_dict from meltingpot.python.utils.substrates import colors from meltingpot.python.utils.substrates import game_object_utils from meltingpot.python.utils.substrates import shapes from meltingpot.python.utils.substrates import specs _COMPASS = ["N", "E", "S", "W"] # This number just needs to be greater than the number of players. MAX_ALLOWED_NUM_PLAYERS = 10 DEFAULT_ASCII_MAP = """ WRRRRRWWRRRRRWWRRRRRW R RR RR R R RR RR R R P RR P RR P R R RR RR R R RR RR R WRRRRRWWRRRRRWWRRRRRW WRRRRRWWRRRRRWWRRRRRW R RR RR R R RR RR R R P RR P RR P R R RR RR R R RR RR R WRRRRRWWRRRRRWWRRRRRW WRRRRRWWRRRRRWWRRRRRW R RR RR R R RR RR R R P RR P RR P R R RR RR R R RR RR R WRRRRRWWRRRRRWWRRRRRW """ # `prefab` determines which prefab game object to use for each `char` in the # ascii map. CHAR_PREFAB_MAP = { "P": "spawn_point", "W": "wall", "R": {"type": "all", "list": ["resource", "reward_indicator"]}, } WALL = { "name": "wall", "components": [ { "component": "StateManager", "kwargs": { "initialState": "wall", "stateConfigs": [{ "state": "wall", "layer": "upperPhysical", "sprite": "Wall", }], } }, { "component": "Appearance", "kwargs": { "renderMode": "ascii_shape", "spriteNames": ["Wall",], "spriteShapes": [shapes.WALL], "palettes": [{"*": (95, 95, 95, 255), "&": (100, 100, 100, 255), "@": (109, 109, 109, 255), "#": (152, 152, 152, 255)}], "noRotates": [True] } }, { "component": "Transform", "kwargs": { "position": (0, 0), "orientation": "N" } }, { "component": "AllBeamBlocker", "kwargs": {} }, ] } SPAWN_POINT = { "name": "spawn_point", "components": [ { "component": "StateManager", "kwargs": { "initialState": "playerSpawnPoint", "stateConfigs": [{ "state": "playerSpawnPoint", "layer": "logic", "groups": ["spawnPoints"], }], } }, { "component": "Appearance", "kwargs": { "renderMode": "invisible", "spriteNames": [], "spriteRGBColors": [] } }, { "component": "Transform", "kwargs": { "position": (0, 0), "orientation": "N" } }, ] } RESOURCE = { "name": "resource", "components": [ { "component": "StateManager", "kwargs": { "initialState": "unclaimed", "stateConfigs": [ {"state": "unclaimed", "layer": "upperPhysical", "sprite": "UnclaimedResourceSprite", "groups": ["unclaimedResources"]}, {"state": "destroyed"}, ], } }, { "component": "Appearance", "kwargs": { "spriteNames": ["UnclaimedResourceSprite"], # This color is grey. "spriteRGBColors": [(64, 64, 64, 255)] } }, { "component": "Transform", "kwargs": { "position": (0, 0), "orientation": "N" } }, { "component": "Resource", "kwargs": { "initialHealth": 2, "destroyedState": "destroyed", "reward": 1.0, "rewardRate": 0.01, "rewardDelay": 100 } }, ] } REWARD_INDICATOR = { "name": "reward_indicator", "components": [ { "component": "StateManager", "kwargs": { "initialState": "inactive", "stateConfigs": [ {"state": "active", "layer": "overlay", "sprite": "ActivelyRewardingResource"}, {"state": "inactive"}, ], } }, { "component": "Appearance", "kwargs": { "spriteNames": ["ActivelyRewardingResource",], "renderMode": "ascii_shape", "spriteShapes": [shapes.PLUS_IN_BOX], "palettes": [{"*": (86, 86, 86, 65), "#": (202, 202, 202, 105), "@": (128, 128, 128, 135), "x": (0, 0, 0, 0)}], "noRotates": [True] } }, { "component": "Transform", "kwargs": { "position": (0, 0), "orientation": "N" } }, { "component": "RewardIndicator", "kwargs": { } }, ] } # PLAYER_COLOR_PALETTES is a list with each entry specifying the color to use # for the player at the corresponding index. PLAYER_COLOR_PALETTES = [] for i in range(MAX_ALLOWED_NUM_PLAYERS): PLAYER_COLOR_PALETTES.append(shapes.get_palette(colors.palette[i])) # Set up player-specific settings for resources. for j, color in enumerate(colors.palette[:MAX_ALLOWED_NUM_PLAYERS]): sprite_name = "Color" + str(j + 1) + "ResourceSprite" game_object_utils.get_first_named_component( RESOURCE, "StateManager")["kwargs"]["stateConfigs"].append({ "state": "claimed_by_" + str(j + 1), "layer": "upperPhysical", "sprite": sprite_name, "groups": ["claimedResources"] }) game_object_utils.get_first_named_component( RESOURCE, "Appearance")["kwargs"]["spriteNames"].append(sprite_name) game_object_utils.get_first_named_component( RESOURCE, "Appearance")["kwargs"]["spriteRGBColors"].append(color) # PREFABS is a dictionary mapping names to template game objects that can # be cloned and placed in multiple locations accoring to an ascii map. PREFABS = { "wall": WALL, "spawn_point": SPAWN_POINT, "resource": RESOURCE, "reward_indicator": REWARD_INDICATOR, } # Primitive action components. # pylint: disable=bad-whitespace # pyformat: disable NOOP = {"move": 0, "turn": 0, "fireZap": 0, "fireClaim": 0} FORWARD = {"move": 1, "turn": 0, "fireZap": 0, "fireClaim": 0} STEP_RIGHT = {"move": 2, "turn": 0, "fireZap": 0, "fireClaim": 0} BACKWARD = {"move": 3, "turn": 0, "fireZap": 0, "fireClaim": 0} STEP_LEFT = {"move": 4, "turn": 0, "fireZap": 0, "fireClaim": 0} TURN_LEFT = {"move": 0, "turn": -1, "fireZap": 0, "fireClaim": 0} TURN_RIGHT = {"move": 0, "turn": 1, "fireZap": 0, "fireClaim": 0} FIRE_ZAP = {"move": 0, "turn": 0, "fireZap": 1, "fireClaim": 0} FIRE_CLAIM = {"move": 0, "turn": 0, "fireZap": 0, "fireClaim": 1} # pyformat: enable # pylint: enable=bad-whitespace ACTION_SET = ( NOOP, FORWARD, BACKWARD, STEP_LEFT, STEP_RIGHT, TURN_LEFT, TURN_RIGHT, FIRE_ZAP, FIRE_CLAIM ) # The Scene object is a non-physical object, its components implement global # logic. def create_scene(): """Creates the global scene.""" scene = { "name": "scene", "components": [ { "component": "StateManager", "kwargs": { "initialState": "scene", "stateConfigs": [{ "state": "scene", }], } }, { "component": "Transform", "kwargs": { "position": (0, 0), "orientation": "N" }, }, { "component": "StochasticIntervalEpisodeEnding", "kwargs": { "minimumFramesPerEpisode": 1000, "intervalLength": 100, # Set equal to unroll length. "probabilityTerminationPerInterval": 0.2 } } ] } return scene def create_avatar_object(player_idx: int) -> Dict[str, Any]: """Create an avatar object that always sees itself as blue.""" # Lua is 1-indexed. lua_index = player_idx + 1 color_palette = PLAYER_COLOR_PALETTES[player_idx] live_state_name = "player{}".format(lua_index) avatar_sprite_name = "avatarSprite{}".format(lua_index) avatar_object = { "name": "avatar", "components": [ { "component": "StateManager", "kwargs": { "initialState": live_state_name, "stateConfigs": [ # Initial player state. {"state": live_state_name, "layer": "upperPhysical", "sprite": avatar_sprite_name, "contact": "avatar", "groups": ["players"]}, # Player wait state used when they have been zapped out. {"state": "playerWait", "groups": ["playerWaits"]}, ] } }, { "component": "Transform", "kwargs": { "position": (0, 0), "orientation": "N" } }, { "component": "Appearance", "kwargs": { "renderMode": "ascii_shape", "spriteNames": [avatar_sprite_name], "spriteShapes": [shapes.CUTE_AVATAR], "palettes": [color_palette], "noRotates": [True] } }, { "component": "Avatar", "kwargs": { "index": lua_index, "aliveState": live_state_name, "waitState": "playerWait", "spawnGroup": "spawnPoints", "actionOrder": ["move", "turn", "fireZap", "fireClaim"], "actionSpec": { "move": {"default": 0, "min": 0, "max": len(_COMPASS)}, "turn": {"default": 0, "min": -1, "max": 1}, "fireZap": {"default": 0, "min": 0, "max": 1}, "fireClaim": {"default": 0, "min": 0, "max": 1}, }, "view": { "left": 5, "right": 5, "forward": 9, "backward": 1, "centered": False }, } }, { "component": "AvatarDirectionIndicator", # We do not normally use direction indicators for the MAGI suite, # but we do use them for territory because they function to claim # any resources they contact. "kwargs": {"color": (202, 202, 202, 50)} }, { "component": "Zapper", "kwargs": { "cooldownTime": 2, "beamLength": 3, "beamRadius": 1, "framesTillRespawn": 1e6, # Effectively never respawn. "penaltyForBeingZapped": 0, "rewardForZapping": 0, } }, { "component": "ReadyToShootObservation", }, { "component": "ResourceClaimer", "kwargs": { "color": color_palette["*"], "playerIndex": lua_index, "beamLength": 2, "beamRadius": 0, "beamWait": 0, } }, { "component": "LocationObserver", "kwargs": { "objectIsAvatar": True, "alsoReportOrientation": True } }, { "component": "Taste", "kwargs": { "role": "none", "rewardAmount": 1.0, } }, ] } return avatar_object def create_avatar_objects(num_players): """Returns list of avatar objects of length 'num_players'.""" avatar_objects = [] for player_idx in range(0, num_players): game_object = create_avatar_object(player_idx) avatar_objects.append(game_object) return avatar_objects def create_lab2d_settings(num_players: int) -> Dict[str, Any]: """Returns the lab2d settings.""" lab2d_settings = { "levelName": "territory", "levelDirectory": "meltingpot/lua/levels", "numPlayers": num_players, # Define upper bound of episode length since episodes end stochastically. "maxEpisodeLengthFrames": 2000, "spriteSize": 8, "topology": "TORUS", # Choose from ["BOUNDED", "TORUS"], "simulation": { "map": DEFAULT_ASCII_MAP, "gameObjects": create_avatar_objects(num_players), "scene": create_scene(), "prefabs": PREFABS, "charPrefabMap": CHAR_PREFAB_MAP, }, } return lab2d_settings def get_config(factory=create_lab2d_settings): """Default configuration for training on the territory level.""" config = config_dict.ConfigDict() # Basic configuration. config.num_players = 9 # Lua script configuration. config.lab2d_settings = factory(config.num_players) # Action set configuration. config.action_set = ACTION_SET # Observation format configuration. config.individual_observation_names = [ "RGB", "READY_TO_SHOOT", "POSITION", "ORIENTATION", ] config.global_observation_names = [ "WORLD.RGB", ] # The specs of the environment (from a single-agent perspective). config.action_spec = specs.action(len(ACTION_SET)) config.timestep_spec = specs.timestep({ "RGB": specs.OBSERVATION["RGB"], "READY_TO_SHOOT": specs.OBSERVATION["READY_TO_SHOOT"], "POSITION": specs.OBSERVATION["POSITION"], "ORIENTATION": specs.OBSERVATION["ORIENTATION"], "WORLD.RGB": specs.rgb(168, 168), }) return config
[ 2, 15069, 12131, 10766, 28478, 21852, 15302, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198,...
1.922581
8,538
#-*- coding: utf-8 -*- import frappe import boto3 import boto3.session import rows import json import zipfile import tempfile import sqlite3 from io import BytesIO from frappe import _ from frappe.utils import cint, flt, today, getdate, get_first_day, add_to_date try: from frappe.utils import file_manager with_file_manager = True except ImportError: with_file_manager = False from frappe.core.doctype.file.file import create_new_folder SQLVIEW = """ select lineitemusageaccountid as account, lineitemproductcode as item_group, productproductfamily as item_code, productinstancetype as item_type, pricingterm as item_term, pricingunit as item_unit, strftime('%Y-%m-%d', min(billbillingperiodstartdate)) as start_date, strftime('%Y-%m-%d', max(billbillingperiodenddate)) as end_date, sum(lineitemusageamount) as consumed_units, sum(ifnull(lineitemunblendedcost, 0.0)) / sum(ifnull(lineitemusageamount, 1.0)) as cost_per_unit from billing_aptech where lineitemlineitemtype != "Tax" group by lineitemusageaccountid, lineitemproductcode, productproductfamily, productinstancetype, pricingterm, pricingunit order by lineitemusageaccountid, lineitemproductcode, productproductfamily, productinstancetype, pricingterm, pricingunit """ import_fields = u""" lineItem/UsageAccountId lineItem/LineItemType lineItem/ProductCode product/productFamily product/instanceType pricing/term pricing/unit bill/BillingPeriodStartDate bill/BillingPeriodEndDate lineItem/UsageAmount lineItem/UnblendedCost lineItem/UnblendedRate """.strip().splitlines()
[ 2, 12, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 5306, 27768, 198, 11748, 275, 2069, 18, 198, 11748, 275, 2069, 18, 13, 29891, 198, 11748, 15274, 198, 11748, 33918, 198, 11748, 19974, 7753, 198, 11748, 20218, ...
2.948435
543
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest from parameterized import parameterized from google.cloud import bigquery from google.api_core.exceptions import GoogleAPICallError from utils import Utils if __name__ == '__main__': unittest.main()
[ 2, 15069, 13130, 3012, 11419, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 2, 921, 743, 733...
3.682028
217
# -*- coding: utf-8 -*- # pylint: disable-msg=E1101,W0612 from warnings import catch_warnings, simplefilter from pandas import Panel from pandas.util.testing import assert_panel_equal from .test_generic import Generic # run all the tests, but wrap each in a warning catcher for t in ['test_rename', 'test_get_numeric_data', 'test_get_default', 'test_nonzero', 'test_downcast', 'test_constructor_compound_dtypes', 'test_head_tail', 'test_size_compat', 'test_split_compat', 'test_unexpected_keyword', 'test_stat_unexpected_keyword', 'test_api_compat', 'test_stat_non_defaults_args', 'test_truncate_out_of_bounds', 'test_metadata_propagation', 'test_copy_and_deepcopy', 'test_pct_change', 'test_sample']: setattr(TestPanel, t, f())
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 279, 2645, 600, 25, 15560, 12, 19662, 28, 36, 1157, 486, 11, 54, 3312, 1065, 198, 198, 6738, 14601, 1330, 4929, 62, 40539, 654, 11, 2829, 24455, 198, 198, 6738, 1...
2.307692
364
# calculate shortest paths between OD pairs # in the map_speed_od postgis table # update the shortest path geometry into the table import requests, json, psycopg2 # get OD pairs from DB conn_string = ( "host='localhost' dbname='' user='' password=''" ) connection = psycopg2.connect(conn_string) connection.autocommit = True c = connection.cursor() c.execute(""" SELECT id, ST_X(ST_StartPoint(vector)) AS lon1, ST_Y(ST_StartPoint(vector)) AS lat1, ST_X(ST_EndPoint(vector)) AS lon2, ST_Y(ST_EndPoint(vector)) AS lat2 FROM map_speed_od """) # iterate over DB pairs for (rid,lon1,lat1,lon2,lat2) in c.fetchall(): # request route for these points options = { 'geometries':'geojson', 'overview':'full', 'steps':'false', 'annotations':'false' } response = requests.get( ('http://206.167.182.17:5000/route/v1/transit/'+str(lon1)+','+str(lat1)+';'+str(lon2)+','+str(lat2)), params=options, timeout=5 ) # parse the result j = json.loads(response.text) print json.dumps(j['routes'][0]['geometry']) # insert the route result c.execute(""" UPDATE map_speed_od SET shortest_path = ST_SetSRID(ST_GeomFromGeoJSON(%s),4326) WHERE id = %s; """, (json.dumps(j['routes'][0]['geometry']),rid,) )
[ 2, 15284, 35581, 13532, 1022, 31245, 14729, 198, 2, 287, 262, 3975, 62, 12287, 62, 375, 1281, 70, 271, 3084, 198, 2, 4296, 262, 35581, 3108, 22939, 656, 262, 3084, 198, 11748, 7007, 11, 33918, 11, 17331, 22163, 70, 17, 198, 198, 2, ...
2.412916
511
#-*- coding:utf-8 -*- # @Time : 2020-02-15 15:49 # @Author : Zhirui(Alex) Yang # @Function : import os
[ 2, 12, 9, 12, 19617, 25, 40477, 12, 23, 532, 9, 12, 198, 2, 2488, 7575, 220, 220, 220, 220, 1058, 12131, 12, 2999, 12, 1314, 1315, 25, 2920, 198, 2, 2488, 13838, 220, 220, 1058, 10511, 343, 9019, 7, 15309, 8, 10998, 198, 2, 24...
2.111111
54
import ssl import socket from typing import Tuple from hyper.common.util import to_native_string from urllib.parse import urlparse from hyper import HTTP11Connection, HTTPConnection from hyper.common.bufsocket import BufferedSocket from hyper.common.exceptions import TLSUpgrade from hyper.contrib import HTTP20Adapter from hyper.tls import init_context from tcp_tls_tunnel.utils import generate_basic_header, generate_proxy_url from tcp_tls_tunnel.dto import ProxyOptions, AdapterOptions, TunnelOptions from tcp_tls_tunnel.exceptions import ProxyError def _create_tunnel(tunnel_opts: TunnelOptions, dest_host: str, dest_port: int, server_name: str = None, proxy: ProxyOptions = None, timeout: int = None) -> Tuple[socket.socket, str]: """ Sends CONNECT method to a proxy and returns a socket with established connection to the target. :returns: socket, proto """ headers = { "Authorization": generate_basic_header(tunnel_opts.auth_login, tunnel_opts.auth_password), "Client": tunnel_opts.client.value, "Connection": 'keep-alive', "Server-Name": server_name or dest_host, "Host": tunnel_opts.host, "Secure": str(int(tunnel_opts.secure)), "HTTP2": str(int(tunnel_opts.http2)), } if proxy: headers["Proxy"] = generate_proxy_url(proxy=proxy) conn = HTTP11Connection(tunnel_opts.host, tunnel_opts.port, timeout=timeout) conn.request('CONNECT', '%s:%d' % (dest_host, dest_port), headers=headers) resp = conn.get_response() try: proto = resp.headers.get("Alpn-Protocol")[0].decode('utf-8') except TypeError: proto = 'http/1.1' if resp.status != 200: raise ProxyError( "Tunnel connection failed: %d %s" % (resp.status, to_native_string(resp.reason)), response=resp ) return getattr(conn, "_sock"), proto
[ 11748, 264, 6649, 198, 11748, 17802, 198, 6738, 19720, 1330, 309, 29291, 198, 6738, 8718, 13, 11321, 13, 22602, 1330, 284, 62, 30191, 62, 8841, 198, 198, 6738, 2956, 297, 571, 13, 29572, 1330, 19016, 29572, 198, 6738, 8718, 1330, 14626,...
2.442424
825
from itertools import * import time import os BASE_DIR = os.path.dirname(os.path.abspath(__file__)) #my own variance function runs much faster than numpy or the Python 3 ported statistics module ##rounding the means and variances helps to collapse them precision_ave=16 precision_var=12 ##perform runs #n can probably just be set to 7 or even lower #code will take a while, you should run copies of this script in parallel for r in range(5,100): n=30-r if n<=7: n=7 run(n,r)
[ 6738, 340, 861, 10141, 1330, 1635, 198, 11748, 640, 198, 11748, 28686, 198, 33, 11159, 62, 34720, 796, 28686, 13, 6978, 13, 15908, 3672, 7, 418, 13, 6978, 13, 397, 2777, 776, 7, 834, 7753, 834, 4008, 628, 198, 198, 2, 1820, 898, 2...
2.896552
174
# coding: utf-8 """ paginate.py ``````````` : api """ from flask import url_for def pagination(lit, page, perpage,endpoint): """ , nextlast {current: next_lit} """ _yu = len(lit) % perpage _chu = len(lit) // perpage if _yu == 0: last = _chu else: last = _chu + 1 current = lit[perpage*(page-1): perpage*page] next_page = "" if page < last: next_page = url_for(endpoint, page=page+1) elif page == last: next_page = "" last_page = url_for(endpoint, page=last) return [current, (next_page, last_page)]
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 37811, 198, 220, 220, 220, 42208, 4559, 13, 9078, 198, 220, 220, 220, 7559, 33153, 33153, 63, 198, 220, 220, 220, 1058, 40391, 198, 37811, 198, 6738, 42903, 1330, 19016, 62, 1640, 628, 198, 4299,...
2.14539
282
import pandas as pd from . import default import wikipedia import json from flask import jsonify import re import os import multiprocessing import requests import urllib import hashlib df = 0 wikipedia.set_lang("de") def get_wikidata_id(article): """Find the Wikidata ID for a given Wikipedia article.""" dapp = urllib.parse.urlencode({"action": "query", "prop": "pageprops", "ppprop":"wikibase_item", "redirects": 1, "format": "json", "titles": article}) query_string = "https://de.wikipedia.org/w/api.php?%s" % dapp ret = requests.get(query_string).json() id = next(iter(ret["query"]["pages"])) # TODO: Catch the case where article has no Wikidata ID # This can happen for new or seldomly edited articles return ret["query"]["pages"][id]["pageprops"]["wikibase_item"] def get_wikidata_image(wikidata_id): """Return the image for the Wikidata item with *wikidata_id*. """ query_string = ("https://www.wikidata.org/wiki/Special:EntityData/%s.json" % wikidata_id) item = json.loads(requests.get(query_string).text) wdata = item["entities"][wikidata_id]["claims"] try: image = wdata["P18"][0]["mainsnak"]["datavalue"]["value"].replace(" ", "_") except KeyError: print("No image on Wikidata.") else: md = hashlib.md5(image.encode('utf-8')).hexdigest() image_url = ("https://upload.wikimedia.org/wikipedia/commons/thumb/%s/%s/%s/64px-%s" % (md[0], md[:2], image, image)) return image_url def get_wikidata_desc(wikidata_id): """Return the image for the Wikidata item with *wikidata_id*. """ dapp = urllib.parse.urlencode({'action':'wbgetentities','ids':get_wikidata_id(wikidata_id),'languages':'de'}) query_string = "https://www.wikidata.org/w/api.php?" + dapp res = requests.get(query_string).text print(query_string) item = json.loads(res) wdata = item["entities"][wikidata_id]["descriptions"]["de"]["value"] return wdata if __name__ == "__main__": wid = get_wikidata_id("Limburger Dom") image_url = get_wikidata_image(wid) print(image_url)
[ 11748, 19798, 292, 355, 279, 67, 198, 6738, 764, 1330, 4277, 198, 11748, 47145, 11151, 198, 11748, 33918, 198, 6738, 42903, 1330, 33918, 1958, 198, 11748, 302, 198, 11748, 28686, 198, 11748, 18540, 305, 919, 278, 198, 11748, 7007, 198, ...
2.213873
1,038
import json,requests print(test)
[ 11748, 33918, 11, 8897, 3558, 198, 198, 4798, 7, 9288, 8 ]
3
11
from camera import board_image_processor as bip from chess.models import * import cv2 import numpy as np from media.sound import * if __name__ == '__main__': main() #main_get_color_ranges()
[ 6738, 4676, 1330, 3096, 62, 9060, 62, 41341, 355, 14141, 198, 6738, 19780, 13, 27530, 1330, 1635, 198, 11748, 269, 85, 17, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 2056, 13, 23661, 1330, 1635, 198, 220, 220, 220, 220, 220, 220, ...
2.423913
92
import numpy as np from numpy import random import glob import scipy.io.wavfile np.random.seed(4)
[ 11748, 299, 32152, 355, 45941, 198, 6738, 299, 32152, 1330, 4738, 198, 11748, 15095, 198, 11748, 629, 541, 88, 13, 952, 13, 45137, 7753, 198, 198, 37659, 13, 25120, 13, 28826, 7, 19, 8, 198 ]
2.828571
35
import a as b import b.c as e b.foo(1) e.baz(1)
[ 11748, 257, 355, 275, 198, 11748, 275, 13, 66, 355, 304, 198, 198, 65, 13, 21943, 7, 16, 8, 198, 68, 13, 65, 1031, 7, 16, 8, 198 ]
1.75
28
#!/usr/bin/python """Summary - Flask Views Used to Control/Wrap a web UI around the Add User Python Script Author: Graham Land Date: 08/12/16 Twitter: @allthingsclowd Github: https://github.com/allthingscloud Blog: https://allthingscloud.eu """ from flask import flash, render_template, session, request, redirect, url_for, json, make_response from app import app import os,binascii import AddUserToProjectv3 as K5User import k5APIwrappersV19 as K5API from functools import wraps app.secret_key = os.urandom(24) JSESSION_ID = binascii.b2a_hex(os.urandom(16)) def login_required(f): """Summary - Decorator used to ensure that routes channeled through this function are authenticated already Otherwise they're returned to the login screen """ return decorated_function
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 37811, 22093, 532, 46947, 29978, 16718, 284, 6779, 14, 54, 2416, 257, 3992, 12454, 198, 220, 220, 220, 1088, 262, 3060, 11787, 11361, 12327, 628, 220, 220, 220, 6434, 25, 11520, 6379, 198, 22...
2.989247
279
from django.contrib.auth.models import AbstractUser from django.core.validators import MinLengthValidator from django.utils.translation import gettext_lazy as _ from django.db import models from . import validators
[ 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 27741, 12982, 198, 6738, 42625, 14208, 13, 7295, 13, 12102, 2024, 1330, 1855, 24539, 47139, 1352, 198, 6738, 42625, 14208, 13, 26791, 13, 41519, 1330, 651, 5239, 62, 75, 125...
3.724138
58
''' :class:`eulxml.xmlmap.XmlObject` classes for working with ABBYY FineReadux OCR XML. Currently supports **FineReader6-schema-v1** and **FineReader8-schema-v2**. ---- ''' from eulxml import xmlmap def frns(xpath): '''Utility function to convert a simple xpath to match any of the configured versions of ABBYY FineReader XML namespaces. Example conversions: * ``page`` becomes ``f1:page|f2:page`` * ``text/par`` becomes ``f1:page/f1:text|f2:page/f2:text`` Uses all declared namespace prefixes from :attr:`Base.ROOT_NAMESPACES` ''' namespaces = Base.ROOT_NAMESPACES.keys() return '|'.join('/'.join('%s:%s' % (ns, el) for el in xpath.split('/')) for ns in namespaces)
[ 7061, 6, 198, 25, 4871, 25, 63, 68, 377, 19875, 13, 19875, 8899, 13, 55, 4029, 10267, 63, 6097, 329, 1762, 351, 9564, 17513, 56, 198, 34389, 5569, 2821, 440, 9419, 23735, 13, 198, 198, 21327, 6971, 12429, 34389, 33634, 21, 12, 15952...
2.451505
299
'''for c in range(1, 10): print(c) print('FIM')''' '''c = 1 while c < 10: print(c) c += 1 print('FIM')''' '''n = 1 while n != 0: #flag ou condio de parada n = int(input('Digite um valor: ')) print('FIM')''' '''r = 'S' while r == 'S': n = int(input('Digite um valor: ')) r = str(input('Quer continuar? [S/N]')).upper() print('FIM')''' n = 1 totPar = totaImpar = 0 while n != 0: n = int(input('Digite um valor: ')) if n != 0: # nao vai contabilizar o 0 no final da contagem if n % 2 ==0: totPar += 1 else: totaImpar += 1 print('Voc digitou {} numeros pares e {} numeros impares.'.format(totPar, totaImpar)) # OBS.: nesse caso no vai considerar o 0 como numero!!!!
[ 7061, 6, 1640, 269, 287, 2837, 7, 16, 11, 838, 2599, 198, 220, 220, 220, 3601, 7, 66, 8, 198, 4798, 10786, 37, 3955, 11537, 7061, 6, 198, 198, 7061, 6, 66, 796, 352, 198, 4514, 269, 1279, 838, 25, 198, 220, 220, 220, 3601, 7, ...
2.084746
354
"""Issue #712""" from nbformat.v4.nbbase import new_code_cell, new_notebook from jupytext import reads, writes from jupytext.cell_to_text import three_backticks_or_more from jupytext.compare import compare, compare_notebooks from .utils import requires_myst
[ 37811, 45147, 1303, 49517, 37811, 198, 6738, 299, 65, 18982, 13, 85, 19, 13, 46803, 8692, 1330, 649, 62, 8189, 62, 3846, 11, 649, 62, 11295, 2070, 198, 198, 6738, 474, 929, 88, 5239, 1330, 9743, 11, 6797, 198, 6738, 474, 929, 88, ...
2.966292
89
# Generated by Django 2.1 on 2018-09-02 14:27 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 362, 13, 16, 319, 2864, 12, 2931, 12, 2999, 1478, 25, 1983, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.966667
30
''' This file provides a wrapper class for Fast_AT (https://github.com/locuslab/fast_adversarial) model for CIFAR-10 dataset. ''' import sys import os import torch import torch.nn as nn import torch.nn.functional as F import tensorflow as tf from ares.model.pytorch_wrapper import pytorch_classifier_with_logits from ares.utils import get_res_path MODEL_PATH = get_res_path('./cifar10/cifar_model_weights_30_epochs.pth') def PreActResNet18(): return PreActResNet(PreActBlock, [2,2,2,2]) if __name__ == '__main__': if not os.path.exists(MODEL_PATH): if not os.path.exists(os.path.dirname(MODEL_PATH)): os.makedirs(os.path.dirname(MODEL_PATH), exist_ok=True) url = 'https://drive.google.com/file/d/1XM-v4hqi9u8EDrQ2xdCo37XXcM9q-R07/view' print('Please download "{}" to "{}".'.format(url, MODEL_PATH))
[ 7061, 6, 770, 2393, 3769, 257, 29908, 1398, 329, 12549, 62, 1404, 357, 5450, 1378, 12567, 13, 785, 14, 75, 10901, 23912, 14, 7217, 62, 324, 690, 36098, 8, 2746, 329, 327, 5064, 1503, 12, 940, 27039, 13, 705, 7061, 198, 198, 11748, ...
2.377778
360
from typing import Callable, TypeVar, List T = TypeVar('T')
[ 6738, 19720, 1330, 4889, 540, 11, 5994, 19852, 11, 7343, 198, 198, 51, 796, 5994, 19852, 10786, 51, 11537, 628 ]
3.1
20
from discord.ext.commands import command, Cog from noheavenbot.utils.constants import TEXTCHANNELS from discord import Member from noheavenbot.utils.database_tables.table_users import Users from noheavenbot.utils.validator import has_role as check_role
[ 6738, 36446, 13, 2302, 13, 9503, 1746, 1330, 3141, 11, 327, 519, 198, 6738, 645, 258, 4005, 13645, 13, 26791, 13, 9979, 1187, 1330, 40383, 3398, 22846, 37142, 198, 6738, 36446, 1330, 10239, 198, 6738, 645, 258, 4005, 13645, 13, 26791, ...
3.493151
73
from mayan.apps.testing.tests.base import GenericViewTestCase from ..events import event_smart_link_edited from ..permissions import permission_smart_link_edit from .mixins import ( SmartLinkConditionViewTestMixin, SmartLinkTestMixin, SmartLinkViewTestMixin )
[ 6738, 743, 272, 13, 18211, 13, 33407, 13, 41989, 13, 8692, 1330, 42044, 7680, 14402, 20448, 198, 198, 6738, 11485, 31534, 1330, 1785, 62, 27004, 62, 8726, 62, 42131, 198, 6738, 11485, 525, 8481, 1330, 7170, 62, 27004, 62, 8726, 62, 19...
3.345679
81
#!/usr/bin/env python # coding: utf-8 # # Self-Driving Car Engineer Nanodegree # # # ## Project: **Finding Lane Lines on the Road** # *** # In this project, you will use the tools you learned about in the lesson to identify lane lines on the road. You can develop your pipeline on a series of individual images, and later apply the result to a video stream (really just a series of images). Check out the video clip "raw-lines-example.mp4" (also contained in this repository) to see what the output should look like after using the helper functions below. # # Once you have a result that looks roughly like "raw-lines-example.mp4", you'll need to get creative and try to average and/or extrapolate the line segments you've detected to map out the full extent of the lane lines. You can see an example of the result you're going for in the video "P1_example.mp4". Ultimately, you would like to draw just one line for the left side of the lane, and one for the right. # # In addition to implementing code, there is a brief writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a [write up template](https://github.com/udacity/CarND-LaneLines-P1/blob/master/writeup_template.md) that can be used to guide the writing process. Completing both the code in the Ipython notebook and the writeup template will cover all of the [rubric points](https://review.udacity.com/#!/rubrics/322/view) for this project. # # --- # Let's have a look at our first image called 'test_images/solidWhiteRight.jpg'. Run the 2 cells below (hit Shift-Enter or the "play" button above) to display the image. # # **Note: If, at any point, you encounter frozen display windows or other confounding issues, you can always start again with a clean slate by going to the "Kernel" menu above and selecting "Restart & Clear Output".** # # --- # **The tools you have are color selection, region of interest selection, grayscaling, Gaussian smoothing, Canny Edge Detection and Hough Tranform line detection. You are also free to explore and try other techniques that were not presented in the lesson. Your goal is piece together a pipeline to detect the line segments in the image, then average/extrapolate them and draw them onto the image for display (as below). Once you have a working pipeline, try it out on the video stream below.** # # --- # # <figure> # <img src="examples/line-segments-example.jpg" width="380" alt="Combined Image" /> # <figcaption> # <p></p> # <p style="text-align: center;"> Your output should look something like this (above) after detecting line segments using the helper functions below </p> # </figcaption> # </figure> # <p></p> # <figure> # <img src="examples/laneLines_thirdPass.jpg" width="380" alt="Combined Image" /> # <figcaption> # <p></p> # <p style="text-align: center;"> Your goal is to connect/average/extrapolate line segments to get output like this</p> # </figcaption> # </figure> # **Run the cell below to import some packages. If you get an `import error` for a package you've already installed, try changing your kernel (select the Kernel menu above --> Change Kernel). Still have problems? Try relaunching Jupyter Notebook from the terminal prompt. Also, consult the forums for more troubleshooting tips.** # ## Import Packages # In[1]: #importing some useful packages import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np import cv2 # ## Read in an Image # In[2]: #reading in an image image = mpimg.imread('test_images/solidWhiteRight.jpg') #printing out some stats and plotting print('This image is:', type(image), 'with dimensions:', image.shape) plt.imshow(image) # if you wanted to show a single color channel image called 'gray', for example, call as plt.imshow(gray, cmap='gray') # ## Ideas for Lane Detection Pipeline # **Some OpenCV functions (beyond those introduced in the lesson) that might be useful for this project are:** # # `cv2.inRange()` for color selection # `cv2.fillPoly()` for regions selection # `cv2.line()` to draw lines on an image given endpoints # `cv2.addWeighted()` to coadd / overlay two images # `cv2.cvtColor()` to grayscale or change color # `cv2.imwrite()` to output images to file # `cv2.bitwise_and()` to apply a mask to an image # # **Check out the OpenCV documentation to learn about these and discover even more awesome functionality!** # ## Helper Functions # Below are some helper functions to help get you started. They should look familiar from the lesson! # In[3]: import math def grayscale(img): """Applies the Grayscale transform This will return an image with only one color channel but NOTE: to see the returned image as grayscale (assuming your grayscaled image is called 'gray') you should call plt.imshow(gray, cmap='gray')""" return cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) # Or use BGR2GRAY if you read an image with cv2.imread() # return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) def canny(img, low_threshold, high_threshold): """Applies the Canny transform""" return cv2.Canny(img, low_threshold, high_threshold) def gaussian_blur(img, kernel_size): """Applies a Gaussian Noise kernel""" return cv2.GaussianBlur(img, (kernel_size, kernel_size), 0) def region_of_interest(img, vertices): """ Applies an image mask. Only keeps the region of the image defined by the polygon formed from `vertices`. The rest of the image is set to black. `vertices` should be a numpy array of integer points. """ #defining a blank mask to start with mask = np.zeros_like(img) #defining a 3 channel or 1 channel color to fill the mask with depending on the input image if len(img.shape) > 2: channel_count = img.shape[2] # i.e. 3 or 4 depending on your image ignore_mask_color = (255,) * channel_count else: ignore_mask_color = 255 #filling pixels inside the polygon defined by "vertices" with the fill color cv2.fillPoly(mask, vertices, ignore_mask_color) #returning the image only where mask pixels are nonzero masked_image = cv2.bitwise_and(img, mask) return masked_image def draw_lines_new(img, lines, color=[255, 0, 0], thickness=6): """ NOTE: this is the function you might want to use as a starting point once you want to average/extrapolate the line segments you detect to map out the full extent of the lane (going from the result shown in raw-lines-example.mp4 to that shown in P1_example.mp4). Think about things like separating line segments by their slope ((y2-y1)/(x2-x1)) to decide which segments are part of the left line vs. the right line. Then, you can average the position of each of the lines and extrapolate to the top and bottom of the lane. This function draws `lines` with `color` and `thickness`. Lines are drawn on the image inplace (mutates the image). If you want to make the lines semi-transparent, think about combining this function with the weighted_img() function below """ ## create an empty array with all the line slope all_slopes = np.zeros((len(lines))) ## create an empty array for left lines left_line_slope = [] ## create an empty array for right lines right_line_slope = [] # keep each line slope in the array for index,line in enumerate(lines): for x1,y1,x2,y2 in line: all_slopes[index] = (y2-y1)/(x2-x1) # get all left line slope if it is positive left_line_slope = all_slopes[all_slopes > 0] # get all left line slope if it is negetive right_line_slope = all_slopes[all_slopes < 0] ## mean value of left slope and right slope m_l = left_line_slope.mean() m_r = right_line_slope.mean() # Create empty list for all the left points and right points final_x4_l = [] final_x3_l = [] final_x4_r = [] final_x3_r = [] ## get fixed y-cordinate in both top and bottom point y4 = 320 y3 = img.shape[0] ## Go for each line to calculate left top x-cordinate, right top x-cordinate, ## left buttom x-cordinate, right bottom top x-cordinate for index,line in enumerate(lines): for x1,y1,x2,y2 in line: m = (y2-y1)/(x2-x1) if m > 0 : final_x4_l.append(int(((x1 + (y4 - y1) / m_l) + (x2 + (y4 - y2) / m_l))/ 2)) final_x3_l.append(int(((x1 + (y3 - y1) / m_l) + (x2 + (y3 - y2) / m_l))/ 2)) else: final_x4_r.append(int(((x1 + (y4 - y1) / m_r) + (x2 + (y4 - y2) / m_r))/ 2)) final_x3_r.append(int(((x1 + (y3 - y1) / m_r) + (x2 + (y3 - y2) / m_r))/ 2)) try : ## taking average of each points x4_l = int(sum(final_x4_l)/ len(final_x4_l)) x4_r = int(sum(final_x4_r)/ len(final_x4_r)) x3_l = int(sum(final_x3_l)/ len(final_x3_l)) x3_r = int(sum(final_x3_r)/ len(final_x3_r)) ## Draw the left line and right line cv2.line(img, (x4_l, y4), (x3_l, y3), color, thickness) cv2.line(img, (x4_r, y4), (x3_r, y3), color, thickness) except: pass def hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap): """ `img` should be the output of a Canny transform. Returns an image with hough lines drawn. """ lines = cv2.HoughLinesP(img, rho, theta, threshold, np.array([]), minLineLength=min_line_len, maxLineGap=max_line_gap) line_img = np.zeros((img.shape[0], img.shape[1], 3), dtype=np.uint8) draw_lines_new(line_img, lines) return line_img # Python 3 has support for cool math symbols. def weighted_img(img, initial_img, =0.8, =1., =0.): """ `img` is the output of the hough_lines(), An image with lines drawn on it. Should be a blank image (all black) with lines drawn on it. `initial_img` should be the image before any processing. The result image is computed as follows: initial_img * + img * + NOTE: initial_img and img must be the same shape! """ return cv2.addWeighted(initial_img, , img, , ) # ## Test Images # # Build your pipeline to work on the images in the directory "test_images" # **You should make sure your pipeline works well on these images before you try the videos.** # In[4]: import os os.listdir("test_images/") # ## Build a Lane Finding Pipeline # # # Build the pipeline and run your solution on all test_images. Make copies into the `test_images_output` directory, and you can use the images in your writeup report. # # Try tuning the various parameters, especially the low and high Canny thresholds as well as the Hough lines parameters. # In[18]: # TODO: Build your pipeline that will draw lane lines on the test_images # then save them to the test_images_output directory. process_test_images('test_images','test_images_output') # In[19]: # In[20]: os.listdir('test_images') # In[21]: # Checking in an image plt.figure(figsize=(15,8)) plt.subplot(121) image = mpimg.imread('test_images/solidYellowCurve.jpg') plt.imshow(image) plt.title('Original image') plt.subplot(122) image = mpimg.imread('test_images_output/whiteCarLaneSwitch.jpg') plt.imshow(image) plt.title('Output image') plt.show() # ## Test on Videos # # You know what's cooler than drawing lanes over images? Drawing lanes over video! # # We can test our solution on two provided videos: # # `solidWhiteRight.mp4` # # `solidYellowLeft.mp4` # # **Note: if you get an import error when you run the next cell, try changing your kernel (select the Kernel menu above --> Change Kernel). Still have problems? Try relaunching Jupyter Notebook from the terminal prompt. Also, consult the forums for more troubleshooting tips.** # # **If you get an error that looks like this:** # ``` # NeedDownloadError: Need ffmpeg exe. # You can download it by calling: # imageio.plugins.ffmpeg.download() # ``` # **Follow the instructions in the error message and check out [this forum post](https://discussions.udacity.com/t/project-error-of-test-on-videos/274082) for more troubleshooting tips across operating systems.** # In[9]: # Import everything needed to edit/save/watch video clips from moviepy.editor import VideoFileClip # In[10]: # Let's try the one with the solid white lane on the right first ... # In[11]: white_output = 'test_videos_output/solidWhiteRight.mp4' ## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video ## To do so add .subclip(start_second,end_second) to the end of the line below ## Where start_second and end_second are integer values representing the start and end of the subclip ## You may also uncomment the following line for a subclip of the first 5 seconds ##clip1 = VideoFileClip("test_videos/solidWhiteRight.mp4").subclip(0,5) clip1 = VideoFileClip("test_videos/solidWhiteRight.mp4") white_clip = clip1.fl_image(process_image) #NOTE: this function expects color images!! white_clip.write_videofile(white_output, audio=False) # ## Improve the draw_lines() function # # **At this point, if you were successful with making the pipeline and tuning parameters, you probably have the Hough line segments drawn onto the road, but what about identifying the full extent of the lane and marking it clearly as in the example video (P1_example.mp4)? Think about defining a line to run the full length of the visible lane based on the line segments you identified with the Hough Transform. As mentioned previously, try to average and/or extrapolate the line segments you've detected to map out the full extent of the lane lines. You can see an example of the result you're going for in the video "P1_example.mp4".** # # **Go back and modify your draw_lines function accordingly and try re-running your pipeline. The new output should draw a single, solid line over the left lane line and a single, solid line over the right lane line. The lines should start from the bottom of the image and extend out to the top of the region of interest.** # Now for the one with the solid yellow lane on the left. This one's more tricky! # In[13]: yellow_output = 'test_videos_output/solidYellowLeft.mp4' ## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video ## To do so add .subclip(start_second,end_second) to the end of the line below ## Where start_second and end_second are integer values representing the start and end of the subclip ## You may also uncomment the following line for a subclip of the first 5 seconds ##clip2 = VideoFileClip('test_videos/solidYellowLeft.mp4').subclip(0,5) clip2 = VideoFileClip('test_videos/solidYellowLeft.mp4') yellow_clip = clip2.fl_image(process_image) yellow_clip.write_videofile(yellow_output, audio=False) # In[16]: challenge_output = 'test_videos_output/challenge.mp4' ## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video ## To do so add .subclip(start_second,end_second) to the end of the line below ## Where start_second and end_second are integer values representing the start and end of the subclip ## You may also uncomment the following line for a subclip of the first 5 seconds ##clip3 = VideoFileClip('test_videos/challenge.mp4').subclip(0,5) clip3 = VideoFileClip('test_videos/challenge.mp4') challenge_clip = clip3.fl_image(process_image) challenge_clip.write_videofile(challenge_output, audio=False)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 2, 1303, 12189, 12, 20564, 1075, 1879, 23164, 18008, 1098, 70, 631, 198, 2, 220, 198, 2, 220, 198, 2, 22492, 4935, 25, 12429, 36276, 15016...
2.909074
5,444
from container.base import TimeBase from container.array import TimeArray, TimeDtype from container.timeseries import TimeSeries from container.timeframe import TimeFrame
[ 6738, 9290, 13, 8692, 1330, 3862, 14881, 198, 6738, 9290, 13, 18747, 1330, 3862, 19182, 11, 3862, 35, 4906, 198, 6738, 9290, 13, 22355, 10640, 1330, 3862, 27996, 198, 6738, 9290, 13, 2435, 14535, 1330, 3862, 19778 ]
4.594595
37
"""Base utility functions, that manipulate basic data structures, etc.""" ################################################################################################### ################################################################################################### def flatten(lst): """Flatten a list of lists into a single list. Parameters ---------- lst : list of list A list of embedded lists. Returns ------- lst A flattened list. """ return [item for sublist in lst for item in sublist]
[ 37811, 14881, 10361, 5499, 11, 326, 18510, 4096, 1366, 8573, 11, 3503, 526, 15931, 198, 198, 29113, 29113, 29113, 21017, 198, 29113, 29113, 29113, 21017, 198, 198, 4299, 27172, 268, 7, 75, 301, 2599, 198, 220, 220, 220, 37227, 7414, 417...
4.043478
138
from django import forms from zentral.core.probes.forms import BaseCreateProbeForm from zentral.utils.forms import validate_sha256 from .probes import (OsqueryProbe, OsqueryComplianceProbe, OsqueryDistributedQueryProbe, OsqueryFileCarveProbe, OsqueryFIMProbe) # OsqueryProbe # OsqueryComplianceProbe KeyFormSet = forms.formset_factory(KeyForm, formset=BaseKeyFormSet, min_num=1, max_num=10, extra=0, can_delete=True) # OsqueryDistributedQueryProbe # OsqueryFileCarveProbe # FIM probes
[ 6738, 42625, 14208, 1330, 5107, 198, 6738, 1976, 298, 1373, 13, 7295, 13, 1676, 12636, 13, 23914, 1330, 7308, 16447, 2964, 1350, 8479, 198, 6738, 1976, 298, 1373, 13, 26791, 13, 23914, 1330, 26571, 62, 26270, 11645, 198, 6738, 764, 1676...
2.148276
290
""" Class description goes here. """ """Package containing gRPC classes.""" __author__ = 'Enrico La Sala <enrico.lasala@bsc.es>' __copyright__ = '2017 Barcelona Supercomputing Center (BSC-CNS)'
[ 198, 37811, 5016, 6764, 2925, 994, 13, 37227, 198, 198, 37811, 27813, 7268, 308, 49, 5662, 6097, 526, 15931, 198, 198, 834, 9800, 834, 796, 705, 4834, 1173, 78, 4689, 4849, 64, 1279, 268, 1173, 78, 13, 21921, 6081, 31, 65, 1416, 13,...
2.940299
67
""" This package contains :class:`~cms.models.offers.offer_template.OfferTemplate` """
[ 37811, 198, 1212, 5301, 4909, 1058, 4871, 25, 63, 93, 46406, 13, 27530, 13, 2364, 364, 13, 47895, 62, 28243, 13, 9362, 263, 30800, 63, 198, 37811, 198 ]
3.107143
28
import numpy from scipy.spatial import distance import matplotlib.pyplot as plt import math import matplotlib.ticker as mtick freqs = [20, 25, 31.5, 40, 50, 63, 80, 100, 125, 160, 200, 250, 315, 400, 500, 630, 800, 1000, 1250, 1600, 2000, 2500, 3150, 4000, 5000, 6300, 8000, 10000, 12500] # from scipy # from scipy # from scipy trigger = [40.49, 39.14, 34.47, 30.5, 39.54, 31.98, 38.37, 43.84, 36.09, 43.72, 40.55, 39.25, 39.15, 38.36, 38.3, 36.58, 39.9, 47.76, 51.64, 37.2, 44.89, 46.6, 51.08, 37.77, 28, 29.59, 30.25, 23.16, 25.74] weight = [0.04,0.04,0.04,0.04,0.04,0.04,0.04,0.14,0.14,0.14,0.14,0.14,0.14,0.14,0.14,0.14,0.14,0.14,0.14, 0.24, 0.41, 0.60, 0.80, 0.94, 1.0, 0.94, 0.80, 0.60, 0.41] ref_spectrum = numpy.genfromtxt('test/test2_far.csv', delimiter=',', skip_header=1, usecols=range(5, 34)) test1_spectrum = numpy.genfromtxt('test/test1_near.csv', delimiter=',', skip_header=1, usecols=range(5, 34)) test2_spectrum = numpy.genfromtxt('test/test2_far_far.csv', delimiter=',', skip_header=1, usecols=range(5, 34)) test3_spectrum = numpy.genfromtxt('test/test_background.csv', delimiter=',', skip_header=1, usecols=range(5, 34)) dist0 = numpy.ones(len(ref_spectrum)) - [distance.cosine(trigger, ref_spectrum[idfreq], w=weight) for idfreq in range(len(ref_spectrum))] dist1 = numpy.ones(len(ref_spectrum)) - [distance.cosine(trigger, test1_spectrum[idfreq], w=weight) for idfreq in range(len(ref_spectrum))] dist2 = numpy.ones(len(ref_spectrum)) - [distance.cosine(trigger, test2_spectrum[idfreq], w=weight) for idfreq in range(len(ref_spectrum))] dist3 = numpy.ones(len(ref_spectrum)) - [distance.cosine(trigger, test3_spectrum[idfreq], w=weight) for idfreq in range(len(ref_spectrum))] dist0_bis = numpy.ones(len(ref_spectrum)) - [dist_cosine(trigger, ref_spectrum[idfreq], w=weight) for idfreq in range(len(ref_spectrum))] #print(numpy.around(dist0_bis - dist0, 3)) ref_spectrum = numpy.rot90(ref_spectrum) test1_spectrum = numpy.rot90(test1_spectrum) test2_spectrum = numpy.rot90(test2_spectrum) test3_spectrum = numpy.rot90(test3_spectrum) fig, axes = plt.subplots(nrows=4, ncols=3, constrained_layout=True) gs = axes[0, 0].get_gridspec() axes[0, 1].imshow(ref_spectrum) autocolor(axes[0, 2].bar(numpy.arange(len(dist0)), dist0)) axes[1, 1].imshow(test1_spectrum) autocolor(axes[1, 2].bar(numpy.arange(len(dist1)), dist1)) axes[2, 1].imshow(test2_spectrum) autocolor(axes[2, 2].bar(numpy.arange(len(dist2)), dist2)) axes[3, 1].imshow(test3_spectrum) axes[3, 2].bar(numpy.arange(len(dist2)), dist3) for ax in axes[0:, 0]: ax.remove() axbig = fig.add_subplot(gs[0:, 0]) axbig.set_title("Spectrum trigger") axbig.imshow(numpy.rot90([trigger])) for i in range(len(axes)): axes[i, 2].set_ylim([0.95, 1.0]) axes[i, 1].set_yticks(range(len(freqs))[::5]) axes[i, 1].set_yticklabels([str(ylab) + " Hz" for ylab in freqs[::5]][::-1]) axes[i, 1].set_xticks(range(len(ref_spectrum[0]))[::20]) axes[i, 1].set_xticklabels([str(xlabel)+" s" % xlabel for xlabel in numpy.arange(0, 10, 0.125)][::20]) axes[i, 2].set_xticks(range(len(ref_spectrum[0]))[::20]) axes[i, 2].set_xticklabels([str(xlabel)+" s" % xlabel for xlabel in numpy.arange(0, 10, 0.125)][::20]) axes[i, 2].set_ylabel("Cosine similarity (%)") axes[i, 2].yaxis.set_major_formatter(mtick.PercentFormatter(1.0)) axes[i, 1].set_title("Spectrogram "+str(i)+" (dB)") axbig.set_yticks(range(len(freqs))) axbig.set_yticklabels([str(ylab) + " Hz" for ylab in freqs][::-1]) axbig.tick_params( axis='x', # changes apply to the x-axis which='both', # both major and minor ticks are affected bottom=False, # ticks along the bottom edge are off top=False, # ticks along the top edge are off labelbottom=False) # labels along the bottom edge are off plt.show()
[ 11748, 299, 32152, 198, 6738, 629, 541, 88, 13, 2777, 34961, 1330, 5253, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 10688, 198, 11748, 2603, 29487, 8019, 13, 83, 15799, 355, 285, 42298, 198, 198, 19503, ...
2.204
1,750
#!/usr/bin/python # # HC-SR04 Ultrasonic ranging sensor # import RPi.GPIO as GPIO import sys, time try: GPIO.setmode(GPIO.BCM) TRIG = 23 ECHO = 24 print "Distance measurement in progress..." GPIO.setup(TRIG, GPIO.OUT) GPIO.setup(ECHO, GPIO.IN) GPIO.output(TRIG, False) while True: print "Waiting for sensor to settle" time.sleep(2) GPIO.output(TRIG, True) time.sleep(0.00001) GPIO.output(TRIG, False) while GPIO.input(ECHO) == 0: pulse_start = time.time() while GPIO.input(ECHO) == 1: pulse_end = time.time() pulse_duration = pulse_end - pulse_start distance = pulse_duration * 17150 distance = round(distance, 2) print "Distance: ", distance, "cm" except KeyboardInterrupt: GPIO.cleanup() print("<Ctrl+C> pressed... exiting.") except: GPIO.cleanup() print("Error: {0} {1}".format(sys.exc_info()[0], sys.exc_info()[1]))
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 198, 2, 27327, 12, 12562, 3023, 46487, 30189, 12897, 12694, 198, 2, 198, 11748, 25812, 72, 13, 16960, 9399, 355, 50143, 198, 11748, 25064, 11, 640, 198, 198, 28311, 25, 198, 220, 220, 22...
1.981884
552
# # -*- coding: utf-8 -*- # Copyright 2020 Red Hat # GNU General Public License v3.0+ # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # from __future__ import absolute_import, division, print_function __metaclass__ = type """ The eos_ospfv3 config file. It is in this file where the current configuration (as dict) is compared to the provided configuration (as dict) and the command set necessary to bring the current configuration to its desired end-state is created. """ import re from ansible.module_utils.six import iteritems from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import ( dict_merge, ) from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.resource_module import ( ResourceModule, ) from ansible_collections.arista.eos.plugins.module_utils.network.eos.facts.facts import ( Facts, ) from ansible_collections.arista.eos.plugins.module_utils.network.eos.rm_templates.ospfv3 import ( Ospfv3Template, ) from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import ( get_from_dict, )
[ 2, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 15069, 12131, 2297, 10983, 198, 2, 22961, 3611, 5094, 13789, 410, 18, 13, 15, 10, 198, 2, 357, 3826, 27975, 45761, 393, 3740, 1378, 2503, 13, 41791, 13, 2...
3.04336
369
from platypush.plugins import Plugin, action # vim:sw=4:ts=4:et:
[ 6738, 40315, 4464, 1530, 13, 37390, 1330, 42636, 11, 2223, 628, 198, 198, 2, 43907, 25, 2032, 28, 19, 25, 912, 28, 19, 25, 316, 25, 628 ]
2.555556
27
from django.test.utils import override_settings from hc.api.models import Channel from hc.test import BaseTestCase
[ 6738, 42625, 14208, 13, 9288, 13, 26791, 1330, 20957, 62, 33692, 198, 6738, 289, 66, 13, 15042, 13, 27530, 1330, 11102, 198, 6738, 289, 66, 13, 9288, 1330, 7308, 14402, 20448, 628 ]
3.625
32
import sys sys.setrecursionlimit(3000) r, c = map(int, input().split()) table = [[0] * c for _ in range(r)] rs, cs = map(lambda x:int(x) - 1, input().split()) rg, cg = map(lambda x:int(x) - 1, input().split()) n = int(input()) draw = [list(map(int, input().split())) for _ in range(n)] for ri, ci, hi, wi in draw: ri -= 1 ci -= 1 for i in range(ri, ri+hi): for j in range(ci, ci+wi): table[i][j] = 1 if table[rs][cs] != 1 or table[rg][cg] != 1: print('NO') else: print('YES' if check(rs, cs) else 'NO')
[ 11748, 25064, 198, 17597, 13, 2617, 8344, 24197, 32374, 7, 23924, 8, 198, 220, 220, 220, 220, 198, 198, 81, 11, 269, 796, 3975, 7, 600, 11, 5128, 22446, 35312, 28955, 198, 11487, 796, 16410, 15, 60, 1635, 269, 329, 4808, 287, 2837, ...
2.140078
257
import json import logging from unittest import mock, TestCase from bullet_train import BulletTrain import os logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) TEST_API_URL = 'https://test.bullet-train.io/api' TEST_IDENTIFIER = 'test-identity' TEST_FEATURE = 'test-feature'
[ 11748, 33918, 198, 11748, 18931, 198, 6738, 555, 715, 395, 1330, 15290, 11, 6208, 20448, 198, 198, 6738, 10492, 62, 27432, 1330, 18003, 44077, 198, 11748, 28686, 198, 198, 6404, 1362, 796, 18931, 13, 1136, 11187, 1362, 7, 834, 3672, 834...
2.805556
108
""" This module contains entry points for command-line utilities provided by Plim package. """ import sys import os import argparse import codecs from pkg_resources import get_distribution from pkg_resources import EntryPoint from mako.template import Template from mako.lookup import TemplateLookup from .util import PY3K def plimc(args=None, stdout=None): """This is the `plimc` command line utility :param args: list of command-line arguments. If None, then ``sys.argv[1:]`` will be used. :type args: list or None :param stdout: file-like object representing stdout. If None, then ``sys.stdout`` will be used. Custom stdout is used for testing purposes. :type stdout: None or a file-like object """ # Parse arguments # ------------------------------------ cli_parser = argparse.ArgumentParser(description='Compile plim source files into mako files.') cli_parser.add_argument('source', help="path to source plim template") cli_parser.add_argument('-o', '--output', help="write result to FILE.") cli_parser.add_argument('-e', '--encoding', default='utf-8', help="content encoding") cli_parser.add_argument('-p', '--preprocessor', default='plim:preprocessor', help="Preprocessor instance that will be used for parsing the template") cli_parser.add_argument('-H', '--html', action='store_true', help="Render HTML output instead of Mako template") cli_parser.add_argument('-V', '--version', action='version', version='Plim {}'.format(get_distribution("Plim").version)) if args is None: args = sys.argv[1:] args = cli_parser.parse_args(args) # Get custom preprocessor, if specified # ------------------------------------- preprocessor_path = args.preprocessor # Add an empty string path, so modules located at the current working dir # are reachable and considered in the first place (see issue #32). sys.path.insert(0, '') preprocessor = EntryPoint.parse('x={}'.format(preprocessor_path)).load(False) # Render to html, if requested # ---------------------------- if args.html: root_dir = os.path.dirname(os.path.abspath(args.source)) template_file = os.path.basename(args.source) lookup = TemplateLookup(directories=[root_dir], input_encoding=args.encoding, output_encoding=args.encoding, preprocessor=preprocessor) content = lookup.get_template(template_file).render_unicode() else: with codecs.open(args.source, 'rb', args.encoding) as fd: content = preprocessor(fd.read()) # Output # ------------------------------------ if args.output is None: if stdout is None: stdout = PY3K and sys.stdout.buffer or sys.stdout fd = stdout content = codecs.encode(content, 'utf-8') else: fd = codecs.open(args.output, 'wb', args.encoding) try: fd.write(content) finally: fd.close()
[ 37811, 198, 1212, 8265, 4909, 5726, 2173, 329, 3141, 12, 1370, 20081, 2810, 416, 1345, 320, 5301, 13, 198, 37811, 198, 11748, 25064, 198, 11748, 28686, 198, 11748, 1822, 29572, 198, 11748, 40481, 82, 198, 6738, 279, 10025, 62, 37540, 13...
2.618044
1,186
#!/usr/bin/python import time import sys import os from copy import deepcopy sys.path.append(os.path.join(os.getcwd(), '..')) from alphafold.partition import DynamicProgrammingData as DP x = [[]]*500 for i in range( 500 ): x[i] = [0.0]*500 dx = deepcopy( x ) xcontrib = [[]]*500 for i in range( 500 ): xcontrib[i] = [[]]*500 xDP = DP( 500 ) # 500x500 object with other stuff in it. N = 500000 print 'Try for ', N, 'cycles each:' # Time getting print 'GETTING' t0 = time.time() for i in range( N ): y = x[56][56] t1 = time.time() print t1 - t0, 'y = x[56][56]' t0 = time.time() for i in range( N ): y = xDP.X[56][56] t1 = time.time() print t1 - t0,'y = xDP.X[56][56]' t0 = time.time() for i in range( N ): y = getval(xDP,56) t1 = time.time() print t1 - t0, 'y = getval(xDP,56)' t0 = time.time() for i in range( N ): y = xDP[56][56] t1 = time.time() print t1 - t0, 'y = xDP[56][56]' # Time setting print 'SETTING' t0 = time.time() for i in range( N ): x[56][56] = 20 t1 = time.time() print t1 - t0, 'x[56][56] = 20' t0 = time.time() for i in range( N ): xDP.X[56][56] = 20 t1 = time.time() print t1 - t0,'xDP.X[56][56] = 20' t0 = time.time() for i in range( N ): val = 20 xDP.X[56][56] = val t1 = time.time() print t1 - t0,'val = 20; xDP.X[56][56] = val' t0 = time.time() for i in range( N ): xDP[56][56] = 20 t1 = time.time() print t1 - t0,'xDP[56][56] = 20' # Time setting, including derivs print 'SETTING INCLUDE DERIVS' t0 = time.time() for i in range( N ): x[56][56] = 20 dx[56][56] = 0 t1 = time.time() print t1 - t0, 'x[56][56] = 20, dx[56][56] = 20' t0 = time.time() for i in range( N ): x[56][56] = (20,0) t1 = time.time() print t1 - t0, 'x[56][56] = (20,0)' t0 = time.time() for i in range( N ): xDP.X[56][56] = 20 xDP.dX[56][56] = 0 t1 = time.time() print t1 - t0,'xDP.X[56][56] = 20, xDP.dX[56][56]' t0 = time.time() for i in range( N ): xDP.add(56,56,20) t1 = time.time() print t1 - t0,'xDP += 20' # Time setting, including derivs and contribs print 'SETTING INCLUDE DERIVS AND CONTRIBS' t0 = time.time() for i in range( N ): x[56][56] = 20 dx[56][56] = 0 xcontrib[56][56].append( [x,56,56,20] ) t1 = time.time() print t1 - t0, 'x[56][56] = 20' t0 = time.time() for i in range( N ): xDP.X[56][56] = 20 xDP.dX[56][56] = 0 xDP.X_contrib[56][56].append( [x,56,56,20] ) t1 = time.time() print t1 - t0,'xDP.X[56][56] = 20' t0 = time.time() for i in range( N ): xDP.add(56,56,20) t1 = time.time() print t1 - t0,'xDP += 20'
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 11748, 640, 198, 11748, 25064, 198, 11748, 28686, 198, 6738, 4866, 1330, 2769, 30073, 198, 17597, 13, 6978, 13, 33295, 7, 418, 13, 6978, 13, 22179, 7, 418, 13, 1136, 66, 16993, 22784, 705, ...
2.084577
1,206
#!/usr/bin/env python3 # -*-coding:Latin-1 -* import time from Definitions import * #from ev3dev2.motor import OUTPUT_B,LargeMotor from ev3dev2.sensor import * from AddSensors import AngleSensor from ev3dev2.sensor.lego import TouchSensor import Trace trace = Trace.Trace() i=0 toucher = TouchSensor(INPUT_3) EncoderSensRight = AngleSensor(INPUT_1) EncoderSensLeft = AngleSensor(INPUT_2) trace.Log('toto\n') while i<50: top = time.time() i=i+1 #toucher.value() fic=open('/sys/class/lego-sensor/sensor0/value0','r') val = fic.read() fic.close() duration = (time.time()-top) trace.Log(val + ': %.2f\n' %(duration*1000)) time.sleep(0.1) trace.Close()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 66, 7656, 25, 49022, 12, 16, 532, 9, 198, 198, 11748, 640, 198, 6738, 45205, 1330, 1635, 198, 2, 6738, 819, 18, 7959, 17, 13, 76, 20965, 1330, 16289, 30076, 62...
2.324324
296
if __name__ == "__main__": import os, sys viclassifier_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) print(viclassifier_dir) sys.path.append(viclassifier_dir) model = load_model('D:\\myai\\projects\\tmp\\git\\viclassifier\\tmps\\model.pth') print(model) image_path = r'C:\xxx\xxx.jpg' # ### python### # d1 = {'a': 1, 'b': 2, 'c': 3} # # # d2 = {} # for key, value in d1.items(): # d2[value] = key # # # # d2 = {k: v for v, k in d1.items()} # # # zip # d2 = dict(zip(d1.value(), d1.key())) class_to_idx = {'bad': 0, 'good': 1} idx_to_class = {k: v for v, k in class_to_idx.items()} predict(model, image_path, idx_to_class, is_show=False, device_type='cuda')
[ 628, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1330, 28686, 11, 25064, 628, 220, 220, 220, 20429, 31172, 7483, 62, 15908, 796, 28686, 13, 6978, 13, 15908, 3672, 7, 418, 13, 6978, 13, 15908, 36...
2.063492
378
# See LICENSE for licensing information. # # Copyright (c) 2016-2019 Regents of the University of California and The Board # of Regents for the Oklahoma Agricultural and Mechanical College # (acting for and on behalf of Oklahoma State University) # All rights reserved. # #!/usr/bin/env python3 "Run a regresion test the library cells for DRC" import unittest from testutils import header,openram_test import sys,os sys.path.append(os.path.join(sys.path[0],"..")) import globals import debug OPTS = globals.OPTS # instantiate a copy of the class to actually run the test if __name__ == "__main__": (OPTS, args) = globals.parse_args() del sys.argv[1:] header(__file__, OPTS.tech_name) unittest.main()
[ 2, 4091, 38559, 24290, 329, 15665, 1321, 13, 198, 2, 198, 2, 15069, 357, 66, 8, 1584, 12, 23344, 3310, 658, 286, 262, 2059, 286, 3442, 290, 383, 5926, 198, 2, 286, 3310, 658, 329, 262, 10433, 36694, 290, 19663, 5535, 198, 2, 357, ...
3.112554
231
# -*- coding: utf-8 -*- """ Created on Sat May 21 17:05:48 2022 @author: Guido Meijer """ import numpy as np import pandas as pd from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score, balanced_accuracy_score, confusion_matrix from ibllib.atlas import BrainRegions from joblib import load from model_functions import load_channel_data, load_trained_model import matplotlib.pyplot as plt import seaborn as sns br = BrainRegions() # Settings FEATURES = ['psd_delta', 'psd_theta', 'psd_alpha', 'psd_beta', 'psd_gamma', 'rms_ap', 'rms_lf', 'spike_rate', 'axial_um', 'x', 'y', 'depth'] # Load in data chan_volt = load_channel_data() # chan_volt = pd.read_parquet("/home/sebastian/Downloads/FlatIron/tables/channels_voltage_features.pqt") chan_volt = chan_volt.loc[~chan_volt['rms_ap'].isnull()] # remove NaNs # 31d8dfb1-71fd-4c53-9229-7cd48bee07e4 64d04585-67e7-4320-baad-8d4589fd18f7 if True: test = chan_volt.loc[['31d8dfb1-71fd-4c53-9229-7cd48bee07e4', '64d04585-67e7-4320-baad-8d4589fd18f7'], : ] else: test = chan_volt feature_arr = test[FEATURES].to_numpy() regions = test['cosmos_acronyms'].values # Load model clf = load_trained_model('channels', 'cosmos') # Decode brain regions print('Decoding brain regions..') predictions = clf.predict(feature_arr) probs = clf.predict_proba(feature_arr) # histogram of response probabilities certainties = probs.max(1) plt.hist(certainties) plt.close() # plot of calibration, how certain are correct versus incorrect predicitions plt.hist(certainties[regions == predictions], label='Correct predictions') plt.hist(certainties[regions != predictions], label='Wrong predictions') plt.title("Model calibration", size=24) plt.legend(frameon=False, fontsize=16) plt.ylabel("Occurences", size=21) plt.xlabel("Prob for predicted region", size=21) plt.xticks(fontsize=14) plt.yticks(fontsize=14) sns.despine() plt.tight_layout() plt.savefig("/home/sebastian/Pictures/calibration") plt.close() # compute accuracy and balanced for our highly imbalanced dataset acc = accuracy_score(regions, predictions) bacc = balanced_accuracy_score(regions, predictions) print(f'Accuracy: {acc*100:.1f}%') print(f'Balanced accuracy: {bacc*100:.1f}%') # compute confusion matrix names = np.unique(np.append(regions, predictions)) cm = confusion_matrix(regions, predictions, labels=names) cm = cm / cm.sum(1)[:, None] cm_copy = cm.copy() # list top n classifications n = 10 np.max(cm[~np.isnan(cm)]) cm[np.isnan(cm)] = 0 for i in range(n): ind = np.unravel_index(np.argmax(cm, axis=None), cm.shape) if ind[0] != ind[1]: print("Top {} classification, mistake: {} gets classified as {}".format(i+1, names[ind[0]], names[ind[1]])) else: print("Top {} classification, success: {} gets classified as {}".format(i+1, names[ind[0]], names[ind[1]])) cm[ind] = 0 # plot confusion matrix plt.imshow(cm_copy) plt.yticks(range(len(names)), names) plt.xticks(range(len(names)), names, rotation='65') plt.show()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 7031, 1737, 2310, 1596, 25, 2713, 25, 2780, 33160, 198, 198, 31, 9800, 25, 1962, 17305, 2185, 2926, 263, 198, 37811, 198, 11748, 299, 32152, 355,...
2.577645
1,172
# Vinicius Ribeiro # Nmec 82773 # Make sure to run pip3 install -r requirements.txt and load the .dump at Neo4j # https://neo4j.com/docs/operations-manual/current/tools/dump-load/ # Dataset: https://neo4j.com/graphgist/beer-amp-breweries-graphgist#_create_nodes_and_relationships import sys from neo4j import GraphDatabase # Connect to local DB init_db("bolt://localhost:7687", "neo4j", "12345")
[ 2, 11820, 291, 3754, 23133, 68, 7058, 198, 2, 399, 76, 721, 807, 1983, 4790, 198, 2, 6889, 1654, 284, 1057, 7347, 18, 2721, 532, 81, 5359, 13, 14116, 290, 3440, 262, 764, 39455, 379, 21227, 19, 73, 198, 2, 3740, 1378, 710, 78, 1...
2.682119
151
#!/usr/bin/env python import pytest from pyxenon_snippets import directory_listing_recursive
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 11748, 12972, 9288, 628, 198, 6738, 12972, 87, 268, 261, 62, 16184, 3974, 1039, 1330, 8619, 62, 4868, 278, 62, 8344, 30753, 628, 198 ]
2.939394
33
import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines sys.setrecursionlimit(10 ** 7) from itertools import product n, m = map(int, readline().split()) inf = float('inf') dp = [inf] * (2 ** n) dp[0] = 0 for _ in range(m): s, c = readline().rstrip().decode().split() c = int(c) bit = [0] * n for i, ss in enumerate(s): if ss == 'Y': bit[i] = 1 for i, v in enumerate(product([0, 1], repeat=n)): if dp[i] != inf: num = 0 for index, (x, y) in enumerate(zip(v[::-1], bit)): if x == 1 or y == 1: num += 2 ** index dp[num] = min(dp[num], dp[i] + c) print(-1 if dp[-1] == inf else dp[-1])
[ 11748, 25064, 198, 961, 796, 25064, 13, 19282, 259, 13, 22252, 13, 961, 198, 961, 1370, 796, 25064, 13, 19282, 259, 13, 22252, 13, 961, 1370, 198, 961, 6615, 796, 25064, 13, 19282, 259, 13, 22252, 13, 961, 6615, 198, 17597, 13, 2617...
1.97416
387
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # 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 warnings from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 from google.api_core import grpc_helpers_async from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dlp_v2.types import dlp from google.protobuf import empty_pb2 # type: ignore from .base import DlpServiceTransport, DEFAULT_CLIENT_INFO from .grpc import DlpServiceGrpcTransport __all__ = ("DlpServiceGrpcAsyncIOTransport",)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 15069, 12131, 3012, 11419, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2...
3.376694
369
import datetime t=datetime.datetime.now() #date format weekday=t.strftime("%a") # %A for abbr day=t.strftime("%d") month=t.strftime("%b") #%B for abbr month_num=t.strftime("%m") year=t.strftime("%Y") date=t.strftime("%Y-%m-%d") print(date) #time format hour_12=t.strftime("%I") hour_24=t.strftime("%H") minutes=t.strftime("%H") seconds=t.strftime("%S") am_pm=t.strftime("%p") time_12=t.strftime("%I:%M:%S %p") #12hrs time AM/PM time_24=t.strftime("%H:%M:%S") #24 Hrs time print(time_12) print(time_24) print(sem_calc(int(month_num))) print(date())
[ 11748, 4818, 8079, 198, 198, 83, 28, 19608, 8079, 13, 19608, 8079, 13, 2197, 3419, 198, 2, 4475, 5794, 198, 198, 10464, 820, 28, 83, 13, 2536, 31387, 7203, 4, 64, 4943, 1303, 4064, 32, 329, 450, 1671, 198, 820, 28, 83, 13, 2536, ...
2.036364
275
password="pbkdf2(1000,20,sha512)$8a062c206755a51e$df13c5122a621a9de3a64d39f26460f175076ca0"
[ 28712, 2625, 40842, 74, 7568, 17, 7, 12825, 11, 1238, 11, 26270, 25836, 8, 3, 23, 64, 3312, 17, 66, 22136, 38172, 64, 4349, 68, 3, 7568, 1485, 66, 20, 18376, 64, 21, 2481, 64, 24, 2934, 18, 64, 2414, 67, 2670, 69, 18897, 1899, ...
1.735849
53
import os from TheKinozal import settings from storages.backends.s3boto3 import S3Boto3Storage from helpers.random_string import generate_random_string from helpers.chunked_upload import ChunkedS3VideoUploader
[ 11748, 28686, 198, 6738, 383, 42, 2879, 89, 282, 1330, 6460, 198, 6738, 336, 273, 1095, 13, 1891, 2412, 13, 82, 18, 65, 2069, 18, 1330, 311, 18, 33, 2069, 18, 31425, 198, 6738, 49385, 13, 25120, 62, 8841, 1330, 7716, 62, 25120, 62...
3.28125
64
import struct import numpy as np import pandas as pd df_train = pd.read_csv('../data/train_data.csv') df_valid = pd.read_csv('../data/valid_data.csv') df_test = pd.read_csv('../data/test_data.csv') with open('result.dat', 'rb') as f: N, = struct.unpack('i', f.read(4)) no_dims, = struct.unpack('i', f.read(4)) print(N, no_dims) mappedX = struct.unpack('{}d'.format(N * no_dims), f.read(8 * N * no_dims)) mappedX = np.array(mappedX).reshape((N, no_dims)) print(mappedX) tsne_train = mappedX[:len(df_train)] tsne_valid = mappedX[len(df_train):len(df_train)+len(df_valid)] tsne_test = mappedX[len(df_train)+len(df_valid):] assert(len(tsne_train) == len(df_train)) assert(len(tsne_valid) == len(df_valid)) assert(len(tsne_test) == len(df_test)) save_path = '../data/tsne_{}d_30p.npz'.format(no_dims) np.savez(save_path, train=tsne_train, valid=tsne_valid, test=tsne_test) print('Saved: {}'.format(save_path)) # landmarks, = struct.unpack('{}i'.format(N), f.read(4 * N)) # costs, = struct.unpack('{}d'.format(N), f.read(8 * N))
[ 11748, 2878, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 198, 7568, 62, 27432, 796, 279, 67, 13, 961, 62, 40664, 10786, 40720, 7890, 14, 27432, 62, 7890, 13, 40664, 11537, 198, 7568, 62, 12102, 796, ...
2.204819
498
from django.conf.urls.defaults import patterns, url, include # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns( '', (r'^log/', include('requestlog.urls')), (r'^admin/', include(admin.site.urls)), # Pass anything that doesn't match on to the mrs app url(r'^', include('moca.mrs.urls')), ) from django.conf import settings if settings.DEBUG: urlpatterns += patterns( '', (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), )
[ 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 13, 12286, 82, 1330, 7572, 11, 19016, 11, 2291, 198, 198, 2, 791, 23893, 262, 1306, 734, 3951, 284, 7139, 262, 13169, 25, 198, 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 28482, ...
2.405405
259
import warnings from django.test import SimpleTestCase from django.utils.deprecation import RemovedInDjango20Warning from django.utils.safestring import mark_safe from ..utils import render, setup
[ 11748, 14601, 198, 198, 6738, 42625, 14208, 13, 9288, 1330, 17427, 14402, 20448, 198, 6738, 42625, 14208, 13, 26791, 13, 10378, 8344, 341, 1330, 28252, 818, 35, 73, 14208, 1238, 20361, 198, 6738, 42625, 14208, 13, 26791, 13, 49585, 395, ...
3.589286
56
import numpy as np import nltk import re import pandas as pd import sys import pickle from sklearn.pipeline import Pipeline from sklearn.metrics import classification_report from sklearn.model_selection import train_test_split from sklearn.multioutput import MultiOutputClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer from sklearn.model_selection import GridSearchCV from sklearn.metrics import f1_score, precision_score, recall_score from nltk.tokenize import word_tokenize from nltk.stem import WordNetLemmatizer from nltk.corpus import stopwords from sqlalchemy import create_engine # download nltk libraries and stopwords nltk.download(['punkt', 'wordnet','stopwords','averaged_perceptron_tagger']) stop_words = stopwords.words('english') # function to load data def load_data(database_filepath): ''' load data from sql database given the database file path. Returns: X (DataFrame): DataFrame - each row is a message Y (DataFrame): DataFrame - each column is a category categories (list): List of category names ''' engine = create_engine('sqlite:///'+database_filepath) df = pd.read_sql_table('disaster_cleaned', con=engine) X = df['message'].values Y = df.drop(columns = ['id', 'message', 'original', 'genre']).values categories = df.drop(columns = ['id', 'message', 'original', 'genre']).columns return X, Y, categories def tokenize(text): """Returns list of processed and tokenized text given input text.""" # tokenize text and convert to lower case tokens = [tok.lower() for tok in word_tokenize(text)] # remove stop words and non alpha-numeric characters tokens = [tok for tok in tokens if tok not in stop_words and tok.isalnum()] # initialize WordNetLemmatizer object lemmatizer = WordNetLemmatizer() # create list of lemmatized tokens clean_tokens = [] for tok in tokens: clean_tok = lemmatizer.lemmatize(tok).strip() clean_tokens.append(clean_tok) return clean_tokens def build_model(): ''' Returns multi-output random forest classifier pipeline. Construct pipeline for count vectorization of input text, TF-IDF transformation, and initialization of multi-output random forest classifier. Initialize hyperparameter tuning using GridSearchCV. ''' pipeline = Pipeline([ ('vect', CountVectorizer(tokenizer=tokenize)), ('tfidf', TfidfTransformer()), ('clf', MultiOutputClassifier(RandomForestClassifier())) ]) parameters = { 'clf__estimator__n_estimators': [50, 100, 200], 'clf__estimator__min_samples_split': [2, 3, 4] } cv = GridSearchCV(pipeline, param_grid=parameters) return cv def evaluate_model(model, X_test, Y_test, category_names): ''' Returns f1 score, precision, and recall for each category. Parameters: model: trained model object X_test: DataFrame of test messages Y_test: DataFrame of test classified categories category_names: List of category names Returns: eval_df: DataFrame of f1 score, precision, and recall per category. ''' # predict on test data y_pred = model.predict(X_test) # calculate f1 score, precision, and recall f1 = [] precision = [] recall = [] for i in range(y_pred.shape[1]): f1.append(f1_score(Y_test[:,i], y_pred[:,i], average='macro', zero_division=0)) precision.append(precision_score(Y_test[:,i], y_pred[:,i], average='macro', zero_division=0)) recall.append(recall_score(Y_test[:,i], y_pred[:,i], average='macro')) eval_df = pd.DataFrame({"f1":f1, "precision":precision, "recall":recall}, index=category_names) return eval_df def save_model(model, model_filepath): """Save trained model as pickle file to given path.""" with open(model_filepath, 'wb') as file: pickle.dump(model, file) if __name__ == '__main__': main()
[ 11748, 299, 32152, 355, 45941, 198, 11748, 299, 2528, 74, 198, 11748, 302, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 25064, 198, 11748, 2298, 293, 198, 6738, 1341, 35720, 13, 79, 541, 4470, 1330, 37709, 198, 6738, 1341, 35720, ...
2.65619
1,559
#!/usr/bin/python # -*- coding: utf-8 -*- # # getauditrecords.py January 2020 # # Extract list of audit records from SAS Infrastructure Data Server using REST API. # # Examples: # # 1. Return list of audit events from all users and applications # ./getauditrecords.py # # Change History # # 10JAN2020 Comments added # # Copyright 2018, SAS Institute Inc., Cary, NC, USA. 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 Python modules import json import socket import argparse, sys from sharedfunctions import callrestapi,getinputjson,simpleresults,getbaseurl,printresult # Sample reqval="/audit/entries?filter=and(eq(application,'reports'),eq(state,'success'),ge(timeStamp,'2018-11-20'),le(timeStamp,'2020-11-20T23:59:59.999Z'))&sortBy=timeStamp&limit=1000" # Parse arguments based on parameters that are passed in on the command line parser = argparse.ArgumentParser() parser.add_argument("-a","--application", help="Filter by Application or Service name",default=None) parser.add_argument("-l","--limit", help="Maximum number of records to display",default='1000') parser.add_argument("-t","--type", help="Filter by entry Type",default=None) parser.add_argument("-c","--action", help="Filter by entry Action",default=None) parser.add_argument("-s","--state", help="Filter by entry State",default=None) parser.add_argument("-u","--user", help="Filter by Username",default=None) parser.add_argument("-A","--after", help="Filter entries that are created after the specified timestamp. For example: 2020-01-03 or 2020-01-03T18:15Z",default=None) parser.add_argument("-B","--before", help="Filter entries that are created before the specified timestamp. For example: 2020-01-03 or 2020-01-03T18:15Z",default=None) parser.add_argument("-S","--sortby", help="Sort the output ascending by this field",default='timeStamp') parser.add_argument("-o","--output", help="Output Style", choices=['csv','json','simple','simplejson'],default='csv') args = parser.parse_args() appname=args.application output_style=args.output sort_order=args.sortby output_limit=args.limit username=args.user entry_type=args.type entry_action=args.action entry_state=args.state ts_after=args.after ts_before=args.before # Create list for filter conditions filtercond=[] if appname!=None: filtercond.append("eq(application,'"+appname+"')") if username!=None: filtercond.append("eq(user,'"+username+"')") if entry_type!=None: filtercond.append("eq(type,'"+entry_type+"')") if entry_action!=None: filtercond.append("eq(action,'"+entry_action+"')") if entry_state!=None: filtercond.append("eq(state,'"+entry_state+"')") if ts_after!=None: filtercond.append("ge(timeStamp,'"+ts_after+"')") if ts_before!=None: filtercond.append("le(timeStamp,'"+ts_before+"')") # Construct filter delimiter = ',' completefilter = 'and('+delimiter.join(filtercond)+')' # Set request reqtype = 'get' reqval = "/audit/entries?filter="+completefilter+"&limit="+output_limit+"&sortBy="+sort_order # Construct & print endpoint URL baseurl=getbaseurl() endpoint=baseurl+reqval # print("REST endpoint: " +endpoint) # Make REST API call, and process & print results files_result_json=callrestapi(reqval,reqtype) cols=['id','timeStamp','type','action','state','user','remoteAddress','application','description','uri'] printresult(files_result_json,output_style,cols)
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 651, 3885, 270, 8344, 3669, 13, 9078, 3269, 12131, 198, 2, 198, 2, 29677, 1351, 286, 14984, 4406, 422, 35516, 3...
3.212855
1,198
""" File contains handler for ReferenceDataRequest """ import asyncio import uuid from typing import Dict from typing import List from .base_handler import HandlerBase from .base_request import RequestBase from .requests import Subscription from .utils.blp_name import RESPONSE_ERROR from .utils.log import get_logger # pylint: disable=ungrouped-imports try: import blpapi except ImportError: from async_blp.utils import env_test as blpapi LOGGER = get_logger() def _response_handler(self, event_: blpapi.Event): """ Process blpapi.Event.RESPONSE events. This is the last event for the corresponding requests, therefore after processing all messages from the event, None will be send to the corresponding requests. """ self._partial_response_handler(event_) for msg in event_: self._close_requests(msg.correlationIds()) class SubscriptionHandler(HandlerBase): """ Handler gets response events from Bloomberg from other thread, then puts it to request queue. Each handler opens its own session Used for handling subscription requests and responses """ def _subscriber_data_handler(self, event_: blpapi.Event): """ Redirect data to the request queue. """ for msg in event_: for cor_id in msg.correlationIds(): self._current_requests[cor_id].send_queue_message(msg) def _subscriber_status_handler(self, event_: blpapi.Event): """ Raise exception if something goes wrong """ for msg in event_: if msg.asElement().name() not in ("SubscriptionStarted", "SubscriptionStreamsActivated", ): self._raise_exception(msg)
[ 37811, 198, 8979, 4909, 21360, 329, 20984, 6601, 18453, 198, 37811, 198, 198, 11748, 30351, 952, 198, 11748, 334, 27112, 198, 6738, 19720, 1330, 360, 713, 198, 6738, 19720, 1330, 7343, 198, 198, 6738, 764, 8692, 62, 30281, 1330, 32412, ...
2.528846
728
import cytochrome_lib #This is a cytochrome library import matplotlib.pyplot as plt import numpy as np version = "Last update: Aug 8, 2017" desription = "This code calculates population distribution in the cytochrome b6f protein and plots kinetic profiles for two different models: \n'nn' and 'np' models \n The outputs are: \n Figure 1: \n Figure 2: The ppulation distributions for different oxydations states of the cytochrome proteins. \n Figure 3: the resulting absorbance and circular dichroism kinetics for two different models" print desription print version #the eclusions_lst is a list of hemes that are taken into account during calculations (1 - include; 0 - exclude); #There are 8 values for 4 hemes and 2 dipoles per heme: [Qx_p1, Qy_p1, Qx_n1, Qy_n1, Qx_p2, Qy_p2, Qx_n2, Qy_n2] ##This is a main part of a code #This part creates two lists of several instances of a cyt class (see cytochrome library) with different input files exclusions_lst = [] exclusions_lst.append([0,0,0,0,0,0,0,0]) exclusions_lst.append([0,0,1,1,0,0,0,0]) exclusions_lst.append([1,1,1,1,0,0,0,0]) exclusions_lst.append([1,1,1,1,0,0,1,1]) exclusions_lst.append([1,1,1,1,1,1,1,1]) cyt_b6f_np = [] for excl in exclusions_lst: cyt_b6f_np.append(cytochrome_lib.cyt('cytochrome_b6f.txt',excl)) for i in range(len(exclusions_lst)): cyt_b6f_np[i].read_structure_file() cyt_b6f_np[i].Hamiltonian() cyt_b6f_np[i].D_and_R_strength() cyt_b6f_np[i].spectra_plot() exclusions_lst = [] exclusions_lst.append([0,0,0,0,0,0,0,0]) exclusions_lst.append([0,0,1,1,0,0,0,0]) exclusions_lst.append([0,0,1,1,0,0,1,1]) exclusions_lst.append([1,1,1,1,0,0,1,1]) exclusions_lst.append([1,1,1,1,1,1,1,1]) cyt_b6f_nn = [] for excl in exclusions_lst: cyt_b6f_nn.append(cytochrome_lib.cyt('cytochrome_b6f.txt',excl)) for i in range(len(exclusions_lst)): cyt_b6f_nn[i].read_structure_file() cyt_b6f_nn[i].Hamiltonian() cyt_b6f_nn[i].D_and_R_strength() cyt_b6f_nn[i].spectra_plot() x_range_nm = cyt_b6f_nn[0].x_range_nm plt.figure(1) plt.ion() plt.subplot(2,2,1) for i in range(len(exclusions_lst)): plt.plot(x_range_nm,np.sum(cyt_b6f_nn[i].specR,axis = 0),linewidth=2) #plt.plot(x_range_nm,np.sum(specR_full,axis = 0),linewidth=5) #plt.legend(['n1p1','n1n2','n1p2','p1n2','p1p2','n2p2']); plt.title('cytochrome b6f np model') plt.subplot(2,2,2) for i in range(len(exclusions_lst)): plt.plot(x_range_nm,np.sum(cyt_b6f_np[i].specR,axis = 0),linewidth=2) #plt.plot(x_range_nm,np.sum(specR_full,axis = 0),linewidth=5) plt.title('cytochrome b6f nn model') plt.subplot(2,2,3) for i in range(len(exclusions_lst)): plt.plot(x_range_nm,np.sum(cyt_b6f_nn[i].specD,axis = 0),linewidth=2) #plt.plot(x_range_nm,np.sum(specR_full,axis = 0),linewidth=5) plt.subplot(2,2,4) for i in range(len(exclusions_lst)): plt.plot(x_range_nm,np.sum(cyt_b6f_np[i].specD,axis = 0),linewidth=2) plt.show() length = 10000 population = cytochrome_lib.kinetics_solve(np.array([1,1,1,1,0,0,0]),length) plt.figure(2) plt.ion() for i in range(5): plt.plot(range(length),population[i,:]) plt.title("Population distribution of proteins in different oxydation states") plt.legend(['0e- state (fully oxydized)','1e- state','2e- state','3e- state','4e- state(fully reduced)']) plt.show() Absorbance_lst_b6f_nn = [] Circular_Dichroism_lst_b6f_nn = [] for i in range(5): Absorbance_lst_b6f_nn.append(population[i,:]*np.sum(np.sum(cyt_b6f_nn[i].specD,axis = 0))) Circular_Dichroism_lst_b6f_nn.append(population[i,:]*np.sum(np.abs(np.sum(cyt_b6f_nn[i].specR,axis = 0)))) Absorbance_b6f_nn = np.asarray(Absorbance_lst_b6f_nn) Circular_Dichroism_b6f_nn = np.asarray(Circular_Dichroism_lst_b6f_nn) Absorbance_lst_b6f_np = [] Circular_Dichroism_lst_b6f_np = [] for i in range(5): Absorbance_lst_b6f_np.append(population[i,:]*np.sum(np.sum(cyt_b6f_np[i].specD,axis = 0))) Circular_Dichroism_lst_b6f_np.append(population[i,:]*np.sum(np.abs(np.sum(cyt_b6f_np[i].specR,axis = 0)))) Absorbance_b6f_np = np.asarray(Absorbance_lst_b6f_np) Circular_Dichroism_b6f_np = np.asarray(Circular_Dichroism_lst_b6f_np) plt.figure(3) plt.ion() plt.title('cytochrome b6f nn and np models') plt.plot(range(length),np.sum(Absorbance_b6f_nn, axis = 0)/np.max(np.sum(Absorbance_b6f_nn, axis = 0))) plt.plot(range(length),np.sum(Absorbance_b6f_np, axis = 0)/np.max(np.sum(Absorbance_b6f_np, axis = 0))) plt.plot(range(length),np.sum(Circular_Dichroism_b6f_nn, axis = 0)/np.max(np.sum(Circular_Dichroism_b6f_nn, axis = 0))) plt.plot(range(length),np.sum(Circular_Dichroism_b6f_np, axis = 0)/np.max(np.sum(Circular_Dichroism_b6f_np, axis = 0))) plt.legend(['OD_nn','OD_np','CD_nn','CD_np']) plt.show() print "\nCalculations are finished. Please, see figures 1-3"
[ 11748, 3075, 1462, 46659, 62, 8019, 1303, 1212, 318, 257, 3075, 1462, 46659, 5888, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 299, 32152, 355, 45941, 628, 198, 198, 9641, 796, 366, 5956, 4296, 25, 2447, ...
2.118878
2,246
from __future__ import unicode_literals from django.conf import settings try: from django.contrib.contenttypes.fields import GenericForeignKey except ImportError: from django.contrib.contenttypes.generic import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models, transaction from django.utils.translation import ugettext_lazy as _ from model_utils import Choices from . import moderation from .constants import (MODERATION_READY_STATE, MODERATION_DRAFT_STATE, MODERATION_STATUS_REJECTED, MODERATION_STATUS_APPROVED, MODERATION_STATUS_PENDING) from .diff import get_changes_between_models from .fields import SerializedObjectField from .managers import ModeratedObjectManager from .signals import post_moderation, pre_moderation from .utils import django_19 import datetime MODERATION_STATES = Choices( (MODERATION_READY_STATE, 'ready', _('Ready for moderation')), (MODERATION_DRAFT_STATE, 'draft', _('Draft')), ) STATUS_CHOICES = Choices( (MODERATION_STATUS_REJECTED, 'rejected', _("Rejected")), (MODERATION_STATUS_APPROVED, 'approved', _("Approved")), (MODERATION_STATUS_PENDING, 'pending', _("Pending")), )
[ 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 28311, 25, 198, 220, 220, 220, 422, 42625, 14208, 13, 3642, 822, 13, 11299, 19199, 13, 25747, 1330, 42044, 33616, 9218...
2.644898
490
from math import floor import pandas as pd def filter_param_cd(df, code): """Return df filtered by approved data """ approved_df = df.copy() params = [param.strip('_cd') for param in df.columns if param.endswith('_cd')] for param in params: #filter out records where param_cd doesn't contain 'A' for approved. approved_df[param].where(approved_df[param + '_cd'].str.contains(code), inplace=True) # drop any rows where all params are nan and return #return approved_df.dropna(axis=0, how='all', subset=params) return approved_df def interp_to_freq(df, freq=15, interp_limit=120, fields=None): """ WARNING: for now this only works on one site at a time, Also must review this function further Args: df (DataFrame): a dataframe with a datetime index freq (int): frequency in minutes interp_limit (int): max time to interpolate over Returns: DataFrame """ #XXX assumes no? multiindex df = df.copy() if type(df) == pd.core.series.Series: df = df.to_frame() #df.reset_index(level=0, inplace=True) limit = floor(interp_limit/freq) freq_str = '{}min'.format(freq) start = df.index[0] end = df.index[-1] new_index = pd.date_range(start=start, end=end, periods=None, freq=freq_str) #new_index = new_index.union(df.index) new_df = pd.DataFrame(index=new_index) new_df = new_df.merge(df, how='outer', left_index=True, right_index=True) #new_df = pd.merge(df, new_df, how='outer', left_index=True, right_index=True) #this resampling eould be more efficient out_df = new_df.interpolate(method='time',limit=limit, limit_direction='both').asfreq(freq_str) out_df = out_df.resample('{}T'.format(freq)).asfreq() out_df.index.name = 'datetime' return out_df #out_df.set_index('site_no', append=True, inplace=True) #return out_df.reorder_levels(['site_no','datetime']) def fill_iv_w_dv(iv_df, dv_df, freq='15min', col='00060'): """Fill gaps in an instantaneous discharge record with daily average estimates Args: iv_df (DataFrame): instantaneous discharge record dv_df (DataFrame): Average daily discharge record. freq (int): frequency of iv record Returns: DataFrame: filled-in discharge record """ #double brackets makes this a dataframe dv_df.rename(axis='columns', mapper={'00060_Mean':'00060'}, inplace=True) #limit ffill to one day or 96 samples at 15min intervals updating_field = dv_df[[col]].asfreq(freq).ffill(limit=96) iv_df.update(updating_field, overwrite=False) #return update_merge(iv_df, updating_field, na_only=True) return iv_df #This function may be deprecated once pandas.update support joins besides left. def update_merge(left, right, na_only=False, on=None): """Performs a combination Args: left (DataFrame): original data right (DataFrame): updated data na_only (bool): if True, only update na values TODO: na_only """ df = left.merge(right, how='outer', left_index=True, right_index=True) # check for column overlap and resolve update for column in df.columns: #if duplicated column, use the value from right if column[-2:] == '_x': name = column[:-2] # find column name if na_only: df[name] = df[name+'_x'].fillna(df[name+'_y']) else: df[name+'_x'].update(df[name+'_y']) df[name] = df[name+'_x'] df.drop([name + '_x', name + '_y'], axis=1, inplace=True) return df
[ 6738, 10688, 1330, 4314, 198, 11748, 19798, 292, 355, 279, 67, 198, 198, 4299, 8106, 62, 17143, 62, 10210, 7, 7568, 11, 2438, 2599, 198, 220, 220, 220, 37227, 13615, 47764, 29083, 416, 6325, 1366, 198, 220, 220, 220, 37227, 198, 220, ...
2.382924
1,546