content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
# -*- coding: utf-8 -*- # # Copyright (C) 2005-2009 Edgewall Software # Copyright (C) 2005-2007 Christopher Lenz <cmlenz@gmx.de> # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://trac.edgewall.org/wiki/TracLicense. # # This software consists of voluntary contributions made by many # individuals. For the exact contribution history, see the revision # history and logs, available at http://trac.edgewall.org/log/. from ConfigParser import ConfigParser from copy import deepcopy from inspect import cleandoc import os.path from .core import ExtensionPoint __all__ = ['Configuration', 'ConfigSection', 'Option', 'BoolOption', 'IntOption', 'FloatOption', 'ListOption', 'OrderedExtensionsOption'] _use_default = object() def as_bool(value): """Convert the given value to a `bool`. If `value` is a string, return `True` for any of "yes", "true", "enabled", "on" or non-zero numbers, ignoring case. For non-string arguments, return the argument converted to a `bool`, or `False` if the conversion fails. """ if isinstance(value, basestring): try: return bool(float(value)) except ValueError: return value.strip().lower() in ('yes', 'true', 'enabled', 'on') try: return bool(value) except (TypeError, ValueError): return False def to_unicode(text, charset=None): """Convert input to an `unicode` object. For a `str` object, we'll first try to decode the bytes using the given `charset` encoding (or UTF-8 if none is specified), then we fall back to the latin1 encoding which might be correct or not, but at least preserves the original byte sequence by mapping each byte to the corresponding unicode code point in the range U+0000 to U+00FF. For anything else, a simple `unicode()` conversion is attempted, with special care taken with `Exception` objects. """ if isinstance(text, str): try: return unicode(text, charset or 'utf-8') except UnicodeDecodeError: return unicode(text, 'latin1') elif isinstance(text, Exception): # two possibilities for storing unicode strings in exception data: try: # custom __str__ method on the exception (e.g. PermissionError) return unicode(text) except UnicodeError: # unicode arguments given to the exception (e.g. parse_date) return ' '.join([to_unicode(arg) for arg in text.args]) return unicode(text) def _get_registry(cls, compmgr=None): """Return the descriptor registry. If `compmgr` is specified, only return descriptors for components that are enabled in the given `ComponentManager`. """ if compmgr is None: return cls.registry from .core import ComponentMeta components = {} for comp in ComponentMeta._components: for attr in comp.__dict__.itervalues(): if isinstance(attr, cls): components[attr] = comp return dict(each for each in cls.registry.iteritems() if each[1] not in components or compmgr.is_enabled(components[each[1]]))
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 15069, 357, 34, 8, 5075, 12, 10531, 1717, 39909, 439, 10442, 198, 2, 15069, 357, 34, 8, 5075, 12, 12726, 12803, 12592, 89, 1279, 66, 4029, 19471, 31, 70, ...
2.785415
1,193
import circuits from PythonQt.QtGui import QQuaternion as Quat from PythonQt.QtGui import QVector3D as Vec import naali COMPNAME = "rotation"
[ 11748, 24907, 198, 6738, 11361, 48, 83, 13, 48, 83, 8205, 72, 1330, 1195, 4507, 9205, 295, 355, 2264, 265, 198, 6738, 11361, 48, 83, 13, 48, 83, 8205, 72, 1330, 1195, 38469, 18, 35, 355, 38692, 198, 11748, 12385, 7344, 198, 198, 9...
2.75
52
# (major, minor, patch, prerelease) VERSION = (0, 0, 6, "") __shortversion__ = '.'.join(map(str, VERSION[:3])) __version__ = '.'.join(map(str, VERSION[:3])) + "".join(VERSION[3:]) __package_name__ = 'pyqubo' __contact_names__ = 'Recruit Communications Co., Ltd.' __contact_emails__ = 'rco_pyqubo@ml.cocorou.jp' __homepage__ = 'https://pyqubo.readthedocs.io/en/latest/' __repository_url__ = 'https://github.com/recruit-communications/pyqubo' __download_url__ = 'https://github.com/recruit-communications/pyqubo' __description__ = 'PyQUBO allows you to create QUBOs or Ising models from mathematical expressions.' __license__ = 'Apache 2.0' __keywords__ = 'QUBO, quantum annealing, annealing machine, ising model, optimization'
[ 2, 357, 22478, 11, 4159, 11, 8529, 11, 662, 20979, 8, 198, 198, 43717, 796, 357, 15, 11, 657, 11, 718, 11, 366, 4943, 198, 834, 19509, 9641, 834, 796, 705, 2637, 13, 22179, 7, 8899, 7, 2536, 11, 44156, 2849, 58, 25, 18, 60, 40...
2.726592
267
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import sys import re import logging import subprocess import errno, os, pty import shlex from subprocess import Popen, PIPE from ConfigReader import configuration import mysql.connector from mysql.connector import errorcode from common.Singleton import Singleton from DBImportConfig import import_config from DBImportOperation import common_operations from datetime import datetime, timedelta import pandas as pd import numpy as np import time
[ 2, 49962, 284, 262, 24843, 10442, 5693, 357, 1921, 37, 8, 739, 530, 198, 2, 393, 517, 18920, 5964, 11704, 13, 220, 4091, 262, 28536, 2393, 198, 2, 9387, 351, 428, 670, 329, 3224, 1321, 198, 2, 5115, 6634, 9238, 13, 220, 383, 7054,...
3.983819
309
from logging import getLogger from numpy import mean, std from pickle import dump from wonambi import Dataset from wonambi.trans import math, concatenate from bidso import Task, Electrodes lg = getLogger(__name__)
[ 6738, 18931, 1330, 651, 11187, 1362, 198, 6738, 299, 32152, 1330, 1612, 11, 14367, 198, 6738, 2298, 293, 1330, 10285, 198, 6738, 1839, 4131, 72, 1330, 16092, 292, 316, 198, 6738, 1839, 4131, 72, 13, 7645, 1330, 10688, 11, 1673, 36686, ...
3.30303
66
# Copyright 2011 Nicholas Bray # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from language.python import ast from . base import Constraint from .. calling import cpa # TODO prevent over splitting? All objects with the same qualifier should be grouped?
[ 2, 15069, 2813, 20320, 43050, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 2, 921, 743, 733...
3.942708
192
import os import zipfile import yaml from dotty_dict import Dotty from pytest_mock import MockerFixture from ddb.__main__ import main from ddb.config import Config from ddb.feature.version import is_git_repository
[ 11748, 28686, 198, 11748, 19974, 7753, 198, 198, 11748, 331, 43695, 198, 6738, 16605, 774, 62, 11600, 1330, 22875, 774, 198, 6738, 12972, 9288, 62, 76, 735, 1330, 337, 12721, 37, 9602, 198, 198, 6738, 288, 9945, 13, 834, 12417, 834, 1...
3.191176
68
import numpy as np import os from scanorama import * from scipy.sparse import vstack from process import load_names from experiments import * from utils import * NAMESPACE = 'zeisel' METHOD = 'svd' DIMRED = 100 data_names = [ 'data/mouse_brain/zeisel/amygdala', 'data/mouse_brain/zeisel/cerebellum', 'data/mouse_brain/zeisel/cortex1', 'data/mouse_brain/zeisel/cortex2', 'data/mouse_brain/zeisel/cortex3', 'data/mouse_brain/zeisel/enteric', 'data/mouse_brain/zeisel/hippocampus', 'data/mouse_brain/zeisel/hypothalamus', 'data/mouse_brain/zeisel/medulla', 'data/mouse_brain/zeisel/midbraindorsal', 'data/mouse_brain/zeisel/midbrainventral', 'data/mouse_brain/zeisel/olfactory', 'data/mouse_brain/zeisel/pons', 'data/mouse_brain/zeisel/spinalcord', 'data/mouse_brain/zeisel/striatumdorsal', 'data/mouse_brain/zeisel/striatumventral', 'data/mouse_brain/zeisel/sympathetic', 'data/mouse_brain/zeisel/thalamus', ] if __name__ == '__main__': datasets, genes_list, n_cells = load_names(data_names, norm=False) datasets, genes = merge_datasets(datasets, genes_list) X = vstack(datasets) if not os.path.isfile('data/dimred/{}_{}.txt'.format(METHOD, NAMESPACE)): log('Dimension reduction with {}...'.format(METHOD)) X_dimred = reduce_dimensionality( normalize(X), method=METHOD, dimred=DIMRED ) log('Dimensionality = {}'.format(X_dimred.shape[1])) np.savetxt('data/dimred/{}_{}.txt'.format(METHOD, NAMESPACE), X_dimred) else: X_dimred = np.loadtxt('data/dimred/{}_{}.txt'.format(METHOD, NAMESPACE)) from ample import gs, uniform, srs #samp_idx = gs(X_dimred, 20000, replace=False) #samp_idx = uniform(X_dimred, 20000, replace=False) samp_idx = srs(X_dimred, 20000, replace=False) #from anndata import AnnData #import scanpy.api as sc #adata = AnnData(X=X_dimred[samp_idx, :]) #sc.pp.neighbors(adata, use_rep='X') #sc.tl.louvain(adata, resolution=1.5, key_added='louvain') # #louv_labels = np.array(adata.obs['louvain'].tolist()) #le = LabelEncoder().fit(louv_labels) #cell_labels = le.transform(louv_labels) # #np.savetxt('data/cell_labels/zeisel_louvain.txt', cell_labels) labels = ( open('data/cell_labels/zeisel_cluster.txt') .read().rstrip().split('\n') ) le = LabelEncoder().fit(labels) cell_labels = le.transform(labels) experiments( X_dimred, NAMESPACE, n_seeds=2, cell_labels=cell_labels, kmeans_ami=True, louvain_ami=True, rare=True, rare_label=le.transform(['Ependymal'])[0], ) exit() embedding = visualize( [ X_dimred[samp_idx, :] ], cell_labels[samp_idx], NAMESPACE + '_srs{}'.format(len(samp_idx)), [ str(ct) for ct in sorted(set(cell_labels)) ], perplexity=100, n_iter=500, image_suffix='.png', viz_cluster=True ) exit() cell_labels = ( open('data/cell_labels/zeisel_louvain.txt') .read().rstrip().split('\n') ) le = LabelEncoder().fit(cell_labels) cell_labels = le.transform(cell_labels) astro = set([ 32, 38, 40, ]) oligo = set([ 2, 5, 12, 20, 23, 33, 37, ]) focus = set([ 15, 36, 41 ]) labels = [] aob_labels = [] for cl in cell_labels: if cl in focus: labels.append(0) aob_labels.append('both') elif cl in astro or cl in oligo: labels.append(1) if cl in astro: aob_labels.append('astro') else: aob_labels.append('oligo') else: labels.append(2) aob_labels.append('none') labels = np.array(labels) aob_labels = np.array(aob_labels) X = np.log1p(normalize(X[samp_idx, :])) from mouse_brain_astrocyte import astro_oligo_joint, astro_oligo_violin #astro_oligo_joint(X, genes, 'GJA1', 'MBP', aob_labels, 'astro', NAMESPACE) #astro_oligo_joint(X, genes, 'GJA1', 'MBP', aob_labels, 'oligo', NAMESPACE) #astro_oligo_joint(X, genes, 'GJA1', 'MBP', aob_labels, 'both', NAMESPACE) #astro_oligo_joint(X, genes, 'GJA1', 'PLP1', aob_labels, 'astro', NAMESPACE) #astro_oligo_joint(X, genes, 'GJA1', 'PLP1', aob_labels, 'oligo', NAMESPACE) #astro_oligo_joint(X, genes, 'GJA1', 'PLP1', aob_labels, 'both', NAMESPACE) astro_oligo_violin(X, genes, 'GJA1', aob_labels, NAMESPACE) astro_oligo_violin(X, genes, 'MBP', aob_labels, NAMESPACE) astro_oligo_violin(X, genes, 'PLP1', aob_labels, NAMESPACE) viz_genes = [ #'GJA1', 'MBP', 'PLP1', 'TRF', #'CST3', 'CPE', 'FTH1', 'APOE', 'MT1', 'NDRG2', 'TSPAN7', #'PLP1', 'MAL', 'PTGDS', 'CLDN11', 'APOD', 'QDPR', 'MAG', 'ERMN', #'PLP1', 'MAL', 'PTGDS', 'MAG', 'CLDN11', 'APOD', 'FTH1', #'ERMN', 'MBP', 'ENPP2', 'QDPR', 'MOBP', 'TRF', #'CST3', 'SPARCL1', 'PTN', 'CD81', 'APOE', 'ATP1A2', 'ITM2B' ] cell_labels = ( open('data/cell_labels/zeisel_cluster.txt') .read().rstrip().split('\n') ) le = LabelEncoder().fit(cell_labels) cell_labels = le.transform(cell_labels) embedding = visualize( [ X_dimred[samp_idx, :] ], cell_labels[samp_idx], NAMESPACE + '_astro{}'.format(len(samp_idx)), [ str(ct) for ct in sorted(set(cell_labels)) ], gene_names=viz_genes, gene_expr=X, genes=genes, perplexity=100, n_iter=500, image_suffix='.png', viz_cluster=True ) #visualize_dropout(X, embedding, image_suffix='.png', # viz_prefix=NAMESPACE + '_dropout') from differential_entropies import differential_entropies differential_entropies(X_dimred, labels)
[ 11748, 299, 32152, 355, 45941, 198, 11748, 28686, 198, 6738, 9367, 36161, 1330, 1635, 198, 6738, 629, 541, 88, 13, 82, 29572, 1330, 410, 25558, 198, 198, 6738, 1429, 1330, 3440, 62, 14933, 198, 6738, 10256, 1330, 1635, 198, 6738, 3384, ...
2.015972
2,880
from threading import Thread import psutil import time
[ 6738, 4704, 278, 1330, 14122, 198, 11748, 26692, 22602, 198, 11748, 640, 628 ]
4.307692
13
import fcntl import os import socket import struct import warnings import subprocess import logging import base64 logger = logging.getLogger(__name__) # Dummy socket used for fcntl functions _socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) class Mac(Addr): bytelen = 6
[ 11748, 277, 66, 429, 75, 198, 11748, 28686, 198, 11748, 17802, 198, 11748, 2878, 198, 11748, 14601, 198, 11748, 850, 14681, 198, 11748, 18931, 198, 11748, 2779, 2414, 198, 198, 6404, 1362, 796, 18931, 13, 1136, 11187, 1362, 7, 834, 3672...
2.918367
98
# -*- coding: utf-8 -*- basic_table = dict(map(lambda s: s.split(u'\t'), u''' a i u e o ka ki ku ke ko sa si su se so ta ti tu te to na ni nu ne no ha hi hu he ho ma mi mu me mo ya yu yo ra ri ru re ro wa wo a i u e o ga gi gu ge go za zi zu ze zo da di du de do ba bi bu be bo pa pi pu pe po kya kyu kyo sya syu syo tya tyu tyo nya nyu nyo hya hyu hyo mya myu myo rya ryu ryo gya gyu gyo zya zyu zyo dya dyu dyo bya byu byo pya pyu pyo kwa gwa a i u e o ka ki ku ke ko sa si su se so ta ti tu te to na ni nu ne no ha hi hu he ho ma mi mu me mo ya yu yo ra ri ru re ro wa wo a i u e o ga gi gu ge go za zi zu ze zo da di du de do ba bi bu be bo pa pi pu pe po kya kyu kyo sya syu syo tya tyu tyo nya nyu nyo hya hyu hyo mya myu myo rya ryu ryo gya gyu gyo zya zyu zyo dya dyu dyo bya byu byo pya pyu pyo kwa gwa '''.strip(u'\n').split(u'\n'))) long_sound_table = dict(u'a i u e o'.split()) long_sounds = u'aa ii uu ee oo ou'.split()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 35487, 62, 11487, 796, 8633, 7, 8899, 7, 50033, 264, 25, 264, 13, 35312, 7, 84, 6, 59, 83, 33809, 334, 7061, 6, 198, 197, 64, 198, 197, 72, 198, 197, 84, 19...
1.369104
848
""" Unit tests for utils.py """ # Standard libraries import json from pathlib import Path # Third-party libraries import pytest # Local libraries from turkey_bowl import utils
[ 37811, 198, 26453, 5254, 329, 3384, 4487, 13, 9078, 198, 37811, 198, 2, 8997, 12782, 198, 11748, 33918, 198, 6738, 3108, 8019, 1330, 10644, 198, 198, 2, 10467, 12, 10608, 12782, 198, 11748, 12972, 9288, 198, 198, 2, 10714, 12782, 198, ...
3.538462
52
"""external method"""
[ 37811, 22615, 2446, 37811 ]
5.25
4
from django.contrib.admin.views.decorators import staff_member_required from django.views.generic import TemplateView, ListView import csv from django.http import HttpResponse from backend.models import CustomUser from django.contrib.auth.mixins import LoginRequiredMixin
[ 6738, 42625, 14208, 13, 3642, 822, 13, 28482, 13, 33571, 13, 12501, 273, 2024, 1330, 3085, 62, 19522, 62, 35827, 198, 198, 6738, 42625, 14208, 13, 33571, 13, 41357, 1330, 37350, 7680, 11, 7343, 7680, 198, 11748, 269, 21370, 198, 6738, ...
3.631579
76
from collections import defaultdict REAL=open("18.txt").readlines() SAMPLE=open("18.sample").readlines() OPEN="." TREE="|" LUMBERYARD="#" import copy sample = solve(SAMPLE, 10) assert sample == 1147 print("*** SAMPLE PASSED ***") # print(solve(REAL, 10000)) loop = """598 570 191420 599 571 189168 600 572 185082 601 573 185227 602 574 185320 603 575 185790 604 576 186120 605 577 189956 606 578 190068 607 579 191080 608 580 190405 # too low 609 581 193795 610 582 190950 611 583 193569 612 584 194350 613 585 196308 614 586 195364 615 587 197911 616 588 199755 617 589 201144 618 590 201607 619 591 203580 620 592 201260 621 593 201950 622 594 200675 # TOO HIGH 623 595 202208 624 596 200151 625 597 198948 626 570 191420 627 571 189168 628 572 185082 629 573 185227 630 574 185320 631 575 185790 632 576 186120 633 577 189956 634 578 190068 635 579 191080 636 580 190405 637 581 193795""" num = 1000000000 nmod = 28 for num in range(570, 638): print(num, (num - 570) % nmod + 570) num = 1000000000 - 1 print(num, (num - 570) % nmod + 570 + nmod)
[ 6738, 17268, 1330, 4277, 11600, 198, 198, 2200, 1847, 28, 9654, 7203, 1507, 13, 14116, 11074, 961, 6615, 3419, 198, 49302, 16437, 28, 9654, 7203, 1507, 13, 39873, 11074, 961, 6615, 3419, 198, 198, 3185, 1677, 2625, 526, 198, 51, 11587, ...
2.472093
430
dis = float(input('Digite a distncia da sua viagem em Km: ')) if dis <= 200: print('O valor da sua passagem ser {:.2f} reais'.format(dis * 0.5)) else: print('O valor da sua passagem ser {:.2f} reais'.format(dis * 0.45))
[ 6381, 796, 12178, 7, 15414, 10786, 19511, 578, 257, 1233, 10782, 544, 12379, 424, 64, 25357, 363, 368, 795, 509, 76, 25, 705, 4008, 198, 361, 595, 19841, 939, 25, 198, 220, 220, 220, 3601, 10786, 46, 1188, 273, 12379, 424, 64, 1208,...
2.326531
98
import bleach import json from django import forms from osf.models import CollectionProvider, CollectionSubmission from admin.base.utils import get_nodelicense_choices, get_defaultlicense_choices
[ 11748, 49024, 198, 11748, 33918, 198, 198, 6738, 42625, 14208, 1330, 5107, 198, 198, 6738, 267, 28202, 13, 27530, 1330, 12251, 29495, 11, 12251, 7004, 3411, 198, 6738, 13169, 13, 8692, 13, 26791, 1330, 651, 62, 77, 375, 417, 291, 1072, ...
3.754717
53
import data_providers as gen import model_storage as storage import numpy as np import data_visualizer import time def evaluate(model_name): """ Evaluates the model stored in the specified file. Parameters ---------- model_name : string The name of the file to read the model from """ model = storage.load_model(model_name) model.summary() start = time.clock() score = model.evaluate_generator(gen.finite_generator("data\\validation"), steps=30) end = time.clock() print("Time per image: {} ".format((end-start)/300)) print (model.metrics_names) print (score) predictions = model.predict_generator(gen.finite_generator("data\\validation"), steps=30) data_visualizer.draw_bounding_boxes("data\\validation", predictions, "data\\results")
[ 198, 11748, 1366, 62, 15234, 4157, 355, 2429, 198, 11748, 2746, 62, 35350, 355, 6143, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 1366, 62, 41464, 7509, 198, 11748, 640, 198, 198, 4299, 13446, 7, 19849, 62, 3672, 2599, 198, 220, 2...
2.970909
275
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from enum import Enum, EnumMeta from six import with_metaclass
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 16529, 35937, 198, 2, 15069, 357, 66, 8, 5413, 10501, 13, 1439, 2489, 10395, 13, 198, 2, 49962, 739, 262, 17168, 13789, 13, 4091, 13789, 13, 14116, 287, 262, 1628, 6808, 329, 5964, 1321, 13, 19...
5.32
100
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.utils.timezone
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 11, 15720, 602, 198, 11748, 42625, 14208, 13, 26791, 13, ...
2.934783
46
import json import oogeso.io.file_io # Read in data, validate date et.c. with methods from io test_data_file = "examples/test case2.yaml" json_data = oogeso.io.file_io.read_data_from_yaml(test_data_file) json_formatted_str = json.dumps(json_data, indent=2) print("Type json formatted str=", type(json_formatted_str)) # deserialize json data to objects # encoder = oogeso.dto.oogeso_input_data_objects.DataclassJSONEncoder decoder = oogeso.dto.oogeso_input_data_objects.DataclassJSONDecoder # decoder = json.JSONDecoder() with open("examples/energysystem.json", "r") as jsonfile: energy_system = json.load(jsonfile, cls=decoder) es_str = oogeso.dto.oogeso_input_data_objects.serialize_oogeso_data(energy_system) print("Type seriealised=", type(es_str)) mydecoder = decoder() energy_system = mydecoder.decode(json_formatted_str) print("Type energysystem=", type(energy_system)) # energy_system = json.loads( # json_formatted_str, cls=encoder # ) # energy_system: oogeso.dto.oogeso_input_data_objects.EnergySystem = ( # oogeso.dto.oogeso_input_data_objects.deserialize_oogeso_data(json_data) # ) print("========================") print("Energy system:") # print("Energy system type=", type(energy_system)) # print("Nodes: ", energy_system.nodes) # print("Node1: ", energy_system.nodes["node1"]) # print("Parameters: ", energy_system.parameters) # print("Parameters type=", type(energy_system.parameters)) # print("planning horizon: ", energy_system.parameters.planning_horizon) # print("Carriers: ", energy_system.carriers) print(energy_system)
[ 11748, 33918, 198, 198, 11748, 267, 519, 274, 78, 13, 952, 13, 7753, 62, 952, 198, 198, 2, 4149, 287, 1366, 11, 26571, 3128, 2123, 13, 66, 13, 351, 5050, 422, 33245, 198, 9288, 62, 7890, 62, 7753, 796, 366, 1069, 12629, 14, 9288, ...
2.683305
581
""" Entry Point for Our Twitoff Flask App """ from .app import create_app APP = create_app()
[ 37811, 21617, 6252, 329, 3954, 1815, 270, 2364, 46947, 2034, 37227, 198, 198, 6738, 764, 1324, 1330, 2251, 62, 1324, 198, 198, 24805, 796, 2251, 62, 1324, 3419 ]
3.357143
28
import numpy import pytest import os from shutil import rmtree from numpy.testing import assert_allclose import scipy.stats import scipy.integrate import scipy.special from fgivenx.mass import PMF, compute_pmf
[ 11748, 299, 32152, 198, 11748, 12972, 9288, 198, 11748, 28686, 198, 6738, 4423, 346, 1330, 374, 16762, 631, 198, 6738, 299, 32152, 13, 33407, 1330, 6818, 62, 439, 19836, 198, 11748, 629, 541, 88, 13, 34242, 198, 11748, 629, 541, 88, 1...
3.101449
69
"""Config flow for Vera.""" from __future__ import annotations from collections.abc import Mapping import logging import re from typing import Any import pyvera as pv from requests.exceptions import RequestException import voluptuous as vol from homeassistant import config_entries from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_EXCLUDE, CONF_LIGHTS, CONF_SOURCE from homeassistant.core import callback from homeassistant.helpers import entity_registry as er from .const import CONF_CONTROLLER, CONF_LEGACY_UNIQUE_ID, DOMAIN LIST_REGEX = re.compile("[^0-9]+") _LOGGER = logging.getLogger(__name__) def fix_device_id_list(data: list[Any]) -> list[int]: """Fix the id list by converting it to a supported int list.""" return str_to_int_list(list_to_str(data)) def str_to_int_list(data: str) -> list[int]: """Convert a string to an int list.""" return [int(s) for s in LIST_REGEX.split(data) if len(s) > 0] def list_to_str(data: list[Any]) -> str: """Convert an int list to a string.""" return " ".join([str(i) for i in data]) def new_options(lights: list[int], exclude: list[int]) -> dict: """Create a standard options object.""" return {CONF_LIGHTS: lights, CONF_EXCLUDE: exclude} def options_schema(options: Mapping[str, Any] = None) -> dict: """Return options schema.""" options = options or {} return { vol.Optional( CONF_LIGHTS, default=list_to_str(options.get(CONF_LIGHTS, [])), ): str, vol.Optional( CONF_EXCLUDE, default=list_to_str(options.get(CONF_EXCLUDE, [])), ): str, } def options_data(user_input: dict) -> dict: """Return options dict.""" return new_options( str_to_int_list(user_input.get(CONF_LIGHTS, "")), str_to_int_list(user_input.get(CONF_EXCLUDE, "")), )
[ 37811, 16934, 5202, 329, 44413, 526, 15931, 198, 6738, 11593, 37443, 834, 1330, 37647, 198, 198, 6738, 17268, 13, 39305, 1330, 337, 5912, 198, 11748, 18931, 198, 11748, 302, 198, 6738, 19720, 1330, 4377, 198, 198, 11748, 12972, 332, 64, ...
2.544355
744
import os from shutil import copy2 as copy # from pysurf.logger import get_logger from pysurf.sampling import Sampling from pysurf.setup import SetupBase from pysurf.utils import exists_and_isfile from pysurf.spp import SurfacePointProvider from colt import Colt from sp_calc import SinglePointCalculation if __name__=="__main__": SetupSpectrum.from_commandline()
[ 11748, 28686, 198, 6738, 4423, 346, 1330, 4866, 17, 355, 4866, 198, 2, 198, 6738, 279, 893, 333, 69, 13, 6404, 1362, 1330, 651, 62, 6404, 1362, 198, 6738, 279, 893, 333, 69, 13, 37687, 11347, 1330, 3409, 11347, 198, 6738, 279, 893, ...
3.02439
123
#033: ler tres numeros e dizer qual o maior e qual o menor: print("Digite 3 numeros:") maiorn = 0 n = int(input("Numero 1: ")) if n > maiorn: maiorn = n menorn = n n = int(input("Numero 2: ")) if n > maiorn: maiorn = n if n < menorn: menorn = n n = int(input("Numero 3: ")) if n > maiorn: maiorn = n if n < menorn: menorn = n print(f"o maior numero foi {maiorn} e o menor foi {menorn}")
[ 2, 44427, 25, 300, 263, 256, 411, 5470, 418, 304, 288, 7509, 4140, 267, 17266, 1504, 304, 4140, 267, 1450, 273, 25, 198, 4798, 7203, 19511, 578, 513, 5470, 418, 25, 4943, 198, 76, 1872, 1211, 796, 657, 198, 198, 77, 796, 493, 7, ...
2.102041
196
import pytest from prop import strict_get from prop import get as dot_get
[ 11748, 12972, 9288, 198, 6738, 2632, 1330, 7646, 62, 1136, 198, 6738, 2632, 1330, 651, 355, 16605, 62, 1136, 628, 628, 628, 628, 628 ]
3.458333
24
from pprint import pprint import SCons.Builder from SCons.Script import * import json import os import copy import collections import xml.etree.ElementTree as ET from mplabx import MPLABXProperties MAKEFILE_TEXT = ''' MKDIR=mkdir CP=cp CCADMIN=CCadmin RANLIB=ranlib build: .build-post .build-pre: .build-post: .build-impl clean: .clean-post .clean-pre: .clean-post: .clean-impl clobber: .clobber-post .clobber-pre: .clobber-post: .clobber-impl all: .all-post .all-pre: .all-post: .all-impl help: .help-post .help-pre: .help-post: .help-impl include nbproject/Makefile-impl.mk include nbproject/Makefile-variables.mk ''' PROJECT_XML_TEXT = ''' <project> <type>com.microchip.mplab.nbide.embedded.makeproject</type> <configuration> <data> <name /> <sourceRootList /> <confList /> </data> </configuration> </project> ''' CONFIGURATIONS_XML_TEXT = ''' <configurationDescriptor version="65"> <logicalFolder name="root" displayName="root" projectFiles="true" /> <sourceRootList /> <projectmakefile>Makefile</projectmakefile> <confs /> </configurationDescriptor> ''' CONFIGURATION_ELEMENT_TEXT = ''' <conf type="2"> <toolsSet> <targetDevice /> <languageToolchain /> <languageToolchainVersion /> </toolsSet> <HI-TECH-COMP /> <HI-TECH-LINK /> <XC8-config-global /> </conf> ''' def build_mplabx_nbproject(target, source, env): ''' target - (singleton list) - Directory node to the project folder source - (list) - XML value nodes for each project configuration ''' project_dir = target[0] nbproject_dir = project_dir.Dir('nbproject') configurations_xml_file = nbproject_dir.File('configurations.xml') project_xml_file = nbproject_dir.File('project.xml') makefile_file = project_dir.File('Makefile') # Make the directories env.Execute(Mkdir(project_dir)) env.Execute(Mkdir(nbproject_dir)) # Generate the XML files confs = source configurations_xml_root, project_xml_root = _build_xml_files( project_name=os.path.basename(str(project_dir)), project_dir=project_dir, confs=confs, source_files=env['source_files']) with open(str(configurations_xml_file), 'w') as f: ET.indent(configurations_xml_root, space=' ') ET.ElementTree(configurations_xml_root).write(f, encoding='unicode') with open(str(project_xml_file), 'w') as f: ET.indent(project_xml_root, space=' ') ET.ElementTree(project_xml_root).write(f, encoding='unicode') with open(str(makefile_file), 'w') as f: f.write(MAKEFILE_TEXT) _mplabx_nbproject_builder = SCons.Builder.Builder(action=build_mplabx_nbproject)
[ 6738, 279, 4798, 1330, 279, 4798, 198, 11748, 6374, 684, 13, 32875, 198, 6738, 6374, 684, 13, 7391, 1330, 1635, 198, 11748, 33918, 198, 11748, 28686, 198, 11748, 4866, 198, 11748, 17268, 198, 11748, 35555, 13, 316, 631, 13, 20180, 27660...
2.413732
1,136
# # test_server.py # # Copyright (C) 2001-2007 Oisin Mulvihill. # Email: oisin.mulvihill@gmail.com # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library (see the file LICENSE.TXT); if not, # write to the Free Software Foundation, Inc., 59 Temple Place, # Suite 330, Boston, MA 02111-1307 USA. # # Date: 2001/12/06 15:54:30 # import sys import socket import xmlrpclib import autoconnect from SimpleXMLRPCServer import SimpleXMLRPCServer if __name__ == '__main__': server = Server() server.main()
[ 2, 201, 198, 2, 220, 220, 1332, 62, 15388, 13, 9078, 201, 198, 2, 201, 198, 2, 220, 220, 15069, 357, 34, 8, 5878, 12, 12726, 440, 45763, 17996, 85, 4449, 359, 13, 201, 198, 2, 220, 220, 9570, 25, 267, 45763, 13, 76, 377, 85, ...
2.893401
394
import os import sys import angr import nose.tools test_location = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', 'binaries', 'tests') if __name__ == "__main__": if len(sys.argv) > 1: globals()['test_' + sys.argv[1]]() else: g = globals().copy() for k, v in g.items(): if k.startswith("test_") and hasattr(v, '__call__'): print(k) v()
[ 11748, 28686, 198, 11748, 25064, 198, 198, 11748, 281, 2164, 198, 11748, 9686, 13, 31391, 198, 198, 9288, 62, 24886, 796, 28686, 13, 6978, 13, 22179, 7, 418, 13, 6978, 13, 15908, 3672, 7, 418, 13, 6978, 13, 5305, 6978, 7, 834, 7753,...
1.995516
223
import serial , time , os import serial.tools.list_ports as port import logging sho_logger = logging.getLogger("shongololo_logger") def open_imets(devices): """Tries to open as many imet device serial ports as there are :return: a list of socket handles """ imet_sockets = [] for d in range(len(devices)): # Create list of imet open ports port = str(devices["Imet" + str(d)]) try: ser = serial.Serial(port, baudrate=57600, parity=serial.PARITY_NONE, bytesize=serial.EIGHTBITS,stopbits=serial.STOPBITS_ONE, timeout=3.0, xonxoff=False) imet_sockets.append(ser) sho_logger.info("\n Successfully opened Imet device on port {}".format(devices["Imet" + str(d)])) except serial.SerialException as e: sho_logger.error(e) sho_logger.critical("\nFailed to open imet on port {}".format(devices["Imet" + str(d)])) return imet_sockets def find_imets(): """ Finds available imet serial ports and determines which device is attached to which /dev/ path :rtype: object :return: A dictionary of devices labled as" imet<number starting from 0> """ device_dict = {} imets = 0 portlist = list(port.comports()) for p in portlist: sp = str(p) if "FT230" in sp: path = sp.split('-')[0] device_dict["Imet" + str(imets)] = path[:-1] imets = imets + 1 sho_logger.info("Found an Imet device on port: %s",path) status=0 else: pass if imets==0: sho_logger.error("No Imet devices found.") else: sho_logger.info("Found {} Imet devices".format(imets)) return device_dict
[ 11748, 11389, 837, 640, 837, 28686, 198, 11748, 11389, 13, 31391, 13, 4868, 62, 3742, 355, 2493, 198, 11748, 18931, 198, 1477, 78, 62, 6404, 1362, 796, 18931, 13, 1136, 11187, 1362, 7203, 1477, 506, 349, 14057, 62, 6404, 1362, 4943, 6...
2.295213
752
#! /usr/bin/env python # Author: David Goodger # Contact: goodger@users.sourceforge.net # Revision: $Revision: 3915 $ # Date: $Date: 2005-10-02 03:06:42 +0200 (Sun, 02 Oct 2005) $ # Copyright: This module has been placed in the public domain. """ Tests for docutils.transforms.peps. """ from __init__ import DocutilsTestSupport from docutils.transforms.peps import TargetNotes from docutils.parsers.rst import Parser totest = {} totest['target_notes'] = ((TargetNotes,), [ ["""\ No references or targets exist, therefore no "References" section should be generated. """, """\ <document source="test data"> <paragraph> No references or targets exist, therefore no "References" section should be generated. """], ["""\ A target exists, here's the reference_. A "References" section should be generated. .. _reference: http://www.example.org """, """\ <document source="test data"> <paragraph> A target exists, here's the \n\ <reference name="reference" refname="reference"> reference \n\ <footnote_reference auto="1" ids="id3" refname="TARGET_NOTE: id2"> . A "References" section should be generated. <target ids="reference" names="reference" refuri="http://www.example.org"> <section ids="id1"> <title> References <footnote auto="1" ids="id2" names="TARGET_NOTE:\ id2"> <paragraph> <reference refuri="http://www.example.org"> http://www.example.org """], ]) if __name__ == '__main__': import unittest unittest.main(defaultTest='suite')
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 2, 6434, 25, 3271, 4599, 1362, 198, 2, 14039, 25, 922, 1362, 31, 18417, 13, 10459, 30293, 13, 3262, 198, 2, 46604, 25, 720, 18009, 1166, 25, 5014, 1314, 720, 198, 2, 7536, ...
2.586922
627
# Generated by Django 4.0.2 on 2022-03-15 22:43 from django.db import migrations
[ 2, 2980, 515, 416, 37770, 604, 13, 15, 13, 17, 319, 33160, 12, 3070, 12, 1314, 2534, 25, 3559, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 628 ]
2.766667
30
import Terminal
[ 11748, 24523, 201 ]
5.333333
3
import re from bs4 import BeautifulSoup # beautifulsoup4 import requests # requests HEADER = { "User-Agent": 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36' } def catch_info(base,pattern,str_add=''): '''base text, pattern to search, string to increment if necessary''' array = [] for match in pattern.finditer(base.prettify()): array.append(str_add+match.group(1)) return list(dict.fromkeys(array)) # set(array_video) # response = generate('PLMKi-ss_sEoOZw9TB4iCrevTK60uY8wg0') # print(response)
[ 11748, 302, 198, 6738, 275, 82, 19, 1330, 23762, 50, 10486, 1303, 4950, 82, 10486, 19, 198, 11748, 7007, 1303, 7007, 198, 198, 37682, 1137, 796, 1391, 198, 220, 220, 220, 366, 12982, 12, 36772, 1298, 705, 44, 8590, 5049, 14, 20, 13,...
2.529412
238
"""Constants for the deCONZ component.""" import logging LOGGER = logging.getLogger(__package__) DOMAIN = "deconz" CONF_BRIDGE_ID = "bridgeid" CONF_GROUP_ID_BASE = "group_id_base" DEFAULT_PORT = 80 DEFAULT_ALLOW_CLIP_SENSOR = False DEFAULT_ALLOW_DECONZ_GROUPS = True DEFAULT_ALLOW_NEW_DEVICES = True CONF_ALLOW_CLIP_SENSOR = "allow_clip_sensor" CONF_ALLOW_DECONZ_GROUPS = "allow_deconz_groups" CONF_ALLOW_NEW_DEVICES = "allow_new_devices" CONF_MASTER_GATEWAY = "master" SUPPORTED_PLATFORMS = [ "binary_sensor", "climate", "cover", "light", "scene", "sensor", "switch", ] NEW_GROUP = "groups" NEW_LIGHT = "lights" NEW_SCENE = "scenes" NEW_SENSOR = "sensors" ATTR_DARK = "dark" ATTR_OFFSET = "offset" ATTR_ON = "on" ATTR_VALVE = "valve" DAMPERS = ["Level controllable output"] WINDOW_COVERS = ["Window covering device", "Window covering controller"] COVER_TYPES = DAMPERS + WINDOW_COVERS POWER_PLUGS = ["On/Off light", "On/Off plug-in unit", "Smart plug"] SIRENS = ["Warning device"] SWITCH_TYPES = POWER_PLUGS + SIRENS CONF_ANGLE = "angle" CONF_GESTURE = "gesture" CONF_XY = "xy"
[ 37811, 34184, 1187, 329, 262, 390, 10943, 57, 7515, 526, 15931, 198, 11748, 18931, 198, 198, 25294, 30373, 796, 18931, 13, 1136, 11187, 1362, 7, 834, 26495, 834, 8, 198, 198, 39170, 29833, 796, 366, 12501, 13569, 1, 198, 198, 10943, 3...
2.309917
484
import json from rest_framework.generics import ListAPIView, get_object_or_404 from rest_framework.response import Response from rest_framework.views import APIView from rest_framework.viewsets import ModelViewSet from course_app.api.serializers import CourseSerializer from course_app.models import Course, Enrolled from users.api.serializers import StudentSerializer from users.models import Student
[ 11748, 33918, 198, 198, 6738, 1334, 62, 30604, 13, 8612, 873, 1330, 7343, 2969, 3824, 769, 11, 651, 62, 15252, 62, 273, 62, 26429, 198, 6738, 1334, 62, 30604, 13, 26209, 1330, 18261, 198, 6738, 1334, 62, 30604, 13, 33571, 1330, 3486, ...
3.895238
105
import os import json import logging import yaml from flask import Blueprint, jsonify, send_file, request, redirect from service.errors import ApiError from utils.repository import generate_repository_path, \ list_objects_in_repository from utils.list_dir import list_dir repository_controller = Blueprint('repository', __name__) repository_dir = os.environ['REPOSITORY_DIR'] metadata_file = 'meta.json' representation_dir = 'data' sub_object_dir = 'parts' viewers_config = os.path.join(os.environ['CONFIG_DIR'], "viewers.yml") with open(viewers_config, 'r', encoding="utf-8") as viewers_file: viewers = yaml.safe_load(viewers_file) def handle_file_request(path): if request.headers.get('Accept') == '*/*': return send_file(path) elif request.accept_mimetypes.accept_html: ext = os.path.splitext(path)[1][1:] if ext in viewers: url = viewers[ext] + path[len(repository_dir):] return redirect(url, code=303) return send_file(path)
[ 11748, 28686, 198, 11748, 33918, 198, 11748, 18931, 198, 11748, 331, 43695, 198, 198, 6738, 42903, 1330, 39932, 11, 33918, 1958, 11, 3758, 62, 7753, 11, 2581, 11, 18941, 198, 198, 6738, 2139, 13, 48277, 1330, 5949, 72, 12331, 198, 6738,...
2.61399
386
#!/usr/bin/python3 #coding=utf-8
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 2, 66, 7656, 28, 40477, 12, 23 ]
2
16
from datetime import datetime import base64 import os import re import requests import sys import urllib.parse import xmltodict import xbmc import xbmcgui import xbmcplugin import xbmcaddon import xbmcvfs __PLUGIN_ID__ = "plugin.audio.podcasts" # see https://forum.kodi.tv/showthread.php?tid=112916 _MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] GPODDER_API = { "login": "%s/api/2/auth/%s/login.json", "subscriptions": "%s/subscriptions/%s.%s" } settings = xbmcaddon.Addon(id=__PLUGIN_ID__) addon_dir = xbmcvfs.translatePath(settings.getAddonInfo('path')) if __name__ == '__main__': mediathek = Mediathek() if sys.argv[1] == "import_gpodder_subscriptions": mediathek.import_gpodder_subscriptions() elif sys.argv[1] == "import_opml": mediathek.import_opml() elif sys.argv[1] == "download_gpodder_subscriptions": mediathek.download_gpodder_subscriptions() elif sys.argv[1] == "unassign_opml": mediathek.unassign_opml() else: mediathek.handle(sys.argv)
[ 6738, 4818, 8079, 1330, 4818, 8079, 198, 11748, 2779, 2414, 198, 11748, 28686, 198, 11748, 302, 198, 11748, 7007, 198, 11748, 25064, 198, 11748, 2956, 297, 571, 13, 29572, 198, 11748, 2124, 76, 2528, 375, 713, 198, 198, 11748, 2124, 204...
2.250513
487
import re import time from lemoncheesecake.events import TestSessionSetupEndEvent, TestSessionTeardownEndEvent, \ TestEndEvent, SuiteSetupEndEvent, SuiteTeardownEndEvent, SuiteEndEvent, SteppedEvent from lemoncheesecake.reporting.report import ReportLocation DEFAULT_REPORT_SAVING_STRATEGY = "at_each_failed_test"
[ 11748, 302, 198, 11748, 640, 198, 198, 6738, 18873, 2395, 274, 46557, 13, 31534, 1330, 6208, 36044, 40786, 12915, 9237, 11, 6208, 36044, 6767, 446, 593, 12915, 9237, 11, 3467, 198, 220, 220, 220, 6208, 12915, 9237, 11, 26264, 40786, 129...
3.30303
99
"""Genshin chronicle notes.""" import datetime import typing import pydantic from genshin.models.genshin import character from genshin.models.model import Aliased, APIModel __all__ = ["Expedition", "ExpeditionCharacter", "Notes"]
[ 37811, 38, 641, 20079, 16199, 1548, 4710, 526, 15931, 198, 11748, 4818, 8079, 198, 11748, 19720, 198, 198, 11748, 279, 5173, 5109, 198, 198, 6738, 308, 641, 20079, 13, 27530, 13, 70, 641, 20079, 1330, 2095, 198, 6738, 308, 641, 20079, ...
3.131579
76
import smart_imports smart_imports.all()
[ 198, 11748, 4451, 62, 320, 3742, 198, 198, 27004, 62, 320, 3742, 13, 439, 3419, 628 ]
2.75
16
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=missing-docstring import tvm from tvm import meta_schedule as ms from tvm.ir import IRModule from tvm.meta_schedule.testing.conv2d_winograd_cpu import conv2d_winograd_cpu from tvm.target import Target from tvm.tir.schedule import Schedule, Trace if __name__ == "__main__": test_conv2d_winograd_cpu()
[ 2, 49962, 284, 262, 24843, 10442, 5693, 357, 1921, 37, 8, 739, 530, 198, 2, 393, 517, 18920, 5964, 11704, 13, 220, 4091, 262, 28536, 2393, 198, 2, 9387, 351, 428, 670, 329, 3224, 1321, 198, 2, 5115, 6634, 9238, 13, 220, 383, 7054,...
3.575563
311
# Copyright 2021 Huawei Technologies Co., Ltd # # 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 mindspore.nn as nn from mindspore.ops import operations as P
[ 2, 15069, 33448, 43208, 21852, 1766, 1539, 12052, 201, 198, 2, 201, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 201, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262,...
3.911917
193
#!/usr/bin/env python import argparse from igf_data.task_tracking.igf_slack import IGF_slack from igf_data.process.data_transfer.sync_seqrun_data_on_remote import Sync_seqrun_data_from_remote parser = argparse.ArgumentParser() parser.add_argument('-r','--remote_server', required=True, help='Remote server address') parser.add_argument('-p','--remote_base_path', required=True, help='Seqrun directory path in remote dir') parser.add_argument('-d','--dbconfig', required=True, help='Database configuration file path') parser.add_argument('-o','--output_dir', required=True, help='Local output directory path') parser.add_argument('-n','--slack_config', required=True, help='Slack configuration file path') args = parser.parse_args() remote_server = args.remote_server remote_base_path = args.remote_base_path dbconfig = args.dbconfig output_dir = args.output_dir slack_config = args.slack_config if __name__=='__main__': try: slack_obj=IGF_slack(slack_config=slack_config) ## FIX ME except Exception as e: message = 'Error while syncing sequencing run directory from remote server: {0}'.format(e) slack_obj.post_message_to_channel(message,reaction='fail') raise ValueError(message)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 11748, 1822, 29572, 198, 6738, 45329, 69, 62, 7890, 13, 35943, 62, 36280, 13, 328, 69, 62, 6649, 441, 1330, 46757, 62, 6649, 441, 198, 6738, 45329, 69, 62, 7890, 13, 14681, 13, 7890,...
3.081633
392
from typing import Callable, Iterable, TypeVar T = TypeVar('T') Num = TypeVar('Num', int, float)
[ 6738, 19720, 1330, 4889, 540, 11, 40806, 540, 11, 5994, 19852, 198, 198, 51, 796, 5994, 19852, 10786, 51, 11537, 198, 33111, 796, 5994, 19852, 10786, 33111, 3256, 493, 11, 12178, 8, 628 ]
3
33
fhand = (romeo.txt) counts = dict() for line in fhand: words = line.split() for word in words(): count word = count.get(word, 0) + 1 st = list for Key,Value in count.items(): st.append((val,key)) st.sort(reverse = true) for val,key in st[:10]: print key, val #Using Sorted Function sorted [(v,k) for k,v in c.items()]:
[ 69, 4993, 796, 357, 5998, 78, 13, 14116, 8, 201, 198, 9127, 82, 796, 8633, 3419, 201, 198, 1640, 1627, 287, 277, 4993, 25, 201, 198, 197, 10879, 796, 1627, 13, 35312, 3419, 201, 198, 197, 1640, 1573, 287, 2456, 33529, 201, 198, 19...
2.340136
147
newlist = lambda x<caret>, y: (x+y)/y x = 1
[ 3605, 4868, 796, 37456, 2124, 27, 6651, 83, 22330, 331, 25, 357, 87, 10, 88, 20679, 88, 198, 87, 796, 352 ]
2.047619
21
import grpc from consts import PORT, SERVER_CERT from grpc_generated_files import api_pb2, api_pb2_grpc if __name__ == "__main__": with open(SERVER_CERT, 'rb') as f: server_cert = f.read() creds = grpc.ssl_channel_credentials(server_cert) # the server IP should be in the common name of the certificate channel = grpc.secure_channel(f'localhost:{PORT}', creds) stub = api_pb2_grpc.ApiStub(channel) main(stub)
[ 11748, 1036, 14751, 198, 198, 6738, 1500, 82, 1330, 350, 9863, 11, 18871, 5959, 62, 34, 17395, 198, 6738, 1036, 14751, 62, 27568, 62, 16624, 1330, 40391, 62, 40842, 17, 11, 40391, 62, 40842, 17, 62, 2164, 14751, 628, 198, 198, 361, ...
2.486034
179
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' ***************************************** Author: zhlinh Email: zhlinhng@gmail.com Version: 0.0.1 Created Time: 2016-03-23 Last_modify: 2016-03-23 ****************************************** ''' ''' Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete at most k transactions. Note: You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). Credits: Special thanks to @Freezen for adding this problem and creating all test cases. '''
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 7061, 6, 198, 17174, 4557, 9, 198, 13838, 25, 220, 220, 220, 220, 220, 220, 220, 220, 1976, 71, 2815, 71, 198, 1533...
3.116279
215
import numpy as np import copy from gips import FLOAT from gips import DOUBLE
[ 11748, 299, 32152, 355, 45941, 198, 11748, 4866, 198, 198, 6738, 308, 2419, 1330, 9977, 46, 1404, 198, 6738, 308, 2419, 1330, 360, 2606, 19146 ]
3.12
25
from discord.ext import commands import discord import requests from bs4 import BeautifulSoup # work in progress! more languages welcome!
[ 6738, 36446, 13, 2302, 1330, 9729, 198, 11748, 36446, 198, 198, 11748, 7007, 198, 6738, 275, 82, 19, 1330, 23762, 50, 10486, 198, 198, 2, 670, 287, 4371, 0, 517, 8950, 7062, 0, 198 ]
4.117647
34
def drop(i_list: list,n:int) -> list: """ Drop at multiple of n from the list :param n: Drop from the list i_list every N element :param i_list: The source list :return: The returned list """ assert(n>0) _shallow_list = [] k=1 for element in i_list: if k % n != 0: _shallow_list.append(element) k+=1 return _shallow_list if __name__ == "__main__": print(drop([1,2,3,4,5],6))
[ 4299, 4268, 7, 72, 62, 4868, 25, 1351, 11, 77, 25, 600, 8, 4613, 1351, 25, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 14258, 379, 3294, 286, 299, 422, 262, 1351, 198, 220, 220, 220, 1058, 17143, 299, 25, 14258, 422, 262, 135...
2.168269
208
# # Copyright (c) 2017 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import operator import random from enum import Enum from typing import List, Tuple, Any, Union import numpy as np from rl_coach.core_types import Transition from rl_coach.memories.memory import MemoryGranularity from rl_coach.memories.non_episodic.experience_replay import ExperienceReplayParameters, ExperienceReplay from rl_coach.schedules import Schedule, ConstantSchedule """ A replay buffer which allows sampling batches which are balanced in terms of the classes that are sampled """
[ 2, 198, 2, 15069, 357, 66, 8, 2177, 8180, 10501, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, ...
3.719178
292
#!/usr/bin/env python # -*- coding: utf-8 -*- from schedprof.enumerated_instance import EnumeratedInstance
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 6038, 5577, 13, 268, 6975, 515, 62, 39098, 1330, 2039, 6975, 515, 33384, 628 ]
2.794872
39
import pyblish.api import avalon.api from openpype.api import version_up from openpype.action import get_errored_plugins_from_data
[ 11748, 12972, 65, 1836, 13, 15042, 198, 11748, 37441, 261, 13, 15042, 198, 198, 6738, 1280, 79, 2981, 13, 15042, 1330, 2196, 62, 929, 198, 6738, 1280, 79, 2981, 13, 2673, 1330, 651, 62, 263, 34640, 62, 37390, 62, 6738, 62, 7890, 628...
3.093023
43
#!/usr/bin/python3 """ Given a binary tree, we install cameras on the nodes of the tree. Each camera at a node can monitor its parent, itself, and its immediate children. Calculate the minimum number of cameras needed to monitor all nodes of the tree. Example 1: Input: [0,0,null,0,0] Output: 1 Explanation: One camera is enough to monitor all nodes if placed as shown. Example 2: Input: [0,0,null,0,null,0,null,null,0] Output: 2 Explanation: At least two cameras are needed to monitor all nodes of the tree. The above image shows one of the valid configurations of camera placement. Note: The number of nodes in the given tree will be in the range [1, 1000]. Every node has value 0. """ # Definition for a binary tree node.
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 37811, 198, 15056, 257, 13934, 5509, 11, 356, 2721, 9073, 319, 262, 13760, 286, 262, 5509, 13, 198, 198, 10871, 4676, 379, 257, 10139, 460, 5671, 663, 2560, 11, 2346, 11, 290, 663, 7103...
3.425926
216
from TikTokApi import TikTokApi api = TikTokApi.get_instance() count = 30 # You can find this from a tiktok getting method in another way or find songs from the discoverMusic method. sound_id = "6601861313180207878" tiktoks = api.by_sound(sound_id, count=count) for tiktok in tiktoks: print(tiktok)
[ 6738, 46338, 19042, 32, 14415, 1330, 46338, 19042, 32, 14415, 198, 198, 15042, 796, 46338, 19042, 32, 14415, 13, 1136, 62, 39098, 3419, 198, 198, 9127, 796, 1542, 198, 198, 2, 921, 460, 1064, 428, 422, 257, 256, 1134, 83, 482, 1972, ...
2.632479
117
from builtins import str from builtins import range from robust.simulations.simulate import filter_gamma_result_dict from SimPleAC_save import load_obj import pickle as pickle import numpy as np import matplotlib.pyplot as plt from SimPleAC_pof_simulate import pof_parameters if __name__ == "__main__": # Retrieving pof parameters [model, methods, gammas, number_of_iterations, min_num_of_linear_sections, max_num_of_linear_sections, verbosity, linearization_tolerance, number_of_time_average_solves, uncertainty_sets, nominal_solution, directly_uncertain_vars_subs, parallel, nominal_number_of_constraints, nominal_solve_time] = pof_parameters() method = methods[0] # only care about Best Pairs # Loading results margin = {} nGammas = nmargins = len(gammas) margins = gammas margin['solutions'] = {} for i in range(nmargins): margin['solutions'][margins[i]] = pickle.load(open("marginResults/" + str(margins[i]), 'rb')) margin['number_of_constraints'] = load_obj('marginnumber_of_constraints', 'marginResults') margin['simulation_results'] = load_obj('marginsimulation_results', 'marginResults') gamma = {} gamma['solutions'] = {} for i in range(nGammas): for j in range(len(methods)): for k in range((len(uncertainty_sets))): gamma['solutions'][gammas[i], methods[j]['name'], uncertainty_sets[k]] = pickle.load(open( "gammaResults\\" + str((gammas[i], methods[j]['name'], uncertainty_sets[k])), 'rb')) gamma['solve_times'] = load_obj('gammasolve_times', 'gammaResults') gamma['simulation_results'] = load_obj('gammasimulation_results', 'gammaResults') gamma['number_of_constraints'] = load_obj('gammanumber_of_constraints', 'gammaResults') # Plotting of cost and probability of failure objective_name = 'Total fuel weight' objective_units = 'N' title = '' filteredResults = [margin['solutions'], filter_gamma_result_dict(gamma['solutions'], 1, method['name'], 2, 'box'), filter_gamma_result_dict(gamma['solutions'], 1, method['name'], 2, 'ellipsoidal')] filteredSimulations = [margin['simulation_results'], filter_gamma_result_dict(gamma['simulation_results'], 1, method['name'], 2, 'box'), filter_gamma_result_dict(gamma['simulation_results'], 1, method['name'], 2, 'ellipsoidal')] objective_varkey = 'W_{f_m}' legend_keys = ['margins', 'box', 'ellipsoidal'] edgecolors = ['#FFBF00', '#CC0000', '#008000'] facecolors = ['#FFE135','#FF2052', '#8DB600'] fig, ax1 = plt.subplots() ax2 = ax1.twinx() lines = [] mincost = 1e10 maxcost = 0 for i in range(len(legend_keys)): sims = list(filteredSimulations[i].items()) pofs = [] objective_costs = [] objective_stddev = [] for j in sims: pofs.append(j[1][0]) objective_costs.append(j[1][1]) objective_stddev.append(j[1][2]) mincost = np.min([mincost] + objective_costs) maxcost = np.max([maxcost] + objective_costs) lines.append(ax1.plot(gammas, objective_costs, color=edgecolors[i], label=legend_keys[i] + ', cost')) inds = np.nonzero(np.ones(len(gammas)) - pofs)[0] uppers = [objective_costs[ind] + objective_stddev[ind] for ind in inds] lowers = [objective_costs[ind] - objective_stddev[ind] for ind in inds] x = [gammas[ind] for ind in inds] ax1.fill_between(x, lowers, uppers, alpha=0.5, edgecolor = edgecolors[i], facecolor = facecolors[i]) lines.append(ax2.plot(gammas, pofs, color=edgecolors[i], label=legend_keys[i] + ', PoF')) ax1.set_xlabel(r'Uncertainty Set Scaling Factor $\Gamma$', fontsize=12) ax1.set_ylabel('Cost [' + objective_name + ' (' + objective_units.capitalize() + ')]', fontsize=12) ax2.set_ylabel("Probability of Failure", fontsize=12) ax1.set_ylim([mincost, maxcost]) ax2.set_ylim([0, 1]) plt.title(title, fontsize=12) labs = [lines[l][0].get_label() for l in [1,3,5,0,2,4]] ax1.legend(labs, loc="lower right", fontsize=9, numpoints=1) # ax1.legend(loc="lower right", fontsize=10, numpoints=1) # fig.legend(loc="lower right", fontsize=10, numpoints=1) plt.show()
[ 6738, 3170, 1040, 1330, 965, 198, 6738, 3170, 1040, 1330, 2837, 198, 6738, 12373, 13, 14323, 5768, 13, 14323, 5039, 1330, 8106, 62, 28483, 2611, 62, 20274, 62, 11600, 198, 6738, 3184, 47, 293, 2246, 62, 21928, 1330, 3440, 62, 26801, 1...
2.254545
1,980
# coding: utf-8 import sys, os sys.path.append(os.pardir) # import numpy as np from dataset.cifar10 import load_cifar10 from PIL import Image np.set_printoptions(threshold=100) (x_train, t_train), (x_test, t_test) = load_cifar10(flatten=False) sample_image = x_test[0:100].reshape((10, 10, 3, 32, 32)).transpose((0, 3, 1, 4, 2)).reshape((320, 320, 3)) # 100 Image.fromarray(np.uint8(sample_image*255)).save('sample.png') print(t_test[0:100].reshape(10,10)) #pil_img = Image.fromarray(np.uint8(sample_image*255)) #pil_img.show()
[ 2, 19617, 25, 3384, 69, 12, 23, 201, 198, 11748, 25064, 11, 28686, 201, 198, 17597, 13, 6978, 13, 33295, 7, 418, 13, 26037, 343, 8, 220, 1303, 220, 201, 198, 11748, 299, 32152, 355, 45941, 201, 198, 6738, 27039, 13, 66, 361, 283, ...
2.268595
242
from . import lights from . import schedule
[ 6738, 764, 1330, 7588, 198, 6738, 764, 1330, 7269, 198 ]
4.4
10
# coding: utf-8 from __future__ import division from __future__ import print_function from __future__ import unicode_literals import sys import argparse import os import numpy as np from read_files import split_imdb_files, split_yahoo_files, split_agnews_files from word_level_process import word_process, get_tokenizer from char_level_process import char_process from neural_networks import word_cnn, char_cnn, bd_lstm, lstm from adversarial_tools import ForwardGradWrapper, adversarial_paraphrase import tensorflow as tf from keras import backend as K import time from unbuffered import Unbuffered sys.stdout = Unbuffered(sys.stdout) config = tf.ConfigProto(allow_soft_placement=True) config.gpu_options.allow_growth = True K.set_session(tf.Session(config=config)) # os.environ["CUDA_VISIBLE_DEVICES"] = "1" parser = argparse.ArgumentParser( description='Craft adversarial examples for a text classifier.') parser.add_argument('--clean_samples_cap', help='Amount of clean(test) samples to fool', type=int, default=1000) parser.add_argument('-m', '--model', help='The model of text classifier', choices=['word_cnn', 'char_cnn', 'word_lstm', 'word_bdlstm'], default='word_cnn') parser.add_argument('-d', '--dataset', help='Data set', choices=['imdb', 'agnews', 'yahoo'], default='imdb') parser.add_argument('-l', '--level', help='The level of process dataset', choices=['word', 'char'], default='word') if __name__ == '__main__': args = parser.parse_args() fool_text_classifier()
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 6738, 11593, 37443, 834, 1330, 7297, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 11748, 25064, 198, 11748, 1822, 29572, ...
2.419718
710
#!/usr/bin/env python from __future__ import absolute_import import numpy as np import os import pytest import tempfile import training_data if __name__ == '__main__': import pytest pytest.main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28686, 198, 11748, 12972, 9288, 198, 11748, 20218, 7753, 198, 198, 11748, 3047, ...
2.929577
71
from datetime import datetime from bee import Psd, CX, On, T from bee import Model, IntegerField, StringField, DateTimeField, Equal, W, C db_exam = Psd.open("exam") # 1) sing table count search, SELECT COUNT(*) AS COUNT FROM t_teacher with db_exam.connection() as conn: teacher_count = db_exam.Select(*CX("COUNT(*)", "COUNT")).From("t_teacher").int() print("total techer count is %s" % teacher_count) # 2) sing table search, SELECT * FROM t_teacher with db_exam.connection() as conn: teachers = db_exam.Select(*CX("*")).From("t_teacher").list() print(teachers) # 3) sing table search, SELECT * FROM t_teacher convert values to model of Teacher with db_exam.connection() as conn: teachers = db_exam.Select(*CX("*")).From("t_teacher").list(Teacher) print(teachers) # 4) sing table search, SELECT * FROM t_teacher WHERE id=? convert values to model of Teacher with db_exam.connection() as conn: teachers = db_exam.Select(*CX("*")).From("t_teacher").Where(W().equal("id", 1004)).list(Teacher) print(teachers) # 5) tow table Join search, SELECT DISTINCT id,cid,score FROM t_student JOIN t_sc ON id=sid WHERE id=? with db_exam.connection() as conn: result = db_exam.Query(C("id", "cid", "score"), True)\ .From("t_student")\ .Join("t_sc", On("id", "sid"))\ .Where(Equal("id", 1001))\ .list() print(result) #or use alias mode like 'SELECT DISTINCT s.id,sc.cid,sc.score FROM t_student AS s JOIN t_sc AS sc ON s.id=sc.sid WHERE s.id=?' with db_exam.connection() as conn: result = db_exam.Query(C("s.id", "sc.cid", "sc.score"), True)\ .From(T("t_student", "s"))\ .Join(T("t_sc", "sc"), On("s.id", "sc.sid"))\ .Where(Equal("s.id", 1001))\ .list() print(result) # 6) with transaction with db_exam.transaction(): # insert sql # update sql # raise exception # update Sql pass # 7) sing table search, SELECT * FROM t_student limit 0, 5 with db_exam.connection() as conn: students = db_exam.Select(*CX("*")).From("t_student").limit(1, 5).list() print(students)
[ 6738, 4818, 8079, 1330, 4818, 8079, 198, 198, 6738, 20697, 1330, 350, 21282, 11, 327, 55, 11, 1550, 11, 309, 198, 6738, 20697, 1330, 9104, 11, 34142, 15878, 11, 10903, 15878, 11, 7536, 7575, 15878, 11, 28701, 11, 370, 11, 327, 198, ...
2.475854
849
import json from scrapy import Selector from scrapy.utils.spider import arg_to_iter from scrapely.htmlpage import parse_html, HtmlTag, HtmlDataFragment from collections import defaultdict from itertools import tee, count, groupby from operator import itemgetter from slybot.utils import (serialize_tag, add_tagids, remove_tagids, TAGID, OPEN_TAG, CLOSE_TAG, UNPAIRED_TAG, GENERATEDTAGID) from .migration import _get_parent, short_guid def _get_data_id(annotation): """Get id (a str) of an annotation.""" if isinstance(annotation, HtmlTag): return annotation.attributes[TAGID]
[ 11748, 33918, 198, 198, 6738, 15881, 88, 1330, 9683, 273, 198, 6738, 15881, 88, 13, 26791, 13, 2777, 1304, 1330, 1822, 62, 1462, 62, 2676, 198, 6738, 42778, 306, 13, 6494, 7700, 1330, 21136, 62, 6494, 11, 367, 20369, 24835, 11, 367, ...
2.758621
232
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. DEPS = [ 'adb', 'depot_tools/bot_update', 'depot_tools/gclient', 'goma', 'recipe_engine/context', 'recipe_engine/json', 'recipe_engine/path', 'recipe_engine/platform', 'recipe_engine/properties', 'recipe_engine/python', 'recipe_engine/step', 'recipe_engine/url', 'depot_tools/tryserver', ]
[ 2, 15069, 1946, 383, 18255, 1505, 46665, 13, 1439, 2489, 10395, 13, 198, 2, 5765, 286, 428, 2723, 2438, 318, 21825, 416, 257, 347, 10305, 12, 7635, 5964, 326, 460, 307, 198, 2, 1043, 287, 262, 38559, 24290, 2393, 13, 198, 198, 7206,...
2.72067
179
# -*- coding:utf8 -*- import random import time from lib.navigation.PathFinding import Pathfinding from lib.control.Control import Control from lib.unit.Player import Player from lib.struct.CoordiPoint import CoordiPoint #
[ 2, 532, 9, 12, 19617, 25, 40477, 23, 532, 9, 12, 198, 11748, 4738, 198, 11748, 640, 198, 6738, 9195, 13, 28341, 7065, 13, 15235, 36276, 1330, 10644, 41070, 198, 6738, 9195, 13, 13716, 13, 15988, 1330, 6779, 198, 6738, 9195, 13, 2085...
3.409091
66
import os import time import sys if(len(sys.argv) is 1): path="/home/pi/storage/" else: path=sys.argv[1] try: arr=[] for filename in os.listdir(path): if("2018-09" in filename): arr.append(filename) for f in arr: filen = os.path.splitext(f)[0] if(("%s.h264" % filen) in arr) and (("%s.mp3" % filen) in arr and ("%s.mp4" % filen) not in arr): if(("%s.h264" % filen) == f): time.sleep(1) os.system("ffmpeg -i %s -i %s -c:v copy -c:a aac -strict experimental %s" % (path + f, path + filen + ".mp3", path + filen + ".mp4")) os.system("rm %s %s" % (path + filen + ".mp3", path + f)) except: print "d"
[ 11748, 28686, 198, 11748, 640, 198, 11748, 25064, 198, 198, 361, 7, 11925, 7, 17597, 13, 853, 85, 8, 318, 352, 2599, 198, 220, 220, 220, 3108, 35922, 11195, 14, 14415, 14, 35350, 30487, 198, 17772, 25, 198, 220, 220, 220, 3108, 28, ...
1.920213
376
petersen_spring = Graph(':I`ES@obGkqegW~') sphinx_plot(petersen_spring)
[ 6449, 46516, 62, 16469, 796, 29681, 7, 10354, 40, 63, 1546, 31, 672, 38, 74, 80, 1533, 54, 93, 11537, 198, 82, 746, 28413, 62, 29487, 7, 6449, 46516, 62, 16469, 8 ]
2.21875
32
t = (19, 42, 21) print(f"The {len(t)} numbers are: {t[0]}, {t[1]}, {t[2]}")
[ 83, 796, 357, 1129, 11, 5433, 11, 2310, 8, 198, 198, 4798, 7, 69, 1, 464, 1391, 11925, 7, 83, 38165, 3146, 389, 25, 1391, 83, 58, 15, 60, 5512, 1391, 83, 58, 16, 60, 5512, 1391, 83, 58, 17, 48999, 4943, 198 ]
1.790698
43
import json import os from os.path import join from random import shuffle import numpy as np from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer from sklearn.preprocessing import MinMaxScaler, normalize from sklearn.linear_model import LogisticRegression from sklearn.model_selection import cross_val_score, StratifiedKFold, train_test_split from sklearn.metrics import accuracy_score from transformers import BertTokenizer, BertConfig, BartTokenizer print(simple_term_counts())
[ 11748, 33918, 198, 11748, 28686, 198, 6738, 28686, 13, 6978, 1330, 4654, 198, 6738, 4738, 1330, 36273, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 1341, 35720, 13, 30053, 62, 2302, 7861, 13, 5239, 1330, 2764, 38469, 7509, 11, 309, 69...
3.681159
138
import logging as _logging
[ 11748, 18931, 355, 4808, 6404, 2667, 628, 628, 628, 628, 628, 198 ]
3.083333
12
#!/opt/libreoffice5.4/program/python # -*- coding: utf-8 -*- import unohelper # (uno) g_exportedScripts = macro, # if __name__ == "__main__": # XSCRIPTCONTEXT = automation() # XSCRIPTCONTEXT macro() #
[ 2, 48443, 8738, 14, 8019, 260, 31810, 20, 13, 19, 14, 23065, 14, 29412, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 555, 78, 2978, 525, 220, 1303, 357, 36909, 8, 198, 70, 62, 1069, 9213, 7391, 82, ...
2.21875
96
word=input() last_letter=(len(word)-1) result=word[last_letter] print(result)
[ 4775, 28, 15414, 3419, 198, 12957, 62, 9291, 16193, 11925, 7, 4775, 13219, 16, 8, 198, 20274, 28, 4775, 58, 12957, 62, 9291, 60, 198, 4798, 7, 20274, 8 ]
2.655172
29
import time from functools import wraps import asyncio from simple_retry.simple_retry.helpers import ( format_retry_message, has_retries_to_go, log_message )
[ 11748, 640, 198, 198, 6738, 1257, 310, 10141, 1330, 27521, 198, 198, 11748, 30351, 952, 198, 198, 6738, 2829, 62, 1186, 563, 13, 36439, 62, 1186, 563, 13, 16794, 364, 1330, 357, 198, 220, 220, 220, 5794, 62, 1186, 563, 62, 20500, 11...
2.626866
67
# application environment import settings import sys sys.path.append(settings.app_home_dir) sys.path.append(settings.app_settings["app_lib_dir"])
[ 2, 3586, 2858, 201, 198, 11748, 6460, 201, 198, 11748, 25064, 201, 198, 201, 198, 17597, 13, 6978, 13, 33295, 7, 33692, 13, 1324, 62, 11195, 62, 15908, 8, 201, 198, 17597, 13, 6978, 13, 33295, 7, 33692, 13, 1324, 62, 33692, 14692, ...
2.942308
52
"""cogeo_mosaic.backend.base: base Backend class.""" import abc import itertools from typing import Any, Dict, List, Optional, Sequence, Tuple, Type, Union import attr import mercantile from cachetools import TTLCache, cached from cachetools.keys import hashkey from morecantile import TileMatrixSet from rio_tiler.constants import WEB_MERCATOR_TMS from rio_tiler.errors import PointOutsideBounds from rio_tiler.io import BaseReader, COGReader from rio_tiler.models import ImageData from rio_tiler.mosaic import mosaic_reader from rio_tiler.tasks import multi_values from cogeo_mosaic.backends.utils import find_quadkeys, get_hash from cogeo_mosaic.cache import cache_config from cogeo_mosaic.errors import NoAssetFoundError from cogeo_mosaic.models import Info, Metadata from cogeo_mosaic.mosaic import MosaicJSON from cogeo_mosaic.utils import bbox_union
[ 37811, 1073, 469, 78, 62, 76, 8546, 291, 13, 1891, 437, 13, 8692, 25, 2779, 5157, 437, 1398, 526, 15931, 198, 198, 11748, 450, 66, 198, 11748, 340, 861, 10141, 198, 6738, 19720, 1330, 4377, 11, 360, 713, 11, 7343, 11, 32233, 11, 4...
2.982699
289
# pylint: disable=missing-module-docstring # # Copyright (C) 2020 by UsergeTeam@Github, < https://github.com/UsergeTeam >. # # This file is part of < https://github.com/UsergeTeam/Userge > project, # and is released under the "GNU v3.0 License Agreement". # Please see < https://github.com/uaudith/Userge/blob/master/LICENSE > # # All rights reserved. __all__ = ['OnFilters'] from pyrogram.filters import Filter as RawFilter from ... import types from . import RawDecorator
[ 2, 279, 2645, 600, 25, 15560, 28, 45688, 12, 21412, 12, 15390, 8841, 198, 2, 198, 2, 15069, 357, 34, 8, 12131, 416, 11787, 469, 15592, 31, 38, 10060, 11, 1279, 3740, 1378, 12567, 13, 785, 14, 12982, 469, 15592, 1875, 13, 198, 2, ...
3.025316
158
import unittest, tempfile from pygromos.simulations.hpc_queuing.job_scheduling.schedulers import simulation_scheduler from pygromos.data.simulation_parameters_templates import template_md from pygromos.data.topology_templates import blank_topo_template from pygromos.simulations.hpc_queuing.submission_systems import DUMMY from pygromos.files.gromos_system.gromos_system import Gromos_System from pygromos.tests.in_testfiles import in_test_file_path from pygromos.tests.test_files import out_test_root_dir
[ 11748, 555, 715, 395, 11, 20218, 7753, 198, 198, 6738, 12972, 70, 398, 418, 13, 14323, 5768, 13, 71, 14751, 62, 4188, 4250, 13, 21858, 62, 1416, 704, 16619, 13, 1416, 704, 377, 364, 1330, 18640, 62, 1416, 704, 18173, 198, 198, 6738,...
2.875706
177
# -*- coding: utf-8 -*- """ Created on Sat Dec 30 17:03:01 2017 @author: misakawa """ from pattern_matching import Match, when, var, T, t, _, overwrite from numpy.random import randint class Bound1: pass assert add(1, 1) == 2 assert add(Bound2()) == 2 assert add(Bound3()) == 3 assert add(1, Bound1(), 'last') == 'last' m = Match(1, 2, (3, int)) [a, b, c] = m.case(var[int], var, *var[tuple]).get assert a == 1 and b == 2 and c == ((3, int), ) [c2] = m.case((_, _, (_, var.when(is_type)))).get assert c2 == int assert summary(list(range(100))) == 4950 qsort(randint(0, 500, size=(1200, ))) assert trait_test(1) == 1 assert trait_test(Population()) == 1000
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 7031, 4280, 1542, 1596, 25, 3070, 25, 486, 2177, 198, 198, 31, 9800, 25, 2984, 461, 6909, 198, 37811, 198, 198, 6738, 3912, 62, 15699, 278, 133...
2.480427
281
# ---------------------------------------------------------------------- # | # | EnvironmentDiffs.py # | # | David Brownell <db@DavidBrownell.com> # | 2018-06-02 22:19:34 # | # ---------------------------------------------------------------------- # | # | Copyright David Brownell 2018-22. # | Distributed under the Boost Software License, Version 1.0. # | (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) # | # ---------------------------------------------------------------------- """Displays changes made by an environment during activation.""" import json import os import sys import textwrap import six import CommonEnvironment from CommonEnvironment import CommandLine from CommonEnvironment.Shell.All import CurrentShell from RepositoryBootstrap import Constants # ---------------------------------------------------------------------- _script_fullpath = CommonEnvironment.ThisFullpath() _script_dir, _script_name = os.path.split(_script_fullpath) # ---------------------------------------------------------------------- # ---------------------------------------------------------------------- # ---------------------------------------------------------------------- # ---------------------------------------------------------------------- # ---------------------------------------------------------------------- # ---------------------------------------------------------------------- def GetOriginalEnvironment(): # Get the original environment generated_dir = os.getenv(Constants.DE_REPO_GENERATED_NAME) assert os.path.isdir(generated_dir), generated_dir original_environment_filename = os.path.join(generated_dir, Constants.GENERATED_ACTIVATION_ORIGINAL_ENVIRONMENT_FILENAME) assert os.path.isfile(original_environment_filename), original_environment_filename with open(original_environment_filename) as f: return json.load(f) # ---------------------------------------------------------------------- # ---------------------------------------------------------------------- # ---------------------------------------------------------------------- # ---------------------------------------------------------------------- # ---------------------------------------------------------------------- # ---------------------------------------------------------------------- if __name__ == "__main__": try: sys.exit(CommandLine.Main()) except KeyboardInterrupt: pass
[ 2, 16529, 23031, 201, 198, 2, 930, 201, 198, 2, 930, 220, 9344, 35, 10203, 13, 9078, 201, 198, 2, 930, 201, 198, 2, 930, 220, 3271, 4373, 695, 1279, 9945, 31, 11006, 20644, 695, 13, 785, 29, 201, 198, 2, 930, 220, 220, 220, 22...
4.568592
554
from datetime import datetime from os.path import join from tests.base import TestCase, main, assets, copy_of_directory from ocrd_utils import ( initLogging, VERSION, MIMETYPE_PAGE ) from ocrd_models import OcrdMets # pylint: disable=protected-access,deprecated-method,too-many-public-methods if __name__ == '__main__': main()
[ 6738, 4818, 8079, 1330, 4818, 8079, 198, 6738, 28686, 13, 6978, 1330, 4654, 198, 6738, 5254, 13, 8692, 1330, 6208, 20448, 11, 1388, 11, 6798, 11, 4866, 62, 1659, 62, 34945, 198, 198, 6738, 267, 66, 4372, 62, 26791, 1330, 357, 198, 2...
2.703125
128
""" Environment for basic obstacle avoidance controlling a robotic arm from UR. In this environment the obstacle is only moving up and down in a vertical line in front of the robot. The goal is for the robot to stay within a predefined minimum distance to the moving obstacle. When feasible the robot should continue to the original configuration, otherwise wait for the obstacle to move away before proceeding """ import numpy as np from typing import Tuple from robo_gym_server_modules.robot_server.grpc_msgs.python import robot_server_pb2 from robo_gym.envs.simulation_wrapper import Simulation from robo_gym.envs.ur.ur_base_avoidance_env import URBaseAvoidanceEnv # base, shoulder, elbow, wrist_1, wrist_2, wrist_3 JOINT_POSITIONS = [-1.57, -1.31, -1.31, -2.18, 1.57, 0.0] DEBUG = True MINIMUM_DISTANCE = 0.3 # the distance [cm] the robot should keep to the obstacle # roslaunch ur_robot_server ur_robot_server.launch ur_model:=ur5 real_robot:=true rviz_gui:=true gui:=true reference_frame:=base max_velocity_scale_factor:=0.2 action_cycle_rate:=20 rs_mode:=moving
[ 37811, 198, 31441, 329, 4096, 22007, 29184, 12755, 257, 25810, 3211, 422, 37902, 13, 198, 198, 818, 428, 2858, 262, 22007, 318, 691, 3867, 510, 290, 866, 287, 257, 11723, 1627, 287, 2166, 286, 262, 9379, 13, 198, 464, 3061, 318, 329, ...
3.193452
336
from django.contrib.auth import get_user_model from django.contrib.auth.hashers import make_password from django.core.management.base import BaseCommand from ._private import populate_user User = get_user_model()
[ 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 1330, 651, 62, 7220, 62, 19849, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 10134, 7084, 1330, 787, 62, 28712, 198, 6738, 42625, 14208, 13, 7295, 13, 27604, 13, 8692, 1330, 7308...
3.451613
62
#!/usr/bin/env python # -*- encoding: utf-8 -*- ## # Copyright 2017 FIWARE Foundation, e.V. # 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. ## __author__ = 'fla' GOOGLE_ACCOUNTS_BASE_URL = 'https://accounts.google.com' APPLICATION_NAME = 'TSC Enablers Dashboard' CREDENTIAL_DIR = '.credentials' CREDENTIAL_FILE = 'sheets.googleapis.com.json' DB_NAME = 'enablers-dashboard.db' DB_FOLDER = 'dbase' LOG_FILE = 'tsc-dashboard.log' # We need to add 16 rows in the number of enablers list corresponding to: # - Title # - Report date # - Data sources updated on # - Source # - Units # - Enabler Impl # - INCUBATED # - DEVELOPMENT # - SUPPORT # - DEPRECATED # - And 6 extra blank rows between them FIXED_ROWS = 16 # We keep the firsts row without change in the sheet (sheet title) INITIAL_ROW = 2 # The number of columns to delete corresponds to: # Source, Catalogue, ReadTheDocs, Docker, GitHub, Coverall, Academy, HelpDesk, Backlog, GitHub_Open_Issues, # GitHub_Closed_Issues, GitHub_Adopters, GitHub_Adopters_Open_Issues, GitHub_Adopters_Closed_Issues, # GitHub_Comits, GitHub_Forks, GitHub_Watchers, GitHub_Stars, Jira_WorkItem_Not_Closed, Jira_WorkItem_Closed # + Extra 2 = 22 FIXED_COLUMNS = 22 # We start to delete from the initial column INITIAL_COLUMN = 1
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 21004, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2235, 198, 2, 15069, 2177, 18930, 33746, 5693, 11, 304, 13, 53, 13, 198, 2, 1439, 6923, 33876, 13, 198, 2, 198, 2, ...
2.986644
599
"""Tests for graphmode_tensornetwork.""" import builtins import sys import pytest import numpy as np from tensornetwork import connect, contract, Node from tensornetwork.backends.base_backend import BaseBackend from tensornetwork.backends import backend_factory def test_base_backend_name(): backend = BaseBackend() assert backend.name == "base backend" def test_base_backend_tensordot_not_implemented(): backend = BaseBackend() with pytest.raises(NotImplementedError): backend.tensordot(np.ones((2, 2)), np.ones((2, 2)), axes=[[0], [0]]) def test_base_backend_reshape_not_implemented(): backend = BaseBackend() with pytest.raises(NotImplementedError): backend.reshape(np.ones((2, 2)), (4, 1)) def test_base_backend_transpose_not_implemented(): backend = BaseBackend() with pytest.raises(NotImplementedError): backend.transpose(np.ones((2, 2)), [0, 1]) def test_base_backend_slice_not_implemented(): backend = BaseBackend() with pytest.raises(NotImplementedError): backend.slice(np.ones((2, 2)), (0, 1), (1, 1)) def test_base_backend_svd_decompositon_not_implemented(): backend = BaseBackend() with pytest.raises(NotImplementedError): backend.svd_decomposition(np.ones((2, 2)), 0) def test_base_backend_qr_decompositon_not_implemented(): backend = BaseBackend() with pytest.raises(NotImplementedError): backend.qr_decomposition(np.ones((2, 2)), 0) def test_base_backend_rq_decompositon_not_implemented(): backend = BaseBackend() with pytest.raises(NotImplementedError): backend.rq_decomposition(np.ones((2, 2)), 0) def test_base_backend_shape_concat_not_implemented(): backend = BaseBackend() with pytest.raises(NotImplementedError): backend.shape_concat([np.ones((2, 2)), np.ones((2, 2))], 0) def test_base_backend_shape_tensor_not_implemented(): backend = BaseBackend() with pytest.raises(NotImplementedError): backend.shape_tensor(np.ones((2, 2))) def test_base_backend_shape_tuple_not_implemented(): backend = BaseBackend() with pytest.raises(NotImplementedError): backend.shape_tuple(np.ones((2, 2))) def test_base_backend_shape_prod_not_implemented(): backend = BaseBackend() with pytest.raises(NotImplementedError): backend.shape_prod(np.ones((2, 2))) def test_base_backend_sqrt_not_implemented(): backend = BaseBackend() with pytest.raises(NotImplementedError): backend.sqrt(np.ones((2, 2))) def test_base_backend_diag_not_implemented(): backend = BaseBackend() with pytest.raises(NotImplementedError): backend.diag(np.ones((2, 2))) def test_base_backend_convert_to_tensor_not_implemented(): backend = BaseBackend() with pytest.raises(NotImplementedError): backend.convert_to_tensor(np.ones((2, 2))) def test_base_backend_trace_not_implemented(): backend = BaseBackend() with pytest.raises(NotImplementedError): backend.trace(np.ones((2, 2))) def test_base_backend_outer_product_not_implemented(): backend = BaseBackend() with pytest.raises(NotImplementedError): backend.outer_product(np.ones((2, 2)), np.ones((2, 2))) def test_base_backend_einsul_not_implemented(): backend = BaseBackend() with pytest.raises(NotImplementedError): backend.einsum("ii", np.ones((2, 2))) def test_base_backend_norm_not_implemented(): backend = BaseBackend() with pytest.raises(NotImplementedError): backend.norm(np.ones((2, 2))) def test_base_backend_eye_not_implemented(): backend = BaseBackend() with pytest.raises(NotImplementedError): backend.eye(2, dtype=np.float64) def test_base_backend_ones_not_implemented(): backend = BaseBackend() with pytest.raises(NotImplementedError): backend.ones((2, 2), dtype=np.float64) def test_base_backend_zeros_not_implemented(): backend = BaseBackend() with pytest.raises(NotImplementedError): backend.zeros((2, 2), dtype=np.float64) def test_base_backend_randn_not_implemented(): backend = BaseBackend() with pytest.raises(NotImplementedError): backend.randn((2, 2)) def test_base_backend_random_uniforl_not_implemented(): backend = BaseBackend() with pytest.raises(NotImplementedError): backend.random_uniform((2, 2)) def test_base_backend_conj_not_implemented(): backend = BaseBackend() with pytest.raises(NotImplementedError): backend.conj(np.ones((2, 2))) def test_base_backend_eigh_not_implemented(): backend = BaseBackend() with pytest.raises(NotImplementedError): backend.eigh(np.ones((2, 2))) def test_base_backend_eigs_not_implemented(): backend = BaseBackend() with pytest.raises(NotImplementedError): backend.eigs(np.ones((2, 2))) def test_base_backend_eigs_lanczos_not_implemented(): backend = BaseBackend() with pytest.raises(NotImplementedError): backend.eigsh_lanczos(lambda x: x, np.ones((2))) def test_base_backend_addition_not_implemented(): backend = BaseBackend() with pytest.raises(NotImplementedError): backend.addition(np.ones((2, 2)), np.ones((2, 2))) def test_base_backend_subtraction_not_implemented(): backend = BaseBackend() with pytest.raises(NotImplementedError): backend.subtraction(np.ones((2, 2)), np.ones((2, 2))) def test_base_backend_multiply_not_implemented(): backend = BaseBackend() with pytest.raises(NotImplementedError): backend.multiply(np.ones((2, 2)), np.ones((2, 2))) def test_base_backend_divide_not_implemented(): backend = BaseBackend() with pytest.raises(NotImplementedError): backend.divide(np.ones((2, 2)), np.ones((2, 2))) def test_base_backend_index_update_not_implemented(): backend = BaseBackend() with pytest.raises(NotImplementedError): backend.index_update(np.ones((2, 2)), np.ones((2, 2)), np.ones((2, 2))) def test_base_backend_inv_not_implemented(): backend = BaseBackend() with pytest.raises(NotImplementedError): backend.inv(np.ones((2, 2))) def test_base_backend_sin_not_implemented(): backend = BaseBackend() with pytest.raises(NotImplementedError): backend.sin(np.ones((2, 2))) def test_base_backend_cos_not_implemented(): backend = BaseBackend() with pytest.raises(NotImplementedError): backend.cos(np.ones((2, 2))) def test_base_backend_exp_not_implemented(): backend = BaseBackend() with pytest.raises(NotImplementedError): backend.exp(np.ones((2, 2))) def test_base_backend_log_not_implemented(): backend = BaseBackend() with pytest.raises(NotImplementedError): backend.log(np.ones((2, 2))) def test_base_backend_expm_not_implemented(): backend = BaseBackend() with pytest.raises(NotImplementedError): backend.expm(np.ones((2, 2))) def test_base_backend_sparse_shape_not_implemented(): backend = BaseBackend() with pytest.raises(NotImplementedError): backend.sparse_shape(np.ones((2, 2))) def test_base_backend_broadcast_right_multiplication_not_implemented(): backend = BaseBackend() with pytest.raises(NotImplementedError): backend.broadcast_right_multiplication(np.ones((2, 2)), np.ones((2, 2))) def test_base_backend_broadcast_left_multiplication_not_implemented(): backend = BaseBackend() with pytest.raises(NotImplementedError): backend.broadcast_left_multiplication(np.ones((2, 2)), np.ones((2, 2))) def test_backend_instantiation(backend): backend1 = backend_factory.get_backend(backend) backend2 = backend_factory.get_backend(backend) assert backend1 is backend2
[ 37811, 51, 3558, 329, 4823, 14171, 62, 83, 641, 1211, 316, 1818, 526, 15931, 198, 11748, 3170, 1040, 198, 11748, 25064, 198, 11748, 12972, 9288, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 11192, 1211, 316, 1818, 1330, 2018, 11, 2775...
2.637237
2,809
#!/usr/bin/env python # -*- coding: utf-8 -*- import pyqtgraph as pg import numpy as np if __name__ == '__main__': w = CustomWidget() w.show()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 12972, 80, 25297, 1470, 355, 23241, 198, 11748, 299, 32152, 355, 45941, 198, 198, 361, 11593, 3672, 834, 66...
2.30303
66
"""Tests for collapsible definition lists. When the option ``html_collapsible_definitions`` is ``True``, some HTML classes should be added to some definition lists but not all of them. """ from pathlib import Path import pytest from sphinx.application import Sphinx from .util import parse_html
[ 37811, 51, 3558, 329, 10777, 856, 6770, 8341, 13, 198, 198, 2215, 262, 3038, 7559, 6494, 62, 26000, 1686, 856, 62, 4299, 50101, 15506, 198, 271, 7559, 17821, 15506, 11, 617, 11532, 6097, 815, 307, 2087, 198, 1462, 617, 6770, 8341, 475...
3.682927
82
import numpy as np import pandas as pd import matplotlib.pyplot as plt from network import NN from evaluate import accuracy if __name__ == '__main__': X, y = read_data('iris.csv') # comment the following line if you don't need the plot anymore plot_data(X, y) X_train, y_train, X_test, y_test = train_test_split(X, y, 0.7) nn = NN(len(X[0]), 5, 1) output = nn.feedforward(X_train) print(output) print(f'w1 before backward propagation: \n{nn.w1} \nw2 before backward propagation:\n{nn.w2}') nn.backward(X_train, y_train, output) print(f'w1 after backward propagation: \n{nn.w1} \nw2 after backward propagation:\n{nn.w2}') nn.train(X_train, y_train) print("Accuracy:") print(accuracy(nn, X_test, y_test))
[ 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 6738, 3127, 1330, 399, 45, 198, 6738, 13446, 1330, 9922, 628, 628, 198, 198, 361, 11593, 3672, 834...
2.434505
313
from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import padding, rsa backend = default_backend()
[ 6738, 45898, 13, 71, 1031, 6759, 13, 1891, 2412, 1330, 4277, 62, 1891, 437, 198, 6738, 45898, 13, 71, 1031, 6759, 13, 19795, 20288, 1330, 46621, 11, 11389, 1634, 198, 6738, 45898, 13, 71, 1031, 6759, 13, 19795, 20288, 13, 4107, 3020, ...
3.639344
61
import unittest import unittest.mock from programy.storage.entities.nodes import NodesStore
[ 11748, 555, 715, 395, 198, 11748, 555, 715, 395, 13, 76, 735, 198, 198, 6738, 1430, 88, 13, 35350, 13, 298, 871, 13, 77, 4147, 1330, 399, 4147, 22658, 628, 198 ]
3.064516
31
import numpy as np import pandas as pd from bokeh.plotting import * # Here is some code to read in some stock data from the Yahoo Finance API AAPL = pd.read_csv( "http://ichart.yahoo.com/table.csv?s=AAPL&a=0&b=1&c=2000", parse_dates=['Date']) GOOG = pd.read_csv( "http://ichart.yahoo.com/table.csv?s=GOOG&a=0&b=1&c=2000", parse_dates=['Date']) MSFT = pd.read_csv( "http://ichart.yahoo.com/table.csv?s=MSFT&a=0&b=1&c=2000", parse_dates=['Date']) IBM = pd.read_csv( "http://ichart.yahoo.com/table.csv?s=IBM&a=0&b=1&c=2000", parse_dates=['Date']) output_file("stocks.html", title="stocks.py example") # EXERCISE: turn on plot hold # EXERCISE: finish this line plot, and add more for the other stocks. Each one should # have a legend, and its own color. line( AAPL['Date'], # x coordinates AAPL['Adj Close'], # y coordinates color='#A6CEE3', # set a color for the line legend='AAPL', # attach a legend label x_axis_type = "datetime", # NOTE: only needed on first tools="pan,wheel_zoom,box_zoom,reset,previewsave" # NOTE: only needed on first ) # EXERCISE: style the plot, set a title, lighten the gridlines, etc. # EXERCISE: start a new figure # Here is some code to compute the 30-day moving average for AAPL aapl = AAPL['Adj Close'] aapl_dates = AAPL['Date'] window_size = 30 window = np.ones(window_size)/float(window_size) aapl_avg = np.convolve(aapl, window, 'same') # EXERCISE: plot a scatter of circles for the individual AAPL prices with legend # 'close'. Remember to set the x axis type and tools on the first renderer. # EXERCISE: plot a line of the AAPL moving average data with the legeng 'avg' # EXERCISE: style the plot, set a title, lighten the gridlines, etc. show() # open a browser
[ 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 198, 6738, 1489, 365, 71, 13, 29487, 889, 1330, 1635, 198, 198, 2, 3423, 318, 617, 2438, 284, 1100, 287, 617, 4283, 1366, 422, 262, 16551, 15007, 7824, 1...
2.289256
847
import graphviz
[ 11748, 4823, 85, 528, 628, 198 ]
3
6
import unittest if __name__ == '__main__': unittest.main()
[ 11748, 555, 715, 395, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 555, 715, 395, 13, 12417, 3419, 198 ]
2.37037
27
''' This is the class to create a scrolling background. Because the background was so large, it was made to be a .jpg. ''' import pygame, os
[ 7061, 6, 198, 220, 220, 220, 770, 318, 262, 1398, 284, 2251, 257, 28659, 4469, 13, 198, 220, 220, 220, 4362, 262, 4469, 373, 523, 1588, 11, 340, 373, 925, 284, 307, 257, 764, 9479, 13, 198, 7061, 6, 198, 198, 11748, 12972, 6057, ...
3.191489
47
import os import shutil from contextlib import contextmanager from tempfile import mkdtemp, mktemp def file_pattern_exists_in_subdir(subdir, pattern): """Search for a file pattern recursively in a subdirectory :param subdir: directory to search recursively :param re.RegexObject pattern: compiled regular expression object from re.compile() :return: True if a file with the named pattern exists in the subdirectory :rtype: bool """ for (dirpath, dirnames, filenames) in os.walk(subdir): for filename in filenames: if pattern.match(filename): return True return False def touch(fname, times=None, makedirs=False): """Creates the specified file at the named path (and optionally sets the time).""" if makedirs: directory = os.path.dirname(fname) if not os.path.exists(directory): os.makedirs(directory) with open(fname, 'a'): os.utime(fname, times)
[ 11748, 28686, 198, 11748, 4423, 346, 198, 6738, 4732, 8019, 1330, 4732, 37153, 198, 6738, 20218, 7753, 1330, 33480, 67, 29510, 11, 33480, 29510, 628, 628, 198, 198, 4299, 2393, 62, 33279, 62, 1069, 1023, 62, 259, 62, 7266, 15908, 7, 7...
3.05
300
import asyncio import os from parser import miniprez_markdown, build_body import logging logger = logging.getLogger("miniprez") def build_html(f_target): """ Build the html from the markdown. """ f_html_output = f_target.replace(".md", ".html") logger.info(f"Building {f_target} to {f_html_output}") with open(f_target) as FIN: markdown = FIN.read() html = miniprez_markdown(markdown) soup = build_body(html) with open(f_html_output, "w") as FOUT: FOUT.write(soup.prettify())
[ 11748, 30351, 952, 198, 11748, 28686, 198, 6738, 30751, 1330, 949, 541, 21107, 62, 4102, 2902, 11, 1382, 62, 2618, 198, 198, 11748, 18931, 198, 198, 6404, 1362, 796, 18931, 13, 1136, 11187, 1362, 7203, 1084, 541, 21107, 4943, 628, 628, ...
2.46789
218
# -*- coding: utf-8 -*- """Linear module for dqn algorithms - Author: Kyunghwan Kim - Contact: kh.kim@medipixel.io """ import math import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from rl_algorithms.common.helper_functions import numpy2floattensor device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 14993, 451, 8265, 329, 288, 80, 77, 16113, 198, 198, 12, 6434, 25, 11118, 403, 456, 8149, 6502, 198, 12, 14039, 25, 44081, 13, 74, 320, 31, 1150, 541, 7168, 1...
2.744361
133
# Advent of Code - 2015 - Day 7 # --- Day 7: Some Assembly Required --- # This year, Santa brought little Bobby Tables a set of wires and bitwise logic gates! Unfortunately, little Bobby is a little under the recommended age range, and he needs help assembling the circuit. # Each wire has an identifier (some lowercase letters) and can carry a 16-bit signal (a number from 0 to 65535). A signal is provided to each wire by a gate, another wire, or some specific value. Each wire can only get a signal from one source, but can provide its signal to multiple destinations. A gate provides no signal until all of its inputs have a signal. # The included instructions booklet describes how to connect the parts together: x AND y -> z means to connect wires x and y to an AND gate, and then connect its output to wire z. # For example: # 123 -> x means that the signal 123 is provided to wire x. # x AND y -> z means that the bitwise AND of wire x and wire y is provided to wire z. # p LSHIFT 2 -> q means that the value from wire p is left-shifted by 2 and then provided to wire q. # NOT e -> f means that the bitwise complement of the value from wire e is provided to wire f. # Other possible gates include OR (bitwise OR) and RSHIFT (right-shift). If, for some reason, you'd like to emulate the circuit instead, almost all programming languages (for example, C, JavaScript, or Python) provide operators for these gates. # For example, here is a simple circuit: # 123 -> x # 456 -> y # x AND y -> d # x OR y -> e # x LSHIFT 2 -> f # y RSHIFT 2 -> g # NOT x -> h # NOT y -> i # After it is run, these are the signals on the wires: # d: 72 # e: 507 # f: 492 # g: 114 # h: 65412 # i: 65079 # x: 123 # y: 456 # In little Bobby's kit's instructions booklet (provided as your puzzle input), what signal is ultimately provided to wire a? import time, math startTime = time.perf_counter() # time in seconds (float) debug = False timing = True unitTesting = False # maybe a dictionary again? # circuitStrings = {"a" : {"input" : 1, "output" : NaN}} # parse the input text file to set up the circuitStrings inputs, then just roll through the dictionary to calculate the outputs # how will I be sure that the output has been calculated to be the input for the next circuitStrings? # can I assume the input file is "in order"? Probably not. # does this mean some sort of recursion algorithm? # maybe if I populate the outputs with 'NaN' (or Python equivalent) then check that it's not that before using it's output # I can make it recurse through the inputs, calculating any that have fully realized inputs? circuitStrings = [] circuitDict = {} # unit tests, kind of if unitTesting: print("Unit Testing") circuitStrings = ["123 -> x","456 -> y", "x AND y -> d", "x OR y -> e", "x LSHIFT 2 -> f", "y RSHIFT 2 -> g", "NOT x -> h", "NOT y -> i"] else: # read the input text file into a variable called presents with open("2015/day7/input-part2.txt","r") as inputString: circuitStrings = inputString.readlines() # remove newlines for i in range(0, len(circuitStrings)): circuitStrings[i] = circuitStrings[i].rstrip() # parse the input to create the dictionary createCircuitDict() doConnection() # show the circuits if debug: for circuit in circuitDict: print(circuit,":",circuitDict[circuit]) if unitTesting: testPass = False testPassOutput = {"d": {"output" : 72}, "e": {"output" : 507}, "f": {"output" : 492}, "g": {"output" : 114}, "h": {"output" : 65412}, "i": {"output" : 65079}, "x": {"output" : 123}, "y": {"output" : 456}} for wire in testPassOutput: testPassWire = testPassOutput[wire]["output"] circuitWire = circuitDict[wire]["output"] if debug: print("wire", wire, "test:", testPassWire, "calc:", circuitWire) testPass = testPassWire == circuitWire if testPass is False: break print("testPass:", testPass) else: print(circuitDict["a"]["output"]) # this answer for my input is 46065 (part 1), 14134 (part 2) endTime = time.perf_counter() # time in seconds (float) if timing: print("Execution took ", endTime - startTime, " seconds.")
[ 2, 33732, 286, 6127, 532, 1853, 532, 3596, 767, 198, 198, 2, 11420, 3596, 767, 25, 2773, 10006, 20906, 11420, 198, 198, 2, 770, 614, 11, 8909, 3181, 1310, 17155, 33220, 257, 900, 286, 19474, 290, 1643, 3083, 9156, 17435, 0, 8989, 11...
3.166541
1,327