content
stringlengths
5
1.05M
from django.contrib.auth.models import BaseUserManager class AccountManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, password, **extra_fields): """ Create and save...
#! python3 # tests.py import json import os import unittest import selenium from selenium import webdriver from selenium.webdriver.firefox.options import Options class TestClassFanGraphs(unittest.TestCase): def test_files_exist(self): directories = { 'leaders': [ 'menu.txt', ...
# -*- coding: utf-8 -*- """Tests for `statemachine` processors.""" import os import cv2 from gabrieltool.statemachine import processor_zoo def drawPred(frame, class_name, conf, left, top, right, bottom): # Draw a bounding box. cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0)) label = '%...
import traceback from flask import Flask, request, jsonify from simulator import config, utils from simulator.exchange import Poloniex from simulator.order_handler import CoreOrder, SimulationOrder from simulator.balance_handler import BalanceHandler api = Flask(__name__) logger = utils.get_logger() @api.route('/...
# Copyright 2012 OpenStack Foundation # 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 requ...
# Generated by Django 2.2.8 on 2020-06-21 19:30 import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('donations', '0016_auto_20200621_1609'), ] operations = [ migrations.AddField( ...
# Generated by Django 2.0.3 on 2018-03-21 18:59 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('patientbasicinfo', '0012_auto_20180321_1827'), ] operations = [ migrations.AddField( model_name='identity', name='em...
def calculate_amstrong_numbers_3_digits(): result = [] for item in range(100, 1000): sum = 0 for number in str(item): sum += int(number) ** 3 if sum == item: result.append(item) return result print("3-digit Amstrong Numbers:") print(calculate_amstrong_numb...
#N 個の街と N−1 本の道路なのでループはない。木構造 #根への距離をそれぞれ求めて、和が2で割り切れるかで判断できそう from collections import defaultdict from collections import deque N, Q = map(int, input().split()) connect_nodes = defaultdict(set) for i in range(N - 1): a, b = map(int, input().split()) connect_nodes[a].add(b) connect_nodes[b].add(a) dist...
# coding: utf-8 # # Permute Hetnets for Interpreting Compressed Latent Spaces # # Modified from @dhimmel - https://github.com/dhimmel/integrate/blob/master/permute.ipynb # # Generate several randomly permuted hetnets to serve as a null distribution. The permutations preserve node degree but randomizes connections b...
#!/usr/bin/env python3 # Converts PLINK covariate and fam file into a covariate file for Gemma import sys import pandas as pd import argparse import numpy as np def readbed(filebed, wind): readbed=open(filebed) dicpos={} dicrange={} for line in readbed: spll=line.replace('\n','').split() if spll[0] ...
class ResizingArrayStack(object): """ """ def __init__(self): self.n = 0 self.capacity = 2 self.resizing_array = [None] * self.capacity def __len__(self): return self.n def __contains__(self, i): """ >>> stack = ResizingArrayStack() >>> stac...
# -*- coding: utf-8 -*- """ Created on Fri Oct 1 16:54:46 2021 @author: vanch """ import argparse import FileToDataFrame as ftd import matplotlib.pyplot as plt def getTopMsgs(people_name, data_frame): top_list = [] col_map = plt.get_cmap('Paired') for name in people_name: tmp_df_by_name = data...
# # PySNMP MIB module IF-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///usr/share/snmp/mibs/ietf/IF-MIB # Produced by pysmi-0.3.2 at Tue Apr 7 17:35:33 2020 # On host sensei platform Linux version 4.19.97-v7l+ by user nagios # Using Python version 3.7.3 (default, Dec 20 2019, 18:57:59) # OctetString, Integer,...
from collections import OrderedDict from pathlib import Path from tempfile import NamedTemporaryFile from typing import Dict, List, Tuple import pytest from datamodel_code_generator import DataTypeManager from datamodel_code_generator.model import DataModel, DataModelFieldBase from datamodel_code_generator.model.pyda...
import collections import io import os import typing import torch import numpy as np from .operators import CommonGraph, ExtendedOperator, GraphOptimizer, HybridQuantizer from .operators.op_version import OPVersioner from .operators.tflite import Tensor from .operators.torch import OPERATOR_CONVERTER_DICT from .opera...
# Copyright (c) 2013, erpcloud.systems and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe import _ def execute(filters=None): columns, data = [], [] columns=get_columns() data=get_data(filters,columns) return columns, data def get_...
from middleware.db import repository from middleware.connection.conn import session from middleware.db.tables import PokemonMoveAvailability from pokedex.db.tables import VersionGroup red_blue_vg = session.query(VersionGroup).filter(VersionGroup.identifier == 'red-blue').one() yellow_vg = session.query(VersionGroup).f...
# Copyright (C) 2014 Universidad Politecnica de Madrid # # 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 la...
""" NFS exports configuration ========================= NFSExports and NFSExportsD provide a parsed output of the content of an exports file as defined in ``man exports(5)``. The content is parsed into a dictionary, where the key is the export path and the value is another dictionary, where the key is the hostname an...
from __future__ import unicode_literals, print_function from jinja2 import FileSystemLoader, StrictUndefined from jinja2.environment import Environment env = Environment(undefined=StrictUndefined) env.loader = FileSystemLoader(".") vrf_list [ {"vrf_name": "blue1", "ipv4_enabled": True, "ipv6_enabled": True,"red": ...
__author__ = 'mattjmorris' from .dynamo import Dynamo from boto.dynamodb2.table import Table from datetime import datetime, date, timedelta from pandas import DataFrame import re DAY_STR_FORMAT = "%Y-%m-%d" DAY_STR_RE = re.compile(r'^(\d{4})-(\d{2})-(\d{2})$') SECOND_STR_FORMAT = "%Y-%m-%d %H:%M:%S" SECOND_STR_RE = ...
# -*- coding: utf-8 -*- from .aliases import * from .helper import Helper from ..consts.lessons import LESSON_ID_MAX_LENGTH, LESSON_TITLE_MAX_LENGTH, LESSON_BODY_MAX_LENGTH, LESSON_DESC_MAX_LENGTH from .topics import Topics from wcics.utils.time import get_time class lessons(dbmodel, Helper): id = dbcol(dbint, pri...
# coding: utf-8 """ ===================================== Feature Extraction for Classification ===================================== Extract acoustic features from labeled data for training an environment or speech classifier. To see how soundpy implements this, see `soundpy.builtin.envclassifier_feats`. """ ####...
import os.path import sys import pytest from shapely.geometry import LineString from shapely.geometry import Point import conftest sys.path.append(os.path.join(os.path.dirname(__file__), '.')) sys.path.append(os.path.join(os.path.dirname(__file__), '..')) from interpoint import models class TestPtOnEdge: def ...
#! /usr/bin/python import time from datetime import datetime import serial from xbee import XBee, ZigBee PORT = '/dev/ttyUSB0' BAUD_RATE = 9600 # Open serial port and enable flow control ser = serial.Serial(PORT, BAUD_RATE, bytesize=8, parity='N', stopbits=1, timeout=None, xonxoff=1, rtscts=1, dsrdtr=1) # Create A...
# Generated by Django 3.0.8 on 2020-08-08 15:07 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django_countries.fields class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ...
from math import cos, pi from typing import Callable, List from src.common.model.line_segment import LineSegment from src.common.model.numerical_integrator import NumericalIntegrator def get_mohler_roots(n: int) -> List[float]: return [cos((2 * k - 1) / (2 * n) * pi) for k in range(1, n + 1)] def get_mohler_co...
# Citcuit pseudocode # Data structures struct op: # operation data tx_type: # type of transaction, see the list: https://docs.google.com/spreadsheets/d/1ejK1MJfVehcwjgjVDFD3E2k1EZ7auqbG_y0DKidS9nA/edit#gid=0 chunk: # op chunk number (0..3) pubdata_chunk: # current chu...
#!/bin/env python3 "ngugen -- generate nginx.unit config files, safely and sanely via a tiny DSL;" if True: from collections import OrderedDict # To make things look 'right'; import json import os import re __author__ = "mr.wooK@gmail.com" __license__ = "MIT License" __copyright__ =...
import datetime import json import os import typing import gpxpy # type: ignore import pint # type: ignore import s2sphere # type: ignore import polyline # type: ignore from stravaviz.exceptions import TrackLoadError from stravaviz.units import Units class Track: """Create and maintain info about a given ac...
import click import pkgutil import os import os.path as osp from . import ( CONFIG_DIR, ) @click.command() @click.option("--config", default=None, type=click.Path(exists=True)) def cli(config): # make the bimker configuration dir os.makedirs(CONFIG_DIR) ## Generate or link to the config file c...
# optimizer optimizer = dict(type='AdamW', lr=1e-4, betas=(0.95, 0.99), weight_decay=0.01,) # learning policy lr_config = dict( policy='CosineAnnealing', warmup='linear', warmup_iters=1600 * 8, warmup_ratio=1.0 / 100, min_lr_ratio=1e-8, by_epoch=False) # test add by_epoch false optimizer_config ...
bl_info = {"name": "Icicle Generator", "author": "Eoin Brennan (Mayeoin Bread)", "version": (2, 1), "blender": (2, 7, 4), "location": "View3D > Add > Mesh", "description": "Adds a linear string of icicles of different sizes", "warning": "", "w...
# ~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~ # 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...
# -*- coding:utf-8 -*- # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "Lic...
# https://opensource.com/article/18/6/tornado-framework # https://stackoverflow.com/questions/6131915/web-sockets-tornado-notify-client-on-database-update # __init__.py from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop from tornado.options import define, options from tornado.web import Applic...
from os import path import subprocess from venv import EnvBuilder projects_dir = path.join(path.abspath(path.dirname(__name__)), 'projects') class PipEnv: def __init__(self, name, libs): self.env = EnvBuilder(clear=True, with_pip=True) if not path.isdir(f"{projects_dir}/{name}"): self....
# -*- coding: utf-8 -*- """ Created on Thu Jan 28 19:30:32 2021 """ GREETING = { 'en' : '''Hi! Im Clockwork Fox I\'m here to greet every new member of your groups, also I can help you with some events you may want to do with friends. If you want to know how to do some you can use some /help ''', 'es' : ''...
from __future__ import division import numpy as np import matplotlib.pyplot as plt import lmfit import scipy.stats import scipy.optimize minimize = lmfit.minimize from fitter import Fitter # To use different defaults, change these three import statements. from kid_readout.analysis.khalil import delayed_generic_s21 a...
import tweepy from keys import consumer_key, consumer_secret, access_token, access_secret from scrape import auth, api, get_tweets from create import markov, dict_maker auth.set_access_token(access_token, access_secret) #Dictionaries for specific accounts are created here playstation = dict_maker("PlayStation") lil_...
import logging from typing import Optional from homeassistant.components.sensor import STATE_CLASS_MEASUREMENT from homeassistant.const import ( DEVICE_CLASS_ENERGY, DEVICE_CLASS_POWER, DEVICE_CLASS_TEMPERATURE, DEVICE_CLASS_BATTERY, DEVICE_CLASS_POWER_FACTOR, DEVICE_CLASS_TIMESTAMP, TEMP_C...
import pytest import sdk_cmd import sdk_install import sdk_hosts import sdk_plan import sdk_utils import retrying from security import transport_encryption from tests import config DEFAULT_JOURNAL_NODE_TLS_PORT = 8481 DEFAULT_NAME_NODE_TLS_PORT = 9003 DEFAULT_DATA_NODE_TLS_PORT = 9006 @pytest.fixture(scope='modu...
import numpy as np import pandas as pd import os import argparse from utils.data_utils import * from tqdm import tqdm import itertools if __name__ == "__main__": """ Generate dataframe where each row represents patient admission """ parser = argparse.ArgumentParser(description="Process Mimic-iii CSV ...
import sys import paho.mqtt.subscribe as subscribe broker = sys.argv[1] topic = sys.argv[2] def callback(client, userdata, message): print("message received ", str(message.payload.decode("utf-8"))) try: subscribe.callback(callback, topic, hostname=broker).loop_forever() except Keybo...
import numpy as np import pandas as pd import cv2 import tensorflow as tf from tensorflow.keras.preprocessing.image import ImageDataGenerator class DataLoader: def __init__ (self, train_dataframe, validation_dataframe, image_dir): self.train_dataframe =train_dataframe self.validation_dataframe = v...
import re import nltk from nltk.stem.porter import PorterStemmer def data_cleaning(text): # Remove symbols and punctuations & apply lower() to string formatted_text = re.sub(r"[^\w\s]", " ", text).lower() # Remove stopwords stopwords = set(nltk.corpus.stopwords.words('english')) words = [i for i i...
import traceback from io import BytesIO from PIL import Image from ocr import ocr import numpy as np import json import os def validBegin(s): return s.startswith("62") or s.startswith("60") or s.startswith("34") or s.startswith("35") or s.startswith("37") or s.startswith("51") or s.startswith("52") or s.startswith...
PHASES = ["build", "test"] CUDA_VERSIONS = [ None, # cpu build "92", "101", "102", ] STANDARD_PYTHON_VERSIONS = [ "3.6", "3.7", "3.8" ]
from dataclasses import dataclass from bindings.gmd.dq_conceptual_consistency_type import DqConceptualConsistencyType __NAMESPACE__ = "http://www.isotc211.org/2005/gmd" @dataclass class DqConceptualConsistency(DqConceptualConsistencyType): class Meta: name = "DQ_ConceptualConsistency" namespace =...
#!/usr/bin/env python """Geoname Annotator""" from __future__ import absolute_import import math import re import sqlite3 from collections import defaultdict from .annotator import Annotator, AnnoTier, AnnoSpan from .ngram_annotator import NgramAnnotator from .ne_annotator import NEAnnotator from geopy.distance import...
"""Processing profile in admin site page """ from django.contrib import admin from .models import Profile admin.site.register(Profile)
# -*- coding: utf-8 -*- from model.contact import Contact def test_add_new_contact(app): app.contact.add_new_contact(Contact(first_name="Fname", middle_name="Mname", last_name="Lname", nickname="Nickname", title="Test_title", company="Test_company", address="Test_address", tel_home="123456", tel_mobile="11223...
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .forms import UserChangeForms, UserCreationForms from .models import User # Register your models here. @admin.register(User) class UserAdmin(UserAdmin): # type: ignore form = UserChangeForms add_form = UserCreationForms ...
from __future__ import division from typing import List, Optional import numpy as np import matplotlib.pyplot as plt import random import cv2 from PIL import Image, ImageDraw, ImageFont import pickle from pathlib import Path import scipy.signal as ssig import scipy.stats as sstat import math def sample_weighted(p_dic...
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. """ Classes for reading/manipulating/writing QChem input files. """ import logging import sys from typing import Union, Dict, List, Optional, Tuple from monty.io import zopen from monty.json import MSONable f...
''' Atakan Ayaşlı 170401066 ''' import socket import time import os import sys def Dosya_listele(): msg = "LİSTE Komutu doğru" msgEn = msg.encode('utf-8') s.sendto(msgEn, clientAddr) F = os.listdir( path="C:\Users\Atakan\Desktop\170401066\server") """ lütfen server.py dosyas...
import torch import numpy as np import streamlit as st from encode import encode_long_text, decode_long_text,colorize import difflib @st.cache(ignore_hash=True) def load_models(): en2fr = torch.hub.load('pytorch/fairseq', 'transformer.wmt19.en-de.single_model', tokenizer='moses', bpe='fastbpe') fr2en = torch.hu...
from biicode.common.edition.hive_manager import HiveManager from biicode.client.exception import ConnectionErrorException, ClientException, NotInAHiveException from biicode.client.checkout.snapshotbuilder import compute_files, compute_deps_files from biicode.common.exception import BiiException from biicode.client.comm...
from django.conf.urls import url from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url('^$', views.index, name='home'), url(r'^search/', views.search_results, name='search_results'), url(r'^singleimage/(\d+)', views.single_photo, name='singleIma...
""" import csv import os class GenericCar: def __init__(self, car_type, brand, photo_file_name, carrying): self.car_type = car_type self.brand = brand self.photo_file_name = photo_file_name self.carrying = float(carrying) def get_photo_file_ext(self): _, file_extension ...
import os from builtins import str from builtins import object from builtins import range from retriever.lib.models import Engine from retriever import DATA_DIR, open_fr, open_fw from retriever.lib.tools import xml2csv, sort_csv class DummyConnection(object): def cursor(self): pass def commit(self)...
"""A data structure for a set of coronal hole tracking (CHT) algorithm. Module purposes: (1) used as a holder for a window of frames and (2) matches coronal holes between frames. Last Modified: July 21st, 2021 (Opal). """ import json import numpy as np import datetime as dt import pickle from chmap.coronal_holes.trac...
# Copyright (c) 2021 Sebastian Pipping <sebastian@pipping.org> # Licensed under the MIT license import base64 import hashlib import os import tempfile from argparse import ArgumentParser import requests def download_url_to_file(url): response = requests.get(url, allow_redirects=True) with tempfile.NamedTemp...
from django import forms from django.forms.fields import DateField from .models import Exam, Question, AnsweredQuestion, Recommendation BIRTH_YEAR_CHOICES = range(1940, 2019) class TakeExamForm(forms.ModelForm): birthdate = forms.DateField( widget=forms.SelectDateWidget(years=BIRTH_YEAR_CHOICES, empty_l...
EMOTIONS = { 0:"anger", 1:"disgust", 2:"fear", 3:"happy", 4:"sad", 5:"surprise", 6:"neutral" } EMOTION2INTEGER = { "anger":0, "disgust":1, "fear":2, "happy":3, "sad":4, "surprise":5, "neutral":6 }
""" Contains the Parameter class. Copyright (c) 2014 Kenn Takara See LICENSE for details """ from sympy import Symbol from pysolve import InvalidNameError from pysolve.variable import Variable class Parameter(Symbol): """ This class contains a 'parameter'. This is an exogenous variable. The ...
# Copyright 2016-2019 Douglas G. Moore. All rights reserved. # Use of this source code is governed by a MIT # license that can be found in the LICENSE file. """ All of the currently implemented time series measures are only defined on discretely-valued time series. However, in practice continuously-valued time series a...
# -*- coding: utf-8 -*- # Generated by Django 1.9.8 on 2016-08-07 19:02 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('skaba', '0005_event_date'), ] operations = [ migrations.RemoveField( ...
import hashlib import json import time from tools import logger as log from tools import auction_house_data_logger as ah_log import strategies from strategies import support_functions def auctionh_get_prices(**kwargs): """ A strategy to get prices from the auction house. :param kwargs: strategy, listen...
# -*- coding: utf-8 -*- """ Allow us to use lib as a package """
# this script needs either the ViennaRNA python bindings or the RNAfold binary to be # available to predict RNA secondary structures def measure_rbp(entry): import os from time import time from pysster import utils output_folder = entry[4] + "_pysster/" if not os.path.isdir(output_folde...
from PIL import Image def resize(file_path="./.tmp/bg.jpg", size=(128, 128)): try: outfile = "./.tmp/bg_{}x{}.jpg".format(size[0], size[1]) im = Image.open(file_path) im.thumbnail(size, Image.ANTIALIAS) im.save(outfile, "JPEG") return outfile except Exception: ...
''' Authors: Alex Wong <alexw@cs.ucla.edu>, Safa Cicek <safacicek@ucla.edu> If this code is useful to you, please cite the following paper: A. Wong, S. Cicek, and S. Soatto. Learning topology from synthetic data for unsupervised depth completion. In the Robotics and Automation Letters (RA-L) 2021 and Proceedings of In...
# coding: utf-8 import numpy as np import pandas as pd ################################################## # メイン ################################################## if __name__ == '__main__': df = pd.DataFrame( { "id": range(1,7), "raw_grade": ['a', 'b', 'b', 'a', 'a', 'e'], "categoric...
#!/usr/bin/env python """Splunk App for Pagerduty.""" __author__ = 'Greg Albrecht <gba@onbeep.com>' __copyright__ = 'Copyright 2014 OnBeep, Inc.' __license__ = 'Apache License, Version 2.0' from .pagerduty import (PagerDutyException, PagerDuty, extract_events, # NOQA trigger_pagerduty, get_pagerduty_api_key)
from . import data_access_layer as DAL import web from web import Appication,NestableBlueprint,jsonify # from flask.views import MethodView,View import json from web.restful import Resource class UserAPI(Resource): Model=DAL.User def create_app(): app=Appication(__name__) app=UserAPI.register_api(app,en...
# -*- coding: utf-8 -*- # # GIS Unit Tests # # To run this script use: # python web2py.py -S eden -M -R applications/eden/modules/unit_tests/s3/s3gis.py import unittest import datetime from gluon import * from gluon.storage import Storage from s3 import * from unit_tests import run_suite # ==========================...
class LibtoolPackage (GnuPackage): def __init__(self): GnuPackage.__init__(self, 'libtool', '2.4.2', override_properties={ 'build_dependency': False}) def install(self): Package.install(self) self.sh('rm -f "%{staged_prefix}/bin/glibtool"') self.sh('...
#!/usr/bin/env python ''' TACO: Multi-sample transcriptome assembly from RNA-Seq Utility script that profiles the splice junctions in a BED file Requirements: pysam library ''' import os import sys import argparse import logging import operator from collections import Counter from taco.lib.base import Strand from ta...
import os from pathlib import Path from h2o import h2o from ..models.AIModel import AIModel class RequestModel: x_names = [] x_values = [] def __init__(self, x_values, x_names): self.x_values = x_values self.x_names = x_names def get_frame(self): return h2o.H2OFrame(dict(zi...
from django.conf.urls import url, include from rest_framework_nested import routers from auv.urls import router from .views import TripViewSet, WayPointViewSet auv_router = routers.NestedSimpleRouter(router, r'auvs', lookup='auv') # api/auvs/{auv_pk}/trips auv_router.register(r'trips', TripViewSet, base_name='trips')...
from unittest import TestCase from scipy.io import wavfile import torch import torch.autograd from torch.nn import ConstantPad2d import torch.nn.functional as F from torch.autograd import Variable, gradcheck from wavenet_training import DilatedQueue, custom_padding from pathlib import Path class Test_dilated_queue(T...
import numpy import torch import torch.nn.functional as F from torch_rl.algos.base import BaseAlgo class PPOAlgo(BaseAlgo): """The class for the Proximal Policy Optimization algorithm ([Schulman et al., 2015](https://arxiv.org/abs/1707.06347)).""" def __init__(self, envs, acmodel, num_frames_per_proc=Non...
dist = input("Enter the distance travelled by youto and fro in kms : ") f_avg = input("Enter the fuel average in your area [km/litre]: ") cost_of_diesel = input("Enter the cost of diesel [int INR]: ") f_cons = float(dist) / float(f_avg) cost = float(f_cons) * float(cost_of_diesel) print("The cost of travel is : ...
import os import sys os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings' from tests import settings settings.INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.contenttypes', 'django.contrib.admin', 'django.contrib.sites', 'paloma', ) def run_tests(sett...
from core.terraform.resources.aws.load_balancer import LoadBalancerResource from resources.vpc.security_group import InfraSecurityGroupResource from core.config import Settings class ApplicationLoadBalancer(LoadBalancerResource): name = "" internal = True load_balancer_type = "application" security_gr...
#!/usr/bin/env python # -*- coding: utf-8 -*- __all__ = ["db"] from flask.ext.sqlalchemy import SQLAlchemy db = SQLAlchemy()
# Step with a savebutton for saving a specified datacollect param # with the perform_save() method # # Works only in datacollect mode. Must be late enough # in the checklist that checklist filename has already been determined import os import sys import posixpath try: # py2.x from urllib import pathname2url...
import requests import json import sys import time from api import * blockTime = get_block_time() difficulty = get_difficulty() usd_price = get_usd_price() data = { 'blockTime': blockTime, 'difficulty': difficulty, 'priceUsd': usd_price, 'lastUpdate': time.time(), } file(sys.argv[1], 'w').write('ethe...
import tensorflow as tf from tensorflow.keras.layers import Dense, Conv2D, BatchNormalization, MaxPool2D from tensorflow.keras import Model class CNN(object): def __init__(self, height, width, channel, num_class, leaning_rate=1e-3, ckpt_dir='./Checkpoint'): print("\nInitializing Neural Network...") ...
import cv2 import numpy as np import glob import os import argparse parser = argparse.ArgumentParser(description='prepare captures for annotation') parser.add_argument('--input_folder', help='the input folder', required=True) parser.add_argument('--video_name', help='the top view video name ... e.g. view2-color.mp4', ...
import fxpt_experiments as fe num_procs = 10 test_data_ids = [ "big1024_base", "big512_base", "big256_base", "full_base", ] for test_data_id in test_data_ids: _ = fe.run_TvB_stability_experiments(test_data_id,num_procs)
""" Load the Kepler light curve from FITS files. Also do a bit of preprocessing. """ import inputs as inp def loadlc(files, usepdc=False, **kwargs): """ Load Kepler light curves. Parameters ---------- files : list of strings The locations of the light curves to load together. usepdc :...
def test_movie_goofs(ia): movie = ia.get_movie('0133093', info=['goofs']) goofs = movie.get('goofs', []) assert len(goofs) > 120
import numpy as np from scipy import misc import matplotlib.pyplot as plt face = misc.face(gray=True) plt.imshow(face, cmap=plt.cm.gray) plt.savefig('face0.png') plt.clf() bwimage = np.zeros_like(face) bwimage[face > 128] = 255 plt.imshow(bwimage, cmap=plt.cm.gray) plt.savefig('face1.png') plt.clf() framedface = np...
"""Added start, enddate to digitize group Revision ID: 4f17336641b9 Revises: 4237cb2ca161 Create Date: 2016-10-18 16:16:56.159752 """ # revision identifiers, used by Alembic. revision = '4f17336641b9' down_revision = '4237cb2ca161' branch_labels = None depends_on = None from alembic import op import sqlalchemy as s...
import teams as t import org as o import employee as emp from empstore import employees from empstore import teams from empstore import org while True: print("Press 1 for add employee") print("Press 2 for delete employee ") print("Press 3 for search employee") print("Press 4 for display employee") print("Press 5 ...
#Felipe Lima #Linguagem: Python #Exercício 06 do site: https://wiki.python.org.br/EstruturaSequencial #Importa biblioteca import math #Entra com o raio raio = float(input("Qual o raio do círculo: ")) #Calcula a área area = math.pi*raio #Imprime o resultado print("A área do círculo, para o raio digitado, é: {:.2f}."...
#-------------------------------------------------------------------------------------------- # Simplistic implementation of the Sinkhorn divergences, with a vanilla PyTorch backend #-------------------------------------------------------------------------------------------- import numpy as np import torch #######...