text stringlengths 3.07k 12.6k |
|---|
###
# Copyright 2015-2020, Institute for Systems Biology
#
# 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 la... |
"""
Ranking Poker Hands
URL: https://www.codewars.com/kata/5739174624fc28e188000465/train/python
A famous casino is suddenly faced with a sharp decline of their revenues.
They decide to offer Texas hold'em also online. Can you help them by
writing an algorithm that can rank poker hands?
Task
Create a poker hand t... |
import traci
from logging import log
from sensors.sensors import sense_characteristics, sense_pedestrians
from algorithm import next_phase
from intersection import NextScheduledPhase
def tsl(step, config, state):
if state.should_switch_phase:
p = calculate_next_phase(step, config, state.phases_state)
... |
from django.conf import settings
from django.core.paginator import Paginator
from django.db.models import Count
from django.shortcuts import get_object_or_404, redirect
from django.template.response import TemplateResponse
from django.urls import reverse
from django.conf import settings
from wagtail.admin.auth import u... |
#!/usr/bin/env python3
"""Loader Module
loading the config and changing some variables inside the config
so that it can be used without anymore refinements.
"""
from copy import deepcopy
import os
from typing import Dict, List, Tuple, Union
from .config import Config, ConfigDict
__all__ = ["load_cfg"]
def _check... |
""" See base class module for general documentation on factories.
"""
from __future__ import print_function, division
import pandas as pd
import logging
from traits.api import Constant, Tuple
from chaco.api import ArrayPlotData, ColorBar, ColormappedSelectionOverlay, \
HPlotContainer, LinearMapper, ScatterInspec... |
import maya.cmds as cmds, os, time
############### update list #########################################
def updateList(update):
cmds.textScrollList('filelistNames', e=True, ra=True)
fileDirectory = cmds.textFieldButtonGrp('fileDirect', q=True, text=True)
prefix = cmds.textFieldGrp('prefix', q=True, ... |
import types
import operator
import six
class Field(object):
getter_takes_serializer = False
def __init__(self, attr=None, call=False, label=None, required=True):
self.attr = attr
self.call = call
self.label = label
self.required = required
def to_value(self, value):
... |
import os
import torch
import glob
class Config(object):
def __init__(self):
self.target_task = ['qmsum-latent', # 0: qmsum-latent
'arxiv-latent', # 1: arxiv-latent
'govreport-latent', # 2: govreport-latent
][2]
... |
#!/usr/bin/env python3
from os import listdir
from os.path import isfile, join
import argparse
import re
import string
from PIL import Image, ImageFont, ImageDraw
import pystache
def print_hex(val):
return "{0:#0{1}x}".format(val,4)
def process_char(font, char):
# Calculate char info
char_size = font.getsize(ch... |
import os
import argparse
import tensorflow as tf
import pdb
from scripts import configs_cv as C
from rl.configs import parser as ps
from rl.tools.utils import tf_utils as U
def setup_pdb(mode):
if mode == 'on':
pdb.set_trace_force = pdb.set_trace
return
elif mode == 'off':
pdb.set_tr... |
import cidc_api
from datetime import datetime
import json
import os
import pytest
from unittest.mock import MagicMock
from cidc_api.models.models import (
TrialMetadata,
UploadJobs,
Users,
)
from cidc_api.models.templates import ClinicalTrial
from cidc_api.models.templates.sync_schemas import (
_make_s... |
# from matplotlib.animation import FuncAnimation
# from matplotlib.animation import FuncAnimation
import matplotlib.animation as animation
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import fsolve
#################Definition of the Four Bar Linkage
# The values are placeholder. Please change... |
import shutil
import unittest
from pysp.sbasic import SFile
from pysp.serror import SDebug
from pysp.sconf import SConfig
class Expected:
default_vehicle = '''
car:
sedan:
SM6:
transmission: cvt
suv:
QM6:
transmission: cvt
'''.strip()
user_vehicle = '''
car:
... |
import imageio
import torch
import time
from tqdm import tqdm
from animate import normalize_kp
from demo import load_checkpoints
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from skimage import img_as_ubyte
from skimage.transform import resize
import cv2
import os
import a... |
import werkzeug.security
from werkzeug.utils import secure_filename
from flask import render_template, redirect, url_for, flash, request
from flask_login import LoginManager, current_user, login_required, logout_user, login_user
from flask_bootstrap import Bootstrap
from gallery import app, db, models
from gallery.form... |
"""
Serialization of AUTOMATED_LOGGING_SETTINGS
"""
from collections import namedtuple
from functools import lru_cache
from logging import INFO, NOTSET, CRITICAL
from pprint import pprint
from marshmallow.fields import Boolean, Integer
from marshmallow.validate import OneOf, Range
from automated_logging.helpers.sche... |
# -*- coding:utf-8 -*-
__author__ = "ChenJun"
import numpy as np
import tensorflow as tf
from tensorflow.contrib import crf
class BatchNormLayer(object):
"""
batch normalization.
"""
def __init__(self, n_in, inputs):
self.gamma = tf.Variable(initial_value=np.ones(n_in,), dtype=tf.float32, nam... |
from chalice import Chalice
import logging
import json
import random
import re
import os
import sys
import alexa_speech
import langs
app = Chalice(app_name='alexa-proglang')
logger = logging.getLogger()
debug = os.environ.get('DEBUG_MODE')
if debug == '1':
logger.setLevel(logging.INFO)
else:
logger.setLevel(lo... |
#!/usr/bin/env python
#
# These are required fields
#
import os
import subprocess
from time import sleep
import src.core.setcore as core
from src.core.menu import text
# Py2/3 compatibility
# Python3 renamed raw_input to input
try:
input = raw_input
except NameError:
pass
# "This is RATTE (Remote Administrat... |
import numpy as np
import pandas as pd
def create_csv():
source = pd.read_csv("/media/wml/新加卷/flushSTEAD/merged.csv")
source = source.drop(['network_code','receiver_code','receiver_type','receiver_latitude','receiver_longitude',
'receiver_elevation_m','p_status','p_weight','... |
# test module for tfrecords
import glob
import os
import pytest
import tensorflow as tf
from deepforest import get_data
from deepforest import preprocess
from deepforest import tfrecords
from deepforest import utilities
from deepforest.keras_retinanet import models
from deepforest.keras_retinanet.preprocessing import... |
from nltk.corpus import brown
from gensim.test.utils import get_tmpfile
from gensim.models import Word2Vec
from nltk import word_tokenize
from gensim.models import KeyedVectors
from nltk.corpus import stopwords
import logging
import re
import nltk
'''
Sentence similarity with Word2Vec model.
Inputs ------------------... |
# -*- coding: utf-8 -*-
"""
sphinx.directives
~~~~~~~~~~~~~~~~~
Handlers for additional ReST directives.
:copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from docutils import nodes
from docutils.parsers.rst import Directive, d... |
import torch._C
from contextlib import contextmanager
from typing import Iterator
from torch.utils import set_module
# These are imported so users can access them from the `torch.jit` module
from torch._jit_internal import (
Final,
Future,
_overload,
_overload_method,
ignore,
_isinstance,
... |
# Copyright 2018 The Cirq Developers
#
# 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 agreed to in ... |
import speech_recognition as sr
from pydub import AudioSegment, silence
import pandas as pd
import os
import shutil
import time
import json
import traceback
# Wav file correction
def export_corrected_wav(file):
audio = AudioSegment.from_file(file, format="wav")
return audio
# Channels split
def split_channels... |
# Copyright 2020 PerfKitBenchmarker 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 appli... |
import os
import re
import shutil
import tempfile
import xml.etree.ElementTree as ET
import zipfile
from typing import BinaryIO, Dict, Optional, TextIO
from haoda import util
from haoda.backend import xilinx as backend
__all__ = (
'ReportDirUtil',
'ReportXoUtil',
'RtlHlsInfo',
)
REPORT_UTIL_COMMANDS = r'... |
import os
#qt bug ???
os.environ['QT_XKB_CONFIG_ROOT']='/usr/share/X11/xkb/'
from lib.include import *
import matplotlib.cm
# draw -----------------------------------
def image_show(name, image, resize=1):
H,W = image.shape[0:2]
cv2.namedWindow(name, cv2.WINDOW_GUI_NORMAL) #WINDOW_NORMAL
#cv2.namedWindo... |
"""Key entity model"""
import io
import logging
from uuid import uuid4
import mongoengine as me
from paramiko.rsakey import RSAKey
import mist.api.tag.models
from mist.api.users.models import Owner
from mist.api.exceptions import BadRequestError
from mist.api.keys import controllers
from mist.api.keys.base import Base... |
"""Some utility functions to support store operations."""
import base64
import os
from os import getenv
from os.path import exists, join, dirname, isdir, realpath
import sqlite3
from subprocess import call, check_output, PIPE, Popen, CalledProcessError
import six
from pynix.exceptions import NixInstantiationError
de... |
#!/usr/bin/env python
# Packages we're going to use
import math
import numpy as np
# Other pydigree objects
from pydigree.individual import Individual
from pydigree.recombination import recombine
from pydigree.individualcontainer import IndividualContainer
from pydigree.genotypes import ChromosomeSet
from pydigree.s... |
# Copyright (c) <NAME> (<EMAIL>).
#
# 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, distri... |
#!/usr/bin/env python
######################################################################
# Copyright (c)
# <NAME> <<EMAIL>>
# All rights reserved.
#
# This software is licensed as described in the file LICENSE.txt, which
# you should have received as part of this distribution.
#
#################################... |
"""
MIT License
Copyright (c) 2019 Samsung. <EMAIL>
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... |
"""
.. module:: filters
:platform: Unix, Windows
:synopsis: A useful module indeed.
.. moduleauthor::
"""
from django import forms
from django.core.exceptions import ImproperlyConfigured
from django.template.loader import render_to_string
from django.http import QueryDict
from .fields import SimpleCompareField
... |
"""Compute name information for a given location in user-space coordinates
using STAT data. This can be used to fill-in automatically the names of an
instance:
.. code:: python
instance = doc.instances[0]
names = getStatNames(doc, instance.getFullUserLocation(doc))
print(names.styleNames)
"""
from __futur... |
# Copyright The PyTorch Lightning team.
#
# 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 i... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8:
# Author: Binux<<EMAIL>>
# http://binux.me
# Created on 2014-08-09 17:52:49
import json
from tornado import gen
from .base import *
from libs import utils
import traceback
class TPLPushHandler(BaseHandler):
@t... |
from sqlalchemy import and_
from api.opds import LibraryAnnotator
from core.opds import VerboseAnnotator
from core.lane import Facets, Pagination
from core.model import (
DataSource,
LicensePool,
Measurement,
Session,
)
from core.model.configuration import ExternalIntegrationLink
from core.opds import ... |
import pyprind
from datetime import datetime
from django.utils.translation import ugettext as _
from arches.app.models import models
from arches.app.models.resource import Resource
from arches.app.models.system_settings import settings
from arches.app.utils import import_class_from_string
from arches.app.search.search_... |
import colorsys
import re
from enum import Enum
from typing import Tuple
import attr
__all__ = [
"Color",
"BrandColors",
"MaterialColors",
"FlatUIColors",
"Colour",
"BrandColours",
"MaterialColours",
"FlatUIColours",
]
@attr.s(init=False, slots=True)
class Color:
hex_regex = re.c... |
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import codecs
import json
import mock
import os
import shutil
import tempfile
import unittest
from telemetry import story
from telemetry import page as page... |
#!/usr/bin/env python
"""Tests for the pysiaf aperture classes.
Authors
-------
<NAME>
"""
import numpy as np
import pytest
from ..aperture import HstAperture
from ..iando import read
from ..siaf import Siaf, get_jwst_apertures
from ..utils.tools import get_grid_coordinates
@pytest.fixture(scope='module')
def... |
from asyncio import Task, sleep, create_task, gather, CancelledError
from functools import wraps
from queue import Queue, Empty
from random import choice
from typing import Callable
from datek_jaipur.application.adapters.console.adapter import ConsoleGoodsType
from datek_jaipur.utils import run_in_thread_pool
class ... |
"""
The following colors are mentioned in Systra's graphical charter: \n
red shades \n
grey shades \n
rainbow shades : spot colors, vivid and highly contrasted \n
sorted colors advised for word documents \n
secondary colors \n
"""
import itertools
import matplotlib.pyplot as plt
import numpy as np
# Couleurs d'accomp... |
import time
from pynamodb.constants import (CAMEL_COUNT, ITEMS, LAST_EVALUATED_KEY, SCANNED_COUNT,
CONSUMED_CAPACITY, TOTAL, CAPACITY_UNITS)
class RateLimiter(object):
"""
RateLimiter limits operations to a pre-set rate of units/seconds
Example:
Initialize a RateLi... |
#!/usr/bin/env python
#
# Copyright 2014 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
from django.shortcuts import render, redirect, get_object_or_404
from django.utils import timezone
from django.db import connection
from .forms import EventCreationForm, EditEventForm
from rso_manage.models import RSO, Registrations
from events.models import Event, Attending
from users.models import Member
import event... |
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import json
import datetime
import os
START_DATE = datetime.date(2014, 9, 10)
END_DATE = datetime.date(2016, 7, 16)
def read_stories_without_tags():
stories = list()
current_date = START_DATE
while current_da... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Python Setuptools for Mathics core
For the easiest installation:
pip install -e .
This will install the library in the default location. For instructions on
how to customize the install procedure read the output of:
python setup.py --help install
In additi... |
import re
files_pattern = re.compile(r"files=(\d+)")
size_pattern = re.compile(r"size=([\d.]*)(.*)")
hosts_pattern = re.compile(r"hosts=(\d+)")
keywords = {
'agg': ":AGGREGATE",
'exg': ":EXCHANGE",
'alt': ":ANALYTIC",
'select': ":SELECT",
'hjoin': ":HASH JOIN",
'ljoin': ":NESTED LOOP JOIN",
... |
# A part of NonVisual Desktop Access (NVDA)
# Copyright (C) 2006-2021 NV Access Limited, <NAME>, Accessolutions, <NAME>
# This file is covered by the GNU General Public License.
# See the file COPYING for more details.
import wx
import gui
import config
from logHandler import log
from speech import SpeechSequ... |
"""
OpenID Connect relying party (RP) authentication backends
=========================================================
This modules defines backends allowing to authenticate a user using a specific token endpoint
of an OpenID Connect provider (OP).
"""
import base64
import hashlib
import requests
f... |
# USAGE: python3 makelr.py file.mgr file_out.py
# But you may want to use compose.py instead.
from grammar import ReprWrap
with open(__file__[:-3] + '_template') as f:
parser_template = f.read()
class State:
def __init__(self, kernel):
self.kernel = kernel
self.items = None
self.act... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from... |
import asyncio
import asyncssh
import sys
import os
import crypt
from importlib.util import find_spec
class MySSHServerSession(asyncssh.SSHServerSession):
def __init__(self, device='iosxr'):
self._input = ''
self._data = None
self.device = device
self.run_as_shell = False
s... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import ast
from dataclasses import dataclass, fields as dataclass_fields
from typing import Any, Callable, Dict, List, Optional
import torch
from pytorchvideo.data.dataset_manifest_utils import (
EncodedVideoInfo,
VideoClipInfo,
Video... |
# -*- coding: utf-8 -*-
"""Tests of early stopping."""
import unittest
from typing import List
import numpy
import pytest
import torch
from torch.optim import Adam
from pykeen.datasets import Nations
from pykeen.evaluation import RankBasedEvaluator
from pykeen.models import Model, TransE
from pykeen.stoppers.early_... |
# Copyright (c) Gorilla-Lab. All rights reserved.
from typing import List
try:
from itertools import ifilterfalse
except ImportError: # py3k
from itertools import filterfalse as ifilterfalse
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import gorilla... |
# coding: utf-8
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from dj... |
#!/usr/bin/python
"""Chevy Volt trip mode."""
import os
import time
import struct
from typing import List, Union
from panda import Panda
import PySimpleGUI as sg
DEFAULT_SPEED_THRESHOLD = 50
class CarState:
"""Store the current speed and drive mode."""
#: Cooldown for mode switching
MODE_SWITCH_COOLDOW... |
# pylint: disable=missing-docstring,invalid-name,missing-docstring
import asyncio
import unittest
from unittest.mock import patch
from os import environ, path, devnull
import socket
from time import sleep
from subprocess import Popen
from sap.xssec import jwt_validation_facade, constants
from sap import xssec
from test... |
#!/usr/bin/evn python
# -*- coding: utf-8 -*-
########################################################################
#
# Copyright (c) 2017 Baidu, 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 o... |
# Copyright 2022 The OFA-Sys Team.
# All rights reserved.
# This source code is licensed under the Apache 2.0 license
# found in the LICENSE file in the root directory.
import json
import logging
import math
from dataclasses import dataclass, field
from typing import Optional
import torch
from fairseq import metric... |
#
# Copyright (c) 2018 Intel 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 ... |
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from .settings import epayco_settings
from .signals import invalid_confirmation_received, confirmation_was_flagged, valid_confirmation_received, \
confirmation_was_approved, confirmation_was_rejected
fr... |
# coding=utf-8
#
# Copyright 2021 <NAME> al. This file is based on code by the authors denoted below and has been modified from its original version.
#
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except i... |
#Simplified chain construction API.
#Automatically handles keeping Merit Holders' Merit Unlocked, unless told otherwise.
from typing import Union, Dict, List, Any
from e2e.Libs.BLS import PrivateKey, Signature
from e2e.Classes.Transactions.Data import Data
from e2e.Classes.Consensus.Element import Element
from e2e.... |
#!/usr/bin/env python
# Lint as: python3
"""Runs an end-to-end test of the kill fleetspeak feature."""
import sys
import time
from typing import Text
from absl import app
from absl import flags
import psutil
from grr_api_client import api
from grr_api_client import flow as api_flow
from grr_response_test.lib import ... |
from __future__ import division
from keras.optimizers import RMSprop
from keras.callbacks import EarlyStopping, ModelCheckpoint, LearningRateScheduler
from keras.layers import Input
from keras.models import Model
#import matlab.engine
import os, cv2, sys
import numpy as np
from config import *
from utilities import pre... |
import os
import sys
import ssl
import argparse
from seldom.logging import log
from seldom.har2case.core import HarParser
from webdriver_manager.firefox import GeckoDriverManager
from webdriver_manager.microsoft import IEDriverManager
from webdriver_manager.microsoft import EdgeChromiumDriverManager
from webdriver_mana... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
#from layers.box_utils import match, log_sum_exp
from dd_utils import match, log_sum_exp
#
# This a slight modified version from originally implementation
# https://github.com/amdegroot/ssd.pytorch
#
class FocalLoss... |
# Created by zhouwang on 2018/5/5.
from .base import BaseRequestHandler, permission
import datetime
import pymysql
import logging
logger = logging.getLogger()
def argements_valid(handler, pk=None):
error = dict()
name = handler.get_argument('name', '')
path = handler.get_argument('path', '')
comment... |
#!/bin/sh
""":" .
exec python "$0" "$@"
"""
# -*- coding: utf-8 -*-
"""
Copyright (c) 2018 beyond-blockchain.org.
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... |
import tweepy
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
import re
import time
import os
import sys
import json
import concurrent.futures
from ibm_watson import NaturalLanguageUnderstandingV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from i... |
import pytest
from colors import yellow, red
from util import UserError, Logger, merge_into, merge, post_process
def test_new_usererror():
msg = f"hello!"
e: UserError = UserError(msg)
assert e.message == msg
@pytest.mark.parametrize("header", ["test header", None])
@pytest.mark.parametrize("indent_amo... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import ressources.config as config
import ressources.bytesManager as bm
from core.symmetric.galois_Z2 import invertGalois2
import time
#################################################
############ Key Schedule #######################
###################################... |
from utils import *
from torch.utils.data import DataLoader
class BASEModel(torch.nn.Module):
def __init__(self, input1_module, input2_module, embedding1_module, embedding2_module, rec_module):
super(BASEModel, self).__init__()
self.input_user_loading = input1_module
self.input_item_loadi... |
import unittest
import torch
import torchdiffeq
from problems import construct_problem
eps = 1e-12
torch.set_default_dtype(torch.float64)
TEST_DEVICE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
def max_abs(tensor):
return torch.max(torch.abs(tensor))
class TestGradient(unittest.TestCase)... |
import random
import time
import math
class Timer(object):
counter = 0
class Fighter(object): # parent class
counter = 0
hp = 100
maxhp = 100
name = ''
ap = 1
armor = 10
def __init__(self, hp, name, ap=1, armor=10, count=None):
self.hp = hp
self.maxhp = hp
s... |
from __future__ import with_statement
import os
import sys
import types
import unittest
import functools
def ensure_in_path(path):
"""
Ensure that a given path is in the sys.path array
"""
if not os.path.isdir(path):
raise RuntimeError('Tried to add nonexisting path')
def _samefile(x, y)... |
#!/usr/bin/env python3
"""
History library
Copyright (c) 2020-2021 <NAME>
Licensed under the MIT License
Written by <NAME> (<EMAIL>)
"""
# Own library
# pylint: disable=E0401
import lib.analysis as analysis
import lib.cache as cache
import lib.common as common
# Debug
# from pdb import set_trace as st
VAL_TYPE_DICT... |
import unittest
from concurrent import futures
import grpc
from testutils import getZserioApi, TEST_ARGS
def _convertRgbToCmyk(rgb):
# see https://www.rapidtables.com/convert/color/rgb-to-cmyk.html
rr = rgb[0] / 255. * 100
gg = rgb[1] / 255. * 100
bb = rgb[2] / 255. * 100
k = 100. - max(rr, gg, b... |
"""
This module tests the interaction of Kafka with Zookeeper with authentication enabled
"""
import logging
import pytest
import sdk_auth
import sdk_cmd
import sdk_hosts
import sdk_install
import sdk_security
import sdk_utils
from security import kerberos as krb5
from tests import auth
from tests import client
from... |
# Copyright 2013-2021 The Salish Sea MEOPAR Contributors
# and The University of British Columbia
# 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... |
# pylint: disable=invalid-name
"""Contains the basic structure necessary to execute the simulation.
"""
# EdgeSimPy components
from edge_sim_py.simulator import Simulator
from edge_sim_py.components.topology import Topology
from edge_sim_py.components.base_station import BaseStation
from edge_sim_py.components.user imp... |
import uuid
import torch
import argparse
import matplotlib
import numpy as np
import pandas as pd
matplotlib.use('Agg')
import seaborn as sns
from pathlib import Path
import matplotlib.pyplot as plt
from external_libs.hessian_eigenthings import compute_hessian_eigenthings
TRIAL_ID = uuid.uuid4().hex.upper()[0:6]
EXPE... |
# -*- coding: utf-8 -*-
"""
DU task for ABP Table:
doing jointly row BIESO and near horizontal cuts SIO
block2line edges do not cross another block.
The cut are based on baselines of text blocks, with some positive or negative inclination.
- the labels of cuts are SIO
Copy... |
from tensorflow import keras
import tensorflow.keras.layers as layers
LETTERS = list('abcdefghijklmnopqrstuvwxyz')
bn_axis = 3 # channels last
# based on https://github.com/keras-team/keras-applications/blob/master/keras_applications/resnet50.py
def identity_block(input_tensor, kernel_size, filters, stage, block):
... |
# -*- coding: utf-8 -*-
import re
import pytest
from inifile import IniFile
from lektor.markdown import (
ImprovedRenderer,
MarkdownConfig,
)
from lektor_responsive_image import (
ResponsiveImage,
resolve_image,
ResponsiveImageMixin,
ResponsiveImagePlugin,
)
class DummyImage(object)... |
import os
import copy
import torch
import pickle
import numpy as np
from language import Lang
def initialize_env(config):
try:
os.mkdir(config['root'])
except:
print("Directory found!!!!")
config['batch_size'] = int(config['batch_size'])
config['bidirectional'] = True if config['bidir... |
"""
This module modifies the 'Figure' class from 'pylatex'
.. :copyright: (c) 2019 by <NAME>.
:license: MIT, see License for more details.
"""
from pylatex import Figure as FigureOriginal
from pylatex import Package, NoEscape
from .saving import LatexSaving
from .float import FloatAdditions
import matplotlib.pypl... |
"""View for player details."""
import string
from typing import Dict
# from django.db.models import F, Window
# from django.db.models.functions import Rank
from django.db.models import QuerySet
from django.views.generic import DetailView, ListView
from django_cricket_statistics.models import (
Grade,
Player,... |
import onnx
from .base_operator import QuantOperatorBase
from .qdq_base_operator import QDQOperatorBase
from ..quant_utils import find_by_name, get_mul_node, QuantizedValue, QuantizedValueType, attribute_to_kwarg, BiasToQuantize
from onnx import onnx_pb as onnx_proto
class ConvInteger(QuantOperatorBase):
def __in... |
import streamlit as st
import pandas as pd
from datetime import datetime
from folium.plugins import HeatMap
import folium
from streamlit_folium import folium_static
import matplotlib.pyplot as plt
import flickrapi
import random
from dotenv import load_dotenv
import os
import urllib
load_dotenv()
# set page layout
st... |
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
import pandas as pd
from epiweeks import Week
from datetime import date
__author__ = '<NAME>, <NAME>'
__copyright__ = '© Pandemic Central, 2021'
__license__ = 'MIT'
__status__ = 'release'
__url__ = 'https://github.com/solveforj/pandemic-central'... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
# import from deconv import Delinear
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules import conv
from torch.nn.modules.utils import _pair
import math
#iteratively solve for inverse sqrt of a... |
import sys
import enum
from typing import List, Optional, TYPE_CHECKING, Union
from antlr4.Token import CommonToken
from antlr4 import ParserRuleContext, InputStream
from antlr4.tree.Tree import TerminalNodeImpl
import colorama
from colorama import Fore, Style
from .preprocessor.stream import PreprocessedInputStream... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.