content
stringlengths
5
1.05M
"""helpers.py: tests global scratch space""" # TODO: move root/paths to pytest official global spaces from os import path import prosper.common.prosper_config as p_config HERE = path.abspath(path.dirname(__file__)) ROOT = path.dirname(HERE) APP_CONFIG = p_config.ProsperConfig(path.join(ROOT, '{{cookiecutter.library_...
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) import os import re from spack import * from spack.package_test import compare_output_file, compile_c_and_execute class...
# -*- coding: utf-8 -*- import sys import os import re import logging import numpy from pandas import DataFrame from pylie.methods.sybyl import AA_SYBYL_TYPES if sys.version_info[0] < 3: from StringIO import StringIO import urlparse import urllib2 as urllib else: from io import StringIO from url...
from setuptools import setup setup( name = 'bplist', packages = ['bplist'], version = '1.0', description = 'Apple binary Property List reader/writer for Python', install_requires=[], author = 'Vladimir Pouzanov', author_email = 'farcaller@gmail.com', url = 'https://github.com/farcaller/bplist-python'...
import os import ctypes import shutil import time, datetime def WriteFile(filename,content): with open(filename,'a', encoding = "UTF-8") as fw: fw.write(str(content)+'\n') def countfiles(): path = r"C:\Users\Students\Desktop\批量转换" ls = os.listdir(path) count = 0 ...
from __future__ import print_function from lime import lime_image, lime_text, lime_tabular from aix360.algorithms.lbbe import LocalBBExplainer class LimeTextExplainer(LocalBBExplainer): """ This class wraps the source class `LimeTextExplainer <https://lime-ml.readthedocs.io/en/latest/lime.html#module-lime.li...
import processing layer = iface.activeLayer() classes = {} features = processing.features(layer) for f in features: attrs = f.attributes() class_value = f['class'] if class_value in classes: classes[class_value] += 1 else: classes[class_value] = 1 print classes
from flask import Blueprint, request, session, jsonify from Utils import Config, MongoConn, JSONUtils, PostgreConn from bson import ObjectId from Wrapper import AuthWrapper from datetime import datetime bp = Blueprint('api_dbtable', __name__, url_prefix='/api/dbtable') #create table @bp.route('/', methods=['POST']) @...
# Copyright (c) 2021 The Regents of the University of California # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: redistributions of source code must retain the above copyright # notice, this lis...
import os, sys, inspect, unittest, scalg currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) sys.path.insert(0, parentdir) DATA = [ [2016, 21999, 62000, 181], [2013, 21540, 89000, 223], [2015, 18900, 100000, 223], [2013, 2420...
#!/usr/bin/python number = list(range(1, 21)) n = 1 for i in range(1, 20): n = n * number[i] for j in range(i): if number[i] % number[j] == 0: n = n / number[j] number[i] = number[i] / number[j] print(n)
import unittest import torch import torch.nn as nn from utils import getModel, getModelWithOptimized from msdnet.dataloader import get_dataloaders_alt from data.ImagenetDataset import get_zipped_dataloaders import os from data.utils import getClassToIndexMapping class TestInferencing(unittest.TestCase): TEST_DAT...
# %% Imports # General stuff import numpy as np import pandas as pd import matplotlib.pyplot as plt from numpy.fft import fft, ifft import os import pathlib # Audio processing/tools import import librosa import librosa.display from scipy.io.wavfile import read from IPython.display import Audio #REMEMBER you need ffm...
import json import itertools import numpy as np import sys from data_utils import DataUtils, MyExceptions from display_colour_image import DisplayColourImage def solve(input_array, out_array=None, graphics=False): assert type(input_array) == np.ndarray column_index = np.nonzero(input_array[0, 0:])[0] row_i...
import subprocess from pathlib import Path from datajob import logger class DatajobPackageWheelError(Exception): """any exception occuring when constructing wheel in data job context.""" def create(project_root): """launch a subprocess to built a wheel. todo - use the setuptools/disttools api to creat...
''' Created on 30 Jan 2019 @author: simon ''' import click, os, grp, pwd, getpass, shutil from os import path from k2 import app_installer @click.group() def k2(): pass @k2.command() @click.option('--base', help='Identify the location of the k2 base directory. If not set defaults to the current directory') @c...
import json import requests class Cards(object): __module__ = 'trello' def __init__(self, apikey, token=None): self._apikey = apikey self._token = token def get(self, card_id_or_shortlink, actions=None, actions_limit=None, action_fields=None, attachments=None, attachment_fields=...
import json import multiprocessing from multivolumecopy.resolvers import resolver import multivolumecopy.copyfile class JobFileResolver(resolver.Resolver): """ Read copyfile src/dst from a JSON jobfile. Example: Sample ``mvcopy-jobdata.json`` .. code-block:: json [ ...
from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By class BasePage(): """Base class to initialize the base page that will be called from pages""" def __init__(self, ...
# Adapted from OpenUserBot for Uniborg """Download & Upload Images on Telegram\n Syntax: `.img <number> <Name>` or `.img <number> (replied message)` \n Upgraded and Google Image Error Fixed by @kirito6969 """ from userbot.utils.google_images_download import googleimagesdownload import os import shutil from re import ...
import mongoengine class User(mongoengine.Document): username: mongoengine.EmailField() # password: mongoengine.ReferenceField
#!/usr/bin/env python3 from bs4 import BeautifulSoup import requests import ftfy import glob import argparse import os import jsonlines from tqdm import tqdm from datetime import datetime def main(args): # Create the new file. Overwrite if it exits f = open(args.output_file, "w+") f.close() n = 0 ...
import os import h5py import sys import skimage.io import numpy as np import tensorflow as tf from keras.backend import clear_session import urllib.request from app import app from flask import Flask, request, redirect, jsonify, send_from_directory from flask_restful import Api, Resource from werkzeug.utils import secu...
#!/usr/bin/python3 """ Initializes the filestore """ from models.engine.file_storage import FileStorage storage = FileStorage() storage.reload()
""" Reporters of twistedchecker. """
from pykeyboard import PyKeyboard import time import pyperclip def fileManager(photopath): pyperclip.copy(photopath) k = PyKeyboard() time.sleep(1) k.press_key(k.control_key) #autoit.win_active("Open") #open can change by your os language if not open change that k.tap_key("l") k.release_key(k....
import datetime from django.contrib import admin from django.core.exceptions import ObjectDoesNotExist from django.db.models import Max from . import models, forms from address.biz import geocode from utils import common from utils.django_base import BaseAdmin # Register your models here. class ParkingPositionInlin...
import time import urllib.request import concurrent.futures url_list = [ "https://www.baidu.com", "https://www.qq.com", "https://www.sogou.com", "https://www.cnblogs.com" ] def get_html(url, timeout=10): with urllib.request.urlopen(url, timeout=timeout) as conn: return conn.read() def main(): ...
import os opta_combined_file = 'opta_combined_ds.csv' wyscout_dataset = 'soccerlogs_ds.csv' data_folder_path = os.path.join('gender_analysis', 'data')
from pysnow.api_handlers.api_handler import APIHandler class AnalysisHandler(APIHandler): def __init__(self, requestor): super().__init__(requestor)
import numpy as np from matplotlib import pyplot def dft_2d(im: np.ndarray): f = np.zeros_like(im, dtype=np.complex128) m, n = im.shape c = -2j * np.pi g = np.zeros_like(im, dtype=np.float64) for u in range(m): for v in range(n): for x in range(m): for y in rang...
"""Tests `oasis test`.""" import os.path as osp from subprocess import PIPE # pylint: disable=relative-beyond-top-level from .conftest import SAMPLE_KEY def test_invoke_npm(oenv, mock_tool): mock_tool.create_at(osp.join(oenv.bin_dir, 'npm')) proj_dir = oenv.create_project() oenv.run('rm yarn.lock', cwd=...
#!/usr/bin/env python import commands import json import requests COMMAND_OUTPUT = commands.getoutput('yarn application -list') IS_RUNNING = False for line in COMMAND_OUTPUT.splitlines(): fields = line.split('\t') if len(fields) >= 6: app = fields[1].strip() state = fields[5].strip() ...
XXX XXXXXXX XXXXXX XXXXXXX XXXXXXX XX XXXX XXXX XXXXXXXXX XXX XXXXX XXXX XXXX XXXXXXXX XXXXXXXXXXX XXXX XXX XXXX XXXX XXXXXXXXXX XX XXXXXX XXX XXXXXXXX XX XXXXXXXXX XX XXXX XXX XXXXXXXXXX XXXXXXXX XXXXXX XX XXXX XXXXXXX XXXXXXXXX XXX XXXXXXXX XX XX XXX XXXXXXXX XXXXX...
from hamcrest import * from mc.string import String def test_string_should_strip_prefix(): assert_that(String("abc").strip_prefix("a"), equal_to("bc")) assert_that(String("abc").strip_prefix("abc"), equal_to("")) assert_that(String("abc").strip_prefix(""), equal_to("abc")) def test_string_should_throw_o...
import pandas as pd # used for making csv files from selenium import webdriver # used for getting the web driver (the chrome window) from selenium.webdriver.support.ui import Select # we will be using a dropdown from selenium.webdriver.chrome.options import Options # dropdown from queue import Queue # multi threading f...
import binascii import logging.handlers import mimetypes import os import base58 import requests import urllib import json import textwrap import random from twisted.web import server from twisted.internet import defer, threads, error, reactor from twisted.internet.task import LoopingCall from twisted.python.failure i...
import datetime import matplotlib.pyplot as plt import matplotlib.dates as mdates import matplotlib.ticker as ticker from matplotlib.dates import MO, TU, WE, TH, FR, SA, SU dates = ['3/25/2020', '3/26/2020', '3/27/2020', '3/28/2020', '3/29/2020', '3/30/2020', '3/31/2020', '4/1/2020', '4/2/2020', '4/3/2020', '4/4/2020'...
from functools import partial import numpy as np import torch import torch.nn as nn from src.utils import args, get_shape from src.modules import * # ----- NN Model Seleciton ----- if args.model == 'VAE': if args.network == 'densenet32': from .image_networks.densenet32 import * else: raise...
import warnings from .sparse_lut import SparseLUT from typing import Any
#!/usr/bin/env python from redis import Redis import os import tqdm redis = Redis.from_url( "redis://" + os.environ.get("EXECUTOR_CONSTR", "127.0.0.1:6379/0") ) from job_registry import base import sys current_resultfile = sys.argv[1] # read current resultfile with open(current_resultfile) as fh: lines = fh...
from cluster_vcf_records import variant_tracking def run(options): with open(options.vcf_fofn) as f: vcf_files = [line.rstrip() for line in f] tracker = variant_tracking.VariantTracker(options.outdir, options.ref_fasta) tracker.merge_vcf_files( vcf_files, temp_dir=options.temp_dir,...
from pygame.locals import * from random import randint import pygame import time from operator import * class Player: x = [0] y = [0] size = 44 direction = 0 length = 3 MaxAllowedMove = 2 updateMove = 0 def __init__(self, length): self.length = length for i in range(0,...
from etherscan.contracts import Contract import json import pandas as pd with open('C:/Yiru Xiong-Professional/实习/CryptoAlgoWheel/S1/task3/api_key.json', mode='r') as key_file: key = json.loads(key_file.read())['key'] address = '0xfb6916095ca1df60bb79ce92ce3ea74c37c5d359' api = Contract(address=address, api...
################################################################################ # Author: Fanyang Cheng # Date: 27/03/2021 # Description: This file ask user to give a "letter phone number" and it will # convert it into a typical phone number. ############################################################################...
from tamr_unify_client.base_resource import BaseResource from tamr_unify_client.categorization.category.collection import CategoryCollection class Taxonomy(BaseResource): """A project's taxonomy""" @classmethod def from_json(cls, client, data, api_path): return super().from_data(client, data, api...
""" Converts various NB forms to other equivalents. In addtion, programs combining rules """ ## LJ Conversions def _LJ_ab_to_ab(coeffs): """ Convert AB representation to AB representation of the LJ potential """ return {'A': coeffs['A'], 'B': coeffs['B']} def _LJ_epsilonsigma_to_ab(coeffs): """ ...
# vim:ts=4:sw=4:et: # Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # no unicode literals import os import WatchmanTestCase @WatchmanTestCase.expand_matrix class TestSizeExpr(WatchmanT...
d,p,q=map(int,input().split()) p,q=max(p,q),min(p,q) prod=0 if d//p <= 1000000: ans=10**10 while True: qprod = 0 dremain = d - p*prod if dremain > 0: qprod = dremain // q if dremain % q > 0: qprod += 1 ans=min(ans, prod*p + qprod*q) ...
c.Exchange.course_id="meinkurs"
import bpy from bpy.types import WindowManager, AddonPreferences from bpy.props import StringProperty, EnumProperty try: import sverchok from sverchok.utils.sv_IO_panel_tools import import_tree SVERCHOK_AVAILABLE=True except ImportError: SVERCHOK_AVAILABLE=False from os.path import join, basename, dir...
import numpy as np import matplotlib.pyplot as plt import math ## Integrand function def f(x): return x**5+x**4 ## Integration interval a =-1.0 b = 1.0 ## Number of random number generations n = 10000 ## Standard MC implementation h=[] for k in range(1,1500): x=np.random.uniform(a,b,n) # [a,b]=[-1.0,1.0] eval...
import argparse from pathlib import Path def main(): parser = argparse.ArgumentParser( description='Unused Image Remover: Unused image removal tool for image annotation work') parser.add_argument('image_dir', help='Input the image directory. (e.g. ./images)') parser.add_argument('-d', '--delete', ...
from py_v_sdk.api import * from py_v_sdk.chain import * from py_v_sdk.account import * from py_v_sdk.tx_req import * from py_v_sdk.model import * from py_v_sdk.contract import * from py_v_sdk.contract.nft_ctrt import * from py_v_sdk.contract.atomic_swap_ctrt import * import py_v_sdk.log
import numpy as np import tensorflow as tf from collections import OrderedDict, defaultdict from itertools import chain, combinations from libspn.graph.scope import Scope from libspn.graph.node import OpNode, Input from libspn.inference.type import InferenceType from libspn import utils from libspn import conf from lib...
"""empty message Revision ID: 12f833559028 Revises: e7607c2bc445 Create Date: 2017-10-13 18:08:41.824664 """ from alembic import op import sqlalchemy as sa import sqlalchemy_utils # revision identifiers, used by Alembic. revision = "12f833559028" down_revision = "e7607c2bc445" branch_labels = None depends_on = None...
from pyeasyga import pyeasyga from . import sga, cga, charts def mono_binary(function, goal_function, size, popsz, noe, maximise=True): # Define data data = [0] * size # # Save the fitness of each execution results_sga = [] hmdatas_sga = [] # Execute the sGA `noe` times (noe: number of executions) for ...
from flask import current_app, request from flask.ext.restful import Resource from flask.ext.discoverer import advertise from flask.ext.cache import Cache from SIMBAD import get_simbad_data from SIMBAD import do_position_query from SIMBAD import parse_position_string from utils import get_objects_from_query_string impo...
from .. import base class Metadata(base.Resource): NAME_ATTR = 'display_name' def __repr__(self): return "<Metadata>" class MetadataManager(base.Manager): resource_class = Metadata def get(self, server_id,key): url = "/servers/%s/metadata/%s" % (server_id,key) return self._...
import numpy as np from ..field import CartesianGrid, UnstructuredCoords from .generic import make_obstructed_circular_aperture, make_spider def make_vlt_aperture(): pass def make_subaru_aperture(): pass def make_lbt_aperture(): pass def make_magellan_aperture(normalized=False): '''Make the Magellan aperture. ...
from tgalice.testing.testing_utils import make_context from dm import StretchDM def test_hello(): dm = StretchDM() resp = dm.respond(make_context(text='Привет', new_session=True)) assert '30' in resp.text
from pathlib import Path from sqlalchemy import desc import quetz from quetz.utils import add_temp_static_file from . import db_models from .api import get_db_manager, router from .repo_signer import RepoSigner @quetz.hookimpl def register_router(): return router @quetz.hookimpl def post_package_indexing(tem...
''' Copyright 2017, Fujitsu Network Communications, 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 w...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Understanding some of the things in the Scheuing & Yang 2008 paper. This is an *extremely* simplified situation where there is one direct path and one indirect path that is recorded by all microphones. Created on Mon Jul 5 10:48:01 2021 @author: thejasvi """ #%%...
import os import uvicorn from dotenv import load_dotenv from fastapi import Depends, FastAPI, Request from fastapi.responses import JSONResponse from fastapi.security import APIKeyHeader, HTTPBearer from fastapi_jwt_auth.exceptions import AuthJWTException from starlette.middleware.base import BaseHTTPMiddleware from s...
######################################################################################################################## # # # Header Replace Script ...
# https://stackoverflow.com/questions/8899905/count-number-of-occurrences-of-a-substring-in-a-string # https://www.geeksforgeeks.org/number-substrings-string/ def count_substring(string, sub_string): k=len(string) m=len(sub_string) i=0 l=0 count=0 while l<k: if string[l:l+m]==sub_strin...
# -*- coding: UTF-8 -*- from flask import Blueprint, session, request, redirect, url_for, flash, jsonify, make_response, g, get_flashed_messages from flask.templating import _default_template_ctx_processor from jinja2 import Environment, PackageLoader from flask_babel import lazy_gettext as gettext from fypress.us...
import math import os # import matplotlib.pyplot as plt import numpy as np import random import torch import torchvision import torchvision.transforms as transforms from torch import Tensor from torch.autograd import Function from torch.nn import init, Module, functional from torch.nn.parameter import Parameter, Unini...
from django.db import migrations def update_contenttypes_table(apps, schema_editor): content_type_model = apps.get_model('contenttypes', 'ContentType') content_type_model.objects.filter(app_label='git').update(app_label='dataset_repo') class Migration(migrations.Migration): dependencies = [ ('dat...
import sys between = map(int, sys.stdin.read().split('-')) def valid1(attempt): if attempt <= 99999 or attempt > 999999: return False consecutive = False attempt, last_d = divmod(attempt, 10) while attempt: attempt, d = divmod(attempt, 10) if d > last_d: return Fa...
def is_palindrome(string): return string.lower() == string[::-1].lower()
find("1416542452932.png") doubleClick("1416542464884.png") type("jenkins\tphoneme\n") wait(Pattern("1416543208055.png").similar(0.39)) find("1416775268385.png") doubleClick("1416775295161.png") find(Pattern("1416773490682.png").targetOffset(136,16)) click("1416775375191.png") doubleClick(Pattern("1416773344427.png").s...
import os from flask import Flask from app.database import db from tqdm.auto import tqdm import os from .recommendation_logic.text_processing import get_text_map import pandas as pd from .testclass import save_to_db from .database import redis_db def create_app(): BASE = os.path.dirname(os.path.abspath(__file_...
#!/usr/bin/env python2 from pwn import * import sys context.log_level = 'error' MSG = """Agent, Greetings. My situation report is as follows: My agent identifying code is: . Down with the Soviets, 006 """ IV_LEN = 16 HASH_LEN = 20 def encrypt(socket,payload1,payload2): socket.recvuntil("Send & verify (S)") socke...
from bs4 import BeautifulSoup from bs4.element import Tag import nltk.tokenize import requests import re from typing import List, Optional import urllib.parse from .models import MovieData, MovieResult from .util import is_subslice def compute_minutes(runtime: str) -> Optional[int]: m = re.match(r"(?:(\d+)h )?(\...
class LocationCoordinates: def __init__( self, lat, lon ): self._lat = lat self._lon = lon @property def lat(self): if self._lat is not None: return float(self._lat) else: return None @property def lon...
import numpy as np import functools import itertools size = (80, 40) seed_of_creation = np.array([np.random.rand(size[0]) for x in np.arange(size[0])]) all_true = np.array([[True for x in np.arange(size[1])] for y in np.arange(size[1])]) bool_of_seed = seed_of_creation > 0.4 # iterations = [] def move_all_left(arra...
from more_collections import tuples import pytest def test_float_tuple1(): assert tuples.typedtuple(float)(.0) == (.0,) def test_float_tuple1_invalid_arity(): with pytest.raises(ValueError): assert tuples.typedtuple(float)(.0, 0.) def test_float_tuple1_invalid_type(): with pytest.raises(Value...
from rlpyt.agents.dqn.r2d1_agent import R2d1Agent, R2d1AlternatingAgent from rlpyt.models.dqn.atari_r2d1_model import AtariR2d1Model from rlpyt.agents.dqn.mixin import Mixin class AtariR2d1Agent(Mixin, R2d1Agent): def __init__(self, ModelCls=AtariR2d1Model, **kwargs): super().__init__(ModelCls=ModelCls, ...
from dart.client.python.dart_client import Dart from dart.model.dataset import Column, DatasetData, Dataset, DataFormat, FileFormat, DataType, Compression, RowFormat, \ LoadType if __name__ == '__main__': dart = Dart('localhost', 5000) assert isinstance(dart, Dart) dataset = dart.save_dataset(Dataset(...
"""renamed latency table header Revision ID: a69472dd044e Revises: 8c0c0ed1d004 Create Date: 2019-03-08 18:27:44.327115 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'a69472dd044e' down_revision = '8c0c0ed1d004' branch_labels = None depends_on = None def up...
#!/usr/bin/env python3 """The script decompiles the given file via RetDec IDA plugin. The supported decompilation modes are: full - decompile entire input file. selective - decompile only the function selected by the given address. """ import argparse import os import shutil import signal import subprocess...
import sys import argparse import configparser import traceback from taky import __version__ from taky.config import load_config from taky import cli def arg_parse(): argp = argparse.ArgumentParser(description="Taky command line utility") argp.add_argument( "-c", action="store", dest=...
"""%tensorboard line magic that patches TensorBoard's implementation to make use of Jupyter TensorBoard server extension providing built-in proxying. Use: %load_ext tensorboard %tensorboard --logdir /logs """ import argparse import uuid from IPython.display import HTML, display def _tensorboard_magic(line):...
#!/usr/bin/env python3.4 # import sys import time import RPi.GPIO as GPIO sys.path.append('../../lib') from ACNode import ACNode class LED(GPIOOut): pin=23 def led(self,onOff): self.gpioout(onOff) if __name__ == "__main__": acnode = LED() acnode.parseArguments() acnode.setup() acnode.forever = True...
expected_output = { 'index': { 1: { 'inside_global': '135.0.0.1', 'inside_local': '35.0.0.1', 'outside_global': '---', 'outside_local': '---', 'protocol': '---' } } }
import click import requests import json @click.group() def ah(): """ Simple CLI for consuming Authors Haven API """ pass @ah.command() @click.option('--limit', default=10, type=str, help='Limit how many articles are displayed') @click.option('--search', type=str, help='E...
from bitcoinlib.keys import Address import binascii from typing import List, Optional, Union from bitcoinlib.transactions import Transaction from xchainpy_client.models import tx_types from .models.common import DerivePath, UTXO, Witness_UTXO from . import sochain_api from xchainpy_util.asset import Asset, AssetLTC fr...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import re import sys import textwrap import six import pytest from _pytest.monkeypatch import MonkeyPatch @pytest.fixture def mp(): cwd = os.getcwd() sys_path = list(sys.path) yield Mo...
import csv from io import StringIO def parse_line(value, quotechar=None, **kwargs): """ A simple wrapper to parse a single CSV value """ quotechar = quotechar or '"' return next(csv.reader([value], quotechar=quotechar, **kwargs), None) def line_to_string(value, **kwargs): """ A simple wr...
from ._session import SessionCommandFactory
""" Main script for data processing and final dataset generation @date Oct 16, 2020 @author Inova Ixtepô """ from create_final_base import create_final_base, create_list_of_cnpj def main(): create_list_of_cnpj(number_cnpjs=250000, max_filiais=100) create_final_base() if __name__ == '__main__': main()
import os BASE_PATH = os.path.dirname(os.path.abspath(__file__)) TRAINED_PATH = os.path.join(BASE_PATH, "output/trained_model") EXPS_PATH = os.path.join(BASE_PATH, "output/experiments") DATA_DIR = os.path.join(BASE_PATH, 'datasets') EMB_DIR = os.path.join(BASE_PATH, 'embeddings') PAD = 0
import logging import time from google.cloud import logging_v2 from cloud_fn_utilities.gcp.cloud_env import CloudEnv from cloud_fn_utilities.gcp.vpc_manager import VpcManager from cloud_fn_utilities.gcp.datastore_manager import DataStoreManager from cloud_fn_utilities.gcp.firewall_rule_manager import FirewallManager ...
from squall import Router, Squall from squall.testclient import TestClient router = Router() sub_router = Router(prefix="/items") app = Squall() @sub_router.get("/") def read_item(): return {"id": "foo"} router.include_router(sub_router) app.include_router(router) openapi_schema = { "openapi": "3.0.2"...
from django import forms from allauth.account.forms import LoginForm class SocialNetworkLoginForm(LoginForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['password'].widget = forms.PasswordInput()
class MyList(list): def __getitem__(self, index): if index == 0: raise IndexError if index > 0: index -= 1 return list.__getitem__(self, index) def __setitem__(self, index, value): if index == 0: raise IndexError if index > 0: ...
from django.test import TestCase from django.contrib.auth.models import User from django.test import Client from truco.models import * from truco.constants import * def carta_es_valida(carta): palos_validos = [ESPADA,BASTO,ORO,COPA] valores_validos = [1,2,3,4,5,6,7,10,11,12] return carta.palo in palos_vali...
import urlparse from .base import * DEBUG = os.getenv("DEBUG", "FALSE") == "TRUE" TEMPLATE_DEBUG = DEBUG SHOW_DEBUG_TOOLBAR = False urlparse.uses_netloc.append("mysql") url = urlparse.urlparse(DATABASE_URL) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': url.path[1:], ...