content
stringlengths
5
1.05M
#!/usr/bin/env python from flask_demo.app import app from flask_demo.db import db def main(): with app.app_context(): db.create_all() if __name__ == '__main__': main()
import argparse import datetime import gym import envs import numpy as np import torch import imageio import itertools from rl.model import GaussianPolicy, QNetwork, DeterministicPolicy from transformer_split.util import getGraphStructure from transformer_split.vae_model import VAE_Model from torch.nn import functio...
# Standard Library Imports import math import random # Third Party Imports import pygame from pygame import mixer # Local Application Imports from classes.rectblock import RectBlock from classes.enemyblock import EnemyBlock from classes.gameobject import ( Player, Enemy, ) from configurations import ( X_L...
"""Class: Printer.""" import ast import sys import astunparse import typed_ast.ast3 class Printer(astunparse.Printer): """Partial rewrite of Printer from astunparse to handle typed_ast.ast3-based trees.""" def __init__( self, file=sys.stdout, indent=" ", annotate_fields: bool = True, ...
N,K=map(int,input().split()) L = [input().split() for i in range(N)] for i in range(N): L[i][2],L[i][3] = int(L[i][2]),int(L[i][3]) L.sort(key = lambda t:t[3]) L.sort(key = lambda t:(-t[2])) cnt = 0 i = 0 d = {} while cnt <K: try: d[L[i][0]]+=1 except: d[L[i][0]]=1 cnt+=1 pri...
#!/usr/bin/python3 '''Advent of Code 2019 Day 10 tests''' import unittest import os import sys sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) from aoc2019 import day10 # pylint: disable=wrong-import-position class TestUM(unittest.TestCase): '''Tests from day ten''' def test_...
#! /usr/bin/python # -*- coding: utf-8 -*- u""" author: Atsushi Sakai """ import numpy as np def solve_qp_with_ep_const(P, q, A, b): """ solve quadratic programming with only equality constraints min 0.5*x*P*x + q.T*x s.t Ax = b """ # input check if not isinstance(P, np.matrix)...
import nltk import numpy as np from nltk.corpus import wordnet def _to_unicode(str_, py3=True): if py3: return str_ else: return unicode(str_) def parse_pos_tag(tag): # https://stackoverflow.com/questions/15586721/wordnet-lemmatization-and-pos-tagging-in-python if tag.startswith('J'): ...
""" This is the main file that holds the Tokenizer, Parser, and Interpreter that actually compile the PDF. """ import os.path as path import re import copy as _copy from decimal import Decimal from placer.placer import Placer from constants import CMND_CHARS, END_LINE_CHARS, ALIGNMENT, TT, TT_M, WHITE_SPACE_CHARS,...
pedidos = [] def criar_pedido(nome, sabor, observacao=None): pedido = {} pedido['nome'] = nome pedido['sabor'] = sabor pedido['observacao'] = observacao return pedido pedidos.append(criar_pedido('mario', 'pepperoni')) pedidos.append(criar_pedido('marco', 'presunto', 'xyz')) for pedido in pedido...
def fib_slow(n): if n < 0: raise ValueError('n must be non-negative') if n == 1 or n == 0: return 1 return fib_slow(n-1) + fib_slow(n-2) def fib_fast(n): cache = {0: 1, 1: 1, 2: 2} def inner_fib(m): if (m in cache): return cache[m] value = inner_fib(m-...
class MyClass: def __init__(self, attr): self.attr = attr def __add__(self, other): return MyClass(self.attr + other.attr) def method(self): print(self.attr) print(self.attr) (MyClass(1) + MyClass(2)).meth<caret>od()
import boto3 import json def publish_to_connect_sns(payload, topic): sns = boto3.client('sns') response = sns.publish ( TargetArn = topic, Message = json.dumps(payload) ) return response def lambda_handler(event, context): #sns_message = json.loads(event['Records'][0]['Sns']['Mes...
''' The split function here finds splits that minimize gini impurity. It runs under numba for speed, since these are the innermost loops in decision tree fitting. author: David Thaler date: August 2017 ''' import numpy as np import numba from . import tree_constants as tc @numba.jit(nopython=True) def split(x, y, w...
#from pyNastran.bdf.field_writer_8 import set_blank_if_default from pyNastran.bdf.field_writer_8 import print_card_8 from pyNastran.bdf.bdf_interface.assign_type import (integer, double) class DLOAD(object): type = 'DLOAD' def __init__(self, model): """ Defines the DLOAD object. P...
import os import unittest from ont_fast5_api.fast5_file import Fast5File from ont_fast5_api.fast5_interface import get_fast5_file from ont_fast5_api.multi_fast5 import MultiFast5File test_data = os.path.join(os.path.dirname(__file__), 'data') class TestFast5Interface(unittest.TestCase): def test_correct_type(se...
# Copyright (c) 2020 fortiss GmbH # # Authors: Julian Bernhard, Klemens Esterle, Patrick Hart and # Tobias Kessler # # This work is licensed under the terms of the MIT license. # For a copy, see <https://opensource.org/licenses/MIT>. import numpy as np import time import os from bark.runtime.commons.parameters import ...
# # PySNMP MIB module COFFEE-POT-MIB (http://pysnmp.sf.net) # ASN.1 source http://mibs.snmplabs.com:80/asn1/COFFEE-POT-MIB # Produced by pysmi-0.0.7 at Sun Feb 14 00:07:06 2016 # On host bldfarm platform Linux version 4.1.13-100.fc21.x86_64 by user goose # Using Python version 3.5.0 (default, Jan 5 2016, 17:11:52) # ...
import numpy as np def accuracy(y, y_hat): # Calculate classification accuracy of model return (y.astype(int) == y_hat.astype(int)).sum() / y.size def rmse(y, y_hat): # Calculate root squared mean error of model return np.sqrt(((y - y_hat) ** 2).mean()) def compute_scores(y, y_hat, classification_...
"""backend URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-ba...
import os import sys # import random from math import sqrt import numpy as np # import matplotlib.pyplot as plt cur_dir = os.getcwd() dt = float(sys.argv[1]) # dt = 1 max_t = int(sys.argv[1]) time_unit = 1 class LoadAllxy(object): """docstring for LoadAllxy""" def __init__(self, particle_indx: int): ...
#!/usr/bin/env python3 # Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 import argparse import sys from sim.elf import load_elf from sim.sim import OTBNSim def main() -> int: parser = argparse.ArgumentParser() ...
# Copyright 2014 NetApp # 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 applic...
# This is an auto-generated Django model module. # You'll have to do the following manually to clean this up: # * Rearrange models' order # * Make sure each model has one field with primary_key=True # * Make sure each ForeignKey has `on_delete` set to the desired behavior. # * Remove `managed = False` lines if ...
import os basedir = os.path.abspath(os.path.dirname(__file__)) class Default(object): # config DataBase SECRET_KEY = os.environ.get("SECRET_KEY") WORK_FACTOR = 12 JWT_SECRET_KEY = os.environ.get("JWT_SECRET_KEY") SQLALCHEMY_TRACK_MODIFICATIONS = False JWT_AUTH_USERNAME_KEY = os.environ.get("J...
# -*- coding: utf-8 -*- ''' Management of ipsets ====================== This is an ipset-specific module designed to manage IPSets for use in IPTables Firewalls. .. code-block:: yaml setname: ipset.set_present: - set_type: bitmap:ip - range: 192.168.0.0/16 - comment: True setna...
from django.contrib import admin # from .models import Test_my # Register your models here. # admin.site.register(Test_my)
## based on dtm1.py but using some cogsci papers import logging from gensim.models import ldaseqmodel from gensim.corpora import Dictionary, bleicorpus, textcorpus import numpy from gensim.matutils import hellinger import re import os def text_to_words(text): clean = re.sub('[^A-Za-z0-9 ]+', '', text) words = cl...
import sys import time import random import openpyxl import csv from pathlib import Path from loguru import logger from pyngsi.sources.source import Source, Row class SourceSampleOrion(Source): """ A SourceSampleOrion implements the Source from the NGSI Walkthrough tutorial. Please have a look at : ...
# -*- coding: utf-8 -*- """ Created on January, 23 2021 @author: Gerd Duscher """ import unittest import numpy as np import sidpy from scipy.ndimage import gaussian_filter from pycroscopy.image import image_clean import sys if sys.version_info.major == 3: unicode = str def make_test_data(): im = np.zeros(...
from django.db import transaction from django.http import HttpResponse from django.views.generic.base import View from reversion.views import create_revision, RevisionMixin from test_app.models import TestModel def save_obj_view(request): return HttpResponse(TestModel.objects.create().id) def save_obj_error_vie...
# -*- coding: utf-8 -*- """ pmutt.test_pmutt_model_statmech_nucl Tests for pmutt module """ import unittest from pmutt.statmech import nucl class TestEmptyNucl(unittest.TestCase): def setUp(self): unittest.TestCase.setUp(self) self.nuclear = nucl.EmptyNucl() self.nuclear_dict = { ...
from contextlib import contextmanager import logging from flask import Flask from flask import render_template from flask import request from flask import json from sqlalchemy import create_engine from sqlalchemy import Column, Integer, String, Float from sqlalchemy.ext.declarative import declarative_base from sqlalc...
# coding: utf-8 """ SimScale API The version of the OpenAPI document: 0.0.0 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six from simscale_sdk.configuration import Configuration class Algorithm(object): """NOTE: This class is auto generated by Ope...
from api.models import Attendance, CourseUnit, Student from logs import general_log from logs.logs_decorator import log_operations_time, log_and_catch_query from django.db import transaction from rest.queries.utils import generate_random_id @log_operations_time @log_and_catch_query( (Exception, "Erro ao obter tod...
#!/usr/bin/env python3 from websearcher import web_downloader """ Download urls in urls_file to out_directory. Use command line arguments. """ downloader = web_downloader.WebDownloader("@./data/input/web_downloader_args.txt") print("Downloading to " + downloader.args.out_directory) downloader.request_urls_write_to_...
from data_collection.management.commands import BaseXpressDemocracyClubCsvImporter class Command(BaseXpressDemocracyClubCsvImporter): council_id = "E09000025" addresses_name = ( "parl.2019-12-12/Version 1/LBNewhamDemocracy_Club__12December2019.TSV" ) stations_name = ( "parl.2019-12-12/...
from .base import SemaceApiClient from .connection import SemaceConnection
#!/usr/bin/python from getpass import getpass from pyzabbix import ZabbixAPI import time import socket import json import time import math from threading import Thread from collections import defaultdict import re import string import os class Poller(object): def __init__(self, length, interval, vms, meas_server, ...
""" measure.py This module performs measurements! """ import numpy as np def calculate_distance(r_a, r_b): """ Calculate the distance between two points. Parameters ========== r_a, r_b : np.ndarray the coordinates of each point Returns ======= distance : float The dis...
from datetime import datetime from sqlalchemy import create_engine, Column, Integer, String, DateTime, ForeignKey, JSON from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship, sessionmaker from upload.common.upload_config import UploadDbConfig Base = declarative_base() cla...
import argparse import json import pcomfortcloud from enum import Enum def print_result(obj, indent = 0): for key in obj: value = obj[key] if isinstance(value, dict): print(" "*indent + key) print_result(value, indent + 4) elif isinstance(value, Enum): ...
""" Metrics that provide data about commits & their associated activity """ import datetime import sqlalchemy as s import pandas as pd from augur.util import register_metric @register_metric() def committers(self, repo_group_id, repo_id=None, begin_date=None, end_date=None, period='month'): """ :param repo_id...
#!/usr/bin/env python3 """ Make a custom colormap from a list of colors References ---------- How to create a colormap: https://matplotlib.org/3.1.0/tutorials/colors/colormap-manipulation.html """ import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import seaborn as sns import json import o...
import csv table = [] with open('iso639-autonyms.tsv', 'rt', newline='', encoding='utf-8') as f: reader = csv.reader(f, dialect='excel-tab') for row in reader: current_row = [] current_row.extend(row[:3]) current_row.append(row[3].title()) table.append(current_row) with open('iso639-autonyms.csv', 'wt', ne...
class Solution: def minReorder(self, n: int, connections: List[List[int]]) -> int: tree = [[] for _ in range(n)] # a --> b for a, b in connections: tree[a].append((b, 1)) tree[b].append((a, 0)) self.ans = 0 def dfs(u, parent): for v, d in t...
# coding: utf-8 """ Control-M Services Provides access to BMC Control-M Services # noqa: E501 OpenAPI spec version: 9.20.215 Contact: [email protected] Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six from clients.ct...
from __future__ import print_function from __future__ import absolute_import from __future__ import division import os import compas if not compas.IPY: import imageio __all__ = ["gif_from_images"] def gif_from_images( files, gif_path, fps=10, loop=0, reverse=False, pingpong=False, ...
from pydantic import BaseModel, Extra class Mqtt5ChannelBinding(BaseModel): """ This document defines how to describe MQTT 5-specific information on AsyncAPI. This object MUST NOT contain any properties. Its name is reserved for future use. """ class Config: extra = Extra.forbid class...
#!/usr/bin/python3 import pandas as pd import os.path from pinja.color.color import * class CsvImprivement: KEYWORD1 = "call" IMPROVEMENT_STR1 = "call 0x0" extension = ".csv" new_tailname_extension = "_TRANS.csv" new_file_name = "" def create_improvement_csv(self, input_csv_file_path): ...
#coding=utf-8 import tornado.web as web from tornado.httpclient import AsyncHTTPClient from tornado.httpclient import HTTPRequest from tornado import gen from tornado.ioloop import IOLoop from tornado.web import StaticFileHandler from tornado.log import enable_pretty_logging import motor import os import json from bson...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import argparse import sc2reader from sc2reader.utils import get_files from sc2reader.exceptions import ReadError def doFile(filename, arguments): '''Prints summary information about SC2 replay file''' try: replay = sc2reader.read_fil...
from c0101_retrieve_ref import retrieve_ref from c0102_timestamp import timestamp_source from c0103_trim_record_to_max import trim_record_to_max from c0104_plot_timestamp import plot_timestamp from c0105_find_records import find_records from c0106_record_to_summary import record_to_summary from c0107_decide_inclusion i...
n = int(input()) third = n % 10 first = n // 100 second = n // 10 % 10 for a in range(1, third + 1): for b in range(1, second + 1): for c in range(1, first + 1): print('{0} * {1} * {2} = {3};'.format(a, b, c, (a * b * c)))
def mul(a, b): """ >>> mul(2, 3) 6 >>> mul('a', 2) 'aa' """ return a * b def add(a, b): """ >>> add(2, 3) 5 >>> add('a', 'b') 'ab' """ return a + b
import pytest from presidio_analyzer import RecognizerResult from presidio_evaluator.data_generator.presidio_perturb import PresidioPerturb from tests import get_mock_fake_df import pandas as pd @pytest.mark.parametrize( # fmt: off "text, entity1, entity2, start1, end1, start2, end2", [ ( ...
# DESCRIPTION: Tests the UI and GUI. # 4920646f6e5c2774206361726520696620697420776f726b73206f6e20796f7572206d61636869 # 6e652120576520617265206e6f74207368697070696e6720796f7572206d616368696e6521 # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # TODO: Finsih off these tests. import un...
import os from options.test_options import TestOptions from models import create_model from PIL import Image import numpy as np import torchvision.transforms as transforms import torch def isSubString(Str,Filters): flag = False for substr in Filters: if substr in Str: flag = True ...
""" Ajay Kc 013213328 EE381 Project 5 Part 2 The problem calculates the percentage of the sample mean fitting under the area between various confidence intervals. """ import numpy as np import matplotlib.pyplot as plt import math as math bearingList = np.random.normal(75,0.75,1000000) def checkConfidenceInterval(mea...
import os import time import numpy as np import pandas as pd from tqdm import tqdm from datetime import datetime import torch import torch.utils.data as data from torch.utils.tensorboard import SummaryWriter import ast from daisy.utils.sampler import Sampler from daisy.utils.parser import parse_args from daisy.utils.s...
""" Module for classes to prepare training datasets Prepare training data for pointer generator (add tags <s> and </s> tags to summaries): Prepare bioasq python prepare_training_data.py -bt Or with the question: python prepare_training_data.py -bt --add-q Prepare training data for bart, with or withou...
# The new config inherits a base config to highlight the necessary modification _base_ = '/home/guest01/projects/mmdetection/configs/cascade_rcnn/cascade_mask_rcnn_r50_fpn_20e_coco.py' # 1. dataset settings dataset_type = 'CocoDataset' classes = ('chromos',) data = dict( samples_per_gpu=2, workers_per_gpu=2, ...
""" Django settings for src project. Generated by 'django-admin startproject' using Django 2.1.2. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # Bui...
#!/usr/bin/python3 # Copyright 2017 ETH Zurich # Copyright 2018 ETH Zurich, Anapaya Systems # # 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 # ...
"""Has binance trading api interface.""" from decimal import Decimal from typing import Optional, Protocol from exapi.models.binance import (BinanceAccountInfoModel, BinanceAccountTrades, BinanceCanceledOrderModel, B...
import kerfi import tests class CleanupPropertyTestCase(tests.BaseTestCase): """ Test cases for kerfi.cleanup_property() function. """ def test(self): """ Tests the kerfi.cleanup_property() function. """ self.assertEquals('key_key', kerfi.cleanup_property(' key key: '...
# Time: O(n) # Space: O(1) # An encoded string S is given. # To find and write the decoded string to a tape, # the encoded string is read one character at a time and the following steps are taken: # # If the character read is a letter, that letter is written onto the tape. # If the character read is a digit (say d), ...
sentence = 'The cat is named Sammy' print(sentence.upper()) print(sentence.lower()) print(sentence.capitalize()) print(sentence.count('i'))
import os from copy import deepcopy from unittest import TestCase from scrapy import Spider from scrapy.settings import Settings from scrapy_httpproxy import get_proxy from scrapy_httpproxy.settings import default_settings from scrapy_httpproxy.storage.environment import EnvironmentStorage from scrapy_httpproxy.stora...
# -*- 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...
""" Created on Wed Jun 13 17:19:23 2018 @author: msdogan This module retrieves inflow data from CDEC for defined station IDs. Detailed info: documentation: http://ulmo.readthedocs.io/en/latest/ GitHub repo: https://github.com/ulmo-dev/ulmo """ import pandas as pd import numpy as np import matplotlib.pyplot as plt imp...
from line2.models.command import Command, Parameter, ParameterType, CommandResult, CommandResultType from random import random from line2.utils import IsEmpty def Echo(message, options, text=''): if not IsEmpty(text): return CommandResult(type=CommandResultType.done, texts=[text]) echoCmd = Command( '...
"""Test of the various bits of the parser.""" # fchic from fchic.parser_definition import ( char_arr_deck, deck, details, fchk, header, integer, ival_deck, name_of_deck, real, real_arr_deck, rval_deck, title, ) def test_data_types() -> None: """Test parsers for vari...
import unittest import numpy import chainer from chainer import cuda from chainer.testing import attr from deepmark_chainer.net import vgg_d class TestVGG_D(unittest.TestCase): def setUp(self): self.x = numpy.random.uniform(-1, 1, (1, 3, 224, 224)).astype(numpy.float32) self.l = vgg_d.VGG_D() ...
# -*- coding: utf-8 -*- """ api.v1.auth.parser ~~~~~~~~~~~~~~~~~~ :copyright: (c) 2017-18 by Wendell Hu. :license: MIT, see LICENSE for more details. """ from flask_restful import reqparse login_parser = reqparse.RequestParser() login_parser.add_argument('username', type=str...
X = float(input()) for i in range(100): print('N[{}] = {:.4f}'.format(i, X)) X /= 2
#! /usr/bin/python -tt # This is a simple command to check that "Is this ok [y/N]: " and yes and no # have either all been translated or none have been translated. import sys import glob from yum.misc import to_utf8 def trans(msg, default): if msg == 'msgstr ""\n': return unicode(default, encoding='utf-...
# Generated by Django 2.2 on 2021-09-16 05:37 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('waterApp', '0016_auto_20210914_1328'), ] operations = [ migrations.CreateModel( name='OfflineLoggerData', fields=[ ...
from transformers import GPT2LMHeadModel, GPT2Tokenizer import torch import torch.nn.functional as F import numpy as np import matplotlib.pyplot as plt MODEL = 'gpt2-medium' DEV = 'cuda' TOP_K = 10 LENGTH = 50 WEIGHTS = [0.01, 0.01] WEIGHTS = [0.02] COND = 'positive politics' COND = 'negative politics' COND = 'posit...
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making GameAISDK available. This source code file is licensed under the GNU General Public License Version 3. For full details, please refer to the file "LICENSE.txt" which is provided as part of this source code package. Copyright...
from pip._vendor.msgpack.fallback import xrange # use KMP algorithm # https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm class Solution: def strStr(self, haystack: str, needle: str) -> int: dic = self.prefix(needle) i = j = 0 while i < len(haystack) and j < len(nee...
import os access_token_key = os.getenv('TWITTER_ACCESS_TOKEN_KEY', '') access_token_secret = os.getenv('TWITTER_ACCESS_TOKEN_SECRET', '') consumer_key = os.getenv('TWITTER_CONSUMER_KEY', '') consumer_secret = os.getenv('TWITTER_CONSUMER_SECRET', '')
from beluga.visualization import BelugaPlot from beluga.visualization.datasources import Dill plots = BelugaPlot('./data.dill', default_sol=-1, default_step=-1, renderer='matplotlib') plots.add_plot().line_series('v', 'h') \ .xlabel('v [$m/s$]').ylabel('h [m]') \ .title('h-v Plot') plots.add_plot().line_seri...
""" Product API Service Test Suite Test cases can be run with the following: nosetests -v --with-spec --spec-color coverage report -m """ import os import logging from unittest import TestCase from unittest.mock import patch from flask_api import status # HTTP Status Codes from service.models import db from servi...
# -*-coding:Utf-8 -* # Copyright (c) 2010-2017 LE GOFF Vincent # 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 # ...
/home/runner/.cache/pip/pool/b8/2b/4a/fe37f69cfbb893fef0f3566d4ce7a89098a8a5665d3203d35344f013d4
import sys import os import curses import subprocess from typing import Any, Dict from typing import Dict from aorc.state import AorcState from aorc.aorc_doit import * from simple_curses import View import simple_curses.validator as validator def state_from_view_values(old_state: AorcState, view_values: Dict[str, Any...
import numpy as np import tensorflow as tf from garage.misc import logger, special from garage.sampler import parallel_sampler from garage.sampler import singleton_pool from garage.sampler.base import BaseSampler from garage.sampler.utils import truncate_paths from garage.tf.misc import tensor_utils def worker_init_...
import batchglm.data as data_utils from batchglm.models.glm_nb import AbstractEstimator, EstimatorStoreXArray, InputData, Model from batchglm.models.base_glm.utils import closedform_glm_mean, closedform_glm_var from batchglm.models.glm_nb.utils import closedform_nb_glm_logmu, closedform_nb_glm_logphi import batchglm....
from reportlab.lib.styles import ParagraphStyle as PS from reportlab.platypus import PageBreak from reportlab.platypus.paragraph import Paragraph from reportlab.platypus.doctemplate import PageTemplate, BaseDocTemplate from reportlab.platypus.tableofcontents import TableOfContents from reportlab.platypus.frames i...
import matplotlib.pyplot as plt #import tabulate import json log_dir = 'log/' experiment = ['baseline', 'N', 'GC', 'BN', 'R2', 'AA', 'AC'] # baseline, BN, GC, N, AA, AC versions = '100'#['100','200','300','400'] results = [] loss = [] acc = [] for e in experiment: xp_path = log_dir+e+versions with open(xp_p...
import argparse import csv import datetime import json import pytz import yaml if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('zoom', help='input zoom yaml file') parser.add_argument('papers', help='input paper csv file') parser.add_argument('problems', help='input open probl...
import numpy as np import pandas as pd from sklearn.covariance import EllipticEnvelope from sklearn.neighbors import LocalOutlierFactor from sklearn.ensemble import IsolationForest from sklearn.svm import OneClassSVM from .base import OutlierDetector __all__ = [ 'RobustCovariance', 'LocalOutlierFactor', ...
class IndexedMessage: __slots__ = ("message", "index") def __init__(self, message: str, index: int) -> None: """Represents a message and its index within a collection Args: message: The message index: The message index """ self.message = message ...
import requests from geopy.geocoders import Nominatim ''' Find a user's local representatives (and their contact details) given an address string input ''' def calculate_lat_long_from_address(address_string): ''' Find latitude and longitude of address Inputs: address_string (str): user's address s...
# -*- coding: utf-8 -*- """ Created on Wed Apr 17 22:31:22 2019 @author: student """ import threading import time import tkinter as tk from tkinter import HORIZONTAL, Button, Entry, Frame, Label, Scale, Tk, mainloop import numpy as np import pinocchio as pin import talos_conf as conf #import romeo_conf as conf impo...
from punc_tokenizer import PuncTokenizer
#!/bin/python import sys def solve(a): n = len(a) sum1 = sum2 = 0 for i in xrange(n/2): sum1 = sum1 + a[i] sum2 = sum2 + a[n - i - 1] return abs(sum1 - sum2) n = int(raw_input().strip()) a = map(int, raw_input().strip().split(' ')) result = solve(a) print(result)
# Copyright 2021, The TensorFlow Federated 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 applicable law o...
# Copyright 2020 Huawei Technologies Co., Ltd # # 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...