content
stringlengths
1
1.04M
input_ids
listlengths
1
774k
ratio_char_token
float64
0.38
22.9
token_count
int64
1
774k
import importlib from django import forms from s3file.apps import S3FileConfig from s3file.forms import S3FileInputMixin
[ 11748, 1330, 8019, 198, 198, 6738, 42625, 14208, 1330, 5107, 198, 198, 6738, 264, 18, 7753, 13, 18211, 1330, 311, 18, 8979, 16934, 198, 6738, 264, 18, 7753, 13, 23914, 1330, 311, 18, 8979, 20560, 35608, 259, 628 ]
3.263158
38
from django.contrib.sites.models import Site
[ 6738, 42625, 14208, 13, 3642, 822, 13, 49315, 13, 27530, 1330, 14413, 628 ]
3.538462
13
"""These methods are copied from https://github.com/Kyubyong/dc_tts/""" import os import copy import librosa import scipy.io.wavfile import numpy as np from tqdm import tqdm from scipy import signal from hparams import HParams as hp def spectrogram2wav(mag): '''# Generate wave file from linear magnitude spectrogram Args: mag: A numpy array of (T, 1+n_fft//2) Returns: wav: A 1-D numpy array. ''' # transpose mag = mag.T # de-noramlize mag = (np.clip(mag, 0, 1) * hp.max_db) - hp.max_db + hp.ref_db # to amplitude mag = np.power(10.0, mag * 0.05) # wav reconstruction wav = griffin_lim(mag ** hp.power) # de-preemphasis wav = signal.lfilter([1], [1, -hp.preemphasis], wav) # trim wav, _ = librosa.effects.trim(wav) return wav.astype(np.float32) def griffin_lim(spectrogram): '''Applies Griffin-Lim's raw.''' X_best = copy.deepcopy(spectrogram) for i in range(hp.n_iter): X_t = invert_spectrogram(X_best) est = librosa.stft(X_t, hp.n_fft, hp.hop_length, win_length=hp.win_length) phase = est / np.maximum(1e-8, np.abs(est)) X_best = spectrogram * phase X_t = invert_spectrogram(X_best) y = np.real(X_t) return y def invert_spectrogram(spectrogram): '''Applies inverse fft. Args: spectrogram: [1+n_fft//2, t] ''' return librosa.istft(spectrogram, hp.hop_length, win_length=hp.win_length, window="hann") def get_spectrograms(fpath): '''Parse the wave file in `fpath` and Returns normalized melspectrogram and linear spectrogram. Args: fpath: A string. The full path of a sound file. Returns: mel: A 2d array of shape (T, n_mels) and dtype of float32. mag: A 2d array of shape (T, 1+n_fft/2) and dtype of float32. ''' # Loading sound file y, sr = librosa.load(fpath, sr=hp.sr) # Trimming y, _ = librosa.effects.trim(y) # Preemphasis y = np.append(y[0], y[1:] - hp.preemphasis * y[:-1]) # stft linear = librosa.stft(y=y, n_fft=hp.n_fft, hop_length=hp.hop_length, win_length=hp.win_length) # magnitude spectrogram mag = np.abs(linear) # (1+n_fft//2, T) # mel spectrogram mel_basis = librosa.filters.mel(hp.sr, hp.n_fft, hp.n_mels) # (n_mels, 1+n_fft//2) mel = np.dot(mel_basis, mag) # (n_mels, t) # to decibel mel = 20 * np.log10(np.maximum(1e-5, mel)) mag = 20 * np.log10(np.maximum(1e-5, mag)) # normalize mel = np.clip((mel - hp.ref_db + hp.max_db) / hp.max_db, 1e-8, 1) mag = np.clip((mag - hp.ref_db + hp.max_db) / hp.max_db, 1e-8, 1) # Transpose mel = mel.T.astype(np.float32) # (T, n_mels) mag = mag.T.astype(np.float32) # (T, 1+n_fft//2) return mel, mag def save_to_wav(mag, filename): """Generate and save an audio file from the given linear spectrogram using Griffin-Lim.""" wav = spectrogram2wav(mag) scipy.io.wavfile.write(filename, hp.sr, wav) def preprocess(dataset_path, speech_dataset): """Preprocess the given dataset.""" wavs_path = os.path.join(dataset_path, 'wavs') mels_path = os.path.join(dataset_path, 'mels') if not os.path.isdir(mels_path): os.mkdir(mels_path) mags_path = os.path.join(dataset_path, 'mags') if not os.path.isdir(mags_path): os.mkdir(mags_path) for fname in tqdm(speech_dataset.fnames): mel, mag = get_spectrograms(os.path.join(wavs_path, '%s.wav' % fname)) t = mel.shape[0] # Marginal padding for reduction shape sync. num_paddings = hp.reduction_rate - (t % hp.reduction_rate) if t % hp.reduction_rate != 0 else 0 mel = np.pad(mel, [[0, num_paddings], [0, 0]], mode="constant") mag = np.pad(mag, [[0, num_paddings], [0, 0]], mode="constant") # Reduction mel = mel[::hp.reduction_rate, :] np.save(os.path.join(mels_path, '%s.npy' % fname), mel) np.save(os.path.join(mags_path, '%s.npy' % fname), mag)
[ 37811, 4711, 5050, 389, 18984, 422, 3740, 1378, 12567, 13, 785, 14, 30630, 549, 88, 506, 14, 17896, 62, 83, 912, 14, 37811, 198, 198, 11748, 28686, 198, 11748, 4866, 198, 11748, 9195, 4951, 64, 198, 11748, 629, 541, 88, 13, 952, 13,...
2.111859
1,931
# Copyright (c) DEV Corporation. All rights reserved. # Licensed under MIT License.
[ 2, 15069, 357, 66, 8, 5550, 53, 10501, 13, 1439, 2489, 10395, 13, 198, 2, 49962, 739, 17168, 13789, 13, 198 ]
4
21
""" Django settings for medical project. Generated by 'django-admin startproject' using Django 3.0.8. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os from .dev import * # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('MEDSTORE_SECRET_KEY', 'g+!ccv7(cweo2*#8^6+%7(x4$na09w-0*+&)18nkt8)=um_+p(') ACCOUNT_FORMS = { "signup": "home.forms.UserSignUp" } ACCOUNT_EMAIL_VERIFICATION = 'none' CRISPY_TEMPLATE_PACK = 'bootstrap4' # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django_filters', 'django.contrib.sitemaps', # For SiteMap # extensions 'crispy_forms', # apps 'medicines.apps.MedicinesConfig', 'home.apps.HomeConfig', 'cart', 'checkout', 'accounts', # For Authentication 'allauth', 'allauth.account', 'allauth.socialaccount', # To whitelist frontend 'corsheaders', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', ] ROOT_URLCONF = 'medical.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'medical.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend' ] # Password validation # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Kolkata' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_URL = '/static/' SITE_ID = 1 LOGIN_REDIRECT_URL = "/" LOGIN_URL = "/login/" try: from . import stripe_conf STR_PUB = stripe_conf.publishable_key STR_SEC = stripe_conf.secret_key STRIPE_ENDPOINT_KEY = stripe_conf.end_key except (ModuleNotFoundError, ImportError): STR_PUB = '' STR_SEC = '' STRIPE_ENDPOINT_KEY = '' # For SMTP Email EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 # Include production settings try: # Check if there's a production environment file from .prod import * except (ModuleNotFoundError, ImportError): pass
[ 37811, 198, 35, 73, 14208, 6460, 329, 3315, 1628, 13, 198, 198, 8645, 515, 416, 705, 28241, 14208, 12, 28482, 923, 16302, 6, 1262, 37770, 513, 13, 15, 13, 23, 13, 198, 198, 1890, 517, 1321, 319, 428, 2393, 11, 766, 198, 5450, 1378...
2.365615
1,838
import dataclasses import enum from typing import Any @dataclasses.dataclass
[ 11748, 4818, 330, 28958, 198, 11748, 33829, 198, 6738, 19720, 1330, 4377, 628, 198, 198, 31, 19608, 330, 28958, 13, 19608, 330, 31172, 198 ]
3.333333
24
from deepsegment import DeepSegment # The default language is 'en' segmenter = DeepSegment('en') segmenter.segment('I am Batman i live in gotham') # ['I am Batman', 'i live in gotham']
[ 6738, 2769, 325, 5154, 1330, 10766, 41030, 434, 198, 2, 383, 4277, 3303, 318, 705, 268, 6, 198, 325, 5154, 263, 796, 10766, 41030, 434, 10786, 268, 11537, 198, 325, 5154, 263, 13, 325, 5154, 10786, 40, 716, 9827, 1312, 2107, 287, 30...
2.983871
62
# -*- coding: utf-8 -*- from django.core.urlresolvers import reverse from django.db import models from django.utils.translation import ugettext_lazy as _
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 42625, 14208, 13, 7295, 13, 6371, 411, 349, 690, 1330, 9575, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 42625, 14208, 13, 26791, 13, 41519, 1330, 33...
2.961538
52
import sys; sys.path.append("..") from policies import max_min_fairness, max_min_fairness_strategy_proof import random import time import numpy as np np.set_printoptions(precision=3, suppress=True)
[ 11748, 25064, 26, 25064, 13, 6978, 13, 33295, 7203, 492, 4943, 198, 6738, 4788, 1330, 3509, 62, 1084, 62, 22043, 1108, 11, 3509, 62, 1084, 62, 22043, 1108, 62, 2536, 4338, 62, 13288, 198, 198, 11748, 4738, 198, 11748, 640, 198, 198, ...
3.076923
65
import os import os.path from print_function import * # Exemple # main.py server start # main.py server start /home/user/kafka/config/server.propersties # main.py server stop # main.py server restart # main.py server restart /home/user/kafka/config/server.propersties KAFKA_HOME = str(os.getenv("KAFKA_HOME")) LOG_DIR = "server.log" BACKGROUND = " > "+LOG_DIR+" 2>&1 &" DEFAULT_CONF = KAFKA_HOME+"config/server.properties"
[ 11748, 28686, 201, 198, 11748, 28686, 13, 6978, 201, 198, 6738, 3601, 62, 8818, 1330, 1635, 201, 198, 201, 198, 2, 1475, 368, 1154, 201, 198, 2, 1388, 13, 9078, 4382, 923, 201, 198, 2, 1388, 13, 9078, 4382, 923, 1220, 11195, 14, 7...
2.511364
176
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- # Generated file, DO NOT EDIT # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------------------------- from msrest.serialization import Model class ContributedFeatureState(Model): """ContributedFeatureState. :param feature_id: The full contribution id of the feature :type feature_id: str :param overridden: True if the effective state was set by an override rule (indicating that the state cannot be managed by the end user) :type overridden: bool :param reason: Reason that the state was set (by a plugin/rule). :type reason: str :param scope: The scope at which this state applies :type scope: :class:`ContributedFeatureSettingScope <feature-management.v4_1.models.ContributedFeatureSettingScope>` :param state: The current state of this feature :type state: object """ _attribute_map = { 'feature_id': {'key': 'featureId', 'type': 'str'}, 'overridden': {'key': 'overridden', 'type': 'bool'}, 'reason': {'key': 'reason', 'type': 'str'}, 'scope': {'key': 'scope', 'type': 'ContributedFeatureSettingScope'}, 'state': {'key': 'state', 'type': 'object'} }
[ 2, 16529, 1783, 10541, 201, 198, 2, 15069, 357, 66, 8, 5413, 10501, 13, 1439, 2489, 10395, 13, 201, 198, 2, 49962, 739, 262, 17168, 13789, 13, 4091, 13789, 13, 14116, 287, 262, 1628, 6808, 329, 5964, 1321, 13, 201, 198, 2, 16529, ...
3.481953
471
""" Gathers up all of the expenses and breaks down the values by month. """ import time import math from operator import itemgetter from gnucash_reports.collate.bucket import PeriodCollate, CategoryCollate, AccountCollate from gnucash_reports.collate.bucket_generation import decimal_generator from gnucash_reports.collate.store import split_summation from gnucash_reports.periods import PeriodStart, PeriodEnd, PeriodSize from gnucash_reports.wrapper import get_splits, account_walker, parse_walker_parameters def expenses_period(expenses=None, start=PeriodStart.this_month_year_ago, end=PeriodEnd.this_month, period_size=PeriodSize.month): """ Calculate the amount of money that when into an expense account over the given period. :param expenses: account walker parameters for accounts to calculate :param start: the start of the time frame for the report :param end: the end of the time frame for the report :param period_size: the size of the buckets for the report :return: dictionary containing: expenses: sorted dictionary containing keys for date and value. """ expenses = expenses or [] accounts = parse_walker_parameters(expenses) start_period = PeriodStart(start) end_period = PeriodEnd(end) period_size = PeriodSize(period_size) bucket = PeriodCollate(start_period.date, end_period.date, decimal_generator, split_summation, frequency=period_size.frequency, interval=period_size.interval) for account in account_walker(**accounts): for split in get_splits(account, start_period.date, end_period.date): bucket.store_value(split) sorted_results = [] for key, value in bucket.container.iteritems(): sorted_results.append((time.mktime(key.timetuple()), value)) data_set = { 'expenses': sorted(sorted_results, key=itemgetter(0)) } return data_set def expenses_box(expenses=None, start=PeriodStart.this_month_year_ago, end=PeriodEnd.this_month, period_size=PeriodSize.month): """ Calculate the amount of money that when into an expense account over the given period. :param expenses: account walker parameters for accounts to calculate :param start: the start of the time frame for the report :param end: the end of the time frame for the report :param period_size: the size of the buckets for the report :return: dictionary containing: expenses: dictionary containing the following keys: low - lowest amount spent high - highest amount spent q1 - first quartile value q2 - second quartile value q3 - third quartile value """ expenses = expenses or [] accounts = parse_walker_parameters(expenses) start_period = PeriodStart(start) end_period = PeriodEnd(end) period_size = PeriodSize(period_size) bucket = PeriodCollate(start_period.date, end_period.date, decimal_generator, split_summation, frequency=period_size.frequency, interval=period_size.interval) for account in account_walker(**accounts): for split in get_splits(account, start_period.date, end_period.date): bucket.store_value(split) results = [] for key, value in bucket.container.iteritems(): results.append(float(value)) results = sorted(results) return {'low': results[0], 'high': results[-1], 'q1': get_median(get_lower_half(results)), 'q2': get_median(results), 'q3': get_median(get_upper_half(results))} def expenses_categories(expenses=None, start=PeriodStart.this_month, end=PeriodEnd.this_month): """ Walk through the accounts defined in expenses base and collate the spending in the period into the categories defined in the configuration object. :param expenses: account walker definition of the accounts to grab expenses for. :param start: when the report should start collecting data from :param end: when the report should stop collecting data :return: dictionary containing: categories - list of tuples (category name, value) containing the results sorted by category name """ expenses = expenses or [] accounts = parse_walker_parameters(expenses) start_period = PeriodStart(start) end_period = PeriodEnd(end) bucket = CategoryCollate(decimal_generator, split_summation) for account in account_walker(**accounts): for split in get_splits(account, start_period.date, end_period.date): bucket.store_value(split) return {'categories': sorted([[key, value] for key, value in bucket.container.iteritems()], key=itemgetter(0))} def expense_accounts(expenses=None, start=PeriodStart.this_month_year_ago, end=PeriodEnd.this_month): """ Walk through the accounts defined in expenses base and collate the spending into categories that are named after the leaf account name. :param expenses: account walker definition of the accounts to grab expenses for. :param start: when the report should start collecting data from :param end: when the report should stop collecting data :return: dictionary containing: categories - list of tuples (category name, value) containing the results sorted by category name """ expenses = expenses or [] accounts = parse_walker_parameters(expenses) start_period = PeriodStart(start) end_period = PeriodEnd(end) bucket = AccountCollate(decimal_generator, split_summation) for account in account_walker(**accounts): for split in get_splits(account, start_period.date, end_period.date): bucket.store_value(split) return {'categories': sorted([[key, value] for key, value in bucket.container.iteritems()], key=itemgetter(0))} # Calculating the quartiles based on: # https://en.wikipedia.org/wiki/Quartile Method 1
[ 37811, 198, 38, 1032, 82, 510, 477, 286, 262, 9307, 290, 9457, 866, 262, 3815, 416, 1227, 13, 198, 37811, 198, 11748, 640, 198, 11748, 10688, 198, 6738, 10088, 1330, 2378, 1136, 353, 198, 198, 6738, 19967, 1229, 1077, 62, 48922, 13, ...
3.036617
1,939
import pandas as pd import numpy as np import sklearn import joblib from flask import Flask, render_template, request, url_for app = Flask(__name__) @app.route('/') @app.route('/predict', methods=['GET', 'POST']) if __name__ == '__main__': app.run(debug=True)
[ 11748, 19798, 292, 355, 279, 67, 201, 198, 11748, 299, 32152, 355, 45941, 201, 198, 11748, 1341, 35720, 201, 198, 11748, 1693, 8019, 201, 198, 6738, 42903, 1330, 46947, 11, 8543, 62, 28243, 11, 2581, 11, 19016, 62, 1640, 201, 198, 201...
2.469565
115
from typing import Tuple from math import prod with open('input', 'r') as fd: bus_lines_raw = fd.readlines()[1].strip().split(',') bus_lines = list(map(int, filter(lambda bl: bl != 'x', bus_lines_raw))) bl_offsets = [i for i, n in enumerate(bus_lines_raw) if n != 'x'] # For an explanation of how this works, look up the Chinese Remainder Theorem, e.g.: # https://en.wikipedia.org/wiki/Chinese_remainder_theorem#Existence_(direct_construction) N = prod(bus_lines) result = 0 for i in range(len(bus_lines)): a_i = bus_lines[i] - bl_offsets[i] n_i = bus_lines[i] N_i = N // n_i # Using a float value here with N / n_i results in overflow errors for high numbers M_i, _ = bezout_coeff(N_i, n_i) result += a_i * M_i * N_i # This calculation finds _a_ solution - other solutions are obtained by adding multiples of N. # We are interested in the smallest positive solution. result %= N print(result)
[ 6738, 19720, 1330, 309, 29291, 198, 6738, 10688, 1330, 40426, 198, 198, 4480, 1280, 10786, 15414, 3256, 705, 81, 11537, 355, 277, 67, 25, 198, 220, 220, 220, 1323, 62, 6615, 62, 1831, 796, 277, 67, 13, 961, 6615, 3419, 58, 16, 4083,...
2.715543
341
""" Concerned with storing and returning books from a list. """ books = [] # def delete_book(name): # This is considered as a Bad Practice. # for book in books: # if book['name'] == name: # books.remove(book) """ SCOPE - as in <line 26> : global books states that books in local scope = (is equal to the) books in the outer scope """
[ 37811, 198, 3103, 49990, 351, 23069, 290, 8024, 3835, 422, 257, 1351, 13, 198, 37811, 198, 12106, 796, 17635, 628, 628, 198, 198, 2, 825, 12233, 62, 2070, 7, 3672, 2599, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 1303, ...
2.705036
139
# Licensed under a 3-clause BSD style license - see LICENSE.rst """Fit and illustrate example spectral data in XSPEC format. Run `xspec_fake.py` first to generate the example input file. """
[ 2, 49962, 739, 257, 513, 12, 565, 682, 347, 10305, 3918, 5964, 532, 766, 38559, 24290, 13, 81, 301, 198, 37811, 31805, 290, 19418, 1672, 37410, 1366, 287, 1395, 48451, 5794, 13, 198, 198, 10987, 4600, 87, 16684, 62, 30706, 13, 9078, ...
3.555556
54
# -*- coding: utf-8 -*- # @Author : William # @Project : TextGAN-william # @FileName : text_process.py # @Time : Created at 2019-05-14 # @Blog : http://zhiweil.ml/ # @Description : # Copyrights (C) 2018. All Rights Reserved. import nltk import os import torch import config as cfg def get_tokenlized(file): """tokenlize the file""" tokenlized = list() with open(file) as raw: for text in raw: text = nltk.word_tokenize(text.lower()) tokenlized.append(text) return tokenlized def get_word_list(tokens): """get word set""" word_set = list() for sentence in tokens: for word in sentence: word_set.append(word) return list(set(word_set)) def get_dict(word_set): """get word_index_dict and index_word_dict""" word_index_dict = dict() index_word_dict = dict() index = 2 word_index_dict[cfg.padding_token] = str(cfg.padding_idx) index_word_dict[str(cfg.padding_idx)] = cfg.padding_token word_index_dict[cfg.start_token] = str(cfg.start_letter) index_word_dict[str(cfg.start_letter)] = cfg.start_token for word in word_set: word_index_dict[word] = str(index) index_word_dict[str(index)] = word index += 1 return word_index_dict, index_word_dict def text_process(train_text_loc, test_text_loc=None): """get sequence length and dict size""" train_tokens = get_tokenlized(train_text_loc) if test_text_loc is None: test_tokens = list() else: test_tokens = get_tokenlized(test_text_loc) word_set = get_word_list(train_tokens + test_tokens) word_index_dict, index_word_dict = get_dict(word_set) if test_text_loc is None: sequence_len = len(max(train_tokens, key=len)) else: sequence_len = max(len(max(train_tokens, key=len)), len(max(test_tokens, key=len))) return sequence_len, len(word_index_dict) # ======================================================================== def init_dict(dataset): """ Initialize dictionaries of dataset, please note that '0': padding_idx, '1': start_letter. Finally save dictionary files locally. """ tokens = get_tokenlized('dataset/{}.txt'.format(dataset)) # tokens.extend(get_tokenlized('dataset/testdata/{}_test.txt'.format(dataset))) # !!! no test data word_set = get_word_list(tokens) word_index_dict, index_word_dict = get_dict(word_set) with open('dataset/{}_wi_dict.txt'.format(dataset), 'w') as dictout: dictout.write(str(word_index_dict)) with open('dataset/{}_iw_dict.txt'.format(dataset), 'w') as dictout: dictout.write(str(index_word_dict)) print('total tokens: ', len(word_index_dict)) def load_dict(dataset): """Load dictionary from local files""" iw_path = 'dataset/{}_iw_dict.txt'.format(dataset) wi_path = 'dataset/{}_wi_dict.txt'.format(dataset) if not os.path.exists(iw_path) or not os.path.exists(iw_path): # initialize dictionaries init_dict(dataset) with open(iw_path, 'r') as dictin: index_word_dict = eval(dictin.read().strip()) with open(wi_path, 'r') as dictin: word_index_dict = eval(dictin.read().strip()) return word_index_dict, index_word_dict def tensor_to_tokens(tensor, dictionary): """transform Tensor to word tokens""" tokens = [] for sent in tensor: sent_token = [] for word in sent.tolist(): if word == cfg.padding_idx: break sent_token.append(dictionary[str(word)]) tokens.append(sent_token) return tokens def tokens_to_tensor(tokens, dictionary): """transform word tokens to Tensor""" tensor = [] for sent in tokens: sent_ten = [] for i, word in enumerate(sent): if word == cfg.padding_token: break sent_ten.append(int(dictionary[str(word)])) while i < cfg.max_seq_len - 1: sent_ten.append(cfg.padding_idx) i += 1 tensor.append(sent_ten[:cfg.max_seq_len]) return torch.LongTensor(tensor) def padding_token(tokens): """pad sentences with padding_token""" pad_tokens = [] for sent in tokens: sent_token = [] for i, word in enumerate(sent): if word == cfg.padding_token: break sent_token.append(word) while i < cfg.max_seq_len - 1: sent_token.append(cfg.padding_token) i += 1 pad_tokens.append(sent_token) return pad_tokens def write_tokens(filename, tokens): """Write word tokens to a local file (For Real data)""" with open(filename, 'w') as fout: for sent in tokens: fout.write(' '.join(sent)) fout.write('\n') def write_tensor(filename, tensor): """Write Tensor to a local file (For Oracle data)""" with open(filename, 'w') as fout: for sent in tensor: fout.write(' '.join([str(i) for i in sent.tolist()])) fout.write('\n')
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2488, 13838, 220, 220, 220, 220, 220, 220, 1058, 3977, 198, 2, 2488, 16775, 220, 220, 220, 220, 220, 1058, 8255, 45028, 12, 10594, 1789, 198, 2, 2488, 8979, 5376, ...
2.274237
2,228
import json from os.path import expanduser, exists from os import makedirs conoha_home = expanduser('~/.conoha') config_path = f'{conoha_home}/config.json' credential_path = f'{conoha_home}/credential.json' token_path = f'{conoha_home}/token.json' if not exists(conoha_home): makedirs(conoha_home)
[ 11748, 33918, 198, 6738, 28686, 13, 6978, 1330, 4292, 7220, 11, 7160, 198, 6738, 28686, 1330, 285, 4335, 17062, 198, 198, 1102, 28083, 62, 11195, 796, 4292, 7220, 10786, 93, 11757, 1102, 28083, 11537, 198, 11250, 62, 6978, 796, 277, 6, ...
2.596639
119
#!/usr/bin/env python # # Copyright (c) 2013 Juniper Networks, Inc. All rights reserved. # # # sandesh_msg_test # import unittest import sys import os import socket import test_utils import time import uuid from itertools import chain sys.path.insert(1, sys.path[0]+'/../../../python') from pysandesh.sandesh_base import * from pysandesh.sandesh_client import * from pysandesh.sandesh_session import * from gen_py.msg_test.ttypes import * # end __init__ # end write # end SandeshSessionTestHelper # end class SandeshMsgTest if __name__ == '__main__': unittest.main(verbosity=2, catchbreak=True)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 2, 198, 2, 15069, 357, 66, 8, 2211, 7653, 9346, 27862, 11, 3457, 13, 1439, 2489, 10395, 13, 198, 2, 198, 198, 2, 198, 2, 6450, 5069, 62, 19662, 62, 9288, 198, 2, 198, 198, ...
2.795455
220
from turtle import * side = 50 COUNT = 8 checker(side)
[ 6738, 28699, 1330, 1635, 198, 1589, 796, 2026, 198, 34, 28270, 796, 807, 628, 198, 9122, 263, 7, 1589, 8, 198 ]
2.714286
21
# flake8: noqa from .base import * from .distillation import * from .metrics import * from .regularizations import * from .unsupervised import * from .losses import *
[ 2, 781, 539, 23, 25, 645, 20402, 198, 6738, 764, 8692, 1330, 1635, 198, 6738, 764, 17080, 40903, 1330, 1635, 198, 6738, 764, 4164, 10466, 1330, 1635, 198, 6738, 764, 16338, 4582, 1330, 1635, 198, 6738, 764, 403, 16668, 16149, 1330, 16...
3.34
50
#!/usr/bin/env python """ Fluentd queue check for v3 """ import argparse import time import subprocess import math from dateutil import parser from datetime import datetime from openshift_tools.monitoring.ocutil import OCUtil from openshift_tools.monitoring.metric_sender import MetricSender import logging logging.basicConfig( format='%(asctime)s - %(relativeCreated)6d - %(levelname)-8s - %(message)s', ) logger = logging.getLogger() logger.setLevel(logging.INFO) ocutil = OCUtil() if __name__ == '__main__': OFQC = OpenshiftFluentdQueueCheck() OFQC.run()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 37811, 198, 220, 34070, 298, 67, 16834, 2198, 329, 410, 18, 198, 37811, 198, 198, 11748, 1822, 29572, 198, 11748, 640, 198, 11748, 850, 14681, 198, 11748, 10688, 198, 6738, 3128, 22602, ...
2.78744
207
import discord import os import inspect from discord.ext import commands class Community(): """Commands for The Bad Server community""" @property @commands.command() async def source(self, ctx, *, command: str = None): """Displays the Bad Bot's source""" if command is None: return await ctx.send(self.source_url) object = self.bot.get_command(command.replace('.', ' ')) if object is None: return await ctx.send('Command not found') src = object.callback.__code__ lines, firstlineno = inspect.getsourcelines(src) if not object.callback.__module__.startswith('discord'): location = os.path.relpath(src.co_filename).replace('\\', '/') else: location = object.callback.__module__.replace('.', '/') + '.py' await ctx.send(f'<{self.source_url}/blob/master/{location}#L{firstlineno}-L{firstlineno + len(lines) - 1}>')
[ 11748, 36446, 198, 11748, 28686, 198, 11748, 10104, 198, 6738, 36446, 13, 2302, 1330, 9729, 198, 198, 4871, 8108, 33529, 198, 220, 220, 220, 37227, 6935, 1746, 329, 383, 7772, 9652, 2055, 37811, 198, 220, 220, 220, 220, 198, 220, 220, ...
2.423559
399
from machine_learning_library.model_discriminant_analysis import Classification import numpy as np
[ 6738, 4572, 62, 40684, 62, 32016, 13, 19849, 62, 15410, 3036, 42483, 62, 20930, 1330, 40984, 198, 11748, 299, 32152, 355, 45941, 628 ]
4.347826
23
# Generated by Django 3.0.7 on 2020-06-12 08:38 from django.db import migrations, models import django.db.models.deletion
[ 2, 2980, 515, 416, 37770, 513, 13, 15, 13, 22, 319, 12131, 12, 3312, 12, 1065, 8487, 25, 2548, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 11748, 42625, 14208, 13, 9945, 13, 27530, 13, 2934, 1616, 295, ...
2.818182
44
import ast import functools from typing import Iterable from typing import List from typing import Optional from typing import Tuple from tokenize_rt import Offset from tokenize_rt import Token from pyupgrade._ast_helpers import ast_to_offset from pyupgrade._data import register from pyupgrade._data import State from pyupgrade._data import TokenFunc from pyupgrade._token_helpers import find_token MOCK_MODULES = frozenset(('mock', 'mock.mock')) @register(ast.ImportFrom) @register(ast.Import) @register(ast.Attribute)
[ 11748, 6468, 198, 11748, 1257, 310, 10141, 198, 6738, 19720, 1330, 40806, 540, 198, 6738, 19720, 1330, 7343, 198, 6738, 19720, 1330, 32233, 198, 6738, 19720, 1330, 309, 29291, 198, 198, 6738, 11241, 1096, 62, 17034, 1330, 3242, 2617, 198,...
3.268293
164
import itertools import matplotlib.pyplot as plt import numpy as np import pandas as pd import plotly.express as px from scipy.optimize import minimize, LinearConstraint, NonlinearConstraint from tqdm import tqdm from utils import constraint_cost, calc_time, calc_cost, ConstraintTime, f_ey, f_conv, f_ideal, \ calc_ideal, calc_conv, fit_ey def main_spb(method): """ Проведение расчетов по предложенной методике для аэропорта Пулково. :param method: Метод решения однокритериальной задачи. """ mu1 = [1 / 87, 1 / 30, 1 / 70] n_max1 = np.array([88, 26, 24]) lam1 = 28659.2 / (24 * 60 * 60) p1 = [0.999, 0.999] s_max = 120 s = np.ones(len(mu1)) t_max = 4 * 60 optf = OptimalFinder(n_max1, s_max, t_max, s, [mu1, lam1, p1]) optf.find_optimal_time(method) optf.find_optimal_cost(method) optf.find_optimal_conv(method, [0.8, 0.2]) for metric in ['2-norm', 'inf']: optf.find_optimal_ideal(method, [0.8, 0.2], metric) df = pd.json_normalize(optf.experiments, sep=' узел ').sort_values(['Критерий', 'Метод'], ignore_index=True) # df.index += 1 # df.index.name = 'Номер эксперимента' df = df.round(2) print(df.iloc[:, 2:].to_string(index=False, decimal=',')) def main_svo(method): """ Проведение расчетов по предложенной методике для терминала С аэропорта Шереметьево. :param method: Метод решения однокритериальной задачи. """ mu1 = [1 / 75, 1 / 50, 1 / 70] n_max1 = np.array([84, 60, 20]) lam1 = 67307.5 * 0.12 / (24 * 60 * 60) p1 = [0.999, 0.999] s_max = 40 s = np.ones(len(mu1)) t_max = 2 * 60 optf = OptimalFinder(n_max1, s_max, t_max, s, [mu1, lam1, p1]) optf.find_optimal_time(method) optf.find_optimal_cost(method) optf.find_optimal_conv(method, [0.8, 0.2]) for metric in ['2-norm', 'inf']: optf.find_optimal_ideal(method, [0.8, 0.2], metric) df = pd.json_normalize(optf.experiments, sep=' узел ').sort_values(['Критерий', 'Метод'], ignore_index=True) # df.index += 1 # df.index.name = 'Номер эксперимента' df = df.round(2) print(df.iloc[:, 2:].to_string(index=False, decimal=',')) def main_spb_brute_force(): """ Проведение расчетов с помощью метода полного перебора для аэропорта Пулково. """ mu1 = [1 / 87, 1 / 30, 1 / 70] n_max1 = np.array([88, 26, 24]) lam1 = 28659.2 / (24 * 60 * 60) p1 = [0.999, 0.999] s_max = 120 s = np.ones(len(mu1)) t_max = 4 * 60 optf = OptimalFinder(n_max1, s_max, t_max, s, [mu1, lam1, p1]) n_df = optf.brute_force([0.8, 0.2], [0.8, 0.2]) n_df = n_df.sort_values(['Критерий'], ignore_index=True) n_df = n_df.round(2) print(n_df.iloc[:, 1:].to_string(index=False, decimal=',')) def main_svo_brute_force(): """ Проведение расчетов с помощью метода полного перебора для терминала С аэропорта Шереметьево. """ mu1 = [1 / 75, 1 / 50, 1 / 70] n_max1 = np.array([84, 60, 20]) lam1 = 67307.5 * 0.12 / (24 * 60 * 60) p1 = [0.999, 0.999] s_max = 40 s = np.ones(len(mu1)) t_max = 2 * 60 optf = OptimalFinder(n_max1, s_max, t_max, s, [mu1, lam1, p1]) n_df = optf.brute_force([0.8, 0.2], [0.8, 0.2]) n_df = n_df.sort_values(['Критерий'], ignore_index=True) n_df = n_df.round(2) print(n_df.iloc[:, 1:].to_string(index=False, decimal=',')) def main_synthetic(method, size): """ Проведение расчетов по предложенной методике для синтетического примера. :param method: Метод решения однокритериальной задачи. :param size: Размер сети аэропорта. """ mu1 = [1 / 70] * size n_max1 = np.array([24] * size) lam1 = 7307.5 * 0.12 / (24 * 60 * 60) p1 = [0.999] * (size - 1) s_max = 40 * size s = np.ones(len(mu1)) t_max = 1.5 * 60 * size optf = OptimalFinder(n_max1, s_max, t_max, s, [mu1, lam1, p1]) optf.find_optimal_time(method) optf.find_optimal_cost(method) optf.find_optimal_conv(method, [0.8, 0.2]) for metric in ['2-norm', 'inf']: optf.find_optimal_ideal(method, [0.8, 0.2], metric) df = pd.json_normalize(optf.experiments, sep=' узел ').sort_values(['Критерий', 'Метод'], ignore_index=True) # df.index += 1 # df.index.name = 'Номер эксперимента' df = df.round(2) print(df.iloc[:, 2:].to_string(index=False, decimal=',')) def main_synthetic_brute_force(size): """ Проведение расчетов методом полного перебора для синтетического примера. :param size: Размер сети аэропорта. """ mu1 = [1 / 70] * size n_max1 = np.array([24] * size) lam1 = 7307.5 * 0.12 / (24 * 60 * 60) p1 = [0.999] * (size - 1) s_max = 40 * size s = np.ones(len(mu1)) t_max = 1.5 * 60 * size optf = OptimalFinder(n_max1, s_max, t_max, s, [mu1, lam1, p1]) n_df = optf.brute_force([0.8, 0.2], [0.8, 0.2]) n_df = n_df.sort_values(['Критерий'], ignore_index=True) n_df = n_df.round(2) print(n_df.iloc[:, 1:].to_string(index=False, decimal=','))
[ 11748, 340, 861, 10141, 201, 198, 201, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 201, 198, 11748, 299, 32152, 355, 45941, 201, 198, 11748, 19798, 292, 355, 279, 67, 201, 198, 11748, 7110, 306, 13, 42712, 355, 279, ...
1.649712
3,126
from __future__ import print_function import argparse import random import torch import torch.optim as optim import torch.utils.data from torch.autograd import Variable import numpy as np import os import utils from torch_geometric.data import Data, Dataset,DataLoader from torch_scatter import scatter_mean import torch_geometric.transforms as GT import math import json from model2 import TbNet from dataset2 import ScitsrDataset parser = argparse.ArgumentParser() parser.add_argument('--workers', type=int, help='number of data loading workers', default=8) parser.add_argument('--batchSize', type=int, default=32, help='input batch size') parser.add_argument('--imgH', type=int, default=32, help='the height of the input image to network') parser.add_argument('--imgW', type=int, default=32, help='the width of the input image to network') parser.add_argument('--nh', type=int, default=256, help='size of the lstm hidden state') parser.add_argument('--niter', type=int, default=10, help='number of epochs to train for') parser.add_argument('--lr', type=float, default=0.001, help='learning rate for Critic, default=0.00005') parser.add_argument('--beta1', type=float, default=0.5, help='beta1 for adam. default=0.5') parser.add_argument('--cuda', action='store_true', help='enables cuda') parser.add_argument('--ngpu', type=int, default=0, help='number of GPUs to use') parser.add_argument('--crnn', default='', help="path to crnn (to continue training)") parser.add_argument('--alphabet', type=str, default='0123456789abcdefghijklmnopqrstuvwxyz\'') parser.add_argument('--experiment', default=None, help='Where to store samples and models') parser.add_argument('--displayInterval', type=int, default=20, help='Interval to be displayed') parser.add_argument('--n_test_disp', type=int, default=100, help='Number of samples to display when test') parser.add_argument('--valInterval', type=int, default=1, help='Interval to be displayed') parser.add_argument('--saveInterval', type=int, default=10, help='Interval to be displayed') parser.add_argument('--adam', action='store_true', help='Whether to use adam (default is rmsprop)') parser.add_argument('--adadelta', action='store_true', help='Whether to use adadelta (default is rmsprop)') parser.add_argument('--keep_ratio', action='store_true', help='whether to keep ratio for image resize') parser.add_argument('--random_sample', action='store_true', help='whether to sample the dataset with random sampler') opt = parser.parse_args() #print(opt) if opt.experiment is None: opt.experiment = 'expr' os.system('mkdir {0}'.format(opt.experiment)) opt.manualSeed = random.randint(1, 10000) # fix seed print("Random Seed: ", opt.manualSeed) random.seed(opt.manualSeed) np.random.seed(opt.manualSeed) torch.manual_seed(opt.manualSeed) #cudnn.benchmark = True #if torch.cuda.is_available() and not opt.cuda: # print("WARNING: You have a CUDA device, so you should probably run with --cuda") root_path = '' train_dataset = ScitsrDataset(root_path) root_path = '' test_dataset = ScitsrDataset(root_path) root_path = '/home/deepvision/lyr/out' eval_dataset = ScitsrDataset(root_path) print("samples:",len(train_dataset),len(eval_dataset)) ,len(test_dataset) train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True) #test_loader = DataLoader(ds_test, batch_size=32) #vob=open("./data/arti-images/vocab_fapiao.txt",'r') #opt.alphabet=vob.readline() #converter = utils.strLabelConverter(opt.alphabet) #criterion = CTCLoss() # pytorch 0.4 #criterion = torch.nn.CTCLoss # pytorch 1.0.0 nclass = 2 input_num = 8 vocab_size = 39 num_text_features = 64 print('num of classes:',nclass) # custom weights initialization called on crnn device = torch.device("cpu" ) model = TbNet(input_num,vocab_size,num_text_features,nclass) model.cuda() #for k,v in crnn.state_dict().items(): # print(k) model.apply(weights_init) criterion = torch.nn.NLLLoss() if opt.cuda: model.cuda() criterion = criterion.cuda() # loss averager loss_avg = utils.averager() # setup optimizer if opt.adam: optimizer = optim.Adam(model.parameters(), lr=opt.lr, betas=(opt.beta1, 0.999)) elif opt.adadelta: optimizer = optim.Adadelta(model.parameters(), lr=opt.lr) else: optimizer = optim.RMSprop(model.parameters(), lr=opt.lr) if opt.crnn != '': print('loading pretrained model from %s' % opt.crnn) crnn.load_state_dict(torch.load(opt.crnn),strict=False) # 直接val一下。 print("On SciTSR Test:") val(model, test_dataset, criterion) print("On Eval:") val(model, eval_dataset, criterion) for epoch in range(opt.niter): train_iter = iter(train_loader) i = 0 print('epoch',epoch, ' dataset size:', len(train_loader)) while i < len(train_loader): for p in model.parameters(): p.requires_grad = True model.train() cost = trainBatch(train_iter, model, criterion, optimizer) loss_avg.add(cost) i += 1 #print(loss_avg) if i % opt.displayInterval == 0: print('[%d/%d][%d/%d] Loss: %f' % (epoch, opt.niter, i, len(train_loader), loss_avg.val())) loss_avg.reset() if epoch % opt.valInterval == 0: print("On SciTSR Test:") val(model, test_dataset, criterion) print("On Eval:") val(model, eval_dataset, criterion) # do checkpointing if epoch % opt.saveInterval == 0 : torch.save(model.state_dict(), '{0}/net_{1}_{2}.pth'.format(opt.experiment, epoch, i)) #for k,v in crnn.state_dict().items(): # print(k)
[ 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 11748, 1822, 29572, 198, 11748, 4738, 198, 11748, 28034, 198, 11748, 28034, 13, 40085, 355, 6436, 198, 11748, 28034, 13, 26791, 13, 7890, 198, 6738, 28034, 13, 2306, 519, 6335, 1330, 3...
2.600092
2,163
import sixdegrees import numpy as np import scipy.sparse as sprs from scipy.special import binom import matplotlib.pyplot as pl N_meas = 1000 betas = np.logspace(-3,0,10) k = 8. N = 100 for beta in betas: hist = np.zeros((N,)) for meas in range(N_meas): _, row, col = sixdegrees.modified_small_world_network_coord_lists( N, k, beta, use_giant_component = False, ) A = sprs.csr_matrix((np.ones_like(row),(row,col)), shape=(N,N)) degree = np.asarray(A.sum(axis=1)).reshape((N,)) for k_ in degree: hist[k_] += 1.0 hist /= hist.sum() kmax = (np.where(hist>0)[0]).max() degrees = np.arange(kmax+1,dtype=int) this_plot, = pl.step(degrees,hist[:kmax+1],where='mid') pl.step(degrees,P_theory(N,k,beta,kmax),c=this_plot.get_color(),lw=3, alpha=0.4,linestyle = '--',where='mid') pl.show()
[ 11748, 2237, 13500, 6037, 220, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 629, 541, 88, 13, 82, 29572, 355, 599, 3808, 198, 6738, 629, 541, 88, 13, 20887, 1330, 9874, 296, 220, 198, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487,...
1.964876
484
import pygame, copy from pygame.locals import * ########################################################################## ## Character ## ## -------------------------------------------------------------------- ## ## Class that defines an instance of an on-screen character sprite. Has ## ## various attributes that help optimize drawing routines. ## ########################################################################## ################# ## Constructor ## ################# ###################################### ## Method to draw to target surface ## ######################################
[ 11748, 12972, 6057, 11, 4866, 198, 6738, 12972, 6057, 13, 17946, 874, 1330, 1635, 198, 198, 29113, 29113, 7804, 2235, 198, 2235, 15684, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 2...
3.797814
183
default_json_pool = { "previousState": "Closing", "stateTransitionTime": "2021-03-18T14:34:51Z", "previousStateTransitionTime": "2021-03-18T14:34:39Z", "lastModified": "2021-03-18T14:34:51Z", "elasticProperty": { "isElastic": False, "minTotalSlots": 1, "maxTotalSlots": 1, "minIdleSlots": 0, "resizePeriod": 180, "rampResizeFactor": 0.8, "minIdleTimeSeconds": 30 }, "preparationTask": None, "constants": [ ], "tags": [ ], "errors": [ { "code": "GHX0782I", "message": "The task was cancelled: The task was cancelled", "debug": None } ], "resourceBuckets": [ ], "advancedResourceBuckets": None, "status": { "timestamp": "0001-01-01T00:00:00Z", "lastUpdateTimestamp": "0001-01-01T00:00:00Z", "downloadProgress": 0, "executionProgress": 100, "uploadProgress": 0, "instanceCount": 0, "downloadTime": "00:00:00", "downloadTimeSec": 0, "environmentTime": "00:00:00", "environmentTimeSec": 0, "executionTime": "00:00:00", "executionTimeSec": 0, "executionTimeByCpuModel": [ ], "executionTimeGhzByCpuModel": [ ], "uploadTime": "00:00:00", "uploadTimeSec": 0, "wallTime": "00:00:15", "wallTimeSec": 15, "succeededRange": "", "executedRange": "0", "failedRange": "0", "startedOnceRange": "", "runningInstancesInfo": { "perRunningInstanceInfo": [ ], "snapshotResults": [ ], "timestamp": "0001-01-01T00:00:00Z", "averageFrequencyGHz": 0, "maxFrequencyGHz": 0, "minFrequencyGHz": 0, "averageMaxFrequencyGHz": 0, "averageCpuUsage": 0, "clusterPowerIndicator": 1, "averageMemoryUsage": 0, "averageNetworkInKbps": 0, "averageNetworkOutKbps": 0, "totalNetworkInKbps": 0, "totalNetworkOutKbps": 0, "runningCoreCountByCpuModel": [ ] } }, "autoDeleteOnCompletion": False, "completionTimeToLive": "00:00:00", "uuid": "6dce9bff-20f0-4909-9ba5-4abe2326a07c", "name": "hello", "shortname": "6dce9bff-20f0-4909-9ba5-4abe2326a07c", "profile": "docker-batch", "state": "Closed", "instanceCount": 1, "creationDate": "2021-03-18T14:34:34Z", "endDate": "2021-03-18T14:34:51Z", "runningInstanceCount": 0, "runningCoreCount": 0, "executionTime": "00:00:00", "wallTime": "00:00:15", "taskDefaultWaitForPoolResourcesSynchronization": None, "credits": 0.01 }
[ 198, 12286, 62, 17752, 62, 7742, 796, 1391, 198, 220, 220, 220, 366, 3866, 1442, 9012, 1298, 220, 366, 2601, 2752, 1600, 198, 220, 220, 220, 366, 5219, 8291, 653, 7575, 1298, 220, 366, 1238, 2481, 12, 3070, 12, 1507, 51, 1415, 25, ...
1.869622
1,534
import unittest from gocdapi.go import Go from gocdapi.pipeline import Pipeline from gocdapi.stage import Stage if __name__ == '__main__': unittest.main()
[ 11748, 555, 715, 395, 198, 198, 6738, 308, 420, 67, 15042, 13, 2188, 1330, 1514, 198, 6738, 308, 420, 67, 15042, 13, 79, 541, 4470, 1330, 37709, 198, 6738, 308, 420, 67, 15042, 13, 14247, 1330, 15371, 628, 198, 198, 361, 11593, 3672...
2.672131
61
# -*- coding: utf-8 -*- """ Created on Mon Jan 4 16:39:41 2021 This will be used to query an FTP server to download csv data from the sensors of interest. @author: sHristov """ import os import time import datetime import logging import gzip import typing import urllib.error import urllib.request import requests import bs4 import numpy as np import pandas as pd def daterange(start_date: datetime.datetime, end_date: datetime.datetime) -> typing.Iterable[datetime.datetime]: """ Function to create a range given start and end dates. Acknowledgment: https://stackoverflow.com/questions/1060279/iterating-through-a-range-of-dates-in-python """ for n in range(int((end_date - start_date).days)): yield start_date + datetime.timedelta(n) def download_data(sensor_name: str, sensor_id: str, start_date = datetime.date(2020, 4, 1)) -> None: """ Function to download data from the sensor.community server and puts it in a data folder. Args: sensor_name - name of sensor sensor_id - id of sensor Returns: None """ folder_main = os.getcwd() data_folder = folder_main + os.sep + 'data' + os.sep try: os.mkdir(data_folder) except FileExistsError: pass # Get data until yesterday - the server is only updated at 00:00 GMT end_date = datetime.date.today() - datetime.timedelta(days=1) for single_date in daterange(start_date, end_date): print('Downloading: ' + str(single_date)) filename = "%s_%s_sensor_%s.csv" % (str(single_date), sensor_name, sensor_id) save_name = os.path.join(data_folder, filename) if os.path.exists(save_name): logging.debug(f"{save_name} exists, skipping file") else: logging.debug("Trying to download...") time.sleep(1) url = 'https://archive.sensor.community/%s/%s' % (str(single_date), filename) req = requests.get(url) url_content = req.content with open(save_name, 'wb') as csv_file: csv_file.write(url_content) csv_file.close() if __name__ == '__main__': # code below is used for testing purposes sensor_name = 'sds011' sensor_id = '6127' """ raise HTTPError (urllib.error.HTTPError) if data does not exist""" download_data(sensor_name=sensor_name, sensor_id=sensor_id)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 201, 198, 37811, 201, 198, 41972, 319, 2892, 2365, 220, 604, 1467, 25, 2670, 25, 3901, 33448, 201, 198, 201, 198, 1212, 481, 307, 973, 284, 12405, 281, 45854, 4382, 284, 43...
2.288058
1,097
#!/bin/env python3 import time import gex with gex.Client(gex.TrxRawUSB()) as client: ow = gex.OneWire(client, 'ow') # print("Presence: ", ow.test_presence()) print("Devices:", ow.search()) while True: (a, b) = meas2(6558392391241695016, 1802309978572980008) # a = meas(6558392391241695016) # b = meas(1802309978572980008) print("in: %.2f °C, out: %f °C" % (a, b)) # # search the bus for alarm # if False: # ow = gex.OneWire(client, 'ow') # print("Presence: ", ow.test_presence()) # print("Devices w alarm:", ow.search(alarm=True)) # # # simple 1w check # if False: # ow = gex.OneWire(client, 'ow') # print("Presence: ", ow.test_presence()) # print("ROM: 0x%016x" % ow.read_address()) # print("Scratch:", ow.query([0xBE], rcount=9, addr=0x7100080104c77610, as_array=True)) # # # testing ds1820 temp meas without polling # if False: # ow = gex.OneWire(client, 'ow') # print("Presence: ", ow.test_presence()) # print("Starting measure...") # ow.write([0x44]) # time.sleep(1) # print("Scratch:", ow.query([0xBE], 9)) # # # testing ds1820 temp meas with polling # if False: # ow = gex.OneWire(client, 'ow') # print("Presence: ", ow.test_presence()) # print("Starting measure...") # ow.write([0x44]) # ow.wait_ready() # data = ow.query([0xBE], 9) # # pp = gex.PayloadParser(data) # # temp = pp.i16()/2.0 # th = pp.i8() # tl = pp.i8() # reserved = pp.i16() # remain = float(pp.u8()) # perc = float(pp.u8()) # # realtemp = temp - 0.25+(perc-remain)/perc # print("Temperature = %f °C (th %d, tl %d)" % (realtemp, th, tl))
[ 2, 48443, 8800, 14, 24330, 21015, 18, 198, 11748, 640, 198, 198, 11748, 308, 1069, 198, 198, 4480, 308, 1069, 13, 11792, 7, 25636, 13, 2898, 87, 27369, 27155, 28955, 355, 5456, 25, 198, 220, 220, 220, 12334, 796, 308, 1069, 13, 3198...
2.006515
921
#coding:utf-8 # # id: bugs.core_5018 # title: Regression: Non-indexed predicates may not be applied immediately after retrieval when tables are being joined # decription: # tracker_id: CORE-5018 # min_versions: ['3.0'] # versions: 3.0 # qmid: None import pytest from firebird.qa import db_factory, isql_act, Action # version: 3.0 # resources: None substitutions_1 = [] init_script_1 = """""" db_1 = db_factory(from_backup='mon-stat-gathering-3_0.fbk', init=init_script_1) test_script_1 = """ recreate table zf ( id int primary key, kont_id int not null ); recreate table u ( id int primary key, kont_id int not null ); recreate table k ( id int primary key ); commit; insert into zf (id, kont_id) values ('1', '1'); insert into zf (id, kont_id) values ('2', '7'); insert into zf (id, kont_id) values ('3', '3'); insert into zf (id, kont_id) values ('4', '5'); insert into zf (id, kont_id) values ('5', '5'); insert into zf (id, kont_id) values ('6', '1'); insert into zf (id, kont_id) values ('7', '4'); insert into zf (id, kont_id) values ('8', '2'); insert into zf (id, kont_id) values ('9', '9'); insert into zf (id, kont_id) values ('10', '1'); insert into k (id) values ('1'); insert into k (id) values ('2'); insert into k (id) values ('3'); insert into k (id) values ('4'); insert into k (id) values ('5'); insert into k (id) values ('6'); insert into k (id) values ('7'); insert into k (id) values ('8'); insert into k (id) values ('9'); insert into k (id) values ('10'); insert into u (id, kont_id) values ('1', '4'); insert into u (id, kont_id) values ('2', '6'); insert into u (id, kont_id) values ('3', '3'); insert into u (id, kont_id) values ('4', '2'); insert into u (id, kont_id) values ('5', '5'); insert into u (id, kont_id) values ('6', '2'); insert into u (id, kont_id) values ('7', '9'); insert into u (id, kont_id) values ('8', '2'); insert into u (id, kont_id) values ('9', '10'); insert into u (id, kont_id) values ('10', '1'); commit; execute procedure sp_truncate_stat; commit; execute procedure sp_gather_stat; commit; set term ^; execute block as declare c int; begin select count(*) from zf inner join u on zf.id=u.id left join k kzf on zf.kont_id=kzf.id left join k kum on u.kont_id=kum.id where zf.kont_id<>u.kont_id into c; if ( rdb$get_context('SYSTEM','ENGINE_VERSION') starting with '4.0' ) then rdb$set_context('USER_SESSION', 'MAX_IDX_READS', '45'); -- 27.07.2016 else rdb$set_context('USER_SESSION', 'MAX_IDX_READS', '30'); -- ^ -- | -- ### T H R E S H O L D ###-------+ end ^ set term ;^ execute procedure sp_gather_stat; commit; set list on; select iif( indexed_reads <= c_max_idx_reads, 'ACCEPTABLE', 'FAILED, TOO BIG: ' || indexed_reads || ' > ' || c_max_idx_reads ) as idx_reads_estimation from ( select indexed_reads, cast(rdb$get_context('USER_SESSION', 'MAX_IDX_READS') as int) as c_max_idx_reads from v_agg_stat_main ); -- WI-V2.5.5.26952 IR=22 -- WI-V3.0.0.32140 IR=33 -- WI-V3.0.0.32179 IR=25 -- WI-T4.0.0.313: IR=39 """ act_1 = isql_act('db_1', test_script_1, substitutions=substitutions_1) expected_stdout_1 = """ IDX_READS_ESTIMATION ACCEPTABLE """ @pytest.mark.version('>=3.0')
[ 2, 66, 7656, 25, 40477, 12, 23, 198, 2, 198, 2, 4686, 25, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 11316, 13, 7295, 62, 20, 29159, 198, 2, 3670, 25, 220, 220, 220, 220, 220, 220, 220, 3310, 2234, 25, 8504, 12, 9630, ...
2.090508
1,812
from torch import random import torch from torch.nn.modules import linear import torch.optim as optim import torch.nn.functional as F from torch.nn.utils import clip_grad_norm_ import logging import numpy as np import random from value_network import ValueNetwork, ConvValueNetwork
[ 6738, 28034, 1330, 4738, 198, 11748, 28034, 198, 6738, 28034, 13, 20471, 13, 18170, 1330, 14174, 198, 11748, 28034, 13, 40085, 355, 6436, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 198, 6738, 28034, 13, 20471, 13, 26791, 1330, 1...
3.944444
72
from sky_iot.utils import UtilsTool _init() read_config()
[ 6738, 6766, 62, 5151, 13, 26791, 1330, 7273, 4487, 25391, 198, 198, 62, 15003, 3419, 198, 198, 961, 62, 11250, 3419 ]
2.809524
21
#!/usr/bin/python import sys,subprocess #user and group id id=171 if len(sys.argv) == 2: if sys.argv[1] == "create-glint-user": create_group() add_user() elif sys.argv[1] == "remove-glint-user": remove_user() #remove_group() else: show_usage() else: show_usage()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 198, 11748, 25064, 11, 7266, 14681, 198, 2, 7220, 290, 1448, 4686, 198, 312, 28, 27192, 198, 198, 361, 18896, 7, 17597, 13, 853, 85, 8, 6624, 362, 25, 198, 220, 220, 220, 611, 25064, 13, ...
2.018868
159
from django.apps import apps from django.test import TestCase from model_bakery import baker from rest_framework import serializers from api.serializers.common import MappedSerializerMixin from api.serializers.registration import UserSerializer from common.constants import models Profile = apps.get_model(models.PROFILE_MODEL)
[ 6738, 42625, 14208, 13, 18211, 1330, 6725, 198, 6738, 42625, 14208, 13, 9288, 1330, 6208, 20448, 198, 6738, 2746, 62, 65, 33684, 1330, 46412, 198, 6738, 1334, 62, 30604, 1330, 11389, 11341, 198, 198, 6738, 40391, 13, 46911, 11341, 13, 1...
3.761364
88
import os import pickle def var_to_pickle(var, filename): ''' Writes the given variable to a pickle file Args: var (any): variable to be written to pickle file filename (str): path and filename of pickle file Returns: None ''' try: with open(filename, 'wb') as f: pickle.dump(var, f) except: print(f'Failed to save pickle to \'{filename}\'') return def read_pickle(filename): ''' Reads the given pickle file Args: filename (str): path and filename of pickle file Returns: any: contents of pickle file if it exists, None if not ''' output = None if os.path.exists(filename): try: with open(filename, 'rb') as f: output = pickle.load(f) except: print(f'Failed to load pickle from \'{filename}\'') return output
[ 11748, 28686, 198, 11748, 2298, 293, 628, 198, 4299, 1401, 62, 1462, 62, 27729, 293, 7, 7785, 11, 29472, 2599, 198, 220, 220, 220, 705, 7061, 198, 220, 220, 220, 12257, 274, 262, 1813, 7885, 284, 257, 2298, 293, 2393, 628, 220, 220,...
2.254364
401
from dbgen import Model from . import schema # noqa: F401 from .generators import add_generators
[ 6738, 20613, 5235, 1330, 9104, 198, 6738, 764, 1330, 32815, 220, 1303, 645, 20402, 25, 376, 21844, 198, 6738, 764, 8612, 2024, 1330, 751, 62, 8612, 2024, 628 ]
3.535714
28
import bisect import collections import functools import math import operator try: import graphviz GRAPHVIZ_INSTALLED = True except ImportError: GRAPHVIZ_INSTALLED = False from .. import base from .. import utils from . import enum def find_best_split(class_counts, feature_counts, split_enum): """ >>> class_counts = {'slow': 2, 'fast': 2} >>> feature_counts = { ... 'grade': { ... 'steep': collections.Counter({'slow': 2, 'fast': 1}), ... 'flat': collections.Counter({'fast': 1}) ... }, ... 'bumpiness': { ... 'bumpy': collections.Counter({'slow': 1, 'fast': 1}), ... 'smooth': collections.Counter({'slow': 1, 'fast': 1}) ... }, ... 'speed_limit': { ... 'yes': collections.Counter({'slow': 2}), ... 'no': collections.Counter({'fast': 2}) ... } ... } >>> split_enum = enum.UnaryEnumerator() >>> find_best_split(class_counts, feature_counts, split_enum) (1.0, 0.311278..., 'speed_limit', ['no']) """ best_gain = -math.inf second_best_gain = -math.inf best_feature = None best_values = None current_entropy = utils.entropy(class_counts) for feature, counts in feature_counts.items(): for left, right in split_enum(sorted(counts.keys())): left_counts = sum_counters(counts[v] for v in left) right_counts = sum_counters(counts[v] for v in right) left_total = sum(left_counts.values()) right_total = sum(right_counts.values()) entropy = left_total * utils.entropy(left_counts) + \ right_total * utils.entropy(right_counts) entropy /= (left_total + right_total) gain = current_entropy - entropy if gain > best_gain: best_gain, second_best_gain = gain, best_gain best_feature = feature best_values = left elif gain > second_best_gain and gain != best_gain: second_best_gain = gain return best_gain, second_best_gain, best_feature, best_values class DecisionTreeClassifier(base.MultiClassifier): """ Parameters: max_bins (int): Maximum number of bins used for discretizing continuous values when using `utils.Histogram`. Attributes: histograms (collections.defaultdict) """ def to_dot(self): """Returns a GraphViz representation of the decision tree.""" if not GRAPHVIZ_INSTALLED: raise RuntimeError('graphviz is not installed') dot = graphviz.Digraph() add_node(self.root, '0') return dot
[ 11748, 47457, 478, 198, 11748, 17268, 198, 11748, 1257, 310, 10141, 198, 11748, 10688, 198, 11748, 10088, 198, 198, 28311, 25, 198, 220, 220, 220, 1330, 4823, 85, 528, 198, 220, 220, 220, 10863, 31300, 12861, 57, 62, 38604, 7036, 1961, ...
2.298723
1,175
from influxdb import InfluxDBClient import json import config import blegateway influxCONFIG = config.get_config('influx') ids = config.get_config('identifiers')
[ 6738, 25065, 9945, 1330, 4806, 22564, 11012, 11792, 198, 11748, 33918, 198, 11748, 4566, 198, 11748, 275, 34637, 1014, 198, 198, 10745, 22564, 10943, 16254, 796, 4566, 13, 1136, 62, 11250, 10786, 10745, 22564, 11537, 198, 2340, 796, 4566, ...
3.446809
47
"""The data models used in ARL: .. note:: There are two visibility formats: :class:`BlockVisibility` is conceived as an ingest and calibration format. The visibility data are kept in a block of shape (number antennas, number antennas, number channels, number polarisation). One block is kept per integration. The other columns are time and uvw. The sampling in time is therefore the same for all baselines. :class:`Visibility` is designed to hold coalesced data where the integration time and channel width can vary with baseline length. The visibility data are kept in a visibility vector of length equal to the number of polarisations. Everything else is a separate column: time, frequency, uvw, channel_bandwidth, integration time. """ import sys import logging from copy import deepcopy from typing import Union import numpy from astropy import units as u from astropy.coordinates import SkyCoord import warnings from astropy.wcs import FITSFixedWarning warnings.simplefilter('ignore', FITSFixedWarning) from data_models.polarisation import PolarisationFrame, ReceptorFrame log = logging.getLogger(__name__) class Configuration: """ Describe a Configuration as locations in x,y,z, mount type, diameter, names, and overall location """ def __init__(self, name='', data=None, location=None, names="%s", xyz=None, mount="alt-az", frame=None, receptor_frame=ReceptorFrame("linear"), diameter=None): """Configuration object describing data for processing :param name: :param data: :param location: :param names: :param xyz: :param mount: :param frame: :param receptor_frame: :param diameter: """ if data is None and xyz is not None: desc = [('names', '>U6'), ('xyz', '>f8', (3,)), ('diameter', '>f8'), ('mount', '>U5')] nants = xyz.shape[0] if isinstance(names, str): names = [names % ant for ant in range(nants)] if isinstance(mount, str): mount = numpy.repeat(mount, nants) data = numpy.zeros(shape=[nants], dtype=desc) data['names'] = names data['xyz'] = xyz data['mount'] = mount data['diameter'] = diameter self.name = name self.data = data self.location = location self.frame = frame self.receptor_frame = receptor_frame def __str__(self): """Default printer for Skycomponent """ s = "Configuration:\n" s += "\nName: %s\n" % self.name s += "\tNumber of antennas/stations: %s\n" % len(self.names) s += "\tNames: %s\n" % self.names s += "\tDiameter: %s\n" % self.diameter s += "\tMount: %s\n" % self.mount s += "\tXYZ: %s\n" % self.xyz return s def size(self): """ Return size in GB """ size = 0 size += self.data.size * sys.getsizeof(self.data) return size / 1024.0 / 1024.0 / 1024.0 @property def names(self): """ Names of the antennas/stations""" return self.data['names'] @property def diameter(self): """ diameter of antennas/stations """ return self.data['diameter'] @property def xyz(self): """ XYZ locations of antennas/stations """ return self.data['xyz'] @property def mount(self): """ Mount type """ return self.data['mount'] class GainTable: """ Gain table with data_models: time, antenna, gain[:, chan, rec, rec], weight columns The weight is usually that output from gain solvers. """ def __init__(self, data=None, gain: numpy.array = None, time: numpy.array = None, interval=None, weight: numpy.array = None, residual: numpy.array = None, frequency: numpy.array = None, receptor_frame: ReceptorFrame = ReceptorFrame("linear")): """ Create a gaintable from arrays The definition of gain is: Vobs = g_i g_j^* Vmodel :param interval: :param data: :param gain: [:, nchan, nrec, nrec] :param time: Centroid of solution :param interval: Interval of validity :param weight: :param residual: :param frequency: :param receptor_frame: :return: Gaintable """ if data is None and gain is not None: nrec = receptor_frame.nrec nrows = gain.shape[0] nants = gain.shape[1] nchan = gain.shape[2] assert len(frequency) == nchan, "Discrepancy in frequency channels" desc = [('gain', '>c16', (nants, nchan, nrec, nrec)), ('weight', '>f8', (nants, nchan, nrec, nrec)), ('residual', '>f8', (nchan, nrec, nrec)), ('time', '>f8'), ('interval', '>f8')] data = numpy.zeros(shape=[nrows], dtype=desc) data['gain'] = gain data['weight'] = weight data['time'] = time data['interval'] = interval data['residual'] = residual self.data = data self.frequency = frequency self.receptor_frame = receptor_frame def size(self): """ Return size in GB """ size = 0 size += self.data.size * sys.getsizeof(self.data) return size / 1024.0 / 1024.0 / 1024.0 @property @property @property @property @property @property @property @property @property def __str__(self): """Default printer for GainTable """ s = "GainTable:\n" s += "\tTimes: %s\n" % str(self.ntimes) s += "\tData shape: %s\n" % str(self.data.shape) s += "\tReceptor frame: %s\n" % str(self.receptor_frame.type) return s class Image: """Image class with Image data (as a numpy.array) and the AstroPy `implementation of a World Coodinate System <http://docs.astropy.org/en/stable/wcs>`_ Many operations can be done conveniently using numpy processing_library on Image.data_models. Most of the imaging processing_library require an image in canonical format: - 4 axes: RA, DEC, POL, FREQ The conventions for indexing in WCS and numpy are opposite. - In astropy.wcs, the order is (longitude, latitude, polarisation, frequency) - in numpy, the order is (frequency, polarisation, latitude, longitude) .. warning:: The polarisation_frame is kept in two places, the WCS and the polarisation_frame variable. The latter should be considered definitive. """ def __init__(self): """ Empty image """ self.data = None self.wcs = None self.polarisation_frame = None def size(self): """ Return size in GB """ size = 0 size += self.data.nbytes return size / 1024.0 / 1024.0 / 1024.0 # noinspection PyArgumentList @property @property @property @property @property @property @property def __str__(self): """Default printer for Image """ s = "Image:\n" s += "\tShape: %s\n" % str(self.data.shape) s += "\tWCS: %s\n" % self.wcs s += "\tPolarisation frame: %s\n" % str(self.polarisation_frame.type) return s class GridData: """Class to hold Gridded data for Fourier processing - Has four or more coordinates: [chan, pol, z, y, x] where x can be u, l; y can be v, m; z can be w, n The conventions for indexing in WCS and numpy are opposite. - In astropy.wcs, the order is (longitude, latitude, polarisation, frequency) - in numpy, the order is (frequency, polarisation, depth, latitude, longitude) .. warning:: The polarisation_frame is kept in two places, the WCS and the polarisation_frame variable. The latter should be considered definitive. """ def __init__(self): """ Empty image """ self.data = None self.grid_wcs = None self.projection_wcs = None self.polarisation_frame = None def size(self): """ Return size in GB """ size = 0 size += self.data.nbytes return size / 1024.0 / 1024.0 / 1024.0 # noinspection PyArgumentList @property @property @property @property @property @property @property @property def __str__(self): """Default printer for GriddedData """ s = "Gridded data:\n" s += "\tShape: %s\n" % str(self.data.shape) s += "\tGrid WCS: %s\n" % self.grid_wcs s += "\tProjection WCS: %s\n" % self.projection_wcs s += "\tPolarisation frame: %s\n" % str(self.polarisation_frame.type) return s class ConvolutionFunction: """Class to hold Gridded data for Fourier processing - Has four or more coordinates: [chan, pol, z, y, x] where x can be u, l; y can be v, m; z can be w, n The conventions for indexing in WCS and numpy are opposite. - In astropy.wcs, the order is (longitude, latitude, polarisation, frequency) - in numpy, the order is (frequency, polarisation, depth, latitude, longitude) .. warning:: The polarisation_frame is kept in two places, the WCS and the polarisation_frame variable. The latter should be considered definitive. """ def __init__(self): """ Empty image """ self.data = None self.grid_wcs = None self.projection_wcs = None self.polarisation_frame = None def size(self): """ Return size in GB """ size = 0 size += self.data.nbytes return size / 1024.0 / 1024.0 / 1024.0 # noinspection PyArgumentList @property @property @property @property @property @property @property @property def __str__(self): """Default printer for GriddedData """ s = "Convolution function:\n" s += "\tShape: %s\n" % str(self.data.shape) s += "\tGrid WCS: %s\n" % self.grid_wcs s += "\tProjection WCS: %s\n" % self.projection_wcs s += "\tPolarisation frame: %s\n" % str(self.polarisation_frame.type) return s class Skycomponent: """Skycomponents are used to represent compact sources on the sky. They possess direction, flux as a function of frequency and polarisation, shape (with params), and polarisation frame. For example, the following creates and predicts the visibility from a collection of point sources drawn from the GLEAM catalog:: sc = create_low_test_skycomponents_from_gleam(flux_limit=1.0, polarisation_frame=PolarisationFrame("stokesIQUV"), frequency=frequency, kind='cubic', phasecentre=phasecentre, radius=0.1) model = create_image_from_visibility(vis, cellsize=0.001, npixel=512, frequency=frequency, polarisation_frame=PolarisationFrame('stokesIQUV')) bm = create_low_test_beam(model=model) sc = apply_beam_to_skycomponent(sc, bm) vis = predict_skycomponent_visibility(vis, sc) """ def __init__(self, direction=None, frequency=None, name=None, flux=None, shape='Point', polarisation_frame=PolarisationFrame('stokesIQUV'), params=None): """ Define the required structure :param direction: SkyCoord :param frequency: numpy.array [nchan] :param name: user friendly name :param flux: numpy.array [nchan, npol] :param shape: str e.g. 'Point' 'Gaussian' :param params: numpy.array shape dependent parameters :param polarisation_frame: Polarisation_frame """ self.direction = direction self.frequency = numpy.array(frequency) self.name = name self.flux = numpy.array(flux) self.shape = shape if params is None: params = {} self.params = params self.polarisation_frame = polarisation_frame assert len(self.frequency.shape) == 1, frequency assert len(self.flux.shape) == 2, flux assert self.frequency.shape[0] == self.flux.shape[0], \ "Frequency shape %s, flux shape %s" % (self.frequency.shape, self.flux.shape) assert polarisation_frame.npol == self.flux.shape[1], \ "Polarisation is %s, flux shape %s" % (polarisation_frame.type, self.flux.shape) @property @property def __str__(self): """Default printer for Skycomponent """ s = "Skycomponent:\n" s += "\tName: %s\n" % self.name s += "\tFlux: %s\n" % self.flux s += "\tFrequency: %s\n" % self.frequency s += "\tDirection: %s\n" % self.direction s += "\tShape: %s\n" % self.shape s += "\tParams: %s\n" % self.params s += "\tPolarisation frame: %s\n" % str(self.polarisation_frame.type) return s class SkyModel: """ A model for the sky """ def __init__(self, images=None, components=None, fixed=False): """ A model of the sky as a list of images and a list of components Use copy_skymodel to make a proper copy of skymodel """ if images is None: images = [] if components is None: components = [] self.images = [im for im in images] self.components = [sc for sc in components] self.fixed = fixed def __str__(self): """Default printer for SkyModel """ s = "SkyModel: fixed: %s\n" % self.fixed for i, sc in enumerate(self.components): s += str(sc) s += "\n" for i, im in enumerate(self.images): s += str(im) s += "\n" return s class Visibility: """ Visibility table class Visibility with uvw, time, integration_time, frequency, channel_bandwidth, a1, a2, vis, weight as separate columns in a numpy structured array, The fundemental unit is a complex vector of polarisation. Visibility is defined to hold an observation with one direction. Polarisation frame is the same for the entire data set and can be stokes, circular, linear The configuration is also an attribute The phasecentre is the direct of delay tracking i.e. n=0. If uvw are rotated then this should be updated with the new delay tracking centre. This is important for wstack and wproject algorithms. If a visibility is created by coalescence then the cindex column is filled with a pointer to the row in the original block visibility that this row has a value for. The original blockvisibility is also preserves as n attribute so that decoalescence is expedited. If you don't need that then the storage can be released by setting self.blockvis to None """ def __init__(self, data=None, frequency=None, channel_bandwidth=None, phasecentre=None, configuration=None, uvw=None, time=None, antenna1=None, antenna2=None, vis=None, weight=None, imaging_weight=None, integration_time=None, polarisation_frame=PolarisationFrame('stokesI'), cindex=None, blockvis=None): """Visibility :param data: :param frequency: :param channel_bandwidth: :param phasecentre: :param configuration: :param uvw: :param time: :param antenna1: :param antenna2: :param vis: :param weight: :param imaging_weight: :param integration_time: :param polarisation_frame: :param cindex: :param blockvis: """ if data is None and vis is not None: if imaging_weight is None: imaging_weight = weight nvis = vis.shape[0] assert len(time) == nvis assert len(frequency) == nvis assert len(channel_bandwidth) == nvis assert len(antenna1) == nvis assert len(antenna2) == nvis npol = polarisation_frame.npol desc = [('index', '>i8'), ('uvw', '>f8', (3,)), ('time', '>f8'), ('frequency', '>f8'), ('channel_bandwidth', '>f8'), ('integration_time', '>f8'), ('antenna1', '>i8'), ('antenna2', '>i8'), ('vis', '>c16', (npol,)), ('weight', '>f8', (npol,)), ('imaging_weight', '>f8', (npol,))] data = numpy.zeros(shape=[nvis], dtype=desc) data['index'] = list(range(nvis)) data['uvw'] = uvw data['time'] = time data['frequency'] = frequency data['channel_bandwidth'] = channel_bandwidth data['integration_time'] = integration_time data['antenna1'] = antenna1 data['antenna2'] = antenna2 data['vis'] = vis data['weight'] = weight data['imaging_weight'] = imaging_weight self.data = data # numpy structured array self.cindex = cindex self.blockvis = blockvis self.phasecentre = phasecentre # Phase centre of observation self.configuration = configuration # Antenna/station configuration self.polarisation_frame = polarisation_frame self.frequency_map = None def __str__(self): """Default printer for Skycomponent """ ufrequency = numpy.unique(self.frequency) s = "Visibility:\n" s += "\tNumber of visibilities: %s\n" % self.nvis s += "\tNumber of channels: %d\n" % len(ufrequency) s += "\tFrequency: %s\n" % ufrequency s += "\tNumber of polarisations: %s\n" % self.npol s += "\tVisibility shape: %s\n" % str(self.vis.shape) s += "\tPolarisation Frame: %s\n" % self.polarisation_frame.type s += "\tPhasecentre: %s\n" % self.phasecentre s += "\tConfiguration: %s\n" % self.configuration.name return s def size(self): """ Return size in GB """ size = 0 for col in self.data.dtype.fields.keys(): size += self.data[col].nbytes return size / 1024.0 / 1024.0 / 1024.0 @property @property @property @property @property @property @property @property @property @property @property @property @property @property @property @property class BlockVisibility: """ Block Visibility table class BlockVisibility with uvw, time, integration_time, frequency, channel_bandwidth, pol, a1, a2, vis, weight Columns in a numpy structured array. BlockVisibility is defined to hold an observation with one direction. The phasecentre is the direct of delay tracking i.e. n=0. If uvw are rotated then this should be updated with the new delay tracking centre. This is important for wstack and wproject algorithms. Polarisation frame is the same for the entire data set and can be stokesI, circular, linear The configuration is also an attribute """ def __init__(self, data=None, frequency=None, channel_bandwidth=None, phasecentre=None, configuration=None, uvw=None, time=None, vis=None, weight=None, integration_time=None, polarisation_frame=PolarisationFrame('stokesI'), imaging_weight=None): """BlockVisibility :param data: :param frequency: :param channel_bandwidth: :param phasecentre: :param configuration: :param uvw: :param time: :param vis: :param weight: :param integration_time: :param polarisation_frame: """ if data is None and vis is not None: ntimes, nants, _, nchan, npol = vis.shape assert vis.shape == weight.shape assert len(frequency) == nchan assert len(channel_bandwidth) == nchan desc = [('index', '>i8'), ('uvw', '>f8', (nants, nants, 3)), ('time', '>f8'), ('integration_time', '>f8'), ('vis', '>c16', (nants, nants, nchan, npol)), ('weight', '>f8', (nants, nants, nchan, npol)), ('imaging_weight', '>f8', (nants, nants, nchan, npol))] data = numpy.zeros(shape=[ntimes], dtype=desc) data['index'] = list(range(ntimes)) data['uvw'] = uvw data['time'] = time data['integration_time'] = integration_time data['vis'] = vis data['weight'] = weight data['imaging_weight'] = imaging_weight self.data = data # numpy structured array self.frequency = frequency self.channel_bandwidth = channel_bandwidth self.phasecentre = phasecentre # Phase centre of observation self.configuration = configuration # Antenna/station configuration self.polarisation_frame = polarisation_frame def __str__(self): """Default printer for BlockVisibility """ s = "BlockVisibility:\n" s += "\tNumber of visibilities: %s\n" % self.nvis s += "\tNumber of integrations: %s\n" % len(self.time) s += "\tVisibility shape: %s\n" % str(self.vis.shape) s += "\tNumber of channels: %d\n" % len(self.frequency) s += "\tFrequency: %s\n" % self.frequency s += "\tNumber of polarisations: %s\n" % self.npol s += "\tPolarisation Frame: %s\n" % self.polarisation_frame.type s += "\tPhasecentre: %s\n" % self.phasecentre s += "\tConfiguration: %s\n" % self.configuration.name return s def size(self): """ Return size in GB """ size = 0 for col in self.data.dtype.fields.keys(): size += self.data[col].nbytes return size / 1024.0 / 1024.0 / 1024.0 @property @property @property @property @property @property @property @property @property @property @property @property @property class QA: """ Quality assessment """ def __init__(self, origin=None, data=None, context=None): """QA :param origin: :param data: :param context: """ self.origin = origin # Name of function originating QA assessment self.data = data # Dictionary containing standard fields self.context = context # Context string def __str__(self): """Default printer for QA """ s = "Quality assessment:\n" s += "\tOrigin: %s\n" % self.origin s += "\tContext: %s\n" % self.context s += "\tData:\n" for dataname in self.data.keys(): s += "\t\t%s: %r\n" % (dataname, str(self.data[dataname])) return s class ScienceDataModel: """ Science Data Model""" def __str__(self): """ Deflaut printer for Science Data Model :return: """ return "" def assert_same_chan_pol(o1, o2): """ Assert that two entities indexed over channels and polarisations have the same number of them. """ assert o1.npol == o2.npol, \ "%s and %s have different number of polarisations: %d != %d" % \ (type(o1).__name__, type(o2).__name__, o1.npol, o2.npol) if isinstance(o1, BlockVisibility) and isinstance(o2, BlockVisibility): assert o1.nchan == o2.nchan, \ "%s and %s have different number of channels: %d != %d" % \ (type(o1).__name__, type(o2).__name__, o1.nchan, o2.nchan) def assert_vis_gt_compatible(vis: Union[Visibility, BlockVisibility], gt: GainTable): """ Check if visibility and gaintable are compatible :param vis: :param gt: :return: """ assert vis.nchan == gt.nchan assert vis.npol == gt.nrec * gt.nrec
[ 37811, 464, 1366, 4981, 973, 287, 5923, 43, 25, 198, 198, 492, 3465, 3712, 198, 220, 220, 220, 1318, 389, 734, 20742, 17519, 25, 628, 220, 220, 220, 1058, 4871, 25, 63, 12235, 15854, 2247, 63, 318, 21581, 355, 281, 26151, 290, 36537...
2.200369
11,394
#tk13.pyw import tkinter as tk root = tk.Tk() root.geometry('300x200') lb = tk.Label(text='This is a Label,This is a label,This is a Label') ms = tk.Label(text='This is a Message.This is a a Message.This is a Message.This is a Message') [widget.pack()for widget in (lb,ms)] root.mainloop()
[ 2, 30488, 1485, 13, 9078, 86, 198, 11748, 256, 74, 3849, 355, 256, 74, 198, 198, 15763, 796, 256, 74, 13, 51, 74, 3419, 198, 15763, 13, 469, 15748, 10786, 6200, 87, 2167, 11537, 198, 23160, 796, 256, 74, 13, 33986, 7, 5239, 11639,...
2.621622
111
from itertools import izip_longest outpath = "redd-test/" dir = "redd-test/house_1/" with open(dir+'channel_5_6.dat') as f3,\ open(dir+'channel_6_7.dat') as f4, open(dir+'channel_7_5.dat') as f5, open(dir+'channel_8_5.dat') as f6,\ open(dir+'channel_9_3.dat') as f7, open(dir+'channel_11_9.dat') as f8, open(dir+'channel_12_10.dat') as f9,\ open(dir+'channel_15_5.dat') as f12, open(dir+'channel_17_3.dat') as f10, open(dir+'channel_18_3.dat') as f11,\ open(outpath+'redd-combined-1.dat', 'wb') as res: # open(dir+'channel_2.dat') as f12, for l1,l2,l3,l4,l5,l6,l7,l8,l9,l10 in izip_longest(f3,f4,f5,f6,f7,f8,f9,f10,f11,f12, fillvalue=""): res.write("{},{},{},{},{},{},{},{},{},{}\n".\ format(l1.rstrip(), l2.rstrip(),l3.rstrip(), l4.rstrip(),\ l5.rstrip(), l6.rstrip(),l7.rstrip(), l8.rstrip(),\ l9.rstrip(), l10.rstrip())) dir2 = "redd-test/house_2/" with open(dir2+'channel_3_5.dat') as f3,\ open(dir2+'channel_4_3.dat') as f4, open(dir2+'channel_5_1.dat') as f5, open(dir2+'channel_6_9.dat') as f6,\ open(dir2+'channel_7_4.dat') as f7, open(dir2+'channel_8_5.dat') as f8, open(dir2+'channel_9_6.dat') as f9,\ open(outpath+'redd-combined-2.dat', 'wb') as res: for l1,l2,l3,l4,l5,l6,l7 in izip_longest(f3,f4,f5,f6,f7,f8,f9, fillvalue=""): res.write("{},{},{},{},{},{},{}\n".\ format(l1.rstrip(), l2.rstrip(),l3.rstrip(), l4.rstrip(),\ l5.rstrip(), l6.rstrip(),l7.rstrip())) dir3 = "redd-test/house_3/" with open(dir3+'channel_5_3.dat') as f3,\ open(dir3+'channel_7_6.dat') as f4, open(dir3+'channel_9_7.dat') as f5, open(dir3+'channel_10_8.dat') as f6,\ open(dir3+'channel_11_3.dat') as f7, open(dir3+'channel_15_3.dat') as f8, open(dir3+'channel_16_9.dat') as f9,\ open(dir3+'channel_17_3.dat') as f10, open(dir3+'channel_19_3.dat') as f11,\ open(outpath+'redd-combined-3.dat', 'wb') as res: for l1,l2,l3,l4,l5,l6,l7,l8,l9 in izip_longest(f3,f4,f5,f6,f7,f8,f9,f10,f11, fillvalue=""): res.write("{},{},{},{},{},{},{},{},{}\n".\ format(l1.rstrip(), l2.rstrip(),l3.rstrip(), l4.rstrip(),\ l5.rstrip(), l6.rstrip(),l7.rstrip(), l8.rstrip(),\ l9.rstrip())) dir4 = "redd-test/house_4/" with open(dir4+'channel_3_3.dat') as f3,\ open(dir4+'channel_4_8.dat') as f4, open(dir4+'channel_5_5.dat') as f5, open(dir4+'channel_7_4.dat') as f6,\ open(dir4+'channel_8_1.dat') as f7, open(dir4+'channel_13_3.dat') as f8, open(dir4+'channel_14_5.dat') as f9,\ open(dir4+'channel_18_3.dat') as f10, open(dir4+'channel_19_3.dat') as f11,\ open(outpath+'redd-combined-4.dat', 'wb') as res: for l1,l2,l3,l4,l5,l6,l7,l8,l9 in izip_longest(f3,f4,f5,f6,f7,f8,f9,f10,f11, fillvalue=""): res.write("{},{},{},{},{},{},{},{},{}\n".\ format(l1.rstrip(), l2.rstrip(),l3.rstrip(), l4.rstrip(),\ l5.rstrip(), l6.rstrip(),l7.rstrip(), l8.rstrip(),\ l9.rstrip())) dir5 = "redd-test/house_5/" with open(dir5+'channel_3_9.dat') as f3,\ open(dir5+'channel_6_8.dat') as f4, open(dir5+'channel_14_3.dat') as f5, open(dir5+'channel_16_10.dat') as f6,\ open(dir5+'channel_18_6.dat') as f7, open(dir5+'channel_19_3.dat') as f8, open(dir5+'channel_20_7.dat') as f9,\ open(dir5+'channel_23_3.dat') as f10,\ open(outpath+'redd-combined-5.dat', 'wb') as res: for l1,l2,l3,l4,l5,l6,l7,l8 in izip_longest(f3,f4,f5,f6,f7,f8,f9,f10, fillvalue=""): res.write("{},{},{},{},{},{},{},{}\n".\ format(l1.rstrip(), l2.rstrip(),l3.rstrip(), l4.rstrip(),\ l5.rstrip(), l6.rstrip(),l7.rstrip(), l8.rstrip())) dir6 = "redd-test/house_6/" with open(dir6+'channel_3_5.dat') as f3,\ open(dir6+'channel_4_4.dat') as f4, open(dir6+'channel_5_1.dat') as f5, open(dir6+'channel_7_10.dat') as f6,\ open(dir6+'channel_8_6.dat') as f7, open(dir6+'channel_12_2.dat') as f8, open(dir6+'channel_13_2.dat') as f9,\ open(dir6+'channel_14_3.dat') as f10, open(dir6+'channel_15_2.dat') as f11,\ open(outpath+'redd-combined-6.dat', 'wb') as res: for l1,l2,l3,l4,l5,l6,l7,l8,l9 in izip_longest(f3,f4,f5,f6,f7,f8,f9,f10,f11, fillvalue=""): res.write("{},{},{},{},{},{},{},{},{}\n".\ format(l1.rstrip(), l2.rstrip(),l3.rstrip(), l4.rstrip(),\ l5.rstrip(), l6.rstrip(),l7.rstrip(), l8.rstrip(),\ l9.rstrip()))
[ 6738, 340, 861, 10141, 1330, 220, 528, 541, 62, 6511, 395, 198, 198, 448, 6978, 796, 366, 26504, 12, 9288, 30487, 198, 198, 15908, 796, 366, 26504, 12, 9288, 14, 4803, 62, 16, 30487, 198, 198, 4480, 1280, 7, 15908, 10, 6, 17620, 6...
1.823653
2,376
import argparse import subprocess from typing import Iterable, Optional, Tuple from attr import attrib, attrs __version__ = '0.15.0' Command = Tuple[str, ...] @attrs(frozen=True) TOOLS = [ CommandTool('flake8', default_files=()), CommandTool( 'isort', run_params=('-c',), fix_params=(), default_files=('.',) ), CommandTool('mypy'), CommandTool( 'black', run_params=('--check',), fix_params=(), default_files=('.',), ), ] if __name__ == '__main__': main()
[ 11748, 1822, 29572, 198, 11748, 850, 14681, 198, 6738, 19720, 1330, 40806, 540, 11, 32233, 11, 309, 29291, 198, 198, 6738, 708, 81, 1330, 708, 822, 11, 708, 3808, 198, 198, 834, 9641, 834, 796, 705, 15, 13, 1314, 13, 15, 6, 628, 1...
2.294872
234
import numpy as np import math import matplotlib.pyplot as plt from matplotlib import cm # Create random input and output data x = np.linspace(-math.pi, math.pi, 2000) y = np.sin(x) # Randomly initialize weights a = np.random.randn() b = np.random.randn() c = np.random.randn() d = np.random.randn() learning_rate = 1e-6 for t in range(2000): # Forward pass: compute predicted y # y = a + b x + c x^2 + d x^3 y_pred = fn_3poly(x, a, b, c, d) # Compute and print loss loss = np.square(y_pred - y).sum() if t % 100 == 99: print(t, loss) # Backprop to compute gradients of a, b, c, d with respect to loss grad_y_pred = 2.0 * (y_pred - y) grad_a = grad_y_pred.sum() grad_b = (grad_y_pred * x).sum() grad_c = (grad_y_pred * x ** 2).sum() grad_d = (grad_y_pred * x ** 3).sum() # Update weights a -= learning_rate * grad_a b -= learning_rate * grad_b c -= learning_rate * grad_c d -= learning_rate * grad_d print(f'Result: y = {a} + {b} x + {c} x^2 + {d} x^3') x_plot = np.arange(-4, 4, 0.02) fig, ax = plt.subplots(1) ax.plot(x_plot, np.sin(x_plot)) ax.plot(x_plot, fn_3poly(x_plot, a, b, c, d)) ax.legend([r'$f(x)=\sin(x)$', r'$a + bx + cx^2 + dx^3$']) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) fig.tight_layout() fig.show() # Saliency map def fn_3poly_dr(x): """direvative of fn_3poly""" return b + 2 * c * x + 3 * d * x **2 saliency = fn_3poly_dr(x_plot) fig, ax = plt.subplots(1) ax.plot(x_plot, np.sin(x_plot)) ax.plot(x_plot, fn_3poly(x_plot, a, b, c, d)) ax.scatter( x_plot, fn_3poly(x_plot, a, b, c, d), c=np.array(cm.tab10.colors[1]).reshape(1, -1), marker='.', s=20 * (saliency - saliency.min()) ) ax.legend([r'$f(x)=\sin(x)$', '$a + bx + cx^2 + dx^3$\nthickness represents saliency']) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) fig.tight_layout() fig.show() fig.savefig('images/saliency.png')
[ 11748, 299, 32152, 355, 45941, 198, 11748, 10688, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 6738, 2603, 29487, 8019, 1330, 12067, 198, 198, 2, 13610, 4738, 5128, 290, 5072, 1366, 198, 87, 796, 45941, 13, 21602, ...
2.159737
914
# Copyright (c) 2015 Microsoft Corporation from z3 import * set_option(auto_config=True) x, y = Ints('x y') print eq(x + y, x + y) print eq(x + y, y + x) n = x + y print eq(n, x + y) # x2 is eq to x x2 = Int('x') print eq(x, x2) # the integer variable x is not equal to # the real variable x print eq(Int('x'), Real('x'))
[ 198, 2, 15069, 357, 66, 8, 1853, 5413, 10501, 198, 6738, 1976, 18, 1330, 1635, 198, 2617, 62, 18076, 7, 23736, 62, 11250, 28, 17821, 8, 198, 198, 87, 11, 331, 796, 2558, 82, 10786, 87, 331, 11537, 198, 4798, 37430, 7, 87, 1343, ...
2.414815
135
# This is a script that turns a KaTrain AI into a sort-of GTP compatible bot import json import random import sys import time import os import json import traceback import math os.environ["KCFG_KIVY_LOG_LEVEL"] = os.environ.get("KCFG_KIVY_LOG_LEVEL", "warning") from katrain.core.ai import generate_ai_move from katrain.core.base_katrain import KaTrainBase from katrain.core.constants import OUTPUT_ERROR, OUTPUT_INFO from katrain.core.engine import EngineDiedException, KataGoEngine from katrain.core.game import Game from katrain.core.sgf_parser import Move from settings import DEFAULT_PORT, bot_strategies, Logger bot = sys.argv[1].strip() port = int(sys.argv[2]) if len(sys.argv) > 2 else DEFAULT_PORT REPORT_SCORE_THRESHOLD = 1.5 MAX_WAIT_ANALYSIS = 10 MAX_PASS = 3 # after opponent passes this many times, we always pass logger = Logger() ENGINE_SETTINGS = { "katago": "", # actual engine settings in engine_server.py "model": "", "config": "", "threads": "", "max_visits": 5, "max_time": 5.0, "_enable_ownership": False, } engine = KataGoEngine(logger, ENGINE_SETTINGS, override_command=f"python engine_connector.py {port}") with open("config.json") as f: settings = json.load(f) all_ai_settings = settings["ai"] sgf_dir = "sgf_ogs/" ai_strategy, x_ai_settings, x_engine_settings = bot_strategies[bot] ai_settings = {**all_ai_settings[ai_strategy], **x_ai_settings} ENGINE_SETTINGS.update(x_engine_settings) print(f"starting bot {bot} using server port {port}", file=sys.stderr) print("setup: ", ai_strategy, ai_settings, engine.override_settings, file=sys.stderr) print(ENGINE_SETTINGS, file=sys.stderr) print(ai_strategy, ai_settings, file=sys.stderr) game = Game(Logger(), engine, game_properties={"SZ": 19, "PW": "OGS", "PB": "OGS"}) while True: line = input().strip() logger.log(f"GOT INPUT {line}", OUTPUT_ERROR) if line.startswith("boardsize"): _, *size = line.strip().split(" ") if len(size) > 1: size = f"{size[0]}:{size[1]}" else: size = int(size[0]) game = Game(Logger(), engine, game_properties={"SZ": size, "PW": "OGS", "PB": "OGS"}) logger.log(f"Init game {game.root.properties}", OUTPUT_ERROR) elif line.startswith("komi"): _, komi = line.split(" ") game.root.set_property("KM", komi.strip()) game.root.set_property("RU", "chinese") logger.log(f"Setting komi {game.root.properties}", OUTPUT_ERROR) elif line.startswith("place_free_handicap"): _, n = line.split(" ") n = int(n) game.place_handicap_stones(n) handicaps = set(game.root.get_list_property("AB")) bx, by = game.board_size while len(handicaps) < min(n, bx * by): # really obscure cases handicaps.add( Move((random.randint(0, bx - 1), random.randint(0, by - 1)), player="B").sgf(board_size=game.board_size) ) game.root.set_property("AB", list(handicaps)) game._calculate_groups() gtp = [Move.from_sgf(m, game.board_size, "B").gtp() for m in handicaps] logger.log(f"Chose handicap placements as {gtp}", OUTPUT_ERROR) print(f"= {' '.join(gtp)}\n") sys.stdout.flush() game.analyze_all_nodes() # re-evaluate root while engine.queries: # and make sure this gets processed time.sleep(0.001) continue elif line.startswith("set_free_handicap"): _, *stones = line.split(" ") game.root.set_property("AB", [Move.from_gtp(move.upper()).sgf(game.board_size) for move in stones]) game._calculate_groups() game.analyze_all_nodes() # re-evaluate root while engine.queries: # and make sure this gets processed time.sleep(0.001) logger.log(f"Set handicap placements to {game.root.get_list_property('AB')}", OUTPUT_ERROR) elif line.startswith("genmove"): _, player = line.strip().split(" ") if player[0].upper() != game.current_node.next_player: logger.log( f"ERROR generating move: UNEXPECTED PLAYER {player} != {game.current_node.next_player}.", OUTPUT_ERROR ) print(f"= ??\n") sys.stdout.flush() continue logger.log(f"{ai_strategy} generating move", OUTPUT_ERROR) game.current_node.analyze(engine) malkovich_analysis(game.current_node) game.root.properties[f"P{game.current_node.next_player}"] = [f"KaTrain {ai_strategy}"] num_passes = sum( [int(n.is_pass or False) for n in game.current_node.nodes_from_root[::-1][0 : 2 * MAX_PASS : 2]] ) bx, by = game.board_size if num_passes >= MAX_PASS and game.current_node.depth - 2 * MAX_PASS >= bx + by: logger.log(f"Forced pass as opponent is passing {MAX_PASS} times", OUTPUT_ERROR) pol = game.current_node.policy if not pol: pol = ["??"] print( f"DISCUSSION:OK, since you passed {MAX_PASS} times after the {bx+by}th move, I will pass as well [policy {pol[-1]:.3%}].", file=sys.stderr, ) move = game.play(Move(None, player=game.current_node.next_player)).move else: move, node = generate_ai_move(game, ai_strategy, ai_settings) logger.log(f"Generated move {move}", OUTPUT_ERROR) print(f"= {move.gtp()}\n") sys.stdout.flush() malkovich_analysis(game.current_node) continue elif line.startswith("play"): _, player, move = line.split(" ") node = game.play(Move.from_gtp(move.upper(), player=player[0].upper()), analyze=False) logger.log(f"played {player} {move}", OUTPUT_ERROR) elif line.startswith("final_score"): logger.log("line=" + line, OUTPUT_ERROR) if "{" in line: gamedata_str = line[12:] game.root.set_property("C", f"AI {ai_strategy} {ai_settings}\nOGS Gamedata: {gamedata_str}") try: gamedata = json.loads(gamedata_str) game.root.set_property( "PW", f"{gamedata['players']['white']['username']} ({rank_to_string(gamedata['players']['white']['rank'])})", ) game.root.set_property( "PB", f"{gamedata['players']['black']['username']} ({rank_to_string(gamedata['players']['black']['rank'])})", ) if any(gamedata["players"][p]["username"] == "katrain-dev-beta" for p in ["white", "black"]): sgf_dir = "sgf_ogs_beta/" except Exception as e: _, _, tb = sys.exc_info() logger.log(f"error while processing gamedata: {e}\n{traceback.format_tb(tb)}", OUTPUT_ERROR) score = game.current_node.format_score() game.game_id += f"_{score}" sgf = game.write_sgf( sgf_dir, trainer_config={"eval_show_ai": True, "save_feedback": [True], "eval_thresholds": []} ) logger.log(f"Game ended. Score was {score} -> saved sgf to {sgf}", OUTPUT_ERROR) sys.stderr.flush() sys.stdout.flush() time.sleep(0.1) # ensure our logging gets handled print(f"= {score}\n") sys.stdout.flush() continue elif line.startswith("quit"): print(f"= \n") break print(f"= \n") sys.stdout.flush() sys.stderr.flush()
[ 2, 770, 318, 257, 4226, 326, 4962, 257, 11611, 44077, 9552, 656, 257, 3297, 12, 1659, 402, 7250, 11670, 10214, 198, 11748, 33918, 198, 11748, 4738, 198, 11748, 25064, 198, 11748, 640, 198, 11748, 28686, 198, 11748, 33918, 198, 11748, 12...
2.127159
3,531
''' The follwing code runs a test lstm network on the CIFAR dataset I will explicitly write the networks here for ease of understanding One convlstm layer right after the first cnn cnn_dropout = 0.4 rnn_dropout = 0.2 , WITH cnivlstm_dropout samples = 10, h = 256, epochs = 50, convlstm activation = relu - out.373233 (Based on best results from cnn - gru) ################# convlstm_cnn_mix_v0_True Validation Accuracy = [0.3555999994277954, 0.37619999051094055, 0.4235999882221222, 0.4275999963283539, 0.46779999136924744, 0.4819999933242798, 0.48980000615119934, 0.4968000054359436, 0.5194000005722046, 0.5131999850273132, 0.5242000222206116, 0.5284000039100647, 0.5144000053405762, 0.5365999937057495, 0.5465999841690063, 0.5496000051498413, 0.5407999753952026, 0.5626000165939331, 0.5573999881744385, 0.5558000206947327, 0.5586000084877014, 0.5645999908447266, 0.5717999935150146, 0.569599986076355, 0.5727999806404114, 0.5630000233650208, 0.571399986743927, 0.5580000281333923, 0.5852000117301941, 0.5753999948501587, 0.5738000273704529, 0.579200029373169, 0.5726000070571899, 0.5789999961853027, 0.5648000240325928, 0.5776000022888184, 0.5763999819755554, 0.5799999833106995, 0.58160001039505, 0.5839999914169312, 0.5860000252723694, 0.5834000110626221, 0.5825999975204468, 0.5860000252723694, 0.5807999968528748, 0.5831999778747559, 0.5789999961853027, 0.5758000016212463, 0.58160001039505, 0.5807999968528748] ################# convlstm_cnn_mix_v0_True Training Accuracy = [0.25715556740760803, 0.36764445900917053, 0.4077777862548828, 0.4264444410800934, 0.4399999976158142, 0.4568444490432739, 0.46862220764160156, 0.4764222204685211, 0.4854666590690613, 0.4959777891635895, 0.5049999952316284, 0.5096889138221741, 0.5180666446685791, 0.5244666934013367, 0.5313777923583984, 0.536133348941803, 0.5363110899925232, 0.5413333177566528, 0.549311101436615, 0.5522222518920898, 0.557022213935852, 0.5595999956130981, 0.563955545425415, 0.5663999915122986, 0.5641111135482788, 0.5719777941703796, 0.5754444599151611, 0.5798222422599792, 0.580644428730011, 0.5836222171783447, 0.5849555730819702, 0.586222231388092, 0.5915555357933044, 0.594355583190918, 0.5944888591766357, 0.5996444225311279, 0.6037111282348633, 0.6028888821601868, 0.6078444719314575, 0.6094889044761658, 0.6093555688858032, 0.6102889180183411, 0.6134666800498962, 0.6152889132499695, 0.6180889010429382, 0.6205999851226807, 0.6215111017227173, 0.6247333288192749, 0.6240666508674622, 0.6295999884605408] cnn_dropout = 0.4 rnn_dropout = 0.2 , WITH cnivlstm_dropout samples = 10, h = 256, epochs = 150, convlstm activation = relu - out.373440 (Based on best results from cnn - gru) ################# convlstm_cnn_mix_v01_True Validation Accuracy = [0.31619998812675476, 0.4059999883174896, 0.4047999978065491, 0.436599999666214, 0.45899999141693115, 0.4731999933719635, 0.4819999933242798, 0.487199991941452, 0.4936000108718872, 0.4991999864578247, 0.5113999843597412, 0.5221999883651733, 0.5235999822616577, 0.5278000235557556, 0.5368000268936157, 0.5289999842643738, 0.5253999829292297, 0.5428000092506409, 0.5382000207901001, 0.5414000153541565, 0.5450000166893005, 0.5511999726295471, 0.5523999929428101, 0.5672000050544739, 0.5468000173568726, 0.5619999766349792, 0.5522000193595886, 0.5722000002861023, 0.5673999786376953, 0.5720000267028809, 0.5690000057220459, 0.5726000070571899, 0.5763999819755554, 0.571399986743927, 0.5673999786376953, 0.5722000002861023, 0.5691999793052673, 0.5781999826431274, 0.578000009059906, 0.5795999765396118, 0.5748000144958496, 0.5888000130653381, 0.5809999704360962, 0.5821999907493591, 0.5759999752044678, 0.5771999955177307, 0.5705999732017517, 0.5825999975204468, 0.5770000219345093, 0.5738000273704529, 0.5756000280380249, 0.5752000212669373, 0.5802000164985657, 0.5781999826431274, 0.5709999799728394, 0.5717999935150146, 0.5781999826431274, 0.5831999778747559, 0.5812000036239624, 0.5849999785423279, 0.5789999961853027, 0.5756000280380249, 0.5758000016212463, 0.5771999955177307, 0.5856000185012817, 0.5785999894142151, 0.5720000267028809, 0.5734000205993652, 0.5741999745368958, 0.5824000239372253, 0.5776000022888184, 0.5756000280380249, 0.5687999725341797, 0.5676000118255615, 0.5738000273704529, 0.5857999920845032, 0.5799999833106995, 0.5766000151634216, 0.5788000226020813, 0.5831999778747559, 0.5753999948501587, 0.5734000205993652, 0.5631999969482422, 0.5687999725341797, 0.5788000226020813, 0.578000009059906, 0.5756000280380249, 0.5708000063896179, 0.5618000030517578, 0.5708000063896179, 0.5741999745368958, 0.5753999948501587, 0.5720000267028809, 0.5722000002861023, 0.5637999773025513, 0.574999988079071, 0.5690000057220459, 0.58160001039505, 0.5694000124931335, 0.5676000118255615, 0.5738000273704529, 0.5651999711990356, 0.574999988079071, 0.5703999996185303, 0.569599986076355, 0.5690000057220459, 0.5672000050544739, 0.5655999779701233, 0.5637999773025513, 0.5691999793052673, 0.5702000260353088, 0.5680000185966492, 0.5613999962806702, 0.5662000179290771, 0.5623999834060669, 0.567799985408783, 0.5662000179290771, 0.5712000131607056, 0.5673999786376953, 0.5630000233650208, 0.5594000220298767, 0.5608000159263611, 0.5681999921798706, 0.5659999847412109, 0.5630000233650208, 0.5619999766349792, 0.5626000165939331, 0.5654000043869019, 0.5654000043869019, 0.5631999969482422, 0.5680000185966492, 0.5601999759674072, 0.5586000084877014, 0.5590000152587891, 0.5605999827384949, 0.5558000206947327, 0.5636000037193298, 0.555400013923645, 0.5644000172615051, 0.5595999956130981, 0.5608000159263611, 0.5685999989509583, 0.5626000165939331, 0.5590000152587891, 0.5623999834060669, 0.5541999936103821, 0.5523999929428101, 0.5519999861717224, 0.5582000017166138, 0.5558000206947327] ################# convlstm_cnn_mix_v01_True Training Accuracy = [0.249466672539711, 0.358822226524353, 0.39959999918937683, 0.41804444789886475, 0.43524444103240967, 0.4512222111225128, 0.4600444436073303, 0.46995556354522705, 0.47760000824928284, 0.48697778582572937, 0.4950222074985504, 0.49779999256134033, 0.5047777891159058, 0.5094444155693054, 0.5156221985816956, 0.5198000073432922, 0.5297999978065491, 0.5285778045654297, 0.5348444581031799, 0.5395777821540833, 0.5428000092506409, 0.5471110939979553, 0.5546444654464722, 0.5557777881622314, 0.5594000220298767, 0.5629777908325195, 0.5652666687965393, 0.5679110884666443, 0.5738222002983093, 0.5741999745368958, 0.5807777643203735, 0.5786888599395752, 0.5838666558265686, 0.5865111351013184, 0.5898444652557373, 0.592199981212616, 0.5955111384391785, 0.5958889126777649, 0.6001777648925781, 0.6027555465698242, 0.6022666692733765, 0.606844425201416, 0.6050666570663452, 0.6121333241462708, 0.6107555627822876, 0.6132222414016724, 0.6163111329078674, 0.6169777512550354, 0.6183333396911621, 0.622511088848114, 0.624822199344635, 0.6251555681228638, 0.6260666847229004, 0.6275110840797424, 0.6320444345474243, 0.6323999762535095, 0.6347333192825317, 0.6363333463668823, 0.6373777985572815, 0.6391111016273499, 0.6382444500923157, 0.63919997215271, 0.6450222134590149, 0.6434000134468079, 0.6443555355072021, 0.6475555300712585, 0.6497777700424194, 0.6504666805267334, 0.6514222025871277, 0.6546000242233276, 0.6522889137268066, 0.6551111340522766, 0.6570000052452087, 0.6564444303512573, 0.658466637134552, 0.6592222452163696, 0.662066638469696, 0.6632444262504578, 0.6638222336769104, 0.6681333184242249, 0.6650221943855286, 0.6649555563926697, 0.6700000166893005, 0.6726666688919067, 0.6718888878822327, 0.6709111332893372, 0.6744444370269775, 0.6745333075523376, 0.6758221983909607, 0.6766666769981384, 0.6747111082077026, 0.6774666905403137, 0.6812666654586792, 0.6800888776779175, 0.6768222451210022, 0.6801333427429199, 0.6830888986587524, 0.6844000220298767, 0.6855999827384949, 0.6861777901649475, 0.686822235584259, 0.6895111203193665, 0.6921555399894714, 0.6860666871070862, 0.6852666735649109, 0.6915333271026611, 0.6921333074569702, 0.6931777596473694, 0.6941555738449097, 0.6948666572570801, 0.6968888640403748, 0.6943777799606323, 0.6979555487632751, 0.6966888904571533, 0.6968888640403748, 0.6993555426597595, 0.6975555419921875, 0.7030444741249084, 0.6989777684211731, 0.7029555439949036, 0.7020221948623657, 0.7024222016334534, 0.7059333324432373, 0.7076444625854492, 0.7047333121299744, 0.7077111005783081, 0.7068444490432739, 0.7082666754722595, 0.7079333066940308, 0.7075555324554443, 0.7076888680458069, 0.7130222320556641, 0.71224445104599, 0.7111555337905884, 0.7123333215713501, 0.7143333554267883, 0.7105333209037781, 0.718155562877655, 0.7120888829231262, 0.7151333093643188, 0.7185778021812439, 0.7164000272750854, 0.7191110849380493, 0.7173110842704773, 0.7188666462898254, 0.7190889120101929, 0.7207777500152588, 0.7199777960777283, 0.7187111377716064, 0.722000002861023] ################# convlstm_cnn_mix_v0_True Validation Accuracy = [0.3555999994277954, 0.37619999051094055, 0.4235999882221222, 0.4275999963283539, 0.46779999136924744, 0.4819999933242798, 0.48980000615119934, 0.4968000054359436, 0.5194000005722046, 0.5131999850273132, 0.5242000222206116, 0.5284000039100647, 0.5144000053405762, 0.5365999937057495, 0.5465999841690063, 0.5496000051498413, 0.5407999753952026, 0.5626000165939331, 0.5573999881744385, 0.5558000206947327, 0.5586000084877014, 0.5645999908447266, 0.5717999935150146, 0.569599986076355, 0.5727999806404114, 0.5630000233650208, 0.571399986743927, 0.5580000281333923, 0.5852000117301941, 0.5753999948501587, 0.5738000273704529, 0.579200029373169, 0.5726000070571899, 0.5789999961853027, 0.5648000240325928, 0.5776000022888184, 0.5763999819755554, 0.5799999833106995, 0.58160001039505, 0.5839999914169312, 0.5860000252723694, 0.5834000110626221, 0.5825999975204468, 0.5860000252723694, 0.5807999968528748, 0.5831999778747559, 0.5789999961853027, 0.5758000016212463, 0.58160001039505, 0.5807999968528748] ################# convlstm_cnn_mix_v0_True Training Accuracy = [0.25715556740760803, 0.36764445900917053, 0.4077777862548828, 0.4264444410800934, 0.4399999976158142, 0.4568444490432739, 0.46862220764160156, 0.4764222204685211, 0.4854666590690613, 0.4959777891635895, 0.5049999952316284, 0.5096889138221741, 0.5180666446685791, 0.5244666934013367, 0.5313777923583984, 0.536133348941803, 0.5363110899925232, 0.5413333177566528, 0.549311101436615, 0.5522222518920898, 0.557022213935852, 0.5595999956130981, 0.563955545425415, 0.5663999915122986, 0.5641111135482788, 0.5719777941703796, 0.5754444599151611, 0.5798222422599792, 0.580644428730011, 0.5836222171783447, 0.5849555730819702, 0.586222231388092, 0.5915555357933044, 0.594355583190918, 0.5944888591766357, 0.5996444225311279, 0.6037111282348633, 0.6028888821601868, 0.6078444719314575, 0.6094889044761658, 0.6093555688858032, 0.6102889180183411, 0.6134666800498962, 0.6152889132499695, 0.6180889010429382, 0.6205999851226807, 0.6215111017227173, 0.6247333288192749, 0.6240666508674622, 0.6295999884605408] with 20 samples and epochs = 50, h=128, out.980236 with 20 samples and epochs = 50, h=256, out.980276 ''' from __future__ import division, print_function, absolute_import print('Starting..................................') import sys sys.path.insert(1, '/home/labs/ahissarlab/orra/imagewalker') import numpy as np import cv2 import misc import pandas as pd import matplotlib.pyplot as plt import pickle from keras_utils import * from misc import * import tensorflow.keras as keras import tensorflow as tf gpus = tf.config.experimental.list_physical_devices('GPU') for gpu in gpus: tf.config.experimental.set_memory_growth(gpu, True) from tensorflow.keras.datasets import cifar10 # load dataset (trainX, trainy), (testX, testy) = cifar10.load_data() images, labels = trainX, trainy #Define function for low resolution lens on syclop kernel_regularizer_list = [None, keras.regularizers.l1(),keras.regularizers.l2(),keras.regularizers.l1_l2()] optimizer_list = [tf.keras.optimizers.Adam, tf.keras.optimizers.Nadam, tf.keras.optimizers.RMSprop] if len(sys.argv) > 1: paramaters = { 'epochs' : int(sys.argv[1]), 'sample' : int(sys.argv[2]), 'res' : int(sys.argv[3]), 'hidden_size' : int(sys.argv[4]), 'concat' : int(sys.argv[5]), 'regularizer' : keras.regularizers.l1(),#kernel_regularizer_list[int(sys.argv[6])], 'optimizer' : optimizer_list[int(sys.argv[7])], 'cnn_dropout' : 0.4, 'rnn_dropout' : 0.2, 'lr' : 5e-4, 'run_id' : np.random.randint(1000,9000) } else: paramaters = { 'epochs' : 1, 'sample' : 5, 'res' : 8, 'hidden_size' : 128, 'concat' : 1, 'regularizer' : None, 'optimizer' : optimizer_list[0], 'cnn_dropout' : 0.4, 'rnn_dropout' : 0.2, 'lr' : 5e-4, 'run_id' : np.random.randint(1000,9000) } print(paramaters) for key,val in paramaters.items(): exec(key + '=val') epochs = epochs sample = sample res = res hidden_size =hidden_size concat = concat regularizer = regularizer optimizer = optimizer cnn_dropout = cnn_dropout rnn_dropout = rnn_dropout lr = lr run_id = run_id n_timesteps = sample def convlstm(n_timesteps = 5, hidden_size = 128,input_size = 32, concat = True): ''' CNN RNN combination that extends the CNN to a network that achieves ~80% accuracy on full res cifar. Parameters ---------- n_timesteps : TYPE, optional DESCRIPTION. The default is 5. img_dim : TYPE, optional DESCRIPTION. The default is 32. hidden_size : TYPE, optional DESCRIPTION. The default is 128. input_size : TYPE, optional DESCRIPTION. The default is 32. Returns ------- model : TYPE DESCRIPTION. ''' inputA = keras.layers.Input(shape=(n_timesteps,input_size,input_size,3)) inputB = keras.layers.Input(shape=(n_timesteps,2)) # define CNN model x1=keras.layers.TimeDistributed(keras.layers.Conv2D(32,(3,3), activation='relu',padding = 'same'))(inputA) x1=keras.layers.ConvLSTM2D(32,(3,3), padding = 'same', dropout = cnn_dropout, recurrent_dropout=rnn_dropout,return_sequences=True)(x1) x1=keras.layers.TimeDistributed(keras.layers.MaxPooling2D(pool_size=(2, 2)))(x1) x1=keras.layers.TimeDistributed(keras.layers.Dropout(cnn_dropout))(x1) x1=keras.layers.TimeDistributed(keras.layers.Conv2D(64,(3,3),activation='relu', padding = 'same'))(x1) x1=keras.layers.TimeDistributed(keras.layers.Conv2D(64,(3,3),activation='relu', padding = 'same'))(x1) x1=keras.layers.TimeDistributed(keras.layers.MaxPooling2D(pool_size=(2, 2)))(x1) x1=keras.layers.TimeDistributed(keras.layers.Dropout(cnn_dropout))(x1) x1=keras.layers.TimeDistributed(keras.layers.Conv2D(128,(3,3),activation='relu', padding = 'same'))(x1) x1=keras.layers.TimeDistributed(keras.layers.Conv2D(128,(3,3),activation='relu', padding = 'same'))(x1) x1=keras.layers.TimeDistributed(keras.layers.MaxPooling2D(pool_size=(2, 2)))(x1) x1=keras.layers.TimeDistributed(keras.layers.Dropout(cnn_dropout))(x1) print(x1.shape) x1=keras.layers.TimeDistributed(keras.layers.Flatten())(x1) print(x1.shape) if concat: x = keras.layers.Concatenate()([x1,inputB]) else: x = x1 print(x.shape) # define LSTM model x = keras.layers.GRU(hidden_size,input_shape=(n_timesteps, None),return_sequences=True,recurrent_dropout=rnn_dropout)(x) x = keras.layers.Flatten()(x) x = keras.layers.Dense(10,activation="softmax")(x) model = keras.models.Model(inputs=[inputA,inputB],outputs=x, name = 'convlstm_cnn_mix_v01_{}'.format(concat)) opt=tf.keras.optimizers.Adam(lr=lr) model.compile( optimizer=opt, loss="sparse_categorical_crossentropy", metrics=["sparse_categorical_accuracy"], ) return model rnn_net = convlstm(n_timesteps = sample, hidden_size = hidden_size,input_size = res, concat = True) #keras.utils.plot_model(rnn_net, expand_nested=True, to_file='{}.png'.format(rnn_net.name)) #cnn_net = cnn_net = extended_cnn_one_img(n_timesteps = sample, input_size = res, dropout = cnn_dropout) # hp = HP() # hp.save_path = 'saved_runs' # hp.description = "syclop cifar net search runs" # hp.this_run_name = 'syclop_{}'.format(rnn_net.name) # deploy_logs() train_dataset, test_dataset = create_cifar_dataset(images, labels,res = res, sample = sample, return_datasets=True, mixed_state = False, add_seed = 0, ) #bad_res_func = bad_res101, up_sample = True) train_dataset_x, train_dataset_y = split_dataset_xy(train_dataset) test_dataset_x, test_dataset_y = split_dataset_xy(test_dataset) print("##################### Fit {} and trajectories model on training data res = {} ##################".format(rnn_net.name,res)) rnn_history = rnn_net.fit( train_dataset_x, train_dataset_y, batch_size=64, epochs=epochs, # We pass some validation for # monitoring validation loss and metrics # at the end of each epoch validation_data=(test_dataset_x, test_dataset_y), verbose = 0) # print('################# {} Validation Accuracy = '.format(cnn_net.name),cnn_history.history['val_sparse_categorical_accuracy']) # print('################# {} Training Accuracy = '.format(cnn_net.name),rnn_history.history['sparse_categorical_accuracy']) print('################# {} Validation Accuracy = '.format(rnn_net.name),rnn_history.history['val_sparse_categorical_accuracy']) print('################# {} Training Accuracy = '.format(rnn_net.name),rnn_history.history['sparse_categorical_accuracy']) plt.figure() plt.plot(rnn_history.history['sparse_categorical_accuracy'], label = 'train') plt.plot(rnn_history.history['val_sparse_categorical_accuracy'], label = 'val') # plt.plot(cnn_history.history['sparse_categorical_accuracy'], label = 'cnn train') # plt.plot(cnn_history.history['val_sparse_categorical_accuracy'], label = 'cnn val') plt.legend() plt.title('{} on cifar res = {} hs = {} dropout = {}, num samples = {}'.format(rnn_net.name, res, hidden_size,cnn_dropout,sample)) plt.savefig('{} on Cifar res = {}, no upsample, val accur = {} hs = {} dropout = {}.png'.format(rnn_net.name,res,rnn_history.history['val_sparse_categorical_accuracy'][-1], hidden_size,cnn_dropout)) with open('/home/labs/ahissarlab/orra/imagewalker/cifar_net_search/{}HistoryDict{}_{}'.format(rnn_net.name, hidden_size,cnn_dropout), 'wb') as file_pi: pickle.dump(rnn_history.history, file_pi) # with open('/home/labs/ahissarlab/orra/imagewalker/cifar_net_search/{}HistoryDict'.format(cnn_net.name), 'wb') as file_pi: # pickle.dump(cnn_history.history, file_pi) dataset_update(rnn_history, rnn_net,paramaters) write_to_file(rnn_history, rnn_net,paramaters)
[ 7061, 6, 198, 464, 22752, 5469, 2438, 4539, 257, 1332, 300, 301, 76, 3127, 319, 262, 327, 5064, 1503, 27039, 220, 198, 198, 40, 481, 11777, 3551, 262, 7686, 994, 329, 10152, 286, 4547, 220, 198, 198, 3198, 3063, 75, 301, 76, 7679, ...
2.174104
8,673
import pytest """ Test Dependency Installation The purpose is to check if core dependencies are installed properly. Typically, failure to these tests indicate an incorrection installation or wrong activation of the virtual environment (i.e. conda, venv, etc.). """
[ 11748, 12972, 9288, 198, 198, 37811, 6208, 37947, 1387, 32588, 198, 198, 464, 4007, 318, 284, 2198, 611, 4755, 20086, 389, 6589, 6105, 13, 198, 49321, 11, 5287, 284, 777, 5254, 7603, 281, 5970, 8243, 9988, 220, 198, 273, 2642, 14916, ...
4.33871
62
from treys import Evaluator, Deck from treys.card import pretty d = Deck.fresh() print(d) print(pretty(d))
[ 6738, 2054, 893, 1330, 26439, 84, 1352, 11, 20961, 198, 6738, 2054, 893, 13, 9517, 1330, 2495, 198, 198, 67, 796, 20961, 13, 48797, 3419, 198, 4798, 7, 67, 8, 198, 4798, 7, 37784, 7, 67, 4008, 628, 198 ]
2.820513
39
#!/usr/bin/env python r""" This module provides command execution functions such as cmd_fnc and cmd_fnc_u. """ import sys import subprocess robot_env = 1 try: from robot.libraries.BuiltIn import BuiltIn except ImportError: robot_env = 0 import gen_print as gp import gen_valid as gv import gen_misc as gm if robot_env: import gen_robot_print as grp ############################################################################### def cmd_fnc(cmd_buf, quiet=None, test_mode=None, debug=0, print_output=1, show_err=1): r""" Run the given command in a shell and return the shell return code. Description of arguments: cmd_buf The command string to be run in a shell. quiet Indicates whether this function should run the pissuing() function prints an "Issuing: <cmd string>" to stdout. test_mode If test_mode is set, this function will not actually run the command. debug If debug is set, this function will print extra debug info. print_output If this is set, this function will print the stdout/stderr generated by the shell command. show_err If show_err is set, this function will print a standardized error report if the shell command returns non-zero. """ quiet = int(gm.global_default(quiet, 0)) test_mode = int(gm.global_default(test_mode, 0)) if debug: gp.print_vars(cmd_buf, quiet, test_mode, debug) err_msg = gv.svalid_value(cmd_buf) if err_msg != "": raise ValueError(err_msg) if not quiet: gp.pissuing(cmd_buf, test_mode) if test_mode: return 0, "" sub_proc = subprocess.Popen(cmd_buf, bufsize=1, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out_buf = "" for line in sub_proc.stdout: out_buf += line if not print_output: continue if robot_env: grp.rprint(line) else: sys.stdout.write(line) if print_output and not robot_env: sys.stdout.flush() sub_proc.communicate() shell_rc = sub_proc.returncode if shell_rc != 0 and show_err: if robot_env: grp.rprint_error_report("The prior command failed.\n" + gp.sprint_var(shell_rc, 1)) else: gp.print_error_report("The prior command failed.\n" + gp.sprint_var(shell_rc, 1)) return shell_rc, out_buf ############################################################################### ############################################################################### def cmd_fnc_u(cmd_buf, quiet=None, debug=None, print_output=1, show_err=1): r""" Call cmd_fnc with test_mode=0. See cmd_fnc (above) for details. Note the "u" in "cmd_fnc_u" stands for "unconditional". """ return cmd_fnc(cmd_buf, test_mode=0, quiet=quiet, debug=debug, print_output=print_output, show_err=show_err) ###############################################################################
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 81, 37811, 198, 1212, 8265, 3769, 3141, 9706, 5499, 884, 355, 23991, 62, 69, 10782, 290, 23991, 62, 69, 10782, 62, 84, 13, 198, 37811, 198, 198, 11748, 25064, 198, 11748, 850, 1...
2.048904
1,779
import turtle as trt distance = 70 angle = 90 for compteur in range(4): if compteur == 0: trt.color("blue") elif compteur == 1: trt.color("red") elif compteur == 2: trt.color("green") else : trt.color("orange") trt.write(compteur) trt.forward(distance) trt.left(angle) trt.done()
[ 11748, 28699, 355, 491, 83, 198, 198, 30246, 796, 4317, 198, 9248, 796, 4101, 198, 198, 1640, 401, 457, 23365, 287, 2837, 7, 19, 2599, 198, 197, 361, 401, 457, 23365, 6624, 657, 25, 198, 197, 197, 2213, 83, 13, 8043, 7203, 17585, ...
2.214815
135
#!/usr/bin/python # # Author: Jashua R. Cloutier (contact via sourceforge username:senexcanis) # # Copyright (C) 2010, Jashua R. Cloutier # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # # * Neither the name of Jashua R. Cloutier nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # # The CppHeaderParser.py script is written in Python 2.4 and released to # the open source community for continuous improvements under the BSD # 2.0 new license, which can be found at: # # http://www.opensource.org/licenses/bsd-license.php # """ CppHeaderParser2.0: April 2011 - August 2011 by HartsAntler http://pyppet.blogspot.com Quick Start - User API: h = CppHeaderParser.CppHeader("someheader.h") for name in h.classes: c = h.classes[name] for method in c['methods']['public']: print method['name'] print dir(method) # view the rest of the API here. ... TODO document more ... New Features by Hart: should be able to parse all c++ files, not just headers parsing global typedefs with resolution parsing global structs fixes nested struct in class changes accessor type parsing if class is abstract parsing more info about variables save ordering of classes, structs, and typedefs handle forward decl of class in a class handle mutable, static, and other variable types handle 1D arrays handle throw keyword and function prefix __attribute__((__const__)) handle nameless parameters "void method(void);" handle simple templates, and global functions. Internal Developer Notes: 1. double name stacks: . the main stack is self.nameStack, this stack is simpler and easy to get hints from . the secondary stack is self.stack is the full name stack, required for parsing somethings . each stack maybe cleared at different points, since they are used to detect different things . it looks ugly but it works :) 2. Had to make the __repr__ methods simple because some of these dicts are interlinked. For nice printing, call something.show() """ import ply.lex as lex import os import sys import re import inspect def lineno(): """Returns the current line number in our program.""" return inspect.currentframe().f_back.f_lineno version = __version__ = "1.9.9o" tokens = [ 'NUMBER', 'NAME', 'OPEN_PAREN', 'CLOSE_PAREN', 'OPEN_BRACE', 'CLOSE_BRACE', 'COLON', 'SEMI_COLON', 'COMMA', 'COMMENT_SINGLELINE', 'COMMENT_MULTILINE', 'PRECOMP_MACRO', 'PRECOMP_MACRO_CONT', 'ASTERISK', 'AMPERSTAND', 'EQUALS', 'MINUS', 'PLUS', 'DIVIDE', 'CHAR_LITERAL', 'STRING_LITERAL', 'OPERATOR_DIVIDE_OVERLOAD', 'NEW_LINE', 'OPEN_BRACKET', 'CLOSE_BRACKET', ] t_OPEN_BRACKET = r'\[' t_CLOSE_BRACKET = r'\]' #t_ignore = " \t\r[].|!?%@" # (cppheaderparser 1.9x) #t_ignore = " \t\r[].|!?%@'^\\" t_ignore = " \t\r.|!?%@'^\\" t_NUMBER = r'[0-9][0-9XxA-Fa-f]*' t_NAME = r'[<>A-Za-z_~][A-Za-z0-9_]*' t_OPERATOR_DIVIDE_OVERLOAD = r'/=' t_OPEN_PAREN = r'\(' t_CLOSE_PAREN = r'\)' t_OPEN_BRACE = r'{' t_CLOSE_BRACE = r'}' t_SEMI_COLON = r';' t_COLON = r':' t_COMMA = r',' t_PRECOMP_MACRO = r'\#.*' t_PRECOMP_MACRO_CONT = r'.*\\\n' def t_COMMENT_SINGLELINE(t): r'\/\/.*\n' global doxygenCommentCache if t.value.startswith("///") or t.value.startswith("//!"): if doxygenCommentCache: doxygenCommentCache += "\n" if t.value.endswith("\n"): doxygenCommentCache += t.value[:-1] else: doxygenCommentCache += t.value t_ASTERISK = r'\*' t_MINUS = r'\-' t_PLUS = r'\+' t_DIVIDE = r'/[^/]' # fails to catch "/(" - method operator that overloads divide t_AMPERSTAND = r'&' t_EQUALS = r'=' t_CHAR_LITERAL = "'.'" #found at http://wordaligned.org/articles/string-literals-and-regular-expressions #TODO: This does not work with the string "bla \" bla" t_STRING_LITERAL = r'"([^"\\]|\\.)*"' #Found at http://ostermiller.org/findcomment.html def t_COMMENT_MULTILINE(t): r'/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/' global doxygenCommentCache if t.value.startswith("/**") or t.value.startswith("/*!"): #not sure why, but get double new lines v = t.value.replace("\n\n", "\n") #strip prefixing whitespace v = re.sub("\n[\s]+\*", "\n*", v) doxygenCommentCache += v def t_NEWLINE(t): r'\n+' t.lexer.lineno += len(t.value) lex.lex() debug = 0 debug_trace = 0 supportedAccessSpecifier = [ 'public', 'protected', 'private' ] enumMaintianValueFormat = False doxygenCommentCache = "" def is_namespace(nameStack): """Determines if a namespace is being specified""" if len(nameStack) == 0: return False if nameStack[0] == "namespace": return True return False def is_enum_namestack(nameStack): """Determines if a namestack is an enum namestack""" if len(nameStack) == 0: return False if nameStack[0] == "enum": return True if len(nameStack) > 1 and nameStack[0] == "typedef" and nameStack[1] == "enum": return True return False class CppClass( _CppClass ): """Takes a name stack and turns it into a class Contains the following Keys: self['name'] - Name of the class self['doxygen'] - Doxygen comments associated with the class if they exist self['inherits'] - List of Classes that this one inherits where the values are of the form {"access": Anything in supportedAccessSpecifier "class": Name of the class self['methods'] - Dictionary where keys are from supportedAccessSpecifier and values are a lists of CppMethod's self['properties'] - Dictionary where keys are from supportedAccessSpecifier and values are lists of CppVariable's self['enums'] - Dictionary where keys are from supportedAccessSpecifier and values are lists of CppEnum's self['structs'] - Dictionary where keys are from supportedAccessSpecifier and values are lists of nested Struct's An example of how this could look is as follows: #self = { 'name': "" 'inherits':[] 'methods': { 'public':[], 'protected':[], 'private':[] }, 'properties': { 'public':[], 'protected':[], 'private':[] }, 'enums': { 'public':[], 'protected':[], 'private':[] } } """ def show(self): """Convert class to a string""" namespace_prefix = "" if self["namespace"]: namespace_prefix = self["namespace"] + "::" rtn = "class %s"%(namespace_prefix + self["name"]) if self['abstract']: rtn += ' (abstract)\n' else: rtn += '\n' if 'doxygen' in self.keys(): rtn += self["doxygen"] + '\n' if 'parent' in self.keys() and self['parent']: rtn += 'parent class:' + self['parent'] + '\n' if "inherits" in self.keys(): rtn += " Inherits: " for inheritClass in self["inherits"]: rtn += "%s %s, "%(inheritClass["access"], inheritClass["class"]) rtn += "\n" rtn += " {\n" for accessSpecifier in supportedAccessSpecifier: rtn += " %s\n"%(accessSpecifier) #Enums if (len(self["enums"][accessSpecifier])): rtn += " <Enums>\n" for enum in self["enums"][accessSpecifier]: rtn += " %s\n"%(repr(enum)) #Properties if (len(self["properties"][accessSpecifier])): rtn += " <Properties>\n" for property in self["properties"][accessSpecifier]: rtn += " %s\n"%(repr(property)) #Methods if (len(self["methods"][accessSpecifier])): rtn += " <Methods>\n" for method in self["methods"][accessSpecifier]: rtn += "\t\t" + method.show() + '\n' rtn += " }\n" print( rtn ) class CppMethod( _CppMethod ): """Takes a name stack and turns it into a method Contains the following Keys: self['returns'] - Return type of the method (ex. "int") self['name'] - Name of the method (ex. "getSize") self['doxygen'] - Doxygen comments associated with the method if they exist self['parameters'] - List of CppVariables """ class CppVariable( _CppVariable ): """Takes a name stack and turns it into a method Contains the following Keys: self['type'] - Type for the variable (ex. "const string &") self['raw_type'] - Type of variable without pointers or other markup (ex. "string") self['name'] - Name of the variable (ex. "numItems") self['namespace'] - Namespace containing the enum self['desc'] - Description of the variable if part of a method (optional) self['doxygen'] - Doxygen comments associated with the method if they exist self['defalt'] - Default value of the variable, this key will only exist if there is a default value """ Vars = [] class CppEnum(_CppEnum): """Takes a name stack and turns it into an Enum Contains the following Keys: self['name'] - Name of the enum (ex. "ItemState") self['namespace'] - Namespace containing the enum self['values'] - List of values where the values are a dictionary of the form {"name": name of the key (ex. "PARSING_HEADER"), "value": Specified value of the enum, this key will only exist if a value for a given enum value was defined } """ C99_NONSTANDARD = { 'int8' : 'signed char', 'int16' : 'short int', 'int32' : 'int', 'int64' : 'int64_t', # this can be: long int (64bit), or long long int (32bit) 'uint' : 'unsigned int', 'uint8' : 'unsigned char', 'uint16' : 'unsigned short int', 'uint32' : 'unsigned int', 'uint64' : 'uint64_t', # depends on host bits } class CppHeader( _CppHeader ): """Parsed C++ class header Variables produced: self.classes - Dictionary of classes found in a given header file where the key is the name of the class """ IGNORE_NAMES = '__extension__'.split() def evaluate_enum_stack(self): """Create an Enum out of the name stack""" newEnum = CppEnum(self.nameStack) if len(newEnum.keys()): if len(self.curClass): newEnum["namespace"] = self.cur_namespace(False) klass = self.classes[self.curClass] klass["enums"][self.curAccessSpecifier].append(newEnum) if self.curAccessSpecifier == 'public': if 'name' in newEnum and newEnum['name']: klass._public_enums[ newEnum['name'] ] = newEnum else: newEnum["namespace"] = self.cur_namespace(True) self.enums.append(newEnum) if 'name' in newEnum and newEnum['name']: self.global_enums[ newEnum['name'] ] = newEnum #This enum has instances, turn them into properties if newEnum.has_key("instances"): instanceType = "enum" if newEnum.has_key("name"): instanceType = newEnum["name"] for instance in newEnum["instances"]: self.nameStack = [instanceType, instance] self.evaluate_property_stack() del newEnum["instances"] def __init__(self, headerFileName, argType="file", **kwargs): """Create the parsed C++ header file parse tree headerFileName - Name of the file to parse OR actual file contents (depends on argType) argType - Indicates how to interpret headerFileName as a file string or file name kwargs - Supports the following keywords "enumMaintianValueFormat" - Set to true for enum values to maintain the original format ('j' will not convert to 106) """ ## reset global state ## global doxygenCommentCache doxygenCommentCache = "" CppVariable.Vars = [] CppStruct.Structs = [] if (argType == "file"): self.headerFileName = os.path.expandvars(headerFileName) self.mainClass = os.path.split(self.headerFileName)[1][:-2] headerFileStr = "" elif argType == "string": self.headerFileName = "" self.mainClass = "???" headerFileStr = headerFileName else: raise Exception("Arg type must be either file or string") self.curClass = "" global enumMaintianValueFormat if kwargs.has_key("enumMaintianValueFormat"): enumMaintianValueFormat = kwargs["enumMaintianValueFormat"] else: enumMaintianValueFormat = False # nested classes have parent::nested, but no extra namespace, # this keeps the API compatible, TODO proper namespace for everything. Resolver.CLASSES = {} self.classes = Resolver.CLASSES self.enums = [] self.global_enums = {} self.nameStack = [] self.nameSpaces = [] self.curAccessSpecifier = 'private' # private is default self._current_access = [] self.initextra() # harts hack if (len(self.headerFileName)): headerFileStr = "\n".join(open(self.headerFileName).readlines()) self.braceDepth = 0 lex.input(headerFileStr) curLine = 0 curChar = 0 if 1: #try: while True: tok = lex.token() if not tok: break if tok.type == 'NAME' and tok.value in self.IGNORE_NAMES: continue if tok.type not in ('PRECOMP_MACRO', 'PRECOMP_MACRO_CONT'): self.stack.append( tok.value ) curLine = tok.lineno curChar = tok.lexpos if tok.type in ('OPEN_BRACKET', 'CLOSE_BRACKET'): self.nameStack.append( tok.value ) elif (tok.type == 'OPEN_BRACE'): _brace = True if len(self.nameStack)>=2 and self.nameStack[0]=='extern' and self.nameStack[1]=='"C"': _brace = False; print( 'extern C') elif len(self.nameStack)>=2 and self.nameStack[0]=='extern' and self.nameStack[1]=='"C++"': _brace = False; print( 'extern C++' ) if _brace: self.braceDepth += 1 if len(self.nameStack) >= 2 and is_namespace(self.nameStack): # namespace {} with no name used in boost, this sets default? self.nameSpaces.append(self.nameStack[1]) ns = self.cur_namespace(); self.stack = [] if ns not in self.namespaces: self.namespaces.append( ns ) if len(self.nameStack) and not is_enum_namestack(self.nameStack): self.evaluate_stack() else: self.nameStack.append(tok.value) if self.stack and self.stack[0] == 'class': self.stack = [] #if _brace: self.braceDepth += 1 elif (tok.type == 'CLOSE_BRACE'): if self.braceDepth == 0: continue if (self.braceDepth == len(self.nameSpaces)): tmp = self.nameSpaces.pop() self.stack = [] # clear stack when namespace ends? if len(self.nameStack) and is_enum_namestack(self.nameStack): self.nameStack.append(tok.value) elif self.braceDepth < 10: self.evaluate_stack() else: self.nameStack = [] self.braceDepth -= 1 if self.braceDepth < 0: print('---------- END OF EXTERN -----------') self.braceDepth = 0 if self.curClass and debug: print( 'CURBD', self._classes_brace_level[ self.curClass ] ) if (self.braceDepth == 0) or (self.curClass and self._classes_brace_level[self.curClass] > self.braceDepth): if self.curClass: print( '------------END OF CLASS DEF-------------', 'braceDepth:', self.braceDepth ) if self._current_access: self._current_access.pop() if self.curClass and self.classes[ self.curClass ]['parent']: self.curClass = self.classes[ self.curClass ]['parent'] if self._current_access: self.curAccessSpecifier = self._current_access[-1] else: self.curClass = "" self.stack = [] #if self.curStruct: self.curStruct = None if self.braceDepth==0 or (self.curStruct and not self.curStruct['type']) or (self.curStruct and self._structs_brace_level[self.curStruct['type']] > self.braceDepth): if self.curStruct: print( '---------END OF STRUCT DEF-------------' ) if self.curStruct and not self.curStruct['type']: self._struct_needs_name = self.curStruct self.curStruct = None if self._method_body and self.braceDepth < self._method_body: self._method_body = None; self.stack = []; self.nameStack = []; print( 'FORCE CLEAR METHBODY' ) if (tok.type == 'OPEN_PAREN'): self.nameStack.append(tok.value) elif (tok.type == 'CLOSE_PAREN'): self.nameStack.append(tok.value) elif (tok.type == 'EQUALS'): self.nameStack.append(tok.value) elif (tok.type == 'COMMA'): self.nameStack.append(tok.value) elif (tok.type == 'NUMBER'): self.nameStack.append(tok.value) elif (tok.type == 'MINUS'): self.nameStack.append(tok.value) elif (tok.type == 'PLUS'): self.nameStack.append(tok.value) elif (tok.type == 'STRING_LITERAL'): self.nameStack.append(tok.value) elif (tok.type == 'NAME' or tok.type == 'AMPERSTAND' or tok.type == 'ASTERISK'): self.nameStack.append(tok.value) elif (tok.type == 'COLON'): #Dont want colon to be first in stack if len(self.nameStack) == 0: continue if self.nameStack and self.nameStack[-1] in supportedAccessSpecifier: if self.curClass or self.curStruct: cas = self.nameStack[-1] self.curAccessSpecifier = cas; print('CURACCESS-set', cas) if self.curClass: if self._current_access: self._current_access[-1] = cas else: self._current_access.append( cas ) else: print('warning - "public ::namespace"', ' '.join(self.nameStack)) self.stack = []; self.nameStack = [] # need to clear nameStack to so that nested structs can be found else: self.nameStack.append(tok.value) elif (tok.type == 'SEMI_COLON'): if (self.braceDepth < 10): self.evaluate_stack( tok.type ) if not self.stack: continue if self.stack[0]=='typedef' and ( '{' not in self.stack or '}' in self.stack ): self.stack = []; trace_print( "REAL CLEAR") elif self.stack[0] != 'typedef': self.stack = []; trace_print('CLEAR STACK') #except: # raise CppParseError("Not able to parse %s on line %d evaluating \"%s\"\nError around: %s" # % (self.headerFileName, tok.lineno, tok.value, " ".join(self.nameStack))) self.finalize() def evaluate_stack(self, token=None): """Evaluates the current name stack""" global doxygenCommentCache print( "Evaluating stack %s\nBraceDepth: %s" %(self.nameStack,self.braceDepth)) print( "Evaluating stack %s\nBraceDepth: %s" %(self.stack,self.braceDepth)) if (len(self.curClass)): if (debug): print( "%s (%s) "%(self.curClass, self.curAccessSpecifier)) #if 'typedef' in self.nameStack: self.evaluate_typedef() # allows nested typedefs, probably a bad idea if not self.curClass and 'typedef' in self.nameStack: print('HIT TYPEDEF', self.stack) if token == 'SEMI_COLON' and ('{' not in self.stack or '}' in self.stack): self.evaluate_typedef() else: return elif (len(self.nameStack) == 0): if (debug): print( "line ",lineno() ) if (debug): print( "(Empty Stack)" ) return elif (self.nameStack[0] == "namespace"): #Taken care of outside of here pass elif len(self.nameStack) >= 2 and self.nameStack[0] == 'using' and self.nameStack[1] == 'namespace': pass # TODO elif is_enum_namestack(self.nameStack): if (debug): print( "line ",lineno() ) self.evaluate_enum_stack() elif self._method_body and self.braceDepth >= self._method_body: #print( 'INSIDE METHOD DEF', self.nameStack ) self.stack = [] #elif is_method_namestack(self.stack) and '(' in self.nameStack: # this fails on "operator /(..." elif ')' in self.nameStack and is_method_namestack(self.stack): #print( 'eval method', self.nameStack ) self.evaluate_method_stack() self.stack = [] elif len(self.nameStack) >= 2 and (self.nameStack[0]=='friend' and self.nameStack[1]=='class'): pass elif ('class' in self.nameStack or 'struct' in self.nameStack) and self.stack[-1] == ';': self.evaluate_forward_decl() elif (self.nameStack[0] == "class") or (self.nameStack[0]=='template' and 'class' in self.nameStack): #print('^^^^^^^^^^^^^^^^^^^^') self.evaluate_class_stack() elif (self.nameStack[0] == "struct") or (len(self.nameStack)>3 and self.stack[-1]=='{' and self.nameStack[-3]=='struct'): print( '------------new struct-----------' ) self.evaluate_struct_stack() self.stack = [] elif self.nameStack[0]=='template' and self.stack[-1]=='{' and 'struct' in self.nameStack: print( '------------new struct - unsafe?' ) self.evaluate_struct_stack() self.stack = [] elif '(' not in self.nameStack and ')' not in self.nameStack and self.stack[-1] == ';': # catching all props? self.evaluate_property_stack() elif not self.curClass: if (debug): print( "line ",lineno() ) if is_enum_namestack(self.nameStack): self.evaluate_enum_stack() elif self.curStruct and self.stack[-1] == ';': self.evaluate_property_stack() # this catches fields of global structs self.nameStack = [] doxygenCommentCache = "" return elif (self.braceDepth < 1): if (debug): print( "line ",lineno() ) #Ignore global stuff for now if (debug): print( "Global stuff: ", self.nameStack ) self.nameStack = [] self._method_body = None doxygenCommentCache = "" return elif (self.braceDepth > len(self.nameSpaces) + 1): if (debug): print( "line ",lineno() ) self.nameStack = [] doxygenCommentCache = "" return self.nameStack = [] # some if/else above return and others not, so this may or may not be reset doxygenCommentCache = ""
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 198, 2, 6434, 25, 449, 1077, 6413, 371, 13, 1012, 448, 959, 357, 32057, 2884, 2723, 30293, 20579, 25, 6248, 1069, 5171, 271, 8, 198, 2, 198, 2, 15069, 357, 34, 8, 3050, 11, 449, 1077...
2.164682
11,926
from csv_cti.blueprints.web_api import web_api from flask import request,current_app,render_template from csv_cti.blueprints.op.md5_token import encrypt_md5 from csv_cti.blueprints.op.tiers import Tiers_op #tiers @web_api.route('/tiers-add/',methods=['POST']) @web_api.route('/tiers-rm/',methods=['POST']) @web_api.route('/tiers-list/',methods=['POST']) @web_api.route('/tiers-test/',methods=['GET'])
[ 6738, 269, 21370, 62, 310, 72, 13, 17585, 17190, 13, 12384, 62, 15042, 1330, 3992, 62, 15042, 198, 6738, 42903, 1330, 2581, 11, 14421, 62, 1324, 11, 13287, 62, 28243, 198, 6738, 269, 21370, 62, 310, 72, 13, 17585, 17190, 13, 404, 13...
2.404762
168
x = lst(1,2,3,4,5,6,7,8,9,10,11,12) print x x.move_even_to_end() print x x.reverse() print x
[ 220, 220, 220, 220, 220, 220, 220, 220, 198, 87, 796, 300, 301, 7, 16, 11, 17, 11, 18, 11, 19, 11, 20, 11, 21, 11, 22, 11, 23, 11, 24, 11, 940, 11, 1157, 11, 1065, 8, 198, 4798, 2124, 198, 87, 13, 21084, 62, 10197, 62, 1...
1.59375
64
import argparse import pandas as pd import numpy as np import os # from os.path import join import sys import logging # import joblib from sklearn.externals import joblib from sklearn.tree import DecisionTreeRegressor from sklearn.ensemble import RandomForestRegressor, AdaBoostRegressor, GradientBoostingRegressor from sklearn import metrics logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) logger.addHandler(logging.StreamHandler(sys.stdout)) if 'SAGEMAKER_METRICS_DIRECTORY' in os.environ: log_file_handler = logging.FileHandler(os.path.join(os.environ['SAGEMAKER_METRICS_DIRECTORY'], "metrics.json")) log_file_handler.setFormatter( "{'time':'%(asctime)s', 'name': '%(name)s', \ 'level': '%(levelname)s', 'message': '%(message)s'}" ) logger.addHandler(log_file_handler) if __name__ == '__main__': parser = argparse.ArgumentParser() # Hyperparameters are described here. In this simple example we are just including one hyperparameter. parser.add_argument('--model_name', type=str, default='decision_tree') parser.add_argument('--n_estimators', type=int, default=10) parser.add_argument('--max_features', type=float, default=0.5) parser.add_argument('--max_depth', type=int, default=4) parser.add_argument('--criterion', type=str, default='mse') # Sagemaker specific arguments. Defaults are set in the environment variables. parser.add_argument('--output-data-dir', type=str, default=os.environ['SM_OUTPUT_DATA_DIR']) parser.add_argument('--model-dir', type=str, default=os.environ['SM_MODEL_DIR']) parser.add_argument('--train', type=str, default=os.environ['SM_CHANNEL_TRAIN']) parser.add_argument('--validation', type=str, default=os.environ.get('SM_CHANNEL_VALIDATION')) args = parser.parse_args() logger.info("Get train data loader") train_data = pd.read_csv('{}/final_train.csv'.format(args.train), engine="python") logger.info("Get valdation data loader") validation_data = pd.read_csv('{}/final_validate.csv'.format(args.validation), engine="python") train_x = train_data.drop('unit_sales', axis=1) train_y = train_data['unit_sales'] model_name = args.model_name n_estimators = args.n_estimators max_features = args.max_features max_depth = args.max_depth criterion = args.criterion if (model_name == 'random_forest'): clf = RandomForestRegressor(random_state=None, n_estimators=n_estimators, max_features=max_features) elif (model_name == 'adaboost'): clf = AdaBoostRegressor(random_state=None, n_estimators=n_estimators) elif (model_name == 'gradient_boosting'): clf = GradientBoostingRegressor(random_state=None, n_estimators=n_estimators, max_depth=max_depth) elif (model_name == 'decision_tree'): clf = DecisionTreeRegressor(random_state=None, criterion=criterion) else: logger.debug("Invalid model name") logger.debug("Training starts") clf = clf.fit(train_x, train_y) logger.debug("Training done") # Save the model joblib.dump(clf, os.path.join(args.model_dir, "model.joblib")) logger.debug("Model written in model_dir") logger.debug("Making prediction on validation data") validation_predictions = make_predictions(clf, validation_data) logger.info('nwrmsle: {:.4f};\n'.format(eval_nwrmsle(validation_predictions, validation_data['unit_sales'].values, validation_data['perishable'].values))) logger.info('r2_score: {:.4f};\n'.format(metrics.r2_score(y_true=validation_data['unit_sales'].values, y_pred=validation_predictions)))
[ 11748, 1822, 29572, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28686, 198, 2, 422, 28686, 13, 6978, 1330, 4654, 198, 11748, 25064, 198, 11748, 18931, 198, 198, 2, 1330, 1693, 8019, 198, 6738, ...
2.389841
1,634
from discretize.utils import ( exampleLrmGrid, meshTensor, closestPoints, ExtractCoreMesh )
[ 6738, 1221, 1186, 1096, 13, 26791, 1330, 357, 198, 220, 220, 220, 1672, 43, 26224, 41339, 11, 19609, 51, 22854, 11, 11706, 40710, 11, 29677, 14055, 37031, 198, 8, 198 ]
3.2
30
import asyncio import pytest from typing import List from tests.setup_nodes import setup_full_system from src.util.ints import uint32 from src.types.full_block import FullBlock from src.util.make_test_constants import make_test_constants_with_genesis from tests.time_out_assert import time_out_assert, time_out_assert_custom_interval test_constants, bt = make_test_constants_with_genesis( { "DIFFICULTY_STARTING": 1000, "MIN_ITERS_STARTING": 100000, "NUMBER_ZERO_BITS_CHALLENGE_SIG": 1, } ) @pytest.fixture(scope="module")
[ 11748, 30351, 952, 198, 11748, 12972, 9288, 198, 6738, 19720, 1330, 7343, 198, 6738, 5254, 13, 40406, 62, 77, 4147, 1330, 9058, 62, 12853, 62, 10057, 198, 6738, 12351, 13, 22602, 13, 29503, 1330, 20398, 2624, 198, 6738, 12351, 13, 19199...
2.585253
217
from __future__ import annotations from typing import Type, Union from enum import Enum import inspect from ..base_schema import Schema from ..dom import DOMElement from ..base_schema import SchemaPrimitive, SchemaEnum def resolve_arg_to_schema(arg: Union[Type, Schema]) -> Schema: """ Resolve an argument of heterogeneous type to a `Schema` instance. :param arg: Argument to resolve to a Schema. Must be one of: A primitive Python type (str, int, bool, float) A subclass of `UserObject` An instance of `Schema`. :return: A `Schema` instance corresponding to the supplied argument. """ if inspect.isclass(arg): if issubclass(arg, DOMElement): return arg.__json_schema__() if issubclass(arg, Enum): return SchemaEnum(arg) else: return SchemaPrimitive(arg) elif isinstance(arg, Schema): return arg else: raise TypeError(f"Unexpected object type: {type(arg)}")
[ 6738, 11593, 37443, 834, 1330, 37647, 198, 198, 6738, 19720, 1330, 5994, 11, 4479, 198, 6738, 33829, 1330, 2039, 388, 198, 198, 11748, 10104, 198, 198, 6738, 11485, 8692, 62, 15952, 2611, 1330, 10011, 2611, 198, 6738, 11485, 3438, 1330, ...
2.491484
411
############################## # support query serve for front web system # filename:query.py # author: liwei # StuID: 1711350 # date: 2019.12.1 ############################## #查询构建 from whoosh import highlight from whoosh import qparser from whoosh import index from flask import Flask from flask import request from flask import jsonify,render_template,abort, redirect, url_for,session, escape,Markup from flask_cors import * import re import logging from numpy import std from data import xy_dict from data import get_html,get_teacher_info,pagerank # from audio import * app = Flask(__name__) CORS(app,supports_credentials=True) # 解决跨域请求无响应问题 app.secret_key=b'\xfa\n\x08\xb9\x84I\xe5xRdE\xea\x9f\xba\xce\x81' mysession =dict() # 自定义的session用来传输数据 url_dict,scores = pagerank(get_teacher_info()) # 获取pageranke计算结果,返回链接映射和排名得分 # 定义日志记录文件的配置 LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s" DATE_FORMAT = "%m/%d/%Y %H:%M:%S %p" logging.basicConfig(filename='my.log', level=logging.DEBUG, format=LOG_FORMAT, datefmt=DATE_FORMAT) ix = index.open_dir("index") #打开该目录一遍存储索引文件 # 网页快照路由 @app.route('/snapshots/<xueyuan>/<filename>',methods=["GET"]) # 主页路由 @app.route('/',methods=["GET"]) # 结果展示页面路由 @app.route('/display/',methods=["GET","POST"]) # 结果展示get请求页面响应 @app.route('/display/<count>&<query>') # # 实现语音输入查询 # @app.route('/audio',methods=['GET','POST']) # def audio_query(): # assert request.path == '/audio' # # 通过语音识别API获取查询输入 # get_audio(in_path) # # 测试代码 # filename = "./speechs/input.wav" # signal = open(filename, "rb").read() # rate = 16000 # token = get_token() # msg = recognize(signal, rate, token) # query_sentence = " " # if "err_no" in dict(msg).keys(): # logging.warning("%d,没有获取有效语音输入!错误消息%s 错误代码%d" %( 404,msg["err_msg"],msg["err_no"])) # return "%d,没有获取有效语音输入!错误消息%s 错误代码%d" %( 404,msg["err_msg"],msg["err_no"]), 404 # else: # query_sentence = msg['result'] # # 记录日志 # logging.info("Audio Query sentence: %s" % query_sentence) # res = [] # with ix.searcher() as searcher: # # 对输入的查询文本进行解析,如果存在按域查询的需求则区分按域查询,默认采用多属性查询模式 # # mark 表示是否需要高亮学院查询区域,默认情况下需要 # highlight_xy = True # # 默认的多域查询 # query = qparser.MultifieldParser(["content", "title", "mtext", "xueyuan"], ix.schema) # if query_sentence.endswith("$姓名$"): # # 按名字查询 # query = qparser.SimpleParser("title", ix.schema) # query_sentence = query_sentence.strip('$姓名$') # elif query_sentence.endswith("$学院$"): # # 按学院查询 # query = qparser.SimpleParser("xueyuan", ix.schema) # query_sentence = query_sentence.strip('$学院$') # # elif query_sentence.endswith("$网页$"): # # 按网页内容查询 # query = qparser.SimpleParser("content", ix.schema) # query_sentence = query_sentence.strip('$网页$') # # # print(query_sentence) # # 引入查询解析器插件 # query.add_plugin(qparser.WildcardPlugin) # # # query.remove_plugin_class(qparser.WildcardPlugin) # query.add_plugin(qparser.PrefixPlugin()) # query.add_plugin(qparser.OperatorsPlugin) # query.add_plugin(qparser.RegexPlugin) # query.add_plugin(qparser.PhrasePlugin) # # # 解析得到查询器 # q = query.parse(query_sentence) # logging.info("Query parse result: %s" % str(q)) # print(q) # # 获取查询结果 # result = searcher.search(q, limit=20) # # print(result) # # 设置碎片的属性 # # Allow larger fragments # my_cf = highlight.ContextFragmenter(maxchars=200, surround=30) # hf = highlight.HtmlFormatter(tagname='em', classname='match', termclass='term') # # hi = highlight.Highlighter(fragmenter=my_cf, formatter=hf) # for hit in result: # print(hit["picpath"]) # print(hit["title"]) # print(escape(hi.highlight_hit(hit, "content"))) # if hit['picpath'] == '#': # if highlight_xy: # res.append({"title": hit['title'], # "xueyuan": Markup(hi.highlight_hit(hit, "xueyuan")), # "url": hit["url"], # 'shotpath': hit['shotpath'], # "content": Markup(hi.highlight_hit(hit, "content")), # "parenturl": hit["parenturl"], # "picpath": '#', # "pagerank": scores[url_dict[hit["url"]]] # }) # else: # res.append({"title": hit['title'], # "xueyuan": hit["xueyuan"], # "url": hit["url"], # 'shotpath': hit['shotpath'], # "content": Markup(hi.highlight_hit(hit, "content")), # "parenturl": hit["parenturl"], # "picpath": '#', # "pagerank": scores[url_dict[hit["url"]]] # }) # else: # if highlight_xy: # res.append({"title": hit['title'], # "xueyuan": Markup(hi.highlight_hit(hit, "xueyuan")), # "url": hit["url"], # 'shotpath': hit['shotpath'], # "content": Markup(hi.highlight_hit(hit, "content")), # "parenturl": hit["parenturl"], # "picpath": "images/%s/%s" % ( # hit['picpath'].split('/')[-3], hit['picpath'].split('/')[-1]), # "pagerank": scores[url_dict[hit["url"]]] # }) # else: # res.append({"title": hit['title'], # "xueyuan": hit["xueyuan"], # "url": hit["url"], # 'shotpath': hit['shotpath'], # "content": Markup(hi.highlight_hit(hit, "content")), # "parenturl": hit["parenturl"], # "picpath": "images/%s/%s" % ( # hit['picpath'].split('/')[-3], hit['picpath'].split('/')[-1]), # "pagerank": scores[url_dict[hit["url"]]] # }) # print(len(result)) # print(res) # count = len(result) # # if count == 0: # logging.warning("%d,没有查询到相关内容!" % 404) # return "没有查询到相关内容!", 404 # else: # # 记录查询日志 # log = "Response: " # for item in res: # log = log + " (name:%s,url:%s) " % (item["title"], item["url"]) # logging.info(log) # # # # 基于page rank 对链接进行排序 # # res.sort(key=lambda k:(k.get("pagerank",0)),reverse = True) # # print(res) # # mysession["data"] = res # 使用会话session传递参数 # return jsonify({"url": "/display/%d&%s" % (count, query_sentence)}) # 基本查询函数,实现前缀、通配、正则匹配,短语、关系运算查询功能 # 基于whoosh的highlighter实现返回高亮查询词块 @app.route('/index',methods=['GET','POST']) if __name__ == '__main__': app.run(debug=False,use_reloader=False)
[ 14468, 7804, 4242, 2235, 198, 2, 1104, 12405, 4691, 329, 2166, 3992, 1080, 198, 2, 29472, 25, 22766, 13, 9078, 198, 2, 1772, 25, 220, 7649, 42990, 198, 2, 520, 84, 2389, 25, 220, 220, 1596, 1157, 14877, 198, 2, 3128, 25, 220, 220,...
1.531307
4,903
""" Make time series plots. """ import galene as ga import datetime data_id_list = [ 'cmems-nrt', 'run001', 'run002', ] var_list = ['slev', 'temp'] start_time = datetime.datetime(2016, 6, 1) end_time = datetime.datetime(2018, 7, 1) for var in var_list: dataset_list = [] for data_id in data_id_list: d = ga.read_dataset(data_id, 'timeseries', var) dataset_list.append(d) # find pairs pairs = ga.find_station_pairs(*dataset_list) for key in pairs: try: cube_list = [] for data_id in data_id_list: if data_id in pairs[key]: cube = pairs[key][data_id] cube_list.append(cube) data_id_str = '-'.join(data_id_list) datatype = 'timeseries' outdir = os.path.join('plots', data_id_str, datatype, var) ga.save_timeseries_figure( cube_list, output_dir=outdir, alpha=0.7, start_time=start_time, end_time=end_time, time_extent='intersection' ) except Exception: pass
[ 37811, 198, 12050, 640, 2168, 21528, 13, 198, 37811, 198, 11748, 9426, 1734, 355, 31986, 198, 11748, 4818, 8079, 198, 198, 7890, 62, 312, 62, 4868, 796, 685, 198, 220, 220, 220, 705, 11215, 5232, 12, 77, 17034, 3256, 198, 220, 220, ...
1.948944
568
import numpy as np import copy from . import cv #TODO need to refactaring
[ 11748, 299, 32152, 355, 45941, 198, 11748, 4866, 198, 198, 6738, 764, 1330, 269, 85, 198, 198, 2, 51, 3727, 46, 761, 284, 1006, 529, 1723 ]
2.884615
26
""" three-layers logistic regression model for not-MNIST dataset Got ~ 87% accuracy. not-MNIST: http://yaroslavvb. blogspot. it/2011/09/notmnist-dataset.html author: ANDY (andy929910266@gmail.com) """ import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' import numpy as np import tensorflow as tf import time import utils # Define paramaters for the model learning_rate = 0.01 batch_size = 128 n_epochs = 50 n_train = 60000 n_test = 10000 # Step 1: Read in data not_mnist_folder = "../../examples/data/not-mnist" # I download the data manually and save into respective non-mnist_folder # use utils.download_mnist(not_mnist_folder) train, val, test = utils.read_mnist(not_mnist_folder, flatten=True) # Step 2: Create datasets and iterator # create training Dataset and batch it train_data = tf.data.Dataset.from_tensor_slices(train) train_data = train_data.shuffle(10000) # if you want to shuffle your data train_data = train_data.batch(batch_size) # create testing Dataset and batch it test_data = tf.data.Dataset.from_tensor_slices(test) test_data = test_data.batch(batch_size) # create one iterator and initialize it with different datasets iterator = tf.data.Iterator.from_structure(train_data.output_types, train_data.output_shapes) img, label = iterator.get_next() train_init = iterator.make_initializer(train_data) # initializer for train_data test_init = iterator.make_initializer(test_data) # initializer for train_data # Step 3: create weights and bias # weights are initialized to random variables with mean of 0, stddev of 0.01 # biases are initialized to 0 # shape of w1 --> (784,256) # shape of b1 --> (1,256) # shape of w2 --> (256,128) # shape of b2 --> (1,128) # shape of w3 --> (128,10) # shape of b3 --> (1,10) w1 = tf.get_variable(name="weight1", shape=[784, 256], initializer=tf.random_normal_initializer()) b1 = tf.get_variable(name="bias1", shape=[1, 256], initializer=tf.zeros_initializer()) w2 = tf.get_variable(name="weight2", shape=[256, 128], initializer=tf.random_normal_initializer()) b2 = tf.get_variable(name="bias2", shape=[1, 128], initializer=tf.zeros_initializer()) w3 = tf.get_variable(name="weight3", shape=[128, 10], initializer=tf.random_normal_initializer()) b3 = tf.get_variable(name="bias3", shape=[1, 10], initializer=tf.zeros_initializer()) # Step 4: build model # the model that returns the logits. # this logits will be later passed through softmax layer hidden_layer1 = tf.matmul(img, w1) + b1 hidden_layer2 = tf.matmul(hidden_layer1, w2) + b2 logits = tf.matmul(hidden_layer2, w3) + b3 # Step 5: define loss function # use cross entropy of softmax of logits as the loss function entropy = tf.nn.softmax_cross_entropy_with_logits_v2(labels=label, logits=logits, name="entopy") loss = tf.reduce_mean(entropy, name="loss") # Step 6: define optimizer # using Adamn Optimizer with pre-defined learning rate to minimize loss optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss) # Step 7: calculate accuracy with test set preds = tf.nn.softmax(logits) correct_preds = tf.equal(tf.argmax(preds, 1), tf.argmax(label, 1)) accuracy = tf.reduce_sum(tf.cast(correct_preds, tf.float32)) writer = tf.summary.FileWriter('../../examples/graphs/not-mnist', tf.get_default_graph()) with tf.Session() as sess: start_time = time.time() sess.run(tf.global_variables_initializer()) # train the model n_epochs times for i in range(n_epochs): sess.run(train_init) # drawing samples from train_data total_loss = 0 n_batches = 0 try: while True: _, l = sess.run([optimizer, loss]) total_loss += l n_batches += 1 except tf.errors.OutOfRangeError: pass print('Average loss epoch {0}: {1}'.format(i, total_loss / n_batches)) print('Total time: {0} seconds'.format(time.time() - start_time)) # test the model sess.run(test_init) # drawing samples from test_data total_correct_preds = 0 try: while True: accuracy_batch = sess.run(accuracy) total_correct_preds += accuracy_batch except tf.errors.OutOfRangeError: pass print('Accuracy {0}'.format(total_correct_preds / n_test)) writer.close()
[ 37811, 198, 197, 15542, 12, 75, 6962, 2604, 2569, 20683, 2746, 329, 407, 12, 39764, 8808, 27039, 198, 197, 30074, 5299, 10083, 4, 9922, 13, 198, 197, 1662, 12, 39764, 8808, 25, 2638, 1378, 88, 283, 26388, 85, 65, 13, 4130, 20485, 13...
2.751333
1,500
import click from collections import defaultdict import importlib import logging import redis import structlog from .redis_scripts import RedisScripts from ._internal import * from .exceptions import * from .retry import * from .schedule import * from .task import Task from .worker import Worker __all__ = ['TaskTiger', 'Worker', 'Task', # Exceptions 'JobTimeoutException', 'RetryException', 'StopRetry', 'TaskImportError', 'TaskNotFound', # Retry methods 'fixed', 'linear', 'exponential', # Schedules 'periodic', ] """ Redis keys: Set of all queues that contain items in the given state. SET <prefix>:queued SET <prefix>:active SET <prefix>:error SET <prefix>:scheduled Serialized task for the given task ID. STRING <prefix>:task:<task_id> List of (failed) task executions LIST <prefix>:task:<task_id>:executions Task IDs waiting in the given queue to be processed, scored by the time the task was queued. ZSET <prefix>:queued:<queue> Task IDs being processed in the specific queue, scored by the time processing started. ZSET <prefix>:active:<queue> Task IDs that failed, scored by the time processing failed. ZSET <prefix>:error:<queue> Task IDs that are scheduled to be executed at a specific time, scored by the time they should be executed. ZSET <prefix>:scheduled:<queue> Channel that receives the queue name as a message whenever a task is queued. CHANNEL <prefix>:activity Task locks STRING <prefix>:lock:<lock_hash> Queue periodic tasks lock STRING <prefix>:queue_periodic_tasks_lock """ @click.command() @click.option('-q', '--queues', help='If specified, only the given queue(s) ' 'are processed. Multiple queues can be ' 'separated by comma.') @click.option('-m', '--module', help="Module(s) to import when launching the " "worker. This improves task performance " "since the module doesn't have to be " "reimported every time a task is forked. " "Multiple modules can be separated by " "comma.") @click.option('-e', '--exclude-queues', help='If specified, exclude the given ' 'queue(s) from processing. ' 'Multiple queues can be ' 'separated by comma.') @click.option('-h', '--host', help='Redis server hostname') @click.option('-p', '--port', help='Redis server port') @click.option('-a', '--password', help='Redis password') @click.option('-n', '--db', help='Redis database number') @click.pass_context if __name__ == '__main__': run_worker()
[ 11748, 3904, 198, 6738, 17268, 1330, 4277, 11600, 198, 11748, 1330, 8019, 198, 11748, 18931, 198, 11748, 2266, 271, 198, 11748, 2878, 6404, 198, 198, 6738, 764, 445, 271, 62, 46521, 1330, 2297, 271, 7391, 82, 198, 198, 6738, 47540, 3253...
2.405542
1,191
# auxiliary from MDAOfabric.accessories import * # solvers from MDAOfabric.solvers import *
[ 2, 37419, 198, 6738, 337, 5631, 5189, 397, 1173, 13, 15526, 1749, 1330, 1635, 198, 198, 2, 1540, 690, 198, 6738, 337, 5631, 5189, 397, 1173, 13, 34453, 690, 1330, 1635, 198 ]
2.90625
32
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'AnalysisPlotWidgetTemplate.ui' # # Created: Mon Aug 16 15:31:49 2010 # by: PyQt4 UI code generator 4.5.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui from acq4.pyqtgraph.PlotWidget import PlotWidget
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 5178, 7822, 7560, 422, 3555, 334, 72, 2393, 705, 32750, 43328, 38300, 30800, 13, 9019, 6, 198, 2, 198, 2, 15622, 25, 2892, 2447, 1467, 1315, 25, 3132, 25, 29...
2.836207
116
r""" Balanced Incomplete Block Designs (BIBD) This module gathers everything related to Balanced Incomplete Block Designs. One can build a BIBD (or check that it can be built) with :func:`balanced_incomplete_block_design`:: sage: BIBD = designs.balanced_incomplete_block_design(7,3) In particular, Sage can build a `(v,k,1)`-BIBD when one exists for all `k\leq 5`. The following functions are available: .. csv-table:: :class: contentstable :widths: 30, 70 :delim: | :func:`balanced_incomplete_block_design` | Return a BIBD of parameters `v,k`. :func:`BIBD_from_TD` | Return a BIBD through TD-based constructions. :func:`BIBD_from_difference_family` | Return the BIBD associated to the difference family ``D`` on the group ``G``. :func:`BIBD_from_PBD` | Return a `(v,k,1)`-BIBD from a `(r,K)`-PBD where `r=(v-1)/(k-1)`. :func:`PBD_from_TD` | Return a `(kt,\{k,t\})`-PBD if `u=0` and a `(kt+u,\{k,k+1,t,u\})`-PBD otherwise. :func:`steiner_triple_system` | Return a Steiner Triple System. :func:`v_5_1_BIBD` | Return a `(v,5,1)`-BIBD. :func:`v_4_1_BIBD` | Return a `(v,4,1)`-BIBD. :func:`PBD_4_5_8_9_12` | Return a `(v,\{4,5,8,9,12\})`-PBD on `v` elements. :func:`BIBD_5q_5_for_q_prime_power` | Return a `(5q,5,1)`-BIBD with `q\equiv 1\pmod 4` a prime power. **Construction of BIBD when** `k=4` Decompositions of `K_v` into `K_4` (i.e. `(v,4,1)`-BIBD) are built following Douglas Stinson's construction as presented in [Stinson2004]_ page 167. It is based upon the construction of `(v\{4,5,8,9,12\})`-PBD (see the doc of :func:`PBD_4_5_8_9_12`), knowing that a `(v\{4,5,8,9,12\})`-PBD on `v` points can always be transformed into a `((k-1)v+1,4,1)`-BIBD, which covers all possible cases of `(v,4,1)`-BIBD. **Construction of BIBD when** `k=5` Decompositions of `K_v` into `K_4` (i.e. `(v,4,1)`-BIBD) are built following Clayton Smith's construction [ClaytonSmith]_. .. [ClaytonSmith] On the existence of `(v,5,1)`-BIBD. http://www.argilo.net/files/bibd.pdf Clayton Smith Functions --------- """ from sage.categories.sets_cat import EmptySetError from sage.misc.unknown import Unknown from design_catalog import transversal_design from block_design import BlockDesign from sage.rings.arith import binomial, is_prime_power from group_divisible_designs import GroupDivisibleDesign from designs_pyx import is_pairwise_balanced_design def balanced_incomplete_block_design(v, k, existence=False, use_LJCR=False): r""" Return a BIBD of parameters `v,k`. A Balanced Incomplete Block Design of parameters `v,k` is a collection `\mathcal C` of `k`-subsets of `V=\{0,\dots,v-1\}` such that for any two distinct elements `x,y\in V` there is a unique element `S\in \mathcal C` such that `x,y\in S`. More general definitions sometimes involve a `\lambda` parameter, and we assume here that `\lambda=1`. For more information on BIBD, see the :wikipedia:`corresponding Wikipedia entry <Block_design#Definition_of_a_BIBD_.28or_2-design.29>`. INPUT: - ``v,k`` (integers) - ``existence`` (boolean) -- instead of building the design, return: - ``True`` -- meaning that Sage knows how to build the design - ``Unknown`` -- meaning that Sage does not know how to build the design, but that the design may exist (see :mod:`sage.misc.unknown`). - ``False`` -- meaning that the design does not exist. - ``use_LJCR`` (boolean) -- whether to query the La Jolla Covering Repository for the design when Sage does not know how to build it (see :func:`~sage.combinat.designs.covering_design.best_known_covering_design_www`). This requires internet. .. SEEALSO:: * :func:`steiner_triple_system` * :func:`v_4_1_BIBD` * :func:`v_5_1_BIBD` TODO: * Implement other constructions from the Handbook of Combinatorial Designs. EXAMPLES:: sage: designs.balanced_incomplete_block_design(7, 3).blocks() [[0, 1, 3], [0, 2, 4], [0, 5, 6], [1, 2, 6], [1, 4, 5], [2, 3, 5], [3, 4, 6]] sage: B = designs.balanced_incomplete_block_design(66, 6, use_LJCR=True) # optional - internet sage: B # optional - internet Incidence structure with 66 points and 143 blocks sage: B.blocks() # optional - internet [[0, 1, 2, 3, 4, 65], [0, 5, 24, 25, 39, 57], [0, 6, 27, 38, 44, 55], ... sage: designs.balanced_incomplete_block_design(66, 6, use_LJCR=True) # optional - internet Incidence structure with 66 points and 143 blocks sage: designs.balanced_incomplete_block_design(216, 6) Traceback (most recent call last): ... NotImplementedError: I don't know how to build a (216,6,1)-BIBD! TESTS:: sage: designs.balanced_incomplete_block_design(85,5,existence=True) True sage: _ = designs.balanced_incomplete_block_design(85,5) A BIBD from a Finite Projective Plane:: sage: _ = designs.balanced_incomplete_block_design(21,5) Some trivial BIBD:: sage: designs.balanced_incomplete_block_design(10,10) (10,10,1)-Balanced Incomplete Block Design sage: designs.balanced_incomplete_block_design(1,10) (1,0,1)-Balanced Incomplete Block Design Existence of BIBD with `k=3,4,5`:: sage: [v for v in xrange(50) if designs.balanced_incomplete_block_design(v,3,existence=True)] [1, 3, 7, 9, 13, 15, 19, 21, 25, 27, 31, 33, 37, 39, 43, 45, 49] sage: [v for v in xrange(100) if designs.balanced_incomplete_block_design(v,4,existence=True)] [1, 4, 13, 16, 25, 28, 37, 40, 49, 52, 61, 64, 73, 76, 85, 88, 97] sage: [v for v in xrange(150) if designs.balanced_incomplete_block_design(v,5,existence=True)] [1, 5, 21, 25, 41, 45, 61, 65, 81, 85, 101, 105, 121, 125, 141, 145] For `k > 5` there are currently very few constructions:: sage: [v for v in xrange(300) if designs.balanced_incomplete_block_design(v,6,existence=True) is True] [1, 6, 31, 66, 76, 91, 96, 106, 111, 121, 126, 136, 141, 151, 156, 171, 181, 186, 196, 201, 211, 241, 271] sage: [v for v in xrange(300) if designs.balanced_incomplete_block_design(v,6,existence=True) is Unknown] [51, 61, 81, 166, 216, 226, 231, 246, 256, 261, 276, 286, 291] Here are some constructions with `k \geq 7` and `v` a prime power:: sage: designs.balanced_incomplete_block_design(169,7) (169,7,1)-Balanced Incomplete Block Design sage: designs.balanced_incomplete_block_design(617,8) (617,8,1)-Balanced Incomplete Block Design sage: designs.balanced_incomplete_block_design(433,9) (433,9,1)-Balanced Incomplete Block Design sage: designs.balanced_incomplete_block_design(1171,10) (1171,10,1)-Balanced Incomplete Block Design And we know some inexistence results:: sage: designs.balanced_incomplete_block_design(21,6,existence=True) False """ lmbd = 1 # Trivial BIBD if v == 1: if existence: return True return BalancedIncompleteBlockDesign(v, [], check=False) if k == v: if existence: return True return BalancedIncompleteBlockDesign(v, [range(v)], check=False, copy=False) # Non-existence of BIBD if (v < k or k < 2 or (v-1) % (k-1) != 0 or (v*(v-1)) % (k*(k-1)) != 0 or # From the Handbook of combinatorial designs: # # With lambda>1 other exceptions are # (15,5,2),(21,6,2),(22,7,2),(22,8,4). (k==6 and v in [36,46]) or (k==7 and v == 43) or # Fisher's inequality (v*(v-1))/(k*(k-1)) < v): if existence: return False raise EmptySetError("There exists no ({},{},{})-BIBD".format(v,k,lmbd)) if k == 2: if existence: return True from itertools import combinations return BalancedIncompleteBlockDesign(v, combinations(range(v),2), check=False, copy=True) if k == 3: if existence: return v%6 == 1 or v%6 == 3 return steiner_triple_system(v) if k == 4: if existence: return v%12 == 1 or v%12 == 4 return BalancedIncompleteBlockDesign(v, v_4_1_BIBD(v), copy=False) if k == 5: if existence: return v%20 == 1 or v%20 == 5 return BalancedIncompleteBlockDesign(v, v_5_1_BIBD(v), copy=False) from difference_family import difference_family from database import BIBD_constructions if (v,k,1) in BIBD_constructions: if existence: return True return BlockDesign(v,BIBD_constructions[(v,k,1)](), copy=False) if BIBD_from_arc_in_desarguesian_projective_plane(v,k,existence=True): if existence: return True B = BIBD_from_arc_in_desarguesian_projective_plane(v,k) return BalancedIncompleteBlockDesign(v, B, copy=False) if BIBD_from_TD(v,k,existence=True): if existence: return True return BalancedIncompleteBlockDesign(v, BIBD_from_TD(v,k), copy=False) if v == (k-1)**2+k and is_prime_power(k-1): if existence: return True from block_design import projective_plane return BalancedIncompleteBlockDesign(v, projective_plane(k-1),copy=False) if difference_family(v,k,existence=True): if existence: return True G,D = difference_family(v,k) return BalancedIncompleteBlockDesign(v, BIBD_from_difference_family(G,D,check=False), copy=False) if use_LJCR: from covering_design import best_known_covering_design_www B = best_known_covering_design_www(v,k,2) # Is it a BIBD or just a good covering ? expected_n_of_blocks = binomial(v,2)/binomial(k,2) if B.low_bd() > expected_n_of_blocks: if existence: return False raise EmptySetError("There exists no ({},{},{})-BIBD".format(v,k,lmbd)) B = B.incidence_structure() if B.num_blocks() == expected_n_of_blocks: if existence: return True else: return B if existence: return Unknown else: raise NotImplementedError("I don't know how to build a ({},{},1)-BIBD!".format(v,k)) def steiner_triple_system(n): r""" Return a Steiner Triple System A Steiner Triple System (STS) of a set `\{0,...,n-1\}` is a family `S` of 3-sets such that for any `i \not = j` there exists exactly one set of `S` in which they are both contained. It can alternatively be thought of as a factorization of the complete graph `K_n` with triangles. A Steiner Triple System of a `n`-set exists if and only if `n \equiv 1 \pmod 6` or `n \equiv 3 \pmod 6`, in which case one can be found through Bose's and Skolem's constructions, respectively [AndHonk97]_. INPUT: - ``n`` return a Steiner Triple System of `\{0,...,n-1\}` EXAMPLE: A Steiner Triple System on `9` elements :: sage: sts = designs.steiner_triple_system(9) sage: sts (9,3,1)-Balanced Incomplete Block Design sage: list(sts) [[0, 1, 5], [0, 2, 4], [0, 3, 6], [0, 7, 8], [1, 2, 3], [1, 4, 7], [1, 6, 8], [2, 5, 8], [2, 6, 7], [3, 4, 8], [3, 5, 7], [4, 5, 6]] As any pair of vertices is covered once, its parameters are :: sage: sts.is_t_design(return_parameters=True) (True, (2, 9, 3, 1)) An exception is raised for invalid values of ``n`` :: sage: designs.steiner_triple_system(10) Traceback (most recent call last): ... EmptySetError: Steiner triple systems only exist for n = 1 mod 6 or n = 3 mod 6 REFERENCE: .. [AndHonk97] A short course in Combinatorial Designs, Ian Anderson, Iiro Honkala, Internet Editions, Spring 1997, http://www.utu.fi/~honkala/designs.ps """ name = "Steiner Triple System on "+str(n)+" elements" if n%6 == 3: t = (n-3) // 6 Z = range(2*t+1) T = lambda x_y : x_y[0] + (2*t+1)*x_y[1] sts = [[(i,0),(i,1),(i,2)] for i in Z] + \ [[(i,k),(j,k),(((t+1)*(i+j)) % (2*t+1),(k+1)%3)] for k in range(3) for i in Z for j in Z if i != j] elif n%6 == 1: t = (n-1) // 6 N = range(2*t) T = lambda x_y : x_y[0]+x_y[1]*t*2 if x_y != (-1,-1) else n-1 L1 = lambda i,j : (i+j) % ((n-1)//3) L = lambda i,j : L1(i,j)//2 if L1(i,j)%2 == 0 else t+(L1(i,j)-1)//2 sts = [[(i,0),(i,1),(i,2)] for i in range(t)] + \ [[(-1,-1),(i,k),(i-t,(k+1) % 3)] for i in range(t,2*t) for k in [0,1,2]] + \ [[(i,k),(j,k),(L(i,j),(k+1) % 3)] for k in [0,1,2] for i in N for j in N if i < j] else: raise EmptySetError("Steiner triple systems only exist for n = 1 mod 6 or n = 3 mod 6") # apply T and remove duplicates sts = set(frozenset(T(xx) for xx in x) for x in sts) return BalancedIncompleteBlockDesign(n, sts, name=name,check=False) def BIBD_from_TD(v,k,existence=False): r""" Return a BIBD through TD-based constructions. INPUT: - ``v,k`` (integers) -- computes a `(v,k,1)`-BIBD. - ``existence`` (boolean) -- instead of building the design, return: - ``True`` -- meaning that Sage knows how to build the design - ``Unknown`` -- meaning that Sage does not know how to build the design, but that the design may exist (see :mod:`sage.misc.unknown`). - ``False`` -- meaning that the design does not exist. This method implements three constructions: - If there exists a `TD(k,v)` and a `(v,k,1)`-BIBD then there exists a `(kv,k,1)`-BIBD. The BIBD is obtained from all blocks of the `TD`, and from the blocks of the `(v,k,1)`-BIBDs defined over the `k` groups of the `TD`. - If there exists a `TD(k,v)` and a `(v+1,k,1)`-BIBD then there exists a `(kv+1,k,1)`-BIBD. The BIBD is obtained from all blocks of the `TD`, and from the blocks of the `(v+1,k,1)`-BIBDs defined over the sets `V_1\cup \infty,\dots,V_k\cup \infty` where the `V_1,\dots,V_k` are the groups of the TD. - If there exists a `TD(k,v)` and a `(v+k,k,1)`-BIBD then there exists a `(kv+k,k,1)`-BIBD. The BIBD is obtained from all blocks of the `TD`, and from the blocks of the `(v+k,k,1)`-BIBDs defined over the sets `V_1\cup \{\infty_1,\dots,\infty_k\},\dots,V_k\cup \{\infty_1,\dots,\infty_k\}` where the `V_1,\dots,V_k` are the groups of the TD. By making sure that all copies of the `(v+k,k,1)`-BIBD contain the block `\{\infty_1,\dots,\infty_k\}`, the result is also a BIBD. These constructions can be found in `<http://www.argilo.net/files/bibd.pdf>`_. EXAMPLES: First construction:: sage: from sage.combinat.designs.bibd import BIBD_from_TD sage: BIBD_from_TD(25,5,existence=True) True sage: _ = BlockDesign(25,BIBD_from_TD(25,5)) Second construction:: sage: from sage.combinat.designs.bibd import BIBD_from_TD sage: BIBD_from_TD(21,5,existence=True) True sage: _ = BlockDesign(21,BIBD_from_TD(21,5)) Third construction:: sage: from sage.combinat.designs.bibd import BIBD_from_TD sage: BIBD_from_TD(85,5,existence=True) True sage: _ = BlockDesign(85,BIBD_from_TD(85,5)) No idea:: sage: from sage.combinat.designs.bibd import BIBD_from_TD sage: BIBD_from_TD(20,5,existence=True) Unknown sage: BIBD_from_TD(20,5) Traceback (most recent call last): ... NotImplementedError: I do not know how to build a (20,5,1)-BIBD! """ # First construction if (v%k == 0 and balanced_incomplete_block_design(v//k,k,existence=True) and transversal_design(k,v//k,existence=True)): if existence: return True v = v//k BIBDvk = balanced_incomplete_block_design(v,k)._blocks TDkv = transversal_design(k,v,check=False) BIBD = TDkv._blocks for i in range(k): BIBD.extend([[x+i*v for x in B] for B in BIBDvk]) # Second construction elif ((v-1)%k == 0 and balanced_incomplete_block_design((v-1)//k+1,k,existence=True) and transversal_design(k,(v-1)//k,existence=True)): if existence: return True v = (v-1)//k BIBDv1k = balanced_incomplete_block_design(v+1,k)._blocks TDkv = transversal_design(k,v,check=False)._blocks inf = v*k BIBD = TDkv for i in range(k): BIBD.extend([[inf if x == v else x+i*v for x in B] for B in BIBDv1k]) # Third construction elif ((v-k)%k == 0 and balanced_incomplete_block_design((v-k)//k+k,k,existence=True) and transversal_design(k,(v-k)//k,existence=True)): if existence: return True v = (v-k)//k BIBDvpkk = balanced_incomplete_block_design(v+k,k) TDkv = transversal_design(k,v,check=False)._blocks inf = v*k BIBD = TDkv # makes sure that [v,...,v+k-1] is a block of BIBDvpkk. Then, we remove it. BIBDvpkk = _relabel_bibd(BIBDvpkk,v+k) BIBDvpkk = [B for B in BIBDvpkk if min(B) < v] for i in range(k): BIBD.extend([[(x-v)+inf if x >= v else x+i*v for x in B] for B in BIBDvpkk]) BIBD.append(range(k*v,v*k+k)) # No idea ... else: if existence: return Unknown else: raise NotImplementedError("I do not know how to build a ({},{},1)-BIBD!".format(v,k)) return BIBD def BIBD_from_difference_family(G, D, lambd=None, check=True): r""" Return the BIBD associated to the difference family ``D`` on the group ``G``. Let `G` be a group. A `(G,k,\lambda)`-*difference family* is a family `B = \{B_1,B_2,\ldots,B_b\}` of `k`-subsets of `G` such that for each element of `G \backslash \{0\}` there exists exactly `\lambda` pairs of elements `(x,y)`, `x` and `y` belonging to the same block, such that `x - y = g` (or x y^{-1} = g` in multiplicative notation). If `\{B_1, B_2, \ldots, B_b\}` is a `(G,k,\lambda)`-difference family then its set of translates `\{B_i \cdot g; i \in \{1,\ldots,b\}, g \in G\}` is a `(v,k,\lambda)`-BIBD where `v` is the cardinality of `G`. INPUT: - ``G`` - a finite additive Abelian group - ``D`` - a difference family on ``G`` (short blocks are allowed). - ``lambd`` - the `\lambda` parameter (optional, only used if ``check`` is ``True``) - ``check`` - whether or not we check the output (default: ``True``) EXAMPLES:: sage: G = Zmod(21) sage: D = [[0,1,4,14,16]] sage: print sorted(G(x-y) for x in D[0] for y in D[0] if x != y) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] sage: from sage.combinat.designs.bibd import BIBD_from_difference_family sage: BIBD_from_difference_family(G, D) [[0, 1, 4, 14, 16], [1, 2, 5, 15, 17], [2, 3, 6, 16, 18], [3, 4, 7, 17, 19], [4, 5, 8, 18, 20], [5, 6, 9, 19, 0], [6, 7, 10, 20, 1], [7, 8, 11, 0, 2], [8, 9, 12, 1, 3], [9, 10, 13, 2, 4], [10, 11, 14, 3, 5], [11, 12, 15, 4, 6], [12, 13, 16, 5, 7], [13, 14, 17, 6, 8], [14, 15, 18, 7, 9], [15, 16, 19, 8, 10], [16, 17, 20, 9, 11], [17, 18, 0, 10, 12], [18, 19, 1, 11, 13], [19, 20, 2, 12, 14], [20, 0, 3, 13, 15]] """ from difference_family import group_law, block_stabilizer identity, mul, inv = group_law(G) bibd = [] Gset = set(G) p_to_i = {g:i for i,g in enumerate(Gset)} for b in D: b = [G(_) for _ in b] S = block_stabilizer(G,b) GG = Gset.copy() while GG: g = GG.pop() if S: GG.difference_update(mul(s,g) for s in S) bibd.append([p_to_i[mul(i,g)] for i in b]) if check: if lambd is None: k = len(bibd[0]) v = G.cardinality() lambd = (len(bibd) * k * (k-1)) // (v * (v-1)) assert is_pairwise_balanced_design(bibd, G.cardinality(), [len(D[0])], lambd=lambd) return bibd ################ # (v,4,1)-BIBD # ################ def v_4_1_BIBD(v, check=True): r""" Return a `(v,4,1)`-BIBD. A `(v,4,1)`-BIBD is an edge-decomposition of the complete graph `K_v` into copies of `K_4`. For more information, see :func:`balanced_incomplete_block_design`. It exists if and only if `v\equiv 1,4 \pmod {12}`. See page 167 of [Stinson2004]_ for the construction details. .. SEEALSO:: * :func:`balanced_incomplete_block_design` INPUT: - ``v`` (integer) -- number of points. - ``check`` (boolean) -- whether to check that output is correct before returning it. As this is expected to be useless (but we are cautious guys), you may want to disable it whenever you want speed. Set to ``True`` by default. EXAMPLES:: sage: from sage.combinat.designs.bibd import v_4_1_BIBD # long time sage: for n in range(13,100): # long time ....: if n%12 in [1,4]: # long time ....: _ = v_4_1_BIBD(n, check = True) # long time TESTS: Check that the `(25,4)` and `(37,4)`-difference family are available:: sage: assert designs.difference_family(25,4,existence=True) sage: _ = designs.difference_family(25,4) sage: assert designs.difference_family(37,4,existence=True) sage: _ = designs.difference_family(37,4) Check some larger `(v,4,1)`-BIBD (see :trac:`17557`):: sage: for v in range(400): # long time ....: if v%12 in [1,4]: # long time ....: _ = designs.balanced_incomplete_block_design(v,4) # long time """ k = 4 if v == 0: return [] if v <= 12 or v%12 not in [1,4]: raise EmptySetError("A K_4-decomposition of K_v exists iif v=2,4 mod 12, v>12 or v==0") # Step 1. Base cases. if v == 13: # note: this construction can also be obtained from difference_family from block_design import projective_plane return projective_plane(3)._blocks if v == 16: from block_design import AffineGeometryDesign from sage.rings.finite_rings.constructor import FiniteField return AffineGeometryDesign(2,1,FiniteField(4,'x'))._blocks if v == 25 or v == 37: from difference_family import difference_family G,D = difference_family(v,4) return BIBD_from_difference_family(G,D,check=False) if v == 28: return [[0, 1, 23, 26], [0, 2, 10, 11], [0, 3, 16, 18], [0, 4, 15, 20], [0, 5, 8, 9], [0, 6, 22, 25], [0, 7, 14, 21], [0, 12, 17, 27], [0, 13, 19, 24], [1, 2, 24, 27], [1, 3, 11, 12], [1, 4, 17, 19], [1, 5, 14, 16], [1, 6, 9, 10], [1, 7, 20, 25], [1, 8, 15, 22], [1, 13, 18, 21], [2, 3, 21, 25], [2, 4, 12, 13], [2, 5, 18, 20], [2, 6, 15, 17], [2, 7, 19, 22], [2, 8, 14, 26], [2, 9, 16, 23], [3, 4, 22, 26], [3, 5, 7, 13], [3, 6, 14, 19], [3, 8, 20, 23], [3, 9, 15, 27], [3, 10, 17, 24], [4, 5, 23, 27], [4, 6, 7, 8], [4, 9, 14, 24], [4, 10, 16, 21], [4, 11, 18, 25], [5, 6, 21, 24], [5, 10, 15, 25], [5, 11, 17, 22], [5, 12, 19, 26], [6, 11, 16, 26], [6, 12, 18, 23], [6, 13, 20, 27], [7, 9, 17, 18], [7, 10, 26, 27], [7, 11, 23, 24], [7, 12, 15, 16], [8, 10, 18, 19], [8, 11, 21, 27], [8, 12, 24, 25], [8, 13, 16, 17], [9, 11, 19, 20], [9, 12, 21, 22], [9, 13, 25, 26], [10, 12, 14, 20], [10, 13, 22, 23], [11, 13, 14, 15], [14, 17, 23, 25], [14, 18, 22, 27], [15, 18, 24, 26], [15, 19, 21, 23], [16, 19, 25, 27], [16, 20, 22, 24], [17, 20, 21, 26]] # Step 2 : this is function PBD_4_5_8_9_12 PBD = PBD_4_5_8_9_12((v-1)/(k-1),check=False) # Step 3 : Theorem 7.20 bibd = BIBD_from_PBD(PBD,v,k,check=False) if check: assert is_pairwise_balanced_design(bibd,v,[k]) return bibd def BIBD_from_PBD(PBD,v,k,check=True,base_cases={}): r""" Return a `(v,k,1)`-BIBD from a `(r,K)`-PBD where `r=(v-1)/(k-1)`. This is Theorem 7.20 from [Stinson2004]_. INPUT: - ``v,k`` -- integers. - ``PBD`` -- A PBD on `r=(v-1)/(k-1)` points, such that for any block of ``PBD`` of size `s` there must exist a `((k-1)s+1,k,1)`-BIBD. - ``check`` (boolean) -- whether to check that output is correct before returning it. As this is expected to be useless (but we are cautious guys), you may want to disable it whenever you want speed. Set to ``True`` by default. - ``base_cases`` -- caching system, for internal use. EXAMPLES:: sage: from sage.combinat.designs.bibd import PBD_4_5_8_9_12 sage: from sage.combinat.designs.bibd import BIBD_from_PBD sage: from sage.combinat.designs.bibd import is_pairwise_balanced_design sage: PBD = PBD_4_5_8_9_12(17) sage: bibd = is_pairwise_balanced_design(BIBD_from_PBD(PBD,52,4),52,[4]) """ r = (v-1) // (k-1) bibd = [] for X in PBD: n = len(X) N = (k-1)*n+1 if not (n,k) in base_cases: base_cases[n,k] = _relabel_bibd(balanced_incomplete_block_design(N,k), N) for XX in base_cases[n,k]: if N-1 in XX: continue bibd.append([X[x//(k-1)] + (x%(k-1))*r for x in XX]) for x in range(r): bibd.append([x+i*r for i in range(k-1)]+[v-1]) if check: assert is_pairwise_balanced_design(bibd,v,[k]) return bibd def _relabel_bibd(B,n,p=None): r""" Relabels the BIBD on `n` points and blocks of size k such that `\{0,...,k-2,n-1\},\{k-1,...,2k-3,n-1\},...,\{n-k,...,n-2,n-1\}` are blocks of the BIBD. INPUT: - ``B`` -- a list of blocks. - ``n`` (integer) -- number of points. - ``p`` (optional) -- the point that will be labeled with n-1. EXAMPLE:: sage: designs.balanced_incomplete_block_design(40,4).blocks() # indirect doctest [[0, 1, 2, 12], [0, 3, 6, 9], [0, 4, 8, 10], [0, 5, 7, 11], [0, 13, 26, 39], [0, 14, 25, 28], [0, 15, 27, 38], [0, 16, 22, 32], [0, 17, 23, 34], ... """ if p is None: p = n-1 found = 0 last = n-1 d = {} for X in B: if last in X: for x in X: if x == last: continue d[x] = found found += 1 if found == n-1: break d[p] = n-1 return [[d[x] for x in X] for X in B] def PBD_4_5_8_9_12(v, check=True): """ Return a `(v,\{4,5,8,9,12\})`-PBD on `v` elements. A `(v,\{4,5,8,9,12\})`-PBD exists if and only if `v\equiv 0,1 \pmod 4`. The construction implemented here appears page 168 in [Stinson2004]_. INPUT: - ``v`` -- an integer congruent to `0` or `1` modulo `4`. - ``check`` (boolean) -- whether to check that output is correct before returning it. As this is expected to be useless (but we are cautious guys), you may want to disable it whenever you want speed. Set to ``True`` by default. EXAMPLES:: sage: designs.balanced_incomplete_block_design(40,4).blocks() # indirect doctest [[0, 1, 2, 12], [0, 3, 6, 9], [0, 4, 8, 10], [0, 5, 7, 11], [0, 13, 26, 39], [0, 14, 25, 28], [0, 15, 27, 38], [0, 16, 22, 32], [0, 17, 23, 34], ... Check that :trac:`16476` is fixed:: sage: from sage.combinat.designs.bibd import PBD_4_5_8_9_12 sage: for v in (0,1,4,5,8,9,12,13,16,17,20,21,24,25): ....: _ = PBD_4_5_8_9_12(v) """ if not v%4 in [0,1]: raise ValueError if v <= 1: PBD = [] elif v <= 12: PBD = [range(v)] elif v == 13 or v == 28: PBD = v_4_1_BIBD(v, check=False) elif v == 29: TD47 = transversal_design(4,7)._blocks four_more_sets = [[28]+[i*7+j for j in range(7)] for i in range(4)] PBD = TD47 + four_more_sets elif v == 41: TD59 = transversal_design(5,9) PBD = ([[x for x in X if x<41] for X in TD59] +[[i*9+j for j in range(9)] for i in range(4)] +[[36,37,38,39,40]]) elif v == 44: TD59 = transversal_design(5,9) PBD = ([[x for x in X if x<44] for X in TD59] +[[i*9+j for j in range(9)] for i in range(4)] +[[36,37,38,39,40,41,42,43]]) elif v == 45: TD59 = transversal_design(5,9)._blocks PBD = (TD59+[[i*9+j for j in range(9)] for i in range(5)]) elif v == 48: TD4_12 = transversal_design(4,12)._blocks PBD = (TD4_12+[[i*12+j for j in range(12)] for i in range(4)]) elif v == 49: # Lemma 7.16 : A (49,{4,13})-PBD TD4_12 = transversal_design(4,12)._blocks # Replacing the block of size 13 with a BIBD BIBD_13_4 = v_4_1_BIBD(13) for i in range(4): for B in BIBD_13_4: TD4_12.append([i*12+x if x != 12 else 48 for x in B]) PBD = TD4_12 else: t,u = _get_t_u(v) TD = transversal_design(5,t) TD = [[x for x in X if x<4*t+u] for X in TD] for B in [range(t*i,t*(i+1)) for i in range(4)]: TD.extend(_PBD_4_5_8_9_12_closure([B])) if u > 1: TD.extend(_PBD_4_5_8_9_12_closure([range(4*t,4*t+u)])) PBD = TD if check: assert is_pairwise_balanced_design(PBD,v,[4,5,8,9,12]) return PBD def _PBD_4_5_8_9_12_closure(B): r""" Makes sure all blocks of `B` have size in `\{4,5,8,9,12\}`. This is a helper function for :func:`PBD_4_5_8_9_12`. Given that `\{4,5,8,9,12\}` is PBD-closed, any block of size not in `\{4,5,8,9,12\}` can be decomposed further. EXAMPLES:: sage: designs.balanced_incomplete_block_design(40,4).blocks() # indirect doctest [[0, 1, 2, 12], [0, 3, 6, 9], [0, 4, 8, 10], [0, 5, 7, 11], [0, 13, 26, 39], [0, 14, 25, 28], [0, 15, 27, 38], [0, 16, 22, 32], [0, 17, 23, 34], ... """ BB = [] for X in B: if len(X) not in [4,5,8,9,12]: PBD = PBD_4_5_8_9_12(len(X), check = False) X = [[X[i] for i in XX] for XX in PBD] BB.extend(X) else: BB.append(X) return BB table_7_1 = { 0:{'t':-4,'u':16,'s':2}, 1:{'t':-4,'u':17,'s':2}, 4:{'t':1,'u':0,'s':1}, 5:{'t':1,'u':1,'s':1}, 8:{'t':1,'u':4,'s':1}, 9:{'t':1,'u':5,'s':1}, 12:{'t':1,'u':8,'s':1}, 13:{'t':1,'u':9,'s':1}, 16:{'t':4,'u':0,'s':0}, 17:{'t':4,'u':1,'s':0}, 20:{'t':5,'u':0,'s':0}, 21:{'t':5,'u':1,'s':0}, 24:{'t':5,'u':4,'s':0}, 25:{'t':5,'u':5,'s':0}, 28:{'t':5,'u':8,'s':1}, 29:{'t':5,'u':9,'s':1}, 32:{'t':8,'u':0,'s':0}, 33:{'t':8,'u':1,'s':0}, 36:{'t':8,'u':4,'s':0}, 37:{'t':8,'u':5,'s':0}, 40:{'t':8,'u':8,'s':0}, 41:{'t':8,'u':9,'s':1}, 44:{'t':8,'u':12,'s':1}, 45:{'t':8,'u':13,'s':1}, } def _get_t_u(v): r""" Return the parameters of table 7.1 from [Stinson2004]_. INPUT: - ``v`` (integer) EXAMPLE:: sage: from sage.combinat.designs.bibd import _get_t_u sage: _get_t_u(20) (5, 0) """ # Table 7.1 v = int(v) global table_7_1 d = table_7_1[v%48] s = v//48 if s < d['s']: raise RuntimeError("This should not have happened.") t = 12*s+d['t'] u = d['u'] return t,u ################ # (v,5,1)-BIBD # ################ def v_5_1_BIBD(v, check=True): r""" Return a `(v,5,1)`-BIBD. This method follows the constuction from [ClaytonSmith]_. INPUT: - ``v`` (integer) .. SEEALSO:: * :func:`balanced_incomplete_block_design` EXAMPLES:: sage: from sage.combinat.designs.bibd import v_5_1_BIBD sage: i = 0 sage: while i<200: ....: i += 20 ....: _ = v_5_1_BIBD(i+1) ....: _ = v_5_1_BIBD(i+5) TESTS: Check that the needed difference families are there:: sage: for v in [21,41,61,81,141,161,281]: ....: assert designs.difference_family(v,5,existence=True) ....: _ = designs.difference_family(v,5) """ v = int(v) assert (v > 1) assert (v%20 == 5 or v%20 == 1) # note: equivalent to (v-1)%4 == 0 and (v*(v-1))%20 == 0 # Lemma 27 if v%5 == 0 and (v//5)%4 == 1 and is_prime_power(v//5): bibd = BIBD_5q_5_for_q_prime_power(v//5) # Lemma 28 elif v in [21,41,61,81,141,161,281]: from difference_family import difference_family G,D = difference_family(v,5) bibd = BIBD_from_difference_family(G, D, check=False) # Lemma 29 elif v == 165: bibd = BIBD_from_PBD(v_5_1_BIBD(41,check=False),165,5,check=False) elif v == 181: bibd = BIBD_from_PBD(v_5_1_BIBD(45,check=False),181,5,check=False) elif v in (201,285,301,401,421,425): # Call directly the BIBD_from_TD function # note: there are (201,5,1) and (421,5)-difference families that can be # obtained from the general constructor bibd = BIBD_from_TD(v,5) # Theorem 31.2 elif (v-1)//4 in [80, 81, 85, 86, 90, 91, 95, 96, 110, 111, 115, 116, 120, 121, 250, 251, 255, 256, 260, 261, 265, 266, 270, 271]: r = (v-1)//4 if r <= 96: k,t,u = 5, 16, r-80 elif r <= 121: k,t,u = 10, 11, r-110 else: k,t,u = 10, 25, r-250 bibd = BIBD_from_PBD(PBD_from_TD(k,t,u),v,5,check=False) else: r,s,t,u = _get_r_s_t_u(v) bibd = BIBD_from_PBD(PBD_from_TD(5,t,u),v,5,check=False) if check: assert is_pairwise_balanced_design(bibd,v,[5]) return bibd def _get_r_s_t_u(v): r""" Implements the table from [ClaytonSmith]_ Return the parameters ``r,s,t,u`` associated with an integer ``v``. INPUT: - ``v`` (integer) EXAMPLES:: sage: from sage.combinat.designs.bibd import _get_r_s_t_u sage: _get_r_s_t_u(25) (6, 0, 1, 1) """ r = int((v-1)/4) s = r//150 x = r%150 if x == 0: t,u = 30*s-5, 25 elif x == 1: t,u = 30*s-5, 26 elif x <= 21: t,u = 30*s+1, x-5 elif x == 25: t,u = 30*s+5, 0 elif x == 26: t,u = 30*s+5, 1 elif x == 30: t,u = 30*s+5, 5 elif x <= 51: t,u = 30*s+5, x-25 elif x <= 66: t,u = 30*s+11, x-55 elif x <= 96: t,u = 30*s+11, x-55 elif x <= 121: t,u = 30*s+11, x-55 elif x <= 146: t,u = 30*s+25, x-125 return r,s,t,u def PBD_from_TD(k,t,u): r""" Return a `(kt,\{k,t\})`-PBD if `u=0` and a `(kt+u,\{k,k+1,t,u\})`-PBD otherwise. This is theorem 23 from [ClaytonSmith]_. The PBD is obtained from the blocks a truncated `TD(k+1,t)`, to which are added the blocks corresponding to the groups of the TD. When `u=0`, a `TD(k,t)` is used instead. INPUT: - ``k,t,u`` -- integers such that `0\leq u \leq t`. EXAMPLES:: sage: from sage.combinat.designs.bibd import PBD_from_TD sage: from sage.combinat.designs.bibd import is_pairwise_balanced_design sage: PBD = PBD_from_TD(2,2,1); PBD [[0, 2, 4], [0, 3], [1, 2], [1, 3, 4], [0, 1], [2, 3]] sage: is_pairwise_balanced_design(PBD,2*2+1,[2,3]) True """ from orthogonal_arrays import transversal_design TD = transversal_design(k+bool(u),t, check=False) TD = [[x for x in X if x<k*t+u] for X in TD] for i in range(k): TD.append(range(t*i,t*i+t)) if u>=2: TD.append(range(k*t,k*t+u)) return TD def BIBD_5q_5_for_q_prime_power(q): r""" Return a `(5q,5,1)`-BIBD with `q\equiv 1\pmod 4` a prime power. See Theorem 24 [ClaytonSmith]_. INPUT: - ``q`` (integer) -- a prime power such that `q\equiv 1\pmod 4`. EXAMPLES:: sage: from sage.combinat.designs.bibd import BIBD_5q_5_for_q_prime_power sage: for q in [25, 45, 65, 85, 125, 145, 185, 205, 305, 405, 605]: # long time ....: _ = BIBD_5q_5_for_q_prime_power(q/5) # long time """ from sage.rings.finite_rings.constructor import FiniteField if q%4 != 1 or not is_prime_power(q): raise ValueError("q is not a prime power or q%4!=1.") d = (q-1)/4 B = [] F = FiniteField(q,'x') a = F.primitive_element() L = {b:i for i,b in enumerate(F)} for b in L: B.append([i*q + L[b] for i in range(5)]) for i in range(5): for j in range(d): B.append([ i*q + L[b ], ((i+1)%5)*q + L[ a**j+b ], ((i+1)%5)*q + L[-a**j+b ], ((i+4)%5)*q + L[ a**(j+d)+b], ((i+4)%5)*q + L[-a**(j+d)+b], ]) return B def BIBD_from_arc_in_desarguesian_projective_plane(n,k,existence=False): r""" Returns a `(n,k,1)`-BIBD from a maximal arc in a projective plane. This function implements a construction from Denniston [Denniston69]_, who describes a maximal :meth:`arc <sage.combinat.designs.bibd.BalancedIncompleteBlockDesign.arc>` in a :func:`Desarguesian Projective Plane <sage.combinat.designs.block_design.DesarguesianProjectivePlaneDesign>` of order `2^k`. From two powers of two `n,q` with `n<q`, it produces a `((n-1)(q+1)+1,n,1)`-BIBD. INPUT: - ``n,k`` (integers) -- must be powers of two (among other restrictions). - ``existence`` (boolean) -- whether to return the BIBD obtained through this construction (default), or to merely indicate with a boolean return value whether this method *can* build the requested BIBD. EXAMPLES: A `(232,8,1)`-BIBD:: sage: from sage.combinat.designs.bibd import BIBD_from_arc_in_desarguesian_projective_plane sage: from sage.combinat.designs.bibd import BalancedIncompleteBlockDesign sage: D = BIBD_from_arc_in_desarguesian_projective_plane(232,8) sage: BalancedIncompleteBlockDesign(232,D) (232,8,1)-Balanced Incomplete Block Design A `(120,8,1)`-BIBD:: sage: D = BIBD_from_arc_in_desarguesian_projective_plane(120,8) sage: BalancedIncompleteBlockDesign(120,D) (120,8,1)-Balanced Incomplete Block Design Other parameters:: sage: all(BIBD_from_arc_in_desarguesian_projective_plane(n,k,existence=True) ....: for n,k in ....: [(120, 8), (232, 8), (456, 8), (904, 8), (496, 16), ....: (976, 16), (1936, 16), (2016, 32), (4000, 32), (8128, 64)]) True Of course, not all can be built this way:: sage: BIBD_from_arc_in_desarguesian_projective_plane(7,3,existence=True) False sage: BIBD_from_arc_in_desarguesian_projective_plane(7,3) Traceback (most recent call last): ... ValueError: This function cannot produce a (7,3,1)-BIBD REFERENCE: .. [Denniston69] R. H. F. Denniston, Some maximal arcs in finite projective planes. Journal of Combinatorial Theory 6, no. 3 (1969): 317-319. http://dx.doi.org/10.1016/S0021-9800(69)80095-5 """ q = (n-1)//(k-1)-1 if (k % 2 or q % 2 or q <= k or n != (k-1)*(q+1)+1 or not is_prime_power(k) or not is_prime_power(q)): if existence: return False raise ValueError("This function cannot produce a ({},{},1)-BIBD".format(n,k)) if existence: return True n = k # From now on, the code assumes the notations of [Denniston69] for n,q, so # that the BIBD returned by the method will have the requested parameters. from sage.rings.finite_rings.constructor import FiniteField as GF from sage.libs.gap.libgap import libgap from sage.matrix.constructor import Matrix K = GF(q,'a') one = K.one() # An irreducible quadratic form over K[X,Y] GO = libgap.GeneralOrthogonalGroup(-1,2,q) M = libgap.InvariantQuadraticForm(GO)['matrix'] M = Matrix(M) M = M.change_ring(K) Q = lambda xx,yy : M[0,0]*xx**2+(M[0,1]+M[1,0])*xx*yy+M[1,1]*yy**2 # Here, the additive subgroup H (of order n) of K mentioned in # [Denniston69] is the set of all elements of K of degree < log_n # (seeing elements of K as polynomials in 'a') K_iter = list(K) # faster iterations log_n = is_prime_power(n,get_data=True)[1] C = [(x,y,one) for x in K_iter for y in K_iter if Q(x,y).polynomial().degree() < log_n] from sage.combinat.designs.block_design import DesarguesianProjectivePlaneDesign return DesarguesianProjectivePlaneDesign(q).trace(C)._blocks class PairwiseBalancedDesign(GroupDivisibleDesign): r""" Pairwise Balanced Design (PBD) A Pairwise Balanced Design, or `(v,K,\lambda)`-PBD, is a collection `\mathcal B` of blocks defined on a set `X` of size `v`, such that any block pair of points `p_1,p_2\in X` occurs in exactly `\lambda` blocks of `\mathcal B`. Besides, for every block `B\in \mathcal B` we must have `|B|\in K`. INPUT: - ``points`` -- the underlying set. If ``points`` is an integer `v`, then the set is considered to be `\{0, ..., v-1\}`. - ``blocks`` -- collection of blocks - ``K`` -- list of integers of which the sizes of the blocks must be elements. Set to ``None`` (automatic guess) by default. - ``lambd`` (integer) -- value of `\lambda`, set to `1` by default. - ``check`` (boolean) -- whether to check that the design is a `PBD` with the right parameters. - ``copy`` -- (use with caution) if set to ``False`` then ``blocks`` must be a list of lists of integers. The list will not be copied but will be modified in place (each block is sorted, and the whole list is sorted). Your ``blocks`` object will become the instance's internal data. """ def __init__(self, points, blocks, K=None, lambd=1, check=True, copy=True,**kwds): r""" Constructor EXAMPLE:: sage: designs.balanced_incomplete_block_design(13,3) # indirect doctest (13,3,1)-Balanced Incomplete Block Design """ try: i = int(points) except TypeError: pass else: points = range(i) GroupDivisibleDesign.__init__(self, points, [[x] for x in points], blocks, K=K, lambd=lambd, check=check, copy=copy, **kwds) def __repr__(self): r""" Returns a string describing the PBD EXAMPLES:: sage: designs.balanced_incomplete_block_design(13,3) # indirect doctest (13,3,1)-Balanced Incomplete Block Design """ return "Pairwise Balanced Design on {} points with sets of sizes in {}".format(self.num_points(),set(self.block_sizes())) class BalancedIncompleteBlockDesign(PairwiseBalancedDesign): r"""" Balanced Incomplete Block Design (BIBD) INPUT: - ``points`` -- the underlying set. If ``points`` is an integer `v`, then the set is considered to be `\{0, ..., v-1\}`. - ``blocks`` -- collection of blocks - ``k`` (integer) -- size of the blocks. Set to ``None`` (automatic guess) by default. - ``lambd`` (integer) -- value of `\lambda`, set to `1` by default. - ``check`` (boolean) -- whether to check that the design is a `PBD` with the right parameters. - ``copy`` -- (use with caution) if set to ``False`` then ``blocks`` must be a list of lists of integers. The list will not be copied but will be modified in place (each block is sorted, and the whole list is sorted). Your ``blocks`` object will become the instance's internal data. EXAMPLES:: sage: b=designs.balanced_incomplete_block_design(9,3); b (9,3,1)-Balanced Incomplete Block Design """ def __init__(self, points, blocks, k=None, lambd=1, check=True, copy=True,**kwds): r""" Constructor EXAMPLE:: sage: b=designs.balanced_incomplete_block_design(9,3); b (9,3,1)-Balanced Incomplete Block Design """ PairwiseBalancedDesign.__init__(self, points, blocks, K=[k] if k is not None else None, lambd=lambd, check=check, copy=copy, **kwds) def __repr__(self): r""" A string to describe self EXAMPLE:: sage: b=designs.balanced_incomplete_block_design(9,3); b (9,3,1)-Balanced Incomplete Block Design """ v = self.num_points() k = len(self._blocks[0]) if self._blocks else 0 l = self._lambd return "({},{},{})-Balanced Incomplete Block Design".format(v,k,l) def arc(self, s=2, solver=None, verbose=0): r""" Return the ``s``-arc with maximum cardinality. A `s`-arc is a subset of points in a BIBD that intersects each block on at most `s` points. It is one possible generalization of independent set for graphs. A simple counting shows that the cardinality of a `s`-arc is at most `(s-1) * r + 1` where `r` is the number of blocks incident to any point. A `s`-arc in a BIBD with cardinality `(s-1) * r + 1` is called maximal and is characterized by the following property: it is not empty and each block either contains `0` or `s` points of this arc. Equivalently, the trace of the BIBD on these points is again a BIBD (with block size `s`). For more informations, see :wikipedia:`Arc_(projective_geometry)`. INPUT: - ``s`` - (default to ``2``) the maximum number of points from the arc in each block - ``solver`` -- (default: ``None``) Specify a Linear Program (LP) solver to be used. If set to ``None``, the default one is used. For more information on LP solvers and which default solver is used, see the method :meth:`solve <sage.numerical.mip.MixedIntegerLinearProgram.solve>` of the class :class:`MixedIntegerLinearProgram <sage.numerical.mip.MixedIntegerLinearProgram>`. - ``verbose`` -- integer (default: ``0``). Sets the level of verbosity. Set to 0 by default, which means quiet. EXAMPLES:: sage: B = designs.balanced_incomplete_block_design(21, 5) sage: a2 = B.arc() sage: a2 # random [5, 9, 10, 12, 15, 20] sage: len(a2) 6 sage: a4 = B.arc(4) sage: a4 # random [0, 1, 2, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 20] sage: len(a4) 16 The `2`-arc and `4`-arc above are maximal. One can check that they intersect the blocks in either 0 or `s` points. Or equivalently that the traces are again BIBD:: sage: r = (21-1)/(5-1) sage: 1 + r*1 6 sage: 1 + r*3 16 sage: B.trace(a2).is_t_design(2, return_parameters=True) (True, (2, 6, 2, 1)) sage: B.trace(a4).is_t_design(2, return_parameters=True) (True, (2, 16, 4, 1)) Some other examples which are not maximal:: sage: B = designs.balanced_incomplete_block_design(25, 4) sage: a2 = B.arc(2) sage: r = (25-1)/(4-1) sage: print len(a2), 1 + r 8 9 sage: sa2 = set(a2) sage: set(len(sa2.intersection(b)) for b in B.blocks()) {0, 1, 2} sage: B.trace(a2).is_t_design(2) False sage: a3 = B.arc(3) sage: print len(a3), 1 + 2*r 15 17 sage: sa3 = set(a3) sage: set(len(sa3.intersection(b)) for b in B.blocks()) == set([0,3]) False sage: B.trace(a3).is_t_design(3) False TESTS: Test consistency with relabeling:: sage: b = designs.balanced_incomplete_block_design(7,3) sage: b.relabel(list("abcdefg")) sage: set(b.arc()).issubset(b.ground_set()) True """ s = int(s) # trivial cases if s <= 0: return [] elif s >= max(self.block_sizes()): return self._points[:] # linear program from sage.numerical.mip import MixedIntegerLinearProgram p = MixedIntegerLinearProgram(solver=solver) b = p.new_variable(binary=True) p.set_objective(p.sum(b[i] for i in range(len(self._points)))) for i in self._blocks: p.add_constraint(p.sum(b[k] for k in i) <= s) p.solve(log=verbose) return [self._points[i] for (i,j) in p.get_values(b).items() if j == 1]
[ 81, 37811, 198, 24597, 2903, 554, 20751, 9726, 49282, 357, 3483, 14529, 8, 198, 198, 1212, 8265, 43609, 2279, 3519, 284, 38984, 554, 20751, 9726, 49282, 13, 1881, 460, 1382, 257, 198, 3483, 14529, 357, 273, 2198, 326, 340, 460, 307, 3...
2.030018
24,785
import numpy as np from collections import OrderedDict from GenPlayground import GenPlayground if __name__ == '__main__': np.set_printoptions(linewidth=200) IP, IP_cycle, IP_pe = GenPlayground() # print(IP_cycle) # print(IP_pe) Gen_CTRL(IP, IP_cycle, IP_pe)
[ 11748, 299, 32152, 355, 45941, 198, 6738, 17268, 1330, 14230, 1068, 35, 713, 198, 198, 6738, 5215, 11002, 2833, 1330, 5215, 11002, 2833, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 45941, 13, ...
2.517857
112
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- from knack.help_files import helps # region VirtualHub helps['network vhub'] = """ type: group short-summary: Manage virtual hubs. """ helps['network vhub create'] = """ type: command short-summary: Create a virtual hub. """ helps['network vhub list'] = """ type: command short-summary: List virtual hubs. """ helps['network vhub show'] = """ type: command short-summary: Get the details of a virtual hub. """ helps['network vhub update'] = """ type: command short-summary: Update settings of a virtual hub. """ helps['network vhub delete'] = """ type: command short-summary: Delete a virtual hub. """ helps['network vhub connection'] = """ type: group short-summary: Manage virtual hub VNet connections. """ helps['network vhub connection create'] = """ type: command short-summary: Create a virtual hub VNet connection. """ helps['network vhub connection list'] = """ type: command short-summary: List virtual hub VNet connections. """ helps['network vhub connection show'] = """ type: command short-summary: Get the details of a virtual hub VNet connection. """ helps['network vhub connection delete'] = """ type: command short-summary: Delete a virtual hub VNet connection. """ helps['network vhub route'] = """ type: group short-summary: Manage entries in the virtual hub route table. """ helps['network vhub route add'] = """ type: command short-summary: Add a route to the virtual hub route table. """ helps['network vhub route list'] = """ type: command short-summary: List routes in the virtual hub route table. """ helps['network vhub route remove'] = """ type: command short-summary: Remove a route from the virtual hub route table. """ # endregion # region VirtualWAN helps['network vwan'] = """ type: group short-summary: Manage virtual WANs. """ helps['network vwan create'] = """ type: command short-summary: Create a virtual WAN. """ helps['network vwan list'] = """ type: command short-summary: List virtual WANs. """ helps['network vwan show'] = """ type: command short-summary: Get the details of a virtual WAN. """ helps['network vwan update'] = """ type: command short-summary: Update settings of a virtual WAN. """ helps['network vwan delete'] = """ type: command short-summary: Delete a virtual WAN. """ # endregion # region VpnGateway helps['network vpn-gateway'] = """ type: group short-summary: Manage VPN gateways. """ helps['network vpn-gateway create'] = """ type: command short-summary: Create a VPN gateway. """ helps['network vpn-gateway list'] = """ type: command short-summary: List VPN gateways. """ helps['network vpn-gateway show'] = """ type: command short-summary: Get the details of a VPN gateway. """ helps['network vpn-gateway update'] = """ type: command short-summary: Update settings of a VPN gateway. """ helps['network vpn-gateway delete'] = """ type: command short-summary: Delete a VPN gateway. """ helps['network vpn-gateway connection'] = """ type: group short-summary: Manage VPN gateway connections. """ helps['network vpn-gateway connection create'] = """ type: command short-summary: Create a VPN gateway connection. """ helps['network vpn-gateway connection list'] = """ type: command short-summary: List VPN gateway connections. """ helps['network vpn-gateway connection show'] = """ type: command short-summary: Get the details of a VPN gateway connection. """ helps['network vpn-gateway connection delete'] = """ type: command short-summary: Delete a VPN gateway connection. """ helps['network vpn-gateway connection ipsec-policy'] = """ type: group short-summary: Manage VPN gateway connection IPSec policies. """ helps['network vpn-gateway connection ipsec-policy add'] = """ type: command short-summary: Add an IPSec policy to a VPN gateway connection. """ helps['network vpn-gateway connection ipsec-policy list'] = """ type: command short-summary: List VPN gateway connection IPSec policies. """ helps['network vpn-gateway connection ipsec-policy remove'] = """ type: command short-summary: Remove an IPSec policy from a VPN gateway connection. """ # endregion # region VpnSite helps['network vpn-site'] = """ type: group short-summary: Manage VPN site configurations. """ helps['network vpn-site create'] = """ type: command short-summary: Create a VPN site configuration. """ helps['network vpn-site list'] = """ type: command short-summary: List VPN site configurations. """ helps['network vpn-site show'] = """ type: command short-summary: Get the details of a VPN site configuration. """ helps['network vpn-site update'] = """ type: command short-summary: Update settings of a VPN site configuration. """ helps['network vpn-site delete'] = """ type: command short-summary: Delete a VPN site configuration. """ helps['network vpn-site download'] = """ type: command short-summary: Provide a SAS-URL to download the configuration for a VPN site. """ # endregion
[ 2, 16529, 1783, 10541, 198, 2, 15069, 357, 66, 8, 5413, 10501, 13, 1439, 2489, 10395, 13, 198, 2, 49962, 739, 262, 17168, 13789, 13, 4091, 13789, 13, 14116, 287, 262, 1628, 6808, 329, 5964, 1321, 13, 198, 2, 16529, 1783, 10541, 198,...
3.272353
1,700
from django.apps import AppConfig
[ 6738, 42625, 14208, 13, 18211, 1330, 2034, 16934, 628 ]
3.888889
9
import signal from telegram.ext import Updater, CommandHandler, MessageHandler, Filters from telegram import Sticker, InlineKeyboardButton, InlineKeyboardMarkup import logging from Utils import telegram_util, twitch_util, config_util if __name__ == '__main__': config = config_util.get_config() logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') if config_util.token_key in config and config[config_util.token_key] is not '': bot = TwitchStickersBot(token=config[config_util.token_key]) bot.start_bot() else: logging.log(logging.ERROR, f"{config_util.token_key} not in {config_util.config_path}!")
[ 11748, 6737, 198, 6738, 573, 30536, 13, 2302, 1330, 3205, 67, 729, 11, 9455, 25060, 11, 16000, 25060, 11, 7066, 1010, 198, 6738, 573, 30536, 1330, 520, 15799, 11, 554, 1370, 9218, 3526, 21864, 11, 554, 1370, 9218, 3526, 9704, 929, 198...
2.610909
275
import matplotlib.pyplot as plt import numpy as np from scipy.stats import norm import math import matplotlib.colors as colors from matplotlib import cm from matplotlib import rc __author__ = 'ernesto' # if use latex or mathtext rc('text', usetex=False) rc('mathtext', fontset='cm') # auxiliar function for plot ticks of equal length in x and y axis despite its scales. ##################################### # PARAMETERS - This can be modified # ##################################### # normal pdf standard deviation sigma1 = 1 sigma2 = sigma1 / 10 # normal pdf mean h1 = 3 h2 = h1 / 2 # maximum deviation from the mean where to plot each gaussian max_mean_dev = 3 * sigma1 ##################### # END OF PARAMETERS # ##################### # abscissa values xmin = h2 - max_mean_dev xmax = h1 + max_mean_dev x = np.linspace(xmin, xmax, 300) # normal distribution and density values in x pdf_h1 = norm.pdf(x, h1, sigma1) pdf_h1_avg = norm.pdf(x, h1, math.sqrt(sigma2)) pdf_h2 = norm.pdf(x, h2, sigma1) pdf_h2_avg = norm.pdf(x, h2, math.sqrt(sigma2)) # axis parameters dx = xmax / 20 xmin_ax = xmin - dx xmax_ax = xmax + dx ym = np.amax(pdf_h1_avg) ymax_ax = ym + ym / 10 ymin_ax = -ym / 10 # length of the ticks for all subplot (6 pixels) display_length = 6 # in pixels # x ticks labels margin xtm = -0.03 # font size fontsize = 14 # colors from coolwarm cNorm = colors.Normalize(vmin=0, vmax=1) scalarMap = cm.ScalarMappable(norm=cNorm, cmap=cm.coolwarm) col10 = scalarMap.to_rgba(0) col20 = scalarMap.to_rgba(1) fig = plt.figure(0, figsize=(10, 3), frameon=False) # PLOT OF F(x | x < a) ax = plt.subplot2grid((1, 8), (0, 0), rowspan=1, colspan=4) plt.xlim(xmin_ax, xmax_ax) plt.ylim(ymin_ax, ymax_ax) # horizontal and vertical ticks length xtl, ytl = convert_display_to_data_coordinates(ax.transData, length=display_length) # axis arrows plt.annotate("", xytext=(xmin_ax, 0), xycoords='data', xy=(xmax_ax, 0), textcoords='data', arrowprops=dict(width=0.1, headwidth=6, headlength=8, facecolor='black', shrink=0.002)) plt.annotate("", xytext=(0, ymin_ax), xycoords='data', xy=(0, ymax_ax), textcoords='data', arrowprops=dict(width=0.1, headwidth=6, headlength=8, facecolor='black', shrink=0.002)) plt.plot(x, pdf_h1, color=col10, linewidth=2) plt.plot(x, pdf_h1_avg, color=col20, linewidth=2) # xlabels and xtickslabels plt.plot([h1, h1], [0, xtl], 'k') plt.text(h1, xtm, '$h$', fontsize=fontsize, ha='center', va='top') plt.text(xmin_ax, ymax_ax-0.1, '$\\alpha=1$', fontsize=fontsize, ha='left', va='baseline') plt.axis('off') # PLOT OF F(x | x < a) ax = plt.subplot2grid((1, 8), (0, 4), rowspan=1, colspan=4) plt.xlim(xmin_ax, xmax_ax) plt.ylim(ymin_ax, ymax_ax) # axis arrows plt.annotate("", xytext=(xmin_ax, 0), xycoords='data', xy=(xmax_ax, 0), textcoords='data', arrowprops=dict(width=0.1, headwidth=6, headlength=8, facecolor='black', shrink=0.002)) plt.annotate("", xytext=(0, ymin_ax), xycoords='data', xy=(0, ymax_ax), textcoords='data', arrowprops=dict(width=0.1, headwidth=6, headlength=8, facecolor='black', shrink=0.002)) plt.plot(x, pdf_h2, color=col10, linewidth=2) plt.plot(x, pdf_h2_avg, color=col20, linewidth=2) # xlabels and xtickslabels plt.plot([h1, h1], [0, xtl], 'k') plt.text(h1, xtm, '$h$', fontsize=fontsize, ha='center', va='top') plt.plot([h2, h2], [0, xtl], 'k') plt.text(h2, xtm, '$\\dfrac{h}{2}$', fontsize=fontsize, ha='center', va='top') plt.text(xmin_ax, ymax_ax-0.1, '$\\alpha=\\dfrac{1}{2}$', fontsize=fontsize, ha='left', va='baseline') # legend leg = plt.legend(['$p(\hat{h}_i)$', '$p(\hat{h})$'], loc=1, fontsize=fontsize) leg.get_frame().set_facecolor(0.97*np.ones((3,))) leg.get_frame().set_edgecolor(0.97*np.ones((3,))) plt.axis('off') # save as pdf image plt.savefig('problem_2_4.pdf', bbox_inches='tight') plt.show()
[ 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 629, 541, 88, 13, 34242, 1330, 2593, 198, 11748, 10688, 198, 11748, 2603, 29487, 8019, 13, 4033, 669, 355, 7577, 198, 198, 6738, 2...
2.276432
1,693
"""Generate a matplotlib canvas and add it to a QWidget contained in a QMainWindow. This will provide the display and interactions for the PyCCD plots.""" from lcmap_tap.logger import log, exc_handler from lcmap_tap.Plotting import POINTS, LINES import sys import datetime as dt import numpy as np import pkg_resources from PyQt5 import QtWidgets, QtCore from PyQt5.QtGui import QIcon, QPixmap import matplotlib matplotlib.use("Qt5Agg") from matplotlib.collections import PathCollection from matplotlib.lines import Line2D from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar sys.excepthook = exc_handler class MplCanvas(FigureCanvas): """ TODO: Add summary line """ def __init__(self, fig): """ TODO: Add Summary Args: fig: """ self.fig = fig FigureCanvas.__init__(self, self.fig) if len(fig.axes) >= 3: sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Ignored, QtWidgets.QSizePolicy.Minimum) else: sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Ignored, QtWidgets.QSizePolicy.Ignored) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) FigureCanvas.setSizePolicy(self, sizePolicy) FigureCanvas.updateGeometry(self)
[ 37811, 8645, 378, 257, 2603, 29487, 8019, 21978, 290, 751, 340, 284, 257, 1195, 38300, 7763, 287, 257, 1195, 13383, 27703, 13, 220, 770, 481, 2148, 262, 198, 13812, 290, 12213, 329, 262, 9485, 4093, 35, 21528, 526, 15931, 198, 198, 67...
2.501748
572
""" Miscellaneous functions for working with files """ import os def canonicalize_path(path: str): """Converts a path string to its canonical form (easier for comparisons)""" return os.path.abspath(os.path.realpath(os.path.expanduser(path)))
[ 37811, 198, 198, 31281, 25673, 5499, 329, 1762, 351, 3696, 198, 198, 37811, 198, 198, 11748, 28686, 198, 198, 4299, 40091, 1096, 62, 6978, 7, 6978, 25, 965, 2599, 198, 220, 220, 220, 37227, 3103, 24040, 257, 3108, 4731, 284, 663, 4009...
3.135802
81
import os import _winreg def get_python_executables(): """ Find the Maya installation paths using _winreg. The path to the python executable is extended from the installation path. The dictionary is made up of keys that are made up of the Maya versions found installed and a path to the executable of that version of Maya as a value. :return: Windows maya python executables :rtype: dict """ # variables maya_pythons = {} registry = _winreg.HKEY_LOCAL_MACHINE registry_maya_path = r"SOFTWARE\Autodesk\Maya" # get maya key maya_key_data = [ registry, registry_maya_path, 0, _winreg.KEY_READ ] with _winreg.OpenKey(*maya_key_data) as maya_key: # loop keys for i in xrange(0, _winreg.QueryInfoKey(maya_key)[0]): # get version maya_version = _winreg.EnumKey(maya_key, i) # validate version if not maya_version.split(".")[0].isdigit(): continue # get install path registry_maya_install_path = os.path.join( registry_maya_path, maya_version, "Setup", "InstallPath" ) # get install key maya_install_key_data = [ registry, registry_maya_install_path, 0, _winreg.KEY_READ ] with _winreg.OpenKey(*maya_install_key_data) as maya_install_key: # get path maya_location_data = [maya_install_key, "MAYA_INSTALL_LOCATION"] maya_location = _winreg.QueryValueEx(*maya_location_data)[0] # set data maya_py = os.path.join(maya_location, "bin", "mayapy.exe") maya_pythons[maya_version] = maya_py return maya_pythons
[ 11748, 28686, 198, 11748, 4808, 5404, 2301, 628, 198, 4299, 651, 62, 29412, 62, 18558, 315, 2977, 33529, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 9938, 262, 26041, 9988, 13532, 1262, 4808, 5404, 2301, 13, 383, 3108, 284, 262, 21...
1.950455
989
"""A rule that provides file(s) specific via DefaultInfo from a given target's DefaultInfo or OutputGroupInfo """ load( "//lib/private:output_files.bzl", _make_output_files = "make_output_files", _output_files = "output_files", ) output_files = _output_files make_output_files = _make_output_files
[ 37811, 32, 3896, 326, 3769, 2393, 7, 82, 8, 2176, 2884, 15161, 12360, 422, 257, 1813, 2496, 338, 15161, 12360, 393, 25235, 13247, 12360, 198, 37811, 198, 198, 2220, 7, 198, 220, 220, 220, 366, 1003, 8019, 14, 19734, 25, 22915, 62, 1...
2.971429
105
"""This script converts a collection of MIDI files to multitrack pianorolls. """ import os import json import argparse import warnings import pretty_midi from pypianoroll import Multitrack from utils import make_sure_path_exists, change_prefix, findall_endswith from config import CONFIG if CONFIG['multicore'] > 1: import joblib warnings.filterwarnings('ignore') def parse_args(): """Return the parsed command line arguments.""" parser = argparse.ArgumentParser() parser.add_argument('src', help="root path to the source dataset") parser.add_argument('dst', help="root path to the destination dataset") parser.add_argument('--midi-info-path', dest='midi_info_path', help="path to save the MIDI info dictionary") args = parser.parse_args() return args.src, args.dst, args.midi_info_path def get_midi_info(pm): """Return useful information from a MIDI object.""" if pm.time_signature_changes: pm.time_signature_changes.sort(key=lambda x: x.time) first_beat_time = pm.time_signature_changes[0].time else: first_beat_time = pm.estimate_beat_start() tc_times, tempi = pm.get_tempo_changes() if len(pm.time_signature_changes) == 1: time_sign = '{}/{}'.format(pm.time_signature_changes[0].numerator, pm.time_signature_changes[0].denominator) else: time_sign = None midi_info = { 'first_beat_time': first_beat_time, 'num_time_signature_change': len(pm.time_signature_changes), 'constant_time_signature': time_sign, 'constant_tempo': tempi[0] if len(tc_times) == 1 else None } return midi_info def converter(filepath, src, dst): """Convert a MIDI file to a multi-track piano-roll and save the resulting multi-track piano-roll to the destination directory. Return a tuple of `midi_md5` and useful information extracted from the MIDI file. """ try: midi_md5 = os.path.splitext(os.path.basename(filepath))[0] multitrack = Multitrack(beat_resolution=CONFIG['beat_resolution'], name=midi_md5) pm = pretty_midi.PrettyMIDI(filepath) multitrack.parse_pretty_midi(pm) midi_info = get_midi_info(pm) result_dir = change_prefix(os.path.dirname(filepath), src, dst) make_sure_path_exists(result_dir) multitrack.save(os.path.join(result_dir, midi_md5 + '.npz')) return (midi_md5, midi_info) except: return None def main(): """Main function.""" src, dst, midi_info_path = parse_args() make_sure_path_exists(dst) midi_info = {} if CONFIG['multicore'] > 1: kv_pairs = joblib.Parallel(n_jobs=CONFIG['multicore'], verbose=5)( joblib.delayed(converter)(midi_path, src, dst) for midi_path in findall_endswith('.mid', src)) for kv_pair in kv_pairs: if kv_pair is not None: midi_info[kv_pair[0]] = kv_pair[1] else: for midi_path in findall_endswith('.mid', src): kv_pair = converter(midi_path, src, dst) if kv_pair is not None: midi_info[kv_pair[0]] = kv_pair[1] if midi_info_path is not None: with open(midi_info_path, 'w') as f: json.dump(midi_info, f) print("{} files have been successfully converted".format(len(midi_info))) if __name__ == "__main__": main()
[ 37811, 1212, 4226, 26161, 257, 4947, 286, 33439, 3696, 284, 41785, 39638, 43923, 273, 33421, 13, 201, 198, 37811, 201, 198, 11748, 28686, 201, 198, 11748, 33918, 201, 198, 11748, 1822, 29572, 201, 198, 11748, 14601, 201, 198, 11748, 2495,...
2.191004
1,623
from flask import request, current_app import jwt from app.models.auth import User from app.api import api # required_token decorator
[ 6738, 42903, 1330, 2581, 11, 1459, 62, 1324, 198, 11748, 474, 46569, 198, 198, 6738, 598, 13, 27530, 13, 18439, 1330, 11787, 198, 6738, 598, 13, 15042, 1330, 40391, 628, 198, 2, 2672, 62, 30001, 11705, 1352, 198 ]
3.605263
38
#!/usr/bin/env python # -*- coding: utf-8 -*- """Fetches audit log data from the Mimecast API and saves to a folder for Sumo Logic data collection""" import base64 import hashlib import hmac import json import logging import os import pickle import uuid import time import datetime import sys from os.path import dirname, abspath import requests # Program Start with open(os.path.join(os.path.join(dirname(dirname(abspath(__file__))), 'checkpoint', 'config.txt')), 'rb') as f: config = pickle.load(f) log_dir = os.path.join(os.path.join(dirname(dirname(abspath(__file__))), 'log')) log_name = 'audit_' + datetime.datetime.utcnow().strftime('%d%m%Y') + '.log' logging.basicConfig(filename=os.path.join(log_dir, log_name), level=logging.INFO, format='%(levelname)s|%(asctime)s|%(message)s') account_code = config['account_code'] if len(account_code) < 0: logging.error('Log collection aborted. Account code not found, exiting.') sys.exit() logging.info('***** Mimecast Data Collector for Sumo Logic v1.0 *****') logging.info('Starting audit log collection for ' + account_code) data_dir = config['data_dir'] if len(data_dir) < 0: logging.error('Data directory not set, exiting.') sys.exit() logging.info('Using data directory: ' + data_dir) access_key = config['access_key'] if len(access_key) < 0: logging.error('Access Key not set, exiting.') sys.exit() secret_key = config['secret_key'] if len(secret_key) < 0: logging.error('Secret Key not set, exiting.') sys.exit() api_base_url = config['api_base_url'] if len(api_base_url) < 0: logging.error('API base URL not set, exiting.') sys.exit() if os.path.exists(os.path.join(dirname(dirname(abspath(__file__))), 'checkpoint', 'checkpoint_audit_start')): with open(os.path.join(dirname(dirname(abspath(__file__))), 'checkpoint', 'checkpoint_audit_start')) as csd: start = csd.read() else: start = get_iso_time(60) end = get_iso_time(0) while get_audit_logs(start=start, end=end) is True: logging.info('Collecting Audit logs') #Clean up data files remove_files(os.path.join(dirname(dirname(abspath(__file__))), 'log')) #Clean up log files remove_files(os.path.join(data_dir, 'audit')) logging.info('Audit log collection complete') sys.exit()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 37, 316, 2052, 14984, 2604, 1366, 422, 262, 337, 524, 2701, 7824, 290, 16031, 284, 257, 9483, 329, 5060, ...
2.570166
905
import unittest from core.poly_parser import * if __name__ == '__main__': unittest.main()
[ 11748, 555, 715, 395, 198, 6738, 4755, 13, 35428, 62, 48610, 1330, 1635, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 555, 715, 395, 13, 12417, 3419, 198 ]
2.621622
37
from typing import List, Optional from dataclasses import dataclass from botbuilder.schema import ActivityTypes, Activity from botbuilder.core import MessageFactory from botbuilder.dialogs import ( WaterfallDialog, WaterfallStepContext, DialogTurnResult, PromptOptions, Choice, ChoicePrompt, ) from botbuilder.dialogs.prompts import OAuthPrompt, OAuthPromptSettings from cards import get_azure_vms_card, AZURE_VMS_CARD_MAX_VMS from dialogs import LogoutDialog from cloud_clients import AzureClient from cloud_models.azure import Subscription, Vm @dataclass
[ 6738, 19720, 1330, 7343, 11, 32233, 198, 6738, 4818, 330, 28958, 1330, 4818, 330, 31172, 198, 6738, 10214, 38272, 13, 15952, 2611, 1330, 24641, 31431, 11, 24641, 198, 6738, 10214, 38272, 13, 7295, 1330, 16000, 22810, 198, 6738, 10214, 382...
3.202186
183
# Theory: Introduction to Python # Computer science has been around for a while, and # programming languages are one of its main tools. These are # designed to help us implement software to run on a computer. # Just as natural languages for people, they serve as a # communication tool, only between people and machines. In this # topic, we will learn about the one exponentially gaining # popularity among developers recently. Behold, this is an # introduction to Python! # 1. What is Python? # Python is a modern general-purpose programming language # initially developed by a Dutch programmer named Guido van # Rossum in the late 1980s. The name comes from the popular # Monty Python show, not the snake, as you might think. This # language has a clean, uniform, and well-readable syntax and is # designed to be easy to learn and use in practice. # Nowadays, Python is one of the most popular programming # languages worldwide, according to the TIOBE index. The # number of programmers who use it is growing every day! # The language has a huge community of developers around the # world. If you have a problem, you can always ask other # programmers for help or find a suitable answer on a site like # Stack Overflow. # Developing software with Python is easy and fun! # Python has a wide range of possible applications, especially in: # - Web development; # - Data science (including machine learning); # - Scripting (task automation, such as text processing or simulation of typical user actions). # It is also used in desktop development, though less commonly. # 2. Python is data science # Python's huge popularity in recent years is mostly due to its use # in data science. What makes it better than other languages for # this purpose. Well, there's a number of reasons: # - Its simple syntax allows people from non-programming # backgrounds to use it for data processing and model # training without spending much time learning a new # language. # - Python supports a very large number of third-party # libraries for machine learning, neural networks, statistics, # numeric calculations, which makes your job much # easier. # - With Python, it is possible to collect, clean, and explore # data, as well as train models and visualize the results - all # in one setting! # - Python ML developers' community is very large, so you # can always find support for your tasks. # As you can see, Python doest have a lot to offer for data science # enthusiats. # 3. A short history of Python # Like other programming languages, Python has gone through # a number of versions. Python 1.0 was released in 1994 and laid # the basic principles of the language with emphasis on simplicity. # # Python 2.0 was released in 2000. This version has become very # popular among programmers. Different 2.x subversions (2.6, # 2.7) are still used in various projects and libraries. The symbol x # in 2.x means any subversion of Python 2. # # Python 3.0 was the next major version released in 2008. It # broke backward compatibility with its predecessors in order to # rid the language of historic clutter and make Python more # readable and consistent. # # Today, two similar but incompatible versions of Python are # commonly used. # Throughout this course, we will be working with Python # 3.x. # 4. First program example # Here is a single line of Python that prints Learn Python to # be great!. print("Learn Python to be great!") # For now, you do not need to understand how this code works: # just appreciate its beautiful syntax that isn't too far from normal # English. # 5. Summary # Let's summarize what we've learned in this topic: # - what Python is; # - it applications; # - the reasons why Python is so popular in the field of data # science; # - the history of the language; # - how to write simple code in Python. # Now, when you know the most basic things about Python, you're # all setteld to continue your journey into it!
[ 2, 17003, 25, 22395, 284, 11361, 198, 2, 13851, 3783, 468, 587, 1088, 329, 257, 981, 11, 290, 198, 2, 8300, 8950, 389, 530, 286, 663, 1388, 4899, 13, 2312, 389, 198, 2, 3562, 284, 1037, 514, 3494, 3788, 284, 1057, 319, 257, 3644, ...
4.026342
987
from __future__ import print_function import pytest import requests from jenkinsapi.jenkins import Requester from jenkinsapi.custom_exceptions import JenkinsAPIException from mock import patch @patch('jenkinsapi.jenkins.Requester.AUTH_COOKIE', 'FAKE') @patch('jenkinsapi.jenkins.Requester.AUTH_COOKIE', 'FAKE')
[ 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 11748, 12972, 9288, 198, 11748, 7007, 198, 6738, 474, 268, 5331, 15042, 13, 48796, 5331, 1330, 9394, 7834, 198, 6738, 474, 268, 5331, 15042, 13, 23144, 62, 1069, 11755, 1330, 21835, 17...
3.008772
114
from flask import Blueprint, flash, redirect, render_template, request, url_for from flask_login import login_required from app.dao.rent import get_all_rentcodes from app.dao.money import get_acc_descs, get_moneydets, get_money_item, toggle_cleared from app.main.money import collect_search_filter, mget_money_acc, mget_money_items, mget_moneydict, \ mpost_money_acc, \ mpost_money_item, mpost_transfer from app.main.dashboard import mget_recent_money_searches, mpost_recent_money, mpost_search from app import db money_bp = Blueprint('money_bp', __name__) @money_bp.route('/money', methods=['GET', 'POST']) @money_bp.route('/money_acc/<int:acc_id>', methods=['GET', 'POST']) @login_required @money_bp.route('/money_item/<int:money_item_id>', methods=['GET', 'POST']) @money_bp.route('/money_items/<int:acc_id>', methods=["GET", "POST"]) @login_required @money_bp.route('/money_save_search', methods=['GET', 'POST']) @money_bp.route('/money_transfer/<int:acc_id>', methods=["GET", "POST"]) @login_required @money_bp.route('/toggle/<int:money_item_id>', methods=['GET', 'POST'])
[ 6738, 42903, 1330, 39932, 11, 7644, 11, 18941, 11, 8543, 62, 28243, 11, 220, 2581, 11, 19016, 62, 1640, 198, 6738, 42903, 62, 38235, 1330, 17594, 62, 35827, 198, 6738, 598, 13, 67, 5488, 13, 1156, 1330, 651, 62, 439, 62, 1156, 40148...
2.70098
408
from synonym_dict import SynonymDict, SynonymSet class QuantitySynonyms(SynonymSet): """ QuantitySynonyms are string terms that all refer to the same quantity of measure. They must all have the same unit, because they are used to define the unit of measure of flowables. To repeat: quantity instances that have the same dimensionality but different units (e.g. kWh and MJ) are NOT SYNONYMS but distinct quantities. The LciaEngine should be able to handle conversions between these kinds of quantities. """ @classmethod @property @quantity.setter def _save_synonyms(self, other): """ adds to other's synonym set- :param other: :return: """ for k in other.terms: self._quantity.add_synonym(k) @property @property
[ 6738, 6171, 5177, 62, 11600, 1330, 16065, 5177, 35, 713, 11, 16065, 5177, 7248, 628, 628, 198, 198, 4871, 39789, 29934, 43612, 7, 29934, 5177, 7248, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 39789, 29934, 43612, 389, 4731, ...
2.885417
288
import os import sys from algorithms import dijkstra, floyd from utils import * TASK1_START = 0 print '-'*35 + '\ntask1 - shortest ways from ({})\n'.format(TASK1_START + 1) + '-'*35 g_list, g_mat = read_graph_list('task1.in') dist, prev, table = dijkstra(g_list, TASK1_START) user_interaction(prev, dist, g_mat) write_debug_table('task1.out.md', table) print '\n' + '-'*35 + '\ntask2\n' + '-'*35 os.remove('task2.out.md') g_mat = read_graph_matrix('task2.in') dist, path = floyd(g_mat)
[ 11748, 28686, 198, 11748, 25064, 198, 198, 6738, 16113, 1330, 2566, 73, 74, 12044, 11, 781, 12192, 198, 6738, 3384, 4487, 1330, 1635, 628, 628, 198, 51, 1921, 42, 16, 62, 2257, 7227, 796, 657, 198, 4798, 705, 19355, 9, 2327, 1343, 7...
2.288372
215
bashCommand = "rostopic pub -1 /spray_onoff std_msgs/Float32 1.0" import subprocess process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE) output, error = process.communicate()
[ 41757, 21575, 796, 366, 305, 11338, 291, 2240, 532, 16, 1220, 34975, 323, 62, 261, 2364, 14367, 62, 907, 14542, 14, 43879, 2624, 352, 13, 15, 1, 198, 11748, 850, 14681, 198, 14681, 796, 850, 14681, 13, 47, 9654, 7, 41757, 21575, 13,...
2.969231
65
from fastapi import FastAPI from config import ServiceConfig from apps.libs import init_app
[ 6738, 3049, 15042, 1330, 12549, 17614, 198, 198, 6738, 4566, 1330, 4809, 16934, 198, 6738, 6725, 13, 8019, 82, 1330, 2315, 62, 1324, 628 ]
3.916667
24
import os from office365.sharepoint.client_context import ClientContext SITE_URL = os.getenv('SITE_URL') USER = os.getenv('USER') PASS = os.getenv('PASS') DESTINATION = os.getenv('DESTINATION') FILE = os.getenv('FILE') FILE_ON_SERVER = os.getenv('FILE_ON_SERVER') if __name__ == "__main__": main()
[ 11748, 28686, 198, 6738, 2607, 24760, 13, 20077, 4122, 13, 16366, 62, 22866, 1330, 20985, 21947, 198, 198, 50, 12709, 62, 21886, 796, 28686, 13, 1136, 24330, 10786, 50, 12709, 62, 21886, 11537, 198, 29904, 796, 28686, 13, 1136, 24330, 1...
2.571429
119
# Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # import torch import torch.nn as nn import torch.nn.functional as F from crlapi.core import CLModel from crlapi.sl.clmodels.finetune import Finetune import time import copy import numpy as np from pydoc import locate class IndexDataset(torch.utils.data.Dataset): """ Wrapper that additionally returns the index for each sample """ class BoostingSampler(torch.utils.data.Sampler): """ Upsample points based on sample weight """
[ 2, 15069, 357, 66, 8, 3203, 11, 3457, 13, 290, 663, 29116, 13, 198, 2, 1439, 2489, 10395, 13, 198, 2, 198, 2, 770, 2723, 2438, 318, 11971, 739, 262, 5964, 1043, 287, 262, 198, 2, 38559, 24290, 2393, 287, 262, 6808, 8619, 286, 42...
3.42246
187
from ibm_db_sa import requirements Requirements = requirements.Requirements
[ 6738, 24283, 76, 62, 9945, 62, 11400, 1330, 5359, 198, 198, 42249, 796, 5359, 13, 42249, 198 ]
4.529412
17
from datetime import datetime, time, timedelta from PyShift.test.base_test import BaseTest from PyShift.workschedule.work_schedule import WorkSchedule
[ 6738, 4818, 8079, 1330, 4818, 8079, 11, 640, 11, 28805, 12514, 198, 6738, 9485, 33377, 13, 9288, 13, 8692, 62, 9288, 1330, 7308, 14402, 198, 6738, 9485, 33377, 13, 5225, 2395, 5950, 13, 1818, 62, 15952, 5950, 1330, 5521, 27054, 5950, ...
2.009174
109
# -*- coding: utf-8 -*- """ ppmeasurements.util ~~~~~~~~~~~~~~ This module contains utility functions for parsing information, checking for non-global IP address, convert traceroutes to machine-readable structures, etc. :author: Muzammil Abdul Rehman :copyright: Northeastern University © 2018. :license: Custom BSD, see LICENSE for more details. :email: passport@ccs.neu.edu """ import json import trparse import socket import datetime import time ###remove-me-later-muz###import ormsettings as DJANGO_SETTINGS from ppstore.models import Hints_country_codes import os import csv import pputils import ipaddress """ Sample JSON: {"source": "127.0.1.1", "destName": "8.8.8.8", "destIP": "8.8.8.8", "resolvers": ["8.8.8.8"], "type": "Input_DNS_Resolver", "startTime": 1472651763386, "timestamp": 1472651763632, "entries": [ {"rtt": [0.231, 0.213, 0.242], "router": ["129.10.113.1", null, null], "routerName": ["unknown", null, null], "numRouters": 1}, {"rtt": [2.21, 2.389, 2.733], "router": ["129.10.110.2", null, null], "routerName": ["unknown", null, null], "numRouters": 1}, {"rtt": [0.963, 0.951, 0.951], "router": ["10.2.29.52", null, null], "routerName": ["unknown", null, null], "numRouters": 1}, {"rtt": [1.465, 1.518, 1.505], "router": ["10.2.29.33", null, null], "routerName": ["unknown", null, null], "numRouters": 1}, {"rtt": [1.554, 1.544, 1.489], "router": ["10.2.29.230", null, null], "routerName": ["unknown", null, null], "numRouters": 1}, {"rtt": [4.289, 4.469, 4.513], "router": ["207.210.142.101", null, null], "routerName": ["nox1sumgw1-neu-cps.nox.org.", null, null], "numRouters": 1}, {"rtt": [31.826, 31.246, 31.229], "router": ["198.71.47.61", null, null], "routerName": ["et-10-0-0.122.rtr.eqch.net.internet2.edu.", null, null], "numRouters": 1}, {"rtt": [31.204, 30.928, 31.072], "router": ["74.125.49.146", null, null], "routerName": ["unknown", null, null], "numRouters": 1}, {"rtt": [31.263, 31.251, 31.791], "router": ["209.85.143.154", "209.85.242.133", "209.85.254.120"], "routerName": ["unknown", "unknown", "unknown"], "numRouters": 3}, {"rtt": [31.787, 31.628, 31.447], "router": ["209.85.243.163", "209.85.241.47", null], "routerName": ["unknown", "unknown", null], "numRouters": 2}, {"rtt": [40.979, 41.171, 40.825], "router": ["209.85.247.4", "216.239.47.121", "209.85.247.4"], "routerName": ["unknown", "unknown", "unknown"], "numRouters": 3}, {"rtt": [40.97, 45.834, 45.785], "router": ["72.14.234.81", "216.239.62.13", "209.85.248.89"], "routerName": ["unknown", "unknown", "unknown"], "numRouters": 3}, {"rtt": [-1.0, -1.0, -1.0], "router": ["unknown", "unknown", "unknown"], "routerName": ["unknown", "unknown", "unknown"], "numRouters": 3}, {"rtt": [40.757, 41.006, 40.924], "router": ["8.8.8.8", null, null], "routerName": ["google-public-dns-a.google.com.", null, null], "numRouters": 1}]} """ if __name__ == "__main__": #test_from_traceroute_to_server_json() pass
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 628, 220, 220, 220, 9788, 1326, 5015, 902, 13, 22602, 198, 220, 220, 220, 220, 15116, 8728, 4907, 628, 220, 220, 220, 770, 8265, 4909, 10361, 5499, 329, 32096, ...
2.181818
1,485
# Copyright (c) 2019-2021, Jonas Eschle, Jim Pivarski, Eduardo Rodrigues, and Henry Schreiner. # # Distributed under the 3-clause BSD license, see accompanying file LICENSE # or https://github.com/scikit-hep/vector for details. import pytest import vector
[ 2, 15069, 357, 66, 8, 13130, 12, 1238, 2481, 11, 40458, 8678, 354, 293, 11, 5395, 350, 452, 945, 4106, 11, 40766, 13109, 16114, 947, 11, 290, 8616, 3059, 260, 7274, 13, 198, 2, 198, 2, 4307, 6169, 739, 262, 513, 12, 565, 682, 34...
3.158537
82
# vim:set ts=8 sw=2 sts=2 et: """Store signals.""" import itertools import struct import wave SAMPLE_SIZE = 16 # In bits class WaveStream(object): """A stream of PCM audio data.""" def __init__(self, channels, sample_rate, sample_size): """Initialize a WaveStream with integer samples. Args: channels: An iterable of the audio channels in the stream. Each item is also an iterable containing the samples of that audio channel. All audio channels must have the same number of samples. The samples are signed integers that fit in the sample size. sample_rate: The number of samples per second in the audio stream, in Hz. sample_size: The number of bits used to store each sample. Must be 16. """ self.channels = channels self.sample_size = sample_size self.sample_rate = sample_rate self.num_channels = len(channels) self.num_samples = len(channels[0]) # TODO(serban): It's convenient to use the struct module to encode the # samples as 16-bit little endian signed integers. To support other sample # sizes, like 20 bits or 24 bits per sample, I would need to use another # utility to encode the samples. For now, only 16-bit samples are supported. assert sample_size == 16, 'Sorry, only 16-bit samples are supported' @classmethod def from_floating_point(cls, channels, sample_rate): """Initialize a WaveStream with floating point samples. Args: channels: An iterable of the audio channels in the stream. Each item is also an iterable containing the samples of that audio channel. All audio channels must have the same number of samples. The samples are floats between -1.0 and 1.0. sample_rate: The number of samples per second in the audio stream, in Hz. Returns: A WaveStream """ sample_max = 2**(SAMPLE_SIZE-1) - 1 int_channels = [ [int(sample * sample_max) for sample in channel] for channel in channels] return cls(int_channels, sample_rate, SAMPLE_SIZE) def get_interleaved_samples(self): """Interleave the samples in the channels into a single bytestring. Returns: A bytestring of little endian signed integers """ num_interleaved_samples = self.num_channels * self.num_samples interleaved_samples = itertools.chain.from_iterable(zip(*self.channels)) struct_format = '<{}h'.format(num_interleaved_samples) return struct.pack(struct_format, *interleaved_samples) def write_wave_file(self, output_path): """Write a WAVE file of the stream contents. Args: output_path: The path to the resulting WAVE file. """ # TODO(serban): As of January 2014, Python 3.4 is still in beta. wave.open() # supports the context manager protocol in Python 3.4, but I'll wait until # it becomes stable before using a context manager here. See # http://docs.python.org/dev/whatsnew/3.4.html#wave for more information. output_file = wave.open(output_path, 'wb') output_file.setsampwidth(self.sample_size // 8) output_file.setframerate(self.sample_rate) output_file.setnchannels(self.num_channels) output_file.setnframes(self.num_samples) output_file.setcomptype('NONE', 'not compressed') output_file.writeframes(self.get_interleaved_samples()) output_file.close()
[ 2, 43907, 25, 2617, 40379, 28, 23, 1509, 28, 17, 39747, 28, 17, 2123, 25, 198, 198, 37811, 22658, 10425, 526, 15931, 198, 198, 11748, 340, 861, 10141, 198, 11748, 2878, 198, 11748, 6769, 628, 198, 49302, 16437, 62, 33489, 796, 1467, ...
2.937118
1,145
# encoding=utf-8 import logging logger = logging.getLogger(__name__)
[ 2, 21004, 28, 40477, 12, 23, 198, 11748, 18931, 198, 198, 6404, 1362, 796, 18931, 13, 1136, 11187, 1362, 7, 834, 3672, 834, 8, 198 ]
2.8
25
import xml.etree.ElementTree as ET from pprint import pprint as pp import re # from OMDB xmlstring = '''<?xml version="1.0" encoding="UTF-8"?> <root response="True"> <movie title="The Prestige" year="2006" rated="PG-13" released="20 Oct 2006" runtime="130 min" genre="Drama, Mystery, Sci-Fi" director="Christopher Nolan" /> <movie title="The Dark Knight" year="2008" rated="PG-13" released="18 Jul 2008" runtime="152 min" genre="Action, Crime, Drama" director="Christopher Nolan" /> <movie title="The Dark Knight Rises" year="2012" rated="PG-13" released="20 Jul 2012" runtime="164 min" genre="Action, Thriller" director="Christopher Nolan" /> <movie title="Dunkirk" year="2017" rated="PG-13" released="21 Jul 2017" runtime="106 min" genre="Action, Drama, History" director="Christopher Nolan" /> <movie title="Interstellar" year="2014" rated="PG-13" released="07 Nov 2014" runtime="169 min" genre="Adventure, Drama, Sci-Fi" director="Christopher Nolan"/> </root>''' # noqa E501 def get_tree(): """You probably want to use ET.fromstring""" root = ET.fromstring(xmlstring) return ET.ElementTree(root) def get_movies(): """Call get_tree and retrieve all movie titles, return a list or generator""" tree = get_tree() root = tree.getroot() for movie in root: yield movie.attrib['title'] def _get_runtime(movie): '''internal help function for receiving runtime of movie''' return int(re.search(r'(\d+) min', movie.attrib['runtime']).group(1)) def get_movie_longest_runtime(): """Call get_tree again and return the movie with the longest runtime in minutes, for latter consider adding a _get_runtime helper""" tree = get_tree() root = tree.getroot() max_runtime = 0 max_runtime_movie = '' for movie in root: if _get_runtime(movie) > max_runtime: max_runtime_movie = movie.attrib['title'] return max_runtime_movie
[ 11748, 35555, 13, 316, 631, 13, 20180, 27660, 355, 12152, 201, 198, 6738, 279, 4798, 1330, 279, 4798, 355, 9788, 201, 198, 11748, 302, 201, 198, 201, 198, 201, 198, 2, 422, 32468, 11012, 201, 198, 19875, 8841, 796, 705, 7061, 47934, ...
2.874818
687