content
stringlengths
5
1.05M
#! python3 """ MIT License Copyright (c) 2020 Walter Wlodarski 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, m...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2017-2022 Rafael S. Guimaraes, Univertity of Bristol # High Performance Networks Group # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # Yo...
from flake8_commas import CommaChecker import os from unittest import TestCase class TestChecks(TestCase): def test_get_noqa_lines(self): checker = CommaChecker(None, filename=get_absolute_path('data/no_qa.py')) self.assertEqual(checker.get_noqa_lines(checker.get_file_contents()), [2]) class Com...
from django.contrib import admin from django.forms import ModelForm from django.forms import TextInput from django.db import models from .models import Crop class CropModelForm(ModelForm): class Meta: model = Crop exclude = ['update_time'] class CropAdmin(admin.ModelAdmin): form = CropModelF...
import pygraphviz as pgv print("blue = question") print("black = answer") G = pgv.AGraph(directed = True) G.add_node("Does a solution exist?", color='blue') G.add_node("Human intervention", color='black') G.add_edge("Does a solution exist?", "Human intervention", color="red", label='n') G.add_node("Can the planner fi...
from django.db import models from api import models as api_models class CoordinatesModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) lat = models.DecimalField(max_digits=10, decimal_places=8) lon = models.DecimalField(max_digits=...
"""Module for Algorand smart contracts integration testing.""" import base64 import pytest from algosdk import constants from algosdk.encoding import encode_address, is_valid_address from algosdk.error import AlgodHTTPError, TemplateInputError from contracts import ( BANK_ACCOUNT_FEE, create_bank_transaction...
import sys from collections import namedtuple from tests.mocks import ui import pytest # mock pythonista ui package sys.modules['ui'] = ui from Three_Column_Sortable_TableView import MyTableView testdata_background_color = [ "lightgrey", "white", ] testdata_name = [ "Name", "Size", "Date", ] ...
"""Methods and classes related to executing Z-Wave commands and publishing these to hass.""" import logging from typing import Dict, Set, Union import voluptuous as vol from zwave_js_server.model.node import Node as ZwaveNode from zwave_js_server.util.node import async_set_config_parameter from homeassistant.const i...
''' Based on https://github.com/tecdatalab/legacy/blob/master/core/em/mrc.h MRC files are a standard format for electron density maps. The first 1024 bytes represent the header followed by the actual densities. 56 4-byte words compose the standard fields followed by custom text labels that can be ad...
import tensorflow as tf import math as math import helpers.helpers as helpers class FeatureColumnsNZFusion: def __init__(self, dataset_options): self.dataset_options = dataset_options; return; def buildModelColumns(self): """Builds a set of wide and deep feature columns.""" #...
import numpy as np def solve(data): # Parse input N = len(data) tests = np.zeros((N, 10), dtype=set) raw_out = np.zeros((N, 4), dtype=set) dec_out = np.zeros_like(raw_out, dtype=int) for i in range(N): line = data[i].split(' | ') tests[i] = [set(x) for x in line[0].split()...
class PriorityElm: def __init__(self, data, priority) -> None: self.data = data self.priority = priority class PriorityHeap: def __init__(self, arr) -> None: self.arr = arr self.heap_size = len(self.arr) def left(self,idx): if idx == 0: return 1 ...
import base64 import json import requests from base import BaseTestCase from django.core.urlresolvers import reverse_lazy from testdata import create_temp_file from contentcuration import models from contentcuration import models as cc ### # Test helper functions ### def add_field_defaults_to_node(node): """ ...
# Extraindo dados de uma lista valores = [] while True: valores.append(int(input('Digite um valor: '))) resp = str(input('Quer continuar? S/N ')) if resp in 'Nn': break print('=-' * 30) print(f'Você digitou {len(valores)} elementos.') valores.sort(reverse=True) print(f'Os valores em ordem decresce...
#!/usr/bin/env python import rospy import traceback from locate_object_skill_class import LocateObjectSkill if __name__ == "__main__": rospy.init_node('locate_object_skill') try: actionName = rospy.get_param('~action_name') except Exception as e: raise KeyError('Unable to access ROS par...
# !/Library/Frameworks/Python.framework/Versions/3.7/bin/python3 # -*- coding:utf-8 -*- # @Author : Jiazhixiang # 在遇到页面交互复杂或是URL加密逻辑复杂的情况时,selenium就派上了用场,它可以真实地打开一个浏览器, # 等待所有数据都加载到Elements中之后,再把这个网页当做静态网页爬取就好了。 # 但是,使用selenium时,当然也有美中不足之处; # 由于要真实地运行本地浏览器,打开浏览器以及等待网渲染完成需要一些时间, # selenium的工作不可避免地牺牲了速度和更多资源,不过,至少不会比人慢。...
# coding: utf8 import sys sys.path.insert(0, '../../../lib/') import ic """ The Wall Street Journal describió dos programas de entrenamiento utilizados por IBM. Doce ejecutivos a quienes se les dio el primer tipo de entrenamiento obtuvieron un promedio de 73.5 en la prueba de competencia. Aunque el artículo de noticia...
""" Take a url, generate queries and calculate retreivability scores for the page. ============================= Author: rose : <Rosanne.English@glasgow.ac.uk> Date: 08/08/2013 Version: 0.1 requires nltk: pip install nltk """ from query_generation import SingleQueryGeneration from ifind.search.query import Query fr...
from django import forms from django import forms from wagtail.admin.forms import WagtailAdminModelForm import PIL import zipfile from datetime import datetime from django.core.files import File from django.conf import settings class AlbumForm(WagtailAdminModelForm): zip = forms.FileField(required=False, widget=...
version https://git-lfs.github.com/spec/v1 oid sha256:e2664c9c863b8c60f506d3e0100b2741070af8cf42eea9dc00fa001ec3cc0922 size 1659
import cv2 from .utils import img_to_tensor, tensor_to_img class OpenCVImagePreprocess: @staticmethod def encode(img, size=None, normalize=True, vrange=(0.0, 255.0), bgr2rgb=True): if size is not None: img = cv2.resize(img, size) tensor = img_to_tensor(img, normalize, vrange, bgr2r...
# -*- coding: utf-8 -*- # Copyright 2021 Tampere University and VTT Technical Research Centre of Finland # This software was developed as a part of the ProCemPlus project: https://www.senecc.fi/projects/procemplus # This source code is licensed under the MIT license. See LICENSE in the repository root directory. # Auth...
# https://binarysearch.com/problems/Invert-Tree class Solution: def solve(self, root): if root == None: return None else: left = self.solve(root.right) right = self.solve(root.left) root.left = left root.right = right return root
"""ask URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based vie...
# Copyright 2017 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 law or agreed to in writin...
class Task: def __init__(self, isStartTimeHard, startTime, endTime, exactDelayBetweenExecutions, priority, task, parameter): pass def schedule(priority, task, parameter): pass def scheduleExactStart(exactStartTime, maxEndTime, priority, task, parameter): pass def scheduleExactDelay(exactDelay, ma...
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest from Box2D import b2Color class testColor (unittest.TestCase): def checkAlmostEqual(self, v1, v2, msg, places=3): for i, (a, b) in enumerate(zip(v1, v2)): self.assertAlmostEqual(a, b, places=places, msg=...
"""Resource module for time_events resources.""" from datetime import datetime import json import logging import os from typing import List from aiohttp.web import ( HTTPBadRequest, HTTPNotFound, HTTPUnprocessableEntity, Response, View, ) from dotenv import load_dotenv from race_se...
import json import requests from copy import deepcopy class Resource(object): """ A base class for API resources """ # """List of allowed methods, allowed values are # ```['GET', 'PUT', 'POST', 'DELETE']``""" # ALLOWED_METHODS = [] def __init__(self, host, port, auth, scheme='http', time...
# coding:utf-8 from django.conf.urls import url, patterns from django.views.generic import TemplateView from views import * urlpatterns = patterns( "", url(r"^domain$", DomainView.as_view(), name="domain"), )
class TicTacToe: def __init__(self, n: int): """ Initialize your data structure here. """ self.p1 = set() self.p2 = set() self.n = n def _check_winner(self, player, row, col): # check the row for i in range(self.n): if (row, i) no...
import junky import numpy as np import os from sklearn.metrics import accuracy_score, f1_score, \ precision_score, recall_score import time import torch from tqdm import tqdm import sys class BaseConfig: def __init__(self, **kwargs): for k, v in kwargs.items(): ass...
# -*- encoding: utf-8 -*- """ Slim CMS - Generated by www.AppSeed.us in Flask AppSeed - developed by RoSoft | www.RoSoftware.ro Licence: MIT """ # Resources used class Assets: WEBSITE_NAME = 'Now UI Dashboard' WEBSITE_INFO = 'Designed by Creative-Tim.com - Coded by AppSeed.us' WEBSITE_KEYWORDS = ...
import logging import os import subprocess subprocess.check_call('pip install pymongo', shell=True) import pymongo log = logging.getLogger(__name__) log.setLevel(logging.DEBUG) def initiate_mongodb_replicaset(): mongo = pymongo.MongoClient( os.environ['MONGO_ADDRESS'], int(os.environ['MONGO_POR...
# Supports app creation from flask import Flask from flask_cors import CORS from flask_jwt_extended import JWTManager from flasgger import Swagger from app.middleware import ErrorHandler, Logger from app.docs import TEMPLATE from app.models import Mongo from app.views import ViewInjector cors = CORS() jwt = JWTManage...
# -*- coding: utf-8 -*- """ Created on Mon Jul 24 02:36:46 2017 @author: Keerthi """ import numpy as np # Need to do sorting later from collections import defaultdict db_ini = {} db_ini = [[0,30,90],[0,20,30],[1,35,10,20],[1,15,30],[1,20,40,60,70],[2,25,30,50,70],[3,20,30],[3,25,40,70],[3,30,90]...
# USAGE # python explore_dims.py --conf conf/cars.json # import the necessary packages from __future__ import print_function from utils import Conf from scipy import io import numpy as np import argparse import glob # construct the argument parser and parse the command line arguments ap = argparse.ArgumentParser() ap...
''' Universidade Federal de Pernambuco (UFPE) (http://www.ufpe.br) Centro de Informática (CIn) (http://www.cin.ufpe.br) Graduando em Sistemas de Informação IF969 - Algoritmos e Estrutura de Dados Autor: Igor Fernandes Carneiro (ifc) E-mail: ifc@cin.ufpe.br Data: 2018-09-22 Copyright(c) 2018 Igor Fernandes Carneiro ''...
# Copyright 2020 by He Peng (sdythp@gmail.com). # All rights reserved. # Licensed under the MIT License. # 将原始的SARShip图像划分为训练集和测试集,对训练集和测试集分别使用不同的参数进行切分 import os import argparse import logging from utils import parse_file_info, crop_image_list logger = logging.getLogger(__name__) class_list = ['ship'] def parser...
# Copyright (c) 2021 - present / Neuralmagic, 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 b...
# coding: utf-8 # In[13]: # %load test.py # In[ ]: from __future__ import print_function import traceback import sys from eccodes import * INPUT = '/home/dp/data/ECMF_DAM/PUB/W_NAFP_C_ECMF_20171108054547_P_C1D11080000110800001' VERBOSE = 1 # verbose error reporting missingValue = 1e+20 # A value out of ra...
import matplotlib.pyplot as plt import argparse import torch from pathlib import Path import typing from typing import TypeVar, Generic, Sequence, Dict, Tuple import pandas as pd import numpy as np import os from egg.zoo.imitation_learning.loader import load_all_interactions from egg.zoo.imitation_learning.st...
if (deficitOnTopLayers / 1000.0 <= 0): diffusionLimitedEvaporation = 8.3 * 1000 else: if (deficitOnTopLayers / 1000 < 25): diffusionLimitedEvaporation = (2 * soilDiffusionConstant * soilDiffusionConstant / (deficitOnTopLayers / 1000.0)) * 1000.0 else: dif...
import cv2 import xml.etree.ElementTree as ET from torchvision.datasets import VOCDetection as _Voc from typing import Optional, Callable, Tuple, Any class VOCDetection(_Voc): """VOC detection dataset that using cv2 backend """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs)...
# Copyright (C) 2011 Nippon Telegraph and Telephone 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 appli...
# coding=utf-8 import dask.array as da import numpy as np import scipy.sparse as sp from scipy.sparse import linalg as ln def calibration_single_ended_ols(ds, st_label, ast_label): cal_ref = ds.ufunc_per_section(label=st_label, ref_temp_broadcasted=True, ...
class Printer (object): """ Base class to print all information from the investigation to the output. All information is written to the default output file passed as parameter. """ def __init__ (self, outputFile, labelSpacing=20, columnTitle="bilayer"): """ Initializes the printer with useful information, ...
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- class MacroCommand: def __init__(self, commands): self.commands = list(commands) def __call__(self): for command in self.commands: command()
import numpy as np import os import pickle from PIL import Image import json from scipy.io import loadmat from libs.tools import get_world_R, normalize_point, yaw_pitch_roll_from_R, R_from_yaw_pitch_roll from utils.sunrgbd_config import SUNRGBD_CONFIG, SUNRGBD_DATA import pandas as pd import jellyfish as jf from copy i...
from .map import map from .private._curry2 import _curry2 from .private._dispatchable import _dispatchable from .private._isFunction import _isFunction from .private._makeFlat import _makeFlat from .private._xchain import _xchain def inner_chain(fn, monad): if _isFunction(monad): def wrapper(x): return fn...
from django.contrib import admin from models import Currency, ExchangeRate class CurrencyAdmin(admin.ModelAdmin): search_fields = ('code',) list_display = ('code', 'name') class ExchangeRateAdmin(admin.ModelAdmin): search_fields = ('source__code', 'target__code') list_display = ('source', 'target', ...
import struct from pyb import UART, millis, delay from mavlink import HEARTBEAT, GLOBAL_POSITION_INT, STATUSTEXT, ATTITUDE, AHRS2, AHRS3 class Message: payload_len = None seq_num = None sys_id = None comp_id = None message_id = None def __init__(self): self._buffer = None def cl...
'''This utility exists to convert the files that describe the courses in each department at MUN into a SQLite database so that information can be easily retrieved later. Note that two sets of courses such as "Engineering One" and "Engineering Work Terms" are treated as separate departments to make searching easier. Of ...
import vars from pyrogram import Client Bot = Client( vars.SESSION_NAME, bot_token=vars.BOT_TOKEN, api_id=int(vars.API_ID), api_hash=vars.API_HASH, plugins=dict(root="plugins") ) Bot.run()
n=int(input("please input your birthyear:")) y=int(input("this year is:")) count=0 for i in range(n,y+1): if i%400==0 or i%100!=0 and i%4==0: count=count+1 print("从你出生到今年共有{}个闰年".format(count))
class User: def log(self): print('logging') class Teacher(User): def log(self): print("I'm a teacher") class Customer(User): def __init__(self, name, membership_type): self.name = name self.membership_type = membership_type # print('customer created') @proper...
import copy import time import pandas as pd from paper_trading.event import Event from paper_trading.utility.event import * from paper_trading.utility.setting import SETTINGS from paper_trading.trade.db_model import ( query_position, query_orders, query_orders_today, query_account_record, query_po...
from setuptools import setup with open('README.md') as f: readme = f.read() setup( name='habu', version='0.0.71', description='Python Network Hacking Toolkit', long_description=readme, long_description_content_type='text/markdown', author='Fabian Martinez Portantier', author_email='fab...
from output.models.nist_data.atomic.date.schema_instance.nistschema_sv_iv_atomic_date_enumeration_5_xsd.nistschema_sv_iv_atomic_date_enumeration_5 import ( NistschemaSvIvAtomicDateEnumeration5, NistschemaSvIvAtomicDateEnumeration5Type, ) __all__ = [ "NistschemaSvIvAtomicDateEnumeration5", "NistschemaSv...
# ~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~ # MIT License # # Copyright (c) 2021 Nathan Juraj Michlo # # 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 Softwar...
""" The purpose of this code is to create the csv files with rmsd, mcss, and physcis score information the code also combines all of the info for each protein, target, start group into one csv file It can be run on sherlock using ml load chemistry ml load schrodinger $ $SCHRODINGER/run python3 get_csv.py all /oak/sta...
from django.shortcuts import render, redirect from django.views.generic import TemplateView from django.contrib.auth.models import Group # Create your views here. class BaseView(TemplateView): template_name = 'base.html'
import json import sys def splitIntoWords(sentence): return sentence.split() def getEDHSub(file): f = open(file) data = json.load(f) sub_goals = [] for i in data['history_subgoals']: sub_goals.append(i) for i in data['future_subgoals']: sub_goals.append(i) dialogue_history = [] for i in data['di...
# -*- coding: utf-8 -*- from uamobile import parser DOCOMO = ( ('DoCoMo/1.0/R692i/c10', { 'version': '1.0', 'model' : 'R692i', 'c' : 10, 'series' : '692i', 'html_version': '3.0', }), ('DoCoMo/1.0/P209is (Google CHTML Proxy/1.0)', { 'version': '1.0', 'mo...
from unittest import TestCase, mock import numpy as np import pandas as pd import xarray as xr from tethysapp.temp_precip_trends.api_helpers import (get_data, jsonify, overlap_ts, param_check, extract_time_series_at_location) class APIHelpersTests(TestCase): ...
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import unicode_literals <<<<<<< HEAD # import pandas as pd ======= >>>>>>> dev import simplejson as json from flask import Flask # pip install -U flask-cors from flask_cors import CORS from flask_restful import Resource, Api, reqparse <<<<<<< HEAD import sys rel...
import math def secant_method(x_i_1, x_i, i, func): iterator = 0 while True: f_i_1 = func(x_i_1) f_i = func(x_i) subs = x_i-x_i_1 x_next = x_i - (f_i*subs/(f_i-f_i_1)) print("x_{} = {}".format(iterator, round(x_next, 4))) if iterator == i: ...
from django.db import models from taggit.models import TagBase, ItemBase, GenericTaggedItemBase from taggit.managers import TaggableManager from treebeard.mp_tree import MP_Node class Site(models.Model): slug = models.SlugField(max_length=250, unique=True) url = models.CharField(max_length=2083) def __st...
import numpy as np import pandas as pd from collections import Counter def summary(df): """ input: The function takes in a data frame output: It counts total number of records and unique records present in each column """ print("Total number of records: ",len(df)) for i in df.columns: ...
__description__ = \ """ models.py Models subclassed from ITCModel used to model (and fit) ITC data. """ __author__ = "Michael J. Harms" __date__ = "2016-06-22" import inspect import numpy as np import scipy.optimize from .base import ITCModel from . import bp_ext class BindingPolynomial(ITCModel): """ Base ...
from collections import namedtuple from sfdo_template_helpers.admin.permissions import IsAPIUser User = namedtuple("User", ("is_superuser",)) Request = namedtuple("Request", ("user",)) def test_isapiuser_permission(): user1 = User(is_superuser=True) user2 = User(is_superuser=False) assert IsAPIUser().h...
import logging from threading import Condition from threading import Thread import cv2 import imutils import rospy import arc852.cli_args as cli from arc852.generic_image_source import GenericImageSource logger = logging.getLogger(__name__) class VideoImageSource(GenericImageSource): args = [cli.filename, cli...
import petl as etl from fhir_petl.util import resolve observations = (etl.io.csv.fromcsv(resolve('work/Observation.csv'))) patients = (etl.io.csv.fromcsv(resolve('work/Patient.csv'))) procedures = (etl.io.csv.fromcsv(resolve('work/Procedure.csv'))) conditions = (etl.io.csv.fromcsv(resolve('work/Condition.csv'))) reque...
from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('core', '0002_invoice_note'), ] operations = [ migrations.RemoveField( model_name='invoice', name='client', ), migrations.RemoveField( model_name=...
# Generated by Django 2.2.18 on 2021-03-18 03:10 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('faults', '0008_move_fault_type_to_fault_types'), ] operations = [ migrations.RemoveField( model_name='fault', name='fault_t...
import factory from factory import Faker, fuzzy from ao.msazure.factories.common import ResourceGroupFactory from ..models import storage as models __all__ = [ 'StorageAccountFactory', ] STORAGE_ACCOUNT_SKUS = [i for i, j in models.STORAGE_ACCOUNT_SKUS] STORAGE_ACCOUNT_KINDS = [i for i, j in models.STORAGE_ACCOUN...
# -*- encoding: utf-8 *-* from collections import OrderedDict from .node_serializable import Serializable from .utils import return_simple_id, dumpException from .node_graphics_edge import * from typing import TYPE_CHECKING, Optional, Type if TYPE_CHECKING: from .node_scene import Scene from .node_socket impo...
import numpy as np import tensorflow as tf from util.default_util import * from util.sequence_labeling_util import * from layer.basic import * __all__ = ["Highway", "ConvHighway", "StackedHighway", "StackedConvHighway"] class Highway(object): """highway layer""" def __init__(self, unit_dim,...
from django.db import models class Categoria(models.Model): nome = models.CharField(max_length=150, db_index=True) slug = models.SlugField(max_length=150, unique=True, db_index=True) data_criacao = models.DateTimeField(auto_now_add=True) data_ultima_alteracao = models.DateTimeField(auto_now=True) ...
from directory import Directory from courses import CourseCatalog
# # (c) Copyright 2016 Hewlett Packard Enterprise Development LP # (c) Copyright 2017-2018 SUSE LLC # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-...
# This file is part of MaixUI # Copyright (c) sipeed.com # # Licensed under the MIT license: # http://www.opensource.org/licenses/mit-license.php # import sys, time from fpioa_manager import fm from Maix import FPIOA, GPIO class button_io: home_button = None next_button = None back_button = None ...
from django.contrib.contenttypes.models import ContentType from django.db import models from django.urls import reverse from .conf import settings from .models import Like def name(obj): return f"{obj._meta.app_label}.{obj._meta.object_name}" def _allowed(model): if isinstance(model, models.Model): ...
#!/usr/bin/env python # coding: utf-8 # In[ ]: import PySimpleGUI as sg import requests import json import subprocess def gui2(): #Sets up Interface layout = [ [ sg.Multiline(size=(90,20),background_color='black',text_color='white',reroute_stdout=True,reroute_stderr=True,autoscroll = True)], ...
""" No citrix, no remembering passwords, no finding things to do, no stress, no... The Republican party is the enemy. Childish thought. """ _formats = { 'ymd': '{d.year}-{d.month}-{d.day}', 'mdy': '{d.month}/{d.day}/{d.year}', 'dmy': '{d.day}/{d.month}/{d.year}', } class Date: def __init__(self, ye...
import uuid from typing import NewType import attr from marshmallow import Schema, fields, post_load, post_dump from ebl.transliteration.domain.museum_number import MuseumNumber Base64 = NewType("Base64", str) @attr.s(auto_attribs=True, frozen=True) class CroppedSignImage: image_id: str image: Base64 ...
#!/usr/bin/env python # -*- coding: utf-8 -*- ########################################################### # WARNING: Generated code! # # ************************** # # Manual changes may get lost if file is generated again. # # Only code inside the [MANUAL] ta...
#Faça programa que leia um número inteiro e diga se ele é ou não um número primo. cont = 0 num = int(input('Digite um número e descubra se ele é um número primo: ')) for c in range(1, num+1): if num % c == 0: cont = cont+1 print('O {} escolhido foi divisível {} vezes'.format(num, cont)) if cont == 2: pr...
import os import json from twisted.trial import unittest from mock import patch, MagicMock # Patch crochet wait_for decorator patch('crochet.wait_for', lambda **x: lambda f : f).start() # Patch flask_login login_required decorator patch('flask_login.login_required', lambda x : x).start() from twisted.internet import...
""" {{ cookiecutter.name }} {{ cookiecutter.description }} """ __title__ = '{{ cookiecutter.package }}' __version__ = '{{ cookiecutter.version }}' __url__ = 'https://github.com/{{ cookiecutter.author_github_username }}/{{ cookiecutter.package }}' __author__ = '{{ cookiecutter.author_name }}' __author_email__ = '{{ co...
import os import numpy as np import scipy.sparse as sp import pickle import torch from torch.utils.data import DataLoader from dgl.data.utils import download, _get_dgl_url, get_download_dir, extract_archive import random import time import dgl from utils import shuffle_walks #np.random.seed(3141592653) def ReadTxtNet(...
from django.db import models from django.utils import timezone # Create your models here. class Article(models.Model): title = models.CharField(max_length=30) content = models.TextField() # created_time = models.DateTimeField(default = timezone.now) created_time = models.DateTimeField(auto_now_add=True...
from mongoengine import * from datetime import datetime from os import urandom class ServiceList(Document): name = StringField(required=True, unique=True) created_at = DateTimeField(required=True, default=datetime.utcnow) price = IntField(default=0, required=True) @queryset_manager def get_all_serv...
# --------------------------------------------------------------------------- # # Author: Ibrahim Odumas # All Rights Reserved # Open-source, free to copy # --------------------------------------------------------------------------- # import utils import os import pandas as pd import matplotlib.pyplot as plt import s...
# -*- coding: utf-8 -*- # © 2016 Lorenzo Battistini - Agile Business Group # © 2016 Csók Tibor - SZEFO Zrt. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from openerp import tools from openerp import models, fields class RaktarKeszletErtekel(models.Model): _name = 'raktar.keszlet_ertekel' _...
#This program will show first 1500 prime number. def prime(X): if X == 1: return 0 else: for i in range(2, X): if X % i == 0: return 0 break else: return 1 P = [] count = 0 i = 1 while True: Y = prime(i) if Y == 1: P...
# Generated by Django 2.1.7 on 2019-08-15 20:30 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('curate', '0048_presentation_supplementalmaterials_video'), ] operations = [ migrations.AddField( model_name='article', ...
# Instruction Class # by Kamyar Mirzavaziri # Contains a class called Instruction which stores all data of a single instruction and can return it in both assembly and machine language from tables import * from eval import evaluate #######################################################################################...
# coding: utf-8 # In[148]: import sys reload(sys) sys.setdefaultencoding('utf-8') import pandas as pd import numpy as np import datetime as dt from sqlalchemy import create_engine import os from os import path from wordcloud import WordCloud import matplotlib.pyplot as plt from calendar import monthrange ...