content
stringlengths
5
1.05M
import numpy as np # type: ignore import pandas as pd # type: ignore # imported ML models from scikit-learn from sklearn.model_selection import (ShuffleSplit, StratifiedShuffleSplit, # type: ignore TimeSeriesSplit, cross_val_score) # type: ignore from sklearn.discriminant_anal...
#!/usr/bin/env python __author__ = 'Florian Hase' #======================================================================= from DatabaseHandler.PickleWriters.db_writer import DB_Writer
# # @lc app=leetcode id=383 lang=python # # [383] Ransom Note # # https://leetcode.com/problems/ransom-note/description/ # # algorithms # Easy (49.29%) # Total Accepted: 107.4K # Total Submissions: 216.8K # Testcase Example: '"a"\n"b"' # # # Given an arbitrary ransom note string and another string containing lette...
""" Guidelines from whitehouse.gov/openingamerica/ SYMPTOMS: - Downward Trajectory of Flu-like illnesses AND - Downward Trajectory of Covid symptoms 14 day period CASES: - Downward Trajectory of documented cases within 14 day period OR - Downward Trajectory of positive tests within 14 days ...
from pymodm import connect, MongoModel, fields from pymodm.base.fields import MongoBaseField import pymongo from datetime import datetime as dt db_server = "mongodb+srv://AtlasUser:8dNHh2kXNijBjNuQ@cluster0.a532e" db_server += ".mongodb.net/ECGServer?retryWrites=true&w=majority" mongodb_server = connect(db_server) ...
from django.urls import path from account.views import ( index, profile, LOGIN, LOGOUT, REGISTER, activate, change_password, update_profile, change_profile_pic ) from account.api import ( check_username_existing, get_users ) app_name = 'account' urlpatterns = [ # API URLs path('api/check_usern...
import msgpack_numpy import os import torch from collections import defaultdict from typing import List import lmdb import magnum as mn import numpy as np from torch.utils.data import Dataset from tqdm import tqdm import habitat from habitat import logger from habitat.datasets.utils import VocabDict from habitat.task...
from visualization import plot_binary_grid # used to show results from wrapper import multi_image # import segmenter for multiple images if __name__ == "__main__": # Apply segmenter to default test images. print("Classifying images...") masks = multi_image() # uses default test image print("Complete...
# from sqlalchemy package we can import Column, String, Integer, Date, Sequence from sqlalchemy import Column, String, Integer, Date, Sequence # imports Config class from config module from config import Config #exception handling using try except for FeatureRequestAppClass. try: # A class FeatureRequestApp will be...
from typing import List import config import datetime from email.mime.text import MIMEText from html.parser import HTMLParser import email.utils as utils import logging import queue import re import sys import threading from time import strftime import socket import feedparser import yaml from imap_wrapper import Im...
from flask.views import MethodView class APIView(MethodView): api_version = None path = None @classmethod def get_path(self): if self.path: return self.path elif self.__name__.endswith('View'): return self.__name__[:-4].lower() else: return ...
''' - Application Factory ''' from app import create_app from fastapi import FastAPI from fastapi.testclient import TestClient from pytest import fixture @fixture def client(): '''Cliente do FastAPI.''' app = create_app() return TestClient(app) def test_create_app(client): assert isinstance(create_a...
"""A module for evaluating policies.""" import os import json import pandas as pd import matplotlib.pyplot as plt from tf_agents.environments.tf_py_environment import TFPyEnvironment from lake_monster.environment.environment import LakeMonsterEnvironment from lake_monster.environment.variations import MultiMonsterEnvi...
import numpy as np from numpy import exp,dot,full,cos,sin,real,imag,power,pi,log,sqrt,roll,linspace,arange,transpose,pad,complex128 as c128, float32 as f32, float64 as f64 from numba import njit,jit,complex128 as nbc128, void import os os.environ['NUMEXPR_MAX_THREADS'] = '16' os.environ['NUMEXPR_NUM_THREADS'] = ...
#!/usr/bin/env python # Copyright (c) 2014 Spotify AB. # # 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 Ap...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from maro.backends.frame import FrameBase, FrameNode from .port import Port from .vessel import gen_vessel_definition from .matrix import gen_matrix def gen_ecr_frame(port_num: int, vessel_num: int, stop_nums: tuple, snapshots_num: int): """...
"""Provide functionality to handle package settings.""" import logging from enum import Enum from os import makedirs from os.path import isdir from urllib.error import URLError from urllib.parse import urlparse from urllib.request import Request, urlopen from dynaconf import Validator, settings LOGGER = logging.getLo...
# Copyright 2017 The Sonnet 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...
#!/usr/bin/env python """ (C) 2007-2019 1024jp """ import pickle import cv2 import numpy as np import matplotlib.pyplot as plt _flags = (cv2.CALIB_ZERO_TANGENT_DIST | cv2.CALIB_FIX_K3 ) class Undistorter: def __init__(self, camera_matrix, dist_coeffs, rvecs, tvecs, image_size, ...
#!/usr/bin/env python names = ["Amy", "Bob", "Cathy", "David", "Eric"] for x in names: print("Hello " + x)
# coding: utf-8 from __future__ import unicode_literals import pytest from django.contrib.auth.models import AnonymousUser from mock import Mock from saleor.cart import decorators from saleor.cart.models import Cart from saleor.checkout.core import Checkout from saleor.discount.models import Voucher from saleor.produ...
#!/usr/bin/env python from re import sub from sys import argv,exit from os import path,getenv from glob import glob import argparse parser = argparse.ArgumentParser(description='make forest') parser.add_argument('--region',metavar='region',type=str,default=None) toProcess = parser.parse_args().region argv=[] import RO...
from tensorflow.keras import initializers from tensorflow.keras import layers from tensorflow.keras.models import Sequential def build_subnet(output_filters, bias_initializer='zeros', name=None): """构建功能子网络. Args: output_filters: int, 功能子网络输出层的神经元数量. bias_initializer: str or tf.ke...
from .seld import *
import numpy as np class UnionFind: def __init__(self, n): self.n = n self.parent = np.arange(n) self.rank = np.zeros(n, dtype=np.int32) self.csize = np.ones(n, dtype=np.int32) def find(self, u): v = u while u != self.parent[u]: u = self.parent[u] ...
import logging.config from .Camera import Camera import time from io import BytesIO from PIL import Image from dateutil import zoneinfo timezone = zoneinfo.get_zonefile_instance().get("Australia/Canberra") try: logging.config.fileConfig("/etc/eyepi/logging.ini") except: pass try: import picamera imp...
# 建立一个登录页面 from tkinter import * root = Tk() root.title("登陆页面") msg = "欢迎进入海绵宝宝系统" sseGif = PhotoImage(file="../img/hmbb1.gif") logo = Label(root,image=sseGif,text=msg, compound=BOTTOM) logo.grid(row=0,column=0,columnspan=2,padx=10,pady=10) accountL = Label(root,text="Account") accountL.grid(row=1) pwdL = Label(r...
from setuptools import setup setup( name='YinPortfolioManagement', author='Yiqiao Yin', version='1.0.0', description="This package uses Long Short-Term Memory (LSTM) to forecast a stock price that user enters.", packages=['YinCapital_forecast'] )
import analysis #Create historgram analysis.histogram() #Create scatterplot analysis.scatterplot("sepal_length","sepal_width") analysis.scatterplot("petal_length","petal_width") analysis.pair_plot() #Create summary.txt analysis.writeToAFile
import os from apscheduler.schedulers.blocking import BlockingScheduler sched = BlockingScheduler() @sched.scheduled_job('cron', hour=9) def scheduled_job(): os.system("python manage.py runbot") sched.start()
from django.db import models from i18nfield.fields import I18nCharField from pretalx.common.mixins import LogMixin from pretalx.common.urls import EventUrls class Track(LogMixin, models.Model): event = models.ForeignKey( to='event.Event', on_delete=models.PROTECT, related_name='tracks' ) name = I...
from sqlalchemy.ext.declarative import declarative_base, declared_attr from sqlalchemy import Column, Integer, String, Boolean, BigInteger, Text, ForeignKey, Float from sqlalchemy.orm import relationship #from sqlalchemy_views import CreateView, DropView # connection.execute("CREATE TABLE `jobs` (`clock` BIGINT(11),`j...
# -*- coding: UTF-8 -*- import os import sys import time import caffe import numpy as np from timer import Timer from db_helper import DBHelper import matplotlib.pyplot as plt from caffe.proto import caffe_pb2 from google.protobuf import text_format # Load LabelMap file. def get_labelmap(labelmap_path): labelmap...
#!/usr/bin/python # -*- coding: utf-8 -*- r""" Script to delete files that are also present on Wikimedia Commons. Do not run this script on Wikimedia Commons itself. It works based on a given array of templates defined below. Files are downloaded and compared. If the files match, it can be deleted on the source wiki...
#@+leo-ver=5-thin #@+node:ville.20110403115003.10348: * @file valuespace.py #@+<< docstring >> #@+node:ville.20110403115003.10349: ** << docstring >> '''Supports Leo scripting using per-Leo-outline namespaces. Commands ======== .. note:: The first four commands are a light weight option for python calculations ...
#Let's do some experiments to understand why to use numpy and what we can do with it. #import numpy with alias np import numpy as np import sys # one dimensional array a=np.array([1,2,3]) print(a) # two dimensional array a= np.array([(1,2,3),(4,5,6)]) print(a) #why numpy better than list.. #1)Less memory #2)faste2...
if '__file__' in globals(): import os, sys sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import numpy as np from dezero import Variable import dezero.functions as F # im2col x1 = np.random.rand(1, 3, 7, 7) col1 = F.im2col(x1, kernel_size=5, stride=1, pad=0, to_matrix=True) print(col1.shape) ...
import sys import os from os.path import join as opj workspace = os.environ["WORKSPACE"] sys.path.append( opj(workspace, 'code/GeDML/src') ) import argparse import logging logging.getLogger().setLevel(logging.INFO) import torch.distributed as dist from gedml.launcher.runners.distributed_runner import Distributed...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models class Company(models.Model): _inherit = 'res.company' hr_presence_control_email_amount = fields.Integer(string="# emails to send") hr_presence_control_ip_list = fields.Char(...
#!/usr/bin/env python """ _ConfigureState_ Populate the states tables with all known states, and set the max retries for each state. Default to one retry. Create the CouchDB and associated views if needed. """ from WMCore.Database.CMSCouch import CouchServer from WMCore.DataStructs.WMObject import WMObject class ...
import numpy as np from numba import float32, jit from numba.np.ufunc import Vectorize from numba.core.errors import TypingError from ..support import TestCase import unittest dtype = np.float32 a = np.arange(80, dtype=dtype).reshape(8, 10) b = a.copy() c = a.copy(order='F') d = np.arange(16 * 20, dtype=dtype).resha...
import json import numpy as np def pack(request): data = request.get_json() furniture = data['furniture'] orientations = [] ''' Test TEST TTEESSTT ''' ################################################################## ####### Preliminary Functions ##############...
#!/usr/bin/env python3 # Dependencies: python3-pandas python3-plotly import pandas as pd import plotly.graph_objects as go from plotly.subplots import make_subplots import plotly.colors df = pd.read_csv(".perf-out/all.csv") fig = make_subplots( rows=2, cols=2, horizontal_spacing = 0.1, vertical_spacing ...
import json, re, pymongo, os from itemadapter import ItemAdapter from scrapy.exceptions import DropItem from unidecode import unidecode from nltk.corpus import stopwords from nltk.tokenize import word_tokenize from datetime import date, datetime from scrapy import settings format="%d/%m/%Y" class NoticiasPipeline:...
from math import * from scipy.integrate import quad from scipy.integrate import dblquad from scipy import integrate from scipy import special from numpy import median from numpy import linspace from copy import deepcopy from scipy.stats import fisk "Defining the parameters for the tests" alpha = 0.05 delta = 0.002 k ...
from rest_framework import permissions class AnonymousPermission(permissions.BasePermission): """ Non Anonymous Users. """ message = "You are already registered. Please logout and try again." def has_permission(self, request, view): print(not request.user.is_authenticated) return n...
# -*- coding: UTF-8 -*- from operator import itemgetter from copy import deepcopy from pydruid.utils import aggregators from pydruid.utils import filters class TestAggregators: def test_aggregators(self): aggs = [('longsum', 'longSum'), ('doublesum', 'doubleSum'), ('min', 'min'), ('max'...
import os from django.templatetags.static import static from django.utils.html import format_html from django.utils.module_loading import import_string from wagtail.core import hooks from wagtail_icons.settings import BASE_PATH, SETS @hooks.register("insert_global_admin_css") def global_admin_css(): stylesheets...
#!/usr/bin/env python # -*- coding: utf-8 -*- '''Author: Ting''' import logging import traceback from argparse import ArgumentParser from datetime import date from pprint import pprint from subprocess import call import re from collections import defaultdict from os.path import join, abspath, dirname, isfile import csv...
# # wcsmod -- module wrapper for WCS calculations. # # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # """ We are fortunate to have several possible choices for a python WCS package compatible with Ginga: astlib, kapteyn, starlink and astropy. kapteyn and astr...
#!/usr/bin/env python3 # # Configure logging # import logging import argparse parser = argparse.ArgumentParser() parser.add_argument("--debug", action="store_true", help="Show debugging output.") args = parser.parse_args() log_level = logging.DEBUG if args.debug else logging.INFO logging.basicConfig(level=log_level, ...
from multiprocessing import Manager, Process def to_add(d, k, v): d[k] = v if __name__ == "__main__": process_dict = Manager().dict() p1 = Process(target=to_add, args=(process_dict, 'name', 'li')) p2 = Process(target=to_add, args=(process_dict, 'age', 13)) p1.start() p2.start() p1.join(...
''' Create words from an existing wordlist ''' import random import re class WordBuilder(object): ''' uses an existing corpus to create new phonemically consistent words ''' def __init__(self, initial='>', terminal='<', chunk_size=2): #indicators for start and ends of words - set if necessary to avoid...
# -*- coding: utf-8 -*- """ Created on Sun May 01 20:28:46 2016 @author: Anna Directory structure: assumes galaxy directory is the working directory, input_data/ should contain pars, phot and fake files This code generates a CMD plot in the same directory where the program, CMDscript.py, is Use optional -phot, -f...
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008,2009,2010,2011,2013,2014 Contributor # # 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...
"""Request handler base classes """ from decorator import decorator from pyramid.httpexceptions import HTTPForbidden from dd_app.django_codec import DjangoSessionCodec from dd_app.messaging.mixins import MsgMixin class DDHandler(object): """Base view handler object """ def __init__(self, request, *args,...
"""Module with view functions that serve each uri.""" from datetime import datetime from learning_journal.models.mymodel import Journal from learning_journal.security import is_authenticated from pyramid.httpexceptions import HTTPFound, HTTPNotFound from pyramid.security import NO_PERMISSION_REQUIRED, forget, remem...
import os import torch import pickle import numpy as np from transformers import RobertaConfig, RobertaModel, RobertaTokenizer tokenizer = RobertaTokenizer.from_pretrained('roberta-base') roberta = RobertaModel.from_pretrained('roberta-base') path = '../wikidata5m_alias' if not os.path.exists('../wikidata5m_alias_emb...
from array import array import numpy as np import os import cv2 import argparse from tensorflow import lite as tflite from matplotlib import pyplot as plt import time import torch from torchvision import transforms from omegaconf import OmegaConf import torch.nn.functional as F import tensorflow as tf from torch.opti...
import os # Bot Setup os.environ["prefix"] = "g!" os.environ["token"] = "NzM5Mjc0NjkxMDg4MjIwMzEw.XyYFNQ.Mb6wJSHhpj9LP5bqO2Hb0w8NBQM" os.environ["botlog"] = "603894328212848651" os.environ["debugEnabled"] = "False" # Database Setup os.environ["db_type"] = "MySQL" # Either MySQL or Flat (or just leave empty for Flat ...
### # Adapted from Avalanche LvisDataset # https://github.com/ContinualAI/avalanche/tree/detection/avalanche/benchmarks/datasets/lvis # # Released under the MIT license, see: # https://github.com/ContinualAI/avalanche/blob/master/LICENSE ### from pathlib import Path from typing import List, Sequence, Union from PIL i...
import os import cv2 import numpy as np from constants import DATA_DIR MYPY = False if MYPY: from typing import Tuple, Union Pair = Tuple[int, int] def scale(image, scale_percent): height, width = image.shape[:2] return cv2.resize(image, (int(width * scale_percent), int(height * scale_percent))) ...
from django.contrib import admin # Register your models here. from .models import SiteConfiguration, SingleOrder, Order, UniqueFeature, Size, Color admin.site.register(Size) admin.site.register(Color) admin.site.register(SiteConfiguration) admin.site.register(UniqueFeature)
import pygame from pygame import draw from .player import Player, Enemy from .utils import Director, TileSet class lvl1(Director): def __init__(self) -> None: super().__init__(self) self.tile = TileSet("assets/tileset.png", 10, 28) self.tile.gen_map(self.alto, self.ancho, 52) self...
from django.urls import path, include from .views import * from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register('titles', TitleViewSet, basename='titles') router.register('categories', CategoryViewSet, basename='categories') router.register('genres', GenreViewSet, basena...
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-06-09 10:07 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import django_prices.models class Migration(migrations.Migration): dependencies = [ ('order', '0016_order_language_co...
# -*- coding: utf-8 -*- ## # @file goldman_equation.py # @brief Contain a function that calculates the equilibrium potential using the Goldman equation # @author Gabriel H Riqueti # @email gabrielhriqueti@gmail.com # @date 22/04/2021 # from biomedical_signal_processing import FARADAYS_CONSTANT as F from biom...
# Copyright 2015 Abhijit Menon-Sen <ams@2ndQuadrant.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any ...
''' Given a binary string str of length N, the task is to find the maximum count of substrings str can be divided into such that all the substrings are balanced i.e. they have equal number of 0s and 1s. If it is not possible to split str satisfying the conditions then print -1. Example: Input: str = “0100110101” Outp...
from Cocoa import * gNumDaysInMonth = ( 0, 31, 28, 31, 30, 21, 30, 31, 31, 30, 31, 30, 31 ) def isLeap(year): return (((year % 4) == 0 and ((year % 100) != 0)) or (year % 400) == 0) class CalendarMatrix (NSMatrix): lastMonthButton = objc.IBOutlet() monthName = objc.IBOutlet() nextMonthButton = objc.I...
import warnings from collections import OrderedDict from ConfigSpace import ConfigurationSpace from ConfigSpace.hyperparameters import CategoricalHyperparameter from mindware.components.feature_engineering.transformations import _bal_balancer, _preprocessor, _rescaler, \ _image_preprocessor, _text_preprocessor, _b...
# Copyright 2020 by Christophe Lambin # All rights reserved. import logging from prometheus_client import start_http_server from libpimon.version import version from libpimon.configuration import print_configuration from libpimon.cpu import CPUTempProbe, CPUFreqProbe from libpimon.gpio import GPIOProbe from libpimon.o...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 1999-2020 Alibaba Group Holding 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-...
# reference: https://github.com/open-mmlab/mmclassification/tree/master/mmcls/models/backbones # modified from mmclassification timm_backbone.py try: import timm except ImportError: timm = None from mmcv.cnn.bricks.registry import NORM_LAYERS from openmixup.utils import get_root_logger from ..builder import B...
import torch import os import pickle if torch.cuda.is_available(): device = torch.device('cuda') else: device = torch.device('cpu') class TrainUtil(): def __init__(self, checkpoint_path='checkpoints', version='mcts_nas_net_v1'): self.checkpoint_path = checkpoint_path self.version = versio...
from pymtl import * from lizard.util.rtl.interface import UseInterface from lizard.util.rtl.method import MethodSpec from lizard.core.rtl.messages import ExecuteMsg, WritebackMsg, PipelineMsgStatus from lizard.util.rtl.pipeline_stage import gen_stage, StageInterface, DropControllerInterface from lizard.core.rtl.kill_un...
# Copyright 2021 NVIDIA Corporation # # 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 wr...
import numpy as np import hmm x = np.random.randint(0, 500, 1000) m = 3 l = np.array([10, 250, 450]) g = np.array([[.8, .1, .1], [.1, .8, .1], [.1, .1, .8]]) d = np.array([.3, .3, .3]) (success, lambda_, gamma_, delta_, aic, bic, nll, niter) = hmm.hmm_poisson_fit_em(x, m, l, g, d, 1000, 1e-6) print(success, aic, bic...
import torch from torch import nn from buglab.models.layers.multihead_attention import MultiheadAttention class RelationalMultiheadAttention(MultiheadAttention): """ A relational multihead implementation supporting two variations of using additional relationship information between tokens: * If no e...
from django.shortcuts import render from datetime import datetime from notifications.models import Notification from users.models import Profile from django.core.urlresolvers import reverse from django.shortcuts import render from django.contrib.auth.decorators import login_required, permission_required from django.con...
from aoc import AOC aoc = AOC(year=2015, day=18) data = aoc.load() ## Part 1 # Initialize the array of lights to all off lights = [x[:] for x in [[0] * len(data.lines())] * len(data.lines())] # For every line in the input in_y = 0 for line in data.lines(): line = line.strip() in_x = 0 for c in line: ...
from pyspark.mllib.regression import LabeledPoint from pyspark.mllib.tree import DecisionTree from pyspark.mllib.linalg import SparseVector from pyspark import SparkContext from operator import add import time import numpy from pyspark.mllib.linalg import Vectors import pyspark.mllib.clustering as cl import os...
#!/usr/bin/env python3 from aws_cdk import core from lab08.lab08_stack import Lab08Stack app = core.App() Lab08Stack(app, "lab08",env={"region":"us-east-1","account":"111111111111"}) app.synth()
import h5py import numpy as np import glob from mne import create_info from mne.io import RawArray def extract_blackrock_info(mat_file, blackrock_type): """ Extracts basic recording info from a blacrock extracted mat file. Extracts the data, sampling rate, channel names, and digital to analog conversion ...
import tensorflow as tf from tf_stft import Spectrogram, Logmel from tensorflow_utils import do_mixup class ConvBlock(tf.keras.Model): """ Convolutional Block Class. """ def __init__(self, out_channels): """ Parameters ---------- out_channels : int Number of ...
# -*- coding: utf-8 -*- def count_days(y, m, d): return (365 * y + (y // 4) - (y // 100) + (y // 400) + ((306 * (m + 1)) // 10) + d - 429) def main(): y = int(input()) m = int(input()) d = int(input()) if m == 1 or m == 2: m += 12 y -= 1 print(count_days(201...
import pytest from azure.ml import MLClient @pytest.fixture def environment_id() -> str: return "/subscriptions/5f08d643-1910-4a38-a7c7-84a39d4f42e0/resourceGroups/sdk_vnext_cli/providers/Microsoft.MachineLearningServices/Environments/AzureML-Minimal" @pytest.fixture def compute_id() -> str: return "testCom...
#!/usr/bin/env python3 # Copyright 2020 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
from rdflib.graph import ConjunctiveGraph from typing import ClassVar from rdflib import Namespace from test.testutils import MockHTTPResponse, ServedSimpleHTTPMock import unittest EG = Namespace("http://example.org/") class TestSPARQLConnector(unittest.TestCase): query_path: ClassVar[str] query_endpoint: Cl...
# Copyright 2021 TUNiB Inc. import torch import torch.distributed as dist from transformers import GPT2Tokenizer from oslo.models.gpt_neo.modeling_gpt_neo import ( GPTNeoForCausalLM, GPTNeoForSequenceClassification, GPTNeoModel, ) class TestPPInference: def __init__(self, num_gpus): self.num...
"""(c) All rights reserved. ECOLE POLYTECHNIQUE FEDERALE DE LAUSANNE, Switzerland, VPSI, 2017""" import ldap3 from epflldap.utils import get_optional_env, EpflLdapException def _get_LDAP_connection(): """ Return a LDAP connection """ server = ldap3.Server('ldap://' + get_optional_env('EPFL_LDAP_SERVE...
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2020 Kyoto University (Hirofumi Inaguma) # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """Conduct forced alignment with the pre-trained CTC model.""" import codecs import logging import os import shutil import sys from tqdm import tqdm from n...
def my_reduce(value): number = 0 for v in value: number+=v return number
from playground.network.packet import PacketType, FIELD_NOT_SET from playground.network.packet.fieldtypes import UINT8, UINT16, UINT32, UINT64, \ STRING, BUFFER, \ ComplexFieldType, PacketFields from playground.network...
"""Base class for patching time and I/O modules.""" import sys import inspect class BasePatcher(object): """Base class for patching time and I/O modules.""" # These modules will not be patched by default, unless explicitly specified # in `modules_to_patch`. # This is done to prevent time-travel from...
#!/usr/bin/env python """ Pox-based OpenFlow manager """ import pox.openflow.libopenflow_01 as of from pox.core import core from pox.lib.recoco import * from pox.lib.revent import * from pox.lib.addresses import IPAddr, EthAddr from pox.lib.util import dpid_to_str from pox.lib.util import str_to_dpid from debussy.uti...
import cv2 as cv # noqa import numpy as np # noqa
r""" Module of trace monoids (free partially commutative monoids). EXAMPLES: We first create a trace monoid:: sage: from sage.monoids.trace_monoid import TraceMonoid sage: M.<a,b,c> = TraceMonoid(I=(('a','c'), ('c','a'))); M Trace monoid on 3 generators ([a], [b], [c]) with independence relation {{a, c}}...
from .handler import get_db_handle __all__ = ["get_db_handle"]
#!/usr/bin/env python3 import os # Third Party from flask import Blueprint from flask import request, jsonify from flask import render_template # main from . import routes main = Blueprint('main', __name__) # Routes main.add_url_rule("/", 'root', view_func=routes.root) main.add_url_rule("/api/", 'api', view_func=r...