text stringlengths 3.07k 12.6k |
|---|
import pandas as pd
from itertools import groupby
def arrange_grouped_line_indices(line_connections, debug=False):
lines = [list(i) for j, i in groupby(line_connections, lambda a: a[2])]
if debug:
print('arrange_grouped_line_indices: %s \n---------\n' % (str(lines)))
arranged_line... |
import keras.backend as K
from keras.engine.topology import Layer
from keras import initializers
from keras import regularizers
from keras import constraints
from keras.layers.convolutional import Conv1D
import numpy as np
class Attention(Layer):
def __init__(self,
W_regularizer=None, b_regulariz... |
import torch
from torch import nn
from torch.nn import functional as F
from torch.utils.data import DataLoader
from torchvision import transforms
import pytorch_lightning as pl
from pytorch_lightning.core.lightning import LightningModule
from Data_loaders import data_loader
from models import hourglass
class Heatmap... |
"""
trains autoencoder
"""
import torch
import sys
import torch.nn as nn
import pickle
import os
# sys.path.insert(0, '/home/Anonymous/PycharmProjects/bayesian_prolo')
import numpy as np
from torch.autograd import Variable
from utils.global_utils import save_pickle
import itertools
sys.path.insert(0, '../')
torch.b... |
# -*- coding:utf-8 -*-
"""대한민국 (+ 세계) 환자수 수집"""
import re
import time
import requests
from bs4 import BeautifulSoup
from utils import postprocess, load_json
from slack_handler import SlackHandler
patients = load_json("./_data.json")
# def scrape_namuWiki():
# """나무위키에서 대한민국 확진환자수, 격리해제수, 사망자수 수집
#
# Return... |
"""
@author starrysky
@date 2020/08/16
@details 定义网络结构, 训练模型, 导出模型参数
"""
import os
import sys
import time
import pandas as pd
import torch
import torch.nn as nn
from PIL import Image
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
# 转换成28*28的Tensor格式
# trans = transforms.Compos... |
import datetime
from dateutil import parser
import json
import os
import struct
class HardwareRange:
def __init__(self, hardware_identifier=None, start=None, end=None):
self.hardware_identifier = hardware_identifier
self.start = start
self.end = end
def __repr__(self):
return ... |
from __future__ import print_function
import argparse
import codecs
import sys
import os
import asstosrt
from asstosrt import translate
def _get_args():
parser = argparse.ArgumentParser(description='A useful tool that \
convert Advanced SubStation Alpha (ASS/SSA) subtitle files \
... |
from .base_obj import *
import struct
import logging
logger = logging.getLogger(__name__)
class DataTypeCode(BaseObject):
"""deprecated by ValueTypeCode"""
ENUM16 = 0x01
ENUM16_BIT = 0x06
UNIT8 = 0x0a
UNIT16 = 0x0b
UINT32 = 0x0c
UINT64 = 0x0d
INT8 = 0x0f
INT16 = 0x10
INT32 ... |
import sqlite3
import numpy as np
import matplotlib as mpl
from prettytable.prettytable import from_db_cursor
import yaml
mpl.use ('Agg')
# mpl.use ('TKAgg')
import matplotlib.pyplot as plt
import kraken.performance_scenarios.utils as utils
import kraken.performance_scenarios.log as log
import kraken.performance_scenar... |
from typing import Sequence, Dict, Tuple
import dataclasses
import torch
from tagger_from_scratch.config import Config
@dataclasses.dataclass
class ConllCourpusSample:
tokens: list = dataclasses.field(default_factory=lambda: [])
pos: list = dataclasses.field(default_factory=lambda: [])
con: list = datac... |
#!python
import os
import numpy as np
import matplotlib.pyplot as plt
plt.ion()
from matplotlib import rc
rc('text', usetex=True)
import seaborn as sns
import matplotlib.patches as mpatches
color_list = sns.color_palette("muted", 10)
sns.palplot(color_list)
def plot_trajs(s, filename, title, ylim=(-2,6), xlim=(-2,6))... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: mcxiaoke
# @Date: 2017-05-29 15:01:41
# @Last Modified by: mcxiaoke
# @Last Modified time: 2017-06-27 17:09:59
from __future__ import print_function
import sys
import os
import codecs
import re
import string
import shutil
from datetime import datetime
ISO_DA... |
import numpy as np
import pandas as pd
from tsl.ops.dataframe import to_numpy
from . import checks
from ...typing import FrameArray
from ...utils.python_utils import ensure_list
class PandasParsingMixin:
def _parse_dataframe(self, df: pd.DataFrame, node_level: bool = True):
assert checks.is_datetime_lik... |
import torch
import torchvision
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D, proj3d
from matplotlib.patches import FancyArrowPatch
from datetime import datetime
from pdb import set_trace
MIN_16, MAX_16... |
import warnings
from dataclasses import dataclass
from typing import List, Optional
import numpy as np
from numpy.lib.stride_tricks import sliding_window_view
from soundsep.core.utils import ceil_div
@dataclass
class Bound:
start: int
stop: int
def __sub__(self, other: int):
return Bound(self.s... |
import sys
from PyQt5 import QtGui, QtWidgets, QtCore
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout, QLayout
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap, QFont
import os
import os.path as op
import olefile
import re
import base64
__author__ = "<NAME>"
__copyright__ ... |
# Copyright 2021 Peng Cheng Laboratory (http://www.szpclab.com/) and FedLab Authors (smilelab.group)
# 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/LICEN... |
#!/usr/bin/env python3.7
# -*- coding: utf-8 -*-
"""Entrypoint main routine"""
import logging
import argparse
import os
import sys
import traceback
from jinja2.exceptions import TemplateSyntaxError
import yaml
from yaml.scanner import ScannerError
from . import __version__ as version
from .hooks import Hooks
from . i... |
# Some basic setup:
import torch, torchvision
# Setup detectron2 logger
import detectron2
from detectron2.utils.logger import setup_logger
setup_logger()
# import some common libraries
import numpy as np
import os, json, cv2, random
from skimage.io import imread
from skimage.segmentation import mark_boundaries
from sk... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# */AIPND-revision/intropyproject-classify-pet-images/print_results.py
#
# PROGRAMMER: petercm
# DATE CREATED: 01/03/2019
# REVISED DATE:
# PURPOSE: Create a function print_results that prints the results statistics
# from the results statistics dictionary (result... |
# coding: utf-8
from django.http import QueryDict
from django.template import Library
from django.utils.formats import localize
register = Library()
@register.filter(name='meta')
def filter_meta(instance, key):
"""
Récupération d'une métadonnée sur une instance
:param key: Clé
:return: Valeur
""... |
import json
import os
import re
from fabric.api import cd, env, get, hide, local, put, require, run, settings, sudo, task
from fabric.colors import red
from fabric.contrib import files, project
from fabric.utils import abort, error
# Directory structure
PROJECT_ROOT = os.path.dirname(__file__)
env.project = 'pycon'
e... |
"""
Unit tests for PersonDao
"""
from datetime import datetime
import os
from os.path import dirname, abspath, join
from pytest import raises
from tempfile import mkstemp
from typing import List, Optional, TextIO
from textwrap import dedent
from manage_accounts.model.person import Person
from manage_accounts.persisten... |
from skimage.morphology import remove_small_holes, binary_erosion
from skimage.measure import regionprops, label
from skimage.filters import threshold_local
from skimage.morphology import disk, binary_opening
from skimage.exposure import rescale_intensity
from scipy.ndimage.filters import gaussian_filter
from skimage.t... |
"""jinja2_loader.py -- loader for jinja2 templates
Copyright 2015 by <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 appl... |
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
class table_3_6(QWidget):
qss = """
QWidget {
background: rgb(221, 221, 221);
border : 0px solid;
}
QPushButton{
background-color: r... |
""" ICODrops Excavator """
# Core Dependencies
from datetime import datetime
# External Dependencies
from bs4 import BeautifulSoup
# Internal Dependencies
from cryptkeeper.quarry.excavator import Excavator
from cryptkeeper.db.librarian import Librarian
import cryptkeeper.db.schema.icodrops as Schema
import cryptkeep... |
#!/usr/bin/env python
"""
Contains functions for performing calculations associated with the Duane model.
"""
# -*- coding: utf-8 -*-
#
# rtk.analyses.statistics.Duane.py is part of The RTK Project
#
# All rights reserved.
# Copyright 2007 - 2017 <NAME> andrew.rowland <AT> reliaqual <DOT> com
#
# Redistribution ... |
import curie as ci
import numpy as np
def basic_examples():
el = ci.Element('Fe')
print(el.S(20.0))
print(el.S(20.0, particle='a'))
el.plot_S()
stack = stack=[{'compound':'Ni', 'name':'Ni01', 'thickness':0.025}, # Thickness only (mm)
{'compound':'Kapton', 'thickness':0.05}, # No name - will not be talli... |
import contextlib
from django.db import transaction
from django.db.models import Manager
from django.db.models import Q
from django_cte import CTEQuerySet
from mptt.managers import TreeManager
from contentcuration.db.models.query import CustomTreeQuerySet
class CustomManager(Manager.from_queryset(CTEQuerySet)):
... |
#!/usr/bin/env python
# coding: utf-8
# In[3]:
## Python basics for novice data scientists, supported by Wagatsuma Lab@Kyutech
#
# The MIT License (MIT): Copyright (c) 2021 <NAME> and Wagatsuma Lab<EMAIL>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associat... |
import inspect
import sys
import time
import discord
from helpers.embed_builder import EmbedBuilder
from events.base import EventHandler
class MemberJoinEvent(EventHandler):
def __init__(self, client_instance):
self.client = client_instance
self.storage = self.client.storage
self.event =... |
import pycnnum
chs_arabic_map = {'零': 0, '一': 1, '二': 2, '三': 3, '四': 4,
'五': 5, '六': 6, '七': 7, '八': 8, '九': 9,
'十': 10, '百': 100, '千': 1000, '万': 10000,
'〇': 0, '壹': 1, '贰': 2, '叁': 3, '肆': 4,
'伍': 5, '陆': 6, '柒': 7, '捌': 8, '玖': 9,
... |
import mplayer, evdev
# Joystics
pl1 = evdev.InputDevice('/dev/input/by-path/platform-3f980000.usb-usb-0:1.5:1.0-event-joystick')
pl2 = evdev.InputDevice('/dev/input/by-path/platform-3f980000.usb-usb-0:1.3:1.0-event-joystick')
# Initialize video
p = mplayer.Player()
p.loadfile("ChildrensMCS.mp4")
p.fullstrceen = Tru... |
import types
import urllib
import locale
import datetime
import codecs
from decimal import Decimal
from django.utils.functional import Promise
class DjangoUnicodeDecodeError(UnicodeDecodeError):
def __init__(self, obj, *args):
self.obj = obj
UnicodeDecodeError.__init__(self, *args)
def __str_... |
from genericpath import exists
import os, subprocess, sys
from posixpath import splitext
import spotipy
import yaml
from spotipy.oauth2 import SpotifyOAuth
from youtube_search import YoutubeSearch
from difflib import SequenceMatcher
from subprocess import Popen, PIPE
## configuration
class config:
def __init__(s... |
""" Flexible swinging pendulum test-case
isort:skip_file
"""
# FIXME without appending sys.path make it more generic
import sys
sys.path.append("../../") # isort:skip
# from collections import defaultdict
# import numpy as np
from matplotlib import pyplot as plt
from elastica import *
class SwingingFlexibleP... |
import numbers
import numpy as np
import pandas as pd
import rpy2.robjects as ro
from rpy2.robjects import numpy2ri
from rpy2.robjects.packages import importr
from sklearn.base import BaseEstimator, ClassifierMixin, RegressorMixin
from sklearn.utils import compute_class_weight
glmnet = importr("glmnet")
base = import... |
# -*- encoding: utf-8 -*-
#
# The MIT License (MIT)
#
# Copyright © 2021 <NAME>
#
# 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 ... |
# Copyright 2021 Google LLC
#
# 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 writing,... |
# Copyright (C) 2017 Open Information Security Foundation
# Copyright (c) 2013 <NAME>
#
# You can copy, redistribute or modify this Program under the terms of
# the GNU General Public License version 2 as published by the Free
# Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# ... |
# 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 u... |
from __future__ import absolute_import, unicode_literals
from .celery import app
from celery.utils.log import get_task_logger
import time
from PIL import Image
import subprocess
from cairosvg import svg2png
from subprocess import check_output, STDOUT
import shlex
import sys
from pathlib import Path
TIMEOUT = 90
logge... |
"""
Generate Steady-State Visually Evoked Potential (SSVEP)
=======================================================
Steady-State Visually Evoked Potential (SSVEP) stimulus presentation.
"""
from time import time
from optparse import OptionParser
import numpy as np
from pandas import DataFrame
from psyc... |
import numpy as np
import csv
import pandas as pd
def open_csv_file(f_name):
"""
:param f_name: name of the csv file
:return: a new csv file with as many (1) as needed to not already exist
"""
try:
f = open(f_name, "x")
return f, f_name
except IOError:
r... |
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.keras.layers import Dense, Flatten, Conv2D, Conv2DTranspose, \
Reshape, BatchNormalization, LeakyReLU, Dropout
from tensorflow.keras import Model
LATENT_DIM = 100
NUM_EPOCHS = 50
BATCH_SIZE = 256
LEARNING_RATE = 1e-4
d_tra... |
# coding=utf-8
# Copyright 2020 The Google Research 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 applicab... |
#
# <NAME> <<EMAIL>>
#
# Copyright 2006, 2007, 2008, 2009, 2010 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use, modify,
# copy, or redistribute it subject to the terms and conditions of the GNU
# General Public License v.2. This program is distributed in the hope that it
# will ... |
# -*- coding: utf-8 -*-
# Copyright (c) 2019 <NAME>; MIT License
"""Response functionality from Telegram Bot Api."""
import jsonpickle
import telegrambotapiwrapper.typelib as types_module
from telegrambotapiwrapper.annotation import AnnotationWrapper
from telegrambotapiwrapper.errors import UnsuccessfulRequest
from t... |
import typing
import joblib
from datetime import datetime
from pathlib import Path
from typing import Optional
from sumo_docker_pipeline.logger_unit import logger
from sumo_docker_pipeline.operation_module.docker_operation_module import SumoDockerController
from sumo_docker_pipeline.operation_module.local_operation_mod... |
from time import time
from .net_utils import get_test_model
import os
import numpy as np
def test_model(opt,model, dataloaders):
model_path = opt['tsk_set']['path']['model_load_path']
if isinstance(model_path, list):
for i, path in enumerate(model_path):
__test_model(opt,model,dataloaders... |
import numpy as np
import gym
import random
import tools
from cvxopt import matrix, solvers
import matplotlib.pyplot as plt
import numpy.random as rn
import copy
import sys
from contextlib import closing
from io import StringIO
from gym import utils
from gym.envs.toy_text import discrete
import os
import argparse
from... |
# -*- encoding:utf8 -*-
import tensorflow as tf
import numpy as np
import os
import sys
from copy import deepcopy
stdout = sys.stdout
reload(sys)
sys.stdout = stdout
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
import cPickle as pkl
from utils import *
from models import DecompAtt
class DecompAttConfig(object):
def... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
'''
<table class="ee-notebook-buttons" align="left">
<td><a target="_blank" href="https://github.com/giswqs/earthengine-py-notebooks/tree/master/Algorithms/CloudMasking/modis_surface_reflectance_qa_band.ipynb"><img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> View source on GitHub</a>... |
from bg.grimm import GRIMMReader
from bg.tree import BGTree
from bg.genome import BGGenome
from bg.vertices import BGVertex
import numpy as np
import os
import csv
get_colors_by_edge = lambda e: e.multicolor.multicolors
def white_proportion(colors):
return np.mean(list(map(lambda c: c == 0, colors)))
def get_... |
# -*- coding: utf-8 -*-
"""
Annotation storage API.
This module provides the core API with access to basic persistence functions
for storing and retrieving annotations. Data passed to these functions is
assumed to be validated.
"""
# FIXME: This module was originally written to be a single point of
# indirectio... |
import numpy as np
import pandas as pd
from scipy import sparse
from sklearn.base import TransformerMixin
from sklearn.utils import Parallel, delayed
from sklearn.utils.metaestimators import _BaseComposition
class FeatureConcat(_BaseComposition, TransformerMixin):
"""Concatenates results of multiple transformer o... |
# -*- coding: UTF-8 -*-
# A part of NonVisual Desktop Access (NVDA)
# This file is covered by the GNU General Public License.
# See the file COPYING for more details.
# Copyright (C) 2006-2021 NV Access Limited, <NAME>
import IAccessibleHandler
from comInterfaces import IAccessible2Lib as IA2
import oleacc
import winU... |
# -*- coding: utf-8 -*-
"""
Created on 16 Sep 2020 15:01:35
@author: jiahuei
"""
import logging
import math
import torch
from torch import optim
logger = logging.getLogger(__name__)
# noinspection PyAttributeOutsideInit
class RateOpt:
"""Optim wrapper that implements rate."""
def step(self, step=None, epoch... |
from unittest import mock
from pytuber import cli
from pytuber.core.commands.cmd_add import (
create_playlist,
parse_jspf,
parse_m3u,
parse_text,
parse_xspf,
)
from pytuber.core.models import PlaylistManager, PlaylistType, Provider
from tests.utils import CommandTestCase, PlaylistFixture
class Co... |
import numpy as np
import pytest
from pandas import DataFrame, Index, Series
import pandas._testing as tm
def test_delitem():
# GH 5542
# should delete the item inplace
s = Series(range(5))
del s[0]
expected = Series(range(1, 5), index=range(1, 5))
tm.assert_series_equal(s, expected)
de... |
# Copyright 2020 Huawei Technologies Co., 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 agreed to... |
from time import sleep
from kivy.app import App
from kivy.properties import ObjectProperty, StringProperty
from kivy.uix.gridlayout import GridLayout
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.treeview import TreeViewLabel
from kivy.uix.popup import Popup
from kivy.uix.floatlayout import Flo... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import functools
import json
import os
import re
import warnings
from base64 import b64encode
import requests
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5
from log import logger
RSA_PUBLIC_KEY = """-----<KEY>
-----END PUBLIC K... |
"""A module for launching docker images from within python applications."""
import contextlib
import pathlib
import random
import subprocess
import typing
from labm8.py import app
from labm8.py import bazelutil
from labm8.py import labtypes
def IsDockerContainer() -> bool:
"""Determine if running inside a docker c... |
from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
import os
app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir,'db.sqlite')
app.config['SQLALCHE... |
# Copyright 2021 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... |
import torch.nn as nn
from functools import reduce
class SKConv(nn.Module):
def __init__(self,in_channels,out_channels,stride=1,M=2,r=16,L=32):
super(SKConv,self).__init__()
d=max(in_channels//r,L)
self.M=M
self.out_channels=out_channels
self.conv=nn.ModuleList()
... |
'''
Utility functions used by the cibuildwheel tests.
This file is added to the PYTHONPATH in the test runner at bin/run_test.py.
'''
import os
import platform as pm
import shutil
import subprocess
import sys
from contextlib import contextmanager
from tempfile import mkdtemp
IS_WINDOWS_RUNNING_ON_AZURE = os.path.exi... |
from django.shortcuts import render,HttpResponse
from apps.interface.services.HTTP_interface_debugService import HTTP_interfaceDebugService
from apps.common.func.CommonFunc import *
from apps.common.func.LanguageFunc import *
from apps.common.helper.ApiReturn import ApiReturn
from AutotestWebD import settings
import js... |
#!/usr/bin/env python3
#
# Copyright © 2020 Google LLC
#
# 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, m... |
import glob
import os
from PIL import Image
from elasticsearch import Elasticsearch
from elasticsearch.helpers import bulk
from flask import Flask, render_template, request, Response
from werkzeug.utils import secure_filename
import json
from capgen import CaptionGenerator
os.environ['CUDA_VISIBLE_DEVICES'] = ''
es ... |
# -*- coding: utf-8 -*-
"""
Transformation function from "graph adjacency matrix" to
1. graph laplacian matrix
2. normalize graph matrix
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from scipy.sparse.csr import csr_matrix
... |
import logging
import time
import random
import csv
import matplotlib.pyplot as plt
import numpy as np
from math import log10
from type_system import Type, PolymorphicType, PrimitiveType, Arrow, List, UnknownType, INT, BOOL
from program import Program, Function, Variable, BasicPrimitive, New
from cfg import CFG
from p... |
#!/usr/bin/env python
# encoding: utf-8
"""
Translate ttf files to IE8 compatible EOT files.
Based on the implementation of ttf2eot in nodejs by fontello.
(https://github.com/fontello/ttf2eot/)
"""
import consts
from .bytebuffer import ByteBuffer
__all__ = ('ttf2eot', )
def strbuf(raw):
b = ByteBuffer(bytearr... |
#!/usr/bin/env python
# work with MPU6050_kalman.ino
from PyQt5 import QtCore, QtWidgets, uic, QtGui
from pyqtgraph import PlotWidget
from PyQt5.QtWidgets import QApplication, QVBoxLayout
import pyqtgraph as pg
import numpy as np
import datetime
import serial
import sys
import os
import time
from time import sleep
fro... |
try:
# absolute import
from pipeline import NO_PAIRS_ERROR
from utils import printRed
except:
# relative import
from ..pipeline import NO_PAIRS_ERROR
from ..utils import printRed
import torch as th
import numpy as np
def overSampling(batch_size, m_list, pairs, function_on_pairs, actions, rewa... |
# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
import os
import sys
import shutil
import subprocess
from fnmatch import fnmatchcase
from distutils.util import convert_path
# Do not EVER use setuptools, it makes cythonization fail
# Distribute fixes that
from distutils.core imp... |
from rest_framework import serializers
from api.pokemon.serializers import PokemonSerializer, PokemonWinnerSerializer
from api.users.serializers import UserSerializer
from battles.models import Battle, BattleTeam
from battles.tasks import run_battle_and_send_result_email
from battles.utils.battle import get_round_winn... |
from collections import defaultdict
from ichnaea.data.base import DataTask
from ichnaea.geocalc import (
distance,
range_to_points,
)
from ichnaea.models import (
Cell,
CellArea,
CellBlacklist,
CellObservation,
Wifi,
WifiBlacklist,
WifiObservation,
)
from ichnaea import util
class... |
import os
import random
import importlib
from source.tool import config_parser
CONVERT_STR2NUM = ["piecewise_lr_decay", "piecewise_boundaries"]
def type_convert(v):
""" convert value to int, float or str"""
try:
float(v)
tp = 1 if v.count(".") == 0 else 2
except ValueError:
tp =... |
import logging
import os.path
from tempfile import NamedTemporaryFile
from time import time as ts
from typing import Dict, List
from . import utils
from .config import config
from .container import ContainerRunner
logger = logging.getLogger(__name__)
DOCKER_IMAGES_ARCHIVE_FILE_NAME = "images.tar"
class CacheManage... |
import pytest
import tensorflow as tf
from speech_recognition.models.deepspeech2 import Convolution, DeepSpeech2, Recurrent
@pytest.mark.parametrize(
"num_layers,channels,kernel_sizes,strides,batch_size,sequence_length,frequency_bins,feature_dim",
[
(1, [32], [[41, 11]], [[2, 2]], 7, 111, 33, 1),
... |
from __future__ import print_function
import os
import cdms2
import MV2
import acme_diags
from acme_diags.plot import plot
from acme_diags.derivations import acme
from acme_diags.metrics import rmse, corr, min_cdms, max_cdms, mean
from acme_diags.driver import utils
def create_metrics(ref, test, ref_regrid, test_reg... |
#!/usr/bin/env python
#
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from builtins import str
from future import standard_library
import dns.exception
import dns.resolver
import logging
import os
import requests
... |
# -*- coding: utf-8 -*-
#
# tests/test_consultarstatusoperacional.py
#
# Copyright 2015 Base4 Sistemas Ltda ME
#
# 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/li... |
import sys
import os
#make sure the program can be executable from test file
dir_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '.'))
sys.path.append(dir_root)
import numpy as np
import matplotlib.pyplot as plt
import math as mt
import numpy.polynomial.legendre as legen
import cmath
#domain is the ra... |
from __future__ import absolute_import, division, print_function
import pytest
pytest.importorskip('bcolz')
from odo.backends.bcolz import (append, convert, ctable, carray, resource,
discover, drop)
from odo.chunks import chunks
from odo import append, convert, discover, into
import n... |
import os
from bs4 import BeautifulSoup, Tag
from logging import getLogger
from requests import Response
from config import IMG_PATH
from .base import SESSION, USERNAME, PASSWORD
from .page import Page
logger = getLogger(__name__)
def get_chaptcha(soup: Tag) -> str:
c = ""
try:
ccaptcha: Tag = soup.f... |
"""
MIT License
Copyright (c) 2020-2021 phenom4n4n
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, publis... |
import torch
from torch.utils.data import IterableDataset, DataLoader
import csv
import torch.nn.functional as F
LOG_FILE = 'logs.txt'
FILENAME = 'full_dataset_bert_title_doc2vec_story.csv'
NUM_CATEGORIES = 19
IGNORE_COLS = ['url', 'story', 'title', 'first_cover_image', 'story_images']
Y_COLS = ['raised']
NUM_TEST = 3... |
"""Imports marvelo problems and results from csv"""
import os
import math
import re
import csv
import numpy as np
from infrastructure import InfrastructureNetwork
from overlay import OverlayNetwork
from embedding import PartialEmbedding
def csv_to_list(csvfile, sep=","):
"""Parses a csv file into a 2d array, ig... |
# -*- coding: utf-8 -*-
from __future__ import generators
import logging
import unittest2 as unittest
from urllib import addinfourl
try:
from contextlib import contextmanager
except ImportError:
from celery.tests.utils import fallback_contextmanager as contextmanager
from StringIO import StringIO
from anyjson... |
#!/usr/bin/env python
from __future__ import print_function, division
import argparse
import sys
try:
import pip._internal.pep425tags as p
except:
import pip.pep425tags as p
try:
# For Python 3.0 and later
from urllib.request import urlopen, HTTPError, Request
except ImportError:
# Fall back to Pyth... |
import tensorflow as tf
from tensorflow.keras.layers import Add
from tensorflow.keras.layers import AveragePooling2D
import gloro
from gloro.layers.network_layers import ResnetBlock
from gloro.utils import l2_normalize
class LipschitzComputer(object):
def __init__(self, layer, *args, **kwargs):
self._... |
# Copyright 2015 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... |
import time
import socket
import zlib
import struct
import pysyncobj.pickle as pickle
import pysyncobj.win_inet_pton
from .poller import POLL_EVENT_TYPE
from .monotonic import monotonic as monotonicTime
class CONNECTION_STATE:
DISCONNECTED = 0
CONNECTING = 1
CONNECTED = 2
def _getAddrType(addr):
tr... |
# Copyright 2016 The Bazel 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 applicable la... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.