text
stringlengths
2
999k
# -*- coding: utf-8 -*- from .base import BaseStorageBackend from django.db import transaction from kaggregate.models import KAggregate import datetime class StorageBackend(BaseStorageBackend): @transaction.commit_on_success def save(self, key, value): try: instance = KAggregate.objects.g...
import argparse import configparser import os import sys import time root_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))) sys.path.append(root_dir) import torch from tatk.nlg.sclstm.multiwoz.loader.dataset_woz import DatasetWoz, SimpleDatasetWoz from ...
#!/usr/bin/env python3 """setuptools installer script for TerraPi.""" import os import platform import shutil import sys from subprocess import call from distutils.cmd import Command from distutils.util import execute from setuptools.command.install import install from setuptools import setup, find_packages class ...
""" This file contains various constants in use by yap-midi. """ MAX_INT_VALUE = 128 # ----------------------- # MIDI Event Constants: # ----------------------- # --== Channel Messages: ==-- NOTE_ON = 0x90 NOTE_OFF = 0x80 POLY_AFTERTOUCH = 0xA0 PROGRAM_CHANGE = 0xC0 AFTER_TOUCH = 0xD0 PITCH_BEND = 0xE0 CONTROL_CHA...
# # Copyright 2021 Ocean Protocol Foundation # SPDX-License-Identifier: Apache-2.0 # import configparser import logging from flask import jsonify from flask_swagger import swagger from flask_swagger_ui import get_swaggerui_blueprint from ocean_provider.config import Config from ocean_provider.constants import BaseUR...
#!/usr/bin/env python3 """ Main window helper """ import os from PyQt5 import QtWidgets, uic class MainDisplay(QtWidgets.QWidget): """ Main window class """ def __init__(self, *args): """ Initialize the MainDisplay container widget. Provides a passthrough to underlying widge...
""" This module defines a domain language for the QuaRel dataset, a simple domain theory for reasoning about qualitative relations. """ from typing import Callable from allennlp.semparse.domain_languages.domain_language import DomainLanguage, predicate class Property: def __init__(self, name: str) -> None: ...
# -*- coding: utf-8 -*- """Plotter. - Author: Junghoon Kim - Email: jhkim@jmarple.ai """ import os from typing import List, NamedTuple, Sequence, Tuple, Union import PIL.Image import matplotlib.axes import matplotlib.pyplot as plt from matplotlib.ticker import FixedLocator import numpy as np import torch import torc...
from datetime import datetime import pytest from pandas import DatetimeIndex import pandas.util.testing as tm from pandas.tseries.holiday import ( AbstractHolidayCalendar, Holiday, Timestamp, USFederalHolidayCalendar, USThanksgivingDay, get_calendar, ) @pytest.mark.parametrize( "transfo...
from config import * from StringStats import stringstats as stats from FTDHandler import ftdhandler as txt def reset_file(): with open(FREQUENCY_FILE, 'w') as file: file.write("") def general_stats(text): words_count = stats.stringstats.words_count(text) characters_count = len(text) general_stats = "There...
from modules.agents import REGISTRY as agent_REGISTRY from components.action_selectors import REGISTRY as action_REGISTRY import torch as th # This multi-agent controller shares parameters between agents class BasicMAC: def __init__(self, scheme, groups, args): self.n_agents = args.n_agents self.a...
import torch.nn as nn import math __all__ = [ 'VGG', 'vgg13', ] class VGG(nn.Module): def __init__(self, features, num_classes=10): super(VGG, self).__init__() self.features = features self.classifier = nn.Sequential( nn.Linear(512, 512), nn.ReLU(True), ...
# 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 # d...
import argparse import gzip import numpy as np import os import tensorflow as tf from six.moves.urllib.request import urlretrieve # Polyaxon from polyaxon.tracking import Run ACTIVATIONS = { 'relu': tf.nn.relu, 'sigmoid': tf.sigmoid, 'tanh': tf.tanh, } OPTIMIZERS = { 'gradient_descent': tf.train.Gra...
from gazette.spiders.base import FecamGazetteSpider class ScBeneditoNovoSpider(FecamGazetteSpider): name = "sc_benedito_novo" FECAM_QUERY = "cod_entidade:39" TERRITORY_ID = "4202206"
''' mailSpamFilterCN.py:用于中文垃圾邮件分类,采用 Naive Bayes 方法 Author:HeRaNO ''' # coding: utf-8 import re import sys import math import jieba import pandas as pd def readContent(path): with open(path, 'r', encoding = 'gbk', errors = 'ignore') as f: l = f.readlines() l = filter(lambda line: line != '\n', l) return ''.j...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Configuration file for the Sphinx documentation builder. # # This file does only contain a selection of the most common options. For a # full list see the documentation: # http://www.sphinx-doc.org/en/master/config # -- Path setup ---------------------------------------...
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If ex...
# 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...
import unittest from functools import partial from mock import patch from pathlib import Path import cv2 from PyQt5.QtWidgets import QMessageBox from inselect.lib.templates.dwc import DWC from inselect.tests.utils import temp_directory_with_files from .gui_test import GUITest TESTDATA = Path(__file__).parent.par...
import json import boto3 from botocore.exceptions import ClientError import base64 def sendSQSMessage(sqsQueueURL, body): """ :param sqsQueueURL: String URL of existing SQS queue :param body: String message body :return: Dictionary containing information about the sent message. If error, retu...
from configuration import DatasetName, WflwConf, W300Conf, DatasetType, LearningConfig, InputDataSize import tensorflow as tf import cv2 import os.path import scipy.io as sio from cnn_model import CNNModel from tqdm import tqdm import numpy as np from os import listdir from os.path import isfile, join from scipy.integ...
""" WorldModelCapsule ^^^^^^^^^^^^^^^^^^ Provides information about the world model. """ import math import ros_numpy import numpy as np from scipy.ndimage import gaussian_filter import matplotlib.pyplot as plt from scipy.interpolate import griddata from PIL import Image, ImageDraw import rospy import tf2_ros as tf2 ...
### FROM http://pythontesting.net/framework/doctest/doctest-introduction/#example ''' Module showing how doctests can be included with source code Each '>>>' line is run as if in a python shell, and counts as a test. The next line, if not '>>>' is the expected output of the previous line. If anything doesn't match exa...
# ----------------------------------------------------------------------------- # Copyright (c) 2014--, The Qiita Development Team. # # Distributed under the terms of the BSD 3-clause License. # # The full license is in the file LICENSE, distributed with this software. # ------------------------------------------------...
from math import ceil import torch from torch import nn, einsum import torch.nn.functional as F from einops import rearrange, repeat from einops.layers.torch import Rearrange # helpers def exists(val): return val is not None def default(val, d): return val if exists(val) else d def cast_tuple(val, l = 3):...
import re class Mod: def __init__(self, bot): self.log = bot.log self.bot = bot self.role = bot.config.admin_role self.bad_words = bot.config.bad_words async def on_message_edit(self, before, after): await self.on_message(after) async def on_message(self, message)...
from colors import ColorsCorpusReader import os import pandas as pd from sklearn.model_selection import train_test_split import torch from torch_color_describer import ( ContextualColorDescriber, create_example_dataset, Encoder, Decoder, EncoderDecoder) import utils import torch.nn as nn from utils impo...
import unittest from commands.urban_search import UrbanSearchCommand class TestUrbanSearchCommand(unittest.TestCase): def test_empty_input(self): command = UrbanSearchCommand() result = command.execute('') self.assertIsNone(result) def test_garbage_input(self): co...
from asservicescanners.abstractscanner import AbstractBannerScrapeScanner from asservicescanners.serviceutils import FTP_PORT, FTP_SCRIPT, launch_script_without_terminal, format_script_args from aslogging import aslog class FTPScanner(AbstractBannerScrapeScanner): def __init__(self, ip, output_dir): supe...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from . import __version__ as app_version app_name = "slick" app_title = "Slick" app_publisher = "Vinay Yadav" app_description = "Application for handling custom workflows" app_icon = "octicon octicon-file-directory" app_color = "green" app_email = "info@s...
# Import batman, for lightcurve models: import batman # Try to import catwoman: try: import catwoman have_catwoman = True except: have_catwoman = False # Import radvel, for RV models: import radvel # Import george for detrending: try: import george except: print( 'Warning: no george install...
import torch.nn as nn """ Convert word indexes to embeddings. Pack padded batch of sequences for RNN module. Forward pass through GRU. Unpack padding. Sum bidirectional GRU outputs. Return output and final hidden state. """ class EncoderRNN(nn.Module): def __init__(self, hidden_size, embedding, n_layers=1, dropou...
#!/usr/bin/env python from generate_example_from_schema import ExampleFileGenerator import jinja2 import json from jsonschema import validate, ValidationError import os import sys DEBUG = False SCHEMAS_DIRECTORY = "schemas" DEPLOYMENTS_DIRECTORY = "deployments" CONTAINER_MOUNT_DIRECTORY = "/metroae_data/deployments"...
# Copyright 2019 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...
# -*- coding: utf-8 -*- from __future__ import print_function from __future__ import unicode_literals from __future__ import division from builtins import str, bytes, dict, int from builtins import map, zip, filter from builtins import object, range from io import open import os import sys sys.path.insert(0, os.pat...
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import py...
# https://leetcode.com/problems/serialize-and-deserialize-binary-tree/ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Codec: def serialize(self, root): """Encodes a tree to a s...
# -*- coding: utf-8 -*- """ Script Name: Author: Do Trinh/Jimmy - 3D artist. Description: """ # ------------------------------------------------------------------------------------------------------------- """ Import """ from PySide2.QtWidgets import QDateEdit class DateEdit(QDateEdit): key = 'DateEdit' ...
#Run this file to create a model to be used in Rust import tensorflow as tf from tensorflow.keras.layers import Dense #Define a custom keras model class custom_model(tf.keras.Model): def __init__(self, *args, **kwargs): super(custom_model, self).__init__(*args, **kwargs) self.dense_1 = Dense(2, ...
from __future__ import absolute_import, division, print_function from io import BytesIO import math import os import timeit import dask import dask.bag as db import numpy as np from PIL.Image import fromarray __all__ = ['render_tiles', 'MercatorTileDefinition'] # helpers ---------------------------------------...
from django.urls import path from platforma.platforma import views urlpatterns = [ path("", views.get_rss_feed, name="platforma_home"), path("update/", views.update_local_endpoint, name="register_for_assignment"), path("combined/", views.get_combined_rss_feed, name="combined_feed"), path( "rem...
from turtle import Turtle START_POSITION = (0,-280) DISTANCE_MOVE = 10 FINISH_LINE = 200 class Player(Turtle): def __init__(self): super().__init__() self.shape("turtle") self.penup() self.go_to_start() self.setheading(90) def go_up(self): self.forward(DISTANCE_MOVE) def go_down(sel...
from rest_framework import serializers from .models import Choice, Question class ChoiceSerializer(serializers.ModelSerializer): class Meta: model = Choice fields = '__all__' class QuestionSerializer(serializers.ModelSerializer): choices = ChoiceSerializer(many=True, required=False) cla...
# # Copyright 2013 eNovance <licensing@enovance.com> # # Authors: Mehdi Abaakouk <mehdi.abaakouk@enovance.com> # # 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/l...
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: # pylint: disable=no-member r""" MRIQC: image quality metrics for functional MRI. Measures for the spatial information ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Definitions are given in the :ref:`summary of st...
import datetime from typing import Text from django.db import models from zerver.models import AbstractPushDeviceToken, Realm def get_remote_server_by_uuid(uuid: Text) -> 'RemoteZulipServer': return RemoteZulipServer.objects.get(uuid=uuid) class RemoteZulipServer(models.Model): uuid = models.CharField(max_l...
# Copyright 2017 The TensorFlow 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 applica...
#!/usr/bin/env python # _*_ coding:utf-8 _*_ import logging import os import xmind2xls.const from io import BytesIO from xml.dom import minidom from xml.sax.saxutils import escape from .parser import config from .utils import get_xmind_testsuites, get_absolute_path from xml.etree.ElementTree import Element, SubElement,...
from __future__ import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'digit.settings') app = Celery('core') # Using a string here means the worke...
""" Tuple Like list but they are immutable It means you can't change them """ my_list = [1, 2, 3] print(my_list) my_list[0] = 0 print(my_list) my_tuple = (1, 2, 3, 2, 2, 3) print(my_tuple) print(my_tuple[0]) print(my_tuple[1:]) print(my_tuple.index(2)) print(my_tuple.count(3))
from django.apps import AppConfig class ProposalsConfig(AppConfig): name = 'proposals' def ready(self): import proposals.signals
"""Base graph class specialized for neural networks on graphs.""" # pylint: disable=too-many-lines from __future__ import absolute_import from collections import defaultdict from contextlib import contextmanager from typing import Iterable from functools import wraps import networkx as nx import dgl from .base import...
import os import mock import pytest from six.moves import shlex_quote from mlflow.exceptions import ExecutionException from mlflow.projects._project_spec import EntryPoint from mlflow.utils.file_utils import TempDir, path_to_local_file_uri from tests.projects.utils import load_project, TEST_PROJECT_DIR def test_ent...
from requests import get import time from datetime import datetime def cmd(self, user, channel, args): def url(arg): return f"https://api.twitch.tv/kraken/{arg}" headers = {"Client-ID": self.CLIENT_ID, "Authorization": f"OAuth {self.SETUP.startup()['token']}", "Accept": "application/v...
# -*- coding: utf-8 -*- # Copyright (c) 2020 Nekokatt # # 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, me...
import bpy from bpy.props import * from bpy.types import Node, NodeSocket from arm.logicnode.arm_nodes import * class TimeNode(Node, ArmLogicTreeNode): '''Time node''' bl_idname = 'LNTimeNode' bl_label = 'Time' bl_icon = 'TIME' def init(self, context): self.outputs.new('NodeSocketFloat...
# encoding: utf-8 # module System.Windows.Annotations.Storage calls itself Storage # from PresentationFramework,Version=4.0.0.0,Culture=neutral,PublicKeyToken=31bf3856ad364e35 # by generator 1.145 """ NamespaceTracker represent a CLS namespace. """ # no imports # no functions # classes class AnnotationStore...
# # 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 # "License"); you may not...
# Crie um programa que leia dois números e mostre a soma entre eles. n1 = int(input('Digite um número: ')) n2 = int(input('Digite mais um número: ')) s = n1 + n2 print('A soma vale', s) # ou print('-'*20) print('A soma entre {} e {} é igual a {}'.format(n1, n2, s))
import time import os def main(input_filename: str): # Generated by generate_files.py on Wed Nov 17 2021 # Return value of -1 is used to signal that this isn't implemented. # Once it is, remove/replace that return (implicitly returning None is fine). return -1 if __name__ == "__main__": os.chdi...
"""cinnamon-udev-locker - Lock Cinnamon desktop session on device removal (i.e YubiKey)""" __version__ = '0.0.0' __author__ = 'Michael Fladischer <michael@fladi.at>' __all__ = []
from typing import Optional import discord from discord.ext import commands from litebot.core import Cog, Context from litebot.utils.tracking_model import TrackedEvent from litebot.utils import embeds from litebot.utils.menus import ConfirmMenu, CONFIRM_YES from plugins.standard.discord_utils.archives.archived_chann...
import numpy as np #==================================================================================================== def Gaussian(p, x): '''Gaussian function''' #kw.get('sigma') #kw.get('mean') #kw.get('amplitude') A, b, mx = p return A * np.exp(-b * (x-mx)**2) def Gaussian2D(p, x, y): ...
import json import os import subprocess import sys from mro_migrator import cli import pytest @pytest.mark.skipif(sys.platform == "darwin", reason="there is no MRO on osx") def test_convert_env(testing_workdir): env_path = os.path.join(testing_workdir, 'env') args = ['conda', 'create', '-yp', env_path, 'mro-...
#Filename: baseCF.py #Author: Wang Yongjie #Email: yongjie.wang@ntu.edu.sg #Date: Sen 14 Des 2020 03:43:39 WIB import numpy as np class ExplainerBase(object): def __init__(self, data_interface, model_interface): self.data_interface = data_interface self.model_interface = model_interface ...
from api import tasks def run(): """ fab command:cmd="runscript backups" """ tasks.backup_postgres(is_deploy=True)
"""Config tests from a string defining a default section""" # pylint: disable=redefined-outer-name # pylint: disable=missing-function-docstring import pytest from youconfigme import Config, ConfigItemNotFound @pytest.fixture def config_from_str_defs(): config_string = """[a] k1=1 k2=2 [b] k3=3 k4=4 """ ret...
from conans import ConanFile, Meson class RangConan(ConanFile): name = "rang" version = "3.2.0" license = "The Unlicense" url = "https://github.com/agauniyal/rang" description = "A Minimal, Header only Modern c++ library for colors in your terminal" generators = "pkg_config" build_requires...
from django.apps import AppConfig from django.utils.translation import gettext_lazy as _ class UsersConfig(AppConfig): name = "sarkasmus.users" verbose_name = _("Users") def ready(self): try: import sarkasmus.users.signals # noqa F401 except ImportError: pass
from django.db import models from django.contrib.auth.models import User class Donor(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_pic = models.ImageField(upload_to='profile_pic/Donor/', null=True, blank=True, default='profile_pic/Donor/default.png') bloodgroup = model...
# Generated by Django 3.0.8 on 2020-07-27 17:29 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Results', fields=[ ('id', models.AutoField(...
project = "Linee guida operative per la fruizione dei servizi SPID da parte dei minori" docs_italia_theme = __import__("docs-italia-theme") html_theme = "docs_italia_theme" html_theme_path = [docs_italia_theme.get_html_theme_path()] html_title = project master_doc = "index" exclude_patterns = [ ".venv*", ".t...
from random import choice, randint class Board: def __init__(self): self.squares = [[None, None, None], [None, None, None], [None, None, None]] self.free_squares = [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), ...
""" Python Character Mapping Codec mac_roman generated z 'MAPPINGS/VENDORS/APPLE/ROMAN.TXT' przy gencodec.py. """#" zaimportuj codecs ### Codec APIs klasa Codec(codecs.Codec): def encode(self,input,errors='strict'): zwróć codecs.charmap_encode(input,errors,encoding_table) def decode(self,input,err...
import re import string import pandas as pd import swifter from Sastrawi.Stemmer.StemmerFactory import StemmerFactory import nltk from nltk.corpus import stopwords from nltk.tokenize import word_tokenize from django import template from django.template.defaultfilters import stringfilter nltk.download('stopwords') nltk...
import itertools import json import pkgutil import re from jsonschema.compat import MutableMapping, str_types, urlsplit class URIDict(MutableMapping): """ Dictionary which uses normalized URIs as keys. """ def normalize(self, uri): return urlsplit(uri).geturl() def __init__(self, *args...
import os ROOT_PATH = os.path.abspath(os.path.dirname(__file__)) #Directories LAYOUT_DIR = os.path.join(ROOT_PATH, 'layout') CONTENT_DIR = os.path.join(ROOT_PATH, 'content') MEDIA_DIR = os.path.join(ROOT_PATH, 'media') DEPLOY_DIR = os.path.join(ROOT_PATH, 'deploy') TMP_DIR = os.path.join(ROOT_PATH, 'deploy_tmp') BAC...
import numpy as np def batch_items(items): if isinstance(items[0], tuple): return tuple(map(batch_items, zip(*items))) elif isinstance(items[0], list): return list(map(batch_items, zip(*items))) else: return np.stack(items) def split_batched_items(items, axis = 0): if isinst...
#! /usr/bin/env python # Copyright (c) 2015, The Linux Foundation. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # not...
"""Setup Tensorflow TTS libarary.""" import os import pip import sys from distutils.version import LooseVersion from setuptools import find_packages from setuptools import setup if LooseVersion(sys.version) < LooseVersion("3.6"): raise RuntimeError( "Tensorflow TTS requires python >= 3.6, " "but ...
from orator.seeds import Seeder class DatabaseSeeder(Seeder): def run(self): """ Run the database seeds. """ pass
""" All ActiGamma exception definitions """ class ActiGammaException(Exception): """ Base exception for all ActiGamma exceptions """ class AbstractClassException(ActiGammaException): """ Exception for all intantiating abstract classes """ class UnphysicalValueException(ActiGamm...
# PsykoDev import os import sqlite3 def set_sql_connect(database_name): return sqlite3.connect(database_name) def set_sql_cursor(database_connect): return database_connect.cursor() def close_connect(vt): if vt: vt.commit() vt.close def set_connect_and_cursor(path='Data/database.sqlite'): ...
import json import logging import random from rest_framework.exceptions import ValidationError import metagov.core.plugin_decorators as Registry import requests from metagov.core.errors import PluginErrorInternal from metagov.core.models import GovernanceProcess, Plugin, ProcessStatus, AuthType logger = logging.getLo...
# -*- coding: utf-8 -*- # Copyright 2018 IBM. # # 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 agre...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ ampere_read.py -------------- This module reads in netCDF files from AMPERE Satellite constellation and converts them into regular data matrices to compare with SWMF-RIM. Created on Tue Jun 5 15:35:01 2018 Last Update on Wed Sep 23 16:52:40 2020 @author: Agnit Mukh...
import argparse import sys import click from pdm.cli import actions from pdm.cli.commands.base import BaseCommand from pdm.cli.options import sections_group from pdm.cli.utils import compatible_dev_flag from pdm.project import Project class Command(BaseCommand): """Install dependencies from lock file""" de...
from flask import Flask, render_template, redirect, url_for, request, flash import numpy as np import pandas as pd import matplotlib.pyplot as plt import statistics as s import base64 from io import BytesIO from matplotlib.figure import Figure app = Flask(__name__) def geometrik(self): geo = self[0] for i in ...
# -*- coding: utf-8 -*- # Copyright 2013 Google 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 requir...
# encoding: utf-8 import numpy as np import os import torch from PIL import Image import matplotlib.pyplot as plt from trainers.re_ranking import re_ranking as re_ranking_func class ResNetEvaluator: def __init__(self, model): self.model = model def save_incorrect_pairs(self, distmat, queryloader, ga...
#!/usr/bin/env python # -*- coding: utf-8 -*- import simplejson as json from alipay.aop.api.response.AlipayResponse import AlipayResponse from alipay.aop.api.domain.RelationInfo import RelationInfo class ZhimaCreditRelationQueryResponse(AlipayResponse): def __init__(self): super(ZhimaCreditRelationQuery...
show_progress_bars = True default_n_jobs = -1 def enable_progress_bars(): global show_progress_bars show_progress_bars = True def disable_progress_bars(): global show_progress_bars show_progress_bars = False def set_default_n_jobs(n_jobs: int) -> None: global default_n_jobs default_n_jobs ...
#!/usr/bin/env python # 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...
import pandas as pd df = pd.read_csv("./Reviews.csv", encoding='utf-8') df.drop_duplicates(keep='first', inplace=True) # 去重,只保留第一次出现的样本 # print(df.shape) # (568454, 10) # columns = df.columns.values # ['Id' 'ProductId' 'UserId' 'ProfileName' 'HelpfulnessNumerator' 'HelpfulnessDenominator' 'Score' 'Time' 'Summary' '...
import collections.abc import dataclasses import enum import math import operator import sys import unittest from typing import * from crosshair.libimpl.builtinslib import ( SymbolicArrayBasedUniformTuple, SymbolicByteArray, SymbolicBytes, SymbolicFrozenSet, SymbolicType, ) from crosshair.libimpl.b...
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors. # # 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 ...
import sys BASIC_DATA_TYPE = (int, str, float) BASIC_DATA_TYPE_BOOL = (bool) TYPE_BASIC = "type_basic" TYPE_BOOL = "type_bool" TYPE_OBJECT = "type_object" TYPE_LIST = "type_list" TYPE_DICT = "type_dict" TYPE_UNDEFINED = "type_undefined" class TypeCheck: @staticmethod def is_list(obj): return type(ob...
from django.shortcuts import render, get_object_or_404 from auth.helpers import authorized_user from boards.models import Board, BoardBlock, BoardFeed def index(request): boards = Board.objects.filter(is_visible=True).all() return render(request, "index.html", { "boards": boards }) def board(re...
import os import shutil from distutils.dir_util import copy_tree from setuptools import find_packages, setup # global variables package_name = 'rfsoc_freqplan' pip_name = 'rfsoc-freqplan' data_files = ['info.html'] # heroku setup if os.path.isfile('Procfile'): # heroku variables requirements = ['numpy>=1.19....