content
stringlengths
5
1.05M
import collections import inspect import os from xia2.Handlers.CIF import CIF, mmCIF from xia2.Handlers.Files import FileHandler from xia2.Handlers.Phil import PhilIndex from xia2.Handlers.Streams import banner from xia2.Handlers.Syminfo import Syminfo from xia2.lib.NMolLib import compute_nmol, compute_solvent from xi...
import os import pickle import unittest from galleries.collections.file_stream_dictionary import FileStreamDictionary from galleries.data_read_write import default_reader_writer class FileStreamDictionaryTests(unittest.TestCase): def setUp(self) -> None: self.file_path = "file.pkl" self.batch_si...
""" My DataParallel Implementation for GMN """ import torch import torch.nn as nn from .scatter_gather import scatter_kwargs, gather class DataParallel(nn.DataParallel): def __init__(self, *args, **kwargs): super(DataParallel, self).__init__(*args, **kwargs) def scatter(self, inputs, kwargs, device_...
""" Exceptions to used by the base client of all NBG APIs. """ import re from requests import Response class InvalidResponse(Exception): """ This exception gets raised when an invalid response was received by the server. """ def __init__(self, response: Response, message: str): self.res...
#!/usr/bin/python import cStringIO import json import io import numpy as np from PIL import Image from PIL import ImageDraw from PIL import ImageFont import tensorflow as tf import logging import threading from Queue import Queue BASE_PATH = "/mllib/objectdetection" # ssd_inception_v2_coco latency - 42ms PATH_TO_CK...
''' (c) University of Liverpool 2020 All rights reserved. @author: neilswainston ''' # pylint: disable=invalid-name # pylint: disable=protected-access # pylint: disable=too-few-public-methods import csv import json import os.path from urllib.request import urlopen from opentrons import simulate metadata = {'apiLev...
from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from django.contrib.admin import AdminSite #for flatpage # from django.contrib.flatpages.admin import FlatPageAdmin # from django.contrib.flatpages.models import FlatPage # from django.utils...
#!/usr/bin/env python3 """Safely install dot-files to home directory.""" from pathlib import Path import argparse import hashlib import os import shutil HERE = Path(__file__).parent.absolute() EXCLUDE = [ HERE / 'install.py', HERE / 'README.md', HERE / 'LICENSE.md', HERE / '.git', HERE / '.gitmo...
#!/usr/bin/python # -*- coding: utf-8 -*- import sys from PyQt4 import QtGui, QtCore class Example(QtGui.QWidget): def __init__(self): super(Example, self).__init__() self.initUI() def initUI(self): self.setGeometry(300, 300, 355, 280) self.setWi...
from django.contrib import admin from .models import Level # Register your models here. admin.site.register(Level)
#!/usr/bin/env python3 """Instantiates a storage object. -> If the environmental variable 'HBNB_TYPE_STORAGE' is set to 'db', instantiates a database storage engine (DBStorage). -> Otherwise, instantiates a file storage engine (FileStorage). """ from os import getenv if getenv("HBNB_TYPE_STORAGE") == "db": fr...
from deeprankcore.models.pair import Pair def test_order_independency(): # These should be the same: pair1 = Pair(1, 2) pair2 = Pair(2, 1) # test comparing: assert pair1 == pair2 # test hashing: d = {pair1: 1} d[pair2] = 2 assert d[pair1] == 2 def test_uniquene...
import cv2 import pandas as pd import numpy as np from matplotlib import pyplot as plt import os from mpl_toolkits.mplot3d import Axes3D # Custom Libs from my_paths import directory, histograms_path save_graphs, save_data = False, False metrics = {'filename': [], 'h': [], 's': [], 'v': []} cols = ['filename', 'h', '...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from bs4 import BeautifulSoup import scrape_common as sc from collections import defaultdict from datetime import datetime main_url = "https://www.baselland.ch/politik-und-behorden/direktionen/volkswirtschafts-und-gesundheitsdirektion/amt-fur-gesundheit/medizinische-dien...
import glob import os from typing import List from ._driver import W1Driver from ._exception import NotFoundSensorException from ._sensor import OneWireInterface, OneWire from ._util import dirname_to_mac, mac_to_dirname class Pi1WireInterface: def find_all_sensors(self) -> List[OneWireInterface]: raise ...
#!/usr/bin/env python3 # encoding=utf-8 #codeby 道长且阻 #email @ydhcui/QQ664284092 from core.plugin import BaseHttpPlugin,BaseWebPlugin,BaseHostPlugin,brute import re import socket import binascii import hashlib import struct import re import time class MssqlNoAuth(BaseHostPlugin): bugname = "Mssql弱口令" ...
#!/usr/bin/python import json import sys G = None XY2LL = None NAME_SUFFIXES = [ ' Forest Preserve', ' Forest Reserve', ' National Conservation Area', ' National Monument', ' NM', ' ONA', ' Outstanding Natural Area', ] BLM_CA_NAME_MAP = { 'BAKERSFIELD FIELD OFFICE': 'Bakersfield Field Offi...
# BSD 3-Clause License # Copyright (c) 2021, Mark Liu # 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...
from django.core.management.base import NoArgsCommand # Python 2.3 doesn't have sorted() try: sorted except NameError: from django.utils.itercompat import sorted class Command(NoArgsCommand): help = "Test No-args commands" requires_model_validation = False def handle_noargs(self, **options): ...
# -*- coding: utf-8 -*- __author__ = "Davyd Maker" __version__ = "1.1.2" from xml.dom import minidom import requests headers = { 'User-Agent': 'Mozilla/5.0' } lastKey = open('checkKey.txt', 'a').close() lastKey = open('checkKey.txt', 'r') content = lastKey.readlines() lastKey.close() i = 1 newkey = False try: ...
""" Progress Transcript - allow stdout to terminal and captured in a file too with the ability to log a progress bar when triggered by 'actions' IMPORTANT: In a Jupyter notebook, the text and progress bars for later cells will show up after the first cell where progress_transcript is s...
def _init(): pass # end _init def _update(): pass # end _update def _draw(): px8_print("Baby step", 40, 64, 1) # end _draw
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models def disable_hydroshare_autosync(apps, schema_editor): HydroShareResource = apps.get_model('export', 'HydroShareResource') HydroShareResource.objects.all().update(autosync=False) class Migration(migratio...
"""Base class for Repository objects.""" import logging import os from typing import NamedTuple from urllib import parse as urlparse from .util import RepoLoggingAdapter, mkdir_p, run logger = logging.getLogger(__name__) class VCSLocation(NamedTuple): url: str rev: str def convert_pip_url(pip_url: str) ->...
result = 0 for num in range(51): result += num print(result)
__author__ = 'Paolo Prandoni' def note_to_freq(note): # general purpose function to convert a note in standard notation # to corresponding frequency if len(note) < 2 or len(note) > 3 or \ note[0] < 'A' or note[0] > 'G': return 0 if len(note) == 3: if note[1] == 'b': ...
# Copyright [2017-2021] [IBM 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 writ...
from win32com.client import gencache from win32com.client import constants, gencache import sys from tkinter import * from tkinter import ttk def createPdf(result, wordPath, pdfPath): word = gencache.EnsureDispatch('Word.Application') doc = word.Documents.Open(wordPath, ReadOnly=1) doc.ExportAsFixedFormat...
import pandas as pd import unittest from api.dataset import Dataset from api.project import Project class projectTest(unittest.TestCase): def setUp(self): self.project = Project() def test_name(self): self.project.set_name("test_project") self.assertEqual(self.project.name, "test_pro...
import re from colored import fg, attr import ransomWare import DBConn class detectionAPI: def __init__(self): """ [This class uses ransomWare extList attribute for its methods.] attributes: extList: List of regexed ransom patterns methods: ransomDetect(): checks for ransom, retur...
import argparse import numpy as np import os import pandas as pd import cv2 from matplotlib import pyplot as plt from tqdm import tqdm import random import gc import torch import torch.nn as nn from torch.utils.data import DataLoader from torch.utils.data.sampler import SequentialSampler, RandomSampler from apex impor...
# -*- coding: utf-8 -*- """ Created on Wed Mar 6 21:51:31 2019 @author: Medeea """ #Simple Linear Regression #Importing the libraries #3 libraries #mathematic tools import numpy as np #plot nice charts import matplotlib.pyplot as plt #import datasets import pandas as pd #importing...
from django.conf.urls import url from . import api urlpatterns = [ url(r'^$', api.index, name='todo'), url(r'^add$', api.add, name='add'), url(r'^delete$', api.delete, name='delete'), url(r'^toggle$', api.toggle, name='toggle'), url(r'^change$', api.change, name='change') ]
# coding=utf-8 """ 演示注入记事本进程。 !!! 运行此脚本前需要首先打开记事本。 """ import frida # 附加到记事本进程,只有附加到目标进程,才能对其进行操作,这个必须是动态插装的第一步 session = frida.attach("notepad.exe") # 获取记事本进程加载的所有模块(动态库、程序) modules = session.enumerate_modules() print("=========== modules ===========") for module in modules: print(module.name) # 加载...
#!/usr/bin/env python import scipy as sp import scipy.stats import pprint import argparse import csv import re import os import MySQLdb try: import xlsxwriter import xlrd writeXLS = True print 'yes XLS module imported' except: writeXLS = False print 'No XLS module imported' ### Note header ...
# -*- coding: utf-8 -*- { '!langcode!': 'id', '!langname!': 'Indonesian', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN', '%d days ago':...
#!/usr/bin/env python import kubernetes import logging import os import os.path import requests import signal import subprocess import time import yaml import urllib3 # Disable warnings when connecting to the kubernetes API urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) logging_level = os.enviro...
from distutils.core import setup setup( name='betwixt', version='1.0', description='Selective fabric deployment of compiled projects using git repositories', author='Joel Purra', author_email='code+betwixt@joelpurra.com', url='https://joelpurra.com/', packages=['betwixt'], requires=['fa...
import os import sys from setuptools import find_packages from setuptools import setup v = sys.version_info if v[:2] < (3, 6): error = "ERROR: IllumiDesk requires Python version 3.6 or above." print(error, file=sys.stderr) sys.exit(1) shell = False if os.name in ("nt", "dos"): shell = True warnin...
# -*- coding: utf-8 -*- from django.urls import path from rest_framework_simplejwt.views import TokenRefreshView from ..views.auth import TokenObtainPairView urlpatterns = [ path('auth/token/', TokenObtainPairView.as_view(), name='auth.token_obtain_pair'), path('auth/token/refresh/', TokenRefreshView.as_vie...
from django.conf.urls import url, include from django.conf import settings from django.conf.urls.static import static from . import views urlpatterns = [ url(r'^$', views.index_page, name='landingpage'), url(r'^search/', views.search_business, name='search_business'), url(r'^createprofile/$', views.creat...
# Copyright 2015 Planet Labs, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wr...
"""priority_fee_for_all Revision ID: 7a86a5703e27 Revises: 5cdd1c1d355e Create Date: 2020-02-26 14:18:10.817049 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '7a86a5703e27' down_revision = '5cdd1c1d355e' branch_labels = None depends_on = None def upgrade():...
# Copyright 2019 Red Hat, 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...
""" .. module:: assembler :synopsis: assemble genes from RNASeq data (normalized genome coverage (bigwig) and junctions) .. moduleauthor:: Ken Sugino <ken.sugino@gmail.com> """ # system imports import gzip import os from functools import reduce from operator import iadd, iand from collections import Counter fro...
#!/usr/bin/env python '''Context functionality within the PyGame environment ''' #test and import pygame try: import pygame from pygame.locals import * import pygame.key import pygame.display except ImportError: raise ImportError, "The pygame package is required for the Pygame GL Context" if pygame...
#!/usr/bin/python3.8 from app.camera.kernel import Kernel _k = Kernel() _k.initialize() def _video_feed() -> any: try: global _k if _k: return _k.get_frame() return None except ValueError as e: return str(e), 400 except Exception as e: print(e) r...
import os from datetime import datetime import gym import gym_kuka_mujoco import numpy as np from stable_baselines import PPO2 from stable_baselines.common.vec_env import DummyVecEnv, SubprocVecEnv, VecNormalize from stable_baselines.common.policies import MlpPolicy num_env = 8 day, time = datetime.now().isoformat(...
#!/usr/bin/env python3 import json TEST_PACKAGES_DATA=""" [ {"full_name": "Atom Editor 1.31.1", "name": "atom", "package_type": "brewcask", "state" : "present" }, {"full_name": "lzip 1.2.0", "name": "lzip", "package_type": "brew", "state" : "absent" }, {"full_name": "Keep It (1.5.2)", "name": "Keep It", "...
"""Methods to export_data tweets.""" from typing import List from .util import clear_file from ..model import Tweet from ..tweet_output import CsvTweetOutput from ..tweet_output import JsonLineFileTweetOutput def export_tweets_to_csv(tweets: List[Tweet], filename: str): """Method to export_data tweets to csv."""...
#Light: #1. Выберете дз, к функциям которого будете писать тесты (например, вебинар 5); #2. Создайте дополнительную ветку в репозитории GitHub с тестами; #3. Напишите не менее 5ти тестов к функциям выбранного урока; #4. В качестве ответа на дз пришлите ссылку на ветку с тестами или ссылку на PullRequest ветки с тестами...
#!/usr/bin/python2 """ Copyright (c) 2014 Timothy Elniski 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, merge,...
import os import sys import nest import getopt import logging # Add the work directory to the PATH sys.path.append('/'.join(os.path.realpath(__file__).split('/')[:-3])) logging.basicConfig(level=logging.DEBUG) from NEST.second_level.src.tools.cleaner import Cleaner from NEST.second_level.src.paths import topologies_p...
# coding: utf-8 import PyPDF2 import os import logging class Combine_PDF(): def __init__(self): self.logger = logging.getLogger("SR_E2W2P.Combine_PDF") self.logger.info("init Combine_PDF") pass def append_PDFReaderObj_to_PDFWriterObj(self, pdfFileObj, pdfWriter): ''' ...
import glob import os ## \file build_xml.py # \brief convert an AMPL format model file to xml file ## # \fn build_xml(xml_name: str, model_name: str): # \brief convert an AMPL format model file to xml file # # @param xml_name The filename of the output xml file # @param model_name The filename of the inp...
# Task 01. No Vowels word = input() VOWELS = ['a', 'o', 'u', 'e', 'i'] no_vowels = [x for x in word if x.lower() not in VOWELS] print(*no_vowels, sep="")
import os import json import logging from django.conf import settings from jsonschema import validate as jsonschemaValidate logger = logging.getLogger(__name__) class JSONSchema: def __init__(self, filepath): abs_filepath = os.path.join(settings.JDH_SCHEMA_ROOT, filepath) logger.info( ...
#!/usr/bin/env python3 import yaml, json import pprint pp = pprint.PrettyPrinter(indent=4) with open("q6_yaml_stuff.yml") as f: cisco_yaml = yaml.load(f) with open("q6_json_stuff.json") as f: cisco_json = json.load(f) print("--- YAML ---") pp.pprint(yaml.dump(cisco_yaml)) print("--- JSON ---") pp.pprint(j...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. """Distributed helpers.""" import torch import torch.distributed as dist def is_root_proc(): """ Determines if the current process is the root process. """ if torch.distributed.is_initialized(): r...
from create_tree import * from nltk import Tree my_tree = generate_data(4) pprint(my_tree) tree_text = ' '.join(str(e) for e in convert_to_list_nltk(my_tree,[])) print(tree_text) nltk_tree = Tree.fromstring(tree_text) from nltk.treeprettyprinter import * print(TreePrettyPrinter(nltk_tree).text()) print(nltk_tree) ...
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="drypy_airflow", version="0.0.4", author="dhan16", author_email="chandan.nath@gmail.com", description="Airflow extensions", long_description=long_description, long_description_conte...
import os import time import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from ..registry import POINT_DETECTOR from .directional import PointDetector, DirectionalPointDetector @POINT_DETECTOR.register class PointDetectorBase(nn.Module): def __init__(self, cfg): super()._...
# -*- coding: utf-8 -*- """ Created on Mon Oct 10 11:30:11 2016 @author: sshank """ import re import os import subprocess import numpy as np from Bio.SeqRecord import SeqRecord from Bio import SeqIO from Bio import AlignIO from Bio.Seq import Seq from Bio.Align import MultipleSeqAlignment from Bio.Alphabet import IUP...
# Copyright Materialize, Inc. and contributors. All rights reserved. # # Use of this software is governed by the Business Source License # included in the LICENSE file at the root of this repository. # # As of the Change Date specified in that file, in accordance with # the Business Source License, use of this software...
# "Coffee Machine" program written by - Amish Verma # Twitter - www.twitter.com/thisisamish # GitHub - www.github.com/thisisamish # Importing data about coffee types import data is_off = False # Declaring and initialize coffee resources variables curr_water = 1000 curr_milk = 500 curr_coffee = 760 total_money = 0 ...
from django.http import Http404 from rest_framework import generics, status from rest_framework.exceptions import NotFound from rest_framework.generics import get_object_or_404 from rest_framework.permissions import IsAdminUser from rest_framework.response import Response from resource_tracker.api.serializers.resource...
import dailymotion import unittest import config import re import time import os import pytest import sys class TestA(unittest.TestCase): @classmethod def setUpClass(self): self.api_base_url = config.BASE_URL or 'http://api.dailymotion.com' self.api_key ...
# ao invés de retornar um valor inteiro baseado na sequência de fibonacci, a função retornará uma string def rec(n): if n == 0: return 'b' elif n == 1: return 'a' else: return rec(n-1)+ rec(n-2) print(rec(int(input())))
import pymysql pymysql.install_as_MySQLdb() import MySQLdb from config import * from db.function.Querry import Querry from db.files.data import * from db.function.ExistProfil import ExistProfil class TphInit(): def __init__(self, id_owner, expiration, frequency): self.id_owner = id_owner self.ex...
# This file is part of the Reproducible and Reusable Data Analysis Workflow # Server (flowServ). # # Copyright (C) 2019-2021 NYU. # # flowServ is free software; you can redistribute it and/or modify it under the # terms of the MIT License; see LICENSE file for more details. """Unit tests for the file store functionali...
import os from unittest.mock import patch import logging from pytest import fixture, mark from traitlets.config import Config from ..bitbucket import BitbucketOAuthenticator from .mocks import setup_oauth_mock def user_model(username): """Return a user model""" return { 'username': username, } ...
import torch from mmcv.ops import nms_match from ..builder import BBOX_SAMPLERS from ..transforms import bbox2roi from .base_sampler import BaseSampler from .sampling_result import SamplingResult @BBOX_SAMPLERS.register_module() class ScoreHLRSampler(BaseSampler): r"""Importance-based Sample Reweighting (ISR_N),...
# Copyright 2021 Viktor Kravchenko (viktor@vik.works) # 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...
""" IO编程: IO(Input/Output流) input: 从磁盘读取文件到内存 output: 把内存计算后的数据写入到磁盘(磁盘文件, 网络等) 流: Stram Input Stream: 数据从磁盘流进内存 Output Stream: 数据从内存流出到磁盘 网站: 浏览器和服务器至少需要两个流 """ # 文件读 # 读写文件的功能都是由操作系统提供的 # 读写文件是请求操作系统打开一个文件对象 # 读文件 try: f = open(r'C:\develop\Inspiration\career\python\20190121\Code\file\test.txt') #...
def get_discount_factor(rate: float, tenor: float) -> float: """The discount factor :param rate: The interest rate. :type rate: float :param tenor: The tenor (in years). :type tenor: float :return: The discount factor. :rtype: float """ assert rate == 5.0 return (1 + rate) ** -...
"""Dynamic programming solver for stamps problem. 1. Break the problem into smaller subproblems 2. Remember the results of the subproblems to avoid recalculation We exploit symmetry in the optimal solutions due to the associative probpery of addition. If [S_a1, ..., S_an] and [S_b1, ..., S_bn] are ...
from typing import Optional from jose import JWTError, jwt from fastapi import HTTPException, status from datetime import datetime, timedelta from model.model_token import TokenData # to get a string like this run: # openssl rand -hex 32 SECRET_KEY = "a92f61642b2561b576d066a20d6459d652977d9eaaa9d4b077b3640487b9468f" ...
# encoding: utf-8 # author: Alex # contact: ialexwwang@gmail.com # version: 0.1 # license: Apache Licence # file: dpcnn_model.py # time: 2019-07-02 19:15 # Reference: # https://ai.tencent.com/ailab/media/publications/ACL3-Brady.pdf # https://github.com/Cheneng/DPCNN # https://github.com/miracleyoo/DPCNN-TextCNN-Pytorc...
from ..publish import check_directory_structure def test_directory_structure(): check_directory_structure()
from .base import WhiteNoise __version__ = '3.3.0' __all__ = ['WhiteNoise']
import pyglet from pyglet import gl import numpy as np from collections import namedtuple from gym_backgammon.envs.backgammon import WHITE, BLACK, NUM_POINTS import os import platform Coords = namedtuple('Coords', ['x', 'y']) SCALING = 2 if platform.system() == 'Darwin' else 1 class Viewer(object): def __init__(s...
from dataclasses import dataclass @dataclass class OkexDTO: base_rest_url: str api_key: str secret_key: str passphrase: str instId: str
# 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 ...
import re text = "N1: +48 123 456 789, N2: +123 (98)7 654 321, N3: 987 654 321, N4: 987654321" pattern = re.compile(r"(?:\+(\d{2,3})[-\s])?\(?(\d{2})\)?(\d[-\s]\d{3}[-\s]\d{3})")
# Copyright 2020 Soda # 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 #...
# -*- coding: utf-8 -*- """ Created on Sun Feb 28 20:53:38 2021 @author: shambhunath gupta """ def common_letter(): str1 = input("Enter first String : ") str2 = input("Enter first String : ") #to remove the duplicates,we use set s1= set(str1) s2= set(str2) #now for common letters ...
# coding: utf-8 """ Fulfillment API Use the Fulfillment API to complete the process of packaging, addressing, handling, and shipping each order on behalf of the seller, in accordance with the payment method and timing specified at checkout. # noqa: E501 OpenAPI spec version: v1.19.9 Generated b...
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function import sys import click from polyaxon_cli.cli.getters.build import get_build_or_local from polyaxon_cli.client import PolyaxonClient from polyaxon_cli.client.exceptions import PolyaxonHTTPError, PolyaxonShouldExitError from poly...
#!/usr/bin/env python class Solution: def countDigitOne(self, n): """ :type n: int :rtype: int """ num, numNew = n, n bitLen = 10 p = [0] * bitLen a = [0] * bitLen ret = 0 for n in range(1, bitLen): p[n] = 10 ** (n-1) + 10 ...
from mock import MagicMock from depman import Apt, Operation from syn.base_utils import assign, is_hashable from depman import apt as depd from depman.apt import Install, Update #------------------------------------------------------------------------------- # Apt def test_apt(): apt = Apt('make') assert apt....
def add(number1, number2): return number1 + number2 def sub(number1, number2): return number1 - number2 def multi(number1 , number2): return number1 * number2 def div(number1, number2): return number1 / number2 # addition_result = add(3, 5) # print(addition_result) # # sub_result = sub(8, 6) # p...
import bpack_utils.resolver as resolver import argparse import os import json import bbuild import sys curdir = os.getcwd() def do_init(name: str, author:str): metafile=os.path.join(curdir, "bpackproject.json") if not os.path.exists(metafile): data = {'name':name, 'version': '0.0.1', "author":author, ...
from time import sleep from userbot import CMD_HELP from userbot.events import register @register(outgoing=True, pattern="^.sdby(?: |$)(.*)") async def typewriter(typew): typew.pattern_match.group(1) sleep(2) await typew.edit("`Pertama-tama lu itu cantik`") sleep(2) await typew.edit("...
#!/usr/bin/python # # Router.py # # Created on: 2 June, 2011 # Author: black # # class definition for the router object. This object will send # a string to the correct agent. # # This material is based on research sponsored by DARPA under agreement # number FA8750-10-2-0165. The U.S. Governm...
import falcon from ebl.fragmentarium.application.fragment_finder import FragmentFinder from ebl.fragmentarium.application.fragment_pager_schema import FragmentPagerInfoSchema from ebl.fragmentarium.web.dtos import parse_museum_number from ebl.users.web.require_scope import require_scope class FragmentPagerResource: ...
#!/usr/bin/python3 """ Python中的多线程 例子1:将耗时间的任务放到线程中以获得更好的用户体验。 有“下载”和“关于”两个按钮,用休眠的方式模拟点击“下载”按钮会联网下载文件需要耗费10秒的时间, 如果不使用“多线程”,我们会发现,当点击“下载”按钮后整个程序的其他部分都被这个耗时间的任务阻塞而无法执行了, 这显然是非常糟糕的用户体验。 version: 0.1 author: icro """ import time import tkinter import tkinter.messagebox from threading import Thread # ================...
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve. # # 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 applic...
## NOTE! See http://western-skies.blogspot.com/2008/02/simple-complete-example-of-python.html for __getstate__() and __setstate__() methods # Imports. import os from ..utils.blender import add_group from .MappedClass import MappedClass try: import bpy is_blender = True except ImportError: is_blender = Fal...
import json import torch import numpy as np ckpt_path = 'checkpoints/zero_padding_best_deeplabv3_resnet50_cityscapes_os16.pth' model = torch.load(ckpt_path, map_location=torch.device('cpu'))["model_state"] print('checkpoint Loaded') model_list = list(model) for k in range(0, len(model_list)): if 'conv' in m...
# modules.__init__.py # # Defines modules_list which is a list of all modules to be registered and # launched. Modules in modules_list are all launched in their own thread. # from modules.ambient_noises.module import AmbientNoisesModule from modules.debug_signals.module import DebugSignalsModule from modules.tv.modul...