content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
import pytest from rampwf.utils.sanitize import _sanitize_input
[ 11748, 12972, 9288, 198, 198, 6738, 10454, 86, 69, 13, 26791, 13, 12807, 270, 1096, 1330, 4808, 12807, 270, 1096, 62, 15414, 628 ]
2.869565
23
from django.apps import AppConfig
[ 6738, 42625, 14208, 13, 18211, 1330, 2034, 16934, 628 ]
3.888889
9
from Parser import Parser from LexicalAnalyzer import LexicalAnalyzer
[ 6738, 23042, 263, 1330, 23042, 263, 220, 220, 220, 220, 220, 220, 198, 6738, 17210, 605, 37702, 9107, 1330, 17210, 605, 37702, 9107 ]
3.26087
23
""" Copyright (c) Facebook, Inc. and its affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ import numpy as np import torch def to_tensor(data): """ Convert numpy array to PyTorch tensor. For complex arrays, the real and imaginary parts are stacked along the last dimension. Args: data (np.array): Input numpy array Returns: torch.Tensor: PyTorch version of data """ if np.iscomplexobj(data): data = np.stack((data.real, data.imag), axis=-1) return torch.from_numpy(data) def to_numpy(data): """ Convert PyTorch tensor to numpy array. For complex tensor with two channels, the complex numpy arrays are used. Args: data (torch.Tensor): Input torch tensor Returns: np.array numpy arrays """ if data.shape[-1] == 2: out = np.zeros(data.shape[:-1], dtype=np.complex64) real = data[..., 0].numpy() imag = data[..., 1].numpy() out.real = real out.imag = imag else: out = data.numpy() return out def apply_mask(data, mask_func, seed=None): """ Subsample given k-space by multiplying with a mask. Args: data (torch.Tensor): The input k-space data. This should have at least 3 dimensions, where dimensions -3 and -2 are the spatial dimensions, and the final dimension has size 2 (for complex values). mask_func (callable): A function that takes a shape (tuple of ints) and a random number seed and returns a mask. seed (int or 1-d array_like, optional): Seed for the random number generator. Returns: (tuple): tuple containing: masked data (torch.Tensor): Subsampled k-space data mask (torch.Tensor): The generated mask """ shape = np.array(data.shape) shape[:-3] = 1 mask = mask_func(shape, seed) return data * mask, mask def fft2(data, normalized=True): """ Apply centered 2 dimensional Fast Fourier Transform. Args: data (torch.Tensor): Complex valued input data containing at least 3 dimensions: dimensions -3 & -2 are spatial dimensions and dimension -1 has size 2. All other dimensions are assumed to be batch dimensions. Returns: torch.Tensor: The FFT of the input. """ assert data.size(-1) == 2 data = ifftshift(data, dim=(-3, -2)) data = torch.fft(data, 2, normalized=normalized) data = fftshift(data, dim=(-3, -2)) return data def rfft2(data): """ Apply centered 2 dimensional Fast Fourier Transform. Args: data (torch.Tensor): Complex valued input data containing at least 3 dimensions: dimensions -3 & -2 are spatial dimensions and dimension -1 has size 2. All other dimensions are assumed to be batch dimensions. Returns: torch.Tensor: The FFT of the input. """ data = ifftshift(data, dim=(-2, -1)) data = torch.rfft(data, 2, normalized=True, onesided=False) data = fftshift(data, dim=(-3, -2)) return data def ifft2(data, normalized=True): """ Apply centered 2-dimensional Inverse Fast Fourier Transform. Args: data (torch.Tensor): Complex valued input data containing at least 3 dimensions: dimensions -3 & -2 are spatial dimensions and dimension -1 has size 2. All other dimensions are assumed to be batch dimensions. Returns: torch.Tensor: The IFFT of the input. """ assert data.size(-1) == 2 data = ifftshift(data, dim=(-3, -2)) data = torch.ifft(data, 2, normalized=normalized) data = fftshift(data, dim=(-3, -2)) return data def irfft2(data): """ Apply centered 2-dimensional Inverse Fast Fourier Transform. Args: data (torch.Tensor): Complex valued input data containing at least 3 dimensions: dimensions -3 & -2 are spatial dimensions and dimension -1 has size 2. All other dimensions are assumed to be batch dimensions. Returns: torch.Tensor: The IFFT of the input. """ data = ifftshift(data, dim=(-3, -2)) data = torch.irfft(data, 2, normalized=True, onesided=False) data = fftshift(data, dim=(-2, -1)) return data def complex_to_mag_phase(data): """ :param data (torch.Tensor): A complex valued tensor, where the size of the third last dimension should be 2 :return: Mag and Phase (torch.Tensor): tensor of same size as input """ assert data.size(-3) == 2 mag = (data ** 2).sum(dim=-3).sqrt() phase = torch.atan2(data[:, 1, :, :], data[:, 0, :, :]) return torch.stack((mag, phase), dim=-3) def mag_phase_to_complex(data): """ :param data (torch.Tensor): Mag and Phase (torch.Tensor): :return: A complex valued tensor, where the size of the third last dimension is 2 """ assert data.size(-3) == 2 real = data[:, 0, :, :] * torch.cos(data[:, 1, :, :]) imag = data[:, 0, :, :] * torch.sin(data[:, 1, :, :]) return torch.stack((real, imag), dim=-3) def partial_fourier(data): """ :param data: :return: """ def complex_abs(data): """ Compute the absolute value of a complex valued input tensor. Args: data (torch.Tensor): A complex valued tensor, where the size of the final dimension should be 2. Returns: torch.Tensor: Absolute value of data """ assert data.size(-1) == 2 or data.size(-3) == 2 return (data ** 2).sum(dim=-1).sqrt() if data.size(-1) == 2 else (data ** 2).sum(dim=-3).sqrt() def root_sum_of_squares(data, dim=0): """ Compute the Root Sum of Squares (RSS) transform along a given dimension of a tensor. Args: data (torch.Tensor): The input tensor dim (int): The dimensions along which to apply the RSS transform Returns: torch.Tensor: The RSS value """ return torch.sqrt((data ** 2).sum(dim)) def center_crop(data, shape): """ Apply a center crop to the input real image or batch of real images. Args: data (torch.Tensor): The input tensor to be center cropped. It should have at least 2 dimensions and the cropping is applied along the last two dimensions. shape (int, int): The output shape. The shape should be smaller than the corresponding dimensions of data. Returns: torch.Tensor: The center cropped image """ assert 0 < shape[0] <= data.shape[-2] assert 0 < shape[1] <= data.shape[-1] w_from = (data.shape[-2] - shape[0]) // 2 h_from = (data.shape[-1] - shape[1]) // 2 w_to = w_from + shape[0] h_to = h_from + shape[1] return data[..., w_from:w_to, h_from:h_to] def complex_center_crop(data, shape): """ Apply a center crop to the input image or batch of complex images. Args: data (torch.Tensor): The complex input tensor to be center cropped. It should have at least 3 dimensions and the cropping is applied along dimensions -3 and -2 and the last dimensions should have a size of 2. shape (int, int): The output shape. The shape should be smaller than the corresponding dimensions of data. Returns: torch.Tensor: The center cropped image """ assert 0 < shape[0] <= data.shape[-3] assert 0 < shape[1] <= data.shape[-2] w_from = (data.shape[-3] - shape[0]) // 2 h_from = (data.shape[-2] - shape[1]) // 2 w_to = w_from + shape[0] h_to = h_from + shape[1] return data[..., w_from:w_to, h_from:h_to, :] def normalize(data, mean, stddev, eps=0.): """ Normalize the given tensor using: (data - mean) / (stddev + eps) Args: data (torch.Tensor): Input data to be normalized mean (float): Mean value stddev (float): Standard deviation eps (float): Added to stddev to prevent dividing by zero Returns: torch.Tensor: Normalized tensor """ return (data - mean) / (stddev + eps) def normalize_instance(data, eps=0.): """ Normalize the given tensor using: (data - mean) / (stddev + eps) where mean and stddev are computed from the data itself. Args: data (torch.Tensor): Input data to be normalized eps (float): Added to stddev to prevent dividing by zero Returns: torch.Tensor: Normalized tensor """ mean = data.mean() std = data.std() return normalize(data, mean, std, eps), mean, std def normalize_volume(data, mean, std, eps=0.): """ Normalize the given tensor using: (data - mean) / (stddev + eps) where mean and stddev are provided and computed from volume. Args: data (torch.Tensor): Input data to be normalized mean: mean of whole volume std: std of whole volume eps (float): Added to stddev to prevent dividing by zero Returns: torch.Tensor: Normalized tensor """ return normalize(data, mean, std, eps), mean, std def normalize_complex(data, eps=0.): """ Normalize the given complex tensor using: (data - mean) / (stddev + eps) where mean and stddev are computed from magnitude of data. Note that data is centered by complex mean so that the result centered data have average zero magnitude. Args: data (torch.Tensor): Input data to be normalized (*, 2) mean: mean of image magnitude std: std of image magnitude eps (float): Added to stddev to prevent dividing by zero Returns: torch.Tensor: Normalized complex tensor with 2 channels (*, 2) """ mag = complex_abs(data) mag_mean = mag.mean() mag_std = mag.std() temp = mag_mean/mag mean_real = data[..., 0] * temp mean_imag = data[..., 1] * temp mean_complex = torch.stack((mean_real, mean_imag), dim=-1) stddev = mag_std return (data - mean_complex) / (stddev + eps), mag_mean, stddev # Helper functions def roll(x, shift, dim): """ Similar to np.roll but applies to PyTorch Tensors """ if isinstance(shift, (tuple, list)): assert len(shift) == len(dim) for s, d in zip(shift, dim): x = roll(x, s, d) return x shift = shift % x.size(dim) if shift == 0: return x left = x.narrow(dim, 0, x.size(dim) - shift) right = x.narrow(dim, x.size(dim) - shift, shift) return torch.cat((right, left), dim=dim) def fftshift(x, dim=None): """ Similar to np.fft.fftshift but applies to PyTorch Tensors """ if dim is None: dim = tuple(range(x.dim())) shift = [dim // 2 for dim in x.shape] elif isinstance(dim, int): shift = x.shape[dim] // 2 else: shift = [x.shape[i] // 2 for i in dim] return roll(x, shift, dim) def ifftshift(x, dim=None): """ Similar to np.fft.ifftshift but applies to PyTorch Tensors """ if dim is None: dim = tuple(range(x.dim())) shift = [(dim + 1) // 2 for dim in x.shape] elif isinstance(dim, int): shift = (x.shape[dim] + 1) // 2 else: shift = [(x.shape[i] + 1) // 2 for i in dim] return roll(x, shift, dim)
[ 37811, 198, 15269, 357, 66, 8, 3203, 11, 3457, 13, 290, 663, 29116, 13, 198, 198, 1212, 2723, 2438, 318, 11971, 739, 262, 17168, 5964, 1043, 287, 262, 198, 43, 2149, 24290, 2393, 287, 262, 6808, 8619, 286, 428, 2723, 5509, 13, 198, ...
2.472577
4,613
import doctest from migrate_exblog import entries_to_mt
[ 11748, 10412, 395, 198, 198, 6738, 32492, 62, 1069, 14036, 1330, 12784, 62, 1462, 62, 16762, 628 ]
3.411765
17
from .server import get_server_params, get_ssl_params, redirect_root_to_docs, start_model_server
[ 6738, 764, 15388, 1330, 651, 62, 15388, 62, 37266, 11, 651, 62, 45163, 62, 37266, 11, 18941, 62, 15763, 62, 1462, 62, 31628, 11, 923, 62, 19849, 62, 15388, 198 ]
3.233333
30
import os import tempfile from types import TracebackType from typing import Any, BinaryIO, Optional, TextIO, Type, Union import yaml
[ 11748, 28686, 198, 11748, 20218, 7753, 198, 6738, 3858, 1330, 34912, 1891, 6030, 198, 6738, 19720, 1330, 4377, 11, 45755, 9399, 11, 32233, 11, 8255, 9399, 11, 5994, 11, 4479, 198, 198, 11748, 331, 43695, 628, 198 ]
3.702703
37
import numpy as np import cv2 def rem_multi_lines(lines, thresh): """ to remove the multiple lines with close proximity :param lines: initial list with all the lines(multiple in place of singular) :param thresh: dist between two lines for them to be considered as same :return: final list with singular lines in place of multiple """ a = [] i = 0 lines.append([800, 0]) # random val/ noise out = [] # this loop collects lines with close proximity in a list (a) and then appends that # complete list in a common list called out. while i < len(lines) - 1: if lines[i] not in a: a.append(lines[i]) if abs(lines[i + 1][0] - lines[i][0]) < thresh: a.append(lines[i + 1]) else: out.append(a) a = [] i += 1 # print(out) final = [] for i in out: a = np.array(i) final.append(np.average(a, axis=0)) # print(final) for i in final.copy(): if i[0] < 0: final.remove(i) return final def draw_r_theta_lines(img, lines, color): """ draw lines on image which are of (r, theta) form :param img: image to draw the lines on :param lines: list of lines on the form (r, theta) :param color: color of lines :return: """ for rho, theta in lines: a = np.cos(theta) b = np.sin(theta) x0 = a * rho y0 = b * rho x1 = int(x0 + 1000 * (-b)) y1 = int(y0 + 1000 * a) x2 = int(x0 - 1000 * (-b)) y2 = int(y0 - 1000 * a) cv2.line(img, (x1, y1), (x2, y2), color, 2)
[ 11748, 299, 32152, 355, 45941, 198, 11748, 269, 85, 17, 628, 198, 4299, 816, 62, 41684, 62, 6615, 7, 6615, 11, 294, 3447, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 284, 4781, 262, 3294, 3951, 351, 1969, 20387, 220, 198, ...
2.120101
791
# Before running this command, you should firstly run: # pip install fairseq # pip install fastBPE # wget https://dl.fbaipublicfiles.com/fairseq/models/lm/wmt19.en.tar.gz # tar zxvf wmt19.en.tar.gz import argparse from itertools import islice import numpy as np from fairseq.models.transformer_lm import TransformerLanguageModel parser = argparse.ArgumentParser() parser.add_argument('--hypo_filename', metavar='N', type=str, help='hypo_filename') parser.add_argument('--out_filename', metavar='N', type=str, help='out_filename') # parser.add_argument('--num_candidates', type=int, help="num_candidates") args, unknown = parser.parse_known_args() en_lm = TransformerLanguageModel.from_pretrained('wmt19.en', 'model.pt', tokenizer='moses', bpe='fastbpe') en_lm.cuda() num_processed = 0 ppl = [] batch_num = 1000 with open(args.hypo_filename, 'r') as f, open(args.out_filename, 'w') as out: while True: n_lines = list(map(lambda x: x.strip(), islice(f, batch_num))) if len(n_lines) == 0: break for ele in en_lm.score(n_lines, beam=1): ppl.append(float(ele['positional_scores'].mean().neg().exp().item())) num_processed += batch_num print(f"Processed {num_processed}") ppl = np.array(ppl) ppl = np.nan_to_num(ppl, nan=np.nanmax(ppl)) # scores = 1 - ppl/ppl.max() # for ele in zip(ppl.tolist(), scores.tolist()): # out.write(f"{np.log(ele[0])}, {ele[0]}, {ele[1]}\n") ppl = np.array(ppl) for ele in ppl.tolist(): out.write(f"{np.log(ele)}\n")
[ 2, 7413, 2491, 428, 3141, 11, 345, 815, 717, 306, 1057, 25, 198, 2, 7347, 2721, 3148, 41068, 198, 2, 7347, 2721, 3049, 33, 11401, 198, 2, 266, 1136, 3740, 1378, 25404, 13, 69, 7012, 541, 841, 16624, 13, 785, 14, 22043, 41068, 14, ...
2.338855
664
import warnings from apispec import APISpec from apispec.ext.marshmallow import MarshmallowPlugin from aioli.service import BaseService from aioli.controller import BaseHttpController from aioli.exceptions import NoMatchFound
[ 11748, 14601, 198, 198, 6738, 2471, 271, 43106, 1330, 3486, 1797, 43106, 198, 6738, 2471, 271, 43106, 13, 2302, 13, 76, 5406, 42725, 1330, 9786, 42725, 37233, 198, 198, 6738, 257, 1669, 72, 13, 15271, 1330, 7308, 16177, 198, 6738, 257, ...
3.693548
62
import pandas as pd import plotly.graph_objs as go
[ 11748, 19798, 292, 355, 279, 67, 198, 11748, 7110, 306, 13, 34960, 62, 672, 8457, 355, 467, 628, 198 ]
2.789474
19
import factory from faker import Faker from popup.models import Popup fake = Faker()
[ 11748, 8860, 198, 6738, 277, 3110, 1330, 376, 3110, 198, 198, 6738, 46207, 13, 27530, 1330, 8099, 929, 198, 198, 30706, 796, 376, 3110, 3419, 628 ]
3.384615
26
import os import glob import shutil import logging # logging.basicConfig(level=logging.DEBUG) # DEBUG:root:Skipping file /Users/hygull/Projects/Python3/DjangoTenantOracleSchemas/django-tenant-oracle-schemas/src/tenants/models.py # logging.basicConfig(format='%(asctime)s %(message)s', level=logging.DEBUG) # 2019-06-24 16:19:29,898 Skipping file /Users/hygull/Projects/Python3/DjangoTenantOracleSchemas/django-tenant-oracle-schemas/src/manage.py # logging.basicConfig(format='%(asctime)s %(message)s', level=logging.DEBUG, datefmt='%d/%m/%Y %H:%M:%S %p') # 24/06/2019 04:23:31 PM Skipping file /Users/hygull/Projects/Python3/DjangoTenantOracleSchemas/django-tenant-oracle-schemas/src/manage.py logging.basicConfig(format='%(asctime)s %(message)s', level=logging.DEBUG, datefmt='[%d/%m/%Y %H:%M:%S %p] =>') # 24/06/2019 16:24:02 PM Skipping file /Users/hygull/Projects/Python3/DjangoTenantOracleSchemas/django-tenant-oracle-schemas/src/manage.py
[ 11748, 28686, 198, 11748, 15095, 198, 11748, 4423, 346, 198, 11748, 18931, 198, 198, 2, 18931, 13, 35487, 16934, 7, 5715, 28, 6404, 2667, 13, 30531, 8, 198, 2, 16959, 25, 15763, 25, 50, 4106, 2105, 2393, 1220, 14490, 14, 12114, 70, ...
2.422392
393
from typing import Callable, List, Union, Optional, Dict, Tuple import re import spacy import logging import math from enum import Enum logger = logging.getLogger(__name__) Preprocessor = PreprocessorBase dots = re.compile(r"[\.\'\"\?, ]{2,}[\w ]*")
[ 6738, 19720, 1330, 4889, 540, 11, 7343, 11, 4479, 11, 32233, 11, 360, 713, 11, 309, 29291, 198, 11748, 302, 198, 11748, 599, 1590, 198, 11748, 18931, 198, 11748, 10688, 198, 6738, 33829, 1330, 2039, 388, 198, 6404, 1362, 796, 18931, 1...
2.857143
91
""" ===== Distributed by: Notre Dame SCAI Lab (MIT Liscense) - Associated publication: url: https://arxiv.org/abs/2010.03957 doi: github: https://github.com/zabaras/transformer-physx ===== """ import logging import h5py import torch from .dataset_phys import PhysicalDataset from ..embedding.embedding_model import EmbeddingModel logger = logging.getLogger(__name__)
[ 37811, 198, 1421, 28, 198, 20344, 6169, 416, 25, 23382, 20377, 6374, 20185, 3498, 357, 36393, 406, 2304, 1072, 8, 198, 12, 10575, 9207, 25, 198, 6371, 25, 3740, 1378, 283, 87, 452, 13, 2398, 14, 8937, 14, 10333, 13, 15, 2670, 3553, ...
2.928571
126
import FWCore.ParameterSet.Config as cms #from ..modules.hltL1TkMuons_cfi import * from ..modules.hltL1TkSingleMuFiltered22_cfi import * from ..sequences.HLTBeginSequence_cfi import * from ..sequences.HLTEndSequence_cfi import * L1T_SingleTkMuon_22 = cms.Path( HLTBeginSequence + # hltL1TkMuons + hltL1TkSingleMuFiltered22 + HLTEndSequence )
[ 11748, 48849, 14055, 13, 36301, 7248, 13, 16934, 355, 269, 907, 198, 198, 2, 6738, 11485, 18170, 13, 71, 2528, 43, 16, 51, 74, 33239, 684, 62, 66, 12463, 1330, 1635, 198, 6738, 11485, 18170, 13, 71, 2528, 43, 16, 51, 74, 28008, 33...
2.286624
157
import os import math import argparse import dbh_util as util from sklearn.ensemble import RandomForestClassifier parser = argparse.ArgumentParser() parser.add_argument('--n-estimators', type=int, default=10, help='The number of trees in the forest') parser.add_argument('--max-depth', type=int, default=5, help='Max decision tree leaf node depth') parser.add_argument('--criterion', default='gini', help='Split quality criterion, "gini" or "entropy"') # # Random Forest approach #
[ 11748, 28686, 198, 11748, 10688, 198, 11748, 1822, 29572, 198, 11748, 20613, 71, 62, 22602, 355, 7736, 198, 198, 6738, 1341, 35720, 13, 1072, 11306, 1330, 14534, 34605, 9487, 7483, 198, 198, 48610, 796, 1822, 29572, 13, 28100, 1713, 46677...
3.344828
145
# Copyright 2017 - Nokia # # 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 time from oslo_log import log as logging from vitrage_tempest_plugin.tests.base import IsEmpty from vitrage_tempest_plugin.tests.common.constants import DOCTOR_DATASOURCE from vitrage_tempest_plugin.tests.common.constants import EntityCategory from vitrage_tempest_plugin.tests.common.constants import VertexProperties \ as VProps from vitrage_tempest_plugin.tests.common.constants import VITRAGE_DATASOURCE from vitrage_tempest_plugin.tests.common import general_utils as g_utils from vitrage_tempest_plugin.tests.common.tempest_clients import TempestClients from vitrage_tempest_plugin.tests.common import vitrage_utils as v_utils from vitrage_tempest_plugin.tests.e2e.test_actions_base import TestActionsBase from vitrage_tempest_plugin.tests import utils LOG = logging.getLogger(__name__) TRIGGER_ALARM_1 = 'e2e.test_overlapping_actions.trigger.alarm1' TRIGGER_ALARM_2 = 'e2e.test_overlapping_actions.trigger.alarm2' TRIGGER_ALARM_3 = 'e2e.test_overlapping_actions.trigger.alarm3' TRIGGER_ALARM_4 = 'e2e.test_overlapping_actions.trigger.alarm4' DEDUCED = 'e2e.test_overlapping_actions.deduced.alarm' TRIGGER_ALARM_1_PROPS = { VProps.NAME: TRIGGER_ALARM_1, VProps.VITRAGE_CATEGORY: EntityCategory.ALARM, VProps.VITRAGE_TYPE: DOCTOR_DATASOURCE, } TRIGGER_ALARM_2_PROPS = { VProps.NAME: TRIGGER_ALARM_2, VProps.VITRAGE_CATEGORY: EntityCategory.ALARM, VProps.VITRAGE_TYPE: DOCTOR_DATASOURCE, } DEDUCED_PROPS = { VProps.NAME: DEDUCED, VProps.VITRAGE_CATEGORY: EntityCategory.ALARM, VProps.VITRAGE_TYPE: VITRAGE_DATASOURCE, }
[ 2, 15069, 2177, 532, 26182, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 921, 743, 7330, 198, 2,...
2.733164
787
import json import os import subprocess import sys TEST_FILENAME = "tmp_py_file" TEST_FOLDER = "clone_tests" TESTS = [ ("clone!( => move || {})", "If you have nothing to clone, no need to use this macro!"), ("clone!(|| {})", "If you have nothing to clone, no need to use this macro!"), ("clone!(|a, b| {})", "If you have nothing to clone, no need to use this macro!"), ("clone!(@strong self => move |x| {})", "Can't use `self` as variable name. Try storing it in a temporary variable or rename it using `as`."), ("clone!(@strong self.v => move |x| {})", "Field accesses are not allowed as is, you must rename it!"), ("clone!(@weak v => @default-return false, || {})", "Closure needs to be \"moved\" so please add `move` before closure"), ("clone!(@weak v => @default-return false, |bla| {})", "Closure needs to be \"moved\" so please add `move` before closure"), ("clone!(@weak v => default-return false, move || {})", "Missing `@` before `default-return`"), ("clone!(@weak v => @default-return false move || {})", "Missing comma after `@default-return`'s value"), ("clone!(@yolo v => move || {})", "Unknown keyword, only `weak` and `strong` are allowed"), ("clone!(v => move || {})", "You need to specify if this is a weak or a strong clone."), ] if __name__ == "__main__": sys.exit(run_tests())
[ 11748, 33918, 198, 11748, 28686, 198, 11748, 850, 14681, 198, 11748, 25064, 628, 198, 51, 6465, 62, 46700, 1677, 10067, 796, 366, 22065, 62, 9078, 62, 7753, 1, 198, 51, 6465, 62, 37, 3535, 14418, 796, 366, 21018, 62, 41989, 1, 198, ...
2.653775
543
from __future__ import unicode_literals from django.http import HttpRequest from django.template import Context, Template, TemplateSyntaxError from django.test import TestCase from snakeoil.models import SeoUrl from .models import TestModel
[ 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 6738, 42625, 14208, 13, 4023, 1330, 367, 29281, 18453, 198, 6738, 42625, 14208, 13, 28243, 1330, 30532, 11, 37350, 11, 37350, 13940, 41641, 12331, 198, 6738, 42625, 142...
3.769231
65
from .trainers import * from .predictors import *
[ 6738, 764, 27432, 364, 1330, 1635, 198, 6738, 764, 79, 17407, 669, 1330, 1635, 198 ]
3.333333
15
import torch from torch_geometric.nn import GravNetConv
[ 11748, 28034, 198, 6738, 28034, 62, 469, 16996, 13, 20471, 1330, 32599, 7934, 3103, 85, 628 ]
3.5625
16
from datetime import datetime from hootpy import HootPy if __name__ == "__main__": cfg = { 'forecast_hours':[0, 3, 6, 9, 12], 'product_title':"NAM Forecast Cross Section KDRT-KGRB", 'image_file_name':"nam_fcross_KDRT-KGRB_f%02d.png" } hpc = CrossPlotter(cfg) hpc.loadData() hpc.plot()
[ 6738, 4818, 8079, 1330, 4818, 8079, 198, 198, 6738, 289, 1025, 9078, 1330, 367, 1025, 20519, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 30218, 70, 796, 1391, 198, 220, 220, 220, 220, 220, ...
2.03681
163
import logging import ldap from django.conf import settings from django.contrib.auth.models import Group from django.core.management.base import BaseCommand from django_auth_ldap.backend import LDAPBackend from chiffee.models import User logger = logging.getLogger('syncldap') # This command synchronizes local database with the LDAP server. # New LDAP user -> new user in the local database. # Deleted LDAP user -> local user is set to inactive.
[ 11748, 18931, 198, 198, 11748, 300, 67, 499, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 4912, 198, 6738, 42625, 14208, 13, 7295, 13, 27604, 13, 8692, 1330, 7308, ...
3.503876
129
from ols import * from diagnostics import * from diagnostics_sp import * from user_output import * from twosls import * from twosls_sp import * from error_sp import * from error_sp_het import * from error_sp_hom import * from ols_regimes import * from twosls_regimes import * from twosls_sp_regimes import * from error_sp_regimes import * from error_sp_het_regimes import * from error_sp_hom_regimes import * from probit import * from ml_lag import * from ml_lag_regimes import * from ml_error import * from ml_error_regimes import * from sur import * from sur_error import * from sur_lag import *
[ 6738, 267, 7278, 1330, 1635, 198, 6738, 6689, 34558, 1330, 1635, 198, 6738, 6689, 34558, 62, 2777, 1330, 1635, 198, 6738, 2836, 62, 22915, 1330, 1635, 198, 6738, 665, 418, 7278, 1330, 1635, 198, 6738, 665, 418, 7278, 62, 2777, 1330, 1...
3.114583
192
from pytest import fixture from encountertk.e_model import EncounterModel, ps_encounter, mean_vol_encountered
[ 6738, 12972, 9288, 1330, 29220, 198, 6738, 8791, 30488, 13, 68, 62, 19849, 1330, 40998, 17633, 11, 26692, 62, 12685, 6828, 11, 1612, 62, 10396, 62, 268, 9127, 1068, 628 ]
3.7
30
import sys from collections import deque a, b, c = sys.stdin.read().split() if __name__ == "__main__": ans = main() print(ans)
[ 11748, 25064, 201, 198, 6738, 17268, 1330, 390, 4188, 201, 198, 201, 198, 64, 11, 275, 11, 269, 796, 25064, 13, 19282, 259, 13, 961, 22446, 35312, 3419, 201, 198, 201, 198, 201, 198, 201, 198, 361, 11593, 3672, 834, 6624, 366, 834, ...
2.257576
66
""" Runs LightGBM using distributed (mpi) training. to execute: > python src/pipelines/azureml/lightgbm_training.py --exp-config conf/experiments/lightgbm_training/cpu.yaml """ # pylint: disable=no-member # NOTE: because it raises 'dict' has no 'outputs' member in dsl.pipeline construction import os import sys import json import logging import argparse # config management from dataclasses import dataclass from omegaconf import OmegaConf, MISSING from typing import Optional, Any, List # AzureML from azure.ml.component import Component from azure.ml.component import dsl from azure.ml.component.environment import Docker # when running this script directly, needed to import common LIGHTGBM_REPO_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')) SCRIPTS_SOURCES_ROOT = os.path.join(LIGHTGBM_REPO_ROOT, 'src') if SCRIPTS_SOURCES_ROOT not in sys.path: logging.info(f"Adding {SCRIPTS_SOURCES_ROOT} to path") sys.path.append(str(SCRIPTS_SOURCES_ROOT)) from common.tasks import training_task, training_variant from common.sweep import SweepParameterParser from common.aml import load_dataset_from_data_input_spec from common.aml import apply_sweep_settings from common.pipelines import ( parse_pipeline_config, azureml_connect, pipeline_submit, COMPONENTS_ROOT ) ### CONFIG DATACLASS ### # Step 1 : to configure your pipeline, add all your fields inside a # properly defined dataclass, pipeline_cli_main will figure out how # to read that config from a given yaml file + hydra override commands ### PIPELINE COMPONENTS ### # Step 2 : your pipeline consists in assembling components # load those components from local yaml specifications # use COMPONENTS_ROOT as base folder lightgbm_train_module = Component.from_yaml(yaml_file=os.path.join(COMPONENTS_ROOT, "training", "lightgbm_python", "spec.yaml")) lightgbm_train_sweep_module = Component.from_yaml(yaml_file=os.path.join(COMPONENTS_ROOT, "training", "lightgbm_python", "sweep_spec.yaml")) partition_data_module = Component.from_yaml(yaml_file=os.path.join(COMPONENTS_ROOT, "data_processing", "partition_data", "spec.yaml")) lightgbm_data2bin_module = Component.from_yaml(yaml_file=os.path.join(COMPONENTS_ROOT, "data_processing", "lightgbm_data2bin", "spec.yaml")) ### PIPELINE SPECIFIC CODE ### def process_sweep_parameters(params_dict, sweep_algorithm): """Parses config and spots sweepable paraneters Args: params_dict (dict): configuration object (see get_config_class()) sweep_algorithm (str): random, grid, bayesian Returns: tunable_params (dict) """ # the class below automates parsing of sweepable parameters sweep_param_parser = SweepParameterParser( tunable_parameters=[ # those are keys and their default values "num_iterations", "num_leaves", "min_data_in_leaf", "learning_rate", "max_bin", "feature_fraction" ], cli_prefix=None, # this is not argparse parameter_sampling=sweep_algorithm ) # provide config as a dictionary to the parser sweep_parameters = { "num_iterations": params_dict['num_iterations'], "num_leaves": params_dict['num_leaves'], "min_data_in_leaf": params_dict['min_data_in_leaf'], "learning_rate": params_dict['learning_rate'], "max_bin": params_dict['max_bin'], "feature_fraction": params_dict['feature_fraction'], } # parser gonna parse sweep_param_parser.parse_from_dict(sweep_parameters) # and return params as we want them tunable_params = sweep_param_parser.get_tunable_params() fixed_params = sweep_param_parser.get_fixed_params() # return dictionaries to fed as params into our pipeline return tunable_params, fixed_params ### TRAINING PIPELINE ### # Step 3: your pipeline consists in creating a python function # decorated with @dsl.pipeline. # You can create as many subgraphs as you want, # but `pipeline_cli_main` will need one pipeline function # taking a single config argument, not a pipeline parameter. # Here you should create an instance of a pipeline function (using your custom config dataclass) # creating an overall pipeline using pipeline_function for each task given ### MAIN BLOCK ### # Step 4: implement main block using helper functions def main(): # use parse helper function to get arguments from CLI config = parse_pipeline_config(lightgbm_training_config) # you'll need a workspace object to connect workspace = azureml_connect(config) # run the pipeline function with the given arguments pipeline_instance = training_all_tasks(workspace, config) # generate a nice markdown description experiment_description="\n".join([ "Training on all specified tasks (see yaml below).", "```yaml""", "data_generation_config:", OmegaConf.to_yaml(config.lightgbm_training_config), "```" ]) # validate/submit the pipeline (if run.submit=True) pipeline_submit( workspace, config, pipeline_instance, experiment_description=experiment_description ) if __name__ == "__main__": main()
[ 37811, 198, 10987, 82, 4401, 4579, 44, 1262, 9387, 357, 3149, 72, 8, 3047, 13, 198, 198, 1462, 12260, 25, 198, 29, 21015, 12351, 14, 79, 541, 20655, 14, 1031, 495, 4029, 14, 2971, 70, 20475, 62, 34409, 13, 9078, 1377, 11201, 12, 1...
2.795853
1,881
from xml.etree import ElementTree as Et import pandas as pd import requests from twinfield.core import Base from twinfield.exceptions import ServerError from twinfield.messages import METADATA_XML
[ 6738, 35555, 13, 316, 631, 1330, 11703, 27660, 355, 17906, 198, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 7007, 198, 198, 6738, 15203, 3245, 13, 7295, 1330, 7308, 198, 6738, 15203, 3245, 13, 1069, 11755, 1330, 9652, 12331, 198, ...
3.636364
55
# Author: Artem Skiba # Created: 20/01/2020 from .dataset import FastDataset from .dataloader import get_dataloader __all__ = [ 'FastDataset', 'get_dataloader' ]
[ 2, 220, 220, 6434, 25, 3683, 368, 3661, 23718, 198, 2, 220, 220, 15622, 25, 1160, 14, 486, 14, 42334, 198, 198, 6738, 764, 19608, 292, 316, 1330, 12549, 27354, 292, 316, 198, 6738, 764, 67, 10254, 1170, 263, 1330, 651, 62, 67, 102...
2.324324
74
INIT = 1 REST = ['START_MODSAFE',[0,0]] NEUTRAL = ['START_MODSAFE',[1,INIT]] FDBK = ['START_MODSAFE',[2,INIT]] LIN = ['START_MODSAFE',[3,INIT]] SIN = ['START_MODSAFE',[4,INIT]] TYPES = {'Vconst':LIN,'Fconst':FDBK,'Zconst':NEUTRAL} try: import epz as tempEpz import inspect _,_,keys,_ = inspect.getargspec(tempEpz.CMD.__init__()) if 'tag' not in keys: from libs.epz import epz as tempEpz epz = tempEpz except: from libs.epz import epz # N set the triggers. The triggers are, in order, adc (deflection), dac (z position), time # 1 = used, 0 = not used #Triggers # K = set adc (deflection) stop trigger (Volts) # L = set dac (z position) stop trigger (Volts) # M = set time stop trigger in microseconds # P = set the setpoint for the feedback (-1, +1) # Q = set the proportional gain for the feedback (0.0 to 1.0) # R = set the integral gain for the feedback (0.0 to 1.0) # S = set the differential gain for the feedback (0.0 to 1.0) # B = set DAC output (Volts) # D = set the piezo speed (Volt/s) # C = set the piezo speed sign ''' SET_DACSTEP:D SET_NUMT6TRIG:T SET_TIMETRIG:M SET_DAC_SOFT:B SET_DAC_HARD:U SET_TRIGGERS:N SET_ZTRIG:L SET_FTRIG:K SET_TIM8PER:8 SET_SETPOINT:P SET_PGAIN:Q SET_IGAIN:R SET_DGAIN:S START_MODSAFE:O SET_DACMODE:F SET_TESTPIN:H INIT_SPI2:I SET_RAMPSIGN:C SET_USECIRCBUFF:G SET_MODEDBG:E SET_DACTO0:J SET_DAC_2OR4:A SWITCH_SPI2:g KILL:k '''
[ 1268, 2043, 796, 352, 198, 198, 49, 6465, 796, 37250, 2257, 7227, 62, 33365, 4090, 15112, 3256, 58, 15, 11, 15, 11907, 198, 12161, 3843, 35296, 796, 37250, 2257, 7227, 62, 33365, 4090, 15112, 3256, 58, 16, 11, 1268, 2043, 11907, 198, ...
2.169753
648
import pytest from mock import patch from app.device.brakes import Brakes from app.utils.servo import Servo from app.utils.exceptions import InvalidArguments
[ 11748, 12972, 9288, 198, 6738, 15290, 1330, 8529, 198, 198, 6738, 598, 13, 25202, 13, 16057, 5209, 1330, 9718, 5209, 198, 6738, 598, 13, 26791, 13, 3168, 78, 1330, 3116, 78, 198, 6738, 598, 13, 26791, 13, 1069, 11755, 1330, 17665, 281...
3.613636
44
from collections import Counter
[ 6738, 17268, 1330, 15034, 198 ]
6.4
5
'''Test package for robosync'''
[ 7061, 6, 14402, 5301, 329, 220, 3857, 418, 13361, 7061, 6, 198 ]
2.75
12
#!/usr/bin/env python # coding: utf-8 """ create at 2017/11/22 by allen """ import re from flask import request, session, current_app from app.lib.constant import ResourceType from app.models.auth import Resource, role_resource, Role, user_role, User from app.lib.exceptions import AuthError, PermissionError _auth_db_loader = AuthDbLoader() _http_basic_auth = HttpBasicAuth(user_loader=_auth_db_loader.load_user)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 37811, 198, 220, 220, 220, 2251, 379, 2177, 14, 1157, 14, 1828, 416, 477, 268, 198, 37811, 198, 198, 11748, 302, 198, 6738, 42903, 1330, 2...
3.007042
142
if __name__ == '__main__': s = Solution() print(s.plus_one([9,9,9]))
[ 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 264, 796, 28186, 3419, 198, 220, 220, 220, 3601, 7, 82, 13, 9541, 62, 505, 26933, 24, 11, 24, 11, 24, 60, 4008, 198 ]
2
39
from django.conf import settings from django.template.loader import render_to_string from vms import models def test_accept(client_admin_invite_factory, user_factory): """ Accepting the invitation should create a new client admin for the user who accepts. """ invite = client_admin_invite_factory() user = user_factory() admin = invite.accept(user) assert admin.client == invite.client assert models.ClientAdminInvite.objects.count() == 0 def test_send(client_admin_invite_factory, request_factory, mailoutbox): """ Sending the invitation should send an email to the email address attached to the invite. """ request = request_factory.get('/') invite = client_admin_invite_factory() invite.send(request) context = { 'accept_url': f'{request.get_host()}{invite.accept_url}', 'client': invite.client, } expected_msg = render_to_string( 'vms/emails/client-admin-invite.txt', context=context, ) assert len(mailoutbox) == 1 msg = mailoutbox[0] assert msg.body == expected_msg assert msg.from_email == settings.DEFAULT_FROM_EMAIL assert msg.subject == 'Client Administrator Invitation' assert msg.to == [invite.email] def test_string_conversion(client_admin_invite_factory): """ Converting an invite to a string should return a string containing the email it was sent to and the linked client. """ invite = client_admin_invite_factory() expected = f'Admin invite for {invite.email} from {invite.client}' assert str(invite) == expected
[ 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 28243, 13, 29356, 1330, 8543, 62, 1462, 62, 8841, 198, 198, 6738, 410, 907, 1330, 4981, 628, 198, 4299, 1332, 62, 13635, 7, 16366, 62, 28482, 62, 16340, 578, 62, ...
2.819298
570
import base64 import os import asyncio from pbx_gs_python_utils.utils.Process import Process from osbot_aws.Dependencies import load_dependency
[ 11748, 2779, 2414, 198, 11748, 28686, 198, 11748, 30351, 952, 198, 198, 6738, 279, 65, 87, 62, 14542, 62, 29412, 62, 26791, 13, 26791, 13, 18709, 1330, 10854, 198, 198, 6738, 28686, 13645, 62, 8356, 13, 35, 2690, 3976, 1330, 3440, 62,...
3.217391
46
""" Filter to convert results from network device show commands obtained from ios_command, eos_command, et cetera to structured data using TextFSM templates. """ from __future__ import unicode_literals from __future__ import print_function import os from textfsm.clitable import CliTableError import textfsm.clitable as clitable def get_template_dir(): """Find and return the ntc-templates/templates dir.""" try: template_dir = os.environ['NET_TEXTFSM'] index = os.path.join(template_dir, 'index') if not os.path.isfile(index): # Assume only base ./ntc-templates specified template_dir = os.path.join(template_dir, 'templates') except KeyError: # Construct path ~/ntc-templates/templates home_dir = os.path.expanduser("~") template_dir = os.path.join(home_dir, 'ntc-templates', 'templates') index = os.path.join(template_dir, 'index') if not os.path.isdir(template_dir) or not os.path.isfile(index): msg = """ Valid ntc-templates not found, please install https://github.com/networktocode/ntc-templates and then set the NET_TEXTFSM environment variable to point to the ./ntc-templates/templates directory.""" raise ValueError(msg) return template_dir def get_structured_data(raw_output, platform, command): """Convert raw CLI output to structured data using TextFSM template.""" template_dir = get_template_dir() index_file = os.path.join(template_dir, 'index') textfsm_obj = clitable.CliTable(index_file, template_dir) attrs = {'Command': command, 'Platform': platform} try: # Parse output through template textfsm_obj.ParseCmd(raw_output, attrs) return clitable_to_dict(textfsm_obj) except CliTableError: return raw_output def clitable_to_dict(cli_table): """Converts TextFSM cli_table object to list of dictionaries.""" objs = [] for row in cli_table: temp_dict = {} for index, element in enumerate(row): temp_dict[cli_table.header[index].lower()] = element objs.append(temp_dict) return objs def net_textfsm_parse(output, platform, command): """Process config find interfaces using ip helper.""" try: output = output['stdout'][0] except (KeyError, IndexError, TypeError): pass return get_structured_data(output, platform, command) if __name__ == "__main__": # Test code pass
[ 37811, 198, 22417, 284, 10385, 2482, 422, 3127, 3335, 905, 9729, 6492, 422, 1312, 418, 62, 21812, 11, 198, 68, 418, 62, 21812, 11, 2123, 269, 2357, 64, 284, 20793, 1366, 1262, 8255, 10652, 44, 24019, 13, 198, 37811, 198, 6738, 11593, ...
2.640172
931
#!/usr/bin/python import threading import Queue import serial import time from datetime import datetime from firebase import firebase import sqlite3 from datetime import datetime, timedelta from gpiozero import Button, LED #/////////////////////////////////////////// import firebase_admin from firebase_admin import credentials from firebase_admin import firestore #///////////////////////////////////////////////// missed_events = [] DB_INTERVAL = 180 ##### pin definitions FAULT = LED(5) FALLA = False IN1 = 13 OUT1 = 6 IN2 = 26 OUT2 = 19 in1_button = Button(IN1, pull_up=False) out1_button = Button(OUT1, pull_up=False) in2_button = Button(IN2, pull_up=False) out2_button = Button(OUT2, pull_up=False) eventQueue = Queue.Queue() #### connected = False if __name__ == '__main__': import argparse parser = argparse.ArgumentParser(description='contador de personas') parser.add_argument('-key', required=True, action='store',help='path to key for remote connection') args = parser.parse_args() keyPath = "" if args.key != None: keyPath = args.key #first_event = False dbTh = threading.Thread(target=periodicDBInsert, args=(keyPath,)) #dbTh = threading.Timer(5, periodicDBInsert, args=(db,)) dbTh.daemon = True # ----- dbTh.start() ### #firebase = firebase.FirebaseApplication(URL, authentication=authentication) in1_button.when_pressed = in1Event out1_button.when_pressed = out1Event in2_button.when_pressed = in2Event out2_button.when_pressed = out2Event while True: if not FALLA: FAULT.on() time.sleep(0.1) FAULT.off() time.sleep(0.9) else: FAULT.on() time.sleep(1) FAULT.on() FAULT.on()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 11748, 4704, 278, 198, 11748, 4670, 518, 198, 11748, 11389, 198, 11748, 640, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 6738, 2046, 8692, 1330, 2046, 8692, 198, 11748, 44161, 578, 18, 198, ...
2.581062
697
#-------------------------------------------------------------------------------------------------- # Function: look-for # Purpose: Loops through all AWS accounts and regions within an Organization to find a specific resource # Inputs: # # { # "view_only": "true|false", # "regions": ["us-east-1", ...] # } # # Leave the regions sections blank to apply to all regions # #-------------------------------------------------------------------------------------------------- import json import boto3 import botocore from botocore.exceptions import ClientError from botocore.exceptions import EndpointConnectionError sts_client = boto3.client('sts') organizations_client = boto3.client('organizations') #-------------------------------------------------------------------------------------------------- # Function handler #-------------------------------------------------------------------------------------------------- #-------------------------------------------------- # function: loop_through_account #--------------------------------------------------
[ 2, 10097, 3880, 438, 198, 2, 15553, 25, 804, 12, 1640, 198, 2, 32039, 25, 220, 6706, 2840, 832, 477, 30865, 5504, 290, 7652, 1626, 281, 12275, 284, 1064, 257, 2176, 8271, 198, 2, 23412, 82, 25, 220, 220, 220, 198, 2, 198, 2, 220...
5.199029
206
import logging from typing import Any, Dict from pydantic import ValidationError from scrapy import Spider from scrapy.http import Response from opennem.pipelines.aemo.downloads import DownloadMonitorPipeline from opennem.schema.aemo.downloads import AEMOFileDownloadSection from opennem.utils.dates import parse_date from opennem.utils.numbers import filesize_from_string from opennem.utils.url import strip_query_string
[ 11748, 18931, 198, 6738, 19720, 1330, 4377, 11, 360, 713, 198, 198, 6738, 279, 5173, 5109, 1330, 3254, 24765, 12331, 198, 6738, 15881, 88, 1330, 12648, 198, 6738, 15881, 88, 13, 4023, 1330, 18261, 198, 198, 6738, 1280, 77, 368, 13, 79...
3.455285
123
import wiringpi as pi pi.wiringPiSetupGpio() pi.pinMode(18, pi.PWM_OUTPUT) pi.pwmSetMode(pi.PWM_MODE_MS) pi.pwmSetClock(2) pi.pwmSetRange(192000) while True: for i in list(range(-90, 90, 10)) + list(range(90, -90, -10)): pi.pwmWrite(18, int(((i + 90) / 180 * (2.4 - 0.5) + 0.5) / 20 * 192000)) pi.delay(200)
[ 11748, 29477, 14415, 355, 31028, 198, 14415, 13, 86, 3428, 38729, 40786, 38, 79, 952, 3419, 198, 198, 14415, 13, 11635, 19076, 7, 1507, 11, 31028, 13, 47, 22117, 62, 2606, 7250, 3843, 8, 198, 14415, 13, 79, 26377, 7248, 19076, 7, 14...
2.018987
158
import cv2 as cv from geometry_msgs.msg import Pose2D from vision_msgs.msg import (BoundingBox2D, Detection2D, Detection2DArray, ObjectHypothesisWithPose) THRESHOLD_MAX = 255 THRESHOLD = 240
[ 11748, 269, 85, 17, 355, 269, 85, 198, 6738, 22939, 62, 907, 14542, 13, 19662, 1330, 37557, 17, 35, 198, 6738, 5761, 62, 907, 14542, 13, 19662, 1330, 357, 33, 9969, 14253, 17, 35, 11, 46254, 17, 35, 11, 46254, 17, 35, 19182, 11, ...
2.242424
99
from setuptools import find_packages, setup setup( name="triplet-reid", version="0.1.0", description="Triplet-based Person Re-Identification", packages=find_packages(), )
[ 6738, 900, 37623, 10141, 1330, 1064, 62, 43789, 11, 9058, 198, 198, 40406, 7, 198, 220, 220, 220, 1438, 2625, 28461, 37069, 12, 260, 312, 1600, 198, 220, 220, 220, 2196, 2625, 15, 13, 16, 13, 15, 1600, 198, 220, 220, 220, 6764, 26...
2.80597
67
import csv import sys from KafNafParserPy import KafNafParser from naflib import * woorden = [r['original'] for r in csv.DictReader(open("klimaatwoorden.csv"))] o = csv.writer(sys.stdout) o.writerow(["file", "sentence", "term", "text"]) for fn in sys.argv[1:]: naf = KafNafParser(fn) for klimaterm in find_terms(naf, woorden): sent = get_sentence(naf, klimaterm) text = " ".join([get_word(naf, t) for t in get_terms_in_sentence(naf, sent)]) o.writerow([fn, sent, klimaterm.get_lemma(), text])
[ 11748, 269, 21370, 198, 11748, 25064, 198, 6738, 33913, 45, 1878, 46677, 20519, 1330, 33913, 45, 1878, 46677, 198, 198, 6738, 299, 1878, 8019, 1330, 1635, 198, 198, 21638, 585, 268, 796, 685, 81, 17816, 14986, 20520, 329, 374, 287, 269,...
2.255319
235
# coding=utf-8 from flask import Blueprint, render_template, redirect from controlers.user import UserCtr from libs.login import login_user, logout_user, current_user bp = Blueprint("user", __name__, url_prefix="/user")
[ 2, 19617, 28, 40477, 12, 23, 198, 6738, 42903, 1330, 39932, 11, 8543, 62, 28243, 11, 18941, 198, 6738, 1630, 364, 13, 7220, 1330, 11787, 34, 2213, 198, 6738, 9195, 82, 13, 38235, 1330, 17594, 62, 7220, 11, 2604, 448, 62, 7220, 11, ...
3.373134
67
#!/usr/bin/env python import vector import math, types, operator """ A sparse matrix class based on a dictionary, supporting matrix (dot) product and a conjugate gradient solver. In this version, the sparse class inherits from the dictionary; this requires Python 2.2 or later. """ ############################################################################### def isSparse(x): return hasattr(x,'__class__') and x.__class__ is sparse def transp(a): " transpose " new = sparse({}) for ij in a: new[(ij[1], ij[0])] = a[ij] return new def dotDot(y,a,x): " double dot product y^+ *A*x " if vector.isVector(y) and isSparse(a) and vector.isVector(x): res = 0. for ij in a.keys(): i,j = ij res += y[i]*a[ij]*x[j] return res else: print 'sparse::Error: dotDot takes vector, sparse , vector as args' def dot(a, b): " vector-matrix, matrix-vector or matrix-matrix product " if isSparse(a) and vector.isVector(b): new = vector.zeros(a.size()[0]) for ij in a.keys(): new[ij[0]] += a[ij]* b[ij[1]] return new elif vector.isVector(a) and isSparse(b): new = vector.zeros(b.size()[1]) for ij in b.keys(): new[ij[1]] += a[ij[0]]* b[ij] return new elif isSparse(a) and isSparse(b): if a.size()[1] != b.size()[0]: print '**Warning shapes do not match in dot(sparse, sparse)' new = sparse({}) n = min([a.size()[1], b.size()[0]]) for i in range(a.size()[0]): for j in range(b.size()[1]): sum = 0. for k in range(n): sum += a.get((i,k),0.)*b.get((k,j),0.) if sum != 0.: new[(i,j)] = sum return new else: raise TypeError, 'in dot' def diag(b): # given a sparse matrix b return its diagonal res = vector.zeros(b.size()[0]) for i in range(b.size()[0]): res[i] = b.get((i,i), 0.) return res def identity(n): if type(n) != types.IntType: raise TypeError, ' in identity: # must be integer' else: new = sparse({}) for i in range(n): new[(i,i)] = 1+0. return new ############################################################################### if __name__ == "__main__": print 'a = sparse()' a = sparse() print 'a.__doc__=',a.__doc__ print 'a[(0,0)] = 1.0' a[(0,0)] = 1.0 a.out() print 'a[(2,3)] = 3.0' a[(2,3)] = 3.0 a.out() print 'len(a)=',len(a) print 'a.size()=', a.size() b = sparse({(0,0):2.0, (0,1):1.0, (1,0):1.0, (1,1):2.0, (1,2):1.0, (2,1):1.0, (2,2):2.0}) print 'a=', a print 'b=', b b.out() print 'a+b' c = a + b c.out() print '-a' c = -a c.out() a.out() print 'a-b' c = a - b c.out() print 'a*1.2' c = a*1.2 c.out() print '1.2*a' c = 1.2*a c.out() print 'a=', a print 'dot(a, b)' print 'a.size()[1]=',a.size()[1],' b.size()[0]=', b.size()[0] c = dot(a, b) c.out() print 'dot(b, a)' print 'b.size()[1]=',b.size()[1],' a.size()[0]=', a.size()[0] c = dot(b, a) c.out() try: print 'dot(b, vector.vector([1,2,3]))' c = dot(b, vector.vector([1,2,3])) c.out() print 'dot(vector.vector([1,2,3]), b)' c = dot(vector.vector([1,2,3]), b) c.out() print 'b.size()=', b.size() except: pass print 'a*b -> element by element product' c = a*b c.out() print 'b*a -> element by element product' c = b*a c.out() print 'a/1.2' c = a/1.2 c.out() print 'c = identity(4)' c = identity(4) c.out() print 'c = transp(a)' c = transp(a) c.out() b[(2,2)]=-10.0 b[(2,0)]=+10.0 try: import vector print 'Check conjugate gradient solver' s = vector.vector([1, 0, 0]) print 's' s.out() x0 = s print 'x = b.biCGsolve(x0, s, 1.0e-10, len(b)+1)' x = b.biCGsolve(x0, s, 1.0e-10, len(b)+1) x.out() print 'check validity of CG' c = dot(b, x) - s c.out() except: pass print 'plot b matrix' b.out() b.plot() print 'del b[(2,2)]' del b[(2,2)] print 'del a' del a #a.out()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 15879, 198, 11748, 10688, 11, 3858, 11, 10088, 198, 198, 37811, 198, 32, 29877, 17593, 1398, 1912, 319, 257, 22155, 11, 6493, 17593, 357, 26518, 8, 198, 11167, 290, 257, 11...
2.06158
1,835
import re
[ 11748, 302, 628 ]
3.666667
3
#https://www.youtube.com/watch?v=f9PR1qcwOyg #create global convention import mysql.connector __cnx=None
[ 2, 5450, 1378, 2503, 13, 11604, 13, 785, 14, 8340, 30, 85, 28, 69, 24, 4805, 16, 80, 66, 86, 46, 35641, 201, 198, 2, 17953, 3298, 9831, 220, 201, 198, 11748, 48761, 13, 8443, 273, 201, 198, 834, 31522, 87, 28, 14202, 201 ]
2.477273
44
import matplotlib.pyplot as plt
[ 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 628, 198 ]
2.833333
12
#!_PYTHONLOC # # (C) COPYRIGHT 2004-2021 Al von Ruff, Bill Longley and Ahasuerus # ALL RIGHTS RESERVED # # The copyright notice above does not evidence any actual or # intended publication of such source code. # # Version: $Revision$ # Date: $Date$ from isfdb import * from isfdblib import * from isfdblib_help import * from isfdblib_print import * from library import * from SQLparsing import * if __name__ == '__main__': series_number = SESSION.Parameter(0, 'int') series = SQLget1Series(series_number) if not series: SESSION.DisplayError('Record Does Not Exist') PrintPreSearch('Series Editor') PrintNavBar('edit/editseries.cgi', series_number) help = HelpSeries() printHelpBox('series', 'SeriesData') print "Note:" print "<ul>" print "<li>Changing the Name field changes the name of the series for all books currently in this series." print "<li>Changing the Parent field does NOT change the name of the parent series." print "<li>If the Parent exists, changing the Parent field relinks the Named series to that parent." print "<li>If the Parent does not exist, a new Parent series will be created and the Named series will be linked to that parent." print "</ul>" print "<hr>" print "<p>" print '<form id="data" METHOD="POST" ACTION="/cgi-bin/edit/submitseries.cgi">' print '<table border="0">' print '<tbody id="tagBody">' # Display the series name printfield("Name", "series_name", help, series[SERIES_NAME]) trans_series_names = SQLloadTransSeriesNames(series[SERIES_PUBID]) printmultiple(trans_series_names, "Transliterated Name", "trans_series_names", help) # Display the name of this series' parent (if one exists) parent_series_name = '' if series[SERIES_PARENT]: parent_series = SQLget1Series(series[SERIES_PARENT]) parent_series_name = parent_series[SERIES_NAME] printfield("Parent", "series_parent", help, parent_series_name) # Display this series' ordering position within its superseries printfield("Series Parent Position", "series_parentposition", help, series[SERIES_PARENT_POSITION]) webpages = SQLloadSeriesWebpages(series[SERIES_PUBID]) printWebPages(webpages, 'series', help) printtextarea('Note', 'series_note', help, SQLgetNotes(series[SERIES_NOTE])) printtextarea('Note to Moderator', 'mod_note', help, '') print '</tbody>' print '</table>' print '<p>' print '<hr>' print '<p>' print '<input NAME="series_id" VALUE="%d" TYPE="HIDDEN">' % series_number print '<input TYPE="SUBMIT" VALUE="Submit Data" tabindex="1">' print '</form>' print '<p>' print '<hr>' PrintPostSearch(0, 0, 0, 0, 0, 0)
[ 2, 0, 62, 47, 56, 4221, 1340, 29701, 198, 2, 198, 2, 220, 220, 220, 220, 357, 34, 8, 27975, 38162, 9947, 5472, 12, 1238, 2481, 220, 220, 978, 18042, 42409, 11, 3941, 5882, 1636, 290, 7900, 292, 15573, 385, 198, 2, 220, 220, 220,...
2.701652
1,029
import pyaudio import numpy as np import mixer
[ 11748, 12972, 24051, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 33938, 198, 220, 220, 220, 220, 220, 220, 220, 220 ]
2.619048
21
""" From https://github.com/brechtm/rinohtype/blob/master/noxutil.py https://github.com/cjolowicz/nox-poetry/discussions/289 """ import json from collections.abc import Iterable from pathlib import Path from typing import Optional from urllib.request import urlopen, Request from poetry.core.factory import Factory from poetry.core.semver import parse_single_constraint as parse_version VERSION_PARTS = ("major", "minor", "patch") def get_versions( dependency: str, granularity: str = "minor", # ascending: bool = False, limit: Optional[int] = None, # allow_prerelease: bool = False, ) -> Iterable[str]: """Yield all versions of `dependency` considering version constraints Args: dependency: the name of the dependency granularity: yield only the newest patch version of each major/minor release ascending: count backwards from latest version, by default (not much use without the 'limit' arg) limit: maximum number of entries to return allow_prerelease: whether to include pre-release versions Yields: All versions of `dependency` that match the version constraints defined and in this project's pyproject.toml and the given `granularity`. """ package = Factory().create_poetry(Path(__file__).parent).package for requirement in package.requires: if requirement.name == dependency: break else: raise ValueError(f"{package.name} has no dependency '{dependency}'") filtered_versions = [ version for version in all_versions(dependency) if requirement.constraint.allows(version) ] parts = VERSION_PARTS[: VERSION_PARTS.index(granularity) + 1] result = {} for version in filtered_versions: key = tuple(getattr(version, part) for part in parts) result[key] = max((result[key], version)) if key in result else version return [str(version) for version in result.values()]
[ 37811, 198, 198, 4863, 3740, 1378, 12567, 13, 785, 14, 4679, 354, 17209, 14, 12769, 1219, 4906, 14, 2436, 672, 14, 9866, 14, 35420, 22602, 13, 9078, 198, 5450, 1378, 12567, 13, 785, 14, 66, 73, 349, 47982, 14, 35420, 12, 7501, 11973...
2.899417
686
from django.contrib import admin from tbutton_web.tbutton_maker.models import Application, Button, DownloadSession, UpdateSession admin.site.register(DownloadSession, DownloadSessionAdmin) admin.site.register(UpdateSession, UpdateSessionAdmin)
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 6738, 256, 16539, 62, 12384, 13, 83, 16539, 62, 10297, 13, 27530, 1330, 15678, 11, 20969, 11, 10472, 36044, 11, 10133, 36044, 198, 28482, 13, 15654, 13, 30238, 7, 10002, 36044, 11, ...
4.118644
59
#PASCALS TRIANGLE USING RECURSION if __name__ == "__main__": print("Enter the number of rows:") n=int(input()) #getting user input print(pascal(n)) #call the pascal triangle function ''' OUTPUT:Enter the number of rows:5 [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]] '''
[ 2, 47, 42643, 23333, 37679, 15567, 2538, 1294, 2751, 19644, 4261, 50, 2849, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 197, 4798, 7203, 17469, 262, 1271, 286, 15274, 25, 4943, 198, 197, 77, 28, 600, 7, 1...
1.913978
186
#!/usr/bin/env python2.7 from __future__ import division import roslib import rospy import tf from nav_msgs.msg import Odometry from nav_msgs.msg import Path from geometry_msgs.msg import PoseStamped import numpy as np import pdb from message_filters import Subscriber, ApproximateTimeSynchronizer if __name__ == '__main__': rospy.init_node('gt_cleaner', anonymous=True) cleaner_obj = GT_cleaner() rospy.spin()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 17, 13, 22, 198, 6738, 11593, 37443, 834, 1330, 7297, 198, 11748, 686, 6649, 571, 198, 11748, 686, 2777, 88, 198, 11748, 48700, 198, 6738, 6812, 62, 907, 14542, 13, 19662, 1330, 10529, 1574...
2.84
150
from datetime import datetime from gpiozero import DistanceSensor from garage_door import garage_door from garage_camera import garage_camera import MQTT_Config import paho.mqtt.client as mqtt from temp_sensor import temp_sensor from time import sleep """ GPIO pin assignments: relays range finder sensor (echo passes thru voltage converter) DHT11 temperature/huidity sensor """ GPIO_Pins = {'temp_1':21, 'relay_1':6, 'relay_2':12, 'trig_1':17, 'echo_1':18, 'trig_2':22, 'echo_2':23} """ MQTT connect callback Subscribing in on_connect() means that if we lose the connection and reconnect then subscriptions will be renewed. """ """ MQTT receive message callback (garage/command) Take action on a subject """ """ MQTT publish callback Mainly for debugging """ """ Just in case """ """ Create client and connect it to the MQTT broker """ mqc = mqtt.Client("garage-pi", clean_session=True) mqc.on_connect = on_connect mqc.on_message = on_message mqc.on_publish = on_publish mqc.username_pw_set(mqtt_account, mqtt_passwd) mqc.connect(mqtt_broker) mqc.loop_start() mqc.publish("garage/foo", "go!") """ Create temperature sensor object """ dht11 = temp_sensor(mqc, GPIO_Pins['temp_1']) """ Create garage camera object """ garage_cam = garage_camera(mqc) """ Create garage door objects """ garage_doors = dict() garage_doors["left"] = garage_door(mqc, "left", GPIO_Pins['relay_1'], GPIO_Pins['echo_1'], GPIO_Pins['trig_1']) garage_doors["right"] = garage_door(mqc, "right", GPIO_Pins['relay_2'], GPIO_Pins['echo_2'], GPIO_Pins['trig_2']) if __name__ == "__main__": main()
[ 6738, 4818, 8079, 1330, 4818, 8079, 198, 6738, 27809, 952, 22570, 1330, 34600, 47864, 198, 6738, 15591, 62, 9424, 1330, 15591, 62, 9424, 198, 6738, 15591, 62, 25695, 1330, 15591, 62, 25695, 198, 11748, 337, 48, 15751, 62, 16934, 198, 11...
2.017294
983
# encoding: utf-8 import os import time from multiprocessing import Pool, cpu_count from selenium import webdriver from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.common.exceptions import TimeoutException from enote.util import get_note, get_notebook, get_notebooks, \ create_resource, create_note, create_notebook, update_note from github.util import get_user_name, get_all_gists from web.util import fullpage_screenshot, get_gist_hash, create_chrome_driver from settings import NOTEBOOK_TO_SYNC from db import get_db DATE_FORMAT = "%Y-%m-%dT%H:%M:%SZ" GIST_BASE_URL = 'https://gist.github.com' notebook = None github_user = get_user_name() # get current login github user for fetching gist content db = get_db() # database to store synchronization info def sync_gist(gist, driver): """Sync the Github gist to the corresponding Evernote note. Create a new Evernote note if there is no corresponding one with the gist. Overwrite existing note's content if gist has been changed. Parameters ---------- gist : dict A Gist acquired by Github GraphQL API with format like: { 'id': 'gist_id', 'name': 'gist_name', 'description': 'description', 'pushAt': '2018-01-15T00:48:23Z' } driver : selenium.webdriver The web driver used to access gist url Returns ------- note : evernote.edam.type.ttpyes.Note None if no new note created or updated """ note_exist = False gist_url = '/'.join((GIST_BASE_URL, gist['name'])) # check existing gist hash before fetch if available prev_hash = db.get_hash_by_id(gist['id']) note_guid = db.get_note_guid_by_id(gist['id']) if prev_hash and note_guid: note_exist = True cur_hash = get_gist_hash(github_user, gist['name']) if prev_hash == cur_hash: print('Gist {} remain the same, ignore.'.format(gist_url)) db.update_gist(gist, note_guid, cur_hash) return None driver.get(gist_url) # wait at most x seconds for Github rendering gist context delay_seconds = 10 try: WebDriverWait(driver, delay_seconds).until(EC.presence_of_element_located((By.CLASS_NAME, 'is-render-ready'))) except TimeoutException: print("Take longer than {} seconds to load page.".format(delay_seconds)) # get first file name as default note title gist_title = driver.find_element(By.CLASS_NAME, 'gist-header-title>a').text # take screen shot for the gist and save it temporally image_path = 'images/{}.png'.format(gist['name']) fullpage_screenshot(driver, image_path) # build skeleton for note (including screenshot) resource, _ = create_resource(image_path) note_title = gist['description'] if gist['description'] else gist_title note_body = format_note_body(gist) # get hash of raw gist content and save gist info to database gist_hash = get_gist_hash(github_user, gist['name']) # create new note / update existing note if not note_exist: note = create_note(note_title, note_body, [resource], parent_notebook=notebook) db.save_gist(gist, note.guid, gist_hash) else: note = get_note(note_guid) update_note(note, note_title, note_body, note_guid, [resource]) db.update_gist(gist, note_guid, gist_hash) os.remove(image_path) print("Finish creating note for gist {}".format(gist_url)) return note def format_note_body(gist): """Create the note content that will be shown before attachments. Parameters ---------- gist : dict Dict that contains all information of the gist Returns ------- note_body : str """ blocks = [] desc = gist['description'] if desc: blocks.append(desc) gist_url = '/'.join((GIST_BASE_URL, gist['name'])) blocks.append('<a href="{}">Gist on Github</a>'.format(gist_url)) note_body = '<br/>'.join(blocks) return note_body if __name__ == '__main__': app()
[ 2, 21004, 25, 3384, 69, 12, 23, 198, 11748, 28686, 198, 11748, 640, 198, 6738, 18540, 305, 919, 278, 1330, 19850, 11, 42804, 62, 9127, 198, 6738, 384, 11925, 1505, 1330, 3992, 26230, 198, 6738, 384, 11925, 1505, 13, 12384, 26230, 13, ...
2.616438
1,606
from .hola import *
[ 6738, 764, 3937, 64, 1330, 1635, 198 ]
2.857143
7
import collections
[ 11748, 17268, 198 ]
6.333333
3
import numpy as np if __name__ == '__main__': try: f = open('test_file.txt', 'w') f.write('this is exception finally') except Exception as e: pass finally: f.close pass
[ 11748, 299, 32152, 355, 45941, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1949, 25, 198, 220, 220, 220, 220, 220, 220, 220, 277, 796, 1280, 10786, 9288, 62, 7753, 13, 14116, 3256, 705, 86...
2.148515
101
import os store.set_global_value("ctrl-space", False) with open(os.path.expanduser("~/.config/polybar/keys.fifo"), "wb") as f: f.write(b"TITLE:\n") store.set_global_value("emacs-chain-keys", [])
[ 11748, 28686, 198, 8095, 13, 2617, 62, 20541, 62, 8367, 7203, 44755, 12, 13200, 1600, 10352, 8, 198, 4480, 1280, 7, 418, 13, 6978, 13, 11201, 392, 7220, 7203, 93, 11757, 11250, 14, 35428, 5657, 14, 13083, 13, 32041, 78, 12340, 366, ...
2.475
80
from .field import Field # NOQA from .datetime_field import DateTime # NOQA from .date import Date # NOQA from .string import String # NOQA from .object import Object # NOQA from .list import List # NOQA from .polymorphic_object import PolymorphicObject # NOQA from .polymorphic_list import PolymorphicList # NOQA from .constant import Constant # NOQA from .int import Int # NOQA from .float import Float # NOQA from .number import Number # NOQA from .bool import Bool # NOQA from .dict import Dict # NOQA
[ 6738, 764, 3245, 1330, 7663, 220, 1303, 8005, 48, 32, 198, 6738, 764, 19608, 8079, 62, 3245, 1330, 7536, 7575, 220, 1303, 8005, 48, 32, 198, 6738, 764, 4475, 1330, 7536, 220, 1303, 8005, 48, 32, 198, 6738, 764, 8841, 1330, 10903, 22...
2.971429
175
from django.urls import path from django.conf.urls import url from . import views urlpatterns = [ path('', views.index, name='index'), path('logout/', views.logoutView, name='logout'), path('signup/', views.signup, name='signup'), url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', views.activate, name='activate'), path('myprofile/', views.myprofile, name='myprofile'), path('myprofile/edit/', views.myprofile_edit, name='myprofile_edit'), path('testing', views.testing, name='testing') ]
[ 6738, 42625, 14208, 13, 6371, 82, 1330, 3108, 198, 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 1330, 19016, 198, 198, 6738, 764, 1330, 5009, 198, 198, 6371, 33279, 82, 796, 685, 198, 220, 220, 220, 3108, 10786, 3256, 5009, 13, 9630, ...
2.431034
232
__version__ = "0.2" import threading import numpy as np import pygame from expyriment.stimuli import Canvas, Rectangle, TextLine from expyriment.stimuli._visual import Visual from expyriment.misc import constants lock_expyriment = threading.Lock() Numpy_array_type = type(np.array([])) def data2pixel(self, values): """ values: numeric or numpy array pixel_min_max: 2D array""" return (values - self._zero_shift) * \ (self.pixel_max - self.pixel_min) / self._range # pixel_factor def trim(self, value): """trims value to the range, ie. set to min or max if <min or > max """ if value < self.min: return self.min elif value > self.max: return self.max return value class PGSurface(Canvas): """PyGame Surface: Expyriment Stimulus for direct Pygame operations and PixelArrays In contrast to other Expyriment stimuli the class does not generate temporary surfaces. """ def unlock_pixel_array(self): """todo""" self._px_array = None def preload(self, inhibit_ogl_compress=False): self.unlock_pixel_array() return Canvas.preload(self, inhibit_ogl_compress) def compress(self): self.unlock_pixel_array() return Canvas.compress(self) def decompress(self): self.unlock_pixel_array() return Canvas.decompress(self) def plot(self, stimulus): self.unlock_pixel_array() return Canvas.plot(self, stimulus) def clear_surface(self): self.unlock_pixel_array() return Canvas.clear_surface(self) def copy(self): self.unlock_pixel_array() return Canvas.copy(self) def unload(self, keep_surface=False): if not keep_surface: self.unlock_pixel_array() return Canvas.unload(self, keep_surface) def rotate(self, degree): self.unlock_pixel_array() return Canvas.rotate(self, degree) def scale(self, factors): self.unlock_pixel_array() return Canvas.scale(self, factors) # expyriment 0.8.0 # def scale_to_fullscreen(self, keep_aspect_ratio=True): # self.unlock_pixel_array() # return Canvas.scale_to_fullscreen(self, keep_aspect_ratio) class Plotter(PGSurface): """Pygame Plotter""" def clear_area(self): self.pixel_array[:, :] = self._background_colour def set_horizontal_line(self, y_values): """y_values: array""" try: self._horizontal_lines = np.array(y_values, dtype=int) except: self._horizontal_lines = None def write_values(self, position, values, set_marker=False, set_point_marker=False): """ additional points: np.array """ if set_marker: self.pixel_array[position, :] = self.marker_colour else: self.pixel_array[position, :] = self._background_colour if set_point_marker: self.pixel_array[position, 0:2] = self.marker_colour if self._horizontal_lines is not None: for c in (self._y_range[1] - self._horizontal_lines): self.pixel_array[:, c:c+1] = self.marker_colour for c, plot_value in enumerate(self._y_range[1] - \ np.array(values, dtype=int)): if plot_value >= 0 and self._previous[c] >= 0 \ and plot_value <= self._height and \ self._previous[c] <= self._height: if self._previous[c] > plot_value: self.pixel_array[position, plot_value:self._previous[c] + 1] = \ self._data_row_colours[c] else: self.pixel_array[position, self._previous[c]:plot_value + 1] = \ self._data_row_colours[c] self._previous[c] = plot_value def add_values(self, values, set_marker=False): """ high level function of write values with type check and shifting to left not used by plotter thread """ if type(values) is not Numpy_array_type and \ not isinstance(values, tuple) and \ not isinstance(values, list): values = [values] if len(values) != self.n_data_rows: raise RuntimeError('Number of data values does not match the ' + 'defined number of data rows!') # move plot one pixel to the left self.pixel_array[:-1, :] = self.pixel_array[1:, :] self.write_values(position=-1, values=values, set_marker=set_marker) def level_indicator(value, text, scaling, width=20, text_size=14, text_gap=20, position=(0,0), thresholds = None, colour=constants.C_EXPYRIMENT_ORANGE): """make an level indicator in for of an Expyriment stimulus text_gap: gap between indicator and text scaling: Scaling object Returns -------- expyriment.Canvas """ value = scaling.trim(value) # indicator height = scaling.pixel_max - scaling.pixel_min indicator = Canvas(size=[width + 2, height + 2], colour=(30, 30, 30)) zero = scaling.data2pixel(0) px_bar_height = scaling.data2pixel(value) - zero bar = Rectangle(size=(width, abs(px_bar_height)), position=(0, zero + int((px_bar_height + 1) / 2)), colour=colour) bar.plot(indicator) # levels & horizontal lines try: px_horizontal_lines = scaling.data2pixel(values=np.array(thresholds.thresholds)) except: px_horizontal_lines = None if px_horizontal_lines is not None: for px in px_horizontal_lines: level = Rectangle(size=(width+6, 2), position=(0, px), colour=constants.C_WHITE) level.plot(indicator) # text labels txt = TextLine(text=text, text_size=text_size, position=(0, -1 * (int(height / 2.0) + text_gap)), text_colour=constants.C_YELLOW) # make return canvas w = max(txt.surface_size[0], indicator.size[0]) h = height + 2 * (txt.surface_size[1]) + text_gap rtn = Canvas(size=(w, h), colour=(0, 0, 0), position=position) indicator.plot(rtn) txt.plot(rtn) return rtn if __name__ == "__main__": pass
[ 834, 9641, 834, 796, 366, 15, 13, 17, 1, 198, 198, 11748, 4704, 278, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 12972, 6057, 198, 6738, 1033, 2417, 3681, 13, 42003, 32176, 1330, 1680, 11017, 11, 48599, 9248, 11, 8255, 13949, 198,...
2.158383
3,018
# -*- coding: utf-8 -*- ################################################################################ # Copyright 2014, Distributed Meta-Analysis System ################################################################################ """ This file provides methods for handling weighting across GCMs under delta method calculations. """ __copyright__ = "Copyright 2014, Distributed Meta-Analysis System" __author__ = "James Rising" __credits__ = ["James Rising"] __maintainer__ = "James Rising" __email__ = "j.a.rising@lse.ac.uk" __status__ = "Production" __version__ = "$Revision$" # $Source$ import numpy as np from scipy.optimize import brentq from scipy.stats import norm if __name__ == '__main__': ## Example between R and python ## R: # means <- rnorm(10) # sds <- rexp(10) # weights <- runif(10) # weights <- weights / sum(weights) # draws <- sapply(1:100000, function(ii) sample(rnorm(10, means, sds), 1, prob=weights)) # pp <- runif(10) # quantile(draws, pp) ## For the values below: # > quantile(draws, pp) # 4.261865% 57.54305% 9.961645% 13.1325% 68.3729% 89.93871% 37.68216% 25.06827% 72.6134% 92.35501% # -2.70958468 0.77240194 -2.15403320 -1.90146370 1.17428553 1.95475922 -0.06482985 -0.92293638 1.36865349 2.00405179 ## Python: means = [-1.10402809, 1.91300947, -2.21007153, 0.65175650, 0.56314868, -0.28337581, 0.98788803, 1.10211432, -0.06220629, -1.45807086] variances = np.array([0.65422226, 0.13413332, 0.61493262, 0.29639041, 2.20748648, 1.69513869, 1.15008972, 0.41550756, 0.03384455, 1.07446232])**2 weights = [0.07420341, 0.16907337, 0.11439943, 0.08439015, 0.01868190, 0.14571485, 0.07630478, 0.17063990, 0.09951820, 0.04707401] pp = [0.04261865, 0.57543051, 0.09961645, 0.13132502, 0.68372897, 0.89938713, 0.37682157, 0.25068274, 0.72613404, 0.92355014] dist = WeightedGMCDF(means, variances, weights) print dist.inverse(pp) # [-2.708582712985005, 0.7720415676939508, -2.152969315647189, -1.8999500392063315, 1.1698917665106159, 1.955783738182657, -0.0641650435162273, -0.9150700927430755, 1.3660161904436894, 2.004650382993468]
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 29113, 29113, 14468, 198, 2, 15069, 1946, 11, 4307, 6169, 30277, 12, 32750, 4482, 198, 29113, 29113, 14468, 198, 198, 37811, 198, 1212, 2393, 3769, 5050, 329, 9041, 3463, ...
2.305585
949
from rest_framework import status from rest_framework.generics import RetrieveUpdateAPIView from rest_framework.response import Response from ecojunk.users.api.v1.serializers import UserSerializer
[ 6738, 1334, 62, 30604, 1330, 3722, 198, 6738, 1334, 62, 30604, 13, 8612, 873, 1330, 4990, 30227, 10260, 2969, 3824, 769, 198, 6738, 1334, 62, 30604, 13, 26209, 1330, 18261, 198, 198, 6738, 34286, 73, 2954, 13, 18417, 13, 15042, 13, 85...
3.901961
51
# encoding: utf-8 # pylint: disable=bad-continuation """ RESTful API Payments resources -------------------------- """ import logging from flask_login import current_user from flask_restplus_patched import Resource from flask_restplus._http import HTTPStatus from app.extensions import db from app.extensions.api import Namespace, abort from app.extensions.api.parameters import PaginationParameters from . import parameters, schemas from .models import Payment log = logging.getLogger(__name__) # pylint: disable=invalid-name api = Namespace('payments', description="Payments") # pylint: disable=invalid-name
[ 2, 21004, 25, 3384, 69, 12, 23, 198, 2, 279, 2645, 600, 25, 15560, 28, 14774, 12, 18487, 2288, 198, 37811, 198, 49, 6465, 913, 7824, 41318, 4133, 198, 22369, 438, 198, 37811, 198, 198, 11748, 18931, 198, 198, 6738, 42903, 62, 38235,...
3.548571
175
import msgraphy_util import argparse from msgraphy import GraphApi if __name__ == "__main__": parser = argparse.ArgumentParser( description='List or search for MS team' ) parser.add_argument("name", type=str, nargs="?", help="show only teams which contains [name]") parser.add_argument("--starts_with", "-s", type=str, nargs="?", metavar="value", help="only teams starting with [value]") parser.add_argument("--exact", "-e", type=str, nargs="?", metavar="value", help="only teams exactly matching [value]") parser.add_argument("--channels", "-c", action='store_true', help="include channels") parser.add_argument("--folder", "-f", action='store_true', help="include channel folder (implies -c)") args = parser.parse_args() main(**vars(args))
[ 11748, 31456, 1470, 88, 62, 22602, 198, 11748, 1822, 29572, 198, 6738, 31456, 1470, 88, 1330, 29681, 32, 14415, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 30751, 796, 1822, 29572, 13, 2...
2.92963
270
import pygame as p from math import floor from copy import deepcopy import Tkinter, tkFileDialog root = Tkinter.Tk() root.withdraw() p.init() running = True tileWidth = 16 tileHeight = 16 mapWidth = 100 mapHeight = 100 camX = 0 camY = 0 scale = 2 uiScale = 2 hand = 1 layerStack = True file_path = '' file_path = tkFileDialog.askopenfilename() if file_path[-3:] != 'png': exit() layers = [] currentLayer = 1 layers.append([-1] * (mapWidth * mapHeight)) layers.append([-1] * (mapWidth * mapHeight)) prevLayers = deepcopy(layers) prevLayerLists = [] prevLayerListsRedo = [] brush = p.image.load('brush.png') brushHover = p.image.load('brushHover.png') square = p.image.load('square.png') squareHover = p.image.load('squareHover.png') brushRect = brush.get_rect() squareRect = square.get_rect() brushRect.width, brushRect.height = brushRect.width * uiScale, brushRect.height * uiScale squareRect.width, squareRect.height = squareRect.width * uiScale, squareRect.height * uiScale (width, height) = (480, 360) p.display.set_caption('Tile Editor') font = p.font.Font('Minecraftia-Regular.ttf', 8) s = p.display.set_mode((width, height), p.RESIZABLE) clock = p.time.Clock() middleClick = False leftClick = False leftClickPrev = False rightClick = False rightClickDown = False rightClickPrev = False mouseOffset = (0, 0) mousePos = (0, 0) buttonClick = False buttonHover = False sDown = False squareT = False sDownStart = False startPos = (0,0) tiles = [] sheetHeight = 0 sheetWidth = 0 load_sheet(file_path) while running: windowResize = False for event in p.event.get(): if event.type == p.QUIT: running = False elif event.type == p.MOUSEMOTION: mousePos = p.mouse.get_pos() elif event.type == p.MOUSEBUTTONDOWN: mousePos = p.mouse.get_pos() if event.button == 2: mouseOffset = (mousePos[0] - camX, mousePos[1] - camY); middleClick = True elif event.button == 1: leftClick = True elif event.button == 3: rightClick = True rightClickDown = True elif event.type == p.MOUSEBUTTONUP: if event.button == 2: middleClick = False elif event.button == 1: leftClick = False elif event.button == 3: rightClick = False elif event.type == p.MOUSEWHEEL and not middleClick: scale += event.y if(scale < 1): scale = 1 elif event.type == p.VIDEORESIZE: width = event.w height = event.h windowResize = True elif event.type == p.KEYDOWN: if event.key == p.K_z and p.key.get_mods() & p.KMOD_CTRL: if len(prevLayerLists) != 0: prevLayerListsRedo.append(layers) layers = prevLayerLists[-1] del prevLayerLists[-1] elif event.key == p.K_y and p.key.get_mods() & p.KMOD_CTRL: if len(prevLayerListsRedo) != 0: prevLayerLists.append(layers) layers = prevLayerListsRedo[-1] del prevLayerListsRedo[-1] elif event.key == p.K_s: sDown = True elif event.type == p.KEYUP: if event.key == p.K_s: sDown = False prevLayers = deepcopy(layers) if middleClick: camX, camY = mousePos[0] - mouseOffset[0], mousePos[1] - mouseOffset[1] x = int(round((mousePos[0] - camX) / (tileWidth * scale))) y = int(round((mousePos[1] - camY) / (tileHeight * scale))) layers[0][(y * mapWidth) + x] = hand if leftClick and not sDownStart: if(mousePos[0] > (9 * uiScale) and mousePos[0] < (sheetWidth + 9) * uiScale and mousePos[1] > (9 * uiScale) and mousePos[1] < (sheetHeight + 9) * uiScale): x = int(round((mousePos[0] - (9 * uiScale)) / (tileWidth * uiScale))) y = int(round((mousePos[1] - (9 * uiScale)) / (tileHeight * uiScale))) hand = (y * (sheetWidth // (tileWidth))) + x else: if(mousePos[0] > camX and mousePos[0] < camX + ((tileWidth * scale) * mapWidth) and mousePos[1] > camY and mousePos[1] < camY + ((tileHeight * scale) * mapHeight)): layers[currentLayer][(y * mapWidth) + x] = hand elif rightClick and not sDown: if(mousePos[0] > camX and mousePos[0] < camX + ((tileWidth * scale) * mapWidth) and mousePos[1] > camY and mousePos[1] < camY + ((tileHeight * scale) * mapHeight)): layers[currentLayer][(y * mapWidth) + x] = -1 s.fill((41,48,50)) renderList = [] for i in range(0, len(layers)): if not i == 0: for x in range(mapWidth): for y in range(mapHeight): if (x * tileWidth * scale) + camX > tileWidth * -scale and (x * tileWidth * scale) + camX < width and (y * tileHeight * scale) + camY > tileHeight * -scale and (y * tileHeight * scale) + camY < height: tile = layers[0][y * mapWidth + x] if not layerStack: if i == currentLayer and tile != -1 and not [x,y] in renderList: renderList.append([x,y]) s.blit(p.transform.scale(tiles[tile][0], (tileWidth * scale, tileHeight * scale)), ((x * tileWidth * scale) + camX, (y * tileHeight * scale) + camY)) else: tile = layers[i][y * mapWidth + x] if not [x,y] in renderList: if tile == -1 and i == currentLayer: if uiScale >= scale: p.draw.rect(s, (86,92,86), p.Rect((x * tileWidth * scale) + camX, (y * tileHeight * scale) + camY, tileWidth * scale, tileHeight * scale), 1) else: p.draw.rect(s, (86,92,86), p.Rect((x * tileWidth * scale) + camX, (y * tileHeight * scale) + camY, tileWidth * scale, tileHeight * scale), uiScale) elif tile != -1: renderList.append([x,y]) s.blit(p.transform.scale(tiles[tile][0], (tileWidth * scale, tileHeight * scale)), ((x * tileWidth * scale) + camX, (y * tileHeight * scale) + camY)) else: if i == currentLayer and tile != -1: renderList.append([x,y,tile]) else: tile = layers[i][y * mapWidth + x] if tile == -1 and i == currentLayer: if uiScale >= scale: p.draw.rect(s, (86,92,86), p.Rect((x * tileWidth * scale) + camX, (y * tileHeight * scale) + camY, tileWidth * scale, tileHeight * scale), 1) else: p.draw.rect(s, (86,92,86), p.Rect((x * tileWidth * scale) + camX, (y * tileHeight * scale) + camY, tileWidth * scale, tileHeight * scale), uiScale) elif tile != -1: renderList.append([x,y,tile]) if layerStack: for i in range(len(renderList)-1, 0, -1): s.blit(p.transform.scale(tiles[renderList[i][2]][0], (tileWidth * scale, tileHeight * scale)), ((renderList[i][0] * tileWidth * scale) + camX, (renderList[i][1] * tileHeight * scale) + camY)) i = sheetHeight + int(tileHeight * 1.5 + 12) s.blit(drawBox(sheetWidth + 12, i, True), (3 * uiScale, 3 * uiScale)) drawButton('New Layer', 3 * uiScale, (i + 6) * uiScale) if buttonClick: layers.append([-1] * (mapWidth * mapHeight)) currentLayer = len(layers)-1 for layer in range(0, len(layers)-1): drawButton('Layer ' + str(layer + 1), 3 * uiScale, (i + 26 * (layer + 1)) * uiScale) if buttonClick: currentLayer = layer + 1 if buttonHover and rightClickDown and len(layers) > 2: prevLayerLists.append(deepcopy(layers)) del layers[layer + 1] if currentLayer > len(layers) - 1: currentLayer -= 1 prevLayers = layers for image in tiles: s.blit(p.transform.scale(image[0], (tileWidth * uiScale, tileHeight * uiScale)), ((image[1] + 9) * uiScale, (image[2] + 9) * uiScale)) s.blit(p.transform.scale(tiles[hand][0], (tileWidth * uiScale, tileHeight * uiScale)), (9 * uiScale, (sheetHeight + tileHeight) * uiScale)) drawButton('Open Tilesheet', (sheetWidth + 18) * uiScale, 3 * uiScale) if buttonClick: file_path = tkFileDialog.askopenfilename() if file_path[-3:] == 'png': load_sheet(file_path) drawButton('Layer Stack', (sheetWidth + 18) * uiScale, 23 * uiScale) if buttonClick: layerStack = not layerStack layers[0] = [-1] * (mapWidth * mapHeight) if not leftClick and leftClickPrev and sDownStart: sDownStart = False for x in range(startPos[0], int(round((mousePos[0] - camX) / (tileWidth * scale))) + 1): for y in range(startPos[1], int(round((mousePos[1] - camY) / (tileHeight * scale))) + 1): if(mousePos[0] > camX and mousePos[0] < camX + ((tileWidth * scale) * mapWidth) and mousePos[1] > camY and mousePos[1] < camY + ((tileHeight * scale) * mapHeight)): layers[currentLayer][(y * mapWidth) + x] = hand for x in range(startPos[0], int(round((mousePos[0] - camX) / (tileWidth * scale))) - 1, -1): for y in range(startPos[1], int(round((mousePos[1] - camY) / (tileHeight * scale))) - 1, -1): if(mousePos[0] > camX and mousePos[0] < camX + ((tileWidth * scale) * mapWidth) and mousePos[1] > camY and mousePos[1] < camY + ((tileHeight * scale) * mapHeight)): layers[currentLayer][(y * mapWidth) + x] = hand for x in range(startPos[0], int(round((mousePos[0] - camX) / (tileWidth * scale))) + 1): for y in range(startPos[1], int(round((mousePos[1] - camY) / (tileHeight * scale))) - 1, -1): if(mousePos[0] > camX and mousePos[0] < camX + ((tileWidth * scale) * mapWidth) and mousePos[1] > camY and mousePos[1] < camY + ((tileHeight * scale) * mapHeight)): layers[currentLayer][(y * mapWidth) + x] = hand for x in range(startPos[0], int(round((mousePos[0] - camX) / (tileWidth * scale))) - 1, -1): for y in range(startPos[1], int(round((mousePos[1] - camY) / (tileHeight * scale))) + 1): if(mousePos[0] > camX and mousePos[0] < camX + ((tileWidth * scale) * mapWidth) and mousePos[1] > camY and mousePos[1] < camY + ((tileHeight * scale) * mapHeight)): layers[currentLayer][(y * mapWidth) + x] = hand elif leftClick and sDownStart: for x in range(startPos[0], int(round((mousePos[0] - camX) / (tileWidth * scale))) + 1): for y in range(startPos[1], int(round((mousePos[1] - camY) / (tileHeight * scale))) + 1): if(mousePos[0] > camX and mousePos[0] < camX + ((tileWidth * scale) * mapWidth) and mousePos[1] > camY and mousePos[1] < camY + ((tileHeight * scale) * mapHeight)): layers[0][(y * mapWidth) + x] = hand for x in range(startPos[0], int(round((mousePos[0] - camX) / (tileWidth * scale))) - 1, -1): for y in range(startPos[1], int(round((mousePos[1] - camY) / (tileHeight * scale))) - 1, -1): if(mousePos[0] > camX and mousePos[0] < camX + ((tileWidth * scale) * mapWidth) and mousePos[1] > camY and mousePos[1] < camY + ((tileHeight * scale) * mapHeight)): layers[0][(y * mapWidth) + x] = hand for x in range(startPos[0], int(round((mousePos[0] - camX) / (tileWidth * scale))) + 1): for y in range(startPos[1], int(round((mousePos[1] - camY) / (tileHeight * scale))) - 1, -1): if(mousePos[0] > camX and mousePos[0] < camX + ((tileWidth * scale) * mapWidth) and mousePos[1] > camY and mousePos[1] < camY + ((tileHeight * scale) * mapHeight)): layers[0][(y * mapWidth) + x] = hand for x in range(startPos[0], int(round((mousePos[0] - camX) / (tileWidth * scale))) - 1, -1): for y in range(startPos[1], int(round((mousePos[1] - camY) / (tileHeight * scale))) + 1): if(mousePos[0] > camX and mousePos[0] < camX + ((tileWidth * scale) * mapWidth) and mousePos[1] > camY and mousePos[1] < camY + ((tileHeight * scale) * mapHeight)): layers[0][(y * mapWidth) + x] = hand if not rightClick and rightClickPrev and sDownStart: sDownStart = False for x in range(startPos[0], int(round((mousePos[0] - camX) / (tileWidth * scale))) + 1): for y in range(startPos[1], int(round((mousePos[1] - camY) / (tileHeight * scale))) + 1): if(mousePos[0] > camX and mousePos[0] < camX + ((tileWidth * scale) * mapWidth) and mousePos[1] > camY and mousePos[1] < camY + ((tileHeight * scale) * mapHeight)): layers[currentLayer][(y * mapWidth) + x] = -1 for x in range(startPos[0], int(round((mousePos[0] - camX) / (tileWidth * scale))) - 1, -1): for y in range(startPos[1], int(round((mousePos[1] - camY) / (tileHeight * scale))) - 1, -1): if(mousePos[0] > camX and mousePos[0] < camX + ((tileWidth * scale) * mapWidth) and mousePos[1] > camY and mousePos[1] < camY + ((tileHeight * scale) * mapHeight)): layers[currentLayer][(y * mapWidth) + x] = -1 for x in range(startPos[0], int(round((mousePos[0] - camX) / (tileWidth * scale))) + 1): for y in range(startPos[1], int(round((mousePos[1] - camY) / (tileHeight * scale))) - 1, -1): if(mousePos[0] > camX and mousePos[0] < camX + ((tileWidth * scale) * mapWidth) and mousePos[1] > camY and mousePos[1] < camY + ((tileHeight * scale) * mapHeight)): layers[currentLayer][(y * mapWidth) + x] = -1 for x in range(startPos[0], int(round((mousePos[0] - camX) / (tileWidth * scale))) - 1, -1): for y in range(startPos[1], int(round((mousePos[1] - camY) / (tileHeight * scale))) + 1): if(mousePos[0] > camX and mousePos[0] < camX + ((tileWidth * scale) * mapWidth) and mousePos[1] > camY and mousePos[1] < camY + ((tileHeight * scale) * mapHeight)): layers[currentLayer][(y * mapWidth) + x] = -1 elif rightClick and sDownStart: for x in range(startPos[0], int(round((mousePos[0] - camX) / (tileWidth * scale))) + 1): for y in range(startPos[1], int(round((mousePos[1] - camY) / (tileHeight * scale))) + 1): if(mousePos[0] > camX and mousePos[0] < camX + ((tileWidth * scale) * mapWidth) and mousePos[1] > camY and mousePos[1] < camY + ((tileHeight * scale) * mapHeight)): layers[0][(y * mapWidth) + x] = -2 for x in range(startPos[0], int(round((mousePos[0] - camX) / (tileWidth * scale))) - 1, -1): for y in range(startPos[1], int(round((mousePos[1] - camY) / (tileHeight * scale))) - 1, -1): if(mousePos[0] > camX and mousePos[0] < camX + ((tileWidth * scale) * mapWidth) and mousePos[1] > camY and mousePos[1] < camY + ((tileHeight * scale) * mapHeight)): layers[0][(y * mapWidth) + x] = -2 for x in range(startPos[0], int(round((mousePos[0] - camX) / (tileWidth * scale))) + 1): for y in range(startPos[1], int(round((mousePos[1] - camY) / (tileHeight * scale))) - 1, -1): if(mousePos[0] > camX and mousePos[0] < camX + ((tileWidth * scale) * mapWidth) and mousePos[1] > camY and mousePos[1] < camY + ((tileHeight * scale) * mapHeight)): layers[0][(y * mapWidth) + x] = -2 for x in range(startPos[0], int(round((mousePos[0] - camX) / (tileWidth * scale))) - 1, -1): for y in range(startPos[1], int(round((mousePos[1] - camY) / (tileHeight * scale))) + 1): if(mousePos[0] > camX and mousePos[0] < camX + ((tileWidth * scale) * mapWidth) and mousePos[1] > camY and mousePos[1] < camY + ((tileHeight * scale) * mapHeight)): layers[0][(y * mapWidth) + x] = -2 if leftClick and not leftClickPrev or rightClick and not rightClickPrev: if sDown: sDownStart = True startPos = (int(round((mousePos[0] - camX) / (tileWidth * scale))), int(round((mousePos[1] - camY) / (tileHeight * scale)))) if prevLayers != layers: prevLayerLists.append(deepcopy(prevLayers)) leftClickPrev = leftClick backDown = False rightClickDown = False brushRect.x,brushRect.y = (sheetWidth + 18) * uiScale, 43 * uiScale if brushRect.collidepoint(mousePos[0], mousePos[1]) or not squareT: if leftClick and brushRect.collidepoint(mousePos[0], mousePos[1]): squareT = False sDown = False s.blit(p.transform.scale(brushHover, (brushRect.width, brushRect.height)), (brushRect.x, brushRect.y + uiScale)) else: s.blit(p.transform.scale(brushHover, (brushRect.width, brushRect.height)), brushRect) else: s.blit(p.transform.scale(brush, (brushRect.width, brushRect.height)), brushRect) squareRect.x,squareRect.y = (sheetWidth + 34) * uiScale, 43 * uiScale if squareRect.collidepoint(mousePos[0], mousePos[1]) or squareT: if leftClick and squareRect.collidepoint(mousePos[0], mousePos[1]): squareT = True s.blit(p.transform.scale(squareHover, (squareRect.width, squareRect.height)), (squareRect.x, squareRect.y + uiScale)) else: s.blit(p.transform.scale(squareHover, (squareRect.width, squareRect.height)), squareRect) else: s.blit(p.transform.scale(square, (squareRect.width, squareRect.height)), squareRect) if squareT: sDown = True rightClickPrev = rightClick p.display.update() clock.tick(60)
[ 11748, 12972, 6057, 355, 279, 198, 6738, 10688, 1330, 4314, 198, 6738, 4866, 1330, 2769, 30073, 198, 11748, 309, 74, 3849, 11, 256, 74, 8979, 44204, 198, 15763, 796, 309, 74, 3849, 13, 51, 74, 3419, 198, 15763, 13, 4480, 19334, 3419, ...
2.13498
8,542
import tkinter as tk from tkinter.colorchooser import askcolor from tkinter import ttk from Scrollable import Scrollable from ViewLedgerWidget import ViewLedgerWidget from List import ListView from Group import Group # window for editing a group prevLens = [ 10, 25, 100 ]
[ 11748, 256, 74, 3849, 355, 256, 74, 198, 6738, 256, 74, 3849, 13, 8043, 6679, 13416, 1330, 1265, 8043, 198, 6738, 256, 74, 3849, 1330, 256, 30488, 198, 6738, 17428, 540, 1330, 17428, 540, 198, 6738, 3582, 42416, 1362, 38300, 1330, 358...
3.605263
76
crabs = sorted(map(int, open("input.txt", "r").readline().strip().split(","))) # position with minimal fuel usage is at the median position median_pos = crabs[len(crabs) // 2] min_fuel = sum([abs(crab_pos - median_pos) for crab_pos in crabs]) print(min_fuel)
[ 6098, 8937, 796, 23243, 7, 8899, 7, 600, 11, 1280, 7203, 15414, 13, 14116, 1600, 366, 81, 11074, 961, 1370, 22446, 36311, 22446, 35312, 7, 2430, 22305, 198, 198, 2, 2292, 351, 10926, 5252, 8748, 318, 379, 262, 14288, 2292, 198, 1150, ...
2.9
90
# Author: Matej Mik from ..component import Component from ..da import DAI import re
[ 2, 6434, 25, 24787, 73, 17722, 198, 198, 6738, 11485, 42895, 1330, 35100, 198, 6738, 11485, 6814, 1330, 17051, 40, 198, 11748, 302, 198 ]
3.583333
24
from SSstache import * from plumbum.path.utils import delete from plumbum.cmd import ls, touch, mkdir #prepareHTMLdir(dirName='xyz') #test_makeHTMLdir()
[ 6738, 6723, 301, 4891, 1330, 1635, 198, 6738, 458, 2178, 388, 13, 6978, 13, 26791, 1330, 12233, 198, 6738, 458, 2178, 388, 13, 28758, 1330, 43979, 11, 3638, 11, 33480, 15908, 628, 198, 220, 220, 220, 220, 198, 220, 220, 220, 220, 19...
2.311688
77
import matplotlib.pyplot as plt x = [1, 2, 5] y = [2, 3, 7] plt.title("1 grafico com python") # Eixos plt.xlabel("Eixo X") plt.ylabel("Eixo Y") plt.plot(x,y) plt.show()
[ 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 198, 87, 796, 685, 16, 11, 362, 11, 642, 60, 198, 88, 796, 685, 17, 11, 513, 11, 767, 60, 198, 198, 489, 83, 13, 7839, 7203, 16, 7933, 69, 3713, 401, 21015, 4943, 1...
1.860215
93
import cv2 import numpy import glob import os images = [] path = os.getcwd()+"\\frames\\" myVideo = cv2.VideoWriter("quicksort-1.mkv", cv2.VideoWriter_fourcc(*"DIVX"), 60, (1920,1080)) for filename in range(len(os.listdir(path))): filename = f"frame-{filename}.png" img = cv2.imread(f"{path}{filename}") height, width, layers = img.shape myVideo.write(img) myVideo.release()
[ 11748, 269, 85, 17, 201, 198, 11748, 299, 32152, 201, 198, 11748, 15095, 201, 198, 11748, 28686, 201, 198, 201, 198, 201, 198, 17566, 796, 17635, 201, 198, 6978, 796, 28686, 13, 1136, 66, 16993, 3419, 10, 1, 6852, 37805, 6852, 1, 20...
2.251337
187
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import numpy as np from model.layers import * from model.build import * import cv2 from model.utils import * model = Darknet("cfg/yolov3.cfg") model.load_weights("yolov3.weights") inp = get_test_input() pred = model(inp, torch.cuda.is_available())
[ 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 198, 6738, 28034, 13, 2306, 519, 6335, 1330, 35748, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 2746, 13, 75, 6962, 1330, ...
2.958333
120
from icemac.addressbook.browser.search.result.handler.manager import ( SearchResultHandler) def makeSRHandler(viewName): """Create a `SearchResultHandler` with the specified `viewName`.""" handler = SearchResultHandler(None, None, None, None) handler.viewName = viewName return handler def test_manager__SearchResultHandler____eq____1(): """It is equal when `viewName` is equal.""" assert makeSRHandler('@@asdf.html') == makeSRHandler('@@asdf.html') def test_manager__SearchResultHandler____eq____2(): """It is not equal with unequal `viewName`.""" # There is no __neq__ implemented! assert not(makeSRHandler('@@foo.html') == makeSRHandler('@@bar.html')) def test_manager__SearchResultHandler____eq____3(): """It is not equal to anything else.""" # There is no __neq__ implemented! assert not(makeSRHandler(None) == object()) def test_manager__SearchResultHandler____hash____1(): """It is hashable. It is only needed for Python 3 where classes having an __eq__ method do not have a __hash__ method. """ assert hash(makeSRHandler(None)) is not None
[ 6738, 14158, 368, 330, 13, 21975, 2070, 13, 40259, 13, 12947, 13, 20274, 13, 30281, 13, 37153, 1330, 357, 198, 220, 220, 220, 11140, 23004, 25060, 8, 628, 198, 4299, 787, 12562, 25060, 7, 1177, 5376, 2599, 198, 220, 220, 220, 37227, ...
3.124309
362
import json import pymysql import random import string import time # def get_data(): # with open('E:\\QQ\\1420944066\\FileRecv\\Code (2)\\data\\nice looking data\\gooddata\\20_30(1).json', 'r') as f: # camera_text = json.load(f) # # print(camera_text) # return camera_text # def data_insert(text): # db = pymysql.connect(host = "localhost",user = "root",password = "lxyroot",database = "superset-test") # cur = db.cursor() # try: # cur.execute("drop table liutu_data") # cur.execute("create table liutu_data(id int,name char(20),fillcolor char(20),time char(20),size_data TINYTEXT)") # except: # cur.execute("create table liutu_data(id int,name char(20),fillcolor char(20),time char(20),size_data TINYTEXT)") # for i in text: # for j in range(0,len(text[0]['size'])): # sql="INSERT INTO liutu_data (id,name,fillcolor,time,size_data) VALUES ('"+str(i['id'])+"','"+i['name']+"','"+i['fillcolor']+"','"+str(j)+"','"+str(i['size'][j])+"');" # cur.execute(sql) # db.commit() # cur.close() if __name__ == "__main__": cur,db = new_table() i = 0 while 1==1: time.sleep(5) print('one update') data_update(cur,20,db) i = i+1
[ 11748, 33918, 198, 11748, 279, 4948, 893, 13976, 198, 11748, 4738, 198, 11748, 4731, 198, 11748, 640, 198, 198, 2, 825, 651, 62, 7890, 33529, 198, 2, 220, 220, 220, 220, 351, 1280, 10786, 36, 25, 6852, 48, 48, 6852, 1415, 1238, 5824...
2.110927
604
import os import random import cv2 import numpy as np import torch from Experiments.all import load_models, embedd_data, save_batch from GenerativeModels.utils.data_utils import get_dataset device = torch.device("cuda") def sample_latent_neighbors(outputs_dir, models_dir): """Find nearest latent neighbors of data samples and create sets of original/reconstructed similar images """ # Load models n = 32 train_dataset = get_dataset('ffhq', split='train', resize=128, val_percent=0.15) encoder, generator = load_models(device, models_dir) embeddings = embedd_data(train_dataset, encoder, 32, device) for i in [11, 15, 16, 25, 48, 53, 60, 67, 68, 78, 122]: os.makedirs(os.path.join(outputs_dir, os.path.basename(models_dir), f"data_neighbors{i}"), exist_ok=True) dists = torch.norm(embeddings - embeddings[i], dim=1) neighbor_indices = torch.argsort(dists)[:n] neighbors = torch.from_numpy(np.array([train_dataset[x][1] for x in neighbor_indices])) save_batch(neighbors, os.path.join(outputs_dir, os.path.basename(models_dir), f"data_neighbors{i}")) if __name__ == '__main__': # sample_latent_neighbors("latent_neighbors_sets", 'trained_models/VGG-None_PT') # sample_latent_neighbors("latent_neighbors_sets", 'trained_models/VGG-random') make_shift_sets('/home/ariel/university/PerceptualLoss/PerceptualLossExperiments/style_transfer/imgs/textures') # create_shifted_colorfull_box_images()
[ 11748, 28686, 198, 11748, 4738, 198, 198, 11748, 269, 85, 17, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 198, 198, 6738, 8170, 6800, 13, 439, 1330, 3440, 62, 27530, 11, 11525, 67, 62, 7890, 11, 3613, 62, 43501, 198, 6738, ...
2.571924
577
def decode(to_be_decoded): """ Decodes a run-length encoded string. :param to_be_decoded: run-length encoded string :return: run-length decoded string """ to_be_decoded_list = list(to_be_decoded) decoded_str_as_list = list() num_to_print_as_list = list() for c in to_be_decoded_list: if c.isdigit(): num_to_print_as_list.append(c) else: if len(num_to_print_as_list) > 0: num_to_print = int(''.join(num_to_print_as_list)) append = c * num_to_print decoded_str_as_list.append(append) num_to_print_as_list = list() else: decoded_str_as_list.append(c) return ''.join(decoded_str_as_list) def encode(to_be_encoded): """ Run-length encodes a string :param to_be_encoded: string to be run-length encoded :return: run-length encoded string """ last_seen = None last_seen_count = 0 to_be_encoded_as_list = list(to_be_encoded) encoded_str_as_list = list() for c in to_be_encoded_as_list: if last_seen: if last_seen == c: last_seen_count += 1 else: if last_seen_count > 1: encoded_str_as_list.append('{}{}'.format(last_seen_count, last_seen)) else: encoded_str_as_list.append('{}'.format(last_seen)) last_seen_count = 1 else: last_seen_count += 1 last_seen = c if last_seen_count > 1: encoded_str_as_list.append('{}{}'.format(last_seen_count, last_seen)) else: if last_seen: encoded_str_as_list.append('{}'.format(last_seen)) else: encoded_str_as_list = list() return ''.join(encoded_str_as_list)
[ 4299, 36899, 7, 1462, 62, 1350, 62, 12501, 9043, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 4280, 4147, 257, 1057, 12, 13664, 30240, 4731, 13, 628, 220, 220, 220, 1058, 17143, 284, 62, 1350, 62, 12501, 9043, 25, 1057, 12, ...
1.940615
943
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import operator_benchmark as op_bench import torch import torch.nn as nn """ Microbenchmarks for Conv1d and ConvTranspose1d operators. """ # Configs for conv-1d ops conv_1d_configs = op_bench.config_list( attrs=[ [16, 33, 3, 1, 1, 64], [16, 33, 3, 2, 16, 128], ], attr_names=[ "in_c", "out_c", "kernel", "stride", "N", "L" ], tags=["short"] ) op_bench.generate_pt_test(conv_1d_configs, Conv1dBenchmark) op_bench.generate_pt_test(conv_1d_configs, ConvTranspose1dBenchmark) """ Microbenchmarks for Conv2d and ConvTranspose2d operators. """ # Configs for Conv2d and ConvTranspose1d conv_2d_configs = op_bench.config_list( attrs=[ [16, 33, 3, 1, 1, 32, 32], [16, 33, 3, 2, 16, 64, 64], ], attr_names=[ "in_c", "out_c", "kernel", "stride", "N", "H", "W" ], tags=["short"] ) op_bench.generate_pt_test(conv_2d_configs, Conv2dBenchmark) op_bench.generate_pt_test(conv_2d_configs, ConvTranspose2dBenchmark) """ Microbenchmarks for Conv3d and ConvTranspose3d operators. """ # Configs for Conv3d and ConvTranspose3d conv_3d_configs = op_bench.config_list( attrs=[ [16, 33, 3, 1, 8, 4, 32, 32], [16, 33, 3, 2, 16, 8, 64, 64], ], attr_names=[ "in_c", "out_c", "kernel", "stride", "N", "D", "H", "W" ], tags=["short"] ) op_bench.generate_pt_test(conv_3d_configs, Conv3dBenchmark) op_bench.generate_pt_test(conv_3d_configs, ConvTranspose3dBenchmark) if __name__ == "__main__": op_bench.benchmark_runner.main()
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 6738, 11593, 37443, 834, 1330, 7297, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 628, 198, 11748, 10088, 62, 2...
2.249012
759
import requests as R
[ 11748, 7007, 355, 371, 628 ]
4.4
5
#from distutils.core import setup #from distutils.extension import Extension #from Cython.Distutils import build_ext #import numpy #setup( #cmdclass = {'build_ext': build_ext}, #ext_modules = [Extension("Z_shooting", ["Z_shooting.c"],)], #include_dirs=[numpy.get_include(),'.', ], #) from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext from Cython.Build import cythonize import numpy #extension = [Extension("Z_shooting", ["Z_shooting.c"],),] setup( cmdclass = {'build_ext': build_ext}, ext_modules = [Extension("FastFused_01", ["FastFused_01.pyx"], include_dirs=[numpy.get_include()])] ) #setup( #cmdclass = {'build_ext': build_ext}, #ext_modules = cythonize("FastFused_01.pyx"), #include_dirs=[numpy.get_include(),'.', ], #)
[ 2, 6738, 1233, 26791, 13, 7295, 1330, 9058, 201, 198, 2, 6738, 1233, 26791, 13, 2302, 3004, 1330, 27995, 201, 198, 2, 6738, 327, 7535, 13, 20344, 26791, 1330, 1382, 62, 2302, 201, 198, 2, 11748, 299, 32152, 201, 198, 201, 198, 2, ...
2.476879
346
import numpy as np import pandas as pd import os from sklearn.preprocessing import MinMaxScaler from data_processing.helpers import Config
[ 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 28686, 198, 6738, 1341, 35720, 13, 3866, 36948, 1330, 1855, 11518, 3351, 36213, 198, 6738, 1366, 62, 36948, 13, 16794, 364, 1330, 17056, 198 ]
3.657895
38
import math speedofLight = 2.9979*pow(10,8) timeIntervalBlinks()
[ 11748, 10688, 198, 12287, 1659, 15047, 796, 362, 13, 2079, 3720, 9, 79, 322, 7, 940, 11, 23, 8, 628, 220, 220, 220, 220, 198, 2435, 9492, 2100, 33, 28751, 3419, 198 ]
2.21875
32
import json from upload.common.upload_area import UploadArea # This lambda function is invoked by messages in the the area_deletion_queue (AWS SQS). # The queue and the lambda function are connected via aws_lambda_event_source_mapping
[ 11748, 33918, 198, 6738, 9516, 13, 11321, 13, 25850, 62, 20337, 1330, 36803, 30547, 628, 198, 2, 770, 37456, 2163, 318, 24399, 416, 6218, 287, 262, 262, 1989, 62, 2934, 1616, 295, 62, 36560, 357, 12298, 50, 49747, 50, 737, 198, 2, 3...
3.761905
63
from ..overlap_detection_2d import detect_overlap_2d from unittest.mock import call, Mock, patch import unittest
[ 6738, 11485, 2502, 37796, 62, 15255, 3213, 62, 17, 67, 1330, 4886, 62, 2502, 37796, 62, 17, 67, 198, 6738, 555, 715, 395, 13, 76, 735, 1330, 869, 11, 44123, 11, 8529, 198, 11748, 555, 715, 395, 628 ]
3
38
teste = list() teste.append('Matheus') teste.append(17) galera = [teste[:]] # Cria uma copia de teste dentro de galera teste[0] = 'Oliver' teste[1] = 22 galera.append(teste) # Cria um vnculo entre teste e galera print(galera) pessoas = [['Harvey', 23], ['Madeleine', 19], ['Roger', 250], ['Mark', 20]] print(pessoas[0][0]) # Mostra o primeiro valor da primeira lista desta lista for p in pessoas: print(f'{p[0]} tem {p[1]} anos de idade.') dados = [] pes = [] for i in range(0, 3): print('-='*10) dados.append(input('Nome: ')) dados.append(int(input('Idade: '))) pes.append(dados[:]) dados.clear() # Exclu os valores dentro de dados for p in pes: print(f'{p[0]} maior de idade.' if p[1] > 20 else f'{p[0]} menor de idade.') # Exerccio 84 -89
[ 9288, 68, 796, 1351, 3419, 198, 198, 9288, 68, 13, 33295, 10786, 19044, 258, 385, 11537, 198, 9288, 68, 13, 33295, 7, 1558, 8, 198, 13528, 8607, 796, 685, 9288, 68, 58, 25, 11907, 220, 1303, 327, 7496, 334, 2611, 2243, 544, 390, 1...
2.187675
357
# -*- coding: utf-8 -*- """Bio2BEL custom errors."""
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 42787, 17, 33, 3698, 2183, 8563, 526, 15931, 628, 628, 628 ]
2.185185
27
# -*- coding: utf8 -*- # Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # FAILEDOPERATION = 'FailedOperation' # FAILEDOPERATION_DBQUERYFAILED = 'FailedOperation.DbQueryFailed' # FAILEDOPERATION_DBRECORDCREATEFAILED = 'FailedOperation.DbRecordCreateFailed' # FAILEDOPERATION_DBRECORDUPDATEFAILED = 'FailedOperation.DbRecordUpdateFailed' # ES FAILEDOPERATION_ESQUERYERROR = 'FailedOperation.ESQueryError' # FAILEDOPERATION_NOVALIDNODES = 'FailedOperation.NoValidNodes' # FAILEDOPERATION_ORDEROUTOFCREDIT = 'FailedOperation.OrderOutOfCredit' # FAILEDOPERATION_RESOURCENOTFOUND = 'FailedOperation.ResourceNotFound' # FAILEDOPERATION_TASKNOTRUNNING = 'FailedOperation.TaskNotRunning' # FAILEDOPERATION_TASKNOTSUSPENDED = 'FailedOperation.TaskNotSuspended' # FAILEDOPERATION_TASKOPERATIONNOTALLOW = 'FailedOperation.TaskOperationNotAllow' # FAILEDOPERATION_TASKTYPENOTSAME = 'FailedOperation.TaskTypeNotSame' # FAILEDOPERATION_TRIALTASKEXCEED = 'FailedOperation.TrialTaskExceed' # INTERNALERROR = 'InternalError' # INVALIDPARAMETER = 'InvalidParameter' # INVALIDPARAMETERVALUE = 'InvalidParameterValue' # MISSINGPARAMETER = 'MissingParameter' # RESOURCENOTFOUND = 'ResourceNotFound' # UNKNOWNPARAMETER = 'UnknownParameter'
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 23, 532, 9, 12, 198, 2, 15069, 357, 66, 8, 2177, 12, 1238, 2481, 2320, 43, 317, 1959, 15302, 11, 257, 9368, 1087, 1664, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 137...
2.834621
647
from django.contrib.auth import get_user_model from django.test import TestCase from django.contrib.staticfiles import finders from django.urls import reverse from .models import StudentProfileInfo, User from .forms import UserForm, ContactForm, UserProfileInfoForm
[ 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 1330, 651, 62, 7220, 62, 19849, 198, 6738, 42625, 14208, 13, 9288, 1330, 6208, 20448, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 12708, 16624, 1330, 1064, 364, 198, 6738, 42625, 14208, 13, ...
3.61039
77
# # Module to support the pickling of different types of connection # objects and file objects so that they can be transferred between # different processes. # # processing/reduction.py # # Copyright (c) 2006-2008, R Oudkerk --- see COPYING.txt # __all__ = [] import os import sys import socket import threading import copy_reg import processing from processing import _processing from processing.logger import debug, subDebug, subWarning from processing.forking import thisThreadIsSpawning from processing.process import _registerAfterFork # # # connections_are_picklable = ( sys.platform == 'win32' or hasattr(_processing, 'recvFd') ) try: fromfd = socket.fromfd except AttributeError: # # Platform specific definitions # if sys.platform == 'win32': import _subprocess from processing._processing import win32 closeHandle = win32.CloseHandle else: closeHandle = os.close duplicateHandle = os.dup # # Support for a per-process server thread which caches pickled handles # _cache = set() _reset(None) _registerAfterFork(_reset, _reset) # # Functions to be used for pickling/unpickling objects with handles # # # Register `_processing.Connection` with `copy_reg` # copy_reg.pickle(_processing.Connection, reduceConnection) # # Register `socket.socket` with `copy_reg` # copy_reg.pickle(socket.socket, reduceSocket) # # Register `_processing.PipeConnection` with `copy_reg` # if sys.platform == 'win32': copy_reg.pickle(_processing.PipeConnection, reducePipeConnection)
[ 2, 201, 198, 2, 19937, 284, 1104, 262, 2298, 1359, 286, 1180, 3858, 286, 4637, 201, 198, 2, 5563, 290, 2393, 5563, 523, 326, 484, 460, 307, 11172, 1022, 201, 198, 2, 1180, 7767, 13, 201, 198, 2, 201, 198, 2, 7587, 14, 445, 8110,...
2.823427
572
""" Print elements of a linked list in reverse order as standard output head could be None as well for empty list Node is defined as class Node(object): def __init__(self, data=None, next_node=None): self.data = data self.next = next_node """
[ 37811, 198, 12578, 4847, 286, 257, 6692, 1351, 287, 9575, 1502, 355, 3210, 5072, 198, 1182, 714, 307, 6045, 355, 880, 329, 6565, 1351, 198, 19081, 318, 5447, 355, 198, 220, 198, 1398, 19081, 7, 15252, 2599, 198, 220, 198, 220, 220, ...
2.504132
121
# MIT License # # Copyright (c) 2020 Aleksandr Zhuravlyov and Zakhar Lanets # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import sys import os import numpy as np import json import pandas as pd import copy import matplotlib.pyplot as plt import time as tm from matplotlib import rc current_path = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.join(current_path, '../../')) from netgrid import save_files_collection_to_file from matplotlib.ticker import FormatStrFormatter from vofpnm.cfd.ini_class import Ini from vofpnm.cfd.cfd_class import Cfd from vofpnm.helpers import plot_rel_perms, plot_conesrvation_check, plot_viscs_vels, plot_av_sat, \ plot_capillary_pressure_curve, plot_capillary_pressures # rc('text', usetex=True) # plt.rcParams["font.family"] = "Times New Roman" start_time = tm.time() ini = Ini(config_file=sys.argv[1]) cfd = Cfd(ini) visc_0 = ini.paramsPnm['visc_0'] visc_1 = ini.paramsPnm['visc_1'] ini.throats_viscs = np.tile(visc_0, ini.netgrid.throats_N) cfd.run_pnm() throats_volumes = cfd.ini.throats_volumes # ### validation with openFoam ### test_case_vofpnm = dict() times_alpha_avs = dict() times_u_mgn_avs = dict() times_F_avs = dict() times_F_avs_new = dict() times_V_in = dict() thrs_velocities_to_output = dict() thrs_alphas_to_output = dict() nus = {'1': visc_0, '2': visc_1} rhos = {'1': ini.paramsPnm['b_dens_fluid1'], '2': ini.paramsPnm['b_dens_fluid1']} test_case_vofpnm['mus'] = nus test_case_vofpnm['rhos'] = rhos test_case_vofpnm['sigma'] = ini.ift # ### validation with openfoam one-phase ### throats_vels = np.absolute(np.array(list(cfd.ini.throats_velocities.values()))) u_mgn_av = np.sum((throats_volumes * throats_vels)) / np.sum(throats_volumes) test_case_vofpnm['ref_u_mgn'] = u_mgn_av print('ref_u_mgn', u_mgn_av) throats_widths = np.absolute(np.array(list(cfd.ini.throats_widths.values()))) av_width = np.sum((throats_volumes * throats_widths)) / np.sum(throats_volumes) test_case_vofpnm['width'] = av_width ini.flow_0_ref = cfd.calc_rel_flow_rate() print('flow_0_ref', ini.flow_0_ref) visc_1 = ini.paramsPnm['visc_1'] ini.throats_viscs = np.tile(visc_1, ini.netgrid.throats_N) cfd.run_pnm() ini.flow_1_ref = cfd.calc_rel_flow_rate() cfd.calc_coupling_params() cfd.run_pnm() rel_perms_0 = [] rel_perms_1 = [] capillary_numbers = [] capillary_pressures = [] av_sats = [] throats_volumes = cfd.ini.throats_volumes throats_av_sats = cfd.ini.equation.throats_av_sats dens_0 = cfd.ini.paramsPnm['dens_0'] mass_already_in = copy.deepcopy(np.sum(throats_volumes * throats_av_sats * dens_0)) mass_rates_in = [] mass_rates_out = [] masses_inside = [] times = [] viscs = [] vol_rates_in = [] vol_rates_out = [] ################# # Paraview output ################# os.system('rm -r inOut/*.vtu') os.system('rm -r inOut/*.pvd') sats_dict = dict() file_name = 'inOut/collection.pvd' files_names = list() files_descriptions = list() cells_arrays = cfd.process_paraview_data() cfd.ini.netgrid.cells_arrays = cells_arrays files_names.append(str(0) + '.vtu') files_descriptions.append(str(0)) cfd.ini.netgrid.save_cells('inOut/' + files_names[-1]) save_files_collection_to_file(file_name, files_names, files_descriptions) ################# time = [0] time_steps = [] cour_number = np.empty([]) time_curr = 0 time_step_curr = 0 time_output_freq = cfd.ini.time_period / 500. round_output_time = int(ini.round_output_time) output_time_step = ini.output_time_step time_bound = output_time_step is_output_step = False is_last_step = False out_idx = int(0) while True: if cfd.ini.time_step_type == 'const': cfd.ini.time_step = cfd.ini.const_time_step elif cfd.ini.time_step_type == 'flow_variable': cfd.ini.time_step = cfd.ini.local.calc_flow_variable_time_step( cfd.ini.throats_velocities) elif cfd.ini.time_step_type == 'div_variable': cfd.ini.time_step = cfd.ini.local.calc_div_variable_time_step( cfd.ini.equation.sats[cfd.ini.equation.i_curr], cfd.ini.throats_velocities) time_step_curr = cfd.ini.time_step if time_curr + time_step_curr >= time_bound: time_step_curr = time_bound - time_curr time_bound += output_time_step is_output_step = True if time_curr + time_step_curr >= cfd.ini.time_period: is_last_step = True if not is_output_step: time_step_curr = cfd.ini.time_period - time_curr time_steps.append(time_step_curr) time_curr += time_step_curr cfd.ini.equation.cfd_procedure_one_step(cfd.ini.throats_velocities, time_step_curr) cfd.calc_coupling_params() mass_inside = copy.deepcopy(np.sum(throats_volumes * throats_av_sats * dens_0)) masses_inside.append(mass_inside) vol_rate_in, vol_rate_out, vol_rate_in_0, vol_rate_out_1 = cfd.calc_flow_rates(mass_rates_in, mass_rates_out) vol_rates_out.append(vol_rate_out_1) cfd.calc_rel_perms(rel_perms_0, rel_perms_1, capillary_numbers, capillary_pressures, av_sats, ini.flow_0_ref, ini.flow_1_ref, vol_rate_in_0) print('time_step: ', round(time_step_curr, round_output_time)) time.append(time_curr) cfd.ini.equation.print_cour_numbers(cfd.ini.throats_velocities, cfd.ini.time_step) print(' percentage executed:', round((time_curr / cfd.ini.time_period * 100.), 2), '%.', '\n') cfd.run_pnm() cells_arrays = cfd.process_paraview_data() if is_output_step: cfd.ini.netgrid.cells_arrays = cells_arrays files_names.append(str(round(time_curr, round_output_time)) + '.vtu') files_descriptions.append(str(round(time_curr, round_output_time))) cfd.ini.netgrid.save_cells('inOut/' + files_names[-1]) save_files_collection_to_file(file_name, files_names, files_descriptions) out_idx += 1 is_output_step = False ####### validation with openfoam ####### throats_vels = np.absolute(np.array(list(cfd.ini.throats_velocities.values()))) u_mgn_av = np.sum(throats_volumes * throats_vels) / np.sum(throats_volumes) alpha_av = np.sum(throats_volumes * throats_av_sats) / np.sum(throats_volumes) F_av = np.sum(throats_volumes * throats_vels * throats_av_sats) / np.sum( throats_volumes * throats_vels) times_u_mgn_avs[str(round(time_curr, round_output_time))] = u_mgn_av times_alpha_avs[str(round(time_curr, round_output_time))] = alpha_av times_F_avs[str(round(time_curr, round_output_time))] = F_av times_F_avs_new[str(round(time_curr, round_output_time))] = ( vol_rate_out - vol_rate_out_1) / vol_rate_out times_V_in[str(round(time_curr, round_output_time))] = vol_rate_in ####### validation with openfoam ####### print(str(round(time_curr, round_output_time)), time_curr) throats_vels = np.absolute(np.array(list(cfd.ini.throats_velocities.values()))) throats_viscs = cfd.ini.throats_viscs visc = np.sum(cfd.ini.throats_volumes * throats_viscs) / np.sum(cfd.ini.throats_volumes) times.append(time_curr) viscs.append(visc) vol_rates_in.append(vol_rate_in) if is_last_step: break execution_time = tm.time() - start_time print("--- %s seconds ---" % execution_time) ############# # Rel perms validation output ############# test_case_vofpnm['times_alpha_avs'] = times_alpha_avs test_case_vofpnm['times_u_mgn_avs'] = times_u_mgn_avs test_case_vofpnm['times_F_avs'] = times_F_avs test_case_vofpnm['times_F_avs_new'] = times_F_avs_new test_case_vofpnm['execution_time'] = execution_time test_case_vofpnm['time_step'] = cfd.ini.output_time_step test_case_vofpnm['grid_volume'] = cfd.ini.grid_volume test_case_vofpnm['total_volume'] = np.sum(throats_volumes) test_case_vofpnm['times_V_in'] = times_V_in json_file_u_mgns = 'inOut/validation/tmp.json' with open(json_file_u_mgns, 'w') as f: json.dump(test_case_vofpnm, f, sort_keys=False, indent=4 * ' ', ensure_ascii=False)
[ 2, 17168, 13789, 198, 2, 198, 2, 15069, 357, 66, 8, 12131, 9300, 591, 46273, 10511, 333, 615, 306, 709, 290, 32605, 9869, 14730, 1039, 198, 2, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 2...
2.303676
3,945
import struct ascii_glyphs = [ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x18, 0x00, 0x6c, 0x6c, 0x6c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x36, 0x36, 0x7f, 0x36, 0x7f, 0x36, 0x36, 0x00, 0x0c, 0x3f, 0x68, 0x3e, 0x0b, 0x7e, 0x18, 0x00, 0x60, 0x66, 0x0c, 0x18, 0x30, 0x66, 0x06, 0x00, 0x38, 0x6c, 0x6c, 0x38, 0x6d, 0x66, 0x3b, 0x00, 0x0c, 0x18, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x18, 0x30, 0x30, 0x30, 0x18, 0x0c, 0x00, 0x30, 0x18, 0x0c, 0x0c, 0x0c, 0x18, 0x30, 0x00, 0x00, 0x18, 0x7e, 0x3c, 0x7e, 0x18, 0x00, 0x00, 0x00, 0x18, 0x18, 0x7e, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x30, 0x00, 0x00, 0x00, 0x7e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x06, 0x0c, 0x18, 0x30, 0x60, 0x00, 0x00, 0x3c, 0x66, 0x6e, 0x7e, 0x76, 0x66, 0x3c, 0x00, 0x18, 0x38, 0x18, 0x18, 0x18, 0x18, 0x7e, 0x00, 0x3c, 0x66, 0x06, 0x0c, 0x18, 0x30, 0x7e, 0x00, 0x3c, 0x66, 0x06, 0x1c, 0x06, 0x66, 0x3c, 0x00, 0x0c, 0x1c, 0x3c, 0x6c, 0x7e, 0x0c, 0x0c, 0x00, 0x7e, 0x60, 0x7c, 0x06, 0x06, 0x66, 0x3c, 0x00, 0x1c, 0x30, 0x60, 0x7c, 0x66, 0x66, 0x3c, 0x00, 0x7e, 0x06, 0x0c, 0x18, 0x30, 0x30, 0x30, 0x00, 0x3c, 0x66, 0x66, 0x3c, 0x66, 0x66, 0x3c, 0x00, 0x3c, 0x66, 0x66, 0x3e, 0x06, 0x0c, 0x38, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x18, 0x18, 0x30, 0x0c, 0x18, 0x30, 0x60, 0x30, 0x18, 0x0c, 0x00, 0x00, 0x00, 0x7e, 0x00, 0x7e, 0x00, 0x00, 0x00, 0x30, 0x18, 0x0c, 0x06, 0x0c, 0x18, 0x30, 0x00, 0x3c, 0x66, 0x0c, 0x18, 0x18, 0x00, 0x18, 0x00, 0x3c, 0x66, 0x6e, 0x6a, 0x6e, 0x60, 0x3c, 0x00, 0x3c, 0x66, 0x66, 0x7e, 0x66, 0x66, 0x66, 0x00, 0x7c, 0x66, 0x66, 0x7c, 0x66, 0x66, 0x7c, 0x00, 0x3c, 0x66, 0x60, 0x60, 0x60, 0x66, 0x3c, 0x00, 0x78, 0x6c, 0x66, 0x66, 0x66, 0x6c, 0x78, 0x00, 0x7e, 0x60, 0x60, 0x7c, 0x60, 0x60, 0x7e, 0x00, 0x7e, 0x60, 0x60, 0x7c, 0x60, 0x60, 0x60, 0x00, 0x3c, 0x66, 0x60, 0x6e, 0x66, 0x66, 0x3c, 0x00, 0x66, 0x66, 0x66, 0x7e, 0x66, 0x66, 0x66, 0x00, 0x7e, 0x18, 0x18, 0x18, 0x18, 0x18, 0x7e, 0x00, 0x3e, 0x0c, 0x0c, 0x0c, 0x0c, 0x6c, 0x38, 0x00, 0x66, 0x6c, 0x78, 0x70, 0x78, 0x6c, 0x66, 0x00, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x7e, 0x00, 0x63, 0x77, 0x7f, 0x6b, 0x6b, 0x63, 0x63, 0x00, 0x66, 0x66, 0x76, 0x7e, 0x6e, 0x66, 0x66, 0x00, 0x3c, 0x66, 0x66, 0x66, 0x66, 0x66, 0x3c, 0x00, 0x7c, 0x66, 0x66, 0x7c, 0x60, 0x60, 0x60, 0x00, 0x3c, 0x66, 0x66, 0x66, 0x6a, 0x6c, 0x36, 0x00, 0x7c, 0x66, 0x66, 0x7c, 0x6c, 0x66, 0x66, 0x00, 0x3c, 0x66, 0x60, 0x3c, 0x06, 0x66, 0x3c, 0x00, 0x7e, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x3c, 0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0x3c, 0x18, 0x00, 0x63, 0x63, 0x6b, 0x6b, 0x7f, 0x77, 0x63, 0x00, 0x66, 0x66, 0x3c, 0x18, 0x3c, 0x66, 0x66, 0x00, 0x66, 0x66, 0x66, 0x3c, 0x18, 0x18, 0x18, 0x00, 0x7e, 0x06, 0x0c, 0x18, 0x30, 0x60, 0x7e, 0x00, 0x7c, 0x60, 0x60, 0x60, 0x60, 0x60, 0x7c, 0x00, 0x00, 0x60, 0x30, 0x18, 0x0c, 0x06, 0x00, 0x00, 0x3e, 0x06, 0x06, 0x06, 0x06, 0x06, 0x3e, 0x00, 0x18, 0x3c, 0x66, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x1c, 0x36, 0x30, 0x7c, 0x30, 0x30, 0x7e, 0x00, 0x00, 0x00, 0x3c, 0x06, 0x3e, 0x66, 0x3e, 0x00, 0x60, 0x60, 0x7c, 0x66, 0x66, 0x66, 0x7c, 0x00, 0x00, 0x00, 0x3c, 0x66, 0x60, 0x66, 0x3c, 0x00, 0x06, 0x06, 0x3e, 0x66, 0x66, 0x66, 0x3e, 0x00, 0x00, 0x00, 0x3c, 0x66, 0x7e, 0x60, 0x3c, 0x00, 0x1c, 0x30, 0x30, 0x7c, 0x30, 0x30, 0x30, 0x00, 0x00, 0x00, 0x3e, 0x66, 0x66, 0x3e, 0x06, 0x3c, 0x60, 0x60, 0x7c, 0x66, 0x66, 0x66, 0x66, 0x00, 0x18, 0x00, 0x38, 0x18, 0x18, 0x18, 0x3c, 0x00, 0x18, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x70, 0x60, 0x60, 0x66, 0x6c, 0x78, 0x6c, 0x66, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3c, 0x00, 0x00, 0x00, 0x36, 0x7f, 0x6b, 0x6b, 0x63, 0x00, 0x00, 0x00, 0x7c, 0x66, 0x66, 0x66, 0x66, 0x00, 0x00, 0x00, 0x3c, 0x66, 0x66, 0x66, 0x3c, 0x00, 0x00, 0x00, 0x7c, 0x66, 0x66, 0x7c, 0x60, 0x60, 0x00, 0x00, 0x3e, 0x66, 0x66, 0x3e, 0x06, 0x07, 0x00, 0x00, 0x6c, 0x76, 0x60, 0x60, 0x60, 0x00, 0x00, 0x00, 0x3e, 0x60, 0x3c, 0x06, 0x7c, 0x00, 0x30, 0x30, 0x7c, 0x30, 0x30, 0x30, 0x1c, 0x00, 0x00, 0x00, 0x66, 0x66, 0x66, 0x66, 0x3e, 0x00, 0x00, 0x00, 0x66, 0x66, 0x66, 0x3c, 0x18, 0x00, 0x00, 0x00, 0x63, 0x6b, 0x6b, 0x7f, 0x36, 0x00, 0x00, 0x00, 0x66, 0x3c, 0x18, 0x3c, 0x66, 0x00, 0x00, 0x00, 0x66, 0x66, 0x66, 0x3e, 0x06, 0x3c, 0x00, 0x00, 0x7e, 0x0c, 0x18, 0x30, 0x7e, 0x00, 0x0c, 0x18, 0x18, 0x70, 0x18, 0x18, 0x0c, 0x00, 0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x00, 0x30, 0x18, 0x18, 0x0e, 0x18, 0x18, 0x30, 0x00, 0x31, 0x6b, 0x46, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, ] from gameduino.registers import * # BaseGameduino is the common base for the Gameduino objects in remote and sim
[ 11748, 2878, 198, 198, 292, 979, 72, 62, 10853, 746, 82, 796, 685, 198, 15, 87, 405, 11, 220, 657, 87, 405, 11, 220, 657, 87, 405, 11, 220, 657, 87, 405, 11, 220, 657, 87, 405, 11, 220, 657, 87, 405, 11, 220, 657, 87, 405, ...
1.339554
4,126
from .sdm import Sdm __red_end_user_data_statement__ = ( "This cog does not persistently store data or metadata about users." )
[ 6738, 764, 21282, 76, 1330, 311, 36020, 198, 198, 834, 445, 62, 437, 62, 7220, 62, 7890, 62, 26090, 834, 796, 357, 198, 220, 220, 220, 366, 1212, 43072, 857, 407, 21160, 1473, 3650, 1366, 393, 20150, 546, 2985, 526, 198, 8, 628 ]
3.116279
43
#!/usr/bin/python """ ************************************************* * @Project: Self Balance * @Description: GPIO Mapping * @Owner: Guilherme Chinellato * @Email: guilhermechinellato@gmail.com ************************************************* """ """ # #Arduino GPIO # 4x encoder (INT0-D2, INT1-D3, D4, D7) 4x motor enable (D5, D6, D11, D12) 2x PWM (D9, D10) 2x I2C (SCL-A5, SDA-A4) """ ''' Deprecated (replaced to Arduino) # #Motors GPIOs # #Motor A & B PWM outputs (BCM pinout) MA_PWM_GPIO = 19 MB_PWM_GPIO = 26 #Motor A & B enable outputs (BCM pinout) MA_CLOCKWISE_GPIO = 5 MA_ANTICLOCKWISE_GPIO = 6 MB_CLOCKWISE_GPIO = 20 MB_ANTICLOCKWISE_GPIO = 21 # #Encoders GPIOs # #Enconders 1 & 2 for each motor (BCM pinout) MA_ENCODER_1 = 12 MA_ENCODER_2 = 13 MB_ENCODER_1 = 7 MB_ENCODER_2 = 8 ''' # #PanTilt GPIOs # #MicroServo Vertical and Horizontal outputs (BCM pinout) SERVO_V_GPIO = 18 SERVO_H_GPIO = 23 '''Servo mapping for servoblaster: 0 on P1-7 GPIO-4 1 on P1-11 GPIO-17 *2 on P1-12 GPIO-18* 3 on P1-13 GPIO-27 4 on P1-15 GPIO-22 *5 on P1-16 GPIO-23* 6 on P1-18 GPIO-24 7 on P1-22 GPIO-25''' #Servo pins SERVO_H = '2' #pin 12 BCM 18 SERVO_V = '5' #pin 16 BCM 23
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 37811, 198, 17174, 8412, 9, 198, 9, 2488, 16775, 25, 12189, 22924, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, ...
1.976226
673
# Copyright (C) 2019 by geehalel@gmail.com # This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) import platform _WIN32 = (platform.system() == 'Windows') VK_USE_PLATFORM_WIN32_KHR = _WIN32 VK_USE_PLATFORM_ANDROID_KHR = False VK_USE_PLATFORM_WAYLAND_KHR = False _DIRECT2DISPLAY = False #VK_USE_PLATFORM_XCB_KHR = True VK_USE_PLATFORM_XCB_KHR = not VK_USE_PLATFORM_WIN32_KHR DEFAULT_FENCE_TIMEOUT = 100000000000
[ 2, 15069, 357, 34, 8, 13130, 416, 308, 1453, 14201, 417, 31, 14816, 13, 785, 198, 2, 770, 2438, 318, 11971, 739, 262, 17168, 5964, 357, 36393, 8, 357, 4023, 1378, 44813, 1668, 13, 2398, 14, 677, 4541, 14, 36393, 8, 198, 198, 11748...
2.480663
181