content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
from enum import Enum import random import collections import numpy as np # ####################################################################### # Data Types ####################################################################### # def __str__(self): return self._string class _Session0(_Session): class Session(Enum): S0 = _Session0() S1 = _Session('01', 1, 'S1') S2 = _Session('10', 2, 'S2') S3 = _Session('11', 3, 'S3') # noinspection PyInitNewSignature def power_on_value(self, interval, persistence, stored_value): return self.__session__.power_on_value( interval, persistence, stored_value) def __str__(self): return self.__session__.__str__() class TagEncoding(Enum): FM0 = ('00', 1, "FM0") M2 = ('01', 2, "M2") M4 = ('10', 4, "M4") M8 = ('11', 8, "M8") # noinspection PyInitNewSignature def __str__(self): return self._string # ####################################################################### # Default system-wide Reader Parameters ####################################################################### # stdParams = StdParams() # ####################################################################### # Tag Operations ####################################################################### # # ####################################################################### # API for encoding basic types ####################################################################### # # ####################################################################### # Commands ####################################################################### # # ####################################################################### # Tag replies ####################################################################### # def to_bytes(value): if isinstance(value, str): return list(bytearray.fromhex(value)) elif isinstance(value, collections.Iterable): value = list(value) for b in value: if not isinstance(b, int) or not (0 <= b < 256): raise ValueError("each array element must represent a byte") return value else: raise ValueError("value must be a hex string or bytes collections") class ReqRnReply(Reply): class ReadReply(Reply): # ####################################################################### # Preambles and frames ####################################################################### # class ReaderPreamble(ReaderSync): class TagPreamble: def get_duration(self, blf): return (self.bitlen * self.encoding.symbols_per_bit) / blf class FM0Preamble(TagPreamble): def __str__(self): return "{{({}){},{},trext({})}}".format( self.bitlen, "0..01010v1" if self.extended else "1010v1", self.encoding, 1 if self.extended else 0) class MillerPreamble(TagPreamble): def __str__(self): return "{{({}){},{},trext({})}}".format( self.bitlen, "DD..DD010111" if self.extended else "DDDD010111", self.encoding, 1 if self.extended else 0) def create_tag_preamble(encoding, extended=False): if encoding == TagEncoding.FM0: return FM0Preamble(extended) else: return MillerPreamble(m=encoding.symbols_per_bit, extended=extended) class ReaderFrame: def __init__(self, preamble, command): super().__init__() self.preamble = preamble self.command = command def __str__(self): return "Frame{{{o.preamble}{o.command}}}".format(o=self) class TagFrame: def __init__(self, preamble, reply): super().__init__() self.preamble = preamble self.reply = reply # FIXME: not vectorized # ####################################################################### # Reader and Tag frames helpers and accessors ####################################################################### # # noinspection PyTypeChecker # noinspection PyTypeChecker # noinspection PyTypeChecker # noinspection PyTypeChecker # noinspection PyTypeChecker # ####################################################################### # Link timings estimation ####################################################################### # # ####################################################################### # Slot duration estimation ####################################################################### # # ####################################################################### # Round duration estimation ####################################################################### # # ####################################################################### # Various helpers ####################################################################### # # noinspection PyTypeChecker
[ 6738, 33829, 1330, 2039, 388, 198, 11748, 4738, 198, 11748, 17268, 198, 11748, 299, 32152, 355, 45941, 628, 198, 2, 198, 29113, 29113, 4242, 21017, 198, 2, 6060, 24897, 198, 29113, 29113, 4242, 21017, 198, 2, 628, 198, 220, 220, 220, ...
3.381968
1,453
''' Given an n x n matrix where each of the rows and columns are sorted in ascending order, return the kth smallest element in the matrix. Note that it is the kth smallest element in the sorted order, not the kth distinct element. Input: matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8 Output: 13 Explanation: The elements in the matrix are [1,5,9,10,11,12,13,13,15], and the 8th smallest number is 13 Input: matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 2 Output: 10 Input: [[1,5,9],[10,11,13],[12,13,15]], k= 9 Output: 15 Input: [[2]], k= 1 Output: 2 Precondition: n >= 1 k <= n*n No int overflow C1: Single element C2: k = n^2 C3: k <= n C4: k > n Algo: Brute force: get elements and sort O(n^2logn^2) Heap: x = min(k, n) Runtime: klogx Space: O(x) if n >= k: compare the first column is enough if n < k for each row, we have a pointer, use a heap to record the pointer value, for k times, pop out the smaller pointer and update that pointer to its next value in its list Init a heap, the heap size should be min of k and n() '''
[ 7061, 6, 198, 15056, 281, 299, 2124, 299, 17593, 810, 1123, 286, 262, 15274, 290, 15180, 389, 23243, 287, 41988, 1502, 11, 1441, 262, 479, 400, 18197, 5002, 287, 262, 17593, 13, 198, 198, 6425, 326, 340, 318, 262, 479, 400, 18197, 5...
2.636816
402
from unittest import TestCase from unittest.mock import Mock import numpy as np from pathfinding.domain.angle import Angle from pathfinding.domain.coord import Coord from vision.domain.image import Image from vision.domain.rectangle import Rectangle from vision.infrastructure.cvVisionException import CameraDoesNotExistError from vision.service.visionService import VisionService
[ 6738, 555, 715, 395, 1330, 6208, 20448, 198, 6738, 555, 715, 395, 13, 76, 735, 1330, 44123, 198, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 3108, 41070, 13, 27830, 13, 9248, 1330, 42375, 198, 6738, 3108, 41070, 13, 27830, 13,...
4.085106
94
from .feature_maps import * import torch.nn as nn def create_grad_feature_map(model: nn.Module, grad_layers: List[LayerGradientComputation], use_float64: bool = False) -> FeatureMap: """ Creates a feature map corresponding to phi_{grad} or phi_{ll}, depending on which layers are provided. :param model: Model to compute gradients of :param grad_layers: All layers of the model whose parameters we want to compute gradients of :param use_float64: Set to true if the gradient features should be converted to float64 after computing them :return: Returns a feature map corresponding to phi_{grad} for the given layers. """ tfms = [ModelGradTransform(model, grad_layers)] if use_float64: tfms.append(ToDoubleTransform()) return SequentialFeatureMap(SumFeatureMap([l.get_feature_map() for l in grad_layers]), tfms) # ----- Specific LayerGradientComputation implementation(s) for linear layers
[ 6738, 764, 30053, 62, 31803, 1330, 1635, 198, 11748, 28034, 13, 20471, 355, 299, 77, 628, 628, 198, 4299, 2251, 62, 9744, 62, 30053, 62, 8899, 7, 19849, 25, 299, 77, 13, 26796, 11, 3915, 62, 75, 6962, 25, 7343, 58, 49925, 42731, 1...
2.885714
350
from configparser import ConfigParser from configparser import DuplicateSectionError from PyQt5 import QtCore, QtGui, QtWidgets from pinsey import Constants from pinsey.Utils import clickable, center, picture_grid, horizontal_line, resolve_message_sender, name_set, windows from pinsey.gui.MessageWindow import MessageWindow from pinsey.gui.component.BrowseListing import BrowseListing from pinsey.gui.component.DislikesListing import DislikesListing from pinsey.gui.component.LikesListing import LikesListing from pinsey.handler.DecisionHandler import DecisionHandler from pinsey.handler.LikesHandler import LikesHandler from pinsey.thread.DownloadPhotosThread import DownloadPhotosThread from pinsey.thread.LikesBotThread import LikesBotThread from pinsey.thread.SessionThread import SessionThread from pinsey.thread.MatchesThread import MatchesThread
[ 6738, 4566, 48610, 1330, 17056, 46677, 198, 6738, 4566, 48610, 1330, 49821, 5344, 16375, 12331, 198, 6738, 9485, 48, 83, 20, 1330, 33734, 14055, 11, 33734, 8205, 72, 11, 33734, 54, 312, 11407, 198, 198, 6738, 6757, 4397, 1330, 4757, 118...
3.855856
222
from os import system as c i = "ipconfig" input(c(i)) # import win32clipboard # from time import sleep as wait # set clipboard data # while True: # win32clipboard.OpenClipboard() # win32clipboard.EmptyClipboard() # win32clipboard.SetClipboardText('Clipboard Blocked!') # win32clipboard.CloseClipboard() # wait(0.1)
[ 6738, 28686, 1330, 1080, 355, 269, 198, 72, 796, 366, 541, 11250, 1, 198, 15414, 7, 66, 7, 72, 4008, 198, 2, 1330, 1592, 2624, 15036, 3526, 198, 2, 422, 640, 1330, 3993, 355, 4043, 198, 198, 2, 900, 47999, 1366, 198, 2, 981, 640...
2.564885
131
# -*- encoding: utf-8 -*- """ @File : emails.py @Contact : 1053522308@qq.com @License : (C)Copyright 2017-2018, Liugroup-NLPR-CASIA @Modify Time @Author @Version @Desciption ------------ ------- -------- ----------- 2020/9/27 10:22 wuxiaoqiang 1.0 None """ import asyncio from email.mime.text import MIMEText import aiosmtplib from app.core.celery_app import celery_app from app.core.config import settings
[ 2, 532, 9, 12, 21004, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 31, 8979, 220, 220, 220, 1058, 220, 220, 7237, 13, 9078, 220, 220, 220, 220, 198, 31, 17829, 1058, 220, 220, 13343, 2327, 1828, 21495, 31, 38227, 13, 785, ...
2.326633
199
import time import copy import random import logging from functools import partial import numpy as np import torch from torch.utils.data import DataLoader from transformers import DistilBertModel, DistilBertForSequenceClassification, DistilBertTokenizer, AlbertModel, AlbertForSequenceClassification, DistilBertTokenizer, AlbertTokenizer, AdamW, get_linear_schedule_with_warmup from lightwood.config.config import CONFIG from lightwood.constants.lightwood import COLUMN_DATA_TYPES, ENCODER_AIM from lightwood.mixers.helpers.default_net import DefaultNet from lightwood.mixers.helpers.ranger import Ranger from lightwood.mixers.helpers.shapes import * from lightwood.mixers.helpers.transformer import Transformer from lightwood.api.gym import Gym if __name__ == "__main__": # Generate some tests data import random from sklearn.metrics import r2_score import logging from lightwood.encoders.numeric import NumericEncoder logging.basicConfig(level=logging.DEBUG) random.seed(2) priming_data = [] primting_target = [] test_data = [] test_target = [] for i in range(0,300): if random.randint(1,5) == 3: test_data.append(str(i) + ''.join(['n'] * i)) #test_data.append(str(i)) test_target.append(i) #else: priming_data.append(str(i) + ''.join(['n'] * i)) #priming_data.append(str(i)) primting_target.append(i) output_1_encoder = NumericEncoder() output_1_encoder.prepare_encoder(primting_target) encoded_data_1 = output_1_encoder.encode(primting_target) encoded_data_1 = encoded_data_1.tolist() enc = DistilBertEncoder() enc.prepare_encoder(priming_data, training_data={'targets': [{'output_type': COLUMN_DATA_TYPES.NUMERIC, 'encoded_output': encoded_data_1}, {'output_type': COLUMN_DATA_TYPES.NUMERIC, 'encoded_output': encoded_data_1}]}) encoded_predicted_target = enc.encode(test_data).tolist() predicted_targets_1 = output_1_encoder.decode(torch.tensor([x[:4] for x in encoded_predicted_target])) predicted_targets_2 = output_1_encoder.decode(torch.tensor([x[4:] for x in encoded_predicted_target])) for predicted_targets in [predicted_targets_1, predicted_targets_2]: real = list(test_target) pred = list(predicted_targets) # handle nan for i in range(len(pred)): try: float(pred[i]) except: pred[i] = 0 print(real[0:25], '\n', pred[0:25]) encoder_accuracy = r2_score(real, pred) print(f'Categorial encoder accuracy for: {encoder_accuracy} on testing dataset') #assert(encoder_accuracy > 0.5)
[ 11748, 640, 198, 11748, 4866, 198, 11748, 4738, 198, 11748, 18931, 198, 6738, 1257, 310, 10141, 1330, 13027, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 198, 6738, 28034, 13, 26791, 13, 7890, 1330, 6060, 17401, 198, 6738, ...
2.442029
1,104
#!/usr/bin/env python ############################################################################### # # scomdominfo.py - Report information folds and classes of a list of SCOP sids # # File: scomdominfo.py # Author: Alex Stivala # Created: November 2008 # # $Id: scopdominfo.py 3009 2009-12-08 03:01:48Z alexs $ # ############################################################################### """ Report information on the folds, superfamilies and classes of a list of SCOP domain identifiers (sids). See usage in docstring for main() SCOP and ASTRAL data is obtained using the Bio.SCOP library (Casbon et al 2006 'A high level interface to SCOP and ASTRAL implemented in Python' BMC Bioinformatics 7:10) and depends on having the data downloaded, in SCOP_DIR (defined below). Downloaded SCOP files from http://scop.mrc-lmb.cam.ac.uk/scop/parse/index.html and ASTRAL files (in scopseq-1.73) from http://astral.berkeley.edu/scopseq-1.73.html The files downlaoded are: /local/charikar/SCOP/: dir.cla.scop.txt_1.73 dir.des.scop.txt_1.73 dir.hie.scop.txt_1.73 /local/charikar/SCOP/scopseq-1.73: astral-scopdom-seqres-all-1.73.fa astral-scopdom-seqres-sel-gs-bib-95-1.73.id Other files there are indices built by Bio.SCOP when first used. """ import sys,os from Bio.SCOP import * from pathdefs import SCOP_DIR,SCOP_VERSION #----------------------------------------------------------------------------- # # Function definitions # #----------------------------------------------------------------------------- def write_scopdom_info(scopsid_list, fh, scop): """ Write information about the list of SCOP sids (domain identifiers) in the scopsid_list to fh. For each domain write the fold and class, then write stats about number of different folds represented and the number of domains in each class. Parameters: scopsid_list - list of SCOP sids (domain ids) fh - open (write) filehandle to write to scop - previously built Bio.SCOP Scop instance Return value: None. """ superfamily_count = {} # dict of {sf_sunid : count} counting domains in eac superfamily fold_count= {} # dict of {fold_sunid : count} counting domains in each fold class_count={} # dict of {class_sunid : count} counting domains in each class for sid in scopsid_list: scop_dom = scop.getDomainBySid(sid) scop_superfamily = scop_dom.getAscendent('superfamily') scop_fold = scop_dom.getAscendent('fold') scop_class = scop_dom.getAscendent('class') if superfamily_count.has_key(scop_superfamily.sunid): superfamily_count[scop_superfamily.sunid] += 1 else: superfamily_count[scop_superfamily.sunid] = 1 if fold_count.has_key(scop_fold.sunid): fold_count[scop_fold.sunid] += 1 else: fold_count[scop_fold.sunid] = 1 if class_count.has_key(scop_class.sunid): class_count[scop_class.sunid] += 1 else: class_count[scop_class.sunid] = 1 fh.write('%s\t(%s) %s\t%s\t%s\n' % (sid, scop_superfamily.sccs,scop_superfamily.description, scop_fold.description, scop_class.description)) num_domains = len(scopsid_list) num_superfamilies = len(superfamily_count) num_folds = len(fold_count) num_classes = len(class_count) fh.write('Totals: %d domains\t%d superfamilies\t%d folds\t%d classes\n' % (num_domains, num_superfamilies, num_folds, num_classes)) fh.write('Class distribution:\n') for (class_sunid, count) in class_count.iteritems(): fh.write('\t%s:\t%d\n' % (scop.getNodeBySunid(class_sunid).description, count)) #----------------------------------------------------------------------------- # # Main # #----------------------------------------------------------------------------- def usage(progname): """ Print usage message and exit """ sys.stderr.write("Usage: " +progname + " < domainidlist\n") sys.exit(1) def main(): """ main for scomdominfo.py Usage: scomdominfo.py < domainidlist The list of SCOP domain ids (sids) is read from stdin Output is written to stdout. """ if len(sys.argv) != 1: usage(os.path.basename(sys.argv[0])) # read SCOP data scop = Scop(dir_path=SCOP_DIR,version=SCOP_VERSION) scopsid_list = sys.stdin.read().split('\n')[:-1] write_scopdom_info(scopsid_list, sys.stdout, scop) if __name__ == "__main__": main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 29113, 29113, 7804, 4242, 21017, 198, 2, 198, 2, 629, 296, 3438, 10951, 13, 9078, 532, 6358, 1321, 38744, 290, 6097, 286, 257, 1351, 286, 6374, 3185, 264, 2340, 198, 2, 198, 2, 9220,...
2.567552
1,769
# Copyright (C) 2020 Intel Corporation # # SPDX-License-Identifier: MIT from tools.test import * import os
[ 2, 15069, 357, 34, 8, 12131, 8180, 10501, 198, 2, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 17168, 198, 198, 6738, 4899, 13, 9288, 1330, 1635, 198, 11748, 28686, 628 ]
3.30303
33
import torch import torch.nn as nn from torch.nn import (TransformerEncoder, TransformerDecoder, TransformerEncoderLayer, TransformerDecoderLayer) from torch import Tensor from typing import Iterable, List import math import os import numpy as np try: from janome.tokenizer import Tokenizer except ModuleNotFoundError: import os os.system('pip install janome') from janome.tokenizer import Tokenizer from google_drive_downloader import GoogleDriveDownloader # DEVICE = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') print('DEVICE :', DEVICE) # SRC (source) : SRC_LANGUAGE = 'jpn' # TGT (target) : TGT_LANGUAGE = 'py' # special_token IDX UNK_IDX, PAD_IDX, SOS_IDX, EOS_IDX = 0, 1, 2, 3 tokenizer = Tokenizer(os.path.join(os.path.dirname( __file__), 'janomedic.csv'), udic_type="simpledic", udic_enc="utf8", wakati=True) # def generate_square_subsequent_mask(sz): mask = (torch.triu(torch.ones((sz, sz), device=DEVICE)) == 1).transpose(0, 1) mask = mask.float().masked_fill(mask == 0, float( '-inf')).masked_fill(mask == 1, float(0.0)) return mask def sequential_transforms(*transforms): return func def tensor_transform(token_ids: List[int]): return torch.cat((torch.tensor([SOS_IDX]), torch.tensor(token_ids), torch.tensor([EOS_IDX]))) def beam_topk(model, ys, memory, beamsize): ys = ys.to(DEVICE) tgt_mask = (generate_square_subsequent_mask( ys.size(0)).type(torch.bool)).to(DEVICE) out = model.decode(ys, memory, tgt_mask) out = out.transpose(0, 1) prob = model.generator(out[:, -1]) next_prob, next_word = prob.topk(k=beamsize, dim=1) return next_prob, next_word # greedy search () special_token = ['<A>', '<B>', '<C>', '<D>', '<E>']
[ 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 6738, 28034, 13, 20471, 1330, 357, 8291, 16354, 27195, 12342, 11, 3602, 16354, 10707, 12342, 11, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220,...
2.32197
792
# Copyright 2010-2012 Opera Software ASA # # 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 standalone import probedb.probedata2.models as Prober import probedb.certs.models as Certs import probedb.resultdb2.models as Results from django.db.models import Q import certhandler import threading import Queue """ Update the database so that the certificate attributes are set for all certificates Used in case there is a failure in the automatic registration of certificates and setting of attributes """ keys = {} selfsigned_keys ={} failed=0 upgraded = 0 EV_conditions = set([ Certs.CertificateConditions.CERTC_EXTENDED_VALIDATION_CERT, Certs.CertificateConditions.CERTC_NOT_EXTENDED_VALIDATION_CERT ]) summaries = dict([(x.id, x) for x in Results.ResultSummaryList.objects.all()]) i=0; for x in summaries.itervalues(): x.start() if 0: for c,d in Results.ResultCondition.RESULTC_VALUES: x.check_condition(c) if 0: i=0; for certificate in Prober.Certificate.objects.filter(issuer_b64=None).iterator(): cert = certhandler.Certificate(certificate.certificate_b64) if not cert: continue certificate.issuer_b64 = cert.IssuerNameDER() certificate.subject_b64 = cert.SubjectNameDER() certificate.save() i+=1 if i%100 == 0: print i print "finished issuer" if 0: i=0 for certificate in Prober.Certificate.objects.filter(subject_b64=None).iterator(): cert = certhandler.Certificate(certificate.certificate_b64) if not cert: continue certificate.issuer_b64 = cert.IssuerNameDER() certificate.subject_b64 = cert.SubjectNameDER() certificate.save() i+=1 if i%100 == 0: print i print "finished subject" if 0: i=0 for certificate in Certs.CertAttributes.objects.filter(serial_number=None).iterator(): cert = certhandler.Certificate(certificate.cert.certificate_b64) if not cert: continue serial = str(cert.GetSerialNumber()) if len(serial) >100: serial = "NaN" certificate.serial_number = serial certificate.save() i+=1 if i%100 == 0: print i print "finished serial numbers" if 1: print "building database" update_queue = Queue.Queue() finished_queue = Queue.Queue() num_probers = 100 threads = [] for i in range(num_probers): new_thread = threading.Thread(target=do_update_cert, args=(update_queue,finished_queue, i)) new_thread.daemon = True new_thread.start() threads.append(new_thread) progress_thread = threading.Thread(target=__ProgressCounter, args=(finished_queue,)) progress_thread.daemon = True progress_thread.start() i=0; c_ids = list(Prober.Certificate.objects.filter(certattributes=None).values_list("id", flat=True)) print len(c_ids) for k in c_ids: #for x in Prober.Certificate.objects.iterator(): i+=1 if i % 100 == 0: print i update_queue.put(k) update_queue.join() finished_queue.join() if 0: print "Marking site certificates" i=0; #for k in list(Certs.CertAttributes.objects.filter(cert__server_cert__id__gt =0).distinct().values_list("id", flat=True)): c_ids = Certs.CertAttributes.objects.filter(cert_kind = Certs.CertAttributes.CERT_UNKNOWN).values_list("cert_id", flat=True) c_cids = list(Prober.ProbeResult.objects.exclude(server_cert__id__in = c_ids).filter(server_cert__id__gt =0).distinct().values_list("server_cert__id", flat=True)) for k in c_ids : i+=1 if i % 100 == 0: print i try: x = Certs.CertAttributes.objects.get(cert__id = k) if x.cert_kind == Certs.CertAttributes.CERT_SELFSIGNED: x.cert_kind = Certs.CertAttributes.CERT_SELFSIGNED_SERVER else: x.cert_kind = Certs.CertAttributes.CERT_SERVER x.save() except: pass if 0: print "Locating intermediates" i=0; already_fixed = set() #for k in list(Certs.CertAttributes.objects.filter(cert__server_cert__id__gt =0).distinct().values_list("id", flat=True)): for k in list(Certs.CertAttributes.objects.exclude(cert_kind__in =[Certs.CertAttributes.CERT_SELFSIGNED, Certs.CertAttributes.CERT_SELFSIGNED_SERVER, Certs.CertAttributes.CERT_INTERMEDIATE_CA, Certs.CertAttributes.CERT_XSIGN_CA, Certs.CertAttributes.CERT_SERVER,] ). filter(cert__proberesult__server_cert__id__gt =0). distinct(). values_list("id", flat=True)): i+=1 if i % 100 == 0: print i if k in already_fixed: continue; x = Certs.CertAttributes.objects.get(id = k) for y in x.cert.proberesult_set.filter(server_cert__id__gt =0): certs0 = [(z, certhandler.Certificate(z.certificate_b64)) for z in y.certificates.all() if z.certattributes.cert_kind not in [Certs.CertAttributes.CERT_SELFSIGNED_SERVER, Certs.CertAttributes.CERT_SERVER]] if not certs0: continue; certs = {} for (z, c) in certs0: if not c: continue subject = c.SubjectNameLine() certs.setdefault(subject,[]).append((z,c)) if not certs: continue site = certhandler.Certificate(y.server_cert.certificate_b64) if not site: continue last = site while True: issuer = last.IssuerNameLine() if issuer not in certs: break; signer = None cert = None for (z,c) in certs[issuer]: if last.IsSignedBy(c): signer = z cert = c break; del certs[issuer] # prevent infinite loop if not signer: break; if signer.certattributes.cert_kind in [Certs.CertAttributes.CERT_SELFSIGNED, Certs.CertAttributes.CERT_TRUSTED_ROOT, ]: break; # Root, already set if signer.certattributes.cert_kind == Certs.CertAttributes.CERT_UNKNOWN or signer.certattributes.cert_kind =="": signer.certattributes.cert_kind = Certs.CertAttributes.CERT_INTERMEDIATE_CA signer.certattributes.save() already_fixed.add(signer.id) last = cert break; if 0: print "Locating intermediates #2" i=0; already_fixed = set() name_matches = 0 signed_by = 0 #for k in list(Certs.CertAttributes.objects.filter(cert__server_cert__id__gt =0).distinct().values_list("id", flat=True)): for k in list(Certs.CertAttributes.objects.exclude(cert_kind__in =[Certs.CertAttributes.CERT_SELFSIGNED, Certs.CertAttributes.CERT_SELFSIGNED_SERVER, Certs.CertAttributes.CERT_INTERMEDIATE_CA, Certs.CertAttributes.CERT_XSIGN_CA, Certs.CertAttributes.CERT_SERVER,] ). distinct(). values_list("id", flat=True)): i+=1 if i % 100 == 0: print i if k in already_fixed: continue; x = Certs.CertAttributes.objects.get(id = k) cert = certhandler.Certificate(x.cert.certificate_b64) if not cert: continue assert not cert.IsSelfSigned() subject = x.subject_oneline for y in Certs.CertAttributes.objects.filter(issuer_oneline=subject): name_matches += 1 cert_cand = certhandler.Certificate(y.cert.certificate_b64) if not cert_cand: continue; if cert_cand.IsSignedBy(cert): signed_by += 1 if x.cert_kind in [Certs.CertAttributes.CERT_UNKNOWN, ""]: x.cert_kind = Certs.CertAttributes.CERT_INTERMEDIATE_CA x.save() already_fixed.add(x.id) break print "Name matches: ", name_matches print "Signed by: ",signed_by print "completed"
[ 2, 220, 220, 15069, 3050, 12, 6999, 26049, 10442, 49599, 220, 198, 2, 198, 2, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 220, 220, 345, 743, 407, 779, 428, 2393, 2845, 28...
2.403698
3,245
from flask import Flask from loguru import logger from flasgger import Swagger from patron.api import api_bp logger.add("api.log", format="{time:YYYY-MM-DD at HH:mm:ss} | {level} | {message}", rotation="500 MB") template = { "swagger": "2.0", "info": { "title": "PATRON", "description": "", "version": "0.0.1" }, "consumes": [ "application/json" ], "produces": [ "application/json" ] } app = Flask(__name__) swagger = Swagger(app, template=template) app.register_blueprint(api_bp, url_prefix='/api')
[ 6738, 42903, 1330, 46947, 198, 6738, 2604, 14717, 1330, 49706, 198, 6738, 781, 292, 26679, 1330, 2451, 7928, 198, 198, 6738, 19686, 13, 15042, 1330, 40391, 62, 46583, 628, 198, 6404, 1362, 13, 2860, 7203, 15042, 13, 6404, 1600, 5794, 26...
2.305221
249
import numpy as np import matplotlib.pylab as plt
[ 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 79, 2645, 397, 355, 458, 83, 198 ]
2.777778
18
# with tidy long table fig, ax = plt.subplots() sns.violinplot(x='station', y='no2', data=data_tidy[data_tidy['datetime'].dt.year == 2011], palette="GnBu_d", ax=ax) ax.set_ylabel("NO$_2$ concentration (g/m)")
[ 2, 351, 43044, 890, 3084, 198, 5647, 11, 7877, 796, 458, 83, 13, 7266, 489, 1747, 3419, 198, 82, 5907, 13, 17069, 259, 29487, 7, 87, 11639, 17529, 3256, 331, 11639, 3919, 17, 3256, 1366, 28, 7890, 62, 83, 19325, 58, 7890, 62, 83, ...
2.363636
88
""" Project: dncnn Author: khalil MEFTAH Date: 2021-11-26 DnCNN: Deep Neural Convolutional Network for Image Denoising model implementation """ import torch from torch import nn import torch.nn.functional as F # helper functions # main classe
[ 37811, 198, 16775, 25, 288, 10782, 20471, 198, 13838, 25, 479, 14201, 346, 11948, 37, 5603, 39, 198, 10430, 25, 33448, 12, 1157, 12, 2075, 198, 35, 77, 18474, 25, 10766, 47986, 34872, 2122, 282, 7311, 329, 7412, 5601, 78, 1710, 2746, ...
3.25
76
#!/usr/bin/python from __future__ import print_function import logging from fabric.api import task,run,local,put,get,execute,settings from fabric.decorators import * from fabric.context_managers import shell_env,quiet from fabric.exceptions import * from fabric.utils import puts,fastprint from time import sleep from contextlib import contextmanager import traceback import os,sys,datetime,re,ast import itertools import glob,shlex,subprocess import pprint sys.path.append('..') from environment import * from experiments import * from experiments import configs from helper import get_cfgs,get_outfile_name,get_execfile_name,get_args,CONFIG_PARAMS,FLAG # (see https://github.com/fabric/fabric/issues/51#issuecomment-96341022) logging.basicConfig() paramiko_logger = logging.getLogger("paramiko.transport") paramiko_logger.disabled = True COLORS = { "info" : 32, #green "warn" : 33, #yellow "error" : 31, #red "debug" : 36, #cyan } #OUT_FMT = "[{h}] {p}: {fn}:".format PP = pprint.PrettyPrinter(indent=4) NOW=datetime.datetime.now() STRNOW=NOW.strftime("%Y%m%d-%H%M%S") os.chdir('../..') #MAX_TIME_PER_EXP = 60 * 2 # in seconds MAX_TIME_PER_EXP = 60 * 10 # in seconds EXECUTE_EXPS = True SKIP = False CC_ALG = "" set_env() ## Basic usage: ## fab using_vcloud run_exps:experiment_1 ## fab using_local run_exps:experiment_1 ## fab using_istc run_exps:experiment_1 # execute(run_exp,exps,delay=delay) ## Basic usage: ## fab using_vcloud network_test ## fab using_istc network_test:4 #delay is in ms #delay is in ms # run("pkill -f runsq") def get_good_hosts(): # good_hosts = [] set_hosts() good_hosts = env.hosts # Find and skip bad hosts ping_results = execute(ping) for host in ping_results: if ping_results[host] == 0: # good_hosts.append(host) continue else: with color("warn"): puts("Skipping non-responsive host {}".format(host),show_prefix=True) good_hosts.remove(host) return good_hosts # for e in experiments: # execute(compile_binary,fmt,e) def succeeded(outcomes): for host,outcome in outcomes.iteritems(): if not outcome: return False return True
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 11748, 18931, 198, 6738, 9664, 13, 15042, 1330, 4876, 11, 5143, 11, 12001, 11, 1996, 11, 1136, 11, 41049, 11, 33692, 198, 6738, 9664, ...
2.404343
967
from django import forms from mezzanine.blog.forms import BlogPostForm from .models import BlogPost # These fields need to be in the form, hidden, with default values, # since it posts to the blog post admin, which includes these fields # and will use empty values instead of the model defaults, without # these specified. hidden_field_defaults = ("status", "gen_description", "allow_comments")
[ 198, 6738, 42625, 14208, 1330, 5107, 198, 198, 6738, 502, 3019, 272, 500, 13, 14036, 13, 23914, 1330, 14001, 6307, 8479, 198, 198, 6738, 764, 27530, 1330, 14001, 6307, 628, 198, 2, 2312, 7032, 761, 284, 307, 287, 262, 1296, 11, 7104, ...
3.893204
103
# -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2019-03-02 15:56 from __future__ import unicode_literals import ckeditor.fields from django.db import migrations, models import django.db.models.deletion
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 352, 13, 1157, 13, 21, 319, 13130, 12, 3070, 12, 2999, 1315, 25, 3980, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, ...
2.789474
76
import platform from setuptools import setup if platform.system() == "Windows": setup( name="intermezzo", version="0.1.0", description="A library for creating cross-platform text-based interfaces using termbox-go.", long_description="", url="https://github.com/imdaveho/intermezzo", author="Dave Ho", author_email="imdaveho@gmail.com", license="MIT", classifiers=[], packages=["intermezzo"], package_data={"intermezzo": ["build/*/*.dll"]}, keywords="termbox tui terminal command-line", install_requires=["cffi>=1.10.0"], cffi_modules=["intermezzo/build/build_ffi_win.py:ffi"], setup_requires=["cffi>=1.10.0"], ) else: setup( name="intermezzo", version="0.1.0", description="A library for creating cross-platform text-based interfaces using termbox-go.", long_description="", url="https://github.com/imdaveho/intermezzo", author="Dave Ho", author_email="imdaveho@gmail.com", license="MIT", classifiers=[], packages=["intermezzo"], package_data={"intermezzo": ["build/*/*.so"]}, keywords="termbox tui terminal command-line", install_requires=["cffi>=1.10.0"], cffi_modules=["intermezzo/build/build_ffi_nix.py:ffi"], setup_requires=["cffi>=1.10.0"], )
[ 11748, 3859, 198, 6738, 900, 37623, 10141, 1330, 9058, 198, 198, 361, 3859, 13, 10057, 3419, 6624, 366, 11209, 1298, 198, 220, 220, 220, 9058, 7, 198, 220, 220, 220, 220, 220, 220, 220, 1438, 2625, 3849, 1326, 47802, 1600, 198, 220, ...
2.192248
645
from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('<str:nome>', views.cumprimentar, name='cumprimentar'), ]
[ 6738, 42625, 14208, 13, 6371, 82, 1330, 3108, 198, 6738, 764, 1330, 5009, 198, 198, 6371, 33279, 82, 796, 685, 198, 220, 220, 220, 3108, 10786, 3256, 5009, 13, 9630, 11, 1438, 11639, 9630, 33809, 198, 220, 220, 220, 3108, 10786, 27, ...
2.621212
66
import numpy as np import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec import cv2, os, sys, glob import scipy import sklearn import imageio import matplotlib.cm as cm import matplotlib import time from sklearn import decomposition, metrics, manifold, svm from tsne import bh_sne from matplotlib.path import Path from numpy import linalg as LA from scipy.signal import butter, filtfilt, cheby1 from scipy.spatial import distance #************************************************************************************************************************** #*************************************************CODE START*************************************************************** #**************************************************************************************************************************
[ 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 2603, 29487, 8019, 13, 2164, 2340, 43106, 355, 50000, 43106, 198, 11748, 269, 85, 17, 11, 28686, 11, 25064, 11, 15095, 198, 11748, ...
4.596685
181
import pygame from game.game_data.cells.Cell import Cell from game.pygame_ import PICS_pygame, CELL_SIZE from game.pygame_.Object import Object
[ 11748, 12972, 6057, 198, 198, 6738, 983, 13, 6057, 62, 7890, 13, 46342, 13, 28780, 1330, 12440, 198, 6738, 983, 13, 9078, 6057, 62, 1330, 350, 19505, 62, 9078, 6057, 11, 18671, 3069, 62, 33489, 198, 6738, 983, 13, 9078, 6057, 44807, ...
3.173913
46
import json import os import torch import math def adjust_learning_rate(optimizer, scale): """ Scale learning rate by a specified factor. :param optimizer: optimizer whose learning rate must be shrunk. :param scale: factor to multiply learning rate with. """ for param_group in optimizer.param_groups: param_group['lr'] = param_group['lr'] * scale print("DECAYING learning rate, the new LR is %f" % (optimizer.param_groups[1]['lr'],)) def warm_up_learning_rate(optimizer, rate=5.): """ Scale learning rate by a specified factor. :param rate: :param optimizer: optimizer whose learning rate must be shrunk. :param scale: factor to multiply learning rate with. """ for param_group in optimizer.param_groups: param_group['lr'] = param_group['lr'] * rate print("WARMING up learning rate, the new LR is %f" % (optimizer.param_groups[1]['lr'],))
[ 11748, 33918, 198, 11748, 28686, 198, 11748, 28034, 198, 11748, 10688, 628, 198, 4299, 4532, 62, 40684, 62, 4873, 7, 40085, 7509, 11, 5046, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 21589, 4673, 2494, 416, 257, 7368, 5766, ...
2.974277
311
from enum import Enum
[ 6738, 33829, 1330, 2039, 388, 628 ]
3.833333
6
#!/bin/python3 """This is the top-level program to operate the Raspberry Pi based lego sorter.""" # Things I can set myself: AWB, Brightness, crop, exposure_mode, # exposure_speed,iso (sensitivity), overlays, preview_alpha, # preview_window, saturation, shutter_speed, # Thought for future enhancement: at start time, calibrate against # a background image. Possibly only evaluate pixels which # deviate significantly in hue from the original background image. # Thoughts on controlling the air valves: # I'm going to take the simple approach first, and hopefully it's sufficient: # 1. Detect different colors in zones in front of their respective valves # 2. If enough of the first color is detected, puff it into that color's bin # 3. Otherwise, let it ride through as many detection zones as # necessary until it's detected or falls off the track # Upsides: # 1. It's dead simple and reactive. No state needed to manage # 2. No timing tuning needed for detect-then-wait method (source of failure) # 3. No tracking needed (source of failure/flakiness) # 4. Less memory/CPU intensive # # Downsides: # 1. A multi-color part could slip past without enough "density" of any one color # 2. More detection zones means more potential variation in the # lighting - same part could look yellow in one zone and orange # in the next, causing misses import os import json import time from datetime import datetime import cv2 from picamera import PiCamera from picamera.array import PiRGBArray import numpy as np # GPIO Imports import RPi.GPIO as GPIO # constants for tweaking WINDOW_NAME = "Recognition" SCALE_PERCENT = 20 PIXEL_THRESHOLD = 50 RANGE_PADDING = 10 SHOW_OVERLAY = True COLOR_COLUMN_WIDTH = 10 OUTPUT_VIDEO = False VIDEO_NAME = "output.avi" LEGO_CONFIG_NAME = "legos.config.json" # setup GPIO (https://pythonhosted.org/RPIO/) VALVE_PIN = 18 GPIO.setmode(GPIO.BCM) GPIO.setup(VALVE_PIN, GPIO.OUT) GPIO.output(VALVE_PIN, GPIO.HIGH) # Detection box location XMIN = 36 XMAX = 85 YMIN = 96 YMAX = 121 SHOW_BOX = True # todo: fork data to a logfile in /var # Setup the display window if SHOW_OVERLAY: cv2.namedWindow(WINDOW_NAME, cv2.WINDOW_NORMAL) cv2.resizeWindow(WINDOW_NAME, 800, 800) # Load jets we want to use jets = [] with open('jets.config.json') as json_file: jets = json.load(json_file) # Load legos we want to recognize legos = [] with open('legos.config.json') as json_file: config = json.load(json_file) for lego_config in config: if((lego_config["jet_number"] >= 0) and (lego_config["jet_number"] < len(jets))): legos.append( Lego( lconfig=lego_config, recognition_box=jets[lego_config["jet_number"]]["bounding_box_corners"], ) ) else: legoname = lego_config["name"] print(f"Lego color {legoname} disabled") # Run the camera with PiCamera( camera_num=0, # default stereo_mode='none', # default stereo_decimate=False, # default resolution=(160, 96), # default (10% of full resolution of 1600x900) framerate=10, # 10 fps, default is 30 sensor_mode=5) as camera: # default=1, 5 is full FOV with 2x2 binning #camera.awb_mode = 'off' # turn off AWB because I will control lighting camera.awb_gains = (1.184, 2.969) # Set constant AWB (tuple for red and blue, or constant) # time.sleep(2) print("{datetime.now()} Camera setup complete.") print(f"{datetime.now()} AWB Gains are {camera.awb_gains}") # time.sleep(3) # Setup the buffer into which we'll capture the images cam_image = PiRGBArray(camera) if OUTPUT_VIDEO: cap = cv2.VideoCapture(0) fourcc = cv2.VideoWriter_fourcc(*'XVID') out = cv2.VideoWriter('output.avi', fourcc, 10.0, (160, 96)) # start the preview window in the top left corner camera.start_preview(resolution=(160, 96), window=(40, 40, 320, 192), fullscreen=False) camera.preview_alpha = 200 print("{datetime.now()} Camera preview started") # continuously capture files last_loop_time = time.time() for i, filename in enumerate( camera.capture_continuous( cam_image, format='bgr', use_video_port=True, # faster, but less good images resize=None # resolution was specified above )): # clear the screen os.system('clear') # load the image image = cam_image.array.copy() image_hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) # Run recognition on the same image for each lego type for lego in legos: lego.recognize_at(image_hsv) all_pixel_counts = 0 for lego in legos: all_pixel_counts += lego.pixel_count print(f"{datetime.now()} {all_pixel_counts} Pixels detected") print_string = "" for lego in legos: print_string += f"{lego.name:^{COLOR_COLUMN_WIDTH}}|" print(print_string) print_string = "" for lego in legos: print_string += f"{lego.pixel_count:^{COLOR_COLUMN_WIDTH}}|" print(print_string) for lego in legos: yxmin = (jets[lego.jet_number]["bounding_box_corners"][0][1], jets[lego.jet_number]["bounding_box_corners"][0][0]) yxmax = (jets[lego.jet_number]["bounding_box_corners"][1][1], jets[lego.jet_number]["bounding_box_corners"][1][0]) if lego.pixel_count > PIXEL_THRESHOLD: GPIO.output(jets[lego.jet_number]["gpio_pin"], GPIO.LOW) print(f"{lego.name} RECOGNIZED! {lego.pixel_count} pixels") if SHOW_BOX: cv2.rectangle(image, yxmin, yxmax, lego.display_bgr, 1) else: GPIO.output(jets[lego.jet_number]["gpio_pin"], GPIO.HIGH) if SHOW_BOX: cv2.rectangle(image, yxmin, yxmax, (0, 0, 0), 1) if SHOW_OVERLAY: for lego in legos: image[lego.recognition_indices[0]+ jets[lego.jet_number]["bounding_box_corners"][0][0], lego.recognition_indices[1]+ jets[lego.jet_number]["bounding_box_corners"][0][1]] = lego.display_bgr cv2.waitKey(1) cv2.imshow(WINDOW_NAME, image) if OUTPUT_VIDEO: out.write(image) # display the loop speed now_time = int(round(time.time() * 1000)) print(f"Loop [{i}] completed in {now_time-last_loop_time}ms") last_loop_time = now_time # clear the buffers for the image cam_image.truncate(0) camera.stop_preview() out.release() cv2.destroyAllWindows()
[ 2, 48443, 8800, 14, 29412, 18, 198, 37811, 1212, 318, 262, 1353, 12, 5715, 1430, 284, 8076, 262, 24244, 13993, 1912, 1232, 78, 264, 4337, 526, 15931, 198, 198, 2, 11597, 314, 460, 900, 3589, 25, 14356, 33, 11, 17558, 1108, 11, 13833...
2.222928
3,149
# -*- coding: utf-8 -*- from yaml import load, dump try: from yaml import CSafeLoader as SafeLoader print "Using CSafeLoader" except ImportError: from yaml import SafeLoader print "Using Python SafeLoader" import os import sys reload(sys) sys.setdefaultencoding("utf-8") from sqlalchemy import Table
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 331, 43695, 1330, 3440, 11, 10285, 198, 28311, 25, 198, 197, 6738, 331, 43695, 1330, 9429, 8635, 17401, 355, 19978, 17401, 198, 197, 4798, 366, 12814, 9429, 8635, ...
3.05
100
from django.shortcuts import render from core.models import Projects,InfoNotifications,WarningNotifications from django.http import HttpResponse from .tasks import sleepy
[ 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 198, 6738, 4755, 13, 27530, 1330, 29898, 11, 12360, 3673, 6637, 11, 20361, 3673, 6637, 198, 6738, 42625, 14208, 13, 4023, 1330, 367, 29281, 31077, 198, 198, 6738, 764, 83, 6791, 1330, 42...
4.119048
42
import tensorflow as tf import numpy as np EPS = 1e-5 def KL_monte_carlo(z, mean, sigma=None, log_sigma=None): """Computes the KL divergence at a point, given by z. Implemented based on https://www.tensorflow.org/tutorials/generative/cvae This is the part "log(p(z)) - log(q(z|x)) where z is sampled from q(z|x). Parameters ---------- z : (B, N) mean : (B, N) sigma : (B, N) | None log_sigma : (B, N) | None Returns ------- KL : (B,) """ if log_sigma is None: log_sigma = tf.math.log(sigma) zeros = tf.zeros_like(z) log_p_z = log_multivar_gaussian(z, mean=zeros, log_sigma=zeros) log_q_z_x = log_multivar_gaussian(z, mean=mean, log_sigma=log_sigma) return log_q_z_x - log_p_z def KL(mean, sigma=None, log_sigma=None): """KL divergence between a multivariate Gaussian and Multivariate N(0, I). Implemented based on https://mr-easy.github.io/2020-04-16-kl-divergence-between-2-gaussian-distributions/ Parameters ---------- mean : (B, N) sigma : (B, N) | None The diagonol of a covariance matrix of a factorized Gaussian distribution. log_sigma : (B, N) | None The log diagonol of a covariance matrix of a factorized Gaussian distribution. One of `sigma` and `log_sigma` has to be passed in. Returns ------- KL : (B,) """ if sigma is None: sigma = tf.math.exp(log_sigma) if log_sigma is None: log_sigma = tf.math.log(sigma) u = tf.reduce_sum(mean * mean, axis=1) # (B,) tr = tf.reduce_sum(sigma, axis=1) # (B,) k = tf.cast(tf.shape(mean)[1], tf.float32) # scalar lg = tf.reduce_sum(log_sigma, axis=1) # (B,) return 0.5 * (u + tr - k - lg) def log_multivar_gaussian(x, mean, sigma=None, log_sigma=None): """Computes log pdf at x of a multi-variate Gaussian. Parameters ---------- x : (B, N) mean : (B, N) sigma : (B, N) | None log_sigma: (B, N) | None Returns ------- log_p : (B,) """ if sigma is None: sigma = tf.math.exp(log_sigma) if log_sigma is None: log_sigma = tf.math.log(sigma) x = x - mean upper = -0.5 * tf.reduce_sum(x * x / (sigma + EPS), axis=-1) # (B,) k = tf.cast(tf.shape(x)[1], tf.float32) log_pi = tf.math.log(np.pi * 2) log_prod_sig = tf.reduce_sum(log_sigma, axis=1) # (B,) lower = -0.5 * (k * log_pi + log_prod_sig) return upper - lower def multivar_gaussian(x, mean, sigma): """Computes pdf at x of a multi-variate Gaussian Parameters ---------- x : (B, N) mean : (B, N) sigma : (B, N) Represents the diagonol of a covariance matrix of a factorized Gaussian distribution. Returns ------- p_x : (B,) """ x = x - mean upper = tf.reduce_sum(x * x / sigma, axis=-1) # (B,) upper = tf.math.exp(-0.5 * upper) # (B,) pi_vec = tf.ones_like(x) * np.pi * 2 # (B, N) lower = pi_vec * sigma lower = tf.reduce_prod(lower, axis=-1) # (B,) lower = tf.math.sqrt(lower) return upper / lower def reconstruction_cross_entropy(prediction, labels, is_logit=True): """Computes reconstruction error using cross entropy. Parameters ---------- prediction : (B, ...) labels : (B, ...) Same dimensions as `prediction` is_logit : bool Whether the prediction is logit (pre-softmax / sigmoid) Returns ------- recons_error : (B,) """ assert is_logit, "Not Implemented" cross_ent = tf.nn.sigmoid_cross_entropy_with_logits( labels=tf.cast(labels, tf.float32), logits=prediction, ) batch_size = tf.shape(prediction)[0] cross_ent = tf.reshape(cross_ent, (batch_size, -1)) return tf.reduce_mean(cross_ent, -1) def reconstruction_mean_square_error(prediction, labels, is_logit=True): """Computes reconstruction error using mean-square-error. Parameters ---------- prediction : (B, ...) labels : (B, ...) Same dimensions as `prediction` is_logit : bool Whether the prediciton is logit. Returns ------- recons_error : (B,) """ if is_logit: prediction = tf.nn.sigmoid(prediction) error = prediction - tf.cast(labels, tf.float32) error = error * error batch_size = tf.shape(labels)[0] error = tf.reshape(error, (batch_size, -1)) return tf.reduce_mean(error, axis=1)
[ 11748, 11192, 273, 11125, 355, 48700, 198, 11748, 299, 32152, 355, 45941, 198, 198, 36, 3705, 796, 352, 68, 12, 20, 628, 198, 4299, 48253, 62, 2144, 660, 62, 7718, 5439, 7, 89, 11, 1612, 11, 264, 13495, 28, 14202, 11, 2604, 62, 82...
2.236291
2,006
from tkinter import * import os, xmltodict, requests def knop1(): 'Open GUI huidig station' global root root.destroy() os.system('Huidig_Station.py') def knop2(): 'Open GUI ander station' global root root.destroy() os.system('Ander_Station.py') def nl_to_eng(): 'Wanneer er op de Engelse vlag wordt gedrukt veranderd de Nederlandstalige tekst naar het Engels' button1['text'] = 'Departure\ntimes current station' button2['text'] = 'Departure\ntimes other station' welkomlabel['text'] = 'Welcome to NS' photo['file'] = 'afbeeldingen\kaartlezerengels.PNG' def eng_to_nl(): 'Wanneer er op de Nederlandse vlag wordt gedrukt veranderd de Engelstalige tekst naar het Nederlands' button1['text'] = 'Actuele vertrektijden\nhuidig station' button2['text'] = 'Actuele vertrektijden\nander station' welkomlabel['text'] = 'Welkom bij NS' photo['file'] = 'afbeeldingen\kaartlezer.PNG' root = Tk() # Maakt het venster root.attributes('-fullscreen',True) #Open fullscreen hoofdframe = Frame(master=root, #Venster gele gedeelte background='#FFD720', width=1920, height=980) hoofdframe.pack(side='top', fill=X) onderframe = Frame(master=root, #Venster blauwe gedeelte background='#001F6A', width=1920, height=100) onderframe.pack(side='bottom', fill=X) welkomlabel = Label(master=hoofdframe, #Welkom bij NS tekst text='Welkom bij NS', foreground='#001F6A', background='#FFD720', font=('Helvetica', 60, 'bold'), width=14, height=3) welkomlabel.place(x=615, y=50) photo = PhotoImage(file='afbeeldingen\kaartlezer.PNG') #Foto kaartlezer fotolabel = Label(master=hoofdframe, image=photo, borderwidth=-1) fotolabel.place(x=745, y=320) button1 = Button(master=hoofdframe, #Knop 2 text="Actuele vertrektijden\nhuidig station", foreground="white", background="#001F6A", font=('arial', 12, 'bold'), width=17, height=3, command=knop1) button1.place(x=765, y=650) button2 = Button(master=hoofdframe, #Knop 3 text="Actuele vertrektijden\nander station", foreground="white", background="#001F6A", font=('arial', 12, 'bold'), width=17, height=3, command=knop2) button2.place(x=965, y=650) buttonNL = Button (master=onderframe, #Knop van Engels naar Nederlands width=10, height=10, command=eng_to_nl) photoNL = PhotoImage (file='afbeeldingen\kroodwitblauw.png') buttonNL.config(image=photoNL, #Het converteren dat de afbeelding een knop wordt width=48, height=25) buttonNL.place(x=50, y=25) labelengels = Label(master=onderframe, #Label onder de Engelse vlag text='English', foreground='white', background='#001F6A', font=('arial', 9)) labelengels.place(x=128, y=55) buttonENG = Button (master=onderframe, #Knop van Nederlands naar Engels width=10, height=10, command=nl_to_eng) photoENG = PhotoImage (file='afbeeldingen\kengenland.png') buttonENG.config(image=photoENG, #Het converteren dat de afbeelding een knop wordt width=48, height=25) buttonENG.place(x=125, y=25) labelnederlands = Label(master=onderframe, #Label onder de Nederlandse vlag text='Nederlands', foreground='white', background='#001F6A', font=('arial', 9)) labelnederlands.place(x=42, y=55) root.mainloop()
[ 6738, 256, 74, 3849, 1330, 1635, 198, 11748, 28686, 11, 2124, 76, 2528, 375, 713, 11, 7007, 628, 198, 198, 4299, 638, 404, 16, 33529, 198, 220, 220, 220, 705, 11505, 25757, 289, 27112, 328, 4429, 6, 198, 220, 220, 220, 3298, 6808, ...
1.823905
2,351
from .py2ifttt import IFTTT
[ 6738, 764, 9078, 17, 361, 926, 83, 1330, 314, 9792, 15751 ]
2.454545
11
import socket import tokens import connection import io import os from PIL import Image from message.literalMessage import LiteralMessage from baseApplication import BaseApplication host = input('Host: ') ClientApplication(host, 50007)
[ 11748, 17802, 201, 198, 11748, 16326, 201, 198, 11748, 4637, 201, 198, 11748, 33245, 201, 198, 11748, 28686, 201, 198, 6738, 350, 4146, 1330, 7412, 201, 198, 6738, 3275, 13, 18250, 1691, 12837, 1330, 25659, 1691, 12837, 201, 198, 6738, ...
3.671642
67
import sys import socket ETH_P_ALL=3 # not defined in socket module, sadly... s=socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(ETH_P_ALL)) s.bind((sys.argv[1], 0)) r=s.recv(2000) sys.stdout.write("<%s>\n"%repr(r))
[ 11748, 25064, 198, 11748, 17802, 198, 198, 20702, 62, 47, 62, 7036, 28, 18, 1303, 407, 5447, 287, 17802, 8265, 11, 21098, 986, 198, 82, 28, 44971, 13, 44971, 7, 44971, 13, 8579, 62, 47, 8120, 2767, 11, 17802, 13, 50, 11290, 62, 20...
2.254902
102
#!/usr/bin/env python3 from json import loads from urllib.request import urlopen, Request SITE = input('Site: ') COOKIE = 'pj=' + input('pj=') examList = loads(urlopen(Request(f'{SITE}/data/module/homework/all.asp?sAct=GetHomeworkListByStudent&iIsExam=1&iPageCount=' + loads(urlopen(Request(f'{SITE}/data/module/homework/all.asp?sAct=GetHomeworkListByStudent&iIsExam=1', headers={'Cookie': COOKIE})).read())['iCount'], headers={'Cookie': COOKIE})).read()) assert examList['sRet'] == 'succeeded', examList for exam in examList['aHomework']: if not exam['sTimeFlag'] and not int(exam['iFinished']): examContent = loads(urlopen(Request(f'{SITE}/data/module/exam/all.asp?sAct=GetExamContent&iExamId=' + exam['sQuestionIds'], headers={'Cookie': COOKIE})).read()) assert examContent['sRet'] == 'succeeded', examContent try: for content in examContent['aContent']: print(content['sTitle']) for process in examContent['aProcess']: print(process['iOrder'], process['sAnswer'], sep='\t') except IndexError: pass
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 6738, 33918, 1330, 15989, 198, 6738, 2956, 297, 571, 13, 25927, 1330, 19016, 9654, 11, 19390, 628, 198, 50, 12709, 796, 5128, 10786, 29123, 25, 705, 8, 198, 34, 15308, 10008, ...
2.376874
467
import sys import os import tkinter.filedialog as fd from time import sleep import datetime import tkinter import tkinter as tk from tkinter import ttk from tkinter import scrolledtext import threading # New File & Duplicate File Save # FileSave
[ 11748, 25064, 198, 11748, 28686, 198, 11748, 256, 74, 3849, 13, 69, 3902, 498, 519, 355, 277, 67, 198, 6738, 640, 1330, 3993, 198, 11748, 4818, 8079, 198, 11748, 256, 74, 3849, 198, 11748, 256, 74, 3849, 355, 256, 74, 198, 6738, 256...
3
86
#!/usr/bin/python # # Copyright 2018-2021 Polyaxon, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import click from polyaxon.logger import logger
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 198, 2, 15069, 2864, 12, 1238, 2481, 12280, 897, 261, 11, 3457, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, ...
3.595628
183
# -*- coding: utf-8 -*- # AUTHOR: Zeray Rice <fanzeyi1994@gmail.com> # FILE: judge/base/__init__.py # CREATED: 01:49:33 08/03/2012 # MODIFIED: 15:42:49 19/04/2012 # DESCRIPTION: Base handler import re import time import urllib import hashlib import httplib import datetime import functools import traceback import simplejson as json from operator import itemgetter from pygments import highlight from pygments.lexers import CLexer from pygments.lexers import CppLexer from pygments.lexers import DelphiLexer from pygments.formatters import HtmlFormatter from sqlalchemy.exc import StatementError from sqlalchemy.orm.exc import NoResultFound import tornado.web import tornado.escape from tornado.httpclient import AsyncHTTPClient from judge.db import Auth from judge.db import Member from judge.utils import _len CODE_LEXER = { 1 : DelphiLexer, 2 : CLexer, 3 : CppLexer, } CODE_LANG = { 1 : "delphi", 2 : "c", 3 : "cpp", } def unauthenticated(method): """Decorate methods with this to require that user be NOT logged in""" return wrapper
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 220, 198, 2, 44746, 25, 37028, 323, 13823, 1279, 24408, 2736, 48111, 22666, 31, 14816, 13, 785, 29, 198, 2, 45811, 25, 5052, 14, 8692, 14, 834, 15003, 834, 13, 9078, 198, ...
2.900804
373
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import markdownx.models import myblog.filename from django.conf import settings
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 11, 15720, 602, 198, 11748, 1317, 2902, 87, 13, 27530, 19...
3.224138
58
test = {'name': 'q6', 'points': 10, 'suites': [{'cases': [{'code': '>>> increment = lambda x: x + 1\n' '\n' '>>> square = lambda x: x * x\n' '\n' '>>> do_nothing = make_zipper(increment, ' 'square, 0)\n' '\n' ">>> do_nothing(2) # Don't call either f1 or " 'f2, just return your input untouched\n' '2\n' '\n' '>>> incincsq = make_zipper(increment, square, ' '112)\n' '\n' '>>> incincsq(2) # ' 'increment(increment(square(2))), so 2 -> 4 -> ' '5 -> 6\n' '6\n' '\n' '>>> sqincsqinc = make_zipper(increment, ' 'square, 2121)\n' '\n' '>>> sqincsqinc(2) # ' 'square(increment(square(increment(2)))), so 2 ' '-> 3 -> 9 -> 10 -> 100\n' '100\n'}], 'scored': True, 'setup': 'from q6 import *', 'type': 'doctest'}]}
[ 9288, 796, 1391, 6, 3672, 10354, 705, 80, 21, 3256, 198, 705, 13033, 10354, 838, 11, 198, 705, 2385, 2737, 10354, 685, 90, 6, 33964, 10354, 685, 90, 6, 8189, 10354, 705, 33409, 18703, 796, 37456, 2124, 25, 2124, 1343, 352, 59, 77, ...
1.356453
1,139
""" This problem was asked by Google. Suppose we represent our file system by a string in the following manner: The string "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext" represents: dir subdir1 subdir2 file.ext The directory dir contains an empty sub-directory subdir1 and a sub-directory subdir2 containing a file file.ext. The string "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext" represents: dir subdir1 file1.ext subsubdir1 subdir2 subsubdir2 file2.ext The directory dir contains two sub-directories subdir1 and subdir2. subdir1 contains a file file1.ext and an empty second-level sub-directory subsubdir1. subdir2 contains a second-level sub-directory subsubdir2 containing a file file2.ext. We are interested in finding the longest (number of characters) absolute path to a file within our file system. For example, in the second example above, the longest absolute path is "dir/subdir2/subsubdir2/file2.ext", and its length is 32 (not including the double quotes). Given a string representing the file system in the above format, return the length of the longest absolute path to a file in the abstracted file system. If there is no file in the system, return 0. Note: The name of a file contains at least a period and an extension. The name of a directory or sub-directory will not contain a period. """ # I am assuming that the number of t's in /n/t/t/t.../t/ stands for the level in the tree # Furthermore, I am assuming the format of the string to be consistent # last but not least I'll make the assumption that this is actually a tree, i.e., it has no cycles # top level idea: deserialize the tree and then perform the operation on it if __name__ == '__main__': print()
[ 37811, 198, 1212, 1917, 373, 1965, 416, 3012, 13, 198, 198, 15979, 577, 356, 2380, 674, 2393, 1080, 416, 257, 4731, 287, 262, 1708, 5642, 25, 198, 198, 464, 4731, 366, 15908, 59, 77, 59, 912, 549, 15908, 16, 59, 77, 59, 912, 549, ...
3.111876
581
from os.path import expanduser, exists from os import makedirs TURBOT_PATH = expanduser('~/.turbot') UPVOTE_LOGS = expanduser("%s/upvote_logs" % TURBOT_PATH) CHECKPOINT = expanduser("%s/checkpoint" % TURBOT_PATH) REFUND_LOG = expanduser("%s/refunds" % TURBOT_PATH)
[ 6738, 28686, 13, 6978, 1330, 4292, 7220, 11, 7160, 198, 6738, 28686, 1330, 285, 4335, 17062, 198, 198, 51, 4261, 33, 2394, 62, 34219, 796, 4292, 7220, 10786, 93, 11757, 83, 5945, 313, 11537, 198, 8577, 53, 23051, 62, 25294, 50, 796, ...
2.40708
113
from output.models.ms_data.additional.member_type021_xsd.member_type021 import Root __all__ = [ "Root", ]
[ 6738, 5072, 13, 27530, 13, 907, 62, 7890, 13, 2860, 1859, 13, 19522, 62, 4906, 46821, 62, 87, 21282, 13, 19522, 62, 4906, 46821, 1330, 20410, 198, 198, 834, 439, 834, 796, 685, 198, 220, 220, 220, 366, 30016, 1600, 198, 60, 198 ]
2.581395
43
reportedCases=eval(input('Enter the number of reported cases:-')) name=input('Enter the name of the region:-') days=eval(input('Enter the number of days:-')) totalHospitalbeds=eval(input('Enter the total number of beds available in the region:')) avgDailyIncomeInUsd=eval(input('Enter the Average income:-')) avgDailyIncomePopulation=eval(input('Enter the average daily income of the population:-'))/100 reportedCases=674 name="Africa" days=28 totalHospitalbeds=1380614 avgDailyIncomeInUsd=1.5 avgDailyIncomePopulation=0.65
[ 628, 198, 26263, 34, 1386, 28, 18206, 7, 15414, 10786, 17469, 262, 1271, 286, 2098, 2663, 25, 19355, 4008, 198, 3672, 28, 15414, 10786, 17469, 262, 1438, 286, 262, 3814, 21912, 11537, 198, 12545, 28, 18206, 7, 15414, 10786, 17469, 262, ...
3.090395
177
#!/usr/bin/env python3 # Original Author @elitest # This script uses boto3 to perform client side decryption # of data encryption keys and associated files # and encryption in ways compatible with the AWS SDKs # This support is not available in boto3 at this time # Wishlist: # Currently only tested with KMS managed symmetric keys. # Error checking import boto3, argparse, base64, json from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import padding from cryptography.hazmat.primitives.ciphers import ( Cipher, algorithms, modes ) # Build the parser argparser = argparse.ArgumentParser(description='Prints info about deleted items in s3 buckets and helps you download them.') argparser.add_argument('bucket', help='The bucket that contains the file.') argparser.add_argument('region', help='The region the CMK is in.') argparser.add_argument('key', help='The name of the file that you would like to download and decrypt.') argparser.add_argument('--profile', default='default', help='The profile name in ~/.aws/credentials') args = argparser.parse_args() # Set variables from arguments bucket = args.bucket region = args.region profile = args.profile key = args.key # Setup AWS clients boto3.setup_default_session(profile_name=profile, region_name=region) s3_client = boto3.client('s3') response = s3_client.get_object(Bucket=bucket,Key=key) kms_client = boto3.client('kms') # This function decrypts the encrypted key associated with the file # and decrypts it # Decrypt the DEK plaintextDek = decrypt_dek(response) # Get the encrypted body # Haven't tested with large files body=response['Body'].read() # We need the content length for GCM to build the tag contentLen = response['Metadata']['x-amz-unencrypted-content-length'] # IV iv = base64.b64decode(response['Metadata']['x-amz-iv']) # Algorithm alg = response['Metadata']['x-amz-cek-alg'] # This splits the tag and data from the body if GCM if alg == 'AES/GCM/NoPadding': data = body[0:int(contentLen)] tagLen = response['Metadata']['x-amz-tag-len'] tag = body[int(contentLen):int(tagLen)] else: data = body[:] tag = '' # Decrypt the file plaintext = decrypt(plaintextDek,alg,iv,data,tag) print(plaintext)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 13745, 6434, 2488, 417, 270, 395, 198, 198, 2, 770, 4226, 3544, 275, 2069, 18, 284, 1620, 5456, 1735, 875, 13168, 198, 2, 286, 1366, 15835, 8251, 290, 3917, 3696, 198, 2, 29...
3.165254
708
from IPython.display import HTML #TO DO - the nested table does not display? #Also, the nested execution seems to take a long time to run? #Profile it to see where I'm going wrong!
[ 6738, 6101, 7535, 13, 13812, 1330, 11532, 628, 198, 2, 10468, 8410, 532, 262, 28376, 3084, 857, 407, 3359, 30, 198, 2, 7583, 11, 262, 28376, 9706, 2331, 284, 1011, 257, 890, 640, 284, 1057, 30, 198, 2, 37046, 340, 284, 766, 810, 3...
3.755102
49
from turtle import width import streamlit as st import numpy as np import pandas as pd from dis import dis import streamlit as st from data.get_saved_library import get_saved_library, display_user_name, display_user_pic from data.get_recently_played import get_recently_played from data.get_top_artists import get_top_artists, get_related_artists, get_top_artists_tracks_features, NormalizeData, draw_feature_plot from data.image_url import path_to_image_html from PIL import Image import requests from io import BytesIO from IPython.core.display import HTML import streamlit.components.v1 as components import plotly.express as px from subpage import SubPage from pages import welcome, artists_top_saved, artists_select_random # @st.cache
[ 6738, 28699, 1330, 9647, 198, 11748, 4269, 18250, 355, 336, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 595, 1330, 595, 198, 11748, 4269, 18250, 355, 336, 198, 6738, 1366, 13, 1136, 62, 82, 958...
3.279476
229
# Author: allannozomu # Runtime: 56 ms # Memory: 13 MB
[ 2, 6434, 25, 477, 1236, 8590, 296, 84, 198, 2, 43160, 25, 7265, 13845, 198, 2, 14059, 25, 1511, 10771, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220 ]
2.030303
33
import pytest from models.contact_number import ContactNumberModel
[ 11748, 12972, 9288, 198, 6738, 4981, 13, 32057, 62, 17618, 1330, 14039, 15057, 17633, 628, 198 ]
4.3125
16
import unittest import numpy as np from sciquence.sequences import * if __name__ == '__main__': unittest.main()
[ 11748, 555, 715, 395, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 629, 1557, 594, 13, 3107, 3007, 1330, 1635, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 555, 715, 395, 13, 12417, 3419, ...
2.767442
43
# -*- coding: utf-8 -*- """ Simple example using BarGraphItem """ # import initExample ## Add path to library (just for examples; you do not need this) import numpy as np import pickle as p import pandas as pd from analysis_guis.dialogs.rotation_filter import RotationFilter from analysis_guis.dialogs import config_dialog from analysis_guis.dialogs.info_dialog import InfoDialog from rotation_analysis.analysis.probe.probe_io.probe_io import TriggerTraceIo, BonsaiIo, IgorIo from PyQt5.QtWidgets import QApplication from datetime import datetime from dateutil import parser import analysis_guis.calc_functions as cfcn import analysis_guis.rotational_analysis as rot import matplotlib.pyplot as plt from pyphys.pyphys.pyphys import PxpParser from collections import OrderedDict import analysis_guis.common_func as cf import pyqtgraph as pg from pyqtgraph.Qt import QtCore, QtGui date2sec = lambda t: np.sum([3600 * t.hour, 60 * t.minute, t.second]) trig_count = lambda data, cond: len(np.where(np.diff(data[cond]['cpg_ttlStim']) > 1)[0]) + 1 get_bin_index = lambda x, y: next((i for i in range(len(y)) if x < y[i]), len(y)) - 1 def setup_polar_spike_freq(r_obj, sFreq, b_sz, is_pos): ''' :param wvPara: :param tSpike: :param sFreq: :param b_sz: :return: ''' # memory allocation wvPara, tSpike = r_obj.wvm_para[i_filt], r_obj.t_spike[i_filt], ind_inv, xi_bin_tot = np.empty(2, dtype=object), np.empty(2, dtype=object) # calculates the bin times xi_bin_tot[0], t_bin, t_phase = rot.calc_wave_kinematic_times(wvPara[0][0], b_sz, sFreq, is_pos, yDir=-1) xi_bin_tot[1], dt_bin = -xi_bin_tot[0], np.diff(t_bin) # determines the bin indices for i in range(2): xi_mid, ind_inv[i] = np.unique(0.5 * (xi_bin_tot[i][:-1] + xi_bin_tot[i][1:]), return_inverse=True) # memory allocation yDir = wvPara[0]['yDir'] n_trial, n_bin = len(yDir), len(xi_mid) tSp_bin = np.zeros((n_bin, n_trial)) # for i_trial in range(n_trial): # combines the time spikes in the order that the CW/CCW phases occur ii = int(yDir[i_trial] == 1) tSp = np.hstack((tSpike[1 + ii][i_trial], tSpike[2 - ii][i_trial] + t_phase)) # appends the times t_hist = np.histogram(tSp, bins=t_bin) for j in range(len(t_hist[0])): i_bin = ind_inv[ii][j] tSp_bin[i_bin, i_trial] += t_hist[0][j] / (2.0 * dt_bin[j]) # returns the final bin return xi_mid, tSp_bin ## Start Qt event loop unless running in interactive mode or using pyside. if __name__ == '__main__': # loads the data for testing with open('C:\\Work\\EPhys\\Code\\Sepi\\wvPara.p', 'rb') as fp: wvPara = p.load(fp) tSpike = p.load(fp) # sFreq = 30000 kb_sz = 10 title_str = ['Displacement', 'Velocity'] lg_str = ['Type 1', 'Type 2', 'Type 3'] # memory allocation n_filt = len(wvPara) c = cf.get_plot_col(n_filt) # fig = plt.figure() ax = np.empty(2, dtype=object) # for i_type in range(2): # sets up the spiking frequency arrays tSp_bin = np.empty(n_filt, dtype=object) for i_filt in range(n_filt): xi_mid, tSp_bin[i_filt] = setup_polar_spike_freq(wvPara[i_filt], tSpike[i_filt], sFreq, kb_sz, i_type==0) # xi_min = xi_mid[0] - np.diff(xi_mid[0:2])[0]/2 theta = np.pi * (1 - (xi_mid - xi_min) / np.abs(2 * xi_min)) x_tick = np.linspace(xi_min, -xi_min, 7 + 2 * i_type) # creates the subplot ax[i_type] = plt.subplot(1, 2, i_type + 1, projection='polar') ax[i_type].set_thetamin(0) ax[i_type].set_thetamax(180) # creates the radial plots for each of the filter types h_plt = [] for i_filt in range(n_filt): # creates the plot and resets the labels tSp_mn = np.mean(tSp_bin[i_filt], axis=1) h_plt.append(ax[i_type].plot(theta, tSp_mn, 'o-', c=c[i_filt])) # sets the axis properties (first filter only) if i_filt == 0: ax[i_type].set_title(title_str[i_type]) ax[i_type].set_xticks(np.pi * (x_tick - xi_min) / np.abs(2 * xi_min)) ax[i_type].set_xticklabels([str(int(np.round(-x))) for x in x_tick]) # sets the legend (first subplot only) if i_type == 0: ax[i_type].legend(lg_str, loc=1) # determines the overall radial maximum (over all subplots) and resets the radial ticks y_max = [max(x.get_ylim()) for x in ax] i_max = np.argmax(y_max) dy = np.diff(ax[i_max].get_yticks())[0] y_max_tot = dy * (np.floor(y_max[i_max] / dy) + 1) # resets the axis radial limits for x in ax: x.set_ylim(0, y_max_tot) # shows the plot plt.show() a = 1 # app = QApplication([]) # h_obj = RotationFilter(data) # h_obj = InfoDialog(data) # a = 1 # # # igor_waveforms_path = 'G:\\Seagate\\Work\\EPhys\\Data\\CA326_C_day3\\Igor\\CA326_C_day3' # bonsai_metadata_path = 'G:\\Seagate\\Work\\EPhys\\Data\\CA326_C_day3\\Bonsai\\CA326_C_day3_all.csv' # # # # file_time_key = 'FileTime' # bonsai_io = BonsaiIo(bonsai_metadata_path) # # # # determines the indices of the experiment condition triel group # t_bonsai = [parser.parse(x) for x in bonsai_io.data['Timestamp']] # t_bonsai_sec = np.array([date2sec(x) for x in t_bonsai]) # d2t_bonsai = np.diff(t_bonsai_sec, 2) # grp_lim = grp_lim = [-1] + list(np.where(d2t_bonsai > 60)[0] + 1) + [len(d2t_bonsai) + 1] # ind_grp = [np.arange(grp_lim[x] + 1, grp_lim[x + 1] + 1) for x in range(len(grp_lim) - 1)] # # # sets the time, name and trigger count from each of these groups # t_bonsai_grp = [t_bonsai_sec[x[0]] for x in ind_grp] # c_bonsai_grp = [bonsai_io.data['Condition'][x[0]] for x in ind_grp] # n_trig_bonsai = [len(x) for x in ind_grp] # # # determines the feasible variables from the igor data file # igor_data = PxpParser(igor_waveforms_path) # var_keys = list(igor_data.data.keys()) # is_ok = ['command' in igor_data.data[x].keys() if isinstance(igor_data.data[x], OrderedDict) else False for x in var_keys] # # # sets the name, time and trigger count from each of the igor trial groups # c_igor_grp = [y for x, y in zip(is_ok, var_keys) if x] # t_igor_grp, t_igor_str, n_trig_igor = [], [], [trig_count(igor_data.data, x) for x in c_igor_grp] # for ck in c_igor_grp: # t_igor_str_nw = igor_data.data[ck]['vars'][file_time_key][0] # t_igor_str.append(t_igor_str_nw) # t_igor_grp.append(date2sec(datetime.strptime(t_igor_str_nw, '%H:%M:%S').time())) # # # calculates the point-wise differences between the trial timer and trigger count # dt_grp = cfcn.calc_pointwise_diff(t_igor_grp, t_bonsai_grp) # dn_grp = cfcn.calc_pointwise_diff(n_trig_igor, n_trig_bonsai) # # # ensures that only groups that have equal trigger counts are matched # dt_max = np.max(dt_grp) + 1 # dt_grp[dn_grp > 0] = dt_max # # # # iter = 0 # while 1: # i2b = np.argmin(dt_grp, axis=1) # i2b_uniq, ni2b = np.unique(i2b, return_counts=True) # # ind_multi = np.where(ni2b > 1)[0] # if len(ind_multi): # if iter == 0: # for ii in ind_multi: # jj = np.where(i2b == i2b_uniq[ii])[0] # # imn = np.argmin(dt_grp[jj, i2b[ii]]) # for kk in jj[jj != jj[imn]]: # dt_grp[kk, i2b[ii]] = dt_max # else: # pass # else: # break # # # sets the igor-to-bonsai name groupings # i2b_key, x = {}, np.array(c_igor_grp)[i2b] # for cc in c_bonsai_grp: # if cc not in i2b_key: # jj = np.where([x == cc for x in c_bonsai_grp])[0] # i2b_key[cc] = x[jj]
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 201, 198, 37811, 201, 198, 26437, 1672, 1262, 2409, 37065, 7449, 201, 198, 37811, 201, 198, 2, 1330, 2315, 16281, 22492, 3060, 3108, 284, 5888, 357, 3137, 329, 6096, 26, 345,...
1.975163
4,147
""" downloads gmail atts """ import base64, os from auth.auth import get_service from msg.label import agencies, get_atts from report.response import get_threads, get_status from att.drive import get_or_create_atts_folder,\ check_if_drive, make_drive_folder, upload_to_drive ### START CONFIG ### buffer_path = '/tmp/' ### END CONFIG ### gmail_service = get_service(type='gmail') def roll_thru(): """ controller function rolls through each agency: - checks if already filed in Drive - checks if labeled done ... if neither: - makes Drive folder - downloads buffer file to this server - uploads file to Drive folder - deleteds buffer file TODO: optimize by check_if_drive first before getting threads """ atts_drive_folder = get_or_create_atts_folder() for agency in agencies: try: threads = get_threads(agency) if not check_if_drive(agency.replace("'","")) and check_if_done(threads,agency): # no apostrophes allowed # only proceed if agency is done, has atts and not already in drive atts = get_agency_atts(threads) if atts: print agency drive_folder = make_drive_folder(agency.replace("'",""),atts_drive_folder) # no apostrophes allowed for att in atts: path = download_buffer_file(att) upload_to_drive(att, drive_folder) os.remove(path) else: print 'skipping', agency except Exception, e: print agency,'failed',e def check_if_done(threads,agency): """ checks if this agency's threads include any messages labeled 'done' """ return get_status(threads,agency) == 'done' def get_agency_atts(threads): """ given a list of threads, iterates through messages, finds attachments and appends att data to atts list """ atts = [] for thread in threads: for msg in gmail_service.users().threads().get(\ id=thread['id'],userId='me').execute().get('messages'): for att in get_atts(msg): atts.append({'att_id':att['body']['attachmentId'],'msg_id':msg['id'],'file_name':att['filename']}) return atts def download_buffer_file(att): """ downloads specified att to buffer file and returns path """ attachment = gmail_service.users().messages().attachments().get(\ id=att['att_id'],messageId=att['msg_id'],userId='me').execute() file_data = base64.urlsafe_b64decode(attachment['data'].encode('UTF-8')) buffer_file_path = buffer_path + att['file_name'] buffer_file = open(buffer_file_path,'w') buffer_file.write(file_data) buffer_file.close() return buffer_file_path
[ 37811, 198, 15002, 82, 308, 4529, 708, 82, 198, 37811, 198, 198, 11748, 2779, 2414, 11, 28686, 198, 6738, 6284, 13, 18439, 1330, 651, 62, 15271, 198, 6738, 31456, 13, 18242, 1330, 5942, 11, 651, 62, 30353, 198, 6738, 989, 13, 26209, ...
2.404722
1,186
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import absolute_import from pex.pip.log_analyzer import LogAnalyzer from pex.typing import TYPE_CHECKING, Generic if TYPE_CHECKING: from typing import Iterable, Mapping, Optional, Text import attr # vendor:skip else: from pex.third_party import attr if TYPE_CHECKING: from typing import TypeVar _L = TypeVar("_L", bound=LogAnalyzer)
[ 2, 15069, 33160, 41689, 1628, 20420, 357, 3826, 27342, 9865, 3843, 20673, 13, 9132, 737, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 3826, 38559, 24290, 737, 198, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 1...
3.109756
164
from typing import Any from typing import Callable from typing import Iterable class NextDispatch(Exception): pass class DispatcherType(type): class Dispatcher(FunctionMixin, metaclass=DispatcherType): dispatch: callable register: callable registry: Iterable class MetaDispatcher(FunctionMixin, metaclass=DispatcherType): dispatch: callable register: callable registry: Iterable class DispatchedCallable(FunctionMixin, _PrioritySortable):
[ 6738, 19720, 1330, 4377, 198, 6738, 19720, 1330, 4889, 540, 198, 6738, 19720, 1330, 40806, 540, 628, 628, 198, 198, 4871, 7406, 49354, 7, 16922, 2599, 198, 220, 220, 220, 1208, 628, 198, 4871, 3167, 8071, 2044, 6030, 7, 4906, 2599, 62...
3.2
150
from pbpstats.resources.enhanced_pbp import StartOfPeriod
[ 6738, 279, 46583, 34242, 13, 37540, 13, 16550, 2903, 62, 40842, 79, 1330, 7253, 5189, 5990, 2101, 628 ]
3.277778
18
# Copyright 2015 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import netaddr from tempest_lib.common.utils import data_utils from tempest_lib import exceptions from tempest.api.network import base from tempest import config from tempest import test CONF = config.CONF def get_subnet_create_options(network_id, ip_version=4, gateway='', cidr=None, mask_bits=None, num_subnet=1, gateway_offset=1, cidr_offset=0, **kwargs): """When cidr_offset>0 it request only one subnet-options: subnet = get_subnet_create_options('abcdefg', 4, num_subnet=4)[3] subnet = get_subnet_create_options('abcdefg', 4, cidr_offset=3) """ gateway_not_set = (gateway == '') if ip_version == 4: cidr = cidr or netaddr.IPNetwork(CONF.network.tenant_network_cidr) mask_bits = mask_bits or CONF.network.tenant_network_mask_bits elif ip_version == 6: cidr = ( cidr or netaddr.IPNetwork(CONF.network.tenant_network_v6_cidr)) mask_bits = mask_bits or CONF.network.tenant_network_v6_mask_bits # Find a cidr that is not in use yet and create a subnet with it subnet_list = [] if cidr_offset > 0: num_subnet = cidr_offset + 1 for subnet_cidr in cidr.subnet(mask_bits): if gateway_not_set: gateway_ip = gateway or ( str(netaddr.IPAddress(subnet_cidr) + gateway_offset)) else: gateway_ip = gateway try: subnet_body = dict( network_id=network_id, cidr=str(subnet_cidr), ip_version=ip_version, gateway_ip=gateway_ip, **kwargs) if num_subnet <= 1: return subnet_body subnet_list.append(subnet_body) if len(subnet_list) >= num_subnet: if cidr_offset > 0: # user request the 'cidr_offset'th of cidr return subnet_list[cidr_offset] # user request list of cidr return subnet_list except exceptions.BadRequest as e: is_overlapping_cidr = 'overlaps with another subnet' in str(e) if not is_overlapping_cidr: raise else: message = 'Available CIDR for subnet creation could not be found' raise exceptions.BuildErrorException(message) return {}
[ 2, 15069, 1853, 4946, 25896, 5693, 198, 2, 1439, 6923, 33876, 13, 198, 2, 198, 2, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 220, 220, 220, 407, 779, 428, ...
2.18404
1,391
#!/usr/bin/env python # coding: utf-8 # In[2]: from collections import defaultdict import csv import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt # ## read data to numpy(not in use) # In[385]: # def readCsvToNumpy(file_name, feat_num): # util_mat = [] # with open(file_name, newline='', encoding='utf-8') as csvfile: # next(csvfile, None) # rd = csv.reader(csvfile, delimiter=' ', quotechar='|') # for idx, row in enumerate(rd): # row = (' '.join(row)) # row = row.split(',') # if len(row) == feat_num: # util_mat.append(row) # # convert 2d list to 2d numpy array # for idx, row in enumerate(util_mat): # util_mat[idx] = np.asarray(row) # util_mat = np.asarray(util_mat) # return util_mat # def getPlayerMatrix(util_mat, left_idx, right_idx): # player_mat = util_mat[:, left_idx:right_idx] # player_mat = player_mat.astype(int) # return player_mat # def getTeamMatrix(util_mat, player_mat, team_idx): # hashmap = defaultdict(list) # for idx, item in enumerate(util_mat): # hashmap[util_mat[idx, team_idx]].append(player_mat[idx, :]) # team_mat = [] # # print('Team number', len(hashmap)) # for key, value in hashmap.items(): # team_avr = [sum(x)/len(value) for x in zip(*value)] # team_mat.append(team_avr) # # team_mat.append((key, temp)) # # for idx, item in enumerate(team_mat): # # if item[0] == 'Arsenal': # # print(idx, item) # # convert team feature matrix to numpy matrix # for idx, row in enumerate(team_mat): # team_mat[idx] = np.asarray(row, dtype=int) # team_mat = np.asarray(team_mat, dtype=int); # return team_mat # if __name__ == "__main__": # util_mat = readCsvToNumpy('data_clean.csv', 74) # # print(util_mat.shape, util_mat) # player_mat = getPlayerMatrix(util_mat, 44, 73) # # print(player_mat.shape, player_mat) # team_mat = getTeamMatrix(util_mat, player_mat, 6) # # print(team_mat[0, :]) # res = np.dot(player_mat, np.transpose(team_mat)) # # # print(hashmap['FC Barcelona']) # # print(res[0,:]) # ## read data to pandas Data frame # In[3]: util_df = pd.read_csv('data_clean.csv', na_filter=False) # print(util_df) player_df = util_df.iloc[:, 44:73] # print(player_df) team_df = util_df.groupby('Club', sort=False).mean() # print(team_df) team_df = team_df.iloc[:, 37:66] # print(team_df) res = np.dot(player_df, np.transpose(team_df)) # In[ ]: util_df.iloc[:,1] # In[54]: # util_df.describe() player_characteristics = ['Crossing','Finishing', 'HeadingAccuracy', 'ShortPassing', 'Volleys', 'Dribbling', 'Curve', 'FKAccuracy', 'LongPassing', 'BallControl', 'Acceleration', 'SprintSpeed', 'Agility', 'Reactions', 'Balance', 'ShotPower', 'Jumping', 'Stamina', 'Strength', 'LongShots', 'Aggression', 'Interceptions', 'Positioning', 'Vision', 'Penalties', 'Composure', 'Marking', 'StandingTackle', 'SlidingTackle'] plt.figure(figsize= (25, 16)) hm=sns.heatmap(util_df.loc[:, player_characteristics + ['Overall']].corr(), annot = True, linewidths=.5, cmap='Reds') hm.set_title(label='Heatmap of dataset', fontsize=20) hm; # corr_matrix = util_df.corr() # corr_matrix.loc[player_characteristics, 'LB'].sort_values(ascending=False).head()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 2, 554, 58, 17, 5974, 628, 198, 6738, 17268, 1330, 4277, 11600, 198, 11748, 269, 21370, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 1979...
2.083333
1,752
# -*- coding: utf-8 -*- from __future__ import absolute_import import keras.backend as K from time import sleep def _ternarize(W, H=1): '''The weights' ternarization function, # References: - [Recurrent Neural Networks with Limited Numerical Precision](http://arxiv.org/abs/1608.06902) - [Ternary Weight Networks](http://arxiv.org/abs/1605.04711) ''' W = W / H cutoff = 0.7*K.mean(K.abs(W)) # # TODO: is this ok?? ones = K.ones_like(W) zeros = K.zeros_like(W) Wt = switch(W > cutoff, ones, switch(W <= -cutoff, -ones, zeros)) Wt *= H return Wt def ternarize(W, H=1): '''The weights' ternarization function, # References: - [Recurrent Neural Networks with Limited Numerical Precision](http://arxiv.org/abs/1608.06902) - [Ternary Weight Networks](http://arxiv.org/abs/1605.04711) ''' Wt = _ternarize(W, H) return W + K.stop_gradient(Wt - W) def ternarize_dot(x, W): '''For RNN (maybe Dense or Conv too). Refer to 'Recurrent Neural Networks with Limited Numerical Precision' Section 3.1 ''' Wt = _ternarize(W) return K.dot(x, W) + K.stop_gradient(K.dot(x, Wt - W))
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 11748, 41927, 292, 13, 1891, 437, 355, 509, 198, 6738, 640, 1330, 3993, 628, 198, 4299, 4808, 759, 283, 1096, 7, 5...
2.370445
494
import asyncio cond = None p_list = [] # # if __name__ == "__main__": asyncio.run(main())
[ 11748, 30351, 952, 198, 198, 17561, 796, 6045, 198, 79, 62, 4868, 796, 17635, 628, 198, 2, 220, 628, 198, 2, 220, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 30351, 952, 13, 5143, 7,...
2.212766
47
from collections import Counter
[ 6738, 17268, 1330, 15034, 198, 220, 220, 220, 220, 220, 220, 220, 220 ]
3.076923
13
"""Mini-functions that do not belong elsewhere.""" from datetime import datetime
[ 37811, 39234, 12, 12543, 2733, 326, 466, 407, 5594, 8057, 526, 15931, 198, 6738, 4818, 8079, 1330, 4818, 8079, 628 ]
4.1
20
import flask_admin as admin # from flask_admin.contrib.sqla import ModelView from app import app # from app import db from models import * # Admin admin = admin.Admin(app) # Add Admin Views
[ 11748, 42903, 62, 28482, 355, 13169, 198, 2, 422, 42903, 62, 28482, 13, 3642, 822, 13, 31166, 5031, 1330, 9104, 7680, 198, 198, 6738, 598, 1330, 598, 198, 2, 422, 598, 1330, 20613, 198, 6738, 4981, 1330, 1635, 198, 198, 2, 32053, 19...
3.327586
58
# Generated by Django 3.0.6 on 2020-05-21 20:38 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 15, 13, 21, 319, 12131, 12, 2713, 12, 2481, 1160, 25, 2548, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.84375
32
import os # We should try to import any custom settings. SETTINGS_MODULE_NAME = os.getenv("MYPI_SETTINGS_MODULE") if SETTINGS_MODULE_NAME: SETTINGS_MODULE = import_module(SETTINGS_MODULE_NAME) else: SETTINGS_MODULE = object() # Try to get everything from the custom settings, but provide a default. PACKAGES_DIR = getattr(SETTINGS_MODULE, "PACKAGES_DIR", "./packages") SITE_TITLE = getattr(SETTINGS_MODULE, "SITE_TITLE", "Python Packages") SITE_URL_BASE = getattr(SETTINGS_MODULE, "SITE_URL_BASE", "") if SITE_URL_BASE.endswith("/"): SITE_URL_BASE = SITE_URL_BASE[:-1]
[ 11748, 28686, 628, 198, 198, 2, 775, 815, 1949, 284, 1330, 597, 2183, 6460, 13, 198, 28480, 51, 20754, 62, 33365, 24212, 62, 20608, 796, 28686, 13, 1136, 24330, 7203, 26708, 11901, 62, 28480, 51, 20754, 62, 33365, 24212, 4943, 198, 36...
2.483051
236
#!/usr/bin/env python # -*- coding: utf-8 -*- import simplejson as json from alipay.aop.api.constant.ParamConstants import *
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 2829, 17752, 355, 33918, 198, 198, 6738, 435, 541, 323, 13, 64, 404, 13, 15042, 13, 9979, 415, 13, 22973, 3418...
2.58
50
from __future__ import division # Use floating point for math calculations from flask import Blueprint from CTFd.models import ( ChallengeFiles, Challenges, Fails, Flags, Hints, Solves, Tags, db, ) from CTFd.plugins import register_plugin_assets_directory from CTFd.plugins.challenges import CHALLENGE_CLASSES, BaseChallenge from CTFd.plugins.flags import get_flag_class from CTFd.utils.uploads import delete_file from CTFd.utils.user import get_ip
[ 6738, 11593, 37443, 834, 1330, 7297, 220, 1303, 5765, 12462, 966, 329, 10688, 16765, 628, 198, 6738, 42903, 1330, 39932, 198, 198, 6738, 327, 10234, 67, 13, 27530, 1330, 357, 198, 220, 220, 220, 13879, 25876, 11, 198, 220, 220, 220, 4...
2.981595
163
shopping_list = { 'Tomatoes': 6, 'Bananas': 5, 'Crackers': 2, 'Sugar': 1, 'Icecream': 1, 'Bread': 3, 'Chocolate': 2 } # Just the keys print(shopping_list.keys()) # Just the values # print(shopping_list.values()) # Both keys and values # print(shopping_list.items())
[ 198, 1477, 33307, 62, 4868, 796, 1391, 198, 220, 220, 220, 705, 13787, 15048, 10354, 718, 11, 198, 220, 220, 220, 705, 30457, 15991, 10354, 642, 11, 198, 220, 220, 220, 705, 13916, 28874, 10354, 362, 11, 198, 220, 220, 220, 705, 50,...
2.322835
127
from .surface import * from .modifiers import * from .evaluator import Evaluator from .lowlevel import display_results
[ 6738, 764, 42029, 1330, 1635, 198, 6738, 764, 4666, 13350, 1330, 1635, 198, 6738, 764, 18206, 84, 1352, 1330, 26439, 84, 1352, 198, 6738, 764, 9319, 5715, 1330, 3359, 62, 43420, 198 ]
3.71875
32
import math from math import* print('enter a positive integer') FacMe=int(input()) primefacts=[1] if not isPrime(FacMe): if FacMe % 2==0: primefacts.append(2) if FacMe % 3==0: primefacts.append(3) for i in range(5,FacMe): if FacMe%i==0: if isPrime(i): primefacts.append(i) else: primefacts.append(FacMe) print(primefacts)
[ 11748, 10688, 201, 198, 6738, 10688, 1330, 9, 201, 198, 201, 198, 4798, 10786, 9255, 257, 3967, 18253, 11537, 201, 198, 47522, 5308, 28, 600, 7, 15414, 28955, 201, 198, 35505, 37473, 41888, 16, 60, 201, 198, 361, 407, 318, 26405, 7, ...
2.004902
204
# encoding: utf-8 """ binary butterfly validator Copyright (c) 2021, binary butterfly GmbH Use of this source code is governed by an MIT-style license that can be found in the LICENSE.txt. """ import re from typing import Any, Optional from ..abstract_input import AbstractInput from ..fields import Field from ..validators import Regexp from ..exceptions import ValidationError from ..external import HostnameValidation
[ 2, 21004, 25, 3384, 69, 12, 23, 198, 198, 37811, 198, 39491, 35113, 4938, 1352, 198, 15269, 357, 66, 8, 33448, 11, 13934, 35113, 402, 2022, 39, 198, 11041, 286, 428, 2723, 2438, 318, 21825, 416, 281, 17168, 12, 7635, 5964, 326, 460,...
3.863636
110
from runner.run_descriptions.run_description import RunDescription, Experiment, ParamGrid _params = ParamGrid([ ('prediction_bonus_coeff', [0.00, 0.05]), ]) _experiments = [ Experiment( 'doom_maze_very_sparse', 'python -m algorithms.curious_a2c.train_curious_a2c --env=doom_maze_very_sparse --gpu_mem_fraction=0.1 --train_for_env_steps=2000000000', _params.generate_params(randomize=False), ), # Experiment( # 'doom_maze_sparse', # 'python -m algorithms.curious_a2c.train_curious_a2c --env=doom_maze_sparse --gpu_mem_fraction=0.1 --train_for_env_steps=100000000', # _params.generate_params(randomize=False), # ), # Experiment( # 'doom_maze', # 'python -m algorithms.curious_a2c.train_curious_a2c --env=doom_maze --gpu_mem_fraction=0.1 --train_for_env_steps=50000000', # _params.generate_params(randomize=False), # ), # Experiment( # 'doom_basic', # 'python -m algorithms.curious_a2c.train_curious_a2c --env=doom_basic --gpu_mem_fraction=0.1 --train_for_env_steps=10000000', # _params.generate_params(randomize=False), # ), ] DOOM_CURIOUS_VS_VANILLA = RunDescription('doom_curious_vs_vanilla', experiments=_experiments, max_parallel=5)
[ 6738, 17490, 13, 5143, 62, 20147, 1968, 507, 13, 5143, 62, 11213, 1330, 5660, 11828, 11, 29544, 11, 25139, 41339, 198, 198, 62, 37266, 796, 25139, 41339, 26933, 198, 220, 220, 220, 19203, 28764, 2867, 62, 4189, 385, 62, 1073, 14822, 3...
2.255773
563
import os from xappt_qt.__version__ import __version__, __build__ from xappt_qt.plugins.interfaces.qt import QtInterface # suppress "qt.qpa.xcb: QXcbConnection: XCB error: 3 (BadWindow)" os.environ['QT_LOGGING_RULES'] = '*.debug=false;qt.qpa.*=false' version = tuple(map(int, __version__.split('.'))) + (__build__, ) version_str = f"{__version__}-{__build__}" executable = None
[ 11748, 28686, 198, 198, 6738, 2124, 1324, 83, 62, 39568, 13, 834, 9641, 834, 1330, 11593, 9641, 834, 11, 11593, 11249, 834, 198, 198, 6738, 2124, 1324, 83, 62, 39568, 13, 37390, 13, 3849, 32186, 13, 39568, 1330, 33734, 39317, 198, 198...
2.57047
149
#!/usr/bin/python3 import sys import sqlite3; import re; import os; import random import qualification from cttable import CandidateTable, TableVotingGroup, PhantomTableVotingGroup import cttable SW_VERSION_SPLIT = (1, 1, 4) SW_VERSION = ".".join([str(x) for x in SW_VERSION_SPLIT]) EARLIEST_COMPATIBLE_DB_VERSION = (0, 7, 0) RANK_WINS_POINTS = 0; RANK_POINTS = 1; RANK_WINS_SPREAD = 2; RATINGS_MANUAL = 0 RATINGS_GRADUATED = 1 RATINGS_UNIFORM = 2 CONTROL_NUMBER = 1 CONTROL_CHECKBOX = 2 UPLOAD_FAIL_TYPE_HTTP = 1 UPLOAD_FAIL_TYPE_REJECTED = 2 LOG_TYPE_NEW_RESULT = 1 LOG_TYPE_CORRECTION = 2 LOG_TYPE_COMMENT = 96 LOG_TYPE_COMMENT_VIDEPRINTER_FLAG = 1 LOG_TYPE_COMMENT_WEB_FLAG = 4 teleost_modes = [ { "id" : "TELEOST_MODE_AUTO", "name" : "Auto", "desc" : "Automatic control. This will show Fixtures at the start of a round, Standings/Videprinter during the round, and Standings/Table Results when all games in the round have been played.", "menuorder" : 0, "image" : "/images/screenthumbs/auto.png", "fetch" : [ "all" ] }, { "id" : "TELEOST_MODE_STANDINGS", "name" : "Standings", "desc" : "The current standings table and nothing else.", "image" : "/images/screenthumbs/standings_only.png", "menuorder" : 5, "fetch" : [ "standings" ] }, { "id" : "TELEOST_MODE_STANDINGS_VIDEPRINTER", "name" : "Standings / Videprinter", "desc" : "Standings table with latest results appearing in the lower third of the screen.", "image" : "/images/screenthumbs/standings_videprinter.png", "menuorder" : 1, "fetch" : [ "standings", "logs" ] }, { "id" : "TELEOST_MODE_STANDINGS_RESULTS", "name" : "Standings / Table Results", "desc" : "Standings table with the current round's fixtures and results cycling on the lower third of the screen.", "image" : "/images/screenthumbs/standings_results.png", "menuorder" : 2, "fetch" : [ "standings", "games" ] }, { "id" : "TELEOST_MODE_TECHNICAL_DIFFICULTIES", "name" : "Technical Difficulties", "desc" : "Ceci n'est pas un probleme technique.", "image" : "/images/screenthumbs/technical_difficulties.png", "menuorder" : 10, "fetch" : [] }, { "id" : "TELEOST_MODE_FIXTURES", "name" : "Fixtures", "desc" : "Table of all fixtures in the next or current round.", "image" : "/images/screenthumbs/fixtures.png", "menuorder" : 3, "fetch" : [ "games" ] }, { "id" : "TELEOST_MODE_TABLE_NUMBER_INDEX", "name" : "Table Number Index", "desc" : "A list of all the player names and their table numbers, in alphabetical order of player name.", "image" : "/images/screenthumbs/table_index.png", "menuorder" : 4, "fetch" : [ "games" ] }, { "id" : "TELEOST_MODE_OVERACHIEVERS", "name" : "Overachievers", "desc" : "Table of players ranked by how highly they finish above their seeding position. This is only relevant if the players have different ratings.", "image" : "/images/screenthumbs/overachievers.png", "menuorder" : 6, "fetch" : [ "overachievers" ] }, { "id" : "TELEOST_MODE_TUFF_LUCK", "name" : "Tuff Luck", "desc" : "Players who have lost three or more games, ordered by the sum of their three lowest losing margins.", "image" : "/images/screenthumbs/tuff_luck.png", "menuorder" : 7, "fetch" : [ "tuffluck" ] }, { "id" : "TELEOST_MODE_HIGH_SCORES", "name" : "High scores", "desc" : "Highest winning scores, losing scores and combined scores in all heat games.", "image" : "/images/screenthumbs/high_scores.jpg", "menuorder" : 8, "fetch" : [ "highscores" ] } #{ # "id" : "TELEOST_MODE_FASTEST_FINISHERS", # "name" : "Fastest Finishers", # "desc" : "A cheeky way to highlight which tables are taking too long to finish their games.", # "image" : "/images/screenthumbs/placeholder.png", # "menuorder" : 9, # "fetch" : [] #} #,{ # "id" : "TELEOST_MODE_CLOCK", # "name" : "Clock", # "desc" : "For some reason.", # "image" : "/images/screenthumbs/placeholder.png", # "menuorder" : 10, # "fetch" : [] #} ] teleost_mode_id_to_num = dict() for idx in range(len(teleost_modes)): teleost_modes[idx]["num"] = idx teleost_mode_id_to_num[teleost_modes[idx]["id"]] = idx teleost_per_view_option_list = [ (teleost_mode_id_to_num["TELEOST_MODE_AUTO"], "autousetableindex", CONTROL_CHECKBOX, "$CONTROL Show name-to-table index at start of round", 0), (teleost_mode_id_to_num["TELEOST_MODE_AUTO"], "autocurrentroundmusthavegamesinalldivisions", CONTROL_CHECKBOX, "$CONTROL Only switch to Fixtures display after fixtures are generated for all divisions", 1), (teleost_mode_id_to_num["TELEOST_MODE_STANDINGS"], "standings_only_lines", CONTROL_NUMBER, "Players per page", 12), (teleost_mode_id_to_num["TELEOST_MODE_STANDINGS"], "standings_only_scroll", CONTROL_NUMBER, "Page scroll interval $CONTROL seconds", 12), (teleost_mode_id_to_num["TELEOST_MODE_STANDINGS_VIDEPRINTER"], "standings_videprinter_standings_lines", CONTROL_NUMBER, "Players per page", 8), (teleost_mode_id_to_num["TELEOST_MODE_STANDINGS_VIDEPRINTER"], "standings_videprinter_standings_scroll", CONTROL_NUMBER, "Page scroll interval $CONTROL seconds", 10), (teleost_mode_id_to_num["TELEOST_MODE_STANDINGS_VIDEPRINTER"], "standings_videprinter_spell_big_scores", CONTROL_CHECKBOX, "$CONTROL Videprinter: repeat unbelievably high scores in words", 0), (teleost_mode_id_to_num["TELEOST_MODE_STANDINGS_VIDEPRINTER"], "standings_videprinter_big_score_min", CONTROL_NUMBER, "$INDENT An unbelievably high score is $CONTROL or more", 90), (teleost_mode_id_to_num["TELEOST_MODE_STANDINGS_RESULTS"], "standings_results_standings_lines", CONTROL_NUMBER, "Players per standings page", 8), (teleost_mode_id_to_num["TELEOST_MODE_STANDINGS_RESULTS"], "standings_results_standings_scroll", CONTROL_NUMBER, "Standings scroll interval $CONTROL seconds", 10), (teleost_mode_id_to_num["TELEOST_MODE_STANDINGS_RESULTS"], "standings_results_results_lines", CONTROL_NUMBER, "Number of results per page", 3), (teleost_mode_id_to_num["TELEOST_MODE_STANDINGS_RESULTS"], "standings_results_results_scroll", CONTROL_NUMBER, "Results scroll interval $CONTROL seconds", 5), (teleost_mode_id_to_num["TELEOST_MODE_STANDINGS_RESULTS"], "standings_results_show_unstarted_round_if_single_game", CONTROL_CHECKBOX, "$CONTROL Show unstarted next round if it only has one game", 1), (teleost_mode_id_to_num["TELEOST_MODE_FIXTURES"], "fixtures_lines", CONTROL_NUMBER, "Lines per page", 12), (teleost_mode_id_to_num["TELEOST_MODE_FIXTURES"], "fixtures_scroll", CONTROL_NUMBER, "Page scroll interval $CONTROL seconds", 10), (teleost_mode_id_to_num["TELEOST_MODE_TABLE_NUMBER_INDEX"], "table_index_rows", CONTROL_NUMBER, "Rows per page $CONTROL", 12), (teleost_mode_id_to_num["TELEOST_MODE_TABLE_NUMBER_INDEX"], "table_index_columns", CONTROL_NUMBER, "Columns per page", 2), (teleost_mode_id_to_num["TELEOST_MODE_TABLE_NUMBER_INDEX"], "table_index_scroll", CONTROL_NUMBER, "Page scroll interval $CONTROL seconds", 12) ] create_tables_sql = """ begin transaction; -- PLAYER table create table if not exists player ( id integer primary key autoincrement, name text, rating float, team_id int, short_name text, withdrawn int not null default 0, division int not null default 0, division_fixed int not null default 0, avoid_prune int not null default 0, require_accessible_table int not null default 0, preferred_table int not null default -1, unique(name), unique(short_name) ); -- TEAM table create table if not exists team ( id integer primary key autoincrement, name text, colour int, unique(name) ); insert into team(name, colour) values('White', 255 * 256 * 256 + 255 * 256 + 255); insert into team(name, colour) values('Blue', 128 * 256 + 255); -- GAME table, containing scheduled games and played games create table if not exists game ( round_no int, seq int, table_no int, division int, game_type text, p1 integer, p1_score integer, p2 integer, p2_score integer, tiebreak int, unique(round_no, seq) ); -- game log, never deleted from create table if not exists game_log ( seq integer primary key autoincrement, ts text, round_no int, round_seq int, table_no int, division int, game_type text, p1 integer, p1_score int, p2 integer, p2_score int, tiebreak int, log_type int, comment text default null ); -- Games where we don't yet know who the players are going to be, but we -- do know it's going to be "winner of this match versus winner of that match". create table if not exists game_pending ( round_no int, seq int, seat int, winner int, from_round_no int, from_seq int, unique(round_no, seq, seat) ); -- options, such as what to sort players by, how to decide fixtures, etc create table if not exists options ( name text primary key, value text ); -- metadata for per-view options in teleost (values stored in "options" above) create table if not exists teleost_options ( mode int, seq int, name text primary key, control_type int, desc text, default_value text, unique(mode, seq) ); -- Table in which we persist the HTML form settings given to a fixture -- generator create table if not exists fixgen_settings ( fixgen text, name text, value text ); -- Round names. When a fixture generator generates some fixtures, it will -- probably create a new round. This is always given a number, but it can -- also be given a name, e.g. "Quarter-finals". The "round type" column is -- no longer used. create table if not exists rounds ( id integer primary key, type text, name text ); create view if not exists rounds_derived as select r.id, case when r.name is not null and r.name != '' then r.name when gc.qf = gc.total then 'Quarter-finals' when gc.sf = gc.total then 'Semi-finals' when gc.f = gc.total then 'Final' when gc.tp = gc.total then 'Third Place' when gc.f + gc.tp = gc.total then 'Final & Third Place' else 'Round ' || cast(r.id as text) end as name from rounds r, (select g.round_no, sum(case when g.game_type = 'QF' then 1 else 0 end) qf, sum(case when g.game_type = 'SF' then 1 else 0 end) sf, sum(case when g.game_type = '3P' then 1 else 0 end) tp, sum(case when g.game_type = 'F' then 1 else 0 end) f, sum(case when g.game_type = 'N' then 1 else 0 end) n, sum(case when g.game_type = 'P' then 1 else 0 end) p, count(*) total from game g group by g.round_no) gc where gc.round_no = r.id; create view if not exists completed_game as select * from game where p1_score is not null and p2_score is not null; create view if not exists completed_heat_game as select * from game where p1_score is not null and p2_score is not null and game_type = 'P'; create view if not exists game_divided as select round_no, seq, table_no, game_type, p1 p_id, p1_score p_score, p2 opp_id, p2_score opp_score, tiebreak from game union all select round_no, seq, table_no, game_type, p2 p_id, p2_score p_score, p1 opp_id, p1_score opp_score, tiebreak from game; create view if not exists heat_game_divided as select * from game_divided where game_type = 'P'; create view if not exists player_wins as select p.id, sum(case when g.p_id is null then 0 when g.p_score is null or g.opp_score is null then 0 when g.p_score == 0 and g.opp_score == 0 and g.tiebreak then 0 when g.p_score > g.opp_score then 1 else 0 end) wins from player p left outer join heat_game_divided g on p.id = g.p_id group by p.id; create view if not exists player_draws as select p.id, sum(case when g.p_id is null then 0 when g.p_score is null or g.opp_score is null then 0 when g.p_score == 0 and g.opp_score == 0 and g.tiebreak then 0 when g.p_score == g.opp_score then 1 else 0 end) draws from player p left outer join heat_game_divided g on p.id = g.p_id group by p.id; create view if not exists player_points as select p.id, sum(case when g.p_score is null then 0 when g.tiebreak and g.p_score > g.opp_score then g.opp_score else g.p_score end) points from player p left outer join heat_game_divided g on p.id = g.p_id group by p.id; create view if not exists player_points_against as select p.id, sum(case when g.opp_score is null then 0 when g.tiebreak and g.opp_score > g.p_score then g.p_score else g.opp_score end) points_against from player p left outer join heat_game_divided g on p.id = g.p_id group by p.id; create view if not exists player_played as select p.id, sum(case when g.p_score is not null and g.opp_score is not null then 1 else 0 end) played from player p left outer join heat_game_divided g on p.id = g.p_id group by p.id; create view if not exists player_played_first as select p.id, count(g.p1) played_first from player p left outer join completed_heat_game g on p.id = g.p1 group by p.id; create table final_game_types(game_type text, power int); insert into final_game_types values ('QF', 2), ('SF', 1), ('F', 0); create view if not exists player_finals_results as select p.id, coalesce(gd.game_type, gt.game_type) game_type, case when gd.p_score is null then '-' when gd.p_score > gd.opp_score then 'W' when gd.p_score = gd.opp_score then 'D' else 'L' end result from player p, final_game_types gt left outer join game_divided gd on p.id = gd.p_id and (gd.game_type = gt.game_type or (gt.game_type = 'F' and gd.game_type = '3P')); create view if not exists player_finals_form as select p.id, coalesce(pfr_qf.result, '-') qf, coalesce(pfr_sf.result, '-') sf, case when pfr_f.result is null then '-' when pfr_f.game_type = '3P' then lower(pfr_f.result) else pfr_f.result end f from player p left outer join player_finals_results pfr_qf on p.id = pfr_qf.id and pfr_qf.game_type = 'QF' left outer join player_finals_results pfr_sf on p.id = pfr_sf.id and pfr_sf.game_type = 'SF' left outer join player_finals_results pfr_f on p.id = pfr_f.id and pfr_f.game_type in ('3P', 'F') group by p.id; create view if not exists player_standings as select p.id, p.name, p.division, played.played, wins.wins, draws.draws, points.points, points_against.points_against, ppf.played_first, pff.qf || pff.sf || upper(pff.f) finals_form, case when pff.f = '-' then 0 else case when pff.qf = 'W' then 48 when pff.qf = 'D' then 32 when pff.qf = 'L' then 16 else case when pff.sf != '-' or pff.f != '-' then 48 else 0 end end + case when pff.sf = 'W' then 12 when pff.sf = 'D' then 8 when pff.sf = 'L' then 4 -- If you're playing in a third place match then you're considered -- to have lost the nonexistent semi-final. If you're playing in a -- final then you're considered to have won the semi-final. else case when pff.f in ('w', 'd', 'l') then 4 when pff.f in ('W', 'D', 'L') then 12 else 0 end end + case when pff.f = 'W' then 3 when pff.f = 'D' then 2 when pff.f = 'L' then 1 else 0 end end finals_points from player p, player_wins wins, player_draws draws, player_played played, player_points points, player_points_against points_against, player_played_first ppf, player_finals_form pff where p.id = wins.id and p.id = played.id and p.id = points.id and p.id = draws.id and p.id = points_against.id and p.id = ppf.id and p.id = pff.id; -- Tables for controlling the display system Teleost create table if not exists teleost(current_mode int); delete from teleost; insert into teleost values(0); create table if not exists teleost_modes(num int, name text, desc text); create table if not exists tr_opts ( bonus float, rating_diff_cap float ); delete from tr_opts; insert into tr_opts (bonus, rating_diff_cap) values (50, 40); -- View for working out tournament ratings -- For each game, you get 50 + your opponent's rating if you win, -- your opponent's rating if you draw, and your opponent's rating - 50 if -- you lost. For the purpose of this calculation, your opponent's rating -- is your opponent's rating at the start of the tourney, except where that -- is more than 40 away from your own, in which case it's your rating +40 or -- -40 as appropriate. -- The 50 and 40 are configurable, in the tr_opts table. create view tournament_rating as select p.id, p.name, avg(case when hgd.p_score > hgd.opp_score then rel_ratings.opp_rating + tr_opts.bonus when hgd.p_score = hgd.opp_score then rel_ratings.opp_rating else rel_ratings.opp_rating - tr_opts.bonus end) tournament_rating from player p, heat_game_divided hgd on p.id = hgd.p_id, (select me.id p_id, you.id opp_id, case when you.rating < me.rating - tr_opts.rating_diff_cap then me.rating - tr_opts.rating_diff_cap when you.rating > me.rating + tr_opts.rating_diff_cap then me.rating + tr_opts.rating_diff_cap else you.rating end opp_rating from player me, player you, tr_opts) rel_ratings on rel_ratings.p_id = p.id and hgd.opp_id = rel_ratings.opp_id, tr_opts where hgd.p_score is not null and hgd.opp_score is not null group by p.id, p.name; -- Table for information about tables (boards). The special table_no -1 means -- the default settings for tables. So if table -1 is marked as accessible -- that means every table not listed is considered to be accessible. create table board ( table_no integer primary key, accessible integer not null ); -- By default, if a board isn't listed in this table then it isn't accessible. insert into board (table_no, accessible) values (-1, 0); -- Log any failures to upload updates create table if not exists upload_error_log ( ts text, failure_type int, message text ); -- Time of last successful upload create table if not exists upload_success ( ts text ); insert into upload_success values (null); commit; """; def get_teleost_mode_services_to_fetch(mode): if mode < 0 or mode >= len(teleost_modes): return [ "all" ] else: return teleost_modes[mode]["fetch"] # When we submit a player list to a new tournament, set_players() takes a list # of these objects. # This object can be on one side and/or other of a Game, just like a Player. # However, it does not represent a player. It represents the winner or loser # of another specific game yet to be played. # COLIN Hangover 2015: each player is assigned a team def get_general_division_name(num): if num < 0: return "Invalid division number %d" % (num) elif num > 25: return "Division %d" % (num + 1) else: return "Division %s" % (chr(ord('A') + num)) def get_general_short_division_name(num): if num < 0: return "" elif num > 25: return int(num + 1) else: return chr(ord('A') + num) def get_5_3_table_sizes(num_players): if num_players < 8: return [] table_sizes = [] players_left = num_players while players_left % 5 != 0: table_sizes.append(3) players_left -= 3 while players_left > 0: table_sizes = [5] + table_sizes players_left -= 5 return table_sizes def get_game_types(): return [ { "code" : "P", "name" : "Standard heat game" }, { "code" : "QF", "name" : "Quarter-final" }, { "code" : "SF", "name" : "Semi-final" }, { "code" : "3P", "name" : "Third-place play-off" }, { "code" : "F", "name" : "Final" } , { "code" : "N", "name" : "Other game not counted in standings" } ] unique_id_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 198, 11748, 25064, 198, 11748, 44161, 578, 18, 26, 198, 11748, 302, 26, 198, 11748, 28686, 26, 198, 11748, 4738, 198, 11748, 28587, 198, 198, 6738, 269, 926, 540, 1330, 40327, 10962, 11, ...
2.385977
8,871
# Copyright (c) Jeremas Casteglione <jrmsdev@gmail.com> # See LICENSE file. from glob import glob from os import path, makedirs
[ 2, 15069, 357, 66, 8, 10272, 5356, 5833, 1533, 75, 7935, 1279, 73, 81, 907, 7959, 31, 14816, 13, 785, 29, 198, 2, 4091, 38559, 24290, 2393, 13, 198, 198, 6738, 15095, 1330, 15095, 198, 6738, 28686, 1330, 3108, 11, 285, 4335, 17062, ...
2.931818
44
""" ############## # jsonReader # ############## """ # Import import json from platform import system from enum import Enum from datetime import timedelta # %% ____________________________________________________________________________________________________ # ____________________________________________________________________________________________________ # Functions def jsonReadWrite(pathToJson, pathWhereToCreateFile, watcher, printJsonFile=False): """ Write csv formatted data into file :param path: path where to create file :type path: str :param watcher: watcher type of the file :type watcher: Watcher :param printJsonFile: ??? :type printJsonFile: bool :return: return csv formatted string :rtype: str """ res = "file generated" with open(pathToJson) as json_file: dataDict = json.load(json_file) if (system() != 'Linux' and system() != 'Windows'): print("{} operating system not supported".format(system())) else: print("{} operating system detected".format(system())) if printJsonFile: print(json.dumps(dataDict, indent=4)) csvFile = open(pathWhereToCreateFile, "w") # "w" to write strings to the file if watcher == Watcher.AFK: print("watcher == Watcher.AFK") # duration: 956.016 # id: 316 # timestamp: 2019 - 01 - 28 # T10: 28:13.770000 + 00: 00 # data: {'status': 'not-afk'} res = "Watcher.AFK detected => does nothing" elif watcher == Watcher.WEB: print("watcher == Watcher.WEB") # duration: 1.518 # id: 3210 # timestamp: 2019 - 01 - 31 # T18: 01:45.794000 + 00: 00 # data: {'title': 'New Tab', 'url': 'about:blank', 'audible': False, 'tabCount': 3, 'incognito': False} res = "Watcher.WEB detected => does nothing" elif watcher == Watcher.WINDOW: print("watcher == Watcher.WINDOW") # duration: 4.017 # <= in seconds # id: 17 # timestamp: 2019 - 01 - 28 # T01: 11:55.570000 + 00: 00 # data: {'title': 'Terminal - arch@ArchDesktop:~', 'app': 'Xfce4-terminal'} # <= app is the interesting thing # if printJsonFile: # # check # for d in dataDict: # print('duration: ' + str(d['duration'])) # print('id: ' + str(d['id'])) # print('timestamp: ' + str(d['timestamp'])) # print('data: ' + str(d['data'])) # print(' title: ' + str(d['data']['title'])) # print(' app: ' + str(d['data']['app'])) # print('') handleWindowWatcher(csvFile, dataDict) else: res = "failed to identify watcher type" print(res) return res
[ 37811, 198, 7804, 4242, 2235, 198, 2, 33918, 33634, 1303, 198, 7804, 4242, 2235, 198, 37811, 198, 198, 2, 17267, 198, 11748, 33918, 198, 6738, 3859, 1330, 1080, 198, 6738, 33829, 1330, 2039, 388, 198, 6738, 4818, 8079, 1330, 28805, 1251...
2.226048
1,336
import re test = input(" : ") test.encode('unicode-escape').decode().replace('\\\\', '\\') print(" : "+test) if re.match(test, "a"): print(test + " Match 1") if re.match(test, "aa"): print(test + " Match 2") if re.match(test, "aaaa"): print(test + " Match 3")
[ 11748, 302, 198, 198, 9288, 796, 5128, 7203, 1058, 366, 8, 198, 198, 9288, 13, 268, 8189, 10786, 46903, 1098, 12, 41915, 27691, 12501, 1098, 22446, 33491, 10786, 13426, 3256, 705, 6852, 11537, 198, 198, 4798, 7203, 1058, 43825, 9288, 8,...
2.376068
117
# t=0 # for x in range(1,9): for y in range(1,11): for z in range(1,13): if 6*x+5*y+4*z==50: print("x ",x," y ",y," z ",z," ") t=t+1 print(" {} ".format(t)) #by xiaozhiyuqwq #https://www.rainyat.work #2021-12-23
[ 2, 201, 198, 83, 28, 15, 201, 198, 2, 201, 198, 1640, 2124, 287, 2837, 7, 16, 11, 24, 2599, 201, 198, 220, 220, 220, 329, 331, 287, 2837, 7, 16, 11, 1157, 2599, 201, 198, 220, 220, 220, 220, 220, 220, 220, 329, 1976, 287, 28...
1.561111
180
# from job_scrapper_gui import naukri_gui from tkinter import * from PIL import ImageTk import PIL.Image import naukri_scrapper import linkedin_scrapper import indeed import simply_hired_scrapper from selenium import webdriver root = Tk() root.title("Compare Jobs") root.geometry("1000x670") root.configure(background='white') # ----------------Header GUI---------------- # -------Creating All labels-------- logo = ImageTk.PhotoImage(PIL.Image.open("./Images\compare.png")) header_frame = LabelFrame(bg="#135EC2",borderwidth=0,highlightthickness=0) # logo logo_label = Label(header_frame,image=logo,bg='#135EC2') # job title container job_title_frame = LabelFrame(header_frame,bg='#135EC2',borderwidth=0,highlightthickness=0) job_label = Label(job_title_frame,text="JOB TITLE",bg='#135EC2',fg="white",font=('Bahnschrift Light', 13, 'normal')) job_profile_box = Entry(job_title_frame, width=30, font=('Bahnschrift Light', 13, 'normal')) # location container location_frame = LabelFrame(header_frame,bg='#135EC2',borderwidth=0,highlightthickness=0) location_label = Label(location_frame,text="LOCATION",bg='#135EC2',fg="white",font=('Bahnschrift Light', 13, 'normal')) location_box = Entry(location_frame, width=30, font=('Bahnschrift Light', 13, 'normal')) # compare button container compare_button_frame = LabelFrame(header_frame,padx=50,pady=10,bg='#135EC2',borderwidth=0,highlightthickness=0) # ------labels created------- # ------packing labels------- header_frame.pack(fill=X) logo_label.grid(row=0,column=0,pady=3,padx=10) job_title_frame.grid(row=0,column=1,pady=10,padx=20) job_profile_box.pack() job_label.pack(side=LEFT) location_frame.grid(row=0,column=2,pady=10,padx=20) location_box.pack() location_label.pack(side=LEFT) compare_button_frame.grid(row=1,column=1,columnspan=2) # ------------Header GUI ends-------------- # ------------Compare JOBS GUI-------------- card_container = LabelFrame(root,bg="white",pady=20,borderwidth=0,highlightthickness=0) card_container.pack(fill=X) # ----Naukri.com GUI---- # ----Naukir.com GUI completed---- # --------indeed GUI-------------- # ----indeed GUI completed---- # -------Linkedin GUI--------- # --------Linkedin GUI completed------------ # ---------SimplyHired GUI------------------ # ----------SimplyHired GUI------------- is_both_empty = False compare_button = Button(compare_button_frame,text="Comapre",padx=15,pady=7,font=('Bahnschrift Light', 12, 'bold'),bg="white",fg="#135EC2",command=compare) compare_button.pack() root.mainloop()
[ 2, 422, 1693, 62, 1416, 430, 2848, 62, 48317, 1330, 299, 559, 74, 380, 62, 48317, 198, 6738, 256, 74, 3849, 1330, 1635, 198, 6738, 350, 4146, 1330, 7412, 51, 74, 198, 11748, 350, 4146, 13, 5159, 198, 11748, 299, 559, 74, 380, 62, ...
2.876289
873
""" multispectrum Zhiang Chen, Feb, 2020 """ import gdal import cv2 import numpy as np import math import os if __name__ == '__main__': st = MultDim() # split tiles """ st.readTiff("./datasets/C3/Orth5.tif", channel=5) R = st.readImage("./datasets/Rock/R.png", channel=1) G = st.readImage("./datasets/Rock/G.png", channel=1) B = st.readImage("./datasets/Rock/B.png", channel=1) RE = st.readImage("./datasets/Rock/RE.png", channel=1) NIR = st.readImage("./datasets/Rock/NIR.png", channel=1) DEM = st.readImage("./datasets/Rock/DEM3.png", channel=3) data = st.cat(R, G) data = st.cat(data, B) data = st.cat(data, RE) data = st.cat(data, NIR) data = st.cat(data, DEM) st.split(data, 400, "./datasets/Rock/mult_10", overlap=10) """ # add annotations # st.addAnnotation("./datasets/Rock/mult/", "./datasets/Rock_test/npy/", "./datasets/Rock_test/mult") #""" RGB = st.readImage("./datasets/C3/C3.png", channel=3) DEM = st.readImage("./datasets/C3/C3_dem.png", channel=3) data = st.cat(RGB, DEM) st.split(data, 400, './datasets/C3/rgbd', overlap=10) #""" #st.addAnnotation("./datasets/C3/rgbd/", "./datasets/C3_test/npy/", "./datasets/C3_test/rocks")
[ 37811, 198, 16680, 271, 806, 6582, 198, 57, 5303, 648, 12555, 11, 198, 15146, 11, 12131, 198, 37811, 198, 198, 11748, 308, 31748, 198, 11748, 269, 85, 17, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 10688, 198, 11748, 28686, 628, ...
2.107744
594
import json from engine.serializers.template import TemplateCellSerializer
[ 11748, 33918, 198, 198, 6738, 3113, 13, 46911, 11341, 13, 28243, 1330, 37350, 28780, 32634, 7509, 628, 198 ]
4.333333
18
#!/usr/bin/env python3 from random import randrange import random import pygame, sys from pygame.locals import * import string pygame.font.init() MENU_WIDTH = 1000 MENU_HEIGHT = 1000 GUESS_WIDTH = 1000 GUESS_HEIGHT = 650 HANGMAN_WIDTH = 1300 HANGMAN_HEIGHT = 720 BLACK = (0,0,0) WHITE = (255,255,255) RED = (255,0,0) GREEN = (0,255,0) LIGHT_YELLOW = (255, 255, 102) frame_rate = pygame.time.Clock() back_ground = pygame.image.load("image_kids.jpg") back_ground_guess = pygame.image.load("schoolboard.jpg") if __name__ == "__main__": menu = Menu() menu.run()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 201, 198, 201, 198, 6738, 4738, 1330, 43720, 9521, 201, 198, 11748, 4738, 201, 198, 11748, 12972, 6057, 11, 25064, 201, 198, 6738, 12972, 6057, 13, 17946, 874, 1330, 1635, 201, 198, 117...
2.143836
292
import numpy as np from PuzzleLib.Backend import gpuarray from PuzzleLib.Backend.Dnn import crossMapLRN, crossMapLRNBackward from PuzzleLib.Modules.LRN import LRN if __name__ == "__main__": unittest()
[ 11748, 299, 32152, 355, 45941, 198, 198, 6738, 23966, 25835, 13, 7282, 437, 1330, 308, 19944, 18747, 198, 6738, 23966, 25835, 13, 7282, 437, 13, 35, 20471, 1330, 3272, 13912, 35972, 45, 11, 3272, 13912, 35972, 45, 7282, 904, 198, 198, ...
2.849315
73
import copy from typing import Iterable import numba as nb import numpy as np import spectrum_utils.spectrum as sus def dot(spectrum1: sus.MsmsSpectrum, spectrum2: sus.MsmsSpectrum, fragment_mz_tolerance: float) -> float: """ Compute the dot product between the given spectra. Parameters ---------- spectrum1 : sus.MsmsSpectrum The first spectrum. spectrum2 : sus.MsmsSpectrum The second spectrum. fragment_mz_tolerance : float The fragment m/z tolerance used to match peaks. Returns ------- float The dot product similarity between the given spectra. """ return _dot(spectrum1.mz, _norm_intensity(np.copy(spectrum1.intensity)), spectrum2.mz, _norm_intensity(np.copy(spectrum2.intensity)), fragment_mz_tolerance) def avg_dot(representative: sus.MsmsSpectrum, cluster_spectra: Iterable[sus.MsmsSpectrum], fragment_mz_tolerance: float) -> float: """ Compute the average dot product between the cluster representative and all cluster members. Parameters ---------- representative : sus.MsmsSpectrum The cluster representative spectrum. cluster_spectra : Iterable[sus.MsmsSpectrum] The cluster member spectra. fragment_mz_tolerance : float Fragment m/z tolerance used during spectrum comparison. Returns ------- float The average dot product between the cluster representative and all cluster members. """ return np.mean([dot(representative, spectrum, fragment_mz_tolerance) for spectrum in cluster_spectra]) def fraction_by(representative: sus.MsmsSpectrum, cluster_spectra: Iterable[sus.MsmsSpectrum], fragment_mz_tolerance: float) -> float: """ Compute the fraction of intensity that is explained by the b and y-ions of the representative spectrum. This will be 0 if no peptide sequence is associated with the representative spectrum. Parameters ---------- representative : sus.MsmsSpectrum The cluster representative spectrum. cluster_spectra : Iterable[sus.MsmsSpectrum] The cluster member spectra. Ignored. fragment_mz_tolerance : float Fragment m/z tolerance used to annotate the peaks of the representative spectrum. Returns ------- float The fraction of intensity that is explained by the b and y-ions of the representative spectrum. """ if representative.peptide is None: return 0 representative = (copy.copy(representative) .remove_precursor_peak(fragment_mz_tolerance, 'Da') .annotate_peptide_fragments(fragment_mz_tolerance, 'Da')) annotated_peaks = [i for i, annot in enumerate(representative.annotation) if annot is not None] return (representative.intensity[annotated_peaks].sum() / representative.intensity.sum())
[ 11748, 4866, 198, 6738, 19720, 1330, 40806, 540, 198, 198, 11748, 997, 7012, 355, 299, 65, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 10958, 62, 26791, 13, 4443, 6582, 355, 2341, 628, 198, 4299, 16605, 7, 4443, 6582, 16, 25, 2341...
2.628028
1,156
""" BP. """ import sys import classicML as cml DATASET_PATH = './datasets/iris_dataset.csv' CALLBACKS = [cml.callbacks.History(loss_name='categorical_crossentropy', metric_name='accuracy')] # ds = cml.data.Dataset(label_mode='one-hot', standardization=True, name='iris') ds.from_csv(DATASET_PATH) # model = cml.BPNN(seed=2021) model.compile(network_structure=[4, 2, 3], optimizer='sgd', loss='categorical_crossentropy', metric='accuracy') # model.fit(ds.x, ds.y, epochs=1000, verbose=True, callbacks=CALLBACKS) # (MacOS, , CI.) if sys.platform != 'darwin': cml.plots.plot_history(CALLBACKS[0])
[ 37811, 198, 20866, 13, 198, 37811, 198, 11748, 25064, 198, 11748, 6833, 5805, 355, 269, 4029, 628, 198, 35, 1404, 1921, 2767, 62, 34219, 796, 705, 19571, 19608, 292, 1039, 14, 29616, 62, 19608, 292, 316, 13, 40664, 6, 198, 34, 7036, ...
1.9437
373
__author__ = "arunrajms" from rest_framework import serializers from pool.models import Pool from rest_framework.validators import UniqueValidator import re TYPE_CHOICES = ['Integer','IP','IPv6','AutoGenerate','Vlan','MgmtIP'] PUT_TYPE_CHOICES = ['Integer','IP','IPv6','Vlan','MgmtIP'] SCOPE_CHOICES = ['global','fabric','switch']
[ 834, 9800, 834, 796, 366, 283, 403, 430, 73, 907, 1, 198, 198, 6738, 1334, 62, 30604, 1330, 11389, 11341, 198, 6738, 5933, 13, 27530, 1330, 19850, 198, 6738, 1334, 62, 30604, 13, 12102, 2024, 1330, 30015, 47139, 1352, 198, 11748, 302,...
3.018182
110
import os import platform from datetime import datetime import time from pathlib import Path import asyncio from dateutil.parser import parse as parsedate from dateutil import tz import aiohttp
[ 11748, 28686, 198, 11748, 3859, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 11748, 640, 198, 6738, 3108, 8019, 1330, 10644, 198, 11748, 30351, 952, 198, 198, 6738, 3128, 22602, 13, 48610, 1330, 21136, 355, 44267, 378, 198, 6738, 3128, ...
3.792453
53
# O(n) time | O(1) space
[ 2, 440, 7, 77, 8, 640, 930, 440, 7, 16, 8, 2272, 628 ]
2
13
import pytest from layers.attention import AttentionLayer from tensorflow.keras.layers import Input, GRU, Dense, Concatenate, TimeDistributed from tensorflow.keras.models import Model import tensorflow as tf def test_attention_layer_standalone_fixed_b_fixed_t(): """ Tests fixed batch size and time steps Encoder and decoder has variable seq length and latent dim """ inp1 = Input(batch_shape=(5,10,15)) inp2 = Input(batch_shape=(5,15,25)) out, e_out = AttentionLayer()([inp1, inp2]) assert out.shape == tf.TensorShape([inp2.shape[0], inp2.shape[1], inp1.shape[2]]) assert e_out.shape == tf.TensorShape([inp1.shape[0], inp2.shape[1], inp1.shape[1]]) '''def test_attention_layer_nmt_none_b_fixed_t(): encoder_inputs = Input(shape=(12, 75), name='encoder_inputs') decoder_inputs = Input(shape=(16 - 1, 80), name='decoder_inputs') # Encoder GRU encoder_gru = GRU(32, return_sequences=True, return_state=True, name='encoder_gru') encoder_out, encoder_state = encoder_gru(encoder_inputs) # Set up the decoder GRU, using `encoder_states` as initial state. decoder_gru = GRU(32, return_sequences=True, return_state=True, name='decoder_gru') decoder_out, decoder_state = decoder_gru(decoder_inputs, initial_state=encoder_state) # Attention layer attn_layer = AttentionLayer(name='attention_layer') attn_out, attn_states = attn_layer([encoder_out, decoder_out]) # Concat attention input and decoder GRU output decoder_concat_input = Concatenate(axis=-1, name='concat_layer')([decoder_out, attn_out]) # Dense layer dense = Dense(80, activation='softmax', name='softmax_layer') dense_time = TimeDistributed(dense, name='time_distributed_layer') decoder_pred = dense_time(decoder_concat_input) # Full model full_model = Model(inputs=[encoder_inputs, decoder_inputs], outputs=decoder_pred) full_model.compile(optimizer='adam', loss='categorical_crossentropy') assert decoder_pred.shape == tf.TensorShape([]) def test_attention_layer_nmt_none_b_none_t(): pass'''
[ 11748, 12972, 9288, 198, 6738, 11685, 13, 1078, 1463, 1330, 47406, 49925, 198, 6738, 11192, 273, 11125, 13, 6122, 292, 13, 75, 6962, 1330, 23412, 11, 10863, 52, 11, 360, 1072, 11, 1482, 9246, 268, 378, 11, 3862, 20344, 6169, 198, 6738...
2.613267
799
from itertools import zip_longest, islice if __name__ == '__main__': L = input() inverse_suffix_array = suffix_array_best(L) suffix_array = inverse_array(inverse_suffix_array) for item in suffix_array: print(item + 1, end=' ') LCP = lcp_array(L, suffix_array) LCP.pop() LCP.insert(0, 'x') print() for item in LCP: print(item, end=' ')
[ 6738, 340, 861, 10141, 1330, 19974, 62, 6511, 395, 11, 318, 75, 501, 201, 198, 201, 198, 201, 198, 201, 198, 201, 198, 201, 198, 201, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 201, 198, 220, 220, 220, 406, 796...
2.009479
211
# -*- coding: utf-8 -*- """ utils.py - Definition of utility functions. """ from collections import namedtuple from lgr.utils import format_cp VariantProperties = namedtuple('VariantProperties', ['cp', 'type', 'when', 'not_when', 'comment']) def display_variant(variant): """ Nicely display a variant. :param variant: The variant to display. """ return "Variant {}: type={} - when={} - not-when={} - comment={}".format( format_cp(variant.cp), variant.type, variant.when, variant.not_when, variant.comment) def compare_objects(first, second, cmp_fct): """ Compare two objects, possibly None. :param first: First object. :param second: Second object. :param cmp_fct: A comparison function. :return: The "greatest" object according to `cmp_fct`, None if both values are None. >>> compare_objects(1, 2, max) 2 >>> compare_objects(1, 2, min) 1 >>> compare_objects(None, None, max) is None True >>> compare_objects(1, None, min) 1 >>> compare_objects(None, 1, min) 1 """ if first is None: return second if second is None: return first return cmp_fct(first, second)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 26791, 13, 9078, 532, 30396, 286, 10361, 5499, 13, 198, 37811, 198, 6738, 17268, 1330, 3706, 83, 29291, 198, 198, 6738, 300, 2164, 13, 26791, 1330, 5794, 62,...
2.279588
583
#!/usr/bin/env python3 # import modules. import sys; sys.path.append("..") import hashlib import json import logging import os import plac import unittest import warnings from tomes_packager.lib.directory_object import * from tomes_packager.lib.file_object import * # enable logging. logging.basicConfig(level=logging.DEBUG) # CLI. def main(filepath:("file path")): "Converts a file to a FolderObject and prints its attributes to screen as JSON.\ \nexample: `python3 test__file_object.py sample_files/sample_rdf.xlsx`" # convert @filepath to a FileObject. dir_obj = DirectoryObject(os.path.dirname(filepath)) file_obj = FileObject(filepath, dir_obj, dir_obj, 0) # collect @file_obj attributes. fdict = {} for att in file_obj.__dict__: if att[0] == "_": continue try: val = getattr(file_obj, att)() except TypeError: val = getattr(file_obj, att) fdict[att] = str(val) # convert @fdict to JSON. js = json.dumps(fdict, indent=2) print(js) if __name__ == "__main__": plac.call(main)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 2, 1330, 13103, 13, 198, 11748, 25064, 26, 25064, 13, 6978, 13, 33295, 7203, 492, 4943, 198, 11748, 12234, 8019, 198, 11748, 33918, 198, 11748, 18931, 198, 11748, 28686, 198, ...
2.433551
459
from unv.web.helpers import url_with_domain, url_for_static
[ 6738, 555, 85, 13, 12384, 13, 16794, 364, 1330, 19016, 62, 4480, 62, 27830, 11, 19016, 62, 1640, 62, 12708, 628, 198 ]
2.818182
22
import pygame icon = pygame.image.load("diamond_pickaxe.png") screen_weight = 1750 screen_height = 980 pygame.init() window = pygame.display.set_mode((screen_weight, screen_height)) pygame.display.set_caption('Pickaxe clicker') pygame.display.set_icon(icon) # zmienne wytrzymao_kilofa = 50 max_wytrzymao_kilofa = 50 dodaj2 = 1 record = 0 game_version = "0.2.2" last_update = "28.01.2022" x_for_kilof = 400 y_for_kilof = 400 x_for_button1 = 1030 y_for_button1 = 80 x_for_button2 = 1030 y_for_button2 = 800 boost = 1 doswiadczenie = 0 dodaj = 1 max_dodaj = 1 kilof_upgrade = 100 choosed_kilof = 1 # obiekty kilof = pygame.image.load("Drewniany_kilof.png") kilof2 = pygame.image.load("Kamienny_kilof.png") kilof3 = pygame.image.load("Zelazny_kilof.png") kilof4 = pygame.image.load("Zloty_kilof.png") kilof5 = pygame.image.load("Diamentowy_kilof.png") button_upgrade = pygame.image.load("Button_upgrade.png") button_upgrade_clicked = pygame.image.load("Button_upgrade_clicked.png") button_upgrade2 = pygame.image.load("Button_upgrade2.png") button_upgrade2_clicked = pygame.image.load("Button_upgrade2_clicked.png") button_restart = pygame.image.load("Button_restart.png") tlo = pygame.image.load("tlo.png") tlo = pygame.transform.scale(tlo, (screen_weight, screen_height)) # skalowanie # hitboxy kilof_hitbox = pygame.rect.Rect(x_for_kilof, y_for_kilof, 160, 160) # tworzy hitbox do kilofa button_upgrade_hitbox = pygame.rect.Rect(x_for_button1, y_for_button1, 650, 100) # tworzy hitbox do przycisku button_upgrade2_hitbox = pygame.rect.Rect(x_for_button2, y_for_button2, 650, 100) # funkcje run = True while run: pygame.time.Clock().tick(100) # maksymalnie 100 fps for event in pygame.event.get(): if event.type == pygame.QUIT: # jeli gracz zamknie okienko run = False keys = pygame.key.get_pressed() if keys[pygame.K_ESCAPE] : run = False # napisy kilof_upgrade2 = kilof_upgrade - 1 text_wersja = pygame.font.Font.render(pygame.font.SysFont("Freemono", 50), f"Version : {game_version} | Last update : {last_update}", True, (255, 200, 100)) # generowanie tekstu text_doswiadczenie = pygame.font.Font.render(pygame.font.SysFont("Dyuthi", 72), f"Doswiadczenie : {doswiadczenie}", True, (100, 100, 100)) # generowanie tekstu text_kilof = pygame.font.Font.render(pygame.font.SysFont("Sawasdee", 25), f"Kup kilof | Koszt : {kilof_upgrade}", True, (255, 255, 255)) # generowanie tekstu text_WIP = pygame.font.Font.render(pygame.font.SysFont("Waree", 25), f"W I P (WORK IN PROGRESS)", True, (255, 255, 255)) # generowanie tekstu 2 text_wytrzymao_kilofa = pygame.font.Font.render(pygame.font.SysFont("Dyuthi", 50), f"Wytrzymalosc kilofa : {wytrzymao_kilofa}", True, (255, 255, 255)) # generowanie tekstu 2 text_record = pygame.font.Font.render(pygame.font.SysFont("Liberation Serif", 50), f"Record : {record}", True, (150, 150, 150)) if choosed_kilof > 0 and choosed_kilof < 5 : if doswiadczenie > kilof_upgrade2 : text_kilof = pygame.font.Font.render(pygame.font.SysFont("Sawasdee", 25), f"Kup kilof | Koszt : {kilof_upgrade}, Dostepne", True, (255, 255, 255)) # generowanie tekstu 2 else : text_kilof = pygame.font.Font.render(pygame.font.SysFont("Sawasdee", 25), f"Kup kilof | Koszt : {kilof_upgrade}, Niedostepne", True, (255, 255, 255)) # generowanie tekstu 2 elif choosed_kilof == 5 : text_kilof = pygame.font.Font.render(pygame.font.SysFont("Sawasdee", 25), f"Nie ma wiecej dostepnych kilofow", True, (255, 255, 255)) # generowanie tekstu 2 boost2 = boost - 1 if doswiadczenie > boost2 : text_ulepszenie = pygame.font.Font.render(pygame.font.SysFont("Sawasdee", 25), f"Ulepszenie kilofa | Koszt : {boost}, Dostepne", True, (255, 255, 255)) # generowanie tekstu else : text_ulepszenie = pygame.font.Font.render(pygame.font.SysFont("Sawasdee", 25), f"Ulepszenie kilofa | Koszt : {boost}, Niedostepne", True, (255, 255, 255)) # generowanie tekstu window.blit(tlo, (0, 0)) # rysowanie ta # rysowanie hitboxw draw_hitbox(kilof_hitbox) # rysowanie hitboxu do kilofa draw_hitbox(button_upgrade_hitbox) # rysowanie hitboxu do przycisku upgrade draw_hitbox(button_upgrade2_hitbox) # rysowanie hitboxu do przycisku upgrade2 # rysowanie obiektw if choosed_kilof == 1 : draw_object(kilof, x_for_kilof, y_for_kilof) # rysowanie kilofu elif choosed_kilof == 2 : draw_object(kilof2, x_for_kilof, y_for_kilof) elif choosed_kilof == 3 : draw_object(kilof3, x_for_kilof, y_for_kilof) elif choosed_kilof == 4 : draw_object(kilof4, x_for_kilof, y_for_kilof) elif choosed_kilof == 5 or choosed_kilof > 5 : draw_object(kilof5, x_for_kilof, y_for_kilof) draw_object(button_upgrade, x_for_button1, y_for_button1) # rysowanie przycisku draw_object(button_upgrade2, x_for_button2, y_for_button2) # rysowanie przycisku 2 draw_object(button_restart, 0, 0) draw_object(text_doswiadczenie, 224, 100) # rysowanie tekstu draw_object(text_ulepszenie, 1040, 110) # rysowanie tekstu 2 draw_object(text_wersja, 10, 5) # rysowanie tekstu 3 draw_object(text_kilof, 1040, 840) draw_object(text_WIP, 1170, 750) draw_object(text_wytrzymao_kilofa, 250, 300) draw_object(text_record, 1280, 0) # sprawdzanie zdarze z myszk zdarzenia_z_myszk() # sprawdzanie if doswiadczenie > record : record = doswiadczenie #if x_for_button1 > 80 : #if x_for_button2 > 800 : # wydrukuj pygame.display.update()
[ 11748, 12972, 6057, 198, 198, 4749, 796, 12972, 6057, 13, 9060, 13, 2220, 7203, 67, 8446, 62, 27729, 38231, 13, 11134, 4943, 198, 198, 9612, 62, 6551, 796, 1596, 1120, 198, 9612, 62, 17015, 796, 32614, 198, 198, 9078, 6057, 13, 15003,...
2.121739
2,760
import os from tempfile import NamedTemporaryFile import h5py import numpy as np import torch from skimage.metrics import adapted_rand_error from torch.utils.data import DataLoader from pytorch3dunet.datasets.hdf5 import StandardHDF5Dataset from pytorch3dunet.datasets.utils import prediction_collate, get_test_loaders from pytorch3dunet.predict import _get_output_file, _get_predictor from pytorch3dunet.unet3d.model import get_model from pytorch3dunet.unet3d.predictor import EmbeddingsPredictor from pytorch3dunet.unet3d.utils import remove_halo
[ 11748, 28686, 198, 6738, 20218, 7753, 1330, 34441, 12966, 5551, 8979, 198, 198, 11748, 289, 20, 9078, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 198, 6738, 1341, 9060, 13, 4164, 10466, 1330, 16573, 62, 25192, 62, 18224, 198, ...
2.826531
196
from django.shortcuts import render, get_object_or_404 from django.contrib.auth.decorators import login_required from catalog.models import Videos, Category, Docs, Subscriber from django.contrib.auth.decorators import login_required
[ 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 11, 651, 62, 15252, 62, 273, 62, 26429, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 12501, 273, 2024, 1330, 17594, 62, 35827, 198, 6738, 18388, 13, 27530, 1330, 18637, 11, 2...
3.434783
69
import MySQLdb db = MySQLdb.connect('localhost', 'root', 'vis_2014', 'FinanceVis') cursor = db.cursor() sql = 'select predict_news_word from all_twitter where symbol=%s order by predict_news_word+0 desc' cursor.execute(sql, ('AAPL', )) results = cursor.fetchall() file_twitter_predict = open('twitter_predict_AAPL.csv', 'wb') for row in results: predict = row[0] if row[0] is None: predict = 'NULL' file_twitter_predict.write(predict+'\n') file_twitter_predict.close() cursor.close() db.close()
[ 11748, 33476, 9945, 198, 198, 9945, 796, 33476, 9945, 13, 8443, 10786, 36750, 3256, 705, 15763, 3256, 705, 4703, 62, 4967, 3256, 705, 37, 14149, 15854, 11537, 198, 66, 21471, 796, 20613, 13, 66, 21471, 3419, 198, 198, 25410, 796, 705, ...
2.621212
198
""" Dot Plot ========= _thumb: .2, .8 _example_title: Plot distribution. """ import matplotlib.pyplot as plt import numpy as np import arviz as az az.style.use("arviz-darkgrid") data = np.random.normal(0, 1, 1000) az.plot_dot(data, dotcolor="C1", point_interval=True, figsize=(12, 6)) plt.show()
[ 37811, 198, 35, 313, 28114, 198, 2559, 28, 198, 198, 62, 400, 2178, 25, 764, 17, 11, 764, 23, 198, 62, 20688, 62, 7839, 25, 28114, 6082, 13, 198, 37811, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 299...
2.447154
123
# https://open.kattis.com/problems/alphabetspam import sys import math xs = input() white = 0 lower = 0 higher =0 other = 0 for i in xs: if i == '_': white += 1 elif ('a' <= i) & (i <= 'z'): lower += 1 elif ('A' <= i) & (i <= "Z"): higher += 1 else: other += 1 print(white / len(xs)) print(lower / len(xs)) print(higher /len(xs)) print(other / len(xs))
[ 2, 3740, 1378, 9654, 13, 74, 1078, 271, 13, 785, 14, 1676, 22143, 14, 17307, 397, 1039, 79, 321, 198, 198, 11748, 25064, 198, 11748, 10688, 198, 198, 34223, 796, 5128, 3419, 198, 198, 11186, 796, 657, 198, 21037, 796, 657, 198, 4650...
2.087629
194
import numpy as np from sympy import simplify, sqrt, symbols from sympy.stats import Normal, covariance as cov, variance as var if __name__ == "__main__": ab, bc, a, b, c = symbols([ "beta_{A_to_B}", "beta_{B_to_C}", "sigma_A", "sigma_B", "sigma_C"]) Na = Normal('Na', 0, 1) Nb = Normal('Nb', 0, 1) Nc = Normal('Nc', 0, 1) # SEM # A -> B -> C # raw A = a * Na B = ab * A + b * Nb C = bc * B + c * Nc # standardized As = A / sqrt(var(A)) Bs = B / sqrt(var(B)) Cs = C / sqrt(var(C)) # scale-harmonized Am = a * Na Bm = (ab / (ab**2 + 1)**(1/2)) * Am + b * Nb Cm = (bc / (bc**2 + 1)**(1/2)) * Bm + c * Nc # forward/backward coefficients in raw setting f1, f2, b1, b2 = regcoeffs(A, B, C) # forward/backward coefficients in standardized setting f1s, f2s, b1s, b2s = regcoeffs(As, Bs, Cs) # forward/backward coefficients in scale-harmonized setting f1m, f2m, b1m, b2m = regcoeffs(Am, Bm, Cm) for weight_range in [(0.5, 2), (0.5, .9), (.1, .9)]: raw = { 'f1<f2,b1>b2': 0, 'f1>f2,b1<b2': 0, 'other': 0 } std = { 'f1<f2,b1>b2': 0, 'f1>f2,b1<b2': 0, 'other': 0 } moj = { 'f1<f2,b1>b2': 0, 'f1>f2,b1<b2': 0, 'other': 0 } for _ in range(100000): # draw model parameters a_to_b, b_to_c = np.random.uniform(*weight_range, size=2) sA, sB, sC = np.random.uniform(0.5, 2, size=3) a_to_b *= np.random.choice([-1, 1]) b_to_c *= np.random.choice([-1, 1]) subs = { ab: a_to_b, bc: b_to_c, a: sA, b: sB, c: sC, } # raw if (abs(f1.subs(subs)) < abs(f2.subs(subs)) and abs(b1.subs(subs)) > abs(b2.subs(subs))): raw['f1<f2,b1>b2'] += 1 elif (abs(f1.subs(subs)) > abs(f2.subs(subs)) and abs(b1.subs(subs)) < abs(b2.subs(subs))): raw['f1>f2,b1<b2'] += 1 else: raw['other'] += 1 # standardized if (abs(f1s.subs(subs)) < abs(f2s.subs(subs)) and abs(b1s.subs(subs)) > abs(b2s.subs(subs))): std['f1<f2,b1>b2'] += 1 elif (abs(f1s.subs(subs)) > abs(f2s.subs(subs)) and abs(b1s.subs(subs)) < abs(b2s.subs(subs))): std['f1>f2,b1<b2'] += 1 else: std['other'] += 1 # scale-harmonized if (abs(f1m.subs(subs)) < abs(f2m.subs(subs)) and abs(b1m.subs(subs)) > abs(b2m.subs(subs))): moj['f1<f2,b1>b2'] += 1 elif (abs(f1m.subs(subs)) > abs(f2m.subs(subs)) and abs(b1m.subs(subs)) < abs(b2m.subs(subs))): moj['f1>f2,b1<b2'] += 1 else: moj['other'] += 1 print('weight_range', weight_range) raw['correct'] = raw['f1<f2,b1>b2'] + raw['other'] / 2 print('raw\t\t', raw) std['correct'] = std['f1<f2,b1>b2'] + std['other'] / 2 print('standardized\t', std) moj['correct'] = moj['f1<f2,b1>b2'] + moj['other'] / 2 print('Mooij-scaled\t', moj) print()
[ 11748, 299, 32152, 355, 45941, 198, 6738, 10558, 88, 1330, 30276, 11, 19862, 17034, 11, 14354, 198, 6738, 10558, 88, 13, 34242, 1330, 14435, 11, 44829, 590, 355, 39849, 11, 24198, 355, 1401, 628, 198, 198, 361, 11593, 3672, 834, 6624, ...
1.576888
2,224
#!/usr/bin/env python2.7 # coding=<UTF-8> # tweetpic.py take a photo with the Pi camera and tweet it # by Alex Eames http://raspi.tv/?p=5918 import tweepy from subprocess import call from datetime import datetime import requests import json i = datetime.now() #take time and date for filename now = i.strftime('%Y%m%d-%H%M%S') photo_name = now + '.jpg' cmd = 'raspistill -t 500 -w 1024 -h 768 -o /home/pi/Pictures' + photo_name call ([cmd], shell=True) #shoot the photo # Freiburger Sensor von sbamueller url = 'http://api.luftdaten.info/static/v1/sensor/534/' tweet = pick_values(url) url = 'http://api.luftdaten.info/static/v1/sensor/533/' tweet = tweet + " " + pick_values(url) # Texte 140 Zeichen Tweets tweet = tweet.replace('temperature: ','| Temp C:') tweet = tweet.replace('P1:','| PM10:') tweet = tweet.replace('P2:','PM2.5:') #print(tweet) # Consumer keys and access tokens, used for OAuth CONSUMER_KEY = 'ihrKey' CONSUMER_SECRET = 'ihrKey' ACCESS_KEY = 'ihrKey' ACCESS_SECRET = 'ihrKey' # OAuth process, using the keys and tokens auth = tweepy.OAuthHandler(CONSUMER_KEY , CONSUMER_SECRET) auth.set_access_token(ACCESS_KEY , ACCESS_SECRET) # Creation of the actual interface, using authentication api = tweepy.API(auth) # Send the tweet with photo photo_path = '/home/pi/Pictures' + photo_name status = 'Blick auf Freiburg mit Feinstaubwerten, Temp & Luftfeuchte ' + i.strf$ status = status + tweet api.update_with_media(photo_path, status=status)
[ 198, 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 17, 13, 22, 220, 220, 198, 2, 19617, 28, 27, 48504, 12, 23, 29, 198, 2, 6126, 16564, 13, 9078, 1011, 257, 4590, 351, 262, 13993, 4676, 290, 6126, 340, 220, 220, 198, 2, 416, 4422...
2.516611
602
from pathlib import Path import pandas as pd from torch.utils.tensorboard import SummaryWriter
[ 6738, 3108, 8019, 1330, 10644, 198, 198, 11748, 19798, 292, 355, 279, 67, 198, 198, 6738, 28034, 13, 26791, 13, 83, 22854, 3526, 1330, 21293, 34379, 628 ]
3.62963
27