content
stringlengths
0
894k
type
stringclasses
2 values
import os import sys ''' 3个空瓶换一瓶 input: n个空瓶 outpu: 最终可换瓶数 ''' def demo1(): while True: try: a = int(input()) if a != 0: print(a//2) except: break ###################################### ''' input: n以及n个随机数组成的数组 output: 去重排序后的数组 ''' def dem...
python
class SETTING: server_list = { "presto": { "connect_type": "PrestoConnector", "url": { "username": "hive" ,"host": "" ,"port": 3600 ,"param" : "hive" ,"schema": "default" ,"metastore": "my...
python
# Copyright 2015: Mirantis 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 ap...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time : 2017/8/23 下午12:54 # @Author : chenyuelong # @Mail : yuelong_chen@yahoo.com # @File : read.py # @Software: PyCharm import os, sys sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(sys.argv[0])))) class read(): ''' fastq中每条read ...
python
# -*- coding: utf-8 -*- """ awsscripter.cli This module implements awsscripter's CLI, and should not be directly imported. """ import os import warnings import click import colorama import yaml from awsscripter.cli.init.init import init_group from awsscripter.cli.audit.audit import audit_group from awsscripter.cli....
python
import tfchain.polyfill.encoding.object as jsobj import tfchain.polyfill.array as jsarr import tfchain.polyfill.asynchronous as jsasync import tfchain.polyfill.crypto as jscrypto import tfchain.client as tfclient import tfchain.errors as tferrors from tfchain.chain import NetworkType, Type from tfchain.balance import...
python
import configparser from fast_arrow import Client, OptionOrder print("----- running {}".format(__file__)) config = configparser.ConfigParser() config.read('config.debug.ini') # # initialize fast_arrow client and authenticate # client = Client( username = config['account']['username'], password = config['a...
python
# This file is part of Indico. # Copyright (C) 2002 - 2020 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from __future__ import unicode_literals from datetime import time from operator import itemgetter import...
python
#!/usr/bin/env python # import necessay modules from lxml import html from lxml import etree import requests # top-level domain parent_domain = 'http://trevecca.smartcatalogiq.com' # parent page showing the porgrams of study parent_page_url = parent_domain + '/en/2015-2016/University-Catalog/Programs-of-Study' paren...
python
x1 = int(input()) y1 = int(input()) x2 = int(input()) y2 = int(input()) x3 = int(input()) y3 = y2 a = abs(x3 - x2) h = abs(y1 - y2) s = a * h / 2 print(s)
python
#!/usr/bin/python import serial import sys import time import string from serial import SerialException import RPi.GPIO as gpio class SerialExpander: def __init__(self, port='/dev/ttyS0', baud=9600, timeout=0, **kwargs): self.__port = port self.__baud = baud self.ser = serial.Serial(self.__port, self.__baud, ...
python
from setuptools import setup, find_packages with open('README.md') as f: readme = f.read() with open('LICENSE') as f: content = f.read() setup( name='Wechatbot', version='0.0.1', description='Wechatbot project', long_description=readme, install_requires=['itchat==1.3.10', 'requests==2.19.1...
python
TLS_VERSIONING = "1.0.23" TLS_DATE = "12 March 2019"
python
""" This module deals with the definition of all the database models needed for the application """ from app import db, app from passlib.apps import custom_app_context as pwd_context from itsdangerous import (TimedJSONWebSignatureSerializer as Serializer, BadSignature, SignatureExpired) from math import cos, sin,...
python
from WConio2 import textcolor, clrscr, getch, setcursortype import ctypes ctypes.windll.kernel32.SetConsoleTitleW("n Numbers HCF") def hcf(n): a, b, r = n[0], n[1], 0 for x in range(0, len(n) - 1): while a != 0: r = b % a b = a a = r a = b if x + 2 ...
python
# Copyright (c) 2019 AT&T Intellectual Property. # Copyright (c) 2018-2019 Nokia. # # 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...
python
# Copyright 2014 Facebook, Inc. # Modified by Vivek Menon from facebookads.adobjects.adaccount import AdAccount from facebookads.adobjects.campaign import Campaign from facebookads.adobjects.adset import AdSet from facebookads.adobjects.adcreative import AdCreative from facebookads.adobjects.ad import Ad from facebook...
python
def solution(s): word_dict = {} for element in s.lower(): word_dict[element] = word_dict.get(element, 0) + 1 if word_dict.get('p', 0) == word_dict.get('y', 0): return True return False if __name__ == '__main__': s = 'pPoooyY' print(solution(s)) """ def solution...
python
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt # ERPNext - web based ERP (http://erpnext.com) # For license information, please see license.txt from __future__ import unicode_literals import frappe, json import http.client import mimetype...
python
import warnings from datetime import datetime import pytest import pandas as pd from mssql_dataframe.connect import connect from mssql_dataframe.core import custom_warnings, custom_errors, create, conversion, conversion_rules from mssql_dataframe.core.write import insert, _exceptions pd.options.mode.chained_assignme...
python
# Server must be restarted after creating new tags file from django import template register = template.Library () @ register.inclusion_tag ('oauth/tags/user_avatar.html') def get_user_avatar_tag (user): '''Return the user's picture, it is an img tag''' return {'user': user}
python
# -*- coding:Utf-8 -*- from gi.repository import Gtk, GObject, GdkPixbuf from crudel import Crudel import glob class PicsouDiapo(Gtk.Window): """ Affichage d'une image dans une Gtk.Window """ def __init__(self, crud, args): Gtk.Window.__init__(self, title=args) self.crud = crud self.ar...
python
""" ====================== Geographic Projections ====================== This shows 4 possible geographic projections. Cartopy_ supports more projections. .. _Cartopy: http://scitools.org.uk/cartopy """ import matplotlib.pyplot as plt ############################################################################### ...
python
""" Wrappers around the Google API's. """ import os import json from datetime import ( datetime, timedelta, ) from collections import namedtuple try: # this is only an issue with Python 2.7 and if the # Google-API packages were not installed with msl-io from enum import Enum except ImportError: ...
python
#!/bin/python #NOTE: modified from original to be more module friendly (PS) #Original source: https://github.com/jczaplew/postgis2geojson/blob/master/postgis2geojson.py import argparse import datetime import decimal import json import subprocess import psycopg2 #defaults for use as a module, possibly modified by t...
python
"""Package initialization procedures. The cli package provides components to build and execute the CLI. """
python
import re # noinspection PyShadowingBuiltins def all(_path): return True def path_contains(*subs): def func(path): return any(map(path.__contains__, subs)) return func def contains_regex(pattern): def func(path): with open(path) as f: code = f.read() return boo...
python
#### import the simple module from the paraview from paraview.simple import * #### disable automatic camera reset on 'Show' paraview.simple._DisableFirstRenderCameraReset() # get color transfer function/color map for 'DICOMImage' dICOMImageLUT = GetColorTransferFunction('DICOMImage') # Rescale transfer function dICOM...
python
from django.db.models.signals import post_save from django.dispatch import receiver from django.core.cache import cache from .models import * @receiver(post_save, sender=Email) def question__delete_caches_on_create(sender, instance, created, **kwargs): cache_name = "get_sent_emails_user_id_" + str(1) if(cache_name i...
python
from flask import Blueprint, session, redirect, render_template, request, flash, url_for, abort from models import PageDetails, Database,Authentication, General from functools import wraps from validator_collection import * admin_remove = Blueprint("admin_remove", __name__) @admin_remove.route("/Admin/Remove", metho...
python
# # Test Netatmo class # import logging import Netatmo def main(): logging.basicConfig(level=logging.DEBUG) netatmo = Netatmo.Netatmo("PyAtmo.conf") home=netatmo.getHomesData() netatmo.getHomeStatus() if __name__ == "__main__": main()
python
# 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...
python
import json import random from flask import Flask, request from flask_restplus import Resource, Api, Namespace import os from datetime import date, datetime from faker import Faker import security fake = Faker('en_AU') ## load bsb data into memory with open('./resources/bsbs.json') as json_file: bsbs = json.load(...
python
import os import pathlib import re from collections import defaultdict from functools import lru_cache import stanza import torch from loguru import logger from nlgeval import NLGEval from transformers import AutoModelForCausalLM, AutoTokenizer current_dir = pathlib.Path(__file__).parent.absolute() def step_len(fun...
python
# # Copyright (c) nexB Inc. and others. All rights reserved. # VulnerableCode is a trademark of nexB Inc. # SPDX-License-Identifier: Apache-2.0 # See http://www.apache.org/licenses/LICENSE-2.0 for the license text. # See https://github.com/nexB/vulnerablecode for support or download. # See https://aboutcode.org for mor...
python
__all__ = ("MDRenderer", "LOGGER", "RenderTreeNode", "DEFAULT_RENDERER_FUNCS") import logging from types import MappingProxyType from typing import Any, Mapping, MutableMapping, Sequence from markdown_it.common.normalize_url import unescape_string from markdown_it.token import Token from mdformat.renderer._default_...
python
import numpy as np from utils import env_paths as paths from base import Train import time class TrainModel(Train): def __init__(self, model, output_freq=1, pickle_f_custom_freq=None, f_custom_eval=None): super(TrainModel, self).__init__(model, pickle_f_custom_freq, f_custom_eval) ...
python
from typing import Text, Type from aiogram import types from aiogram.dispatcher.filters.builtin import Command, Text from aiogram.dispatcher import FSMContext from aiogram.types import message from middlewares.states.all_states import download_sticker_state import os from loader import dp @dp.message_handler(text="/c...
python
import csv import argparse import enum import sys from normalizer import normalizer from common import common def RepresentsFloat(val): try: float(val) return True except ValueError: return False if __name__ == "__main__": ft_type = enum.Enum("ft_type", ("train", "valid")) p...
python
import os import sys import json import tweepy import requests import pandas as pd from defipulse import DefiPulse from coingecko import CoinGecko from subprocess import call # Data Preprocessing and Feature Engineering consumer_key = os.environ.get('TWITTER_CONSUMER_KEY', 'ap-northeast-1') consumer_secret = os.enviro...
python
# # Copyright (c) 2021 Incisive Technology Ltd # # 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, pu...
python
"""Remote apps ============= """
python
import os import sqlite3 ''' THING I THINK I'M MISSING The completed date shouldn't be a boolean because it can be overdue. It was an integer before so it could be set to the date in which it was marked completed. This should be changed back. ''' class Equipment: def __init__(self, pk=-1, name=''): sel...
python
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html from scrapy import Item, Field from collections import OrderedDict import six class ScholarshipItem(Item): University = Field() Program = Field() Degree = ...
python
import boto3 import csv profile = "default" def get_instance(instance_name): ec2 = boto3.resource('ec2') return ec2.instances.filter(Filters=[{'Name': 'tag:Name', 'Values': [instance_name]}]) boto3.setup_default_session(profile_name=profile) ec2 = boto3.client('ec2') ec2_list = [] sg_name_dict = {} # dict ...
python
# Copyright 2017-present Open Networking Foundation # # 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 agr...
python
from ..resources.resource import Resource import requests from requests.auth import HTTPBasicAuth class Suppliers(Resource): def __init__(self): super().__init__("suppliers") def delete(self, id): raise NotImplementedError("Not possible to post a warehouse")
python
def tree(x): print("\n".join([f"{'*'*(2* n + 1):^{2*x+1}}" for n in range(x)])) def trunk(n): for i in range(n): for j in range(n-1): print(' ', end=' ') print('***') tree(1) trunk(3)
python
# -*- coding: utf-8 -*- import tkinter as tk from tkinter import messagebox import algoritmo import aicSpider class SampleApp(tk.Tk): def __init__(self): tk.Tk.__init__(self) self._frame = None self.switch_frame(StartPage) def switch_frame(self, frame_class): """Destroi frame ...
python
from django.conf import settings from django.urls import include, path from . import views urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("...
python
import argparse import os import torch from torch import nn, optim from torch.nn import functional as F from torch.utils.data import DataLoader from torchvision import datasets, transforms # setup parser = argparse.ArgumentParser(description='PyTorch MNIST Example') parser.add_argument('--batch-size', type=int, defaul...
python
"""Using a class as a decorator demo. Count the number of times a function is called. """ class CallCount: def __init__(self, function): self.f = function self.count = 0 def __call__(self, *args, **kwargs): self.count = 1 return self.f(*args, **kwargs) @property de...
python
# Copyright (c) Open-MMLab. All rights reserved. from mmcv.runner.hooks.hook import HOOKS, Hook @HOOKS.register_module() class AlternateTrainingHook(Hook): # def before_train_iter(self, runner): def before_train_epoch(self, runner): runner.model.module.neck.epoch_num = runner._epoch # if runner...
python
import os import logging from flask import Flask from slack import WebClient from slackeventsapi import SlackEventAdapter # Initialize a Flask app to host the events adapter app = Flask(__name__) # Create an events adapter and register it to an endpoint in the slack app for event injestion. slack_events_adapter = Slac...
python
import os import sys import glob import argparse import numpy as np from PIL import Image from Utility import * from keras.applications.vgg16 import VGG16, preprocess_input from keras.models import Model, load_model from keras.layers import Dense, GlobalAveragePooling2D, BatchNormalization from keras.preprocessing.im...
python
from __future__ import absolute_import from .base import Model from .base import DifferentiableModel class ModelWrapper(Model): """Base class for models that wrap other models. This base class can be used to implement model wrappers that turn models into new models, for example by preprocessing the ...
python
from jinja2 import Template import bot_logger import lang import models def help_user(msg): user = models.User(msg.author.name) if user.is_registered(): msg.reply(Template(lang.message_help + lang.message_footer).render( username=msg.author.name, address=user.address)) else: b...
python
#!/usr/bin/env python import sys import random import itertools import ast def nbackseq(n, length, words): """Generate n-back balanced sequences :param n: int How many characters (including the current one) to look back to assure no duplicates :param length: int The total length o...
python
sir = "mere pere droguri mofturi CamIoane" rime = {} for i in range(len(sir)): if (i == 0 or sir[i - 1] == " "): k = i if (sir[i] == " "): if (rime.get(sir[i - 2:i]) == None): rime[sir[i - 2:i]] = [sir[k:i]] else: rime[sir[i - 2:i]].append(sir[k:i]) ...
python
import os import sys import cherrypy import ConfigParser import urllib import urllib2 import simplejson as json import webtools import time import datetime import random import pprint from pyechonest import song as song_api, config config.TRACE_API_CALLS=True config.ECHO_NEST_API_KEY='EHY4JJEGIOFA1RCJP' import collec...
python
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ppretredit.ui' # # Created: Mon Jan 11 21:22:20 2010 # by: PyQt4 UI code generator 4.6 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui class Ui_TrainerEditDlg(object): def setupUi(self, Tra...
python
import datetime as dt import smtplib import random import pandas import os PLACEHOLDER = "[NAME]" MY_EMAIL = "my_email@gmail.com" MY_PASSWORD = "my_password" LETTER_TO_SEND = "" now = dt.datetime.now() is_day = now.day is_month = now.month data = pandas.read_csv("./birthdays.csv") birthdays = data.to_dict(orient="rec...
python
# coding=utf-8 import json from ibm_watson import LanguageTranslatorV3 from ibm_cloud_sdk_core.authenticators import IAMAuthenticator authenticator = IAMAuthenticator('your_api_key') language_translator = LanguageTranslatorV3( version='2018-05-01', authenticator=authenticator) language_translator.set_service_u...
python
# TODO: support axis=k to create multiple factors for each row/col # TODO: knapsack (how to pass costs? must check broadcast/shape) class Logic(object): def __init__(self, variables): self._variables = variables # TODO: deal with negated def _construct(self, fg, variables): return [fg.crea...
python
import sys import os import numpy as np import shutil from common import PostProcess, update_metrics_in_report_json from common import read_limits, check_limits_and_add_to_report_json #from common import VirtualVehicleMakeMetrics as VVM def main(): print "in main....." sampleRate = 0.10 startAna...
python
# Algorithms > Warmup > Simple Array Sum # Calculate the sum of integers in an array. # # https://www.hackerrank.com/challenges/simple-array-sum/problem # # # Complete the simpleArraySum function below. # def simpleArraySum(ar): # # Write your code here. # return sum(ar) if __n...
python
from cached_property import cached_property from onegov.activity import Activity, Attendee, Booking, Occasion from onegov.feriennet import _ from onegov.feriennet import FeriennetApp from onegov.feriennet.collections import BillingCollection, MatchCollection from onegov.feriennet.exports.unlucky import UnluckyExport fr...
python
# -*- coding: utf-8 -*- """Configurations for slimming simple network. - Author: Curt-Park - Email: jwpark@jmarple.ai """ from config.train.cifar100 import simplenet, simplenet_finetune train_config = simplenet.config regularizer_params = { "REGULARIZER": "BnWeight", "REGULARIZER_PARAMS": dict(coeff=1e-5), ...
python
# hack to capture stdout to a string, to test it import re import os import subprocess import io import sys from contextlib import contextmanager import filecmp def test_rr_cases(): # now for various combinations of inputs output_file = 'test_output.csv' # test exact round robin case, but just once ...
python
from gpkit import Model, Variable, VectorVariable, SignomialsEnabled import numpy as np class MST(Model): def setup(self, N): edgeCost = VectorVariable([N, N], 'edgeCost') edgeMaxFlow = VectorVariable([N, N], 'edgeMaxFlow') ...
python
import pytest from auth import create_jwt_payload @pytest.mark.usefixtures("default_qr_code") def test_qr_exists(client, default_qr_code): code = default_qr_code["code"] graph_ql_query_string = f"""query CheckQrExistence {{ qrExists(qrCode: "{code}") }}""" data = {"query": grap...
python
import os import time import requests from flask import render_template, request, flash, redirect, url_for, abort from jinja2 import Markup from app import app, PLOTS_FOLDER, UPLOAD_FOLDER from functions import dir_listing, process_images @app.route('/') def home(): return render_template('home.html') @app.ro...
python
# Packages from sys import argv, exit from os.path import realpath, dirname from flask import Flask from flask_script import Manager from flask_migrate import Migrate, MigrateCommand from flask_sqlalchemy import SQLAlchemy # Local from config import Config path = dirname(realpath(__file__)) secret = "%s/app/app.secre...
python
#! /usr/bin/env python from __future__ import print_function from builtins import str import sys import os from vmrunner import vmrunner import socket # Get an auto-created VM from the vmrunner vm = vmrunner.vms[0] def UDP_test(trigger_line): print("<Test.py> Performing UDP tests") HOST, PORT = "10.0.0.55", 4242...
python
#!/usr/bin/python3 spam = ['apples', 'bannanas', 'tofus', 'cats'] length = len(spam) item = 0 while item < length - 1: print(spam[item], end=' ') item = item + 1 print(' and ' + spam[item])
python
from SOC.models import Manna import numpy as np import pytest def test_boundary_shape(): sim = Manna(L=10) assert sim.values.shape == (12, 12) assert sim.L_with_boundary == 12 def test_run_abel(): sim = Manna(L=20) sim.run(5) def test_run_nonabel(): sim = Manna(L=20, abelian = False) sim....
python
# Copyright 2020 PerfKitBenchmarker 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 appli...
python
# Code adapted from https://github.com/araffin/learning-to-drive-in-5-minutes/ # Author: Sheelabhadra Dey import argparse import os import time from collections import OrderedDict from pprint import pprint import numpy as np import yaml from stable_baselines.common import set_global_seeds from stable_baselines.common....
python
# -*- coding: utf-8 -*- # MegEngine is Licensed under the Apache License, Version 2.0 (the "License") # # Copyright (c) 2014-2021 Megvii Inc. All rights reserved. # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTI...
python
from glue.config import DictRegistry __all__ = ['viewer_registry', 'ViewerRegistry'] class ViewerRegistry(DictRegistry): """ Registry containing references to custom viewers. """ def __call__(self, name=None): def decorator(cls): self.add(name, cls) return cls ...
python
# -*- coding: utf-8 -*- ''' Code List Object =============== ''' from __future__ import annotations __all__ = ('CodeList',) from typing import Tuple from builder.commands.scode import SCode from builder.datatypes.builderexception import BuilderError from builder.utils import assertion from builder.utils.logger impo...
python
# import logging from xml.etree import ElementTree as ET import lxml.etree as LET from ckeditor.fields import RichTextField from acdh_tei_pyutils.tei import TeiReader from curator.models import Upload # Create your models here. from django.db import models from django.utils.timezone import now from .namespaces import ...
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings import django_fsm.db.fields.fsmfield class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] ope...
python
from pycket.interpreter import ( App, Begin, Begin0, BeginForSyntax, CaseLambda, Cell, CellRef, DefineValues, If, Lambda, Let, Letrec, LexicalVar, Module, ModuleVar, LinkletVar, Quote, QuoteSyntax, Require, SetBang, ToplevelVar, Va...
python
# -*- coding: UTF-8 -*- """ @CreateDate: 2021/07/25 @Author: Xingyan Liu @File: builder.py @Project: stagewiseNN """ import os import sys from pathlib import Path from typing import Sequence, Mapping, Optional, Union, Callable import logging import pandas as pd import numpy as np from scipy import sparse import scanpy ...
python
# A import performance test of standard classes, dataclasses, attrs, and cluegen import sys import time standard_template = ''' class C{n}: def __init__(self, a, b, c, d, e): self.a = a self.b = b self.c = c self.d = d self.e = e def __repr__(self): return f'C{...
python
from __future__ import print_function from __future__ import division from collections import defaultdict, OrderedDict from itertools import izip import numbers from time import time import itertools import math import scipy.sparse as sparse import sklearn from sklearn.base import BaseEstimator from sklearn.ensemble i...
python
# -*- encoding: utf-8 -*- text = u""" Mr. Speaker, Mr. President, distinguished Members of the Congress, honored guests, and fellow citizens: I come before you to report on the state of our Union, and I'm pleased to report that after 4 years of united effort, the American people have brought forth a nation renewed, s...
python
# # PySNMP MIB module HUAWEI-SEP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-SEP-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:36:43 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2...
python
import unittest import unittest.mock import denonavr.__main__ as avr class TestDenonAVR(unittest.TestCase): def test_valid_input_source(self): self.assertTrue(avr._is_valid_input_source("DVD")) self.assertTrue(avr._is_valid_input_source("BD")) self.assertTrue(avr._is_valid_input_source("G...
python
from ...hek.defs.obje import * def get(): return obje_def # replace the model animations dependency with an open sauce one obje_attrs = dict(obje_attrs) obje_attrs[8] = dependency('animation_graph', valid_model_animations_yelo) obje_body = Struct('tagdata', obje_attrs ) obje_def = TagDef("o...
python
class Coordenadas(): def __init__(self, coordenadaX , coordenadaY): self.coordenadaX = coordenadaX self.coordenadaY = coordenadaY def valores(self): print("Los valores ingresados fueron:","(" , self.coordenadaX,",", self.coordenadaY ,")") def cuadrante(self): if...
python
import sys import unittest import os script_dir = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(1, os.path.abspath( os.path.join(script_dir, os.path.join('..', '..')))) import pake class SubpakeTest(unittest.TestCase): def file_helper_test_stub(self, ctx, silent): fp = pake.FileHelp...
python
import sys import re def main(): file = sys.stdin if file.isatty(): filename = input('Input file name: ') file = open(filename) rules = file.readlines() file.close() bags = parseRules(rules) shinyGoldBag = bags['shiny gold'] shinyGoldContainers = shinyGoldBag.findCont...
python
import copy import logging import os import typing import yaml from nbcollection.ci.constants import ENCODING, SCANNER_ARTIFACT_DEST_DIR from nbcollection.ci.generate_ci_environment.constants import NBCOLLECTION_BUILDER, CONFIG_TEMPLATE, JOB_TEMPLATE, \ PULL_REQUEST_TEMPLATE, NBCOLLECTION_WORKFLOW_NAME, PUBLIS...
python
""" protonate.py: Wrapper method for the reduce program: protonate (i.e., add hydrogens) a pdb using reduce and save to an output file. Pablo Gainza - LPDI STI EPFL 2019 Released under an Apache License 2.0 """ from subprocess import Popen, PIPE import os from ipdb import set_trace def protonate(in_...
python
import collections import logging from arekit.common.data.input.providers.opinions import OpinionProvider logger = logging.getLogger(__name__) class BaseRowProvider(object): """ Base provider for rows that suppose to be filled into BaseRowsStorage. """ # region protected methods def _provide_rows(...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from distutils.core import setup readme = open('README.rst').read() history = open('HISTORY.rst').read().replace('.. :changelog:', '') requirements = [ 'pan-python', ] test_requirements = [ 'pan-pyt...
python
class Activation(object): def __init__(self): pass from deepend.activations.Softmax import Softmax from deepend.activations.LeakyReLU import LeakyReLU from deepend.activations.Linear import Linear from deepend.activations.TanH import TanH from deepend.activations.Sigmoid import Sigmoid from deepend.activations.ReLU...
python
"""Exemplo melhorias de Contraste.""" from PIL import Image, ImageEnhance im = Image.open('beijo.jpg') contrast = ImageEnhance.Contrast(im) contrast.enhance(1.2) contrast.show()
python