content
stringlengths
5
1.05M
from pprint import pprint from functools import reduce from collections import defaultdict data = open("input.txt","r").read() # part 1: 40 times for i in range(50): j = 0 nd = "" while j < len(data): count = 0 curr = data[j] j += 1 count += 1 while j < len(data) an...
from .stanzas.action import Action, SYNC_PROTOS from .stanzas.counter import CounterQuery import stanzas.action from peak.util.addons import AddOn from threading import RLock from util.threads.timeout_thread import ResetTimer from collections import defaultdict import warnings import traceback COUNT_TIMEOUT ...
"""tests of the AlaskaTemperatureBMI component of permamodel using bmi API""" import datetime import pathlib import pkg_resources from cru_alaska_temperature import AlaskaTemperatureBMI default_config_filename = ( pathlib.Path(pkg_resources.resource_filename("cru_alaska_temperature", "examples")) / "defau...
class CostClient(object): CURRENT_COST_URL = '/olap_reports/cost/current' INSTANCE_COST_URL = '/olap_reports/cost/current/instance' HISTORY_COST_URL = '/olap_reports/cost/history' CUSTOM_REPORT_URL = '/olap_reports/custom/' ACCOUNTS_HISTORY_COST_URL = '/olap_reports/custom/893353198679' DAYS_COS...
from django.apps import AppConfig class AppointmentsConfig(AppConfig): name = 'appointments' def ready(self): import appointments.signals # register receiver functions for signals
import time import numpy as np from scipy.integrate import solve_ivp from scipy.constants import c as c_luz #metros/segundos from scipy.integrate import simps,trapz,cumtrapz c_luz_km = c_luz/1000 import sys import os from os.path import join as osjoin from pc_path import definir_path path_git, path_datos_global = defi...
"""Tests related to enriched RichHandler""" import io import logging import re from typing import Tuple, Union import pytest from enrich.console import Console from enrich.logging import RichHandler def strip_ansi_escape(text: Union[str, bytes]) -> str: """Remove all ANSI escapes from string or bytes. If b...
class Solution: def alienOrder(self, words: List[str]) -> str: n = len(words) indegrees = [0] * 26 outs = collections.defaultdict(set) for i in range(1, n): w1, w2 = words[i - 1], words[i] for c1, c2 in zip(w1, w2): if c1 != c2: ...
import pytest from django.shortcuts import reverse from django.contrib.auth.models import User import json pytestmark = pytest.mark.django_db def test_get_user_return_200(client): url = reverse('users:users') response = client.get(url) assert response.status_code == 200 def test_list_user_return_list_...
class Table: def __init__(self, table_file): import collections enc = self.detect_encoding(table_file) val_map = {} char_map = {} err_count = 0 with open(table_file, encoding=enc) as to: line = to.readline() cnt = 1 while line: ...
""" TODO """ from selenium.webdriver.common.by import By from .base import BasePageLocators # pylint: disable=too-few-public-methods class CartPageLocators(BasePageLocators): """ TODO """ GO_CHECKOUT = (By.XPATH, '//*[@id="content"]/div[3]/div[2]/a') EMPTY_CART_TEXT = (By.XPATH, '//*[@id="content"...
import os import tempfile import pytest from audiomate import corpus from audiomate.corpus import io from audiomate.utils import textfile from tests import resources @pytest.fixture() def writer(): return io.MozillaDeepSpeechWriter() @pytest.fixture() def path(): return tempfile.mkdtemp() class TestMozi...
from client import linodeClient import os linode = linodeClient(os.getcwd() + '/../.config') userInput = raw_input("What do you want to do?\n") if userInput == 'create': print(linode.createLinode('3', '1')) if userInput == 'destroy': userInput = raw_input("What do you want to destroy?\n") response = lin...
#!/usr/bin/env python #################### # Required Modules # #################### # Generic import json import logging import os import random import subprocess from collections import defaultdict, OrderedDict from glob import glob from pathlib import Path from string import Template # Libs import numpy as np imp...
#!/usr/bin/env python3 # Decription: # This program takes user input commands and sends them # to a seperate program that deals with making the motors # on the ROSPerch either turn on or off. # Adapted Sources: # Motor command code is adapted from the UTAP 2020 # code at https://github.com/jdicecco/UTAP/ # ROS talker/l...
import serial, keyboard, sys import win32api, win32gui, winsound import time, random, pyautogui import logging, json import cv2, os from datetime import datetime from tkinter import * from PIL import Image, ImageFilter, ImageChops import pytesseract import numpy as np import cv2 import PIL.ImageOps import pyperclip # f...
# import numpy as np # import sqlalchemy # from sqlalchemy.ext.automap import automap_base # from sqlalchemy.orm import Session # from sqlalchemy import create_engine, func from flask import Flask, jsonify app = Flask(__name__) @app.route('/api/v1.0/measurement') def api(): data = {"date","prcp" } ...
"""Main entrypoint for preprocessor commands.""" import os import argparse import logging import sys import pickle import vectorizer.ast2vec.train as ast2vec from vectorizer.node_map import NODE_LIST from vectorizer.ast2vec import parameters as ast2vec_params LOG_FILE = 'vectorizer/vectorizer.log' def main(): ""...
from flask import Flask import youtube_dl app = Flask(__name__) @app.route("/download/<videoId>") def download(videoId): ydl_opts = { "format": "best" } url = "https://www.youtube.com/watch?v=" + videoId with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download([url]) return {"s...
from flask import Flask, render_template, request, redirect, url_for from flask_sqlalchemy import SQLAlchemy from flask_security import Security, SQLAlchemyUserDatastore, login_required, \ UserMixin, RoleMixin from flask_security.utils import hash_password app = Flask(__name__) app.config['SECRET_KEY'] = 't...
''' Setup some basic requirements. Should not be open source due to security problems ''' from app.models import Role # insert roles, User for id=1, Administrator for id=2, Moderator for id=3 Role.insert_roles() # Role.query.all()
from django.core.urlresolvers import reverse from menu import Menu from apps.main.menus import ViewMenuItem EducacionMenu = Menu() # Perfil auth_children = ( ViewMenuItem( "Currículo", reverse('curriculo'), weight=30, icon="fa-users"),) Menu.add_item( "educacion", ViewMenu...
# ------------------------------------------------------------ # Copyright (c) 2017-present, SeetaTech, Co.,Ltd. # # Licensed under the BSD 2-Clause License. # You should have received a copy of the BSD 2-Clause License # along with the software. If not, See, # # <https://opensource.org/licenses/BSD-2-Clause> # # -...
""" Converts RGB and long RGB values to hexadecimal colours Awesome work of Robert Chmielowiec. """ def rgb_to_rgblong(red, green, blue): return red * pow(256, 2) + green * 256 + blue def rgblong_to_rgb(rgb): return rgb // pow(256, 2), (rgb & 65535 ^ 255) // 256, rgb & 255 def rgb_to_hex(red, green, blue)...
from common.basedir import BASEDIR is_in_travis = BASEDIR.strip('/').split('/')[0] != 'data'
from PyQt5 import QtCore from PyQt5.QtWidgets import QPushButton class DelayPushButton(QPushButton): def __init__(self, text, delay): super().__init__() self._track = -1 self._text = text self._delay = delay self.setText(self._text) self.ani = QtCore.QVariantAnima...
import struct import distutils.util import json import warnings import logging logger = logging.getLogger("modbus_server_logger") try: import redis except ImportError: logging.info("Could not import redis, RedisDatastore is not available") class DictDatastore: def __init__(self): self.empty_data...
tekst = """Something in the way Ummmmm Something in the way, yeah Ummmmm Something in the way Ummmmm""" print(tekst.count("m"))
import os from typing import List from syspass_api_client import api METHODS = { "search": "account/search", "view": "account/view", "view_pass": "account/viewPass", "edit_pass": "account/editPass", "create": "account/create", "edit": "account/edit", "delete": "account/delete", } class A...
#MenuTitle: Wrap and Extend Features # -*- coding: utf-8 -*- __doc__=""" Enclose all features with lookups and divide them into sub groups of 3000 lines max. It will also add the useExtension parameter allowing you to have a 32 bits limit insead of the 16 bits. """ import GlyphsApp import string import re # Global va...
#%% src 1: https://www.tutorialspoint.com/python_pandas/python_pandas_iteration.htm # In short, basic iteration (for i in object) produces − # Series − values # DataFrame − column labels # Panel − item labels # Note − Do not try to modify any object while iterating. # Iterating is meant for reading and the iterator r...
from pyspark.sql import SparkSession def clean_poetry_generated_requirement_file(spark, input_file_path, output_file_path): raw = spark.read.option("delimiter", ";").csv(input_file_path).toDF("dependency", "python-version") # raw.show(5, False) dep = raw.select("dependency") dep.show(50, False) de...
# Copyright 2021 The TensorFlow Authors. 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 applica...
import datetime from decimal import Decimal import random from django.utils import unittest from nose.tools import eq_ import amo import amo.tests from market.models import Refund, Price from mkt.stats import tasks from mkt.stats.search import cut, handle_kwargs from mkt.inapp_pay.models import InappConfig, InappPay...
from typing import List, Dict, Any, Optional, Text from py2neo import Graph,Node,data,Path, Relationship,NodeMatcher from schema import schema,slot_neo4j_dict class KnowledgeBase(object): def get_entities(self, entity_type:Text, attributes:Optional[List[Dict[Text,Text]]] ...
''' Created on Dec 1, 2011 @author: Lukasz Kreczko Email: Lukasz.Kreczko@cern.ch Provides error sources for histograms: - QCD estimation error - QCD shape error - b-tagging error (only for b-tagged hists), flat (in theory only up to 250GeV) - lumi error, flat - JEC error? Flat? '''
# This file is part of the bapsflib package, a Python toolkit for the # BaPSF group at UCLA. # # http://plasma.physics.ucla.edu/ # # Copyright 2017-2019 Erik T. Everson and contributors # # License: Standard 3-clause BSD; see "LICENSES/LICENSE.txt" for full # license terms and contributor agreement. # """ Module for ...
import rclpy from rclpy.node import Node from threading import Thread, Lock import time import sys import os import os.path from os import path from pathlib import Path import importlib.util from workcell_interfaces.srv import * from workcell_interfaces.msg import * from ot2_workcell_manager_client.retry_api import * f...
""" GraphSense API GraphSense API # noqa: E501 The version of the OpenAPI document: 0.4.5 Generated by: https://openapi-generator.tech """ import sys import unittest import graphsense from graphsense.model.address import Address from graphsense.model.entity import Entity from graphsense.model.neig...
"""User Model Copyright 2015 Archive Analytics Solutions - University of Liverpool 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 ap...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Count and display statistics of the data. ## Examples ```shell parlai data_stats -t convai2 -dt train:ordered ``` "...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # С клавиатуры вводится цифра (от 1 до 4). # Вывести на экран названия месяцев, соответствующих времени года с номером (считать зиму временем года № 1). if __name__ == '__main__': a = input ('введите число') if a == 1: print ('Зима') elif a == ...
import serial from . aiming import GunAngles import time UPDATE_FREQUENCY = 50.0 last_update_time = time.monotonic() ser = None current_gun_angles = GunAngles(pan=0,tilt=0) def get_serial(): global ser # return None #TODO remove # TTY failed, don't retry if ser == -1: return None # Try...
from logs import sonarlog import conf_domainsize import conf_nodes import placement_L2 import math import numpy as np # Setup Sonar logging logger = sonarlog.getLogger('placement') class L2Demand(placement_L2.L2): def test_nodes(self, new_domain, nodelist): norms = [] for node in nodelist: ...
from sense_hat import SenseHat sense = SenseHat() sense.show_message("Makes sense ;-)")
""" Aggregates the data from all databases into one CSV with minimal cutting/processing """ import sqlite3 import csv import pandas as pd HEADERS = list(['track_id', 'title', 'song_id', 'release', 'artist_id', 'artist_mbid', 'artist_name', 'duration', 'artist_familiarity', 'artist_hotttnesss', ...
from nipype.interfaces.utility import Function from nipype.pipeline import Node def tsv2subjectinfo(in_file, exclude=None): import pandas as pd from nipype.interfaces.base import Bunch import numpy as np events = pd.read_csv(in_file, sep=str('\t')) if exclude is not None: # not tested ...
"""This module defines tests for the user class and its methods""" import unittest from app.models.user import User class UserTests(unittest.TestCase): """Define and setup testing class""" def setUp(self): """ Set up user object before each test""" self.user = User() def test_isuccessful...
# (c) Copyright 2020 Hewlett Packard Enterprise Development LP # # @author alok ranjan from tests.nimbleclientbase import SKIPTEST, log_to_file as log '''AlarmsTestCase is not implemented due to external dependency ''' log("**** AlarmsTestCase is not implemented due to external dependency *****'")
import sys, textwrap, bisect from ..util import TerminalColors256 class TaggedTextDocument(object): """ Class representing a document as a list of TaggedTextBlocks """ def __init__(self, blocks=None): self.blocks = [] if blocks is None else blocks def __repr__(self): return '\n\n'...
def for_Q(): for row in range(7): for col in range(6): if ((col==0 or col==4) and (row!=0 and row!=6)) or (col>0 and col<4) and (row==0 or row==6) or (row>2 and row-col==1): print("*",end=" ") else: print(end=" ") print() def while_Q...
#!/usr/bin/env python import os tags = ["infra"] try: with open("/etc/infra/tags", "r") as f: for line in f.readlines(): tags.append(line.strip()) except IOError: pass try: for filename in os.listdir("/etc/infra/tags.d"): tags.append(filename) except OSError: pass line =...
import os import numpy as np import csv from sklearn.utils import shuffle from sklearn.model_selection import train_test_split import cv2 def extract_samples(samples): with open('../data/driving_log_processed.csv') as csvfile: reader = csv.reader(csvfile) next(reader, None) #this is necessary to s...
#!/usr/bin/env python from OpenGL.GLUT import * from OpenGL.GLU import * from OpenGL.GL import * import sys name = 'ball_glut' def main(): glutInit(sys.argv) glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH) glutInitWindowSize(400,400) glutCreateWindow(name) glClearColor(0.,0.,0.,1.) ...
#!/usr/bin/python # encoding: utf-8 from logicbit.logic import * from threading import Thread import time # Author Cleoner S. Pietralonga # e-mail: cleonerp@gmail.com # Apache License class Clock(Thread): def __init__(self, Method, Frequency=1, Samples=1): Thread.__init__(self) self.__th_clk = Tr...
import sys # TODO 4 change the exit code sys.exit (120)
from keras.models import Sequential, load_model from keras.layers import ConvLSTM2D, MaxPooling3D, Dense, TimeDistributed, Flatten from keras.optimizers import Adam from keras.callbacks import ModelCheckpoint from keras.preprocessing.image import ImageDataGenerator import numpy as np import pandas as pd import tensorf...
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = "Chris Griffith" from pathlib import Path import pkg_resources name = "AV1 (SVT AV1)" requires = "libsvtav1" video_extension = "mkv" video_dimension_divisor = 8 icon = str(Path(pkg_resources.resource_filename(__name__, f"../../data/encoders/icon_svt_av1.png"...
""" 1) find the client with the highest aggregate amount of purchase """ from config import * x = purchase.groupby(['cid'])['amount'].sum() x = x.reset_index() x = x.rename(columns=dict(amount='total_purchase')) printn(x, 'grouped') max_purchase = x.total_purchase.max() printn(max_purchase, 'max purchase') mask = x....
from typing import Any, Tuple import torchvision.datasets as datasets from torch.utils.data import Dataset class MNISTDataset(Dataset): """ `MNIST <http://yann.lecun.com/exdb/mnist/>`_ Dataset. Built using TorchVision Dataset class. Args: transform (callable, optional): A function/transform that ...
import pandas as pd series = pd.Series([21, 23, 56, 54]) print(series) print(series.index) print(series.values) print(series.dtype) brands = ['BMW', 'Jaguar', 'Ford', 'Kia'] quantities = [20, 10, 50, 75] series2 = pd.Series(quantities, index=brands) print(series2) # Access via index print(f'series[1]: {series[1]}')...
# iban.py - functions for handling Spanish IBANs # coding: utf-8 # # Copyright (C) 2016 Arthur de Jong # # 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 Licens...
from sklearn.datasets import * from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score from sklearn.preprocessing import OneHotEncoder, StandardScaler import numpy as np import matplotlib.pyplot as plt from net import Net from dataloader import train_loader from functional impo...
from rdflib import Literal, XSD from rdflib.plugins.sparql.evalutils import _eval from rdflib.plugins.sparql.operators import numeric from rdflib.plugins.sparql.datatypes import type_promotion from rdflib.plugins.sparql.compat import num_max, num_min from decimal import Decimal """ Aggregation functions """ def _...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Aug 1 10:13:27 2019 @author: adamreidsmith """ ''' ManifoldNet neural network based of an algorithm presented here: https://arxiv.org/abs/1809.06211 Trains on SO(3) matrices. ''' import torch import numpy as np from torch import nn from torch.nn...
#! /usr/local/bin/python3 """Secrets generator.""" import argparse import base64 import hashlib import secrets def setup_args_parser(): """Parse command line arguments.""" parser = argparse.ArgumentParser() parser.add_argument( '-l', choices=[256, 512, 1024, 2048, 4096], help='R...
# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-09-25 12:17 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('content...
import pandas as pd from pathlib import Path import datetime df = pd.read_csv(Path('Data Collection/Data/final_data.csv'), parse_dates=['date_local']) # df['date_local'] = [datetime.datetime.strptime(date, '%Y-%m-%d') for date in df['date_local']] df.sort_values(by=['date_local'], inplace=True) df['New Cases'] = df.gr...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from app.comm.psql_wrapper import PostgresqlWrapper from app.models.sync_model import SyncModel class CustomFields(SyncModel): """Acts as a client to query and modify information from and to database""" def __init__(self, db_params: dict, table_names: dict): ...
import os import tensorflow as tf from tensorflow.keras.layers import ( Conv2D, AveragePooling2D, Flatten, Dense, BatchNormalization, Activation, Softmax, add, ) from tensorflow.keras.models import Model from tensorflow.keras.optimizers import SGD from tensorflow.keras import backend as...
import torch import torch.nn as nn from catalyst.contrib.models import SequentialNet from catalyst.contrib.modules import LamaPooling class StateNet(nn.Module): def __init__( self, main_net: nn.Module, observation_net: nn.Module = None, aggregation_net: nn.Module = None, ): ...
from .Connection1 import Connection
import torch import numpy as np import time import traceback import logging from copy import deepcopy class NoValidResultsError(Exception): pass class UnsupportedError(Exception): pass # Logger logger = logging.getLogger(__name__) algorithm_defaults = {'n_steps': 30, 'executor': Non...
from django.apps import AppConfig class MovimentacoesConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'movimentacoes'
""" - 集爬取、清洗、分类与测试为一体的STAFF采集队列自动化更新组件 - 需要本机启动系统全局代理,或使用“国外”服务器部署 """ from .sspanel_checker import SSPanelStaffChecker from .sspanel_classifier import SSPanelHostsClassifier from .sspanel_collector import SSPanelHostsCollector __version__ = 'v0.2.2' __all__ = ['SSPanelHostsCollector', "SSPanelStaffChecker", ...
# ------------------------------------------------------------ Imports ----------------------------------------------------------- # # System import os # Local from .utils import Utils from .texts import new_class, new_enum, new_license, new_file, new_flow, gitignore, readme # ---------------------------------------...
import httpx from docs_src.tutorial.dependencies.tutorial_001 import app from xpresso import Dependant from xpresso.testclient import TestClient def test_client_injection(): async def handler(request: httpx.Request) -> httpx.Response: assert request.url == "https://httpbin.org/get" return httpx.R...
import unittest from click.testing import CliRunner from stable_world import errors from stable_world.script import main from fixture import CLITest class Test(CLITest): def test_main(self): runner = CliRunner() obj = self.application_mock() # User exists obj.client.token.retur...
import nnabla as nn import numpy as np import os from .identity import IdentityConverter from .helpers import GraphInfo class BatchNormalizationFoldedConverter(IdentityConverter): """ Single `Convolution -> BatchNormalization` pass is folded into one `Convolution`. If there is a `Convolution -> BatchNo...
""" sift image matching then infer the position of tufts. """ import numpy as np import cv2 as cv import xml.etree.ElementTree as ET from scipy.spatial.kdtree import KDTree import os def parse_xml(xml_path): """parse xml file and calculate center point of each bounding box Args: xml_path (str): path...
from django.core.management.base import BaseCommand from optparse import make_option from django.template.loader import render_to_string from aspc.sagelist.models import BookSale from datetime import datetime, timedelta class Command(BaseCommand): args = '[max age in days, default: 6*30]' help = 'expires book...
# These values are used for creating request arguments # We group them together so they're near each other # when using --debug URL = "url" BRANCH = "branch" TAG = "tag" COMMIT = "commit" COMMITTED_AT = "committed_at" PULL_REQUEST = "pull_request" SERVICE = "service" PROJECT_HOST = "project_host" PROJECT_OWNER = "proje...
import os import winshell class startup(): def __init__(self): self.startupdirectory() def startupdirectory(self): return winshell.startup() if __name__ == "__main__": print(startup()) with open(os.path.join(winshell.startup(), 'test.py'), 'w') as file: file.write('import te...
import logging import os from files.user_file_storage import UserFileStorage from utils import file_utils RESULT_FILES_FOLDER = 'uploadFiles' LOGGER = logging.getLogger('script_server.file_upload_feature') class FileUploadFeature: def __init__(self, user_file_storage: UserFileStorage, temp_folder) -> None: ...
from enum import Enum class MetricType(Enum): Absolute = "absolute" Relative = "relative"
__author__ = 'Mariusz' from pyltes import devices import numpy as np import matplotlib.pyplot as plt import matplotlib import math class Printer: """Class that prints network deployment""" def __init__(self,parent): self.parent = parent self.tilesInLine = 100 self.imageMatrixValid = Fa...
import math def isPrime(n): if n > 0: for i in range(2, int(math.sqrt(n)) + 1): if n % i == 0: return False return True return False def isCirculerPrime(n): string = str(n) length = len(string) for i in range(length): if not isPrime(n): ...
# -*- coding: UTF-8 -*- from flask import Blueprint __author__ = 'longo' train = Blueprint('train', __name__) from . import views
from rlalgos.pytorch.mf import dqn as dqn_pytorch, sac as sac_pytorch, td3 as td3_pytorch, \ categorical_dqn as c51_pytorch, qr_dqn as qr_dqn_pytorch from rlalgos.pytorch.mf.atari import categorical_dqn as c51_pytorch, dqn as atari_dqn_pytorch, \ qr_dqn as atari_qr_dqn_pytorch from rlalgos.pytorch.offline impor...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import gi import sqlite3 import zlib import datetime testing = True gi.require_version('Gtk', '3.0') from gi.repository import Gtk, Gdk from engineers.mikeUtil import MikeGtk from widgets.widgets_quiz21 import WidgetsConstructor from model.model_quiz21 import s...
from loguru import logger from kirsche.connect import append_connections import json class DataViews: def __init__(self, data) -> None: if not data: logger.warning("No data provided!") self.data = [] else: self.data = data @property def json_full(self):...
class OneLayerActiveScriptGen: def __init__(self, args): layernames = args.split(':') self.lgroups = "app.activeDocument.layerSets.getByName('" + layernames[0] + "')" if len(layernames) > 1: for x in range(1,len(layernames)): self.lgroups = self.lgroups + ".l...
# Python program to check whether a string is numeric. string = "Cla73829re" count = 0 string2 = '' for i in string: if (i.isnumeric()) == True: count +=1 else: string2 +=i print(string2) print(count)
KEY_ATTR_MAPPER = { "GAME_ID": "game_id", "GAME_DATE_EST": "date", "HOME_TEAM_ID": "home_team_id", "VISITOR_TEAM_ID": "visitor_team_id", "GAME_STATUS_TEXT": "status", } class StatsNbaGameItem(object): """ Class for game data from stats.nba.com :param dict item: dict with game data ...
"""Testes para GetUserController""" from unittest.mock import patch from pytest import raises from mitmirror.errors import HttpNotFound, HttpBadRequestError, HttpUnprocessableEntity from tests.mocks import mock_user user = mock_user() def test_handler(get_user_controller, user_repository_spy, fake_user): """Tes...
import torch as t import torch.nn as nn import torch.nn.functional as F from warnings import warn from torch.optim.adam import Adam from components.reduction.selfatt import BiliAttnReduction from components.sequence.CNN import CNNEncoder1D from components.sequence.LSTM import BiLstmEncoder from utils.training import e...
# coding=utf-8 """Horner's method for polynomial evaluation in O(n) time Python implementation.""" def horner(poly, x): result = poly[0] for i in range(1, len(poly)): result = result * x + poly[i] return result if __name__ == '__main__': poly = [2, -6, 2, -1] x = 3 print(horner(poly,...
from .clock import Clock # H-H M-M S-S # +-+-+ +-+-+ +-+-+ # 2^3=8 |1|2| |1|2| |1|2| # 2^2=4 |3|4| |3|4| |3|4| # 2^1=2 |5|6| |5|6| |5|6| # 2^0=1 |7|8| |7|8| |7|8| # +-+-+ +-+-+ +-+-+ def launch(): root = Clock() root.title("BinaryClock") root.resizable(...
import base64 import datetime import json import logging import re from typing import Dict, List from flask import g, session, url_for from flask_babel import lazy_gettext as _ from flask_jwt_extended import current_user as current_user_jwt from flask_jwt_extended import JWTManager from flask_login import current_user...
#csvsckit tagger from RecoBTag.CSVscikit.csvscikit_EventSetup_cff import * from RecoBTag.CSVscikit.pfInclusiveSecondaryVertexFinderCvsLTagInfos_cfi import * from RecoBTag.CSVscikit.pfInclusiveSecondaryVertexFinderNegativeCvsLTagInfos_cfi import * from RecoBTag.CSVscikit.pfCombinedSecondaryVertexSoftLeptonCvsLJetTags...