content
stringlengths
5
1.05M
# Cloudera Airflow Provider # (C) Cloudera, Inc. 2021-2021 # All rights reserved. # Applicable Open Source License: Apache License Version 2.0 # # NOTE: Cloudera open source products are modular software products # made up of hundreds of individual components, each of which was # individually copyrighted. Each ...
from datatypes_timex_expression import Time def test_datatypes_time_constructor(): time = Time(23, 45, 32) assert time.hour is 23 assert time.minute is 45 assert time.second is 32 def test_datatypes_time_gettime(): time = Time(23, 45, 32) assert time.get_time() == 85532000
import os f = open(os.path.join(os.path.dirname(__file__), '../input/12/part1.txt'), 'r') def main(): programs = [] line = f.readline().rstrip() while line: parts = line.split(' <-> ') pipes = [ int(pipeString) for pipeString in parts[1].split(', ') ] programs.append(pipes) ...
from matplotlib_views import utils def two_dimensional_hex( ax, xvalues, yvalues, density=25, mincount=2, colormap="PuRd", bins="log" ): """ Wrapper for MPL hexbin func with sane defaults """ # Settings lineswidth = 0.0 # white lines lineswidth = 0.2 # perfect fit li...
from duckietown_utils.system_cmd_imp import system_cmd_result from comptests import comptest, run_module_tests from what_the_duck.check import Check, CheckFailed, CheckError from what_the_duck.entry import Diagnosis from what_the_duck.list_of_checks import Manager from what_the_duck.sanity_checks import run_checks fro...
# ws2def.py # Copyright (c) 2012 Maxim Kolosov AF_UNSPEC = 0 AF_UNIX = 1 AF_INET = 2 AF_IMPLINK = 3 AF_PUP = 4 AF_CHAOS = 5 AF_NS = 6 AF_IPX = AF_NS AF_ISO = 7 AF_OSI = AF_ISO AF_ECMA = 8 AF_DATAKIT = 9 AF_CCITT = 10 AF_SNA = 11 AF_DECnet = 12 AF_DLI = 13 AF_LAT = 14 AF_HYLINK = 15 AF_APPLETALK = 16 AF_NETBIOS = 17 AF...
from django.urls import include from django.urls import path from .views import HomeView urlpatterns = [ path('accounts/', include('django.contrib.auth.urls')), path('', HomeView.as_view(), name='home'), ]
"""tables.py contains modules for implementing view tables for different models.""" import django_tables2 as tables from django_tables2 import A from nautobot.utilities.tables import BaseTable, ToggleColumn, ButtonsColumn from nautobot_version_control.models import ( Branch, Conflicts, Commit, PullReq...
# Generated by Django 2.2.24 on 2022-05-09 23:06 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('events', '0016_auto_20220509_2146'), ] operations = [ migrations.CreateModel( name='Proposal',...
import asyncio import sys import pytest collect_ignore = [] if sys.version_info[:2] < (3, 6): collect_ignore.append("async_fixtures/test_async_gen_fixtures_36.py") collect_ignore.append("async_fixtures/test_nested_36.py") @pytest.yield_fixture() def dependent_fixture(event_loop): """A fixture dependent ...
"""This module defines `shapely` object based geometry """ from typing import Union, Any from pyproj import CRS from shapely.geometry import Polygon, MultiPolygon from ocsmesh.geom.base import BaseGeom class ShapelyGeom(BaseGeom): """Base class for geoms based on shapely objects""" class PolygonGeom(ShapelyG...
# -*- test-case-name: epsilon.test.test_process -*- # Copyright (c) 2008 Divmod. See LICENSE for details. """ Process and stdio related functionality. """ import os, sys, imp from zope.interface import implements from twisted.internet import reactor from twisted.application.service import IService, Service from tw...
from uuid import uuid4 DEBUG = True TEMPLATE_DEBUG = DEBUG INSTALLED_APPS = [ 'django.contrib.contenttypes', 'celery_rpc.runtests', 'celery_rpc.tests' ] DATABASE_ENGINE = 'django.db.backends.sqlite3', DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:...
# (C) Copyright 2005-2021 Enthought, Inc., Austin, TX # All rights reserved. # # This software is provided without warranty under the terms of the BSD # license included in LICENSE.txt and may be redistributed only under # the conditions described in the aforementioned license. The license # is also available online at...
from __future__ import annotations import functools import re from pathlib import Path from typing import TYPE_CHECKING, Callable, List, Optional, TypeVar import nox if TYPE_CHECKING: from typing_extensions import Concatenate, ParamSpec P = ParamSpec("P") T = TypeVar("T") NoxSessionFunc = Callable[...
# -*- coding: utf-8 -*- """ Characters ~~~~~ :copyright: (c) 2014 by Halfmoon Labs :license: MIT, see LICENSE for more details. """ __version__ = '0.1.0' from .charset import change_charset, charset_to_int, int_to_charset from .hex import hex_to_int, int_to_hex, is_hex
import appyter.ext.multiprocessing import os import uuid import logging import pytest from appyter.ext.pytest import assert_eq from appyter.ext.asyncio.event_loop import with_event_loop @pytest.fixture(scope="session", autouse=True) def event_loop_fixture(): with with_event_loop(): yield FSSPEC_URI = os.enviro...
""" Modified version of imagenet torchvision dataset source code to allow customised token for automatic download. """ from __future__ import print_function import os import shutil import tempfile import torch from torchvision.datasets import ImageFolder from torchvision.datasets.utils import check_integrity, downlo...
from app import app, db from app.models import Article, Category @app.shell_context_processor def make_shell_context(): return {'db': db, 'Article': Article, 'Category': Category}
from bioinformatics import bioinformatics #Importing required libraries import os, subprocess, glob, ntpath, zipfile, gzip, tarfile from flask import Flask, render_template, request, redirect, jsonify from werkzeug.datastructures import FileStorage from subprocess import call #Libraries for downloading # import wget ...
#!/usr/bin/env python # # -*- coding: iso-8859-15 -*- # # Copyright 2003-2015 CORE Security Technologies # # 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/L...
import unittest from flask_monitoringdashboard.test.utils import set_test_environment, clear_db, add_fake_data, login, get_test_app class TestLogin(unittest.TestCase): def setUp(self): set_test_environment() clear_db() add_fake_data() self.app = get_test_app() def test_login...
from pybib import formatters from hamcrest import * mock_entry = { 'deposited': { 'date-parts': [[2015, 1, 1]], 'timestamp': 1000 }, 'subject': ['General'], 'DOI': 'test.doi.010101', 'reference-count': 0, 'URL': 'http://dx.doi.org/test.doi.010101', 'title': ['Test'], 'score': 0.0, 'issu...
#!/usr/bin/env python3 ages = { 'Keith': 30, 'Levi': 25, 'John': 20, } del ages['Keith'] print(ages) values = ['Kevin Bacon', 60, '555-555-5555', False] val = not values[-1] print(val) ages = { 'Keith': 30, 'Levi': 25, 'John': 20, } output = [str(value) for value in ages.values()] print(outpu...
# -*- encoding: utf-8 -*- # # This IDA script decrypts the strings inside *unpacked* samples of the # Win32/TorrentLocker crypto-ransomware. # For details about TorrentLocker, see: # http://www.welivesecurity.com/2016/09/01/torrentlocker-crypto-ransomware-still-active-using-tactics/ # # For feedback or questions contac...
#!/usr/bin/env python3 from citing import getBibTeX import random import string from sed_input import read_ascii, read_cleaned, magToJy, JyToLamFlam import argparse import sys, os import numpy as np from pathlib import Path description = \ """ description: Read in photometric data and output it in a LaTeX-rea...
from __future__ import print_function from paraview.simple import * from paraview import smtesting smtesting.ProcessCommandLineArguments() def RegressionTest(imageName, baselineName): from paraview.vtk.vtkTestingRendering import vtkTesting testing = vtkTesting() testing.AddArgument("-T") testing.AddArg...
#!/usr/bin/env python """ This example demonstrates how to create a project and configure media and metadata type definitions. """ import logging import sys import tator logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) logger = logging.getLogger(__name__) if __name__ == '__main__': ...
import os import subprocess from typing import Union from app.service.file_operator import FileOperator from config import Config class ScoreGenerator: """ Provide interface to access lilypond functionality """ def __init__(self, lilypond_path): self._lilypond_path = lilypond_path @stat...
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-07 18:44 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('courses', '0015_auto_20170207_1844'), ] operations = [ migrations.RenameField( ...
from django.contrib import admin from .models import Company, CareerContact, CareerRole # Register your models here. models = [ CareerRole, Company, CareerContact ] for model in models: admin.site.register(model)
import json import pymysql def GetReviewsByID(business_id): conn = pymysql.Connect(host='localhost', user='root', passwd='',charset='utf8', db='yelpdb') cursor = conn.cursor() cursor.execute( "SELECT stars, date FROM review WHERE business_id = %s", business_id ) conn.commit() result = cursor.fetc...
from query import Query from protector.influxdb.keyword import Keyword class DropQuery(Query): """ Construct new InfluxDB drop statement object """ def __init__(self, series_stmt): super(DropQuery, self).__init__() self.set_type(Keyword.DROP) self.series_stmt = series_stmt ...
from typing import List from pydantic import BaseModel # pylint: disable=E0611 from . import subschema class HelmValues(BaseModel): """ Schema for Helm values. """ dagit: subschema.Dagit userDeployments: subschema.UserDeployments postgresql: subschema.PostgreSQL rabbitmq: subschema.Rab...
#!/usr/bin/env python3 # Script to facilitate executing Prow utilities that require information about # a pull request. Sets the following variables based on its arguments: # # - BASE_REF # - BASE_SHA # - PULL_NUMBER # - PULL_SHA # - PULL_AUTHOR # # and can be used for a single execution: # # $ ./pj_env.py openshift/r...
from argparse import ArgumentParser from pathlib import Path import numpy as np import os def format_runs(runs, data_dir, shape, modes, run_type, mode='spatial'): out = r'#!/bin/bash' + '\nset -x' + '\n\n' out += f'data_dir={data_dir}\n' out += ("if [ $# -gt 0 ]; then\n" " ranks=$1\n" ...
from intermol.decorators import * import re class Constraint(object): @accepts_compatible_units(None, None, None, None, None, None, None, None, None, units.nanometers, units.nanometers, units.nanometers, units.nanometers, units.nanometers, units.nanometers, units.nanometers, units.nanomete...
"""chat 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-based...
import logging import redis from rq import Worker, Queue, Connection import os from timeouts import JobTimeoutException listen = ['high'] redis_url = str(os.environ.get("REDISTOGO_URL", None)) conn = redis.from_url(redis_url) # catch the JobTimeoutException def timeout_handler(job, exc_type, exc_value, traceback):...
""" Bearer Python bindings """ from typing import Optional, Union, Dict from logging import DEBUG, INFO from textwrap import dedent from requests.adapters import HTTPAdapter from requests.packages.urllib3.util.retry import Retry import warnings import requests import pkg_resources import logging from .auth_details ...
import requests from datetime import datetime import re from bs4 import BeautifulSoup from bs4.element import Tag from time import sleep import json class KvartirantScraper: """Get data on flats available for rent from https://r.onliner.by/ak/ according to the desired settings""" def __init__(self): s...
""" @author johannpistorius """ from load_json import JSON import sys def error_message(): sys.exit("Could not match ingredient to list. Please try again.") class Ingredient: def __init__(self, item): self.ingredient = item self.data = JSON() self.out = {} def get_ingredients_l...
### # Copyright (c) 2016, Santiago Gil # Copyright (c) 2020, oddluck <oddluck@riseup.net> # # This program 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 # ...
""" Profile ../profile-datasets-py/standard101lev_nogas_ppmvdry/001.py file automaticaly created by prof_gen.py script """ self["ID"] = "../profile-datasets-py/standard101lev_nogas_ppmvdry/001.py" self["Q"] = numpy.array([ 1.41160900e+00, 2.63139700e+00, 3.88323100e+00, 4.84522000e+00, 5.5...
"""Create an application instance.""" from server import create_app app = create_app()
# -*- coding:utf-8 -*- from os.path import join from os.path import split from bs4 import BeautifulSoup from jinja2 import Environment from jinja2 import PackageLoader from plate.common import is_absolute def local_url_for(endpoint, **values): dir_path, file_path = split(values['filename']) dir_path = dir...
from main.models import SiteInfo def site_name(request): obj = SiteInfo.objects.order_by().values('title','portfolio_url').last() if obj: return obj return {}
import pytest from lumicks.pylake.fitting.profile_likelihood import clamp_step, StepConfig, do_step import numpy as np @pytest.mark.parametrize("origin,step,lb,ub,result", [ # Positive quadrant (np.array([1, 1]), np.array([-2, -4]), np.array([0, 0]), np.array([2, 2]), np.array([0.5, 0.0])), (np.array([1, ...
""" CLI for tibanna awsf3 package """ # -*- coding: utf-8 -*- import argparse import inspect from tibanna._version import __version__ # for now use the same version as tibanna from . import utils PACKAGE_NAME = 'awsf3' class Subcommands(object): def __init__(self): pass @property def descrip...
from sys import path path.append('/home/joerojas/Desarrollo/Curso-Basico-Python/102_misPaquetes/packages') import extra.iota print(extra.iota.FunI())
curr_threads, created_threads, updated_threads = 0,0,0 curr_comments, created_comments, updated_comments = 0,0,0 curr_users, created_users, updated_users = 0,0,0
""" Master path Pattern List for the application. Most of the patterns here should be top-level pass-offs to sub-modules, who will have their own paths.py defining actions within. """ # pylint: disable=E1120 from django.contrib import admin from django.conf import settings from django.urls import path, inclu...
import os from match_pattern import Pattern # with glob assert Pattern("*ab").test("this is a long text that ends with ab") is True # with regex assert Pattern("re::^.*ab$").test("this is a long text that ends with ab") is True # multiple glob (or) assert Pattern("*ab|*kd").test("this is a long text that ends with k...
from base64 import urlsafe_b64decode, urlsafe_b64encode import requests from django.conf import settings from jose import jwt import logging try: from urllib import urlencode except ImportError: from urllib.parse import urlencode logger = logging.getLogger("auth0_auth") DOMAIN = getattr(settings, "AUTH0_D...
import requests from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django.urls import resolve from urllib.parse import urlparse from django.urls import reverse from json.decoder import JSONDecodeError from . import utils import json from frontend.forms import OrderCreat...
import mysql.connector from colorama import Fore, Style from PyInquirer import prompt, print_json import os from pyfiglet import Figlet from tabulate import tabulate def clear(): if os.name == 'nt': _ = os.system('cls') else: _ = os.system('clear') clear() f = Figlet(font='slant', width=100)...
#!/usr/bin/python # # Test pymol API # UCD @2010 import __main__ __main__.pymol_argv = [ 'pymol', '-qc'] # Quiet and no GUI import sys, time, os import pickle import pymol import pymol.cmd as cmd from pymol import stored pymol.finish_launching() pdbfile = os.path.abspath(sys.argv[1]) ghostsfile = os.path.abspath(sys...
import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() NAME = "mdserve" VERSION = "1.4.6" requirements = [ n.strip() for n in read('requirements.txt').split('\n') if n.strip() ] setup( name=NAME, version=VERSION, ...
from functools import total_ordering @total_ordering class Number: def __init__(self, value): self.value = value def __lt__(self, other): return self.value < other.value def __eq__(self, other): return self.value == other.value print(Number(1) < Number(2)) print(Number(10) > Nu...
from fabric.api import * import yaml def load_conf(filename): return yaml.load(open(filename).read()) def start(filename="config.yml"): local("../cache-server --port 6381 --daemonize yes") for name, instance in load_conf(filename).items(): if "proxy" in name: local("../cache-proxy -d -...
from ....tools.conversion import r_function from ....tools.decorators import method from ....tools.utils import check_version import numpy as np import pandas as pd _rctd = r_function("rctd.R") @method( method_name="RCTD", paper_name="Robust decomposition of cell type mixtures in spatial transcriptomics", ...
from testish.lib import forms import unittest import webob import urllib from BeautifulSoup import BeautifulSoup class Test(unittest.TestCase): def request(self, d): r = webob.Request.blank('http://localhost/') r.method = 'POST' r.content_type = 'application/x-www-form-urlencoded' ...
from ...Generator import PYTHON_TYPE, TAB, TAB2, TAB3, TAB4, TAB5, TAB6, TAB7 from ...Generator.read_fct import is_list_pyleecan_type, is_dict_pyleecan_type def generate_str(gen_dict, class_dict): """Generate the code for the __str__ method of the class Parameters ---------- gen_dict : dict D...
# -*- coding: utf-8 -*- """Test of performance. """ import os import time import pytest import shutil import filecmp import lxml.etree as ET from emparser.preprocess import Lexer # from emparser.mainprocess import Parser from emparser import Parser from emparser.postprocess import CSTHandler from empar...
# -*- coding: utf-8 -*- # MIT License # # Copyright (c) 2020 PANGAEA (https://www.pangaea.de/) # # 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 limitat...
from __future__ import absolute_import # # arcctl controllers for all installations # # arcctl deploy from .ThirdPartyDeployment import ThirdPartyControl # arcctl test-ca from .TestCA import TestCAControl CTL_COMPONENTS = [ ThirdPartyControl, TestCAControl ] # # arcctl controllers for ARC services # # arcc...
#!/usr/bin/env python ''' mbed SDK Copyright (c) 2011-2015 ARM Limited 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 ...
#!/usr/bin/python # coding=utf-8 # Copyright Matus Chochlik. # Distributed under the Boost Software License, Version 1.0. # See accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt # # usage: blender -b myfile.blend -P bake_to_vertex.py [-- [--help|options...]] import os import sys impo...
import os from all.logging import DummyWriter from all.experiments import SingleEnvExperiment, ParallelEnvExperiment, MultiagentEnvExperiment from all.presets import ParallelPreset, Preset class TestSingleEnvExperiment(SingleEnvExperiment): def _make_writer(self, logdir, agent_name, env_name, write_loss, writer):...
from app.helper import create_directory from app.multiheadcamera import MultiHeadCamera from time import sleep def test_multi_head(): output_directory = create_directory('/app/data/test', False) multi_head_camera = MultiHeadCamera(video_sources=['csi://0', 'csi://1'], o...
import unittest import subprocess import time from datetime import datetime, timedelta import volttron.platform.messaging.topics from volttron.platform.agent import utils, matching from volttron.platform.agent import PublishMixin, BaseAgent from volttron.tests import base """ Test """ AGENT_DIR = "Agents/ActuatorA...
""" Author: Hemanth Kumar Veeranki Handle:harry7 """ #!/usr/bin/python p="31415926535897932384626433833" for _ in xrange(input()): lis=raw_input().split() s="" for j in lis: s+=str(len(j)) pf=p[:len(s)] if(pf==s): print "It's a pi song." else: print "It's not a pi song."
# coding=utf-8 # -------------------------------------------------------------------------- # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from ...
# -*- coding: utf-8 -*- # pylint: disable= import os import logging import time import uuid from datetime import datetime from random import randint import kafka from kafka import KafkaProducer from kafka.admin import KafkaAdminClient, NewTopic if __name__ == "__main__": # change logging config logging.bas...
#!/usr/bin/python from lxml import etree import requests class GrokScraper: __slots__ = ['url', 'domain', 'proj', 'path', 'nresults', 'errors', 'getRevisionText'] def __init__(self, **kwargs): #different grok versions might place the revision data in a different part of the DOM relative to the li...
# -*- coding: utf-8 -*- import subprocess from AppKit import NSPasteboard, NSArray #! 地址在传递参数中均使用base64编码 防止出错 from base64 import b64decode import alfred alfred.setDefaultEncodingUTF8() import yyets # 拷贝到剪切板 def copyToClipboard(): try: word = b64decode(alfred.argv(2)) pb = NSPasteboard.generalP...
import os import gpustat import time class Experiments(object): def __init__(self): self.atlasnet = { 1: "python train.py --shapenet13 --dir_name log/atlasnet_autoencoder_1_sphere --nb_primitives 1 --template_type SPHERE", 2: "python train.py --shapenet13 --dir_name log/atlasnet_a...
import random import torch import numpy as np from gym_env import make_env from meta.meta_agent import MetaAgent from meta.peer import Peer from misc.rl_utils import collect_trajectory from misc.utils import log_performance from tensorboardX import SummaryWriter torch.set_num_threads(1) def meta_train(shared_meta_ag...
import os import pytest from django.core import management from creator.organizations.factories import OrganizationFactory, Organization from creator.studies.factories import StudyFactory from creator.data_templates.management.commands.faketemplates import ( TEMPLATES_PATH, create_templates_from_workbook ) d...
#Params Param = { 'LAT_NRO' : 0.62729799791922308, 'lens_offset_x' : [0, 0.0, 12.99, 12.99, 0.0, -12.99, -12.99, 0.0, 12.99, 25.98, 25.98, 25.98, 12.99, 0.0, -12.99, -25.98, -25.98, -25.98, -12.99, 0.0, 12.99, 25.98, 38.97, 38.97, 38.97, 38.97, 25.98, 12.99, 0.0, -12.99, -25.98, -3...
"""GitHub Type tests""" from django.test import TestCase from authentik.sources.oauth.models import OAuthSource from authentik.sources.oauth.types.github import GitHubOAuth2Callback # https://developer.github.com/v3/users/#get-the-authenticated-user GITHUB_USER = { "login": "octocat", "id": 1, "node_id": ...
from rest_framework import viewsets, mixins from rest_framework.decorators import detail_route from django.contrib.auth.models import Group from rest_framework.response import Response from rest_framework.filters import DjangoFilterBackend from rest_framework.serializers import ValidationError import datetime from lim...
import abaverify as av class ParametricTests(av.TestCase): """ Simple example of parametric tests """ # Specify meta class __metaclass__ = av.ParametricMetaClass # Refers to the template input file name baseName = "test_CPS4R_parametric" # Range of parameters to test; multiple can b...
from django import template from django.conf import settings from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.contrib.contenttypes.models import ContentType from comment.models import Comment from comment.forms import CommentForm register = template.Library() @register.simple_tag...
import bpy # Translation functions _ = bpy.app.translations.pgettext iface_ = bpy.app.translations.pgettext_iface tip_ = bpy.app.translations.pgettext_tip data_ = bpy.app.translations.pgettext_data def __format_with_translation_function(func): # create a new format function using the specified function f...
import os from tarfile import BLOCKSIZE import cv2 as cv import numpy as np import matplotlib.pylab as plt class VOStereo: TILE_WIDTH = 50 TILE_HEIGHT = 50 FLOW = 10 feature_params = dict(maxCorners = 100, qualityLevel = 0.3, minDistance = 7...
from __future__ import print_function import os import sys import base64 import hashlib import json import threading import time from collections import defaultdict from multiprocessing.pool import ThreadPool import boto3 current_path = os.path.dirname(os.path.realpath(__file__)) sys.path.append(os.path.join(curren...
import datetime import logging from dateutil.parser import parse from redash.query_runner import * from redash.utils import JSONEncoder, json_dumps, json_loads, parse_human_time import json logger = logging.getLogger(__name__) try: import requests import httplib2 except ImportError as e: logger.error("Fa...
""" 61 - Faça um programa que calcule o maior número palíndromo a partir do produto de dois números de 3 dígitos. Exemplo o maior palíndromo feito a partir do produto de dois dígitos é 9009 = 91 * 99 """ maiorNumero = int(input('Digite o primeiro número com dois dígitos: ')) menorNumero = int(input('Digite o segundo nú...
# -*- coding: utf-8 -*- """ Created on Sat May 23 18:43:17 2020 @author: Reuben This example for Tutorial 2 illustrates how to handle discontinuities. """ import numpy as np from scipy.integrate import odeint import matplotlib.pyplot as plt import npsolve from npsolve.soft_functions import negdiff, below G = -9.8...
""" This example show how to read and apply a simple filter to the output.csv from SEVN using pandas. The output files are store in ../sevn_outputs_example/sevn_output_single """ import pandas as pd #pandas is already shipped with python anaconda, otherwise install it with pip install pandas """1- Load the output c...
# TODO: Move security information separately from flask import Flask, Blueprint from flask_sqlalchemy import SQLAlchemy from classes import * from flask import render_template, redirect, request, url_for, jsonify from schedule import create_schedule2 from flask_restplus import Resource, Api # CONFIGURATION app = Flask...
""" import sys sys.path.append(r'C:\Users\paz\Documents\git\prmaya\test\plugins') import test_prVectorMath reload(test_prVectorMath) test_prVectorMath.SETTINGS['plugin_path'] = r'C:\Users\paz\Documents\git\prmaya\prmaya\plugins\prVectorMath.py' test_prVectorMath.SETTINGS['file'] = r'C:\Users\paz\Documents\git\prmaya\t...
import six CRLF = '\r\n' NL = CRLF if six.PY2: from .py2 import HTTPGenerator # noqa else: from email.generator import Generator from email._policybase import Compat32 class BatchPolicy(Compat32): linesep = CRLF class HTTPGenerator(Generator, object): def __init__(self, *args,...
import scipy from glob import glob import numpy as np import os max_text_len = 7 CHAR_VECTOR = "abcdefghijklmnopqrstuvwxyz0123456789_" letters = [letter for letter in CHAR_VECTOR] num_classes = len(letters) class DataLoader(): def __init__(self, dataset_name, img_res=(128, 128),): self.dataset_name = da...
import random import Board import Role from RandomPlayer import RandomPlayer class HeuristicPlayer: def heuristic_play(self, board, role): """ 1 Do Not Lose 2 Win """ # Closing opponenet's winning moves winning_moves = board.get_winning_cells_for(Role.get_op...
import logging from unittest import TestCase from foxylib.tools.compare.minimax_tool import MinimaxTool from foxylib.tools.log.foxylib_logger import FoxylibLogger class TestMinimaxTool(TestCase): @classmethod def setUpClass(cls): FoxylibLogger.attach_stderr2loggers(logging.DEBUG) def test_01(sel...
# -*- coding: utf-8 -*- # @Author:FelixFu # @Date: 2021.12.17 # @GitHub:https://github.com/felixfu520 # @Copy From: from dotmap import DotMap from loguru import logger from core.tools import register_modules from core.modules.register import Registers def Export(config=None, custom_modules=None): exp = DotMap(...
import os from os.path import join import matplotlib.pyplot as plt import seaborn as sns def savefig(fpath, dpi=100, close=True): plt.savefig(fpath, bbox_inches='tight', dpi=dpi) if close: plt.close() def maybe_save(name, save_dir=None, dpi=100, close=True): if save_dir is not None: os....
import asyncio import firebase_admin from firebase_admin import credentials, messaging from datetime import datetime from odmantic import AIOEngine from app.common import MIN_PRICE, MAX_PRICE, MIN_AREA, MAX_AREA, MIN_YEAR, MAX_YEAR from app.models import Apartment, Subscription # FCM cred = credentials.Certificate("/...