content
stringlengths
5
1.05M
class Vocabulary: UNK = '<unk>' def __init__(self): self.__size = 1 self.__dict = {self.UNK: 0} self.__reverse_dict = {'0': self.UNK} self.__freeze = False def __len__(self): return self.__size def freeze(self): self.__freeze = True def transform(...
from AVL_TABLE import AVL_TABLE as AvlT import os class Nodo: def __init__(self, avlTable, name): self.name = name self.avlTable = avlTable self.izq = None self.der = None self.factor = 1 class AVL_DB: def __init__(self): self.raiz = None def insertar(s...
import importlib class BMCType: pass class BMCError(Exception): pass types = [] def register_bmc_type(klass): inst = klass() types.append(inst) def resolve_bmc_type(klass_name): return next(t for t in types if t.name == klass_name) def list_bmc_types(): return types importlib.impor...
import pandas as pd import numpy as np import re import json # dataset is downloaded from https://data.cityofnewyork.us/Health/DOHMH-New-York-City-Restaurant-Inspection-Results/rs6k-p7g6 data = pd.read_csv('../data/raw_data/DOHMH_New_York_City_Restaurant_Inspection_Results.csv') # select columns of interest isp_data ...
#!/usr/bin/env python # Score is: # % gene level right or - gene's num txpts # + % txpt level right # + % uniq calls right # + % definitive rel calls right import os, re, sys from os.path import basename, exists, getsize from operator import itemgetter from sys import stderr import argparse class G: """Gene...
import os, os.path, datetime, string, errno from maperipy import * import GenIsraelHikingTiles # http://stackoverflow.com/questions/749711/how-to-get-the-python-exe-location-programmatically MaperitiveDir = os.path.dirname(os.path.dirname(os.path.normpath(os.__file__))) # App.log('MaperitiveDir: ' + MaperitiveDir) Pro...
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np import scipy.stats def get_meta_backbone(name, state_dict=None): if name == 'conv4': from meta_backbones import conv4 backbone = conv4() elif name == 'resnet12': from meta_backbones import resnet12 ...
import rclpy #ros from rclpy.node import Node from std_msgs.msg import String #msg class MinimalSubscriber(Node): def __init__(self): super().__init__('minimal_subscriber') self.subscription = self.create_subscription(String,'topic', self.listener_callback,10) self.subscription # prevent ...
from flask import Flask, request, jsonify from flask_basicauth import BasicAuth from textblob import TextBlob import pickle as pkl import pandas as pd import os model = pkl.load(open('./models/model.pkl','rb')) app = Flask(__name__) app.config['BASIC_AUTH_USERNAME'] = os.environ.get('BASIC_AUTH_USERNAME') app.confi...
from flask import render_template, redirect, url_for, abort, flash, request from . import main from flask_login import login_required, current_user from app.models import User, Post, Category from .. import db,photos from .forms import UpdateProfile,CommentsForm,PostForm @main.route('/') def index(): posts = Po...
import re import pandas as pd import numpy as np import scipy as sp from scipy.spatial.distance import pdist import sys import warnings import sklearn import importlib import copy if (sys.version_info < (3, 0)): warnings.warn("As of version 0.29.0 shap only supports Python 3 (not 2)!") import_errors = {} def as...
# I gave up on Haskell for this one after I spent hours optimizing... from blist import * numPlayers = 458 numBalls = 7130700 scores = blist([0]*numPlayers) balls = blist([0]) lastPos = 0 for i in range(1, numBalls): if (i%1000 == 0): print(i, numBalls) player = i % numPlayers # print(i, lastPos,...
import requests from datetime import datetime def get_country(country): url = 'https://corona.lmao.ninja/countries/' + country response = requests.get(url) data = [ response.json()['country'], response.json()['cases'], response.json()['todayCases'], response.json()['deaths'...
from abc import ABC import json import os import logging import numpy as np import torch from torch.utils.data import TensorDataset, DataLoader, SequentialSampler import torch.nn as nn from transformers.modeling_bert import BertPreTrainedModel, BertModel from torchcrf import CRF from ts.torch_handler.base_handler imp...
# <Copyright 2020, Argo AI, LLC. Released under the MIT license.> import os import shutil from collections import defaultdict from pathlib import Path from typing import Any, DefaultDict, Dict, List, Mapping, NamedTuple, Tuple import numpy as np from scipy.spatial.transform import Rotation from argoverse.evaluation....
""" HTTP interface for retrieving a topology. Currently this means an XML representation of an NML topology. Author: Henrik Thostrup Jensen <htj@nordu.net> Copyright: NORDUnet (2013) """ from xml.etree import ElementTree as ET from opennsa.shared import modifiableresource from opennsa.topology import nmlxml class...
import argparse parser = argparse.ArgumentParser() parser.add_argument('--file', type=str, required=True) parser.add_argument('--line', type=int, required=True) args = parser.parse_args() filename = args.file line = args.line with open(filename, 'rt') as f: lines = f.readlines() newcontent = [l for i, l in e...
from netmiko import ConnectHandler class Router(object): def __init__(self, hostname=None, os=None, device_type='cisco_ios', ip=None, username='cisco', password='cisco', secret='cisco'): self.hostname = hostname self.os = os self.interfaces = 2 self.device_type = device_type ...
from mycroft import MycroftSkill, intent_file_handler from SPARQLWrapper import SPARQLWrapper, JSON import os from mycroft.util.log import LOG from difflib import SequenceMatcher def similar(a, b): return SequenceMatcher(None, a, b).ratio() def uri_to_str(uri): str = uri.split("/").pop().split("#").pop() ...
# -*- coding: utf-8 -*- from os import getcwd from time import sleep import boto3 from api.rdb.config import get, is_test from api.rdb.utils.cognito import get_cognito_app_client_id from api.rdb.utils.lambda_logger import lambda_logger from api.rdb.utils.service_framework import handle_request logger = lambda_logge...
''' Flask app intialization ''' from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config.from_object('config') db = SQLAlchemy(app) import mysite.routes
from __future__ import absolute_import, division, print_function import numpy as np from sklearn.base import BaseEstimator from SparseGroupLasso.linalg import vec_norm, dot from .utils import S, norm_non0 __author__ = 'Romain Tavenard romain.tavenard[at]univ-rennes2.fr' class SSGL(BaseEstimator): """A Semi-Spa...
# -*- coding: utf-8 -*- """Example that runs the checks on all structures in the CoRE MOF""" import concurrent.futures from glob import glob import pandas as pd from tqdm import tqdm # pylint:disable=import-error from mofchecker import MOFChecker from mofchecker.errors import NoMetal all_structures = glob("2019-11-...
# -*- coding: utf-8 -*- from celery.schedules import crontab from celery.task import periodic_task from celery import group from .models import User from .subtasks.user import task_check_user @periodic_task(run_every=crontab(minute=0), ignore_result=True) def task_start_worker(): user_id_list = User.objects.filter...
# -*- coding: utf-8 -* """FaceNet inference implementation.""" import tensorflow.compat.v1 as tf class FaceNet: """FaceNet inference implementation.""" def __init__(self, model_path): """Class constructor. Parameters ---------- model_path : str Path to a trained F...
class UserGroup: def __init__(self, group_name, members): self.group_name = group_name self.members = members self.members_count = len(self.members) def update_group_expense(self, lender, amount): # Check if lender is in the group if lender in self.members: count_shares = self.members_count - 1 els...
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: hack2020team/headposeservice/pose_service.proto from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf i...
#!/usr/bin/env python import os import sys import fastq import generalUtils import argparse parser = argparse.ArgumentParser(description='writes sequence length distribution') parser.add_argument('-i', required= True, help='input') parser.add_argument('-o', required= True, help='output') parser.add_argument('-l', requ...
import re import requests import weather_dao from requests.exceptions import RequestException def get_one_page(url, headers): try: response = requests.get(url, headers=headers) if response.status_code == 200: response.encoding = 'utf-8' return response.text return N...
def fun(): n=int(input()) total=(n*(n+1)*(2*n+1))/6 sum=(n+1)*(n+1) sum=(sum*(sum-1))/12 print(int(sum//total)) n=int(input()) while n!=0: n-=1 fun()
import torch import torch.nn as nn import os from collections import OrderedDict from functools import partial import colossalai import colossalai.nn as col_nn import torch import torch.nn as nn from colossalai.builder import build_pipeline_model from colossalai.engine.schedule import (InterleavedPipeline...
import os from slackclient import SlackClient slack_token = os.environ["SLACK_API_TOKEN"] sc = SlackClient(slack_token) # Get the group channels with the following # for group in sc.api_call("groups.list").get("groups"): # print("{}-{}".format(group['id'],group['name'])) sc.api_call( "chat.postMessage", chann...
#!/usr/bin/env python3 # coding: utf8 # Author: Lenz Furrer, 2017 ''' Iteration utilities. ''' import json import itertools as it def iter_chunks(iterable, chunksize): ''' Iterate over chunks of fixed size. ''' base = iter(iterable) # make sure items are consumed by islice() while True: ...
import os import random import discord from discord.ext import commands from dotenv import load_dotenv load_dotenv() token = os.getenv('DISCORD_TOKEN') GUILD = os.getenv('DISCORD_GUILD') bot = commands.Bot(command_prefix='!') @bot.event async def on_ready(): guild = discord.utils.get(bot.guilds, name=GUILD) ...
import numpy as np import scipy.stats import pandas class EvalIRModel(object): def __init__(self,dictModels,dictMetrics,queries): self.dictModels = dictModels self.dictMetrics = dictMetrics self.queries = queries def evalSimple(self,idq,mod,met): liste = self.dictMo...
from kitsune.karma.actions import KarmaAction from kitsune.karma.manager import KarmaManager class TestAction1(KarmaAction): """A test action for testing!""" action_type = 'test-action-1' default_points = 3 class TestAction2(KarmaAction): """Another test action for testing!""" action_type = 'tes...
from __future__ import absolute_import import pytest from sentry.auth.exceptions import IdentityNotValid from sentry.models import AuthIdentity, AuthProvider from sentry.testutils import TestCase from sentry_auth_chy.constants import DATA_VERSION class ChyOAuth2ProviderTest(TestCase): def setUp(self): ...
"""Common utils for the project""" import csv from datetime import datetime from functools import wraps AIRPORTS = { 'AMS': { 'city_code': 'NL', 'country': 'BKK' }, 'BKK': { 'city_code': 'FRA', 'country': 'DE' }, 'BUR': { 'city_code': 'BUR', 'countr...
"""shmap.py A class for working with imported shmeppy .json maps """ import json from datetime import datetime import shmobjs TOKEN_OPS = { 'CreateToken': ['color', 'position', 'tokenId'], 'MoveToken': ['position', 'tokenId'], 'UpdateTokenLabel': ['label', 'tokenId'], 'DeleteToken': ['tokenId'], ...
#!/usr/bin/env python3 import asyncio import requests import sys from concurrent.futures import ThreadPoolExecutor import pyfiglet #ascii_banner = pyfiglet.figlet_format("S3LURKARN") url = 'https://s3.amazonaws.com/' name = sys.argv[1].strip() connectors = ['-','_',''] url = url + name def fetch(session, com): ...
from django import forms from django.contrib.contenttypes.models import ContentType class VoteForm(forms.Form): content_type = forms.ModelChoiceField(widget=forms.HiddenInput, queryset=ContentType.objects.all()) object_id = forms.IntegerField(widget=forms.HiddenInput) vote = forms.IntegerField(widget=forms.HiddenIn...
load("@bazel_gazelle//:deps.bzl", "go_repository") # Run this to update: # bazel run //:gazelle -- update-repos -from_file=go.mod -to_macro=deps.bzl%go_dependencies def go_dependencies(): go_repository( name = "co_honnef_go_tools", importpath = "honnef.co/go/tools", sum = "h1:W18jzjh8mfPe...
import numpy as np from PuzzleLib.Backend import gpuarray from PuzzleLib.Containers.Sequential import Sequential from PuzzleLib.Modules.Conv2D import Conv2D from PuzzleLib.Modules.Activation import Activation, relu from PuzzleLib.Modules.MaxPool2D import MaxPool2D from PuzzleLib.Modules.AvgPool2D import AvgPool2D fro...
from __future__ import unicode_literals import json import mock import time from base64 import b64encode from copy import deepcopy from unittest import TestCase from oauthlib.common import urlencode from oauthlib.oauth2 import TokenExpiredError, OAuth2Error from oauthlib.oauth2 import MismatchingStateError from oauthl...
# Copyright (c) Ye Liu. All rights reserved. from .io import dump, dumps, list_from_file, load, loads, open __all__ = ['dump', 'dumps', 'list_from_file', 'load', 'loads', 'open']
"""SELU Activation Function""" from torch.nn import SELU as _SELU from neuralpy.utils import CustomLayer class SELU(CustomLayer): """ SELU applies scaled exponential linear units to input tensors For more information, check https://pytorch.org/docs/stable/nn.html#selu Supported Arguments name...
import pandas as pd df = pd.read_csv('CFR_WorldData.csv') """ Pasar de: 1. Entity 2. Code 3. Date 4. Total confirmed deaths due to COVID-19 (deaths) 5. Total confirmed cases of COVID-19 (cases) a las siguientes tablas, una por pais 1. date 2. total cases 3. total deaths """ filt = d...
import unittest import os import foowise.test def additional_tests(): this_suite_path = os.path.abspath(__file__) test_dir = os.path.dirname(this_suite_path) loader = unittest.TestLoader() return loader.discover(test_dir, pattern='Test_*.py')
import binascii; """ def bin2hex(bin_prog): hex_prog = ""; j = 0; for i in range(int(len(bin_prog)/8)): hex_prog = hex_prog + (binascii.b2a_hex(bin_prog[(i*8)+4])); hex_prog = hex_prog + (binascii.b2a_hex(bin_prog[(i*8)+5])); hex_prog = hex_prog + (binascii.b2a_hex(bin_prog[(i*8)+6])); hex_prog = hex_prog...
import cv2 import time import imutils cam=cv2.VideoCapture(0) time.sleep(1) firstFrame=None area=500 while True: _,img=cam.read() text="Normal" img=imutils.resize(img,width=500) grayImg=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) gaussianImg=cv2.GaussianBlur(grayImg,(21,21),0) if f...
from algorithms import * from utils import DataUtils if __name__ == '__main__': logging.basicConfig(level=logging.INFO) data = DataUtils('data/基站经纬度.csv', 'data/上网信息输出表(日表)6月15号之后.csv') mip_placer = MIPServerPlacer(data.base_stations, data.distances) mip_placer.place_server(10, 2) print(mip_placer...
#!/usr/bin/env python from setuptools import find_packages from distutils.core import setup version = {} with open('src/version.py', 'r') as fp: exec(fp.read(), version) with open('requirements.txt', 'r') as fp: required = fp.read().splitlines() with open('README.md', 'r') as fh: long_description = fh.r...
from convs.condconv import * from convs.cc_inf import * from convs.dyconv import * from convs.dyres_conv import * from convs.dyres_inf import * from convs.ddsnet import * from convs.dds_exp import * from convs.dychannel import * from flops_counter import get_model_complexity_info import torch x = torch.randn(1, 16, 3...
from pyroot_easiroc.MuonTrackReconstructor import MuonTrackReconstructor from tqdm import tqdm rootfile_path = "/data/hamada/easiroc_data/run017.root" threshold_s = [1200] * 64 mtr = MuonTrackReconstructor(rootfile_path, threshold_s) mtr._pre_cut_threshold_layer() mtr._multi_hit() mtr._under_layer_limit() mtr.hit_muo...
import argparse import os import anndata import numpy as np import pandas as pd import scanpy as sc from scipy import sparse import trvae if not os.getcwd().endswith("tests"): os.chdir("./tests") from matplotlib import pyplot as plt FASHION_MNIST_CLASS_DICT = { 0: "T-shirt or top", 1: "Trouser", 2:...
"""Qt windows for camera controlled labeling Colin Dietrich 2019 """ from functools import partial from PyQt5 import QtGui, QtCore from PyQt5.QtWidgets import QWidget, QApplication # import everything, since it's hard to remember what class does what from PyQt5.QtWidgets import QMainWindow,\ QApplication,...
''' Created on Feb 8, 2016 @author: hanhanwu ''' import math import load_match_data import preprocess_data def sumsqures(v): return sum([p**2 for p in v]) # radial-basis function, used as a kernel to get best linear separation for a given data set with proper adjustments def rbf(v1, v2, gamma=20): dv = [v1[i...
#!/usr/bin/env python3 from collections import namedtuple import contextlib import io import json import logging import os from pathlib import Path import shlex import signal import subprocess import sys import tempfile import uuid import zmq from .simplesetup import RemoteTeamPlayer, SimpleController, SimplePublish...
name = input("What's your name?") old = input("How old are u?") live = input("Where are u from?") print("This is:", name) print("It is:", old) print("She(he) lives in:", live)
from __future__ import annotations from spark_auto_mapper_fhir.fhir_types.uri import FhirUri from spark_auto_mapper_fhir.value_sets.generic_type import GenericTypeCode from spark_auto_mapper.type_definitions.defined_types import AutoMapperTextInputType # This file is auto-generated by generate_classes so do not edi...
import sys from PyQt5 import QtWidgets, QtGui def window(): app = QtWidgets.QApplication(sys.argv) w = QtWidgets.QWidget() l1 = QtWidgets.QLabel(w) l2 = QtWidgets.QLabel(w) l1.setText('this is a test') l2.setPixmap(QtGui.QPixmap('../resources/lab-badge.png')) w.setWindowTitle('ImageAlign...
import os, sys import yaml import logging import click from voluptuous import Schema from .defaults import settings from .validators import SchemaCheck from .config_utils import process_config from .exceptions import * from .utils import * from .indexlist import IndexList from .snapshotlist import SnapshotList from .ac...
# # PySNMP MIB module JUNIPER-JS-DNS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/JUNIPER-JS-DNS-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:59:32 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, ...
from sklearn.feature_extraction.text import TfidfVectorizer from mosestokenizer import MosesDetokenizer from nltk.corpus import stopwords #open to file in this directory f1= open('/home/shuchita-rahman/Documents/thesis/f1', 'r') f2= open('/home/shuchita-rahman/Documents/thesis/f2', 'r') #put file data in data variabl...
frase = (input('Digite uma frase: ').upper().strip()) print('Sua frase tem {} letras A'.format(frase.count('A'))) print('A primeira letra A está na posição: {}'.format(frase.find('A')+1)) print('A última letra A está na posição: {}'.format(frase.rfind('A')+1))
# 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 by applicable law or agreed to in...
# 띄어쓰기, 들여쓰기 꼭 확인하세요! # answer와 같은 형태가 되도록 string1, string2, string3를 수정하고 조합해주세요! answer = "3/29은 NEXT 세션하는 날!" string1 = "2021-03-29은 " string2 = "next" string3 = " 세션하는 날! " string1 = string1.replace("2021-0", "").replace("-", "/") string2 = string2.upper() string3 = string3.strip() string = string1 +...
import socket from six.moves.urllib.parse import urlparse from frappe import get_conf config = get_conf() REDIS_KEYS = ('redis_cache', 'redis_queue', 'redis_socketio') def is_open(ip, port, timeout=10): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(timeout) try: s.connect((ip, int(port))) ...
from torch import nn from pystiche.image import CaffePreprocessing, TorchPreprocessing PREPROCESSORS = {"torch": TorchPreprocessing, "caffe": CaffePreprocessing} __all__ = ["get_preprocessor"] def get_preprocessor(framework: str) -> nn.Module: return PREPROCESSORS[framework]()
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012, Red Hat, 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 # ...
import sys from io import StringIO from contextlib import contextmanager @contextmanager def capture_output(): ''' Context manager to capture stdout and stderr. Captures stddout and stderr from a Python code section, using two StringIO objects. Example:: with capture_output() as (out, err...
def file(path:str, operation:str = 'r'): with open(path, operation) as f: return f.read()
import pygame import sys from definitions import * from gameParameters import backgroundImage, gameDisplay, display_width, \ display_height, clock class Button: """Class for rectangular buttons Args: location (tuple, int): Defines self.x, self.y width (int, default=80): Defines self._widt...
from dataclasses import dataclass from typing import List from omegaconf import DictConfig @dataclass class Data: name: str num_classes: int root: str @dataclass class Logger: name: str save_dir: str @dataclass class Preprocess: horizontal_flip: bool horizontal_flip_rate: float ra...
import logging import sys import warnings import numpy as np import pytest import rasterio from rasterio.enums import MaskFlags from rasterio.errors import NodataShadowWarning, RasterioDeprecationWarning @pytest.fixture(scope='function') def tiffs(tmpdir): with rasterio.open('tests/data/RGB.byte.tif') as src: ...
import tensorflow as tf from sklearn.utils import shuffle import pickle as pkl import datetime import numpy as np import os from utils import initialize_uninitialized, batch_retrieve class BNN(object): def __init__(self, sess, checkpoint_dir, log_dir, x_dim, y_dim, num_models, n_data, ...
from empire.python.typings import * from empire.enums.base_enum import BaseEnum class TemperatureStates(BaseEnum): NORMAL: Final[str] = 'normal' HIGH: Final[str] = 'high' CRITICAL: Final[str] = 'critical' UNKNOWN: Final[str] = 'unknown'
from .nodes import Node, Producer, Consumer, SynchronousConsumer from .utils import connect, start, stop from .queues import Queue
########################################################################## # # pgAdmin 4 - PostgreSQL Tools # # Copyright (C) 2013 - 2020, The pgAdmin Development Team # This software is released under the PostgreSQL Licence # ########################################################################## import json from...
# encoding = utf-8 ERROR_TEMPLATE = '''{"error_code": "%s", "error_msg": "%s", "reason": "%s"}''' class TraderError(Exception): ''' 交易错误和代码定义 ''' ERROR_CODE = '0' ERROR_MSG = 'Success' def __init__(self, reason): super(TraderError, self).__init__(ERROR_TEMPLATE % (self.ERROR_CODE, se...
from .dataset import Dataset from .dataset_group import DatasetGroup from .image import DockerImage from .image_config import DockerImageConfig from .image_relationship import DockerImageRelationship from .iteration import Iteration from .model import Model from .model_group import ModelGroup from .project import Proje...
import csv import os from flask import Flask, request, send_file, render_template, flash, redirect, url_for from io import BytesIO, StringIO from vpg.VoucherPrint import VoucherPrint import subprocess import mysql.connector from mysql.connector import errorcode import tempfile import itertools PDFJAM_BIN = "/usr/bin/...
# Copyright 2020 Google LLC. 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 by applicable law or a...
from time import sleep from userbot import CMD_HELP from userbot.events import register @register(outgoing=True, pattern='^.yins(?: |$)(.*)') async def typewriter(typew): typew.pattern_match.group(1) sleep(3) await typew.edit("`𝙃𝙖𝙞 𝙋𝙚𝙧𝙠𝙚𝙣𝙖𝙡𝙠𝙖𝙣 𝙉𝙖𝙢𝙖 𝙂𝙪𝙖 𝘼𝙮𝙞𝙞𝙣`") sleep(3) a...
from typing import Any, List import torch.nn as nn from torch import Tensor class BasicBlock(nn.Module): def __init__( self, in_channels: int, out_channels: int, kernel_size: int, stride: int, padding: int, use_batch_norm: bool = False ) -> None: ...
# The MIT License # # Copyright (c) 2017 Transact Pro. # # 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...
from smtplib import SMTPException from typing import Tuple, Optional, Dict from urllib.parse import urlencode from django import forms from django.utils.translation import gettext as _ from django.core.exceptions import ObjectDoesNotExist from django.core.mail import send_mail from django.template.loader import render...
""" Sonde check attempts to read each sonde file with netCDF4, error files are sent to a new directory. """ import glob import os import shutil import stat import netCDF4 files = glob.glob('/lustre/or-hydra/cades-arm/proj-shared/sgpsondewnpnC1.b1/*') for file in files: try: sonde = netCDF4.Dataset(file...
import ai from detect import detectar_resultado tabuleiro = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ' ] class JogadaInvalida(RuntimeError): pass def coordenada_esta_no_limite(c, texto): while (c < 0) or (c > 2): c = int(input('Digite o valor da '+ str(texto) + ': '...
"""Abstract graphs in ReGraph. This module contains abstract classes for graph objects in ReGraph. Such graph objects represent simple graphs with dictionary-like attributes on nodes and edges. """ import json import os import warnings from abc import ABC, abstractmethod from regraph.exceptions import (ReGraphError...
#对比ecl prt中trans结果与cloud trans结果,NNC要实用 'ALLNNC' ##参数 PRTPATH = r"C:\Users\shixi\Documents\newLandProj\zaoyuan\SimCases\C_project\C\C.PRT" CLOUDTRANSPATH=r"C:\Users\shixi\Desktop\trans.test" NX=71 NY=140 NZ=42 ##PRTPATH = r"C:\Users\shixi\Desktop\cases\ZhanJiang\BASE_newC\BASE_newC.PRT" ##CLOUDTRANSPATH=r"C:\User...
""" A test for the buttons on the mini-PiTFT display from adafruit. The code is based on an example on adafruit.com Note: Inside the while-loop, a sleep function is used to avoid 100% CPU usage. This is the because the script is run very fast and the loop is repeating continuously. Sleeping for 0.01s make not visible...
# Copyright 2020 The Oppia Authors. 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 by applicable ...
class ContextError(Exception): """ Top-level error handling all context problems. """ def __init__(self): Exception.__init__(self, 'General run context error') class ContextRegistrationError(RuntimeError): pass class ContextAlreadyRegisteredError(ContextRegistrationError): def __in...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt import seaborn as sns import pandas as pd from sepia.DataContainer import DataContainer sns.set() class SepiaData(object): """ Data object used for SepiaModel, containing potentially both `sim_data` and `obs_...
import sys from django.contrib.auth import get_user_model from django.contrib.auth.models import Group from django.core.management.base import BaseCommand from core.utils import create_temporary_password from ...utils import ensure_group_exists, create_user, ensure_user_is_member_of_group, CrowdError def dot(ch='....
import numpy as np from helper_class1.data_reader import DataReader from helper_class1.hyper_parameters import HyperParameters from helper_class1.neural_net import NeuralNet from matplotlib import pyplot as plt file_name = '../../../ai-edu/A-基础教程/A2-神经网络基本原理简明教程/data/ch04.npz' data_reader = DataReader(file_na...
#!/usr/bin/env python from sys import stdin def main(): m = int(stdin.readline()) dom = {} count = [0]*7 for i in range(7): for j in range(7): if i != j: dom[i, j] = [] for i in range(m): j, k = stdin.readline().split() j, k = int(j), int(k) count[j] += 1 count[k] += 1 dom[j, k...
from rest_framework.permissions import BasePermission from cride.circles.models import Membership class isCircleAdmin(BasePermission): def has_object_permission(self, request, view, obj): """verify user have a membership in the obj Args: request ([type]): [description] ...
from csrv.model import actions from csrv.model import timing_phases from csrv.model.cards import asset from csrv.model.cards import card_info class YesCard01087(actions.Action): DESCRIPTION = 'Give the runner tags' def __init__(self, game, player, advancements): self.advancements = advancements def resolv...