content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
import pandas as pd import ta from app.common import reshape_data from app.strategies.base_strategy import BaseStrategy pd.set_option("display.max_columns", None) pd.set_option("display.width", None)
[ 11748, 19798, 292, 355, 279, 67, 198, 11748, 20486, 198, 198, 6738, 598, 13, 11321, 1330, 27179, 1758, 62, 7890, 198, 6738, 598, 13, 2536, 2397, 444, 13, 8692, 62, 2536, 4338, 1330, 7308, 13290, 4338, 198, 198, 30094, 13, 2617, 62, ...
3.029851
67
# Python Basics # String concatenaton added_strings = str(32) + "_342" # Getting input input_from_user = input() # Basic print function print(input_from_user) # Mixing boolean and comparison operations if (4 < 5) and (5 < 6): print("True") # Basic if & if else flow if name == 'Alice': print('Hi, Alice.') elif age < 12: print("You are not Alice, kiddo.") elif age > 2000: print('Unlike you, Alice is not an undead, immortal vampire.') elif age > 100: print('You are not Alice, grannie.') # Loops in Python 3 spam = 0 while spam < 5: print('Spam, spam!') spam = spam + 1 # Access loop while True: print('Who are you?') name = input() if name != 'Joe': continue print('Hello, Joe. What is the password? (It is a fish.)') password = input() if password = 'swordfish': break print('Access granted.') # For loops using range function print("My name is") for i in range(5): print('Jimmy Five Times (' + str(i) + ')') # Using starting range for i in range(12, 16): print(i) # Importing modules import random for i in range(5): print(random.randint(1, 10)) # Exiting a python program import sys while True: print('Type exit to exit.') response = input() if response == 'exit': sys.exit() print('You typed ' + response + '.')
[ 2, 11361, 45884, 198, 198, 2, 10903, 1673, 36686, 13951, 198, 29373, 62, 37336, 796, 220, 965, 7, 2624, 8, 1343, 45434, 31575, 1, 198, 198, 2, 18067, 5128, 198, 15414, 62, 6738, 62, 7220, 796, 5128, 3419, 198, 198, 2, 14392, 3601, ...
2.688129
497
DATABASE_OPTIONS = { 'database': 'klazor', 'user': 'root', 'password': '', 'charset': 'utf8mb4', } HOSTS = ['127.0.0.1', '67.209.115.211']
[ 35, 1404, 6242, 11159, 62, 3185, 51, 11053, 796, 1391, 198, 220, 220, 220, 705, 48806, 10354, 705, 41582, 17725, 3256, 198, 220, 220, 220, 705, 7220, 10354, 705, 15763, 3256, 198, 220, 220, 220, 705, 28712, 10354, 705, 3256, 198, 220,...
1.902439
82
""" Django settings. Generated by 'django-admin startproject' using Django 2.2.4. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ #DEBUG = False DEBUG = True SERVE_STATIC = DEBUG ALLOWED_HOSTS = [] # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { #'ENGINE': 'django.db.backends.oracle' #'ENGINE': 'django.db.backends.mysql', #'ENGINE': 'django.db.backends.sqlite3', 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'mydatabase', 'USER': 'mydatabaseuser', 'PASSWORD': 'mypassword', 'HOST': '127.0.0.1', 'PORT': '5432', } }
[ 37811, 198, 35, 73, 14208, 6460, 13, 198, 198, 8645, 515, 416, 705, 28241, 14208, 12, 28482, 923, 16302, 6, 1262, 37770, 362, 13, 17, 13, 19, 13, 198, 198, 1890, 517, 1321, 319, 428, 2393, 11, 766, 198, 5450, 1378, 31628, 13, 2824...
2.222826
368
from django import forms from .models import Contact
[ 6738, 42625, 14208, 1330, 5107, 198, 6738, 764, 27530, 1330, 14039, 628, 198 ]
4.230769
13
# Copyright (c) 2017 Ansible, Inc. # All Rights Reserved. from django.urls import re_path from awx.api.views import ( AdHocCommandList, AdHocCommandDetail, AdHocCommandCancel, AdHocCommandRelaunch, AdHocCommandAdHocCommandEventsList, AdHocCommandActivityStreamList, AdHocCommandNotificationsList, AdHocCommandStdout, ) urls = [ re_path(r'^$', AdHocCommandList.as_view(), name='ad_hoc_command_list'), re_path(r'^(?P<pk>[0-9]+)/$', AdHocCommandDetail.as_view(), name='ad_hoc_command_detail'), re_path(r'^(?P<pk>[0-9]+)/cancel/$', AdHocCommandCancel.as_view(), name='ad_hoc_command_cancel'), re_path(r'^(?P<pk>[0-9]+)/relaunch/$', AdHocCommandRelaunch.as_view(), name='ad_hoc_command_relaunch'), re_path(r'^(?P<pk>[0-9]+)/events/$', AdHocCommandAdHocCommandEventsList.as_view(), name='ad_hoc_command_ad_hoc_command_events_list'), re_path(r'^(?P<pk>[0-9]+)/activity_stream/$', AdHocCommandActivityStreamList.as_view(), name='ad_hoc_command_activity_stream_list'), re_path(r'^(?P<pk>[0-9]+)/notifications/$', AdHocCommandNotificationsList.as_view(), name='ad_hoc_command_notifications_list'), re_path(r'^(?P<pk>[0-9]+)/stdout/$', AdHocCommandStdout.as_view(), name='ad_hoc_command_stdout'), ] __all__ = ['urls']
[ 2, 15069, 357, 66, 8, 2177, 28038, 856, 11, 3457, 13, 198, 2, 1439, 6923, 33876, 13, 198, 198, 6738, 42625, 14208, 13, 6371, 82, 1330, 302, 62, 6978, 198, 198, 6738, 3253, 87, 13, 15042, 13, 33571, 1330, 357, 198, 220, 220, 220, ...
2.294964
556
#test.py from time_tools import * # print(compareTimestamp(111,222)) time.showNowTime() # now time is XX:XX:XX
[ 2, 9288, 13, 9078, 198, 6738, 640, 62, 31391, 1330, 1635, 198, 2, 3601, 7, 5589, 533, 14967, 27823, 7, 16243, 11, 23148, 4008, 198, 2435, 13, 12860, 3844, 7575, 3419, 198, 2, 783, 640, 318, 21044, 25, 8051, 25, 8051 ]
2.682927
41
import arcade from arcade import FACE_RIGHT, FACE_DOWN, FACE_UP, FACE_LEFT
[ 11748, 27210, 198, 6738, 27210, 1330, 46587, 62, 49, 9947, 11, 46587, 62, 41925, 11, 46587, 62, 8577, 11, 46587, 62, 2538, 9792, 198 ]
3.125
24
from numpy.core.fromnumeric import transpose from sklearn import linear_model from scipy.special import logit from scipy import stats from copy import deepcopy from numpy import random, concatenate, quantile, matmul, transpose import logging
[ 6738, 299, 32152, 13, 7295, 13, 6738, 77, 39223, 1330, 1007, 3455, 198, 6738, 1341, 35720, 1330, 14174, 62, 19849, 198, 6738, 629, 541, 88, 13, 20887, 1330, 2604, 270, 198, 6738, 629, 541, 88, 1330, 9756, 198, 6738, 4866, 1330, 2769, ...
3.626866
67
import numpy as np import matplotlib.pyplot as plt from scipy import stats from sklearn.linear_model import ARDRegression, LinearRegression # Parameters of the example np.random.seed(0) n_samples, n_features = 100, 100 # Create Gaussian data X = np.random.randn(n_samples, n_features) # Create weights with a precision lambda_ of 4. lambda_ = 4. w = np.zeros(n_features) # Only keep 10 weights of interest relevant_features = np.random.randint(0, n_features, 10) for i in relevant_features: w[i] = stats.norm.rvs(loc=0, scale=1. / np.sqrt(lambda_)) # Create noise with a precision alpha of 50. alpha_ = 50. noise = stats.norm.rvs(loc=0, scale=1. / np.sqrt(alpha_), size=n_samples) # Create the target< y = np.dot(X, w) + noise clf = ARDRegression(fit_intercept=False, n_iter=1000) clf.fit(X, y) ols = LinearRegression(fit_intercept=False) ols.fit(X, y) from copy import deepcopy from sds.distributions.lingauss import SingleOutputLinearGaussianWithKnownPrecision from sds.distributions.lingauss import SingleOutputLinearGaussianWithKnownMean from sds.distributions.gaussian import GaussianWithPrecision from sds.distributions.gaussian import GaussianWithKnownMeanAndDiagonalPrecision from sds.distributions.gamma import Gamma likelihood_precision_prior = Gamma(dim=1, alphas=np.ones((1, )), betas=1e-6 * np.ones((1, ))) parameter_precision_prior = Gamma(dim=n_features, alphas=np.ones((n_features, )), betas=1e-6 * np.ones((n_features, ))) likelihood_precision_posterior = deepcopy(likelihood_precision_prior) parameter_precision_posterior = deepcopy(parameter_precision_prior) parameter_posterior = None for i in range(100): # parameter posterior alphas = parameter_precision_posterior.mean() parameter_prior = GaussianWithPrecision(dim=n_features, mu=np.zeros((n_features, )), lmbda=np.diag(alphas)) parameter_posterior = deepcopy(parameter_prior) beta = likelihood_precision_posterior.mean() likelihood_known_precision = SingleOutputLinearGaussianWithKnownPrecision(column_dim=n_features, lmbda=beta, affine=False) stats = likelihood_known_precision.statistics(X, y) parameter_posterior.nat_param = parameter_prior.nat_param + stats # likelihood precision posterior param = parameter_posterior.mean() likelihood_known_mean = SingleOutputLinearGaussianWithKnownMean(column_dim=n_features, W=param, affine=False) stats = likelihood_known_mean.statistics(X, y) likelihood_precision_posterior.nat_param = likelihood_precision_prior.nat_param + stats # parameter precision posterior parameter_likelihood = GaussianWithKnownMeanAndDiagonalPrecision(dim=n_features) param = parameter_posterior.mean() stats = parameter_likelihood.statistics(param) parameter_precision_posterior.nat_param = parameter_precision_prior.nat_param + stats our_ard = parameter_posterior.mode() from sds.distributions.composite import MatrixNormalGamma from sds.distributions.lingauss import LinearGaussianWithDiagonalPrecision M = np.zeros((1, n_features)) K = 1e-16 * np.eye(n_features) alphas = 1e-16 * np.ones((1, )) betas = 1e-16 * np.ones((1, )) prior = MatrixNormalGamma(column_dim=n_features, row_dim=1, M=M, K=K, alphas=alphas, betas=betas) posterior = deepcopy(prior) likelihood = LinearGaussianWithDiagonalPrecision(column_dim=n_features, row_dim=1, affine=False) stats = likelihood.statistics(X, np.atleast_2d(y).T) posterior.nat_param = prior.nat_param + stats our_ols = posterior.mode()[0] plt.figure(figsize=(6, 5)) plt.title("Weights of the model") plt.plot(w, color='orange', linestyle='-', linewidth=2, label="Ground truth") plt.plot(clf.coef_, color='darkblue', linestyle='-', linewidth=2, label="Sklearn ARD") plt.plot(our_ard, color='red', linestyle='-', linewidth=2, label="Our ARD") # plt.plot(ols.coef_, color='yellowgreen', linestyle=':', linewidth=2, label="Sklearn OLS") # plt.plot(our_ols.flatten(), color='cyan', linestyle='-', linewidth=2, label="Our OLS") plt.xlabel("Features") plt.ylabel("Values of the weights") plt.legend(loc=1) plt.show()
[ 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 6738, 629, 541, 88, 1330, 9756, 198, 198, 6738, 1341, 35720, 13, 29127, 62, 19849, 1330, 5923, 7707, 1533, 2234, 11, 44800, 8081, 2234, ...
2.302984
1,977
#!/usr/bin/python3 import os import json import re import ast import json from graphviz import Digraph import pandas as pd # color the graph import graph_tool.all as gt import copy import matplotlib.colors as mcolors import sys import utils from tompkins.ilp import schedule, jobs_when_where from collections import defaultdict from pulp import value import re import ast import json from graphviz import Digraph import pandas as pd # color the graph import graph_tool.all as gt import copy import matplotlib.colors as mcolors import sys import seaborn as sns import pulp as pl import time results_dir = './benchmarks' stats_dir='./benchmarks' benchmarks = get_benchmarks() #benchmarks = ['dom4x61GB1B', 'dom2x41GB1B', 'tree4x61GB1B'] for bnch in benchmarks: for bw in [1*1024, 16*1024, 512, 32*1024, 8*1024, 4*1024, 2*1024, 256, 128, 64, 32]: print(f'process {bnch}') g = build_graph(bnch) sched2, stats = find_optimal(g, bw) with open(f'{results_dir}/optimal_compuation_stats.csv', 'a') as fd: fd.write(f'{bnch},{stats["makespan"]},{stats["constraints"]},{stats["variables"]},{stats["time"]},no,{bw}\n') with open(f'{results_dir}/{bnch}.nonetworkcontention.{bw}mbps.optimal', 'w') as fd: for s in sched2: fd.write(f'v,{s[0]},{s[1]},{s[2]}\n') #fd.write(f'{s[4]},{s[3]},{s[0]},{s[1]},{s[2]}\n') #v = int(s[0].replace('t', '')) #g.vp.worker[v] = s[2] break #break
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 198, 11748, 28686, 198, 11748, 33918, 198, 11748, 302, 198, 11748, 6468, 198, 11748, 33918, 198, 6738, 4823, 85, 528, 1330, 7367, 1470, 198, 11748, 19798, 292, 355, 279, 67, 198, 198, 2, ...
2.203463
693
from __future__ import absolute_import import unittest from testutils import ADMIN_CLIENT from testutils import TEARDOWN from library.user import User from library.project import Project from library.repository import Repository from library.repository import pull_harbor_image from library.repository import push_image_to_project from testutils import harbor_server from library.base import _assert_status_code if __name__ == '__main__': unittest.main()
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 198, 11748, 555, 715, 395, 198, 198, 6738, 1332, 26791, 1330, 5984, 23678, 62, 5097, 28495, 198, 6738, 1332, 26791, 1330, 13368, 9795, 14165, 198, 6738, 5888, 13, 7220, 1330, 11787, 1...
3.601563
128
import datetime as dt import logging from babel import Locale, UnknownLocaleError from babel.dates import format_datetime, format_time, format_date import pytz from tzlocal import get_localzone from . import settings logger = logging.getLogger(__name__) def format_datetime_str(self, my_datetime: dt.datetime) -> str: """returns formated datetime string for given dt using locale""" return format_datetime(my_datetime, format="short", locale=self.locale) def get_datetime_formatted_str(self, ts: int) -> str: """return given timestamp as formated datetime string using locale""" my_datetime = self.get_datetime_from_ts(ts) return format_datetime(my_datetime, format="short", locale=self.locale) def get_time_formatted_str(self, ts: int) -> str: """return given timestamp as formated datetime string using locale""" my_datetime = self.get_datetime_from_ts(ts) return format_time(my_datetime, format="short", locale=self.locale) def get_datetime_from_ts(self, ts: int) -> dt.datetime: """returns datetime object of a unix timestamp with local timezone""" my_datetime = dt.datetime.fromtimestamp(float(ts), pytz.UTC) return my_datetime.astimezone(self.timezone)
[ 11748, 4818, 8079, 355, 288, 83, 198, 11748, 18931, 198, 198, 6738, 9289, 417, 1330, 15181, 1000, 11, 16185, 33711, 1000, 12331, 198, 6738, 9289, 417, 13, 19581, 1330, 5794, 62, 19608, 8079, 11, 5794, 62, 2435, 11, 5794, 62, 4475, 198...
2.735484
465
import os ######################################################################
[ 11748, 28686, 628, 198, 198, 29113, 29113, 4242, 2235, 628, 628 ]
7.909091
11
# !/usr/bin/env python # -- coding: utf-8 -- # @Author zengxiaohui # Datatime:8/31/2021 1:37 PM # @File:GlobalAvgPool2d import torch.nn as nn from python_developer_tools.cv.bases.activates.swish import h_swish
[ 2, 5145, 14, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 1377, 19617, 25, 3384, 69, 12, 23, 1377, 198, 2, 2488, 13838, 1976, 1516, 36072, 1219, 9019, 198, 2, 16092, 265, 524, 25, 23, 14, 3132, 14, 1238, 2481, 352, 25, 2718, 3122, ...
2.397727
88
"""Some utility functions""" # Authors: Eric Larson <larsoner@uw.edu> # # License: BSD (3-clause) import warnings import operator from copy import deepcopy import subprocess import importlib import os import os.path as op import inspect import sys import tempfile import ssl from shutil import rmtree import atexit import json from functools import partial from distutils.version import LooseVersion from numpy import sqrt, convolve, ones import logging import datetime from timeit import default_timer as clock from threading import Timer import numpy as np import scipy as sp from ._externals import decorator # set this first thing to make sure it "takes" try: import pyglet pyglet.options['debug_gl'] = False del pyglet except Exception: pass # for py3k (eventually) if sys.version.startswith('2'): string_types = basestring # noqa input = raw_input # noqa, input is raw_input in py3k text_type = unicode # noqa from __builtin__ import reload from urllib2 import urlopen # noqa from cStringIO import StringIO # noqa else: string_types = str text_type = str from urllib.request import urlopen input = input from io import StringIO # noqa, analysis:ignore from importlib import reload # noqa, analysis:ignore ############################################################################### # LOGGING EXP = 25 logging.addLevelName(EXP, 'EXP') def exp(self, message, *args, **kwargs): """Experiment-level logging.""" self.log(EXP, message, *args, **kwargs) logging.Logger.exp = exp logger = logging.getLogger('expyfun') def flush_logger(): """Flush expyfun logger""" for handler in logger.handlers: handler.flush() def set_log_level(verbose=None, return_old_level=False): """Convenience function for setting the logging level Parameters ---------- verbose : bool, str, int, or None The verbosity of messages to print. If a str, it can be either DEBUG, INFO, WARNING, ERROR, or CRITICAL. Note that these are for convenience and are equivalent to passing in logging.DEBUG, etc. For bool, True is the same as 'INFO', False is the same as 'WARNING'. If None, the environment variable EXPYFUN_LOGGING_LEVEL is read, and if it doesn't exist, defaults to INFO. return_old_level : bool If True, return the old verbosity level. """ if verbose is None: verbose = get_config('EXPYFUN_LOGGING_LEVEL', 'INFO') elif isinstance(verbose, bool): verbose = 'INFO' if verbose is True else 'WARNING' if isinstance(verbose, string_types): verbose = verbose.upper() logging_types = dict(DEBUG=logging.DEBUG, INFO=logging.INFO, WARNING=logging.WARNING, ERROR=logging.ERROR, CRITICAL=logging.CRITICAL) if verbose not in logging_types: raise ValueError('verbose must be of a valid type') verbose = logging_types[verbose] old_verbose = logger.level logger.setLevel(verbose) return (old_verbose if return_old_level else None) def set_log_file(fname=None, output_format='%(asctime)s - %(levelname)-7s - %(message)s', overwrite=None): """Convenience function for setting the log to print to a file Parameters ---------- fname : str, or None Filename of the log to print to. If None, stdout is used. To suppress log outputs, use set_log_level('WARN'). output_format : str Format of the output messages. See the following for examples: http://docs.python.org/dev/howto/logging.html e.g., "%(asctime)s - %(levelname)s - %(message)s". overwrite : bool, or None Overwrite the log file (if it exists). Otherwise, statements will be appended to the log (default). None is the same as False, but additionally raises a warning to notify the user that log entries will be appended. """ handlers = logger.handlers for h in handlers: if isinstance(h, logging.FileHandler): h.close() logger.removeHandler(h) if fname is not None: if op.isfile(fname) and overwrite is None: warnings.warn('Log entries will be appended to the file. Use ' 'overwrite=False to avoid this message in the ' 'future.') mode = 'w' if overwrite is True else 'a' lh = logging.FileHandler(fname, mode=mode) else: """ we should just be able to do: lh = logging.StreamHandler(sys.stdout) but because doctests uses some magic on stdout, we have to do this: """ lh = logging.StreamHandler(WrapStdOut()) lh.setFormatter(logging.Formatter(output_format)) # actually add the stream handler logger.addHandler(lh) ############################################################################### # RANDOM UTILITIES building_doc = any('sphinx-build' in ((''.join(i[4]).lower() + i[1]) if i[4] is not None else '') for i in inspect.stack()) def run_subprocess(command, **kwargs): """Run command using subprocess.Popen Run command and wait for command to complete. If the return code was zero then return, otherwise raise CalledProcessError. By default, this will also add stdout= and stderr=subproces.PIPE to the call to Popen to suppress printing to the terminal. Parameters ---------- command : list of str Command to run as subprocess (see subprocess.Popen documentation). **kwargs : objects Keywoard arguments to pass to ``subprocess.Popen``. Returns ------- stdout : str Stdout returned by the process. stderr : str Stderr returned by the process. """ # code adapted with permission from mne-python kw = dict(stderr=subprocess.PIPE, stdout=subprocess.PIPE) kw.update(kwargs) p = subprocess.Popen(command, **kw) stdout_, stderr = p.communicate() output = (stdout_.decode(), stderr.decode()) if p.returncode: err_fun = subprocess.CalledProcessError.__init__ if 'output' in _get_args(err_fun): raise subprocess.CalledProcessError(p.returncode, command, output) else: raise subprocess.CalledProcessError(p.returncode, command) return output def date_str(): """Produce a date string for the current date and time Returns ------- datestr : str The date string. """ return str(datetime.datetime.today()).replace(':', '_') def check_units(units): """Ensure user passed valid units type Parameters ---------- units : str Must be ``'norm'``, ``'deg'``, or ``'pix'``. """ good_units = ['norm', 'pix', 'deg'] if units not in good_units: raise ValueError('"units" must be one of {}, not {}' ''.format(good_units, units)) ############################################################################### # DECORATORS # Following deprecated class copied from scikit-learn if hasattr(inspect, 'signature'): # py35 else: def requires_video(): """Requires FFmpeg/AVbin decorator.""" import pytest return pytest.mark.skipif(not _has_video(), reason='Requires FFmpeg/AVbin') def requires_opengl21(func): """Requires OpenGL decorator.""" import pytest import pyglet.gl vendor = pyglet.gl.gl_info.get_vendor() version = pyglet.gl.gl_info.get_version() sufficient = pyglet.gl.gl_info.have_version(2, 0) return pytest.mark.skipif(not sufficient, reason='OpenGL too old: %s %s' % (vendor, version,))(func) def requires_lib(lib): """Requires lib decorator.""" import pytest try: importlib.import_module(lib) except Exception as exp: val = True reason = 'Needs %s (%s)' % (lib, exp) else: val = False reason = '' return pytest.mark.skipif(val, reason=reason) def _get_user_home_path(): """Return standard preferences path""" # this has been checked on OSX64, Linux64, and Win32 val = os.getenv('APPDATA' if 'nt' == os.name.lower() else 'HOME', None) if val is None: raise ValueError('expyfun config file path could ' 'not be determined, please report this ' 'error to expyfun developers') return val def fetch_data_file(fname): """Fetch example remote file Parameters ---------- fname : str The remote filename to get. If the filename already exists on the local system, the file will not be fetched again. Returns ------- fname : str The filename on the local system where the file was downloaded. """ path = get_config('EXPYFUN_DATA_PATH', op.join(_get_user_home_path(), '.expyfun', 'data')) fname_out = op.join(path, fname) if not op.isdir(op.dirname(fname_out)): os.makedirs(op.dirname(fname_out)) fname_url = ('https://github.com/LABSN/expyfun-data/raw/master/{0}' ''.format(fname)) try: # until we get proper certificates context = ssl._create_unverified_context() this_urlopen = partial(urlopen, context=context) except AttributeError: context = None this_urlopen = urlopen if not op.isfile(fname_out): try: with open(fname_out, 'wb') as fid: www = this_urlopen(fname_url, timeout=30.0) try: fid.write(www.read()) finally: www.close() except Exception: os.remove(fname_out) raise return fname_out def get_config_path(): r"""Get path to standard expyfun config file. Returns ------- config_path : str The path to the expyfun configuration file. On windows, this will be '%APPDATA%\.expyfun\expyfun.json'. On every other system, this will be $HOME/.expyfun/expyfun.json. """ val = op.join(_get_user_home_path(), '.expyfun', 'expyfun.json') return val # List the known configuration values known_config_types = ('RESPONSE_DEVICE', 'AUDIO_CONTROLLER', 'DB_OF_SINE_AT_1KHZ_1RMS', 'EXPYFUN_EYELINK', 'SOUND_CARD_API', 'SOUND_CARD_BACKEND', 'SOUND_CARD_FS', 'SOUND_CARD_NAME', 'SOUND_CARD_FIXED_DELAY', 'TDT_CIRCUIT_PATH', 'TDT_DELAY', 'TDT_INTERFACE', 'TDT_MODEL', 'TDT_TRIG_DELAY', 'TRIGGER_CONTROLLER', 'TRIGGER_ADDRESS', 'WINDOW_SIZE', 'SCREEN_NUM', 'SCREEN_WIDTH', 'SCREEN_DISTANCE', 'SCREEN_SIZE_PIX', 'EXPYFUN_LOGGING_LEVEL', ) # These allow for partial matches: 'NAME_1' is okay key if 'NAME' is listed known_config_wildcards = () def get_config(key=None, default=None, raise_error=False): """Read expyfun preference from env, then expyfun config Parameters ---------- key : str The preference key to look for. The os environment is searched first, then the expyfun config file is parsed. default : str | None Value to return if the key is not found. raise_error : bool If True, raise an error if the key is not found (instead of returning default). Returns ------- value : str | None The preference key value. """ if key is not None and not isinstance(key, string_types): raise ValueError('key must be a string') # first, check to see if key is in env if key is not None and key in os.environ: return os.environ[key] # second, look for it in expyfun config file config_path = get_config_path() if not op.isfile(config_path): key_found = False val = default else: with open(config_path, 'r') as fid: config = json.load(fid) if key is None: return config key_found = True if key in config else False val = config.get(key, default) if not key_found and raise_error is True: meth_1 = 'os.environ["%s"] = VALUE' % key meth_2 = 'expyfun.utils.set_config("%s", VALUE)' % key raise KeyError('Key "%s" not found in environment or in the ' 'expyfun config file:\n%s\nTry either:\n' ' %s\nfor a temporary solution, or:\n' ' %s\nfor a permanent one. You can also ' 'set the environment variable before ' 'running python.' % (key, config_path, meth_1, meth_2)) return val def set_config(key, value): """Set expyfun preference in config Parameters ---------- key : str | None The preference key to set. If None, a tuple of the valid keys is returned, and ``value`` is ignored. value : str | None The value to assign to the preference key. If None, the key is deleted. """ if key is None: return sorted(known_config_types) if not isinstance(key, string_types): raise ValueError('key must be a string') # While JSON allow non-string types, we allow users to override config # settings using env, which are strings, so we enforce that here if not isinstance(value, string_types) and value is not None: raise ValueError('value must be a string or None') if key not in known_config_types and not \ any(k in key for k in known_config_wildcards): warnings.warn('Setting non-standard config type: "%s"' % key) # Read all previous values config_path = get_config_path() if op.isfile(config_path): with open(config_path, 'r') as fid: config = json.load(fid) else: config = dict() logger.info('Attempting to create new expyfun configuration ' 'file:\n%s' % config_path) if value is None: config.pop(key, None) else: config[key] = value # Write all values directory = op.split(config_path)[0] if not op.isdir(directory): os.mkdir(directory) with open(config_path, 'w') as fid: json.dump(config, fid, sort_keys=True, indent=0) ############################################################################### # MISC def fake_button_press(ec, button='1', delay=0.): """Fake a button press after a delay Notes ----- This function only works with the keyboard controller (not TDT)! It uses threads to ensure that control is passed back, so other commands can be called (like wait_for_presses). """ Timer(delay, send).start() if delay > 0. else send() def fake_mouse_click(ec, pos, button='left', delay=0.): """Fake a mouse click after a delay""" button = dict(left=1, middle=2, right=4)[button] # trans to pyglet Timer(delay, send).start() if delay > 0. else send() def _check_pyglet_version(raise_error=False): """Check pyglet version, return True if usable. """ import pyglet is_usable = LooseVersion(pyglet.version) >= LooseVersion('1.2') if raise_error is True and is_usable is False: raise ImportError('On Linux, you must run at least Pyglet ' 'version 1.2, and you are running ' '{0}'.format(pyglet.version)) return is_usable def _wait_secs(secs, ec=None): """Wait a specified number of seconds. Parameters ---------- secs : float Number of seconds to wait. ec : None | expyfun.ExperimentController instance The ExperimentController. Notes ----- This function uses a while loop. Although this slams the CPU, it will guarantee that events (keypresses, etc.) are processed. """ # hog the cpu, checking time t0 = clock() if ec is not None: while (clock() - t0) < secs: ec._dispatch_events() ec.check_force_quit() else: wins = _get_display().get_windows() for win in wins: win.dispatch_events() def running_rms(signal, win_length): """RMS of ``signal`` with rectangular window ``win_length`` samples long. Parameters ---------- signal : array_like The (1-dimesional) signal of interest. win_length : int Length (in samples) of the rectangular window """ return sqrt(convolve(signal ** 2, ones(win_length) / win_length, 'valid')) def _fix_audio_dims(signal, n_channels): """Make it so a valid audio buffer is in the standard dimensions Parameters ---------- signal : array_like The signal whose dimensions should be checked and fixed. n_channels : int The number of channels that the output should have. If the input is mono and n_channels=2, it will be tiled to be shape (2, n_samples). Otherwise, the number of channels in signal must match n_channels. Returns ------- signal_fixed : array The signal with standard dimensions (n_channels, N). """ # Check requested channel output n_channels = int(operator.index(n_channels)) signal = np.asarray(np.atleast_2d(signal), dtype=np.float32) # Check dimensionality if signal.ndim != 2: raise ValueError('Sound data must have one or two dimensions, got %s.' % (signal.ndim,)) # Return data with correct dimensions if n_channels == 2 and signal.shape[0] == 1: signal = np.tile(signal, (n_channels, 1)) if signal.shape[0] != n_channels: raise ValueError('signal channel count %d did not match required ' 'channel count %d' % (signal.shape[0], n_channels)) return signal def _sanitize(text_like): """Cast as string, encode as UTF-8 and sanitize any escape characters. """ return text_type(text_like).encode('unicode_escape').decode('utf-8') def _sort_keys(x): """Sort and return keys of dict""" keys = list(x.keys()) # note: not thread-safe idx = np.argsort([str(k) for k in keys]) keys = [keys[ii] for ii in idx] return keys def object_diff(a, b, pre=''): """Compute all differences between two python variables Parameters ---------- a : object Currently supported: dict, list, tuple, ndarray, int, str, bytes, float, StringIO, BytesIO. b : object Must be same type as ``a``. pre : str String to prepend to each line. Returns ------- diffs : str A string representation of the differences. Notes ----- Taken from mne-python with permission. """ out = '' if type(a) != type(b): out += pre + ' type mismatch (%s, %s)\n' % (type(a), type(b)) elif isinstance(a, dict): k1s = _sort_keys(a) k2s = _sort_keys(b) m1 = set(k2s) - set(k1s) if len(m1): out += pre + ' x1 missing keys %s\n' % (m1) for key in k1s: if key not in k2s: out += pre + ' x2 missing key %s\n' % key else: out += object_diff(a[key], b[key], pre + 'd1[%s]' % repr(key)) elif isinstance(a, (list, tuple)): if len(a) != len(b): out += pre + ' length mismatch (%s, %s)\n' % (len(a), len(b)) else: for xx1, xx2 in zip(a, b): out += object_diff(xx1, xx2, pre='') elif isinstance(a, (string_types, int, float, bytes)): if a != b: out += pre + ' value mismatch (%s, %s)\n' % (a, b) elif a is None: if b is not None: out += pre + ' a is None, b is not (%s)\n' % (b) elif isinstance(a, np.ndarray): if not np.array_equal(a, b): out += pre + ' array mismatch\n' else: raise RuntimeError(pre + ': unsupported type %s (%s)' % (type(a), a)) return out
[ 37811, 4366, 10361, 5499, 37811, 198, 198, 2, 46665, 25, 7651, 42630, 1279, 75, 12613, 263, 31, 84, 86, 13, 15532, 29, 198, 2, 198, 2, 13789, 25, 347, 10305, 357, 18, 12, 565, 682, 8, 198, 198, 11748, 14601, 198, 11748, 10088, 198...
2.351299
8,702
import signal
[ 11748, 6737, 198 ]
4.666667
3
a = HAHA() print(a) print(a[0])
[ 201, 198, 64, 796, 14558, 7801, 3419, 201, 198, 4798, 7, 64, 8, 201, 198, 4798, 7, 64, 58, 15, 12962, 201, 198 ]
1.608696
23
import torch import torch.overrides import linecache from typing import Type, Dict, List, Any, Union from .graph import Graph import copy # normal exec loses the source code, however we can patch # the linecache module to still recover it. # using exec_with_source will add it to our local cache # and then tools like TorchScript will be able to get source info. _next_id = 0 # patch linecache so that any code we exec using exec_with_source # works with inspect _eval_cache : Dict[str, List[str]] = {} _orig_getlines = linecache.getlines linecache.getlines = patched_getline def deserialize_graphmodule(body : dict) -> torch.nn.Module: """ Deserialize a GraphModule given the dictionary of the original module, using the code to reconstruct the graph. We delete the actual graph before saving the dictionary so that changes to the in-memory graph format do not get serialized. """ # We create a dummy class here because symbolic_trace pulls the forward() # function off of the class, rather than the instance CodeOnlyModule.forward = _forward_from_src(body['code']) from .symbolic_trace import Tracer # we shouldn't trace into any of the submodules, they were not # because they were not traced in the original GraphModule return KeepModules().trace(CodeOnlyModule(body)) # copy an attribute value with qualified name 'target' from 'from_module' to 'to_module' # This installs empty Modules where none exist yet if they are subpaths of target # Assign attribute 'from_obj' to the qualified name 'target' on 'to_module # This installs empty Modules where none exist yet if they are subpaths of target # because __reduce__ is defined for serialization, # we need to define deepcopy otherwise it will call __reduce__ # and cause symbolic tracing to occur every time we try to copy the object def __deepcopy__(self, memo): fake_mod = torch.nn.Module() fake_mod.__dict__ = copy.deepcopy(self.__dict__) return GraphModule(fake_mod, self.graph) def __copy__(self): return GraphModule(self, self.graph) def __str__(self) -> str: orig_str = super().__str__() return '\n'.join([orig_str, self.code]) # workarounds for issues in __torch_function__ # WAR for __torch_function__ not handling tensor lists, # fix is in https://github.com/pytorch/pytorch/pull/34725 # orig_cat = torch.cat # def patched_cat(*args, **kwargs): # tensors = args[0] # for t in tensors: # if isinstance(t, Proxy): # return t.__torch_function__(patched_cat, (), args, kwargs) # return orig_cat(*args, **kwargs) # patched_cat.__module__ = 'torch' # patched_cat.__name__ = 'cat' # torch.cat = patched_cat
[ 11748, 28034, 198, 11748, 28034, 13, 2502, 81, 1460, 198, 11748, 1627, 23870, 198, 6738, 19720, 1330, 5994, 11, 360, 713, 11, 7343, 11, 4377, 11, 4479, 198, 6738, 764, 34960, 1330, 29681, 198, 11748, 4866, 198, 198, 2, 3487, 2452, 147...
3.075281
890
# # Copyright (c) 2016 Christoph Heiss <me@christoph-heiss.me> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # import os import json import struct import threading import socket import queue import tempfile import base64 import select from behem0th import utils, log BLOCK_SIZE = 4096 """ { "action": "<action>", "path": "<relpath-to-file>" } <action> can be either 'receive' or 'send' Payload are base64 encoded chunks (BLOCK_SIZE bytes) """ """ { "type": "<type>", "path": "<relpath-to-file>" } <type> can be one of 'file-created', 'file-deleted', 'file-moved' """ ROUTES = { 'filelist': FilelistRoute(), 'file': FileRoute(), 'event': EventRoute() } """ behem0th's protocol is completely text-based, using utf-8 encoding and encoded in JSON for easy parsing. A request usually looks like this: { "route": "<route-name>", "data": "<data>" } 'data' holds additional data which is then passed to the route. There is no special format designed for 'data' and is specific to each route. After each request there is a newline to separate them. (think of HTTP) If a route needs to transfer additional data (a 'payload'), it has to send them in a text-based format, e.g. base-64 encoding for binary data. After the payload, if any, there has to be another newline to separate it from the next request. """
[ 2, 198, 2, 15069, 357, 66, 8, 1584, 1951, 2522, 679, 747, 1279, 1326, 31, 43533, 2522, 12, 258, 747, 13, 1326, 29, 198, 2, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 257, 4866, 198, 2, ...
3.368046
701
from hover.utils.metrics import classification_accuracy import numpy as np
[ 6738, 20599, 13, 26791, 13, 4164, 10466, 1330, 17923, 62, 4134, 23843, 198, 11748, 299, 32152, 355, 45941, 198 ]
3.947368
19
#!/usr/bin/python # # This source file is part of appleseed. # Visit https://appleseedhq.net/ for additional information and resources. # # This software is released under the MIT license. # # Copyright (c) 2017-2018 Esteban Tovagliari, The appleseedhq Organization # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the 'Software'), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # from __future__ import print_function from distutils import archive_util, dir_util from xml.etree.ElementTree import ElementTree import argparse import colorama import datetime import glob import os import platform import re import shutil import stat import subprocess import sys import time import traceback import urllib #-------------------------------------------------------------------------------------------------- # Constants. #-------------------------------------------------------------------------------------------------- VERSION = "1.1.0" SETTINGS_FILENAME = "blenderseed.package.configuration.xml" #-------------------------------------------------------------------------------------------------- # Utility functions. #-------------------------------------------------------------------------------------------------- GREEN_CHECKMARK = u"{0}\u2713{1}".format(colorama.Style.BRIGHT + colorama.Fore.GREEN, colorama.Style.RESET_ALL) RED_CROSSMARK = u"{0}\u2717{1}".format(colorama.Style.BRIGHT + colorama.Fore.RED, colorama.Style.RESET_ALL) #-------------------------------------------------------------------------------------------------- # Settings. #-------------------------------------------------------------------------------------------------- #-------------------------------------------------------------------------------------------------- # Base package builder. #-------------------------------------------------------------------------------------------------- #-------------------------------------------------------------------------------------------------- # Windows package builder. #-------------------------------------------------------------------------------------------------- #-------------------------------------------------------------------------------------------------- # Mac package builder. #-------------------------------------------------------------------------------------------------- #-------------------------------------------------------------------------------------------------- # Linux package builder. #-------------------------------------------------------------------------------------------------- #-------------------------------------------------------------------------------------------------- # Entry point. #-------------------------------------------------------------------------------------------------- def main(): colorama.init() parser = argparse.ArgumentParser(description="build a blenderseed package from sources") parser.add_argument("--nozip", action="store_true", help="copies appleseed binaries to blenderseed folder but does not build a release package") args = parser.parse_args() no_release = args.nozip package_version = subprocess.Popen("git describe --long", stdout=subprocess.PIPE, shell=True).stdout.read().strip() build_date = datetime.date.today().isoformat() print("blenderseed.package version " + VERSION) print("") settings = Settings() settings.load() settings.print_summary() if os.name == "nt": package_builder = WindowsPackageBuilder(settings, package_version, build_date, no_release) elif os.name == "posix" and platform.mac_ver()[0] != "": package_builder = MacPackageBuilder(settings, package_version, build_date, no_release) elif os.name == "posix" and platform.mac_ver()[0] == "": package_builder = LinuxPackageBuilder(settings, package_version, build_date, no_release) else: fatal("Unsupported platform: " + os.name) package_builder.build_package() if __name__ == "__main__": main()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 198, 2, 198, 2, 770, 2723, 2393, 318, 636, 286, 22514, 2308, 13, 198, 2, 16440, 3740, 1378, 1324, 829, 2308, 71, 80, 13, 3262, 14, 329, 3224, 1321, 290, 4133, 13, 198, 2, 198, 2, 770, ...
4.426025
1,122
ser = int(input()) mas = list(map(int, input().split())) mas.sort() print(*mas)
[ 2655, 796, 493, 7, 15414, 28955, 198, 5356, 796, 1351, 7, 8899, 7, 600, 11, 5128, 22446, 35312, 3419, 4008, 198, 5356, 13, 30619, 3419, 198, 4798, 46491, 5356, 8, 198 ]
2.580645
31
from django.utils.translation import gettext from wagtail.admin.rich_text.editors.draftail import features as draftail_features from wagtail.core import hooks from .richtext import KaTeXEntityElementHandler, katex_entity_decorator
[ 6738, 42625, 14208, 13, 26791, 13, 41519, 1330, 651, 5239, 198, 198, 6738, 266, 363, 13199, 13, 28482, 13, 7527, 62, 5239, 13, 276, 6742, 13, 35679, 603, 1330, 3033, 355, 4538, 603, 62, 40890, 198, 6738, 266, 363, 13199, 13, 7295, 1...
3.492537
67
############################################################### # Autogenerated module. Please don't modify. # # Edit according file in protocol_generator/templates instead # ############################################################### from typing import Dict from ...structs.api.elect_preferred_leaders_request import ElectPreferredLeadersRequestData, TopicPartition from ._main_serializers import ArraySerializer, ClassSerializer, Schema, int32Serializer, stringSerializer topicPartitionSchemas: Dict[int, Schema] = { 0: [("topic", stringSerializer), ("partition_id", ArraySerializer(int32Serializer))] } topicPartitionSerializers: Dict[int, ClassSerializer[TopicPartition]] = { version: ClassSerializer(TopicPartition, schema) for version, schema in topicPartitionSchemas.items() } topicPartitionSerializers[-1] = topicPartitionSerializers[0] electPreferredLeadersRequestDataSchemas: Dict[int, Schema] = { 0: [("topic_partitions", ArraySerializer(topicPartitionSerializers[0])), ("timeout_ms", int32Serializer)] } electPreferredLeadersRequestDataSerializers: Dict[int, ClassSerializer[ElectPreferredLeadersRequestData]] = { version: ClassSerializer(ElectPreferredLeadersRequestData, schema) for version, schema in electPreferredLeadersRequestDataSchemas.items() } electPreferredLeadersRequestDataSerializers[-1] = electPreferredLeadersRequestDataSerializers[0]
[ 29113, 14468, 7804, 4242, 21017, 198, 2, 5231, 519, 877, 515, 8265, 13, 4222, 836, 470, 13096, 13, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 1303, 198, 2, 5312, 1864, 2393, 287, 8435, 62,...
3.476658
407
''' Copyright 2017 Dell Inc. or its subsidiaries. All Rights Reserved. This script tests arbitrary payload of the RackHD API 2.0 OS bootstrap workflows. The default case is running a minimum payload Windows OS install. Other Windows-type OS install cases can be specified by creating a payload file and specifiying it using the '-extra' argument. This test takes 30-45 minutes to run. Example payload file (installed in configuration dir): {"bootstrap-payload": {"name": "Graph.InstallWindowsServer", "options": {"defaults": {"version": "2012", "repo": "http://172.31.128.1:8080/repo/winpe", "smbRepo": "\\\\172.31.128.1\\windowsServer2012", "productkey": "XXXXX-XXXXX-XXXXX-XXXXX-XXXXX", "username": "rackhduser", "password": "RackHDRocks", "smbUser": "vagrant", "smbPassword": "vagrant"}}} } Example command line using external payload file: python run_tests.py -stack 4 -test tests/bootstrap/test_api20_windows_bootstrap.py -extra base_windows_2012_install.json RackHD Windows installation workflow requires special configuration of the RackHD server: - A customized WinPE environment installed on RackHD server as documented here: https://github.com/RackHD/on-tools/tree/master/winpe - Samba installed on the RackHD server and configured as documented here: http://rackhd.readthedocs.io/en/latest/rackhd/install_os.html?highlight=os%20install - Windows 2012 installation distro installed on RackHD server or equivalent NFS mount. - Windows 2012 activation key in the installation payload file. ''' import fit_path # NOQA: unused import from nose.plugins.attrib import attr import fit_common import flogging import random import json import time from nosedep import depends from datetime import datetime log = flogging.get_loggers() # sample default base payload PAYLOAD = {"name": "Graph.InstallWindowsServer", "options": {"defaults": {"version": "2012", "repo": "http://172.31.128.1:8080/repo/winpe", "smbRepo": "\\\\172.31.128.1\\windowsServer2012", "productkey": "XXXXX-XXXXX-XXXXX-XXXXX-XXXXX", "username": "rackhduser", "password": "RackHDRocks", "smbUser": "vagrant", "smbPassword": "vagrant"}}} # if an external payload file is specified, use that config = fit_common.fitcfg().get('bootstrap-payload', None) if config: PAYLOAD = config # function to return the value of a field from the workflow response # this routine polls a workflow task ID for completion # ------------------------ Tests ------------------------------------- if __name__ == '__main__': fit_common.unittest.main()
[ 7061, 6, 198, 15269, 2177, 23617, 3457, 13, 393, 663, 34943, 13, 1439, 6923, 33876, 13, 198, 198, 1212, 4226, 5254, 14977, 21437, 286, 262, 37927, 10227, 7824, 362, 13, 15, 7294, 6297, 26418, 670, 44041, 13, 198, 464, 4277, 1339, 318,...
2.399531
1,279
from flask import Flask, render_template from flask_ask import Ask, statement import random app = Flask(__name__) ask = Ask(app, '/') if __name__ == '__main__': app.run(debug=True)
[ 6738, 42903, 1330, 46947, 11, 8543, 62, 28243, 198, 6738, 42903, 62, 2093, 1330, 16981, 11, 2643, 198, 11748, 4738, 198, 198, 1324, 796, 46947, 7, 834, 3672, 834, 8, 198, 2093, 796, 16981, 7, 1324, 11, 31051, 11537, 198, 198, 361, 1...
2.952381
63
import torch import numpy as np import torch.nn as nn import torch.nn.functional as F import torchvision.models as models from model.laplacian import LapLoss device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # flow could have any channels. # https://github.com/coolbeam/OIFlow/blob/main/utils/tools.py def flow_smooth_delta(flow, if_second_order=False): dx, dy = gradient(flow) # dx2, dxdy = gradient(dx) # dydx, dy2 = gradient(dy) if if_second_order: dx2, dxdy = gradient(dx) dydx, dy2 = gradient(dy) smooth_loss = dx.abs().mean() + dy.abs().mean() + dx2.abs().mean() + dxdy.abs().mean() + dydx.abs().mean() + dy2.abs().mean() else: smooth_loss = dx.abs().mean() + dy.abs().mean() # smooth_loss = dx.abs().mean() + dy.abs().mean() # + dx2.abs().mean() + dxdy.abs().mean() + dydx.abs().mean() + dy2.abs().mean() # photo loss TODO return smooth_loss # flow should have 4 channels. # https://github.com/coolbeam/OIFlow/blob/main/utils/tools.py # weight_type='exp' seems to perform better than 'gauss'. # Dual teaching helps slightly. if __name__ == '__main__': img0 = torch.zeros(3, 3, 256, 256).float().to(device) img1 = torch.tensor(np.random.normal( 0, 1, (3, 3, 256, 256))).float().to(device) ternary_loss = Ternary() print(ternary_loss(img0, img1).shape)
[ 11748, 28034, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 198, 11748, 28034, 10178, 13, 27530, 355, 4981, 198, 6738, 2746, 13, 5031, 489, 330, 666, ...
2.476619
556
import numpy as np import pybullet as p import itertools from robot import Robot
[ 11748, 299, 32152, 355, 45941, 198, 11748, 12972, 15065, 1616, 355, 279, 198, 11748, 340, 861, 10141, 198, 198, 6738, 9379, 1330, 16071, 198, 220, 220, 220, 220, 220, 220, 220, 220, 198 ]
2.757576
33
# Copyright (c) 2006-2012 Mitch Garnaat http://garnaat.org/ # Copyright (c) 2012 Amazon.com, Inc. or its affiliates. # All Rights Reserved # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, dis- # tribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the fol- # lowing conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL- # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT # SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. # """ This module provides an interface to the Elastic Compute Cloud (EC2) load balancing service from AWS. """ from boto.connection import AWSQueryConnection from boto.ec2.instanceinfo import InstanceInfo from boto.ec2.elb.loadbalancer import LoadBalancer, LoadBalancerZones from boto.ec2.elb.instancestate import InstanceState from boto.ec2.elb.healthcheck import HealthCheck from boto.ec2.elb.listelement import ListElement from boto.regioninfo import RegionInfo, get_regions, load_regions import boto RegionData = load_regions().get('elasticloadbalancing', {}) def regions(): """ Get all available regions for the ELB service. :rtype: list :return: A list of :class:`boto.RegionInfo` instances """ return get_regions('elasticloadbalancing', connection_cls=ELBConnection) def connect_to_region(region_name, **kw_params): """ Given a valid region name, return a :class:`boto.ec2.elb.ELBConnection`. :param str region_name: The name of the region to connect to. :rtype: :class:`boto.ec2.ELBConnection` or ``None`` :return: A connection to the given region, or None if an invalid region name is given """ for region in regions(): if region.name == region_name: return region.connect(**kw_params) return None
[ 2, 15069, 357, 66, 8, 4793, 12, 6999, 20472, 402, 28610, 265, 2638, 1378, 70, 28610, 265, 13, 2398, 14, 198, 2, 15069, 357, 66, 8, 2321, 6186, 13, 785, 11, 3457, 13, 393, 663, 29116, 13, 198, 2, 1439, 6923, 33876, 198, 2, 198, ...
3.22987
770
''' Command line interface for the basis set exchange ''' import argparse import argcomplete from .. import version from .bse_handlers import bse_cli_handle_subcmd from .check import cli_check_normalize_args from .complete import (cli_case_insensitive_validator, cli_family_completer, cli_role_completer, cli_bsname_completer, cli_write_fmt_completer, cli_read_fmt_completer, cli_reffmt_completer)
[ 7061, 6, 198, 21575, 1627, 7071, 329, 262, 4308, 900, 5163, 198, 7061, 6, 198, 198, 11748, 1822, 29572, 198, 11748, 1822, 20751, 198, 6738, 11485, 1330, 2196, 198, 6738, 764, 65, 325, 62, 4993, 8116, 1330, 275, 325, 62, 44506, 62, 2...
2.397849
186
""" 3 16 3 5 7 11 13 """ import math left, right = map(int, input().split()) array = [True for i in range(right+1)] array[1] = 0 for i in range(2, int(math.sqrt(right)) + 1): if array[i] == True: j = 2 while i * j <= right: array[i * j] = False j += 1 for i in range(left, right+1): if array[i]: print(i)
[ 37811, 198, 220, 198, 18, 1467, 628, 220, 198, 18, 198, 20, 198, 22, 198, 1157, 198, 1485, 198, 37811, 198, 11748, 10688, 198, 198, 9464, 11, 826, 796, 3975, 7, 600, 11, 5128, 22446, 35312, 28955, 198, 18747, 796, 685, 17821, 329, ...
1.978495
186
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests the graph quantization script. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys import numpy as np from tensorflow.core.framework import graph_pb2 from tensorflow.python.client import session from tensorflow.python.framework import dtypes from tensorflow.python.framework import graph_util from tensorflow.python.framework import importer from tensorflow.python.framework import ops as ops_lib from tensorflow.python.platform import flags as flags_lib from tensorflow.python.platform import test from tensorflow.python.platform import tf_logging from tensorflow.tools.quantization import quantize_graph flags = flags_lib FLAGS = flags.FLAGS def test_mat_mul(m, n, k, a, b): """Tests a MatMul replacement.""" a_constant_name = "a_constant" b_constant_name = "b_constant" mat_mul_name = "mat_mul" float_graph_def = graph_pb2.GraphDef() a_constant = quantize_graph.create_constant_node( a_constant_name, value=a, dtype=dtypes.float32, shape=[m, k]) float_graph_def.node.extend([a_constant]) b_constant = quantize_graph.create_constant_node( b_constant_name, value=b, dtype=dtypes.float32, shape=[k, n]) float_graph_def.node.extend([b_constant]) mat_mul_node = quantize_graph.create_node("MatMul", mat_mul_name, [a_constant_name, b_constant_name]) quantize_graph.set_attr_dtype(mat_mul_node, "T", dtypes.float32) quantize_graph.set_attr_bool(mat_mul_node, "transpose_a", False) quantize_graph.set_attr_bool(mat_mul_node, "transpose_b", False) float_graph_def.node.extend([mat_mul_node]) test_graph(float_graph_def, {}, [mat_mul_name]) def test_conv(depth, image_width, image_height, image_batch_count, filter_size, filter_count, stride, padding, input_values, filter_values): """Tests a Conv replacement.""" input_constant_name = "input_constant" filter_constant_name = "filter_constant" conv_name = "conv" float_graph_def = graph_pb2.GraphDef() input_constant = quantize_graph.create_constant_node( input_constant_name, value=input_values, dtype=dtypes.float32, shape=[image_batch_count, image_height, image_width, depth]) float_graph_def.node.extend([input_constant]) filter_constant = quantize_graph.create_constant_node( filter_constant_name, value=filter_values, dtype=dtypes.float32, shape=[filter_size, filter_size, depth, filter_count]) float_graph_def.node.extend([filter_constant]) conv_node = quantize_graph.create_node( "Conv2D", conv_name, [input_constant_name, filter_constant_name]) quantize_graph.set_attr_dtype(conv_node, "T", dtypes.float32) quantize_graph.set_attr_int_list(conv_node, "strides", [1, stride, stride, 1]) quantize_graph.set_attr_string(conv_node, "padding", padding) float_graph_def.node.extend([conv_node]) test_graph(float_graph_def, {}, [conv_name]) def are_tensors_near(a, b, tolerance): """Tests whether two tensors are nearly identical. This is a specialized comparison function designed to help debug problems with quantization. It prints out information about the differences between tensors on failure, paying special attention to possible biases by looking at the mean and absolute average errors. Args: a: First comparison tensor. b: Second comparison tensor. tolerance: Float value indicating how large an error between values is ok. Returns: Boolean indicating whether the two inputs were close enough. """ flat_a = a.flatten() flat_b = b.flatten() if len(flat_a) != len(flat_b): tf_logging.info("Tensors are different sizes: " + str(len(flat_a)) + " vs " + str(len(flat_b))) return False value_count = len(flat_a) how_many_different = 0 total_difference = 0 total_abs_difference = 0 for index in range(value_count): a_value = flat_a[index] b_value = flat_b[index] difference = a_value - b_value total_difference += difference total_abs_difference += abs(difference) if abs(difference) > tolerance: how_many_different += 1 mean_difference = total_difference / value_count mean_abs_difference = total_abs_difference / value_count proportion_different = (how_many_different * 1.0) / value_count if how_many_different == 0: return True else: tf_logging.info("Tensors have {0} different values ({1}%), with mean" " difference {2} and mean absolute difference {3}".format( how_many_different, proportion_different * 100, mean_difference, mean_abs_difference)) return False def test_graph(float_graph_def, input_map, output_names, log_graph=False): """Runs the float graph through the rewriter and tests the results.""" float_results = run_graph_def( float_graph_def, input_map, [output_name + ":0" for output_name in output_names]) # TODO(petewarden): round test is currently failing because there is no # RoundToSteps op available. # round_rewriter = quantize_graph.GraphRewriter(float_graph_def, "round") # round_graph_def = round_rewriter.rewrite(output_name) # round_results = run_graph_def(round_graph_def, input_map, # [output_name + ":0"]) # assert are_tensors_near(expected, round_results[0], 1.0) # # TODO(petewarden): Add test for "quantize" mode. eightbit_rewriter = quantize_graph.GraphRewriter( float_graph_def, "eightbit", quantized_input_range=None) eightbit_graph_def = eightbit_rewriter.rewrite(output_names) eightbit_results = run_graph_def( eightbit_graph_def, input_map, [output_name + ":0" for output_name in output_names]) for expected, result in zip(float_results, eightbit_results): assert are_tensors_near(expected, result, 1.0) if log_graph: tf_logging.info("8bit:\n%s", str(eightbit_graph_def)) # Test the weights_rounded mode. This uses the default bit_depth. weights_rounded_rewriter = quantize_graph.GraphRewriter( float_graph_def, "weights_rounded", quantized_input_range=None) weights_rounded_graph_def = weights_rounded_rewriter.rewrite(output_names) weights_rounded_results = run_graph_def( weights_rounded_graph_def, input_map, [output_name + ":0" for output_name in output_names]) for expected, result in zip(float_results, weights_rounded_results): assert are_tensors_near(expected, result, 1.0) if __name__ == "__main__": test.main()
[ 2, 15069, 1853, 383, 309, 22854, 37535, 46665, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, ...
2.799303
2,581
# -*- coding: utf-8 -*- # Generated by Django 1.11.10 on 2018-04-26 09:14 import colorfield.fields from django.db import migrations, models import django.db.models.deletion import giscube.utils
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 352, 13, 1157, 13, 940, 319, 2864, 12, 3023, 12, 2075, 7769, 25, 1415, 628, 198, 11748, 3124, 3245, 13, 25747, 198, 6738, 42625, 14208, 13, ...
2.774648
71
backgroundurl = "https://storage.needpix.com/rsynced_images/colored-background.jpg" # <- Need to be a Image URL!!! lang = "en" # <- language code displayset = True # <- Display the Set of the Item raritytext = True # <- Display the Rarity of the Item typeconfig = { "BannerToken": True, "AthenaBackpack": True, "AthenaPetCarrier": True, "AthenaPet": True, "AthenaPickaxe": True, "AthenaCharacter": True, "AthenaSkyDiveContrail": True, "AthenaGlider": True, "AthenaDance": True, "AthenaEmoji": True, "AthenaLoadingScreen": True, "AthenaMusicPack": True, "AthenaSpray": True, "AthenaToy": True, "AthenaBattleBus": True, "AthenaItemWrap": True } interval = 5 # <- Time (in seconds) until the bot checks for leaks again | Recommend: 7 watermark = "" # <- Leave it empty if you dont want one watermarksize = 25 # <- Size of the Watermark
[ 25249, 6371, 796, 366, 5450, 1378, 35350, 13, 31227, 79, 844, 13, 785, 14, 81, 28869, 771, 62, 17566, 14, 25717, 12, 25249, 13, 9479, 1, 220, 1303, 24293, 10664, 284, 307, 257, 7412, 10289, 10185, 198, 198, 17204, 796, 366, 268, 1, ...
2.585227
352
import unittest import settings from healthvaultlib.helpers.connection import Connection
[ 11748, 555, 715, 395, 198, 198, 11748, 6460, 198, 6738, 1535, 85, 1721, 8019, 13, 16794, 364, 13, 38659, 1330, 26923, 198 ]
4.090909
22
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-06-09 03:01 from __future__ import unicode_literals from django.db import migrations, models
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 352, 13, 940, 13, 21, 319, 2177, 12, 3312, 12, 2931, 7643, 25, 486, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 1...
2.736842
57
''' multi-threading (python3 version) https://docs.python.org/3/library/threading.html ''' from time import clock import threading THREADS=2 lock = threading.Lock() A = 0 B = 0 C = 0 main()
[ 7061, 6, 198, 41684, 12, 16663, 278, 357, 29412, 18, 2196, 8, 198, 5450, 1378, 31628, 13, 29412, 13, 2398, 14, 18, 14, 32016, 14, 16663, 278, 13, 6494, 198, 7061, 6, 198, 198, 6738, 640, 1330, 8801, 198, 11748, 4704, 278, 198, 198...
2.621622
74
import numpy as np
[ 11748, 299, 32152, 355, 45941, 198 ]
3.166667
6
""" Zoe Game Engine Core Implementation =================================== Requirements ------------ [pygame](http://www.pygame.org/) """ # core packages # third-party packages import pygame # local package import layer __version__ = '0.0.0' #=============================================================================
[ 37811, 198, 57, 2577, 3776, 7117, 7231, 46333, 198, 10052, 18604, 198, 198, 42249, 198, 10541, 198, 198, 58, 9078, 6057, 16151, 4023, 1378, 2503, 13, 9078, 6057, 13, 2398, 34729, 198, 37811, 198, 198, 2, 4755, 10392, 198, 198, 2, 2368...
4.311688
77
# Generated by Django 3.0.6 on 2020-11-15 09:05 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 15, 13, 21, 319, 12131, 12, 1157, 12, 1314, 7769, 25, 2713, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.84375
32
from django.urls import path, re_path from django.views.generic.base import TemplateView from .views import dashboard_cost, dashboard_energy, MotorDataListView app_name = 'dashboard' urlpatterns = [ path('', MotorDataListView.as_view(), name='dashboard_custom'), #path('', dashboard_custom, name='dashboard_custom'), path('energy', dashboard_energy, name='dashboard_energy'), path('cost', dashboard_cost, name='dashboard_cost'), ]
[ 198, 220, 198, 6738, 42625, 14208, 13, 6371, 82, 1330, 3108, 11, 302, 62, 6978, 198, 6738, 42625, 14208, 13, 33571, 13, 41357, 13, 8692, 1330, 37350, 7680, 198, 6738, 764, 33571, 1330, 30415, 62, 15805, 11, 30415, 62, 22554, 11, 220, ...
3.116438
146
hrs = input("Enter Hours:") rate = input("Enter rate:") pay = float(hrs) * float(rate) print("Pay: " +str(pay))
[ 71, 3808, 796, 5128, 7203, 17469, 19347, 25, 4943, 198, 4873, 796, 5128, 7203, 17469, 2494, 25, 4943, 198, 15577, 796, 12178, 7, 71, 3808, 8, 1635, 12178, 7, 4873, 8, 198, 4798, 7203, 19197, 25, 366, 1343, 2536, 7, 15577, 4008 ]
2.642857
42
# # This file is part of LiteX-Boards. # # Copyright (c) 2017-2019 Florent Kermarrec <florent@enjoy-digital.fr> # SPDX-License-Identifier: BSD-2-Clause from litex.build.generic_platform import * from litex.build.xilinx import XilinxPlatform, VivadoProgrammer # IOs ---------------------------------------------------------------------------------------------- _io = [ # Clk / Rst ("clk125", 0, Subsignal("p", Pins("G10"), IOStandard("LVDS")), Subsignal("n", Pins("F10"), IOStandard("LVDS")) ), ("clk300", 0, Subsignal("p", Pins("AK17"), IOStandard("DIFF_SSTL12")), Subsignal("n", Pins("AK16"), IOStandard("DIFF_SSTL12")) ), ("cpu_reset", 0, Pins("AN8"), IOStandard("LVCMOS18")), # Leds ("user_led", 0, Pins("AP8"), IOStandard("LVCMOS18")), ("user_led", 1, Pins("H23"), IOStandard("LVCMOS18")), ("user_led", 2, Pins("P20"), IOStandard("LVCMOS18")), ("user_led", 3, Pins("P21"), IOStandard("LVCMOS18")), ("user_led", 4, Pins("N22"), IOStandard("LVCMOS18")), ("user_led", 5, Pins("M22"), IOStandard("LVCMOS18")), ("user_led", 6, Pins("R23"), IOStandard("LVCMOS18")), ("user_led", 7, Pins("P23"), IOStandard("LVCMOS18")), # Buttons ("user_btn_c", 0, Pins("AE10"), IOStandard("LVCMOS18")), ("user_btn_n", 0, Pins("AD10"), IOStandard("LVCMOS18")), ("user_btn_s", 0, Pins("AF8"), IOStandard("LVCMOS18")), ("user_btn_w", 0, Pins("AF9"), IOStandard("LVCMOS18")), ("user_btn_e", 0, Pins("AE8"), IOStandard("LVCMOS18")), # Switches ("user_dip_btn", 0, Pins("AN16"), IOStandard("LVCMOS12")), ("user_dip_btn", 1, Pins("AN19"), IOStandard("LVCMOS12")), ("user_dip_btn", 2, Pins("AP18"), IOStandard("LVCMOS12")), ("user_dip_btn", 3, Pins("AN14"), IOStandard("LVCMOS12")), # SMA ("user_sma_clock", 0, Subsignal("p", Pins("D23"), IOStandard("LVDS")), Subsignal("n", Pins("C23"), IOStandard("LVDS")) ), ("user_sma_clock_p", 0, Pins("D23"), IOStandard("LVCMOS18")), ("user_sma_clock_n", 0, Pins("C23"), IOStandard("LVCMOS18")), ("user_sma_gpio", 0, Subsignal("p", Pins("H27"), IOStandard("LVDS")), Subsignal("n", Pins("G27"), IOStandard("LVDS")) ), ("user_sma_gpio_p", 0, Pins("H27"), IOStandard("LVCMOS18")), ("user_sma_gpio_n", 0, Pins("G27"), IOStandard("LVCMOS18")), # I2C ("i2c", 0, Subsignal("scl", Pins("J24")), Subsignal("sda", Pins("J25")), IOStandard("LVCMOS18") ), # Serial ("serial", 0, Subsignal("cts", Pins("L23")), Subsignal("rts", Pins("K27")), Subsignal("tx", Pins("K26")), Subsignal("rx", Pins("G25")), IOStandard("LVCMOS18") ), # SPIFlash ("spiflash", 0, # clock needs to be accessed through primitive Subsignal("cs_n", Pins("U7")), Subsignal("dq", Pins("AC7 AB7 AA7 Y7")), IOStandard("LVCMOS18") ), ("spiflash", 1, # clock needs to be accessed through primitive Subsignal("cs_n", Pins("G26")), Subsignal("dq", Pins("M20 L20 R21 R22")), IOStandard("LVCMOS18") ), # SDCard ("spisdcard", 0, Subsignal("clk", Pins("AL10")), Subsignal("cs_n", Pins("AH8")), Subsignal("mosi", Pins("AD9"), Misc("PULLUP")), Subsignal("miso", Pins("AP9"), Misc("PULLUP")), Misc("SLEW=FAST"), IOStandard("LVCMOS18") ), ("sdcard", 0, Subsignal("clk", Pins("AL10")), Subsignal("cmd", Pins("AD9"), Misc("PULLUP True")), Subsignal("data", Pins("AP9 AN9 AH9 AH8"), Misc("PULLUP True")), Misc("SLEW=FAST"), IOStandard("LVCMOS18") ), # Rotary Encoder ("rotary", 0, Subsignal("a", Pins("Y21")), Subsignal("b", Pins("AD26")), Subsignal("push", Pins("AF28")), IOStandard("LVCMOS18") ), # HDMI ("hdmi", 0, Subsignal("d", Pins( "AK11 AP11 AP13 AN13 AN11 AM11 AN12 AM12", "AL12 AK12 AL13 AK13 AD11 AH12 AG12 AJ11", "AG10 AK8")), Subsignal("de", Pins("AE11")), Subsignal("clk", Pins("AF13")), Subsignal("vsync", Pins("AH13")), Subsignal("hsync", Pins("AE13")), Subsignal("spdif", Pins("AE12")), Subsignal("spdif_out", Pins("AF12")), IOStandard("LVCMOS18") ), # DDR4 SDRAM ("ddram", 0, Subsignal("a", Pins( "AE17 AH17 AE18 AJ15 AG16 AL17 AK18 AG17", "AF18 AH19 AF15 AD19 AJ14 AG19"), IOStandard("SSTL12_DCI")), Subsignal("ba", Pins("AF17 AL15"), IOStandard("SSTL12_DCI")), Subsignal("bg", Pins("AG15"), IOStandard("SSTL12_DCI")), Subsignal("ras_n", Pins("AF14"), IOStandard("SSTL12_DCI")), # A16 Subsignal("cas_n", Pins("AG14"), IOStandard("SSTL12_DCI")), # A15 Subsignal("we_n", Pins("AD16"), IOStandard("SSTL12_DCI")), # A14 Subsignal("cs_n", Pins("AL19"), IOStandard("SSTL12_DCI")), Subsignal("act_n", Pins("AH14"), IOStandard("SSTL12_DCI")), #Subsignal("ten", Pins("AH16"), IOStandard("SSTL12_DCI")), #Subsignal("alert_n", Pins("AJ16"), IOStandard("SSTL12_DCI")), #Subsignal("par", Pins("AD18"), IOStandard("SSTL12_DCI")), Subsignal("dm", Pins("AD21 AE25 AJ21 AM21 AH26 AN26 AJ29 AL32"), IOStandard("POD12_DCI")), Subsignal("dq", Pins( "AE23 AG20 AF22 AF20 AE22 AD20 AG22 AE20", "AJ24 AG24 AJ23 AF23 AH23 AF24 AH22 AG25", "AL22 AL25 AM20 AK23 AK22 AL24 AL20 AL23", "AM24 AN23 AN24 AP23 AP25 AN22 AP24 AM22", "AH28 AK26 AK28 AM27 AJ28 AH27 AK27 AM26", "AL30 AP29 AM30 AN28 AL29 AP28 AM29 AN27", "AH31 AH32 AJ34 AK31 AJ31 AJ30 AH34 AK32", "AN33 AP33 AM34 AP31 AM32 AN31 AL34 AN32"), IOStandard("POD12_DCI"), Misc("PRE_EMPHASIS=RDRV_240"), Misc("EQUALIZATION=EQ_LEVEL2")), Subsignal("dqs_p", Pins("AG21 AH24 AJ20 AP20 AL27 AN29 AH33 AN34"), IOStandard("DIFF_POD12_DCI"), Misc("PRE_EMPHASIS=RDRV_240"), Misc("EQUALIZATION=EQ_LEVEL2")), Subsignal("dqs_n", Pins("AH21 AJ25 AK20 AP21 AL28 AP30 AJ33 AP34"), IOStandard("DIFF_POD12_DCI"), Misc("PRE_EMPHASIS=RDRV_240"), Misc("EQUALIZATION=EQ_LEVEL2")), Subsignal("clk_p", Pins("AE16"), IOStandard("DIFF_SSTL12_DCI")), Subsignal("clk_n", Pins("AE15"), IOStandard("DIFF_SSTL12_DCI")), Subsignal("cke", Pins("AD15"), IOStandard("SSTL12_DCI")), Subsignal("odt", Pins("AJ18"), IOStandard("SSTL12_DCI")), Subsignal("reset_n", Pins("AL18"), IOStandard("LVCMOS12")), Misc("SLEW=FAST"), ), # PCIe ("pcie_x1", 0, Subsignal("rst_n", Pins("K22"), IOStandard("LVCMOS18")), Subsignal("clk_p", Pins("AB6")), Subsignal("clk_n", Pins("AB5")), Subsignal("rx_p", Pins("AB2")), Subsignal("rx_n", Pins("AB1")), Subsignal("tx_p", Pins("AC4")), Subsignal("tx_n", Pins("AC3")) ), ("pcie_x2", 0, Subsignal("rst_n", Pins("K22"), IOStandard("LVCMOS18")), Subsignal("clk_p", Pins("AB6")), Subsignal("clk_n", Pins("AB5")), Subsignal("rx_p", Pins("AB2 AD2")), Subsignal("rx_n", Pins("AB1 AD1")), Subsignal("tx_p", Pins("AC4 AE4")), Subsignal("tx_n", Pins("AC3 AE3")) ), ("pcie_x4", 0, Subsignal("rst_n", Pins("K22"), IOStandard("LVCMOS18")), Subsignal("clk_p", Pins("AB6")), Subsignal("clk_n", Pins("AB5")), Subsignal("rx_p", Pins("AB2 AD2 AF2 AH2")), Subsignal("rx_n", Pins("AB1 AD1 AF1 AH1")), Subsignal("tx_p", Pins("AC4 AE4 AG4 AH6")), Subsignal("tx_n", Pins("AC3 AE3 AG3 AH5")) ), ("pcie_x8", 0, Subsignal("rst_n", Pins("K22"), IOStandard("LVCMOS18")), Subsignal("clk_p", Pins("AB6")), Subsignal("clk_n", Pins("AB5")), Subsignal("rx_p", Pins("AB2 AD2 AF2 AH2 AJ4 AK2 AM2 AP2")), Subsignal("rx_n", Pins("AB1 AD1 AF1 AH1 AJ3 AK1 AM1 AP1")), Subsignal("tx_p", Pins("AC4 AE4 AG4 AH6 AK6 AL4 AM6 AN4")), Subsignal("tx_n", Pins("AC3 AE3 AG3 AH5 AK5 AL3 AM5 AN3")) ), # SGMII Clk ("sgmii_clock", 0, Subsignal("p", Pins("P26"), IOStandard("LVDS_25")), Subsignal("n", Pins("N26"), IOStandard("LVDS_25")) ), # SI570 ("si570_refclk", 0, Subsignal("p", Pins("P6")), Subsignal("n", Pins("P5")) ), # SMA ("user_sma_mgt_refclk", 0, Subsignal("p", Pins("V6")), Subsignal("n", Pins("V5")) ), ("user_sma_mgt_tx", 0, Subsignal("p", Pins("R4")), Subsignal("n", Pins("R3")) ), ("user_sma_mgt_rx", 0, Subsignal("p", Pins("P2")), Subsignal("n", Pins("P1")) ), # SFP ("sfp", 0, Subsignal("txp", Pins("U4")), Subsignal("txn", Pins("U3")), Subsignal("rxp", Pins("T2")), Subsignal("rxn", Pins("T1")) ), ("sfp_tx", 0, Subsignal("p", Pins("U4")), Subsignal("n", Pins("U3")), ), ("sfp_rx", 0, Subsignal("p", Pins("T2")), Subsignal("n", Pins("T1")), ), ("sfp_tx_disable_n", 0, Pins("AL8"), IOStandard("LVCMOS18")), ("sfp", 1, Subsignal("txp", Pins("W4")), Subsignal("txn", Pins("W3")), Subsignal("rxp", Pins("V2")), Subsignal("rxn", Pins("V1")) ), ("sfp_tx", 1, Subsignal("p", Pins("W4")), Subsignal("n", Pins("W3")), ), ("sfp_rx", 1, Subsignal("p", Pins("V2")), Subsignal("n", Pins("V1")), ), ("sfp_tx_disable_n", 1, Pins("D28"), IOStandard("LVCMOS18")), ] # Connectors --------------------------------------------------------------------------------------- _connectors = [ ("HPC", { "DP0_C2M_P" : "F6", "DP0_C2M_N" : "F5", "DP0_M2C_P" : "E4", "DP0_M2C_N" : "E3", "DP1_C2M_P" : "D6", "DP1_C2M_N" : "D5", "DP1_M2C_P" : "D2", "DP1_M2C_N" : "D1", "DP2_C2M_P" : "C4", "DP2_C2M_N" : "C3", "DP2_M2C_P" : "B2", "DP2_M2C_N" : "B1", "DP3_C2M_P" : "B6", "DP3_C2M_N" : "B5", "DP3_M2C_P" : "A4", "DP3_M2C_N" : "A3", "DP4_C2M_P" : "N4", "DP4_C2M_N" : "N3", "DP4_M2C_P" : "M2", "DP4_M2C_N" : "M1", "DP5_C2M_P" : "J4", "DP5_C2M_N" : "J3", "DP5_M2C_P" : "H2", "DP5_M2C_N" : "H1", "DP6_C2M_P" : "L4", "DP6_C2M_N" : "L3", "DP6_M2C_P" : "K2", "DP6_M2C_N" : "K1", "DP7_C2M_P" : "G4", "DP7_C2M_N" : "G3", "DP7_M2C_P" : "F2", "DP7_M2C_N" : "F1", "LA06_P" : "D13", "LA06_N" : "C13", "LA10_P" : "L8", "LA10_N" : "K8", "LA14_P" : "B10", "LA14_N" : "A10", "LA18_CC_P" : "E22", "LA18_CC_N" : "E23", "LA27_P" : "H21", "LA27_N" : "G21", "HA01_CC_P" : "E16", "HA01_CC_N" : "D16", "HA05_P" : "J15", "HA05_N" : "J14", "HA09_P" : "F18", "HA09_N" : "F17", "HA13_P" : "B14", "HA13_N" : "A14", "HA16_P" : "A19", "HA16_N" : "A18", "HA20_P" : "C19", "HA20_N" : "B19", "CLK1_M2C_P" : "E25", "CLK1_M2C_N" : "D25", "LA00_CC_P" : "H11", "LA00_CC_N" : "G11", "LA03_P" : "A13", "LA03_N" : "A12", "LA08_P" : "J8", "LA08_N" : "H8", "LA12_P" : "E10", "LA12_N" : "D10", "LA16_P" : "B9", "LA16_N" : "A9", "LA20_P" : "B24", "LA20_N" : "A24", "LA22_P" : "G24", "LA22_N" : "F25", "LA25_P" : "D20", "LA25_N" : "D21", "LA29_P" : "B20", "LA29_N" : "A20", "LA31_P" : "B25", "LA31_N" : "A25", "LA33_P" : "A27", "LA33_N" : "A28", "HA03_P" : "G15", "HA03_N" : "G14", "HA07_P" : "L19", "HA07_N" : "L18", "HA11_P" : "J19", "HA11_N" : "J18", "HA14_P" : "F15", "HA14_N" : "F14", "HA18_P" : "B17", "HA18_N" : "B16", "HA22_P" : "C18", "HA22_N" : "C17", "GBTCLK1_M2C_P" : "H6", "GBTCLK1_M2C_N" : "H5", "GBTCLK0_M2C_P" : "K6", "GBTCLK0_M2C_N" : "K5", "LA01_CC_P" : "G9", "LA01_CC_N" : "F9", "LA05_P" : "L13", "LA05_N" : "K13", "LA09_P" : "J9", "LA09_N" : "H9", "LA13_P" : "D9", "LA13_N" : "C9", "LA17_CC_P" : "D24", "LA17_CC_N" : "C24", "LA23_P" : "G22", "LA23_N" : "F22", "LA26_P" : "G20", "LA26_N" : "F20", "PG_M2C" : "L27", "HA00_CC_P" : "G17", "HA00_CC_N" : "G16", "HA04_P" : "G19", "HA04_N" : "F19", "HA08_P" : "K18", "HA08_N" : "K17", "HA12_P" : "K16", "HA12_N" : "J16", "HA15_P" : "D14", "HA15_N" : "C14", "HA19_P" : "D19", "HA19_N" : "D18", "PRSNT_M2C_B" : "H24", "CLK0_M2C_P" : "H12", "CLK0_M2C_N" : "G12", "LA02_P" : "K10", "LA02_N" : "J10", "LA04_P" : "L12", "LA04_N" : "K12", "LA07_P" : "F8", "LA07_N" : "E8", "LA11_P" : "K11", "LA11_N" : "J11", "LA15_P" : "D8", "LA15_N" : "C8", "LA19_P" : "C21", "LA19_N" : "C22", "LA21_P" : "F23", "LA21_N" : "F24", "LA24_P" : "E20", "LA24_N" : "E21", "LA28_P" : "B21", "LA28_N" : "B22", "LA30_P" : "C26", "LA30_N" : "B26", "LA32_P" : "E26", "LA32_N" : "D26", "HA02_P" : "H19", "HA02_N" : "H18", "HA06_P" : "L15", "HA06_N" : "K15", "HA10_P" : "H17", "HA10_N" : "H16", "HA17_CC_P" : "E18", "HA17_CC_N" : "E17", "HA21_P" : "E15", "HA21_N" : "D15", "HA23_P" : "B15", "HA23_N" : "A15", } ), ("LPC", { "GBTCLK0_M2C_P" : "AA24", "GBTCLK0_M2C_N" : "AA25", "LA01_CC_P" : "W25", "LA01_CC_N" : "Y25", "LA05_P" : "V27", "LA05_N" : "V28", "LA09_P" : "V26", "LA09_N" : "W26", "LA13_P" : "AA20", "LA13_N" : "AB20", "LA17_CC_P" : "AA32", "LA17_CC_N" : "AB32", "LA23_P" : "AD30", "LA23_N" : "AD31", "LA26_P" : "AF33", "LA26_N" : "AG34", "CLK0_M2C_P" : "AA24", "CLK0_M2C_N" : "AA25", "LA02_P" : "AA22", "LA02_N" : "AB22", "LA04_P" : "U26", "LA04_N" : "U27", "LA07_P" : "V22", "LA07_N" : "V23", "LA11_P" : "V21", "LA11_N" : "W21", "LA15_P" : "AB25", "LA15_N" : "AB26", "LA19_P" : "AA29", "LA19_N" : "AB29", "LA21_P" : "AC33", "LA21_N" : "AD33", "LA24_P" : "AE32", "LA24_N" : "AF32", "LA28_P" : "V31", "LA28_N" : "W31", "LA30_P" : "Y31", "LA30_N" : "Y32", "LA32_P" : "W30", "LA32_N" : "Y30", "LA06_P" : "V29", "LA06_N" : "W29", "LA10_P" : "T22", "LA10_N" : "T23", "LA14_P" : "U21", "LA14_N" : "U22", "LA18_CC_P" : "AB30", "LA18_CC_N" : "AB31", "LA27_P" : "AG31", "LA27_N" : "AG32", "CLK1_M2C_P" : "AC31", "CLK1_M2C_N" : "AC32", "LA00_CC_P" : "W23", "LA00_CC_N" : "W24", "LA03_P" : "W28", "LA03_N" : "Y28", "LA08_P" : "U24", "LA08_N" : "U25", "LA12_P" : "AC22", "LA12_N" : "AC23", "LA16_P" : "AB21", "LA16_N" : "AC21", "LA20_P" : "AA34", "LA20_N" : "AB34", "LA22_P" : "AC34", "LA22_N" : "AD34", "LA25_P" : "AE33", "LA25_N" : "AF34", "LA29_P" : "U34", "LA29_N" : "V34", "LA31_P" : "V33", "LA31_N" : "W34", "LA33_P" : "W33", "LA33_N" : "Y33", } ), ("pmod0", "AK25 AN21 AH18 AM19 AE26 AF25 AE21 AM17"), ("pmod1", "AL14 AM14 AP16 AP15 AM16 AM15 AN18 AN17"), ] # Platform -----------------------------------------------------------------------------------------
[ 2, 198, 2, 770, 2393, 318, 636, 286, 27395, 55, 12, 16635, 1371, 13, 198, 2, 198, 2, 15069, 357, 66, 8, 2177, 12, 23344, 23347, 429, 17337, 3876, 8344, 1279, 2704, 382, 429, 31, 268, 2633, 12, 34725, 13, 8310, 29, 198, 2, 30628,...
1.56743
11,434
#!/usr/bin/env python # coding: utf-8 # In[1]: import numpy as np import math # In[2]: fileObj = open('../data/advent_of_code_input_day_three.txt', "r") #opens the file in read mode. items = fileObj. read(). splitlines() #puts the file into an array. # In[3]: #print (items) holding = [] for i, line in enumerate(items): result = split(line) holding.append(result) holding = np.array(holding) holding[holding == '.'] = 0 holding[holding == '#'] = 1 holding = holding.astype(int) print (holding) # In[7]: down1_right3 = dup_and_count(3,1,holding) down1_right1 = dup_and_count(1,1,holding) down1_right5 = dup_and_count(5,1,holding) down1_right7 = dup_and_count(7,1,holding) down2_right1 = dup_and_count(1,2,holding) results = np.array([down1_right3, down1_right1, down1_right5, down1_right7, down2_right1], dtype=np.int64) print(results) product = np.prod(results) print (product) # In[ ]:
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 2, 554, 58, 16, 5974, 628, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 10688, 628, 198, 2, 554, 58, 17, 5974, 628, 198, 198, 7753, 4...
2.470588
374
import os import traceback if __name__ == '__main__': obj = InputHandler() print(obj.listFiles())
[ 11748, 28686, 198, 11748, 12854, 1891, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 26181, 796, 23412, 25060, 3419, 198, 220, 220, 220, 3601, 7, 26801, 13, 4868, 25876, 28955 ]
2.815789
38
#!/usr/bin/python import os import sys SITENAME = os.environ.get("BEPASTY_SITENAME", None) if SITENAME is None: print("\n\nEnvironment variable BEPASTY_SITENAME must be set.") sys.exit(1) SECRET_KEY = os.environ.get("BEPASTY_SECRET_KEY", None) if SECRET_KEY is None: print("\n\nEnvironment variable BEPASTY_SECRET_KEY must be set.") sys.exit(1) APP_BASE_PATH = os.environ.get("BEPASTY_APP_BASE_PATH", None) STORAGE_FILESYSTEM_DIRECTORY = os.environ.get( "BEPASTY_STORAGE_FILESYSTEM_DIRECTORY", "/app/data", ) DEFAULT_PERMISSIONS = os.environ.get("BEPASTY_DEFAULT_PERMISSIONS", "create,read") PERMISSIONS = {} admin_secret = os.environ.get("BEPASTY_ADMIN_SECRET", None) if admin_secret is not None: PERMISSIONS.update({admin_secret: "admin,list,create,modify,read,delete"}) try: max_allowed_file_size = os.environ.get("BEPASTY_MAX_ALLOWED_FILE_SIZE", 5000000000) MAX_ALLOWED_FILE_SIZE = int(max_allowed_file_size) except ValueError as err: print("\n\nInvalid BEPASTY_MAX_ALLOWED_FILE_SIZE: %s", str(err)) sys.exit(1) try: max_body_size = os.environ.get("BEPASTY_MAX_BODY_SIZE", 1040384) MAX_BODY_SIZE = int(max_body_size) except ValueError as err: print("\n\nInvalid BEPASTY_MAX_BODY_SIZE: %s", str(err)) sys.exit(1)
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 198, 11748, 28686, 198, 11748, 25064, 198, 198, 50, 2043, 1677, 10067, 796, 28686, 13, 268, 2268, 13, 1136, 7203, 33, 8905, 1921, 9936, 62, 50, 2043, 1677, 10067, 1600, 6045, 8, 198, 361, 3...
2.275311
563
from io import StringIO import re import tokenize import os from collections import deque, ChainMap from functools import lru_cache from enum import Enum import pysh from pysh.path import PathWrapper, Path from typing import List, Callable, Iterator, Tuple, NamedTuple, Deque, Union, Any TBangTransformer = Callable[ [List[str]], Iterator[str]] # runtime symbols __all__ = ['BangExpr', 'BangOp', 'BangSeq', 'BangGlob', 'BangEnv', 'BangBang'] TBangLexerToken = Tuple[str, str, Tuple[int,int]] class BangEnv: __slots__ = ('name',) def parse_bangexpr(code: str) -> str: as_str = lambda s: "'{}'".format(s.replace("\\", "\\\\").replace("'", "\\'")) lexer = BangLexer().scan(code) seq = [] exprs = [] while True: tkn = next(lexer, None) if tkn and tkn.type != BangTokenType.OP: if tkn.type in (BangTokenType.LOCAL, BangTokenType.EXPR): seq.append(tkn.value) elif tkn.type == BangTokenType.ENV: seq.append('pysh.BangEnv({})'.format(as_str(tkn.value))) elif tkn.type == BangTokenType.OPAQUE: seq.append('{}'.format(as_str(tkn.value))) elif tkn.type == BangTokenType.GLOB: seq.append('pysh.BangGlob({})'.format(as_str(tkn.value))) else: assert False, 'Unexpected token {}'.format(tkn.type) continue if seq: if len(seq) > 1: exprs.append('pysh.BangSeq({})'.format(', '.join(seq))) else: exprs.append(seq[0]) seq = [] if not tkn: break assert tkn.type == BangTokenType.OP if tkn.value == ' ': continue exprs.append('pysh.BangOp("{}")'.format(tkn.value)) # We need to provide locals/globals so we can resolve commands to variables return 'pysh.BangExpr({}, locals=locals(), globals=globals())'.format(', '.join(exprs)) def transform(code: StringIO, transformer: TBangTransformer) -> Iterator[str]: """ Scans python code to transform bang expressions. Given some python code it will extract bang expressions and process them with a callback that can report back the transformation. Returns a generator that allows to consume the transformed code line by line. """ tokens = tokenize.generate_tokens(code.readline) bangexpr = [] # type: List[str] bangcont = False prebang = None ptkn = None indent = 0 bang_indent = -100 last_bang_line = -100 for ctkn in tokens: if ctkn.type == tokenize.INDENT: indent += 1 if last_bang_line + 1 == ctkn.start[0]: bang_indent = indent elif ctkn.type == tokenize.DEDENT: indent -= 1 if bang_indent > indent: bang_indent = -100 # due to continuations we can't rely on NEWLINE tokens, instead we have # use the lexical information to detect when we're on a new line #TODO: Support indent/dedent for multiline if ptkn and ctkn.start[0] > ptkn.start[0]: if bangcont or bang_indent == indent: if ctkn.type is tokenize.ENDMARKER: raise SyntaxError('BangExpr continuation at program end') line = ctkn.line.rstrip('\r\n') bangexpr.append(line) bangcont = line.endswith('\\') last_bang_line = ctkn.start[0] elif bangexpr: lines = list(transformer(bangexpr)) assert len(lines) <= len(bangexpr) if lines and prebang: lines[0] = prebang + lines[0] yield from lines bangexpr = [] last_bang_line = ptkn.start[0] else: yield ptkn.line ptkn = ctkn if bangexpr: continue if ctkn.string == '!': col = ctkn.start[1] prebang = ctkn.line[0:col] line = ctkn.line[col+1:].lstrip(' \t').rstrip('\r\n') bangexpr.append(line.rstrip('\\')) bangcont = line.endswith('\\') last_bang_line = ctkn.start[0] assert not bangexpr, bangexpr def transformer(lines: List[str]) -> Iterator[str]: if lines[0].startswith('!'): #TODO: Detect $ident to expose them on env when evaluated lines[0] = lines[0][1:] code = '\n'.join(lines) code = code.strip().replace("'", "\\'").replace("\\", "\\\\") code = "pysh.BangBang('{}')".format(code) lines = code.split('\n') for line in lines: yield line else: yield from parse_bangexpr(' '.join(lines)).split('\n') from io import StringIO code = r''' foo = ! ls foo${bar}.* \ | grep foo > /dev/null foo = r' ls foo${bar} ' >> expr expr<' ls foo${bar} ' !! #!/bin/fish ls .* '''.strip() #TODO: !! is probably better solved with: # locals are solved with inspect.frame.f_locals sh << r''' # << means with variables interpolated # < is plain text ls .* ''' for line in transform(StringIO(code), transformer): print(line.rstrip('\n')) from pysh.command import command ls = command('ls') grep = command('grep') bar = 10 print('::BangExpr::') be = BangExpr('ls', BangSeq('foo', bar, BangGlob('.*')), BangOp("|"), 'grep', 'foo', 'baz', BangOp(">"), '/dev/null', locals=locals(), globals=globals()) # print(be) print('::BangBang::') bb = BangBang('''#!/bin/bash ls *.py''') print(bb)
[ 6738, 33245, 1330, 10903, 9399, 198, 11748, 302, 198, 11748, 11241, 1096, 198, 11748, 28686, 198, 6738, 17268, 1330, 390, 4188, 11, 21853, 13912, 198, 6738, 1257, 310, 10141, 1330, 300, 622, 62, 23870, 198, 6738, 33829, 1330, 2039, 388, ...
2.126476
2,625
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from __future__ import print_function import numpy import os import ssl
[ 2, 49962, 284, 262, 24843, 10442, 5693, 357, 1921, 37, 8, 739, 530, 198, 2, 393, 517, 18920, 5964, 11704, 13, 220, 4091, 262, 28536, 2393, 198, 2, 9387, 351, 428, 670, 329, 3224, 1321, 198, 2, 5115, 6634, 9238, 13, 220, 383, 7054,...
4.023364
214
import os import tmdbsimple as tmdb import media import fresh_tomatoes as ft movies = [] if os.environ.get('TMDB_API', False): # Retrieve API KEY tmdb.API_KEY = os.environ['TMDB_API'] # TMDB Movie Ids movie_ids = [271110, 297761, 246655, 278154, 135397, 188927] # Get Configuration configuration = tmdb.Configuration().info() image_base_url = configuration['images']['secure_base_url'] image_width = "w500" for movie_id in movie_ids: m = tmdb.Movies(movie_id) # Retrieve Image URL minfo = m.info() poster_image_url = image_base_url + image_width + minfo['poster_path'] # Retrieve Youtube Video URL videos = m.videos() video = videos['results'][0] youtube_url = 'https://youtube.com/watch?v=' + video['key'] # Append Movie object movie = media.Movie(m.title) movie.storyline = m.overview movie.poster_url = poster_image_url movie.trailer_url = youtube_url movies.append(movie) else: # Avatar avatar = media.Movie("Avatar") avatar.storyline = ("A paraplegic marine dispatched to the moon Pandora " "on a unique mission becomes torn between following " "his orders and protecting the world he feels is " "his home.") avatar.poster_url = ("https://upload.wikimedia.org/wikipedia/" "en/b/b0/Avatar-Teaser-Poster.jpg") avatar.trailer_url = "https://www.youtube.com/watch?v=-9ceBgWV8io" # Deadpool deadpool = media.Movie("Deadpool") deadpool.storyline = ("A fast-talking mercenary with a morbid sense of " "humor is subjected to a rogue experiment that " "leaves him with accelerated healing powers and a " "quest for revenge.") deadpool.poster_url = ("https://upload.wikimedia.org/wikipedia/en/4/46/" "Deadpool_poster.jpg") deadpool.trailer_url = "https://www.youtube.com/watch?v=gtTfd6tISfw" # Ghostbusters ghostbusters = media.Movie("Ghostbusters") ghostbusters.storyline = ("Following a ghost invasion of Manhattan, " "paranormal enthusiasts Erin Gilbert and Abby " "Yates, nuclear engineer Jillian Holtzmann, " "and subway worker Patty Tolan band together " "to stop the otherworldly threat.") ghostbusters.poster_url = ("https://upload.wikimedia.org/wikipedia/" "en/3/32/Ghostbusters_2016_film_poster.png") ghostbusters.trailer_url = "https://www.youtube.com/watch?v=w3ugHP-yZXw" # Olympus olympus = media.Movie("Olympus Has Fallen") olympus.storyline = ("Disgraced Secret Service agent (and former " "presidential guard) Mike Banning finds himself " "trapped inside the White House in the wake of a " "terrorist attack; using his inside knowledge, " "Banning works with national security to rescue " "the President from his kidnappers.") olympus.poster_url = ("https://upload.wikimedia.org/wikipedia/en/b/bf/" "Olympus_Has_Fallen_poster.jpg") olympus.trailer_url = "https://www.youtube.com/watch?v=vwx1f0kyNwI" # Angry Birds angry_birds = media.Movie("The Angry Birds Movie") angry_birds.storyline = ("Find out why the birds are so angry. When an " "island populated by happy, flightless birds " "is visited by mysterious green piggies, it's " "up to three unlikely outcasts - Red, Chuck " "and Bomb - to figure out what the pigs are up " "to.") angry_birds.poster_url = ("https://upload.wikimedia.org/wikipedia/en/f/" "f9/The_Angry_Birds_Movie_poster.png") angry_birds.trailer_url = "https://www.youtube.com/watch?v=1U2DKKqxHgE" # Ironman ironman = media.Movie("Iron Man") ironman.storyline = ("After being held captive in an Afghan cave, " "billionaire engineer Tony Stark creates a unique " "weaponized suit of armor to fight evil.") ironman.poster_url = ("https://upload.wikimedia.org/wikipedia/en/7/70/" "Ironmanposter.JPG") ironman.trailer_url = "https://www.youtube.com/watch?v=8hYlB38asDY" movies = [avatar, deadpool, ghostbusters, olympus, angry_birds, ironman] ft.open_movies_page(movies)
[ 11748, 28686, 198, 11748, 256, 9132, 1443, 320, 1154, 355, 256, 9132, 65, 198, 11748, 2056, 198, 11748, 4713, 62, 39532, 15048, 355, 10117, 198, 198, 76, 20526, 796, 17635, 198, 198, 361, 28686, 13, 268, 2268, 13, 1136, 10786, 15972, ...
2.175688
2,180
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file './elements_ui.ui', # licensing of './elements_ui.ui' applies. # # Created: Wed Jun 16 14:29:03 2021 # by: pyside2-uic running on PySide2 5.13.2 # # WARNING! All changes made in this file will be lost! from PySide2 import QtCore, QtGui, QtWidgets from . import main_window_rc_rc
[ 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, 19571, 68, 3639, 62, 9019, 13, 9019, 3256, 198, 2, 15665, 286, 705, 19571, 68, 3639, 62, 9019, 13, 9019, 6, ...
2.65942
138
digit = input(" the cube of which digit do you want >") result = cube(int(digit)) print(result)
[ 198, 198, 27003, 796, 5128, 7203, 262, 23441, 286, 543, 16839, 466, 345, 765, 1875, 4943, 220, 198, 20274, 796, 23441, 7, 600, 7, 27003, 4008, 220, 198, 4798, 7, 20274, 8, 198 ]
3.030303
33
try: from unittest.mock import patch except ImportError: # pragma: no cover from mock import patch from proofreader.runner import run, _run_command
[ 28311, 25, 198, 220, 220, 220, 422, 555, 715, 395, 13, 76, 735, 1330, 8529, 198, 16341, 17267, 12331, 25, 220, 1303, 23864, 2611, 25, 645, 3002, 198, 220, 220, 220, 422, 15290, 1330, 8529, 198, 198, 6738, 6617, 46862, 13, 16737, 133...
3.134615
52
from tanim.utils.config_ops import digest_config from tanim.utils.iterables import list_update # Currently, this is only used by both Scene and Mobject. # Still, we abstract its functionality here, albeit purely nominally. # All actual implementation has to be handled by derived classes for now.
[ 6738, 256, 11227, 13, 26791, 13, 11250, 62, 2840, 1330, 16274, 62, 11250, 198, 6738, 256, 11227, 13, 26791, 13, 2676, 2977, 1330, 1351, 62, 19119, 628, 198, 2, 16888, 11, 428, 318, 691, 973, 416, 1111, 28315, 290, 337, 15252, 13, 19...
4.067568
74
from config import *
[ 6738, 4566, 1330, 1635, 628, 628, 628, 628, 628, 628, 628, 628 ]
3
12
#!/usr/bin/env python """Extract events from kafka and write them to hdfs """ import json from pyspark.sql import SparkSession, Row from pyspark.sql.functions import udf def main(): """main """ spark = SparkSession \ .builder \ .appName("ExtractEventsJob") \ .getOrCreate() raw_events = spark \ .read \ .format("kafka") \ .option("kafka.bootstrap.servers", "kafka:29092") \ .option("subscribe", "events") \ .option("startingOffsets", "earliest") \ .option("endingOffsets", "latest") \ .load() purchase_events = raw_events \ .select(raw_events.value.cast('string').alias('raw'), raw_events.timestamp.cast('string')) \ .filter(is_purchase('raw')) extracted_purchase_events = purchase_events \ .rdd \ .map(lambda r: Row(timestamp=r.timestamp, **json.loads(r.raw))) \ .toDF() extracted_purchase_events.printSchema() extracted_purchase_events.show() if __name__ == "__main__": main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 37811, 11627, 974, 2995, 422, 479, 1878, 4914, 290, 3551, 606, 284, 289, 7568, 82, 198, 37811, 198, 11748, 33918, 198, 6738, 279, 893, 20928, 13, 25410, 1330, 17732, 36044, 11, 11314, ...
2.287257
463
import numpy as np from pysz import compress, decompress test_compress_decompress()
[ 11748, 299, 32152, 355, 45941, 198, 6738, 279, 893, 89, 1330, 27413, 11, 38237, 601, 628, 198, 198, 9288, 62, 5589, 601, 62, 12501, 3361, 601, 3419, 198 ]
3.107143
28
import json from sparkdq.outliers.params.OutlierSolverParams import OutlierSolverParams from sparkdq.outliers.OutlierSolver import OutlierSolver
[ 11748, 33918, 198, 198, 6738, 9009, 49506, 13, 448, 75, 3183, 13, 37266, 13, 7975, 2505, 50, 14375, 10044, 4105, 1330, 3806, 2505, 50, 14375, 10044, 4105, 198, 6738, 9009, 49506, 13, 448, 75, 3183, 13, 7975, 2505, 50, 14375, 1330, 380...
3.195652
46
from alerta.models.alert import Alert from alerta.webhooks import WebhookBase
[ 198, 6738, 7995, 64, 13, 27530, 13, 44598, 1330, 23276, 198, 6738, 7995, 64, 13, 12384, 25480, 82, 1330, 5313, 25480, 14881, 628 ]
3.478261
23
import re from setuptools import setup, find_packages import sys if sys.version_info < (3, 5): raise 'must use Python version 3.5 or higher' with open('./gmailapi_backend/__init__.py', 'r') as f: MATCH_EXPR = "__version__[^'\"]+(['\"])([^'\"]+)" VERSION = re.search(MATCH_EXPR, f.read()).group(2).strip() setup( name='django-gmailapi-backend', version=VERSION, packages=find_packages(), author="Michele Dolfi", author_email="michele.dolfi@gmail.com", license="Apache License 2.0", entry_points={ 'console_scripts': [ 'gmail_oauth2 = gmailapi_backend.bin.gmail_oauth2:main', ] }, install_requires=[ 'google-api-python-client~=2.0', 'google-auth>=1.16.0,<3.0.0dev', ], url="https://github.com/dolfim/django-gmailapi-backend", long_description_content_type='text/markdown', long_description=open('README.md').read(), description='Email backend for Django which sends email via the Gmail API', classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Framework :: Django', 'Topic :: Communications :: Email', 'Development Status :: 4 - Beta' ], )
[ 11748, 302, 198, 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 198, 198, 11748, 25064, 198, 361, 25064, 13, 9641, 62, 10951, 1279, 357, 18, 11, 642, 2599, 198, 220, 220, 220, 5298, 705, 27238, 779, 11361, 2196, 513, 13, ...
2.461087
681
"""Script to ensure a configuration file exists.""" import argparse import os import openpeerpower.config as config_util from openpeerpower.core import OpenPeerPower # mypy: allow-untyped-calls, allow-untyped-defs def run(args): """Handle ensure config commandline script.""" parser = argparse.ArgumentParser( description=( "Ensure a Open Peer Power config exists, creates one if necessary." ) ) parser.add_argument( "-c", "--config", metavar="path_to_config_dir", default=config_util.get_default_config_dir(), help="Directory that contains the Open Peer Power configuration", ) parser.add_argument("--script", choices=["ensure_config"]) args = parser.parse_args() config_dir = os.path.join(os.getcwd(), args.config) # Test if configuration directory exists if not os.path.isdir(config_dir): print("Creating directory", config_dir) os.makedirs(config_dir) opp = OpenPeerPower() opp.config.config_dir = config_dir config_path = opp.loop.run_until_complete(async_run(opp)) print("Configuration file:", config_path) return 0
[ 37811, 7391, 284, 4155, 257, 8398, 2393, 7160, 526, 15931, 198, 11748, 1822, 29572, 198, 11748, 28686, 198, 198, 11748, 1280, 33350, 6477, 13, 11250, 355, 4566, 62, 22602, 198, 6738, 1280, 33350, 6477, 13, 7295, 1330, 4946, 6435, 263, 1...
2.676538
439
# Vicfred # https://atcoder.jp/contests/abc132/tasks/abc132_a # implementation S = list(input()) if len(set(S)) == 2: if S.count(S[0]) == 2: print("Yes") quit() print("No")
[ 2, 24017, 39193, 198, 2, 3740, 1378, 265, 66, 12342, 13, 34523, 14, 3642, 3558, 14, 39305, 19924, 14, 83, 6791, 14, 39305, 19924, 62, 64, 198, 2, 7822, 198, 50, 796, 1351, 7, 15414, 28955, 198, 198, 361, 18896, 7, 2617, 7, 50, 4...
2.119565
92
import pytest import numpy as np import pandas as pd import matplotlib.pyplot as plt import itertools from sklearn.datasets import (make_regression, make_blobs, load_digits, fetch_openml, load_diabetes) from sklearn.preprocessing import KBinsDiscretizer from dabl.preprocessing import clean, detect_types, guess_ordinal from dabl.plot.supervised import ( plot, plot_classification_categorical, plot_classification_continuous, plot_regression_categorical, plot_regression_continuous) from dabl.utils import data_df_from_bunch from dabl import set_config # FIXME: check that target is not y but a column name def test_float_classification_target(): # check we can plot even if we do classification with a float target X, y = make_blobs() data = pd.DataFrame(X) data['target'] = y.astype(np.float) types = detect_types(data) assert types.categorical['target'] plot(data, target_col='target') # same with "actual float" - we need to specify classification for that :-/ data['target'] = y.astype(np.float) + .2 plot(data, target_col='target', type_hints={'target': 'categorical'}) plt.close("all")
[ 11748, 12972, 9288, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 198, 11748, 340, 861, 10141, 198, 198, 6738, 1341, 35720, 13, 19608, 292, ...
2.773672
433
################################################################################ # Copyright (c) 2017 Dan Iorga, Tyler Sorenson, Alastair Donaldson # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all #copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. ################################################################################ import sys import json from pprint import pprint if __name__ == "__main__": if len(sys.argv) != 2: print("usage: " + sys.argv[0] + " <ranked_environments>.json\n") exit(1) rank = CalculateRank(sys.argv[1]) rank.get_rank()
[ 29113, 29113, 14468, 198, 1303, 15069, 357, 66, 8, 2177, 6035, 314, 2398, 64, 11, 14886, 311, 29578, 1559, 11, 978, 459, 958, 3759, 1559, 628, 1303, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 257, ...
3.781022
411
import sys import subprocess as sub import os """ Simple utility script to generate HTML charts of how ANTLR parses every query and what is the resulting AST. """ if __name__ == '__main__': if len(sys.argv) == 1: sys.argv.insert(1, "StandardLuceneGrammar") run(*sys.argv[1:])
[ 198, 11748, 25064, 198, 11748, 850, 14681, 355, 850, 198, 11748, 28686, 198, 198, 37811, 198, 26437, 10361, 4226, 284, 7716, 11532, 15907, 286, 703, 3537, 14990, 49, 13544, 274, 198, 16833, 12405, 290, 644, 318, 262, 7186, 29273, 13, 22...
2.416667
132
""" MIT License Copyright (c) 2020 Susant Achary <sache.meet@yahoo.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from visual_perception.Detection.yolov4.tf import YOLOv4 as yolo_main import numpy as np import cv2 labels = {0: 'person', 1: 'bicycle', 2: 'car', 3: 'motorcycle', 4: 'airplane', 5: 'bus', 6: 'train', 7: 'truck', 8: 'boat', 9: 'traffic light', 10: 'fire hydrant', 11: 'stop sign', 12: 'parking meter', 13: 'bench', 14: 'bird', 15: 'cat', 16: 'dog', 17: 'horse', 18: 'sheep', 19: 'cow', 20: 'elephant', 21: 'bear', 22: 'zebra', 23: 'giraffe', 24: 'backpack', 25: 'umbrella', 26: 'handbag', 27: 'tie', 28: 'suitcase', 29: 'frisbee', 30: 'skis', 31: 'snowboard', 32: 'sports ball', 33: 'kite', 34: 'baseball bat', 35: 'baseball glove', 36: 'skateboard', 37: 'surfboard', 38: 'tennis racket', 39: 'bottle', 40: 'wine glass', 41: 'cup', 42: 'fork', 43: 'knife', 44: 'spoon', 45: 'bowl', 46: 'banana', 47: 'apple', 48: 'sandwich', 49: 'orange', 50: 'broccoli', 51: 'carrot', 52: 'hot dog', 53: 'pizza', 54: 'donut', 55: 'cake', 56: 'chair', 57: 'couch', 58: 'potted plant', 59: 'bed', 60: 'dining table', 61: 'toilet', 62: 'tv', 63: 'laptop', 64: 'mouse', 65: 'remote', 66: 'keyboard', 67: 'cell phone', 68: 'microwave', 69: 'oven', 70: 'toaster', 71: 'sink', 72: 'refrigerator', 73: 'book', 74: 'clock', 75: 'vase', 76: 'scissors', 77: 'teddy bear', 78: 'hair drier', 79: 'toothbrush'}
[ 37811, 198, 36393, 13789, 198, 198, 15269, 357, 66, 8, 12131, 8932, 415, 26219, 560, 1279, 82, 4891, 13, 47745, 31, 40774, 13, 785, 29, 198, 198, 5990, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 257, 486...
2.712581
922
import paho.client as mqtt HOST = 'localhost' PORT = 1883
[ 11748, 279, 17108, 13, 16366, 355, 285, 80, 926, 198, 198, 39, 10892, 796, 705, 36750, 6, 198, 15490, 796, 1248, 5999 ]
2.636364
22
#!/bin/env python from black import main import spacy import json from spacy import displacy import unidecode import pandas as pd import numpy as np import os csv_source = "scripts/spacy_files/data/thesis_200_with_school.csv" df = pd.read_csv(csv_source) df = df[df['isScan']==False] df = df.sort_values('isScan', ascending=False) text1= "Escuela de Enfermera" text2 = "ESCUELA DE ENFERMERIA" file = open("scripts/spacy_files/data/escuelas.json", "r") file = json.load(file) temp_list = [] for facultad in file: temp_list.append(facultad['escuela']) #print(facultad['escuela']) escuelas = [item for sublist in temp_list for item in sublist] # make the list flat #print(escuelas) text1_u = unidecode.unidecode(text1) text1_l_u = text1_u.lower() text2_l_u = unidecode.unidecode(text2).lower() print(text1_l_u, "<-->", text2_l_u) if text1_l_u == text2_l_u: print(text1, " is correct.") if __name__ == "__main__": u_escuelas = set_school_to_unaccent(escuelas) u_escuelas_dict = create_dictionary(u_escuelas) escuelas_dict = create_dictionary(escuelas) print(u_escuelas_dict) print(escuelas_dict) print(set_schools_accents("No school", u_escuelas_dict, escuelas_dict))
[ 2, 48443, 8800, 14, 24330, 21015, 198, 6738, 2042, 1330, 1388, 198, 11748, 599, 1590, 198, 11748, 33918, 198, 6738, 599, 1590, 1330, 7845, 1590, 198, 11748, 555, 485, 8189, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, ...
2.413174
501
# Copyright 2018 Tensorforce Team. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== from copy import deepcopy from datetime import datetime import os import sys import warnings from tensorforce import TensorforceError from tensorforce.agents import Agent from tensorforce.core.layers import Layer from tensorforce.environments import Environment from tensorforce.execution import Runner from test.unittest_environment import UnittestEnvironment os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
[ 2, 15069, 2864, 309, 22854, 3174, 4816, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, ...
4.007353
272
"""init module for reveal app""" # pylint: disable=invalid-name default_app_config = "mspray.apps.reveal.apps.RevealConfig" # noqa
[ 37811, 15003, 8265, 329, 7766, 598, 37811, 198, 2, 279, 2645, 600, 25, 15560, 28, 259, 12102, 12, 3672, 198, 12286, 62, 1324, 62, 11250, 796, 366, 907, 1050, 323, 13, 18211, 13, 36955, 282, 13, 18211, 13, 3041, 303, 282, 16934, 1, ...
2.75
48
from django.db import models from django import forms from audit_log.models.managers import AuditLog # Create your models here.
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 42625, 14208, 1330, 5107, 198, 6738, 14984, 62, 6404, 13, 27530, 13, 805, 10321, 1330, 46450, 11187, 628, 198, 2, 13610, 534, 4981, 994, 13, 628 ]
3.742857
35
# Generated by Django 2.2.5 on 2019-09-25 00:12 from django.db import migrations
[ 2, 2980, 515, 416, 37770, 362, 13, 17, 13, 20, 319, 13130, 12, 2931, 12, 1495, 3571, 25, 1065, 201, 198, 201, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 201, 198, 201, 198 ]
2.485714
35
import tensorflow as tf import json import math import cv2 import time import argparse import concurrent.futures import posenet import keyboard import sys import numpy as np from threading import Thread from slugify import slugify parser = argparse.ArgumentParser() parser.add_argument('--model', type=int, default=101) parser.add_argument('--cam_id', type=int, default=0) parser.add_argument('--cam_width', type=int, default=1280) parser.add_argument('--cam_height', type=int, default=720) parser.add_argument('--scale_factor', type=float, default=0.7125) parser.add_argument('--file', type=str, default=None, help="Optionally use a video file instead of a live camera") args = parser.parse_args() if __name__ == "__main__": main()
[ 11748, 11192, 273, 11125, 355, 48700, 198, 11748, 33918, 198, 11748, 10688, 198, 11748, 269, 85, 17, 198, 11748, 640, 198, 11748, 1822, 29572, 198, 11748, 24580, 13, 69, 315, 942, 198, 11748, 1426, 268, 316, 198, 11748, 10586, 198, 1174...
3.162393
234
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # import datetime import random import uuid import mock from openstackclient.tests.unit import utils from otcextensions.tests.unit.osclient import test_base from otcextensions.sdk.dcs.v1 import backup from otcextensions.sdk.dcs.v1 import config from otcextensions.sdk.dcs.v1 import instance from otcextensions.sdk.dcs.v1 import restore from otcextensions.sdk.dcs.v1 import statistic
[ 2, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 220, 220, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 921, 743, 7330, 198, 2, 220, 220, 257, 4866,...
3.248299
294
from ._ffi.base import string_types from ._ffi.object import register_object, Object from ._ffi.node import register_node, NodeBase from ._ffi.node import convert_to_node as _convert_to_node from ._ffi.node_generic import _scalar_type_inference from ._ffi.function import Function from ._ffi.function import _init_api, register_func, get_global_func, extract_ext_funcs from ._ffi.function import convert_to_tvm_func as _convert_tvm_func from ._ffi.runtime_ctypes import TVMType from . import _api_internal from . import make as _make from . import expr as _expr from . import tensor as _tensor from . import schedule as _schedule from . import container as _container from . import tag as _tag int8 = "int8" int32 = "int32" float32 = "float32" handle = "handle"
[ 6738, 47540, 487, 72, 13, 8692, 1330, 4731, 62, 19199, 198, 6738, 47540, 487, 72, 13, 15252, 1330, 7881, 62, 15252, 11, 9515, 198, 6738, 47540, 487, 72, 13, 17440, 1330, 7881, 62, 17440, 11, 19081, 14881, 198, 6738, 47540, 487, 72, ...
3.118367
245
import copy import torch from ..attack import Attack
[ 11748, 4866, 198, 11748, 28034, 198, 198, 6738, 11485, 20358, 1330, 8307, 628 ]
4.230769
13
# -*- coding:utf-8 -*- # Copyright (c) 2020 Huawei Technologies Co.,Ltd. # # openGauss is licensed under Mulan PSL v2. # You can use this software according to the terms # and conditions of the Mulan PSL v2. # You may obtain a copy of Mulan PSL v2 at: # # http://license.coscl.org.cn/MulanPSL2 # # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, # WITHOUT WARRANTIES OF ANY KIND, # EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, # MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. # See the Mulan PSL v2 for more details. # ---------------------------------------------------------------------------- import subprocess from gspylib.inspection.common.CheckItem import BaseItem from gspylib.inspection.common.CheckResult import ResultStatus
[ 2, 532, 9, 12, 19617, 25, 40477, 12, 23, 532, 9, 12, 198, 2, 15069, 357, 66, 8, 12131, 43208, 21852, 1766, 1539, 43, 8671, 13, 198, 2, 198, 2, 1280, 35389, 1046, 318, 11971, 739, 17996, 272, 6599, 43, 410, 17, 13, 198, 2, 921,...
3.211618
241
import subprocess import sys from . import ROOT, PY_SRC, _run, PY, DIST CONDA_ORDER = [ "core", "html", "lab", "datagrid", "svg", "tpl-jjinja" "yaml" ] CONDA_BUILD_ARGS = [ "conda-build", "-c", "conda-forge", "--output-folder", DIST / "conda-bld", ] if __name__ == "__main__": for pkg in PY_SRC.glob("wxyz_*"): _run([PY, "setup.py", "sdist", "--dist-dir", DIST / "sdist"], cwd=str(pkg)) try: _run([*CONDA_BUILD_ARGS, "--skip-existing", "."], cwd=ROOT / "recipes") except: for pkg in CONDA_ORDER: _run([*CONDA_BUILD_ARGS, f"wxyz-{pkg}"], cwd=ROOT / "recipes")
[ 11748, 850, 14681, 198, 11748, 25064, 198, 198, 6738, 764, 1330, 15107, 2394, 11, 350, 56, 62, 50, 7397, 11, 4808, 5143, 11, 350, 56, 11, 360, 8808, 628, 198, 10943, 5631, 62, 12532, 1137, 796, 685, 198, 220, 220, 220, 366, 7295, ...
1.894428
341
import requests, time, re, rsa, json, base64 from urllib import parse s = requests.Session() username = "" password = "" if(username == "" or password == ""): username = input("") password = input("") BI_RM = list("0123456789abcdefghijklmnopqrstuvwxyz") b64map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" if __name__ == "__main__": main()
[ 11748, 7007, 11, 640, 11, 302, 11, 374, 11400, 11, 33918, 11, 2779, 2414, 198, 6738, 2956, 297, 571, 1330, 21136, 198, 198, 82, 796, 7007, 13, 36044, 3419, 198, 198, 29460, 796, 13538, 198, 28712, 796, 13538, 198, 198, 361, 7, 29460...
2.380368
163
import subprocess from .Genome_fasta import get_fasta import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as plt import numpy as np import pysam if __name__=="__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument('-b','--bamfile',help="bam file name", metavar="FILE") parser.add_argument('-g','--genome',help="Genome fasta file path") parser.add_argument('-o','--output',help="pie figure's filename") run(parser)
[ 11748, 850, 14681, 198, 6738, 764, 13746, 462, 62, 7217, 64, 1330, 651, 62, 7217, 64, 198, 11748, 2603, 29487, 8019, 198, 6759, 29487, 8019, 13, 1904, 10786, 46384, 11537, 198, 6738, 2603, 29487, 8019, 1330, 12972, 29487, 355, 458, 83, ...
2.794286
175
"""A clean customisable Sphinx documentation theme.""" __version__ = "2020.9.8.beta2" from pathlib import Path from .body import wrap_tables from .code import get_pygments_style_colors from .navigation import get_navigation_tree from .toc import should_hide_toc def setup(app): """Entry point for sphinx theming.""" theme_path = (Path(__file__).parent / "theme").resolve() app.add_html_theme("furo", str(theme_path)) app.connect("html-page-context", _html_page_context)
[ 37811, 32, 3424, 2183, 43942, 45368, 28413, 10314, 7505, 526, 15931, 198, 198, 834, 9641, 834, 796, 366, 42334, 13, 24, 13, 23, 13, 31361, 17, 1, 198, 198, 6738, 3108, 8019, 1330, 10644, 198, 198, 6738, 764, 2618, 1330, 14441, 62, 8...
2.91716
169
#!/usr/bin/env python3 # Copyright 2016 Curtis Sand # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A test for what happens when two waveforms are averaged together.""" from potty_oh import common from potty_oh.wav_file import wav_file_context from potty_oh.waveform import mix_down from potty_oh.signal_generator import Generator from potty_oh.music.pitch import Key from potty_oh.music.interval import Interval if __name__ == "__main__": common.call_main(main)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 15069, 1584, 25157, 3837, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 2...
3.31
300
from dataclasses import dataclass from hrepr import H from hrepr import hrepr as real_hrepr from hrepr.h import styledir from .common import one_test_per_assert css_hrepr = open(f"{styledir}/hrepr.css", encoding="utf-8").read() hrepr = real_hrepr.variant(fill_resources=False) def hshort(x, **kw): return hrepr(x, max_depth=0, **kw) def test_function(): assert hrepr(Opaque) == H.span["hreprk-class"]( H.span["hrepr-defn-key"]("class"), " ", H.span["hrepr-defn-name"]("Opaque"), ) def test_structures(): for typ, o, c in ( (tuple, "(", ")"), (list, "[", "]"), (set, "{", "}"), (frozenset, "{", "}"), ): clsname = typ.__name__ assert hrepr(typ((1, 2))) == H.div[ f"hreprt-{clsname}", "hrepr-bracketed" ]( H.div["hrepr-open"](o), H.div["hreprl-h", "hrepr-body"]( H.div(H.span["hreprt-int"]("1")), H.div(H.span["hreprt-int"]("2")), ), H.div["hrepr-close"](c), )
[ 6738, 4818, 330, 28958, 1330, 4818, 330, 31172, 198, 198, 6738, 289, 260, 1050, 1330, 367, 198, 6738, 289, 260, 1050, 1330, 289, 260, 1050, 355, 1103, 62, 71, 260, 1050, 198, 6738, 289, 260, 1050, 13, 71, 1330, 45552, 343, 198, 198,...
1.823529
595
import inspect from sympy.core.cache import cacheit from sympy.core.singleton import S from sympy.core.sympify import _sympify from sympy.logic.boolalg import Boolean from sympy.utilities.source import get_class from contextlib import contextmanager global_assumptions = AssumptionsContext()
[ 11748, 10104, 198, 6738, 10558, 88, 13, 7295, 13, 23870, 1330, 12940, 270, 198, 6738, 10558, 88, 13, 7295, 13, 12215, 10565, 1330, 311, 198, 6738, 10558, 88, 13, 7295, 13, 1837, 3149, 1958, 1330, 4808, 1837, 3149, 1958, 198, 6738, 105...
3.453488
86
import numpy as np from unittest import TestCase import numpy.testing as npt from distancematrix.util import diag_indices_of from distancematrix.consumer.distance_matrix import DistanceMatrix
[ 11748, 299, 32152, 355, 45941, 198, 6738, 555, 715, 395, 1330, 6208, 20448, 198, 11748, 299, 32152, 13, 33407, 355, 299, 457, 198, 198, 6738, 5253, 6759, 8609, 13, 22602, 1330, 2566, 363, 62, 521, 1063, 62, 1659, 198, 6738, 5253, 6759...
3.592593
54
"""Constants file for Supervisor.""" from enum import Enum from ipaddress import ip_network from pathlib import Path SUPERVISOR_VERSION = "DEV" URL_HASSIO_ADDONS = "https://github.com/home-assistant/addons" URL_HASSIO_APPARMOR = "https://version.home-assistant.io/apparmor.txt" URL_HASSIO_VERSION = "https://version.home-assistant.io/{channel}.json" SUPERVISOR_DATA = Path("/data") FILE_HASSIO_ADDONS = Path(SUPERVISOR_DATA, "addons.json") FILE_HASSIO_AUTH = Path(SUPERVISOR_DATA, "auth.json") FILE_HASSIO_CONFIG = Path(SUPERVISOR_DATA, "config.json") FILE_HASSIO_DISCOVERY = Path(SUPERVISOR_DATA, "discovery.json") FILE_HASSIO_DOCKER = Path(SUPERVISOR_DATA, "docker.json") FILE_HASSIO_HOMEASSISTANT = Path(SUPERVISOR_DATA, "homeassistant.json") FILE_HASSIO_INGRESS = Path(SUPERVISOR_DATA, "ingress.json") FILE_HASSIO_SERVICES = Path(SUPERVISOR_DATA, "services.json") FILE_HASSIO_UPDATER = Path(SUPERVISOR_DATA, "updater.json") FILE_SUFFIX_CONFIGURATION = [".yaml", ".yml", ".json"] MACHINE_ID = Path("/etc/machine-id") SOCKET_DBUS = Path("/run/dbus/system_bus_socket") SOCKET_DOCKER = Path("/run/docker.sock") RUN_SUPERVISOR_STATE = Path("/run/supervisor") SYSTEMD_JOURNAL_PERSISTENT = Path("/var/log/journal") SYSTEMD_JOURNAL_VOLATILE = Path("/run/log/journal") DOCKER_NETWORK = "hassio" DOCKER_NETWORK_MASK = ip_network("172.30.32.0/23") DOCKER_NETWORK_RANGE = ip_network("172.30.33.0/24") # This needs to match the dockerd --cpu-rt-runtime= argument. DOCKER_CPU_RUNTIME_TOTAL = 950_000 # The rt runtimes are guarantees, hence we cannot allocate more # time than available! Support up to 5 containers with equal time # allocated. # Note that the time is multiplied by CPU count. This means that # a single container can schedule up to 950/5*4 = 760ms in RT priority # on a quad core system. DOCKER_CPU_RUNTIME_ALLOCATION = int(DOCKER_CPU_RUNTIME_TOTAL / 5) DNS_SUFFIX = "local.hass.io" LABEL_ARCH = "io.hass.arch" LABEL_MACHINE = "io.hass.machine" LABEL_TYPE = "io.hass.type" LABEL_VERSION = "io.hass.version" META_ADDON = "addon" META_HOMEASSISTANT = "homeassistant" META_SUPERVISOR = "supervisor" JSON_DATA = "data" JSON_MESSAGE = "message" JSON_RESULT = "result" RESULT_ERROR = "error" RESULT_OK = "ok" CONTENT_TYPE_BINARY = "application/octet-stream" CONTENT_TYPE_JSON = "application/json" CONTENT_TYPE_PNG = "image/png" CONTENT_TYPE_TAR = "application/tar" CONTENT_TYPE_TEXT = "text/plain" CONTENT_TYPE_URL = "application/x-www-form-urlencoded" COOKIE_INGRESS = "ingress_session" HEADER_TOKEN = "X-Supervisor-Token" HEADER_TOKEN_OLD = "X-Hassio-Key" ENV_TIME = "TZ" ENV_TOKEN = "SUPERVISOR_TOKEN" ENV_TOKEN_HASSIO = "HASSIO_TOKEN" ENV_HOMEASSISTANT_REPOSITORY = "HOMEASSISTANT_REPOSITORY" ENV_SUPERVISOR_DEV = "SUPERVISOR_DEV" ENV_SUPERVISOR_MACHINE = "SUPERVISOR_MACHINE" ENV_SUPERVISOR_NAME = "SUPERVISOR_NAME" ENV_SUPERVISOR_SHARE = "SUPERVISOR_SHARE" ENV_SUPERVISOR_CPU_RT = "SUPERVISOR_CPU_RT" REQUEST_FROM = "HASSIO_FROM" ATTR_ACCESS_TOKEN = "access_token" ATTR_ACCESSPOINTS = "accesspoints" ATTR_ACTIVE = "active" ATTR_ADDON = "addon" ATTR_ADDONS = "addons" ATTR_ADDONS_CUSTOM_LIST = "addons_custom_list" ATTR_ADDONS_REPOSITORIES = "addons_repositories" ATTR_ADDRESS = "address" ATTR_ADDRESS_DATA = "address-data" ATTR_ADMIN = "admin" ATTR_ADVANCED = "advanced" ATTR_APPARMOR = "apparmor" ATTR_APPLICATION = "application" ATTR_ARCH = "arch" ATTR_ARGS = "args" ATTR_LABELS = "labels" ATTR_AUDIO = "audio" ATTR_AUDIO_INPUT = "audio_input" ATTR_AUDIO_OUTPUT = "audio_output" ATTR_AUTH = "auth" ATTR_AUTH_API = "auth_api" ATTR_AUTO_UPDATE = "auto_update" ATTR_AVAILABLE = "available" ATTR_BLK_READ = "blk_read" ATTR_BLK_WRITE = "blk_write" ATTR_BOARD = "board" ATTR_BOOT = "boot" ATTR_BRANCH = "branch" ATTR_BUILD = "build" ATTR_BUILD_FROM = "build_from" ATTR_CARD = "card" ATTR_CHANGELOG = "changelog" ATTR_CHANNEL = "channel" ATTR_CHASSIS = "chassis" ATTR_CHECKS = "checks" ATTR_CLI = "cli" ATTR_CONFIG = "config" ATTR_CONFIGURATION = "configuration" ATTR_CONNECTED = "connected" ATTR_CONNECTIONS = "connections" ATTR_CONTAINERS = "containers" ATTR_CPE = "cpe" ATTR_CPU_PERCENT = "cpu_percent" ATTR_CRYPTO = "crypto" ATTR_DATA = "data" ATTR_DATE = "date" ATTR_DEBUG = "debug" ATTR_DEBUG_BLOCK = "debug_block" ATTR_DEFAULT = "default" ATTR_DEPLOYMENT = "deployment" ATTR_DESCRIPTON = "description" ATTR_DETACHED = "detached" ATTR_DEVICES = "devices" ATTR_DEVICETREE = "devicetree" ATTR_DIAGNOSTICS = "diagnostics" ATTR_DISCOVERY = "discovery" ATTR_DISK = "disk" ATTR_DISK_FREE = "disk_free" ATTR_DISK_LIFE_TIME = "disk_life_time" ATTR_DISK_TOTAL = "disk_total" ATTR_DISK_USED = "disk_used" ATTR_DNS = "dns" ATTR_DOCKER = "docker" ATTR_DOCKER_API = "docker_api" ATTR_DOCUMENTATION = "documentation" ATTR_DOMAINS = "domains" ATTR_ENABLE = "enable" ATTR_ENABLED = "enabled" ATTR_ENVIRONMENT = "environment" ATTR_EVENT = "event" ATTR_FEATURES = "features" ATTR_FILENAME = "filename" ATTR_FLAGS = "flags" ATTR_FOLDERS = "folders" ATTR_FREQUENCY = "frequency" ATTR_FULL_ACCESS = "full_access" ATTR_GATEWAY = "gateway" ATTR_GPIO = "gpio" ATTR_HASSIO_API = "hassio_api" ATTR_HASSIO_ROLE = "hassio_role" ATTR_HASSOS = "hassos" ATTR_HEALTHY = "healthy" ATTR_HOMEASSISTANT = "homeassistant" ATTR_HOMEASSISTANT_API = "homeassistant_api" ATTR_HOST = "host" ATTR_HOST_DBUS = "host_dbus" ATTR_HOST_INTERNET = "host_internet" ATTR_HOST_IPC = "host_ipc" ATTR_HOST_NETWORK = "host_network" ATTR_HOST_PID = "host_pid" ATTR_HOSTNAME = "hostname" ATTR_ICON = "icon" ATTR_ID = "id" ATTR_IMAGE = "image" ATTR_IMAGES = "images" ATTR_INDEX = "index" ATTR_INGRESS = "ingress" ATTR_INGRESS_ENTRY = "ingress_entry" ATTR_INGRESS_PANEL = "ingress_panel" ATTR_INGRESS_PORT = "ingress_port" ATTR_INGRESS_TOKEN = "ingress_token" ATTR_INGRESS_URL = "ingress_url" ATTR_INIT = "init" ATTR_INITIALIZE = "initialize" ATTR_INPUT = "input" ATTR_INSTALLED = "installed" ATTR_INTERFACE = "interface" ATTR_INTERFACES = "interfaces" ATTR_IP_ADDRESS = "ip_address" ATTR_IPV4 = "ipv4" ATTR_IPV6 = "ipv6" ATTR_ISSUES = "issues" ATTR_KERNEL = "kernel" ATTR_KERNEL_MODULES = "kernel_modules" ATTR_LAST_BOOT = "last_boot" ATTR_LEGACY = "legacy" ATTR_LOCALS = "locals" ATTR_LOCATON = "location" ATTR_LOGGING = "logging" ATTR_LOGO = "logo" ATTR_LONG_DESCRIPTION = "long_description" ATTR_MAC = "mac" ATTR_MACHINE = "machine" ATTR_MAINTAINER = "maintainer" ATTR_MAP = "map" ATTR_MEMORY_LIMIT = "memory_limit" ATTR_MEMORY_PERCENT = "memory_percent" ATTR_MEMORY_USAGE = "memory_usage" ATTR_MESSAGE = "message" ATTR_METHOD = "method" ATTR_MODE = "mode" ATTR_MULTICAST = "multicast" ATTR_NAME = "name" ATTR_NAMESERVERS = "nameservers" ATTR_NETWORK = "network" ATTR_NETWORK_DESCRIPTION = "network_description" ATTR_NETWORK_RX = "network_rx" ATTR_NETWORK_TX = "network_tx" ATTR_OBSERVER = "observer" ATTR_OPERATING_SYSTEM = "operating_system" ATTR_OPTIONS = "options" ATTR_OTA = "ota" ATTR_OUTPUT = "output" ATTR_PANEL_ADMIN = "panel_admin" ATTR_PANEL_ICON = "panel_icon" ATTR_PANEL_TITLE = "panel_title" ATTR_PANELS = "panels" ATTR_PARENT = "parent" ATTR_PASSWORD = "password" ATTR_PORT = "port" ATTR_PORTS = "ports" ATTR_PORTS_DESCRIPTION = "ports_description" ATTR_PREFIX = "prefix" ATTR_PRIMARY = "primary" ATTR_PRIORITY = "priority" ATTR_PRIVILEGED = "privileged" ATTR_PROTECTED = "protected" ATTR_PROVIDERS = "providers" ATTR_PSK = "psk" ATTR_RATING = "rating" ATTR_REALTIME = "realtime" ATTR_REFRESH_TOKEN = "refresh_token" ATTR_REGISTRIES = "registries" ATTR_REGISTRY = "registry" ATTR_REPOSITORIES = "repositories" ATTR_REPOSITORY = "repository" ATTR_SCHEMA = "schema" ATTR_SECURITY = "security" ATTR_SERIAL = "serial" ATTR_SERVERS = "servers" ATTR_SERVICE = "service" ATTR_SERVICES = "services" ATTR_SESSION = "session" ATTR_SIGNAL = "signal" ATTR_SIZE = "size" ATTR_SLUG = "slug" ATTR_SNAPSHOT_EXCLUDE = "snapshot_exclude" ATTR_SNAPSHOTS = "snapshots" ATTR_SOURCE = "source" ATTR_SQUASH = "squash" ATTR_SSD = "ssid" ATTR_SSID = "ssid" ATTR_SSL = "ssl" ATTR_STAGE = "stage" ATTR_STARTUP = "startup" ATTR_STATE = "state" ATTR_STATIC = "static" ATTR_STDIN = "stdin" ATTR_STORAGE = "storage" ATTR_SUGGESTIONS = "suggestions" ATTR_SUPERVISOR = "supervisor" ATTR_SUPERVISOR_INTERNET = "supervisor_internet" ATTR_SUPPORTED = "supported" ATTR_SUPPORTED_ARCH = "supported_arch" ATTR_SYSTEM = "system" ATTR_JOURNALD = "journald" ATTR_TIMEOUT = "timeout" ATTR_TIMEZONE = "timezone" ATTR_TITLE = "title" ATTR_TMPFS = "tmpfs" ATTR_TOTP = "totp" ATTR_TRANSLATIONS = "translations" ATTR_TYPE = "type" ATTR_UART = "uart" ATTR_UDEV = "udev" ATTR_UNHEALTHY = "unhealthy" ATTR_UNSAVED = "unsaved" ATTR_UNSUPPORTED = "unsupported" ATTR_UPDATE_AVAILABLE = "update_available" ATTR_UPDATE_KEY = "update_key" ATTR_URL = "url" ATTR_USB = "usb" ATTR_USER = "user" ATTR_USERNAME = "username" ATTR_UUID = "uuid" ATTR_VALID = "valid" ATTR_VALUE = "value" ATTR_VERSION = "version" ATTR_VERSION_LATEST = "version_latest" ATTR_VIDEO = "video" ATTR_VLAN = "vlan" ATTR_VOLUME = "volume" ATTR_VPN = "vpn" ATTR_WAIT_BOOT = "wait_boot" ATTR_WATCHDOG = "watchdog" ATTR_WEBUI = "webui" ATTR_WIFI = "wifi" ATTR_CONTENT_TRUST = "content_trust" ATTR_FORCE_SECURITY = "force_security" PROVIDE_SERVICE = "provide" NEED_SERVICE = "need" WANT_SERVICE = "want" MAP_CONFIG = "config" MAP_SSL = "ssl" MAP_ADDONS = "addons" MAP_BACKUP = "backup" MAP_SHARE = "share" MAP_MEDIA = "media" ARCH_ARMHF = "armhf" ARCH_ARMV7 = "armv7" ARCH_AARCH64 = "aarch64" ARCH_AMD64 = "amd64" ARCH_I386 = "i386" ARCH_ALL = [ARCH_ARMHF, ARCH_ARMV7, ARCH_AARCH64, ARCH_AMD64, ARCH_I386] REPOSITORY_CORE = "core" REPOSITORY_LOCAL = "local" FOLDER_HOMEASSISTANT = "homeassistant" FOLDER_SHARE = "share" FOLDER_ADDONS = "addons/local" FOLDER_SSL = "ssl" FOLDER_MEDIA = "media" SNAPSHOT_FULL = "full" SNAPSHOT_PARTIAL = "partial" CRYPTO_AES128 = "aes128" SECURITY_PROFILE = "profile" SECURITY_DEFAULT = "default" SECURITY_DISABLE = "disable" ROLE_DEFAULT = "default" ROLE_HOMEASSISTANT = "homeassistant" ROLE_BACKUP = "backup" ROLE_MANAGER = "manager" ROLE_ADMIN = "admin" ROLE_ALL = [ROLE_DEFAULT, ROLE_HOMEASSISTANT, ROLE_BACKUP, ROLE_MANAGER, ROLE_ADMIN]
[ 37811, 34184, 1187, 2393, 329, 45673, 526, 15931, 198, 6738, 33829, 1330, 2039, 388, 198, 6738, 20966, 21975, 1330, 20966, 62, 27349, 198, 6738, 3108, 8019, 1330, 10644, 198, 198, 40331, 1137, 29817, 1581, 62, 43717, 796, 366, 39345, 1, ...
2.250056
4,483
import inspect from math import hypot, sin, asin, cos, radians, degrees from abc import ABCMeta, abstractmethod from random import randint, choice from typing import Dict, List, Tuple, Union
[ 11748, 10104, 198, 198, 6738, 10688, 1330, 8813, 11, 7813, 11, 355, 259, 11, 8615, 11, 2511, 1547, 11, 7370, 198, 6738, 450, 66, 1330, 9738, 48526, 11, 12531, 24396, 198, 6738, 4738, 1330, 43720, 600, 11, 3572, 198, 6738, 19720, 1330,...
3.711538
52
import torch import torch.nn as nn import os import torch.nn.functional as F def vgg(cfg, i, batch_norm=False): layers = [] in_channels = i for v in cfg: if v == 'M': layers += [nn.MaxPool2d(kernel_size=2, stride=2)] elif v == 'C': layers += [nn.MaxPool2d(kernel_size=2, stride=2, ceil_mode=True)] else: conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1) if batch_norm: layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=False)] else: layers += [conv2d, nn.ReLU(inplace=False)] in_channels = v pool5 = nn.MaxPool2d(kernel_size=3, stride=1, padding=1) conv6 = nn.Conv2d(512, 1024, kernel_size=3, padding=6, dilation=6) conv7 = nn.Conv2d(1024, 1024, kernel_size=1) layers += [pool5, conv6, nn.ReLU(inplace=False), conv7, nn.ReLU(inplace=False)] return layers base = { '300': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'C', 512, 512, 512, 'M', 512, 512, 512]} extras = { '300': [1024, 'S', 512, 'S', 256]} mbox = { '300': [6, 6, 6, 6, 4, 4]}
[ 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28686, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 628, 628, 628, 628, 628, 198, 198, 4299, 410, 1130, 7, 37581, 11, 1312, 11, 15458, 62, 27237, 28, 25101, ...
1.907166
614
#!/usr/bin/env python from wand.image import Image from wand.drawing import Drawing from wand.color import Color import wandplus.image as wpi from wandplus.textutil import calcSuitableFontsize, calcSuitableImagesize import os import unittest tmpdir = '_tmp/' class CheckTextUtil(unittest.TestCase): if __name__ == '__main__': unittest.main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 6738, 11569, 13, 9060, 1330, 7412, 198, 6738, 11569, 13, 19334, 278, 1330, 40027, 198, 6738, 11569, 13, 8043, 1330, 5315, 198, 11748, 11569, 9541, 13, 9060, 355, 266, 14415, 198, ...
3.060345
116
import mitsuba import pytest import enoki as ek from enoki.dynamic import Float32 as Float from mitsuba.python.test.util import fresolver_append_path from mitsuba.python.util import traverse def test04_normal_weighting_scheme(variant_scalar_rgb): from mitsuba.core import Struct, float_dtype, Vector3f from mitsuba.render import Mesh import numpy as np """Tests the weighting scheme that is used to compute surface normals.""" m = Mesh("MyMesh", 5, 2, has_vertex_normals=True) vertices = m.vertex_positions_buffer() normals = m.vertex_normals_buffer() a, b = 1.0, 0.5 vertices[:] = [0, 0, 0, -a, 1, 0, a, 1, 0, -b, 0, 1, b, 0, 1] n0 = Vector3f(0.0, 0.0, -1.0) n1 = Vector3f(0.0, 1.0, 0.0) angle_0 = ek.pi / 2.0 angle_1 = ek.acos(3.0 / 5.0) n2 = n0 * angle_0 + n1 * angle_1 n2 /= ek.norm(n2) n = np.vstack([n2, n0, n0, n1, n1]).transpose() m.faces_buffer()[:] = [0, 1, 2, 0, 3, 4] m.recompute_vertex_normals() for i in range(5): assert ek.allclose(normals[i*3:(i+1)*3], n[:, i], 5e-4) def test08_mesh_add_attribute(variant_scalar_rgb): from mitsuba.core import Struct, float_dtype from mitsuba.render import Mesh m = Mesh("MyMesh", 3, 2) m.vertex_positions_buffer()[:] = [0.0, 0.0, 0.0, 1.0, 0.2, 0.0, 0.2, 1.0, 0.0] m.faces_buffer()[:] = [0, 1, 2, 1, 2, 0] m.parameters_changed() m.add_attribute("vertex_color", 3)[:] = [0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0] assert str(m) == """Mesh[ name = "MyMesh", bbox = BoundingBox3f[ min = [0, 0, 0], max = [1, 1, 0] ], vertex_count = 3, vertices = [72 B of vertex data], face_count = 2, faces = [24 B of face data], disable_vertex_normals = 0, surface_area = 0.96, mesh attributes = [ vertex_color: 3 floats ] ]"""
[ 11748, 285, 896, 22013, 198, 11748, 12972, 9288, 198, 11748, 551, 18228, 355, 304, 74, 198, 6738, 551, 18228, 13, 67, 28995, 1330, 48436, 2624, 355, 48436, 198, 198, 6738, 285, 896, 22013, 13, 29412, 13, 9288, 13, 22602, 1330, 34093, ...
2.122827
863
from __future__ import (absolute_import, division, print_function, unicode_literals) from builtins import (ascii, bytes, chr, dict, filter, hex, input, int, map, next, oct, open, pow, range, round, str, super, zip) from ...._utils import send_session_request from ..._PortalEndpointBase import PortalEndpointBase from .CreateUpdateGroupParams import CreateUpdateGroupParams def get_properties(self): """ Gets the properties of the item. """ return self._get() def update(self, update_group_params, clear_empty_fields=False): """ Updates the group properties. """ update_group_params = update_group_params._get_params() if isinstance( update_group_params, CreateUpdateGroupParams) else update_group_params.copy() if not "clearEmptyFields" in update_group_params: update_group_params["clearEmptyFields"] = clear_empty_fields r = self._create_operation_request(self, "update", method="POST", data=update_group_params) return send_session_request(self._session, r).json()
[ 6738, 11593, 37443, 834, 1330, 357, 48546, 62, 11748, 11, 7297, 11, 3601, 62, 8818, 11, 28000, 1098, 62, 17201, 874, 8, 198, 6738, 3170, 1040, 1330, 357, 292, 979, 72, 11, 9881, 11, 442, 81, 11, 8633, 11, 8106, 11, 17910, 11, 5128...
2.711165
412
# Generated by Django 2.1.7 on 2019-08-09 09:36 from django.db import migrations, models def migrate_public_event(apps, schema_editor): """Migrate options previously with no contents (displayed as "Other:") to a new contents ("other"). The field containing these options is in CommonRequest abstract model, implemented in WorkshopRequest, WorkshopInquiryRequest, and SelfOrganizedSubmission models.""" WorkshopRequest = apps.get_model('workshops', 'WorkshopRequest') WorkshopInquiryRequest = apps.get_model('extrequests', 'WorkshopInquiryRequest') SelfOrganizedSubmission = apps.get_model('extrequests', 'SelfOrganizedSubmission') WorkshopRequest.objects.filter(public_event="") \ .update(public_event="other") WorkshopInquiryRequest.objects.filter(public_event="") \ .update(public_event="other") SelfOrganizedSubmission.objects.filter(public_event="") \ .update(public_event="other")
[ 2, 2980, 515, 416, 37770, 362, 13, 16, 13, 22, 319, 13130, 12, 2919, 12, 2931, 7769, 25, 2623, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628, 198, 4299, 32492, 62, 11377, 62, 15596, 7, 18211, 11, 32815, 6...
2.381356
472
import torch import torch.nn as nn
[ 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198 ]
3.181818
11
from unittest import TestCase import numpy as np from robustnessgym.cachedops.spacy import Spacy from robustnessgym.slicebuilders.subpopulations.length import LengthSubpopulation from tests.testbeds import MockTestBedv0
[ 6738, 555, 715, 395, 1330, 6208, 20448, 198, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 12373, 1108, 1360, 76, 13, 66, 2317, 2840, 13, 2777, 1590, 1330, 1338, 1590, 198, 6738, 12373, 1108, 1360, 76, 13, 48369, 50034, 13, 7266...
3.484375
64
import json from astroquery.vizier import Vizier with open("Jankowski_2018_raw.txt", "r") as raw_file: lines = raw_file.readlines() print(lines) pulsar_dict = {} for row in lines[3:]: row = row.split("|") print(row) pulsar = row[0].strip().replace("", "-") freqs = [] fluxs = [] flux_errs = [] # If no error means it's an upper limit andnow sure how to handle it if row[1].strip() != "" and row[2].strip() != "": freqs.append(728) fluxs.append(float(row[1].strip())) flux_errs.append(float(row[2].strip())) if row[3].strip() != "" and row[4].strip() != "": freqs.append(1382) fluxs.append(float(row[3].strip())) flux_errs.append(float(row[4].strip())) if row[5].strip() != "" and row[6].strip() != "": freqs.append(3100) fluxs.append(float(row[5].strip())) flux_errs.append(float(row[6].strip())) pulsar_dict[pulsar] = {"Frequency MHz":freqs, "Flux Density mJy":fluxs, "Flux Density error mJy":flux_errs} with open("Jankowski_2018.yaml", "w") as cat_file: cat_file.write(json.dumps(pulsar_dict)) print(pulsar_dict)
[ 11748, 33918, 198, 6738, 6468, 305, 22766, 13, 85, 528, 959, 1330, 36339, 959, 198, 198, 4480, 1280, 7203, 41, 962, 12079, 62, 7908, 62, 1831, 13, 14116, 1600, 366, 81, 4943, 355, 8246, 62, 7753, 25, 198, 220, 220, 220, 3951, 796, ...
2.210425
518
# Copyright (c) 2018, WSO2 Inc. (http://wso2.com) All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # importing required modules import sys from xml.etree import ElementTree as ET import toml import subprocess import wget import logging import inspect import os import shutil import pymysql import sqlparse import re from pathlib import Path import urllib.request as urllib2 from xml.dom import minidom import intg_test_manager as cm from subprocess import Popen, PIPE import os from prod_test_constant import DB_META_DATA, DIST_POM_PATH, INTEGRATION_PATH, DISTRIBUTION_PATH, \ DATASOURCE_PATHS, LIB_PATH, WSO2SERVER, M2_PATH, ARTIFACT_REPORTS_PATHS, POM_FILE_PATHS from intg_test_constant import NS, ZIP_FILE_EXTENSION, CARBON_NAME, VALUE_TAG, SURFACE_PLUGIN_ARTIFACT_ID, \ DEPLOYMENT_PROPERTY_FILE_NAME, LOG_FILE_NAME, PRODUCT_STORAGE_DIR_NAME, \ DEFAULT_DB_USERNAME, LOG_STORAGE, TEST_OUTPUT_DIR_NAME, DEFAULT_ORACLE_SID, MYSQL_DB_ENGINE, \ ORACLE_DB_ENGINE, PRODUCT_STORAGE_DIR_NAME, MSSQL_DB_ENGINE database_names = [] db_engine = None sql_driver_location = None identity_db_url = None identity_db_username = None identity_db_password = None identity_db_driver = None shared_db_url = None shared_db_username = None shared_db_password = None shared_db_driver = None identity_db = "WSO2_IDENTITY_DB" shared_db = "WSO2_SHARED_DB" # Since we have added a method to clone a given git branch and checkout to the latest released tag it is not required to # modify pom files. Hence in the current implementation this method is not using. # However, in order to execute this method you can define pom file paths in const_<prod>.py as a constant # and import it to run-intg-test.py. Thereafter assign it to global variable called pom_file_paths in the # configure_product method and call the modify_pom_files method. #TODO: Improve the method in generic way to support all products #TODO: Improve the method in generic way to support all products #TODO: Improve the method in generic way to support all products # def set_custom_testng(): # if cm.use_custom_testng_file == "TRUE": # testng_source = Path(cm.workspace + "/" + "testng.xml") # testng_destination = Path(cm.workspace + "/" + cm.product_id + "/" + TESTNG_DIST_XML_PATHS) # testng_server_mgt_source = Path(cm.workspace + "/" + "testng-server-mgt.xml") # testng_server_mgt_destination = Path(cm.workspace + "/" + cm.product_id + "/" + TESTNG_SERVER_MGT_DIST) # # replace testng source # cm.replace_file(testng_source, testng_destination) # # replace testng server mgt source # cm.replace_file(testng_server_mgt_source, testng_server_mgt_destination) def build_source_without_tests(source_path): """Build the product-source. """ logger.info('Building the source skipping tests') if sys.platform.startswith('win'): subprocess.call(['mvn', 'clean', 'install', '-B', '-e','-Dmaven.test.skip=true'], shell=True, cwd=source_path) else: subprocess.call(['mvn', 'clean', 'install', '-B', '-e', '-Dmaven.test.skip=true'], cwd=source_path) logger.info('Module build is completed. Module: ' + str(source_path)) if __name__ == "__main__": main()
[ 2, 15069, 357, 66, 8, 2864, 11, 370, 15821, 17, 3457, 13, 357, 4023, 1378, 86, 568, 17, 13, 785, 8, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198,...
2.816679
1,331
# Copyright (c) 2019 Leiden University Medical Center # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import subprocess import sys from pathlib import Path SOUNDS_DIR = (Path(__file__).parent / Path("sounds")).absolute() DEFAULT_SUCCESS_SOUND = SOUNDS_DIR / Path("applause") DEFAULT_FAIL_SOUND = SOUNDS_DIR / Path("buzzer") def _play_sound_unix(sound_file: Path, program): """ Play a sound file on unix with the program. :param sound_file: Path to the sound file. :param program: Which program to use. :return: No returns. Plays a sound file. """ # Play the sound non blocking, use Popen. subprocess.Popen([program, str(sound_file)])
[ 2, 15069, 357, 66, 8, 13130, 1004, 14029, 2059, 8366, 3337, 198, 2, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 257, 4866, 198, 2, 286, 428, 3788, 290, 3917, 10314, 3696, 357, 1169, 366, 2...
3.421589
491
from math import sqrt
[ 6738, 10688, 1330, 19862, 17034, 198 ]
3.666667
6
#!/usr/bin/env python3 # Copyright (c) 2016 Anki, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License in the file LICENSE.txt or at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. '''"If This Then That" Gmail example This example demonstrates how "If This Then That" (http://ifttt.com) can be used make Cozmo respond when a Gmail account receives an email. Instructions below will lead you through setting up an applet on the IFTTT website. When the applet trigger is called (which sends a web request received by the web server started in this example), Cozmo will play an animation, speak the email sender's name and show a mailbox image on his face. Please place Cozmo on the charger for this example. When necessary, he will be rolled off and back on. Follow these steps to set up and run the example: 1) Provide a a static ip, URL or similar that can be reached from the If This Then That server. One easy way to do this is with ngrok, which sets up a secure tunnel to localhost running on your machine. To set up ngrok: a) Follow instructions here to download and install: https://ngrok.com/download b) Run this command to create a secure public URL for port 8080: ./ngrok http 8080 c) Note the HTTP forwarding address shown in the terminal (e.g., http://55e57164.ngrok.io). You will use this address in your applet, below. WARNING: Using ngrok exposes your local web server to the internet. See the ngrok documentation for more information: https://ngrok.com/docs 2) Set up your applet on the "If This Then That" website. a) Sign up and sign into https://ifttt.com b) Create an applet: https://ifttt.com/create c) Set up your trigger. 1. Click "this". 2. Select "Gmail" as your service. If prompted, click "Connect", select your Gmail account, and click Allow to provide permissions to IFTTT for your email account. Click "Done". 3. Under "Choose a Trigger", select Any new email in inbox". d) Set up your action. 1. Click that". 2. Select Maker" to set it as your action channel. Connect to the Maker channel if prompted. 3. Click Make a web request" and fill out the fields as follows. Remember your publicly accessible URL from above (e.g., http://55e57164.ngrok.io) and use it in the URL field, followed by "/iftttGmail" as shown below: URL: http://55e57164.ngrok.io/iftttGmail Method: POST Content Type: application/json Body: {"FromAddress":"{{FromAddress}}"} 5. Click Create Action" then Finish". 3) Test your applet. a) Run this script at the command line: ./ifttt_gmail.py b) On ifttt.com, on your applet page, click Check now. See that IFTTT confirms that the applet was checked. c) Send an email to the Gmail account in your recipe d) On your IFTTT applet webpage, again click Check now. This should cause IFTTT to detect that the email was received and send a web request to the ifttt_gmail.py script. e) In response to the ifttt web request, Cozmo should roll off the charger, raise and lower his lift, announce the email, and then show a mailbox image on his face. ''' import asyncio import re import sys try: from aiohttp import web except ImportError: sys.exit("Cannot import from aiohttp. Do `pip3 install --user aiohttp` to install") import cozmo from common import IFTTTRobot app = web.Application() # Attach the function as an HTTP handler. app.router.add_post('/iftttGmail', serve_gmail) if __name__ == '__main__': cozmo.setup_basic_logging() cozmo.robot.Robot.drive_off_charger_on_connect = False # Use our custom robot class with extra helper methods cozmo.conn.CozmoConnection.robot_factory = IFTTTRobot try: sdk_conn = cozmo.connect_on_loop(app.loop) # Wait for the robot to become available and add it to the app object. app['robot'] = app.loop.run_until_complete(sdk_conn.wait_for_robot()) except cozmo.ConnectionError as e: sys.exit("A connection error occurred: %s" % e) web.run_app(app)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 2, 15069, 357, 66, 8, 1584, 1052, 4106, 11, 3457, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 7...
2.803269
1,713
# -*- coding: utf-8 -*- """ Created on Fri May 30 17:15:27 2014 @author: Parke """ from __future__ import division, print_function, absolute_import import numpy as np import matplotlib as mplot import matplotlib.pyplot as plt import mypy.my_numpy as mnp dpi = 100 fullwidth = 10.0 halfwidth = 5.0 # use these with line.set_dashes and iterate through more linestyles than come with matplotlib # consider ussing a ::2 slice for fewer dashes = [[], [30, 10], [20, 8], [10, 5], [3, 2], [30, 5, 3, 5, 10, 5, 3, 5], [15] + [5, 3]*3 + [5], [15] + [5, 3]*2 + [5], [15] + [5, 3] + [5]] def textSize(ax_or_fig=None, coordinate='data'): """ Return x & y scale factors for converting text sizes in points to another coordinate. Useful for properly spacing text labels and such when you need to know sizes before the text is made (otherwise you can use textBoxSize). Coordinate can be 'data', 'axes', or 'figure'. If data coordinates are requested and the data is plotted on a log scale, then the factor will be given in dex. """ if ax_or_fig is None: fig = plt.gcf() ax = fig.gca() else: if isinstance(ax_or_fig, plt.Figure): fig = ax_or_fig ax = fig.gca() elif isinstance(ax_or_fig, plt.Axes): ax = ax_or_fig fig = ax.get_figure() else: raise TypeError('ax_or_fig must be a Figure or Axes instance, if given.') w_fig_in, h_fig_in = ax.get_figure().get_size_inches() if coordinate == 'fig': return 1.0/(w_fig_in*72), 1.0/(h_fig_in*72) w_ax_norm, h_ax_norm = ax.get_position().size w_ax_in = w_ax_norm * w_fig_in h_ax_in = h_ax_norm * h_fig_in w_ax_pts, h_ax_pts = w_ax_in*72, h_ax_in*72 if coordinate == 'axes': return 1.0/w_ax_pts, 1.0/h_ax_pts if coordinate == 'data': xlim = ax.get_xlim() ylim = ax.get_ylim() if ax.get_xscale() == 'log': xlim = np.log10(xlim) if ax.get_yscale() == 'log': ylim = np.log10(ylim) w_ax_data = xlim[1] - xlim[0] h_ax_data = ylim[1] - ylim[0] return w_ax_data/w_ax_pts, h_ax_data/h_ax_pts #TODO: discard this function? def standard_figure(app, slideAR=1.6, height=1.0): """Generate a figure of standard size for publishing. implemented values for app (application) are: 'fullslide' height is the fractional height of the figure relative to the "standard" height. For slides the standard is the full height of a slide. returns the figure object and default font size """ if app == 'fullslide': fontsize = 20 figsize = [fullwidth, fullwidth/slideAR*height] fig = mplot.pyplot.figure(figsize=figsize, dpi=dpi) mplot.rcParams.update({'font.size': fontsize}) return fig, fontsize def pcolor_reg(x, y, z, **kw): """ Similar to `pcolor`, but assume that the grid is uniform, and do plotting with the (much faster) `imshow` function. """ x, y, z = np.asarray(x), np.asarray(y), np.asarray(z) if x.ndim != 1 or y.ndim != 1: raise ValueError("x and y should be 1-dimensional") if z.ndim != 2 or z.shape != (y.size, x.size): raise ValueError("z.shape should be (y.size, x.size)") dx = np.diff(x) dy = np.diff(y) if not np.allclose(dx, dx[0], 1e-2) or not np.allclose(dy, dy[0], 1e-2): raise ValueError("The grid must be uniform") if np.issubdtype(z.dtype, np.complexfloating): zp = np.zeros(z.shape, float) zp[...] = z[...] z = zp plt.imshow(z, origin='lower', extent=[x.min(), x.max(), y.min(), y.max()], interpolation='nearest', aspect='auto', **kw) plt.axis('tight') def onscreen_pres(mpl, screenwidth=1200): """ Set matplotlibrc values so that plots are readable as they are created and maximized for an audience far from a screen. Parameters ---------- mpl : module Current matplotlib module. Use 'import matplotlib as mpl'. screewidth : int Width of the screen in question in pixels. Returns ------- None """ mpl.rcParams['lines.linewidth'] = 2 fontsize = round(14 / (800.0 / screenwidth)) mpl.rcParams['font.size'] = fontsize def textBoxSize(txt, transformation=None, figure=None): """Get the width and height of a text object's bounding box transformed to the desired coordinates. Defaults to figure coordinates if transformation is None.""" fig= txt.get_figure() if figure is None else figure if transformation is None: transformation = fig.transFigure coordConvert = transformation.inverted().transform bboxDisp = txt.get_window_extent(fig.canvas.renderer) bboxConv = coordConvert(bboxDisp) w = bboxConv[1,0] - bboxConv[0,0] h = bboxConv[1,1] - bboxConv[0,1] return w, h def stars3d(ra, dec, dist, T=5000.0, r=1.0, labels='', view=None, size=(800,800), txt_scale=1.0): """ Make a 3D diagram of stars positions relative to the Sun, with semi-accurate colors and distances as desired. Coordinates must be in degrees. Distance is assumed to be in pc (for axes labels). Meant to be used with only a handful of stars. """ from mayavi import mlab from color.maps import true_temp n = len(ra) dec, ra = dec*np.pi/180.0, ra*np.pi/180.0 makearr = lambda v: np.array([v] * n) if np.isscalar(v) else v T, r, labels = list(map(makearr, (T, r, labels))) # add the sun ra, dec, dist = list(map(np.append, (ra, dec, dist), (0.0, 0.0, 0.0))) r, T, labels = list(map(np.append, (r, T, labels), (1.0, 5780.0, 'Sun'))) # get xyz coordinates z = dist * np.sin(dec) h = dist * np.cos(dec) x = h * np.cos(ra) y = h * np.sin(ra) # make figure fig = mlab.figure(bgcolor=(0,0,0), fgcolor=(1,1,1), size=size) # plot lines down to the dec=0 plane for all but the sun lines = [] for x1, y1, z1 in list(zip(x, y, z))[:-1]: xx, yy, zz = [x1, x1], [y1, y1], [0.0, z1] line = mlab.plot3d(xx, yy, zz, color=(0.7,0.7,0.7), line_width=0.5, figure=fig) lines.append(line) # plot spheres r_factor = np.max(dist) / 30.0 pts = mlab.quiver3d(x, y, z, r, r, r, scalars=T, mode='sphere', scale_factor=r_factor, figure=fig, resolution=100) pts.glyph.color_mode = 'color_by_scalar' # center the glyphs on the data point pts.glyph.glyph_source.glyph_source.center = [0, 0, 0] # set a temperature colormap cmap = true_temp(T) pts.module_manager.scalar_lut_manager.lut.table = cmap # set the camera view mlab.view(focalpoint=(0.0, 0.0, 0.0), figure=fig) if view is not None: mlab.view(*view, figure=fig) ## add labels # unit vec to camera view = mlab.view() az, el = view[:2] hc = np.sin(el * np.pi / 180.0) xc = hc * np.cos(az * np.pi / 180.0) yc = hc * np.sin(az * np.pi / 180.0) zc = -np.cos(el * np.pi / 180.0) # unit vec orthoganal to camera if xc**2 + yc**2 == 0.0: xoff = 1.0 yoff = 0.0 zoff = 0.0 else: xoff = yc / np.sqrt(xc**2 + yc**2) yoff = np.sqrt(1.0 - xoff**2) zoff = 0.0 # xoff, yoff, zoff = xc, yc, zc # scale orthogonal vec by sphere size r_label = 1.0 * r_factor xoff, yoff, zoff = [r_label * v for v in [xoff, yoff, zoff]] # plot labels size = r_factor * txt_scale * 0.75 for xx, yy, zz, label in zip(x, y, z, labels): mlab.text3d(xx + xoff, yy + yoff, zz + zoff, label, figure=fig, color=(1,1,1), scale=size) ## add translucent dec=0 surface n = 101 t = np.linspace(0.0, 2*np.pi, n) r = np.max(dist * np.cos(dec)) x, y = r*np.cos(t), r*np.sin(t) z = np.zeros(n+1) x, y = [np.insert(a, 0, 0.0) for a in [x,y]] triangles = [(0, i, i + 1) for i in range(1, n)] mlab.triangular_mesh(x, y, z, triangles, color=(1,1,1), opacity=0.3, figure=fig) ## add ra=0 line line = mlab.plot3d([0, r], [0, 0], [0, 0], color=(1,1,1), line_width=1, figure=fig) rtxt = '{:.1f} pc'.format(r) orientation=np.array([180.0, 180.0, 0.0]) mlab.text3d(r, 0, 0, rtxt, figure=fig, scale=size*1.25, orient_to_camera=False, orientation=orientation) if view is not None: mlab.view(*view, figure=fig) return fig
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 19480, 1737, 1542, 1596, 25, 1314, 25, 1983, 1946, 198, 198, 31, 9800, 25, 2547, 365, 198, 37811, 198, 198, 6738, 11593, 37443, 834, 1330, 7297, ...
2.183726
3,908