text stringlengths 3.07k 12.6k |
|---|
import math
import random
import string
from datetime import datetime, timedelta
from textwrap import dedent
import config
import discord
from discord.ext import commands
import asyncio
actinos_to_search = [
discord.AuditLogAction.ban,
discord.AuditLogAction.unban,
discord.AuditLogAction.kick,
discor... |
from bs4 import BeautifulSoup
import pathlib
import pytest
from emis.scrape import (
parse_utility,
Zdroj,
get_indexes,
Indexes,
retrieve_id,
retrieve_nuts3,
)
@pytest.fixture
def melnik_soup():
with open(pathlib.Path('tests/elektrarna-melnik.html')) as f:
return BeautifulSoup(f.r... |
from json import loads
from typing import Optional, Tuple, Union, Dict, Any
from django.http import HttpRequest
from django.utils.crypto import get_random_string
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from api.models import Course, Post, Tag
class UserS... |
# -*- coding: utf-8 -*-
import sys
import inspect
import argparse
import abc
from fnmatch import fnmatch
from collections import OrderedDict
from six import add_metaclass, text_type
from .resource import Resource
from .resource import Collection, RootCollection
from .schema import ResourceNotDefined
from .utils impor... |
"""doc
# deeptech.data.datasets.coco
> An implementation of the coco dataset.
"""
import cv2
import json
import numpy as np
import os
from collections import namedtuple
from deeptech.core.config import inject_kwargs, get_main_config
from deeptech.core.definitions import SPLIT_TRAIN, SPLIT_VAL, SPLIT_TEST
from deeptech... |
""" Tests for basic logger setup call """
import itertools
import logging
import random
import string
import sys
import pytest
from logmuse import init_logger
from logmuse.est import DEFAULT_STREAM, LOGGING_LEVEL, PACKAGE_NAME
__author__ = "<NAME>"
__email__ = "<EMAIL>"
def _random_filename():
""" Generate rand... |
from discord import Embed
import asyncio
from . import BASE_URL, http
from .utils import *
from .season import Season
from .newspost import NewsPost
import logging
log = logging.getLogger(__name__)
__all__ = (
"PartialGame",
"Game"
)
class PartialGame:
def __init__(self, data) -> None:
self.id = ... |
import itertools
# Creates decreasing frequency dictionary from existing letter mapping
def remap_letter_frequency(dict_to_rev):
dict_inv = {}
for key, value in dict_to_rev.items():
if value in dict_inv:
dict_inv[value].append(key)
else:
dict_inv[value] = [key]
retur... |
import os.path
from . import consts
from .utils import request, s3_zipped_download, s3_zipped_upload, safe_call
tillerino_api = "https://api.tillerino.org"
def download_beatmap(ctx):
"""Download a .osu file."""
if not ctx.beatmap:
return None
osu_path = "/tmp/%s.osu" % ctx.beatmap.file_md5
... |
import numpy as np
import cv2
from sklearn.datasets import load_files
from keras.utils import np_utils
def read_folders(path):
data = load_files(path)
files = np.array(data['filenames'])
targets = np_utils.to_categorical(np.array(data['target']))
return files, targets
def load_data(files, targets, s... |
"""
This is a set of top-level routines that have been wrapped for convenience
"""
from bioflow.annotation_network.BioKnowledgeInterface import \
GeneOntologyInterface as AnnotomeInterface
from bioflow.molecular_network.InteractomeInterface import \
InteractomeInterface as InteractomeInterface
from bioflow.neo4... |
import numpy as np
import pandas as pd
import scipy.sparse as sp
import torch
from torch.utils.data import TensorDataset, DataLoader
from torch.autograd import grad, Variable
from .design import design_matrices
from .summary import param_table
##
## constants
##
eps = 1e-7
##
## sparse
##
# make a sparse tensor
d... |
import sys
import os
import time
import torch
import pytorch_lightning as pl
from pytorch_lightning import Trainer, TrainResult, EvalResult, seed_everything
from pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping # , LearningRateLogger
from pytorch_lightning.loggers import TensorBoardLogger
from pytorc... |
# coding:utf-8
from typing import List, Tuple
from os import path
from typing import Dict, List, Union
from xml.etree import ElementTree as ET
import cv2 as cv
import numpy as np
import torch
from torch.utils.data import Dataset, RandomSampler, BatchSampler
from utils.augmentation_utils import Transformer
class Ann... |
#!/usr/bin/env python
import argparse
import urllib.request
from bs4 import BeautifulSoup
from bibtexparser.bibdatabase import BibDatabase
from bibtexparser.bwriter import BibTexWriter
import webbrowser
def main():
"""
commandline tool to extract bibtex entries
for ISMRM abstracts from
https://archiv... |
import logging
import os
import csv
from datetime import datetime, timedelta
from pathlib import Path
def new_transaction_lists(impact, t_lists, account_name, network_name):
"""Transforms new transaction records by adding the Impact tracker ID for the environment (desktop/mobile),
finding the correct Impac... |
import collections
import datetime
import numpy as np
def to_list(x, length=None):
"""
Often a list is required, but for convenience it is desired to enter a
single object, e.g. string.
Complicated corner cases are e.g. `range()` and `dict.values()`, which are
handled here.
>>> to_list(1)
... |
#
# This file is part of LiteDRAM.
#
# Copyright (c) 2018-2019 <NAME> <<EMAIL>>
# SPDX-License-Identifier: BSD-2-Clause
"""
ECC frontend for LiteDRAM
Adds ECC support to Native ports.
Features:
- Single Error Correction.
- Double Error Detection.
- Errors injection.
- Errors reporting.
Limitations:
- Write byte ena... |
"""The terrain subrenderer.
Uses the raymarcher module to render
the terrain.
"""
import math
import typing
from ...util import interpolate, interpolate_color
from ..raymarcher import Ray, Raymarcher
from . import SubrendererUtilMixin
from .sky import SkySubrenderer # to get the fog color
if typing.TYPE_CHECKING:
... |
"""Benchmark a lstm model
Original Model from https://github.com/keras-team/keras/blob/master/examples/lstm_text_generation.py
Benchmark for a LSTM model.
Script template modified from TensorFlow Benchmark repo:
https://github.com/tensorflow/benchmarks/blob/keras-benchmarks/scripts/keras_benchmarks/models/lstm_benchmar... |
from http.server import HTTPServer, BaseHTTPRequestHandler
import api_keys
import threading
import re
import urllib
import webbrowser
import requests # Module not included in standard python libarary
from datetime import datetime, timedelta
import os
import json
import logging
if True:
API, SECRET = api_keys.getK... |
#!/usr/bin/env python3
# nome: shodan
# Criador: olive
# descrição: Traduzido de inglês-O shodan é um mecanismo de busca.
# modulos importados
import shodan
import os
import sys
import time
import subprocess
def main():
os.system('sh cor3/.banner.sh')
print ("""
\t1 -> Adicionar {chave}
\t2 -> ... |
import numpy as np
from sklearn.manifold import TSNE
from sklearn import datasets
from time import time
import matplotlib.pyplot as plt
import os
import fnmatch
import cv2
ubuntu = 0
windows = 1
platform = windows
def get_data_example():
digits = datasets.load_digits(n_class=6)
data = digits.data
label = ... |
from __future__ import absolute_import, division, generators, nested_scopes, print_function
import logging
from ply.yacc import yacc
from jpath_finder.jpath_errors import JPathError, JPathParseError
from jpath_finder.jpath_lexer import JPathLexer
from jpath_finder.jpath_nodes import (
BINARY_OP_MAP,
BOOLEAN_... |
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.wait import WebDriverWait
import os
# 'General' tab
def general_tab(driver):
# set Status... |
"""
AIOHappyBase connection pool module.
"""
import logging
import socket
import asyncio as aio
import queue
import threading
from numbers import Real
from typing import Any, Dict, Awaitable
from thriftpy2.thrift import TException
from .connection import Connection
try:
from asyncio import current_task
except I... |
from __future__ import division, print_function
import numpy as np
import emcee
import gus_utils as gu
import corner_plot as cp
import matplotlib.pyplot as plt
def likelihood(params, v, vmin):
"""
Likelihood function for the speed.
Arguments
---------
params: array_like
A, k, vesc
v: array_like
speed... |
from __future__ import print_function
from P13pt.mascril.measurement import MeasurementBase
from P13pt.mascril.parameter import Sweep, Folder, Boolean, String
from P13pt.drivers.keithley2400 import K2400
from rohdeschwarz.instruments.vna import Vna as RohdeSchwarzVNA
import time
import os
import errno
def create_pa... |
import os
import glob
import numpy as np
from PIL import Image, ImageFile
import albumentations as A
from albumentations.pytorch import ToTensorV2
import json
import cv2
ImageFile.LOAD_TRUNCATED_IMAGES = True
from torch.utils.data import Dataset,DataLoader
import torch
from utils import torch_distributed_zero_first
fro... |
# encoding -utf8-
"""
read and concatenate daily files variables into a xarray Datatset
"""
import time
import xarray
import glob
import logging
import datetime
import numpy as np
import os
import resource
from src.config import DIR_L2F_WV_DAILY
def preprocess_L2F(ds, variables=None, add_ecmwf_wind=True):
"""
... |
import operator
from fileinput import FileInput
from functools import reduce
from typing import Iterable
from core import aggregate_by
Guess = dict[str, set[str]]
Bins = tuple[Guess, Guess, Guess]
DIGITS: dict[frozenset[str], str] = {
# cSpell: disable
frozenset("abcefg"): "0",
frozenset("cf"): "1",
... |
#!/usr/bin/env python3
from functools import reduce
from .version import __version__
import argparse
import itertools
import socket
import sys
HOST = 'whois.crsnic.net'
PORT = 43
class Whois:
def __init__(self, server, port):
self.server = server
self.port = port
def lookup(self, domain, ve... |
"""
Module to generate encrypt and decrypt token
"""
import os
from cryptography.hazmat.backends.openssl.backend import backend
from cryptography.hazmat.primitives.ciphers import Cipher
from cryptography.hazmat.primitives.ciphers import algorithms
from cryptography.hazmat.primitives.ciphers import modes
from cryptograp... |
import json
from logging import getLogger
from typing import Callable, Dict, List, Optional
from kafka.record.abc import ABCRecord
from opentelemetry import context, propagate, trace
from opentelemetry.propagators import textmap
from opentelemetry.semconv.trace import SpanAttributes
from opentelemetry.trace import Tr... |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.utils import cint
def setup_global_search_table():
'''Creates __global_seach table'''
if not '__global_search' in frappe.d... |
"""
Source classes for CHIANTI filetypes not attached to ions
"""
import os
import numpy as np
import astropy.units as u
from astropy.table import Column
import fortranformat
import plasmapy
from ..generic import GenericParser
__all__ = ['AbundParser', 'IoneqParser', 'IpParser']
class AbundParser(GenericParser):
... |
"""
pytest unit tests
"""
import random
import threading
import time
import pytest
from src.grip.grip import (
GenericItem,
GenericRateLimitedItemProcessor,
GRIP_Deque
)
VALID = 'valid'
INVALID = 'invalid'
THREAD = 'thread'
# each tuple contains the num_items, num_seconds
RATE_LIMITING_TEST_DATA = [
... |
import requests
import re
import time
from datetime import datetime
import json
from tqdm import tqdm
import numpy as np
import seaborn as sns
from matplotlib import patches
import pandas as pd
import parser
import sys
import random
from collections import Counter
from bs4 import BeautifulSoup
from sklearn import prepr... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import markdown
from sklearn import metrics
from sklearn.externals import joblib
import re
def plot_precision_recall_n(y_true, y_prob, model_name=None):
# thanks rayid
from sklearn.metrics import precision_recall_curve
y_score = y_prob
... |
import sys
import maya.OpenMaya as OpenMaya
import maya.OpenMayaMPx as OpenMayaMPx
import maya.cmds as cmds
__author__ = '<NAME>'
__copyright__ = 'Copyright (C) 2016 - Duiker Research Corp'
__license__ = ''
__maintainer__ = '<NAME>'
__email__ = '<EMAIL>'
__status__ = 'Production'
__major_version__ = '1'
__minor_versi... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
Created on 17/06/03 17:36:11
@author: <NAME>
"""
import numpy as np
import json
import os
import re
def read_line(filename):
with open(filename, "r", encoding="utf8") as f:
for line in f:
yield line.strip()
def build_offset_mapping(text):
... |
#!/usr/bin/env python
import sys
# Inspired by https://www.learnpython.org
# - print(“Hello World”) from terminal
# - explain functions, indexing
# - create project, init, args, print help
# - variables, variable types, casting
def __main__():
# To handle application arguments
# if len(sys.argv) > 1:
# ... |
import pandas as pd
import fasttext
import string
import re
import jieba
import sys
data_path = './real/data/'
tiny_mode = False
tiny_pre = 'tiny_'
keyword_num = {
"财经" : 50,
"时政" : 50,
"房产" : 50,
"科技" : 50,
"教育" : 50,
"时尚" : 50,
"游戏" : 50,
"家居" : 50,
"体育" : 50,
"娱乐" : 50,
}... |
import collections
import io
import logging
import os
import re
import subprocess
import sys
from esphome import const
_LOGGER = logging.getLogger(__name__)
class RegistryEntry:
def __init__(self, name, fun, type_id, schema):
self.name = name
self.fun = fun
self.type_id = type_id
... |
# flake8: noqa
import asyncio
import logging
import os
import re
import shutil
import tempfile
import urllib.parse
import aiohttp
from . import exception
logger = logging.getLogger(__name__)
subprocess_logger = logging.getLogger(__name__ + ".stderr")
def _find_filename(url, resp):
# Filename should be url base... |
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT
"""
`fingerprint_template_file_compare.py`
====================================================
This is an example program to demo storing fingerprint templates in a file. It also allows
comparing a newly obtained pr... |
# rhythm - Static Site Generator based on Python 3
# Key features - see readme.md
# filename - main.py
# The MIT License (MIT)
#
# Copyright (c) Lumos AI LLC
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to de... |
# Welcome to foundrycli.py (🔥, 🐍)
# Add `from foundrycli import foundry_cli` to your script
# See`README.md` for examples
from decimal import Decimal
from subprocess import run, PIPE
from json import loads
def foundry_cli(command: str, force_string_output=False):
# throw if cli is not forge or cast
cli = c... |
"""
Calls from the advanced API to the Search API.
"""
import types
from ..core.helpers import console, wrapMessages
from .condense import condense
def searchApi(app):
app.search = types.MethodType(search, app)
def search(app, query, silent=False, sets=None, shallow=False, sort=True, limit=None):
"""Searc... |
import unittest
import argparse
import params
class TestParamArg(unittest.TestCase):
"""Test the params decorators"""
def setUp(self):
self.cls = type('X', (object,), dict(a=1))
params.ARGPARSE_PARAMETERS = set()
def test_params(self):
"""Ensure that the decorator param create a P... |
import copy
class Othello :
def __init__(self):
self.hauteur = 8
self.largeur = 8
self.nb_joueurs = 2
def initialisation (self,plateau):
"""Empty the plate and set the correct configuration"""
plateau.set_case(4,4,False, 1)
plateau.set_case(3,3,False, 1)
... |
import os
import pytest
import random
import subprocess
import pyfastaq
from viridian_workflow import sample_reads
# Make a 1kb reference genome with 4 amplicons, and then some read pairs
# that do different things (both mapped, one mapped, mapped to different
# amplicons ... etc)
def make_test_ref_genome(outfile):
... |
import os
import numpy as np
import torch
from skimage import io
from torch.utils.data import DataLoader, Dataset
from torchvision import transforms as T
from torchvision.transforms import functional as F
from typing import Callable
def to_long_tensor(pic):
# handle numpy array
img = torch.from_numpy(np.ar... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import time
from lck.django.common import nested_commit_on_success
from lxml import etree as ET
import paramiko
from ralph.util import Eth
from... |
import click
import sys
import copy
import six
from ecstools.resources.service import Service
import ecstools.lib.utils as utils
@click.command(short_help='Manage environment variables')
@click.argument('cluster', nargs=1)
@click.argument('service', nargs=1)
@click.argument('pairs', nargs=-1)
@click.option('-d', '--... |
import plotly.graph_objs as go
from plotly.offline import plot
import cea.plots.demand
from cea.plots.variable_naming import NAMING, COLOR, LOGO
from cea.constants import HOURS_IN_YEAR
import pandas as pd
__author__ = "<NAME>"
__copyright__ = "Copyright 2018, Architecture and Building Systems - ETH Zurich"
__credit... |
# -*- coding: utf-8 -*-
# (C) Copyright 2015 Hewlett Packard Enterprise Development LP
# 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.a... |
"""
# @Time : 2021/7/3 5:07 下午
# @Author : hezhiqiang01
# @Email : <EMAIL>
# @File : naiveDDPG.py
"""
import argparse
import torch
import gym
import numpy as np
import collections
import torch.nn as nn
import torch.nn.functional as F
Experience = collections.namedtuple(typename="Experience", field_names=['s... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2014 uralbash <<EMAIL>>
#
# Distributed under terms of the MIT license.
import json
from pyramid.i18n import get_localizer
from pyramid.threadlocal import get_current_request
import deform
import colander
from saexttype import ChoiceType
... |
#!/usr/bin/env python3
# Copyright © 2020 <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, modif... |
import logging
from abc import ABCMeta, abstractmethod
from typing import NamedTuple, List, Dict
from services.lib.constants import NetworkIdents
from services.models.last_block import LastBlock
from services.models.pool_info import PoolInfoHistoricEntry, PoolInfoMap, PoolInfo
from services.models.pool_member import P... |
import argparse
import logging
import os
from timeit import default_timer as timer
import matplotlib
matplotlib.use('Agg') # Fixes weird segfaults, see http://matplotlib.org/faq/howto_faq.html#matplotlib-in-a-web-application-server
from fsm_effective_stress import compute_damage, compute_effective_stress
from fsm_loa... |
import xml.etree.ElementTree as ET
import os
import re
import time
import requests
import json
import csv
import datetime
from . import utils
class SFApiException(Exception):
pass
class BulkJob:
def __init__(self, api):
self.api = api
def run_job(self, operation, object_type, data):
""... |
#!/usr/bin/env python3
from devnet2019.models import Devicedb, DeviceInterface, MonitorInterval
from django.shortcuts import render
from datetime import datetime, timedelta
import numpy as np
from django.http import JsonResponse
# 获取速率监控间隔
def get_speed_monitor_interval():
try:
speed_monitor_interval = M... |
"""Idea comes from here:
https://github.com/keras-team/keras/blob/master/examples/addition_rnn.py
"""
import os
import pickle
import numpy as np
from manager import Manager
from keras.callbacks import TensorBoard, ModelCheckpoint
from keras.models import load_model
from chatbot.config import PATHS
from chatbot.trai... |
"""The sliding window matching algorithm for identifying recurring patterns in a neural signal."""
import numpy as np
from neurodsp.utils.decorators import multidim
###################################################################################################
####################################################... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author: zparteka
"""
import numpy as np
# from chiapet_operations.chiapet_given_region import read_region
from math import ceil
from os import path
from glob import glob
from scripts.config import hg19_chromosomes_dict as chromosomes_hg19
from scripts.config import hg... |
import errno
import os
import unittest
import random
import re
import tarfile
from string import ascii_uppercase, ascii_lowercase, digits
from gitsecrets import GitSecrets
class GSTestCase(unittest.TestCase):
"""
Base test case for GitSecrets
"""
def setUp(self):
self.datdir = 'tests/data'
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 16 16:43:04 2016
@author: <EMAIL>
"""
import networkx as nx
import numpy as np
from numpy import zeros
import pandas as pd
import os.path
import sys
import time
from time import sleep
def expected_remaining_time(start,iter,total): return ((total - iter) * (time.time() -... |
"""Tables for config_officer plugin."""
import django_tables2 as tables
from utilities.tables import BaseTable, ToggleColumn, ColoredLabelColumn, TagColumn
from .models import (
Collection,
Template,
Service
)
from tenancy.tables import TenantColumn
from django_tables2.utils import Accessor
from dcim.mode... |
import sys
import numpy
import os
import argparse
from scipy.constants import c
from src.util import hexagonal_array
from src.util import redundant_baseline_finder
from src.radiotelescope import AntennaPositions
from src.radiotelescope import BaselineTable
from src.radiotelescope import RadioTelescope
from src.covaria... |
import qcodes as qc
import numpy as np
import types
import os
import matplotlib.pyplot as plt
import scipy.fftpack as fftpack
from scipy.optimize import curve_fit
from qcodes import config
from qcodes.dataset.data_set import load_by_id
from qcodes.dataset.plotting import plot_by_id
from qcodes.dataset.data_export impo... |
from numpy import sqrt, linspace, array
import pandas as pd
from scipy.stats import gaussian_kde, norm
from numpy.random import normal
XLIM = (1868, 1973)
def get_fig_data(ssmodel, state_col, error_col, confidence=0.9):
""""""
percentile = 0.5 + 0.5 * confidence
quantile = norm.ppf(percentile)
state_... |
#!/usr/bin/env python
#######################################################################
# Copyright (C) 2009-2020 by Carnegie Mellon University.
#
# @OPENSOURCE_LICENSE_START@
# See license information in ../../../LICENSE.txt
# @OPENSOURCE_LICENSE_END@
#
###########################################################... |
import markdown
from jinja2 import PackageLoader, FileSystemLoader
from os import listdir
import os
import pathlib
from pathlib import Path
import sys
from dipor.readers.markdown import MarkdownReader
from dipor.utils.context import get_structural_context
from dipor.jinja_changes import RelEnvironment, SilentUndefined... |
# -*- coding: utf-8 -*-
from .constants import *
import collections
import numpy as np
class RunningAverageFilter():
"""
This is a general purpose filter that outputs the average of the last
N samples, where N is defined at initialization.
"""
def __init__(self, N, average=0):
"""
... |
import os.path as op
import array
import pynodegl as ngl
from pynodegl_utils.misc import scene
def _load_model(fp):
index = 0
vertices = []
uvs = []
normals = []
vertex_indices = []
uv_indices = []
normal_indices = []
indexed_vertices = array.array('f')
indexed_uvs = array.array... |
#!/usr/bin/python
from .. import QtCore, QtWidgets, QtGui
from .stylesheet import STYLE_TABSEARCH, STYLE_TABSEARCH_LIST, STYLE_QMENU
from collections import OrderedDict
import re
def fuzzyFinder(key, collection):
suggestions = []
pattern = '.*?'.join(key.lower())
regex = re.compile(pattern)
for item i... |
import numpy as np
#import scipy as sp
from scipy import integrate
import time
from IPython import embed
import os, ctypes
from scipy import integrate, LowLevelCallable
lib = ctypes.CDLL(os.path.abspath('testlib.so'))
lib.f.restype = ctypes.c_double
lib.f.argtypes = (ctypes.c_int,
ctypes.POINTER(c... |
from flask import Blueprint, request, jsonify
from sqlalchemy.exc import OperationalError, ProgrammingError
from werkzeug.wrappers import Response
from app import db
class Stakeholder(db.Model):
"""
Stakeholder class.
"""
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(300... |
import codecs
import os
from inspect import getsourcefile
from spacy.language import Language
from ..utils import lexicons, components
from ..component import Asent
from .emoji import LEXICON as E_LEXICON
def read_lexicon():
lexicon_file = os.path.join("..", "lexicons", "no_lexicon_v1.txt")
_this_module_fi... |
#!/usr/bin/env python3.8
from random import choice,randint
import pyperclip #import this module for copy paste operations
from user import User
"""import the user class blueprint"""
from credentials import Credentials
"""import the credentials class blueprint"""
def create_user(username,password):
'''
Function to ... |
#!/usr/bin/env python
"""A TeamCity >= 9.1 build chain runtime stats gatherer"""
import requests, json
import dateutil.parser
from collections import namedtuple
###################
__BuildStat = namedtuple("BuildStat", "build_id build_configuration_id duration start_date")
__BuildChain = namedtuple("BuildChain", "b... |
"""
Signal Processing
=================
The Signal Processing module contains functions for signal processing.
"""
from multipledispatch import dispatch, Dispatcher
import numbers
import numpy as np
import noisy
import streaming
from streaming.stream import Stream, BlockStream, count
import itertools
from functools i... |
"""=============================================================
~/uglmu_common/common/tests/api/test_management_units.py
Created: 18 Apr 2020 09:30:08
DESCRIPTION:
Tests for the api end points for Management Units
Management Units detail should include: label, mu-type, slug, lake,
centroid, and envelope (op... |
# -*- coding: utf-8 -*-
# Copyright (C) 2013 Yahoo! 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... |
#!/usr/bin/env python3
# MIT License
#
# Copyright (c) 2020 <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
... |
import torch
import numpy as np
import matplotlib.pyplot as plt
from torchvtk.utils import tex_from_pts
def show(img, ax=plt, title=None, interpolation='nearest', xticks=False):
'''Displays a Tensor as image
Args:
img (torch.Tensor): Tensor containing the image. Shape (C, H, W)
ax (pyplot.Ax... |
from collections import OrderedDict
import hashlib
import requests
import json
class STMSignature:
def __init__(self, salt, ignore_unsupported_values=False):
if isinstance(salt, bytes):
raise ValueError('Salt should be a string')
self.salt = salt
self.ignore_unsupported_value... |
from __future__ import annotations
from unittest import SkipTest, mock
import django
import pytest
from django.db import DEFAULT_DB_ALIAS, connection, connections
from django.test import SimpleTestCase, TestCase
from django_mysql.utils import (
WeightedAverageRate,
connection_is_mariadb,
format_duration,... |
from re import findall, match
from datetime import datetime
from datetime import timedelta
abs_due_regex = r'^[:<>](\d{0,2})(\d{0,2})(\d{2})?:?(\d{0,2})(\d{0,2})$'
rel_due_regex = r'^:(?:(\d+)y)?(?:(\d+)mo)?(?:(\d+)w)?(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?$'
secs_in_sec = 1
secs_in_min = 60
mins_in_hour = 60
hours_in... |
from flask import render_template, redirect, url_for, flash, request, current_app
from werkzeug.urls import url_parse
from flask_login import login_user, logout_user, current_user
from app import db
from app.auth import bp
from app.auth.forms import LoginForm, SimpleRegistrationForm, RegistrationForm, \
ResetPasswordR... |
import db
import nhl_api_calls
# parsing the api call response into two main dicts: dates and games. Dates contains dates, games contains teams,
# their season record, status, gameid, score if game already played/in progress
def parse_strings_for_tweets(data):
dates = {}
games = {}
for date in data["dates... |
import random
import re
import xml.etree.ElementTree as ET
from collections import defaultdict
from itertools import accumulate
from pathlib import Path
import torch
from torch.utils.data.dataset import Dataset
from torchaudio.sox_effects import apply_effects_file, apply_effects_tensor
class QUESST14Trainset(Dataset... |
"""Generic utilities that don't depend on anything outside of the Python stdlib
& standard numeric libs, and are all pure Python."""
from contextlib import contextmanager
from json import dumps
from time import time
from weakref import proxy, ProxyTypes
import ctypes
import random
import struct
import sys
import num... |
# -*- coding: utf-8 -*-
import re
import keras
import numpy as np
import os
from gensim.models import word2vec
import random
from textcnn_model_v2 import TextCNN
def clean_string(string, TREC=False):
string = re.sub(r"[^A-Za-z0-9(),!?\'\`]", " ", string)
string = re.sub(r"\'s", " \'s", string)
string = ... |
"""Contains the Solver class"""
import copy
import time
import os
def solved(values):
"""Checks if a sudoku puzzle is solved or unsolvable, returns -1 if unsolvable, 1 if solved and 0 if not solved"""
for u in values:
if len(values[u]) < 1:
return -1
elif len(values[u]) ... |
import os
import argparse
import hashlib
import json
from tqdm import tqdm
import nibabel
import numpy as np
import torch
from torch.nn.functional import interpolate
EXCLUDED_CASES = []#[23, 68, 125, 133, 15, 37]
MAX_ID = 210
MEAN_VAL = 101.0
STDDEV_VAL = 76.9
MIN_CLIP_VAL = -79.0
MAX_CLIP_VAL = 304.0
TARGET_SPACING... |
#!/usr/bin/env python3
# In this sample you will see how to create a bonded network interface on top
# of the existing ethernet interfaces, change the settings of the bonded
# network interface and unbond it to recover the slave interfaces back to
# normal ethernet interfaces using REST API.
import json
import os
imp... |
#-------------------------------------------------------------------------------
#
# Project: EOxServer <http://eoxserver.org>
# Authors: <NAME> <<EMAIL>>
#
#-------------------------------------------------------------------------------
# Copyright (C) 2013 EOX IT Services GmbH
#
# Permission is hereby granted, free o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.