text stringlengths 3.07k 22.1k |
|---|
"""
This code provides some utility functions for the mhe implementation.
"""
import numpy as np
import bioptim
from biosiglive.io.save_data import add_data_to_pickle
from biosiglive.gui.plot import LivePlot
from time import strftime
import datetime
from scipy.interpolate import interp1d
import os
def check_and_adju... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2016, <NAME> <<EMAIL>>
# Copyright: (c) 2016, <NAME> <<EMAIL>>
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METAD... |
# -*- coding: utf-8 -*-
"""
Find cuts of a page and generates BIESO annotation
Do BIESO in each cell, taking into account x-overlap
Compute usual metrics is MPXML is annotated
It looks for horizontal or vertical cuts, tolerating to cut accross some small object along its path (hyperpara... |
# Copyright 2021 Cambridge Quantum Computing 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 a... |
# -*- coding: utf-8 -*-
"""
TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-权限中心(BlueKing-IAM) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with th... |
from som.interpreter.bc.bytecodes import bytecode_length, Bytecodes
from som.interpreter.control_flow import ReturnException
from som.vmobjects.block_bc import BcBlock
from rpython.rlib import jit
class Interpreter(object):
_immutable_fields_ = ["_universe", "_add_symbol"]
def __init__(self, universe):
... |
#-*- coding: utf-8 -*-
# audio-offset-finder
#
# Copyright (c) 2014 British Broadcasting Corporation
# Copyright (c) 2018 <NAME>
# Copyright (c) 2021 <NAME>
#
# 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 t... |
# Copyright (c) 2013 Rackspace
# 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... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 1999-2018 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-... |
from copy import copy
import logging
import os
from random import choice
from random import randint
import re
import sys
from tabulate import tabulate
from Legobot.Connectors.Slack import Slack
from Legobot.Lego import Lego
LOCAL_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)))
sys.path.append(LOCAL_D... |
# Copyright (c) 2021, <NAME>
# License: MIT License
import pytest
import math
import ezdxf
from ezdxf.upright import upright, _flip_deg_angle
from ezdxf import path
from ezdxf.entities import (
Circle,
Arc,
DXFEntity,
Text,
Solid,
Trace,
Ellipse,
LWPolyline,
Hatch,
)
from ezdxf.ma... |
import tensorflow as tf
from tensorflow.contrib import layers
from config import MovieQAPath
from raw_input import Input
_mp = MovieQAPath()
hp = {'emb_dim': 256, 'feat_dim': 512, 'dropout_rate': 0.2}
def dropout(x, training):
return tf.layers.dropout(x, hp['dropout_rate'], training=training)
def l2_norm(x, a... |
import os
import random
import re
import time
import string
import weakref
from io import StringIO
from functools import partial
from itertools import tee, filterfalse
from typing import Union, Any
import importlib
import types
import blosc
import wrapt
from . import __version__
from .constants import DIR_HANGAR
cl... |
"""Tree based data generation script for logic programs."""
import argparse
import random as R
# Symbol Pool
CONST_SYMBOLS = "abcdefghijklmnopqrstuvwxyz"
VAR_SYMBOLS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
PRED_SYMBOLS = "abcdefghijklmnopqrstuvwxyz"
EXTRA_SYMBOLS = "-,()"
CHARS = sorted(list(set(CONST_SYMBOLS+VAR_SYMBOLS+PRED... |
'''A collection of useful classes and functions for asynchronous programming.
'''
from abc import ABC, abstractmethod
import asyncio
from datetime import datetime, timedelta
import functools
from typing import Coroutine, ParamSpec, TypeVar, Callable, Generator, Generic, AsyncGenerator, Any
T = TypeVar('T')
U = TypeVa... |
"""
zeep.wsdl.definitions
~~~~~~~~~~~~~~~~~~~~~
A WSDL document exists out of a number of definitions. There are 6 major
definitions, these are:
- types
- message
- portType
- binding
- port
- service
This module defines the definitions which occur within a WSDL docu... |
# mypy: ignore-errors
from collections import defaultdict
from typing import (
Iterable,
List,
Optional,
Tuple,
Union,
Dict,
DefaultDict,
Sequence,
Mapping,
NamedTuple,
)
import numpy as np
from rlo import analytics
from rlo.cum_sequence import CumMaxSequence
from rlo.expressio... |
import fnmatch
import math
import os
import sys
from operator import itemgetter
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from PIL import Image
from torch.utils.data import Dataset
from torchvision import transforms
from darknet import Darknet
class PatchTransformer(nn.Mod... |
import numpy as np
from copy import deepcopy
import torch
from enum import Enum
from ..constants.constants import (
PredictionKeys,
TrainingMetaKeys,
PredictionMetaKeys
)
from ..exceptions import IllegalArgument
from .model_template import ModelTemplate
from ..estimators.stan_estimator import StanEstimator... |
import sys
import bleAdapter
from bleAdapter import bleAdapter
import time
import dbus.mainloop.glib
try:
from gi.repository import GObject
except ImportError:
import gobject as GObject
mainloop = GObject.MainLoop()
testResult = None
def discoveryStoppedCb(testDevice = None):
global testResult
testResult ... |
from __future__ import print_function
import os, time
from io import StringIO
import scipy.misc
import numpy as np
from glob import glob
from tqdm import trange
from itertools import chain
from collections import deque
try:
from beholder.beholder import Beholder
from yellowfin import YFOptimizer
except:
pass
from... |
"""
The ``train`` subcommand can be used to train a model.
It requires a configuration file and a directory in
which to write the results.
.. code-block:: bash
$ python -m allennlp.run train --help
usage: python -m allennlp.run [command] train [-h] -s SERIALIZATION_DIR
... |
# ----- CONFIGURE YOUR EDITOR TO USE 4 SPACES PER TAB ----- #
import settings
import sys,os
sys.path.append(os.path.join(os.path.split(os.path.abspath(__file__))[0], 'lib'))
import pymysql as db
NoneType = type(None)
import gensim
from gensim.parsing.preprocessing import remove_stopwords, STOPWORDS
from gensim.parsin... |
from __future__ import division, print_function, absolute_import
import numpy as np
from scipy.ndimage import map_coordinates
from dipy.viz.colormap import line_colors
# Conditional import machinery for vtk
from dipy.utils.optpkg import optional_package
# import vtk
# Allow import, but disable doctests if we don't ... |
#!/usr/bin/python
__author__ = '<NAME>, <NAME>'
#import sys
#sys.path.insert(0, '../lib')
import numpy as np
from .functions import *
from .errors import Error, InputError, FittingError
from .Warning_log import Warning_log
# classes for processing RV files
NDSETMAX=20
class rvfile(object):
def... |
#-----------------------------------------------------------------------------------------------#
# #
# I M P O R T L I B R A R I E S #
# ... |
# -*- coding: utf-8 -*-
#
# packages.py — Packages controller
#
# This file is part of debexpo - https://alioth.debian.org/projects/debexpo/
#
# Copyright © 2008 <NAME> <<EMAIL>>
# Copyright © 2010 <NAME> <<EMAIL>>
# 2011 <NAME> <<EMAIL>>
#
# Permission is hereby granted, free of charge, to any ... |
"""Utilities for identifying local IP addresses."""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import os
import re
import socket
from subprocess import Popen, PIPE
from warnings import warn
LOCAL_IPS = []
PUBLIC_IPS = []
LOCALHOST = ''
def _uniq_stable(e... |
# Copyright 2020 The TensorFlow 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 applica... |
# coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..compat import compat_str
from ..utils import (
parse_iso8601,
parse_duration,
)
class SkyNewsArabiaBaseIE(InfoExtractor):
_IMAGE_BASE_URL = "http://www.skynewsarabia.com/web/images"
def _call_api(self, p... |
from flask import Flask, session, Response
from Module.randomCmdMenu import RandomCmdMenu
from Module.randomBGM import RandomBGM
from Module.startingInventory import StartingInventory
from Module.modifier import SeedModifier
from Module.seedEvaluation import SeedValidator
from List.configDict import miscConfig, locatio... |
import os
import numpy as np
import skimage
import skimage.io
import csv
import glob
import h5py
import re
from tqdm import tqdm
from util import im_processing, text_processing
debug = False
# root directory
root_dir = os.getcwd()
# data directory
a2d_dir = '/mnt/lustre/share/huitianrui/DATASET/A2D-Sentences'
def b... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
from copy import deepcopy
from typing import Dict, List, Tuple
import torch
from torch import Tensor
from torch.nn import Module
def config_list_canonical(model: Module, config_list: List[Dict]) -> List[Dict]:
'''
Split the config by o... |
# why?: predict side effects in biotech
# how?: identify K-length substrings of a target not present in a host
# what?: hamming distance cutoff
import multiprocessing as mp
import os
from itertools import product
from Bio import AlignIO, SeqIO
from cassandra.cluster import Cluster
from tqdm import tqdm
# cpus
CPUS = ... |
import numpy as np
import torch
from ..primitives import inside_outside_function, points_to_cuboid_distances, \
transform_to_primitives_centric_system, deform, \
ray_plane_intersections
from ..utils.stats_logger import StatsLogger
def _euclidean_dual_loss_impl(
X,
prim_params,
sampler,
use_... |
#!/usr/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
"""
Base class for reading NLP tagging data.
"""
import os
import re
import abc
import logging
import numpy as np
from collections import Counter
from nlpnet import attributes
from nlpnet import metadata
from nlpnet import config
from... |
import os
import sys
from dued import Programa
import pytest
from _util import confirmar, trap, RAIZ
marcapytest = pytest.mark.usefixtures("integracion")
@trap
def _completar(invocacion, coleccion=None, **kwargs):
cadenacol = ""
if coleccion:
cadenacol = "-c {}".format(coleccion)
comando = "d... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2018 <NAME> <<EMAIL>>
#
# Distributed under terms of the MIT license.
"""
cluster_generation.py
In this script, I will explore several approaches on generation of cluster files for each problem.
The output will be simply a npz file with n... |
#! -*- coding:utf-8 -*-
# 文本分类例子下的模型压缩
# 方法为BERT-of-Theseus
# 论文:https://arxiv.org/abs/2002.02925
# 博客:https://kexue.fm/archives/7575
import json
import numpy as np
from bert4keras.backend import keras, K
from bert4keras.tokenizers import Tokenizer
from bert4keras.models import build_transformer_model
from bert4keras.... |
#!/usr/bin/env
# -*- coding: utf-8 -*-
"""
Copyright 2017-2018 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable l... |
import numpy as np
def shannon(data, sigma=1.0):
"""Given data (squared differences of vectors), return the entropy and p_ij values for the data."""
# Compute P-row and corresponding perplexity
arg = -data/(2*sigma**2)
if (arg > 0).any():
raise ValueError('At least one probability is negative'... |
import numpy as np
from scipy.special import expit
from math import ceil
# Given a predicate's semantic function, calculate a distribution over entity vectors,
# approximating the posterior distribution over entities, given that the predicate is true
### Initialisation
def get_semfunc(pred_wei, pred_bias):
"""
... |
import sys
from time import sleep
import pygame
from bala import Bala
from alien import Alien
def check_keydown_events(event, config, screen, nave, balas):
if event.key == pygame.K_RIGHT:
# move a espaçonave para a direita
nave.mover_direita = True
# move a espaçonave ... |
#! /home/smithw/.tensorflow2/bin/python
# use python in (TF2) venv on acer: opencv installed there
# video_testing.py
# WESmith 02/08/22
# test out opencv video processing for change detection, etc.
import cv2
import os, sys, time
import pickle
import pdb
class VideoGrab():
def __init__(self, data, scale, row_f... |
from torch.utils.tensorboard import SummaryWriter
from base_config import BaseConfigByEpoch
from model_map import get_model_fn
from data.data_factory import create_dataset, load_cuda_data, num_iters_per_epoch
from torch.nn.modules.loss import CrossEntropyLoss
from utils.engine import Engine
from utils.pyt_utils import ... |
import datetime
from datetime import datetime as dt
from datetime import date
import time
import re
#basic search with error handling
def check(search_params,string):
try:
data = re.search(search_params,string)
if data != None:
return data.group(0)
else:
return None
... |
"""
/*******************************************************************************
* Copyright (c) 2011, 2013 IBM Corp.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Eclipse Distribution License v1.0 which accomp... |
import argparse
import datetime
import json
import random
import time
from pathlib import Path
import numpy as np
import torch
from PIL import Image
from PIL import ImageDraw,ImageFont
from models import build_model
import datasets.transforms as T
from util import box_ops
def get_args_parser():
parser = argpars... |
from collections import defaultdict
result = 0
logFile = open("log1.txt", "w")
def printLog(*s):
s = " ".join([str(i) for i in s])
logFile.write(s)
logFile.write("\n")
class Group():
def __init__(
self,
id,
faction,
numUnits,
hitPoints,
weaknesses,
... |
# Copyright 2018 Tensorforce Team. 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 la... |
from typing import Union, Any, Sequence, Dict, Tuple, Optional
import numpy as np
import tensorflow as tf
from tensorflow import Tensor as _Tensor
from babilim.core.itensor import ITensor, ITensorWrapper
_variable_wrappers = {}
class TensorWrapper(ITensorWrapper):
def __init__(self):
pass
def wrap... |
import logging
import datetime
from discord.ext import commands
from utils import Flipbook
log = logging.getLogger(f'charfred.{__name__}')
class Admin(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.cfg = bot.cfg
@commands.command(hidden=True)
@commands.is_owner()
async d... |
# MLP
import csv
from itertools import islice
import random
import matplotlib.pyplot as plt
import numpy as np
from sklearn.neural_network import MLPRegressor
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import KFold, train_test_split
import pandas as pd
from sklearn.utils import shuffle
... |
# Copyright (c) 2015-2021 <NAME> and contributors.
# mc3 is open-source software under the MIT license (see LICENSE).
__all__ = [
'ROOT',
'ignore_system_exit',
'parray',
'saveascii', 'loadascii',
'savebin', 'loadbin',
'isfile',
'burn',
'default_parnames',
]
import os
import sys
imp... |
#!/usr/bin/env python
"""Prepare a Review Board tree for development."""
from __future__ import print_function, unicode_literals
import argparse
import os
import platform
import stat
import subprocess
import sys
from random import choice
# This is one of the few things in Django that is safe to import here.
from dja... |
from decimal import Decimal
from exceptions import ValueError
import colorsys
class Temperature(object):
"""
A class for working with temperatures. It provides helpers for converting
between Kelvin, Celsius, Fahrenheit, and Rankine. Internally, the
temperature is stored as Kelvin in a Decim... |
#!/usr/bin/python3 -O
import argparse
import os
import re
import configparser
import sys
import socket
import lib.misc as misc
import json
import pwd
isRoot = (pwd.getpwuid( os.getuid() ).pw_uid == 0)
#
# This is needed to force ipv4 on ipv6 devices. It's sometimes needed
# if there isn't a clean ipv6 route to get to... |
import math
import fvcore.nn.weight_init as weight_init
import torch.nn.functional as F
from torch import nn
import torch
import numpy as np
from detectron2.layers import (
Conv2d, ShapeSpec, get_norm, cat
)
from mvdnet.layers import MaxPool2d, ConvTranspose2d
from detectron2.modeling import Backbone
from detectr... |
#!/usr/bin/env python
"""kmer.py
Classes to convert dsk counts to sklearn objects
"""
import contextlib
import dask.delayed
from dask.diagnostics import ProgressBar
import dask.array as da
from dask_ml.decomposition import PCA
import dask.multiprocessing
import logging
import os
import numpy as np
import plyvel
imp... |
from __future__ import division
from __future__ import print_function
# 路径初始化
import os, sys
curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(curPath)[0]
sys.path.append(rootPath)
sys.path.append('E:\\Anaconda\\lib\\site-packages\\')
# print(sys.path)
print('Path initialization finished!\n... |
# Zip lists: zipped_lists
zipped_lists = zip(feature_names, row_vals)
# Create a dictionary: rs_dict
rs_dict = dict(zipped_lists)
# Print the dictionary
print(rs_dict)
# Define lists2dict()
def lists2dict(list1, list2):
"""Return a dictionary where list1 provides
the keys and list2 provides the values."""
... |
#%%
from __future__ import print_function
import os
import cv2
import torch
import argparse
import numpy as np
from glob import glob
import torch.backends.cudnn as cudnn
from data import cfg_mnet, cfg_re50
from layers.functions.prior_box import PriorBox
from utils.nms.py_cpu_nms import py_cpu_nms
from model... |
import datetime
import pytest
from coronastats import db
from playhouse.shortcuts import model_to_dict
pytestmark = pytest.mark.usefixtures("db")
def test_add_corona_log_inserts_new():
assert list(db.CoronaLog.select()) == []
today = datetime.date.today()
yesterday = today - datetime.timedelta(days=1)
... |
# extract_upstream_regions.py
# script that accepts a 2 column file of locus
# ids and a boolean flag of whether than locus
# might be in an operon. It returns a fasta file
# from 1 base before the ATG through -300bp
# upstream for all genes NOT possibly in an operon.
import argparse
from Bio import SeqIO
import os
i... |
import asyncio
import json
import os
import time
import warnings
import wave
from queue import Queue
from typing import Callable
import numpy as np
import pvporcupine
import sounddevice as sd
import vosk
from fluxhelper import osInterface
from speech_recognition import AudioFile, Recognizer, UnknownValueError
from ten... |
import math
def swap(arr, i, j):
arr[i], arr[j] = arr[j], arr[i]
def selection_sort(a, lo, hi):
for i in range(lo, hi):
m = i
for j in range(i, hi):
if a[j] < a[m]:
m = j
swap(a, i, m)
def bubble_sort(a, lo, hi):
for i in range(lo, hi):
for j... |
import csv
import six
import sys
import time
from datetime import (
datetime,
date,
timedelta,
)
from xml.etree import cElementTree as ElementTree
from django.core.management.base import BaseCommand
from corehq.apps.users.util import SYSTEM_USER_ID
from corehq.form_processor.backends.sql.dbaccessors impo... |
import platform
from conans.client.graph.graph import CONTEXT_BUILD
from conans.errors import ConanException
class _SystemPackageManagerTool(object):
mode_check = "check"
mode_install = "install"
tool_name = None
install_command = ""
update_command = ""
check_command = ""
def __init__(se... |
import os, sys
import numpy as np
import pandas as pd
import scipy
import scanpy.api as sc
import anndata
## plot
import matplotlib.pyplot as plt
from preprocess import load_pancreatic_data
from preprocess import load_mousebrain_data
from preprocess import load_mouseFC_data
from preprocess import purify_cells
FEAST_... |
import logging
from http import HTTPStatus
from typing import Dict, Optional
from urllib.parse import urlencode
import pytest
from django.http import (
HttpResponseBadRequest,
HttpResponseNotAllowed,
HttpResponseNotFound,
)
from django.test import Client
from django.urls import reverse
from pytest_django.a... |
import tweepy
import logging
from botConfig import create_api
import time
from shutil import copyfile
import os,sys
import subprocess
from datetime import datetime
from unidecode import unidecode
import re
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger()
def check_mentions(api, since_id):
logg... |
import os
import uuid
class PageRep:
def __init__(self,
ownerParcelInfoItem,
valueInfoItemList,
saleTransferInfoItemList,
pageUrl
):
self.OwnerParcelInfo = ownerParcelInfoItem
self.ValueInfoItemList = valueInfoItemList
self.SaleTransferInfoList = saleTransferInfoItemLis... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# LICENSE file in the root directory of this source tree.
# this script is a prototype implementation of transferring H... |
import time
import uuid
from datetime import datetime
from notion.block.basic import (
TextBlock,
ToDoBlock,
HeaderBlock,
SubHeaderBlock,
PageBlock,
QuoteBlock,
BulletedListBlock,
CalloutBlock,
ColumnBlock,
ColumnListBlock,
)
from notion.block.collection.media import CollectionV... |
from lib2to3.refactor import MultiprocessingUnsupported
import uuid
from xmlrpc.client import _iso8601_format
from flight_blender.celery import app
import logging
from scd_operations.scd_data_definitions import Volume4D
from . import dss_rid_helper
import redis
from auth_helper.common import get_redis
from .... |
# -*- coding: utf-8 -*-
import itertools
from collections import namedtuple, defaultdict
from ethereum import slogging
from raiden.blockchain.abi import (
CONTRACT_MANAGER,
CONTRACT_CHANNEL_MANAGER,
CONTRACT_NETTING_CHANNEL,
CONTRACT_REGISTRY,
)
from raiden.exceptions import (
AddressWithoutCode,
... |
import time
from fastapi import APIRouter, Request, BackgroundTasks
from loguru import logger
from func.jd_web_hook.models import WebHookItem
from conf import Settings
from robak import Jdy, JdySerialize
doc = '''
客户实销量核对单 -> 流程完成 -> 触发
目标表单:
客户自销量奖励核算申请
新增或修改:
(新... |
from itertools import starmap, repeat
from operator import add, mod
from functools import reduce
from telegram.ext import Updater
from telegram import error, Bot
from googletrans import Translator
from re import compile
import re
tr = Translator()
trans_re = compile(r"^([\S]*)\s*(\'[\w\-]*\')?\s*(.*)", re.M|re.U|re.DO... |
import random
from typing import List
from enforce_typing import enforce_types
from agents.PoolAgent import PoolAgent
from sol057.contracts.oceanv3 import oceanv3util
from engine import AgentBase
from util import globaltokens
from util.base18 import toBase18
from util.constants import S_PER_DAY
# magic numbers
DEFAU... |
import datetime
import sqlite3
import sys
import time
import discord
from discord.ext import commands
sys.path.insert(0, '')
from TypeRacerStats.config import MAIN_COLOR
from TypeRacerStats.file_paths import DATABASE_PATH
from TypeRacerStats.Core.Common.accounts import check_account, check_banned_status, get_player
fro... |
import numpy as np
import skimage.draw
def swapRB(im):
"""Swaps the first and third channels (i.e. swaps RGB to BGR).
Parameters
----------
im : np.ndarray
(GBR) image array.
Returns
-------
np.ndarray
(RGB) image array.
"""
cp = im.copy()
cp[:, :, 0] ... |
# This work is based on original code developed and copyrighted by TNO 2020.
# Subsequent contributions are licensed to you by the developers of such code and are
# made available to the Project under one or several contributor license agreements.
#
# This work is licensed to you under the Apache License, Version 2... |
import time
import random
import os
from time import sleep
secret = 0
def clear():
if os.name == 'nt':
os.system("cls")
else:
os.system("clear")
def madlibs_10():
clear()
Name = input("Name: ")
Verb = input("Verb: ")
Noun = input("Noun: ")
Place = input("Place: ")
print... |
from random import choice
class TSPGraph:
"""
Class to create a directed graph.
"""
def __init__(self, vertices, edges=[]):
"""
Initialize Graph object with vertices
and (optional) directed edges
args:
vertices: List of nodes in graph
edges: (Optional) List of tuples where
each tuple is format... |
# RUN: %PYTHON %s | FileCheck %s
from typing import Optional, Sequence
from mlir.ir import *
from mlir.dialects import builtin
from mlir.dialects import linalg
from mlir.dialects import std
from mlir.dialects.linalg.opdsl.lang import *
@linalg_structured_op
def matmul_mono(A=TensorDef(T, S.M, S.K),
... |
#
# MIT License
#
# Copyright (c) 2020 Airbyte
#
# 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, pu... |
import time
import pytest
from c4.system.backend import Backend
from c4.system.deviceManager import DeviceManagerStatus
from c4.system.manager import SystemManagerStatus
from c4.utils.jsonutil import Datetime
class MockDeviceManagerStatus(DeviceManagerStatus):
def __init__(self, value, timestampString):
... |
"""DBF fields definitions.
TODO:
- make memos work
"""
"""History (most recent first):
26-may-2009 [als] DbfNumericFieldDef.decodeValue: strip zero bytes
05-feb-2009 [als] DbfDateFieldDef.encodeValue: empty arg produces empty date
16-sep-2008 [als] DbfNumericFieldDef decoding looks for decimal point
... |
import numpy as np
def probability_of_result_list(result_list, inverted_rankings, tau=3.0):
'''
ARGS: (all np.array of docids)
- result_list: the multileaved list
- inverted_rankings: dtype:float matrix (rankers x documents) where [x,y] corresponds to the rank of doc y in ranker x
- clicked_docs: ... |
# -*- coding: utf-8 -*- #
"""*********************************************************************************************"""
# FileName [ preprocess_data.py ]
# Synopsis [ Pre-processing the raw Cornell Movie Dialogs Corpus dataset ]
# Author [ <NAME> (Andi611) ]
# Copyright [ Copyleft(c), NTU... |
# Copyright (c) 2015, Palo Alto Networks
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS... |
""" Prepapres a file from Arxiv data (as well as additional mag contexts) as per the hyperdoc2vec format.
All the citation markers in the output file are MAG Ids (for the ACL papers, the mapping from ACL to
MAG can be found in /home/ashwath/Programs/ArxivCS/SQLITEDB/arxivcs_mag_mapping.sqlite3 -- table name: arxivcs_ma... |
"""
CIS 422 Project 1 Student Roster
Description: The object classes for students and student data handling is implemented here.
Authors: <NAME>, <NAME>, <NAME>
Last modified by: <NAME>
Date last modified: 2/03/20
TODO:
* Design and implement various error handling
"""
# check TODOs
from typing import List
im... |
#!/usr/local/bin/python3
# file: net_eng.py
# author: <NAME>
# created: 2018-12-26
# last modified: 2021-02-06
# purpose:
# common functions I have used over the years when Python scripting against
# networking equipment
# original dates are lost to time, so added dates when added to this module
# usage:
# use at y... |
"""
Generate sources with settings.
"""
from __future__ import absolute_import
import srcgen
from unique_table import UniqueSeqTable
import constant_hash
from cdsl import camel_case
from cdsl.settings import BoolSetting, NumSetting, EnumSetting
from base import settings
try:
from typing import Sequence, Set, Tuple... |
from .array import DataArray
from .units import is_valid_unit
class ConstantDict(dict):
def __repr__(self):
return self._repr()
def _repr(self, sphinx=False):
return_string = ''
for category, name_list in constant_names_by_category.items():
if len(name_list) > 0:
... |
#
# 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 Apache License, Version 2.0
# (the "License"); you may not us... |
# issue: https://github.com/0-complexity/openvcloud/issues/768
def init_actions_(service, args):
"""
this needs to returns an array of actions representing the depencies between actions.
Looks at ACTION_DEPS in this module for an example of what is expected
"""
return {
'test': ['install']
... |
from __future__ import print_function
import operator
import random
from datetime import datetime
from collections import OrderedDict
from six import add_metaclass
try: # pragma: no cover
from .plot import (
draw_peaklist, draw_raw, annotate_scan, annotate_scan_single,
has_plot)
except (RuntimeEr... |
"""Abstract collection for UserContent and sub-classes of StaticSection, HiglassViewConfig, etc."""
from uuid import uuid4
from snovault import (
abstract_collection,
calculated_property,
collection,
load_schema
)
from snovault.interfaces import STORAGE
from .base import (
Item,
ALLOW_CURRENT,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.