content
stringlengths
5
1.05M
import pytest from rpi_backlight import Backlight, _permission_denied from rpi_backlight.utils import FakeBacklightSysfs def test_permission_denied() -> None: with pytest.raises(PermissionError): _permission_denied() def test_get_value() -> None: with FakeBacklightSysfs() as backlight_sysfs: ...
__author__ = 'fmoscato' from datetime import datetime from collections import OrderedDict from itertools import groupby from operator import itemgetter import pymongo import constants as c # The Aggregation DAO handles interactions with the publication collection, # and aggregate the results. class Aggregation...
# Generated by Django 3.2.3 on 2021-05-22 08:45 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('auctions', '0006_auction_time'), ] operations = [ migrations.AlterField( model_name='auction', name='time', ...
import discord import modules.codenames.globals as global_values class Player(): team = -1 def __init__(self, user): self.user = user
# https://github.com/sbarratt/inception-score-pytorch # Revised by [elvisyjlin](https://github.com/elvisyjlin) import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.data as data from torch.autograd import Variable from torchvision.models.inception import inception_v3 import numpy as np...
""" Tests simple example. """ import os from silvera.lang.meta import get_metamodel from silvera.utils import get_root_path def test_example(): examples_path = os.path.join(get_root_path(), "tests", "examples") metamodel = get_metamodel() path = os.path.join(examples_path, "example.si") metamodel.mod...
# Preprocessing for CMIP6 models import warnings import cf_xarray.units import numpy as np import pandas as pd import pint import pint_xarray import xarray as xr from cmip6_preprocessing.utils import _maybe_make_list, cmip6_dataset_id # global object for units _desired_units = {"lev": "m"} _unit_overrides = {name: ...
# Write a function is_factor(f, n) that passes the tests below. import sys def is_factor(f, n): return n % f == 0 def test(did_pass): """ Print the result of a test. """ linenum = sys._getframe(1).f_lineno # Get the caller's line number. if did_pass: msg = "Test at line {0} ok.".format(l...
#!/usr/bin/env python from dockerpython.source import Source if __name__ == '__main__': print("hello world") asource = Source('env/env.sh') assert 'some env' in asource.atestenv
from sklearn import svm from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier import pandas as pd from sklearn.decomposition import PCA, FastICA def read_data(csv_file_path, is_PCA): dataset = pd.read_csv(csv_file_path) dataset.columns = ['edible', '...
print("Kinjal Raykarmakar\nSec: CSE2H\tRoll: 29\n") def s_list(l,size): return [l[i:i+size] for i in range(0, len(l), size)] lis=[1,3,4,7,9,8,6,2] size=int(input("Enter the size: ")) print(s_list(lis,size))
# encoding: utf-8 # 该文件,为无界面启动文件,以vtServer为容器,加载MainEngine # 配置: # self.gateway_name ,gateway 的连接名称,在vtEngine.initGateway()里面定义,对应的配置文件是 "连接名称_connect.json", # self.strategies:启动的策略实例,须在catStrategy/CtaSetting.json 里面定义 [u'S28_RB1001', u'S28_TFT', u'S28_HCRB',u'atr_rsi'] # vtServer的ZMQ端口: 从VT_Setting.json中配置,根据AU...
a = 14 ^ 15
import torch import torchvision.datasets as datasets import torchvision.transforms as transforms def make_imagenet_dataloader(train_batch_size, test_batch_size, image_size, **kwargs): assert(image_size == -1 or image_size == 224), 'Currently we only use default (224x224) for imagenet' num_classes = 1000 I...
# coding=utf-8 n, k = map(int, input().split()) s = [[]for _ in range(n)] for i in range(n): s[i] = input() f = [[1 for d in range(n)] for _ in range(n)] for i in range(n): for j in range(n): ssum = 0 for t in range(j, min(j+k, n)): if s[i][t] == '.': ssum += 1 ...
import numpy import qrtools import scipy.ndimage import os def qrpng2pcbpoly(qrpngfilename, x0=9600, y0=3200): im = scipy.ndimage.imread(qrpngfilename, flatten=True) ymax, xmax = im.shape y, x = numpy.where(im == 255) x0 = x0 - 450 y0 = y0 + 430 step = 14 polygons = [] for ix, xvalue in enumerate(x): x1 = x0...
from __future__ import absolute_import from .jaccard import batched_f_measure, batched_jaccard
import demistomock as demisto from CommonServerPython import * from typing import Optional, Tuple, Union from datetime import datetime, timedelta import json import requests import urllib3 import dateparser # Disable insecure warnings urllib3.disable_warnings() ALL_EVENTS = "All" ISSUES_EVENTS = "Issues" BLOCKED_CLI...
from setuptools import setup, find_packages setup( name='dfilter', version='0.1', description='filter and query tools for dictionaries', long_description=open('README.rst').read(), author='Martin Slabber', author_email='martin.slabber@gmail.com', license='MIT', packages=find_packages(e...
from __future__ import unicode_literals from django.db import models import datetime from django.utils import timezone # Create your models here. class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # pylint: disable=missing-docstring, import-error import functools import tick_pb as tick def _main(): t = tick.Tick(lambda elapsed_ms: print(f"elapsed: {elapsed_ms} ms"), 500, 1000, lambda: print("run beg"), lambda: print("run end")) ...
""" Module for finding an expression given a float Note that this is of course just guessing. """ import math def namednumber(num): """ attempt to find exact constant for float """ def isnear(val): return abs(num-val)<0.00001 if isnear(0.0): return "0" if num<0: sign = "-" num...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Text diff/match analyzer API. """ __license__ = """ GoLismero 2.0 - The web knife - Copyright (C) 2011-2014 Golismero project site: https://github.com/golismero Golismero project mail: contact@golismero-project.com This program is free software; you can redistribute...
# -*- coding: utf-8 -*- import sys from library.components.SensorFactory import SensorFactory as SensorFactory from library.components.JobModule import JobModule as Job from collections import defaultdict import time import json #add the project folder to pythpath sys.path.append('../../') class FileLogMetaData(Job...
from society import UKSociety, HighValencyTester from society.test import TestQueue import random class TwoTrackTester(UKSociety): CONTACT_VALENCY_THRESHOLD = 22 # vF PROPORTION_FAST_TRACK = 0.5 DAYS_TO_CONTACTS_SECOND_TEST = 3 MIN_CONTACTS_TEST = 0 def __init__(self, **kwargs): UKSoci...
from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class Car(models.Model): vin = models.CharField(verbose_name='Vin', db_index=True, unique=True, max_length=64) color = models.CharField(verbose_name='Color', max_length=64) brand = models.CharField(verbose...
from transformers import BertTokenizer,RobertaTokenizer, AutoTokenizer import json import torch import os import numpy as np from formatter.Basic import BasicFormatter import random class HierarchyFormatter(BasicFormatter): def __init__(self, config, mode, *args, **params): super().__init__(config, mode, ...
#!/usr/bin/python import datetime,redis,ConfigParser import xml.etree.ElementTree as ET import requests from walrus import * from requests.auth import HTTPBasicAuth import argparse db = redis.Redis('localhost') def ConfigSectionMap(section): dict1 = {} options = Config.options(section) for option in opt...
from distutils.core import setup, Extension import glob _DEBUG = True _DEBUG_LEVEL = 1 _UICAL_LOG_LEVEL = 5 extra_compile_args = ["-std=c++11", "-Wall", "-Wextra", "-Wno-missing-field-initializers"] if _DEBUG: extra_compile_args += ["-g3", "-O0", "-DDEBUG=%s" % _DEBUG_LEVEL, "-UNDEBUG", "-DUICAL_LOG_LEVEL=%s" %...
import logging from logging.handlers import TimedRotatingFileHandler logFormatter = logging.Formatter("%(asctime)s - %(levelname)s :\t%(message)s") timedHandler = TimedRotatingFileHandler(filename="./logs/stardust.log", when="m", interval=10, backupCount=0) timedHandler.setFormatter(logFormatter) stardustLogger = logg...
""" Copyright 2019 Goldman Sachs. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software di...
# The API requires specific book codes, so I have to be able to translate all of them. key -> value is the best for this. def books_dict(): return dict([("GENESIS", "GEN"), ("EXODUS", "EXO"), ("LEVITICUS", "LEV"), ("NUMBERS", "NUM"), ("DEUTERONOMY"...
"""Minify HTML A quick hack at the moment. """ import sys import argparse from parser import parseHTML, ParseException def doMin(fileName): body = parseHTML(fileName) sys.stdout.write(body.toStr({'discardComments':True, 'deploy':True})) if __name__ == "__main__": cmdParser = argparse.ArgumentParser(des...
from shutil import copyfile import numpy as np from navec import Navec path = 'ru/navec_hudlit_v1_12B_500K_300d_100q.tar' navec = Navec.load(path) words = [] embeddings = [] for word, id in navec.vocab.word_ids.items(): if word == '<unk>': word = '*UNK*' words.append(word) embeddings.append(navec...
"""This example is a loose HyperparameterHunter adaptation of the SKLearn example on the "Effect of transforming the targets in regression models" (https://scikit-learn.org/stable/auto_examples/compose/plot_transformed_target.html#real-world-data-set). Specifically, we'll be looking at the section using the Boston Hous...
from importlib.abc import Loader, MetaPathFinder from importlib.util import spec_from_loader from io import BytesIO import os import random import sys import webbrowser import fabulous.image import fabulous.utils import requests from dotenv import load_dotenv load_dotenv() EDAMAM_ENDPOINT = "https://api.edamam.com/s...
import math import torch import torch.nn as nn from torch.nn.parameter import Parameter class Scale(nn.Module): def __init__(self, init_value=1e-3): super(Scale, self).__init__() self.scale = Parameter(torch.FloatTensor([init_value])) def forward(self, x): return x * self.scale clas...
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from gaiatest import GaiaTestCase from gaiatest.apps.homescreen.app import Homescreen class TestRocketBarAddCollection...
import base64 import io import os import urllib.error import urllib.parse import urllib.request import uuid import PIL from PIL import Image from flask import current_app from flask import current_app as app from sqlalchemy.orm.exc import NoResultFound from xhtml2pdf import pisa from app import get_settings from app....
from categories.base import CategoryBaseAdminForm from categories.models import Category class CategoryAdminForm(CategoryBaseAdminForm): class Meta: model = Category def clean_alternate_title(self): if self.instance is None or not self.cleaned_data["alternate_title"]: return self....
# Copyright 2019 Google 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-2.0 # # Unless required by applicable law or agreed to in writing, ...
from abc import ABC, ABCMeta, abstractmethod class Véhicule(ABC): def demarrer(self): pass class Voiture(Véhicule): def demarrer(self): print("C'est une voiture") pass class Moto(Véhicule): def demarrer(self): print("C'est une moto eeeeh ouais bg ca se demarre au cick") ...
import numpy as np import random import sys import mnist # This is just to get the training data working class Net: # Simple neural network for classification problems def __init__(self,nodes,initialisation=random.random): # Initialisation is the function which is used to intialise the weights and biases self.n...
# Copyright (c) 2013, Helio de Jesus and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe, erpnext from frappe import _ from frappe.utils import flt from frappe.model.meta import get_field_precision from frappe.utils.xlsxutils import handle_html from ...
from django.db.models import CharField, DateTimeField, JSONField, Model, TextField class FailedMessage(Model): created = DateTimeField(auto_now_add=True) topic_name = CharField(max_length=255) subscription_name = CharField(max_length=255) subject = CharField(max_length=255) message = JSONField() ...
n = int(input()) a = 0 b = 1 # while a != n: # a, b = b, a + b print(f"{0} {0} {n}")
#!/usr/local/bin/python # # WSPR receiver. # # switches among bands if weakcat.py understands the radio. # reports to wsprnet if mycall/mygrid defined in weak.ini. # # Robert Morris, AB1HL # import wspr import sys import os import time import weakaudio import numpy import threading import re import random import copy...
import tensorflow as tf import tensorflow.keras.applications as keras_applications import efficientnet.tfkeras as efficientnet from tensorflow.keras import layers as keras_layers from tensorflow.keras import backend as K from glrec.train import utils as train_utils from glrec.train.constants import constants as train_...
import shlex import subprocess from game_control.game import Game class ExecutableGame(Game): """Implementation of abstract base class to control an executable game.""" def __init__(self, executable_filepath, **kwargs): """Constructs and starts an executable game. Args: executab...
import comprehender import ItemSearch import deserializer as ds TEST_TEXT=""" People have known since ancient times that aspirin helps to reduce pain and high body temperature. But that is not all aspirin can do. It has gained important new uses in recent years. Small amounts of the drug may help prevent a heart atta...
#!/usr/bin/env python3 import numpy as np def run_round(board, stuck=False): size = board.shape[1] new_board = np.zeros(board.shape, dtype=bool) for r in range(size): for c in range(size): n_on = np.count_nonzero(board[max(0, r - 1):min(r + 2, size), max(0, c - 1):min(c + 2, size)]) ...
import os import sys import csv import numpy as np import scipy.io import scipy.misc as spm import cv2 from scipy import ndimage import tensorflow as tf from tensorflow.python.framework import ops def showImg(img): cv2.imshow("test", img) cv2.waitKey(-1) def dense_to_one_hot(labels_dense, num_classes): ...
import pkg_resources from rfhub.version import __version__ import rfhub.kwdb # this will be defined once the app starts KWDB = None
BATCH_SIZE = 64 EPOCHS = 100 IMG_WIDTH = 1801 IMG_HEIGHT = 32 NUM_CHANNELS = 3 NUM_CLASSES = 2 NUM_REGRESSION_OUTPUTS = 24 K_NEGATIVE_SAMPLE_RATIO_WEIGHT = 4 INPUT_SHAPE = (IMG_HEIGHT, IMG_WIDTH, NUM_CHANNELS) PREDICTION_FILE_NAME = 'objects_obs1_lidar_predictions.csv' PREDICTION_MD_FILE_NAME = 'objects_obs1_metadata....
#!/usr/bin/python """ Sphinx HTML output has leading newlines for some reason. This prevents GH-Pages from auto-forwarding the root url to index.html, so need to trim out the leading newlines. Very easy to do from the shell, but use a python script in the interest of cross-platform compatibility. This script removes...
import time import heapq class PriorityQueue: def __init__(self): self._q = [] def add(self, value, priority=0): heapq.heappush(self._q, (priority, time.time(), value)) def pop(self): return heapq.heappop(self._q)[-1] f1 = lambda: print("hello") f2 = lambda: print("world") pq ...
import click from data.services import RottenTomatoesSearcher from tables.builders import MovieSearchTableBuilder, TvShowSearchTableBuilder from tables.rows.builders import MovieSearchRowBuilder, TvShowSearchRowBuilder searcher = RottenTomatoesSearcher() movie_search_table_builder = MovieSearchTableBuilder(MovieSearc...
# 2017.12.16 by xiaohang import sys from caffenet import * import numpy as np import argparse import torch.nn as nn from torch.autograd import Variable from torch.nn.parameter import Parameter import time class CaffeDataLoader: def __init__(self, protofile): caffe.set_mode_cpu() self.net = caffe.Ne...
import sys import pandas as pd data_type = sys.argv[1] folder_no = sys.argv[2] filename = '../data/MTA/MTA_videos_coords/' + data_type + '/cam_' + folder_no + '/coords_cam_' + folder_no + '.csv' # filename = '../data/MTA/mta_data/images/' + data_type + '/cam_' + folder_no + '/coords_cam_' + folder_no + '.csv' # file...
import numpy as np import cupy as cp class model_mixer: ''' Functions for combining the weights of different models. The models should probably be based on an initial training run so that the majority of parameters are the same to begin with.''' def __init__(self): self._model_parame...
#!/usr/bin/env python import pytest """ Test 1771. Maximize Palindrome Length From Subsequences """ @pytest.fixture(scope="session") def init_variables_1771(): from src.leetcode_1771_maximize_palindrome_length_from_subsequences import Solution solution = Solution() def _init_variables_1771(): ...
matches = 0 for line in open('2/input.txt'): acceptable_positions, letter, password = line.split(" ") low, high = acceptable_positions.split("-") if (letter[0] == password[int(low)-1] ) != (letter[0] == password[int(high)-1]): matches += 1 print(matches)
import numpy as np def editDistance(s1, s2): m=len(s1)+1 n=len(s2)+1 tbl = np.empty([m,n]) for i in xrange(m): tbl[i,0]=i for j in xrange(n): tbl[0,j]=j for i in xrange(1, m): for j in xrange(1, n): cost = 0 if s1[i-1] == s2[j-1] else 1 tbl[i,j] = min(tbl[i, j-1...
from setuptools import find_packages, setup __version__ = '0.1' url = 'https://github.com/ntt123/haiku_trainer' download_url = '{}/archive/{}.tar.gz'.format(url, __version__) install_requires = [] setup_requires = [] tests_require = [] setup( name='haiku_trainer', version=__version__, description='A help...
import requests import os import sys import time import datetime start = time.mktime(time.localtime()) t = datetime.datetime.now() today = t.strftime('%m-%d-%Y') vm_name = "Kali-%s" % today url = 'https://images.offensive-security.com/\ virtual-images/kali-linux-2020.3-vbox-amd64.ova' local_filename = url.split('/'...
from bolsonaro.models.model_raw_results import ModelRawResults from bolsonaro.models.omp_forest_regressor import OmpForestRegressor from bolsonaro.models.omp_forest_classifier import OmpForestBinaryClassifier, OmpForestMulticlassClassifier from bolsonaro.models.nn_omp_forest_regressor import NonNegativeOmpForestRegress...
from __future__ import absolute_import from django.test import TestCase from django.test.utils import override_settings import django_dynamic_fixture as fixture from readthedocs.projects.models import Project @override_settings( USE_SUBDOMAIN=True, PUBLIC_DOMAIN='public.readthedocs.org', SERVE_PUBLIC_DOCS=True ...
# Copyright (c) 2017-2019 Uber Technologies, Inc. # SPDX-License-Identifier: Apache-2.0 import logging import warnings from collections import defaultdict import pytest import torch from torch.distributions import constraints import pyro import pyro.distributions as dist import pyro.poutine as poutine from pyro.dist...
""" Main program dla 2to3. """ z __future__ zaimportuj with_statement, print_function zaimportuj sys zaimportuj os zaimportuj difflib zaimportuj logging zaimportuj shutil zaimportuj optparse z . zaimportuj refactor def diff_texts(a, b, filename): """Return a unified diff of two strings.""" a = a.splitlines...
from django import forms from zentral.contrib.inventory.models import BusinessUnit from .models import SimpleMDMInstance from .api_client import APIClient, APIClientError class SimpleMDMInstanceForm(forms.ModelForm): class Meta: model = SimpleMDMInstance fields = ("business_unit", "api_key") ...
import logging import urllib.request import time import sys import bot def is_connected(url_string): connected = False try: urllib.request.urlopen(url_string, timeout=5) connected = True except Exception as e: logging.error(e) return connected def usage(): print("Usage ...
# Copyright (c) 2017-2021 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. # SPDX-License-Identifier: Apache-2.0 """ The core scheduling of logic, managing the tricky interaction between the man asyncio event loop and background threads. """ from asyncio import CancelledError, Future, Invali...
# Copyright (C) 2015 Twitter, Inc. """Container for all campaign management logic used by the Ads API SDK.""" from twitter_ads.enum import TRANSFORM from twitter_ads.analytics import Analytics from twitter_ads.resource import resource_property, Resource, Persistence, Batch from twitter_ads.http import Request from tw...
from typing import Optional from password_manager.database_manager import DatabaseManager from password_manager.encryption.record_reader import EncryptedRecordReader from password_manager.encryption.record_writer import EncryptedRecordWriter from password_manager.integration.controller import IntegrationController fro...
from facade_formatter import FacadeFormatter class InterfaceDisplay: def __init__(self): self.formatter = FacadeFormatter() def format_rows(self, rows): formatted_rows = [] for row in rows: formatted_rows.append(self.formatter.format_row(row)) return formatted_rows...
import numpy as np havaDurumu = [[12,21,31],[6,17,18],[11,12,13]] print(havaDurumu) print('-----------------------------------------') a = np.arange(15).reshape(3,5) print(a) print(type(a)) print("Dimension Count : " + str(a.ndim)) # Boyut print('-----------------------------------------') b = np.ara...
import logging class _Decorators: @classmethod def try_decorator(cls, fn): logger = logging.getLogger(__name__) async def decorated(*args, **kw): for _ in range(5): try: value = fn(*args, **kw) except Exception as error: ...
#!/usr/bin/env python # # freqresp_test.py - test frequency response functions # RMM, 30 May 2016 (based on timeresp_test.py) # # This is a rudimentary set of tests for frequency response functions, # including bode plots. import unittest import numpy as np import control as ctrl from control.statesp import StateSpace...
# -------------------------------------------------------------------------- # Copyright (c) <2017> <Lionel Garcia> # BE-BI-PM, CERN (European Organization for Nuclear Research) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files ...
import unittest from biothings_explorer.registry import Registry from biothings_explorer.user_query_dispatcher import SingleEdgeQueryDispatcher from .utils import get_apis reg = Registry() class TestSingleHopQuery(unittest.TestCase): def test_anatomy2protein(self): """Test gene-protein""" seqd = ...
from packetbeat import (BaseTest, TRANS_REQUIRED_FIELDS) def check_event(event, expected): for key in expected: assert key in event, "key '{0}' not found in event".format(key) assert event[key] == expected[key],\ "key '{0}' has value '{1}', expected '{2}'".format(key, ...
################################################################################### # Copyright (c) 2015, NVIDIA CORPORATION. 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 ...
from argparse import ArgumentParser from functools import partial from glob import glob import h5py import numpy as np import os import sys from .reader import DataCollection, H5File, FileAccess class ValidationError(Exception): def __init__(self, problems): self.problems = problems def __str__(self...
import cv2 import numpy as np import matplotlib.pyplot as plt from Load_Model import * import easyocr detection_threshold = 0.4 region_threshold = 0.6 category_index = label_map_util.create_category_index_from_labelmap(files['LABELMAP']) def filter_text(region, ocr_result, region_threshold): rectangle_size = reg...
#!/usr/bin/env python from setuptools import setup, find_packages setup( name='pysensu-yelp', version='0.4.4', provides=['pysensu_yelp'], description='Emits Yelp-flavored Sensu events to a Sensu Client', url='https://github.com/Yelp/pysensu-yelp', author='Yelp Operations Team', author_emai...
from grammars.grammars import lang_dict from treemanager import TreeManager from grammar_parser.gparser import MagicTerminal from utils import KEY_UP as UP, KEY_DOWN as DOWN, KEY_LEFT as LEFT, KEY_RIGHT as RIGHT from grammars.grammars import EcoFile import pytest calc = lang_dict["Basic Calculator"] python = lang_dic...
""" A test spanning all the capabilities of all the serializers. This class sets up a model for each model field type (except for image types, because of the Pillow dependency). """ from django.db import models from django.contrib.contenttypes.fields import ( GenericForeignKey, GenericRelation ) from django.contri...
import adventure import json if __name__ == '__main__': # load configure file config_file = open("config/config.json", "r") config_obj = json.load(config_file) instance = adventure.default; instance.init(config_obj) instance.start()
# from bottle import run import requests import csv def send(): while True: print("Enter number") number = input() xml = f"<?xml version='1.0' encoding='utf-8'?><data>{number}</data>" headers = {"Content-Type": "application/xml"} # set what your server accepts response = r...
n = int(input("Digite o n-ésimo termo para mostra a série de Fibonaci: ")) a = 0 b = 1 print(a) for x in range(b, n): c = a a = b b = a + c print(a)
from django.db import models from applications.utils.models import Language class Information(Language): full_name = models.CharField(max_length=150) phone = models.CharField(max_length=20, blank=True, null=True) website = models.URLField(blank=True, null=True) email = models.EmailField(blank=True, n...
import uuid from abc import ABCMeta, abstractmethod class Recording(object): """ Holds a recording of an operation that was recorded using the TapeRecorder """ __metaclass__ = ABCMeta def __init__(self, _id=None): self.id = _id or uuid.uuid1().hex self._closed = False @abstr...
import cv2 import yaml class parkingSpaceBoundary: def __init__(self, img, file): self.image = img self.filePath = file self.parkingSpace = [] self.id = 1 data = [] def dumpYML(self): with open(self.filePath, "a") as yml: yaml.dump(self.data, yml) ...
''' The bulk of this program is based off of the sample code that Instagram put out to run their API the myInfo section was written by Tim with minor modifications in the models.py so that the username and id number could be shown to the user To run it: * Download bottle if you don't already have it: pip install bo...
#!/usr/bin/env python # SPDX-License-Identifier: Apache-2.0 # # The OpenSearch Contributors require contributions made to # this file be licensed under the Apache-2.0 license or a # compatible open source license. import logging import os from build_workflow.build_args import BuildArgs from build_workflow.build_reco...
import frappe class TallyImportCurrencyItems: def __init__(self, value, ow): self.currency_table_map = { 'MAILINGNAME' : 'name', 'DECIMALSYMBOL' : 'fraction', 'ORIGINALNAME' : 'symbol' } self.overwrite = ow self.process_node = value...
from flask import current_app, _app_ctx_stack import flask_login from flaskloginintegration import _user_loader, User from views import login_views class ZKPP(object): def __init__(self, app=None, login_manager=flask_login.LoginManager()): self.app = app self.login_manager = login_manager ...
# -*- coding: utf-8 -*- import json from geventwebsocket.exceptions import WebSocketError from putils.patterns import Singleton import re import logging logger = logging.getLogger(__name__) class Router(Singleton): CONNECTED = "router_connected" DISCONNECTED = "router_disconnected" def __init__(self, server): s...
import hashlib import os from contextlib import contextmanager from pathlib import Path from tempfile import NamedTemporaryFile __all__ = ["inplace", "assert_file_exist", "file_hash"] @contextmanager def inplace(filepath: Path): folder = filepath.parents[0] name = filepath.name success = True try: ...
# -*- coding: utf-8 -*- from typing import Optional import os from matminer.data_retrieval.retrieve_Citrine import CitrineDataRetrieval import pandas as pd import numpy as np from pathlib import Path from tqdm import tqdm from src.data.utils import countSimilarEntriesWithMP, LOG from src.data import get_data_base clas...