text stringlengths 3.07k 12.6k |
|---|
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
#
"""
Testing utilities to be used with pytest.
"""
# Stdlib imports
import os
from unittest.mock import Mock
# Third party imports
import pytest
from qtpy.QtGui import QFont
from qtpy.QtCore import QMim... |
#!/usr/bin/env python
# Copyright (c) 2016, <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list... |
from __future__ import division
from django.shortcuts import render
from django.db.models import Q
from django.contrib.auth.decorators import login_required
from rest_framework.decorators import (api_view,
permission_classes)
from rest_framework.response import Response
from res... |
#!/usr/bin/env python3
import sys
from typing import Iterable, Tuple, Type, Union
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
Ndegrees = 90
# structure expected by matplotlib.
# unlike the input, each color can have different "gradient segments"
# with op... |
# Copyright (c) 2021 MobileCoin. All rights reserved.
from django.contrib import admin
from .models import (
Store,
Customer,
Drop,
Item,
CustomerStorePreferences,
CustomerDropRefunds,
DropSession,
BonusCoin,
ChatbotSettings,
Order,
Sku,
)
from .models.messages import (
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This sample need to be improve to provide
a clean API to output animation
Monthly
python samples/example_animate.py --by M --exit_at 5 --rmax 1000
Daily
python samples/example_animate.py --by D --exit_at 5 --rmax 60
"""
import click
import time
import logging
impo... |
import datetime
import logging
import time
from pathlib import Path
from typing import Dict, List
import nibabel as nib
import numpy as np
import SimpleITK as sitk
from nilearn.image import resample_img
log = logging.getLogger(__name__)
def time_it(func):
def wrapper(*args, **kwargs):
start = time.time(... |
"""
correspondence checking with peddy (https://github.com/brentp/peddy)
"""
import collections
import os
import shutil
import toolz as tz
from collections import defaultdict
from bcbio.distributed.transaction import tx_tmpdir
from bcbio import utils
from bcbio.cwl import cwlutils
from bcbio.utils import safe_makedir... |
import glob
import re
import librosa
import torch
import yaml
from sklearn.preprocessing import StandardScaler
from torch import nn
from modules.parallel_wavegan.models import ParallelWaveGANGenerator
from modules.parallel_wavegan.utils import read_hdf5
from utils.hparams import hparams
from utils.pitch_utils import f0... |
import anndata
import dask.array
import dask.dataframe
import numpy as np
import os
import pandas as pd
from pathlib import Path
import pickle
import scipy.sparse
from typing import List, Tuple, Union
import zarr
def _buffered_path(path_base, path, fn):
path_base = os.path.join(path_base, path)
if not os.path... |
from modules import *
from loss import *
from optims import *
from dataset import *
from modules.config import *
#from modules.viz import *
import numpy as np
import argparse
import torch
from functools import partial
import torch.distributed as dist
def run_epoch(epoch, data_iter, dev_rank, ndev, model, loss_compute,... |
import smtplib
import sys
import time
class bColors:
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
BLUE = '\033[94m'
def banner():
print(bColors.BLUE + '<<< Email-Bomber v2.0>>>')
print(bColors.YELLOW + r'''
_
| |
| |___
| _ \ _ _
| |_) | (_) |
\___... |
import cv2
import numpy as np
import math
def _np_resize_to_range(image, min_size, max_size):
im_shape = image.shape
im_size_min = np.min(im_shape[0:2])
im_size_max = np.max(im_shape[0:2])
im_scale = min(min_size / im_size_min, max_size / im_size_max)
image = cv2.resize(
image,
No... |
# Run as:
# python3 part1.py [input|sample]
import operator
import sys
from itertools import islice
from functools import reduce
class Packet:
TYPES = {
4: 'LITERAL_VALUE',
0: 'OPERATOR_SUM',
1: 'OPERATOR_PRODUCT',
2: 'OPERATOR_MIN',
3: 'OPERATOR_MAX',
5: 'OPERATOR_GREATER_THAN',
6: 'O... |
from utils import get_optimizer, get_loss_function, make_copy_repeat_dataset, make_dirs, get_accuracy, AutoClip
from torch.utils.tensorboard import SummaryWriter
from core import Controller
from tqdm import tqdm
import numpy as np
import torch
import os
def unroll_through_time(controller, loss_function, inputs, targe... |
# %%
import sys
from pathlib import Path
from typing import List
import altair as alt
import pandas as pd
from traffic.data import airports
alt.renderers.set_embed_options(actions=False)
# %%
dataset_path = sys.argv[1]
dates = [
"20200101",
"20200201",
"20200301",
"20200401",
"20200501",
"... |
import json, os, boto3
import requests
import os
#from botocore.vendored import requests
from datetime import datetime, timedelta, timezone
SLACK_OAUTH_TOKEN = os.getenv ('SLACK_OAUTH_TOKEN')
SLACK_CHECK_CHANNEL = os.getenv('SLACK_CHECK_CHANNEL')
EVENT_TABLE = os.getenv('TABLE_NAME', 'connect_up_slack')
USER_TABLE =... |
import os
import shutil
from os.path import isfile, basename, join, abspath, isdir
from uuid import uuid1
from pathlib import Path as P
import logging
from ..common import maybe_create_symlink
from .MqparParser import MqparParser
class MaxquantRunner:
def __init__(
self,
fasta_file,
mqpa... |
import os
import sys
from pyspark import SparkContext, SparkConf
import json
import itertools
import math
import time
from queue import deque
appName = 'assignment4'
master = 'local[*]'
conf = SparkConf().setAppName(appName).setMaster(master)
sc = SparkContext(conf=conf)
sc.setLogLevel("ERROR")
def create_adjacency_... |
#!/usr/bin/env python
import sys, multiprocessing, subprocess, os, shutil, argparse, time, inspect
from Bio import SeqIO
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir)
import lib.library as lib
#setup menu wit... |
from tqdm import tqdm
from .logger import DummyLogger
import torch
from pathlib import Path
import torchvision.io as io
def save_png(img, path, gamma=1/2.2):
img = img[0,:]
if gamma < 1: img = img.clip(min=1e-6)
img = img**gamma
io.write_png((img * 255).byte().cpu(), path, compression_level=0)
class T... |
#!/usr/bin/env python3
from progress.bar import Bar, ChargingBar
from multiprocessing import Pool
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
from numpy import sin
from numpy import cos
from numpy import tan
from numpy import abs
from ecuaciones_drone import f, escribe, imagen,... |
import tensorflow as tf
def weighted_pooling(raw_representation, positional_weighting, tokens):
"""Performs a pooling operation that is similar to average pooling, but uses a weight for every position. Therefore
not all positions are equally important and contribute equally to the resulting vector.
:par... |
import numpy as np
from scipy import ndimage
import warnings
def matlab_round(array):
'''round equivalent to matlab function, which rounds .5 away from zero
(used in matlab_histo so we can unit test against matlab code).
But np.round() would rounds .5 to nearest even number, e.g.:
- np.round(0.5) = ... |
import json
import logging
import requests
import binascii
from json.decoder import JSONDecodeError
from ....core.transactions import transaction_with_commit_on_errors
from django.http import (
HttpResponse,
HttpResponseBadRequest,
HttpResponseNotFound,
)
from django.core.handlers.wsgi import WSGIRequest
f... |
""" Captcha.Visual.Text
Text generation for visual CAPTCHAs.
"""
#
# PyCAPTCHA Package
# Copyright (C) 2004 <NAME> <<EMAIL>>
#
#import os
import re
import random
from PIL import ImageFont
from PIL import ImageDraw
from Captcha import Visual, File, get_random
class FontFactory(File.RandomFileFactory):
"""Picks ... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from nntools.nnet import AbstractNet
class ResConv(nn.Module):
def __init__(self, input_chan, features, stride, base_name=''):
super(ResConv, self).__init__()
self.branch_1 = nn.Sequential(nn.BatchNorm2d(input_chan),
... |
"""
Author: <NAME>
Date : Feb 07, 2020
Longest Common Sub-Sequence
Given two sequences, find the length of longest subsequence present in both of them.
A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous.
For example, “abc”, “abg”, “bdf”, “aeg”, ‘”acefg”, .. etc are su... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class double_conv(nn.Module):
'''(conv => BN => ReLU) * 2'''
def __init__(self, in_ch, out_ch):
super(double_conv, self).__init__()
self.conv = nn.Sequential(
nn.Conv2d(in_ch, out_ch, 3, padding=1)... |
# Software License Agreement (BSD License)
#
# Copyright (c) 2013, Open Source Robotics Foundation, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code mus... |
########################################################################
#
# Date: April 2006 Authors: <NAME>, <NAME>
#
# <EMAIL>
# <EMAIL>
#
# The Scripps Research Institute (TSRI)
# Molecular Graphics Lab
# La Jolla, CA 92037, USA
#
# Copyright: <NAME>, <NAME> and TSRI
#
# revision:
#
########... |
import argparse
import numpy as np
from sklearn.metrics import accuracy_score, auc, roc_curve
from sklearn.datasets import load_svmlight_file
from sklearn.model_selection import train_test_split
from sklearn.model_selection import StratifiedKFold
from scipy.stats import chi2
import os
from FDA import FDA
parser = argp... |
import json
import argparse
from multiprocessing import Pool
import os
from os.path import exists, splitext, isdir, isfile, join, split, dirname
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import matplotlib.image as mpimg
from matplotlib.path import Path
from matplotlib.font... |
import logging
class IdAssigner():
someId = 1
def getNextId():
IdAssigner.someId+=1
return IdAssigner.someId
def sentenceToHtml(sentenceText, foundSentence):
hiddenSentence = ''
# if foundSentence is None:
# hiddenSentence = 'hidden'
resultSentenceHtml = ' <span... |
""" Module for reading and compensating data from raw test files produced by the biaxial testing machine
"""
import numpy as np
def read(name, min_num_columns=9, num_rows=0):
"""Read the raw experiment data file into a numpy array and include additional information from the header.
:param name: The path... |
import numpy as np
from ....utils.code_utils import deprecate_class
import properties
from ....utils import sdiag
from ....survey import BaseRx as BaseSimPEGRx, RxLocationArray
import warnings
# Receiver classes
class BaseRx(BaseSimPEGRx):
"""
Base DC receiver
"""
orientation = properties.StringCho... |
import scanpy as sc
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import scipy as sp
import tensorflow as tf
from tensorflow.contrib.opt import ScipyOptimizerInterface
nb_zero = lambda t, mu: (t/(mu+t))**t
zinb_zero = lambda t, mu, p: p + ((1.-p)*((t/(mu+t))**t))
sigmoid... |
#coding:utf-8
import tensorflow as tf
import numpy as np
from sklearn.cross_validation import train_test_split
import time
from sklearn.preprocessing import normalize
import os
learning_rate = 0.001
max_samples = 700000
batch_size = 128
display_step = 100
batchid=0
n_input = 2
n_steps = 2
n_hidden = 128
n_classes... |
import mailbox
mbox = mailbox.mbox('enron.mbox')
import re
def cleanup_email(msgbody):
regex_replies = re.compile('(\-+Original Message|\-\-+|~~+).*', re.DOTALL) # find 'Original Message...' and variants
msgbody = re.sub(regex_replies, '', msgbody)
msgbody = re.sub(r'=\d\d', ' ', msgbody) # remove funny ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Version: 0.0.1
Python library for the bargaining protocol
'''
from bitcoin.transaction import select, deserialize, serialize
from pybargain_protocol.constants import *
from pybargain_protocol.bargaining_cancellation import BargainingCancellationDetails
from pybargain_pr... |
from abc import ABC, abstractmethod
from typing import List, Dict, NamedTuple, Iterable, Tuple
from mlagents_envs.base_env import (
DecisionSteps,
TerminalSteps,
BehaviorSpec,
BehaviorName,
)
from mlagents_envs.side_channel.stats_side_channel import EnvironmentStats
from mlagents.trainers.policy impor... |
import struct
IV = "7380166f 4914b2b9 172442d7 da8a0600 a96f30bc 163138aa e38dee4d b0fb0e4e"
IV = int(IV.replace(" ", ""), 16)
a = []
for i in range(0, 8):
a.append(0)
a[i] = (IV >> ((7 - i) * 32)) & 0xFFFFFFFF
IV = a
def out_hex(list1):
result = ""
for i in list1:
result = result +... |
from kivy.animation import Animation
from kivy.app import App
from kivy.core.audio import SoundLoader
from kivy.lang import Builder
from kivy.properties import StringProperty, ObjectProperty, Clock
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.floatlayout import FloatLayout
f... |
from actuator.register import fm;
from .task import *
import data.db as database
import copy
class self_handlers:
handlers = {};
def route(self,func):
def registe(cls):
self.handlers[func] = cls;
return cls;
return registe;
this = self_handlers()
@fm.route("sina.com.c... |
import logging
from django.core.urlresolvers import reverse
from django.utils.translation import pgettext_lazy
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import ungettext_lazy
from horizon import tables
from openstack_dashboard import api
from openstack_dashboard import pol... |
from abc import abstractmethod
from typing import Dict, Union, Optional, Tuple
from unittest.mock import MagicMock
import argparse
from tmtccmd.utility.tmtc_printer import TmTcPrinter
from tmtccmd.config.com_if import CommunicationInterface
from tmtccmd.config.definitions import DEFAULT_APID
from tmtccmd.config.defini... |
import warnings
from selfies.compatibility import modernize_symbol
from selfies.exceptions import DecoderError
from selfies.grammar_rules import (
next_atom_state,
next_branch_state,
next_ring_state,
process_atom_symbol,
process_branch_symbol,
process_ring_symbol
)
from selfies.index_alphabet i... |
import asyncio
import logging
import logging.handlers
import queue
import threading
import urllib.request
from pathlib import Path
from typing import List, NamedTuple
try:
from typing import Literal
except ImportError:
from typing_extensions import Literal # type: ignore
import cv2
import matplotlib.pyplot a... |
# -*- coding: UTF-8 -*-
"""
Main module of preprocessor package. Can be executed by `python -m preprocessor`.
"""
import os
import pickle
from random import shuffle
import numpy as np
from chicksexer.constant import POSITIVE_CLASS, NEGATIVE_CLASS, NEUTRAL_CLASS, CLASS2DEFAULT_CUTOFF
from chicksexer.util import get_lo... |
#!/bin/env python
import csv
import sys, datetime
import xml.etree.ElementTree as ET
import math
info = {
"last": 0,
"first": 1,
"legal_name": 2,
"number": 3,
"homeroom": 4,
"gender": 5,
"year_entered": 6,
}
# (type, grade)
points_dict = {
("SE", 8): [87, 88, 89, 90, 91, 92, 93],
(... |
import argparse
import gym
import numpy as np
from itertools import count
from collections import deque
from skimage.color import rgb2gray
from skimage import transform
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.distribu... |
import numpy as np
import scipy
import sklearn.metrics
def precision_at_n(adj_test, adj_true, n):
assert (len(adj_test.shape) == 1) and (len(adj_true.shape) == 1), "Expect 1-dimensional arrays"
sorted_args = np.argsort(adj_test)[::-1]
return np.sum(adj_true[sorted_args][:n] > 0) / n
def true_positive(ad... |
import sys
import os
import numpy as np
from numpy.testing import assert_array_equal
from nose.tools import assert_equal, assert_true
from pystruct.models import LatentGridCRF, LatentDirectionalGridCRF
from pystruct.learners import (LatentSSVM, NSlackSSVM, OneSlackSSVM,
SubgradientSSVM)
... |
import itertools
import operator
# Use of itertool.accumulate() function
def accumulate_usage():
data = [1,2,8,3,4,5]
# Multiply items with result
multipy_result = itertools.accumulate(data, operator.mul)
# Find Max Values
max_result = itertools.accumulate(data,max)
# If no function, sum i... |
import os
import sys
import orjson
import gzip
import json
import tempfile
from typing import TextIO
from argparse import ArgumentParser
from eltetrado.analysis import eltetrado
from eltetrado.model import generate_dto
from eltetrado.structure import read_3d_structure, read_2d_structure
import drawtetrado.structure a... |
"""
desispec.io.sky
===============
IO routines for sky.
"""
from __future__ import absolute_import, division
import os
import time
from astropy.io import fits
from desiutil.log import get_logger
import numpy as np
from . import iotime
def write_skycorr(outfile, skycorr):
"""Write sky model.
Args:
o... |
import os.path
from pympler.asizeof import asizeof
import featuretools as ft
from featuretools import config
from featuretools.feature_base import IdentityFeature
from featuretools.primitives import Last, Mode, Sum
from featuretools.variable_types import Categorical, Datetime, Id, Numeric
def test_copy_features_doe... |
import json
import requests
import smtplib
from email.mime.text import MIMEText
from email.header import Header
# 通知类
class SendMessage:
def __init__(self, con):
self.rl = RlMessage(con['rl_email'], con['rl_emailApiUrl'])
self.qmsg = Qmsg(con['qmsg_key'], con['qmsg_qq'], con['qmsg_isGroup'])
... |
from __future__ import annotations
from typing import TYPE_CHECKING, List, Optional, Dict, Tuple
if TYPE_CHECKING:
from . import Game, Submission, Flag, Challenge
from ..store import *
from . import WithGameLifecycle
from ..state import ScoreBoard
class Users(WithGameLifecycle):
def __init__(self, game: G... |
# -*- coding: utf-8 -*- #
# Copyright 2021 Google LLC. 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 requir... |
# base implementation
import anyio
from functools import partial
try:
from contextlib import asynccontextmanager
except ImportError:
from async_generator import asynccontextmanager
from typing import Optional, Union
from .server import Server
from .device import Device
from .event import ServerRegistered, S... |
from time import strftime, gmtime, localtime
import codecs
import os
import shutil
import re
import imp
import tempfile
import sys
from simple_db_migrate.helpers import Utils
class Migration(object):
MIGRATION_FILES_EXTENSION = ".migration"
MIGRATION_FILES_MASK = r"[0-9]{14}_[\w\-]+%s$" % MIGRATION_FILES_EXTE... |
# --------------------------------------------------------
# Tensorflow Faster R-CNN
# Licensed under The MIT License [see LICENSE for details]
# Written by <NAME>, <NAME>, based on code from <NAME>
# --------------------------------------------------------
from __future__ import absolute_import
from __future__ import ... |
# -*- python -*-
# This software was produced by NIST, an agency of the U.S. government,
# and by statute is not subject to copyright in the United States.
# Recipients of this software assume all responsibilities associated
# with its operation, modification and maintenance. However, to
# facilitate maintenance we as... |
import mock
import pytest
from pytest_data import get_data, use_data
from dsw_sdk.common.attributes import StringAttribute
from dsw_sdk.high_level_api.models.model import (
AlreadyRemovedError,
ExistingState,
DeletedState,
ListOfModelsAttribute,
Model,
ModelAttribute,
NewState,
)
def modi... |
import numpy as np
import six
import string
import random
import torch
import os
import re
import sys
import json
import argparse
import logging
import os.path as osp
from six.moves import cPickle
from six.moves import range
def invert_dictionary(d):
inv_map = {v: k for k, v in six.iteritems(d)}
return inv_ma... |
import os
import glob
import pickle
from os.path import join
import cv2
import matplotlib.pyplot as plt
import imageio
from skimage import img_as_ubyte
from contrastive_highlights.ffmpeg import ffmpeg_contrastive, ffmpeg_highlights
class Trace(object):
def __init__(self):
self.obs = []
self.acti... |
from django.db import transaction
from memoized import memoized
from dimagi.utils.logging import notify_exception
from corehq.util.soft_assert import soft_assert
from corehq.util.test_utils import unit_testing_only
from corehq.util.view_utils import absolute_reverse
skipped_destructive_rebuild_assert = soft_assert(... |
"""
Credits goes to https://github.com/python-discord for the cog and docker
"""
import os
import re
import textwrap
from io import BytesIO
from signal import Signals
from typing import Optional, Tuple
import aiohttp
import discord
from discord.ext import commands
ip = os.environ.get("ip") # for docker container
SIG... |
"""Support for tariff selection."""
from __future__ import annotations
import logging
import voluptuous as vol
from homeassistant.components.select import SelectEntity
from homeassistant.components.select.const import (
ATTR_OPTION,
ATTR_OPTIONS,
DOMAIN as SELECT_DOMAIN,
SERVICE_SELECT_OPTION,
)
from... |
import _ExocortexAlembicPython as alembic
import sys
import argparse
# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
# global variables
b_verbose = False
obj_filter = None
typ_filter = None
noo_filter = None
not_filter = None
# ----... |
import numpy as np
# import tensorflow as tf
import pandas as pd
from keras.models import Sequential
from keras.layers import Dense, Activation, Dropout
from keras.optimizers import SGD, Adam
from keras.utils import plot_model
import matplotlib.pyplot as plt
import re
import tensorflowvisu as tfvu
df = pd.read_csv('t... |
import os
import shutil
import json
import sys
import logging
import click
import gc
import time
import logging
import time
import chainer
from chainer.iterators import MultithreadIterator
from chainer.training.updaters import StandardUpdater
from chainer.training import extensions, Trainer
from chainer.optimizers im... |
import numpy as np
from scipy.ndimage import gaussian_filter
import torch
from torchvision import transforms
import scipy.io as sio
import os
import cv2 as cv
import glob
class Beads:
def __init__(self, side=256, beadradMax=10, beadradMin=3, numbeadsMax=20, numbeadsMin=10, sigma=1):
self.side = side
... |
# =============================================================================
# file: JUnitHelper
# contains functions for compiling and running JUnit Tests
# =============================================================================
import os
import re
from subprocess import Popen, PIPE, STDOUT, TimeoutExpired
im... |
#
# 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... |
from functools import partial
from ...compat.collections import Counter
from ...external.qt.QtGui import (QWidget, QSlider, QLabel, QComboBox,
QHBoxLayout, QVBoxLayout)
from ...external.qt.QtCore import Qt, Signal
from ..widget_properties import (TextProperty,
... |
import wx
import sys
from copy import deepcopy
from wx import StaticText, EXPAND, TOP, ALIGN_CENTER, VERTICAL, HORIZONTAL, \
Color, ALIGN_CENTER_VERTICAL, CheckBox, Choice
from gettext import ngettext
from gui.uberwidgets.autoheightstatictext import AutoHeightStaticText
UPDATE_DESC_TEXT = _('Twitter allows... |
import json
from ploomber.constants import TaskStatus
from ploomber.products.metadata import Metadata
class _RemoteFile:
"""
A product-like object to check status using remote metadata. Since it
partially conforms to the Product API, it can use the same Metadata
implementation (like File). This is us... |
# Copyright 2017 the pycolab Authors
#
# 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 ... |
# Copyright The OpenTelemetry Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
"""Fireflies, by <NAME> <EMAIL>
A beautiful animation of fireflies. Press Ctrl-C to stop."""
__version__ = 1
# This program MUST be run in a Terminal/Command Prompt window.
# This program draws points that rotate on the surface of a sphere. The
# sphere is invisible and projected onto the user's 2D screen, so the po... |
import json
import os
import random
import threading
import urllib
import websocket
import thread
from texts import PAIRED, UNPAIRED_FROM_ALEXA
from utils import debug, notify, is_websocket_debug_mode, error
import xbmc
import xbmcaddon
NUM_SERVERS = 16
SERVER_DOMAIN = 'miracle-gw-%s.vertolab.com'
SERVER_PORT = 8012... |
import re
import time
import requests
from concurrent.futures import ThreadPoolExecutor, as_completed
from urllib.parse import urlparse, unquote
from lxml import etree
from functools import lru_cache
from cps.services.Metadata import Metadata, MetaSourceInfo, MetaRecord
DOUBAN_SEARCH_JSON_URL = "https://www.douban.c... |
import pandas as pd
import numpy as np
from ..misc import sort_data
# -----------------------------------------------------------------------------
#
# Functions and classes test implemented?
#
# get_turning_points yes
# filter_turning_points yes
# count_turning_points yes
# respons... |
class AVLTree:
"""Class encapsulating the AVL Tree
An empty subtree is defined to have a height of -1
Use only the following methods:
insert: to insert a value into the Tree
delete: delete a value from the Tree
search: returns the node containing the passed value or None if not found
height:... |
__version__ = '0.1b0'
import functools
import logging
import logging.config
import os
import sys
import shutil
import aiohttp
import aiohttp.web
import sys
import json
import requests_oauthlib
import ssl
import modconf
import argparse
import asyncio
import pickle
import base64
import subprocess
import async_patterns... |
from . import about
from . import _dbg
from . import gs
from . import gspatch
from .margo_state import ViewPathName
import sublime
STATUS_KEY = '#mg.Status'
STATUS_PFX = ' '
STATUS_SFX = ' '
STATUS_SEP = ' '
def render(*, mg, view, state, status):
def cb():
_render_tooltips(view, state.tooltips)
_render_st... |
import board
import digitalio
import time
import pyRTOS
def led1(self):
ledpin1 = digitalio.DigitalInOut(board.GP0)
ledpin1.direction = digitalio.Direction.OUTPUT
ledpin1.value = False
yield
while True:
ledpin1.value = not ledpin1.value
yield [pyRTOS.timeout(1)]
def... |
#!/usr/bin/env python
"""
This utility spawns a number of sub-processes for asynchronously processing
files located in `datadir` with the aim of making it easier to get the full use
from a multi-core PC.
Example usage:
batch.py --help
prints the command line help text
batch.py /path/to/data/directory
Use... |
#!/usr/bin/python
from __future__ import print_function
import yaml
import types
#EPSILON = 1e-6
EPSILON = 1e-5
def get_yaml_data (fname):
return yaml.load(open(fname).read());
def eps_equal (v1, v2, eps=EPSILON):
return abs(v1 - v2) < eps;
def list_eps_equal (v1, v2, eps=EPSILON):
return all(map (lamb... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import sqlite3
GLOB_CONNECTIONS_DICT = {}
def _data_path(db=''):
return os.path.realpath(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data', db))
def download(db='all', overwrite=Fal... |
import os.path
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from colorama import init
init(convert=True)
import click
import gzip
import re
import codecs
from fastq_wiper import log
def open_fastq_file(file_path: str):
fastq_file_handler = None
if '/' not in ... |
"""
Parser for VT100 input stream.
"""
from __future__ import unicode_literals
import re
import six
from six.moves import range
from ..key_binding.key_processor import KeyPress
from ..keys import Keys
from .ansi_escape_sequences import ANSI_SEQUENCES
__all__ = [
'Vt100Parser',
]
# Regex matching any CPR respo... |
import argparse
import json
import os
import sys
import urllib.request
import shutil
import subprocess
REPO_ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
sys.path.append(REPO_ROOT)
MODEL_STORE_DIR = os.path.join(REPO_ROOT, "model_store_gen")
os.makedirs(MODEL_STORE_DIR, exist_ok=True)
MAR_CONFI... |
import os
from tqdm import tqdm
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.io import wavfile
from python_speech_features import mfcc, logfbank #this is the library by jameslyones from practicalcryptography blog instead of librosa
import librosa
def plot_signals(signals):
fig,... |
# Copyright (c) 2008 Princeton University
# Copyright (c) 2009 Advanced Micro Devices, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met: redistributions of source code must retain the above c... |
from dataclasses import dataclass, field, fields
from functools import partial, wraps
from keyword import iskeyword
from types import FunctionType, MethodType
from typing import Dict, List, Sequence, Tuple, Union
from uuid import uuid4
from flash.core.serve.core import Connection, make_param_dict, make_parameter_conta... |
from enum import Enum
from typing import Iterable, Optional, Union, List
import pandas as pd
import torch
from einops import rearrange
from torch import Tensor
from torch_sparse import SparseTensor
import tsl
from tsl.ops.dataframe import to_numpy
class SynchMode(Enum):
WINDOW = 'window'
HORIZON = 'horizon'... |
import torch
from torch import nn
from torch.nn import functional as F
import torchvision.models as models
import ssl
import matplotlib.pyplot as plt
import config
from efficientnet_pytorch import EfficientNet
ssl._create_default_https_context = ssl._create_stdlib_context
def plot_image(img):
plt.axis("off")
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.