content
stringlengths
1
1.04M
input_ids
listlengths
1
774k
ratio_char_token
float64
0.38
22.9
token_count
int64
1
774k
import platform from friendlyshell.basic_shell import BasicShell import pytest from mock import patch @pytest.mark.skipif(platform.python_implementation()=="PyPy", reason="Test not supported on PyPy") if __name__ == "__main__": pytest.main([__file__, "-v", "-s"])
[ 11748, 3859, 198, 6738, 8030, 29149, 13, 35487, 62, 29149, 1330, 14392, 23248, 198, 11748, 12972, 9288, 198, 6738, 15290, 1330, 8529, 628, 198, 31, 9078, 9288, 13, 4102, 13, 48267, 361, 7, 24254, 13, 29412, 62, 320, 32851, 3419, 855, ...
2.745283
106
import json import hashlib import base64
[ 11748, 33918, 198, 11748, 12234, 8019, 198, 11748, 2779, 2414, 198 ]
3.727273
11
import json import os import time from subprocess import call from threading import Thread import django from django.conf import settings from django.test import RequestFactory, TestCase from django.views.generic.base import TemplateView from django_jinja.builtins import DEFAULT_EXTENSIONS from unittest2 import skipIf from webpack_loader.exceptions import ( WebpackError, WebpackLoaderBadStatsError, WebpackLoaderTimeoutError, WebpackBundleLookupError ) from webpack_loader.utils import get_loader BUNDLE_PATH = os.path.join(settings.BASE_DIR, 'assets/bundles/') DEFAULT_CONFIG = 'DEFAULT'
[ 11748, 33918, 198, 11748, 28686, 198, 11748, 640, 198, 6738, 850, 14681, 1330, 869, 198, 6738, 4704, 278, 1330, 14122, 198, 198, 11748, 42625, 14208, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 9288, 1330,...
3.204188
191
from django.http import HttpRequest, HttpResponse from zerver.models import UserProfile from zerver.lib.actions import notify_attachment_update from zerver.lib.validator import check_int from zerver.lib.response import json_success from zerver.lib.attachments import user_attachments, remove_attachment, \ access_attachment_by_id
[ 6738, 42625, 14208, 13, 4023, 1330, 367, 29281, 18453, 11, 367, 29281, 31077, 198, 198, 6738, 1976, 18497, 13, 27530, 1330, 11787, 37046, 198, 6738, 1976, 18497, 13, 8019, 13, 4658, 1330, 19361, 62, 1078, 15520, 62, 19119, 198, 6738, 19...
3.438776
98
from multiprocessing import Process, Queue import warnings class ErrorInProcessException(RuntimeError): """Exception raised when one or more parallel processes raises an exception""" def run_parallel(*functions): """Runs a series of functions in parallel. Return values are ordered by the order in which their functions were passed. >>> val1, val2 = run_parallel( >>> lambda: 1 + 1 >>> lambda: 0 >>> ) If an exception is raised within one of the processes, that exception will be caught at the process level and raised by the parent process as an ErrorInProcessException, which will track all errors raised in all processes. You can catch the exception raised for more details into the process exceptions: >>> try: >>> val1, val2 = run_parallel(fn1, fn2) >>> except ErrorInProcessException, e: >>> print.e.errors @param functions: The functions to run specified as individual arguments @return: List of results for those functions. Unpacking is recommended if you do not need to iterate over the results as it enforces the number of functions you pass in. >>> val1, val2 = run_parallel(fn1, fn2, fn3) # Will raise an error >>> vals = run_parallel(fn1, fn2, fn3) # Will not raise an error @raise: ErrorInProcessException """ errors = Queue() queue = Queue() jobs = list() for i, function in enumerate(functions): jobs.append(Process(target=target(function), args=(queue, errors, i))) [job.start() for job in jobs] [job.join() for job in jobs] # Get the results in the queue and put them back in the order in which the function was specified in the args results = [queue.get() for _ in jobs] results = sorted(results, key=lambda x: x[0]) if not errors.empty(): error_list = list() while not errors.empty(): error_list.append(errors.get()) raise ErrorInProcessException('Exceptions raised in parallel threads: {}'.format(error_list), errors=error_list) return [r[1] for r in results]
[ 6738, 18540, 305, 919, 278, 1330, 10854, 11, 4670, 518, 198, 11748, 14601, 628, 198, 4871, 13047, 818, 18709, 16922, 7, 41006, 12331, 2599, 198, 220, 220, 220, 37227, 16922, 4376, 618, 530, 393, 517, 10730, 7767, 12073, 281, 6631, 37811...
2.995781
711
# Script to add the min and max mz values to feature objects # takes as input the path of a dictionary file that must have a 'features' key import os import pickle import numpy as np import sys os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ms2ldaviz.settings") import django django.setup() from basicviz.models import Feature,Experiment if __name__ == '__main__': infile = sys.argv[1] with open(infile,'r') as f: lda_dict = pickle.load(f) experiment_name = infile.split('/')[-1].split('.')[0] experiment = Experiment.objects.get(name = experiment_name) features = lda_dict['features'] n_features = len(features) ndone = 0 for feature in features: f = Feature.objects.get(name = feature,experiment = experiment) f.min_mz = features[feature][0] f.max_mz = features[feature][1] f.save() ndone += 1 if ndone % 100 == 0: print "Done {} of {}".format(ndone,n_features)
[ 2, 12327, 284, 751, 262, 949, 290, 3509, 285, 89, 3815, 284, 3895, 5563, 198, 2, 2753, 355, 5128, 262, 3108, 286, 257, 22155, 2393, 326, 1276, 423, 257, 705, 40890, 6, 1994, 198, 198, 11748, 28686, 198, 11748, 2298, 293, 198, 11748,...
2.746177
327
import os import json
[ 11748, 28686, 198, 11748, 33918, 198 ]
3.666667
6
# # Copyright (c) 2022 Airbyte, Inc., all rights reserved. # import importlib.resources as pkg_resources import os from pathlib import Path from typing import Iterable, Tuple import click from octavia_cli.base_commands import OctaviaCommand from . import example_files DIRECTORIES_TO_CREATE = {"connections", "destinations", "sources"} DEFAULT_API_HEADERS_FILE_CONTENT = pkg_resources.read_text(example_files, "example_api_http_headers.yaml") API_HTTP_HEADERS_TARGET_PATH = Path("api_http_headers.yaml") @click.command(cls=OctaviaCommand, help="Initialize required directories for the project.") @click.pass_context
[ 2, 198, 2, 15069, 357, 66, 8, 33160, 3701, 26327, 11, 3457, 1539, 477, 2489, 10395, 13, 198, 2, 198, 198, 11748, 1330, 8019, 13, 37540, 355, 279, 10025, 62, 37540, 198, 11748, 28686, 198, 6738, 3108, 8019, 1330, 10644, 198, 6738, 19...
3.183673
196
# python peripherals import random import os import sys import math sys.path.insert(1, os.path.join(sys.path[0], '../..')) # numpy import numpy # pandas import pandas # ipython from IPython.display import display, HTML # matplotlib import matplotlib.pyplot as plt import matplotlib.ticker as ticker import matplotlib.lines # pytorch import torch from torch.utils.data.sampler import SubsetRandomSampler from torch.utils.data.sampler import SequentialSampler from torch.utils.data import DataLoader # deep signature from deep_signature.utils import utils from deep_signature.data_generation.curve_generation import LevelCurvesGenerator from deep_signature.data_manipulation import curve_processing from deep_signature.nn.datasets import DeepSignatureTupletsDataset from deep_signature.nn.networks import DeepSignatureArcLengthNet from deep_signature.nn.networks import DeepSignatureCurvatureNet from deep_signature.nn.losses import ContrastiveLoss from deep_signature.nn.trainers import ModelTrainer from deep_signature.data_manipulation import curve_sampling from deep_signature.data_manipulation import curve_processing from deep_signature.linalg import euclidean_transform from deep_signature.linalg import affine_transform # common from common import settings from common import utils as common_utils # notebooks from notebooks.utils import utils as notebook_utils # plt.style.use("dark_background") transform_type = 'affine' if transform_type == 'euclidean': level_curves_arclength_tuplets_dir_path = settings.level_curves_euclidean_arclength_tuplets_dir_path level_curves_arclength_tuplets_results_dir_path = settings.level_curves_euclidean_arclength_tuplets_results_dir_path elif transform_type == 'equiaffine': level_curves_arclength_tuplets_dir_path = settings.level_curves_equiaffine_arclength_tuplets_dir_path level_curves_arclength_tuplets_results_dir_path = settings.level_curves_equiaffine_arclength_tuplets_results_dir_path elif transform_type == 'affine': level_curves_arclength_tuplets_dir_path = settings.level_curves_affine_arclength_tuplets_dir_path level_curves_arclength_tuplets_results_dir_path = settings.level_curves_affine_arclength_tuplets_results_dir_path if transform_type == 'euclidean': level_curves_curvature_tuplets_dir_path = settings.level_curves_euclidean_curvature_tuplets_dir_path level_curves_curvature_tuplets_results_dir_path = settings.level_curves_euclidean_curvature_tuplets_results_dir_path elif transform_type == 'equiaffine': level_curves_curvature_tuplets_dir_path = settings.level_curves_equiaffine_curvature_tuplets_dir_path level_curves_curvature_tuplets_results_dir_path = settings.level_curves_equiaffine_curvature_tuplets_results_dir_path elif transform_type == 'affine': level_curves_curvature_tuplets_dir_path = settings.level_curves_affine_curvature_tuplets_dir_path level_curves_curvature_tuplets_results_dir_path = settings.level_curves_affine_curvature_tuplets_results_dir_path import warnings warnings.filterwarnings("ignore") # constants true_arclength_colors = ['#FF8C00', '#444444'] predicted_arclength_colors = ['#AA0000', '#00AA00'] sample_colors = ['#AA0000', '#00AA00'] curve_colors = ['#AA0000', '#00AA00'] limit = 5 step = 60 comparison_curves_count = 1 section_supporting_points_count = 20 neighborhood_supporting_points_count = 3 curvature_sample_points = 2*neighborhood_supporting_points_count + 1 arclength_sample_points = section_supporting_points_count sampling_ratio = 0.2 anchors_ratio = 0.2 device = torch.device('cuda') # if we're in the equiaffine case, snap 'step' to the closest mutiple of 3 (from above) # if transform_type == "equiaffine": # step = int(3 * numpy.ceil(step / 3)) # package settings torch.set_default_dtype(torch.float64) numpy.random.seed(60) # create models arclength_model = DeepSignatureArcLengthNet(sample_points=arclength_sample_points).cuda() curvature_model = DeepSignatureCurvatureNet(sample_points=curvature_sample_points).cuda() # load arclength model state latest_subdir = common_utils.get_latest_subdirectory(level_curves_arclength_tuplets_results_dir_path) results = numpy.load(f"{latest_subdir}/results.npy", allow_pickle=True).item() arclength_model.load_state_dict(torch.load(results['model_file_path'], map_location=device)) arclength_model.eval() # load curvature model state latest_subdir = common_utils.get_latest_subdirectory(level_curves_curvature_tuplets_results_dir_path) results = numpy.load(f"{latest_subdir}/results.npy", allow_pickle=True).item() curvature_model.load_state_dict(torch.load(results['model_file_path'], map_location=device)) curvature_model.eval() # load curves (+ shuffle) curves = LevelCurvesGenerator.load_curves(dir_path=settings.level_curves_dir_path_train) numpy.random.shuffle(curves) curves = curves[:limit] # create color map color_map = plt.get_cmap('rainbow', limit) # generate curve records curve_records = notebook_utils.generate_curve_records( arclength_model=arclength_model, curvature_model=curvature_model, curves=curves, transform_type=transform_type, comparison_curves_count=comparison_curves_count, sampling_ratio=sampling_ratio, anchors_ratio=anchors_ratio, step=step, neighborhood_supporting_points_count=neighborhood_supporting_points_count, section_supporting_points_count=section_supporting_points_count) notebook_utils.plot_curve_signature_comparisons( curve_records=curve_records, curve_colors=curve_colors) notebook_utils.plot_curve_arclength_records( curve_records=curve_records, true_arclength_colors=true_arclength_colors, predicted_arclength_colors=predicted_arclength_colors, sample_colors=sample_colors)
[ 2, 21015, 18375, 874, 198, 11748, 4738, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 10688, 198, 17597, 13, 6978, 13, 28463, 7, 16, 11, 28686, 13, 6978, 13, 22179, 7, 17597, 13, 6978, 58, 15, 4357, 705, 40720, 492, 6, 4008, 198...
2.767375
2,072
from django.shortcuts import render from met.models import Artist from api.serializers import ArtistSerializer from rest_framework import generics, permissions, status, viewsets from rest_framework.response import Response class ArtistViewSet(viewsets.ModelViewSet): """ This ViewSet provides both 'list' and 'detail' views. """ queryset = Artist.objects.all().order_by('artist_display_name') serializer_class = ArtistSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
[ 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 198, 6738, 1138, 13, 27530, 1330, 18902, 220, 198, 6738, 40391, 13, 46911, 11341, 1330, 18902, 32634, 7509, 198, 6738, 1334, 62, 30604, 1330, 1152, 873, 11, 21627, 11, 3722, 11, 5009, 10...
3.625899
139
from datetime import datetime, timedelta, timezone from collections import deque from math import sqrt from time import monotonic from logging import getLogger from pkg_resources import resource_stream from tempfile import NamedTemporaryFile from .utils import load_pickle, dump_pickle from .db import Session, get_pokemon_ranking, estimate_remaining_time from .names import POKEMON_NAMES, MOVES from . import config # set unset config options to None for variable_name in ('PB_API_KEY', 'PB_CHANNEL', 'TWITTER_CONSUMER_KEY', 'TWITTER_CONSUMER_SECRET', 'TWITTER_ACCESS_KEY', 'TWITTER_ACCESS_SECRET', 'LANDMARKS', 'AREA_NAME', 'HASHTAGS', 'TZ_OFFSET', 'ENCOUNTER', 'INITIAL_RANKING', 'NOTIFY', 'NAME_FONT', 'IV_FONT', 'MOVE_FONT', 'TWEET_IMAGES', 'NOTIFY_IDS', 'NEVER_NOTIFY_IDS', 'RARITY_OVERRIDE', 'IGNORE_IVS', 'IGNORE_RARITY', 'WEBHOOKS'): if not hasattr(config, variable_name): setattr(config, variable_name, None) _optional = { 'ALWAYS_NOTIFY': 9, 'FULL_TIME': 1800, 'TIME_REQUIRED': 300, 'NOTIFY_RANKING': 90, 'ALWAYS_NOTIFY_IDS': set(), 'NOTIFICATION_CACHE': 100 } # set defaults for unset config options for setting_name, default in _optional.items(): if not hasattr(config, setting_name): setattr(config, setting_name, default) del _optional if config.NOTIFY: WEBHOOK = False TWITTER = False PUSHBULLET = False if all((config.TWITTER_CONSUMER_KEY, config.TWITTER_CONSUMER_SECRET, config.TWITTER_ACCESS_KEY, config.TWITTER_ACCESS_SECRET)): try: import twitter from twitter.twitter_utils import calc_expected_status_length except ImportError as e: raise ImportError("You specified a TWITTER_ACCESS_KEY but you don't have python-twitter installed.") from e TWITTER=True if config.TWEET_IMAGES: if not config.ENCOUNTER: raise ValueError('You enabled TWEET_IMAGES but ENCOUNTER is not set.') try: import cairo except ImportError as e: raise ImportError('You enabled TWEET_IMAGES but Cairo could not be imported.') from e if config.PB_API_KEY: try: from pushbullet import Pushbullet except ImportError as e: raise ImportError("You specified a PB_API_KEY but you don't have pushbullet.py installed.") from e PUSHBULLET=True if config.WEBHOOKS: if not isinstance(config.WEBHOOKS, (set, list, tuple)): raise ValueError('WEBHOOKS must be a set of addresses.') try: import requests except ImportError as e: raise ImportError("You specified a WEBHOOKS address but you don't have requests installed.") from e WEBHOOK = True NATIVE = TWITTER or PUSHBULLET if not (NATIVE or WEBHOOK): raise ValueError('NOTIFY is enabled but no keys or webhook address were provided.') try: if config.INITIAL_SCORE < config.MINIMUM_SCORE: raise ValueError('INITIAL_SCORE should be greater than or equal to MINIMUM_SCORE.') except TypeError: raise AttributeError('INITIAL_SCORE or MINIMUM_SCORE are not set.') if config.NOTIFY_RANKING and config.NOTIFY_IDS: raise ValueError('Only set NOTIFY_RANKING or NOTIFY_IDS, not both.') elif not any((config.NOTIFY_RANKING, config.NOTIFY_IDS, config.ALWAYS_NOTIFY_IDS)): raise ValueError('Must set either NOTIFY_RANKING, NOTIFY_IDS, or ALWAYS_NOTIFY_IDS.')
[ 6738, 4818, 8079, 1330, 4818, 8079, 11, 28805, 12514, 11, 640, 11340, 198, 6738, 17268, 1330, 390, 4188, 198, 6738, 10688, 1330, 19862, 17034, 198, 6738, 640, 1330, 937, 313, 9229, 198, 6738, 18931, 1330, 651, 11187, 1362, 198, 6738, 27...
2.278882
1,610
# uncompyle6 version 3.4.1 # Python bytecode 2.7 (62211) # Decompiled from: Python 2.7.16 (v2.7.16:413a49145e, Mar 2 2019, 14:32:10) # [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] # Embedded file name: /Users/versonator/Jenkins/live/output/mac_64_static/Release/python-bundle/MIDI Remote Scripts/SL_MkIII/skin.py # Compiled at: 2019-04-23 14:43:03 from __future__ import absolute_import, print_function, unicode_literals from ableton.v2.control_surface import Skin from .colors import Rgb skin = Skin(Colors)
[ 2, 34318, 2349, 21, 2196, 513, 13, 19, 13, 16, 198, 2, 11361, 18022, 8189, 362, 13, 22, 357, 21, 1828, 1157, 8, 198, 2, 4280, 3361, 3902, 422, 25, 11361, 362, 13, 22, 13, 1433, 357, 85, 17, 13, 22, 13, 1433, 25, 44103, 64, 2...
2.558824
204
med=0 c=0 while c!=2: n=float(input()) if n>=0 and n<=10: med=med+n c=c+1 else: print("nota invalida") med=med/2 print("media = %.2f" %med)
[ 1150, 28, 15, 198, 66, 28, 15, 198, 4514, 269, 0, 28, 17, 25, 198, 220, 220, 220, 220, 299, 28, 22468, 7, 15414, 28955, 198, 220, 220, 220, 220, 611, 299, 29, 28, 15, 290, 299, 27, 28, 940, 25, 198, 220, 220, 220, 220, 220, ...
1.603448
116
for _ in range(int(input())): A, B, C, D = map(int, input().split()) if A < B or C + D < B: print("No") continue elif C >= B - 1: print("Yes") continue ret = [] s_set = set() now = A while True: now %= B if now in s_set: print("Yes", ret) break else: s_set.add(now) if now <= C: now += D ret.append(now) else: print("No", ret) break
[ 1640, 4808, 287, 2837, 7, 600, 7, 15414, 28955, 2599, 198, 220, 220, 220, 317, 11, 347, 11, 327, 11, 360, 796, 3975, 7, 600, 11, 5128, 22446, 35312, 28955, 198, 220, 220, 220, 611, 317, 1279, 347, 393, 327, 1343, 360, 1279, 347, ...
1.689542
306
''' A.Q. Snyder TFR Tire Data Analysis this code is written to analyze the TTC FSAE tire data the code is written in a linear, easy to read format catered towards an engineering mindset rather than efficient software Contact: aaron.snyder@temple.edu for help running or understanding the program ''' #_______________________________________________________________________________________________________________________ import matplotlib.pyplot as plt import pandas as pd import numpy as np #run_input = input("Enter the run number you want to study: ") # example of input B1965run2 run_input = 'B1965run2' data = pd.read_excel (r'C:\Users\Fizics\Desktop\TTC\data\RunData_cornering_ASCII_SI_10in_round8 excel/'+(run_input)+(".xlsx"),skiprows=2) df = pd.DataFrame(data) df = df.drop(df.index[0:5000]) # SI Units are being used # This varaibles are mostly used in the splash graph. You can add whatever other variables you want to look at speed=df["V"] # kph pressure=df["P"] # kPa inclinationAngle=df["IA"] # deg slipAngle = df["SA"] # deg verticalLoad = df["FZ"] * -1 # N Radius_loaded=df["RL"] # cm lateralForce = df["FY"] # N alignTorque = df["MZ"] # Nm slipAngle = np.array(slipAngle) verticalLoad = np.array(verticalLoad) lateralForce = np.array(lateralForce) Z1 = np.where(np.logical_and(verticalLoad>= 0, verticalLoad<=320)) Z2 = np.where(np.logical_and(verticalLoad>= 320, verticalLoad<=550)) Z3 = np.where(np.logical_and(verticalLoad>= 550, verticalLoad<=750)) Z4 = np.where(np.logical_and(verticalLoad>= 750, verticalLoad<=950)) Z5 = np.where(np.logical_and(verticalLoad>= 980, verticalLoad<=1200)) labelAvgZ1 = str(np.round(np.average(verticalLoad[Z1])))+(' N') labelAvgZ2 = str(np.round(np.average(verticalLoad[Z2])))+(' N') labelAvgZ3 = str(np.round(np.average(verticalLoad[Z3])))+(' N') labelAvgZ4 = str(np.round(np.average(verticalLoad[Z4])))+(' N') labelAvgZ5 = str(np.round(np.average(verticalLoad[Z5])))+(' N') d = 10 x1 = np.flip(np.sort(slipAngle[Z1])) y1 = np.sort(lateralForce[Z1]) curve1 = np.polyfit(x1,y1,d) poly1 = np.poly1d(curve1) x2 = np.flip(np.sort(slipAngle[Z2])) y2 = np.sort(lateralForce[Z2]) curve2 = np.polyfit(x2,y2,d) poly2 = np.poly1d(curve2) x3 = np.flip(np.sort(slipAngle[Z3])) y3 = np.sort(lateralForce[Z3]) curve3 = np.polyfit(x3,y3,d) poly3 = np.poly1d(curve3) x4 = np.flip(np.sort(slipAngle[Z4])) y4 = np.sort(lateralForce[Z4]) curve4 = np.polyfit(x4,y4,d) poly4 = np.poly1d(curve4) x5 = np.flip(np.sort(slipAngle[Z5])) y5 = np.sort(lateralForce[Z5]) curve5 = np.polyfit(x5,y5,d) poly5 = np.poly1d(curve5) fig1 = plt.figure(figsize = (10,7)) ax1 = plt.axes(projection="3d") ax1.scatter3D(slipAngle[Z1],lateralForce[Z1],verticalLoad[Z1],marker = 'x',linewidths=0.08,color = 'midnightblue') ax1.scatter3D(slipAngle[Z2],lateralForce[Z2],verticalLoad[Z2],marker = 'x',linewidths=0.08,color = 'mediumblue') ax1.scatter3D(slipAngle[Z3],lateralForce[Z3],verticalLoad[Z3],marker = 'x',linewidths=0.08,color = 'slateblue') ax1.scatter3D(slipAngle[Z4],lateralForce[Z4],verticalLoad[Z4],marker = 'x',linewidths=0.08,color = 'mediumpurple') ax1.scatter3D(slipAngle[Z5],lateralForce[Z5],verticalLoad[Z5],marker = 'x',linewidths=0.08,color = 'plum') ax1.plot(x1, poly1(x1), c='lime', label=labelAvgZ1) ax1.plot(x2, poly2(x2), c='lime', label=labelAvgZ1) ax1.plot(x4, poly4(x4), c='lime', label=labelAvgZ1) ax1.plot(x5, poly5(x5), c='lime', label=labelAvgZ1) ax1.set_xlabel('Slip Angle') ax1.set_ylabel('Lateral Force') ax1.set_zlabel('Vertical Load') plt.show()
[ 7061, 6, 198, 32, 13, 48, 13, 22543, 198, 10234, 49, 45942, 6060, 14691, 198, 5661, 2438, 318, 3194, 284, 16602, 262, 42662, 42894, 36, 15867, 1366, 198, 1169, 2438, 318, 3194, 287, 257, 14174, 11, 2562, 284, 1100, 5794, 269, 34190, ...
2.338635
1,509
from clickhouse_driver import Client from utils import * from configs.default import * def connect_db(): ''' Creates a connection to the CLickhouse database. :return: Error if some exception occurred else tuple containing connection object and None. ''' try: client = Client(host='localhost') except Exception as e: print("Exception:", e) return None, e return client, None def get_data_path(gcs_client, db_name): ''' :return: ''' query = "SELECT metadata_path FROM system.tables WHERE database == '%s' limit 1" % (db_name) try: result = gcs_client.execute(query) global_path = '/'.join(result[0][0].split('/')[:4]) except Exception as e: print("Exception:", e) return None, e return global_path, None def freeze_partitions(clickhouse_client, db_name, table_name, start_date, end_date): ''' Freeze the partitions that falls between the given dates. :param clickhouse_client: :param db_name: :param table_name: :param start_date: :param end_date: :return: Error if some exception occurred else tuple containing list of partitions that got freeze and None. ''' query = """select distinct partition_id from system.parts where database='%s' and table='%s' and partition_id>='%s' and partition_id<='%s'""" % \ (db_name, table_name, start_date, end_date) try: partitions = clickhouse_client.execute(query) partitions = list(map(lambda x: x[0], partitions)) for partition in partitions: query = "ALTER TABLE `%s`.%s FREEZE PARTITION ID '%s';" % (db_name, table_name, partition) clickhouse_client.execute(query) except Exception as e: print("Exception:", e) return None, e return partitions, None def delete_partitions(clickhouse_client, db_name, table_name, partitions): ''' Drops the partitions from the given table. :param clickhouse_client: :param db_name: :param table_name: :param partitions: :return: Error if some exception is raised else None. ''' try: for partition in partitions: query = "ALTER TABLE `%s`.%s DROP PARTITION ID '%s';" % (db_name, table_name, partition) clickhouse_client.execute(query) except Exception as e: print("Exception:", e) return e def attach_partitions(clickhouse_client, db_name, table_name, partitions): ''' Attach the partitions to the specified table. :param clickhouse_client: :param db_name: :param table_name: :param partitions: :return: Error if some exception is raised else None ''' """List of partitions will be something like ['20190424_122_122_0_113', '20190425_110_110_0_113', '20190427_111_111_0_113'] so we need to split each one by '_' and get the first element.""" try: for partition in partitions: query = "ALTER TABLE `%s`.%s ATTACH PARTITION ID '%s';" % (db_name, table_name, partition.split('_')[0]) clickhouse_client.execute(query) except Exception as e: print("Exception:", e) return e def move_from_shadow(db_name, table_name): ''' Move the freezed partitions into backup folder :return: Error if some exception is raised else None ''' try: data_path = "data/%s/%s/" % (db_name.replace("-", "%2D"), table_name) for folder in os.listdir(SHADOW_PATH): if folder == "increment.txt": continue partitions_path = os.path.join(SHADOW_PATH, folder, data_path) for partition in os.listdir(partitions_path): src_path = os.path.join(partitions_path, partition) copy_dir(src_path, BACKUP_PATH) except Exception as e: print("Exception :", e) return e def move_to_detached(db_name, table_name): ''' Move the backup partitions into the detached folder :return: Error if some exception is raised else a tuple containing list of partitions moved to detached and None. ''' try: detached_path = os.path.join(GLOBAL_PATH, "data", db_name.replace("-", "%2D"), table_name, "detached") restore_backup_path = os.path.join(RESTORE_PATH, "backup") partitions = os.listdir(restore_backup_path) for partition in partitions: partition_path = os.path.join(restore_backup_path, partition) copy_dir(partition_path, detached_path) except Exception as e: print("Exception:", e) return None, e return partitions, None
[ 6738, 3904, 4803, 62, 26230, 1330, 20985, 198, 6738, 3384, 4487, 1330, 1635, 198, 6738, 4566, 82, 13, 12286, 1330, 1635, 628, 198, 4299, 2018, 62, 9945, 33529, 198, 220, 220, 220, 705, 7061, 198, 220, 220, 220, 7921, 274, 257, 4637, ...
2.537954
1,818
from tasks.models import Task, TaskTaken from issues.models import Issue from django.conf import settings from django.db.models import Q from django.db import transaction from django.shortcuts import render_to_response, get_object_or_404, redirect from django.contrib.auth.decorators import login_required from django.template import RequestContext from django.utils.translation import ugettext_lazy as _ import datetime @login_required @transaction.commit_on_success @login_required
[ 6738, 8861, 13, 27530, 1330, 15941, 11, 15941, 51, 1685, 198, 6738, 2428, 13, 27530, 1330, 18232, 198, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 9945, 13, 27530, 1330, 1195, 198, 6738, 42625, 14208, 13...
3.521429
140
from pathlib import Path from typing import Any, Optional, Union from pydantic import BaseModel, BaseSettings, Extra, Field SettingsField = Field # noqa """Extendable settings field""" class BaseDynaconf: """Extendable model""" def _d_get_value(self, key: str, default: Any = None) -> Any: """Get a setting value. :param key: The setting key :param default: The default value to return if the setting is not found or an exception to raise if the setting is not found. :return: The setting value - This is called only when the attribute is not found in the instance. - if the key has `__` in it, it is treated as a compound setting. (__ will be replaced with . to get the key) - If the key is a dot separated path, e.g. 'a.b.c', it will be split into a list of keys and passed to d_get_value for recursive nesting lookup. - try to get a swaped case A -> b, B -> a, etc. - try to get a lower case version of the key - try to get an uppercase version of the key - if the final value is a callable it will be called with the key + settings instance as arguments. """ if "__" in key or "." in key: key = key.replace("__", ".") head, *tail = key.split(".") return self._d_get_value( head, default )._d_get_value( ".".join(tail), default ) for lookup_key in ( key.swapcase(), key.lower(), key.upper(), ): try: return self.__getattribute__(lookup_key) except AttributeError: continue if issubclass(default, Exception): raise default( f"'{self.__class__.__name__}' object has no attribute '{key}'" ) return default(key, self) if callable(default) else default def __getattr__(self, name: str) -> Any: """Get a setting value by its attribute name.""" return self._d_get_value(name, default=AttributeError) def __getitem__(self, key: str) -> Any: """Get a setting value by its key name (simulate a dictionary). try to get the get as an attribute as it is if an exception is raised then try the get_value lookup. """ try: return getattr(self, key) except AttributeError: return self._d_get_value(key, default=KeyError) def get(self, key: str, default: Any = None) -> Any: """Get a setting value by its key name. Delegate to __getitem__ to simulate a dictionary. :param key: The setting key :param default: The default value to return if the setting is not found :return: The setting value """ try: return self[key] except KeyError: return default class SubModel(BaseDynaconf, BaseModel): """A Type for compound settings. Represents a Dict under a Dynaconf object. """ class Dynaconf(BaseDynaconf, BaseSettings): """Settings Management.""" class Config(BaseSettings.Config): """Settings Configuration.""" env_prefix = "DYNACONF_" env_file = None env_file_encoding = 'utf-8' secrets_dir = None validate_all = True extra = Extra.allow arbitrary_types_allowed = True case_sensitive = False __config__: Config # type: ignore
[ 6738, 3108, 8019, 1330, 10644, 198, 6738, 19720, 1330, 4377, 11, 32233, 11, 4479, 198, 198, 6738, 279, 5173, 5109, 1330, 7308, 17633, 11, 7308, 26232, 11, 17221, 11, 7663, 628, 198, 26232, 15878, 796, 7663, 220, 1303, 645, 20402, 198, ...
2.365756
1,501
from helper import unittest, PillowTestCase, hopper from PIL import Image if __name__ == '__main__': unittest.main() # End of file
[ 6738, 31904, 1330, 555, 715, 395, 11, 19770, 322, 14402, 20448, 11, 8169, 2848, 198, 198, 6738, 350, 4146, 1330, 7412, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 555, 715, 395, 13, 1...
2.745098
51
''' Functions Summary: This file contains Example: Usage of Todo: * ''' ''' Imports ''' # data array handling import numpy as np # data table handling import pandas as pd from operator import itemgetter from itertools import groupby ''' Current-Voltage File Format Parse Functions ''' def type_loana(file_path): ''' Parse HALM Current-Voltage Format Import current-voltage measurement settings and data from a HALM format file # inputs _file_path (str): full filepath Returns: dict: extracted data and parameters ''' #res = {} # open data file and extract lines with open(file_path, 'r', encoding = 'iso-8859-1') as file: lines = file.readlines() results = {} head_ids = [ i for i in range(len(lines)) if lines[i].startswith('[') ] tail_ids = [ i for i in range(len(lines)) if lines[i].startswith('\n') ] seg_ids = list(zip(head_ids, tail_ids)) for seg in seg_ids[:]: header = lines[seg[0]].strip('\n[]') results[header] = {} for j in range(seg[0]+1, seg[1]): val = lines[j].strip('\n').split('\t') results[header][val[0][:-1]] = val[1:] idx = [ i for i in range(len(lines)) if lines[i].startswith('**Data**') ][0] + 1 data = np.array([ [ float(l) for l in lines[i].strip('\n').split('\t') ] for i in range(idx, len(lines)) ]) #print(results.keys()) results['Data'] = data # open data file and extract lines with open(file_path[:-3]+'drk', 'r', encoding = 'iso-8859-1') as file: lines = file.readlines() dark_results = {} head_ids = [ i for i in range(len(lines)) if lines[i].startswith('[') ] tail_ids = [ i for i in range(len(lines)) if lines[i].startswith('\n') ] seg_ids = list(zip(head_ids, tail_ids)) for seg in seg_ids[:]: header = lines[seg[0]].strip('\n[]') dark_results[header] = {} for j in range(seg[0]+1, seg[1]): val = lines[j].strip('\n').split('\t') dark_results[header][val[0][:-1]] = val[1:] results['Dark'] = dark_results # open data file and extract lines with open(file_path[:-3]+'jv', 'r', encoding = 'iso-8859-1') as file: lines = file.readlines() jv_results = {} head_ids = [ i for i in range(len(lines)) if lines[i].startswith('[') ] tail_ids = [ i for i in range(len(lines)) if lines[i].startswith('\n') ] seg_ids = list(zip(head_ids, tail_ids)) for seg in seg_ids[:]: header = lines[seg[0]].strip('\n[]') jv_results[header] = {} for j in range(seg[0]+1, seg[1]): val = lines[j].strip('\n').split('\t') jv_results[header][val[0][:-1]] = val[1:] results['JV'] = jv_results keep = ['Results', 'Data', 'Sample', 'Dark', 'JV'] #keep = ['Results'] # only keep desired data results = { k:v for k,v in results.items() if k in keep } #print(results) #res = { **res, **{ '{}-{}'.format(ff,k):float(v[0]) for k,v in results['Results'].items() if k != 'Model' } } # return data dict return results def type_loana_bak(file_path): ''' Parse HALM Current-Voltage Format Import current-voltage measurement settings and data from a HALM format file # inputs _file_path (str): full filepath Returns: dict: extracted data and parameters ''' res = {} # iterate over loana data files for ff in ['lgt', 'drk', 'jv', ]: # open data file and extract lines with open(file_path[:-3]+ff, 'r', encoding = 'iso-8859-1') as file: lines = file.readlines() results = {} head_ids = [ i for i in range(len(lines)) if lines[i].startswith('[') ] tail_ids = [ i for i in range(len(lines)) if lines[i].startswith('\n') ] seg_ids = list(zip(head_ids, tail_ids)) for seg in seg_ids[:]: header = lines[seg[0]].strip('\n[]') results[header] = {} for j in range(seg[0]+1, seg[1]): val = lines[j].strip('\n').split('\t') results[header][val[0][:-1]] = val[1:] idx = [ i for i in range(len(lines)) if lines[i].startswith('**Data**') ][0] + 1 data = np.array([ [ float(l) for l in lines[i].strip('\n').split('\t') ] for i in range(idx, len(lines)) ]) results['data'] = data keep = ['Results',] # only keep desired data results = { k:v for k,v in results.items() if k in keep } #print(results) #if ff == 'lgt': #print(ff, results['Results']['Intensity']) #ff = '{}-{}'.format(ff,'{}s{}'.format( # *str(float(results['Results']['Intensity'][0])).split('.'))) #print(ff) res = { **res, **{ '{}-{}'.format(ff,k):float(v[0]) for k,v in results['Results'].items() if k != 'Model' } } # return data dict return res def loana(file_type, file_path, file_name): ''' Parse File Parse source data file of given format, run post parse processing, and return imported data Args: file_path (str): full file path including name with extension file_type (str): data file format information Returns: dict: parsed, processed data and parameters from file ''' # HALM IV if file_type == 'loana-bak': #if True: # import raw data from file data = type_loana_bak(file_path = '{}/{}'.format(file_path, file_name)) elif file_type == 'loana': # import raw data from file data = type_loana(file_path = '{}/{}'.format(file_path, file_name)) # return imported data return data
[ 198, 7061, 6, 40480, 198, 198, 22093, 25, 198, 220, 220, 220, 770, 2393, 4909, 198, 198, 16281, 25, 198, 220, 220, 220, 29566, 286, 198, 198, 51, 24313, 25, 198, 220, 220, 220, 1635, 198, 7061, 6, 628, 198, 198, 7061, 6, 1846, 3...
2.274283
2,512
# pylint: disable=missing-docstring from unittest.mock import Mock import pytest from peltak.core.hooks import HooksRegister
[ 2, 279, 2645, 600, 25, 15560, 28, 45688, 12, 15390, 8841, 198, 6738, 555, 715, 395, 13, 76, 735, 1330, 44123, 198, 198, 11748, 12972, 9288, 198, 198, 6738, 279, 2120, 461, 13, 7295, 13, 25480, 82, 1330, 18531, 82, 38804, 628, 628, ...
2.934783
46
""" Test datasets """ from fastapi.testclient import TestClient from main import app, PREFIX client = TestClient(app) EXAMPLE_DATASET_BODY = { "name": "Unit Test Dataset", "description": "Dataset created during a unit test", "labels": [ { "name": "Boolean", "variant": "boolean", }, { "name": "Numerical", "variant": "numerical", "minimum": -1, "maximum": 1, "interval": 0.5, }, ], } def test_get_datasets(): """Unit test for hitting the /datasets endpoint""" response = client.get(f"{PREFIX}/datasets") assert response.status_code == 200 def test_get_nonexistent_dataset(): """Unit test for trying to fetch a nonexistent dataset""" response = client.get(f"{PREFIX}/datasets/daflkadsjflkajdflkadfadadfadsfad") assert response.status_code == 404 def test_create_delete_dataset(): """Unit test for creating and subsequently deleting a dataset""" body = EXAMPLE_DATASET_BODY.copy() response = client.post(f"{PREFIX}/datasets", json=body) response_body = response.json() dataset_id = response_body["dataset_id"] assert response.status_code == 200 assert response_body["name"] == "Unit Test Dataset" assert response_body["description"] == "Dataset created during a unit test" response = client.get(f"{PREFIX}/datasets/{dataset_id}") assert response.status_code == 200 response = client.delete(f"{PREFIX}/datasets/{dataset_id}") assert response.status_code == 200 def test_create_missing_fields_dataset(): """Unit test for creating a dataset with missing important fields""" for field in ["name", "description", "labels"]: body = EXAMPLE_DATASET_BODY.copy() del body[field] response = client.post(f"{PREFIX}/datasets", json=body) assert response.status_code == 422 def test_delete_nonexistent_dataset(): """Unit test for trying to delete a nonexistent dataset""" response = client.delete(f"{PREFIX}/datasets/daflkadsjflkajdflkadfadadfadsfad") assert response.status_code == 404
[ 37811, 198, 14402, 40522, 198, 37811, 198, 198, 6738, 3049, 15042, 13, 9288, 16366, 1330, 6208, 11792, 198, 198, 6738, 1388, 1330, 598, 11, 22814, 47084, 198, 198, 16366, 796, 6208, 11792, 7, 1324, 8, 198, 198, 6369, 2390, 16437, 62, ...
2.468499
873
import os import re #If len > 0, the HTML line given contains single and/or double quotation marks #Takes the HTML lines with quotation marks and returns the codification #depending on if it has single or double quotation marks. if __name__ == "__main__": # test_bits_total() # test_num_attributes_line() main()
[ 11748, 28686, 198, 11748, 302, 198, 198, 2, 1532, 18896, 1875, 657, 11, 262, 11532, 1627, 1813, 4909, 2060, 290, 14, 273, 4274, 35777, 8849, 628, 628, 198, 198, 2, 51, 1124, 262, 11532, 3951, 351, 35777, 8849, 290, 5860, 262, 14873, ...
3.306931
101
import json from abc import ABCMeta, abstractmethod import time import threading import hashlib import base64 import random from typing import Optional, List from pathlib import Path from api import Marketplace, Producer from server import MerchantServer from models import SoldOffer, Offer
[ 11748, 33918, 198, 6738, 450, 66, 1330, 9738, 48526, 11, 12531, 24396, 198, 11748, 640, 198, 11748, 4704, 278, 198, 11748, 12234, 8019, 198, 11748, 2779, 2414, 198, 11748, 4738, 198, 6738, 19720, 1330, 32233, 11, 7343, 198, 6738, 3108, ...
4.373134
67
import argparse import glob import os from video_ffmpeg_utils import VideoFfmpegUtils """ Copy Timecode and enc ProResHQ or h265 Example: python3 copy_timecode.py \ --video-src "PATH_TO_VIDEO_SRC" \ --video-out "PATH_TO_VIDEO_OUT" \ --codec h265 \ --copy-tc \ """ # --------------- Arguments --------------- parser = argparse.ArgumentParser(description='Copy Timecode') parser.add_argument('--video-src', type=str, required=True) parser.add_argument('--video-out', type=str, default="output.mov", help="Path to video onto which to encode the output") parser.add_argument('--codec', type=str, default='h265', choices=['proreshq', 'h265']) parser.add_argument('--copy-tc', action='store_true', help="Used when copying timecode") args = parser.parse_args() # --------------- Main --------------- if __name__ == '__main__': video_utils = VideoFfmpegUtils() # Get Video Info by ffprobe video_info = video_utils.get_video_info(args.video_src) print("Check video_src_info:",video_info) # enc ProResHQ or h265 if args.codec == 'proreshq': print("run_ProResHQ_enc") if args.copy_tc: timecode = video_utils.get_timecode(args.video_src) print("video_src_timecode:", timecode) video_utils.run_ProResHQ_enc(args.video_src, args.video_out, timecode) else: video_utils.run_ProResHQ_enc(args.video_src, args.video_out) if args.codec == 'h265': print("run_hevc_nvenc") if args.copy_tc: timecode = video_utils.get_timecode(args.video_src) print("video_src_timecode:", timecode) video_utils.run_hevc_nvenc(args.video_src, args.video_out, timecode) else: video_utils.run_hevc_nvenc(args.video_src, args.video_out) # Check video_out_info video_info = video_utils.get_video_info(args.video_out) print("Check video_out_info:",video_info)
[ 11748, 1822, 29572, 198, 11748, 15095, 198, 11748, 28686, 198, 198, 6738, 2008, 62, 487, 43913, 62, 26791, 1330, 7623, 37, 38353, 22071, 18274, 4487, 628, 198, 37811, 198, 29881, 3862, 8189, 290, 2207, 1041, 4965, 41275, 393, 289, 22980, ...
2.389976
818
"""Codec functions for IDP Common Message Format supported by Inmarsat MGS. Also supported on ORBCOMM IGWS1. """ from binascii import b2a_base64 from math import log2, ceil from struct import pack, unpack from typing import Tuple, Union from warnings import WarningMessage, warn import xml.etree.ElementTree as ET from xml.dom.minidom import parseString from idpmodem.constants import FORMAT_HEX, FORMAT_B64, SATELLITE_GENERAL_TRACE __version__ = '2.0.0' DATA_TYPES = { 'bool': 'BooleanField', 'int_8': 'SignedIntField', 'uint_8': 'UnsignedIntField', 'int_16': 'SignedIntField', 'uint_16': 'UnsignedIntField', 'int_32': 'SignedIntField', 'uint_32': 'UnsignedIntField', 'int_64': 'SignedIntField', 'uint_64': 'UnsignedIntField', 'float': 'DataField', 'double': 'DataField', 'string': 'StringField', 'data': 'DataField', 'enum': 'EnumField', 'array': 'ArrayField', # TODO: support for array type } XML_NAMESPACE = { 'xsi': 'http://www.w3.org/2001/XMLSchema-instance', 'xsd': 'http://www.w3.org/2001/XMLSchema' } SIN_RANGE = (16, 255) for ns in XML_NAMESPACE: ET.register_namespace(ns, XML_NAMESPACE[ns]) def optimal_bits(value_range: tuple) -> int: """Returns the optimal number of bits for encoding a specified range.""" if not (isinstance(value_range, tuple) and len(value_range) == 2 and value_range[0] <= value_range[1]): #: non-compliant raise ValueError('value_range must be of form (min, max)') total_range = value_range[1] - value_range[0] total_range += 1 if value_range[0] == 0 else 0 optimal_bits = max(1, ceil(log2(value_range[1] - value_range[0]))) return optimal_bits class BaseField: """The base class for a Field. Attributes: data_type (str): The data type from a supported list. name (str): The unique Field name. description (str): Optional description. optional (bool): Optional indication the field is optional. """ def __init__(self, name: str, data_type: str, description: str = None, optional: bool = False) -> None: """Instantiates the base field. Args: name: The field name must be unique within a Message. data_type: The data type represented within the field. description: (Optional) Description/purpose of the field. optional: (Optional) Indicates if the field is mandatory. """ if data_type not in DATA_TYPES: raise ValueError('Invalid data type {}'.format(data_type)) if name is None or name.strip() == '': raise ValueError('Invalid name must be non-empty') self.data_type = data_type self.name = name self.description = description self.optional = optional class Message: """The Payload structure for Message Definition Files uploaded to a Mailbox. Attributes: name (str): The message name sin (int): The Service Identification Number min (int): The Message Identification Number fields (list): A list of Fields description (str): Optional description is_forward (bool): Indicates if the message is mobile-terminated """ def __init__(self, name: str, sin: int, min: int, description: str = None, is_forward: bool = False, fields: "list[BaseField]" = None): """Instantiates a Message. Args: name: The message name should be unique within the xMessages list. sin: The Service Identification Number (16..255) min: The Message Identification Number (0..255) description: (Optional) Description/purpose of the Message. is_forward: Indicates if the message is intended to be Mobile-Terminated. fields: Optional definition of fields during instantiation. """ if not isinstance(sin, int) or sin not in range(16, 256): raise ValueError('Invalid SIN {} must be in range 16..255'.format( sin)) if not isinstance(min, int) or min not in range (0, 256): raise ValueError('Invalid MIN {} must be in range 0..255'.format( min)) self.name = name self.description = description self.is_forward = is_forward self.sin = sin self.min = min self.fields = fields or Fields() @property @fields.setter @property def decode(self, databytes: bytes) -> None: """Parses and stores field values from raw data (received over-the-air). Args: databytes: A bytes array (typically from the forward message) """ binary_str = ''.join(format(int(b), '08b') for b in databytes) bit_offset = 16 #: Begin after SIN/MIN bytes for field in self.fields: if field.optional: present = binary_str[bit_offset] == '1' bit_offset += 1 if not present: continue bit_offset += field.decode(binary_str[bit_offset:]) def derive(self, databytes: bytes) -> None: """Derives field values from raw data bytes (received over-the-air). Deprecated/replaced by `decode`. Args: databytes: A bytes array (typically from the forward message) """ self.decode(databytes) def encode(self, data_format: int = FORMAT_B64, exclude: list = None) -> dict: """Encodes using the specified data format (base64 or hex). Args: data_format (int): 2=ASCII-Hex, 3=base64 exclude (list[str]): A list of optional field names to exclude Returns: Dictionary with sin, min, data_format and data to pass into AT%MGRT or atcommand function `message_mo_send` """ if data_format not in [FORMAT_B64, FORMAT_HEX]: raise ValueError('data_format {} unsupported'.format(data_format)) #:AT%MGRT uses '{}.{},{},{}'.format(sin, min, data_format, data) bin_str = '' for field in self.fields: if field.optional: if exclude is not None and field.name in exclude: present = False elif hasattr(field, 'value'): present = field.value is not None elif hasattr(field, 'elements'): present = field.elements is not None else: raise ValueError('Unknown value of optional') bin_str += '1' if present else '0' if not present: continue bin_str += field.encode() for _ in range(0, 8 - len(bin_str) % 8): #:pad to next byte bin_str += '0' _format = '0{}X'.format(int(len(bin_str) / 8 * 2)) #:hex bytes 2 chars hex_str = format(int(bin_str, 2), _format) if (self.is_forward and len(hex_str) / 2 > 9998 or not self.is_forward and len(hex_str) / 2 > 6398): raise ValueError('{} bytes exceeds maximum size for Payload'.format( len(hex_str) / 2)) if data_format == FORMAT_HEX: data = hex_str else: data = b2a_base64(bytearray.fromhex(hex_str)).strip().decode() return { 'sin': self.sin, 'min': self.min, 'data_format': data_format, 'data': data } def xml(self, indent: bool = False) -> ET.Element: """Returns the XML definition for a Message Definition File.""" xmessage = ET.Element('Message') name = ET.SubElement(xmessage, 'Name') name.text = self.name min = ET.SubElement(xmessage, 'MIN') min.text = str(self.min) fields = ET.SubElement(xmessage, 'Fields') for field in self.fields: fields.append(field.xml()) return xmessage if not indent else _indent_xml(xmessage) class Service: """A data structure holding a set of related Forward and Return Messages. Attributes: name (str): The service name sin (int): Service Identification Number or codec service id (16..255) description (str): A description of the service (unsupported) messages_forward (list): A list of mobile-terminated Message definitions messages_return (list): A list of mobile-originated Message definitions """ def __init__(self, name: str, sin: int, description: str = None, messages_forward: "list[Message]" = None, messages_return: "list[Message]" = None) -> None: """Instantiates a Service made up of Messages. Args: name: The service name should be unique within a MessageDefinitions sin: The Service Identification Number (16..255) description: (Optional) """ if not isinstance(name, str) or name == '': raise ValueError('Invalid service name {}'.format(name)) if sin not in range(16, 256): raise ValueError('Invalid SIN must be 16..255') self.name = name self.sin = sin if description is not None: warn('Service Description not currently supported') self.description = None self.messages_forward = messages_forward or Messages(self.sin, is_forward=True) self.messages_return = messages_return or Messages(self.sin, is_forward=False) def xml(self, indent: bool = False) -> ET.Element: """Returns the XML structure of the Service for a MDF.""" if len(self.messages_forward) == 0 and len(self.messages_return) == 0: raise ValueError('No messages defined for service {}'.format( self.sin)) xservice = ET.Element('Service') name = ET.SubElement(xservice, 'Name') name.text = str(self.name) sin = ET.SubElement(xservice, 'SIN') sin.text = str(self.sin) if self.description: desc = ET.SubElement(xservice, 'Description') desc.text = str(self.description) if len(self.messages_forward) > 0: forward_messages = ET.SubElement(xservice, 'ForwardMessages') for m in self.messages_forward: forward_messages.append(m.xml()) if len(self.messages_return) > 0: return_messages = ET.SubElement(xservice, 'ReturnMessages') for m in self.messages_return: return_messages.append(m.xml()) return xservice if not indent else _indent_xml(xservice) class ObjectList(list): """Base class for a specific object type list. Used for Fields, Messages, Services. Attributes: list_type: The object type the list is comprised of. """ SUPPORTED_TYPES = [ BaseField, # Field, Message, Service, ] def add(self, obj: object) -> bool: """Add an object to the end of the list. Args: obj (object): A valid object according to the list_type Raises: ValueError if there is a duplicate or invalid name, invalid value_range or unsupported data_type """ if not isinstance(obj, self.list_type): raise ValueError('Invalid {} definition'.format(self.list_type)) for o in self: if o.name == obj.name: raise ValueError('Duplicate {} name {} found'.format( self.list_type, obj.name)) self.append(obj) return True def __getitem__(self, n: Union[str, int]) -> object: """Retrieves an object by name or index. Args: n: The object name or list index Returns: object """ if isinstance(n, str): for o in self: if o.name == n: return o raise ValueError('{} name {} not found'.format(self.list_type, n)) return super().__getitem__(n) def delete(self, name: str) -> bool: """Delete an object from the list by name. Args: name: The name of the object. Returns: boolean: success """ for o in self: if o.name == name: self.remove(o) return True return False class Fields(ObjectList): """The list of Fields defining a Message or ArrayElement.""" class Messages(ObjectList): """The list of Messages (Forward or Return) within a Service.""" def add(self, message: Message) -> bool: """Add a message to the list if it matches the parent SIN. Overrides the base class add method. Args: message (object): A valid Message Raises: ValueError if there is a duplicate or invalid name, invalid value_range or unsupported data_type """ if not isinstance(message, Message): raise ValueError('Invalid message definition') if message.sin != self.sin: raise ValueError('Message SIN {} does not match service {}'.format( message.sin, self.sin)) for m in self: if m.name == message.name: raise ValueError('Duplicate message name {} found'.format( message.name)) if m.min == message.min: raise ValueError('Duplicate message MIN {} found'.format( message.min)) self.append(message) return True class Services(ObjectList): """The list of Service(s) within a MessageDefinitions.""" def add(self, service: Service) -> None: """Adds a Service to the list of Services.""" if not isinstance(service, Service): raise ValueError('{} is not a valid Service'.format(service)) if service.name in self: raise ValueError('Duplicate Service {}'.format(service.name)) for existing_service in self: if existing_service.sin == service.sin: raise ValueError('Duplicate SIN {}'.format(service.sin)) self.append(service) class BooleanField(BaseField): """A Boolean field.""" @property @default.setter @property @value.setter @property def encode(self) -> str: """Returns the binary string of the field value.""" if self.value is None and not self.optional: raise ValueError('No value assigned to field') return '1' if self.value else '0' def decode(self, binary_str: str) -> int: """Populates the field value from binary and returns the next offset. Args: binary_str (str): The binary string to decode Returns: The bit offset after parsing """ self.value = True if binary_str[0] == '1' else False return 1 class EnumField(BaseField): """An enumerated field sends an index over-the-air representing a string.""" def __init__(self, name: str, items: "list[str]", size: int, description: str = None, optional: bool = False, default: int = None, value: int = None) -> None: """Instantiates a EnumField. Args: name: The field name must be unique within a Message. items: A list of strings (indexed from 0). size: The number of *bits* used to encode the index over-the-air. description: An optional description/purpose for the field. optional: Indicates if the field is optional in the Message. default: A default value for the enum. value: Optional value to set during initialization. """ super().__init__(name=name, data_type='enum', description=description, optional=optional) if items is None or not all(isinstance(item, str) for item in items): raise ValueError('Items must all be strings') if not isinstance(size, int) or size < 1: raise ValueError('Size must be integer greater than 0 bits') self.items = items self.size = size self.default = default self.value = value if value is not None else self.default @property @items.setter @property @default.setter @property @value.setter @property @size.setter @property def encode(self) -> str: """Returns the binary string of the field value.""" if self.value is None: raise ValueError('No value configured in EnumField {}'.format( self.name)) _format = '0{}b'.format(self.bits) binstr = format(self.items.index(self.value), _format) return binstr def decode(self, binary_str: str) -> int: """Populates the field value from binary and returns the next offset. Args: binary_str (str): The binary string to decode Returns: The bit offset after parsing """ self.value = binary_str[:self.bits] return self.bits class UnsignedIntField(BaseField): """An unsigned integer value using a defined number of bits over-the-air.""" def __init__(self, name: str, size: int, data_type: str = 'uint_16', description: str = None, optional: bool = False, default: int = None, value: int = None) -> None: """Instantiates a UnsignedIntField. Args: name: The field name must be unique within a Message. size: The number of *bits* used to encode the integer over-the-air (maximum 32). data_type: The integer type represented (for decoding). description: An optional description/purpose for the string. optional: Indicates if the string is optional in the Message. default: A default value for the string. value: Optional value to set during initialization. """ if data_type not in ['uint_8', 'uint_16', 'uint_32']: raise ValueError('Invalid unsignedint type {}'.format(data_type)) super().__init__(name=name, data_type=data_type, description=description, optional=optional) self.size = size self.default = default self.value = value if value is not None else default @property @size.setter @property @value.setter @property @default.setter @property def encode(self) -> str: """Returns the binary string of the field value.""" if self.value is None: raise ValueError('No value defined in UnsignedIntField {}'.format( self.name)) _format = '0{}b'.format(self.bits) return format(self.value, _format) def decode(self, binary_str: str) -> int: """Populates the field value from binary and returns the next offset. Args: binary_str (str): The binary string to decode Returns: The bit offset after parsing """ self.value = int(binary_str[:self.bits], 2) return self.bits class SignedIntField(BaseField): """A signed integer value using a defined number of bits over-the-air.""" def __init__(self, name: str, size: int, data_type: str = 'int_16', description: str = None, optional: bool = False, default: int = None, value: int = None) -> None: """Instantiates a SignedIntField. Args: name: The field name must be unique within a Message. size: The number of *bits* used to encode the integer over-the-air (maximum 32). data_type: The integer type represented (for decoding). description: An optional description/purpose for the string. optional: Indicates if the string is optional in the Message. default: A default value for the string. value: Optional value to set during initialization. """ if data_type not in ['int_8', 'int_16', 'int_32']: raise ValueError('Invalid unsignedint type {}'.format(data_type)) super().__init__(name=name, data_type=data_type, description=description, optional=optional) self.size = size self.default = default self.value = value if value is not None else default @property @size.setter @property @value.setter @property @default.setter @property def encode(self) -> str: """Returns the binary string of the field value.""" if self.value is None: raise ValueError('No value defined in UnsignedIntField {}'.format( self.name)) _format = '0{}b'.format(self.bits) if self.value < 0: invertedbin = format(self.value * -1, _format) twocomplementbin = '' i = 0 while len(twocomplementbin) < len(invertedbin): twocomplementbin += '1' if invertedbin[i] == '0' else '0' i += 1 binstr = format(int(twocomplementbin, 2) + 1, _format) else: binstr = format(self.value, _format) return binstr def decode(self, binary_str: str) -> int: """Populates the field value from binary and returns the next offset. Args: binary_str (str): The binary string to decode Returns: The bit offset after parsing """ value = int(binary_str[:self.bits], 2) if (value & (1 << (self.bits - 1))) != 0: #:sign bit set e.g. 8bit: 128-255 value = value - (1 << self.bits) #:compute negative value self.value = value return self.bits class StringField(BaseField): """A character string sent over-the-air.""" def __init__(self, name: str, size: int, description: str = None, optional: bool = False, fixed: bool = False, default: str = None, value: str = None) -> None: """Instantiates a StringField. Args: name: The field name must be unique within a Message. size: The maximum number of characters in the string. description: An optional description/purpose for the string. optional: Indicates if the string is optional in the Message. fixed: Indicates if the string is always fixed length `size`. default: A default value for the string. value: Optional value to set during initialization. """ super().__init__(name=name, data_type='string', description=description, optional=optional) self.size = size self.fixed = fixed self.default = default self.value = value if value is not None else default @property @size.setter @property @default.setter @property @value.setter @property def encode(self) -> str: """Returns the binary string of the field value.""" if self.value is None and not self.optional: raise ValueError('No value defined for StringField {}'.format( self.name)) binstr = ''.join(format(ord(c), '08b') for c in self.value) if self.fixed: binstr += ''.join('0' for bit in range(len(binstr), self.bits)) else: binstr = _encode_field_length(len(self.value)) + binstr return binstr def decode(self, binary_str: str) -> int: """Populates the field value from binary and returns the next offset. Args: binary_str (str): The binary string to decode Returns: The bit offset after parsing """ if self.fixed: length = self.size bit_index = 0 else: (length, bit_index) = _decode_field_length(binary_str) n = int(binary_str[bit_index:bit_index + length * 8], 2) char_bytes = n.to_bytes((n.bit_length() + 7) // 8, 'big') for i, byte in enumerate(char_bytes): if byte == 0: warn('Truncating after 0 byte in string') char_bytes = char_bytes[:i] break self.value = char_bytes.decode('utf-8', 'surrogatepass') or '\0' return bit_index + length * 8 def xml(self) -> ET.Element: """Returns the message definition XML representation of the field.""" xmlfield = self._base_xml() size = ET.SubElement(xmlfield, 'Size') size.text = str(self.size) if self.fixed: fixed = ET.SubElement(xmlfield, 'Fixed') fixed.text = 'true' if self.default: default = ET.SubElement(xmlfield, 'Default') default.text = str(self.default) return xmlfield class DataField(BaseField): """A data field of raw bytes sent over-the-air. Can also be used to hold floating point, double-precision or large integers. """ supported_data_types = ['data', 'float', 'double'] def __init__(self, name: str, size: int, data_type: str = 'data', description: str = None, optional: bool = False, fixed: bool = False, default: bytes = None, value: bytes = None) -> None: """Instantiates a EnumField. Args: name: The field name must be unique within a Message. size: The maximum number of bytes to send over-the-air. data_type: The data type represented within the bytes. description: An optional description/purpose for the field. optional: Indicates if the field is optional in the Message. fixed: Indicates if the data bytes are a fixed `size`. default: A default value for the enum. value: Optional value to set during initialization. """ if data_type is None or data_type not in self.supported_data_types: raise ValueError('Invalid data type {}'.format(data_type)) super().__init__(name=name, data_type=data_type, description=description, optional=optional) self.fixed = fixed self.size = size self.default = default self.value = value if value is not None else default @property @size.setter @property @value.setter @property def encode(self) -> str: """Returns the binary string of the field value.""" if self.value is None and not self.optional: raise ValueError('No value defined for DataField {}'.format( self.name)) binstr = '' binstr = ''.join(format(b, '08b') for b in self._value) if self.fixed: #:pad to fixed length binstr += ''.join('0' for bit in range(len(binstr), self.bits)) else: binstr = _encode_field_length(len(self._value)) + binstr return binstr def decode(self, binary_str: str) -> int: """Populates the field value from binary and returns the next offset. Args: binary_str (str): The binary string to decode Returns: The bit offset after parsing """ if self.fixed: binary = binary_str[:self.bits] bits = self.bits else: (length, bit_index) = _decode_field_length(binary_str) binary = binary_str[bit_index:length * 8 + bit_index] bits = len(binary) self._value = int(binary, 2).to_bytes(int(bits / 8), 'big') return self.bits class ArrayField(BaseField): """An Array Field provides a list where each element is a set of Fields. Attributes: name (str): The name of the field instance. size (int): The maximum number of elements allowed. fields (Fields): A list of Field types comprising each ArrayElement description (str): An optional description of the array/use. optional (bool): Indicates if the array is optional in the Message fixed (bool): Indicates if the array is always the fixed `size` elements (list): The enumerated list of ArrayElements """ def __init__(self, name: str, size: int, fields: Fields, description: str = None, optional: bool = False, fixed: bool = False, elements: "list[Fields]" = None) -> None: """Initializes an ArrayField instance. Args: name: The unique field name within the Message. size: The maximum number of elements allowed. fields: The list of Field types comprising each element. description: An optional description/purpose of the array. optional: Indicates if the array is optional in the Message. fixed: Indicates if the array is always the fixed `size`. elements: Option to populate elements of Fields during instantiation. """ super().__init__(name=name, data_type='array', description=description, optional=optional) self.size = size self.fixed = fixed self.fields = fields self.elements = elements or [] @property @size.setter @property @fields.setter @property @elements.setter @property def append(self, element: Fields): """Adds the array element to the list of elements.""" if not isinstance(element, Fields): raise ValueError('Invalid element definition must be Fields') if self._valid_element(element): for i, field in enumerate(element): if (hasattr(field, 'description') and field.description != self.fields[i].description): field.description = self.fields[i].description if hasattr(field, 'value') and field.value is None: field.value = self.fields[i].default self._elements.append(element) def new_element(self) -> Fields: """Returns an empty element at the end of the elements list.""" new_index = len(self._elements) self._elements.append(Fields(self.fields)) return self.elements[new_index] def encode(self) -> str: """Returns the binary string of the field value.""" if len(self.elements) == 0: raise ValueError('No elements to encode') binstr = '' for element in self.elements: for field in element: binstr += field.encode() if not self.fixed: binstr = _encode_field_length(len(self.elements)) + binstr return binstr def decode(self, binary_str: str) -> int: """Populates the field value from binary and returns the next offset. Args: binary_str (str): The binary string to decode Returns: The bit offset after parsing """ if self.fixed: length = self.size bit_index = 0 else: (length, bit_index) = _decode_field_length(binary_str) for index in range(0, length): fields = Fields(self.fields) for field in fields: if field.optional: if binary_str[bit_index] == '0': bit_index += 1 continue bit_index += 1 bit_index += field.decode(binary_str[bit_index:]) try: self._elements[index] = fields except IndexError: self._elements.append(fields) return bit_index class MessageDefinitions: """A set of Message Definitions grouped into Services. Attributes: services: The list of Services with Messages defined. """
[ 37811, 43806, 721, 5499, 329, 4522, 47, 8070, 16000, 18980, 4855, 416, 554, 76, 945, 265, 337, 14313, 13, 198, 198, 7583, 4855, 319, 6375, 2749, 2662, 44, 35336, 19416, 16, 13, 198, 37811, 198, 198, 6738, 9874, 292, 979, 72, 1330, 2...
2.18657
15,383
if __name__ == "__main__" : main()
[ 628, 628, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1, 1058, 1388, 3419 ]
2.4375
16
from pathlib import Path TEST_DATA_DIR = Path("/Users/sean/code/pharedox/data")
[ 6738, 3108, 8019, 1330, 10644, 628, 198, 51, 6465, 62, 26947, 62, 34720, 796, 10644, 7203, 14, 14490, 14, 325, 272, 14, 8189, 14, 746, 1144, 1140, 14, 7890, 4943, 198 ]
2.645161
31
"""Service module.""" import datetime import uuid import zoneinfo from typing import Any, Optional from ... import config from ...utils import encoding from . import password_hashing, repository async def create_user( username: str, email: str, first_name: str, last_name: str, password: str, date_joined: Optional[datetime.datetime] = None, is_superuser=False, is_staff=False, is_active=True, last_login: Optional[datetime.datetime] = None, ) -> repository.User: """Inserts a user into the database. Args: username: The username of the user. email: The email of the user. first_name: The first name of the user. last_name: The last name of the user. password: The password (not hashed) of the user. date_joined: The datetime the user joined the system. is_superuser: A flag that indicates if this user is super user. is_staff: A flag that indicated if this user can is staff. is_active: A flag that indicates if this user is active. last_login: The datetime the user last logged in. Returns: A repository.User representing the created user. Raises: UsernameAlreadyExistsError: If the username already exists. EmailAlreadyExistsError: If the email already exists. """ username = encoding.normalize_str(username) email = encoding.normalize_str(email) first_name = encoding.normalize_str(first_name) last_name = encoding.normalize_str(last_name) if date_joined is None: tzinfo = zoneinfo.ZoneInfo(config.settings["APPLICATION"]["timezone"]) date_joined = datetime.datetime.now(tz=tzinfo) password_hash = password_hashing.make_password(password) return await repository.insert_user( username=username, email=email, first_name=first_name, last_name=last_name, password=password_hash, date_joined=date_joined, is_superuser=is_superuser, is_staff=is_staff, is_active=is_active, last_login=last_login, ) async def get_user_by_id(user_id: uuid.UUID) -> Optional[repository.User]: """Returns the user with the specified user_id from the database. Args: user_id: The user_id of the searched user. Returns: A repository.User representing the searched user, None if the user was not found. """ return await repository.get_user_by_id(user_id) async def update_user_by_id( user_id: uuid.UUID, **kwargs: Any ) -> Optional[repository.User]: """Updates the data of the user with the specified user_id in the database. Args: user_id: The user_id of the user that will be updated. **username (str): The username of the user. **email (str): The email of the user. **first_name (str): The first name of the user. **last_name (str): The last name of the user. **password (str): The password (not hashed) of the user. **is_superuser (bool): A flag that indicates if this user is super user. **is_staff (bool): A flag that indicated if this user can is staff. **is_active (bool): A flag that indicates if this user is active. **date_joined (datetime.datetime): The datetime the user joined the system. **last_login (datetime.datetime): The datetime the user last logged in. Returns: A repository.User representing the updated user, None if the user was not updated. Raises: UsernameAlreadyExistsError: If the username already exists. EmailAlreadyExistsError: If the email already exists. """ if "username" in kwargs: kwargs["username"] = encoding.normalize_str(kwargs["username"]) if "email" in kwargs: kwargs["email"] = encoding.normalize_str(kwargs["email"]) if "first_name" in kwargs: kwargs["first_name"] = encoding.normalize_str(kwargs["first_name"]) if "last_name" in kwargs: kwargs["last_name"] = encoding.normalize_str(kwargs["last_name"]) if "password" in kwargs: kwargs["password"] = password_hashing.make_password(kwargs["password"]) return await repository.update_user_by_id(user_id, **kwargs) async def delete_user_by_id(user_id: uuid.UUID) -> Optional[repository.User]: """Deletes the user with the specified user_id from the database. Args: user_id: The user_id of the user that will be deleted. Returns: A repository.User representing the deleted user, None if the user was not deleted. """ return await repository.delete_user_by_id(user_id)
[ 37811, 16177, 8265, 526, 15931, 198, 198, 11748, 4818, 8079, 198, 11748, 334, 27112, 198, 11748, 6516, 10951, 198, 6738, 19720, 1330, 4377, 11, 32233, 198, 198, 6738, 2644, 1330, 4566, 198, 6738, 2644, 26791, 1330, 21004, 198, 6738, 764, ...
2.701651
1,696
import numpy as np def GSFC_NK(data, **kwargs): ''' Picker algorithm by NASA Goddard Arguments must include the snowradar trace data itself (passed as a 1D float array) as well as any parameters required by the algorithm for layer-picking Only 2 picked layers are expected 1. air-snow layer pick (integer indexing the passed snowradar trace) 2. snow-ice layer pick (integer indexing the passed snowradar trace) ''' as_pick = np.int64(0) si_pick = np.int64(1) return as_pick, si_pick def NSIDC(data): ''' This is a placeholder for the NASA Goddard product hosted at NSIDC. Arguments must include the snowradar trace data itself (passed as a 1D float array) as well as any parameters required by the algorithm for layer-picking Only 2 picked layers are expected 1. air-snow layer pick (integer indexing the passed snowradar trace) 2. snow-ice layer pick (integer indexing the passed snowradar trace) ''' as_pick = np.int64(0) si_pick = np.int64(1) return as_pick, si_pick
[ 11748, 299, 32152, 355, 45941, 198, 198, 4299, 26681, 4851, 62, 46888, 7, 7890, 11, 12429, 46265, 22046, 2599, 198, 220, 220, 220, 705, 7061, 198, 220, 220, 220, 12346, 263, 11862, 416, 8884, 47386, 628, 220, 220, 220, 20559, 2886, 12...
2.819121
387
from typing import Dict, Tuple, Union from numpy.typing import DTypeLike # noqa: F401 DimsT = Tuple[Union[str, None]] ShapeT = Tuple[Union[int, None]] ChunksT = Union[bool, Dict[str, Union[int, None]]]
[ 6738, 19720, 1330, 360, 713, 11, 309, 29291, 11, 4479, 198, 198, 6738, 299, 32152, 13, 774, 13886, 1330, 360, 6030, 7594, 220, 1303, 645, 20402, 25, 376, 21844, 198, 198, 35, 12078, 51, 796, 309, 29291, 58, 38176, 58, 2536, 11, 6045...
2.594937
79
from modules.feedback.models.feedback_field import FeedbackField from modules.feedback.models.feedback_score_field import FeedbackScoreField from modules.feedback.models.feedback import Feedback
[ 6738, 13103, 13, 12363, 1891, 13, 27530, 13, 12363, 1891, 62, 3245, 1330, 37774, 15878, 198, 6738, 13103, 13, 12363, 1891, 13, 27530, 13, 12363, 1891, 62, 26675, 62, 3245, 1330, 37774, 26595, 15878, 198, 6738, 13103, 13, 12363, 1891, 13...
4.0625
48
from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() install_requires = [ 'luigi', 'gokart>=0.1.20', 'python-dateutil==2.7.5', 'pandas', 'scipy', 'numpy', 'gensim', 'scikit-learn', 'tensorflow>=1.13.1, <2.0', 'tqdm', 'optuna==0.6.0', 'docutils==0.15' # to avoid dependency conflict ] setup( name='redshells', use_scm_version=True, setup_requires=['setuptools_scm'], description='Tasks which are defined using gokart.TaskOnKart. The tasks can be used with data pipeline library "luigi".', long_description=long_description, long_description_content_type="text/markdown", author='M3, inc.', url='https://github.com/m3dev/redshells', license='MIT License', packages=find_packages(), install_requires=install_requires, test_suite='test')
[ 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 198, 6738, 40481, 82, 1330, 1280, 198, 6738, 28686, 1330, 3108, 198, 198, 1456, 796, 3108, 13, 397, 2777, 776, 7, 6978, 13, 15908, 3672, 7, 834, 7753, 834, 4008, 198, 4480, 1...
2.428916
415
"""rio_viz.cli.""" import os import tempfile from contextlib import contextmanager, ExitStack import click from rio_viz import app, raster from rio_cogeo.cogeo import cog_validate, cog_translate from rio_cogeo.profiles import cog_profiles @contextmanager def TemporaryRasterFile(dst_path, suffix=".tif"): """Create temporary file.""" fileobj = tempfile.NamedTemporaryFile( dir=os.path.dirname(dst_path), suffix=suffix, delete=False ) fileobj.close() try: yield fileobj finally: os.remove(fileobj.name) class MbxTokenType(click.ParamType): """Mapbox token type.""" name = "token" def convert(self, value, param, ctx): """Validate token.""" try: if not value: return "" assert value.startswith("pk") return value except (AttributeError, AssertionError): raise click.ClickException( "Mapbox access token must be public (pk). " "Please sign up at https://www.mapbox.com/signup/ to get a public token. " "If you already have an account, you can retreive your " "token at https://www.mapbox.com/account/." ) @click.command() @click.argument("src_paths", type=str, nargs=-1, required=True) @click.option( "--style", type=click.Choice(["satellite", "basic"]), default="basic", help="Mapbox basemap", ) @click.option("--port", type=int, default=8080, help="Webserver port (default: 8080)") @click.option( "--mapbox-token", type=MbxTokenType(), metavar="TOKEN", default=lambda: os.environ.get("MAPBOX_ACCESS_TOKEN", ""), help="Pass Mapbox token", ) @click.option("--no-check", is_flag=True, help="Ignore COG validation") def viz(src_paths, style, port, mapbox_token, no_check): """Rasterio Viz cli.""" # Check if cog src_paths = list(src_paths) with ExitStack() as ctx: for ii, src_path in enumerate(src_paths): if not no_check and not cog_validate(src_path): # create tmp COG click.echo("create temporaty COG") tmp_path = ctx.enter_context(TemporaryRasterFile(src_path)) output_profile = cog_profiles.get("deflate") output_profile.update(dict(blockxsize="256", blockysize="256")) config = dict( GDAL_TIFF_INTERNAL_MASK=os.environ.get( "GDAL_TIFF_INTERNAL_MASK", True ), GDAL_TIFF_OVR_BLOCKSIZE="128", ) cog_translate(src_path, tmp_path.name, output_profile, config=config) src_paths[ii] = tmp_path.name src_dst = raster.RasterTiles(src_paths) application = app.viz(src_dst, token=mapbox_token, port=port, style=style) url = application.get_template_url() click.echo(f"Viewer started at {url}", err=True) click.launch(url) application.start()
[ 37811, 27250, 62, 85, 528, 13, 44506, 526, 15931, 198, 198, 11748, 28686, 198, 11748, 20218, 7753, 198, 6738, 4732, 8019, 1330, 4732, 37153, 11, 29739, 25896, 198, 198, 11748, 3904, 198, 6738, 374, 952, 62, 85, 528, 1330, 598, 11, 374...
2.15253
1,403
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-01-24 09:04 from __future__ import unicode_literals from django.db import migrations, models import django.utils.timezone
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 352, 13, 940, 13, 20, 319, 2177, 12, 486, 12, 1731, 7769, 25, 3023, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 1...
2.80303
66
#-*- coding: utf-8 -*- import sys import os import glob import click #import click_completion #click_completion.init() from sequana import version import functools __all__ = ["main"] import sequana import colorlog logger = colorlog.getLogger(__name__) # This can be used by all commands as a simple decorator CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help']) import pkg_resources pipelines = [item.key for item in pkg_resources.working_set if item.key.startswith("sequana")] if len(pipelines): version +="\nThe following pipelines are installed:\n" for item in pkg_resources.working_set: if item.key.startswith("sequana") and item.key != 'sequana': version += "\n - {} version: {}".format(item.key, item.version) @click.group(context_settings=CONTEXT_SETTINGS) @click.version_option(version=version) def main(**kwargs): """\bThis is the main entry point for a set of Sequana applications. Pipelines such as sequana_rnaseq, sequana_variant_calling have their own application and help. In addition, more advanced tools such as sequana_taxonomy or sequana_coverage have their own standalone. """ pass @main.command() @click.argument('filename', type=click.STRING, nargs=-1) @click.option("-o", "--output", help="filename where to save results. to be used with --head, --tail") @click.option("--count-reads", is_flag=True) @click.option("--head", type=click.INT, help='number of reads to extract from the head') @click.option("--merge", is_flag=True) @click.option("--tail", type=click.INT, help="number of reads to extract from the tail") def fastq(**kwargs): """Set of useful utilities for FastQ manipulation. Input file can be gzipped or not. The --output-file """ from sequana.fastq import FastQ filenames = kwargs['filename'] # users may provide a wildcards such as "A*gz" or list of files. if len(filenames) == 1: # if existing files or glob, a glob would give the same answer. filenames = glob.glob(filenames[0]) for filename in filenames: os.path.exists(filename) # could be simplified calling count_reads only once if kwargs['count_reads']: for filename in filenames: f = FastQ(filename) Nreads = f.count_reads() Nlines = Nreads * 4 print(f"Number of reads in {filename}: {Nreads}") print(f"Number of lines in {filename}: {Nlines}") elif kwargs['head']: for filename in filenames: f = FastQ(filename) if kwargs['output'] is None: logger.error("Please use --output to tell us where to save the results") sys.exit(1) N = kwargs['head'] * 4 f.extract_head(N=N, output_filename=kwargs['output']) elif kwargs['tail']: #pragma: no cover raise NotImplementedError elif kwargs['merge']: import subprocess # merge all input files (assuming gz extension) extensions = [filename.split(".")[-1] for filename in filenames] if set(extensions) != set(['gz']): raise ValueError("Your input FastQ files must be zipped") output_filename = kwargs['output'] if output_filename is None: logger.error("You must use --output filename.gz") sys.exit(1) if output_filename.endswith(".gz") is False: raise ValueError("your output file must end in .gz") p1 = subprocess.Popen(['zcat'] + list(filenames), stdout=subprocess.PIPE) fout = open(output_filename, 'wb') p2 = subprocess.run(['pigz'], stdin=p1.stdout, stdout=fout) else: #pragma: no cover print("Use one of the commands") @main.command() @click.argument('name', type=click.STRING) @click.option('--check', is_flag=True) @click.option('--extract-adapters', is_flag=True) @click.option('--quick-fix', is_flag=True) @click.option('--output', default=None) def samplesheet(**kwargs): """Utilities to manipulate sample sheet""" name = kwargs['name'] from sequana.iem import IEM if kwargs['check']: iem = IEM(name) iem.validate() logger.info("SampleSheet looks correct") elif kwargs["extract_adapters"]: iem = IEM(name) iem.to_fasta() elif kwargs["quick_fix"]: iem = IEM(name, tryme=True) if kwargs['output']: filename = kwargs['output'] else: filename = name + ".fixed" logger.info("Saving fixed version in {}".format(filename)) iem.quick_fix(output_filename=filename) # This will be a complex command to provide HTML summary page for # input files (e.g. bam), or results from pipelines. For each module, # we should have corresponding option that starts with the module's name # This can also takes as input various types of data (e.g. FastA) @main.command() @click.argument("name", type=click.Path(exists=True), nargs=-1) @click.option("--module", required=False, type=click.Choice(["bamqc", "bam", "fasta", "fastq", "gff"])) def summary(**kwargs): """Create a HTML report for various type of NGS formats. \b * bamqc * fastq This will process all files in the given pattern (in back quotes) sequentially and procude one HTML file per input file. Other module all work in the same way. For example, for FastQ files:: sequana summary one_input.fastq sequana summary `ls *fastq` """ names = kwargs['name'] module = kwargs['module'] if module is None: if names[0].endswith('fastq.gz') or names[0].endswith('.fastq'): module = "fastq" elif names[0].endswith('.bam'): module = "bam" elif names[0].endswith('.gff') or names[0].endswith('gff3'): module = "gff" elif names[0].endswith('fasta.gz') or names[0].endswith('.fasta'): module = "fasta" else: logger.error("please use --module to tell us about the input fimes") sys.exit(1) if module == "bamqc": for name in names: print(f"Processing {name}") from sequana.modules_report.bamqc import BAMQCModule report = BAMQCModule(name, "bamqc.html") elif module == "fasta": # there is no module per se. HEre we just call FastA.summary() from sequana.fasta import FastA for name in names: f = FastA(name) f.summary() elif module == "fastq": # there is no module per se. HEre we just call FastA.summary() from sequana.fastq import FastQ from sequana import FastQC for filename in names: ff = FastQC(filename, max_sample=1e6, verbose=False) stats = ff.get_stats() print(stats) elif module == "bam": import pandas as pd from sequana import BAM for filename in names: ff = BAM(filename) stats = ff.get_stats() df = pd.Series(stats).to_frame().T print(df) elif module == "gff": import pandas as pd from sequana import GFF3 for filename in names: ff = GFF3(filename) print("#filename: {}".format(filename)) print("#Number of entries per genetic type:") print(ff.df.value_counts('type').to_string()) print("#Number of duplicated attribute (if any) per attribute:") ff.get_duplicated_attributes_per_type() @main.command() @click.option("--file1", type=click.Path(), default=None, required=True, help="""The first input RNA-seq table to compare""") @click.option("--file2", type=click.Path(), default=None, required=True, help="""The second input RNA-seq table to compare""") @common_logger def rnaseq_compare(**kwargs): """Compare 2 tables created by the 'sequana rnadiff' command""" from sequana.compare import RNADiffCompare c = RNADiffCompare(kwargs['file1'], kwargs['file2']) c.plot_volcano_differences() from pylab import savefig savefig("sequana_rnaseq_compare_volcano.png", dpi=200) @main.command() @click.option("--annotation", type=click.Path(), default=None, help="""The annotation GFF file used to perform the feature count""") @click.option("--report-only", is_flag=True, default=False, help="""Generate report assuming results are already present""") @click.option("--output-directory", type=click.Path(), default="rnadiff", help="""Output directory where are saved the results""") @click.option("--features", type=click.Path(), default="all_features.out", help="""The Counts from feature counts. This should be the output of the sequana_rnaseq pipeline all_features.out """) #FIXME I think it would be better to have a single file with multiple columns #for alternative condition (specified using the "condition" option) @click.option("--design", type=click.Path(), default="design.csv", help="""It should have been generated by sequana_rnaseq. If not, it must be a comma separated file with two columns. One for the label to be found in the --features file and one column with the condition to which it belong. E.g. with 3 replicates and 2 conditions. It should look like: \b label,condition WT1,WT WT2,WT WT3,WT file1,cond1 fileother,cond1 """) @click.option("--condition", type=str, default="condition", help="""The name of the column in design.csv to use as condition for the differential analysis. Default is 'condition'""") @click.option("--feature-name", default="gene", help="""The feature name compatible with your GFF. Default is 'gene'""") @click.option("--attribute-name", default="ID", help="""The attribute used as identifier. compatible with your GFF. Default is 'ID'""") @click.option("--reference", type=click.Path(), default=None, help="""The reference to test DGE against. If provided, conditions not involving the reference are ignored. Otherwise all combinations are tested""") @click.option("--comparisons", type=click.Path(), default=None, help="""Not yet implemented. By default, all comparisons are computed""") @click.option("--cooks-cutoff", type=click.Path(), default=None, help="""if none, let DESeq2 choose the cutoff""") @click.option("--independent-filtering/--no-independent-filtering", default=False, help="""Do not perform independent_filtering by default. low counts may not have adjusted pvalues otherwise""") @click.option("--beta-prior/--no-beta-prior", default=False, help="Use beta priori or not. Default is no beta prior") @click.option("--fit-type", default="parametric", help="DESeq2 type of fit. Default is 'parametric'") @common_logger def rnadiff(**kwargs): """Perform RNA-seq differential analysis. This command performs the differential analysis of gene expression. The analysis is performed on feature counts generated by a RNA-seq analysis (see e.g. https://github.com/sequana/rnaseq pipeline). The analysis is performed by DESeq2. A HTML report is created as well as a set of output files, including summary table of the analysis. To perform this analysis, you will need the GFF file used during the RNA-seq analysis, the feature stored altogether in a single file, an experimental design file, and the feature and attribute used during the feature count. Here is an example: \b sequana rnadiff --annotation Lepto.gff --design design.csv --features all_features.out --feature-name gene --attribute-name ID """ import pandas as pd from sequana.featurecounts import FeatureCount from sequana.rnadiff import RNADiffAnalysis, RNADesign from sequana.modules_report.rnadiff import RNAdiffModule logger.setLevel(kwargs['logger']) outdir = kwargs['output_directory'] feature = kwargs['feature_name'] attribute = kwargs['attribute_name'] design = kwargs['design'] reference=kwargs['reference'] if kwargs['annotation']: gff = kwargs['annotation'] logger.info(f"Checking annotation file") from sequana import GFF3 g = GFF3(gff) #.save_annotation_to_csv() if feature not in g.features: logger.critical(f"{feature} not found in the GFF. Most probably a wrong feature name") attributes = g.get_attributes(feature) if attribute not in attributes: logger.critical(f"{attribute} not found in the GFF for the provided feature. Most probably a wrong feature name. Please change --attribute-name option or do not provide any GFF") sys.exit(1) else: gff = None design_check = RNADesign(design, reference=reference) compa_csv = kwargs['comparisons'] if compa_csv: compa_df = pd.read_csv(compa_csv) comparisons = list(zip(compa_df["alternative"], compa_df["reference"])) else: comparisons = design_check.comparisons if kwargs['report_only'] is False: logger.info(f"Processing features counts and saving into {outdir}/light_counts.csv") fc = FeatureCount(kwargs['features']) from easydev import mkdirs mkdirs(f"{outdir}") fc.rnadiff_df.to_csv(f"{outdir}/light_counts.csv") logger.info(f"Differential analysis to be saved into ./{outdir}") for k in sorted(["independent_filtering", "beta_prior", "cooks_cutoff", "fit_type", "reference"]): logger.info(f" Parameter {k} set to : {kwargs[k]}") r = RNADiffAnalysis(f"{outdir}/light_counts.csv", design, condition=kwargs["condition"], comparisons=comparisons, fc_feature=feature, fc_attribute=attribute, outdir=outdir, gff=gff, cooks_cutoff=kwargs.get("cooks_cutoff"), independent_filtering=kwargs.get("independent_filtering"), beta_prior=kwargs.get("beta_prior"), fit_type=kwargs.get('fit_type') ) logger.info(f"Saving output files into {outdir}/rnadiff.csv") try: results = r.run() results.to_csv(f"{outdir}/rnadiff.csv") except Exception as err: logger.error(err) sys.exit(1) else: logger.info(f"DGE done.") # cleanup if succesful os.remove(f"{outdir}/rnadiff.err") os.remove(f"{outdir}/rnadiff.out") os.remove(f"{outdir}/rnadiff_light.R") logger.info(f"Reporting. Saving in rnadiff.html") report = RNAdiffModule(outdir, kwargs['design'], gff=gff, fc_attribute=attribute, fc_feature=feature, alpha=0.05, log2_fc=0, condition=kwargs["condition"], annot_cols=None, pattern="*vs*_degs_DESeq2.csv") @main.command() @click.option("--mart", default="ENSEMBL_MART_ENSEMBL", show_default=True, help="A valid mart name") @click.option("--dataset", required=True, help="A valid dataset name. e.g. mmusculus_gene_ensembl, hsapiens_gene_ensembl") @click.option("--attributes", multiple=True, default=["ensembl_gene_id","go_id","entrezgene_id","external_gene_name"], show_default=True, help="A list of valid attributes to look for in the dataset") @click.option("--output", default=None, help="""by default save results into a CSV file named biomart_<dataset>_<YEAR>_<MONTH>_<DAY>.csv""") @common_logger def biomart(**kwargs): """Retrieve information from biomart and save into CSV file This command uses BioMart from BioServices to introspect a MART service (--mart) and a specific dataset (default to mmusculus_gene_ensembl). Then, for all ensembl IDs, it will fetch the requested attributes (--attributes). Finally, it saves the CSV file into an output file (--output). This takes about 5-10 minutes to retrieve the data depending on the connection. """ print(kwargs) logger.setLevel(kwargs["logger"]) mart = kwargs['mart'] attributes = kwargs['attributes'] dataset = kwargs["dataset"] from sequana.enrichment import Mart conv = Mart(dataset, mart) df = conv.query(attributes) conv.save(df, filename=kwargs['output']) @main.command() @click.option("-i", "--input", required=True, help="The salmon input file.") @click.option("-o", "--output", required=True, help="The feature counts output file") @click.option("-f", "--gff", required=True, help="A GFF file compatible with your salmon file") @click.option("-a", "--attribute", default="ID", help="A valid attribute to be found in the GFF file and salmon input") @click.option("-a", "--feature", default="gene", help="A valid feature") def salmon(**kwargs): """Convert output of Salmon into a feature counts file """ from sequana import salmon salmon_input = kwargs['input'] output = kwargs["output"] if os.path.exists(salmon_input) is False: logger.critical("Input file does not exists ({})".format(salmon_input)) gff = kwargs["gff"] attribute = kwargs['attribute'] feature = kwargs['feature'] # reads file generated by salmon and generated count file as expected by # DGE. s = salmon.Salmon(salmon_input, gff) s.save_feature_counts(output, feature=feature, attribute=attribute) @main.command() @click.option("-i", "--input", required=True) @click.option("-o", "--output", required=True) def gtf_fixer(**kwargs): """Reads GTF and fix known issues (exon and genes uniqueness)""" from sequana.gtf import GTFFixer gtf = GTFFixer(kwargs['input']) res = gtf.fix_exons_uniqueness(kwargs['output']) #res = gtf.fix_exons_uniqueness(kwargs['output']) print(res) # This will be a complex command to provide HTML summary page for # input files (e.g. bam), or results from pipelines. For each module, # we should have corresponding option that starts with the module's name # This can also takes as input various types of data (e.g. FastA) @main.command() @click.argument("name", type=click.Path(exists=True), nargs=1) @click.option("--annotation-attribute", type=click.STRING, #required=True, default="Name", help="a valid taxon identifiers") @click.option("--panther-taxon", type=click.INT, #required=True, default=0, help="a valid taxon identifiers") @click.option("--kegg-name", type=click.STRING, default=None, help="a valid KEGG name (automatically filled for 9606 (human) and 10090 (mmusculus)") @click.option("--log2-foldchange-cutoff", type=click.FLOAT, default=1, show_default=True, help="remove events with absolute log2 fold change below this value") @click.option("--padj-cutoff", type=click.FLOAT, default=0.05, show_default=True, help="remove events with pvalue abobe this value default (0.05).") @click.option("--biomart", type=click.STRING, default=None, help="""you may need a biomart mapping of your identifier for the kegg pathways analysis. If you do not have this file, you can use 'sequana biomart' command""") @click.option("--go-only", type=click.BOOL, default=False, is_flag=True, help="""to run only panther db enrichment""") @click.option("--plot-linearx", type=click.BOOL, default=False, is_flag=True, help="""Default is log2 fold enrichment in the plots. use this to use linear scale""") @click.option("--compute-levels", type=click.BOOL, default=False, is_flag=True, help="""to compute the GO levels (slow) in the plots""") @click.option("--max-genes", type=click.INT, default=2000, help="""Maximum number of genes (up or down) to use in PantherDB, which is limited to about 3000""") @click.option("--kegg-only", type=click.BOOL, default=False, is_flag=True, help="""to run only kegg patways enrichment""") @click.option("--kegg-pathways-directory", type=click.Path(), default=None, help="""a place where to find the pathways for each organism""") @click.option("--kegg-background", type=click.INT, default=None, help="""a background for kegg enrichment. If None, set to number of genes found in KEGG""") @common_logger def enrichment(**kwargs): """Create a HTML report for various sequana out \b * enrichment: the output of RNADiff pipeline Example for the enrichment module: sequana enrichment rnadiff.csv --panther-taxon 10090 --log2-foldchange-cutoff 2 --kegg-only The KEGG pathways are loaded and it may take time. Once done, they are saved in kegg_pathways/organism and be loaded next time: sequana enrichment rnadiff/rnadiff.csv --panther-taxon 189518 \ --log2-foldchange-cutoff 2 --kegg-only \ --kegg-name lbi\ --annotation file.gff """ import pandas as pd from sequana.modules_report.enrichment import Enrichment logger.setLevel(kwargs['logger']) taxon = kwargs['panther_taxon'] if taxon == 0: logger.error("You must provide a taxon with --panther-taxon") return keggname = kwargs['kegg_name'] params = {"padj": kwargs['padj_cutoff'], "log2_fc": kwargs['log2_foldchange_cutoff'], "max_entries": kwargs['max_genes'], "mapper": kwargs['biomart'], "kegg_background": kwargs['kegg_background'], "preload_directory": kwargs['kegg_pathways_directory'], "plot_logx": not kwargs['plot_linearx'], "plot_compute_levels": kwargs['compute_levels'], } filename = kwargs['biomart'] if filename and os.path.exists(filename) is False: logger.error("{} does not exists".format(filename)) sys.exit(1) filename = kwargs['kegg_pathways_directory'] if filename and os.path.exists(filename) is False: logger.error("{} does not exists".format(filename)) sys.exit(1) rnadiff_file = kwargs['name'] logger.info(f"Reading {rnadiff_file}") rnadiff = pd.read_csv(rnadiff_file, index_col=0, header=[0,1]) # now that we have loaded all results from a rnadiff analysis, let us # perform the enrichment for each comparison found in the file annot_col = kwargs['annotation_attribute'] Nmax = kwargs['max_genes'] from sequana.utils import config for compa in rnadiff.columns.levels[0]: if compa not in ['statistics', 'annotation']: # get gene list df = rnadiff[compa].copy() # we add the annotation for x in rnadiff['annotation'].columns: df[x] = rnadiff['annotation'][x] # now we find the gene lists padj = params['padj'] log2fc = params['log2_fc'] df = df.query("(log2FoldChange >=@log2fc or log2FoldChange<=-@log2fc) and padj <= @padj") df.reset_index(inplace=True) dfup = df.sort_values("log2FoldChange", ascending=False) up_genes = list(dfup.query("log2FoldChange > 0")[annot_col])[:Nmax] dfdown = df.sort_values("log2FoldChange", ascending=True) down_genes = list(dfdown.query("log2FoldChange < 0")[annot_col])[:Nmax] all_genes = list( df.sort_values("log2FoldChange", key=abs,ascending=False)[annot_col] )[:Nmax] gene_dict = { "up": up_genes, "down": down_genes, "all": all_genes, } Nup = len(up_genes) Ndown = len(down_genes) N = Nup + Ndown logger.info(f"Computing enrichment for the {compa} case") logger.info(f"Found {Nup} genes up-regulated, {Ndown} down regulated ({N} in total).") config.output_dir = f"enrichment/{compa}" try:os.mkdir("enrichment") except:pass report = Enrichment(gene_dict, taxon, df, kegg_organism=keggname, enrichment_params=params, go_only=kwargs["go_only"], kegg_only=kwargs["kegg_only"], command=" ".join(['sequana'] + sys.argv[1:])) @main.command() @click.option("--search-kegg", type=click.Path(), default=None, help="""Search a pattern amongst all KEGG organism""") @click.option("--search-panther", type=click.Path(), default=None, help="""Search a pattern amongst all KEGG organism""") @common_logger def taxonomy(**kwargs): """Tool to retrieve taxonomic information. sequana taxonomy --search-kegg leptospira """ if kwargs['search_kegg']: from sequana.kegg import KEGGHelper k = KEGGHelper() results = k.search(kwargs['search_kegg'].lower()) print(results) elif kwargs['search_panther']: import pandas as pd from sequana import sequana_data df = pd.read_csv(sequana_data("panther.csv"), index_col=0) pattern = kwargs['search_panther'] f1 = df[[True if pattern in x else False for x in df['name']]] f2 = df[[True if pattern in x else False for x in df.short_name]] f3 = df[[True if pattern in x else False for x in df.long_name]] indices = list(f1.index) + list(f2.index) + list(f3.index) if len(indices) == 0: # maybe it is a taxon ID ? f4 = df[[True if pattern in str(x) else False for x in df.taxon_id]] indices = list(f4.index) indices = set(indices) print(df.loc[indices]) @main.command() @click.argument("gff_filename", type=click.Path(exists=True)) @common_logger def gff2gtf(**kwargs): """Convert a GFF file into GTF This is experimental convertion. Use with care. """ filename = kwargs["gff_filename"] assert filename.endswith(".gff") or filename.endswith(".gff3") from sequana.gff3 import GFF3 g = GFF3(filename) if filename.endswith(".gff"): g.to_gtf(os.path.basename(filename).replace(".gff", ".gtf")) elif filename.endswith(".gff3"): g.to_gtf(os.path.basename(filename).replace(".gff3", ".gtf"))
[ 2, 12, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 25064, 198, 11748, 28686, 198, 11748, 15095, 198, 11748, 3904, 198, 2, 11748, 3904, 62, 785, 24547, 198, 198, 2, 12976, 62, 785, 24547, 13, 15003, 3419, 198, ...
2.443369
10,745
def problem463(): """ The function $f$ is defined for all positive integers as follows: • $f(1)=1$ • $f(3)=3$ • $f(2n)=f(n)$ • $f(4n + 1)=2f(2n + 1) - f(n)$ • $f(4n + 3)=3f(2n + 1) - 2f(n)$ The function $S(n)$ is defined as $\\sum_{i=1}^{n}f(i)$. $S(8)=22$ and $S(100)=3604$. Find $S(3^{37})$. Give the last 9 digits of your answer. """ pass
[ 4299, 1917, 38380, 33529, 198, 220, 220, 220, 37227, 628, 198, 220, 220, 220, 383, 2163, 720, 69, 3, 318, 5447, 329, 477, 3967, 37014, 355, 5679, 25, 628, 220, 220, 220, 220, 220, 220, 220, 220, 5595, 720, 69, 7, 16, 47505, 16, ...
1.784232
241
#this is for testing, an internal testbench to verify implemented features from bs4 import BeautifulSoup from course import MyCourse import requests import csv import cscraper cscraper.updateCSV() courses = cscraper.findCoursebyID("MaTh 170") for course in courses: course.printCourse() courses = cscraper.findCoursebyDesc("experiment") for course in courses: print(course) courses = cscraper.findCoursebyTitle("Materials") for course in courses: print(course) #url = "https://ucsd.edu/catalog/front/courses.html" #req = requests.get(url) #soup = BeautifulSoup(req.text, "lxml") #for tag in soup.findAll("a", string="courses"): #print(tag.get('href')) #for tag in soup.findAll('p','course-name'): # print(tag.text) # print(tag.find_next('p','course-descriptions').text
[ 2, 5661, 318, 329, 4856, 11, 281, 5387, 1332, 26968, 284, 11767, 9177, 3033, 198, 198, 6738, 275, 82, 19, 1330, 23762, 50, 10486, 198, 6738, 1781, 1330, 2011, 49046, 198, 11748, 7007, 198, 11748, 269, 21370, 198, 11748, 269, 1416, 385...
2.890511
274
from pymantic.compat import ( binary_type, ) class LarkParser(object): """Provide a consistent interface for parsing serialized RDF using one of the lark parsers. """ def parse(self, string_or_stream, graph=None): """Parse a string or file-like object into RDF primitives and add them to either the provided graph or a new graph. """ tf = self.lark.options.transformer try: if graph is None: graph = tf._make_graph() tf._prepare_parse(graph) if hasattr(string_or_stream, 'readline'): triples = self.line_by_line_parser(string_or_stream) else: # Presume string. triples = self.lark.parse(string_or_stream) graph.addAll(triples) finally: tf._cleanup_parse() return graph def parse_string(self, string_or_bytes, graph=None): """Parse a string, decoding it from bytes to UTF-8 if necessary. """ if isinstance(string_or_bytes, binary_type): string = string_or_bytes.decode('utf-8') else: string = string_or_bytes return self.parse(string, graph)
[ 6738, 279, 4948, 5109, 13, 5589, 265, 1330, 357, 198, 220, 220, 220, 13934, 62, 4906, 11, 198, 8, 628, 198, 4871, 406, 668, 46677, 7, 15252, 2599, 198, 220, 220, 220, 37227, 15946, 485, 257, 6414, 7071, 329, 32096, 11389, 1143, 371,...
2.182624
564
import unittest import numpy as np from utils_ml.src.data_processing import data_processing_utils if __name__ == '__main__': unittest.main()
[ 11748, 555, 715, 395, 198, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 3384, 4487, 62, 4029, 13, 10677, 13, 7890, 62, 36948, 1330, 1366, 62, 36948, 62, 26791, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, ...
2.777778
54
"""Main TTX application, Mac-only""" #make sure we don't lose events to SIOUX import MacOS MacOS.EnableAppswitch(-1) SetWatchCursor() # a few constants LOGFILENAME = "TTX errors" PREFSFILENAME = "TTX preferences" DEFAULTXMLOUTPUT = ":XML output" DEFAULTTTOUTPUT = ":TrueType output" import FrameWork import MiniAEFrame, AppleEvents import EasyDialogs import Res import macfs import os import sys, time import re, string import traceback from fontTools import ttLib, version from fontTools.ttLib import xmlImport from fontTools.ttLib.macUtils import ProgressBar abouttext = """\ TTX - The free TrueType to XML to TrueType converter (version %s) Copyright 1999-2001, Just van Rossum (Letterror) just@letterror.com""" % version default_prefs = """\ xmloutput: ":XML output" ttoutput: ":TrueType output" makesuitcases: 1 """ sys.stdin = dummy_stdin() # redirect all output to a log file sys.stdout = sys.stderr = open(LOGFILENAME, "w", 0) # unbuffered print "Starting TTX at " + time.ctime(time.time()) # fire it up! ttx = TTX() ttx.mainloop() # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # clues for BuildApplication/MacFreeze. # # These modules somehow get imported, but we don't want/have them: # # macfreeze: exclude msvcrt # macfreeze: exclude W # macfreeze: exclude SOCKS # macfreeze: exclude TERMIOS # macfreeze: exclude termios # macfreeze: exclude icglue # macfreeze: exclude ce # # these modules are imported dynamically, so MacFreeze won't see them: # # macfreeze: include fontTools.ttLib.tables._c_m_a_p # macfreeze: include fontTools.ttLib.tables._c_v_t # macfreeze: include fontTools.ttLib.tables._f_p_g_m # macfreeze: include fontTools.ttLib.tables._g_a_s_p # macfreeze: include fontTools.ttLib.tables._g_l_y_f # macfreeze: include fontTools.ttLib.tables._h_d_m_x # macfreeze: include fontTools.ttLib.tables._h_e_a_d # macfreeze: include fontTools.ttLib.tables._h_h_e_a # macfreeze: include fontTools.ttLib.tables._h_m_t_x # macfreeze: include fontTools.ttLib.tables._k_e_r_n # macfreeze: include fontTools.ttLib.tables._l_o_c_a # macfreeze: include fontTools.ttLib.tables._m_a_x_p # macfreeze: include fontTools.ttLib.tables._n_a_m_e # macfreeze: include fontTools.ttLib.tables._p_o_s_t # macfreeze: include fontTools.ttLib.tables._p_r_e_p # macfreeze: include fontTools.ttLib.tables._v_h_e_a # macfreeze: include fontTools.ttLib.tables._v_m_t_x # macfreeze: include fontTools.ttLib.tables.L_T_S_H_ # macfreeze: include fontTools.ttLib.tables.O_S_2f_2 # macfreeze: include fontTools.ttLib.tables.T_S_I__0 # macfreeze: include fontTools.ttLib.tables.T_S_I__1 # macfreeze: include fontTools.ttLib.tables.T_S_I__2 # macfreeze: include fontTools.ttLib.tables.T_S_I__3 # macfreeze: include fontTools.ttLib.tables.T_S_I__5 # macfreeze: include fontTools.ttLib.tables.C_F_F_
[ 37811, 13383, 26653, 55, 3586, 11, 4100, 12, 8807, 37811, 628, 198, 2, 15883, 1654, 356, 836, 470, 4425, 2995, 284, 25861, 2606, 55, 198, 11748, 4100, 2640, 198, 14155, 2640, 13, 36695, 4677, 31943, 32590, 16, 8, 198, 198, 7248, 10723...
2.583333
1,092
#!/usr/bin/env python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import os import sys import logging import __builtin__ from google.appengine.ext.webapp import util # Enable info logging by the app (this is separate from appserver's # logging). logging.getLogger().setLevel(logging.INFO) # Force sys.path to have our own directory first, so we can import from it. sys.path.insert(0, os.path.abspath(os.path.dirname(__file__))) os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' try: from django import v1_5 as django except ImportError: pass # Import the part of Django that we use here. import django.core.handlers.wsgi if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 198, 2, 15069, 4343, 3012, 3457, 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, ...
3.288828
367
from unittest import TestCase from scrapy.exporters import JsonLinesItemExporter, JsonItemExporter from scrapy.settings import BaseSettings, default_settings from s3pipeline import S3Pipeline from s3pipeline.strategies.s3 import S3Strategy from s3pipeline.strategies.gcs import GCSStrategy
[ 6738, 555, 715, 395, 1330, 6208, 20448, 198, 198, 6738, 15881, 88, 13, 1069, 1819, 1010, 1330, 449, 1559, 43, 1127, 7449, 3109, 26634, 11, 449, 1559, 7449, 3109, 26634, 198, 6738, 15881, 88, 13, 33692, 1330, 7308, 26232, 11, 4277, 62,...
3.052083
96
""" Vim YouCompleteMe""" import pathlib
[ 37811, 36645, 921, 20988, 5308, 37811, 198, 11748, 3108, 8019, 198 ]
3.636364
11
import base64 enc_response = base64.b64encode(flow.getVariable("sf.response")) flow.setVariable("sf.response", enc_response)
[ 11748, 2779, 2414, 198, 12685, 62, 26209, 796, 2779, 2414, 13, 65, 2414, 268, 8189, 7, 11125, 13, 1136, 43015, 7203, 28202, 13, 26209, 48774, 198, 11125, 13, 2617, 43015, 7203, 28202, 13, 26209, 1600, 2207, 62, 26209, 8 ]
3.179487
39
# -*- coding: utf-8 -*- ########################################################################### # Copyright (c), The AiiDA team. All rights reserved. # # This file is part of the AiiDA code. # # # # The code is hosted on GitHub at https://github.com/aiidateam/aiida-core # # For further information on the license, see the LICENSE.txt file # # For further information please visit http://www.aiida.net # ########################################################################### """A temporary backend, using an in-memory sqlite database. This backend is intended for testing and demonstration purposes. Whenever it is instantiated, it creates a fresh storage backend, and destroys it when it is garbage collected. """ # AUTO-GENERATED # yapf: disable # pylint: disable=wildcard-import from .backend import * __all__ = ( 'SqliteTempBackend', ) # yapf: enable
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 29113, 29113, 7804, 21017, 198, 2, 15069, 357, 66, 828, 383, 317, 4178, 5631, 1074, 13, 1439, 2489, 10395, 13, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, ...
2.675393
382
"""connection full name Revision ID: e1855559096 Revises: 401bc82cc255 Create Date: 2015-09-26 17:40:20.742180 """ # revision identifiers, used by Alembic. revision = 'e1855559096' down_revision = '401bc82cc255' from alembic import op import sqlalchemy as sa
[ 37811, 38659, 1336, 1438, 198, 198, 18009, 1166, 4522, 25, 304, 1507, 2816, 38605, 2931, 21, 198, 18009, 2696, 25, 22219, 15630, 6469, 535, 13381, 198, 16447, 7536, 25, 1853, 12, 2931, 12, 2075, 1596, 25, 1821, 25, 1238, 13, 22, 3682,...
2.65
100
import logging from typing import Iterator from my_foo_project.foo import Foo from my_foo_project.client import foo_pb2 from optionalgrpc import IS_RUNNING_LOCAL
[ 11748, 18931, 198, 6738, 19720, 1330, 40806, 1352, 198, 198, 6738, 616, 62, 21943, 62, 16302, 13, 21943, 1330, 36080, 198, 6738, 616, 62, 21943, 62, 16302, 13, 16366, 1330, 22944, 62, 40842, 17, 198, 6738, 11902, 2164, 14751, 1330, 3180...
3.346939
49
__author__ = "jwely" __all__ = ["to_numpy"] from is_rast import is_rast from metadata import metadata import os import arcpy import numpy def to_numpy(raster, numpy_datatype = None): """ Wrapper for arcpy.RasterToNumpyArray with better metadata handling This is just a wraper for the RasterToNumPyArray function within arcpy, but it also extracts out all the spatial referencing information that will probably be needed to save the raster after desired manipulations have been performed. also see raster.from_numpy function in this module. :param raster: Any raster supported by the arcpy.RasterToNumPyArray function :param numpy_datatype: must be a string equal to any of the types listed at the following address [http://docs.scipy.org/doc/numpy/user/basics.types.html] for example: 'uint8' or 'int32' or 'float32' :return numpy_rast: the numpy array version of the input raster :return Metadata: a metadata object. see ``raster.metadata`` """ # perform some checks to convert to supported data format if not is_rast(raster): try: print("Raster '{0}' may not be supported, converting to tif".format(raster)) tifraster = raster + ".tif" if not os.path.exists(raster + ".tif"): arcpy.CompositeBands_management(raster, tifraster) raster = tifraster except: raise Exception("Raster type could not be recognized") # read in the raster as a numpy array numpy_rast = arcpy.RasterToNumPyArray(raster) # build metadata for multi band raster if len(numpy_rast.shape) == 3: zs, ys, xs = numpy_rast.shape meta = [] for i in range(zs): bandpath = raster + "\\Band_{0}".format(i+1) meta.append(metadata(bandpath, xs, ys)) if numpy_datatype is None: numpy_datatype = meta[0].numpy_datatype # build metadata for single band raster else: ys, xs = numpy_rast.shape meta = metadata(raster, xs, ys) if numpy_datatype is None: numpy_datatype = meta.numpy_datatype numpy_rast = numpy_rast.astype(numpy_datatype) # mask NoData values from the array if 'float' in numpy_datatype: numpy_rast[numpy_rast == meta.NoData_Value] = numpy.nan numpy_rast = numpy.ma.masked_array(numpy_rast, numpy.isnan(numpy_rast), dtype = numpy_datatype) elif 'int' in numpy_datatype: # (numpy.nan not supported by ints) mask = numpy.zeros(numpy_rast.shape) mask[numpy_rast != meta.NoData_Value] = False # do not mask mask[numpy_rast == meta.NoData_Value] = True # mask numpy_rast = numpy.ma.masked_array(numpy_rast, mask, dtype = numpy_datatype) return numpy_rast, meta # testing area if __name__ == "__main__": path = r"C:\Users\jwely\Desktop\troubleshooting\test\MOD10A1\frac_snow\MYD09GQ.A2015160.h18v02.005.2015162071112_000.tif" rast, meta = to_numpy(path)
[ 834, 9800, 834, 796, 366, 73, 732, 306, 1, 198, 834, 439, 834, 796, 14631, 1462, 62, 77, 32152, 8973, 628, 198, 6738, 318, 62, 5685, 1330, 318, 62, 5685, 198, 6738, 20150, 1330, 20150, 198, 198, 11748, 28686, 198, 11748, 10389, 9078...
2.262366
1,395
from output.models.nist_data.list_pkg.duration.schema_instance.nistschema_sv_iv_list_duration_length_2_xsd.nistschema_sv_iv_list_duration_length_2 import NistschemaSvIvListDurationLength2 __all__ = [ "NistschemaSvIvListDurationLength2", ]
[ 6738, 5072, 13, 27530, 13, 77, 396, 62, 7890, 13, 4868, 62, 35339, 13, 32257, 13, 15952, 2611, 62, 39098, 13, 77, 1023, 2395, 2611, 62, 21370, 62, 452, 62, 4868, 62, 32257, 62, 13664, 62, 17, 62, 87, 21282, 13, 77, 1023, 2395, 2...
2.541667
96
from lxml import etree import os import sys import shutil import iwjam_util # Performs an import of a mod project into a base project given a # previously computed ProjectDiff between them, # and a list of folder names to prefix # ('%modname%' will be replaced with the mod's name)
[ 6738, 300, 19875, 1330, 2123, 631, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 4423, 346, 198, 11748, 1312, 86, 39159, 62, 22602, 198, 198, 2, 2448, 23914, 281, 1330, 286, 257, 953, 1628, 656, 257, 2779, 1628, 1813, 257, 198, 2,...
3.423529
85
import numpy as np import matplotlib.pyplot as plt """ SDA.py: Plots the probability of the SDA model generating a connection based on different parameters for Figure 2.4. """ n = 3 alphas = [2, 3, 8] betas = [2, 3, 5] colors = ['r', 'g', 'b'] d = np.arange(0.0, 10.0, 0.1) ax = plt.subplot() for i in range(n): res = prop(alphas[i], betas[i], d) label = 'alpha= {}, beta= {}'.format(alphas[i], betas[i]) ax.plot(d, res, color=colors[i], label=label) plt.xlabel('d(i,j)') plt.ylabel('p(i,j)') plt.legend() plt.show()
[ 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 198, 37811, 198, 220, 220, 220, 311, 5631, 13, 9078, 25, 1345, 1747, 262, 12867, 286, 262, 311, 5631, 2746, 15453, 257, 4637, 198, 220, ...
2.189516
248
import pandas as pd from sklearn.model_selection._split import _BaseKFold from partition_optimizers import equally_partition_into_bins, mixed_equally_partition_into_bins # Using get_n_splits from the super class.
[ 11748, 19798, 292, 355, 279, 67, 198, 6738, 1341, 35720, 13, 19849, 62, 49283, 13557, 35312, 1330, 4808, 14881, 42, 37, 727, 198, 6738, 18398, 62, 40085, 11341, 1330, 8603, 62, 3911, 653, 62, 20424, 62, 65, 1040, 11, 7668, 62, 4853, ...
3.19403
67
# Generated by Django 2.1.5 on 2019-03-31 08:34 from django.db import migrations, models import django.db.models.deletion
[ 2, 2980, 515, 416, 37770, 362, 13, 16, 13, 20, 319, 13130, 12, 3070, 12, 3132, 8487, 25, 2682, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 11748, 42625, 14208, 13, 9945, 13, 27530, 13, 2934, 1616, 295, ...
2.818182
44
import numpy from numpy import genfromtxt my_data = genfromtxt('matrix.csv', delimiter=',') def bin_ndarray(ndarray, new_shape, operation='sum'): """ Bins an ndarray in all axes based on the target shape, by summing or averaging. Number of output dimensions must match number of input dimensions and new axes must divide old ones. Example ------- >>> m = numpy.arange(0,100,1).reshape((10,10)) >>> n = bin_ndarray(m, new_shape=(5,5), operation='sum') >>> print(n) [[ 22 30 38 46 54] [102 110 118 126 134] [182 190 198 206 214] [262 270 278 286 294] [342 350 358 366 374]] """ operation = operation.lower() if not operation in ['sum', 'mean']: raise ValueError("Operation not supported.") if ndarray.ndim != len(new_shape): raise ValueError("Shape mismatch: {} -> {}".format(ndarray.shape, new_shape)) compression_pairs = [(d, c//d) for d,c in zip(new_shape, ndarray.shape)] flattened = [l for p in compression_pairs for l in p] ndarray = ndarray.reshape(flattened) for i in range(len(new_shape)): op = getattr(ndarray, operation) ndarray = op(-1*(i+1)) return ndarray def resize_array(a, new_rows, new_cols): ''' This function takes an 2D numpy array a and produces a smaller array of size new_rows, new_cols. new_rows and new_cols must be less than or equal to the number of rows and columns in a. ''' rows = len(a) cols = len(a[0]) yscale = float(rows) / new_rows xscale = float(cols) / new_cols # first average across the cols to shorten rows new_a = numpy.zeros((rows, new_cols)) for j in range(new_cols): # get the indices of the original array we are going to average across the_x_range = (j*xscale, (j+1)*xscale) firstx = int(the_x_range[0]) lastx = int(the_x_range[1]) # figure out the portion of the first and last index that overlap # with the new index, and thus the portion of those cells that # we need to include in our average x0_scale = 1 - (the_x_range[0]-int(the_x_range[0])) xEnd_scale = (the_x_range[1]-int(the_x_range[1])) # scale_line is a 1d array that corresponds to the portion of each old # index in the_x_range that should be included in the new average scale_line = numpy.ones((lastx-firstx+1)) scale_line[0] = x0_scale scale_line[-1] = xEnd_scale # Make sure you don't screw up and include an index that is too large # for the array. This isn't great, as there could be some floating # point errors that mess up this comparison. if scale_line[-1] == 0: scale_line = scale_line[:-1] lastx = lastx - 1 # Now it's linear algebra time. Take the dot product of a slice of # the original array and the scale_line new_a[:,j] = numpy.dot(a[:firstx:lastx+1], scale_line)/scale_line.sum() # Then average across the rows to shorten the cols. Same method as above. # It is probably possible to simplify this code, as this is more or less # the same procedure as the block of code above, but transposed. # Here I'm reusing the variable a. Sorry if that's confusing. a = numpy.zeros((new_rows, new_cols)) for i in range(new_rows): the_y_range = (i*yscale, (i+1)*yscale) firsty = int(the_y_range[0]) lasty = int(the_y_range[1]) y0_scale = 1 - (the_y_range[0]-int(the_y_range[0])) yEnd_scale = (the_y_range[1]-int(the_y_range[1])) scale_line = numpy.ones((lasty-firsty+1)) scale_line[0] = y0_scale scale_line[-1] = yEnd_scale if scale_line[-1] == 0: scale_line = scale_line[:-1] lasty = lasty - 1 a[i:,] = numpy.dot(scale_line, new_a[firsty:lasty+1,])/scale_line.sum() return a red = [ [1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0], [1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1], [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1], [1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0], [1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1], [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1], [1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0], [1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1], [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1], [1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0], [1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1], [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1], ] green = [ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], ] blue = [ [1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0], [1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0], [1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0], [1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0], [1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0], [1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0], [1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0], [1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0], [1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0], [1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0], [1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0], [1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0], [1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0], [1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0], [1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0], [1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0], ] rgb = numpy.array([ red, green, blue ]) big = [ [1, 1, 0, 0, 1, 1, 0, 0], [1, 1, 0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 0, 0, 1, 1], [0, 0, 1, 1, 0, 0, 1, 1], [1, 1, 0, 0, 1, 1, 0, 0], [1, 1, 0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 0, 0, 1, 1], [0, 0, 1, 1, 0, 0, 1, 1], ] fac2_small = [ [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], ] fac4_small = [ [0.5, 0.5], [0.5, 0.5], ] fac = 2 new_arr = [] # s = [0, 1, 2, 3, 4, 5] # len(s) = 6 # ci = 7 # if ci < len(s) print("\n------------------------") print("Original") print("========================") for row in big: print(row) print("\n--------------------") print("50%") print("====================") small2 = alex2_meth(big, 2) for row in small2: print(row) print("\n----------") print("33%") print("==========") small4 = alex2_meth(big, 3) for row in small4: print(row) print("\n----------") print("25%") print("==========") small4 = alex2_meth(big, 4) for row in small4: print(row)
[ 11748, 299, 32152, 628, 198, 6738, 299, 32152, 1330, 2429, 6738, 14116, 198, 1820, 62, 7890, 796, 2429, 6738, 14116, 10786, 6759, 8609, 13, 40664, 3256, 46728, 2676, 28, 3256, 11537, 628, 198, 4299, 9874, 62, 358, 18747, 7, 358, 18747, ...
1.878359
4,094
from django.shortcuts import render from django.views.generic import View from django.shortcuts import render, redirect, HttpResponseRedirect, reverse, HttpResponse from alipay import Alipay import time import string import random import json from operation.models import ShoppingCart, Shopping from .models import * from scenicspots.models import Spots, Active from utils.mixin_utils import LoginRequiredMixin from treval import settings def create_alipay(): """ 创建支付宝对象 :return: 支付宝对象 """ alipay = Alipay( appid=settings.ALIPAY_APPID, # 回调地址 app_notify_url=None, # 公钥路径 alipay_public_key_path=settings.ALIPAY_PUBLIC_KEY_PATH, # 私钥路径 app_private_key_path=settings.APP_PRIVATE_KEY_PATH, # 加密方式 sign_type='RSA2', debug=True, ) return alipay def creat_order_num(user_id): """ 生成订单号 :param user_id: 用户id :return: 订单号 """ time_stamp = int(round(time.time() * 1000)) randomnum = '%04d' % random.randint(0, 100000) order_num = str(time_stamp) + str(randomnum) + str(user_id) return order_num def creat_cdk(): """ 创建cdk :return: cdk """ cdk_area = string.digits + string.ascii_letters cdk = '' for i in range(1, 21): cdk += random.choice(cdk_area) # 获取随机字符或数字 if i % 5 == 0 and i != 20: # 每隔4个字符增加'-' cdk += '-' return cdk def check_cdk(): """ cdk检测 :return: cdk """ # 首先创建一个cdk cdk = creat_cdk() try: # 如果能查到订单 order = ScenicOrdersMainTable.objects.get(cdk=cdk) # 重新执行检测 check_cdk() except: # 没找到就返回这个cdk return cdk # Create your views here. class AliPayTestView(View): """ 支付宝测试 """ class SubmitOrderView(LoginRequiredMixin, View): """ 提交订单 """ class FinishPayView(View): """ 支付完成后执行的操作 """ class ProjectOrderView(View): """ 商品订单页面 """ class SubmitTravelsOrderView(View): """ 旅游订单提交 """ class ScenicOrderView(View): """ 旅游订单页面 """
[ 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 198, 6738, 42625, 14208, 13, 33571, 13, 41357, 1330, 3582, 198, 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 11, 18941, 11, 367, 29281, 31077, 7738, 1060, 11, 9575, 11, 367, 29281, ...
1.767812
1,193
from decimal import Decimal import urllib import requests from authorize.exceptions import AuthorizeConnectionError, \ AuthorizeResponseError PROD_URL = 'https://secure.authorize.net/gateway/transact.dll' TEST_URL = 'https://test.authorize.net/gateway/transact.dll' RESPONSE_FIELDS = { 0: 'response_code', 2: 'response_reason_code', 3: 'response_reason_text', 4: 'authorization_code', 5: 'avs_response', 6: 'transaction_id', 9: 'amount', 11: 'transaction_type', 38: 'cvv_response', }
[ 6738, 32465, 1330, 4280, 4402, 198, 11748, 2956, 297, 571, 198, 11748, 7007, 198, 198, 6738, 29145, 13, 1069, 11755, 1330, 6434, 1096, 32048, 12331, 11, 3467, 198, 220, 220, 220, 6434, 1096, 31077, 12331, 628, 198, 4805, 3727, 62, 21886...
2.516432
213
# Copyright 2008-2018 Univa Corporation # # 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. # pylint: disable=no-member import gettext from tortuga.cli.tortugaCli import TortugaCli from tortuga.helper.osHelper import getOsInfo from tortuga.wsapi.kitWsApi import KitWsApi from tortuga.wsapi.nodeWsApi import NodeWsApi from tortuga.wsapi.softwareProfileWsApi import SoftwareProfileWsApi _ = gettext.gettext
[ 2, 15069, 3648, 12, 7908, 791, 12151, 10501, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 2...
3.463602
261
# coding: utf-8 # Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401 from oci.decorators import init_model_state_from_kwargs @init_model_state_from_kwargs class SoftwarePackageFile(object): """ A file associated with a package """ def __init__(self, **kwargs): """ Initializes a new SoftwarePackageFile object with values from keyword arguments. The following keyword arguments are supported (corresponding to the getters/setters of this class): :param path: The value to assign to the path property of this SoftwarePackageFile. :type path: str :param type: The value to assign to the type property of this SoftwarePackageFile. :type type: str :param time_modified: The value to assign to the time_modified property of this SoftwarePackageFile. :type time_modified: datetime :param checksum: The value to assign to the checksum property of this SoftwarePackageFile. :type checksum: str :param checksum_type: The value to assign to the checksum_type property of this SoftwarePackageFile. :type checksum_type: str :param size_in_bytes: The value to assign to the size_in_bytes property of this SoftwarePackageFile. :type size_in_bytes: int """ self.swagger_types = { 'path': 'str', 'type': 'str', 'time_modified': 'datetime', 'checksum': 'str', 'checksum_type': 'str', 'size_in_bytes': 'int' } self.attribute_map = { 'path': 'path', 'type': 'type', 'time_modified': 'timeModified', 'checksum': 'checksum', 'checksum_type': 'checksumType', 'size_in_bytes': 'sizeInBytes' } self._path = None self._type = None self._time_modified = None self._checksum = None self._checksum_type = None self._size_in_bytes = None @property def path(self): """ Gets the path of this SoftwarePackageFile. file path :return: The path of this SoftwarePackageFile. :rtype: str """ return self._path @path.setter def path(self, path): """ Sets the path of this SoftwarePackageFile. file path :param path: The path of this SoftwarePackageFile. :type: str """ self._path = path @property def type(self): """ Gets the type of this SoftwarePackageFile. type of the file :return: The type of this SoftwarePackageFile. :rtype: str """ return self._type @type.setter def type(self, type): """ Sets the type of this SoftwarePackageFile. type of the file :param type: The type of this SoftwarePackageFile. :type: str """ self._type = type @property def time_modified(self): """ Gets the time_modified of this SoftwarePackageFile. The date and time of the last modification to this file, as described in `RFC 3339`__, section 14.29. __ https://tools.ietf.org/rfc/rfc3339 :return: The time_modified of this SoftwarePackageFile. :rtype: datetime """ return self._time_modified @time_modified.setter def time_modified(self, time_modified): """ Sets the time_modified of this SoftwarePackageFile. The date and time of the last modification to this file, as described in `RFC 3339`__, section 14.29. __ https://tools.ietf.org/rfc/rfc3339 :param time_modified: The time_modified of this SoftwarePackageFile. :type: datetime """ self._time_modified = time_modified @property def checksum(self): """ Gets the checksum of this SoftwarePackageFile. checksum of the file :return: The checksum of this SoftwarePackageFile. :rtype: str """ return self._checksum @checksum.setter def checksum(self, checksum): """ Sets the checksum of this SoftwarePackageFile. checksum of the file :param checksum: The checksum of this SoftwarePackageFile. :type: str """ self._checksum = checksum @property def checksum_type(self): """ Gets the checksum_type of this SoftwarePackageFile. type of the checksum :return: The checksum_type of this SoftwarePackageFile. :rtype: str """ return self._checksum_type @checksum_type.setter def checksum_type(self, checksum_type): """ Sets the checksum_type of this SoftwarePackageFile. type of the checksum :param checksum_type: The checksum_type of this SoftwarePackageFile. :type: str """ self._checksum_type = checksum_type @property def size_in_bytes(self): """ Gets the size_in_bytes of this SoftwarePackageFile. size of the file in bytes :return: The size_in_bytes of this SoftwarePackageFile. :rtype: int """ return self._size_in_bytes @size_in_bytes.setter def size_in_bytes(self, size_in_bytes): """ Sets the size_in_bytes of this SoftwarePackageFile. size of the file in bytes :param size_in_bytes: The size_in_bytes of this SoftwarePackageFile. :type: int """ self._size_in_bytes = size_in_bytes
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 2, 15069, 357, 66, 8, 1584, 11, 12131, 11, 18650, 290, 14, 273, 663, 29116, 13, 220, 1439, 2489, 10395, 13, 198, 2, 770, 3788, 318, 10668, 12, 36612, 284, 345, 739, 262, 14499, 2448, 33532, 1...
2.359844
2,565
import os import btree from .util import file_exists DBNAME = 'defines.db'
[ 11748, 28686, 198, 11748, 275, 21048, 198, 6738, 764, 22602, 1330, 2393, 62, 1069, 1023, 198, 198, 11012, 20608, 796, 705, 4299, 1127, 13, 9945, 6, 628 ]
2.851852
27
from app.bootstrap.configmanager import ConfigManager DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'USER': ConfigManager.get('db.user'), 'NAME': ConfigManager.get('db.name'), 'PASSWORD': ConfigManager.get('db.pass'), 'HOST': ConfigManager.get('db.host'), 'PORT': ConfigManager.get('db.port'), } } migration_subfolder = ConfigManager.get('main.migration_branch_name') if not migration_subfolder: migration_subfolder = 'unnamed' MIGRATION_MODULES = {'app': f'migrations.{migration_subfolder}'} DEFAULT_AUTO_FIELD = 'django.db.models.AutoField'
[ 6738, 598, 13, 18769, 26418, 13, 11250, 37153, 1330, 17056, 13511, 198, 198, 35, 1404, 6242, 1921, 1546, 796, 1391, 198, 220, 220, 220, 705, 12286, 10354, 1391, 198, 220, 220, 220, 220, 220, 220, 220, 705, 26808, 8881, 10354, 705, 282...
2.451362
257
import turtle #module tha drawn things draw_square()
[ 11748, 28699, 1303, 21412, 28110, 7428, 1243, 198, 19334, 62, 23415, 3419, 628, 198 ]
3.928571
14
import pytest from jarg.dialects import FormDialect, JSONDialect
[ 11748, 12972, 9288, 198, 198, 6738, 474, 853, 13, 38969, 478, 82, 1330, 5178, 24400, 478, 11, 19449, 24400, 478, 628, 628 ]
3.136364
22
# -*- coding: utf-8 -*- # Copyright 2021 Cohesity Inc. class NfsConnection(object): """Implementation of the 'NfsConnection' model. :TODO Type description here. Attributes: client_ip (string): Information of a Universal Data Adapter cluster, only valid for an entity of view_name kCluster. node_ip (string): Specifies a Node IP address where the connection request is received. server_ip (string): Specifies the Server IP address of the connection. This could be a VIP, VLAN IP, or node IP on the Cluster. view_id (long|int): Specifies the id of the view. view_name (string): Specifies the name of the view. """ # Create a mapping from Model property names to API property names _names = { "client_ip":'clientIp', "node_ip":'nodeIp', "server_ip":'serverIp', "view_id":'viewId', "view_name":'viewName' } def __init__(self, client_ip=None, node_ip=None, server_ip=None, view_id=None, view_name=None): """Constructor for the NfsConnection class""" # Initialize members of the class self.client_ip = client_ip self.node_ip = node_ip self.server_ip = server_ip self.view_id = view_id self.view_name = view_name @classmethod def from_dictionary(cls, dictionary): """Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the object as obtained from the deserialization of the server's response. The keys MUST match property names in the API description. Returns: object: An instance of this structure class. """ if dictionary is None: return None # Extract variables from the dictionary client_ip = dictionary.get('clientIp') node_ip = dictionary.get('nodeIp') server_ip = dictionary.get('serverIp') view_id = dictionary.get('viewId') view_name = dictionary.get('viewName') # Return an object of this model return cls(client_ip, node_ip, server_ip, view_id, view_name)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 15069, 33448, 1766, 956, 414, 3457, 13, 198, 198, 4871, 399, 9501, 32048, 7, 15252, 2599, 628, 220, 220, 220, 37227, 3546, 32851, 286, 262, 705, 45, 9501, 32048, 6,...
2.247191
1,068
import os.path, sys from modules.windows_jumplist.consts import * from ctypes import * from modules.windows_jumplist.lib.delphi import * from modules.windows_jumplist.lib.yjSysUtils import * from modules.windows_jumplist.lib.yjDateTime import * from modules.windows_jumplist.LNKFileParser import TLNKFileParser from modules.windows_jumplist.lib import olefile # https://pypi.org/project/olefile/ from modules.windows_jumplist.lib.yjSQLite3 import TSQLite3 def split_filename(fn): """ 경로가 포함된 파일명 텍스트를 ['경로', '파일명', '파일확장자'] 로 나눈다. """ v = os.path.splitext(fn) fileext = v[1] v = os.path.split(v[0]) if (fileext == '') and (len(v[1]) > 0) and (v[1][0] == '.'): v = list(v) fileext = v[1] v[1] = '' return [v[0], v[1], fileext] def get_files(path, w = '*'): """ 지정 경로의 파일목록을 구한다. """ if os.path.isdir(path): import glob try: path = IncludeTrailingBackslash(path) return [v for v in glob.glob(path + w) if os.path.isfile(v)] finally: del glob else: return [] fileext_customdestination = '.customdestinations-ms' fileext_automaticdestinations = '.automaticdestinations-ms' FILE_ATTRIBUTE_READONLY = 0x00000001 FILE_ATTRIBUTE_HIDDEN = 0x00000002 FILE_ATTRIBUTE_SYSTEM = 0x00000004 FILE_ATTRIBUTE_DIRECTORY = 0x00000010 FILE_ATTRIBUTE_ARCHIVE = 0x00000020 # DestListEntry : https://bonggang.tistory.com/120 """ if sys.version_info < (3, 8): print('\'%s\' \r\nError: \'%s\' works on Python v3.8 and above.' % (sys.version, ExtractFileName(__file__))) exit(1) """ """ if __name__ == "__main__": app_path = IncludeTrailingBackslash(os.path.dirname(os.path.abspath( __file__ ))) main(sys.argv, len(sys.argv)) """
[ 11748, 28686, 13, 6978, 11, 25064, 198, 198, 6738, 13103, 13, 28457, 62, 73, 388, 489, 396, 13, 1102, 6448, 1330, 1635, 198, 6738, 269, 19199, 1330, 1635, 198, 6738, 13103, 13, 28457, 62, 73, 388, 489, 396, 13, 8019, 13, 12381, 3484...
2.057715
849
import RPi.GPIO as GPIO import binascii import time GPIO.setmode(GPIO.BCM) GPIO.setup(12, GPIO.OUT) GPIO.setup(16, GPIO.OUT) GPIO.setup(5, GPIO.OUT) GPIO.setup(6, GPIO.OUT) GPIO.setup(13, GPIO.OUT) GPIO.setup(19, GPIO.OUT) pin = [12, 16, 5, 6, 13, 19] k = 0 st="110101011010111" cols = 6 rows = len(st)/3 arr = [[0]*cols]*rows for i in range(rows): if st[k] == '0': arr[i][0] = 1 else: arr[i][1] = 1 if st[k+1] == '0' and st[k+2] == '0': arr[i][2] = 1 elif st[k+1] == '0' and st[k+2] == '1': arr[i][3] = 1 elif st[k+1] == '1' and st[k+2] == '0': arr[i][4] = 1 elif st[k+1] == '1' and st[k+2] == '1': arr[i][5] = 1 k = k+3 while True: for i in range(rows): for j in range(cols): GPIO.output(pin[j], arr[i][j]) time.sleep(0.01) GPIO.cleanup()
[ 11748, 25812, 72, 13, 16960, 9399, 355, 50143, 198, 11748, 9874, 292, 979, 72, 198, 11748, 640, 198, 198, 16960, 9399, 13, 2617, 14171, 7, 16960, 9399, 13, 2749, 44, 8, 198, 16960, 9399, 13, 40406, 7, 1065, 11, 50143, 13, 12425, 8, ...
1.83848
421
# coding=utf-8 import os import re import string from string import Template if __name__ == '__main__': root_dir = os.path.dirname(os.path.abspath(__file__)) input_file = open(os.path.join(root_dir, 'input.cpp'), 'r', encoding='gb18030', errors='ignore') out_file = open(os.path.join(root_dir, 'output.cpp'), 'w', encoding='gb18030') template_http_api_file = open( os.path.join(root_dir, os.path.join('template', 'tcp_api.template')), 'r') attri_tmpl = Template('JY_PROPERTY_READWRITE($type_name, $var_up_name) \t\t') request_param_tmpl = Template('params.insert("$var_name", _$var_up_name);\n') response_replace_tmpl = Template('map.insert("$var_up_name","$var_name");\n') constructor_tmpl = Template('this->_$var_up_name\t\t\t= obj._$var_up_name;\n') http_api_tmpl = Template(template_http_api_file.read()) line_first = input_file.readline().split() class_name = line_first[0] request_type = line_first[1] module_id = line_first[2] response_name = class_name if 'Notify' not in response_name: response_name += 'Response' print(class_name, request_type, module_id, response_name) input_file.readline() #空行 request_attri = '' request_param = '' response_constructor = '' response_attri = '' response_replace = '' table = str.maketrans({key: None for key in string.punctuation}) # new_s = s.translate(table) while 1: line = input_file.readline() line = line.strip() if not line: break attri_name, attri_up_name, attri_type, comment = fun_get_attri(line) attri_item = attri_tmpl.safe_substitute(type_name=attri_type, var_up_name=attri_up_name) request_attri += ' ' + attri_item + comment + '\n' param_item = request_param_tmpl.safe_substitute(var_name=attri_name, var_up_name=attri_up_name) request_param += ' ' + param_item while 1: line = input_file.readline() line = line.strip() if not line: break attri_name, attri_up_name, attri_type, comment = fun_get_attri(line) attri_item = attri_tmpl.safe_substitute(type_name=attri_type, var_up_name=attri_up_name) response_attri += ' ' + attri_item + comment + '\n' replace_item = response_replace_tmpl.safe_substitute(var_name=attri_name, var_up_name=attri_up_name) response_replace += ' ' + replace_item str_out = http_api_tmpl.safe_substitute(str_api_class=class_name, str_api_class_response=response_name, str_request_type=request_type, str_module_id=module_id, str_request_atti=request_attri, str_request_params=request_param, str_response_atti=response_attri, str_response_replace=response_replace) out_file.write(str_out) print(request_attri) print(request_param) print(response_attri) print(response_replace) input_file.close() out_file.close()
[ 2, 19617, 28, 40477, 12, 23, 198, 198, 11748, 28686, 198, 11748, 302, 198, 11748, 4731, 198, 6738, 4731, 1330, 37350, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 6808, 62, 15908, 796, 28686,...
2.333861
1,264
import pandas as pd import sys import os deep_go_data = sys.argv[1] dataset_path_in = sys.argv[2] dataset_path_out = sys.argv[3] go_file_out = sys.argv[4] df = pd.read_pickle(deep_go_data) targets = list(df.targets) gos = list(df.gos) go_freqs = {} target2go = dict(zip(targets, gos)) target_path = os.path.join(dataset_path_in, 'Target files') map_path = os.path.join(dataset_path_in, 'Mapping files') file_numbers = [] map_files = os.listdir(map_path) sp_map_files = [f for f in map_files if 'sp_species' in f] for file in sp_map_files: file_numbers.append(file.split('.')[1]) with open(dataset_path_out, 'w') as ofile: for file_number in file_numbers: print('Working with file {}'.format(file_number)) target_file = os.path.join(target_path, 'target.{}.fasta'.format(file_number)) # retrieve gos from uniprot seq = "" saving = False with open(target_file, 'r') as ifile: for line in ifile: if line.startswith('>'): if saving: saving = False gos = target2go[target_id] for go in gos: if not go in go_freqs: go_freqs[go] = 1 else: go_freqs[go] += 1 if not len(seq) > 1000: if not len(gos) == 0: ofile.write('{};{};{}\n'.format(target_id, seq, ','.join(gos))) else: print('No gos found for target {}'.format(target_id)) else: print('Sequence too long for target {}'.format(target_id)) seq = "" target_id = line[1:].split()[0].strip() if target_id in target2go: print('OK for tareget {}'.format(target_id)) targets.remove(target_id) saving = True else: saving = False else: if saving: seq += line.strip() print('Did not find entries for:\n{}'.format('\n'.join(targets))) go_freq_keys = sorted(list(go_freqs.keys()), key=lambda x: -go_freqs[x]) with open(go_file_out, 'w') as ofile: for go in go_freq_keys: ofile.write(' {} {}.csv\n'.format(go_freqs[go], go))
[ 11748, 19798, 292, 355, 279, 67, 198, 11748, 25064, 198, 11748, 28686, 198, 198, 22089, 62, 2188, 62, 7890, 796, 25064, 13, 853, 85, 58, 16, 60, 198, 19608, 292, 316, 62, 6978, 62, 259, 796, 25064, 13, 853, 85, 58, 17, 60, 198, ...
1.751743
1,434
import requests, json from bs4 import BeautifulSoup import shutil import os try: os.chdir('img') #means cd path except: print('path error') imageUrlPattern = 'http://www.watsons.com.tw' res =requests.get('http://www.watsons.com.tw/%E7%86%B1%E9%8A%B7%E5%95%86%E5%93%81/c/bestSeller?q=:igcBestSeller:category:1041&page=5&resultsForPage=30&text=&sort=') soup = BeautifulSoup(res.text) for i in soup.select('img'): try: fname = i['alt'] imageUrl = imageUrlPattern + i['src'] ires = requests.get(imageUrl,stream=True) f = open(fname,'wb') shutil.copyfileobj(ires.raw,f) f.close() del ires except Exception as e: print(i) print(e)
[ 11748, 7007, 11, 33918, 198, 6738, 275, 82, 19, 1330, 23762, 50, 10486, 198, 11748, 4423, 346, 198, 11748, 28686, 198, 28311, 25, 198, 220, 220, 220, 28686, 13, 354, 15908, 10786, 9600, 11537, 198, 220, 220, 220, 1303, 1326, 504, 2292...
2.102639
341
"""Implementation of the MediaRemoteTV Protocol used by ATV4 and later.""" import logging import asyncio from datetime import datetime from pyatv import (const, exceptions) from pyatv.mrp import (messages, protobuf) from pyatv.mrp.srp import SRPAuthHandler from pyatv.mrp.connection import MrpConnection from pyatv.mrp.protocol import MrpProtocol from pyatv.mrp.protobuf import CommandInfo_pb2, SetStateMessage_pb2 from pyatv.mrp.player_state import PlayerStateManager from pyatv.interface import (AppleTV, RemoteControl, Metadata, Playing, PushUpdater) _LOGGER = logging.getLogger(__name__) # Source: https://github.com/Daij-Djan/DDHidLib/blob/master/usb_hid_usages.txt _KEY_LOOKUP = { # name: [usage_page, usage, button hold time (seconds)] 'up': [1, 0x8C, 0], 'down': [1, 0x8D, 0], 'left': [1, 0x8B, 0], 'right': [1, 0x8A, 0], 'stop': [12, 0xB7, 0], 'next': [12, 0xB5, 0], 'previous': [12, 0xB6, 0], 'select': [1, 0x89, 0], 'menu': [1, 0x86, 0], 'top_menu': [12, 0x60, 0], 'home': [12, 0x40, 0], 'home_hold': [12, 0x40, 1], 'suspend': [1, 0x82, 0], 'volume_up': [12, 0xE9, 0], 'volume_down': [12, 0xEA, 0], # 'mic': [12, 0x04, 0], # Siri } class MrpRemoteControl(RemoteControl): """Implementation of API for controlling an Apple TV.""" def __init__(self, loop, protocol): """Initialize a new MrpRemoteControl.""" self.loop = loop self.protocol = protocol def up(self): """Press key up.""" return self._press_key('up') def down(self): """Press key down.""" return self._press_key('down') def left(self): """Press key left.""" return self._press_key('left') def right(self): """Press key right.""" return self._press_key('right') def play(self): """Press key play.""" return self.protocol.send(messages.command(CommandInfo_pb2.Play)) def pause(self): """Press key play.""" return self.protocol.send(messages.command(CommandInfo_pb2.Pause)) def stop(self): """Press key stop.""" return self.protocol.send(messages.command(CommandInfo_pb2.Stop)) def next(self): """Press key next.""" return self.protocol.send(messages.command(CommandInfo_pb2.NextTrack)) def previous(self): """Press key previous.""" return self.protocol.send( messages.command(CommandInfo_pb2.PreviousTrack)) def select(self): """Press key select.""" return self._press_key('select') def menu(self): """Press key menu.""" return self._press_key('menu') def volume_up(self): """Press key volume up.""" return self._press_key('volume_up') def volume_down(self): """Press key volume down.""" return self._press_key('volume_down') def home(self): """Press key home.""" return self._press_key('home') def home_hold(self): """Hold key home.""" return self._press_key('home_hold') def top_menu(self): """Go to main menu (long press menu).""" return self._press_key('top_menu') def suspend(self): """Suspend the device.""" return self._press_key('suspend') def set_position(self, pos): """Seek in the current playing media.""" return self.protocol.send(messages.seek_to_position(pos)) def set_shuffle(self, is_on): """Change shuffle mode to on or off.""" return self.protocol.send(messages.shuffle(is_on)) def set_repeat(self, repeat_mode): """Change repeat mode.""" # TODO: extract to convert module if int(repeat_mode) == const.REPEAT_STATE_OFF: state = 1 elif int(repeat_mode) == const.REPEAT_STATE_ALL: state = 2 elif int(repeat_mode) == const.REPEAT_STATE_TRACK: state = 3 else: raise ValueError('Invalid repeat mode: ' + str(repeat_mode)) return self.protocol.send(messages.repeat(state)) class MrpPlaying(Playing): """Implementation of API for retrieving what is playing.""" def __init__(self, state): """Initialize a new MrpPlaying.""" self._state = state @property def media_type(self): """Type of media is currently playing, e.g. video, music.""" if self._state.metadata: media_type = self._state.metadata.mediaType cim = protobuf.ContentItemMetadata_pb2.ContentItemMetadata if media_type == cim.Audio: return const.MEDIA_TYPE_MUSIC if media_type == cim.Video: return const.MEDIA_TYPE_VIDEO return const.MEDIA_TYPE_UNKNOWN @property def play_state(self): """Play state, e.g. playing or paused.""" if self._state is None: return const.PLAY_STATE_IDLE state = self._state.playback_state ssm = SetStateMessage_pb2.SetStateMessage if state == ssm.Playing: return const.PLAY_STATE_PLAYING if state == ssm.Paused: return const.PLAY_STATE_PAUSED if state == ssm.Stopped: return const.PLAY_STATE_STOPPED if state == ssm.Interrupted: return const.PLAY_STATE_LOADING # if state == SetStateMessage_pb2.Seeking # return XXX return const.PLAY_STATE_PAUSED @property def title(self): """Title of the current media, e.g. movie or song name.""" return self._state.metadata_field('title') @property def artist(self): """Artist of the currently playing song.""" return self._state.metadata_field('trackArtistName') @property def album(self): """Album of the currently playing song.""" return self._state.metadata_field('albumName') @property def genre(self): """Genre of the currently playing song.""" return self._state.metadata_field('genre') @property def total_time(self): """Total play time in seconds.""" duration = self._state.metadata_field('duration') return None if duration is None else int(duration) @property def position(self): """Position in the playing media (seconds).""" elapsed_time = self._state.metadata_field('elapsedTime') if elapsed_time: diff = (datetime.now() - self._state.timestamp).total_seconds() if self.play_state == const.PLAY_STATE_PLAYING: return int(elapsed_time + diff) return int(elapsed_time) return None @property def shuffle(self): """If shuffle is enabled or not.""" info = self._get_command_info(CommandInfo_pb2.ChangeShuffleMode) return None if info is None else info.shuffleMode @property def repeat(self): """Repeat mode.""" info = self._get_command_info(CommandInfo_pb2.ChangeRepeatMode) return None if info is None else info.repeatMode class MrpMetadata(Metadata): """Implementation of API for retrieving metadata.""" def __init__(self, psm, identifier): """Initialize a new MrpPlaying.""" super().__init__(identifier) self.psm = psm async def artwork(self): """Return artwork for what is currently playing (or None).""" raise exceptions.NotSupportedError async def playing(self): """Return what is currently playing.""" return MrpPlaying(self.psm.playing) class MrpPushUpdater(PushUpdater): """Implementation of API for handling push update from an Apple TV.""" def __init__(self, loop, metadata, psm): """Initialize a new MrpPushUpdater instance.""" super().__init__() self.loop = loop self.metadata = metadata self.psm = psm self.listener = None def start(self, initial_delay=0): """Wait for push updates from device. Will throw NoAsyncListenerError if no listner has been set. """ if self.listener is None: raise exceptions.NoAsyncListenerError self.psm.listener = self def stop(self): """No longer wait for push updates.""" self.psm.listener = None async def state_updated(self): """State was updated for active player.""" playstatus = await self.metadata.playing() self.loop.call_soon( self.listener.playstatus_update, self, playstatus) class MrpAppleTV(AppleTV): """Implementation of API support for Apple TV.""" # This is a container class so it's OK with many attributes # pylint: disable=too-many-instance-attributes def __init__(self, loop, session, config, airplay): """Initialize a new Apple TV.""" super().__init__() self._session = session self._mrp_service = config.get_service(const.PROTOCOL_MRP) self._connection = MrpConnection( config.address, self._mrp_service.port, loop) self._srp = SRPAuthHandler() self._protocol = MrpProtocol( loop, self._connection, self._srp, self._mrp_service) self._psm = PlayerStateManager(self._protocol, loop) self._mrp_remote = MrpRemoteControl(loop, self._protocol) self._mrp_metadata = MrpMetadata(self._psm, config.identifier) self._mrp_push_updater = MrpPushUpdater( loop, self._mrp_metadata, self._psm) self._airplay = airplay async def connect(self): """Initiate connection to device. Not needed as it is performed automatically. """ await self._protocol.start() async def close(self): """Close connection and release allocated resources.""" await self._session.close() self._protocol.stop() @property def service(self): """Return service used to connect to the Apple TV.""" return self._mrp_service @property def remote_control(self): """Return API for controlling the Apple TV.""" return self._mrp_remote @property def metadata(self): """Return API for retrieving metadata from Apple TV.""" return self._mrp_metadata @property def push_updater(self): """Return API for handling push update from the Apple TV.""" return self._mrp_push_updater @property def airplay(self): """Return API for working with AirPlay.""" return self._airplay
[ 37811, 3546, 32851, 286, 262, 6343, 36510, 6849, 20497, 973, 416, 5161, 53, 19, 290, 1568, 526, 15931, 198, 198, 11748, 18931, 198, 11748, 30351, 952, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 198, 6738, 12972, 265, 85, 1330, 357, ...
2.401776
4,393
from .chain import Chain import pickle from collections import OrderedDict import pandas as pd import copy from quantipy.core.tools.view.query import get_dataframe from quantipy.core.helpers.functions import get_text import os class Cluster(OrderedDict): """ Container class in form of an OrderedDict of Chains. It is possible to interact with individual Chains through the Cluster object. Clusters are mainly used to prepare aggregations for an export/ build, e.g. MS Excel Workbooks. """ def _verify_banked_chain_spec(self, spec): """ Verify chain conforms to the expected banked chain structure. """ if not type(spec) is dict: return False try: ctype = spec['type'] cname = spec['name'] ctext = spec['text'] citems = spec['items'] cbases = spec['bases'] for c in citems: cichain = c['chain'] citext = c['text'] except: return False if not ctype=='banked-chain': return False if not isinstance(cname, str): return False if not isinstance(ctext, dict): return False for key, value in list(ctext.items()): if not isinstance(key, str): return False if not isinstance(value, str): return False if not isinstance(citems, list): return False if not isinstance(cbases, bool): return False if not all([isinstance(item['chain'], Chain) for item in citems]): return False if not all([isinstance(item['text'], dict) for item in citems]): return False if not all([len(item['text'])>0 for item in citems]): return False for item in citems: for key, value in list(item['text'].items()): if not isinstance(key, str): return False if not isinstance(value, str): return False cview = spec.get('view', None) if cview is None: for c in citems: if 'view' in c: if not isinstance(c['view'], str): return False else: return False else: if not isinstance(cview, str): return False return True def add_chain(self, chains=None): """ Adds chains to a cluster """ # If a single item was supplied, change it to a list of items is_banked_spec = False if not isinstance(chains, (list, Chain, pd.DataFrame, dict)): raise TypeError( "You must pass either a Chain, a list of Chains or a" " banked chain definition (as a dict) into" " Cluster.add_chain().") elif isinstance(chains, dict): if chains.get('type', None)=='banked-chain': is_banked_spec = True if not self._verify_banked_chain_spec(chains): raise TypeError( "Your banked-chain definition is not correctly" " formed. Please check it again.") if isinstance(chains, Chain): self[chains.name] = chains elif is_banked_spec: self[chains.get('name')] = chains elif isinstance(chains, list) and all([ isinstance(chain, Chain) or \ self._verify_banked_chain_spec(chain) for chain in chains]): # Ensure that all items in chains is of the type Chain. for chain in chains: if chain.get('type', None)=='banked-chain': self[chain.get('name')] = chain else: self[chain.name] = chain elif isinstance(chains, pd.DataFrame): if any([ isinstance(idx, pd.MultiIndex) for idx in [chains.index, chains.columns]]): if isinstance(chains.index, pd.MultiIndex): idxs = '_'.join(chains.index.levels[0].tolist()) else: idxs = chains.index if isinstance(chains.columns, pd.MultiIndex): cols = '_'.join(chains.columns.levels[0].tolist()) else: idxs = chains.columns self['_|_'.join([idxs, cols])] = chains else: self['_'.join(chains.columns.tolist())] = chains else: # One or more of the items in chains is not a chain. raise TypeError("One or more of the supplied chains has an inappropriate type.") def bank_chains(self, spec, text_key): """ Return a banked chain as defined by spec. This method returns a banked or compound chain where the spec describes how the view results from multiple chains should be banked together into the same set of dataframes in a single chain. Parameters ---------- spec : dict The banked chain specification object. text_key : str, default='values' Paint the x-axis of the banked chain using the spec provided and this text_key. Returns ------- bchain : quantipy.Chain The banked chain. """ if isinstance(text_key, str): text_key = {'x': [text_key]} chains = [c['chain'] for c in spec['items']] bchain = chains[0].copy() dk = bchain.data_key fk = bchain.filter xk = bchain.source_name yks = bchain.content_of_axis vk = spec.get('view', None) if vk is None: vk = spec['items'][0]['view'] else: get_vk = False for i, item in enumerate(spec['items']): if not 'view' in item: spec['items'][i].update({'view': vk}) vks = list(set([item['view'] for item in spec['items']])) if len(vks)==1: notation = vks[0].split('|') notation[-1] = 'banked-{}'.format(spec['name']) bvk = '|'.join(notation) else: base_method = vks[0].split('|')[1] same_method = all([ vk.split('|')[1]==base_method for vk in vks[1:]]) if same_method: bvk = 'x|{}||||banked-{}'.format(base_method, spec['name']) else: bvk = 'x|||||banked-{}'.format(spec['name']) for yk in list(bchain[dk][fk][xk].keys()): bchain[dk][fk][xk][yk][bvk] = bchain[dk][fk][xk][yk].pop(vks[0]) bchain[dk][fk][xk][yk][bvk].name = bvk bchain.views = [ vk_test for vk_test in bchain.views if 'cbase' in vk_test ] bchain.views.append(bvk) # Auto-painting approach idx_cbase = pd.MultiIndex.from_tuples([ (get_text(spec['text'], text_key, 'x'), 'cbase')], names=['Question', 'Values']) # Non-auto-painting approach # idx_cbase = pd.MultiIndex.from_tuples([ # (spec['name'], 'cbase')], # names=['Question', 'Values']) idx_banked = [] banked = {} for yk in yks: banked[yk] = [] for c, chain in enumerate(chains): xk = chain.source_name vk_temp = spec['items'][c]['view'] # print xk, yk, vk_temp df = get_dataframe(chain, keys=[dk, fk, xk, yk, vk_temp]) if isinstance(idx_banked, list): idx_banked.extend([ (spec['name'], '{}:{}'.format(xk, value[1])) for value in df.index.values ]) banked[yk].append(df) banked[yk] = pd.concat(banked[yk], axis=0) if banked[yk].columns.levels[1][0]=='@': banked[yk] = pd.DataFrame( banked[yk].max(axis=1), index=banked[yk].index, columns=pd.MultiIndex.from_tuples( [(spec['name'], '@')], names=['Question', 'Values']) ) xk = bchain.source_name if isinstance(idx_banked, list): banked_values_meta = [ {'value': idx[1], 'text': spec['items'][i]['text']} for i, idx in enumerate(idx_banked)] bchain.banked_meta = { 'name': spec['name'], 'type': spec['type'], 'text': spec['text'], 'values': banked_values_meta } # When switching to non-auto-painting, use this # idx_banked = pd.MultiIndex.from_tuples( # idx_banked, # names=['Question', 'Values']) # Auto-painting question_text = get_text(spec['text'], text_key, 'x') idx_banked = pd.MultiIndex.from_tuples([ (question_text, get_text(value['text'], text_key, 'x')) for i, value in enumerate(bchain.banked_meta['values'])], names=['Question', 'Values']) banked[yk].index = idx_banked bchain[dk][fk][xk][yk][bvk].dataframe = banked[yk] bchain[dk][fk][xk][yk][bvk]._notation = bvk # bchain[dk][fk][xk][yk][bvk].meta()['shape'] = banked[yk].shape bchain[dk][fk][xk][yk][bvk]._x['name'] = spec['name'] bchain[dk][fk][xk][yk][bvk]._x['size'] = banked[yk].shape[0] bchain.name = 'banked-{}'.format(bchain.name) for yk in yks: for vk in list(bchain[dk][fk][xk][yk].keys()): if vk in bchain.views: if 'cbase' in vk: bchain[dk][fk][xk][yk][vk].dataframe.index = idx_cbase bchain[dk][fk][xk][yk][vk]._x['name'] = spec['name'] else: del bchain[dk][fk][xk][yk][vk] bchain[dk][fk][spec['name']] = bchain[dk][fk].pop(xk) bchain.props_tests = list() bchain.props_tests_levels = list() bchain.means_tests = list() bchain.means_tests_levels = list() bchain.has_props_tests = False bchain.has_means_tests = False bchain.annotations = None bchain.is_banked = True bchain.source_name = spec['name'] bchain.banked_view_key = bvk bchain.banked_spec = spec for i, item in enumerate(spec['items']): bchain.banked_spec['items'][i]['chain'] = item['chain'].name return bchain def _build(self, type): """ The Build exports the chains using methods supplied with 'type'. """ pass def merge(self): """ Merges all Chains found in the Cluster into a new pandas.DataFrame. """ orient = self[list(self.keys())[0]].orientation chainnames = list(self.keys()) if orient == 'y': return pd.concat([self[chainname].concat() for chainname in chainnames], axis=1) else: return pd.concat([self[chainname].concat() for chainname in chainnames], axis=0) def save(self, path_cluster): """ Load Stack instance from .stack file. Parameters ---------- path_cluster : str The full path to the .cluster file that should be created, including the extension. Returns ------- None """ if not path_cluster.endswith('.cluster'): raise ValueError( "To avoid ambiguity, when using Cluster.save() you must provide the full path to " "the cluster file you want to create, including the file extension. For example: " "cluster.save(path_cluster='./output/MyCluster.cluster'). Your call looks like this: " "cluster.save(path_cluster='%s', ...)" % (path_cluster) ) f = open(path_cluster, 'wb') pickle.dump(self, f, pickle.HIGHEST_PROTOCOL) f.close() # STATIC METHODS @staticmethod def load(path_cluster): """ Load Stack instance from .stack file. Parameters ---------- path_cluster : str The full path to the .cluster file that should be created, including the extension. Returns ------- None """ if not path_cluster.endswith('.cluster'): raise ValueError( "To avoid ambiguity, when using Cluster.load() you must provide the full path to " "the cluster file you want to create, including the file extension. For example: " "cluster.load(path_cluster='./output/MyCluster.cluster'). Your call looks like this: " "cluster.load(path_cluster='%s', ...)" % (path_cluster) ) f = open(path_cluster, 'rb') obj = pickle.load(f) f.close() return obj
[ 6738, 764, 7983, 1330, 21853, 201, 198, 11748, 2298, 293, 201, 198, 6738, 17268, 1330, 14230, 1068, 35, 713, 201, 198, 11748, 19798, 292, 355, 279, 67, 201, 198, 11748, 4866, 201, 198, 6738, 5554, 541, 88, 13, 7295, 13, 31391, 13, 1...
1.823637
7,683
import pymysql import logging # 对数据进行转码 db = MySQLDB(user='root', password='root', db='test')
[ 11748, 279, 4948, 893, 13976, 198, 11748, 18931, 628, 198, 197, 2, 10263, 107, 117, 46763, 108, 162, 235, 106, 32573, 249, 26193, 234, 164, 121, 105, 163, 254, 223, 628, 198, 9945, 796, 33476, 11012, 7, 7220, 11639, 15763, 3256, 9206,...
1.98
50
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable import xarray as xr from skimage.segmentation import find_boundaries from skimage.exposure import rescale_intensity from ark.utils import load_utils from ark.utils import misc_utils # plotting functions from ark.utils.misc_utils import verify_in_list def plot_clustering_result(img_xr, fovs, save_dir=None, cmap='tab20', fov_col='fovs', figsize=(10, 10)): """Takes an xarray containing labeled images and displays them. Args: img_xr (xr.DataArray): xarray containing labeled cell objects. fovs (list): list of fovs to display. save_dir (str): If provided, the image will be saved to this location. cmap (str): Cmap to use for the image that will be displayed. fov_col (str): column with the fovs names in img_xr. figsize (tuple): Size of the image that will be displayed. """ verify_in_list(fov_names=fovs, unique_fovs=img_xr.fovs) for fov in fovs: plt.figure(figsize=figsize) ax = plt.gca() plt.title(fov) plt.imshow(img_xr[img_xr[fov_col] == fov].values.squeeze(), cmap=cmap) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) plt.colorbar(cax=cax) if save_dir: misc_utils.save_figure(save_dir, f'{fov}.png') def tif_overlay_preprocess(segmentation_labels, plotting_tif): """Validates plotting_tif and preprocesses it accordingly Args: segmentation_labels (numpy.ndarray): 2D numpy array of labeled cell objects plotting_tif (numpy.ndarray): 2D or 3D numpy array of imaging signal Returns: numpy.ndarray: The preprocessed image """ if len(plotting_tif.shape) == 2: if plotting_tif.shape != segmentation_labels.shape: raise ValueError("plotting_tif and segmentation_labels array dimensions not equal.") else: # convert RGB image with the blue channel containing the plotting tif data formatted_tif = np.zeros((plotting_tif.shape[0], plotting_tif.shape[1], 3), dtype=plotting_tif.dtype) formatted_tif[..., 2] = plotting_tif elif len(plotting_tif.shape) == 3: # can only support up to 3 channels if plotting_tif.shape[2] > 3: raise ValueError("max 3 channels of overlay supported, got {}". format(plotting_tif.shape)) # set first n channels (in reverse order) of formatted_tif to plotting_tif # (n = num channels in plotting_tif) formatted_tif = np.zeros((plotting_tif.shape[0], plotting_tif.shape[1], 3), dtype=plotting_tif.dtype) formatted_tif[..., :plotting_tif.shape[2]] = plotting_tif formatted_tif = np.flip(formatted_tif, axis=2) else: raise ValueError("plotting tif must be 2D or 3D array, got {}". format(plotting_tif.shape)) return formatted_tif def create_overlay(fov, segmentation_dir, data_dir, img_overlay_chans, seg_overlay_comp, alternate_segmentation=None, dtype='int16'): """Take in labeled contour data, along with optional mibi tif and second contour, and overlay them for comparison" Generates the outline(s) of the mask(s) as well as intensity from plotting tif. Predicted contours are colored red, while alternate contours are colored white. Args: fov (str): The name of the fov to overlay segmentation_dir (str): The path to the directory containing the segmentatation data data_dir (str): The path to the directory containing the nuclear and whole cell image data img_overlay_chans (list): List of channels the user will overlay seg_overlay_comp (str): The segmentted compartment the user will overlay alternate_segmentation (numpy.ndarray): 2D numpy array of labeled cell objects dtype (str/type): optional specifier of image type. Overwritten with warning for float images Returns: numpy.ndarray: The image with the channel overlay """ # load the specified fov data in plotting_tif = load_utils.load_imgs_from_dir( data_dir=data_dir, files=[fov + '.tif'], xr_dim_name='channels', xr_channel_names=['nuclear_channel', 'membrane_channel'], dtype=dtype ) # verify that the provided image channels exist in plotting_tif misc_utils.verify_in_list( provided_channels=img_overlay_chans, img_channels=plotting_tif.channels.values ) # subset the plotting tif with the provided image overlay channels plotting_tif = plotting_tif.loc[fov, :, :, img_overlay_chans].values # read the segmentation data in segmentation_labels_cell = load_utils.load_imgs_from_dir(data_dir=segmentation_dir, files=[fov + '_feature_0.tif'], xr_dim_name='compartments', xr_channel_names=['whole_cell'], trim_suffix='_feature_0', match_substring='_feature_0', force_ints=True) segmentation_labels_nuc = load_utils.load_imgs_from_dir(data_dir=segmentation_dir, files=[fov + '_feature_1.tif'], xr_dim_name='compartments', xr_channel_names=['nuclear'], trim_suffix='_feature_1', match_substring='_feature_1', force_ints=True) segmentation_labels = xr.DataArray(np.concatenate((segmentation_labels_cell.values, segmentation_labels_nuc.values), axis=-1), coords=[segmentation_labels_cell.fovs, segmentation_labels_cell.rows, segmentation_labels_cell.cols, ['whole_cell', 'nuclear']], dims=segmentation_labels_cell.dims) # verify that the provided segmentation channels exist in segmentation_labels misc_utils.verify_in_list( provided_compartments=seg_overlay_comp, seg_compartments=segmentation_labels.compartments.values ) # subset segmentation labels with the provided segmentation overlay channels segmentation_labels = segmentation_labels.loc[fov, :, :, seg_overlay_comp].values # overlay the segmentation labels over the image plotting_tif = tif_overlay_preprocess(segmentation_labels, plotting_tif) # define borders of cells in mask predicted_contour_mask = find_boundaries(segmentation_labels, connectivity=1, mode='inner').astype(np.uint8) predicted_contour_mask[predicted_contour_mask > 0] = 255 # rescale each channel to go from 0 to 255 rescaled = np.zeros(plotting_tif.shape, dtype='uint8') for idx in range(plotting_tif.shape[2]): if np.max(plotting_tif[:, :, idx]) == 0: # don't need to rescale this channel pass else: percentiles = np.percentile(plotting_tif[:, :, idx][plotting_tif[:, :, idx] > 0], [5, 95]) rescaled_intensity = rescale_intensity(plotting_tif[:, :, idx], in_range=(percentiles[0], percentiles[1]), out_range='uint8') rescaled[:, :, idx] = rescaled_intensity # overlay first contour on all three RGB, to have it show up as white border rescaled[predicted_contour_mask > 0, :] = 255 # overlay second contour as red outline if present if alternate_segmentation is not None: if segmentation_labels.shape != alternate_segmentation.shape: raise ValueError("segmentation_labels and alternate_" "segmentation array dimensions not equal.") # define borders of cell in mask alternate_contour_mask = find_boundaries(alternate_segmentation, connectivity=1, mode='inner').astype(np.uint8) rescaled[alternate_contour_mask > 0, 0] = 255 rescaled[alternate_contour_mask > 0, 1:] = 0 return rescaled
[ 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 6738, 285, 489, 62, 25981, 74, 896, 13, 897, 274, 62, 25928, 16, 1330, 787, 62, 897, 274, 62, 17946, 21156, 198, 11748, 2124, 18747, 3...
2.008692
4,602
from trainer.gan import dcgan from misc.gpu_utils import parallel_forward as pforward from model.utils import forward_utils as futils _parent_class = dcgan.GANTrainer
[ 6738, 21997, 13, 1030, 1330, 30736, 1030, 198, 6738, 12747, 13, 46999, 62, 26791, 1330, 10730, 62, 11813, 355, 279, 11813, 198, 6738, 2746, 13, 26791, 1330, 2651, 62, 26791, 355, 13294, 4487, 198, 62, 8000, 62, 4871, 796, 30736, 1030, ...
3.652174
46
# # Collective Knowledge (individual environment - setup) # # See CK LICENSE.txt for licensing details # See CK COPYRIGHT.txt for copyright details # # Developer: Grigori Fursin, Grigori.Fursin@cTuning.org, http://fursin.net # ############################################################################## # setup environment setup def setup(i): """ Input: { cfg - meta of this soft entry self_cfg - meta of module soft ck_kernel - import CK kernel module (to reuse functions) host_os_uoa - host OS UOA host_os_uid - host OS UID host_os_dict - host OS meta target_os_uoa - target OS UOA target_os_uid - target OS UID target_os_dict - target OS meta target_device_id - target device ID (if via ADB) tags - list of tags used to search this entry env - updated environment vars from meta customize - updated customize vars from meta deps - resolved dependencies for this soft interactive - if 'yes', can ask questions, otherwise quiet } Output: { return - return code = 0, if successful > 0, if error (error) - error text if return > 0 bat - prepared string for bat file } """ import os # Get variables ck=i['ck_kernel'] s='' iv=i.get('interactive','') env=i.get('env',{}) cfg=i.get('cfg',{}) deps=i.get('deps',{}) tags=i.get('tags',[]) cus=i.get('customize',{}) host_d=i.get('host_os_dict',{}) target_d=i.get('target_os_dict',{}) winh=host_d.get('windows_base','') win=target_d.get('windows_base','') remote=target_d.get('remote','') mingw=target_d.get('mingw','') tbits=target_d.get('bits','') sdirs=host_d.get('dir_sep','') envp=cus.get('env_prefix','') pi=cus.get('path_install','') fp=cus.get('full_path','') p1=os.path.dirname(fp) pi=os.path.dirname(p1) pb=pi+sdirs+'bin' cus['path_bin']=pb ep=cus.get('env_prefix','') if pi!='' and ep!='': env[ep]=pi env[ep+'_BIN']=pb ############################################################ # Prepare environment if winh=='yes': s='\n' s+='set CCC_ROOT='+pi+'\n' s+='set CCC_PLUGINS=%CCC_ROOT%\\src-plat-indep\n' s+='set PATH=%CCC_ROOT%\\src-plat-indep\\plugins;%PATH%\n' s+='set CTUNING_ANALYSIS_CC=%CK_ENV_COMPILER_GCC%\\bin\\gcc\n' s+='set CTUNING_ANALYSIS_CPP=%CK_ENV_COMPILER_GCC%\\bin\\g++\n' s+='set CTUNING_ANALYSIS_FORTRAN=%CK_ENV_COMPILER_GCC%\\bin\\gfortran\n' s+='\n' s+='set CTUNING_COMPILER_CC=%CK_CC%\n' s+='set CTUNING_COMPILER_CPP=%CK_CXX%\n' s+='set CTUNING_COMPILER_FORTRAN=%CK_FC%\n' s+='\n' s+='if "%CK_CC%" == "ctuning-cc" (\n' s+=' set CTUNING_COMPILER_CC=gcc\n' s+=' set CTUNING_COMPILER_CPP=g++\n' s+=' set CTUNING_COMPILER_FORTRAN=gfortran\n' s+=')\n' s+='\n' s+='set CK_MAKE=make\n' s+='set CK_OBJDUMP="objdump -d"\n' s+='\n' s+='rem PRESET SOME DEFAULT VARIABLES\n' s+='set ICI_PROG_FEAT_PASS=fre\n' s+='\n' s+='rem set cTuning web-service parameters\n' s+='set CCC_CTS_URL=cTuning.org/wiki/index.php/Special:CDatabase?request=\n' s+='rem set CCC_CTS_URL=localhost/cTuning/wiki/index.php/Special:CDatabase?request=\n' s+='set CCC_CTS_DB=fursinne_coptcases\n' s+='rem set cTuning username (self-register at http://cTuning.org/wiki/index.php/Special:UserLogin)\n' s+='set CCC_CTS_USER=gfursin\n' s+='\n' s+='rem compiler which was used to extract features for all programs to keep at cTuning.org\n' s+='rem do not change it unless you understand what you do ;) ...\n' s+='set CCC_COMPILER_FEATURES_ID=129504539516446542\n' s+='\n' s+='rem use architecture flags from cTuning\n' s+='set CCC_OPT_ARCH_USE=0\n' s+='\n' s+='rem retrieve opt cases only when execution time > TIME_THRESHOLD\n' s+='set TIME_THRESHOLD=0.3\n' s+='\n' s+='rem retrieve opt cases only with specific notes\n' s+='rem set NOTES=\n' s+='\n' s+='rem retrieve opt cases only when profile info is !=""\n' s+='rem set PG_USE=1\n' s+='\n' s+='rem retrieve opt cases only when execution output is correct (or not if =0)\n' s+='set OUTPUT_CORRECT=1\n' s+='\n' s+='rem check user or total execution time\n' s+='rem set RUN_TIME=RUN_TIME_USER\n' s+='set RUN_TIME=RUN_TIME\n' s+='\n' s+='rem Sort optimization case by speedup (0 - ex. time, 1 - code size, 2 - comp time)\n' s+='set SORT=012\n' s+='\n' s+='rem produce additional optimization report including optimization space froniters\n' s+='set CT_OPT_REPORT=1\n' s+='\n' s+='rem Produce optimization space frontier\n' s+='rem set DIM=01 (2D frontier)\n' s+='rem set DIM=02 (2D frontier)\n' s+='rem set DIM=12 (2D frontier)\n' s+='rem set DIM=012 (3D frontier)\n' s+='rem set DIM=012\n' s+='\n' s+='rem Cut cases when producing frontier (select cases when speedup 0,1 or 2 is more than some threshold)\n' s+='rem set CUT=0,0,1.2\n' s+='rem set CUT=1,0.80,1\n' s+='rem set CUT=0,0,1\n' s+='\n' s+='rem find similar cases from the following platform\n' s+='set CCC_PLATFORM_ID=2111574609159278179\n' s+='set CCC_ENVIRONMENT_ID=2781195477254972989\n' s+='set CCC_COMPILER_ID=331350613878705696\n' else: s='\n' s+='export CCC_ROOT='+pi+'\n' s+='export CCC_PLUGINS=$CCC_ROOT/src-plat-indep\n' s+='export PATH=$CCC_ROOT/src-plat-indep/plugins:$PATH\n' s+='export CTUNING_ANALYSIS_CC=$CK_ENV_COMPILER_GCC/bin/gcc\n' s+='export CTUNING_ANALYSIS_CPP=$CK_ENV_COMPILER_GCC/bin/g++\n' s+='export CTUNING_ANALYSIS_FORTRAN=$CK_ENV_COMPILER_GCC/bin/gfortran\n' s+='\n' s+='export CTUNING_COMPILER_CC=$CK_CC\n' s+='export CTUNING_COMPILER_CPP=$CK_CXX\n' s+='export CTUNING_COMPILER_FORTRAN=$CK_FC\n' s+='\n' s+='if [ "${CK_CC}" == "ctuning-cc" ] ; then\n' s+=' export CTUNING_COMPILER_CC=gcc\n' s+=' export CTUNING_COMPILER_CPP=g++\n' s+=' export CTUNING_COMPILER_FORTRAN=gfortran\n' s+='fi\n' s+='\n' s+='export CK_MAKE=make\n' s+='export CK_OBJDUMP="objdump -d"\n' s+='\n' s+='# PRESET SOME DEFAULT VARIABLES\n' s+='export ICI_PROG_FEAT_PASS=fre\n' s+='\n' s+='#set cTuning web-service parameters\n' s+='export CCC_CTS_URL=cTuning.org/wiki/index.php/Special:CDatabase?request=\n' s+='#export CCC_CTS_URL=localhost/cTuning/wiki/index.php/Special:CDatabase?request=\n' s+='export CCC_CTS_DB=fursinne_coptcases\n' s+='#set cTuning username (self-register at http://cTuning.org/wiki/index.php/Special:UserLogin)\n' s+='export CCC_CTS_USER=gfursin\n' s+='\n' s+='#compiler which was used to extract features for all programs to keep at cTuning.org\n' s+='#do not change it unless you understand what you do ;) ...\n' s+='export CCC_COMPILER_FEATURES_ID=129504539516446542\n' s+='\n' s+='#use architecture flags from cTuning\n' s+='export CCC_OPT_ARCH_USE=0\n' s+='\n' s+='#retrieve opt cases only when execution time > TIME_THRESHOLD\n' s+='export TIME_THRESHOLD=0.3\n' s+='\n' s+='#retrieve opt cases only with specific notes\n' s+='#export NOTES=\n' s+='\n' s+='#retrieve opt cases only when profile info is !=""\n' s+='#export PG_USE=1\n' s+='\n' s+='#retrieve opt cases only when execution output is correct (or not if =0)\n' s+='export OUTPUT_CORRECT=1\n' s+='\n' s+='#check user or total execution time\n' s+='#export RUN_TIME=RUN_TIME_USER\n' s+='export RUN_TIME=RUN_TIME\n' s+='\n' s+='#Sort optimization case by speedup (0 - ex. time, 1 - code size, 2 - comp time)\n' s+='export SORT=012\n' s+='\n' s+='#produce additional optimization report including optimization space froniters\n' s+='export CT_OPT_REPORT=1\n' s+='\n' s+='#Produce optimization space frontier\n' s+='#export DIM=01 (2D frontier)\n' s+='#export DIM=02 (2D frontier)\n' s+='#export DIM=12 (2D frontier)\n' s+='#export DIM=012 (3D frontier)\n' s+='#export DIM=012\n' s+='\n' s+='#Cut cases when producing frontier (select cases when speedup 0,1 or 2 is more than some threshold)\n' s+='#export CUT=0,0,1.2\n' s+='#export CUT=1,0.80,1\n' s+='#export CUT=0,0,1\n' s+='\n' s+='#find similar cases from the following platform\n' s+='export CCC_PLATFORM_ID=2111574609159278179\n' s+='export CCC_ENVIRONMENT_ID=2781195477254972989\n' s+='export CCC_COMPILER_ID=331350613878705696\n' return {'return':0, 'bat':s, 'env':env, 'tags':tags}
[ 2, 198, 2, 29128, 20414, 357, 43129, 2858, 532, 9058, 8, 198, 2, 198, 2, 4091, 45233, 38559, 24290, 13, 14116, 329, 15665, 3307, 198, 2, 4091, 45233, 27975, 38162, 9947, 13, 14116, 329, 6634, 3307, 198, 2, 198, 2, 23836, 25, 1902, ...
1.934039
4,912
#!/usr/bin/env python import numpy as np import colorsys import matplotlib.pyplot as plt from matplotlib.ticker import (MultipleLocator, FormatStrFormatter, AutoMinorLocator,ScalarFormatter) import netCDF4 import os import pyproj import pickle from statsmodels.stats.weightstats import DescrStatsW from matplotlib import rcParams, rcParamsDefault import xarray as xr geod = pyproj.Geod(ellps='WGS84') def gmtColormap(fileName,GMTPath = None): ''' https://scipy-cookbook.readthedocs.io/items/Matplotlib_Loading_a_colormap_dynamically.html modified from James Boyle and Andrew Straw - Thomas Theunissen 2021''' if type(GMTPath) == type(None): filePath = "./"+ fileName+".cpt" else: filePath = GMTPath+"/"+ fileName +".cpt" try: f = open(filePath) except: print("file "+filePath+"not found") return None lines = f.readlines() f.close() x = [] r = [] g = [] b = [] colorModel = "RGB" for l in lines: ls = l.split() if (len(l)>1): if l[0] == "#": if ls[-1] == "HSV": colorModel = "HSV" continue else: continue if ls[0] == "B" or ls[0] == "F" or ls[0] == "N": pass else: x.append(float(ls[0])) r.append(float(ls[1])) g.append(float(ls[2])) b.append(float(ls[3])) xtemp = float(ls[4]) rtemp = float(ls[5]) gtemp = float(ls[6]) btemp = float(ls[7]) x.append(xtemp) r.append(rtemp) g.append(gtemp) b.append(btemp) nTable = len(r) x = np.array( x , np.float32) r = np.array( r , np.float32) g = np.array( g , np.float32) b = np.array( b , np.float32) if colorModel == "HSV": for i in range(r.shape[0]): rr,gg,bb = colorsys.hsv_to_rgb(r[i]/360.,g[i],b[i]) r[i] = rr ; g[i] = gg ; b[i] = bb if colorModel == "HSV": for i in range(r.shape[0]): rr,gg,bb = colorsys.hsv_to_rgb(r[i]/360.,g[i],b[i]) r[i] = rr ; g[i] = gg ; b[i] = bb if colorModel == "RGB": r = r/255. g = g/255. b = b/255. xNorm = (x - x[0])/(x[-1] - x[0]) red = [] blue = [] green = [] for i in range(len(x)): red.append([xNorm[i],r[i],r[i]]) green.append([xNorm[i],g[i],g[i]]) blue.append([xNorm[i],b[i],b[i]]) colorDict = {"red":red, "green":green, "blue":blue} return (colorDict) def shoot(lon, lat, azimuth, maxdist=None): """Shooter Function Original javascript on http://williams.best.vwh.net/gccalc.htm Translated to python by Thomas Lecocq https://www.geophysique.be/2011/02/20/matplotlib-basemap-tutorial-09-drawing-circles/ """ glat1 = lat * np.pi / 180. glon1 = lon * np.pi / 180. s = maxdist / 1.852 faz = azimuth * np.pi / 180. EPS= 0.00000000005 if ((np.abs(np.cos(glat1))<EPS) and not (np.abs(np.sin(faz))<EPS)): alert("Only N-S courses are meaningful, starting at a pole!") a=6378.13/1.852 f=1/298.257223563 r = 1 - f tu = r * np.tan(glat1) sf = np.sin(faz) cf = np.cos(faz) if (cf==0): b=0. else: b=2. * np.arctan2 (tu, cf) cu = 1. / np.sqrt(1 + tu * tu) su = tu * cu sa = cu * sf c2a = 1 - sa * sa x = 1. + np.sqrt(1. + c2a * (1. / (r * r) - 1.)) x = (x - 2.) / x c = 1. - x c = (x * x / 4. + 1.) / c d = (0.375 * x * x - 1.) * x tu = s / (r * a * c) y = tu c = y + 1 while (np.abs (y - c) > EPS): sy = np.sin(y) cy = np.cos(y) cz = np.cos(b + y) e = 2. * cz * cz - 1. c = y x = e * cy y = e + e - 1. y = (((sy * sy * 4. - 3.) * y * cz * d / 6. + x) * d / 4. - cz) * sy * d + tu b = cu * cy * cf - su * sy c = r * np.sqrt(sa * sa + b * b) d = su * cy + cu * sy * cf glat2 = (np.arctan2(d, c) + np.pi) % (2*np.pi) - np.pi c = cu * cy - su * sy * cf x = np.arctan2(sy * sf, c) c = ((-3. * c2a + 4.) * f + 4.) * c2a * f / 16. d = ((e * cy * c + cz) * sy * c + y) * sa glon2 = ((glon1 + x - (1. - c) * d * f + np.pi) % (2*np.pi)) - np.pi baz = (np.arctan2(sa, b) + np.pi) % (2 * np.pi) glon2 *= 180./np.pi glat2 *= 180./np.pi baz *= 180./np.pi return (glon2, glat2, baz) def equi(m, centerlon, centerlat, radius, *args, **kwargs): ''' Plotting circles on a map ''' glon1 = centerlon glat1 = centerlat X = [] ; Y = [] ; for azimuth in range(0, 360): glon2, glat2, baz = shoot(glon1, glat1, azimuth, radius) X.append(glon2) Y.append(glat2) X.append(X[0]) Y.append(Y[0]) X=np.asarray(X) Y=np.asarray(Y) diff = 999999999999999 if (np.min(X)>0): diff = np.max(X)-np.min(X) elif (np.min(X)<0 and np.max(X)>0): diff = np.max(X)-np.min(X) elif (np.min(X)<0 and np.max(X)<0): diff = np.abs(np.min(X))-np.abs(np.max(X)) # Wrapping the circle correctly across map bounds # simple fix enough here if (diff>300): X2 = X[X>0] Y2 = Y[X>0] Y = Y[X<=0] X = X[X<=0] X2,Y2 = m(X2,Y2) p = plt.plot(X2,Y2,**kwargs) X,Y = m(X,Y) if 'color' in kwargs: plt.plot(X,Y,**kwargs) else: plt.plot(X,Y,color=p[0].get_color(),**kwargs) else: #~ m.plot(X,Y,**kwargs) #Should work, but doesn't... X,Y = m(X,Y) plt.plot(X,Y,**kwargs) def plot_histo(data,title, filename='histo.pdf', xlabel='Elevation (m)',unit='m', GaussianModel=False,sigmamodel=270,meanmodel=-2950, legends="upper right",text="left", approximation_display="int", xlim=None, savefig=False, fig_x=9.5, fig_y=9, weights=None,nbins=40): ''' Plot histogram with some statistics ''' define_rcParams() plt.figure(figsize=(fig_x/2.54,fig_y/2.54)) if xlim: data = np.ma.MaskedArray(data, mask=( (data<xlim[0]) | (data>xlim[1]) )) n, bins, patches = plt.hist(x=data,bins=nbins, color='#0504aa',alpha=0.7, rwidth=0.85,weights=weights) plt.grid(axis='y', alpha=0.75) plt.xlabel(xlabel) plt.ylabel('Frequency') plt.title(title) mean = np.nanmean(data) median = np.ma.median(data) sigma = np.nanstd(data) if weights is not None: ma = np.ma.MaskedArray(data, mask=np.isnan(data)) meanW = np.ma.average(ma, weights=weights) dsw = DescrStatsW(ma, weights=weights) stdW = dsw.std # weighted std mean = meanW sigma = stdW xval = np.linspace(np.nanmin(data),np.nanmax(data),1000) yval = np.exp(-(xval-mean)**2/(2*sigma**2)) / np.sqrt(2*np.pi*sigma**2) yval = yval*n.max()/np.nanmax(yval) plt.plot(xval,yval,label='Data Gaussian model') if GaussianModel: yval2 = np.exp(-(xval-meanmodel)**2/(2*sigmamodel**2)) / np.sqrt(2*np.pi*sigmamodel**2) yval2 = yval2*n.max()/np.nanmax(yval2) p = plt.plot(xval,yval2,label='Estimated Gaussian model') if approximation_display=="int": mean = int(np.ceil(mean)) med = int(np.ceil(median)) sigma = int(np.ceil(sigma)) else: mean = np.around(mean,1) med = np.around(median,1) sigma = np.around(sigma,1) if legends=="upper right": plt.legend(loc=legends, bbox_to_anchor=(1,1),framealpha=0.4) elif legends=="upper left": plt.legend(loc=legends, bbox_to_anchor=(0,1),framealpha=0.4) ax = plt.gca() if text=="right": xtext = 0.7 else: xtext = 0.05 ytext = 0.7 ; voff = 0.035 ; hoff = 0.1 if weights is not None: plt.text(xtext,ytext ,r'$\overline{elev}_W$',transform=ax.transAxes) ; plt.text(xtext+hoff,ytext ,r'$=$'+str(mean) +' '+unit,transform=ax.transAxes) else: plt.text(xtext,ytext ,r'$\overline{elev}$',transform=ax.transAxes) ; plt.text(xtext+hoff,ytext ,r'$=$'+str(mean) +' '+unit,transform=ax.transAxes) plt.text(xtext,ytext-voff ,r'$median$',transform=ax.transAxes) ; plt.text(xtext+hoff,ytext-voff ,r'$=$'+str(med) +' '+unit,transform=ax.transAxes) if weights is not None: plt.text(xtext,ytext-2*voff,r'$\sigma_{W}$',transform=ax.transAxes) ; plt.text(xtext+hoff,ytext-2*voff,r'$=$'+str(sigma) +' '+unit,transform=ax.transAxes) else: plt.text(xtext,ytext-2*voff,r'$\sigma$',transform=ax.transAxes) ; plt.text(xtext+hoff,ytext-2*voff,r'$=$'+str(sigma) +' '+unit,transform=ax.transAxes) if GaussianModel: # model if weights is None: vshift = 0.15 else: vshift = 0.18 plt.text(xtext,ytext-vshift ,r'$\overline{elev}$',transform=ax.transAxes,color=p[0].get_color()) plt.text(xtext+hoff,ytext-vshift,r'$=$'+str(meanmodel) +' '+unit,transform=ax.transAxes,color=p[0].get_color()) plt.text(xtext,ytext-vshift-voff ,r'$\sigma$',transform=ax.transAxes,color=p[0].get_color()) plt.text(xtext+hoff,ytext-vshift-voff,r'$=$'+str(sigmamodel) +' '+unit,transform=ax.transAxes,color=p[0].get_color()) maxfreq = n.max() plt.ylim(ymax=np.ceil(maxfreq / 10) * 10 if maxfreq % 10 else maxfreq + 10) if xlim: plt.xlim(xlim) ax.yaxis.set_major_formatter(ScalarFormatter(useMathText=True)) ax.yaxis.get_major_formatter().set_powerlimits((0, 1)) if (savefig): plt.savefig(filename,dpi=300) return ax def plot_correlation(x,y,title,filename='correlation.pdf', nbins = 20, xlabel='x',ylabel='y',unit='m',text="right",plottext=True, xlim=None,ylim=None,ticks=None, savefig=False, fig_x=9.5, fig_y=9, weights=None): ''' ticks = [tick_dx1,tick_dx2,tick_dy1,tick_dy2] unit = from "y" variable ''' define_rcParams() plt.figure(figsize=(fig_x/2.54,fig_y/2.54)) ax = plt.gca() plt.plot(x,y,'ko',markersize=0.5,zorder=0,rasterized=True) if (xlim): xstat = np.linspace(xlim[0],xlim[1],nbins) nb12 = (xlim[1]-xlim[0])/(2*nbins) else: xstat = np.linspace(np.nanmin(x),np.nanmax(x),nbins) nb12 = (np.nanmax(x)-np.nanmin(x))/(2*nbins) mean = [] ; median = [] ; sigma = [] ; xused = [] for rate in xstat: data = y[( (x>=rate-nb12) & (x<=rate+nb12))] if weights is not None: selweights = weights[( (x>=rate-nb12) & (x<=rate+nb12))] if data!=[]: xused.append(rate) med = np.ma.median(data) if weights is None: avg = np.nanmean(data) std = np.nanstd(data) else: ma = np.ma.MaskedArray(data, mask=np.isnan(data)) avgW = np.ma.average(ma, weights=selweights) dsw = DescrStatsW(ma, weights=selweights) stdW = dsw.std # weighted std avg = avgW std = stdW mean.append(avg) median.append(med) sigma.append(std) mean = np.asarray(mean) ; sigma = np.asarray(sigma) ; median = np.asarray(median) ; xused = np.asarray(xused) plt.plot(xused,median,color='r',zorder=3,linewidth=2,label='median') plt.plot(xused,np.add(median,sigma),color='g',linewidth=2,zorder=4) plt.plot(xused,np.subtract(median,sigma),color='g',linewidth=2,zorder=5) plt.plot(xused,mean,color='b',zorder=3,linewidth=2,label='mean') if plottext: if (xlim): xstat = np.linspace(xlim[0],xlim[1],1000) else: xstat = np.linspace(np.nanmin(x),np.nanmax(x),1000) themedian = np.zeros_like(xstat) themedian = themedian + np.ma.median(median) mean = np.around(np.nanmean(median),1) med = np.around(np.ma.median(median),1) sigma = np.around(np.nanstd(median),1) plt.plot(xstat,themedian) if text=="left": xtext = 0.25 elif text=="right": xtext = 0.7 else: xtext = 0.35 ytext = 0.85 ; voff = 0.03 ; hoff = 0.1 plt.text(xtext,ytext ,r'$\overline{elev}$',transform=ax.transAxes) ; plt.text(xtext+hoff,ytext ,r'$=$'+str(mean) +' '+unit,transform=ax.transAxes) plt.text(xtext,ytext-voff ,r'$median$',transform=ax.transAxes) ; plt.text(xtext+hoff,ytext-voff ,r'$=$'+str(med) +' '+unit,transform=ax.transAxes) plt.text(xtext,ytext-2*voff,r'$\sigma$',transform=ax.transAxes) ; plt.text(xtext+hoff,ytext-2*voff,r'$=$'+str(sigma) +' '+unit,transform=ax.transAxes) ax.yaxis.set_major_formatter(ScalarFormatter(useMathText=True)) ax.yaxis.get_major_formatter().set_powerlimits((0, 1)) if not ticks: if (xlim): tick_dx1 = int(np.ceil((xlim[1]-xlim[0])/6)) tick_dx2 = int(np.ceil((xlim[1]-xlim[0])/24)) else: tick_dx1 = int(np.ceil((np.nanmax(x)-np.nanmin(x))/6)) tick_dx2 = int(np.ceil((np.nanmax(x)-np.nanmin(x))/24)) if (ylim): tick_dy1 = int(np.ceil((ylim[1]-ylim[0])/5)) tick_dy2 = int(np.ceil((ylim[1]-ylim[0])/20)) else: tick_dy1 = int(np.ceil((np.nanmax(y)-np.nanmin(y))/5)) tick_dy2 = int(np.ceil((np.nanmax(y)-np.nanmin(y))/20)) else: tick_dx1 = ticks[0] tick_dx2 = ticks[1] tick_dy1 = ticks[2] tick_dy2 = ticks[3] ax.yaxis.set_major_locator(MultipleLocator(tick_dy1)) ax.yaxis.set_minor_locator(MultipleLocator(tick_dy2)) ax.xaxis.set_major_locator(MultipleLocator(tick_dx1)) ax.xaxis.set_minor_locator(MultipleLocator(tick_dx2)) plt.title(title) plt.xlabel(xlabel) plt.ylabel(ylabel) if (xlim): plt.xlim(xlim) if (ylim): plt.ylim(ylim) plt.legend() if (savefig): plt.savefig(filename,dpi=300) return ax #--------------------------- READING DATA --------------------- def define_MOR_pts(path='./data/topography/',selection_name='MOR_pts_all',distance_between_pts_along_ridges = 25): ''' Define points with elevation and spreading rates along MOR selection_name = 'MOR_pts_all' or 'MOR_pts_far_from_hs' or 'MOR_pts_close_to_hs' ''' if os.path.exists('./data_figshare/topography/'): path='./data_figshare/topography/' filename = './'+selection_name+'_'+str(distance_between_pts_along_ridges)+'km.dat' distance_between_pts_along_ridges = distance_between_pts_along_ridges*1e3 if not (os.path.isfile(path+filename)): print("#################### Loading datasets #########################") x,y,elev = load_etopo(path=path) x,y,spreading_rate = load_spreading_rate(path=path) x,y,age = load_seafloor_ages(path=path) x,y,strain_rate = load_strain_rate(path=path) x,y,dist_closest_hs = load_hotspots(path=path) print("#################### Applying mask on datasets #########################") # data selection min_dist_hs = 1000000 # m max_seafloor_age = 10 # Myrs the width depends on spreading rate - 10 Myrs is a good compromise for computational reason # It gives 50 km from ridge axis for ultra-slow 1 cm/yr full spreading rate MOR max_seafloor_age_for_ridge_axis = 0.5 threshold_strain_rate = 1e-16 # s-1 xx, yy = np.meshgrid(x, y) if selection_name=='MOR_pts_all': mask = ( (elev<0) & (age<=max_seafloor_age) ) mask_axis = ( (elev<0) & (age<=max_seafloor_age_for_ridge_axis) ) elif selection_name=='MOR_pts_far_from_hs': mask = ( (elev<0) & (age<=max_seafloor_age) & (dist_closest_hs > min_dist_hs) ) mask_axis = ( (elev<0) & (age<=max_seafloor_age_for_ridge_axis) & (dist_closest_hs > min_dist_hs) ) elif selection_name=='MOR_pts_close_to_hs': mask = ( (elev<0) & (age<=max_seafloor_age) & (dist_closest_hs <= min_dist_hs) ) mask_axis = ( (elev<0) & (age<=max_seafloor_age_for_ridge_axis) & (dist_closest_hs <= min_dist_hs) ) else: print("ERROR incorrect selection_name ") quit() # this array is used to define the localisation of the MOR active_MOR_elev = elev[mask] active_MOR_x = xx[mask] active_MOR_y = yy[mask] active_MOR_x_axis = xx[mask_axis] active_MOR_y_axis = yy[mask_axis] active_MOR_spreading_rate = spreading_rate[mask] active_MOR_strain_rate = strain_rate[mask] dd = 1.5 # Distance to look for points in the grid that belong to the same MOR segment # given in degrees for computational reason, could be function of the spreading rate # Here, we define a constant that cover all cases (Fig. S4b) (~150-200 km) # W ~ 100-150 km ~ distance between rift flanks at ultra-slow spreading rates (Fig. 3) # new_active_MOR_y = [] ; new_active_MOR_x = [] ; new_active_MOR_elev = [] ; new_active_MOR_spreading_rate = [] ipt = 0 print('Total #pts on the grid for age<={} Myrs = {} '.format(max_seafloor_age_for_ridge_axis,len(active_MOR_x_axis))) print("#################### Browsing all MOR points #########################") for xpt,ypt in zip(active_MOR_x_axis,active_MOR_y_axis): xsel = active_MOR_x_axis[ ( (np.abs(active_MOR_x_axis-xpt)<=dd/2) & (np.abs(active_MOR_y_axis-ypt)<=dd/2) ) ] ysel = active_MOR_y_axis[ ( (np.abs(active_MOR_x_axis-xpt)<=dd/2) & (np.abs(active_MOR_y_axis-ypt)<=dd/2) ) ] newx = np.median(xsel) newy = np.median(ysel) if (ipt==0): new_active_MOR_x.append(newx) new_active_MOR_y.append(newy) esel = active_MOR_elev[ ( (np.abs(active_MOR_x-newx)<=dd/2) & (np.abs(active_MOR_y-newy)<=dd/2) ) ] new_active_MOR_elev.append(np.max(esel)) srsel = active_MOR_spreading_rate[ ( (np.abs(active_MOR_x-newx)<=dd/2) & (np.abs(active_MOR_y-newy)<=dd/2) ) ] new_active_MOR_spreading_rate.append(np.median(srsel)) else: stsel = active_MOR_strain_rate[ ( (np.abs(active_MOR_x-newx)<=dd/2) & (np.abs(active_MOR_y-newy)<=dd/2) ) ] if (np.any(stsel>=threshold_strain_rate)): azimuth1, azimuth2, dist = geod.inv(new_active_MOR_x[-1], new_active_MOR_y[-1], newx, newy) if ( dist >= distance_between_pts_along_ridges ): esel = active_MOR_elev[ ( (np.abs(active_MOR_x-newx)<=dd/2) & (np.abs(active_MOR_y-newy)<=dd/2) ) ] srsel = active_MOR_spreading_rate[ ( (np.abs(active_MOR_x-newx)<=dd/2) & (np.abs(active_MOR_y-newy)<=dd/2) ) ] new_active_MOR_x.append(newx) new_active_MOR_y.append(newy) new_active_MOR_elev.append(np.max(esel)) new_active_MOR_spreading_rate.append(np.median(srsel)) ipt = ipt + 1 if ipt%5000 == 0: print("{}/{}".format(ipt,len(active_MOR_x_axis))) new_active_MOR_x = np.asarray(new_active_MOR_x) new_active_MOR_y = np.asarray(new_active_MOR_y) new_active_MOR_elev = np.asarray(new_active_MOR_elev) new_active_MOR_spreading_rate = np.asarray(new_active_MOR_spreading_rate) with open(path+filename, 'wb') as filehandle: pickle.dump([new_active_MOR_x,new_active_MOR_y,new_active_MOR_elev,new_active_MOR_spreading_rate],filehandle) print('Total defined pts along MOR = {} '.format(len(new_active_MOR_x))) else: print("This selection already exists ({})".format(path+filename)) with open(path+filename, 'rb') as filehandle: # read the data as binary data stream [new_active_MOR_x,new_active_MOR_y,new_active_MOR_elev,new_active_MOR_spreading_rate] = pickle.load(filehandle) print('Total defined pts along MOR = {} '.format(len(new_active_MOR_x)))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 7577, 893, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 6738, 2603, 29487, 8019, 13, 83, 15799, 1330, 357, 31217, ...
1.826298
11,560
import numpy as np content = np.loadtxt('/data/rasa.content') with open('/data/join.fasta') as fasta: with open('/data/rasa.cites', 'a+') as w: line = fasta.readline() num = 0 while line: if(line[0] == '>'): line = fasta.readline() continue length = len(line.strip()) i = 0 while i < length: #if(i>0 and i<length-1 and content[num+i][-2] != content[num+i-1][-2] and content[num+i][-2] != content[num+i+1][-2]): #continue if(i == length-1 and content[num+i][-2] != content[num+i-1][-2]): break flag1 = i + num flag2 = i + num for j in range(i,length-1): if(content[num+j][-2] != content[num+j+1][-2]): flag2 = j + num break if(j == length-2): flag2 = length + num #print('i=' + str(i)) #print('flag1=' + str(flag1)) #print('flag2=' + str(flag2)) w.write(str(int(content[flag1][0])) + ' ' + str(int(content[flag2][0])) + '\n') #print(str(int(content[t][0])) + ' ' + str(int(content[m][0]))) if((i + flag2 - flag1 + 1) > content[-1][0]-1): break i += flag2 - flag1 + 1 num += length line = fasta.readline()
[ 11748, 299, 32152, 355, 45941, 198, 198, 11299, 796, 45941, 13, 2220, 14116, 10786, 14, 7890, 14, 8847, 64, 13, 11299, 11537, 198, 4480, 1280, 10786, 14, 7890, 14, 22179, 13, 7217, 64, 11537, 355, 3049, 64, 25, 198, 220, 220, 220, 3...
1.594622
1,004
#!/usr/bin/python import numpy as np #fin = open("H56.bas",r) bas=np.genfromtxt("H56.bas", skip_header=1) #bas=bas[:5] #print( bas ) k0=30.0 l0=0.0 mol0=0 pos0 = np.array([0.0,0.0,0.0]) fout = open("linkers.ini",'w') fout.write("%i\n" %(len(bas)) ) for i,l in enumerate( bas ): pos = l[1:] fout.write("%i %i %s %s %f %f\n" %( mol0,i+1, ' '.join(map(str,pos)),' '.join(map(str,pos0)), k0, l0 ) ) fout.close()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 198, 11748, 299, 32152, 355, 45941, 198, 198, 2, 15643, 796, 1280, 7203, 39, 3980, 13, 12093, 1600, 81, 8, 198, 198, 12093, 28, 37659, 13, 5235, 6738, 14116, 7203, 39, 3980, 13, 12093, 1600...
1.826271
236
from collections import defaultdict abc = Solution() print (abc.findItinerary([["JFK","KUL"],["JFK","NRT"],["NRT","JFK"]])) # ["JFK","NRT","JFK","KUL"] print (abc.findItinerary([["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]])) print (abc.findItinerary([["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]))
[ 6738, 17268, 1330, 4277, 11600, 198, 198, 39305, 796, 28186, 3419, 198, 4798, 357, 39305, 13, 19796, 1026, 7274, 560, 26933, 14692, 41, 26236, 2430, 42, 6239, 33116, 14692, 41, 26236, 2430, 45, 14181, 33116, 14692, 45, 14181, 2430, 41, ...
2.302013
149
import argparse, glob,os from keras.callbacks import ModelCheckpoint, LearningRateScheduler, EarlyStopping, ReduceLROnPlateau from keras.optimizers import Adam import data_loader from metrics import * from net.Unet import Net # from net.GCUnet import Net os.environ["CUDA_VISIBLE_DEVICES"] = "3" parser = argparse.ArgumentParser() parser.add_argument("--train_images", type=str, default='dataset/CRACK500/traincrop/') parser.add_argument("--train_annotations", type=str,default='dataset/CRACK500/traincrop/') parser.add_argument("--img_height", type=int, default=224) parser.add_argument("--img_width", type=int, default=224) parser.add_argument("--augment", type=bool, default=True) parser.add_argument("--val_images", type=str, default='dataset/CRACK500/valcrop/') parser.add_argument("--val_annotations", type=str, default='dataset/CRACK500/valcrop/') parser.add_argument("--epochs", type=int, default=100) parser.add_argument("--batch_size", type=int, default=32) parser.add_argument("--load_weights", type=str, default=None) parser.add_argument("--model", type=str, default='checkpoint/Unet',help="path to output model") args = parser.parse_args() if not os.path.exists(args.model): os.makedirs(args.model) train_images_path = args.train_images train_segs_path = args.train_annotations batch_size = args.batch_size img_height = args.img_height img_width = args.img_width epochs = args.epochs load_weights = args.load_weights val_images_path = args.val_images val_segs_path = args.val_annotations num_train_images = len(glob.glob(train_images_path + '*.jpg')) num_valid_images = len(glob.glob(val_images_path + '*.jpg')) m = Net() m.compile(loss='binary_crossentropy',optimizer= Adam(lr=1e-4),metrics=['accuracy', f1_score]) if load_weights: m.load_weights(load_weights) print("Model output shape: {}".format(m.output_shape)) train_gen = data_loader.imageSegmentationGenerator(train_images_path, train_segs_path, batch_size, img_height, img_width, args.augment, phase='train') val_gen = data_loader.imageSegmentationGenerator(val_images_path, val_segs_path, batch_size, img_height, img_width, False, phase='test') filepath = "weights-{epoch:03d}-{val_loss:.4f}-{val_acc:.4f}.h5" model_weights = os.path.join(args.model, filepath) checkpoint = ModelCheckpoint(model_weights, monitor='val_loss', verbose=1,save_best_only=False, mode='min', save_weights_only=True) reduceLROnPlat = ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=5, verbose=1, mode='auto', epsilon=0.0001) m.fit_generator(train_gen, steps_per_epoch = num_train_images//batch_size, validation_data = val_gen, validation_steps = num_valid_images//batch_size, epochs = epochs, verbose = 1, callbacks = [checkpoint, reduceLROnPlat])
[ 11748, 1822, 29572, 11, 15095, 11, 418, 198, 6738, 41927, 292, 13, 13345, 10146, 1330, 9104, 9787, 4122, 11, 18252, 32184, 50, 1740, 18173, 11, 12556, 1273, 33307, 11, 44048, 35972, 2202, 3646, 378, 559, 198, 6738, 41927, 292, 13, 40085...
2.533566
1,147
import datetime print(datetime.date.today()) today = datetime.date.today() print(today) print(today.year) print(today.month) print(today.day) print(today.strftime("%d %b %Y")) print(today.strftime("%A %B %y")) print(today.strftime("Please attend out event %A, %B %d in the year %Y")) userInput = input("Please enter your birthday (mm/dd/yyyy) ") birthday = datetime.datetime.strptime(userInput, "%m/%d/%Y").date() print(birthday) days = birthday - today print(days.days)
[ 11748, 4818, 8079, 198, 198, 4798, 7, 19608, 8079, 13, 4475, 13, 40838, 28955, 198, 198, 40838, 796, 4818, 8079, 13, 4475, 13, 40838, 3419, 198, 4798, 7, 40838, 8, 198, 4798, 7, 40838, 13, 1941, 8, 198, 4798, 7, 40838, 13, 8424, 8...
2.689266
177
# =============================================================================== # Copyright 2016 ross # # Licensed under the Apache License, Version 2.0 (the 'License'); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an 'AS IS' BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # =============================================================================== # ============= standard library imports ======================== import datetime import os import logging from dateutil import rrule from arcpy import env from numpy import array, multiply, column_stack, savetxt # ============= local library imports ========================== if __name__ == '__main__': p = os.path.join('C:', 'Users', 'David', 'Documents', 'Recharge', 'Gauges', 'Gauge_Data_HF_csv') op = os.path.join('C:', 'Users', 'David', 'Documents', 'Recharge', 'Gauges', 'Gauge_ppt_csv') sp = os.path.join('C:', 'Recharge_GIS', 'Watersheds', 'nm_wtrs_11DEC15.shp') dr = os.path.join('C:', 'Recharge_GIS', 'Precip', '800m', 'Daily') precip(sp, p, op, dr) # ============= EOF =============================================
[ 2, 38093, 25609, 855, 198, 2, 15069, 1584, 686, 824, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 705, 34156, 24036, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13...
3.582126
414
# Your python setup file. An example can be found at: # https://github.com/pypa/sampleproject/blob/master/setup.py
[ 2, 3406, 21015, 9058, 2393, 13, 1052, 1672, 460, 307, 1043, 379, 25, 198, 2, 3740, 1378, 12567, 13, 785, 14, 79, 4464, 64, 14, 39873, 16302, 14, 2436, 672, 14, 9866, 14, 40406, 13, 9078, 198 ]
3.108108
37
import sys import os sys.path.insert(1, os.path.join(sys.path[0], '..')) import torch from torchtext.legacy import data from torchtext.legacy import datasets import random import torch.optim as optim import torch.nn as nn import time from train_eval_models import train, evaluate from lstm_model import LSTM from utils import epoch_time, EarlyStopping from opacus import PrivacyEngine from opacus.utils import module_modification from tuning_structs import Privacy import numpy as np # download the dataset takes time so only do it once since it is not effected by the SEED if __name__ == "__main__": pass
[ 11748, 25064, 198, 11748, 28686, 198, 17597, 13, 6978, 13, 28463, 7, 16, 11, 28686, 13, 6978, 13, 22179, 7, 17597, 13, 6978, 58, 15, 4357, 705, 492, 6, 4008, 198, 11748, 28034, 198, 6738, 28034, 5239, 13, 1455, 1590, 1330, 1366, 198...
3.449438
178
# BOJ 14889 import sys from itertools import combinations si = sys.stdin.readline n = int(si()) graph = [list(map(int, si().split())) for _ in range(n)] people = [i for i in range(n)] comb = list(combinations(people, n // 2)) size = len(comb) start = comb[: size // 2] link = list(reversed(comb[size // 2 :])) sub = 10000000 for i in range(size // 2): s_couple = start[i] l_couple = link[i] s_s = 0 l_s = 0 for j in s_couple: for k in s_couple: s_s += graph[j][k] for j in l_couple: for k in l_couple: l_s += graph[j][k] if sub > abs(s_s - l_s): sub = abs(s_s - l_s) print(sub)
[ 2, 16494, 41, 1478, 39121, 198, 11748, 25064, 198, 6738, 340, 861, 10141, 1330, 17790, 198, 198, 13396, 796, 25064, 13, 19282, 259, 13, 961, 1370, 198, 198, 77, 796, 493, 7, 13396, 28955, 198, 34960, 796, 685, 4868, 7, 8899, 7, 600,...
2.059375
320
""" ## Questions: EASY ### 949. [Largest Time for Given Digits](https://leetcode.com/problems/largest-time-for-given-digits) Given an array of 4 digits, return the largest 24 hour time that can be made. The smallest 24 hour time is 00:00, and the largest is 23:59. Starting from 00:00, a time is larger if more time has elapsed since midnight. Return the answer as a string of length 5. If no valid time can be made, return an empty string. Example 1: Input: [1,2,3,4] Output: "23:41" Example 2: Input: [5,5,5,5] Output: "" Note: A.length == 4 0 <= A[i] <= 9 """ # Solutions from itertools import permutations # Runtime : 36 ms, faster than 63.05% of Python3 online submissions # Memory Usage : 13.8 MB, less than 80.23% of Python3 online submissions
[ 37811, 198, 2235, 20396, 25, 412, 26483, 198, 198, 21017, 860, 2920, 13, 685, 43, 853, 395, 3862, 329, 11259, 7367, 896, 16151, 5450, 1378, 293, 316, 8189, 13, 785, 14, 1676, 22143, 14, 28209, 12, 2435, 12, 1640, 12, 35569, 12, 1289...
2.969231
260
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # import os import sys import shutil sys.path.insert(0, os.path.abspath(os.path.dirname(os.path.dirname(__file__)))) import fdtd # -- Project information ----------------------------------------------------- project = fdtd.__name__ copyright = "2021, {fdtd.__author__}" author = fdtd.__author__ # The full version, including alpha/beta/rc tags release = fdtd.__version__ # -- General configuration --------------------------------------------------- master_doc = "index" # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ "sphinx.ext.autodoc", "sphinx.ext.napoleon", "sphinx.ext.mathjax", "sphinx.ext.viewcode", "nbsphinx", "sphinx_rtd_theme", ] # Add any paths that contain templates here, relative to this directory. templates_path = ["_templates"] # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = "sphinx_rtd_theme" # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ["_static"] # Change how type hints are displayed (requires sphinx.ext.autodoc.typehints) autodoc_typehints = "signature" # signature, description, none autodoc_type_aliases = {} # -- Autodoc ---------------------------------------------------------------- autodoc_mock_imports = ["tqdm", "numpy", "matplotlib", "torch"] # -- Examples Folder --------------------------------------------------------- sourcedir = os.path.dirname(__file__) staticdir = os.path.join(sourcedir, "_static") fdtd_src = os.path.abspath(os.path.join(sourcedir, "..", "fdtd")) examples_src = os.path.abspath(os.path.join(sourcedir, "..", "examples")) examples_dst = os.path.abspath(os.path.join(sourcedir, "examples")) os.makedirs(staticdir, exist_ok=True) shutil.rmtree(examples_dst, ignore_errors=True) shutil.copytree(examples_src, examples_dst) shutil.copytree(fdtd_src, os.path.join(examples_dst, "fdtd"))
[ 2, 28373, 2393, 329, 262, 45368, 28413, 10314, 27098, 13, 198, 2, 198, 2, 770, 2393, 691, 4909, 257, 6356, 286, 262, 749, 2219, 3689, 13, 1114, 257, 1336, 198, 2, 1351, 766, 262, 10314, 25, 198, 2, 3740, 1378, 2503, 13, 82, 746, ...
3.289247
930
from typing import Any, Dict from flask import jsonify, make_response, request, abort from flask.helpers import make_response from flask_restful import Resource from werkzeug.exceptions import HTTPException from werkzeug.wrappers import Response
[ 6738, 19720, 1330, 4377, 11, 360, 713, 198, 6738, 42903, 1330, 33918, 1958, 11, 787, 62, 26209, 11, 2581, 11, 15614, 198, 6738, 42903, 13, 16794, 364, 1330, 787, 62, 26209, 198, 6738, 42903, 62, 2118, 913, 1330, 20857, 198, 6738, 266,...
3.231707
82
from typing import List from app.models.common import DateTimeModelMixin, IDModelMixin from app.models.domain.profiles import Profile from app.models.domain.rwmodel import RWModel
[ 6738, 19720, 1330, 7343, 198, 198, 6738, 598, 13, 27530, 13, 11321, 1330, 7536, 7575, 17633, 35608, 259, 11, 4522, 17633, 35608, 259, 198, 6738, 598, 13, 27530, 13, 27830, 13, 5577, 2915, 1330, 13118, 198, 6738, 598, 13, 27530, 13, 27...
3.714286
49
import numpy as np from visual_mpc.policy.policy import Policy import sys if sys.version_info[0] < 3: import cPickle as pkl else: import pickle as pkl
[ 11748, 299, 32152, 355, 45941, 198, 6738, 5874, 62, 3149, 66, 13, 30586, 13, 30586, 1330, 7820, 198, 11748, 25064, 198, 361, 25064, 13, 9641, 62, 10951, 58, 15, 60, 1279, 513, 25, 198, 220, 220, 220, 1330, 269, 31686, 293, 355, 279,...
2.758621
58
import os from scrapy.spider import BaseSpider from scrapy.selector import HtmlXPathSelector from scrapy.http import Request, HtmlResponse from scrapy.utils.url import urljoin_rfc from scrapy.utils.response import get_base_url from product_spiders.items import Product, ProductLoaderWithNameStrip as ProductLoader from product_spiders.fuzzywuzzy import process from product_spiders.fuzzywuzzy import fuzz HERE = os.path.abspath(os.path.dirname(__file__))
[ 11748, 28686, 198, 6738, 15881, 88, 13, 2777, 1304, 1330, 7308, 41294, 198, 6738, 15881, 88, 13, 19738, 273, 1330, 367, 20369, 55, 15235, 17563, 273, 198, 6738, 15881, 88, 13, 4023, 1330, 19390, 11, 367, 20369, 31077, 198, 6738, 15881, ...
3.21831
142
""" Unit test AgentManager """ import pytest import secrets from starfish.agent_manager import AgentManager from starfish.asset import DataAsset from starfish.network.ddo import DDO
[ 37811, 198, 198, 26453, 1332, 15906, 13511, 198, 198, 37811, 198, 11748, 12972, 9288, 198, 11748, 13141, 198, 198, 6738, 3491, 11084, 13, 25781, 62, 37153, 1330, 15906, 13511, 198, 6738, 3491, 11084, 13, 562, 316, 1330, 6060, 45869, 198, ...
3.54717
53
# # import modules # from ahvl.options.base import OptionsBase from ahvl.helper import AhvlMsg, AhvlHelper # # helper/message # msg = AhvlMsg() hlp = AhvlHelper() # # OptionsLookupSSHHostKey # # set option prefix # set path # useable variables: # - {find} # - {hostname} # set default options # calculate any remaining options # set required options
[ 2, 198, 2, 1330, 13103, 198, 2, 198, 6738, 29042, 19279, 13, 25811, 13, 8692, 1330, 18634, 14881, 198, 6738, 29042, 19279, 13, 2978, 525, 1330, 7900, 19279, 50108, 11, 7900, 19279, 47429, 198, 198, 2, 198, 2, 31904, 14, 20500, 198, ...
2.717241
145
""" Copyright (c) 2021 SolarLiner, jdrprod, Arxaqapi This software is released under the MIT License. https://opensource.org/licenses/MIT """ import os import json import unittest from pathlib import Path from Simple.document import Document
[ 37811, 198, 15069, 357, 66, 8, 33448, 12347, 43, 7274, 11, 474, 7109, 1676, 67, 11, 943, 27865, 80, 15042, 198, 220, 198, 770, 3788, 318, 2716, 739, 262, 17168, 13789, 13, 198, 3740, 1378, 44813, 1668, 13, 2398, 14, 677, 4541, 14, ...
3.391892
74
import json from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.core.exceptions import ValidationError from django.db.models import Q from django.shortcuts import redirect from django.urls import reverse from django.views.generic import DetailView, ListView, TemplateView from meta.views import MetadataMixin from bot.notifications import telegram_notify from ..models import TradeOffer, TradeOfferAnswer, TradeOfferLine, YEARS from .common import TradingPeriodMixin
[ 11748, 33918, 198, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 19816, 1040, 1330, 23093, 37374, 35608, 259, 11, 11787, 47, 13978, 14402, 35608, 259, 198, 6738, 42625, 14208, 13, 7295, 13, 1069, 11755, 1330, 3254, 24765, 12331, ...
3.537415
147
#!~/envs/python3/udacity_python_mongodb import xlrd import pprint datafile = "datasets/2013_ERCOT_Hourly_Load_Data.xls" data = parse_file(datafile) pprint.pprint(data) assert data['maxtime'] == (2013, 8, 13, 17, 0, 0) assert round(data['maxvalue'], 10) == round(18779.02551, 10)
[ 2, 0, 93, 14, 268, 14259, 14, 29412, 18, 14, 463, 4355, 62, 29412, 62, 31059, 375, 65, 198, 198, 11748, 2124, 75, 4372, 198, 198, 11748, 279, 4798, 198, 198, 7890, 7753, 796, 366, 19608, 292, 1039, 14, 6390, 62, 47691, 2394, 62, ...
2.344262
122
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None l1 = ListNode(1) l2 = ListNode(6) l3 = ListNode(2) l4 = ListNode(5) l5 = ListNode(4) l1.next = l2 l2.next = l3 l3.next = l4 l4.next = l5 list = [1,2,3,4] print("cond",list) s = Solution() s.partition(l1, 3) # s.removeNthFromEnd(l1, 2)
[ 198, 198, 2, 30396, 329, 1702, 306, 12, 25614, 1351, 13, 198, 2, 1398, 7343, 19667, 25, 198, 2, 220, 220, 220, 220, 825, 11593, 15003, 834, 7, 944, 11, 2124, 2599, 198, 2, 220, 220, 220, 220, 220, 220, 220, 220, 2116, 13, 2100, ...
1.933333
195
# -*- coding: utf-8 -*- """ Scheduled restarting RAdam """ import math import torch from optimizer import Optimizer
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 50, 1740, 6309, 15765, 278, 371, 23159, 198, 37811, 198, 11748, 10688, 198, 11748, 28034, 198, 6738, 6436, 7509, 1330, 30011, 7509 ]
3.026316
38
import os import shutil root_cwd = os.path.abspath("../")
[ 11748, 28686, 198, 11748, 4423, 346, 198, 198, 15763, 62, 66, 16993, 796, 28686, 13, 6978, 13, 397, 2777, 776, 7203, 40720, 4943, 628 ]
2.5
24
"""Address file. Handles address encoding and decoding.""" # Types. from typing import Tuple, Optional, Any # Keccak hash function. from Cryptodome.Hash import keccak # Crypto class. from cryptonote.crypto.crypto import Crypto # Base58 Character Set. BASE58: str = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" # AddressError. class AddressError(Exception): """AddressError Exception. Used when an invalid address is parsed.""" # Address class. class Address: """Contains address info and the serialized address.""" def __init__( self, crypto: Crypto, key_pair: Tuple[bytes, bytes], payment_id: Optional[bytes] = None, network_byte: Optional[bytes] = None, address: Optional[str] = None, ) -> None: """Converts a ViewKey and a SpendKey into an address.""" # Verify the data lengths if len(crypto.network_bytes) not in {2, 3}: raise Exception("Invalid network bytes.") if (len(key_pair[0]) != 32) or (len(key_pair[1]) != 32): raise Exception("Invalid key pair length.") if (payment_id is not None) and ( len(payment_id) not in crypto.payment_id_lengths ): raise Exception("Invalid payment ID.") self.network: bytes self.view_key: bytes = key_pair[0] self.spend_key: bytes = key_pair[1] self.payment_id: Optional[bytes] = payment_id # If we were passed in an address, verify it against the regex. if address is not None: # Require a network byte was also specified. if network_byte is None: raise Exception("Address parsed without a specified network byte.") if (not crypto.address_regex.match(address)) and ( not crypto.integrated_address_regex.match(address) ): raise Exception("Invalid address used in constructor override.") # Set the network byte, address type, and address. Then return. self.network = network_byte self.address: str = address return # If there's a payment ID, set the network byte to integrated address. # Else, set it to subaddress if there is a subaddress byte. # Else, set it to regular address. if self.payment_id is not None: self.network = crypto.network_bytes[1] else: if len(crypto.network_bytes) == 3: self.network = crypto.network_bytes[2] else: self.network = crypto.network_bytes[0] # If a network byte was specified, despite an address not being specified, use that. if network_byte is not None: self.network = network_byte if self.network not in crypto.network_bytes: raise Exception("Address doesn't have a valid network byte.") # Get the data to be encoded. data: bytes = self.network if (self.payment_id is not None) and crypto.payment_id_leading: data += self.payment_id data += self.spend_key + self.view_key if (self.payment_id is not None) and (not crypto.payment_id_leading): data += self.payment_id # Add the checksum. checksum_hash: Any = keccak.new(digest_bits=256) checksum_hash.update(data) data += checksum_hash.digest()[0:4] # Convert the bytes to Base58. result: str = "" for i in range(0, len(data), 8): block: bytes = data[i : i + 8] blockInt: int = int.from_bytes(block, byteorder="big") blockStr: str = "" remainder: int while blockInt > 0: remainder = blockInt % 58 blockInt = blockInt // 58 blockStr += BASE58[remainder] # Pad the block as needed. if len(block) == 8: while len(blockStr) < 11: blockStr += BASE58[0] elif len(block) == 5: while len(blockStr) < 7: blockStr += BASE58[0] result += blockStr[::-1] # Set the address. self.address: str = result @staticmethod def parse(crypto: Crypto, address: str) -> Any: """ Parse an address and extract the contained info. Raises AddressError if it fails to parse the address. """ # Check the address against the regex. if (not crypto.address_regex.match(address)) and ( not crypto.integrated_address_regex.match(address) ): raise AddressError("Invalid address.") # Convert the Base58 to bytes. data: bytes = bytes() for i in range(0, len(address), 11): blockStr: str = address[i : i + 11] blockInt: int = 0 multi = 1 for char in blockStr[::-1]: blockInt += multi * BASE58.index(char) multi = multi * 58 if len(blockStr) == 11: data += blockInt.to_bytes(8, byteorder="big") elif len(blockStr) == 7: data += blockInt.to_bytes(5, byteorder="big") # Extract the payment ID and checksum. payment_id: Optional[bytes] if crypto.payment_id_leading: payment_id = data[crypto.network_byte_length : -68] else: payment_id = data[(crypto.network_byte_length + 64) : -4] if not payment_id: payment_id = None checksum: bytes = data[-4:] # Check the checksum. checksum_hash: Any = keccak.new(digest_bits=256) checksum_hash.update(data[0:-4]) if checksum_hash.digest()[0:4] != checksum: raise AddressError("Invalid address checksum.") # Verify the network byte is valid. network_byte: bytes = data[0 : crypto.network_byte_length] if (network_byte not in crypto.network_bytes) or ( (payment_id is not None) and (network_byte != crypto.network_bytes[1]) ): raise AddressError("Address doesn't have a valid network byte.") # Return the Address. view_key: bytes spend_key: bytes if crypto.payment_id_leading: view_key = data[-36:-4] spend_key = data[-68:-36] else: view_key = data[ (crypto.network_byte_length + 32) : (crypto.network_byte_length + 64) ] spend_key = data[ crypto.network_byte_length : (crypto.network_byte_length + 32) ] return Address( crypto, (view_key, spend_key), payment_id, network_byte, address, ) def __eq__(self, other: Any) -> bool: """Equality operator. Used by the tests.""" if ( (not isinstance(other, Address)) or (self.network != other.network) or (self.view_key != other.view_key) or (self.spend_key != other.spend_key) or (self.payment_id != other.payment_id) or (self.address != other.address) ): return False return True
[ 37811, 20231, 2393, 13, 7157, 829, 2209, 21004, 290, 39938, 526, 15931, 198, 198, 2, 24897, 13, 198, 6738, 19720, 1330, 309, 29291, 11, 32233, 11, 4377, 198, 198, 2, 3873, 535, 461, 12234, 2163, 13, 198, 6738, 15126, 375, 462, 13, 2...
2.188274
3,309