content
stringlengths
5
1.05M
import textwrap import uuid from multiprocessing import Pool from pprint import pprint import oyaml as yaml from cloudmesh.common.DateTime import DateTime from cloudmesh.common.console import Console from cloudmesh.configuration.Config import Config from cloudmesh.mongo.CmDatabase import CmDatabase from cloudmesh.mong...
import collections.abc import re import numpy as np import pandas as pd import torch import joblib import os from pathlib import Path from loguru import logger from sklearn.model_selection import train_test_split from torch._six import string_classes, int_classes from ivadomed import utils as imed_utils from ivadomed.k...
""" tunning, featuralization, output formatting """ import numpy as np import time def functionongraph(graphs_, i, key='deg', edge_flag=False): # for graphs_[i], get the key-val distribution components = len(graphs_[i]); lis = [] for j in range(components): g = graphs_[i][j] try: ...
import discord from discord.ext import commands from discord.ext.commands.cooldowns import BucketType from .utils.video import run_command, video_size, has_audio from .utils.message import get_nearest, get_msg_video, get_msg_image, get_msg_video_or_img import tempfile import os import io from PIL import Image import ra...
# This file contain all routes of secretary #################################################################### # import #################################################################### from flask_restx import Resource, reqparse # to use Resource, that expose http request method from ...
from view import View from serialConnection import SerialConnection from PyQt5.QtWidgets import QApplication import time class Controller: def __init__(self, serialConnection, Instructions): self.serialConnection = serialConnection self.Instructions = Instructions self.samples = [] ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from configurable import Configurable #*************************************************************** class BaseOptimizer(Configurable...
# %% from sre_constants import error import pandas as pd import openpyxl as pxl from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions a...
import unittest from libpysal.examples import load_example import geopandas as gpd import numpy as np from segregation.aspatial import MultiRelativeDiversity class Multi_Relative_Diversity_Tester(unittest.TestCase): def test_Multi_Relative_Diversity(self): s_map = gpd.read_file(load_example("Sacramento1")...
#!/usr/bin/python # -*- coding: utf-8 -*- ### BEGIN LICENSE #Copyright (c) 2009 Eugene Kaznacheev <qetzal@gmail.com> #Copyright (c) 2013 Joshua Tasker <jtasker@gmail.com> #Permission is hereby granted, free of charge, to any person #obtaining a copy of this software and associated documentation #files (the "So...
#! /usr/bin/python3 from __future__ import unicode_literals # from _typeshed import NoneType import math import os import sys import datetime from typing import TextIO import python_magnetrun import numpy as np import matplotlib # print("matplotlib=", matplotlib.rcParams.keys()) matplotlib.rcParams['text.usetex'] = ...
import itertools import numpy as np import pytest from pyquil import Program from pyquil.gate_matrices import QUANTUM_GATES as GATES from pyquil.gates import * from pyquil.numpy_simulator import targeted_einsum, NumpyWavefunctionSimulator, \ all_bitstrings, targeted_tensordot, _term_expectation from pyquil.paulis...
from future.utils import iteritems from pandaharvester.harvestercore.plugin_base import PluginBase from pandaharvester.harvestermover import mover_utils # preparator plugin with RSE + no data motion class RseDirectPreparator(PluginBase): """The workflow for RseDirectPreparator is as follows. First panda makes a ...
''' Created on Jun 6, 2012 @author: kristof ''' import time import datetime import general_settings from twython import Twython from klout import KloutInfluence import tweeql.extras.sentiment import tweeql.extras.sentiment.analysis from pkg_resources import resource_filename from dateutil import parser import itertool...
import os import sys sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../../'))) from src.Utils.Point import Point from src.Utils.Vector import Vector from src.Utils.LinearEquation import LinearEquation import math """ This module regroups a lot of class definition that are basic encapsulat...
#!/usr/bin/env python import glob import yaml import sys import argparse import cparser import generator import json from clang.cindex import Index, CursorKind, Config import codecs import re import os from typing import List, Dict file_cache = {} rules = [ [r'@c\s+(\w+)', 'inlinecode'], [r'\s*[@\\]code(.*?...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Created by yetongxue<me@xander-ye.com> import socket client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect(('127.0.0.1', 8001)) while True: re_data = input() client.send(re_data.encode('utf8')) data = client.recv(1024) print(data...
from gym_nav.envs.nav_env import NavEnv from gym_nav.envs.multi_nav_env import MultiNavEnv
from .get_data import get_all_data, get_data_from_api from ..dict_as_attribute import DictAsObj as DictToObj class Items: states = {} countries = {} total = {} data = get_data_from_api() for entity in data: if 'Countries' == entity: countries.update(data[entity]) elif ...
# Copyright 2017, Google Inc. # 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 # notice, this list of conditions and the f...
#!/usr/bin/python3 """ Copyright 2018-2019 Firmin.Sun (fmsunyh@gmail.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/licenses/LICENSE-2.0 Unless required by applic...
import json from typing import Any import pytest from pydantic import BaseModel, ConfigError, NoneBytes, NoneStr, ValidationError, pretty_errors class UltraSimpleModel(BaseModel): a: float = ... b: int = 10 def test_ultra_simple_success(): m = UltraSimpleModel(a=10.2) assert m.a == 10.2 assert...
from accountancy.helpers import sort_multiple from nominals.models import NominalTransaction from vat.models import VatTransaction from cashbook.models import CashBookLine def create_lines(line_cls, header, lines): # DO WE NEED THIS? tmp = [] for i, line in enumerate(lines): line["line_no"] = i +...
import random from django.http import Http404, JsonResponse from django.shortcuts import render from .models import Tweet def home_view(request, *args, **kwargs): return render(request, "pages/home.html", context={}, status=200) def tweet_list_view(request, *args, **kwargs): qs = Tweet.objects.all() tw...
from models.db import db from models.post import Post from flask_restful import Resource from flask import request from sqlalchemy.orm import joinedload from resources.s3 import * class Posts(Resource): def get(self): posts = Post.find_all() return posts def post(self): data = request...
from .base import BaseAttack from .fgsm import FGSMAttack
""" rg_utils load helpers methods from python """ import pandas as pd import re import robustnessgym as rg from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score def update_pred(dp, model, dp_only=False): """ Updating data panel with model prediction""" model.predict_batch(dp, [...
# Generated by Django 3.0.7 on 2020-07-29 17:16 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('permafrost', '0012_auto_20200729_1710'), ('permafrost', '0015_auto_20200606_0042'), ] operations = [ ]
from flask import Flask app = Flask(__name__) def wrap_html(message): html = """ <html> <body> <div style='font-size:80px;'> <center> <image height="600" width="531" src="https://secure.meetupstatic.com/photos/event/2/a/a/3/600_452110915.jpeg"> ...
""" Every issue is reported as ``robocop.rules.Message`` object. It can be later printed or used by post-run reports. Output message format --------------------- Output message of rules can be defined with ``-f`` / ``--format`` argument. Default value:: "{source}:{line}:{col} [{severity}] {rule_id} {desc} ({name...
#! /usr/bin/env python # -*- coding: utf-8 -*- # # vim: fenc=utf-8 # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 # # """ File name: favorites.py Version: 0.1 Author: dhilipsiva <dhilipsiva@gmail.com> Date created: 2015-07-26 """ __author__ = "dhilipsiva" __status__ = "development" """ """ fmt = """ "%i" ...
__author__ = 'Pauli Salmenrinne' from setuptools import setup requires = [ ] setup( name='sarch2', version="1.1.0", description='Simple archiving solution', scripts=['bin/sarch2'], packages=['sarch2'], long_description=open('README.rst').read(), url='https://githu...
#!/usr/bin/python # # Copyright (c) 2012 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Recover duts. This module runs at system startup on Chromium OS test images. It runs through a set of hooks to keep a DUT from...
#-*-coding: utf8-*- import redis def connection(ip, port): r = redis.StrictRedis(host=ip, port=port, db=0) return r def add(r, query, suggestions): ''' :param query: string :param suggestions: {sug1:score1,sugg2:score2...} use SortedSet to store suggestions ''' r.zadd('suggestions',...
import sys import click from tabulate import tabulate from . import admin from ...session import Session from ..pretty import print_error @admin.command() @click.option('--status', default='RUNNING', type=click.Choice(['PREPARING', 'BUILDING', 'RUNNING', 'RESTARTING', ...
import io import time from typing import Optional, Tuple from rich.console import Console from rich.live import Live from rich.panel import Panel from rich.progress import ( BarColumn, DownloadColumn, FileSizeColumn, MofNCompleteColumn, Progress, ProgressColumn, SpinnerColumn, Task, ...
from django.apps import AppConfig class CapstoneConfig(AppConfig): name = 'capstone'
""" Iterative deepening Depth-first Search specialization of a generic search algorithm. """ from typing import Optional from search.algorithms.search import Node, SearchAlgorithm from search.space import Space from search.algorithms.dfs import DFS import time from math import sqrt, pi class IDDFS(DFS): """Iter...
from __clrclasses__.System import Comparison as _n_0_t_0 from __clrclasses__.System import ValueType as _n_0_t_1 from __clrclasses__.System import Predicate as _n_0_t_2 from __clrclasses__.System import Array as _n_0_t_3 from __clrclasses__.System import IDisposable as _n_0_t_4 from __clrclasses__.System import SystemE...
from pytorch.schedulers.imports import * from system.imports import * @accepts(dict, post_trace=True) @TraceFunction(trace_args=False, trace_rv=False) def load_scheduler(system_dict): learning_rate_scheduler = system_dict["local"]["learning_rate_scheduler"]; optimizer = system_dict["local"]["optimizer"]; ...
#!/usr/local/bin/python3 # A wrapper to test query v2 API # Advantage: directly replace the `query` variable with any SQL string # to run the test. In command line, the SQL has to be in one-line # to ensure nothing wrong, which is cumbersome. import subprocess import sys import os MY_ENV = os....
from sys import stdin def main(): for s in sorted(list(map(int, stdin.readline().strip())), reverse=True): print("", end="".join(str(s))) if __name__ == "__main__": main()
""" Description: Defines the QAOACustom and CircuitSamplerCustom classes that replace the qiskit QAOA and CircuitSampler classes respectively. It is more easily customised than qiskit's built in ones and includes a variety of helper methods. Author: Gary Mooney Adapted from Qiskit 0.26.2 documentation...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2017~2999 - cologler <skyoflw@gmail.com> # ---------- # # ---------- import os import importlib from .common import TypeMatcher for name in os.listdir(os.path.dirname(__file__)): if name.startswith('_') or not name.endswith('.py'): continue ...
# Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
# -*- coding: utf-8 -*- # MegEngine is Licensed under the Apache License, Version 2.0 (the "License") # # Copyright (c) 2014-2021 Megvii Inc. All rights reserved. # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTI...
import json import pathlib import os print("Please enter the input path to the filepath you want to use for Mistos") print("We will create a folder called 'Mistos' there. It contains your input and output directory") path = input() is_dir = False while is_dir == False: path = pathlib.Path(path) if path.is_di...
"Tests for presto.map" import unittest as ut from presto.map import System, Constellation, Region class TestMap(ut.TestCase): def test_map(self): "Basic map data functionality test" stacmon = System.by_name("Stacmon") self.assertTrue(stacmon) self.assertEqual(len(list(stacmon.nei...
import logging import smores.medkit as medkit failures = [] def rxnorm_ingredient(rxcui, expect): _return_check=False _med_key_check=None _ing_key_check=None _overall=False _failures=[] ingredients = medkit.get_ingredients(rxcui, 'RXNORM') if ingredients is not None: if len(ingredie...
# Generated by Django 2.1.3 on 2018-12-01 22:19 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Eprint_users', '0011_auto_20181130_0119'), ] operations = [ migrations.AlterField( model_name='profile', name='image...
#!/usr/bin/env python """ Loop over a list of blog post src filenames and generate a blog index markdown file. """ import sys import os.path from datetime import datetime from utils import parse_metadata POST_TEMPLATE = """ --- ## [{title}]({htmlname}) ### {subtitle} {description} _{datestr}_ | [Read more...]({...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.http import HttpResponse from django.shortcuts import render def home(request): """return HttpResponse('<h1>Hello, Welcome to this test</h1>')""" """Le chemin des templates est renseigne dans "DIRS" de "TEMPLATES" dans settings.py DONC P...
#!/usr/bin/env python # Copyright (c) 2013. Mark E. Madsen <mark@madsenlab.org> # # This work is licensed under the terms of the Apache Software License, Version 2.0. See the file LICENSE for details. """ Description here """ import logging as log import networkx as nx import madsenlab.axelrod.utils.configuration ...
#!/usr/bin/env python3 # coding:utf-8 class Solution: def maxInWindows(self, num, size): if num == []: return [] if len(num) < size: return [max(num)] res = [] queue = num[:size] res.append(max(queue)) for i in range(size, len(num)): ...
__all__=["greeters"] # *** # *** Use __init__.py to expose different parts of the submodules in the desired namespace # *** # *** Define what can be seen in the main "skeleton." namespace (as this is skeleton/__init__.py) like this: # from .greeters.fancy import * # now you can do: from skeleton import FancyHelloWo...
import iota_client # client will connect to testnet by default client = iota_client.Client() print(client.get_info())
from django.apps import AppConfig class SiteAdocaoConfig(AppConfig): name = 'site_adocao'
# Copyright 2019 Quantapix 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 l...
import aita if __name__ == "__main__": # Development, Testing, Production app = aita.create_app('Development') app.run()
import json from logging import root import os import warnings from skimage.color import rgb2lab, gray2rgb, rgba2rgb from skimage.util import img_as_float import numpy as np import numpy.typing as npt import torch from torch.utils.data import DataLoader import torch.optim as optim import torch.nn as nn from torch...
from functools import partial from PyQt5.QtCore import pyqtSignal, QTimer, Qt from PyQt5.QtWidgets import QInputDialog, QLabel, QVBoxLayout, QLineEdit, QWidget, QPushButton from electrum.i18n import _ from electrum.plugin import hook from electrum.wallet import Standard_Wallet from electrum.gui.qt.util import WindowM...
from data.scrapers import * import pandas as pd from wordcloud import WordCloud import matplotlib.pyplot as plt def model_run(model, freq='1111111', existing=None): scraper = model(freq) dfs = scraper.run() for df in dfs: existing.append(df) return existing def generate_wordcloud(text, year=...
import numpy as np from ..pakbase import Package class ModflowFlwob(Package): """ Head-dependent flow boundary Observation package class. Minimal working example that will be refactored in a future version. Parameters ---------- nqfb : int Number of cell groups for the hea...
# globals.py # Logic to get a list of the DBS instances available on DAS. # Currently hardcoding. There's probably a better way! instances = ['prod/global', 'prod/phys01', 'prod/phys02', 'prod/phys03', 'prod/caf']
from hashlib import sha1 from multiprocessing.dummy import Lock m_lock = Lock() z_lock = Lock() print(f"是否相等:{m_lock==z_lock}\n{m_lock}\n{z_lock}") # 地址不一样 m_code = hash(m_lock) z_code = hash(z_lock) print(f"是否相等:{m_code==z_code}\n{m_code}\n{z_code}") # 值一样 # Java可以使用:identityhashcode m_code = sha1(str(m_lock).enc...
import codecs import csv import json import os import random import sys directory = str(os.getcwd()) final_data = {"url": "http://10.10.0.112"} def getNumberRecords(): ''' Counts the number of username-password for admin.csv file Arguments: None Returns: number of username-pass...
# Copyright 2020 Yuhao Zhang and Arun Kumar. 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 app...
def ejercicio01MCM(): #Definir variables y otros print("--> EJERCICIO 01 <--") notaFinal=round(0.0) #Datos de entrada n1=float(input("Ingrese la 1ra nota: ")) n2=float(input("Ingrese la 2da nota: ")) n3=float(input("Ingrese la 2da nota: ")) n4=float(input("Ingrese la 4ta nota: ")) #Proceso notaFinal...
from __future__ import absolute_import from django.test import RequestFactory from exam import fixture from mock import patch from sentry.middleware.stats import RequestTimingMiddleware, add_request_metric_tags from sentry.testutils import TestCase from sentry.testutils.helpers.faux import Mock class RequestTimingM...
from django.conf.urls import url from django.urls import path from rest.quiklash import views from rest.push_the_buttons.views import PushTheButtonView urlpatterns = [ path('api/qa/game/start', views.QuicklashMainGame.as_view()), path('api/qa/question/new', views.QuiklashQuestionListView.as_view()), path('a...
# coding: utf-8 from __future__ import annotations from datetime import date, datetime # noqa: F401 import re # noqa: F401 from typing import Any, Dict, List, Optional # noqa: F401 from pydantic import AnyUrl, BaseModel, EmailStr, validator # noqa: F401 from acapy_wrapper.models.indy_proof_requested_proof_predic...
# Basic training configuration file from pathlib import Path from torchvision.transforms import RandomVerticalFlip, RandomHorizontalFlip, CenterCrop from torchvision.transforms import RandomApply, RandomAffine from torchvision.transforms import ToTensor, Normalize from common.dataset import get_test_data_loader SEED ...
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright 2021 Red Hat # GNU General Public License v3.0+ # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) """ The module file for nxos_bgp_global """ from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = """ modu...
print("merhaba") print("merhaba") print("merhaba") print("merhaba")
r""" Base class for polyhedra, part 6 Define methods related to plotting including affine hull projection. """ # **************************************************************************** # Copyright (C) 2008-2012 Marshall Hampton <hamptonio@gmail.com> # Copyright (C) 2011-2015 Volker Braun <vbraun.name...
import discord from discord.ext import commands import traceback import datetime import asyncio import random from datetime import datetime from storage import * pat_gifs = [ "https://cdn.discordapp.com/attachments/670153232039018516/674299983117156362/1edd1db645f55aa7f2923838b5afabfc863fc109_hq.gif", "https:/...
import Tkinter as tk import warnings VAR_TYPES = { int: tk.IntVar, float: tk.DoubleVar, str: tk.StringVar } class ParameterController(tk.Frame): def __init__(self,parent, key, value): tk.Frame.__init__(self, parent) self.value_type = type(value) self._var = VAR_TYPES[self.v...
import factory import factory.fuzzy from user.models import User from company.tests.factories import CompanyFactory class UserFactory(factory.django.DjangoModelFactory): sso_id = factory.Iterator(range(99999999)) name = factory.fuzzy.FuzzyText(length=12) company_email = factory.LazyAttribute( lam...
class Solution: def combine(self, n: int, k: int) -> List[List[int]]: # Using dfs to record all possible def dfs(nums, path=None, res=[]): if path is None: path = [] if len(path) == k: res += [path] return res for id...
from typing import Optional import requests from libgravatar import Gravatar from bs4 import BeautifulSoup def get_gravatar_image(email) -> Optional[str]: """Only will return a url if the user exists and is correct on gravatar, otherwise None""" g = Gravatar(email) profile_url = g.get_profile() res =...
patterns = ['you cannot perform this operation as root'] def match(command): if command.script_parts and command.script_parts[0] != 'sudo': return False for pattern in patterns: if pattern in command.output.lower(): return True return False def get_new_command(command): ...
import json import os from py2neo import Graph class GraphInstanceFactory: def __init__(self, config_file_path): """ init the graph factory by a config path. the config json file format example: [ { "server_name": "LocalHostServer", "se...
from datetime import datetime class mentions_self: nom = 'я'; gen = ['меня', 'себя']; dat = ['мне', 'себе'] acc = ['меня', 'себя']; ins = ['мной', 'собой']; abl = ['мне','себе'] class mentions_unknown: all = 'всех' him = 'его'; her = 'её'; it = 'это' they = 'их'; them = 'их'; us = 'нас' nam...
from flask import ( Blueprint, render_template, ) from sqlalchemy import desc, func, or_, text from .. import db from ..models import ( Video, Vote, GamePeriod, Reward, ) game = Blueprint( 'game', __name__, template_folder='templates' ) @game.route('/') def index(): q = """ ...
import torch import torch.nn.utils.rnn as rnn import numpy as np import pandas from torch.utils.data import Dataset from sklearn.preprocessing import LabelEncoder from parsers.spacy_wrapper import spacy_whitespace_parser as spacy_ws from common.symbols import SPACY_POS_TAGS import json import transformers from transfo...
# coding=utf-8 from selenium.webdriver.common.by import By from view_models import certification_services, sidebar, ss_system_parameters import re import time def test_ca_cs_details_view_cert(case, profile_class=None): ''' :param case: MainController object :param profile_class: string The fully qualifie...
#!/usr/bin/env python # -*- coding:utf-8 -*- # @Author: Niccolò Bonacchi # @Date: Thursday, January 31st 2019, 1:15:46 pm from pathlib import Path import argparse import ibllib.io.params as params import oneibl.params from alf.one_iblrig import create from poop_count import main as poop IBLRIG_DATA = Path().cwd().pare...
""" Flask-Limiter extension for rate limiting """ from ._version import get_versions __version__ = get_versions()['version'] del get_versions from .errors import ConfigurationError, RateLimitExceeded from .extension import Limiter, HEADERS
from foldrm import Classifier import numpy as np def acute(): attrs = ['a1', 'a2', 'a3', 'a4', 'a5', 'a6'] nums = ['a1'] model = Classifier(attrs=attrs, numeric=nums, label='label') data = model.load_data('data/acute/acute.csv') print('\n% acute dataset', np.shape(data)) return model, data de...
import tensorflow as tf # 本节主要讲 placeholder input1 = tf.placeholder(tf.float32) input2 = tf.placeholder(tf.float32) # 原教程中为 mul, 我使用的版本为 multiply output = tf.multiply(input1, input2) with tf.Session() as sess: print(sess.run(output, feed_dict={input1: [7.], input2: [2.]}))
'''Statistical tests for NDVars Common Attributes ----------------- The following attributes are always present. For ANOVA, they are lists with the corresponding items for different effects. t/f/... : NDVar Map of the statistical parameter. p_uncorrected : NDVar Map of uncorrected p values. p : NDVar | None ...
class SelectionSort: @staticmethod def sort(a): for i, v in enumerate(a): minimum = i j = i+1 while j < len(a): if a[j] < a[minimum]: minimum = j j += 1 tmp = a[i] a[i] = a[minimum] ...
# -*- coding: utf-8 -*- # @Time : 2019/1/18 15:40
# 정수를 저장하는 큐를 구현한 다음, 입력으로 주어지는 명령을 처리하는 프로그램을 작성하시오. # 명령은 총 여섯 가지이다. # push X: 정수 X를 큐에 넣는 연산이다. # pop: 큐에서 가장 앞에 있는 정수를 빼고, 그 수를 출력한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 출력한다. # size: 큐에 들어있는 정수의 개수를 출력한다. # empty: 큐가 비어있으면 1, 아니면 0을 출력한다. # front: 큐의 가장 앞에 있는 정수를 출력한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 출력한다. # back: 큐의 가장 뒤에 있는...
from clickhouse_orm import migrations from ..test_migrations import * operations = [migrations.AlterIndexes(ModelWithIndex2, reindex=True)]
from functools import partial import pytest from stp_core.loop.eventually import eventuallyAll from plenum.test import waits from plenum.test.helper import checkReqNack whitelist = ['discarding message'] class TestVerifier: @staticmethod def verify(operation): assert operation['amount'] <= 100, 'a...
import torch from torch import autograd def steptaker(data, critic, step, num_step = 1): """Applies gradient descent (GD) to data using critic Inputs - data; data to apply GD to - critic; critic to compute gradients of - step; how large of a step to take - num_step; how finely to discretize fl...
from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow import pickle import pprint import datefinder # What the program can access within Calendar # See more at https://developers.google.com/calendar/auth scopes = ["https://www.googleapis.com/auth/calendar"] flow = Installe...
# -*- coding: utf-8 -*- """binomial_mix. Chen Qiao: cqiao@connect.hku.hk """ import sys import warnings import numpy as np from scipy.special import gammaln, logsumexp from .model_base import ModelBase class MixtureBinomial(ModelBase): """Mixture of Binomial Models This class implements...
from keras.layers import Conv2D, SeparableConv2D, MaxPooling2D, Flatten, Dense from keras.layers import Dropout, Input, BatchNormalization, Activation, add, GlobalAveragePooling2D from keras.losses import categorical_crossentropy from keras.optimizers import Adam from keras.utils import plot_model from keras import cal...