hexsha
stringlengths
40
40
size
int64
5
2.06M
ext
stringclasses
11 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
251
max_stars_repo_name
stringlengths
4
130
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
251
max_issues_repo_name
stringlengths
4
130
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
116k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
251
max_forks_repo_name
stringlengths
4
130
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
1
1.05M
avg_line_length
float64
1
1.02M
max_line_length
int64
3
1.04M
alphanum_fraction
float64
0
1
de725902f24523dc4f0cb06e33505cadc76a710c
38,783
py
Python
pysim/epcstd.py
larioandr/thesis-rfidsim
6a5b3ef02964ff2d49bf5dae55af270801af28a5
[ "MIT" ]
null
null
null
pysim/epcstd.py
larioandr/thesis-rfidsim
6a5b3ef02964ff2d49bf5dae55af270801af28a5
[ "MIT" ]
null
null
null
pysim/epcstd.py
larioandr/thesis-rfidsim
6a5b3ef02964ff2d49bf5dae55af270801af28a5
[ "MIT" ]
null
null
null
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
30.610103
79
0.592682
de72e8f348089a00d8a491df1f651cf4a945ca9c
1,500
py
Python
Heap/378-Kth_Smalles_Element_in_a_Sorted_Matrix.py
dingwenzheng730/Leet
c08bd48e8dcc6bca41134d218d39f66bfc112eaf
[ "MIT" ]
1
2021-06-15T21:01:53.000Z
2021-06-15T21:01:53.000Z
Heap/378-Kth_Smalles_Element_in_a_Sorted_Matrix.py
dingwenzheng730/Leet
c08bd48e8dcc6bca41134d218d39f66bfc112eaf
[ "MIT" ]
null
null
null
Heap/378-Kth_Smalles_Element_in_a_Sorted_Matrix.py
dingwenzheng730/Leet
c08bd48e8dcc6bca41134d218d39f66bfc112eaf
[ "MIT" ]
null
null
null
''' 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() '''
24.193548
134
0.611333
de73b0477272b09621a0a7e87406fe9c6c2a1f06
5,088
py
Python
baseStation/test/vision/service/test_visionService.py
olgam4/design3
6e05d123a24deae7dda646df535844a158ef5cc0
[ "WTFPL" ]
null
null
null
baseStation/test/vision/service/test_visionService.py
olgam4/design3
6e05d123a24deae7dda646df535844a158ef5cc0
[ "WTFPL" ]
null
null
null
baseStation/test/vision/service/test_visionService.py
olgam4/design3
6e05d123a24deae7dda646df535844a158ef5cc0
[ "WTFPL" ]
null
null
null
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
45.428571
117
0.725825
de758aaeb7ae98b14c58fbe707173fad48237087
8,753
py
Python
bmdal/layer_features.py
dholzmueller/bmdal_reg
1a9e9c19fbd350ec32a2bd7b505e7015df7dc9bf
[ "Apache-2.0" ]
3
2022-03-19T21:30:10.000Z
2022-03-30T08:20:48.000Z
bmdal/layer_features.py
dholzmueller/bmdal_reg
1a9e9c19fbd350ec32a2bd7b505e7015df7dc9bf
[ "Apache-2.0" ]
null
null
null
bmdal/layer_features.py
dholzmueller/bmdal_reg
1a9e9c19fbd350ec32a2bd7b505e7015df7dc9bf
[ "Apache-2.0" ]
null
null
null
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
44.207071
118
0.682052
de759ba42ef02e88463fee41b02959bd0f0ddd2c
35,389
py
Python
pinsey/gui/MainWindow.py
RailKill/Pinsey
72a283e6c5683b27918b511d80e45c3af4e67539
[ "MIT" ]
3
2021-02-01T06:47:06.000Z
2022-01-09T05:54:35.000Z
pinsey/gui/MainWindow.py
RailKill/Pinsey
72a283e6c5683b27918b511d80e45c3af4e67539
[ "MIT" ]
4
2019-10-23T09:52:36.000Z
2022-03-11T23:17:23.000Z
pinsey/gui/MainWindow.py
RailKill/Pinsey
72a283e6c5683b27918b511d80e45c3af4e67539
[ "MIT" ]
null
null
null
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
50.700573
121
0.628755
de7659b57f254205c0bc591d8af1e1375127f4d8
336
py
Python
Chat app/Check IP.py
ArturWagnerBusiness/Projects-2018-2020
37a217dc325f3ba42d8a7a1a743e5b6f8fab5df4
[ "MIT" ]
null
null
null
Chat app/Check IP.py
ArturWagnerBusiness/Projects-2018-2020
37a217dc325f3ba42d8a7a1a743e5b6f8fab5df4
[ "MIT" ]
null
null
null
Chat app/Check IP.py
ArturWagnerBusiness/Projects-2018-2020
37a217dc325f3ba42d8a7a1a743e5b6f8fab5df4
[ "MIT" ]
null
null
null
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)
24
59
0.720238
de766a3b6f5c4477c098e9f336005c2394afbbc1
1,506
py
Python
app/api/api_v1/tasks/emails.py
cdlaimin/fastapi
4acf1a1da4a1eedd81a3bdf6256661c2464928b9
[ "BSD-3-Clause" ]
null
null
null
app/api/api_v1/tasks/emails.py
cdlaimin/fastapi
4acf1a1da4a1eedd81a3bdf6256661c2464928b9
[ "BSD-3-Clause" ]
null
null
null
app/api/api_v1/tasks/emails.py
cdlaimin/fastapi
4acf1a1da4a1eedd81a3bdf6256661c2464928b9
[ "BSD-3-Clause" ]
null
null
null
# -*- 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
34.227273
108
0.625498
de76f5e1a1407299a65c28e63772cca898458059
13,487
py
Python
lightwood/encoders/text/distilbert.py
ritwik12/lightwood
7975688355fba8b0f8349dd55a1b6cb625c3efd0
[ "MIT" ]
null
null
null
lightwood/encoders/text/distilbert.py
ritwik12/lightwood
7975688355fba8b0f8349dd55a1b6cb625c3efd0
[ "MIT" ]
null
null
null
lightwood/encoders/text/distilbert.py
ritwik12/lightwood
7975688355fba8b0f8349dd55a1b6cb625c3efd0
[ "MIT" ]
null
null
null
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)
46.993031
456
0.671091
de775456d4d41592b9970922b77c527e29122163
4,542
py
Python
scripts/scopdominfo.py
stivalaa/cuda_satabsearch
b947fb711f8b138e5a50c81e7331727c372eb87d
[ "MIT" ]
null
null
null
scripts/scopdominfo.py
stivalaa/cuda_satabsearch
b947fb711f8b138e5a50c81e7331727c372eb87d
[ "MIT" ]
null
null
null
scripts/scopdominfo.py
stivalaa/cuda_satabsearch
b947fb711f8b138e5a50c81e7331727c372eb87d
[ "MIT" ]
null
null
null
#!/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()
30.689189
148
0.610524
de79c16d6df471bd5320f3fc4154354634f400a7
1,334
py
Python
serverless/pytorch/foolwood/siammask/nuclio/model_handler.py
arthurtibame/cvat
0062ecdec34a9ffcad33e1664a7cac663bec4ecf
[ "MIT" ]
null
null
null
serverless/pytorch/foolwood/siammask/nuclio/model_handler.py
arthurtibame/cvat
0062ecdec34a9ffcad33e1664a7cac663bec4ecf
[ "MIT" ]
null
null
null
serverless/pytorch/foolwood/siammask/nuclio/model_handler.py
arthurtibame/cvat
0062ecdec34a9ffcad33e1664a7cac663bec4ecf
[ "MIT" ]
1
2021-09-17T10:19:30.000Z
2021-09-17T10:19:30.000Z
# Copyright (C) 2020 Intel Corporation # # SPDX-License-Identifier: MIT from tools.test import * import os
34.205128
93
0.614693
de79c50bcf2db093ce388c48ecf4f5cdef4ddb45
10,842
py
Python
pynmt/__init__.py
obrmmk/demo
b5deb85b2b2bf118b850f93c255ee88d055156a8
[ "MIT" ]
null
null
null
pynmt/__init__.py
obrmmk/demo
b5deb85b2b2bf118b850f93c255ee88d055156a8
[ "MIT" ]
null
null
null
pynmt/__init__.py
obrmmk/demo
b5deb85b2b2bf118b850f93c255ee88d055156a8
[ "MIT" ]
1
2021-11-23T14:04:36.000Z
2021-11-23T14:04:36.000Z
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>']
36.14
168
0.620365
de7a78e426a815b7bd976727be3160a469af797a
9,185
py
Python
probedb/certs/builddb.py
dingdang2012/tlsprober
927f6177939470235bf336bca27096369932fc66
[ "Apache-2.0" ]
1
2019-01-30T13:18:02.000Z
2019-01-30T13:18:02.000Z
probedb/certs/builddb.py
dingdang2012/tlsprober
927f6177939470235bf336bca27096369932fc66
[ "Apache-2.0" ]
null
null
null
probedb/certs/builddb.py
dingdang2012/tlsprober
927f6177939470235bf336bca27096369932fc66
[ "Apache-2.0" ]
null
null
null
# 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"
27.665663
163
0.706369
de7c4534ed26f1d3158aaf6b53415fa79e0c249d
574
py
Python
patron/__init__.py
rafaelaraujobsb/patron
b2d23d4149a5f48156a4a2b0638daac33a66cc6a
[ "MIT" ]
null
null
null
patron/__init__.py
rafaelaraujobsb/patron
b2d23d4149a5f48156a4a2b0638daac33a66cc6a
[ "MIT" ]
null
null
null
patron/__init__.py
rafaelaraujobsb/patron
b2d23d4149a5f48156a4a2b0638daac33a66cc6a
[ "MIT" ]
null
null
null
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')
19.793103
102
0.602787
de7dc549a1952d8dda02b33f493f1bb859b37917
735
py
Python
src/perceptron.py
tomoki/deep-learning-from-scratch
0b6144806b6b79462d6d65616a64b1774f876973
[ "MIT" ]
1
2018-08-31T09:39:11.000Z
2018-08-31T09:39:11.000Z
src/perceptron.py
tomoki/deep-learning-from-scratch
0b6144806b6b79462d6d65616a64b1774f876973
[ "MIT" ]
null
null
null
src/perceptron.py
tomoki/deep-learning-from-scratch
0b6144806b6b79462d6d65616a64b1774f876973
[ "MIT" ]
null
null
null
import numpy as np import matplotlib.pylab as plt
17.093023
31
0.469388
de8007cfcf1b7fa53b4609e54f0ca14a7d5ba1bb
210
py
Python
notebooks/_solutions/case4_air_quality_analysis18.py
jorisvandenbossche/2018-Bordeaux-pandas-course
3f6b9fe6f02c2ab484c3f9744d7d39b926438dd6
[ "BSD-3-Clause" ]
3
2019-07-23T15:14:03.000Z
2020-11-10T06:12:18.000Z
notebooks/_solutions/case4_air_quality_analysis18.py
jorisvandenbossche/2018-Bordeaux-pandas-course
3f6b9fe6f02c2ab484c3f9744d7d39b926438dd6
[ "BSD-3-Clause" ]
null
null
null
notebooks/_solutions/case4_air_quality_analysis18.py
jorisvandenbossche/2018-Bordeaux-pandas-course
3f6b9fe6f02c2ab484c3f9744d7d39b926438dd6
[ "BSD-3-Clause" ]
3
2020-03-04T23:40:20.000Z
2021-11-04T16:41:10.000Z
# 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)")
52.5
116
0.704762
de82bbe06365e1885857bfec2f5eb9144e01b08c
1,729
py
Python
dncnn/dncnn.py
kTonpa/DnCNN
aca7e07ccbe6b75bee7d4763958dade4a8eee609
[ "MIT" ]
null
null
null
dncnn/dncnn.py
kTonpa/DnCNN
aca7e07ccbe6b75bee7d4763958dade4a8eee609
[ "MIT" ]
null
null
null
dncnn/dncnn.py
kTonpa/DnCNN
aca7e07ccbe6b75bee7d4763958dade4a8eee609
[ "MIT" ]
null
null
null
""" 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
25.80597
142
0.638519
de848d1a58c8622dd6042ce58386b34d78eaa285
41,886
py
Python
scripts/fabfile/tasks.py
Alchem-Lab/deneva
5201ef12fd8235fea7833709b8bffe45f53877eb
[ "Apache-2.0" ]
88
2017-01-19T03:15:24.000Z
2022-03-30T16:22:19.000Z
scripts/fabfile/tasks.py
Alchem-Lab/deneva
5201ef12fd8235fea7833709b8bffe45f53877eb
[ "Apache-2.0" ]
null
null
null
scripts/fabfile/tasks.py
Alchem-Lab/deneva
5201ef12fd8235fea7833709b8bffe45f53877eb
[ "Apache-2.0" ]
22
2017-01-20T10:22:31.000Z
2022-02-10T18:55:36.000Z
#!/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
36.549738
172
0.542138
de852461942a9c2a911b8c95e145d87c827bf61c
651
py
Python
mezzanine_recipes/forms.py
tjetzinger/mezzanine-recipes
f00be89ae5b93fdb2cf2771270efb4ecfa30e313
[ "MIT" ]
6
2015-02-01T18:08:41.000Z
2021-06-20T16:24:11.000Z
mezzanine_recipes/forms.py
tjetzinger/mezzanine-recipes
f00be89ae5b93fdb2cf2771270efb4ecfa30e313
[ "MIT" ]
2
2020-02-11T21:19:13.000Z
2020-06-05T16:38:44.000Z
mezzanine_recipes/forms.py
tjetzinger/mezzanine-recipes
f00be89ae5b93fdb2cf2771270efb4ecfa30e313
[ "MIT" ]
1
2016-05-17T20:16:25.000Z
2016-05-17T20:16:25.000Z
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")
26.04
73
0.723502
de86c719ac9ffce9e1f273be9d0dc93bbd224576
14,533
py
Python
reviews/migrations/0022_auto_20190302_1556.py
UrbanBogger/horrorexplosion
3698e00a6899a5e8b224cd3d1259c3deb3a2ca80
[ "MIT" ]
null
null
null
reviews/migrations/0022_auto_20190302_1556.py
UrbanBogger/horrorexplosion
3698e00a6899a5e8b224cd3d1259c3deb3a2ca80
[ "MIT" ]
4
2020-06-05T18:21:18.000Z
2021-06-10T20:17:31.000Z
reviews/migrations/0022_auto_20190302_1556.py
UrbanBogger/horrorexplosion
3698e00a6899a5e8b224cd3d1259c3deb3a2ca80
[ "MIT" ]
null
null
null
# -*- 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
113.539063
1,908
0.637515
de876b3ed14bbdc7196b4d80c31ffed86152546c
1,414
py
Python
setup.py
imdaveho/intermezzo
3fe4824a747face996e301ca5190caec0cb0a6fd
[ "MIT" ]
8
2018-02-26T16:24:07.000Z
2021-06-30T07:40:52.000Z
setup.py
imdaveho/intermezzo
3fe4824a747face996e301ca5190caec0cb0a6fd
[ "MIT" ]
null
null
null
setup.py
imdaveho/intermezzo
3fe4824a747face996e301ca5190caec0cb0a6fd
[ "MIT" ]
null
null
null
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"], )
35.35
100
0.601839
de87df11dbf3b3a221e585a21372627cd71cbf40
173
py
Python
aula3/ola/urls.py
Danilo-Xaxa/django_cs50w
5ae2e076f35a8c32a4e445f8cfd1c66500fbc496
[ "MIT" ]
null
null
null
aula3/ola/urls.py
Danilo-Xaxa/django_cs50w
5ae2e076f35a8c32a4e445f8cfd1c66500fbc496
[ "MIT" ]
null
null
null
aula3/ola/urls.py
Danilo-Xaxa/django_cs50w
5ae2e076f35a8c32a4e445f8cfd1c66500fbc496
[ "MIT" ]
null
null
null
from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('<str:nome>', views.cumprimentar, name='cumprimentar'), ]
24.714286
64
0.676301
de88715741307a44df748cb0254417ebbcf130e6
70,016
py
Python
MOTION.py
catubc/MOTION
528ce8a860e4f1f1075b85d3bcb162fb78bdad81
[ "MIT" ]
null
null
null
MOTION.py
catubc/MOTION
528ce8a860e4f1f1075b85d3bcb162fb78bdad81
[ "MIT" ]
null
null
null
MOTION.py
catubc/MOTION
528ce8a860e4f1f1075b85d3bcb162fb78bdad81
[ "MIT" ]
null
null
null
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*************************************************************** #**************************************************************************************************************************
39.049637
257
0.638211
de88b285c3b2ad75dee639aa1cc273972692cd58
619
py
Python
MinersArchers/game/game_data/cells/Cell_pygame.py
ea-evdokimov/MinersArchers
2e2830d3723b66cbd0e8829092124e30f8b4c854
[ "MIT" ]
null
null
null
MinersArchers/game/game_data/cells/Cell_pygame.py
ea-evdokimov/MinersArchers
2e2830d3723b66cbd0e8829092124e30f8b4c854
[ "MIT" ]
null
null
null
MinersArchers/game/game_data/cells/Cell_pygame.py
ea-evdokimov/MinersArchers
2e2830d3723b66cbd0e8829092124e30f8b4c854
[ "MIT" ]
null
null
null
import pygame from game.game_data.cells.Cell import Cell from game.pygame_ import PICS_pygame, CELL_SIZE from game.pygame_.Object import Object
30.95
91
0.691438
de8b266bc66642e780d1f515de7639ab0386bd85
2,690
py
Python
scheduler.py
shuaiqi361/a-PyTorch-Tutorial-to-Object-Detection
5706b82ff67911864967aa72adf7e4a994c7ec89
[ "MIT" ]
null
null
null
scheduler.py
shuaiqi361/a-PyTorch-Tutorial-to-Object-Detection
5706b82ff67911864967aa72adf7e4a994c7ec89
[ "MIT" ]
null
null
null
scheduler.py
shuaiqi361/a-PyTorch-Tutorial-to-Object-Detection
5706b82ff67911864967aa72adf7e4a994c7ec89
[ "MIT" ]
null
null
null
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'],))
36.351351
106
0.600743
de8c74beee9cae08acd3e8037eb35833307f76e4
93
py
Python
app/routing/feeds/feed_type.py
wolfhardfehre/guide-io
cf076bad0634bcaf4ad0be4822539b7c8d254e76
[ "MIT" ]
null
null
null
app/routing/feeds/feed_type.py
wolfhardfehre/guide-io
cf076bad0634bcaf4ad0be4822539b7c8d254e76
[ "MIT" ]
null
null
null
app/routing/feeds/feed_type.py
wolfhardfehre/guide-io
cf076bad0634bcaf4ad0be4822539b7c8d254e76
[ "MIT" ]
null
null
null
from enum import Enum
13.285714
26
0.645161
de8c915237260239c036a5cbacb8018944e669da
8,774
py
Python
lego_sorter.py
bmleedy/lego_sorter
0164bc0042127f255590d1883b5edadfba781537
[ "BSD-2-Clause" ]
null
null
null
lego_sorter.py
bmleedy/lego_sorter
0164bc0042127f255590d1883b5edadfba781537
[ "BSD-2-Clause" ]
null
null
null
lego_sorter.py
bmleedy/lego_sorter
0164bc0042127f255590d1883b5edadfba781537
[ "BSD-2-Clause" ]
null
null
null
#!/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()
35.379032
94
0.624915
de8d539f5152c1d0482b8d70ccc7c573352b8f81
6,061
py
Python
tableloader/tableFunctions/types.py
warlof/yamlloader
ff1c1e62ec40787dd77115f6deded8a93e77ebf6
[ "MIT" ]
26
2015-07-08T12:55:30.000Z
2022-01-21T11:44:35.000Z
tableloader/tableFunctions/types.py
warlof/yamlloader
ff1c1e62ec40787dd77115f6deded8a93e77ebf6
[ "MIT" ]
16
2016-05-01T17:42:44.000Z
2021-06-02T04:33:53.000Z
tableloader/tableFunctions/types.py
warlof/yamlloader
ff1c1e62ec40787dd77115f6deded8a93e77ebf6
[ "MIT" ]
17
2016-05-01T11:15:00.000Z
2021-12-02T03:25:04.000Z
# -*- 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
63.135417
193
0.530606
de8e61ed55aedc48bfff03d78334a493e87826b6
242
py
Python
core/views.py
AlikBerry/countdown_timer
457f6d499b1fd702d43c348a012ae78780009e3b
[ "MIT" ]
null
null
null
core/views.py
AlikBerry/countdown_timer
457f6d499b1fd702d43c348a012ae78780009e3b
[ "MIT" ]
null
null
null
core/views.py
AlikBerry/countdown_timer
457f6d499b1fd702d43c348a012ae78780009e3b
[ "MIT" ]
null
null
null
from django.shortcuts import render from core.models import Projects,InfoNotifications,WarningNotifications from django.http import HttpResponse from .tasks import sleepy
22
71
0.801653
de8e8bcbbb73ed82dfadbb561cfbfe8bb447a711
5,017
py
Python
networks/autoencoder/losses.py
annachen/dl_playground
f263dc16b4f0d91f6d33d94e678a9bbe2ace8913
[ "MIT" ]
null
null
null
networks/autoencoder/losses.py
annachen/dl_playground
f263dc16b4f0d91f6d33d94e678a9bbe2ace8913
[ "MIT" ]
null
null
null
networks/autoencoder/losses.py
annachen/dl_playground
f263dc16b4f0d91f6d33d94e678a9bbe2ace8913
[ "MIT" ]
null
null
null
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)
24.960199
88
0.590592
de9037d4a2c6b5fbbf0a5f4e22a9796ae161e5b0
4,288
py
Python
Onderdelen/Hoofdscherm.py
RemcoTaal/IDP
33959e29235448c38b7936f16c7421a24130e745
[ "MIT" ]
null
null
null
Onderdelen/Hoofdscherm.py
RemcoTaal/IDP
33959e29235448c38b7936f16c7421a24130e745
[ "MIT" ]
null
null
null
Onderdelen/Hoofdscherm.py
RemcoTaal/IDP
33959e29235448c38b7936f16c7421a24130e745
[ "MIT" ]
null
null
null
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()
34.861789
117
0.541045
de93263b9043812ffa8057bd744f43dfad03bbdf
27
py
Python
py2ifttt/__init__.py
moevis/py2ifttt
99dc2be647c53c9279f2f212528fef7190de7476
[ "MIT" ]
3
2018-05-04T12:50:04.000Z
2020-02-28T03:22:53.000Z
py2ifttt/__init__.py
moevis/py2ifttt
99dc2be647c53c9279f2f212528fef7190de7476
[ "MIT" ]
null
null
null
py2ifttt/__init__.py
moevis/py2ifttt
99dc2be647c53c9279f2f212528fef7190de7476
[ "MIT" ]
null
null
null
from .py2ifttt import IFTTT
27
27
0.851852
de9373d0df66278e0b02dc262104db37303b9a61
3,806
py
Python
server-program/clientApplication.py
ezequias2d/projeto-so
993f3dd12135946fe5b4351e8488b7aa8a18f37e
[ "MIT" ]
null
null
null
server-program/clientApplication.py
ezequias2d/projeto-so
993f3dd12135946fe5b4351e8488b7aa8a18f37e
[ "MIT" ]
null
null
null
server-program/clientApplication.py
ezequias2d/projeto-so
993f3dd12135946fe5b4351e8488b7aa8a18f37e
[ "MIT" ]
null
null
null
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)
34.288288
121
0.547031
de949d00cedaeb2c6790aaae5c34a82b7c16d8c5
230
py
Python
ethernet/recv.py
bobbae/pingcap
c573688b42d35cefdbfa0121580807885aae8869
[ "Unlicense" ]
null
null
null
ethernet/recv.py
bobbae/pingcap
c573688b42d35cefdbfa0121580807885aae8869
[ "Unlicense" ]
1
2019-10-11T16:16:22.000Z
2019-10-11T16:16:22.000Z
ethernet/recv.py
bobbae/pingcap
c573688b42d35cefdbfa0121580807885aae8869
[ "Unlicense" ]
null
null
null
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))
25.555556
75
0.726087
de94dc8dcf783cae1964a6addda472d802119e98
1,110
py
Python
legacy/exam.py
wangxinhe2006/xyzzyy
3267614132a3b9e448b6733f13e8019aa79db922
[ "MIT" ]
1
2021-07-16T02:29:35.000Z
2021-07-16T02:29:35.000Z
legacy/exam.py
wangxinhe2006/xyzzyy
3267614132a3b9e448b6733f13e8019aa79db922
[ "MIT" ]
null
null
null
legacy/exam.py
wangxinhe2006/xyzzyy
3267614132a3b9e448b6733f13e8019aa79db922
[ "MIT" ]
null
null
null
#!/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
48.26087
312
0.664865
de95cb380efb4a5351375e80063db451dd2899b5
3,803
py
Python
TkPy/module.py
tbor8080/pyprog
3642b9af2a92f7369d9b6fa138e47ba22df3271c
[ "MIT" ]
null
null
null
TkPy/module.py
tbor8080/pyprog
3642b9af2a92f7369d9b6fa138e47ba22df3271c
[ "MIT" ]
null
null
null
TkPy/module.py
tbor8080/pyprog
3642b9af2a92f7369d9b6fa138e47ba22df3271c
[ "MIT" ]
null
null
null
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
34.261261
106
0.616618
de97499bd44b3c33d3853cafca12103889273c3c
6,005
py
Python
core/polyaxon/cli/components/tuner.py
Ohtar10/polyaxon
1e41804e4ae6466b6928d06bc6ee6d2d9c7b8931
[ "Apache-2.0" ]
null
null
null
core/polyaxon/cli/components/tuner.py
Ohtar10/polyaxon
1e41804e4ae6466b6928d06bc6ee6d2d9c7b8931
[ "Apache-2.0" ]
null
null
null
core/polyaxon/cli/components/tuner.py
Ohtar10/polyaxon
1e41804e4ae6466b6928d06bc6ee6d2d9c7b8931
[ "Apache-2.0" ]
null
null
null
#!/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
28.732057
85
0.657119
de974a6af213636bff804abc1abfb40a31e4354d
8,810
py
Python
judge/base/__init__.py
fanzeyi/Vulpix
9448e968973073c98231b22663bbebb2a452dcd7
[ "BSD-3-Clause" ]
13
2015-03-08T11:59:28.000Z
2021-07-11T11:58:01.000Z
src/tornado/demos/Vulpix-master/judge/base/__init__.py
ptphp/PyLib
07ac99cf2deb725475f5771b123b9ea1375f5e65
[ "Apache-2.0" ]
null
null
null
src/tornado/demos/Vulpix-master/judge/base/__init__.py
ptphp/PyLib
07ac99cf2deb725475f5771b123b9ea1375f5e65
[ "Apache-2.0" ]
3
2015-05-29T16:14:08.000Z
2016-04-29T07:25:26.000Z
# -*- 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
40.787037
147
0.559932
de9773cffe9839ef07dd2219fd1b0246be382284
1,839
py
Python
src/blog/migrations/0001_initial.py
triump0870/rohan
3bd56ccdc35cb67823117e78dc02becbfbd0b329
[ "MIT" ]
null
null
null
src/blog/migrations/0001_initial.py
triump0870/rohan
3bd56ccdc35cb67823117e78dc02becbfbd0b329
[ "MIT" ]
null
null
null
src/blog/migrations/0001_initial.py
triump0870/rohan
3bd56ccdc35cb67823117e78dc02becbfbd0b329
[ "MIT" ]
null
null
null
# -*- 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
39.12766
152
0.582926
de9904583298a90d85047bd7e803be42fe6b0d62
1,545
py
Python
exams/61a-su20-practice-mt/q6/tests/q6.py
jjllzhang/CS61A
57b68c7c06999210d96499f6d84e4ec99085d396
[ "MIT" ]
1
2022-01-22T11:45:01.000Z
2022-01-22T11:45:01.000Z
exams/61a-su20-practice-mt/q6/tests/q6.py
jjllzhang/CS61A
57b68c7c06999210d96499f6d84e4ec99085d396
[ "MIT" ]
null
null
null
exams/61a-su20-practice-mt/q6/tests/q6.py
jjllzhang/CS61A
57b68c7c06999210d96499f6d84e4ec99085d396
[ "MIT" ]
null
null
null
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'}]}
49.83871
80
0.253722
de9bc65cbfa30de1a8294fb16fd3712d1ce427db
3,566
py
Python
#17.py
Domino2357/daily-coding-problem
95ddef9db53c8b895f2c085ba6399a3144a4f8e6
[ "MIT" ]
null
null
null
#17.py
Domino2357/daily-coding-problem
95ddef9db53c8b895f2c085ba6399a3144a4f8e6
[ "MIT" ]
null
null
null
#17.py
Domino2357/daily-coding-problem
95ddef9db53c8b895f2c085ba6399a3144a4f8e6
[ "MIT" ]
null
null
null
""" 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()
31.280702
124
0.666854
de9bd50729808fda9f77f7ae5831c5d7b432a027
1,315
py
Python
turbot/db.py
emre/turbot
7bc49a8b79bce7f2490036d9255e5b3df8fff4b1
[ "MIT" ]
3
2017-10-17T22:02:06.000Z
2018-05-07T10:29:31.000Z
turbot/db.py
emre/turbot
7bc49a8b79bce7f2490036d9255e5b3df8fff4b1
[ "MIT" ]
null
null
null
turbot/db.py
emre/turbot
7bc49a8b79bce7f2490036d9255e5b3df8fff4b1
[ "MIT" ]
3
2018-10-16T13:28:57.000Z
2021-02-24T13:23:29.000Z
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)
24.351852
56
0.650951
de9c334f30690be489dc54509a0861d269ca08ea
111
py
Python
output/models/ms_data/additional/member_type021_xsd/__init__.py
tefra/xsdata-w3c-tests
b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f
[ "MIT" ]
1
2021-08-14T17:59:21.000Z
2021-08-14T17:59:21.000Z
output/models/ms_data/additional/member_type021_xsd/__init__.py
tefra/xsdata-w3c-tests
b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f
[ "MIT" ]
4
2020-02-12T21:30:44.000Z
2020-04-15T20:06:46.000Z
output/models/ms_data/additional/member_type021_xsd/__init__.py
tefra/xsdata-w3c-tests
b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f
[ "MIT" ]
null
null
null
from output.models.ms_data.additional.member_type021_xsd.member_type021 import Root __all__ = [ "Root", ]
18.5
83
0.774775
de9ca51de5e3ba22b379f50a5e136405d59c8422
4,361
py
Python
estimator.py
2besweet/Covid-19-project
8cfa76662ed0b84999134a9faacbf390e8de31f3
[ "MIT" ]
1
2021-01-31T19:04:11.000Z
2021-01-31T19:04:11.000Z
estimator.py
2besweet/Covid-19-project
8cfa76662ed0b84999134a9faacbf390e8de31f3
[ "MIT" ]
1
2021-05-11T10:34:00.000Z
2021-05-11T10:34:00.000Z
estimator.py
2besweet/Covid-19-project
8cfa76662ed0b84999134a9faacbf390e8de31f3
[ "MIT" ]
null
null
null
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
40.757009
127
0.698234
dea196647fceafaeec0ee9058ac3907d2c76082c
3,752
py
Python
pys3crypto.py
elitest/pys3crypto
9dfef5935ff1c663b8641eaa052e778cdf34a565
[ "MIT" ]
null
null
null
pys3crypto.py
elitest/pys3crypto
9dfef5935ff1c663b8641eaa052e778cdf34a565
[ "MIT" ]
null
null
null
pys3crypto.py
elitest/pys3crypto
9dfef5935ff1c663b8641eaa052e778cdf34a565
[ "MIT" ]
null
null
null
#!/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)
36.427184
125
0.709488
dea3d4b6a9500edd440cd83df9ceb44f4b4e36eb
1,777
py
Python
openTEL_11_19/presentation_figures/tm112_utils.py
psychemedia/presentations
a4d7058b1f716c59a89d0bcd1390ead75d769d43
[ "Apache-2.0" ]
null
null
null
openTEL_11_19/presentation_figures/tm112_utils.py
psychemedia/presentations
a4d7058b1f716c59a89d0bcd1390ead75d769d43
[ "Apache-2.0" ]
null
null
null
openTEL_11_19/presentation_figures/tm112_utils.py
psychemedia/presentations
a4d7058b1f716c59a89d0bcd1390ead75d769d43
[ "Apache-2.0" ]
1
2019-11-05T10:35:40.000Z
2019-11-05T10:35:40.000Z
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!
38.630435
133
0.563309
dea4ec2e4ccc51ad602efcb7e648252790b6ff2d
984
py
Python
src/pages/artists_main.py
haoweini/spotify_stream
83fd13d4da9fb54a595611d4c0cd594eb5b8a9fd
[ "MIT" ]
null
null
null
src/pages/artists_main.py
haoweini/spotify_stream
83fd13d4da9fb54a595611d4c0cd594eb5b8a9fd
[ "MIT" ]
null
null
null
src/pages/artists_main.py
haoweini/spotify_stream
83fd13d4da9fb54a595611d4c0cd594eb5b8a9fd
[ "MIT" ]
null
null
null
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
31.741935
136
0.816057
dea61adbc856f28630be94c795fc850aa45a1770
595
py
Python
Leetcode/res/Longest Common Prefix/2.py
AllanNozomu/CompetitiveProgramming
ac560ab5784d2e2861016434a97e6dcc44e26dc8
[ "MIT" ]
1
2022-03-04T16:06:41.000Z
2022-03-04T16:06:41.000Z
Leetcode/res/Longest Common Prefix/2.py
AllanNozomu/CompetitiveProgramming
ac560ab5784d2e2861016434a97e6dcc44e26dc8
[ "MIT" ]
null
null
null
Leetcode/res/Longest Common Prefix/2.py
AllanNozomu/CompetitiveProgramming
ac560ab5784d2e2861016434a97e6dcc44e26dc8
[ "MIT" ]
null
null
null
# Author: allannozomu # Runtime: 56 ms # Memory: 13 MB
24.791667
58
0.403361
dea6d3637da9acba0c0473fcafaedf9d82d434e7
884
py
Python
tests/factory_fixtures/contact_number.py
donovan-PNW/dwellinglybackend
448df61f6ea81f00dde7dab751f8b2106f0eb7b1
[ "MIT" ]
null
null
null
tests/factory_fixtures/contact_number.py
donovan-PNW/dwellinglybackend
448df61f6ea81f00dde7dab751f8b2106f0eb7b1
[ "MIT" ]
56
2021-08-05T02:49:38.000Z
2022-03-31T19:35:13.000Z
tests/factory_fixtures/contact_number.py
donovan-PNW/dwellinglybackend
448df61f6ea81f00dde7dab751f8b2106f0eb7b1
[ "MIT" ]
null
null
null
import pytest from models.contact_number import ContactNumberModel
29.466667
82
0.70362
dea6d4847a9416f809c2342943ab00ca26b745bd
835
py
Python
tests/test_seq_comparision.py
krzjoa/sciquence
6a5f758c757200fffeb0fdc9206462f1f89e2444
[ "MIT" ]
8
2017-10-23T17:59:35.000Z
2021-05-10T03:01:30.000Z
tests/test_seq_comparision.py
krzjoa/sciquence
6a5f758c757200fffeb0fdc9206462f1f89e2444
[ "MIT" ]
2
2019-08-25T19:24:12.000Z
2019-09-05T12:16:10.000Z
tests/test_seq_comparision.py
krzjoa/sciquence
6a5f758c757200fffeb0fdc9206462f1f89e2444
[ "MIT" ]
2
2018-02-28T09:47:53.000Z
2019-08-25T19:24:16.000Z
import unittest import numpy as np from sciquence.sequences import * if __name__ == '__main__': unittest.main()
30.925926
91
0.475449
dea6f4a43ec33dab31441d90f5221fa29eeb9456
8,191
py
Python
analysis_guis/code_test.py
Sepidak/spikeGUI
25ae60160308c0a34e7180f3e39a1c4dc6aad708
[ "MIT" ]
null
null
null
analysis_guis/code_test.py
Sepidak/spikeGUI
25ae60160308c0a34e7180f3e39a1c4dc6aad708
[ "MIT" ]
3
2021-08-09T21:51:41.000Z
2021-08-09T21:51:45.000Z
analysis_guis/code_test.py
Sepidak/spikeGUI
25ae60160308c0a34e7180f3e39a1c4dc6aad708
[ "MIT" ]
3
2021-10-16T14:07:59.000Z
2021-10-16T17:09:03.000Z
# -*- 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]
37.401826
129
0.605421
dea94f5c042a5187e7e181584aadcbc88251aee3
2,852
py
Python
att/gm.py
thexdesk/foiamail
d135bbb5f52d5a31ca8ce3450bd0035f94a182f5
[ "MIT" ]
null
null
null
att/gm.py
thexdesk/foiamail
d135bbb5f52d5a31ca8ce3450bd0035f94a182f5
[ "MIT" ]
null
null
null
att/gm.py
thexdesk/foiamail
d135bbb5f52d5a31ca8ce3450bd0035f94a182f5
[ "MIT" ]
null
null
null
""" 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
32.781609
119
0.630785
dea9df41450058a28e28c535ce8960f8b770dc38
1,147
py
Python
pex/pip/download_observer.py
sthagen/pantsbuild-pex
bffe6c3641b809cd3b20adbc7fdb2cf7e5f54309
[ "Apache-2.0" ]
null
null
null
pex/pip/download_observer.py
sthagen/pantsbuild-pex
bffe6c3641b809cd3b20adbc7fdb2cf7e5f54309
[ "Apache-2.0" ]
null
null
null
pex/pip/download_observer.py
sthagen/pantsbuild-pex
bffe6c3641b809cd3b20adbc7fdb2cf7e5f54309
[ "Apache-2.0" ]
null
null
null
# 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)
23.408163
66
0.646905
deaa58029f2b553b02dbaa81816ff5ce9e456f8a
3,424
py
Python
dispatchlib/types.py
ryxcommar/dispatchlib
bf3b6e5617af41579b240a7733cd9cc86a8a38ed
[ "MIT" ]
null
null
null
dispatchlib/types.py
ryxcommar/dispatchlib
bf3b6e5617af41579b240a7733cd9cc86a8a38ed
[ "MIT" ]
null
null
null
dispatchlib/types.py
ryxcommar/dispatchlib
bf3b6e5617af41579b240a7733cd9cc86a8a38ed
[ "MIT" ]
null
null
null
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):
26.96063
79
0.651285
deabe0363fc1143c6a3fe5cc62b534d0a3e480ca
2,096
py
Python
pbpstats/data_loader/nba_possession_loader.py
pauldevos/pbpstats
71c0b5e2bd45d0ca031646c70cd1c1f30c6a7152
[ "MIT" ]
null
null
null
pbpstats/data_loader/nba_possession_loader.py
pauldevos/pbpstats
71c0b5e2bd45d0ca031646c70cd1c1f30c6a7152
[ "MIT" ]
null
null
null
pbpstats/data_loader/nba_possession_loader.py
pauldevos/pbpstats
71c0b5e2bd45d0ca031646c70cd1c1f30c6a7152
[ "MIT" ]
null
null
null
from pbpstats.resources.enhanced_pbp import StartOfPeriod
39.54717
121
0.624046
dead01ec590550c2d98b328ed72222f137d3778b
7,033
py
Python
vmware_nsx_tempest/tests/nsxv/api/base_provider.py
gravity-tak/vmware-nsx-tempest
3a1007d401c471d989345bb5a3f9769f84bd4ac6
[ "Apache-2.0" ]
null
null
null
vmware_nsx_tempest/tests/nsxv/api/base_provider.py
gravity-tak/vmware-nsx-tempest
3a1007d401c471d989345bb5a3f9769f84bd4ac6
[ "Apache-2.0" ]
null
null
null
vmware_nsx_tempest/tests/nsxv/api/base_provider.py
gravity-tak/vmware-nsx-tempest
3a1007d401c471d989345bb5a3f9769f84bd4ac6
[ "Apache-2.0" ]
null
null
null
# 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 {}
39.072222
78
0.65278
deadc8ea87d0e57d203447ee89704b440dd4a622
3,650
py
Python
read_csv.py
BigTony666/football-manager
12a4c3dc2bb60f9634b419b7c230d6f78df8d650
[ "MIT" ]
11
2019-04-23T23:15:43.000Z
2021-07-13T06:37:25.000Z
read_csv.py
BigTony666/football-manager
12a4c3dc2bb60f9634b419b7c230d6f78df8d650
[ "MIT" ]
null
null
null
read_csv.py
BigTony666/football-manager
12a4c3dc2bb60f9634b419b7c230d6f78df8d650
[ "MIT" ]
2
2019-03-07T21:07:34.000Z
2020-04-19T15:28:31.000Z
#!/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()
27.037037
117
0.596164
deaf2eb47ddc3dd822c0c77690801b5b8b2a48b0
1,492
py
Python
layers/ternary_ops.py
victorjoos/QuantizedNeuralNetworks-Keras-Tensorflow
4080ddff9c9e9a6fd5c1dd90997c63968195bb7e
[ "BSD-3-Clause" ]
1
2018-08-22T12:13:25.000Z
2018-08-22T12:13:25.000Z
layers/ternary_ops.py
victorjoos/QuantizedNeuralNetworks-Keras-Tensorflow
4080ddff9c9e9a6fd5c1dd90997c63968195bb7e
[ "BSD-3-Clause" ]
null
null
null
layers/ternary_ops.py
victorjoos/QuantizedNeuralNetworks-Keras-Tensorflow
4080ddff9c9e9a6fd5c1dd90997c63968195bb7e
[ "BSD-3-Clause" ]
null
null
null
# -*- 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))
27.127273
99
0.632038
deafcfc518bad5ab9572431f7de653f846580238
1,050
py
Python
python/5.concurrent/ZCoroutine/z_new_ipc/8.condition.py
lotapp/BaseCode
0255f498e1fe67ed2b3f66c84c96e44ef1f7d320
[ "Apache-2.0" ]
25
2018-06-13T08:13:44.000Z
2020-11-19T14:02:11.000Z
python/5.concurrent/ZCoroutine/z_new_ipc/8.condition.py
lotapp/BaseCode
0255f498e1fe67ed2b3f66c84c96e44ef1f7d320
[ "Apache-2.0" ]
null
null
null
python/5.concurrent/ZCoroutine/z_new_ipc/8.condition.py
lotapp/BaseCode
0255f498e1fe67ed2b3f66c84c96e44ef1f7d320
[ "Apache-2.0" ]
13
2018-06-13T08:13:38.000Z
2022-01-06T06:45:07.000Z
import asyncio cond = None p_list = [] # # if __name__ == "__main__": asyncio.run(main())
23.333333
75
0.526667
deb039b791ed71607787c0d4ffc9f5bb4edef521
930
py
Python
Q846_Hand-of-Straights.py
xiaosean/leetcode_python
844ece02d699bfc620519bd94828ed0e18597f3e
[ "MIT" ]
null
null
null
Q846_Hand-of-Straights.py
xiaosean/leetcode_python
844ece02d699bfc620519bd94828ed0e18597f3e
[ "MIT" ]
null
null
null
Q846_Hand-of-Straights.py
xiaosean/leetcode_python
844ece02d699bfc620519bd94828ed0e18597f3e
[ "MIT" ]
null
null
null
from collections import Counter
31
63
0.410753
deb1c543d933d4026fb5899f87ff8c3384301fea
174
py
Python
hover/utils/misc.py
haochuanwei/hover
53eb38c718e44445b18a97e391b7f90270802b04
[ "MIT" ]
1
2020-12-08T13:04:18.000Z
2020-12-08T13:04:18.000Z
hover/utils/misc.py
MaxCodeXTC/hover
feeb0e0c59295a3c883823ccef918dfe388b603c
[ "MIT" ]
null
null
null
hover/utils/misc.py
MaxCodeXTC/hover
feeb0e0c59295a3c883823ccef918dfe388b603c
[ "MIT" ]
null
null
null
"""Mini-functions that do not belong elsewhere.""" from datetime import datetime
24.857143
50
0.718391
deb28e42e8f7639fbbb2df4266120ee03fd2a028
193
py
Python
admin.py
sfchronicle/najee
0c66b05ba10616243d9828465da97dee7bfedc0d
[ "MIT", "Unlicense" ]
null
null
null
admin.py
sfchronicle/najee
0c66b05ba10616243d9828465da97dee7bfedc0d
[ "MIT", "Unlicense" ]
null
null
null
admin.py
sfchronicle/najee
0c66b05ba10616243d9828465da97dee7bfedc0d
[ "MIT", "Unlicense" ]
null
null
null
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
16.083333
48
0.766839
deb449183523148b00bdabf18e21714bbe3551c8
467
py
Python
src/courses/migrations/0006_auto_20200521_2038.py
GiomarOsorio/another-e-learning-platform
5cfc76420eb3466691f5187c915c179afb13199a
[ "MIT" ]
null
null
null
src/courses/migrations/0006_auto_20200521_2038.py
GiomarOsorio/another-e-learning-platform
5cfc76420eb3466691f5187c915c179afb13199a
[ "MIT" ]
8
2020-06-25T22:16:20.000Z
2022-03-12T00:39:27.000Z
src/courses/migrations/0006_auto_20200521_2038.py
GiomarOsorio/another-e-learning-platform
5cfc76420eb3466691f5187c915c179afb13199a
[ "MIT" ]
null
null
null
# Generated by Django 3.0.6 on 2020-05-21 20:38 from django.db import migrations, models
24.578947
129
0.631692
deb684b2e0198456aadb77cab383b2b6c0c2748f
776
py
Python
mypi/settings.py
sujaymansingh/mypi
768bdda2ed43faba8a69c7985ee063e1016b9299
[ "BSD-2-Clause-FreeBSD" ]
4
2016-08-22T17:13:43.000Z
2020-10-21T16:50:07.000Z
mypi/settings.py
sujaymansingh/mypi
768bdda2ed43faba8a69c7985ee063e1016b9299
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
mypi/settings.py
sujaymansingh/mypi
768bdda2ed43faba8a69c7985ee063e1016b9299
[ "BSD-2-Clause-FreeBSD" ]
1
2016-08-22T17:13:47.000Z
2016-08-22T17:13:47.000Z
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]
29.846154
72
0.744845
deb7178741e12b76740cccb10cf2e3f8e186116d
1,866
py
Python
alipay/aop/api/domain/KbAdvertPreserveCommissionClause.py
articuly/alipay-sdk-python-all
0259cd28eca0f219b97dac7f41c2458441d5e7a6
[ "Apache-2.0" ]
null
null
null
alipay/aop/api/domain/KbAdvertPreserveCommissionClause.py
articuly/alipay-sdk-python-all
0259cd28eca0f219b97dac7f41c2458441d5e7a6
[ "Apache-2.0" ]
null
null
null
alipay/aop/api/domain/KbAdvertPreserveCommissionClause.py
articuly/alipay-sdk-python-all
0259cd28eca0f219b97dac7f41c2458441d5e7a6
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- import simplejson as json from alipay.aop.api.constant.ParamConstants import *
29.15625
81
0.587889
deba0ac91a90f7d9408ab094dc6d137f7476170c
4,495
py
Python
smart_contract/__init__.py
publicqi/CTFd-Fox
b1d0169db884cdf3cb665faa8987443e7630d108
[ "MIT" ]
1
2021-01-09T15:20:14.000Z
2021-01-09T15:20:14.000Z
smart_contract/__init__.py
publicqi/CTFd-Fox
b1d0169db884cdf3cb665faa8987443e7630d108
[ "MIT" ]
null
null
null
smart_contract/__init__.py
publicqi/CTFd-Fox
b1d0169db884cdf3cb665faa8987443e7630d108
[ "MIT" ]
null
null
null
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
32.338129
87
0.629588
deba5b19ee11e4b42757cf8302210ae77f1c6474
295
py
Python
01-data_types/d13.py
philiphinton/learn_python
6ddfe3c7818d6c919bfa49bd6302c75ee761b6a4
[ "MIT" ]
null
null
null
01-data_types/d13.py
philiphinton/learn_python
6ddfe3c7818d6c919bfa49bd6302c75ee761b6a4
[ "MIT" ]
3
2022-01-17T22:55:09.000Z
2022-01-26T07:26:13.000Z
01-data_types/d13.py
philiphinton/learn_python
6ddfe3c7818d6c919bfa49bd6302c75ee761b6a4
[ "MIT" ]
1
2021-12-14T01:33:21.000Z
2021-12-14T01:33:21.000Z
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())
17.352941
31
0.610169
debc22c03ed999e303334d1da3320e421b5bfacc
119
py
Python
applications/jupyter-extension/nteract_on_jupyter/notebooks/utils/cb/python/__init__.py
jjhenkel/nteract
088222484b59af14b1da22de4d0990d8925adf95
[ "BSD-3-Clause" ]
null
null
null
applications/jupyter-extension/nteract_on_jupyter/notebooks/utils/cb/python/__init__.py
jjhenkel/nteract
088222484b59af14b1da22de4d0990d8925adf95
[ "BSD-3-Clause" ]
null
null
null
applications/jupyter-extension/nteract_on_jupyter/notebooks/utils/cb/python/__init__.py
jjhenkel/nteract
088222484b59af14b1da22de4d0990d8925adf95
[ "BSD-3-Clause" ]
null
null
null
from .surface import * from .modifiers import * from .evaluator import Evaluator from .lowlevel import display_results
23.8
37
0.815126
debcd3fde3c56a4f5ccca0c23d8a57a7d2afd960
588
py
Python
Numbers/PrimeFac.py
Arjuna197/the100
2963b4fe1b1b8e673a23b2cf97f4bcb263af9781
[ "MIT" ]
1
2022-02-20T18:49:49.000Z
2022-02-20T18:49:49.000Z
Numbers/PrimeFac.py
dan-garvey/the100
2963b4fe1b1b8e673a23b2cf97f4bcb263af9781
[ "MIT" ]
13
2017-12-13T02:31:54.000Z
2017-12-13T02:37:45.000Z
Numbers/PrimeFac.py
dan-garvey/the100
2963b4fe1b1b8e673a23b2cf97f4bcb263af9781
[ "MIT" ]
null
null
null
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)
21.777778
40
0.547619
debd457fd6d2c1141a031eefaca5f163110cfa64
1,130
py
Python
src/wtfjson/validators/url.py
binary-butterfly/wtfjson
551ad07c895ce3c94ac3015b6b5ecc2102599b56
[ "MIT" ]
null
null
null
src/wtfjson/validators/url.py
binary-butterfly/wtfjson
551ad07c895ce3c94ac3015b6b5ecc2102599b56
[ "MIT" ]
1
2021-10-11T08:55:45.000Z
2021-10-11T08:55:45.000Z
src/wtfjson/validators/url.py
binary-butterfly/wtfjson
551ad07c895ce3c94ac3015b6b5ecc2102599b56
[ "MIT" ]
null
null
null
# 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
30.540541
103
0.650442
debe6ce18f853e6b1e54abf97ade00987edf8450
1,270
py
Python
runner/run_descriptions/runs/curious_vs_vanilla.py
alex-petrenko/curious-rl
6cd0eb78ab409c68f8dad1a8542d625f0dd39114
[ "MIT" ]
18
2018-12-29T01:52:25.000Z
2021-11-08T06:48:20.000Z
runner/run_descriptions/runs/curious_vs_vanilla.py
alex-petrenko/curious-rl
6cd0eb78ab409c68f8dad1a8542d625f0dd39114
[ "MIT" ]
2
2019-06-13T12:52:55.000Z
2019-10-30T03:27:11.000Z
runner/run_descriptions/runs/curious_vs_vanilla.py
alex-petrenko/curious-rl
6cd0eb78ab409c68f8dad1a8542d625f0dd39114
[ "MIT" ]
3
2019-05-11T07:50:53.000Z
2021-11-18T08:15:56.000Z
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)
40.967742
145
0.711024
debed6abf0cd6d720ad9aac4713a4ef0c18b842a
383
py
Python
xappt_qt/__init__.py
cmontesano/xappt_qt
74f8c62e0104a67b4b4eb65382df851221bf0bab
[ "MIT" ]
null
null
null
xappt_qt/__init__.py
cmontesano/xappt_qt
74f8c62e0104a67b4b4eb65382df851221bf0bab
[ "MIT" ]
12
2020-10-11T22:42:12.000Z
2021-10-04T19:38:51.000Z
xappt_qt/__init__.py
cmontesano/xappt_qt
74f8c62e0104a67b4b4eb65382df851221bf0bab
[ "MIT" ]
1
2021-09-29T23:53:34.000Z
2021-09-29T23:53:34.000Z
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
27.357143
65
0.749347
dec0b14005ec6feafc62d8f18253556640fa35db
145,150
py
Python
py/countdowntourney.py
elocemearg/atropine
894010bcc89d4e6962cf3fc15ef526068c38898d
[ "CC-BY-4.0" ]
null
null
null
py/countdowntourney.py
elocemearg/atropine
894010bcc89d4e6962cf3fc15ef526068c38898d
[ "CC-BY-4.0" ]
null
null
null
py/countdowntourney.py
elocemearg/atropine
894010bcc89d4e6962cf3fc15ef526068c38898d
[ "CC-BY-4.0" ]
null
null
null
#!/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"
39.691004
388
0.586035
dec0da50ce4a56fc78832aa67c6d71d1a1a1c437
995
py
Python
t/plugin/plugin_020deploy_test.py
jrmsdev/pysadm
0d6b3f0c8d870d83ab499c8d9487ec8e3a89fc37
[ "BSD-3-Clause" ]
1
2019-10-15T08:37:56.000Z
2019-10-15T08:37:56.000Z
t/plugin/plugin_020deploy_test.py
jrmsdev/pysadm
0d6b3f0c8d870d83ab499c8d9487ec8e3a89fc37
[ "BSD-3-Clause" ]
null
null
null
t/plugin/plugin_020deploy_test.py
jrmsdev/pysadm
0d6b3f0c8d870d83ab499c8d9487ec8e3a89fc37
[ "BSD-3-Clause" ]
null
null
null
# Copyright (c) Jeremas Casteglione <jrmsdev@gmail.com> # See LICENSE file. from glob import glob from os import path, makedirs
36.851852
80
0.676382
dec30d56b6d0887d305f33e490a67d25b3dd39cd
4,189
py
Python
jsonReadWrite.py
nsobczak/ActivityWatchToCSV
cefb67e9f1c834008f2b39c0baf6c7c506327a4d
[ "Apache-2.0" ]
null
null
null
jsonReadWrite.py
nsobczak/ActivityWatchToCSV
cefb67e9f1c834008f2b39c0baf6c7c506327a4d
[ "Apache-2.0" ]
null
null
null
jsonReadWrite.py
nsobczak/ActivityWatchToCSV
cefb67e9f1c834008f2b39c0baf6c7c506327a4d
[ "Apache-2.0" ]
null
null
null
""" ############## # 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
30.136691
121
0.545476
dec3721fd14d0e108bf21ac443dd1b7796946011
286
py
Python
pythons/reTesting.py
whats2000/coding-stuff-I-make-from-learning
d82809ba12f9d74bdb41eca5ba8f12f4cd96929e
[ "MIT" ]
null
null
null
pythons/reTesting.py
whats2000/coding-stuff-I-make-from-learning
d82809ba12f9d74bdb41eca5ba8f12f4cd96929e
[ "MIT" ]
null
null
null
pythons/reTesting.py
whats2000/coding-stuff-I-make-from-learning
d82809ba12f9d74bdb41eca5ba8f12f4cd96929e
[ "MIT" ]
null
null
null
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")
16.823529
60
0.562937
dec3efd877d3ce87cbe9fc53530bf43be70d8149
306
py
Python
2021-12-23/1.py
xiaozhiyuqwq/seniorschool
7375038b00a6d2deaec5d70bfac25ddbf4d2558e
[ "Apache-2.0" ]
null
null
null
2021-12-23/1.py
xiaozhiyuqwq/seniorschool
7375038b00a6d2deaec5d70bfac25ddbf4d2558e
[ "Apache-2.0" ]
null
null
null
2021-12-23/1.py
xiaozhiyuqwq/seniorschool
7375038b00a6d2deaec5d70bfac25ddbf4d2558e
[ "Apache-2.0" ]
null
null
null
# 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
21.857143
60
0.46732
dec6337c650811d4d0bda0d9fb32eb5e333b7344
15,088
py
Python
Project-2/Ishan Pandey/job_compare.py
Mercury1508/IEEE-LEAD-2.0
91d24ccf2f24c62f92f0d23bcfcb3988e6d5acd8
[ "MIT" ]
1
2021-06-03T16:08:33.000Z
2021-06-03T16:08:33.000Z
Project-2/Ishan Pandey/job_compare.py
Mercury1508/IEEE-LEAD-2.0
91d24ccf2f24c62f92f0d23bcfcb3988e6d5acd8
[ "MIT" ]
16
2021-04-27T12:58:03.000Z
2021-05-28T14:02:14.000Z
Project-2/Ishan Pandey/job_compare.py
Mercury1508/IEEE-LEAD-2.0
91d24ccf2f24c62f92f0d23bcfcb3988e6d5acd8
[ "MIT" ]
70
2021-04-26T13:48:35.000Z
2021-05-28T21:04:34.000Z
# 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()
57.808429
176
0.696911
dec771d07fef05c3b6f9bec75d34bca56cffa1b5
3,648
py
Python
data_augmentor/multidimension.py
ZhiangChen/tornado_ML
d8bded61a6a234ca67e31776bc8576c6c18f5621
[ "MIT" ]
2
2018-12-09T20:08:51.000Z
2021-02-01T17:49:14.000Z
data_augmentor/multidimension.py
ZhiangChen/tornado_ML
d8bded61a6a234ca67e31776bc8576c6c18f5621
[ "MIT" ]
1
2019-11-15T06:15:03.000Z
2019-11-15T06:15:03.000Z
multidimension.py
DREAMS-lab/data_augmentor
f204ee3af805b17d9946d3d5c6e7ca62398f09e5
[ "MIT" ]
null
null
null
""" 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")
35.076923
105
0.569353
dec7a039bcd25fbdc90d163100b8870f23f0424a
399
py
Python
tests/serializers/test_template_data_serializers.py
banillie/bcompiler-engine
26b63b6e630e2925175ffff6b48b42d70f7ba544
[ "MIT" ]
2
2019-09-23T08:51:48.000Z
2019-10-14T08:44:28.000Z
tests/serializers/test_template_data_serializers.py
banillie/bcompiler-engine
26b63b6e630e2925175ffff6b48b42d70f7ba544
[ "MIT" ]
27
2019-07-08T11:15:03.000Z
2020-06-22T15:47:25.000Z
tests/serializers/test_template_data_serializers.py
yulqen/bcompiler-engine
40eff19e04eabacac991bb34d31a7e7a7d6b729a
[ "MIT" ]
1
2019-09-07T14:05:16.000Z
2019-09-07T14:05:16.000Z
import json from engine.serializers.template import TemplateCellSerializer
30.692308
75
0.802005
deca8e26bb6a2a9ae53903a22809984f7a74b454
26,490
py
Python
project.py
PetruSicoe/Python101-GameProject
82121a8e110ee484acdf85843725882d60957b25
[ "CC-BY-4.0" ]
null
null
null
project.py
PetruSicoe/Python101-GameProject
82121a8e110ee484acdf85843725882d60957b25
[ "CC-BY-4.0" ]
null
null
null
project.py
PetruSicoe/Python101-GameProject
82121a8e110ee484acdf85843725882d60957b25
[ "CC-BY-4.0" ]
null
null
null
#!/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()
40.197269
177
0.555795
decaa14b52fa5524baf2d5d190931296e44de823
2,018
py
Python
Modules/CrossMapLRN.py
EmilPi/PuzzleLib
31aa0fab3b5e9472b9b9871ca52e4d94ea683fa9
[ "Apache-2.0" ]
52
2020-02-28T20:40:15.000Z
2021-08-25T05:35:17.000Z
Modules/CrossMapLRN.py
EmilPi/PuzzleLib
31aa0fab3b5e9472b9b9871ca52e4d94ea683fa9
[ "Apache-2.0" ]
2
2021-02-14T15:57:03.000Z
2021-10-05T12:21:34.000Z
Modules/CrossMapLRN.py
EmilPi/PuzzleLib
31aa0fab3b5e9472b9b9871ca52e4d94ea683fa9
[ "Apache-2.0" ]
8
2020-02-28T20:40:11.000Z
2020-07-09T13:27:23.000Z
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()
32.031746
101
0.700198
decc19f50e9a41be1bc95cb6e0bf5f4f77162b78
4,802
py
Python
src/metrics.py
enryH/specpride
1bedd87dc8f31a6b86426c6e03dc0c27706bc9aa
[ "Apache-2.0" ]
2
2020-01-14T12:02:52.000Z
2020-01-14T14:03:30.000Z
src/metrics.py
enryH/specpride
1bedd87dc8f31a6b86426c6e03dc0c27706bc9aa
[ "Apache-2.0" ]
5
2019-12-09T10:59:10.000Z
2020-01-16T14:32:00.000Z
src/metrics.py
enryH/specpride
1bedd87dc8f31a6b86426c6e03dc0c27706bc9aa
[ "Apache-2.0" ]
9
2020-01-14T12:26:54.000Z
2020-01-16T08:26:06.000Z
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())
31.592105
79
0.660975
deccbee42c5be781692fc226272ac89e27a4e7a6
797
py
Python
examples/multi-class_neural_network.py
sun1638650145/classicML
7e0c2155bccb6e491a150ee689d3786526b74565
[ "Apache-2.0" ]
12
2020-05-10T12:11:06.000Z
2021-10-31T13:23:55.000Z
examples/multi-class_neural_network.py
sun1638650145/classicML
7e0c2155bccb6e491a150ee689d3786526b74565
[ "Apache-2.0" ]
null
null
null
examples/multi-class_neural_network.py
sun1638650145/classicML
7e0c2155bccb6e491a150ee689d3786526b74565
[ "Apache-2.0" ]
2
2021-01-17T06:22:05.000Z
2021-01-18T14:32:51.000Z
""" 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])
28.464286
72
0.644918
decdd56ee9283490fb231ea62e1de89aa2fa1fee
2,596
py
Python
pool/serializer/PoolSerializer.py
salran40/POAP
9ff2ab68b55aeffe104d127c4beb8b1372b2c8de
[ "Apache-2.0" ]
null
null
null
pool/serializer/PoolSerializer.py
salran40/POAP
9ff2ab68b55aeffe104d127c4beb8b1372b2c8de
[ "Apache-2.0" ]
null
null
null
pool/serializer/PoolSerializer.py
salran40/POAP
9ff2ab68b55aeffe104d127c4beb8b1372b2c8de
[ "Apache-2.0" ]
null
null
null
__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']
36.56338
91
0.724961
dece77460bb0515a4dff433a0f6f8e80d7adc76c
3,735
py
Python
yiffscraper/downloader.py
ScraperT/yiffscraper
49482a544fc7f11e6ea5db2626dbc2404529d656
[ "MIT" ]
42
2019-12-23T23:55:12.000Z
2022-02-07T04:12:59.000Z
yiffscraper/downloader.py
arin17bishwa/yiffscraper
49482a544fc7f11e6ea5db2626dbc2404529d656
[ "MIT" ]
7
2020-01-12T13:04:56.000Z
2020-05-18T07:11:51.000Z
yiffscraper/downloader.py
arin17bishwa/yiffscraper
49482a544fc7f11e6ea5db2626dbc2404529d656
[ "MIT" ]
7
2020-03-12T03:47:53.000Z
2020-07-26T08:05:55.000Z
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
31.923077
122
0.626774
ded08df80894e1241c99188254ecd7f7c259352b
380
py
Python
linked_lists/find_loop.py
maanavshah/coding-interview
4c842cdbc6870da79684635f379966d1caec2162
[ "MIT" ]
null
null
null
linked_lists/find_loop.py
maanavshah/coding-interview
4c842cdbc6870da79684635f379966d1caec2162
[ "MIT" ]
null
null
null
linked_lists/find_loop.py
maanavshah/coding-interview
4c842cdbc6870da79684635f379966d1caec2162
[ "MIT" ]
null
null
null
# O(n) time | O(1) space
20
30
0.560526
ded4491d8cef57cccb094e0f83641638968be15a
3,066
py
Python
src/tests/attention_test.py
feperessim/attention_keras
322a16ee147122026b63305aaa5e899d9e5de883
[ "MIT" ]
422
2019-03-17T13:08:59.000Z
2022-03-31T12:08:29.000Z
src/tests/attention_test.py
JKhodadadi/attention_keras
322a16ee147122026b63305aaa5e899d9e5de883
[ "MIT" ]
51
2019-03-17T20:08:11.000Z
2022-03-18T03:51:42.000Z
src/tests/attention_test.py
JKhodadadi/attention_keras
322a16ee147122026b63305aaa5e899d9e5de883
[ "MIT" ]
285
2019-03-17T19:06:22.000Z
2022-03-31T02:29:17.000Z
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'''
37.390244
101
0.7182
ded5e7681d684ad45f836b0b523b89035ed45f16
1,572
py
Python
Python/9248_Suffix_Array/9248_suffix_array_lcp_array.py
ire4564/Baekjoon_Solutions
3e6689efa30d6b850cdc29570c76408a1e1b2b49
[ "Apache-2.0" ]
4
2020-11-17T09:52:29.000Z
2020-12-13T11:36:14.000Z
Python/9248_Suffix_Array/9248_suffix_array_lcp_array.py
ire4564/Baekjoon_Solutions
3e6689efa30d6b850cdc29570c76408a1e1b2b49
[ "Apache-2.0" ]
2
2020-11-19T11:21:02.000Z
2020-11-19T22:07:15.000Z
Python/9248_Suffix_Array/9248_suffix_array_lcp_array.py
ire4564/Baekjoon_Solutions
3e6689efa30d6b850cdc29570c76408a1e1b2b49
[ "Apache-2.0" ]
12
2020-11-17T06:55:13.000Z
2021-05-16T14:39:37.000Z
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=' ')
20.684211
64
0.448473
ded667020b68f181edc8b21f22dbb71557c2c7cc
1,329
py
Python
lgr/tools/compare/utils.py
ron813c/lgr-core
68ba730bf7f9e61cb97c9c08f61bc58b8ea24e7b
[ "BSD-3-Clause" ]
7
2017-07-10T22:39:52.000Z
2021-06-25T20:19:28.000Z
lgr/tools/compare/utils.py
ron813c/lgr-core
68ba730bf7f9e61cb97c9c08f61bc58b8ea24e7b
[ "BSD-3-Clause" ]
13
2016-10-26T19:42:00.000Z
2021-12-13T19:43:42.000Z
lgr/tools/compare/utils.py
ron813c/lgr-core
68ba730bf7f9e61cb97c9c08f61bc58b8ea24e7b
[ "BSD-3-Clause" ]
8
2016-11-07T15:40:27.000Z
2020-09-22T13:48:52.000Z
# -*- 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)
24.611111
77
0.574116
ded78378f0da72d7d6e0a021bbb1b4a6004db8f0
2,386
py
Python
tests/test__file_object.py
StateArchivesOfNorthCarolina/tomes_metadata
8b73096c1b16e0db2895a6c01d4fc4fd9621cf55
[ "MIT" ]
null
null
null
tests/test__file_object.py
StateArchivesOfNorthCarolina/tomes_metadata
8b73096c1b16e0db2895a6c01d4fc4fd9621cf55
[ "MIT" ]
2
2018-09-12T20:36:22.000Z
2018-09-13T20:14:50.000Z
tests/test__file_object.py
StateArchivesOfNorthCarolina/tomes-packager
8b73096c1b16e0db2895a6c01d4fc4fd9621cf55
[ "MIT" ]
null
null
null
#!/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)
27.744186
84
0.642079
ded98a6b09e99064104171c0327f9f5f8f68c1fa
244
py
Python
tests/test_helpers.py
c137digital/unv_web
52bea090c630b4e2a393c70907d35c9558d259fa
[ "MIT" ]
null
null
null
tests/test_helpers.py
c137digital/unv_web
52bea090c630b4e2a393c70907d35c9558d259fa
[ "MIT" ]
null
null
null
tests/test_helpers.py
c137digital/unv_web
52bea090c630b4e2a393c70907d35c9558d259fa
[ "MIT" ]
null
null
null
from unv.web.helpers import url_with_domain, url_for_static
24.4
63
0.737705
deda4206dc73f8dbe4b33d7d756e79510962b4d8
10,829
py
Python
game.py
IliketoTranslate/Pickaxe-clicker
e74ebd66842bd47c4ed1c4460e9f45e30a2ad1d7
[ "MIT" ]
null
null
null
game.py
IliketoTranslate/Pickaxe-clicker
e74ebd66842bd47c4ed1c4460e9f45e30a2ad1d7
[ "MIT" ]
null
null
null
game.py
IliketoTranslate/Pickaxe-clicker
e74ebd66842bd47c4ed1c4460e9f45e30a2ad1d7
[ "MIT" ]
null
null
null
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()
49.447489
296
0.576138
dedba85b4c2428f8778fd3f7f0d4d19fee14a759
4,383
py
Python
tests/test_predictor.py
WeijieChen2017/pytorch-3dunet
15c782481cb7bc3e2083a80bcc8b114cc8697c20
[ "MIT" ]
1
2021-08-04T04:03:37.000Z
2021-08-04T04:03:37.000Z
tests/test_predictor.py
LalithShiyam/pytorch-3dunet
f6b6c13cb0bb6194e95976b0245b76aaa9e9a496
[ "MIT" ]
null
null
null
tests/test_predictor.py
LalithShiyam/pytorch-3dunet
f6b6c13cb0bb6194e95976b0245b76aaa9e9a496
[ "MIT" ]
1
2022-03-14T04:43:24.000Z
2022-03-14T04:43:24.000Z
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
35.346774
114
0.62423
dedbd6180bc5f6b44a69dd4d23b7983f144a3239
2,560
py
Python
catalog/views.py
DigimundoTesca/Tv-Mundo
09904759d1f4f9bf2d5c7c31b97af82c3c963bfd
[ "MIT" ]
null
null
null
catalog/views.py
DigimundoTesca/Tv-Mundo
09904759d1f4f9bf2d5c7c31b97af82c3c963bfd
[ "MIT" ]
6
2017-09-19T07:26:14.000Z
2017-09-27T10:06:49.000Z
catalog/views.py
DigimundoTesca/Tv-Mundo
09904759d1f4f9bf2d5c7c31b97af82c3c963bfd
[ "MIT" ]
null
null
null
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
24.380952
76
0.622656
dedc38f09d494832d839db3e999852609e6a45ac
519
py
Python
python/database/get_twitter_predict_by_order.py
visdata/DeepClue
8d80ecd783919c97ba225db67664a0dfe5f3fb37
[ "Apache-2.0" ]
1
2020-12-06T08:04:32.000Z
2020-12-06T08:04:32.000Z
python/database/get_twitter_predict_by_order.py
visdata/DeepClue
8d80ecd783919c97ba225db67664a0dfe5f3fb37
[ "Apache-2.0" ]
null
null
null
python/database/get_twitter_predict_by_order.py
visdata/DeepClue
8d80ecd783919c97ba225db67664a0dfe5f3fb37
[ "Apache-2.0" ]
null
null
null
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()
25.95
99
0.714836
dedd33f5b7d0869e4ad454abba7866e56edaacbb
301
py
Python
examples/matplotlib/mpl_plot_dot.py
sudojarvis/arviz
73531be4f23df7d764b2e3bec8c5ef5cb882590d
[ "Apache-2.0" ]
1,159
2018-04-03T08:50:54.000Z
2022-03-31T18:03:52.000Z
examples/matplotlib/mpl_plot_dot.py
sudojarvis/arviz
73531be4f23df7d764b2e3bec8c5ef5cb882590d
[ "Apache-2.0" ]
1,656
2018-03-23T14:15:05.000Z
2022-03-31T14:00:28.000Z
examples/matplotlib/mpl_plot_dot.py
sudojarvis/arviz
73531be4f23df7d764b2e3bec8c5ef5cb882590d
[ "Apache-2.0" ]
316
2018-04-03T14:25:52.000Z
2022-03-25T10:41:29.000Z
""" 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()
15.842105
70
0.69103
dedeaccf1b8d4bb294ba8b9e2278d86179d43f0e
405
py
Python
kattis/solutions/alphabetspam.py
yifeng-pan/competitive_programming
c59edb1e08aa2db2158a814e3d34f4302658d98e
[ "Unlicense" ]
null
null
null
kattis/solutions/alphabetspam.py
yifeng-pan/competitive_programming
c59edb1e08aa2db2158a814e3d34f4302658d98e
[ "Unlicense" ]
null
null
null
kattis/solutions/alphabetspam.py
yifeng-pan/competitive_programming
c59edb1e08aa2db2158a814e3d34f4302658d98e
[ "Unlicense" ]
null
null
null
# 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))
15.576923
47
0.511111
dee0061d48e6e49cac68657f95ed5ac4927eaa8e
3,813
py
Python
src/chain_orientation_three_vars_symbolic.py
Scriddie/Varsortability
357213d5ceefb6362060c56e12c18b41dc689306
[ "MIT" ]
4
2021-12-08T07:54:00.000Z
2022-03-09T07:55:21.000Z
src/chain_orientation_three_vars_symbolic.py
Scriddie/Varsortability
357213d5ceefb6362060c56e12c18b41dc689306
[ "MIT" ]
null
null
null
src/chain_orientation_three_vars_symbolic.py
Scriddie/Varsortability
357213d5ceefb6362060c56e12c18b41dc689306
[ "MIT" ]
1
2022-03-09T07:55:43.000Z
2022-03-09T07:55:43.000Z
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()
28.455224
69
0.441385
dee00922a67f6dff4732cf526028648896d0fc92
2,290
py
Python
Phototweet.py
sbamueller/RasperryPi_BildFeinstaub
3666db384ead64893b3c548065aa31cef6c126af
[ "Apache-2.0" ]
null
null
null
Phototweet.py
sbamueller/RasperryPi_BildFeinstaub
3666db384ead64893b3c548065aa31cef6c126af
[ "Apache-2.0" ]
null
null
null
Phototweet.py
sbamueller/RasperryPi_BildFeinstaub
3666db384ead64893b3c548065aa31cef6c126af
[ "Apache-2.0" ]
null
null
null
#!/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)
31.369863
80
0.691266
dee0dfeab71167aee2a17e14945c71c0e31e66be
1,762
py
Python
jaffalearn/logging.py
tqbl/jaffalearn
a5bb79fcb3e84fd6e17b6356429e5885386a5a58
[ "0BSD" ]
null
null
null
jaffalearn/logging.py
tqbl/jaffalearn
a5bb79fcb3e84fd6e17b6356429e5885386a5a58
[ "0BSD" ]
null
null
null
jaffalearn/logging.py
tqbl/jaffalearn
a5bb79fcb3e84fd6e17b6356429e5885386a5a58
[ "0BSD" ]
null
null
null
from pathlib import Path import pandas as pd from torch.utils.tensorboard import SummaryWriter
30.37931
70
0.605562