content stringlengths 5 1.05M |
|---|
import numpy as np
from rltime.general.type_registry import get_registered_type
from rltime.env_wrappers.vec_env.simple import make_simple_vec_env
from rltime.env_wrappers.vec_env.sub_proc import make_sub_proc_vec_env
from rltime.general.utils import deep_apply, deep_dictionary_update
from .acting_interface import Act... |
'''
test.py
'''
import pytest
import unittest
import pandas as pd
import pandas.api.types as ptypes
import pandas.testing
import re
from tecan_od_analyzer.tecan_od_analyzer import argument_parser, gr_plots, parse_data, read_xlsx, sample_outcome, time_formater, reshape_dataframe, vol_correlation, compensation_lm, gr_... |
# Copyright 2017 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 required by applicable law or ag... |
from pyepsolartracer.client import EPsolarTracerClient
from pyepsolartracer.registers import registers,coils
#from test.testdata import ModbusMockClient as ModbusClient
from pymodbus.client.sync import ModbusSerialClient as ModbusClient
# configure the client logging
import logging
logging.basicConfig()
log = logging... |
from yaml import load
from json import dump
with open("../polyphone/polyphone.yaml", 'r') as in_fp:
with open("../polyphone/polyphone.json", 'w') as out_fp:
new_dict = load(in_fp)
dump(new_dict, out_fp, sort_keys = True, ensure_ascii = False,
indent = 4)
|
from .base import *
DEBUG = True
INSTALLED_APPS += [
"debug_toolbar",
]
MIDDLEWARE += [
"debug_toolbar.middleware.DebugToolbarMiddleware",
]
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
def show_toolbar(request):
return True
DEBUG_TOOLBAR_CONFIG = {
"SHOW_TOOLBAR_CALLBACK": ... |
# package org.apache.helix.model
#from org.apache.helix.model import *
class Partition:
def getPartitionName(self):
"""
Returns String
"""
return _partitionName
"""
Parameters:
String partitionName
"""
def __init__(self, partitionName):
self._... |
from utils.preprocess_utils import get_yolo
import xml.etree.ElementTree as ET
import os
import shutil
class Preprocessor():
def __init__(self):
self.labels = ['with_mask', 'mask_weared_incorrect', 'without_mask']
self.labels_files = None
self.images_files = None
print("Starting p... |
"""
:copyright: Copyright since 2006 by Oliver Schoenborn, all rights reserved.
:license: BSD, see LICENSE_BSD_Simple.txt for details.
"""
from .publisherbase import PublisherBase
from .datamsg import Message
from .. import (policies, py2and3)
class Publisher(PublisherBase):
"""
Publisher use... |
import numpy as np
class NeuralNetwork:
pass
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
urlparse是一个用于对url进行操作的库。
"""
import six
if six.PY2:
import urlparse
elif six.PY3:
import urllib.parse as urlparse
def test_urlsplit():
"""
**中文文档**
将url的各个成分分离。
"""
url = "https://docs.python.org/3/library/urllib.parse.html"
result... |
# -*- coding: utf-8 -*-
__all__ = [
"XLMRobertaEmbedding",
"XLMRobertaWordPieceEncoder"
]
from functools import partial
import warnings
from itertools import chain
import numpy as np
import torch
import torch.nn as nn
from fastNLP.embeddings.contextual_embedding import ContextualEmbedding
from fastNLP.core... |
from github import Github
# Creating this to mass update all of our repos settings.
# First you need to create a personal token (this way the script will know what access you have to repos).
# https://github.com/settings/tokens
# I gave it all access except to delete repos, well because I don't want that power in any... |
import os
import random
import argparse
import numpy as np
import colorsys
from skimage import measure
import tqdm
import open3d as o3d
import torch
import torch.nn as nn
import torch.nn.functional as F
from utils import build_network
def predict(net, device, nb_grid):
x = np.linspace(-1.5, 1.5, nb_grid)
y... |
#!/usr/bin/env python
import argparse
import rospy
from std_msgs.msg import Int32
from geometry_msgs.msg import PoseStamped
from styx_msgs.msg import Lane, Waypoint
import math
import sys
import numpy as np
import csv
class DumpWaypoints():
def __init__(self, outfile):
# initialize and subscribe to the cu... |
import asyncio
import gc
import logging
import os
import tracemalloc
import pamqp
import pytest
from aiomisc_pytest.pytest_plugin import TCPProxy
from yarl import URL
import aiormq
from aiormq import Connection
def cert_path(*args):
return os.path.join(
os.path.abspath(os.path.dirname(__file__)), "certs... |
import json
from concurrent.futures import ThreadPoolExecutor
import psutil
from notebook.base.handlers import IPythonHandler
from tornado import web
from tornado.concurrent import run_on_executor
import os
try:
# Traitlets >= 4.3.3
from traitlets import Callable
except ImportError:
from .utils import Cal... |
# Example of mutual recursion with even/odd.
#
# Eli Bendersky [http://eli.thegreenplace.net]
# This code is in the public domain.
def is_even(n):
if n == 0:
return True
else:
return is_odd(n - 1)
def is_odd(n):
if n == 0:
return False
else:
return is_even(n - 1)
de... |
from django.db import models
class PermissionGroup(models.Model):
'''
权限组表.可以做为菜单名显示
'''
title = models.CharField(verbose_name='权限组名', max_length=32)
def __str__(self):
return self.title
class Permission(models.Model):
'''
权限表
'''
title = models.CharField(verbose_name='权... |
def calc(x):
return x+1 |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#
# Copyright (c) 2018-2019 SMHI, Swedish Meteorological and Hydrological Institute
# License: MIT License (see LICENSE.txt or http://opensource.org/licenses/mit).
try:
import numpy as np
import seawater as sw
except:
pass
class QC(object):
def __init__(s... |
from __future__ import annotations
from typing import List
import pytest
from pydiggy import Facets, Node, generate_mutation, hydrate, is_facets, reverse
@pytest.fixture
def retrieved_data_simple():
return {
"allRegions": [
{
"uid": "0x11",
"_type": "Region",... |
import logging
import re
from bentoml.exceptions import YataiDeploymentException
logger = logging.getLogger(__name__)
def to_valid_docker_image_name(name):
# https://docs.docker.com/engine/reference/commandline/tag/#extended-description
return name.lower().strip("._-")
def to_valid_docker_image_version(ve... |
#Adams Moulton Method:
#implicit corrector Method
import numpy as np
ynp1 = 0.6841
yn = 0.4228
ynm1 = 0.2027
ynm2 = 0
xnp1 = 0.6
xn = 0.4
xnm1 = 0.2
xnm2 = 0
n = 2
h = 0.2
order = 4
def dy(x,y):
dyvalue = 1 + y**2
return dyvalue
i = 0
if order == 2:
print("order2")
while i<=n:
ynp1 ... |
import pytest
from sksurgeryvtk.text.text_overlay import VTKLargeTextCentreOfScreen
def test_position_correct(setup_vtk_overlay_window):
# Create a window, and check the text position
# is correct.
vtk_overlay_window, _, _ = setup_vtk_overlay_window
vtk_text = VTKLargeTextCentreOfScreen("Some text")... |
from asyncio import sleep
from pytest import fixture
from pytest_gather_fixtures import ConcurrentFixtureGroup
Foo = ConcurrentFixtureGroup('Foo')
@Foo.fixture
async def s1(parallel_checker):
with parallel_checker.context('1_start'):
await sleep(0.1)
return 1
@Foo.fixture
async def s2_1(parallel_... |
"""Run static analysis on the project."""
import argparse
import os
import sys
import shutil
import subprocess
import tempfile
def do_process(args, shell=False):
"""Run program provided by args.
Return True on success.
Output failed message on non-zero exit and return False.
Exit if command is not... |
from config import Config
import torch
import torch.nn as nn
import torch.nn.functional as F
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from dataset import ImageDataSet
from tqdm import tqdm
import time
from model import EAST
from loss import LossFunction
from utils import non_max... |
from .models import *
from .authenticate import AuthorizationError
import time
import json
try:
from json.decoder import JSONDecodeError
except ImportError:
JSONDecodeError = ValueError
class Schoology:
_ROOT = 'https://api.schoology.com/v1/'
key = ''
secret = ''
limit = 20
start = 0
... |
test_connection_success = \
{
"HTTP Status Code" : 200,
"HTTP Reason" : "OK",
"HTTP Body" : {
"result": True
}
}
test_connection_failure = \
{
"HTTP Status Code" : 200,
"HTTP Reason" : "OK",
"HTTP Body" : {
"result": False
}
}
test_connection_inval... |
#!/usr/bin/python
#
#
import sys
import json
import codecs
from collections import OrderedDict
from default import BaseXmlToDictParser
from author_names import AuthorNames
class WrongSchemaException(Exception):
pass
class MissingDoiException(Exception):
pass
class MissingAuthorsException(Exception):
... |
"""
In some sessions, the raw data were mistakenly loaded as ADBit values in Offline Sorter.
It significantly decreased the amplitude of the waveform of those clusters isolated under that setting.
This program converts the amplitude of those clusters by using ADbit value
"""
def main(query):
"""
Input: SQL q... |
# -*- encoding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
import odoo.addons.decimal_precision as dp
from odoo.exceptions import UserError
class PurchaseRequisitionType(models.Model):
_name = "purchase.requisition.type"
_descr... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@file preprocessing.py
@brief turn an audio block of arbitrary length into
a transformed output of unified length
@author paradigm
"""
import logging
import numpy as np
from scipy.fft import dct
class AudioPreprocessor:
""... |
""" Write a function called make_shirt() that accepts a size
and the text of a message that should be printed on the shirt.
The function should print a sentence summarizing the size of
the shirt and the message printed on it."""
def make_shirt(size, message):
return f'The size of the shirt is: {size}\nThe messa... |
"""
Author: David Walshe
Date: 13 May 2021
"""
import logging
from flask import g, current_app # Flask globals
from flask_httpauth import HTTPBasicAuth, HTTPTokenAuth, MultiAuth
from itsdangerous import TimedJSONWebSignatureSerializer as JWS
from werkzeug.security import check_password_hash
from ..models ... |
import importlib
from hydroDL.master import basins
from hydroDL.app import waterQuality
from hydroDL import kPath, utils
from hydroDL.model import trainTS
from hydroDL.data import gageII, usgs
from hydroDL.post import axplot, figplot
import torch
import os
import json
import pandas as pd
import numpy as np
import matp... |
#!/usr/bin/env python
"""
Trains a neural neutwork with MNIST data using TwoLayerModel
"""
import argparse
import numpy as np
import time
import torch
from torch import nn, optim
from taivasnet.dataloaders import MNISTDataLoader
class TwoLayerModel(nn.Module):
def __init__(self):
super().__init__()
... |
from dagster_k8s import DagsterK8sJobConfig, construct_dagster_k8s_job
from dagster_k8s.job import get_user_defined_k8s_config
from docs_snippets.deploying.kubernetes.k8s_config_tag import my_job, my_op
def test_k8s_tag_job():
assert my_job
user_defined_cfg = get_user_defined_k8s_config(my_job.tags)
cfg... |
# Generated by Django 2.2.13 on 2020-08-21 15:09
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("eventstore", "0034_remove_like_indexes")]
operations = [
migrations.AddField(
model_name="covid19triage",
name="place_of_work",
... |
from .data_structures import \
GizmoDataset
from .fields import \
GizmoFieldInfo
|
# -*- coding: utf-8 -*-
from datetime import timedelta
DUTCH_PERIOD = timedelta(minutes=405)
QUICK_DUTCH_PERIOD = timedelta(minutes=10)
TENDER_PERIOD_STATUSES = ['active.tendering', 'active.auction']
NUMBER_OF_STAGES = 80 # from openprocurement.auction.tessel.constants import DUTCH_ROUNDS as NUMBER_OF_STAGES
DUTCH_... |
def max_sum(arr):
lst = []
for i in range(len(arr)):
arr = arr[-1:]+arr[:-1]
add=0
print(arr)
for i in range(len(arr)):
print(i * arr[i])
add += i * arr[i]
lst.append(add)
print("####")
print("Maximum Sum is :"+st... |
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
import glob
import cv2
import numpy as np
import Radiograph
import util
from models import ToothModel, InitializationModel
DATA_DIR = os.path.join(os.path.dirname(__file__), "../../", "resources", "data")
class MaskGenerator:
... |
from typing import Dict
from ray.dag import (
DAGNode,
InputNode,
InputAttributeNode,
FunctionNode,
ClassNode,
ClassMethodNode,
)
class DAGNodeNameGenerator(object):
"""
Generate unique suffix for each given Node in the DAG.
Apply monotonic increasing id suffix for duplicated name... |
"""Reproduction related aspects."""
from schematics.models import Model
from plantstuff.schema.types import (
FloatType,
ListType,
StringType,
)
class PropagationMethod(Model):
"""The plant propagation type."""
name = StringType(
required=True,
choices=[
"bare_root",
... |
"""Unit tests for input / output operations."""
from pkg_resources import resource_filename
from pyirf.io import load_config
# TO DO: test DL2 data in HDF5 and FITS format
def test_load_config():
config_file = resource_filename("pyirf", "resources/config.yml")
assert load_config(config_file) is not None
|
# Generated by Django 3.1.8 on 2021-04-26 13:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('payment_system', '0049_projectsubscription_renewal_date'),
]
operations = [
migrations.AlterField(
model_name='projectsubscripti... |
# Copyright (c) 2019.
# Authored by: Alexandre Ryjoukhine
# Licensed under MIT
import datetime
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm.collections import InstrumentedList
from sqlalchemy import Index
from com.web.web_app import app
import properties as props
app.config['SQLALCHEMY_DATABASE_URI'... |
from html5print import HTMLBeautifier, JSBeautifier, CSSBeautifier
from os import path
from urllib import response
import json
from flask import Response
def file_extension(url):
if url:
url_find = url.find('?')
url = url if url_find == -1 else url[:url_find]
_, ext = path.splitext(url)
... |
from Root import b
import unittest
class test1(unittest.TestCase):
def test_shuffle(self):
self.assertEqual(b.add(1,2),3)
def test_add(self):
self.assertEqual(b.add(4,2),6)
def test_addFail(self):
self.assertEqual(b.add(1,2),4)
if __name__ == '__main__':
unittest.main()
|
'''
Created on Apr 26, 2011
@author: woosanguk
'''
from django.conf.urls.defaults import patterns,include
urlpatterns = patterns('',
)
# index page
urlpatterns += patterns('viewIndex.handler_Index',
(r'^$','handler_Index'),
(r'iphone','handler_Iphone'),
(r'redirect/','handler_Redirect'),
... |
from sqlalchemy.dialects.postgresql import UUID
from app import db
from marshmallow_sqlalchemy import SQLAlchemySchema, auto_field
import uuid
class Genre(db.Model):
__tablename__ = 'genre'
id = db.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
genre = db.Column(db.String(120), nullable... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 9 12:12:25 2017
@author: stu
"""
import openmc
pit = openmc.Material(name='pit')
aDensity49 = 3.7047e-2;
aDensity40 = 1.751e-3;
aDensity41 = 1.17e-4;
aDensityGa = 1.375e-3;
aDensityNi = 9.1322e-2;
aDensity_pit = aDensity49+aDensity40+aDensity... |
import pygame, time
from Model.Game.game import Game
from Controller import Controller
from View.view import View
from moviepy.editor import VideoFileClip
def launchGame():
# Load view and initialize it
view = View(1920, 1050, "assets/images/background.jpg")
view.loadGame()
# Load controller and ru... |
# proxy module
from pyface.splash_screen import *
|
import argparse
import random
from pydub import AudioSegment
from pydub.playback import play
def my_parser():
parser = argparse.ArgumentParser()
parser.add_argument(
"--stringy",
default="The quick brown fox jumps over the lazy dog.",
help="input string"
)
parser.add_argument(
... |
# coding: utf8
import mock
import zeit.cms.browser.breadcrumbs
import zeit.cms.checkout.interfaces
import zeit.cms.repository.folder
import zeit.cms.repository.interfaces
import zeit.cms.testcontenttype.testcontenttype
import zeit.cms.testing
import zeit.cms.workingcopy.interfaces
import zope.publisher.browser
class ... |
import os
from .handlers import DefaultHandler
from jupyter_server.extension.application import ExtensionApp
from jupyter_server.extension.application import ExtensionAppJinjaMixin
DEFAULT_STATIC_FILES_PATH = os.path.join(os.path.dirname(__file__), "static")
DEFAULT_TEMPLATE_FILES_PATH = os.path.join(os.path.dirname(... |
from fog.phonetics.cologne import cologne
from fog.phonetics.rusalka import rusalka
|
from .place import Place
class Recommendation:
def __init__(self, name, place, rating):
self.name = name
self.place = place
self.rating = rating |
"""
This module contains a config dict with simulation related values.
Config values can be provided to the simulator using a json file name after the _CONFIG_FILE constant.
For a complete description of the config specification and its default values,
see the JSON schema (schemas/starling_config.schema.json):
.. li... |
# this is in early stage, now useless but created for using in future
from pydantic import BaseModel
class ProcessEventOptions(BaseModel):
do_not_handle: bool
|
import torch
from dqn_model import DQN, MLP
from utils.gym_dino_run import DinoRunEnv
from utils.extract import get_screen
def infer(env, mlp=False):
action_size = env.action_space.n
if mlp:
policy_net = MLP(num_actions=action_size)
else:
policy_net = DQN()
... |
# https://www.youtube.com/watch?v=RpgcYiky7uw
# https://www.geeksforgeeks.org/strongly-connected-components/
# 強連結成分分解(SCC): グラフGに対するSCCを行う
# 入力: <N>: 頂点サイズ, <G>: 順方向の有向グラフ, <RG>: 逆方向の有向グラフ
# 出力: (<ラベル数>, <各頂点のラベル番号>)
def scc(N, G, RG):
order = []
used = [0]*N
group = [None]*N
def dfs(s):
used... |
# python-mpd2: Python MPD client library
#
# Copyright (C) 2008-2010 J. Alexander Treuman <jat@spatialrift.net>
# Copyright (C) 2012 J. Thalheim <jthalheim@gmail.com>
# Copyright (C) 2016 Robert Niederreiter <rnix@squarewave.at>
#
# python-mpd2 is free software: you can redistribute it and/or modify
# it under the t... |
#
# Copyright 2019 XEBIALABS
#
# 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, merge, publish, distribute, subli... |
from TRANSrisk_fcm_project.settings_management.base_settings import *
#import dj_database_url
# Update database configuration with $DATABASE_URL.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'transrisk_fcm_db',
'USER': 'postgres',
'PASSWORD': 'matis... |
from .algos import ga, es, ga_moo
def get_algo_from_exp(exp):
assert type(exp.policy.handler) is str, "Invalid policy type"
if exp.policy.handler == 'ga_moo':
return ga_moo.GAMoo()
if exp.policy.handler == 'GA':
return ga.GA()
if exp.policy.handler == 'ES':
return es.ES()
|
from paida_core.PAbsorber import *
|
import logging
import pyflux as pf
from TorchTSA.model import ARCHModel
from TorchTSA.simulate import ARCHSim
logging.basicConfig(level=logging.INFO)
arch_sim = ARCHSim((0.6, 0.1), _const=0.1, _mu=0.0)
sim_data = arch_sim.sample_n(1000)
arch_model = ARCHModel(2, _use_mu=True)
arch_model.fit(sim_data)
print(
ar... |
import json
import datetime
def _is_timezone_aware(value):
"""
Determine if a given datetime.datetime is aware.
The concept is defined in Python's docs:
https://docs.python.org/library/datetime.html#datetime.tzinfo
Assuming value.tzinfo is either None or a proper datetime.tzinfo,
value.utcof... |
# Generated by Django 2.0.2 on 2018-06-06 15:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('authority_backend', '0005_storage'),
]
operations = [
migrations.AlterField(
model_name='access',
name='rid',
... |
import os
import time
from multiprocessing.dummy import Pool as ThreadPool
from sudoku.sudokupuzzle import SudokuPuzzle
from sudoku.textfiles import puzzle2text, show_errors_in_file
def fill_file(runs, filename='boards.txt'):
if isinstance(runs, list):
runs, filename, index = runs
print(f'Started... |
#!/usr/bin/python
# coding=utf-8
from flask import Flask
import logging
from logging.handlers import RotatingFileHandler
from redis import Redis
app = Flask(__name__, instance_relative_config=True)
app.config.from_object('config')
app.config.from_pyfile('config.py')
handler = RotatingFileHandler('aggg.log', maxByt... |
import numpy as np
import pandas as pd
def affection_tilt(covdf:pd.DataFrame, love:[str]=None, hate:[str]=None, intensity=1.0):
""" Convert list of tickers loved and hated into relative means
:param covdf: covariance pandas dataframe with tickers as columns and index
:param love:
:param hate:
:... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-06-16 18:45
from __future__ import unicode_literals
import content_gallery.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('content_gallery', '0006_auto_20170504_2334'),
]
operations = ... |
def coinDistance():
coin = hero.findNearestItem()
if coin:
return hero.distanceTo(coin)
return 0
while True:
distance = coinDistance()
if distance > 0:
hero.say(distance)
|
"""curses.panel
Module for using panels with curses.
"""
__revision__ = "$Id: panel.py 18511 2000-12-22 21:58:29Z akuchling $"
from _curses_panel import *
|
import sys # noqa: E402
sys.path.append('../')
from data.restaurants_dao import get_yelp_dataframe # noqa: E402
import unittest # noqa: E402
import pandas as pd # noqa: E402
class TestFilter(unittest.TestCase):
def setUp(self):
data = {
'name': ["John's Chinese BBQ Restaurant", "Delmonic... |
"""Generic testing tools that do NOT depend on Twisted.
In particular, this module exposes a set of top-level assert* functions that
can be used in place of nose.tools.assert* in method generators (the ones in
nose can not, at least as of nose 0.10.4).
Note: our testing package contains testing.util, which does depen... |
#!/usr/bin/env python3
#
# Copyright (C) 2018 Alpha Griffin
# @%@~LICENSE~@%@
from ag.orbit.command import main
from ag.orbit.webapi import Endpoints
from ag.orbit.node.config import get_webapi_interface, get_webapi_port
from ag.orbit.node.db import TokenDB
from flask import Flask, request, abort
import json
class ... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from tensorflow.python.ops import control_flow_ops
def dot(x, y):
"""Compute dot product between a 2-D tensor and a 1-D tensor.
If x is a `[M x N]` matrix, then y is a `M`-vector... |
# @author: Ryan West (ryan.west@sovrin.org)
# This script requires 4 parameters as follows:
# pool_name - The name of the pool you created to attach to the
# Sovrin Network (pool must already exist)
# wallet_name - The name of the wallet containing the DID used to
# send ledger requests (wallet... |
import cython
import numpy as np
def move_right(map: cython.int[:, ::1]) -> tuple:
map_h = map.shape[0]
map_w = map.shape[1]
new_map: cython.int[:, :] = np.zeros_like(map)
changed = False
for x in range(map_w):
for y in range(map_h):
x_inc = x + 1 if x + 1 != map_w else 0
... |
#-*- coding:utf-8 -*-
import os
import time
import random
import redis
import sys
sys.path.append(os.path.dirname(__file__))
from PluginManager import PluginManager
def start():
r = redis.Redis(host="127.0.0.1", port=6379, db=0)
# load the plugins for every device
plugin_manager = PluginManager()
... |
import os
import sys
import random
import time
from datetime import datetime
import numpy as np
import math
import argparse
random.seed(42)
from tqdm import tqdm
import logging
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO, format="%(message)s")
from tensorboardX import SummaryWriter #... |
import torch
from modeling_layoutlm import LayoutLMForTokenClassification
from transformers import (
BertConfig,
BertTokenizer,
)
from utils_docvqa import (
read_docvqa_examples,
convert_examples_to_features)
from torch.utils.data import DataLoader, SequentialSampler, TensorDataset
from transformers.dat... |
class ValidationException(Exception):
""" Thrown when validation fails """
pass
class BadValidatorException(Exception):
""" Thrown when a validator is bad """
def __init__(self, extra):
message = "Row does not contain the following unique_with fields: {}"
super(BadValidatorException,... |
from flask import Flask
import sqlite3
import time
# TODO: Create table that handles "current time"?
create_param_table = """
CREATE TABLE IF NOT EXISTS parameters
(distribution TEXT, params BLOB)
"""
def create_app():
app = Flask(__name__)
conn = sqlite3.connect('mcwi.db')
c = conn.cursor()
... |
import pytest
from ocs_ci.framework.pytest_customization.marks import tier1
@tier1
@pytest.mark.last
class TestFailurePropagator:
"""
Test class for failure propagator test case. The test intention is to run last and propagate
teardown failures caught during the test execution, so regular test cases won'... |
# -*- encoding: utf-8 -*-
from __future__ import unicode_literals
import datetime
import os
import re
import mimetypes
from tempfile import SpooledTemporaryFile
import django
from django.conf import settings
from django.core.exceptions import SuspiciousFileOperation
from django.core.files.base import File
from django... |
# _ _ _
# / \ _ __ __| (_)_ __ ___ _ __ _ _
# / _ \ | '_ \ / _` | | '_ \ / _ \| '_ \| | | |
# / ___ \| | | | (_| | | | | | (_) | |_) | |_| |
# /_/ \_\_| |_|\__,_|_|_| |_|\___/| .__/ \__, |
# |_| |___/
# by Jakob Groß
import abc
class ... |
#
# Copyright 2016 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 ... |
frase = ' Curso em Vídeo Python '
print(frase[::2])
print(frase.count('o'))
print(frase.count('O'))
print(frase.upper().count('O'))
print(len(frase))
print(len(frase.strip()))
print(frase.replace('Python', 'Android'))
print('Curso' in frase)
print(frase.find('Vídeo'))
print(frase.find('vídeo'))
print(frase.lower().... |
from py2neo import Graph,authenticate,Node,Relationship
import MySQLdb
import threading
authenticate("localhost:7474","neo4j","8760neo4j")
graph = Graph()
mynode = list(graph.find('fw', property_key='count'))
ct=1
fobj = open("textdump1.txt","r").readlines()
file_tacker=open("tarcker.txt","a")
#for i in fobj:
def inde... |
import random
import subprocess
char = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z']
char1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y',... |
import xmltodict
class Reader:
def __init__(self, format_type):
self.format_type = format_type
def read_file(self, path):
with open(path, "r") as file:
data = file.read()
return self._parse_xml(data)
def _parse_xml(self, xml_data):
json_da... |
#!/usr/bin/python
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: import_workload_cleanup
short_description: Clean up temporary vo... |
"""Factory for generating CARD AMR result models for testing."""
from random import randint
from app.tool_results.card_amrs import CARDAMRToolResult
def simulate_gene():
"""Return one row."""
gene_name = 'sample_card_amr_gene_{}'.format(randint(1, 100))
rpk = randint(1, 1000) / 0.66666
rpkm = randin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.