content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
from django.apps import AppConfig from django.utils.translation import gettext_lazy as _
[ 6738, 42625, 14208, 13, 18211, 1330, 2034, 16934, 198, 6738, 42625, 14208, 13, 26791, 13, 41519, 1330, 651, 5239, 62, 75, 12582, 355, 4808, 198 ]
3.56
25
import csv from pylab import * import matplotlib.pyplot as plt count1=[] req_data=[] if __name__ == '__main__': main()
[ 11748, 269, 21370, 201, 198, 6738, 279, 2645, 397, 1330, 1635, 201, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 201, 198, 9127, 16, 28, 21737, 201, 198, 42180, 62, 7890, 28, 21737, 201, 198, 201, 198, 361, 11593, 3...
2.237288
59
## 2018/08/17 Initial ## 2018/08/18 Add CSV format ## 2018/08/23 Add def get_stockidxname_SeymourExcel(),def get_stockidx_SeymourExcel() ## def get_all_stockidx_SeymourExcel() from test_crawl.py ## 2018/09/06 Add value of column 'PBR' in def readExcel() ## 2018/10/27 Add exception handling in def readExcel(self,dir_execlfile) ## 2019/07/20 Add get_all_stockidxname_SeymourExcel, get_stockname_SeymourExcel and get_all_stockname_SeymourExcel ################################################################# import xlrd import xlwt import xlutils.copy import csv import os from logger import logger
[ 2235, 2864, 14, 2919, 14, 1558, 20768, 198, 2235, 2864, 14, 2919, 14, 1507, 3060, 44189, 5794, 198, 2235, 2864, 14, 2919, 14, 1954, 3060, 825, 651, 62, 13578, 312, 87, 3672, 62, 50, 2959, 76, 454, 3109, 5276, 22784, 4299, 651, 62, ...
2.723684
228
#!/usr/bin/env python import os import sys import time from getpass import getpass from optparse import OptionParser from termcolor import colored from launchpadlib.launchpad import Launchpad from github3 import login as github_login from github3 import GitHubError ACTIVE_STATUSES = [ "New", "Confirmed", "Triaged", "In Progress" ] IMPORTED_FIELDS = [ "owner", "web_link", "date_created", "date_last_updated", "tags", ] if __name__ == "__main__": sys.exit(main(sys.argv[1:]))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 640, 198, 6738, 651, 6603, 1330, 651, 6603, 198, 6738, 2172, 29572, 1330, 16018, 46677, 198, 198, 6738, 3381, 8043, 1330, 16396, 198, 67...
2.841808
177
entrada = str(input('Em que cidade voc nasceu? ')) cidade = entrada.strip().lower() partido = cidade.split() pnome = partido[0] santo = (pnome == 'santo') print(santo)
[ 298, 81, 4763, 796, 965, 7, 15414, 10786, 10161, 8358, 269, 312, 671, 12776, 25221, 344, 84, 30, 705, 4008, 198, 66, 312, 671, 796, 24481, 4763, 13, 36311, 22446, 21037, 3419, 198, 3911, 17305, 796, 269, 312, 671, 13, 35312, 3419, 1...
2.42029
69
# # Test for the standard lead acid parameters # import pybamm from tests import get_discretisation_for_testing import unittest if __name__ == "__main__": print("Add -v for more debug output") import sys if "-v" in sys.argv: debug = True pybamm.settings.debug_mode = True unittest.main()
[ 2, 198, 2, 6208, 329, 262, 3210, 1085, 7408, 10007, 198, 2, 198, 11748, 12972, 65, 6475, 198, 6738, 5254, 1330, 651, 62, 15410, 1186, 5612, 62, 1640, 62, 33407, 198, 198, 11748, 555, 715, 395, 628, 198, 198, 361, 11593, 3672, 834, ...
2.675
120
#!/usr/bin/env python from datetime import datetime import serial import sys import time SERIAL_BAUD = 9600 SERIAL_PORT = '/dev/ttyUSB0' TIME_FORMAT = "T%s" # Reset device to activate time setting routine DO_RST = True # Open serial dong print 'opening serial port %s...' % SERIAL_PORT uart = serial.Serial( port=SERIAL_PORT, baudrate=SERIAL_BAUD, dsrdtr=DO_RST, ) # Frobulate the DTR pin to reset the target if DO_RST: print 'twiddling DTR to reset' uart.setRTS(False) uart.setDTR(False) uart.flush() time.sleep(0.2) uart.flushInput() uart.setRTS(True) uart.setDTR(True) time.sleep(1) print 'reset done' # Send start command to begin cycle time.sleep(1) for i in xrange(0, 30): time.sleep(0.1) now = datetime.now().strftime(TIME_FORMAT) uart.write(now + "\r\n") uart.flush() uart.close() print 'done!' sys.exit(0)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 11748, 11389, 198, 11748, 25064, 198, 11748, 640, 198, 198, 35009, 12576, 62, 4339, 8322, 796, 860, 8054, 198, 35009, 12576, 62, 15490, 796,...
2.317708
384
#!/usr/bin/env python # ====================================================================== # This software is distributed under the MIT license reproduced below: # # Copyright (C) 2009-2014 Giampaolo Rodola' <g.rodola@gmail.com> # # Permission to use, copy, modify, and distribute this software and # its documentation for any purpose and without fee is hereby # granted, provided that the above copyright notice appear in all # copies and that both that copyright notice and this permission # notice appear in supporting documentation, and that the name of # Giampaolo Rodola' not be used in advertising or publicity pertaining to # distribution of the software without specific, written prior # permission. # # Giampaolo Rodola' DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, # INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN # NO EVENT Giampaolo Rodola' BE LIABLE FOR ANY SPECIAL, 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 sys try: from setuptools import Extension, setup except ImportError: from distutils.core import Extension, setup NAME = 'pysendfile' VERSION = '2.0.1' if sys.version_info < (2, 5): sys.exit('python version not supported (< 2.5)') if 'sunos' in sys.platform: libraries = ["sendfile"] else: libraries = [] if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 2, 38093, 1421, 28, 198, 2, 770, 3788, 318, 9387, 739, 262, 17168, 5964, 31759, 2174, 25, 198, 2, 198, 2, 220, 220, 220, 220, 15069, 357, 34, 8, 3717, 12, 4967, 220, 8118, 1...
3.615044
452
#!/usr/bin/python2.7 import sys import time import pprint import libiopc_rest as rst action_list=[ {"NAME":"set_env", "FUNCTION":set_env}, {"NAME":"gen_ssh_key", "FUNCTION":gen_ssh_key}, {"NAME":"start_ssh", "FUNCTION":start_ssh}, {"NAME":"stop_ssh", "FUNCTION":stop_ssh}, ] if __name__ == '__main__': if len(sys.argv) < 3: help_usage() hostname=sys.argv[1] action=sys.argv[2] request_list(hostname, 'json', action)
[ 2, 48443, 14629, 14, 8800, 14, 29412, 17, 13, 22, 198, 198, 11748, 25064, 198, 11748, 640, 198, 11748, 279, 4798, 198, 11748, 9195, 14922, 66, 62, 2118, 355, 374, 301, 198, 198, 2673, 62, 4868, 41888, 198, 4895, 20608, 2404, 2617, 6...
2.179245
212
from Stroke import Stroke from TactileBrush import TactileBrush import json from sortedcontainers import SortedList EPSILON = 0.001 def create_pattern(motion : dict): pattern = VibrationPattern(duration, False, 0) for activation_time, steps in motion.items(): # Create starting frame start_frame = Frame(activation_time) for step in steps: # Calculate end time end_time = max(0, min(activation_time + step.duration, pattern.duration)) point = Point(step.column, step.line) # Get pin from config pin = Config.mapping[point] value = step.intensity # Add to starting frame start_frame.actuators.add(ActuatorValue(pin, value)) # Create end frame end_frame = Frame(end_time) end_frame.actuators.add(ActuatorValue(pin, 0.0)) # Add frames pattern.add_frame(start_frame) pattern.add_frame(end_frame) return pattern def get_position_from_string(s : str): s = s.strip() # remove whitespace pos_x = 0 pos_y = 0 try: split = s.split(',') pos_x = float(split[0]) pos_y = float(split[1]) except Exception as e: raise Exception("Invalid position was passed. Format must be 'x,y.") return pos_x, pos_y def get_duration_from_string(s : str): s = s.strip() duration = 0 try: duration = float(s) except Exception as e: raise Exception("Invalid duration was passed. A decimal value must be passed.") return duration if __name__ == "__main__": print("Enter stroke start position (x,y):") start_str = input() start_x, start_y = get_position_from_string(start_str) print("Enter stroke start position (x,y):") end_str = input() end_x, end_y = get_position_from_string(end_str) print("Enter duration of stroke in msec:") duration_str = input() duration = get_duration_from_string(duration_str) t = TactileBrush(Config.lines, Config.columns, Config.spacing) s = Stroke(start_x, start_y, end_x, end_y, duration, 1) motion = t.compute_stroke_steps(s) pattern = create_pattern(motion) print("Json Pattern:\n") print(pattern.to_json())
[ 6738, 30183, 365, 1330, 30183, 365, 198, 6738, 15324, 576, 9414, 1530, 1330, 15324, 576, 9414, 1530, 198, 11748, 33918, 198, 6738, 23243, 3642, 50221, 1330, 311, 9741, 8053, 198, 198, 36, 3705, 4146, 1340, 796, 657, 13, 8298, 198, 198, ...
2.392075
959
import select import socket import json import threading import time import clipboard import math from datetime import datetime ip = "" localpart = "" name = "" tcp = 5555 udp = 5556 buffer_size = 1024 broadcast_try_count = 3 ping_try_count = 3 members = [] # item - (str) ipaddress current_room_ip = "" my_room_name = "" # only room owner has this data discovered_rooms = set() # item - (roomname, roomip) REQUESTED_ROOM = ("", "") CLIPBOARD_DATA = clipboard.paste() CLIPBOARD_LOCK = threading.Lock() DATA_LOCK = threading.Lock() SHARED_TIME_BASE = 0 PRIVATE_TIME_BASE = 0 LATENCY = 0 RECEIVED_PING_COUNTER = 0 LAST_CHANGED_TS = 0 is_main_ui = True input_active = True if __name__ == '__main__': main()
[ 11748, 2922, 198, 11748, 17802, 198, 11748, 33918, 198, 11748, 4704, 278, 198, 11748, 640, 198, 11748, 47999, 198, 11748, 10688, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 198, 541, 796, 13538, 198, 12001, 3911, 796, 13538, 198, 3672, ...
2.629758
289
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import socket import logging import numpy as np import paddle.fluid as fluid from .pruner import Pruner from ..core import VarWrapper, OpWrapper, GraphWrapper from ..common import SAController from ..common import get_logger from ..analysis import flops from ..common import ControllerServer from ..common import ControllerClient __all__ = ["AutoPruner"] _logger = get_logger(__name__, level=logging.INFO)
[ 2, 15069, 357, 66, 8, 13130, 220, 350, 37382, 47, 37382, 46665, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 1, 198, 2, 345, 743, 407, 779, 428, 2393, 2...
3.655914
279
import sys import json from h5model import h5model if len(sys.argv) < 2: print('Usage: ' + sys.argv[0] + ' ' + '<model name>') exit(1) modelName = sys.argv[1] model = h5model(modelName) model.createModel() if model.responseStatus >= 400: print("Unable to create model '" + modelName + "': " + model.errorMessage, file = sys.stderr) exit(1) print(model.responseSuccessPayload)
[ 11748, 25064, 198, 11748, 33918, 198, 6738, 289, 20, 19849, 1330, 289, 20, 19849, 198, 198, 361, 18896, 7, 17597, 13, 853, 85, 8, 1279, 362, 25, 198, 220, 3601, 10786, 28350, 25, 705, 1343, 25064, 13, 853, 85, 58, 15, 60, 1343, 70...
2.668966
145
a='' n=int(input()) while n != 0: a=str(n%2)+a n//=2 print(a)
[ 64, 28, 7061, 198, 77, 28, 600, 7, 15414, 28955, 198, 4514, 299, 14512, 657, 25, 198, 220, 220, 220, 257, 28, 2536, 7, 77, 4, 17, 47762, 64, 198, 220, 220, 220, 299, 1003, 28, 17, 198, 4798, 7, 64, 8, 198 ]
1.627907
43
from anthill.framework.utils.translation import translate_lazy as _ from anthill.platform.conf.settings import * import os # Build paths inside the application like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'nrc_!b1_n4!7cx!4!^&amp;hfu^5axl3_fhki)rbyavnh@mthrk@op' DEBUG = False ADMINS = ( ('Lysenko Vladimir', 'wofkin@gmail.com'), ) SQLALCHEMY_DATABASE_URI = 'postgres://anthill_media@/anthill_media' LOCATION = 'http://localhost:9615' BROKER = 'amqp://guest:guest@localhost:5672' # ROUTES_CONF = 'media.routes' LOCALE_PATH = os.path.join(BASE_DIR, 'locale') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' # APPLICATION_CLASS = 'media.apps.AnthillApplication' APPLICATION_NAME = 'media' APPLICATION_VERBOSE_NAME = _('Media') APPLICATION_DESCRIPTION = _('Manage user uploaded files') APPLICATION_ICON_CLASS = 'icon-file-media' APPLICATION_COLOR = 'teal' # SERVICE_CLASS = 'media.services.Service' CACHES["default"]["LOCATION"] = "redis://localhost:6379/25" CACHES["default"]["KEY_PREFIX"] = "media.anthill" EMAIL_SUBJECT_PREFIX = '[Anthill: media] ' LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'anthill.framework.utils.log.RequireDebugFalse', }, 'require_debug_true': { '()': 'anthill.framework.utils.log.RequireDebugTrue', }, }, 'formatters': { 'anthill.server': { '()': 'anthill.framework.utils.log.ServerFormatter', 'fmt': '%(color)s[%(levelname)1.1s %(asctime)s %(module)s:%(lineno)d]%(end_color)s %(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S', 'color': False, } }, 'handlers': { 'console': { 'level': 'DEBUG', 'filters': ['require_debug_true'], 'class': 'logging.StreamHandler', 'formatter': 'anthill.server', }, 'anthill.server': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'filename': os.path.join(LOGGING_ROOT_DIR, 'media.log'), 'formatter': 'anthill.server', 'maxBytes': 100 * 1024 * 1024, # 100 MiB 'backupCount': 10 }, 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'anthill.framework.utils.log.AdminEmailHandler' } }, 'loggers': { 'anthill': { 'handlers': ['console', 'mail_admins'], 'level': 'INFO', }, 'anthill.application': { 'handlers': ['anthill.server'], 'level': 'INFO', 'propagate': False }, 'tornado.access': { 'handlers': ['anthill.server'], 'level': 'INFO', 'propagate': False }, 'tornado.application': { 'handlers': ['anthill.server'], 'level': 'INFO', 'propagate': False }, 'tornado.general': { 'handlers': ['anthill.server'], 'level': 'INFO', 'propagate': False }, 'celery': { 'handlers': ['anthill.server'], 'level': 'INFO', 'propagate': False }, 'celery.worker': { 'handlers': ['anthill.server'], 'level': 'INFO', 'propagate': False }, 'celery.task': { 'handlers': ['anthill.server'], 'level': 'INFO', 'propagate': False }, 'celery.redirected': { 'handlers': ['anthill.server'], 'level': 'INFO', 'propagate': False }, 'asyncio': { 'handlers': ['anthill.server'], 'level': 'INFO', 'propagate': False }, } } ######### # GEOIP # ######### GEOIP_PATH = os.path.join(BASE_DIR, '../') ######### # HTTPS # ######### # HTTPS = { # 'key_file': os.path.join(BASE_DIR, '../server.key'), # 'crt_file': os.path.join(BASE_DIR, '../server.crt'), # } HTTPS = None ############ # GRAPHENE # ############ GRAPHENE = { 'SCHEMA': 'media.api.v1.public.schema', 'MIDDLEWARE': () } ############# # THUMBNAIL # ############# THUMBNAIL_DEFAULT_OPTIONS = { 'resize': 'fill', # 'fill', 'fit', 'stretch' 'upscale': True, 'format': None, # 'JPEG', 'PNG' 'quality': 90, 'progressive': True, 'orientation': True, 'optimize': False, } THUMBNAIL_ALIASES = { 'test': { 'geometry': '250x250', 'filters': [('crop', '250x250', 'center', 'center')], 'options': {'optimize': True, 'quality': 90, 'format': 'PNG'} } } THUMBNAIL_DIR = 'thumbs'
[ 6738, 26794, 359, 13, 30604, 13, 26791, 13, 41519, 1330, 15772, 62, 75, 12582, 355, 4808, 198, 6738, 26794, 359, 13, 24254, 13, 10414, 13, 33692, 1330, 1635, 198, 11748, 28686, 198, 198, 2, 10934, 13532, 2641, 262, 3586, 588, 428, 25,...
1.99388
2,451
# -*- coding: utf-8 -*- import os, sys from PyQt5.QtWidgets import (QWizard, QMessageBox) from PyQt5.QtGui import QPixmap from PyQt5.QtCore import pyqtSlot, Qt try: import odmltables have_odmltables = True except: have_odmltables = False from .settings import Settings
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 28686, 11, 25064, 198, 6738, 9485, 48, 83, 20, 13, 48, 83, 54, 312, 11407, 1330, 357, 48, 54, 8669, 11, 1195, 12837, 14253, 8, 198, 6738, 9485, 48, 83, ...
2.352459
122
import math #constants and globals background = '0' NORTH = 0 EAST = 1 SOUTH = 2 WEST = 3 dirs = {0 : "NORTH", 1 : "EAST", 2 : "SOUTH", 3 : "WEST"}
[ 11748, 10688, 198, 198, 2, 9979, 1187, 290, 15095, 874, 198, 25249, 796, 705, 15, 6, 198, 35510, 4221, 796, 657, 198, 36, 11262, 796, 352, 198, 50, 2606, 4221, 796, 362, 198, 54, 6465, 796, 513, 198, 198, 15908, 82, 796, 1391, 15,...
2.051282
78
import argparse import glob import json import os import os.path import re import sys from collections import Counter, defaultdict from datetime import datetime from os import path import numpy as np import pandas as pd import tensorflow as tf from acr_module.acr.acr_module_service import get_all_file, load_json_config from nar_module.nar.tf_records_management import (make_sequential_feature, save_rows_to_tf_record_file) from nar_module.nar.utils import (deserialize, extract_local_hour_weekday, gini_index, serialize) # sys.path.append("/home/tungtv/Documents/Code/News/newsrecomdeepneural") from pick_singleton.pick_singleton import ACR_Pickle_Singleton from redis_connector.RedisClient import PageView, RedisClient, Session sys.path.append("/data/tungtv/Code/NewsRecomDeepLearning") # from ..tf_records_management import save_rows_to_tf_record_file, make_sequential_feature # from ..utils import serialize, deserialize, hash_str_to_int, extract_local_hour_weekday, gini_index numeric_scalers = { '_elapsed_ms_since_last_click': { #Set Maximum of 60 min, just to separate returning users, whose elapsed time since last click will be greater than the max 30-min limit for sessions 'valid_max': 60 * 60 * 1000.0, 'avg': 789935.7, 'stddev': 1371436.0}, 'active_time_secs': { 'valid_max': 900.0, 'avg': 65.0, 'stddev': 69.37}, 'active_time_secs_by_word': { 'valid_max': 10.0, 'avg': 1.854, 'stddev': 1.474}, 'text_length':{ 'avg':728 } } if __name__ == '__main__': main_nar_preprocess_2()
[ 11748, 1822, 29572, 198, 11748, 15095, 198, 11748, 33918, 198, 11748, 28686, 198, 11748, 28686, 13, 6978, 198, 11748, 302, 198, 11748, 25064, 198, 6738, 17268, 1330, 15034, 11, 4277, 11600, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 67...
2.185851
834
import pytest # Negative Test case which verifies label search by searching unset labels without pagination. # Negative Test case which verifies label search by searching unset labels with pagination.
[ 11748, 12972, 9288, 628, 628, 198, 2, 36183, 6208, 1339, 543, 3326, 6945, 6167, 2989, 416, 10342, 555, 2617, 14722, 1231, 42208, 1883, 13, 628, 198, 2, 36183, 6208, 1339, 543, 3326, 6945, 6167, 2989, 416, 10342, 555, 2617, 14722, 351, ...
4.622222
45
# Copyright (c) Microsoft. All rights reserved. # Licensed under the MIT license. See LICENSE.md file in the project root # for full license information. # ============================================================================== import sys import numbers import collections import copy import numpy as np from numbers import Number from scipy import sparse from .. import cntk_py from ..device import use_default_device, cpu from ..axis import Axis from cntk.internal import typemap # To __remove__ from cntk.logging import * # End to remove _VARIABLE_OR_FUNCTION = (cntk_py.Variable, cntk_py.Function) # To __remove__ # End to remove def get_data_type(*args): """ Calculates the highest precision numpy data type of the provided parameters. If the parameter is a Function instance, it calculates it based on its inputs. Placeholders are ignored in the type determination. Args: args (number, list, NumPy array, :class:`~cntk.ops.variables.Variable`, or :class:`~cntk.ops.functions.Function`): input Returns: np.float32, np.float64, or None """ from ..ops.variables import Variable cntk_dtypes = set() numpy_dtypes = set() if len(args) == 1 and isinstance(args, _VARIABLE_OR_FUNCTION): args = [args] for arg in args: if isinstance(arg, Variable) and arg.is_placeholder == True: continue if isinstance(arg, (cntk_py.Variable, cntk_py.Value, cntk_py.NDArrayView)): if cntk_py.DataType_Double == arg.get_data_type(): cntk_dtypes.add(np.float64) elif cntk_py.DataType_Float == arg.get_data_type(): cntk_dtypes.add(np.float32) elif isinstance(arg, np.ndarray): if arg.dtype not in (np.float32, np.float64): raise ValueError( 'NumPy type "%s" is not supported' % arg.dtype) numpy_dtypes.add(arg.dtype.type) elif isinstance(arg, _VARIABLE_OR_FUNCTION): var_outputs = arg.outputs if len(var_outputs) > 1: raise ValueError( 'expected single output, but got %i' % len(var_outputs)) var_type = var_outputs[0].get_data_type() if cntk_py.DataType_Double == var_type: cntk_dtypes.add(np.float64) else: cntk_dtypes.add(np.float32) else: # We don't know anything so we convert everything to float32. If it # works, we know the type. # TODO figure out a better/faster way. np.asarray(arg, dtype=np.float32) numpy_dtypes.add(np.float32) if cntk_dtypes: if np.float64 in cntk_dtypes: return np.float64 elif np.float32 in cntk_dtypes: return np.float32 else: if np.float64 in numpy_dtypes: return np.float64 elif np.float32 in numpy_dtypes: return np.float32 def _ones_like(batch, precision): ''' Returns a new batch, which has the same format as ``batch`` but all values set to 1. Args: batch (list of NumPy arrays): a list of sequences, which are NumPy arrays ''' from cntk.internal import sanitize_precision return [np.ones_like(sample, dtype=sanitize_precision(precision)) for sample in batch] def get_train_loss(trainer): ''' Fetch the train loss from the last minibatch and copy it to the CPU in case it is on the GPU. Args: trainer (:class:`~cntk.train.trainer.Trainer`): the trainer used. Returns: the loss value ''' # we copy the value so swig does not destroy it when we leave the scope return copy.copy(trainer.previous_minibatch_loss_average) def get_train_eval_criterion(trainer): ''' Fetch the train evaluation criterion (e.g., classification error) from the last minibatch and copy it to the CPU in case it is on the GPU. Args: trainer (:class:`Trainer`): the trainer used. Returns: the criterion value ''' # we copy the value so swig does not destroy it when we leave the scope return copy.copy(trainer.previous_minibatch_evaluation_average) # Obsolete: All usages should be replaced with the variable_value_to_seq # procedure below def value_to_seq(value): ''' Convert a Value to a sequence of NumPy arrays that have their masked entries removed. Args: value (:class:`~cntk.core.Value`): Value as it is returned by Swig Returns: a list of NumPy arrays ''' np_data = np.asarray(value) mask = value.mask() if mask: mask = np.asarray(mask) np_data = [seq[mask[idx] != cntk_py.MaskKind_Invalid] for idx, seq in enumerate(np_data)] return np_data def variable_value_to_seq(value, variable): ''' Convert a Value to a sequence of NumPy arrays that have their masked entries removed. Args: value (:class:`~cntk.core.Value`): Value as it is returned by Swig Returns: a list of NumPy arrays ''' mask = value.mask() if mask: value_sequences = value.unpack_variable_value(variable, True, cpu()) return [np.asarray(seq) for seq in value_sequences[0]] else: return np.asarray(value) def eval(op, arguments=None, precision=None, device=None, backward_pass=False, expected_backward=None): ''' It evaluates ``op`` on the data provided by the reader. This is useful mainly to explore the operators and for convenient unit testing. Args: op (:class:`Function`): operation to evaluate arguments: maps variables to their input data. The interpretation depends on the input type: * `dict`: keys are input variable or names, and values are the input data. * any other type: if node has a unique input, ``arguments`` is mapped to this input. For nodes with more than one input, only `dict` is allowed. In both cases, every sample in the data will be interpreted as a new sequence. To mark samples as continuations of the previous sequence, specify ``arguments`` as `tuple`: the first element will be used as ``arguments``, and the second one will be used as a list of bools, denoting whether a sequence is a new one (`True`) or a continuation of the previous one (`False`). Data should be either NumPy arrays or a :class:`~cntk.io.MinibatchData` instance. seq_starts (list of bools or None): if None, every sequence is treated as a new sequence. Otherwise, it is interpreted as a list of Booleans that tell whether a sequence is a new sequence (`True`) or a continuation of the sequence in the same slot of the previous minibatch (`False`) precision (str or None): precision being 'float32', 'float64', or None, in which case it will be determined by inspecting the operator (costly) device (:class:`~cntk.device.DeviceDescriptor`, default None): device this value should be put on backward_pass (`bool`, optional): whether a backward pass is performed expected_backward (`dict` or None): keys are variables for which to compute a backward ouptut. By default (None) all entries from 'arguments' are used Returns: mapping of output variables to their values. ''' if backward_pass: state, forward_output = op.forward(arguments, op.outputs, op.outputs, device=device) if expected_backward is None: expected_backward = arguments root_gradients = {v: _ones_like(o, precision) for v, o in forward_output.items()} backward_output = op.backward(state, root_gradients, expected_backward) return forward_output, backward_output else: state, forward_output = op.forward( arguments, op.outputs, None, device=device) return forward_output, None def get_python_function_arguments(f): ''' Helper to get the parameter names and annotations of a Python function. ''' # Note that we only return non-optional arguments (we assume that any optional args are not specified). # This allows to, e.g., accept max(a, b, *more, name='') as a binary function import sys if sys.version_info.major >= 3: from inspect import getfullargspec else: param_specs = getfullargspec(f) annotations = param_specs.annotations arg_names = param_specs.args defaults = param_specs.defaults # "if this tuple has n elements, they correspond to the last n elements listed in args" if defaults: arg_names = arg_names[:-len(defaults)] # we allow Function(functions with default arguments), but those args will always have default values since CNTK Functions do not support this return (arg_names, annotations) def map_function_arguments(params, params_dict, *args, **kwargs): ''' Helper to determine the argument map for use with various call operations. Returns a dictionary from parameters to whatever arguments are passed. Accepted are both positional and keyword arguments. This mimics Python's argument interpretation, except that keyword arguments are not optional. This does not require the arguments to be Variables or Functions. It is also called by train_minibatch() and @Signature. ''' # start with positional arguments arg_map = dict(zip(params, args)) # now look up keyword arguments if len(kwargs) != 0: for name, arg in kwargs.items(): # keyword args are matched by name if name not in params_dict: raise TypeError("got an unexpected keyword argument '%s'" % name) param = params_dict[name] if param in arg_map: raise SyntaxError("got multiple values for argument '%s'" % name) arg_map[param] = arg # add kw argument to dict assert len(arg_map) == len(params) return arg_map def Signature(*args, **kwargs): ''' ``@Signature`` is a decorator to implement the function-argument annotations in Python-2.7, as needed by the ``@Function`` decorator. This is only needed when you have not yet migrated to Python 3.x. Note: Although this is aimed at enabling ``@Function`` syntax with type annotations in Python 2.7, ``@Signature`` is independent of CNTK and can be used for any argument annotation. Args: *args: types of arguments of the function that this decorator is applied to, in the same order. **kwargs: types of arguments with optional names, e.g. `x=Tensor[42]`. Use this second form for longer argument lists. Example:: # Python 3: @Function def f(x: Tensor[42]): return sigmoid(x) # Python 2.7: @Function @Signature(Tensor[42]) def f(x): return sigmoid(x) # note that this: @Function @Signature(x:int) def sqr(x): return x*x # is identical to: def sqr(x): return x*x sqr.__annotations__ = {'x': int}`` ''' # this function returns another function which is the actual decorator applied to the def: return add_annotations def start_profiler(dir='profiler', sync_gpu=True, reserve_mem=cntk_py.default_profiler_buffer_size): ''' Start profiler to prepare performance statistics gathering. Note that the profiler is not enabled after start (`example <https://github.com/Microsoft/CNTK/wiki/Performance-Profiler#for-python>`_). Args: dir: directory for profiler output sync_gpu: whether profiler syncs CPU with GPU when timing reserve_mem: size in byte for profiler memory reserved ''' cntk_py.start_profiler(dir, sync_gpu, reserve_mem) def stop_profiler(): ''' Stop profiler from gathering performance statistics and flush them to file ''' cntk_py.stop_profiler() def enable_profiler(): ''' Enable profiler to gather data. Note that in training_session, profiler would be enabled automatically after the first check point ''' cntk_py.enable_profiler() def disable_profiler(): ''' Disable profiler from gathering data. ''' cntk_py.disable_profiler()
[ 2, 15069, 357, 66, 8, 5413, 13, 1439, 2489, 10395, 13, 198, 2, 49962, 739, 262, 17168, 5964, 13, 4091, 38559, 24290, 13, 9132, 2393, 287, 262, 1628, 6808, 198, 2, 329, 1336, 5964, 1321, 13, 198, 2, 38093, 25609, 28, 198, 198, 1174...
2.588174
4,803
import math
[ 11748, 10688, 628, 628, 198 ]
3.2
5
# @l2g 932 python3 # [932] Beautiful Array # Difficulty: Medium # https://leetcode.com/problems/beautiful-array # # An array nums of length n is beautiful if: # # nums is a permutation of the integers in the range [1, n]. # For every 0 <= i < j < n, there is no index k with i < k < j where 2 * nums[k] == nums[i] + nums[j]. # # Given the integer n,return any beautiful array nums of length n. # There will be at least one valid answer for the given n. # # Example 1: # Input: n = 4 # Output: [2,1,4,3] # Example 2: # Input: n = 5 # Output: [3,1,2,5,4] # # # Constraints: # # 1 <= n <= 1000 # # from typing import List if __name__ == "__main__": import os import pytest pytest.main([os.path.join("tests", "test_932.py")])
[ 2, 2488, 75, 17, 70, 860, 2624, 21015, 18, 198, 2, 685, 24, 2624, 60, 23762, 15690, 198, 2, 27419, 25, 13398, 198, 2, 3740, 1378, 293, 316, 8189, 13, 785, 14, 1676, 22143, 14, 40544, 4135, 12, 18747, 198, 2, 198, 2, 1052, 7177, ...
2.569444
288
from cdm.objectmodel import CdmCorpusDefinition, CdmManifestDefinition from cdm.storage import LocalAdapter from cdm.enums import CdmObjectType def generate_manifest(local_root_path: str) -> 'CdmManifestDefinition': """ Creates a manifest used for the tests. """ cdmCorpus = CdmCorpusDefinition() cdmCorpus.storage.default_namespace = 'local' adapter = LocalAdapter(root=local_root_path) cdmCorpus.storage.mount('local', adapter) # add cdm namespace cdmCorpus.storage.mount('cdm', adapter) manifest = CdmManifestDefinition(cdmCorpus.ctx, 'manifest') manifest.folder_path = '/' manifest.namespace = 'local' return manifest def create_document_for_entity(cdm_corpus: 'CdmCorpusDefinition', entity: 'CdmEntityDefinition', nameSpace: str = 'local'): """ For an entity, it creates a document that will contain the entity. """ cdm_folder_def = cdm_corpus.storage.fetch_root_folder(nameSpace) entity_doc = cdm_corpus.ctx.corpus.make_object(CdmObjectType.DOCUMENT_DEF, '{}.cdm.json'.format(entity.entity_name), False) cdm_folder_def.documents.append(entity_doc) entity_doc.definitions.append(entity) return entity_doc
[ 6738, 22927, 76, 13, 15252, 19849, 1330, 327, 36020, 45680, 385, 36621, 11, 327, 36020, 5124, 8409, 36621, 198, 6738, 22927, 76, 13, 35350, 1330, 10714, 47307, 198, 6738, 22927, 76, 13, 268, 5700, 1330, 327, 36020, 10267, 6030, 628, 198...
2.747727
440
import eventlet from eventlet.green import urllib2 import logging logging.basicConfig() logger = logging.getLogger(__file__) logger.setLevel(logging.DEBUG) if __name__ == '__main__': url = 'http://127.0.0.1/1' num_consumers = 10 num_tasks = 100 task_queue = eventlet.Queue() pool = eventlet.GreenPool() for i in xrange(num_consumers): pool.spawn(consumer, task_queue) for i in xrange(num_tasks): task_queue.put(Task(url)) logger.info('async_call finish loop ' + str(i)) task_queue.join()
[ 11748, 1785, 1616, 198, 6738, 1785, 1616, 13, 14809, 1330, 2956, 297, 571, 17, 198, 11748, 18931, 198, 198, 6404, 2667, 13, 35487, 16934, 3419, 198, 6404, 1362, 796, 18931, 13, 1136, 11187, 1362, 7, 834, 7753, 834, 8, 198, 6404, 1362,...
2.41048
229
from flask.ext.login import UserMixin from werkzeug.security import generate_password_hash, check_password_hash from app import db class Tool(db.Model): """ Tools details. """ __tablename__ = 'tools' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String())
[ 6738, 42903, 13, 2302, 13, 38235, 1330, 11787, 35608, 259, 198, 6738, 266, 9587, 2736, 1018, 13, 12961, 1330, 7716, 62, 28712, 62, 17831, 11, 2198, 62, 28712, 62, 17831, 198, 198, 6738, 598, 1330, 20613, 198, 198, 4871, 16984, 7, 9945...
2.684211
114
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2013 UnitedStack Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # # Copyright (c) 2013-2018 Wind River Systems, Inc. # import jsonpatch import pecan from pecan import rest import wsme from wsme import types as wtypes import wsmeext.pecan as wsme_pecan from sysinv.api.controllers.v1 import base from sysinv.api.controllers.v1 import collection from sysinv.api.controllers.v1 import link from sysinv.api.controllers.v1 import types from sysinv.api.controllers.v1 import utils from sysinv.common import constants from sysinv.common import exception from sysinv.common import health from sysinv.common import utils as cutils from sysinv import objects from sysinv.openstack.common import log from sysinv.openstack.common.gettextutils import _ from fm_api import constants as fm_constants from sysinv.common.storage_backend_conf import StorageBackendConfig LOG = log.getLogger(__name__) def _total_size_controller_multi_fs(controller_fs_new_list): """This function is called to verify file system capability on controller with primary (initial) storage backend already configured calling from initial config (config_controller stage) will result in failure """ total_size = 0 for fs in controller_fs_new_list: if fs.name == constants.FILESYSTEM_NAME_DATABASE: total_size += (2 * fs.size) else: total_size += fs.size return total_size def _total_size_controller_fs(controller_fs_new, controller_fs_list): """This function is called to verify file system capability on controller with primary (initial) storage backend already configured calling from initial config (config_controller stage) will result in failure """ total_size = 0 for fs in controller_fs_list: size = fs['size'] if controller_fs_new and fs['name'] == controller_fs_new['name']: size = controller_fs_new['size'] if fs['name'] == "database": size = size * 2 total_size += size LOG.info( "_total_size_controller_fs total filesysem size %s" % total_size) return total_size def _check_relative_controller_multi_fs(controller_fs_new_list): """ This function verifies the relative controller_fs sizes. :param controller_fs_new_list: :return: None. Raise Client exception on failure. """ if cutils.is_virtual(): return backup_gib_min = constants.BACKUP_OVERHEAD for fs in controller_fs_new_list: if fs.name == constants.FILESYSTEM_NAME_DATABASE: database_gib = fs.size backup_gib_min += fs.size elif fs.name == constants.FILESYSTEM_NAME_CGCS: cgcs_gib = fs.size backup_gib_min += fs.size elif fs.name == constants.FILESYSTEM_NAME_BACKUP: backup_gib = fs.size if backup_gib < backup_gib_min: raise wsme.exc.ClientSideError(_("backup size of %d is " "insufficient. " "Minimum backup size of %d is " "required based upon glance size %d " "and database size %d. " "Rejecting modification " "request." % (backup_gib, backup_gib_min, cgcs_gib, database_gib ))) def _check_relative_controller_fs(controller_fs_new, controller_fs_list): """ This function verifies the relative controller_fs sizes. :param controller_fs_new: :param controller_fs_list: :return: None. Raise Client exception on failure. """ if cutils.is_virtual(): return backup_gib = 0 database_gib = 0 cgcs_gib = 0 for fs in controller_fs_list: if controller_fs_new and fs['name'] == controller_fs_new['name']: fs['size'] = controller_fs_new['size'] if fs['name'] == "backup": backup_gib = fs['size'] elif fs['name'] == constants.DRBD_CGCS: cgcs_gib = fs['size'] elif fs['name'] == "database": database_gib = fs['size'] if backup_gib == 0: LOG.info( "_check_relative_controller_fs backup filesystem not yet setup") return # Required mininum backup filesystem size backup_gib_min = cgcs_gib + database_gib + constants.BACKUP_OVERHEAD if backup_gib < backup_gib_min: raise wsme.exc.ClientSideError(_("backup size of %d is " "insufficient. " "Minimum backup size of %d is " "required based on upon " "glance=%d and database=%d and " "backup overhead of %d. " "Rejecting modification " "request." % (backup_gib, backup_gib_min, cgcs_gib, database_gib, constants.BACKUP_OVERHEAD ))) def _check_controller_state(): """ This function verifies the administrative, operational, availability of each controller. """ chosts = pecan.request.dbapi.ihost_get_by_personality( constants.CONTROLLER) for chost in chosts: if (chost.administrative != constants.ADMIN_UNLOCKED or chost.availability != constants.AVAILABILITY_AVAILABLE or chost.operational != constants.OPERATIONAL_ENABLED): # A node can become degraded due to not free space available in a FS # and thus block the resize operation. If the only alarm that degrades # a controller node is a filesystem alarm, we shouldn't block the resize # as the resize itself will clear the degrade. health_helper = health.Health(pecan.request.dbapi) degrade_alarms = health_helper.get_alarms_degrade( pecan.request.context, alarm_ignore_list=[fm_constants.FM_ALARM_ID_FS_USAGE], entity_instance_id_filter="controller-") allowed_resize = False if (not degrade_alarms and chost.availability == constants.AVAILABILITY_DEGRADED): allowed_resize = True if not allowed_resize: alarm_explanation = "" if degrade_alarms: alarm_explanation = "Check alarms with the following IDs: %s" % str(degrade_alarms) raise wsme.exc.ClientSideError( _("This operation requires controllers to be %s, %s, %s. " "Current status is %s, %s, %s. %s." % (constants.ADMIN_UNLOCKED, constants.OPERATIONAL_ENABLED, constants.AVAILABILITY_AVAILABLE, chost.administrative, chost.operational, chost.availability, alarm_explanation))) return True def _get_controller_cgtsvg_limit(): """Calculate space for controller fs returns: cgtsvg_max_free_GiB """ cgtsvg0_free_mib = 0 cgtsvg1_free_mib = 0 cgtsvg_max_free_GiB = 0 chosts = pecan.request.dbapi.ihost_get_by_personality( constants.CONTROLLER) for chost in chosts: if chost.hostname == constants.CONTROLLER_0_HOSTNAME: ipvs = pecan.request.dbapi.ipv_get_by_ihost(chost.uuid) for ipv in ipvs: if (ipv.lvm_vg_name == constants.LVG_CGTS_VG and ipv.pv_state != constants.PROVISIONED): msg = _("Cannot resize filesystem. There are still " "unprovisioned physical volumes on controller-0.") raise wsme.exc.ClientSideError(msg) ilvgs = pecan.request.dbapi.ilvg_get_by_ihost(chost.uuid) for ilvg in ilvgs: if (ilvg.lvm_vg_name == constants.LVG_CGTS_VG and ilvg.lvm_vg_size and ilvg.lvm_vg_total_pe): cgtsvg0_free_mib = (int(ilvg.lvm_vg_size) * int(ilvg.lvm_vg_free_pe) / int( ilvg.lvm_vg_total_pe)) / (1024 * 1024) break else: ipvs = pecan.request.dbapi.ipv_get_by_ihost(chost.uuid) for ipv in ipvs: if (ipv.lvm_vg_name == constants.LVG_CGTS_VG and ipv.pv_state != constants.PROVISIONED): msg = _("Cannot resize filesystem. There are still " "unprovisioned physical volumes on controller-1.") raise wsme.exc.ClientSideError(msg) ilvgs = pecan.request.dbapi.ilvg_get_by_ihost(chost.uuid) for ilvg in ilvgs: if (ilvg.lvm_vg_name == constants.LVG_CGTS_VG and ilvg.lvm_vg_size and ilvg.lvm_vg_total_pe): cgtsvg1_free_mib = (int(ilvg.lvm_vg_size) * int(ilvg.lvm_vg_free_pe) / int( ilvg.lvm_vg_total_pe)) / (1024 * 1024) break LOG.info("_get_controller_cgtsvg_limit cgtsvg0_free_mib=%s, " "cgtsvg1_free_mib=%s" % (cgtsvg0_free_mib, cgtsvg1_free_mib)) if cgtsvg0_free_mib > 0 and cgtsvg1_free_mib > 0: cgtsvg_max_free_GiB = min(cgtsvg0_free_mib, cgtsvg1_free_mib) / 1024 LOG.info("min of cgtsvg0_free_mib=%s and cgtsvg1_free_mib=%s is " "cgtsvg_max_free_GiB=%s" % (cgtsvg0_free_mib, cgtsvg1_free_mib, cgtsvg_max_free_GiB)) elif cgtsvg1_free_mib > 0: cgtsvg_max_free_GiB = cgtsvg1_free_mib / 1024 else: cgtsvg_max_free_GiB = cgtsvg0_free_mib / 1024 LOG.info("SYS_I filesystem limits cgtsvg0_free_mib=%s, " "cgtsvg1_free_mib=%s, cgtsvg_max_free_GiB=%s" % (cgtsvg0_free_mib, cgtsvg1_free_mib, cgtsvg_max_free_GiB)) return cgtsvg_max_free_GiB def _check_controller_multi_fs_data(context, controller_fs_list_new, modified_fs): """ Check controller filesystem data and return growth returns: cgtsvg_growth_gib """ cgtsvg_growth_gib = 0 # Check if we need img_conversions img_conversion_required = False lvdisplay_keys = [constants.FILESYSTEM_LV_DICT[constants.FILESYSTEM_NAME_DATABASE], constants.FILESYSTEM_LV_DICT[constants.FILESYSTEM_NAME_CGCS], constants.FILESYSTEM_LV_DICT[constants.FILESYSTEM_NAME_BACKUP], constants.FILESYSTEM_LV_DICT[constants.FILESYSTEM_NAME_SCRATCH], constants.FILESYSTEM_LV_DICT[constants.FILESYSTEM_NAME_GNOCCHI]] # On primary region, img-conversions always exists in controller_fs DB table. # On secondary region, if both glance and cinder are sharing from the primary # region, img-conversions won't exist in controller_fs DB table. We already # have semantic check not to allow img-conversions resizing. if (StorageBackendConfig.has_backend(pecan.request.dbapi, constants.SB_TYPE_LVM) or StorageBackendConfig.has_backend(pecan.request.dbapi, constants.SB_TYPE_CEPH)): img_conversion_required = True lvdisplay_keys.append(constants.FILESYSTEM_LV_DICT[constants.FILESYSTEM_NAME_IMG_CONVERSIONS]) if (constants.FILESYSTEM_NAME_IMG_CONVERSIONS in modified_fs and not img_conversion_required): raise wsme.exc.ClientSideError( _("%s is not modifiable: no cinder backend is " "currently configured.") % constants.FILESYSTEM_NAME_IMG_CONVERSIONS) lvdisplay_dict = pecan.request.rpcapi.get_controllerfs_lv_sizes(context) for key in lvdisplay_keys: if not lvdisplay_dict.get(key, None): raise wsme.exc.ClientSideError(_("Unable to determine the " "current size of %s. " "Rejecting modification " "request." % key)) for fs in controller_fs_list_new: lv = fs.logical_volume if lvdisplay_dict.get(lv, None): orig = int(float(lvdisplay_dict[lv])) new = int(fs.size) if fs.name == constants.FILESYSTEM_NAME_DATABASE: orig = orig / 2 if orig > new: raise wsme.exc.ClientSideError(_("'%s' must be at least: " "%s" % (fs.name, orig))) if fs.name == constants.FILESYSTEM_NAME_DATABASE: cgtsvg_growth_gib += 2 * (new - orig) else: cgtsvg_growth_gib += (new - orig) LOG.info("_check_controller_multi_fs_data cgtsvg_growth_gib=%s" % cgtsvg_growth_gib) return cgtsvg_growth_gib LOCK_NAME = 'ControllerFsController'
[ 2, 43907, 25, 7400, 11338, 28, 19, 6482, 10394, 28, 19, 2705, 8658, 11338, 28, 19, 198, 198, 2, 198, 2, 15069, 2211, 1578, 25896, 3457, 13, 198, 2, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, ...
2.000286
6,999
import unittest import torch from easy_bert.losses.label_smoothing_loss import LabelSmoothingCrossEntropy if __name__ == '__main__': unittest.main()
[ 11748, 555, 715, 395, 198, 198, 11748, 28034, 198, 198, 6738, 2562, 62, 4835, 13, 22462, 274, 13, 18242, 62, 5796, 1025, 722, 62, 22462, 1330, 36052, 7556, 1025, 722, 21544, 14539, 28338, 628, 198, 198, 361, 11593, 3672, 834, 6624, 70...
2.77193
57
""" ALGORITHM : Merge Sort WORST CASE => { PERFORMANCE: O(n log(n)) SPACE: O(n) } """ if __name__ == '__main__': sorted_arr = merge_sort([8, 4, 2, 9, 1, 3]) print(sorted_arr)
[ 37811, 201, 198, 1847, 38, 1581, 10554, 44, 1058, 39407, 33947, 201, 198, 45359, 2257, 42001, 5218, 1391, 201, 198, 220, 220, 220, 19878, 13775, 10725, 5222, 25, 220, 440, 7, 77, 2604, 7, 77, 4008, 201, 198, 220, 220, 220, 37253, 25...
1.837607
117
import scrapy from locations.items import GeojsonPointItem from urllib.parse import urlencode from scrapy.selector import Selector from locations.hours import OpeningHours Days = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"]
[ 11748, 15881, 88, 198, 6738, 7064, 13, 23814, 1330, 2269, 13210, 1559, 12727, 7449, 198, 6738, 2956, 297, 571, 13, 29572, 1330, 2956, 11925, 8189, 198, 6738, 15881, 88, 13, 19738, 273, 1330, 9683, 273, 198, 6738, 7064, 13, 24425, 1330, ...
3.246377
69
# import the necessary packages from imutils.video import VideoStream import face_recognition import imutils import pickle import time import cv2 import os # https://www.pyimagesearch.com/2018/06/18/face-recognition-with-opencv-python-and-deep-learning/ # https://www.pyimagesearch.com/2018/06/11/how-to-build-a-custom-face-recognition-dataset/ args = {} # path to serialized db of facial encodings args['encodings'] = os.path.join(os.path.dirname(__file__), 'encodings.pickle') # path to output video args['output'] = None # whether or not to display output frame to screen args['display'] = 1 # face detection model to use: either `hog` or `cnn` args['detection_method'] = 'hog' # load the known faces and embeddings print("[INFO] loading encodings...") data = pickle.loads(open(args["encodings"], "rb").read()) # initialize the video stream and pointer to output video file, then # allow the camera sensor to warm up print("[INFO] starting video stream...") vs = VideoStream(src=0).start() writer = None time.sleep(2.0) # loop over frames from the video file stream while True: # grab the frame from the threaded video stream frame = vs.read() # convert the input frame from BGR to RGB then resize it to have # a width of 750px (to speedup processing) rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) rgb = imutils.resize(frame, width=750) r = frame.shape[1] / float(rgb.shape[1]) # detect the (x, y)-coordinates of the bounding boxes # corresponding to each face in the input frame, then compute # the facial embeddings for each face boxes = face_recognition.face_locations(rgb, model=args["detection_method"]) encodings = face_recognition.face_encodings(rgb, boxes) names = [] # loop over the facial embeddings for encoding in encodings: # attempt to match each face in the input image to our known # encodings matches = face_recognition.compare_faces(data["encodings"], encoding) name = "Unknown" # check to see if we have found a match if True in matches: # find the indexes of all matched faces then initialize a # dictionary to count the total number of times each face # was matched matchedIdxs = [i for (i, b) in enumerate(matches) if b] counts = {} # loop over the matched indexes and maintain a count for # each recognized face face for i in matchedIdxs: name = data["names"][i] counts[name] = counts.get(name, 0) + 1 # determine the recognized face with the largest number # of votes (note: in the event of an unlikely tie Python # will select first entry in the dictionary) name = max(counts, key=counts.get) # update the list of names names.append(name) # loop over the recognized faces for ((top, right, bottom, left), name) in zip(boxes, names): # rescale the face coordinates top = int(top * r) right = int(right * r) bottom = int(bottom * r) left = int(left * r) # draw the predicted face name on the image cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2) y = top - 15 if top - 15 > 15 else top + 15 cv2.putText(frame, name, (left, y), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 2) # if the video writer is None *AND* we are supposed to write # the output video to disk initialize the writer # if writer is None and args["output"] is not None: # fourcc = cv2.VideoWriter_fourcc(*"MJPG") # writer = cv2.VideoWriter(args["output"], fourcc, 20, # (frame.shape[1], frame.shape[0]), True) # # # if the writer is not None, write the frame with recognized # # faces to disk # if writer is not None: # writer.write(frame) # check to see if we are supposed to display the output frame to # the screen if args["display"] > 0: cv2.imshow("Frame", frame) key = cv2.waitKey(1) & 0xFF # if the `q` key was pressed, break from the loop if key == ord("q"): break # do a bit of cleanup cv2.destroyAllWindows() vs.stop() # check to see if the video writer point needs to be released if writer is not None: writer.release()
[ 2, 1330, 262, 3306, 10392, 198, 6738, 545, 26791, 13, 15588, 1330, 7623, 12124, 198, 11748, 1986, 62, 26243, 653, 198, 11748, 545, 26791, 198, 11748, 2298, 293, 198, 11748, 640, 198, 11748, 269, 85, 17, 198, 11748, 28686, 198, 2, 3740...
2.414443
1,911
from pytint.interpreters import FiniteAutomaton from typing import List, Union, Dict, Iterable import collections import yaml def load_machine(yaml_input: str, machine_type: str = "", name: str = ""): # loads yaml from input data = yaml.safe_load(yaml_input) # if no type override, attempt to load type from data if not machine_type: if "type" in data: machine_type = str(data["type"]).lower() else: # can't find machine type raise IncompleteMachine("type", "machine") if not name and "name" in data: name = data["name"] if "start" in data: start = str(data["start"]) start else: raise IncompleteMachine("start", machine_type) if machine_type == "dfa" or machine_type == "nfa": machine = FiniteAutomaton(name) machine.set_start_state(start) if "accept-states" in data: raw_accepted: Union[any, Iterable[any]] = data["accept-states"] if isinstance(raw_accepted, str) or not isinstance(raw_accepted, collections.Iterable): raw_accepted = [raw_accepted] accepted: List[str] = list(map(lambda x: str(x), raw_accepted)) for accept_state in accepted: machine.add_accepting_state(accept_state) else: raise IncompleteMachine("accept-states", machine_type) if "transitions" in data: for transition in data["transitions"]: if len(transition) < 3: raise Exception("Transitions are 3-tuples!") state: str = str(transition[0]) raw_symbols: Union[any, Iterable[any]] = str(transition[1]) if isinstance(raw_symbols, str) or not isinstance(raw_symbols, collections.Iterable): raw_symbols = [raw_symbols] symbols: List[str] = list(map(lambda x: str(x), raw_symbols)) raw_next_states: Union[any, Iterable[any]] = transition[2] if isinstance(raw_next_states, str) or not isinstance(raw_next_states, collections.Iterable): raw_next_states = [raw_next_states] next_states: List[str] = list(map(lambda x: str(x), raw_next_states)) for symbol in symbols: if symbol.lower() == "epsilon" or symbol.lower() == "": # process epsilon symbol = "" for next_state in next_states: machine.add_transition(state, symbol, next_state) else: raise IncompleteMachine("transitions", machine_type) return machine else: raise UnsupportedMachine("{} is not a supported machine type!".format(machine_type)) def load_machine_from_file(path: str, machine_type: str = "", name: str = ""): with open(path, "r") as f: text = f.read() return load_machine(text, machine_type, name)
[ 6738, 12972, 83, 600, 13, 3849, 3866, 1010, 1330, 4463, 578, 38062, 13951, 198, 6738, 19720, 1330, 7343, 11, 4479, 11, 360, 713, 11, 40806, 540, 198, 11748, 17268, 198, 11748, 331, 43695, 628, 628, 198, 4299, 3440, 62, 30243, 7, 88, ...
2.219805
1,333
import dash from dash.dependencies import Input, Output # type: ignore import datetime from treemap import generate_treemap, get_plot_data from app import app from store import store
[ 11748, 14470, 198, 6738, 14470, 13, 45841, 3976, 1330, 23412, 11, 25235, 220, 1303, 2099, 25, 8856, 198, 11748, 4818, 8079, 198, 198, 6738, 2054, 368, 499, 1330, 7716, 62, 33945, 368, 499, 11, 651, 62, 29487, 62, 7890, 198, 6738, 598,...
3.72
50
from django.shortcuts import render from rest_framework.viewsets import ModelViewSet from useraccount.serializer import UserSerializer,AgentUserSerializer from rest_framework.views import APIView from useraccount.models import User from django.http.response import JsonResponse from django.template.loader import render_to_string from django.core.mail import send_mail from rest_framework.authtoken.models import Token from rest_framework.authentication import TokenAuthentication from ticket.models import Organization import random import array
[ 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 198, 6738, 1334, 62, 30604, 13, 1177, 28709, 1330, 9104, 7680, 7248, 198, 6738, 2836, 23317, 13, 46911, 7509, 1330, 11787, 32634, 7509, 11, 36772, 12982, 32634, 7509, 198, 6738, 1334, 62, ...
4.028571
140
# -*- coding: utf-8 -* # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. if __name__ == "__main__": sp = SpecialCharacter({'special_character_dict_path': './special_character_dict.txt'}) print(sp.normalText('01'.decode('utf-8')))
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 198, 2, 15069, 357, 66, 8, 12131, 350, 37382, 47, 37382, 46665, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 3...
3.429185
233
#!/usr/bin/env python from __future__ import absolute_import, print_function, unicode_literals from setuptools import setup, find_packages from unique_uploadto import __version__ with open('README.rst', 'r') as f: readme = f.read() setup( name='django-unique-uploadto', version=__version__, description='Use a unique filename for django uploads', long_description=readme, author='Ionata Digital', author_email='webmaster@ionata.com.au', url='https://github.com/ionata/django-unique-uploadto', license='BSD', packages=find_packages(), install_requires=[ 'django>=1.8.0', ], package_data={}, include_package_data=True, classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Framework :: Django', ], )
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 11, 3601, 62, 8818, 11, 28000, 1098, 62, 17201, 874, 198, 198, 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 198, 198, 6738,...
2.654462
437
import random normal="\033[0m" bold="\033[1m" faint="\033[2m" italic="\033[3m" underline="\033[4m" blinkSlow="\033[5m" blinkRapid="\033[6m" inverse="\033[7m" conceal="\033[8m" crossedOut="\033[9m" black="\033[30m" red="\033[31m" green="\033[32m" yellow="\033[33m" blue="\033[34m" magenta="\033[35m" cyan="\033[36m" white="\033[37m" bgBlack="\033[40m" bgRed="\033[41m" bgGreen="\033[42m" bgYellow="\033[43m" bgBlue="\033[44m" bgMagenta="\033[45m" bgCyan="\033[46m" bgWhite="\033[47m" noStyle="\033[0m" noUnderline="\033[24m" noInverse="\033[27m" noColor="\033[39m"
[ 11748, 4738, 198, 198, 11265, 2625, 59, 44427, 58, 15, 76, 1, 198, 36575, 2625, 59, 44427, 58, 16, 76, 1, 198, 69, 2913, 2625, 59, 44427, 58, 17, 76, 1, 198, 1287, 291, 2625, 59, 44427, 58, 18, 76, 1, 198, 4625, 1370, 2625, 59...
1.855738
305
#!/usr/bin/env python # -*- coding: utf-8 -*- from tree_node import AVLTreeNode from binary_search_tree import BinarySearchTree if __name__ == '__main__': t = AVLTree() t.insert(10) t.insert(15) t.insert(20) t.insert(25) t.insert(30) p = t.search(20) print p, p.left, p.right, p.height, p.parent p = t.search(15) print p, p.left, p.right, p.height, p.parent p = t.search(25) print p, p.left, p.right, p.height, p.parent
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 5509, 62, 17440, 1330, 14661, 43, 27660, 19667, 198, 6738, 13934, 62, 12947, 62, 21048, 1330, 45755, 18243, ...
2.146119
219
from django.apps import AppConfig
[ 6738, 42625, 14208, 13, 18211, 1330, 2034, 16934, 628 ]
3.888889
9
"""This module contains custom data-structures.""" import six
[ 37811, 1212, 8265, 4909, 2183, 1366, 12, 7249, 942, 526, 15931, 198, 11748, 2237, 628 ]
4.2
15
# functions for actions import random import string import GUI
[ 2, 5499, 329, 4028, 198, 11748, 4738, 198, 11748, 4731, 198, 11748, 25757, 628, 198 ]
4.333333
15
# Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import datasets.registry from foundations import hparams from foundations.step import Step from lottery.branch import base import models.registry from pruning.mask import Mask from pruning.pruned_model import PrunedModel from training import train
[ 2, 15069, 357, 66, 8, 3203, 11, 3457, 13, 290, 663, 29116, 13, 198, 198, 2, 770, 2723, 2438, 318, 11971, 739, 262, 17168, 5964, 1043, 287, 262, 198, 2, 38559, 24290, 2393, 287, 262, 6808, 8619, 286, 428, 2723, 5509, 13, 198, 198, ...
4.135922
103
""" Created on Thu Mar 22 15:07:43 2018 @author: Tanvee First attempt at an program for the EV3 bot. The main aim of this is to develop an algorithm to search clockwise for and identify close objects, before rushing to meet them. """ print(0) from time import sleep import sys, os # Import the ev3dev specific library from ev3dev.ev3 import * print(1) # Connect motors rightMotor = LargeMotor(OUTPUT_C) assert rightMotor.connected leftMotor = LargeMotor(OUTPUT_B) assert leftMotor.connected # Connect sensors print(2) tsRIGHT = TouchSensor(INPUT_3) assert tsRIGHT.connected tsLEFT = TouchSensor(INPUT_2) assert tsLEFT.connected us = UltrasonicSensor() assert us.connected cs = ColorSensor(INPUT_4) assert cs.connected print("All Connected") # The gyro is reset when the mode is changed, so the first line is extra, just so we # can change the mode the 'GYRO-ANGLE', which is what we want # gs.mode = 'GYRO-RATE' # Changing the mode resets the gyro # gs.mode = 'GYRO-ANG' # Set gyro mode to return compass angle # We will need to check EV3 buttons state. btn = Button() # FUNCTION DEFINITIONS def drive(left, right): """ Start both motors at the given speeds. """ leftMotor.run_direct(duty_cycle_sp=left) rightMotor.run_direct(duty_cycle_sp=right) """ The default action is to spin around in an attempt to detect any object within a certain radius using the ultrasonic sensor. If the ultrasonic detects anything within 500mm the robot's reacts by "charging" at the object """ while True: main()
[ 37811, 198, 41972, 319, 26223, 1526, 2534, 1315, 25, 2998, 25, 3559, 2864, 198, 31, 9800, 25, 11818, 303, 68, 198, 5962, 2230, 379, 281, 1430, 329, 262, 8696, 18, 10214, 13, 198, 464, 1388, 4031, 286, 428, 318, 284, 1205, 281, 11862...
3.11022
499
from unittest import TestCase, mock from modelgen import ModelGenerator, Base from os import getcwd, path
[ 6738, 555, 715, 395, 1330, 6208, 20448, 11, 15290, 198, 6738, 2746, 5235, 1330, 9104, 8645, 1352, 11, 7308, 198, 6738, 28686, 1330, 651, 66, 16993, 11, 3108 ]
3.75
28
from django.apps import AppConfig # def ready(self): # from papermerge.apps.data_retention import signals # noqa
[ 6738, 42625, 14208, 13, 18211, 1330, 2034, 16934, 628, 198, 2, 220, 220, 220, 825, 3492, 7, 944, 2599, 198, 2, 220, 220, 220, 220, 220, 220, 220, 422, 3348, 647, 469, 13, 18211, 13, 7890, 62, 1186, 1463, 1330, 10425, 220, 1303, 64...
2.73913
46
from logging import getLogger from random import randrange import re from simone.handlers import Registry, exclude_private from .models import Shout # Based loosely on https://github.com/desert-planet/hayt/blob/master/scripts/loud.coffee Registry.register_handler(Loud())
[ 6738, 18931, 1330, 651, 11187, 1362, 198, 6738, 4738, 1330, 43720, 9521, 198, 11748, 302, 198, 198, 6738, 985, 505, 13, 4993, 8116, 1330, 33432, 11, 19607, 62, 19734, 198, 6738, 764, 27530, 1330, 911, 448, 628, 198, 2, 13403, 28845, 3...
3.378049
82
# Time: O(|V| + |E|) # Space: O(|V|) # """ # This is HtmlParser's API interface. # You should not implement it, or speculate about its implementation # """
[ 2, 3862, 25, 220, 440, 7, 91, 53, 91, 1343, 930, 36, 91, 8, 198, 2, 4687, 25, 440, 7, 91, 53, 91, 8, 198, 198, 2, 37227, 198, 2, 770, 318, 367, 20369, 46677, 338, 7824, 7071, 13, 198, 2, 921, 815, 407, 3494, 340, 11, 393, ...
2.839286
56
#!/usr/bin python3 """ The script to collect training data """ import logging import os import cv2 as cv import numpy as np from google_images_download import google_images_download as gid from lib.utils import get_folder from os.path import exists, isfile, join logger = logging.getLogger(__name__) # pylint: disable=invalid-name FRONT_FACE_CASCADE = cv.CascadeClassifier('scripts/haarcascades/haarcascade_frontalface_default.xml') PROFILE_FACE_CASCADE = cv.CascadeClassifier('scripts/haarcascades/haarcascade_profileface.xml') # TODO: Need a function to put images in S3 bucket. # TODO: Retrieve face images from a given video file.
[ 2, 48443, 14629, 14, 8800, 21015, 18, 198, 37811, 383, 4226, 284, 2824, 3047, 1366, 37227, 198, 198, 11748, 18931, 198, 11748, 28686, 198, 11748, 269, 85, 17, 355, 269, 85, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 23645, 62...
3.117073
205
import os import random from shutil import copyfile import json random.seed(123) ROOT_PATH = './data/' k = 5 target_path = './data/wiki_5_splits/' ''' Splits the training set to 5 folds. In each split, the held out set is used for test. ''' path = os.path.join(ROOT_PATH, 'train_wiki' + '.json') data = json.load(open(path, 'r')) relations = list(data.keys()) num_relations = len(relations) rels_per_split = round(num_relations / k) random.shuffle(relations) for i in range(k): split_val_rels = relations[i*rels_per_split: (i+1)*rels_per_split] split_train = {} split_val = {} for rel, examples in data.items(): if rel in split_val_rels: split_val[rel] = examples else: split_train[rel] = examples print(f"split {i}: train: {len(split_val.keys())}, test: {len(split_train.keys())}") os.makedirs(os.path.join(target_path, str(i)), exist_ok=True) with open(os.path.join(target_path, str(i), 'train.json'), 'w') as f: json.dump(split_train, f) with open(os.path.join(target_path, str(i), 'val.json'), 'w') as f: json.dump(split_val, f)
[ 11748, 28686, 198, 11748, 4738, 198, 6738, 4423, 346, 1330, 4866, 7753, 198, 11748, 33918, 198, 198, 25120, 13, 28826, 7, 10163, 8, 198, 198, 13252, 2394, 62, 34219, 796, 705, 19571, 7890, 14, 6, 198, 198, 74, 796, 642, 198, 16793, ...
2.35343
481
from heisen.config import settings from jsonrpclib.request import ConnectionPool rpc_call = get_rpc_connection()
[ 6738, 339, 13254, 13, 11250, 1330, 6460, 198, 6738, 33918, 81, 79, 565, 571, 13, 25927, 1330, 26923, 27201, 628, 198, 198, 81, 14751, 62, 13345, 796, 651, 62, 81, 14751, 62, 38659, 3419, 198 ]
3.314286
35
# =============================================================================== # Copyright 2013 Jake Ross # # 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. # =============================================================================== # ============= enthought library imports ======================= from __future__ import absolute_import from traits.api import Event # ============= standard library imports ======================== # ============= local library imports ========================== from pychron.graph.graph import Graph from pychron.graph.stacked_graph import StackedGraph from pychron.graph.stacked_regression_graph import StackedRegressionGraph # ============= EOF =============================================
[ 2, 38093, 25609, 855, 198, 2, 15069, 2211, 14757, 9847, 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, ...
4.704545
264
#!/usr/bin/env python """ NGINX Status Stub Returns sample resources usage """ import logging import logging.handlers import random from optparse import OptionParser from flask import Flask app = Flask(__name__) app.debug = True # Initialisation logging.basicConfig(format='[%(asctime)-15s] [%(threadName)s] %(levelname)s %(message)s', level=logging.INFO) logger = logging.getLogger('root') if __name__ == "__main__": # Parse options opts_parser = OptionParser() opts_parser.add_option('--port', type="int", dest='port', help='IP Port to listen to.', default=8000) opts_parser.add_option('--debug', action='store_true', dest='debug', help='Print verbose output.', default=False) options, args = opts_parser.parse_args() if options.debug: logger.setLevel(logging.DEBUG) logger.debug('Enabled DEBUG logging level.') logger.info('Options parsed') app.run(host='0.0.0.0', port=options.port)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 37811, 198, 220, 220, 220, 39058, 1268, 55, 12678, 41135, 198, 220, 220, 220, 16409, 6291, 4133, 8748, 198, 37811, 198, 11748, 18931, 198, 11748, 18931, 13, 4993, 8116, 198, 11748, 4738,...
2.807692
338
""" Question 4 Level 1 Question: Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number. Suppose the following input is supplied to the program: 34,67,55,33,12,98 Then, the output should be: ['34', '67', '55', '33', '12', '98'] ('34', '67', '55', '33', '12', '98') Hints: In case of input data being supplied to the question, it should be assumed to be a console input. tuple() method can convert list to tuple """ import unittest from unittest.mock import patch from question4 import listicle, tuplicle, listpicle suite = unittest.TestLoader().loadTestsFromTestCase(TestDict) unittest.TextTestRunner(verbosity=2).run(suite)
[ 37811, 198, 24361, 604, 198, 4971, 352, 198, 198, 24361, 25, 198, 16594, 257, 1430, 543, 18178, 257, 8379, 286, 39650, 12, 25512, 515, 3146, 422, 8624, 290, 7716, 257, 1351, 290, 257, 46545, 543, 4909, 790, 1271, 13, 198, 15979, 577, ...
3.215247
223
from scipy.integrate import quad __all__ = ["quad"]
[ 6738, 629, 541, 88, 13, 18908, 4873, 1330, 15094, 198, 198, 834, 439, 834, 796, 14631, 47003, 8973, 198 ]
2.789474
19
import logging import discord import discord.ext.commands as commands _LOG = logging.getLogger('discord-util').getChild("uwu")
[ 11748, 18931, 198, 198, 11748, 36446, 198, 11748, 36446, 13, 2302, 13, 9503, 1746, 355, 9729, 198, 198, 62, 25294, 796, 18931, 13, 1136, 11187, 1362, 10786, 15410, 585, 12, 22602, 27691, 1136, 16424, 7203, 84, 43812, 4943, 198 ]
3.307692
39
import math import os from curses_tools import draw_frame, get_frame_size def _limit(value, min_value, max_value): """Limit value by min_value and max_value.""" if value < min_value: return min_value if value > max_value: return max_value return value def _apply_acceleration(speed, speed_limit, forward=True): """Change speed accelerate or brake according to force direction.""" speed_limit = abs(speed_limit) speed_fraction = speed / speed_limit # , # , delta = math.cos(speed_fraction) * 0.75 if forward: result_speed = speed + delta else: result_speed = speed - delta result_speed = _limit(result_speed, -speed_limit, speed_limit) # , if abs(result_speed) < 0.1: result_speed = 0 return result_speed
[ 11748, 10688, 198, 11748, 28686, 198, 198, 6738, 43878, 62, 31391, 1330, 3197, 62, 14535, 11, 651, 62, 14535, 62, 7857, 628, 198, 4299, 4808, 32374, 7, 8367, 11, 949, 62, 8367, 11, 3509, 62, 8367, 2599, 198, 220, 220, 220, 37227, 39...
2.531532
333
import secrets import asyncio from datetime import datetime, timedelta import discord from discord.ext import commands from database import DatabasePersonality, DatabaseDeck #### Utilities functions #### def min_until_next_claim(id_server, id_user): """Return minutes until next claim (0 if the user can claim now).""" last_claim = DatabaseDeck.get().get_last_claim(id_server, id_user) time_until_claim = 0 if last_claim: claim_interval = DatabaseDeck.get().get_server_configuration(id_server)['claim_interval'] date_last_claim = datetime.strptime(last_claim, '%Y-%m-%d %H:%M:%S') minute_since_last_claim = int(divmod((datetime.now() - date_last_claim).total_seconds(), 60)[0]) if minute_since_last_claim < claim_interval: time_until_claim = claim_interval - minute_since_last_claim return time_until_claim def min_until_next_roll(id_server, id_user): """Return minutes until next roll (0 if the user can roll now).""" last_roll = DatabaseDeck.get().get_last_roll(id_server, id_user) if not last_roll: return 0 last_roll = datetime.strptime(last_roll, '%Y-%m-%d %H:%M:%S') now = datetime.now() # If a new hour began if now.date() != last_roll.date() or (now.date() == last_roll.date() and now.hour != last_roll.hour): DatabaseDeck.get().set_nb_rolls(id_server, id_user, 0) return 0 max_rolls = DatabaseDeck.get().get_rolls_per_hour(id_server) user_nb_rolls = DatabaseDeck.get().get_nb_rolls(id_server, id_user) if user_nb_rolls < max_rolls: return 0 else: return 60 - now.minute
[ 11748, 13141, 198, 11748, 30351, 952, 198, 6738, 4818, 8079, 1330, 4818, 8079, 11, 28805, 12514, 198, 198, 11748, 36446, 198, 6738, 36446, 13, 2302, 1330, 9729, 198, 198, 6738, 6831, 1330, 24047, 15439, 1483, 11, 24047, 5005, 694, 628, ...
2.529231
650
from __future__ import print_function import time from sr.robot import * SEARCHING = "SEARCHING" DRIVING = "DRIVING" R = Robot() state = SEARCHING while True: if state == SEARCHING: print("Searching for gold tokens...") tokens = get_gold_tokens() print(tokens) if len(tokens) > 0: m = tokens[0] # TODO: Pick the closest token, not just any token. print("Token sighted. {0} is {1}m away, bearing {2} degrees." \ .format(m.info.offset, m.dist, m.rot_y)) state = DRIVING else: print("Can't see anything.") turn(25, 0.3) time.sleep(0.2) elif state == DRIVING: print("Aligning...") tokens = get_gold_tokens() if len(tokens) == 0: state = SEARCHING else: m = tokens[0] if m.dist < 0.4: print("Found it!") if R.grab(): print("Gotcha!") turn(50, 0.5) drive(50, 1) R.release() drive(-50, 0.5) else: print("Aww, I'm not close enough.") exit() elif -15 <= m.rot_y <= 15: print("Ah, that'll do.") drive(50, 0.5) elif m.rot_y < -15: print("Left a bit...") turn(-12.5, 0.5) elif m.rot_y > 15: print("Right a bit...") turn(12.5, 0.5)
[ 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 198, 11748, 640, 198, 198, 6738, 19677, 13, 305, 13645, 1330, 1635, 198, 198, 5188, 31315, 2751, 796, 366, 5188, 31315, 2751, 1, 198, 7707, 3824, 2751, 796, 366, 7707, 3824, 2751, 1,...
1.688242
927
from math import log
[ 6738, 10688, 1330, 2604, 628, 628, 628, 628, 628, 628, 628, 628, 198 ]
2.846154
13
#!/usr/bin/python # -*- coding: utf-8 -*- # ====================================================================== # Copyright 2017 Julien LE CLEACH # # 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 pytest from supvisors.mainloop import * from supvisors.ttypes import AddressStates from supvisors.utils import DeferredRequestHeaders from threading import Thread from unittest.mock import call, patch, Mock, DEFAULT from .base import DummyRpcInterface def test_creation(supvisors, mocked_rpc, main_loop): """ Test the values set at construction. """ assert isinstance(main_loop, Thread) assert main_loop.supvisors is supvisors assert not main_loop.stop_event.is_set() assert main_loop.env == {'SUPERVISOR_SERVER_URL': 'http://127.0.0.1:65000', 'SUPERVISOR_USERNAME': '', 'SUPERVISOR_PASSWORD': ''} assert mocked_rpc.call_args_list == [call('localhost', main_loop.env)] def test_stopping(mocked_rpc, main_loop): """ Test the get_loop method. """ assert not main_loop.stopping() main_loop.stop_event.set() assert main_loop.stopping() def test_stop(mocker, mocked_rpc, main_loop): """ Test the stopping of the main loop thread. """ mocked_join = mocker.patch.object(main_loop, 'join') # try to stop main loop before it is started main_loop.stop() assert not main_loop.stop_event.is_set() assert not mocked_join.called # stop main loop when alive mocker.patch.object(main_loop, 'is_alive', return_value=True) main_loop.stop() assert main_loop.stop_event.is_set() assert mocked_join.call_count == 1 def test_run(mocker, main_loop): """ Test the running of the main loop thread. """ mocked_evt = mocker.patch('supvisors.mainloop.SupvisorsMainLoop.check_events') mocked_req = mocker.patch('supvisors.mainloop.SupvisorsMainLoop.check_requests') mocked_poll = mocker.patch('supvisors.supvisorszmq.SupvisorsZmq.poll') # patch one loops mocker.patch.object(main_loop, 'stopping', side_effect=[False, False, True]) main_loop.run() # test that poll was called once assert mocked_poll.call_args_list == [call()] # test that check_requests was called once assert mocked_evt.call_count == 1 # test that check_events was called once assert mocked_req.call_count == 1 def test_check_events(mocker, main_loop): """ Test the processing of the events received. """ mocked_send = mocker.patch('supvisors.mainloop.SupvisorsMainLoop.send_remote_comm_event') # prepare context mocked_sockets = Mock(**{'check_subscriber.return_value': None}) # test with empty socks main_loop.check_events(mocked_sockets, 'poll result') assert mocked_sockets.check_subscriber.call_args_list == [call('poll result')] assert not mocked_send.called # reset mocks mocked_sockets.check_subscriber.reset_mock() # test with appropriate socks but with exception mocked_sockets.check_subscriber.return_value = 'a message' main_loop.check_events(mocked_sockets, 'poll result') assert mocked_sockets.check_subscriber.call_args_list == [call('poll result')] assert mocked_send.call_args_list == [call('event', '"a message"')] def test_check_requests(mocker, main_loop): """ Test the processing of the requests received. """ mocked_send = mocker.patch('supvisors.mainloop.SupvisorsMainLoop.send_request') # prepare context mocked_sockets = Mock(**{'check_puller.return_value': None}) # test with empty socks main_loop.check_requests(mocked_sockets, 'poll result') assert mocked_sockets.check_puller.call_args_list == [call('poll result')] assert not mocked_sockets.disconnect_subscriber.called assert not mocked_send.called # reset mocks mocked_sockets.check_puller.reset_mock() # test with appropriate socks but with exception mocked_sockets.check_puller.return_value = DeferredRequestHeaders.ISOLATE_NODES, 'a message' main_loop.check_requests(mocked_sockets, 'poll result') assert mocked_sockets.check_puller.call_args_list == [call('poll result')] assert mocked_sockets.disconnect_subscriber.call_args_list == [call('a message')] assert not mocked_send.called # reset mocks mocked_sockets.check_puller.reset_mock() mocked_sockets.disconnect_subscriber.reset_mock() # test with appropriate socks but with exception mocked_sockets.check_puller.return_value = 'event', 'a message' main_loop.check_requests(mocked_sockets, 'poll result') assert mocked_sockets.check_puller.call_args_list == [call('poll result')] assert not mocked_sockets.disconnect_subscriber.called assert mocked_send.call_args_list == [call('event', 'a message')] def test_check_node(mocker, mocked_rpc, main_loop): """ Test the protocol to get the processes handled by a remote Supervisor. """ mocker.patch('supvisors.mainloop.stderr') mocked_evt = mocker.patch('supvisors.mainloop.SupvisorsMainLoop.send_remote_comm_event') # test rpc error: no event is sent to local Supervisor mocked_rpc.side_effect = ValueError main_loop.check_node('10.0.0.1') assert mocked_rpc.call_count == 2 assert mocked_rpc.call_args == call('10.0.0.1', main_loop.env) assert mocked_evt.call_count == 0 # test with a mocked rpc interface dummy_info = [{'name': 'proc', 'group': 'appli', 'state': 10, 'start': 5, 'now': 10, 'pid': 1234, 'spawnerr': ''}] rpc_intf = DummyRpcInterface() mocked_all = rpc_intf.supervisor.getAllProcessInfo = Mock() mocked_local = rpc_intf.supvisors.get_all_local_process_info = Mock(return_value=dummy_info) mocked_addr = rpc_intf.supvisors.get_address_info = Mock() rpc_intf.supvisors.get_master_address = Mock(return_value='10.0.0.5') rpc_intf.supvisors.get_supvisors_state = Mock(return_value={'statename': 'RUNNING'}) mocked_rpc.return_value = rpc_intf mocked_rpc.side_effect = None mocked_rpc.reset_mock() # test with address in isolation for state in [AddressStates.ISOLATING, AddressStates.ISOLATED]: mocked_addr.return_value = {'statecode': state} main_loop.check_node('10.0.0.1') assert mocked_rpc.call_args_list == [call('10.0.0.1', main_loop.env)] expected = 'node_name:10.0.0.1 authorized:False master_node_name:10.0.0.5 supvisors_state:RUNNING' assert mocked_evt.call_args_list == [call('auth', expected)] assert not mocked_all.called # reset counters mocked_evt.reset_mock() mocked_rpc.reset_mock() # test with address not in isolation for state in [AddressStates.UNKNOWN, AddressStates.CHECKING, AddressStates.RUNNING, AddressStates.SILENT]: mocked_addr.return_value = {'statecode': state} main_loop.check_node('10.0.0.1') assert mocked_rpc.call_count == 1 assert mocked_rpc.call_args == call('10.0.0.1', main_loop.env) assert mocked_evt.call_count == 2 assert mocked_local.call_count == 1 # reset counters mocked_evt.reset_mock() mocked_local.reset_mock() mocked_rpc.reset_mock() def test_start_process(mocker, mocked_rpc, main_loop): """ Test the protocol to start a process handled by a remote Supervisor. """ mocker.patch('supvisors.mainloop.stderr') # test rpc error mocked_rpc.side_effect = KeyError main_loop.start_process('10.0.0.1', 'dummy_process', 'extra args') assert mocked_rpc.call_count == 2 assert mocked_rpc.call_args == call('10.0.0.1', main_loop.env) # test with a mocked rpc interface rpc_intf = DummyRpcInterface() mocked_rpc.side_effect = None mocked_rpc.return_value = rpc_intf mocked_supvisors = mocker.patch.object(rpc_intf.supvisors, 'start_args') main_loop.start_process('10.0.0.1', 'dummy_process', 'extra args') assert mocked_rpc.call_count == 3 assert mocked_rpc.call_args == call('10.0.0.1', main_loop.env) assert mocked_supvisors.call_count == 1 assert mocked_supvisors.call_args == call('dummy_process', 'extra args', False) def test_stop_process(mocker, mocked_rpc, main_loop): """ Test the protocol to stop a process handled by a remote Supervisor. """ mocker.patch('supvisors.mainloop.stderr') # test rpc error mocked_rpc.side_effect = ConnectionResetError main_loop.stop_process('10.0.0.1', 'dummy_process') assert mocked_rpc.call_count == 2 assert mocked_rpc.call_args == call('10.0.0.1', main_loop.env) # test with a mocked rpc interface rpc_intf = DummyRpcInterface() mocked_rpc.side_effect = None mocked_rpc.return_value = rpc_intf mocked_supervisor = mocker.patch.object(rpc_intf.supervisor, 'stopProcess') main_loop.stop_process('10.0.0.1', 'dummy_process') assert mocked_rpc.call_count == 3 assert mocked_rpc.call_args == call('10.0.0.1', main_loop.env) assert mocked_supervisor.call_count == 1 assert mocked_supervisor.call_args == call('dummy_process', False) def test_restart(mocker, mocked_rpc, main_loop): """ Test the protocol to restart a remote Supervisor. """ mocker.patch('supvisors.mainloop.stderr') # test rpc error mocked_rpc.side_effect = OSError main_loop.restart('10.0.0.1') assert mocked_rpc.call_count == 2 assert mocked_rpc.call_args == call('10.0.0.1', main_loop.env) # test with a mocked rpc interface rpc_intf = DummyRpcInterface() mocked_rpc.side_effect = None mocked_rpc.return_value = rpc_intf mocked_supervisor = mocker.patch.object(rpc_intf.supervisor, 'restart') main_loop.restart('10.0.0.1') assert mocked_rpc.call_count == 3 assert mocked_rpc.call_args == call('10.0.0.1', main_loop.env) assert mocked_supervisor.call_count == 1 assert mocked_supervisor.call_args == call() def test_shutdown(mocker, mocked_rpc, main_loop): """ Test the protocol to shutdown a remote Supervisor. """ mocker.patch('supvisors.mainloop.stderr') # test rpc error mocked_rpc.side_effect = RPCError(12) main_loop.shutdown('10.0.0.1') assert mocked_rpc.call_count == 2 assert mocked_rpc.call_args == call('10.0.0.1', main_loop.env) # test with a mocked rpc interface rpc_intf = DummyRpcInterface() mocked_rpc.side_effect = None mocked_rpc.return_value = rpc_intf mocked_shutdown = mocker.patch.object(rpc_intf.supervisor, 'shutdown') main_loop.shutdown('10.0.0.1') assert mocked_rpc.call_count == 3 assert mocked_rpc.call_args == call('10.0.0.1', main_loop.env) assert mocked_shutdown.call_count == 1 assert mocked_shutdown.call_args == call() def test_restart_all(mocker, mocked_rpc, main_loop): """ Test the protocol to restart Supvisors. """ mocker.patch('supvisors.mainloop.stderr') # test rpc error mocked_rpc.side_effect = OSError main_loop.restart_all('10.0.0.1') assert mocked_rpc.call_count == 2 assert mocked_rpc.call_args == call('10.0.0.1', main_loop.env) # test with a mocked rpc interface rpc_intf = DummyRpcInterface() mocked_rpc.side_effect = None mocked_rpc.return_value = rpc_intf mocked_supervisor = mocker.patch.object(rpc_intf.supvisors, 'restart') main_loop.restart_all('10.0.0.1') assert mocked_rpc.call_count == 3 assert mocked_rpc.call_args == call('10.0.0.1', main_loop.env) assert mocked_supervisor.call_count == 1 assert mocked_supervisor.call_args == call() def test_shutdown_all(mocker, mocked_rpc, main_loop): """ Test the protocol to shutdown Supvisors. """ mocker.patch('supvisors.mainloop.stderr') # test rpc error mocked_rpc.side_effect = RPCError(12) main_loop.shutdown_all('10.0.0.1') assert mocked_rpc.call_count == 2 assert mocked_rpc.call_args == call('10.0.0.1', main_loop.env) # test with a mocked rpc interface rpc_intf = DummyRpcInterface() mocked_rpc.side_effect = None mocked_rpc.return_value = rpc_intf mocked_shutdown = mocker.patch.object(rpc_intf.supvisors, 'shutdown') main_loop.shutdown_all('10.0.0.1') assert mocked_rpc.call_count == 3 assert mocked_rpc.call_args == call('10.0.0.1', main_loop.env) assert mocked_shutdown.call_count == 1 assert mocked_shutdown.call_args == call() def test_comm_event(mocker, mocked_rpc, main_loop): """ Test the protocol to send a comm event to the local Supervisor. """ mocker.patch('supvisors.mainloop.stderr') # test rpc error mocker.patch.object(main_loop.proxy.supervisor, 'sendRemoteCommEvent', side_effect=RPCError(100)) main_loop.send_remote_comm_event('event type', 'event data') # test with a mocked rpc interface mocked_supervisor = mocker.patch.object(main_loop.proxy.supervisor, 'sendRemoteCommEvent') main_loop.send_remote_comm_event('event type', 'event data') assert mocked_supervisor.call_args_list == [call('event type', 'event data')] def check_call(main_loop, mocked_loop, method_name, request, args): """ Perform a main loop request and check what has been called. """ # send request main_loop.send_request(request.value, args) # test mocked main loop for key, mocked in mocked_loop.items(): if key == method_name: assert mocked.call_count == 1 assert mocked.call_args == call(*args) mocked.reset_mock() else: assert not mocked.called def test_send_request(mocker, main_loop): """ Test the execution of a deferred Supervisor request. """ # patch main loop subscriber mocked_loop = mocker.patch.multiple(main_loop, check_node=DEFAULT, start_process=DEFAULT, stop_process=DEFAULT, restart=DEFAULT, shutdown=DEFAULT, restart_all=DEFAULT, shutdown_all=DEFAULT) # test check address check_call(main_loop, mocked_loop, 'check_node', DeferredRequestHeaders.CHECK_NODE, ('10.0.0.2',)) # test start process check_call(main_loop, mocked_loop, 'start_process', DeferredRequestHeaders.START_PROCESS, ('10.0.0.2', 'dummy_process', 'extra args')) # test stop process check_call(main_loop, mocked_loop, 'stop_process', DeferredRequestHeaders.STOP_PROCESS, ('10.0.0.2', 'dummy_process')) # test restart check_call(main_loop, mocked_loop, 'restart', DeferredRequestHeaders.RESTART, ('10.0.0.2',)) # test shutdown check_call(main_loop, mocked_loop, 'shutdown', DeferredRequestHeaders.SHUTDOWN, ('10.0.0.2',)) # test restart_all check_call(main_loop, mocked_loop, 'restart_all', DeferredRequestHeaders.RESTART_ALL, ('10.0.0.2',)) # test shutdown check_call(main_loop, mocked_loop, 'shutdown_all', DeferredRequestHeaders.SHUTDOWN_ALL, ('10.0.0.2',))
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 38093, 1421, 28, 198, 2, 15069, 2177, 5979, 2013, 12509, 30301, 16219, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789...
2.588166
5,983
#!/usr/bin/env python import rospy from geometry_msgs.msg import Twist, TransformStamped from std_msgs.msg import String from enum import Enum import tf2_ros import math if __name__ == '__main__': try: mission() except rospy.ROSInterruptException: pass
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 11748, 686, 2777, 88, 198, 6738, 22939, 62, 907, 14542, 13, 19662, 1330, 44088, 11, 26981, 1273, 13322, 198, 6738, 14367, 62, 907, 14542, 13, 19662, 1330, 10903, 198, 6738, 33829, 1330, ...
2.663462
104
#!/usr/bin/python # Copyright 2021 Northern.tech AS # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # 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 common import ( init_users, init_users_f, init_users_mt, init_users_mt_f, cli, api_client_mgmt, mongo, make_auth, ) import bravado import pytest import tenantadm
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 15069, 33448, 8342, 13, 13670, 7054, 198, 2, 198, 2, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 220, 220, 220, 345, 743...
2.937282
287
import os chrom_bins = {} with open("GSE88952_Sc_Su.32000.bed") as in_file: for line in in_file: line = line.strip().split() chrom_bins[line[3]] = "{}\t{}\t{}".format(line[0], line[1], line[2]) in_file.close() if not os.path.isfile("ctrl_32kb.bed"): with open("ctrl_32kb.bed", "w") as out_file: with open("ctrl_32kb_matrix.txt") as in_file: for line in in_file: line = line.strip().split() bin1 = line[0] chrom_string1 = chrom_bins[bin1] bin2 = line[1] chrom_string2 = chrom_bins[bin2] if float(line[3]) != 0: out_file.write("\t".join((chrom_string1, chrom_string2, line[3]))) out_file.write("\n") in_file.close() out_file.close() if not os.path.isfile("galactose_32kb.bed"): with open("galactose_32kb.bed", "w") as out_file: with open("galactose_32kb_matrix.txt") as in_file: for line in in_file: line = line.strip().split() bin1 = line[0] chrom_string1 = chrom_bins[bin1] bin2 = line[1] chrom_string2 = chrom_bins[bin2] if float(line[3]) != 0: out_file.write("\t".join((chrom_string1, chrom_string2, line[3]))) out_file.write("\n") in_file.close() out_file.close()
[ 11748, 28686, 198, 198, 28663, 62, 65, 1040, 796, 23884, 198, 198, 4480, 1280, 7203, 38, 5188, 3459, 49234, 62, 3351, 62, 5606, 13, 2624, 830, 13, 3077, 4943, 355, 287, 62, 7753, 25, 198, 197, 1640, 1627, 287, 287, 62, 7753, 25, 1...
2.102703
555
# Author: Xinshuo Weng # email: xinshuo.weng@gmail.com import matplotlib.pyplot as plt, numpy as np # import seaborn as sns # from pandas import DataFrame # from sklearn.neighbors import NearestNeighbors from terminaltables import AsciiTable from collections import Counter from .private import save_vis_close_helper, get_fig_ax_helper from xinshuo_miscellaneous import isdict, islogical, is_path_exists, isscalar, islist, is_path_exists_or_creatable, CHECK_EQ_LIST_UNORDERED, isnparray, isinteger, isstring, scalarlist2strlist, islistoflist, iscolorimage_dimension, isgrayimage_dimension, istuple from xinshuo_math import calculate_truncated_mse color_set = ['r', 'b', 'g', 'c', 'm', 'y', 'k', 'w', 'lime', 'cyan', 'aqua'] linestyle_set = ['-', '--', '-.', ':', None, ' ', 'solid', 'dashed'] dpi = 80 def visualize_ced(normed_mean_error_dict, error_threshold, normalized=True, truncated_list=None, display2terminal=True, display_list=None, title='2D PCK curve', debug=True, vis=False, pck_savepath=None, table_savepath=None, closefig=True): ''' visualize the cumulative error distribution curve (alse called NME curve or pck curve) all parameters are represented by percentage parameter: normed_mean_error_dict: a dictionary whose keys are the method name and values are (N, ) numpy array to represent error in evaluation error_threshold: threshold to display in x axis return: AUC: area under the curve MSE: mean square error ''' if debug: assert isdict(normed_mean_error_dict), 'the input normalized mean error dictionary is not correct' assert islogical(normalized), 'the normalization flag should be logical' if normalized: assert error_threshold > 0 and error_threshold < 100, 'threshold percentage is not well set' if save: assert is_path_exists_or_creatable(pck_savepath), 'please provide a valid path to save the pck results' assert is_path_exists_or_creatable(table_savepath), 'please provide a valid path to save the table results' assert isstring(title), 'title is not correct' if truncated_list is not None: assert islistofscalar(truncated_list), 'the input truncated list is not correct' if display_list is not None: assert islist(display_list) and len(display_list) == len(normed_mean_error_dict), 'the input display list is not correct' assert CHECK_EQ_LIST_UNORDERED(display_list, normed_mean_error_dict.keys(), debug=debug), 'the input display list does not match the error dictionary key list' else: display_list = normed_mean_error_dict.keys() # set display parameters width, height = 1000, 800 legend_fontsize = 10 scale_distance = 48.8 line_index, color_index = 0, 0 figsize = width / float(dpi), height / float(dpi) fig = plt.figure(figsize=figsize) # set figure handle num_bins = 1000 if normalized: maximum_x = 1 scale = num_bins / 100 else: maximum_x = error_threshold + 1 scale = num_bins / maximum_x x_axis = np.linspace(0, maximum_x, num_bins) # error axis, percentage of normalization factor y_axis = np.zeros(num_bins) interval_y = 10 interval_x = 1 plt.xlim(0, error_threshold) plt.ylim(0, 100) plt.yticks(np.arange(0, 100 + interval_y, interval_y)) plt.xticks(np.arange(0, error_threshold + interval_x, interval_x)) plt.grid() plt.title(title, fontsize=20) if normalized: plt.xlabel('Normalized error euclidean distance (%)', fontsize=16) else: plt.xlabel('Absolute error euclidean distance', fontsize=16) # calculate metrics for each method num_methods = len(normed_mean_error_dict) num_images = len(normed_mean_error_dict.values()[0]) metrics_dict = dict() metrics_table = list() table_title = ['Method Name / Metrics', 'AUC', 'MSE'] append2title = False assert num_images > 0, 'number of error array should be larger than 0' for ordered_index in range(num_methods): method_name = display_list[ordered_index] normed_mean_error = normed_mean_error_dict[method_name] if debug: assert isnparray(normed_mean_error) and normed_mean_error.ndim == 1, 'shape of error distance is not good' assert len(normed_mean_error) == num_images, 'number of testing images should be equal for all methods' assert len(linestyle_set) * len(color_set) >= len(normed_mean_error_dict) color_tmp = color_set[color_index] line_tmp = linestyle_set[line_index] for i in range(num_bins): y_axis[i] = float((normed_mean_error < x_axis[i]).sum()) / num_images # percentage of error # calculate area under the curve and mean square error entry = dict() entry['AUC'] = np.sum(y_axis[:error_threshold * scale]) / (error_threshold * scale) # bigger, better entry['MSE'] = np.mean(normed_mean_error) # smaller, better metrics_table_tmp = [str(method_name), '%.2f' % (entry['AUC']), '%.1f' % (entry['MSE'])] if truncated_list is not None: tmse_dict = calculate_truncated_mse(normed_mean_error.tolist(), truncated_list, debug=debug) for threshold in truncated_list: entry['AUC/%s'%threshold] = np.sum(y_axis[:error_threshold * scale]) / (error_threshold * scale) # bigger, better entry['MSE/%s'%threshold] = tmse_dict[threshold]['T-MSE'] entry['percentage/%s'%threshold] = tmse_dict[threshold]['percentage'] if not append2title: table_title.append('AUC/%s'%threshold) table_title.append('MSE/%s'%threshold) table_title.append('pct/%s'%threshold) metrics_table_tmp.append('%.2f' % (entry['AUC/%s'%threshold])) metrics_table_tmp.append('%.1f' % (entry['MSE/%s'%threshold])) metrics_table_tmp.append('%.1f' % (100 * entry['percentage/%s'%threshold]) + '%') # print metrics_table_tmp metrics_table.append(metrics_table_tmp) append2title = True metrics_dict[method_name] = entry # draw label = '%s, AUC: %.2f, MSE: %.1f (%.0f um)' % (method_name, entry['AUC'], entry['MSE'], entry['MSE'] * scale_distance) if normalized: plt.plot(x_axis*100, y_axis*100, color=color_tmp, linestyle=line_tmp, label=label, lw=3) else: plt.plot(x_axis, y_axis*100, color=color_tmp, linestyle=line_tmp, label=label, lw=3) plt.legend(loc=4, fontsize=legend_fontsize) color_index += 1 if color_index / len(color_set) == 1: line_index += 1 color_index = color_index % len(color_set) # plt.grid() plt.ylabel('{} Test Images (%)'.format(num_images), fontsize=16) save_vis_close_helper(fig=fig, ax=None, vis=vis, transparent=False, save_path=pck_savepath, debug=debug, closefig=closefig) # reorder the table order_index_list = [display_list.index(method_name_tmp) for method_name_tmp in normed_mean_error_dict.keys()] order_index_list = [0] + [order_index_tmp + 1 for order_index_tmp in order_index_list] # print table to terminal metrics_table = [table_title] + metrics_table # metrics_table = list_reorder([table_title] + metrics_table, order_index_list, debug=debug) table = AsciiTable(metrics_table) if display2terminal: print('\nprint detailed metrics') print(table.table) # save table to file if table_savepath is not None: table_file = open(table_savepath, 'w') table_file.write(table.table) table_file.close() if display2terminal: print('\nsave detailed metrics to %s' % table_savepath) return metrics_dict, metrics_table def visualize_nearest_neighbor(featuremap_dict, num_neighbor=5, top_number=5, vis=True, save_csv=False, csv_save_path=None, save_vis=False, save_img=False, save_thumb_name='nearest_neighbor.png', img_src_folder=None, ext_filter='.jpg', nn_save_folder=None, debug=True): ''' visualize nearest neighbor for featuremap from images parameter: featuremap_dict: a dictionary contains image path as key, and featuremap as value, the featuremap needs to be numpy array with any shape. No flatten needed num_neighbor: number of neighbor to visualize, the first nearest is itself top_number: number of top to visualize, since there might be tons of featuremap (length of dictionary), we choose the top ten with lowest distance with their nearest neighbor csv_save_path: path to save .csv file which contains indices and distance array for all elements nn_save_folder: save the nearest neighbor images for top featuremap return: all_sorted_nearest_id: a 2d matrix, each row is a feature followed by its nearest neighbor in whole feature dataset, the column is sorted by the distance of all nearest neighbor each row selected_nearest_id: only top number of sorted nearest id ''' print('processing feature map to nearest neightbor.......') if debug: assert isdict(featuremap_dict), 'featuremap should be dictionary' assert all(isnparray(featuremap_tmp) for featuremap_tmp in featuremap_dict.values()), 'value of dictionary should be numpy array' assert isinteger(num_neighbor) and num_neighbor > 1, 'number of neighborhodd is an integer larger than 1' if save_csv and csv_save_path is not None: assert is_path_exists_or_creatable(csv_save_path), 'path to save .csv file is not correct' if save_vis or save_img: if nn_save_folder is not None: # save image directly assert isstring(ext_filter), 'extension filter is not correct' assert is_path_exists(img_src_folder), 'source folder for image is not correct' assert all(isstring(path_tmp) for path_tmp in featuremap_dict.keys()) # key should be the path for the image assert is_path_exists_or_creatable(nn_save_folder), 'folder to save top visualized images is not correct' assert isstring(save_thumb_name), 'name of thumbnail is not correct' if ext_filter.find('.') == -1: ext_filter = '.%s' % ext_filter # flatten the feature map nn_feature_dict = dict() for key, featuremap_tmp in featuremap_dict.items(): nn_feature_dict[key] = featuremap_tmp.flatten() num_features = len(nn_feature_dict) # nearest neighbor featuremap = np.array(nn_feature_dict.values()) nearbrs = NearestNeighbors(n_neighbors=num_neighbor, algorithm='ball_tree').fit(featuremap) distances, indices = nearbrs.kneighbors(featuremap) if debug: assert featuremap.shape[0] == num_features, 'shape of feature map is not correct' assert indices.shape == (num_features, num_neighbor), 'shape of indices is not correct' assert distances.shape == (num_features, num_neighbor), 'shape of indices is not correct' # convert the nearest indices for all featuremap to the key accordingly id_list = nn_feature_dict.keys() max_length = len(max(id_list, key=len)) # find the maximum length of string in the key nearest_id = np.chararray(indices.shape, itemsize=max_length+1) for x in range(nearest_id.shape[0]): for y in range(nearest_id.shape[1]): nearest_id[x, y] = id_list[indices[x, y]] if debug: assert list(nearest_id[:, 0]) == id_list, 'nearest neighbor has problem' # sort the feature based on distance print('sorting the feature based on distance') featuremap_distance = np.sum(distances, axis=1) if debug: assert featuremap_distance.shape == (num_features, ), 'distance is not correct' sorted_indices = np.argsort(featuremap_distance) all_sorted_nearest_id = nearest_id[sorted_indices, :] # save to the csv file if save_csv and csv_save_path is not None: print('Saving nearest neighbor result as .csv to path: %s' % csv_save_path) with open(csv_save_path, 'w+') as file: np.savetxt(file, distances, delimiter=',', fmt='%f') np.savetxt(file, all_sorted_nearest_id, delimiter=',', fmt='%s') file.close() # choose the best to visualize selected_sorted_indices = sorted_indices[0:top_number] if debug: for i in range(num_features-1): assert featuremap_distance[sorted_indices[i]] < featuremap_distance[sorted_indices[i+1]], 'feature map is not well sorted based on distance' selected_nearest_id = nearest_id[selected_sorted_indices, :] if save_vis: fig, axarray = plt.subplots(top_number, num_neighbor) for index in range(top_number): for nearest_index in range(num_neighbor): img_path = os.path.join(img_src_folder, '%s%s'%(selected_nearest_id[index, nearest_index], ext_filter)) if debug: print('loading image from %s'%img_path) img = imread(img_path) if isgrayimage_dimension(img): axarray[index, nearest_index].imshow(img, cmap='gray') elif iscolorimage_dimension(img): axarray[index, nearest_index].imshow(img) else: assert False, 'unknown error' axarray[index, nearest_index].axis('off') save_thumb = os.path.join(nn_save_folder, save_thumb_name) fig.savefig(save_thumb) if vis: plt.show() plt.close(fig) # save top visualization to the folder if save_img and nn_save_folder is not None: for top_index in range(top_number): file_list = selected_nearest_id[top_index] save_subfolder = os.path.join(nn_save_folder, file_list[0]) mkdir_if_missing(save_subfolder) for file_tmp in file_list: file_src = os.path.join(img_src_folder, '%s%s'%(file_tmp, ext_filter)) save_path = os.path.join(save_subfolder, '%s%s'%(file_tmp, ext_filter)) if debug: print('saving %s to %s' % (file_src, save_path)) shutil.copyfile(file_src, save_path) return all_sorted_nearest_id, selected_nearest_id def visualize_distribution(data, bin_size=None, vis=False, save_path=None, debug=True, closefig=True): ''' visualize the histogram of a data, which can be a dictionary or list or numpy array or tuple or a list of list ''' if debug: assert istuple(data) or isdict(data) or islist(data) or isnparray(data), 'input data is not correct' # convert data type if istuple(data): data = list(data) elif isdict(data): data = data.values() elif isnparray(data): data = data.tolist() num_bins = 1000.0 fig, ax = get_fig_ax_helper(fig=None, ax=None) # calculate bin size if bin_size is None: if islistoflist(data): max_value = np.max(np.max(data)) min_value = np.min(np.min(data)) else: max_value = np.max(data) min_value = np.min(data) bin_size = (max_value - min_value) / num_bins else: try: bin_size = float(bin_size) except TypeError: print('size of bin should be an float value') # plot if islistoflist(data): max_value = np.max(np.max(data)) min_value = np.min(np.min(data)) bins = np.arange(min_value - bin_size, max_value + bin_size, bin_size) # fixed bin size plt.xlim([min_value - bin_size, max_value + bin_size]) for data_list_tmp in data: if debug: assert islist(data_list_tmp), 'the nested list is not correct!' # plt.hist(data_list_tmp, bins=bins, alpha=0.3) sns.distplot(data_list_tmp, bins=bins, kde=False) # sns.distplot(data_list_tmp, bins=bins, kde=False) else: bins = np.arange(min(data) - 10 * bin_size, max(data) + 10 * bin_size, bin_size) # fixed bin size plt.xlim([min(data) - bin_size, max(data) + bin_size]) plt.hist(data, bins=bins, alpha=0.5) plt.title('distribution of data') plt.xlabel('data (bin size = %f)' % bin_size) plt.ylabel('count') return save_vis_close_helper(fig=fig, ax=ax, vis=vis, save_path=save_path, debug=debug, closefig=closefig) def visualize_bar(data, bin_size=2.0, title='Bar Graph of Key-Value Pair', xlabel='index', ylabel='count', vis=True, save_path=None, debug=True, closefig=True): ''' visualize the bar graph of a data, which can be a dictionary or list of dictionary different from function of visualize_bar_graph, this function does not depend on panda and dataframe, it's simpler but with less functionality also the key of this function takes continuous scalar variable ''' if debug: assert isstring(title) and isstring(xlabel) and isstring(ylabel), 'title/xlabel/ylabel is not correct' assert isdict(data) or islist(data), 'input data is not correct' assert isscalar(bin_size), 'the bin size is not a floating number' if isdict(data): index_list = data.keys() if debug: assert islistofscalar(index_list), 'the input dictionary does not contain a scalar key' frequencies = data.values() else: index_list = range(len(data)) frequencies = data index_str_list = scalarlist2strlist(index_list, debug=debug) index_list = np.array(index_list) fig, ax = get_fig_ax_helper(fig=None, ax=None) # ax.set_xticks(index_list) # ax.set_xticklabels(index_str_list) plt.bar(index_list, frequencies, bin_size, color='r', alpha=0.5) plt.title(title, fontsize=20) plt.xlabel(xlabel) plt.ylabel(ylabel) return save_vis_close_helper(fig=fig, ax=ax, vis=vis, save_path=save_path, debug=debug, transparent=False, closefig=closefig) def visualize_bar_graph(data, title='Bar Graph of Key-Value Pair', xlabel='pixel error', ylabel='keypoint index', label=False, label_list=None, vis=True, save_path=None, debug=True, closefig=True): ''' visualize the bar graph of a data, which can be a dictionary or list of dictionary inside each dictionary, the keys (string) should be the same which is the y label, the values should be scalar ''' if debug: assert isstring(title) and isstring(xlabel) and isstring(ylabel), 'title/xlabel/ylabel is not correct' assert isdict(data) or islistofdict(data), 'input data is not correct' if isdict(data): assert all(isstring(key_tmp) for key_tmp in data.keys()), 'the keys are not all strings' assert all(isscalar(value_tmp) for value_tmp in data.values()), 'the keys are not all strings' else: assert len(data) <= len(color_set), 'number of data set is larger than number of color to use' keys = sorted(data[0].keys()) for dict_tmp in data: if not (sorted(dict_tmp.keys()) == keys): print(dict_tmp.keys()) print(keys) assert False, 'the keys are not equal across different input set' assert all(isstring(key_tmp) for key_tmp in dict_tmp.keys()), 'the keys are not all strings' assert all(isscalar(value_tmp) for value_tmp in dict_tmp.values()), 'the values are not all scalars' # convert dictionary to DataFrame data_new = dict() if isdict(data): key_list = data.keys() sorted_index = sorted(range(len(key_list)), key=lambda k: key_list[k]) data_new['names'] = (np.asarray(key_list)[sorted_index]).tolist() data_new['values'] = (np.asarray(data.values())[sorted_index]).tolist() else: key_list = data[0].keys() sorted_index = sorted(range(len(key_list)), key=lambda k: key_list[k]) data_new['names'] = (np.asarray(key_list)[sorted_index]).tolist() num_sets = len(data) for set_index in range(num_sets): data_new['value_%03d'%set_index] = (np.asarray(data[set_index].values())[sorted_index]).tolist() dataframe = DataFrame(data_new) # plot width = 2000 height = 2000 alpha = 0.5 figsize = width / float(dpi), height / float(dpi) fig = plt.figure(figsize=figsize) sns.set(style='whitegrid') # fig, ax = get_fig_ax_helper(fig=None, ax=None) if isdict(data): g = sns.barplot(x='values', y='names', data=dataframe, label='data', color='b') plt.legend(ncol=1, loc='lower right', frameon=True, fontsize=5) else: num_sets = len(data) for set_index in range(num_sets): if set_index == 0: sns.set_color_codes('pastel') else: sns.set_color_codes('muted') if label: sns.barplot(x='value_%03d'%set_index, y='names', data=dataframe, label=label_list[set_index], color=color_set[set_index], alpha=alpha) else: sns.barplot(x='value_%03d'%set_index, y='names', data=dataframe, color=solor_set[set_index], alpha=alpha) plt.legend(ncol=len(data), loc='lower right', frameon=True, fontsize=5) sns.despine(left=True, bottom=True) plt.title(title, fontsize=20) plt.xlim([0, 50]) plt.xlabel(xlabel) plt.ylabel(ylabel) num_yticks = len(data_new['names']) adaptive_fontsize = -0.0555556 * num_yticks + 15.111 plt.yticks(fontsize=adaptive_fontsize) return save_vis_close_helper(fig=fig, vis=vis, save_path=save_path, debug=debug, closefig=closefig)
[ 2, 6434, 25, 1395, 1040, 13415, 78, 370, 1516, 198, 2, 3053, 25, 2124, 1040, 13415, 78, 13, 86, 1516, 31, 14816, 13, 785, 198, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 11, 299, 32152, 355, 45941, 198, 2, 1330,...
2.359845
9,304
from django.apps import AppConfig
[ 6738, 42625, 14208, 13, 18211, 1330, 2034, 16934, 628 ]
3.888889
9
"""Vary the rhoref parameter to find a sane value. Copyright 2019 Simulation Lab University of Freiburg Author: Lukas Elflein <elfleinl@cs.uni-freiburg.de> """ from __future__ import print_function import os import shutil #import multiprocessing #import sys import random from loop_cost_functions import calc_cost_function from smamp.tools import cd from smamp.tools import check_existence def get_tasks(path_to_subdir): """Vary the lnrho weighting parameter, create folder and execute.""" sweep_dir = 'lnrho_sweep' if os.path.exists(sweep_dir): # print('Removing old dir') # shutil.rmtree(sweep_dir) pass else: print('making dir') os.mkdir(sweep_dir) print('dir made.') tasks = [] skipped = 0 for sigma in [0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4]: #for lnrho in [-9, -8, -7, -6, -5, -4, -3, -2]: for lnrho in [-7, -6, -5.5, -5, -4.75, -4.5, -4.25, -4, -3.5]: output_name = os.path.join(sweep_dir, 'cost_{}_{}.h5'.format(lnrho, sigma)) if os.path.exists(output_name): # print('{} exists. Do not include in worklist.'.format(output_name)) skipped += 1 continue else: tasks += [(path_to_subdir, lnrho, sigma, output_name)] print('{} files found and skipped.'.format(skipped)) return tasks def main(): """ Execute everything.""" print('This is {}.'.format(__file__)) print('Current working dir: {}'.format(os.getcwd())) tasks = [] # Crawl the directory structure for subdir, dirs, files in sorted(os.walk('.')): # Exclude template folders from search if 'template' in subdir or 'exclude' in subdir or 'lnrho_sweep' in subdir: continue # Select the folder to calculate in if 'horton_cost_function' in subdir: print('Moving to {}'.format(subdir)) with cd(subdir): subdir_tasks = get_tasks(subdir) tasks += subdir_tasks calculate_tasks(tasks) print('Done.') if __name__ == '__main__': main()
[ 37811, 53, 560, 262, 9529, 382, 69, 11507, 284, 1064, 257, 33241, 1988, 13, 198, 15269, 13130, 41798, 3498, 198, 21009, 286, 4848, 571, 3686, 198, 13838, 25, 28102, 292, 19067, 33663, 1279, 7046, 33663, 75, 31, 6359, 13, 35657, 12, 19...
2.283664
906
from __future__ import absolute_import, unicode_literals import pytest from libweasyl import staff from libweasyl.legacy import UNIXTIME_OFFSET from weasyl import errorcode from weasyl import siteupdate from weasyl.define import sessionmaker from weasyl.test import db_utils _FORM = { u'title': u'Title', u'content': u'Content', }
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 11, 28000, 1098, 62, 17201, 874, 198, 198, 11748, 12972, 9288, 198, 198, 6738, 9195, 732, 292, 2645, 1330, 3085, 198, 6738, 9195, 732, 292, 2645, 13, 1455, 1590, 1330, 4725, 10426, 34694, ...
2.927419
124
import sys N = int(sys.stdin.readline()) dis = list(map(int, sys.stdin.readline().split())) coin = list(map(int, sys.stdin.readline().split())) use_coin = coin[0] tot = dis[0] * use_coin for i in range(1, N - 1): if coin[i] < use_coin: use_coin = coin[i] tot += dis[i] * use_coin print(tot)
[ 11748, 25064, 198, 198, 45, 796, 493, 7, 17597, 13, 19282, 259, 13, 961, 1370, 28955, 198, 6381, 796, 1351, 7, 8899, 7, 600, 11, 25064, 13, 19282, 259, 13, 961, 1370, 22446, 35312, 3419, 4008, 198, 3630, 796, 1351, 7, 8899, 7, 600...
2.223881
134
from twisted.internet import defer, reactor if __name__ == '__main__': reactor.callWhenRunning(main) reactor.run()
[ 6738, 19074, 13, 37675, 1330, 29135, 11, 21905, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 21905, 13, 13345, 2215, 28768, 7, 12417, 8, 198, 220, 220, 220, 21905, 13, 5143, 3419, 198 ]
3.02439
41
# Converts user-defined currencies using Google import webbrowser, os, selenium from selenium import webdriver driver = webdriver.Firefox() headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} currencyX = input("Original Currency: ") currencyYname = input("Output Currency: ") currencyX_value = input("Value in " + currencyX + ": ") URL = 'https://www.google.com/search?client=firefox-b-d&q=' + currencyX_value + ' ' + currencyX + ' to ' + currencyYname driver.get(URL) goal = driver.find_element_by_class_name('SwHCTb') currencyY = goal.text print('Value in ' + currencyYname + ': ' + currencyY)
[ 2, 1482, 24040, 2836, 12, 23211, 19247, 1262, 3012, 201, 198, 11748, 3992, 40259, 11, 28686, 11, 384, 11925, 1505, 201, 198, 6738, 384, 11925, 1505, 1330, 3992, 26230, 201, 198, 201, 198, 26230, 796, 3992, 26230, 13, 13543, 12792, 3419,...
2.756757
259
from stilio.crawler.dht.node import Node
[ 6738, 336, 346, 952, 13, 66, 39464, 13, 67, 4352, 13, 17440, 1330, 19081, 628 ]
2.8
15
import napari import time from napari._qt.qthreading import thread_worker import numpy as np # create a viewer window viewer = napari.Viewer() # https://napari.org/guides/stable/threading.html def update_layer(image): """ Updates the image in the layer 'result' or adds this layer. """ try: viewer.layers['result'].data = image except KeyError: viewer.add_image(image, name='result') # Start the loop worker = loop_run() worker.yielded.connect(update_layer) worker.start() # Start napari napari.run()
[ 11748, 25422, 2743, 198, 11748, 640, 198, 6738, 25422, 2743, 13557, 39568, 13, 80, 16663, 278, 1330, 4704, 62, 28816, 198, 11748, 299, 32152, 355, 45941, 198, 198, 2, 2251, 257, 19091, 4324, 198, 1177, 263, 796, 25422, 2743, 13, 7680, ...
2.707921
202
from enum import Enum from requests import Response from urllib.parse import unquote import json
[ 6738, 33829, 1330, 2039, 388, 198, 6738, 7007, 1330, 18261, 198, 6738, 2956, 297, 571, 13, 29572, 1330, 555, 22708, 198, 11748, 33918, 628 ]
4.083333
24
""" This module provides a ``CompositePKModel`` which allows for basic retrieval and saving of models with composite keys. It is limited to the above tasks, and any use of the model past this is not guaranteed to work. A model with composite PK should look something like this:: from composite_pk import composite class Lot(composite.CompositePKModel): auction = models.ForeignKey(Auction, primary_key=True) lot_number = models.IntegerField(primary_key=True) objects = composite.CompositePKManager() So it must: * subclass the ``CompositePKModel``, * have two or more fields which set the ``primary_key`` attribute to True, and * use the ``CompositePKManager`` as the initial manager. """ __version__ = "1.0.1" __author__ = "Ubuviz" from django.db import models from django.db.models.base import ModelBase
[ 37811, 198, 1212, 8265, 3769, 257, 7559, 5377, 1930, 578, 40492, 17633, 15506, 543, 3578, 329, 4096, 45069, 198, 392, 8914, 286, 4981, 351, 24185, 8251, 13, 198, 220, 198, 1026, 318, 3614, 284, 262, 2029, 8861, 11, 290, 597, 779, 286,...
2.936877
301
from math import erf, sqrt from functools import partial from ..library.multinomial import multinomial, to_multinomial def gaussian(mu, sigma, block, kernel=None): ''' Construct to create a discrete approximation of the gaussian distribution using mu and sigma (gaussian 0 1 blocka) ''' return multinomial(*multinomial(-3, 3, 64, gaussian_cdfp(float(mu), float(sigma))), offset=block, definitions=kernel.definitions)
[ 6738, 10688, 1330, 1931, 69, 11, 19862, 17034, 198, 6738, 1257, 310, 10141, 1330, 13027, 198, 198, 6738, 11485, 32016, 13, 16680, 259, 49070, 1330, 1963, 259, 49070, 11, 284, 62, 16680, 259, 49070, 198, 198, 4299, 31986, 31562, 7, 30300...
3.076923
143
import numpy as np import torch import time from scipy import optimize from scipy.stats import norm import tmac.probability_distributions as tpd import tmac.fourier as tfo def tmac_ac(red_np, green_np, optimizer='BFGS', verbose=False, truncate_freq=False): """ Implementation of the Two-channel motion artifact correction method (TMAC) This is tmac_ac because it is the additive and circular boundary version This code takes in imaging fluoresence data from two simultaneously recorded channels and attempts to remove shared motion artifacts between the two channels Args: red_np: numpy array, [time, neurons], activity independent channel green_np: numpy array, [time, neurons], activity dependent channel optimizer: string, scipy optimizer verbose: boolean, if true, outputs when inference is complete on each neuron and estimates time to finish truncate_freq: boolean, if true truncates low amplitude frequencies in Fourier domain. This should give the same results but may give sensitivity to the initial conditions Returns: a dictionary containing: all the inferred parameters of the model """ # optimization is performed using Scipy optimize, so all tensors should stay on the CPU device = 'cpu' dtype = torch.float64 red_nan = np.any(np.isnan(red_np)) red_inf = np.any(np.isinf(red_np)) green_nan = np.any(np.isnan(green_np)) green_inf = np.any(np.isinf(green_np)) if red_nan or red_inf or green_nan or green_inf: raise Exception('Input data cannot have any nan or inf') # convert data to units of fold mean and subtract mean red_np = red_np / np.mean(red_np, axis=0) - 1 green_np = green_np / np.mean(green_np, axis=0) - 1 # convert to tensors and fourier transform red = torch.tensor(red_np, device=device, dtype=dtype) green = torch.tensor(green_np, device=device, dtype=dtype) red_fft = tfo.real_fft(red) green_fft = tfo.real_fft(green) # estimate all model parameters from the data variance_r_noise_init = np.var(red_np, axis=0) variance_g_noise_init = np.var(green_np, axis=0) variance_a_init = np.var(green_np, axis=0) variance_m_init = np.var(red_np, axis=0) # initialize length scale using the autocorrelation of the data length_scale_a_init = np.zeros(red_np.shape[1]) length_scale_m_init = np.zeros(red_np.shape[1]) for n in range(green_np.shape[1]): # approximate as the standard deviation of a gaussian fit to the autocorrelation function length_scale_m_init[n] = initialize_length_scale(red_np[:, n]) length_scale_a_init[n] = initialize_length_scale(green_np[:, n]) # preallocate space for all the training variables a_trained = np.zeros(red_np.shape) m_trained = np.zeros(red_np.shape) variance_r_noise_trained = np.zeros(variance_r_noise_init.shape) variance_g_noise_trained = np.zeros(variance_g_noise_init.shape) variance_a_trained = np.zeros(variance_a_init.shape) length_scale_a_trained = np.zeros(length_scale_a_init.shape) variance_m_trained = np.zeros(variance_m_init.shape) length_scale_m_trained = np.zeros(length_scale_m_init.shape) # loop through each neuron and perform inference start = time.time() for n in range(red_np.shape[1]): # get the initial values for the hyperparameters of this neuron # All hyperparameters are positive so we fit them in log space evidence_training_variables = np.log([variance_r_noise_init[n], variance_g_noise_init[n], variance_a_init[n], length_scale_a_init[n], variance_m_init[n], length_scale_m_init[n]]) # define the evidence loss function. This function takes in and returns pytorch tensors # a wrapper function of evidence that takes in and returns numpy variables # wrapper function of for Jacobian of the evidence that takes in and returns numpy variables # optimization function with Jacobian from pytorch trained_variances = optimize.minimize(evidence_loss_fn_np, evidence_training_variables, jac=evidence_loss_jacobian_np, method=optimizer) # calculate the posterior values # The posterior is gaussian so we don't need to optimize, we find a and m in one step trained_variance_torch = torch.tensor(trained_variances.x, dtype=dtype, device=device) a, m = tpd.tmac_evidence_and_posterior(red[:, n], red_fft[:, n], trained_variance_torch[0], green[:, n], green_fft[:, n], trained_variance_torch[1], trained_variance_torch[2], trained_variance_torch[3], trained_variance_torch[4], trained_variance_torch[5], calculate_posterior=True, truncate_freq=truncate_freq) a_trained[:, n] = a.numpy() m_trained[:, n] = m.numpy() variance_r_noise_trained[n] = torch.exp(trained_variance_torch[0]).numpy() variance_g_noise_trained[n] = torch.exp(trained_variance_torch[1]).numpy() variance_a_trained[n] = torch.exp(trained_variance_torch[2]).numpy() length_scale_a_trained[n] = torch.exp(trained_variance_torch[3]).numpy() variance_m_trained[n] = torch.exp(trained_variance_torch[4]).numpy() length_scale_m_trained[n] = torch.exp(trained_variance_torch[5]).numpy() if verbose: decimals = 1e3 # print out timing elapsed = time.time() - start remaining = elapsed / (n + 1) * (red_np.shape[1] - (n + 1)) elapsed_truncated = np.round(elapsed * decimals) / decimals remaining_truncated = np.round(remaining * decimals) / decimals print(str(n + 1) + '/' + str(red_np.shape[1]) + ' neurons complete') print(str(elapsed_truncated) + 's elapsed, estimated ' + str(remaining_truncated) + 's remaining') trained_variables = {'a': a_trained, 'm': m_trained, 'variance_r_noise': variance_r_noise_trained, 'variance_g_noise': variance_g_noise_trained, 'variance_a': variance_a_trained, 'length_scale_a': length_scale_a_trained, 'variance_m': variance_m_trained, 'length_scale_m': length_scale_m_trained, } return trained_variables def initialize_length_scale(y): """ Function to fit a Gaussian to the autocorrelation of y Args: y: numpy vector Returns: Standard deviation of a Gaussian fit to the autocorrelation of y """ x = np.arange(-len(y)/2, len(y)/2) + 0.5 y_z_score = (y - np.mean(y)) / np.std(y) y_corr = np.correlate(y_z_score, y_z_score, mode='same') # fit the std of a gaussian to the correlation function p_init = np.array((np.max(y_corr), 1.0)) p_hat = optimize.leastsq(loss, p_init)[0] # return the standard deviation return p_hat[1]
[ 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 198, 11748, 640, 198, 6738, 629, 541, 88, 1330, 27183, 198, 6738, 629, 541, 88, 13, 34242, 1330, 2593, 198, 11748, 256, 20285, 13, 1676, 65, 1799, 62, 17080, 2455, 507, 355, 256, 30094...
2.383461
2,999
from arguments import get_args import numpy as np from network.models import MLP_Net from utils.utils import get_env_params import torch import os, gym """ script to watch the demo of the ESIL """ # process the inputs if __name__ == '__main__': args = get_args() # create environment env = gym.make(args.env_name) # get the environment parameters env_params = get_env_params(env) # start to create model model_path = '{}/{}/model.pt'.format(args.save_dir, args.env_name) network = MLP_Net(env_params['obs'] + env_params['goal'], env_params['action'], args.dist) network_model, obs_mean, obs_std, g_mean, g_std = torch.load(model_path, map_location='cpu') network.load_state_dict(network_model) network.eval() # start to do the testing for i in range(args.demo_length): observation = env.reset() # start to do the demo obs, g = observation['observation'], observation['desired_goal'] for t in range(env._max_episode_steps): if args.render: env.render() inputs = process_inputs(obs, g, obs_mean, obs_std, g_mean, g_std, args) with torch.no_grad(): _, pi = network(inputs) if args.dist == 'gauss': mean, std = pi input_actions = mean.detach().cpu().numpy().squeeze() else: raise NotImplementedError # put actions into the environment observation_new, reward, _, info = env.step(input_actions) obs = observation_new['observation'] print('the episode is: {}, is success: {}'.format(i, info['is_success']))
[ 6738, 7159, 1330, 651, 62, 22046, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 3127, 13, 27530, 1330, 10373, 47, 62, 7934, 198, 6738, 3384, 4487, 13, 26791, 1330, 651, 62, 24330, 62, 37266, 198, 11748, 28034, 198, 11748, 28686, 11, ...
2.314637
731
from datetime import datetime from kickbase_api.models._transforms import parse_date, parse_key_value_array_to_dict from kickbase_api.models.base_model import BaseModel from kickbase_api.models.league_user_season_stats import LeagueUserSeasonStats
[ 6738, 4818, 8079, 1330, 4818, 8079, 198, 198, 6738, 4829, 8692, 62, 15042, 13, 27530, 13557, 7645, 23914, 1330, 21136, 62, 4475, 11, 21136, 62, 2539, 62, 8367, 62, 18747, 62, 1462, 62, 11600, 198, 6738, 4829, 8692, 62, 15042, 13, 2753...
3.521127
71
""" Interfaces for FCRepoRequestFactory, FCRepoResponse and FCRepoResponseBody. """ from exceptions import NotImplementedError # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
[ 37811, 4225, 32186, 329, 10029, 6207, 78, 18453, 22810, 11, 10029, 6207, 78, 31077, 290, 10029, 6207, 78, 31077, 25842, 13, 198, 37811, 198, 198, 6738, 13269, 1330, 1892, 3546, 1154, 12061, 12331, 628, 198, 2, 1303, 1303, 1303, 1303, 13...
2.300613
163
#utf8 from __future__ import print_function, division import subprocess import os import os.path import sys import time default_tmp_mesh_filename = '/tmp/Mesh_1.med' # salome 9.x may be too new for this script, some version released in 2018 is better # salome_app = '/media/sf_OneDrive/Salome-9.8.0/salome' salome_app = '/home/qingfeng/SALOME-9.7.0/salome' gmsh_app = '/media/sf_OneDrive/gmsh-4.10.2-Linux64/bin/gmsh'
[ 2, 40477, 23, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 11, 7297, 198, 11748, 850, 14681, 198, 11748, 28686, 198, 11748, 28686, 13, 6978, 198, 11748, 25064, 198, 11748, 640, 198, 198, 12286, 62, 22065, 62, 76, 5069, 62, 3434...
2.576687
163
"""Values for controlled vocabularies from ENA. Taken from - https://ena-docs.readthedocs.io/en/latest/submit/reads/webin-cli.html """ # Constants for platform definitions. LS454 = "LS454" ILLUMINA = "ILLUMINA" PACBIO_SMRT = "PACBIO_SMRT" IONTORRENT = "ION_TORRENT" CAPILLARY = "CAPILLARY" ONT = "OXFORD_NANOPORE" BGISEQ = "BGISEQ" DNBSEQ = "DNBSEQ" #: Allowed platforms in ENA. PLATFORMS = (LS454, ILLUMINA, PACBIO_SMRT, IONTORRENT, CAPILLARY, ONT, BGISEQ, DNBSEQ) # Constants for platforms. LS454_454GS = "454 GS" LS454_454GS_240 = "454 GS 20" LS454_454GS_FLX = "454 GS FLX" LS454_454GS_FLX_PLUS = "454 GS FLX+" LS454_454GS_FLX_TITANIUM = "454 GS FLX Titanium" LS454_454GS_JUNIOR = "454 GS Junior" ILLUMINA_HISEQX_FIVE = "HiSeq X Five" ILLUMINA_HISEQX_TEN = "HiSeq X Ten" ILLUMINA_GA = "Illumina Genome Analyzer" ILLUMINA_GA2 = "Illumina Genome Analyzer II" ILLUMINA_GA2x = "Illumina Genome Analyzer IIx" ILLUMINA_HISCANQ = "Illumina HiScanSQ" ILLUMINA_HISEQ_1000 = "Illumina HiSeq 1000" ILLUMINA_HISEQ_1500 = "Illumina HiSeq 1500" ILLUMINA_HISEQ_2000 = "Illumina HiSeq 2000" ILLUMINA_HISEQ_2500 = "Illumina HiSeq 2500" ILLUMINA_HISEQ_3000 = "Illumina HiSeq 3000" ILLUMINA_HISEQ_4000 = "Illumina HiSeq 4000" ILLUMINA_ISEQ_100 = "Illumina iSeq 100" ILLUMINA_MISEQ = "Illumina MiSeq" ILLUMINA_MINISEQ = "Illumina MiniSeq" ILLUMINA_NOVASEQ_6000 = "Illumina NovaSeq 6000" ILLUMINA_NETSEQ_500 = "NextSeq 500" ILLUMINA_NETSEQ_550 = "NextSeq 550" PACBIO_RS = "PacBio RS" PACBIO_RS2 = "PacBio RS II" PACBIO_SEQEL = "Sequel" IONTORRENT_PGM = "Ion Torrent PGM" IONTORRENT_PROTON = "Ion Torrent Proton" IONTORRENT_S5 = "Ion Torrent S5" IONTORRENT_S5XL = "Ion Torrent S5 XL" ABI_AB3730XL = "AB 3730xL Genetic Analyzer" ABI_AB3730 = "AB 3730 Genetic Analyzer" ABI_AB3500XL = "AB 3500xL Genetic Analyzer" ABI_AB3500 = "AB 3500 Genetic Analyzer" ABI_AB3130XL = "AB 3130xL Genetic Analyzer" ABI_AB3130 = "AB 3130 Genetic Analyzer" ABI_AB310 = "AB 310 Genetic Analyzer" ONT_MINION = "MinION" ONT_GRIDION = "GridION" ONT_PROMETHION = "PromethION" BGI_BGISEQ500 = "BGISEQ-500" DNB_T7 = "DNBSEQ-T7" DNB_G400 = "DNBSEQ-G400" DNB_G50 = "DNBSEQ-G50" DNB_G400_FAST = "DNBSEQ-G400 FAST" UNSPECIFIED = "unspecified" #: Allowed values for instruments in ENA records. INSTRUMENTS = ( LS454_454GS, LS454_454GS_240, LS454_454GS_FLX, LS454_454GS_FLX_PLUS, LS454_454GS_FLX_TITANIUM, LS454_454GS_JUNIOR, ILLUMINA_HISEQX_FIVE, ILLUMINA_HISEQX_TEN, ILLUMINA_GA, ILLUMINA_GA2, ILLUMINA_GA2x, ILLUMINA_HISCANQ, ILLUMINA_HISEQ_1000, ILLUMINA_HISEQ_1500, ILLUMINA_HISEQ_2000, ILLUMINA_HISEQ_2500, ILLUMINA_HISEQ_3000, ILLUMINA_HISEQ_4000, ILLUMINA_ISEQ_100, ILLUMINA_MISEQ, ILLUMINA_MINISEQ, ILLUMINA_NOVASEQ_6000, ILLUMINA_NETSEQ_500, ILLUMINA_NETSEQ_550, PACBIO_RS, PACBIO_RS2, PACBIO_SEQEL, IONTORRENT_PGM, IONTORRENT_PROTON, IONTORRENT_S5, IONTORRENT_S5XL, ABI_AB3730XL, ABI_AB3730, ABI_AB3500XL, ABI_AB3500, ABI_AB3130XL, ABI_AB3130, ABI_AB310, ONT_MINION, ONT_GRIDION, ONT_PROMETHION, BGI_BGISEQ500, DNB_T7, DNB_G400, DNB_G50, DNB_G400_FAST, UNSPECIFIED, ) # Constants for library selection. LIBSEL_RANDOM = "RANDOM" LIBSEL_PCR = "PCR" LIBSEL_RANDOM_PCR = "RANDOM PCR" LIBSEL_RT_PCR = "RT-PCR" LIBSEL_HMPR = "HMPR" LIBSEL_MF = "MF" LIBSEL_REPEAT_FRACTIONATION = "repeat fractionation" LIBSEL_SIZE_FRACTIONATION = "size fractionation" LIBSEL_MSLL = "MSLL" LIBSEL_CDNA = "cDNA" LIBSEL_CDNA_RANDOM_PRIMING = "cDNA_randomPriming" LIBSEL_CDNA_OLIGO_DT = "cDNA_oligo_dT" LIBSEL_POLYA = "PolyA" LIBSEL_OLIGO_DT = "Oligo-dT" LIBSEL_INVERSE_RNA = "Inverse rRNA" LIBSEL_INVERSE_RNA_SELECTION = "Inverse rRNA selection" LIBSEL_CHIP = "ChIP" LIBSEL_CHIP_SEQ = "ChIP-Seq" LIBSEL_MNASE = "MNase" LIBSEL_DNASE = "DNase" LIBSEL_HYBRID_SELECTION = "Hybrid Selection" LIBSEL_REDUCED_REPRESENTATION = "Reduced Representation" LIBSEL_RESTRICTION_DIGEST = "Restriction Digest" LIBSEL_5HETYHLCYTITINE_ANTIBODY = "5-methylcytidine antibody" LIBSEL_MBD2_PROTEIN_METHYL_CPG_BINDING_DOMAIN = "MBD2 protein methyl-CpG binding domain" LIBSEL_CAGE = "CAGE" LIBSEL_RACE = "RACE" LIBSEL_MDA = "MDA" LIBSEL_PADLOCK_PROBES_CPATURE_METHOD = "padlock probes capture method" LIBSEL_OTHER = "other" LIBSEL_UNSPECIFIED = "unspecified" #: Allowed library selection strategies for ENA records. LIBRARY_SELECTIONS = ( LIBSEL_RANDOM, LIBSEL_PCR, LIBSEL_RANDOM_PCR, LIBSEL_RT_PCR, LIBSEL_HMPR, LIBSEL_MF, LIBSEL_REPEAT_FRACTIONATION, LIBSEL_SIZE_FRACTIONATION, LIBSEL_MSLL, LIBSEL_CDNA, LIBSEL_CDNA_RANDOM_PRIMING, LIBSEL_CDNA_OLIGO_DT, LIBSEL_POLYA, LIBSEL_OLIGO_DT, LIBSEL_INVERSE_RNA, LIBSEL_INVERSE_RNA_SELECTION, LIBSEL_CHIP, LIBSEL_CHIP_SEQ, LIBSEL_MNASE, LIBSEL_DNASE, LIBSEL_HYBRID_SELECTION, LIBSEL_REDUCED_REPRESENTATION, LIBSEL_RESTRICTION_DIGEST, LIBSEL_5HETYHLCYTITINE_ANTIBODY, LIBSEL_MBD2_PROTEIN_METHYL_CPG_BINDING_DOMAIN, LIBSEL_CAGE, LIBSEL_RACE, LIBSEL_MDA, LIBSEL_PADLOCK_PROBES_CPATURE_METHOD, LIBSEL_OTHER, LIBSEL_UNSPECIFIED, ) # Constants for library sources. LIBSRC_GENOMIC = "GENOMIC" LIBSRC_GENOMIC_SC = "GENOMIC SINGLE CELL" LIBSRC_TRANSCRIPTOMIC = "TRANSCRIPTOMIC" LIBSRC_TRANSCRIPTOMIC_SC = "TRANSCRIPTOMIC SINGLE CELL" LIBSRC_METAGENOMIC = "METAGENOMIC" LIBSRC_METATRANSCRIPTOMIC = "METATRANSCRIPTOMIC" LIBSRC_SYNTHETIC = "SYNTHETIC" LIBSRC_VIRAL_RNA = "VIRAL RNA" LIBSRC_OTHER = "OTHER" #: Allowed library sources for ENA records. LIBRARY_SOURCES = ( LIBSRC_GENOMIC, LIBSRC_GENOMIC_SC, LIBSRC_TRANSCRIPTOMIC, LIBSRC_TRANSCRIPTOMIC_SC, LIBSRC_METAGENOMIC, LIBSRC_METATRANSCRIPTOMIC, LIBSRC_SYNTHETIC, LIBSRC_VIRAL_RNA, LIBSRC_OTHER, ) # Constants for library strategies. LIBSTR_WGS = "WGS" LIBSTR_WGA = "WGA" LIBSTR_WXS = "WXS" LIBSTR_RNA_SEQ = "RNA-Seq" LIBSTR_SSRNA_SEQ = "ssRNA-seq" LIBSTR_MIRNA_SEQ = "miRNA-Seq" LIBSTR_NCRNA_SEQ = "ncRNA-Seq" LIBSTR_FL_CDNA = "FL-cDNA" LIBSTR_EST = "EST" LIBSTR_HIC = "Hi-C" LIBSTR_ATAC_SEQ = "ATAC-seq" LIBSTR_WCS = "WCS" LIBSTR_RAD_SEQ = "RAD-Seq" LIBSTR_CLONE = "CLONE" LIBSTR_POOLCLONE = "POOLCLONE" LIBSTR_AMPLICON = "AMPLICON" LIBSTR_CLONEEND = "CLONEEND" LIBSTR_FINISHING = "FINISHING" LIBSTR_CHIP_SEQ = "ChIP-Seq" LIBSTR_MNASE_EQ = "MNase-Seq" LIBSTR_DNASE_HYPERSENSITIVITY = "DNase-Hypersensitivity" LIBSTR_BISULFITE_SEQ = "Bisulfite-Seq" LIBSTR_CTS = "CTS" LIBSTR_MRE_SEQ = "MRE-Seq" LIBSTR_MEDIP_SEQ = "MeDIP-Seq" LIBSTR_MBD_SEQ = "MBD-Seq" LIBSTR_TN_SEQ = "Tn-Seq" LIBSTR_VALIDATION = "VALIDATION" LIBSTR_FAIRE_SEQ = "FAIRE-seq" LIBSTR_SELEX = "SELEX" LIBSTR_RIP_SEQ = "RIP-Seq" LIBSTR_CHIA_PET = "ChIA-PET" LIBSTR_SYNTHEETIC_LONG_READ = "Synthetic-Long-Read" LIBSTR_TARGETED_CAPTURE = "Targeted-Capture" LIBSTR_TETHERED_CHROMATIN_CONFORMATION_CAPTURE = "Tethered Chromatin Conformation Capture" LIBSTR_OTHER = "OTHER" #: Allowed library strategies for ENA records. LIBRARY_STRATEGIES = ( LIBSTR_WGS, LIBSTR_WGA, LIBSTR_WXS, LIBSTR_RNA_SEQ, LIBSTR_SSRNA_SEQ, LIBSTR_MIRNA_SEQ, LIBSTR_NCRNA_SEQ, LIBSTR_FL_CDNA, LIBSTR_EST, LIBSTR_HIC, LIBSTR_ATAC_SEQ, LIBSTR_WCS, LIBSTR_RAD_SEQ, LIBSTR_CLONE, LIBSTR_POOLCLONE, LIBSTR_AMPLICON, LIBSTR_CLONEEND, LIBSTR_FINISHING, LIBSTR_CHIP_SEQ, LIBSTR_MNASE_EQ, LIBSTR_DNASE_HYPERSENSITIVITY, LIBSTR_BISULFITE_SEQ, LIBSTR_CTS, LIBSTR_MRE_SEQ, LIBSTR_MEDIP_SEQ, LIBSTR_MBD_SEQ, LIBSTR_TN_SEQ, LIBSTR_VALIDATION, LIBSTR_FAIRE_SEQ, LIBSTR_SELEX, LIBSTR_RIP_SEQ, LIBSTR_CHIA_PET, LIBSTR_SYNTHEETIC_LONG_READ, LIBSTR_TARGETED_CAPTURE, LIBSTR_TETHERED_CHROMATIN_CONFORMATION_CAPTURE, LIBSTR_OTHER, )
[ 37811, 40161, 329, 6856, 12776, 397, 934, 444, 422, 412, 4535, 13, 201, 198, 201, 198, 51, 1685, 422, 201, 198, 201, 198, 12, 3740, 1378, 8107, 12, 31628, 13, 961, 83, 704, 420, 82, 13, 952, 14, 268, 14, 42861, 14, 46002, 14, 40...
1.892816
4,301
""" Copyright 2012 Numan Sachwani <numan@7Geese.com> This file is provided to you 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_string comes form Werkzeug # http://werkzeug.pocoo.org def import_string(import_name, silent=False): """Imports an object based on a string. If *silent* is True the return value will be None if the import fails. Simplified version of the function with same name from `Werkzeug`_. :param import_name: The dotted name for the object to import. :param silent: If True, import errors are ignored and None is returned instead. :returns: The imported object. """ import_name = str(import_name) try: if '.' in import_name: module, obj = import_name.rsplit('.', 1) return getattr(__import__(module, None, None, [obj]), obj) else: return __import__(import_name) except (ImportError, AttributeError): if not silent: raise
[ 37811, 198, 15269, 2321, 399, 3778, 20678, 86, 3216, 1279, 77, 3778, 31, 22, 10082, 2771, 13, 785, 29, 198, 198, 1212, 2393, 318, 2810, 284, 345, 739, 262, 24843, 13789, 11, 198, 14815, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345...
2.931864
499
from .lemkelcp import lemkelcp
[ 6738, 764, 10671, 7750, 13155, 1330, 443, 76, 7750, 13155, 198 ]
2.818182
11
""" Settings for re-running the experiments from the paper "Layer-wise relevance propagation for explaining deep neural network decisions in MRI-based Alzheimers disease classification". Please note that you need to download the ADNI data from http://adni.loni.usc.edu/ and preprocess it using https://github.com/ANTsX/ANTs/blob/master/Scripts/antsRegistrationSyNQuick.sh Please prepare the data, such that you will get three HDF5 files, consisting of a training, a validation and a holdout (test) set. Each HDF5 file is required to have 2 datasets, namely X and y, containing the data matrix and label vector accordingly. We have included the "Data Split ADNI.ipynb" file as a guideline for data splitting. Please note that it is highly dependent on the format of your data storage and needs to be individualized as such. Furthermore you will need SPM12 https://www.fil.ion.ucl.ac.uk/spm/software/spm12/ in order to access the Neuromorphometrics atlas. Arguments: model_path: Path to the trained pytorch model parameters data_path: Path where the outputs will be stored and retrieved ADNI_DIR: Path to the root of your downloaded ADNI data train_h5: Path to the training set HDF5 file val_h5: Path to the validation set HDF5 file holdout_h5: Path to the holdout set HDF5 file binary_brain_mask: Path to the mask used for masking the images, included in the repository. nmm_mask_path: Path to the Neuromorphometrics mask. Needs to be acquired from SPM12. Typically located under ~/spm12/tpm/labels_Neuromorphometrics.nii nmm_mask_path_scaled: Path to the rescaled Neuromorphometrics mask. """ settings = { "model_path": INSERT, "data_path": INSERT, "ADNI_DIR": INSERT, "train_h5": INSERT, "val_h5": INSERT, "holdout_h5": INSERT, "binary_brain_mask": "binary_brain_mask.nii.gz", "nmm_mask_path": "~/spm12/tpm/labels_Neuromorphometrics.nii", "nmm_mask_path_scaled": "nmm_mask_rescaled.nii" }
[ 37811, 198, 26232, 329, 302, 12, 20270, 262, 10256, 422, 262, 3348, 366, 49925, 12, 3083, 198, 260, 2768, 590, 43594, 329, 11170, 2769, 17019, 3127, 5370, 198, 259, 30278, 12, 3106, 21535, 9096, 364, 4369, 17923, 1911, 198, 198, 5492, ...
2.946903
678
''' # Test the compiler ''' from ACOW import * data = ''' a1 U[1,2] !a0&G[1,3]a3 ''' print('MTL Formula:',data) # Test lex print('\nLex Test:') lexer.input(data) for tok in lexer: print(tok) # Test parser print('\nParser Test:') result = parser.parse(data) print(result)
[ 7061, 6, 198, 2, 6208, 262, 17050, 198, 7061, 6, 198, 6738, 7125, 3913, 1330, 1635, 198, 198, 7890, 796, 705, 7061, 198, 64, 16, 471, 58, 16, 11, 17, 60, 5145, 64, 15, 5, 38, 58, 16, 11, 18, 60, 64, 18, 198, 7061, 6, 198, ...
2.264463
121
import board import time import random import usb_hid from adafruit_hid.mouse import Mouse from adafruit_hid.keyboard import Keyboard mouse = Mouse(usb_hid.devices) goright=True while True: #2 parts to sequence, move mostly right, then mostly left # set up for big move #longwait=random.randint(250,350) longwait=random.randint(2,3) bigoffsetx=random.randint(-10,10) bigoffsety=random.randint(-7,7) # do 1st big move if goright: # do a right move print("moving right") mouse.move(100+bigoffsetx,bigoffsety) goright=False else: # do a left move print("moving left") mouse.move(-100+bigoffsetx,bigoffsety) goright=True # do some quick clicks and moves numberofclicks=random.randint(3,6) print("doing some clicks") for ismall in range(1,numberofclicks): #shortwait in ms (double click is usually less than 500ms) shortwait=0.001*random.randint(250,600) #print(shortwait) shortmovex=random.randint(-9,9) shortmovey=random.randint(-7,7) #move, wait, click mouse.move(shortmovex,shortmovey) time.sleep(shortwait) mouse.click(Mouse.LEFT_BUTTON) time.sleep(longwait) print("waiting for next move")
[ 11748, 3096, 198, 11748, 640, 198, 11748, 4738, 198, 11748, 38551, 62, 49675, 198, 6738, 512, 1878, 4872, 62, 49675, 13, 35888, 1330, 21839, 198, 6738, 512, 1878, 4872, 62, 49675, 13, 2539, 3526, 1330, 31973, 198, 198, 35888, 796, 21839...
2.33213
554
from django.contrib import admin from .models import Post, Comment, UserProfile # Register your models here. admin.site.register(Post) admin.site.register(Comment) admin.site.register(UserProfile, admin_class=ProfileAdmin)
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 6738, 764, 27530, 1330, 2947, 11, 18957, 11, 11787, 37046, 198, 198, 2, 17296, 534, 4981, 994, 13, 198, 28482, 13, 15654, 13, 30238, 7, 6307, 8, 198, 28482, 13, 15654, 13, 30238, ...
3.571429
63
# -*- coding: utf-8 -*- # Generated by Django 1.11.16 on 2018-11-27 14:43 from __future__ import unicode_literals import ckeditor.fields from django.conf import settings import django.contrib.postgres.fields.jsonb from django.db import migrations, models import django.db.models.deletion import django_countries.fields import jagdreisencheck.custom_fields
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 352, 13, 1157, 13, 1433, 319, 2864, 12, 1157, 12, 1983, 1478, 25, 3559, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198,...
2.983333
120
from Bio.SeqIO import parse from Bio import SeqIO from Bio.SeqRecord import SeqRecord from Bio.Seq import Seq from Bio.Alphabet import IUPAC, generic_dna from Bio import Alphabet, Entrez from Bio.SeqUtils import GC from Bio.Blast import NCBIWWW, NCBIXML from Bio import pairwise2 from Bio.pairwise2 import format_alignment from Bio import motifs __author__ = 'Maciej Michalczyk' __version__ = '09122019' # def convertFASTAtoGENBANK(self, filename): # file = open(filename + ".fasta") # record = SeqIO.read(file, "fasta") # record.seq.alphabet = generic_dna # file_genbank = open(filename + ".gbk", "w") # SeqIO.write(record, file_genbank, "genbank") # file_genbank.close() # file.close() if __name__ == '__main__': session = CurrentSession() while True: print("""////Bio Python//// 1. Load FASTA file 2. Load record info 3. Get complementary sequence 4. Transcribe sequence 5. Translate sequence 6. Get GC content 7. Fetch and load FASTA from Entrez *8. Convert FASTA to GenBank 9. Run BLAST 10. Perform pairwise aligment 11. Create motifs and weblogo 12. Save your actions made on FASTA file to txt file 13. Print sequence substrings === Current session file: {} === Type 'help' for help. Type 'quit' to exit.""".format(session.file_session)) menu_pos = input('>>').lower() if menu_pos == str(1): try: print("Type name of FASTA file to process: ") filename = input() file_handle = session.openFile(filename) print("FASTA loaded!") except Exception as e: print("No such file or directory.") elif menu_pos == str(2): try: file_handle = session.openFile(filename) session.getSequenceInfo(file_handle) session.closeFile(file_handle) except Exception as e: print("File is not loaded.") elif menu_pos == str(3): try: file_handle = session.openFile(filename) session.getComplementarySequence(file_handle) session.closeFile(file_handle) except Exception as e: print("File is not loaded.") elif menu_pos == str(4): try: file_handle = session.openFile(filename) session.transcribeSequence(file_handle) session.closeFile(file_handle) except Exception as e: print("File is not loaded.") elif menu_pos == str(5): stop = input('Stop translating at first stop codon? [y/n]').lower() try: file_handle = session.openFile(filename) session.translateSequence(file_handle, stop) session.closeFile(file_handle) except Exception as e: print("File is not loaded.") elif menu_pos == str(6): try: file_handle = session.openFile(filename) session.get_GC_Content(file_handle) session.closeFile(file_handle) except Exception as e: print("File is not loaded.") elif menu_pos == str(7): try: db = input("Type database name: ").lower() accession = input("Type accession to find: ") filename = session.fetchRecord(db, accession) file_handle = session.openFile(filename) except Exception as e: print("File is not loaded.") elif menu_pos == str(8): try: print("Type name of FASTA file to process: ") filename = input() # session.convertFASTAtoGENBANK(filename) except Exception as e: print("File is not loaded.") elif menu_pos == str(9): try: file_handle = session.openFile(filename) type = input("Type the type of BLAST: ") database = input("Type database name: ") session.runBlast(type, database) except Exception as e: print("File is not loaded.") elif menu_pos == str(10): try: print("""Choose type of aligment: 1. Global Pairwise (default parameters) 2. Local Pairwise (default parameters) 3. Global Pairwise with custom parameters""") alignment_type = input('>>') file_handle = session.openFile(filename) session.alignPairwise(file_handle, alignment_type) session.closeFile(file_handle) except Exception as e: print("File is not loaded.") elif menu_pos == str(11): try: file_handle = session.openFile(filename) session.createMotif(file_handle) session.closeFile(file_handle) except Exception as e: print("File is not loaded") elif menu_pos == str(12): session.saveActions() elif menu_pos == str(13): try: length = int(input("Length of substrings:")) iterator = session.getElems(length) print(session.sequence) i = 0 for base in iterator: print(' ' * i + base) i += 1 print(' ' * i + next(iterator)) i += 1 except StopIteration: pass except Exception as e: print("File is not loaded") elif menu_pos == 'debug': print("{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n".format(session.id, session.name, session.desc,session.sequence, session.comp_seq, session.transcribed_seq, session.translated_seq, session.gc_perc)) elif menu_pos == 'quit': break elif menu_pos == 'help': print(""" quickHELP: Indent operations in menu needs file to be opened first. Be patient while doing BLAST. If in menu something is marked with an asterisk, then it is not usable. Have fun! """) else: print("Unknown command.")
[ 6738, 16024, 13, 4653, 80, 9399, 1330, 21136, 198, 6738, 16024, 1330, 1001, 80, 9399, 198, 6738, 16024, 13, 4653, 80, 23739, 1330, 1001, 80, 23739, 198, 6738, 16024, 13, 4653, 80, 1330, 1001, 80, 198, 6738, 16024, 13, 2348, 19557, 133...
2.013643
3,225
#!/usr/bin/env python # Exploit Title: Unauthenticated SQL Injection on CMS Made Simple <= 2.2.9 # Date: 30-03-2019 # Exploit Author: Daniele Scanu @ Certimeter Group # Vendor Homepage: https://www.cmsmadesimple.org/ # Software Link: https://www.cmsmadesimple.org/downloads/cmsms/ # Version: <= 2.2.9 # Tested on: Ubuntu 18.04 LTS # CVE : CVE-2019-9053 import requests from termcolor import colored import time from termcolor import cprint import optparse import hashlib parser = optparse.OptionParser() parser.add_option('-u', '--url', action="store", dest="url", help="Base target uri (ex. http://10.10.10.100/cms)") parser.add_option('-w', '--wordlist', action="store", dest="wordlist", help="Wordlist for crack admin password") parser.add_option('-c', '--crack', action="store_true", dest="cracking", help="Crack password with wordlist", default=False) options, args = parser.parse_args() if not options.url: print "[+] Specify an url target" print "[+] Example usage (no cracking password): exploit.py -u http://target-uri" print "[+] Example usage (with cracking password): exploit.py -u http://target-uri --crack -w /path-wordlist" print "[+] Setup the variable TIME with an appropriate time, because this sql injection is a time based." exit() url_vuln = options.url + '/moduleinterface.php?mact=News,m1_,default,0' session = requests.Session() dictionary = '1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM@._-$' flag = True password = "" temp_password = "" TIME = 1 db_name = "" output = "" email = "" salt = '' wordlist = "" if options.wordlist: wordlist += options.wordlist dump_salt() dump_username() dump_email() dump_password() if options.cracking: print colored("[*] Now try to crack password") crack_password() beautify_print()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 201, 198, 2, 5905, 30711, 11851, 25, 791, 41299, 3474, 16363, 554, 29192, 319, 40773, 14446, 17427, 19841, 362, 13, 17, 13, 24, 201, 198, 2, 7536, 25, 1542, 12, 3070, 12, 23344, 201, 198,...
2.782282
666
import pymongo client = pymongo.MongoClient('''mongodb://dakotapope:passwrd@ cluster0-shard-00-00-iaoct.mongodb.net:27017,cluster0-shard-00 -01-iaoct.mongodb.net:27017,cluster0-shard-00-02-iaoct.mongodb. net:27017/test?ssl=true&replicaSet=Cluster0-shard-0&authSource= admin&retryWrites=true''') # investigate the databases already initialized client.database_names() # -->['rpg_data', 'test', 'admin', 'local'] # since I created the table on the Mongo Atlas dashboard I wil use it here rpgs = client.rpg_data.rpg # loadout the json file to prep for dumping into a mongo db table with open('''C:/Users/dakot/Documents/GitHub/DS-Unit-3-Sprint-2-SQL-and- Databases/module3-nosql-and-document-oriented-databases/rpg.json''') as f: file_data = json.load(f) # make a space for the data to go rpg_table = rpg['rpg_data'] # Dump the json data into the mongodb cloud. rpg_table.insert_many(file_data) # <pymongo.results.InsertManyResult at 0x2c80a7c8688> # And DONE!
[ 11748, 279, 4948, 25162, 198, 198, 16366, 796, 279, 4948, 25162, 13, 44, 25162, 11792, 7, 7061, 6, 31059, 375, 65, 1378, 67, 461, 313, 499, 3008, 25, 6603, 86, 4372, 31, 198, 565, 5819, 15, 12, 1477, 446, 12, 405, 12, 405, 12, 1...
2.527415
383
#!/usr/bin/python3 import xlrd import csv import sys import getopt # input configuration iColDate = 0 iColTransactionType = 1 iColAmount = 3 iColDescription = 6 transactionType = 'Repayment' descriptionType = 'Interest' #output configuration outHeader = ['Datum', 'Typ', 'Wert'] outType = 'Zinsen' outDelimiter = ';' if __name__ == "__main__": main(sys.argv[1:])
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 11748, 2124, 75, 4372, 198, 11748, 269, 21370, 198, 11748, 25064, 198, 11748, 651, 8738, 198, 198, 2, 5128, 8398, 198, 72, 5216, 10430, 796, 657, 198, 72, 5216, 48720, 6030, 796, 352, 1...
2.720588
136
"""Promises, promises, promises.""" from __future__ import absolute_import, unicode_literals import re from collections import namedtuple from .abstract import Thenable from .promises import promise from .synchronization import barrier from .funtools import ( maybe_promise, ensure_promise, ppartial, preplace, starpromise, transform, wrap, ) __version__ = '1.3.0' __author__ = 'Ask Solem' __contact__ = 'ask@celeryproject.org' __homepage__ = 'http://github.com/celery/vine' __docformat__ = 'restructuredtext' # -eof meta- version_info_t = namedtuple('version_info_t', ( 'major', 'minor', 'micro', 'releaselevel', 'serial', )) # bump version can only search for {current_version} # so we have to parse the version here. _temp = re.match( r'(\d+)\.(\d+).(\d+)(.+)?', __version__).groups() VERSION = version_info = version_info_t( int(_temp[0]), int(_temp[1]), int(_temp[2]), _temp[3] or '', '') del(_temp) del(re) __all__ = [ 'Thenable', 'promise', 'barrier', 'maybe_promise', 'ensure_promise', 'ppartial', 'preplace', 'starpromise', 'transform', 'wrap', ]
[ 37811, 24129, 2696, 11, 10497, 11, 10497, 526, 15931, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 11, 28000, 1098, 62, 17201, 874, 198, 198, 11748, 302, 198, 198, 6738, 17268, 1330, 3706, 83, 29291, 198, 198, 6738, 764, 397, ...
2.719603
403
#!/usr/bin/env python import numpy as np import matplotlib.pyplot as plt from LLC_Membranes.timeseries.forecast_ctrw import System from LLC_Membranes.llclib import file_rw import names residues = ["GCL", "SOH"] wt = 10 path = "/home/bcoscia/Documents/Gromacs/Transport/NaGA3C11" colors = ['blue', 'red'] opacity = 1 nbins = 25 lw = 2 fig, ax = plt.subplots(1, 2, figsize=(10, 5)) for j, r in enumerate(residues): obj = file_rw.load_object('%s/%s/%swt/forecast_%s.pl' % (path, r, wt, r)) hops = [] for i in obj.hop_lengths: hops += i print(max(hops)) if j == 0: hop_hist, edges = np.histogram(hops, density=True, bins=nbins) bounds = [edges[0], edges[-1]] else: hop_hist, edges = np.histogram(hops, density=True, bins=np.linspace(bounds[0], bounds[1], nbins + 1)) hop_outline = np.zeros([len(hop_hist)*2 + 2, 2]) hop_outline[::2, 0] = edges hop_outline[1::2, 0] = edges hop_outline[1:-1:2, 1] = hop_hist hop_outline[2:-1:2, 1] = hop_hist if j == 0: dwell_hist, edges = np.histogram(obj.dwell_times, density=True, bins=nbins) bounds_power = [edges[0], edges[-1]] else: dwell_hist, edges = np.histogram(obj.dwell_times, density=True, bins=np.linspace(bounds_power[0], bounds_power[1], nbins + 1)) dwell_outline = np.zeros([len(dwell_hist)*2 + 2, 2]) dwell_outline[::2, 0] = edges dwell_outline[1::2, 0] = edges dwell_outline[1:-1:2, 1] = dwell_hist dwell_outline[2:-1:2, 1] = dwell_hist ax[0].plot(hop_outline[:, 0], hop_outline[:, 1], color=colors[j], alpha=opacity, linewidth=lw) ax[1].plot(dwell_outline[:, 0], dwell_outline[:, 1], color=colors[j], alpha=opacity, label=names.res_to_name[r], linewidth=lw) ax[0].tick_params(labelsize=14) ax[1].tick_params(labelsize=14) ax[1].legend(fontsize=14) ax[0].set_ylabel('Frequency', fontsize=14) ax[0].set_xlabel('Hop Length (nm)', fontsize=14) ax[1].set_xlabel('Dwell Time (ns)', fontsize=14) plt.tight_layout() plt.savefig('dwell_hop_%s.pdf' % '_'.join(residues)) plt.show()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 6738, 11419, 62, 13579, 1671, 7305, 13, 22355, 10640, 13, 754, 2701, 62, 24087, 8...
2.222851
884
start_time=[] end_time=[] query_time=0 students_count=0 string_to_list('start time : ',start_time) string_to_list('end time : ',end_time) query_time=int(input('query time : ')) if not(1<=len(start_time)<=100): print('start time list out of range') exit() elif not(1<=len(end_time)<=100): print('end time list out of range') exit() elif len(start_time)!=len(end_time): print('length of lists start and end are not the same') exit() elif not(1<=query_time<=1000): print('query time out of range') exit() for i in range(len(start_time)): if not(1<=start_time[i]<=1000): print(f'start time [{i}] out of range') exit() elif not(1<=end_time[i]<=1000): print(f'end time [{i}] out of range') exit() if start_time[i]<=end_time[i]: temp=end_time[i]-start_time[i] if temp>=query_time: students_count+=1 print(students_count)
[ 198, 9688, 62, 2435, 28, 21737, 198, 437, 62, 2435, 28, 21737, 198, 22766, 62, 2435, 28, 15, 198, 19149, 658, 62, 9127, 28, 15, 198, 8841, 62, 1462, 62, 4868, 10786, 9688, 640, 1058, 46083, 9688, 62, 2435, 8, 198, 8841, 62, 1462, ...
2.218447
412
"""Added tariff Revision ID: 4dbaa3104f4 Revises: 1d6f96d1df Create Date: 2015-05-27 16:00:09.343862 """ # revision identifiers, used by Alembic. revision = '4dbaa3104f4' down_revision = '1d6f96d1df' branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa
[ 37811, 13003, 36427, 198, 198, 18009, 1166, 4522, 25, 604, 67, 7012, 64, 18, 13464, 69, 19, 198, 18009, 2696, 25, 352, 67, 21, 69, 4846, 67, 16, 7568, 198, 16447, 7536, 25, 1853, 12, 2713, 12, 1983, 1467, 25, 405, 25, 2931, 13, ...
2.34375
128
#imports import os import subprocess from colorama import init,Fore, Back, Style import asyncio import urllib.parse import time from time import perf_counter init(convert=True) #vars ver = "Beta, Lots of commits going on!" ping = 0 pings = [] tempping = 0 searches = 0 base = 300 delay = 0 gotQ = "" dropTime = 0 reqTime = 0 #funcs #THIS PING CHECK CODE IS FROM kingscratss#3407 on discord!! #cool ascii text thing/creds os.system("cls") print(Fore.LIGHTBLUE_EX + ''' ''') print(Fore.LIGHTBLUE_EX + " By Mythological, Version: " + ver) print() print() #assign vars ping = setupPing() searches = setupSearches() #computate and print delay = calc() out()
[ 2, 320, 3742, 198, 11748, 28686, 198, 11748, 850, 14681, 198, 6738, 3124, 1689, 1330, 2315, 11, 16351, 11, 5157, 11, 17738, 198, 11748, 30351, 952, 198, 11748, 2956, 297, 571, 13, 29572, 198, 11748, 640, 198, 6738, 640, 1330, 23035, 6...
2.33871
310
#!/usr/bin/env python3 # # calc_qual.py # # A program to calculate the quality factors and magnetic angle within some defined region # of an Athena++ disk using MPI # # To run: # mpirun -n [n] python calc_qual.py [options] # for [n] cores. # import numpy as np import os import sys sys.path.insert(0, '/home/per29/rds/rds-accretion-zyNhkonJSR8/athena-analysis/dependencies') #sys.path.insert(0, '/Users/paytonrodman/athena-sim/athena-analysis/dependencies') import athena_read import AAT import glob import re import csv import scipy.stats as st import argparse from math import sqrt from mpi4py import MPI # Execute main function if __name__ == '__main__': parser = argparse.ArgumentParser(description='Calculate various quality factors from raw simulation data.') parser.add_argument('prob_id', help='base name of the data being analysed, e.g. inflow_var or disk_base') parser.add_argument('-u', '--update', action="store_true", help='specify whether the results being analysed are from a restart') parser.add_argument('-rl', '--r_lower', type=float, default=None, help='value of lower r bound of region being analysed, must be between x1min and x1max (default=5)') parser.add_argument('-ru', '--r_upper', type=float, default=None, help='value of upper r bound of region being analysed, must be between x1min and x1max (default=100)') parser.add_argument('-tl', '--theta_lower', type=float, default=None, help='value of lower theta bound of region being analysed, must be between x2min and x2max (default=0.982)') parser.add_argument('-tu', '--theta_upper', type=float, default=None, help='value of upper theta bound of region being analysed, must be between x2min and x2max (default=2.159)') args = parser.parse_args() main(**vars(args))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 198, 2, 42302, 62, 13255, 13, 9078, 198, 2, 198, 2, 317, 1430, 284, 15284, 262, 3081, 5087, 290, 14091, 9848, 1626, 617, 5447, 3814, 198, 2, 286, 281, 21341, 4880, 11898, 12...
2.247899
952
from sqlalchemy import Column, String, Integer, Text, Boolean, DateTime from config.access import Base from sqlalchemy.ext.declarative import declared_attr from datetime import datetime def export(self): pass class AccessAuthor(Base, BaseFunctions): """ Author model """ __tablename__ = "Author" sort_name = "Author" id = Column(Integer, primary_key=True) abbreviation = Column(String(64), unique=True, nullable=False) full_name = Column(String(64)) notes = Column(String(128)) class AccessDefinition(Base, BaseFunctions): __tablename__ = 'WordDefinition' sort_name = "Definition" word_id = Column("WID", Integer) position = Column("I", Integer, nullable=False) usage = Column("Usage", String(64)) grammar = Column("Grammar", String(8)) body = Column("Definition", Text, nullable=False) main = Column("Main", String(8)) case_tags = Column("Tags", String(16)) id = Column("id", Integer, primary_key=True) class AccessEvent(Base, BaseFunctions): """ Event model """ __tablename__ = "LexEvent" sort_name = "Event" id = Column("EVT", Integer, primary_key=True) name = Column("Event", String(64), nullable=False) date = Column("When", String(32), nullable=False) definition = Column("WhyWhat", Text, nullable=False) annotation = Column("DictionaryAnnotation", String(16)) suffix = Column("FilenameSuffix", String(16)) class AccessSetting(Base, BaseFunctions): """ Setting model """ __tablename__ = "Settings" sort_name = "Settings" date = Column("DateModified", DateTime, primary_key=True) db_version = Column("DBVersion", Integer, nullable=False) last_word_id = Column("LastWID", Integer, nullable=False) db_release = Column("DBRelease", String(16), nullable=False) class AccessSyllable(Base, BaseFunctions): """ Syllable model """ __tablename__ = "Syllable" sort_name = "Syllable" id = Column(Integer, primary_key=True, autoincrement=True) name = Column("characters", String(8), primary_key=True) type = Column(String(32), nullable=False) allowed = Column(Boolean) class AccessType(Base, BaseFunctions): """ Type model """ __tablename__ = "Type" sort_name = "Type" id = Column(Integer, primary_key=True) type = Column(String(16), nullable=False) type_x = Column(String(16), nullable=False) group = Column(String(16), nullable=False) parentable = Column(Boolean, nullable=False) description = Column(String(255), nullable=True) class AccessWord(Base, BaseFunctions): """ Word model """ __tablename__ = "Words" sort_name = "Word" word_id = Column("WID", Integer, nullable=False, primary_key=True) type = Column("Type", String(16), nullable=False) type_x = Column("XType", String(16), nullable=False) affixes = Column("Affixes", String(16)) match = Column("Match", String(8)) authors = Column("Source", String(64)) year = Column("Year", String(128)) rank = Column("Rank", String(128)) origin = Column("Origin", String(128)) origin_x = Column("OriginX", String(64)) used_in = Column("UsedIn", Text) TID_old = Column("TID", Integer) # references class AccessWordSpell(Base, BaseFunctions): """WordSpell model""" __tablename__ = "WordSpell" sort_name = "WordSpell" word_id = Column("WID", Integer, nullable=False) word = Column("Word", String(64), nullable=False) sort_a = Column("SortA", String(64), nullable=False) sort_b = Column("SortB", String(64), nullable=False) event_start_id = Column("SEVT", Integer, nullable=False) event_end_id = Column("EEVT", Integer, nullable=False) origin_x = Column("OriginX", String(64)) id = Column(Integer, primary_key=True) ''' class AccessXWord(Base, BaseFunctions): """XWord model""" __tablename__ = "XWord" sort_name = "XWord" XSortA = Column(String) XSortB = Column(String) WID = Column(String, primary_key=True) I = Column(String) XWord = Column(String) '''
[ 6738, 44161, 282, 26599, 1330, 29201, 11, 10903, 11, 34142, 11, 8255, 11, 41146, 11, 7536, 7575, 198, 198, 6738, 4566, 13, 15526, 1330, 7308, 198, 6738, 44161, 282, 26599, 13, 2302, 13, 32446, 283, 876, 1330, 6875, 62, 35226, 198, 673...
2.71504
1,516
import ctypes import struct import time from fixate.core.common import bits from fixate.core.exceptions import InstrumentError, InstrumentNotConnected import fixate.config import fixate.core.discover def open(ftdi_description=""): """Open is the public api for the bit bang driver for discovering and opening a connection to a valid bit bang device :param restrictions: A dictionary containing the extents of the required equipment :return: A instantiated class connected to a valid bit_bang class """ devices = fixate.core.discover.discover_ftdi() for dev in devices: if ftdi_description.encode() == dev.Description or ftdi_description == "": return FTDI2xx(dev.Description) raise InstrumentNotConnected("No valid ftdi found by description '{}'".format(ftdi_description)) # Definitions UCHAR = ctypes.c_ubyte PCHAR = ctypes.POINTER(ctypes.c_char) PUCHAR = ctypes.POINTER(ctypes.c_ubyte) DWORD = ctypes.c_ulong LPDWORD = ctypes.POINTER(ctypes.c_ulong) FT_HANDLE = DWORD # Add null padding if 64 bit if struct.calcsize("P") == 8: else: # 32 bit try: ftdI2xx = ctypes.WinDLL("FTD2XX.dll") except Exception as e: raise ImportError("Unable to find FTD2XX.dll.\nPlugging in FDTI device will install DLL.") from e _ipdwNumDevs = DWORD(0) _p_ipdwNumDevs = LPDWORD(_ipdwNumDevs) # FT_GetDeviceInfoList def configure_bit_bang(self, bit_mode, bytes_required, latch_mask=1, clk_mask=2, data_mask=4, invert_mask=0b000): """ :param bit_mode: :param bytes_required: :param latch_mask: CBUS Pin for latch. 1 Default for Relay Matrix :param clk_mask: CBUS Pin for clock. 2 Default for Relay Matrix :param data_mask: CBUS Pin for data. 4 Default for Relay Matrix :param invert_mask: Mask for inverting. 0b111 For all inverted 0b000 for all non inverted based on MSB 0b<latch><clock><data> LSB :return: """ self.bb_bytes = bytes_required self.bit_mode = bit_mode self.write_bit_mode(self.pin_value_mask) self.bb_data = data_mask self.bb_clk = clk_mask self.bb_latch = latch_mask self.bb_inv_mask = 0 if (1 << 2) & invert_mask: self.bb_inv_mask += self.bb_latch if (1 << 1) & invert_mask: self.bb_inv_mask += self.bb_clk if 1 & invert_mask: self.bb_inv_mask += self.bb_data
[ 11748, 269, 19199, 198, 11748, 2878, 198, 11748, 640, 198, 6738, 4259, 378, 13, 7295, 13, 11321, 1330, 10340, 198, 6738, 4259, 378, 13, 7295, 13, 1069, 11755, 1330, 42410, 12331, 11, 42410, 3673, 13313, 276, 198, 11748, 4259, 378, 13, ...
2.438684
1,003
# You are given an array (which will have a length of at least 3, but could be very large) containing integers. The array is either entirely comprised of odd integers or entirely comprised of even integers except for a single integer N. Write a method that takes the array as an argument and returns this "outlier" N. # Examples # find_outlier([2, 4, 6, 7]) => 7 # find_outlier([3, 7, 11, 2]) => 2
[ 2, 921, 389, 1813, 281, 7177, 357, 4758, 481, 423, 257, 4129, 286, 379, 1551, 513, 11, 475, 714, 307, 845, 1588, 8, 7268, 37014, 13, 383, 7177, 318, 2035, 5000, 19869, 286, 5629, 37014, 393, 5000, 19869, 286, 772, 37014, 2845, 329, ...
3.764151
106