text
stringlengths
1
927k
import datetime from django.test import TestCase from django.utils import timezone from catalog.forms import RenewBookForm class RenewBookFormTest(TestCase): def test_renew_form_date_field_label(self): form = RenewBookForm() self.assertTrue(form.fields['renewal_date'].label == None or form.fields...
from decimal import Decimal import pytest from vyper.exceptions import ( ArgumentException, InvalidType, StateAccessViolation, StructureException, UndeclaredDefinition, UnknownType, ) def test_external_contract_calls(get_contract, get_contract_with_gas_estimation): contract_1 = """ @exte...
# 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 u...
# # SensApp::Storage # # Copyright (C) 2018 SINTEF Digital # All rights reserved. # # This software may be modified and distributed under the terms # of the MIT license. See the LICENSE file for details. # import yaml import logging import logging.config from storage.queues import QueueListener from storage.db im...
""" Normalization Free Nets. NFNet, NF-RegNet, NF-ResNet (pre-activation) Models Paper: `Characterizing signal propagation to close the performance gap in unnormalized ResNets` - https://arxiv.org/abs/2101.08692 Paper: `High-Performance Large-Scale Image Recognition Without Normalization` - https://arxiv.org/...
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Creature() result.template = "object/mobile/shared_dressed_commoner_artisan_bith_male_01.iff" result.attribute_te...
#!/usr/bin/python import string import random # this will generate a random key used for the XOR encrpytion for 1kb = same as the TCP socket size key = ''.join(random.choice(string.ascii_lowercase + string.ascii_uppercase + string.digits + '^!\$%&/()=?{[]}+~#-_.:,;<>|\\') for _ in range(1024)) # printing data print(k...
import os from youtube_transcript_api import YouTubeTranscriptApi from youtube_transcript_api.formatters import JSONFormatter from argparse import ArgumentParser, Namespace from tqdm import tqdm from typing import List def _get_video_id_from_url(url: str) -> str: assert "watch?v=" in url, "URL format is incorre...
def count_step(m, w, h): m = [[i for i in l] for l in m] next_pos = [(0, 0)] while next_pos: x, y = next_pos.pop(0) for i, j in ((-1, 0), (1, 0), (0, -1), (0, 1)): x_, y_ = x + i, y + j if 0 <= x_ < w and 0 <= y_ < h: if not m[y_][x_]: ...
#!/usr/bin/env python import os from glob import glob def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration from numpy.distutils.system_info import get_info config = Configuration('lapack',parent_package,top_path) config.add_sconscript('SConstruct') ...
# coding: utf-8 # Python libs from __future__ import absolute_import import logging # Salt testing libs from tests.support.unit import skipIf, TestCase from tests.support.mock import NO_MOCK, NO_MOCK_REASON, patch, MagicMock, mock_open from tests.support.mixins import LoaderModuleMockMixin # Salt libs import salt.be...
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name='wangle', version='0.1.3', author="Ben Harpin", author_email="benjaminharpin@gmail.com", description="A python library for natural language manipulation.", long_description=long_descr...
from .....core import BaseAnalyzer, Validator, Required from .....config.consts import CONFIG_FORMAT, CONFIG_FORCE_STRINGS class GSheetFormatAnalyzer(BaseAnalyzer): REQUIRES = Validator( Required(CONFIG_FORMAT) ) def run(self): if self.config[CONFIG_FORMAT] == 'gsheet': self....
# Copyright 2019 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...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import...
from generative_playground.models.encoder.basic_cnn import SimpleCNNEncoder from generative_playground.models.encoder.basic_rnn import SimpleRNN from generative_playground.models.heads.attention_aggregating_head import AttentionAggregatingHead from generative_playground.models.transformer.Models import TransformerEncod...
from urllib.parse import quote_plus as url_quoteplus from urllib.parse import urlsplit from selenium.webdriver.common.by import By as WebBy from selenium.webdriver.support.ui import Select as WebSelect def allow_flash(driver, url): def _base_url(url): if url.find("://") == -1: url = "http://{}...
# -*- coding: utf-8 -*- def get_end(self): """Return the end point of the arc Parameters ---------- self : Arc3 An Arc3 object Returns ------- end: complex Complex coordinates of the end point of the Arc3 """ return self.end
from dynaconf import Dynaconf settings_files = ["settings.toml", "other.toml"] settings = Dynaconf(settings_files=settings_files) expected_value = "s3a://kewl_bucket" assert settings.s3_url == expected_value assert settings.s3_url1 == expected_value assert settings.s3_url2 == expected_value assert settings.s3_url3 ...
from discord.ext import commands import os import discord import random token = 'token' bot = discord.Client() bot = commands.Bot(command_prefix='!') bot.remove_command('help') for file in os.listdir("cogs"): if file.endswith(".py"): name = file[:-3] bot.load_extension(f"cogs.{name}") @bot.event...
from stard.services import Executable class Service(Executable): start_command = ('mount', '-a') post_start_commands = ( ('mount', '-o', 'remount,rw', '/'), ) stop_command = ('sh', '-c', 'umount -af; true') post_stop_commands = ( ('mount', '-o', 'remount,ro', '/'), ) onesh...
#!/usr/bin/env python __all__ = ['netease_download'] from ..common import * from ..common import print_more_compatible as print from ..util import fs from json import loads import hashlib import base64 import os def netease_hymn(): return """ player's Game Over, u can abandon. u get pissed, get ...
import sqlite3 import threading import notify2 from datetime import datetime from http.server import HTTPServer, BaseHTTPRequestHandler from urllib.parse import parse_qs from halo import Halo from prompt_toolkit import ANSI from prompt_toolkit.application import Application, get_app from prompt_toolkit.buffer import B...
""" Category queries application file. """ from lib import database as db def printAvailableCategories(): """ Iterate through Categories in db to print out name and Profile count for each. :return: None """ print(" Category | Profiles") print("------------------------...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Rogue documentation build configuration file, created by # sphinx-quickstart on Thu Feb 15 13:57:19 2018. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # auto...
from users.models import Users from .serializers import UsersSerializer from rest_framework import viewsets from django.contrib.auth.hashers import make_password from rest_framework.response import Response from rest_framework.decorators import api_view, action from users.models import Users from clients.models import ...
import base64 from django.core import mail from django.utils.six.moves import cPickle as pickle from django.test import TestCase from django.test.utils import override_settings from django.contrib.auth import get_user_model from django.contrib.sites.models import Site from ..conf import settings from ..models import...
import logging import snap7 # for setup the Logo connection please follow this link # http://snap7.sourceforge.net/logo.html logging.basicConfig(level=logging.INFO) # Siemens LOGO devices Logo 8 is the default Logo_7 = True logger = logging.getLogger(__name__) plc = snap7.logo.Logo() plc.connect("192.168.0.41",0...
# Copyright 2015 Google Inc. 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 a...
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: pogoprotos/networking/responses/get_player_response.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from...
# -*- coding: utf-8 -*- """MongoDB result store backend.""" from __future__ import absolute_import, unicode_literals from datetime import datetime, timedelta from kombu.exceptions import EncodeError from kombu.utils.objects import cached_property from kombu.utils.url import maybe_sanitize_url, urlparse from celery i...
# Copyright 2015 Google Inc. 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 a...
""" A tool to notify Docker contianers about changes in mounts on Windows. """ import re import argparse import logging import pywintypes from docker_volume_watcher.container_monitor import ContainerMonitor def main(): """ Parse command line arguments and start monitoring. """ parser = argparse.Argu...
from rest_framework.serializers import ModelSerializer as DefaultModelSerializer from rest_framework.validators import UniqueValidator, UniqueTogetherValidator from rest_framework.fields import JSONField from ..fields import JSONBField DefaultModelSerializer.serializer_field_mapping[JSONBField] = JSONField class Mo...
import torch from inference_Alexnet import AlexNet def main(): pytorch_model = AlexNet() pytorch_model.load_state_dict(torch.load('cifar100_Alexnet.pt')) pytorch_model.eval() dummy_input = torch.zeros(128*128*4) torch.onnx.export(pytorch_model, dummy_input, 'cifar100_Alexnet.onnx', verbose=True) if __nam...
"""pareeksha URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-...
from copy import deepcopy from django.test import TestCase from django.core.exceptions import ValidationError from django.core import management from avocado.query import oldparsers as parsers from avocado.models import DataConcept, DataField, DataConceptField from ....models import Employee class DataContextParserTe...
#!/usr/bin/env python # coding: utf-8 # /*########################################################################## # # Copyright (c) 2016-2019 European Synchrotron Radiation Facility # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files ...
import pytest def pytest_addoption(parser): parser.addoption( "--integration", action="store_true", default=False, help="run integration tests (hits N2EX endpoint)" ) def pytest_configure(config): config.addinivalue_line("markers", "integration: mark test as slow to run") def pytest_collection...
"""Plotting routines.""" from pyvista import MAX_N_COLOR_BARS from .colors import (color_char_to_word, get_cmap_safe, hex_to_rgb, hexcolors, string_to_rgb, PARAVIEW_BACKGROUND) from .export_vtkjs import export_plotter_vtkjs, get_vtkjs_url from .helpers import plot, plot_arrows, plot_compare_four, ...
#coverage:ignore import dataclasses import datetime import math from typing import Tuple, Iterator @dataclasses.dataclass(frozen=True, unsafe_hash=True) class MagicStateFactory: details: str physical_qubit_footprint: int rounds: int failure_rate: int @dataclasses.dataclass(frozen=True, unsafe_hash=T...
from collections import defaultdict from biothings.web.analytics.channels import SlackChannel, GAChannel from tornado.httpclient import AsyncHTTPClient from tornado.web import RequestHandler class Notifier: def __init__(self, settings): self.channels = [] if hasattr(settings, 'SLACK_WEBHOOKS'):...
colors = {"clean": "\033[m", "red": "\033[31m", "green": "\033[32m", "yellow": "\033[33m", "blue": "\033[34m", "purple": "\033[35m", "cian": "\033[36m"} teams = ("Fortaleza", "Athletico-PR", "Atlético-GO", "Bragantino", "Bahia", "Fluminense", "Palmeiras", "Fla...
# Copyright (c) 2020 PaddlePaddle 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 app...
""" Code for the combined model approach. @author: Shashank Swaminathan """ from src.BayesReg import GPM from src.StockRNN import StockRNN import pandas as pd import numpy as np from datetime import datetime from datetime import date ZERO_TIME = " 00:00:00" DEVICE = "cuda" # selects the gpu to be used TO_GPU_FAIL_...
#@+leo-ver=5-thin #@+node:ekr.20170925083314.1: * @file ../plugins/leo_cloud.py #@+<< docstring >> #@+node:ekr.20210518113636.1: ** << docstring >> """ leo_cloud.py - synchronize Leo subtrees with remote central server Terry N. Brown, terrynbrown@gmail.com, Fri Sep 22 10:34:10 2017 This plugin allows subtrees within ...
from __future__ import absolute_import, generators, nested_scopes, division import pytest from reference_database import * from test_01_storage import test_store_main_table as setup_main_table import os from pandas import NaT import simdb.databaseAPI as api def setup_module(): setup_main_table() def map_dateti...
import pexpect from ethpm_cli.main import ENTRY_DESCRIPTION def test_ipfs_scrape(tmp_path): ipfs_dir = tmp_path / "ipfs" ipfs_dir.mkdir() child = pexpect.spawn(f"ethpm scrape --ipfs-dir {ipfs_dir} --start-block 1") child.expect(ENTRY_DESCRIPTION) child.expect("\r\n") child.expect("Scraping fr...
#!/usr/bin/python3 '''This module contains one class, Rectangle ''' class Rectangle: '''Rectangle is an empty class ''' pass
# Copyright (c) 2013-2015, Rethink Robotics # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditio...
# # 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 # ...
import esphome.codegen as cg import esphome.config_validation as cv from esphome.components import light, output from esphome.const import ( CONF_BLUE, CONF_COLOR_INTERLOCK, CONF_GREEN, CONF_RED, CONF_OUTPUT_ID, CONF_WHITE, ) rgbw_ns = cg.esphome_ns.namespace("rgbw") RGBWLightOutput = rgbw_ns.c...
# coding: utf-8 # # Copyright 2014 The Oppia 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 requi...
# MIT LICENSE # # Copyright 1997 - 2020 by IXIA Keysight # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify,...
from django.contrib import admin from django.contrib.contenttypes.admin import GenericTabularInline from import_export.admin import ExportMixin from .models import AdditionalSpeaker, TalkProposal, TutorialProposal from .resources import TalkProposalResource class AdditionalSpeakerInline(GenericTabularInline): m...
# uncompyle6 version 2.9.10 # Python bytecode 2.7 (62211) # Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10) # [GCC 6.2.0 20161005] # Embedded file name: BaseHTTPServer.py """HTTP server base class. Note: the class in this module doesn't implement any HTTP request; see SimpleHTTPServer for simple impl...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import traceback import wx import pygame import util import battle import yadodb import data import dice import effectmotion import event import eventhandler import eventrelay import features import scenariodb import setting import skin import animat...
import csv,pdb import mysql.connector import random Movie2test = [] for i in range(100): m = random.randint(1,14000) if m not in Movie2test: Movie2test.append(m) Movie2test = sorted(Movie2test) """ connecting the database... """ cnx = mysql.connector.connect(user='root', password = '54321', host = '127.0.0.1'...
#coding=utf-8 from wxpy import * import numpy import cv2 import time import os from hyperlpr import pipline def recognize(filename): image = cv2.imread(filename) #通过文件名读入一张图片 放到 image中 return pipline.RecognizePlateJson(image) #识别一张图片并返回json结果 # 人脸检测的功能,这里用到了OpenCV里面的人脸检测代码 # 由于接收和处理图片都需要一点点时间 这里偷懒直接用...
import unittest from datetime import datetime import archive class TestArchive(unittest.TestCase): """ Various unit tests for wiki.web.archive Lucas Combs April 2019 """ def test_remove_file_extension(self): """ Verify that the file extension is removed. ...
""" These are video related models. """ from dataclasses import dataclass, field from typing import Optional, List import isodate from isodate import ISO8601Error from pyyoutube.error import ErrorCode, ErrorMessage, PyYouTubeException from .base import BaseModel from .common import ( BaseApiResponse, Base...
""" Unit test for the DirectSolver linear solver. """ import unittest import numpy as np from openmdao.api import Group, Problem, IndepVarComp, ExecComp, DirectSolver, \ LinearGaussSeidel, Newton from openmdao.core.test.test_residual_sign import SimpleImplicitSL from openmdao.test.converge_di...
import os.path from abc import ABC, abstractmethod from dataclasses import dataclass from typing import Iterator, Type from common import directories, file_utils from common.commands.base import ArxivBatchCommand from common.parse_tex import EntityExtractor from common.types import ArxivId, FileContents, RelativePath,...
# -*- coding: utf-8 -*- import csv import glob import time import queue import struct import numpy as np import tensorflow as tf from random import shuffle from threading import Thread from tensorflow.core.example import example_pb2 from utils import utils from utils import config import random random.seed(1234) #...
import json from time import sleep from typing import TYPE_CHECKING, List, Optional, TypedDict import boto3 from botocore.config import Config from mypy_boto3_dynamodb import DynamoDBClient from opta.utils import fmt_msg, logger if TYPE_CHECKING: from opta.layer import Layer, StructuredConfig class AwsArn(Type...
# Generated by Django 2.2.4 on 2019-12-31 11:32 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('tasks', '0004_task_teams...
import csv import pandas as pd one=pd.read_csv("pa_dashboards.csv") two=pd.read_csv("pa_dashboards(1).csv", squeeze=True) pattern = '|'.join(two) exist=one['sentences'].str.contains(pattern, na=False) with open('new.csv', 'w') as outFile: for cols in exist: if pattern in exist: outFile.writ...
from __future__ import unicode_literals from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils import importlib from django.utils.translation import get_language_info import pytz from appconf import AppConf def load_path_attr(path): i = path.rfind(".") mo...
from cytnx import * A = Tensor([3,4,5]) A.to_(Device.cuda+0); print(A.device_str())
# The plot server must be running # Go to http://localhost:5006/bokeh to view this plot import numpy as np import pandas as pd from bokeh.plotting import * # Generate some synthetic time series for six different categories cats = list("abcdef") y = np.random.randn(2000) g = np.random.choice(cats, 2000) for i, l in en...
#! /usr/bin/env python3 import sys import math from SWEET import * from mule.plotting.Plotting import * from mule.postprocessing.JobsData import * from mule.postprocessing.JobsDataConsolidate import * sys.path.append('../') import pretty_plotting as pp sys.path.pop() mule_plotting_usetex(False) groups = ['runtime....
from struct import unpack def calc8bitFletcherChecksum(msgBytes): """Calculate 8-bit Fletcher checksum for Li-1 radio packets. Args: msgBytes: Raw message bytes to calculate checksum of. """ ck_A = 0 ck_B = 0 for msgByte in msgBytes: ck_A += int(msgByte) ck_B += ck_A ...
# -*- coding: utf-8 -*- """A client to the Monarch Disease Ontology (MONDO).""" from typing import Optional from indra.databases.obo_client import OboClient _client = OboClient(prefix='mondo') def get_name_from_id(mondo_id: str) -> Optional[str]: """Return the name corresponding to the given MONDO ID. Pa...
import atexit import binascii import os import tempfile iconhexdata = '00000100010032321000000000007007000016000000280000003200000064' \ '00000001000400000000000807000000000000000000000000000000000000' \ '00000000000080000080000000808000800000008000800080800000808080' \ '00c0c...
""" Copyright 2013 Steven Diamond This file is part of CVXPY. CVXPY is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. CVXPY is distributed i...
class FreightPlane: def __init__(self): pass
from setuptools import setup with open("README.md", "r") as f: long_description = f.read() import spotdl setup( # 'spotify-downloader' was already taken :/ name="spotdl", # Tests are included automatically: # https://docs.python.org/3.6/distutils/sourcedist.html#specifying-the-files-to-distribute...
# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import itertools from textwrap import dedent from flake8_pantsbuild import PB10, PB11, PB12, PB13, PB20, PB30 def test_pb_10(flake8dir) -> None: template = dedent( """\ ...
import logging import requestresponder from edge.httputility import HttpUtility class ProxyWriter(requestresponder.RequestResponder): def __init__(self, configFilePath): super(ProxyWriter, self).__init__(configFilePath) def get(self, requestHandler): super(ProxyWriter, self).get(requestHandle...
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import hydra from hydra.utils import instantiate import logging from overlap.train_net import train_net from overlap.test_net import test_net ...
from enum import Enum from schematics.exceptions import DataError from schematics.models import Model from schematics.types import StringType, DateTimeType, DecimalType class ResultStatus(str, Enum): OK = 'ok' PENDING = 'pending' ERROR = 'error' class CommandResult(object): def __init__(self, statu...
import numpy as np import pyviz3d.visualizer as viz def create_color_palette(): return np.array([ (0, 0, 0), (174, 199, 232), # wall (152, 223, 138), # floor (31, 119, 180), # cabinet (255, 187, 120), # bed (188, 189, 34), # chair (140, 86, 75), # sofa ...
import numpy as np from phonopy.cui.settings import Settings, ConfParser, fracval class Phono3pySettings(Settings): def __init__(self): Settings.__init__(self) self._boundary_mfp = 1.0e6 # In micrometre. The default value is # just set to avoid divergence. ...
#!/usr/bin/env python import unittest from mock import patch from mock import MagicMock from flask import request from StringIO import StringIO from src.app import espaweb from src.mocks import app as mock_app from src.utils import User class ApplicationTestCase(unittest.TestCase): def setUp(self): sel...
import pandas def load_schrute(): """ The entire script transcriptions from The Office in pandas dataframe format. """ full_path = "https://github.com/bradlindblad/schrutepy/raw/master/data/schrute.csv" df = pandas.read_csv(full_path) df = df.drop("Unnamed: 0", axis=1) return df
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. """ Learn a world model on gym environments """ import argparse import json import logging import sys from typing import Dict, Optional import ml.rl.types as rlt import numpy as np import torch from ml.rl.evaluation.world_mo...
#!/usr/bin/env python3 import os import argparse import sys import pickle import asyncio import time import numpy as np import zmq import pytao from p4p.nt import NTTable from p4p.server import Server as PVAServer from p4p.server.asyncio import SharedPV from zmq.asyncio import Context import simulacrum model_service_...
import numpy as np from ..util import is_binary_file # define a numpy datatype for the STL file _stl_dtype = np.dtype([('normals', np.float32, (3)), ('vertices', np.float32, (3, 3)), ('attributes', np.uint16)]) _stl_dtype_header = np.dtype([('header', np.void, 80), ('face_count', np.int32)]) def load_stl(file_obj, ...
from appPortas.models import * from appPonto.models import * from datetime import datetime pessoa = Pessoa.objects.get(id) print(pessoa)
# https://adventofcode.com/2018/day/1 with open("../../input/2018-01-input.txt") as file: changes = [int(i) for i in file.read().splitlines()] # part 1 print(sum(changes)) # 561 # part 2 frequency = 0 i = 0 seen = set() while True: for change in changes: if frequency in seen: break ...
import argparse import client import config import logging import os import server # Set up parser parser = argparse.ArgumentParser() parser.add_argument('-c', '--config', type=str, default='./config.json', help='Federated learning configuration file.') parser.add_argument('-l', '--log', type=str,...
#!/usr/bin/python #-*- coding: utf-8 -*- import pymongo as pym import re def removeDuplicates(): client = pym.MongoClient() c = client.tweet.tweet duplicates = [] removepipe = [{"$group":{"_id":"$t_id", "dups":{"$push":"$_id"},"count":{"$sum":1}}},{"$match":{"count":{"$gt":1}}}] try : for ...
from scrapli_netconf.driver import NetconfDriver from scrapli_netconf.transport.plugins.system.transport import NetconfSystemTransport def test_init(): conn = NetconfDriver(host="localhost") assert isinstance(conn.transport, NetconfSystemTransport)
from functools import partial from typing import List, Optional from flair.data import Span def _get_text_from_spans(text: str, spans: List[Span], tag: str) -> Optional[str]: for span in spans: if span.tag == tag: return text[span.start_pos : span.end_pos] return None _get_type_from_spa...
FIELDS = { 'FADD': 6, 'FSUB': 6, 'FMUL': 6, 'FDIV': 6, 'NUM': 0, 'CHAR': 1, 'HLT': 2, 'SLA': 0, 'SRA': 1, 'SLAX': 2, 'SRAX': 3, 'SLC': 4, 'SRC': 5, 'STJ': 2, 'JMP': 0, 'JSJ': 1, 'JOV': 2, 'JNOV': 3, 'JL': 4, 'JE': 5, 'JG': 6, 'JGE': 7, 'JNE': 8, 'JLE': 9, 'JAN': 0, 'JAZ': 1, 'JAP': 2...
# Copyright 2019 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. import os.path import posixpath import web_idl from . import name_style from .blink_v8_bridge import blink_class_name class PathManager(object): """ ...
# Copyright 2021 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
class Solution: def getPermutation(self, n, k): import math nums = range(1, n + 1) ans = '' k -= 1 while n > 0: n -= 1 index, k = divmod(k, math.factorial(n)) ans += str(nums[index]) nums.remove(nums[index]) return ans ...
#!/usr/bin/env -S python3 -u import argparse import os import random import shutil import signal import subprocess import sys N_SIMPLE = 10 DEFAULT_TIMEOUT = 40 REPEAT = 5 def setup_terminal(): cols, rows = shutil.get_terminal_size(fallback=(132, 43)) os.environ['COLUMNS'] = str(cols) os.environ['LINE...
__author__ = 'Dirk Dittert' from sensor_phy_drive import PegasusPhysicalDriveSensor from sensor_enclosure import PegasusEnclosureSensor