text stringlengths 3.07k 12.6k |
|---|
from __future__ import print_function
import sys
import numpy as np
import os
if __name__ == '__main__':
import matplotlib
matplotlib.use('Agg')
from astrometry.util.fits import fits_table, merge_tables
from astrometry.util.file import trymakedirs
from legacypipe.survey import LegacySurveyData
'''
This scrip... |
#!/usr/bin/env python
"""Wrapper for TMHMM v2.0 for use in Galaxy.
This script takes exactly three command line arguments - number of threads,
an input protein FASTA filename, and an output tabular filename. It then
calls the standalone TMHMM v2.0 program (not the webservice) requesting
the short output (one line per ... |
# No member error in this file are for inheritance in Odoo!
# pylint: disable=E1101
from odoo import models, fields, _
from odoo.exceptions import ValidationError, UserError
# The original definition is done in account_check_printing/models/account_payment.py !
MAP_INVOICE_TYPE_PARTNER_TYPE = {
'out_invoice': 'c... |
# from segmentation_models_pytorch.base import modules as md
import torch
import torch.nn as nn
import torch.nn.functional as F
from deadtrees.network.extra import modules as md
class ASPP(nn.Module):
"""ASPP described in https://arxiv.org/pdf/1706.05587.pdf but without the concatenation of 1x1, original feature ... |
import networkx as nx
import random
import numpy as np
def n_ary_tree(size, n):
G=nx.DiGraph()
for i in range(1, size + 1):
G.add_node(i)
for i in range(1, size + 1):
for j in range(0, n):
if i * n + j - (n - 2) < size + 1:
G.add_edge(i, i * n + j - (n - 2))
... |
import time
import threading
import math
import traceback
from sensor_msgs.msg import LaserScan
import rclpy
from rclpy.node import Node
from rcl_interfaces.msg import ParameterDescriptor
from .driver import YDLidar
from .parser import YDLidarScanParser
from .logging_rclpy import *
class YDLidarNode(Node):
def ... |
"""Common verification functions for BFD"""
# Python
import logging
# Genie
from genie.utils.timeout import Timeout
from genie.metaparser.util.exceptions import SchemaEmptyParserError
from genie.utils import Dq
log = logging.getLogger(__name__)
def verify_bfd_session(device, session_address, expected_... |
#!/usr/bin/env python3
import abc
import enum
import re
class TokenType(enum.Enum):
NEWLINE = enum.auto()
SYMBOL = enum.auto()
DEFINE = enum.auto()
IN = enum.auto()
EXCLAMATION = enum.auto()
INQUIRY = enum.auto()
UNION ... |
# Converted from juypter notebook script
# Calculate correlation between stocks. Here the following methodology is used:
# Correlate daily change (X[i]-X[i-1])/X[i-1] (this seems to be the most reasonable, and is what the internet suggests)
# Historic stock performance downloaded as wkn_[wkn]_historic.csv with semicolo... |
import os,inspect,argparse, datetime, copy, itertools, time
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(os.path.dirname(currentdir))
os.sys.path.insert(0, parentdir)
os.sys.path.insert(0, os.path.dirname(currentdir))
# from b3px_gym.b3px_env.single... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 26 14:07:29 2019
@author: yuhanyao
"""
import glob
import numpy as np
import pandas as pd
from astropy.io import fits
import csv
from astropy.time import Time
#import astropy.io.ascii as asci
# w3browse-270382.tar, obsid: 00011286001; startdate: 20... |
from datetime import timedelta, date, datetime, tzinfo, timedelta
from django.template import Template, Context, add_to_builtins
from django.utils import unittest
from django.utils.dateformat import DateFormat
from django.utils.translation import ugettext as _
from django.utils.html import escape
add_to_builtins('dja... |
# -*- coding: utf-8 -*-
"""
@author: salimt
"""
"""
A restaurant recommendation system.
Here are some example dictionaries. These correspond to the information in
restaurants_small.txt.
Restaurant name to rating:
# dict of {str: int}
{'Georgie Porgie': 87,
'Queen St. Cafe': 82,
'Dumplings R Us': 71,
'Mexican Gri... |
import os, re, pdb, json, argparse
import pandas as pd
# import matplotlib.pyplot as plt
from natsort import natsorted
import numpy as np
import time
import sys
sys.path.append('../')
def print_result(hvac, coil, ppd):
print(' HVAC POWER:', hvac, 'BASELINE DIFF:', baseline_hvac - hvac )
print(' COIL POWER... |
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
import random
import os
import socket
import sys
from shutil import make_archive
import argparse
from urllib.parse import quote
import atexit
import zipfile
import tempfile
import qrcode
def is_supported_env():
return sys.platform != 'win32' or... |
# Copyright 2018 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... |
import pickle
from tqdm import tqdm
import time
import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Dense, Embedding
from tensorflow.keras.layers import LSTM
from tensorflow.keras.layers import Activation
from tensorflow.keras.layers import SpatialDropout1D
import tensorflow.keras.backend... |
import signal
import os.path
import logging.config
import functools
import time
import sys
import argparse
import subprocess
import yaml
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk
ETC_ROOT = os.path.join('/', 'etc', 'carillon')
CONFIG_ROOT = os.path.join(ETC_ROOT, 'conf.d')
USER_CONFIG =... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time
import numpy as np
import tensorflow as tf
import tensorlayer as tl
from tensorlayer.layers import (
Dense, Dropout, Flatten, Input, MaxPool2d, QuanConv2d, QuanConv2dWithBN, QuanDense, QuanDenseLayerWithBN
)
from tensorlayer.models import Model
tl.loggi... |
import os
import unittest
from ..deserializers import CoverageDeserializer
from ..deserializers import NosetestDeserializer
from ..parsers import NosetestParser
from ..parsers import RadonParser
def _get_data_filename(filename):
return os.path.join(
os.path.dirname(os.path.realpath(__file__)),
'... |
# -*- encoding: utf-8 -*-
#
#
# Copyright (C) 2006-2011 <NAME> <<EMAIL>>
#
# This file is part of PyX (http://pyx.sourceforge.net/).
#
# PyX is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of ... |
from __future__ import absolute_import, unicode_literals
from django.contrib import messages
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render_to_response
from django.templ... |
import argparse
import numpy as np
import open3d as o3d
import random
import time
import torch
from torch.utils.data import DataLoader
from tqdm import tqdm
from data import CustomData
from models import IterativeBenchmark, icp
from metrics import compute_metrics, summary_metrics, print_metrics
from utils import npy2pc... |
import pandas as pd
import numpy as np
from parse_computed import get_interval_df
from raw_dex_reader import get_dex_as_dataframe as get_dex_as_dataframe2
def get_dex_as_dataframe(fn, well_name):
raw = get_dex_as_dataframe2(fn)
raw["Well_name"] = well_name
return raw
def transform_labels_to_ages... |
"""BaseCleaner for all Cleaner transformers."""
from collections import namedtuple
import pandas as pd
from foreshadow.base import BaseEstimator, TransformerMixin
from foreshadow.exceptions import InvalidDataFrame
from foreshadow.logging import logging
from foreshadow.metrics import (
MetricWrapper,
avg_col_... |
import base64
import io
import optparse
import os
import cv2
import flask
import numpy as np
import requests
from PIL import Image
import forward
UPLOAD_FOLDER = '/tmp/demo'
ALLOWED_EXTENSIONS = {'bmp', 'jpeg', 'jpg', 'jpe', 'png', 'pbm', 'tif'}
classes = ['Apple Braeburn', 'Apple Crimson Snow', 'Apple Golden 1', 'A... |
import os
import torch
import torch.multiprocessing as mp
import torch.utils.data as data
import torchvision.transforms as transforms
from pathlib import Path
from PIL import Image
from ml import cv
# Thread-safe image dataset with cache
# Metadata: cls, subdir, basename
"""
def pil_imread(path):
# open path as f... |
#!/usr/bin/python
#
# Copyright (C) 2007, 2008 Google Inc.
#
# 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 applicabl... |
import glob, os
import shutil
import json
import numpy as np
import random
import cv2
from .utils import *
from distutils.dir_util import copy_tree
def splitAndCastToFloat(line):
line = line.split()
line = line[0:3]
return list(map(float, line))
def get_ply_bb_corners(ply_model):
with open(ply_model) as f:
cont... |
#!/usr/bin/env python
# coding: utf-8
from bs4 import BeautifulSoup
from ebooklib import epub
import ebooklib
import docx
from difflib import SequenceMatcher
from pdfminer.pdfparser import PDFParser
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfinterp import resolve... |
from weakref import WeakKeyDictionary
import six
from ..cypher.operations import CypherExpression, CypherOperatorInterface
from ..exceptions import ImmutableAttributeError
try:
str = unicode
except NameError:
pass
class SetOnceDescriptor(object):
def __init__(self, name, type=None):
self.name =... |
#!/usr/bin/env python
#
# Author: <NAME> <<EMAIL>>
#
import time
import ctypes
import numpy
import scipy.linalg
from pyscf import lib
from pyscf.lib import logger
from pyscf import gto
from pyscf.df import incore
from pyscf.scf import _vhf
libri = lib.load_library('libri')
# (ij|L)
def aux_e2(mol, auxmol, intor='cin... |
"""Fuse 1000 RGB-D images from the 7-scenes dataset into a TSDF voxel volume with 2cm resolution.
"""
import time
import cv2
import numpy as np
import pyk4a
from pyk4a import Config, PyK4A
import fusion
from numba import jit
#import icp.basicICP as icp
import Generalized_ICP.Generalized_ICP
def configureCamera():
... |
import os
import pickle
import numpy as np
from sklearn.decomposition import PCA
from utils.CSV_data_generator import CSVDataGen
from utils.Semantic.SemanticFeatureSelection import SemanticFeatureSelection
from utils.PatternFeatureReduction import PatternFeatureSelection
from utils.SemanticPatternFeatureSelection impo... |
import base64
import json
import logging
from urllib import parse
from authlib_gino.fastapi_session.api import (
auth,
login_context,
require_user,
)
from authlib_gino.fastapi_session.models import User
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.ciphers imp... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import warnings
from spacy_stanfordnlp import StanfordNLPLanguage
import stanfordnlp
from copy import deepcopy
from spacy_conll import ConllFormatter
from pathlib import Path
from qa2nli.qa_readers.race import read_data as race_read_data
from qa2nli.qa_readers.race impor... |
#!/usr/bin/env python
import os
import sys
from argparse import ArgumentParser
import h5py
import numpy as np
from skimage.morphology import watershed
from scipy.ndimage.morphology import grey_dilation, binary_erosion
from scipy.special import expit
from scipy.ndimage import distance_transform_edt
from skimage.morpho... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import tensorflow as tf
import numpy as np
# load data
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
# create a graph and then launch it in a session
sess = tf.InteractiveSession(... |
from math import sqrt
from compyle.api import declare
from pysph.sph.equation import Equation
class ComputeNormals(Equation):
"""Compute normals using a simple approach
.. math::
-\frac{m_j}{\rho_j} DW_{ij}
First compute the normals, then average them and finally normalize them.
"""
d... |
# -*- coding: utf-8 -*-
###############################################################################
#
# WeatherByCenterPointSubgridSummarized
# Retrieve weather information for a rectangle defined by a center point and distances in the latitudinal and longitudinal directions.
#
# Python versions 2.6, 2.7, 3.x
#
# ... |
#!/usr/bin/env python
"""Functions to display tree for a Panseq Loci
"""
import tempfile
import colorsys
import re
from collections import namedtuple
from ete3 import Tree, AttrFace, TextFace, TreeStyle
from panseqtrees.fasttree import FastTreeWrapper
from panseqtrees.seqaligner import SeqAligner
__author__ = "<... |
"""
colours.py
Pretty colours, colours everywhere
Parses colours using a $(colour) or $(formatting) template.
Supports both the American and British spellings of many colours and words.
Created By:
- Zarthus <<EMAIL>>
Maintainer:
- <NAME> <https://github.com/lukeroge>
License:
MIT License (MIT)
Copy... |
import torch
from elegantrl.agents.AgentBase import AgentBase
from elegantrl.agents.net import QNet, QNetDuel
class AgentDQN(AgentBase):
"""
Bases: ``AgentBase``
Deep Q-Network algorithm. “Human-Level Control Through Deep Reinforcement Learning”. Mnih V. et al.. 2015.
:param net_dim[int]: the dimens... |
#!/usr/bin/env python
import datetime
import os
import shutil
import subprocess
import json
from netCDF4 import Dataset
from pyclowder.utils import CheckMessage
from pyclowder.datasets import get_info, get_file_list, download_metadata, upload_metadata
from pyclowder.files import upload_to_dataset, submit_extraction
f... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... |
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2019 by <NAME> <<EMAIL>>
# All rights reserved. BSD 3-clause License.
# This file is part of the SPORCO package. Details of the copyright
# and user license can be found in the 'LICENSE.txt' file distributed
# with the package.
"""Construct variant of admm subpackage that u... |
from flask import render_template, request, abort, g, Blueprint
from flask import Flask
from flask_babel import Babel
import requests_cache
import requests
import datetime
import json
import time
import keen
from flask_wtf import FlaskForm
from wtforms import StringField
from wtforms.validators import DataRequired
impo... |
import websocket
import argparse
import json
import RPi.GPIO as GPIO
import time
###################################################
## ROBOT STUFF
###################################################
#Definition of motor pin
IN1 = 20
IN2 = 21
IN3 = 19
IN4 = 26
ENA = 16
ENB = 13
#Definition of RGB module pins
LED_R... |
import uuid
import json
import logging
import redis
import datetime
# Extended TTL to 24 hours for https://github.com/Occupancy-App/Occupancy-App-API/issues/6
key_expire_value = 60 * 60 * 24
def get_redis_hash_by_id( db_handle, space_id ):
# Make sure the space ID string is a legit UUID
space_uuid = uuid.UUI... |
# referenced from Megatron and used to testify communication
import os.path as osp
import pytest
import torch
from torch.utils.data import DataLoader
from colossalai.builder import ModelInitializer, build_dataset, build_optimizer, build_loss
from colossalai.communication import p2p as p2p_communication
from colossala... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2017-present Alibaba Group Holding Limited. <NAME> <<EMAIL>>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it u... |
import glob
import random
import shutil
import base64
import gym
from PIL import Image
from io import BytesIO
from skimage.color import rgb2gray
import gym_maze
import numpy as np
from flask import Flask, request, send_from_directory, jsonify
import os
from example.dcgan_example.explore.dream import Dream
dir_path ... |
"""
This module contains robust functions for creating and maintianing a persistent network connection between two different network stacks.
It manages network discovery, socket connections, pubsub behaviors, detection of disconnection, reconnection, and status messaging.
The syntax for invoking this module is:
my_c... |
import timeit
from django.utils import timezone
from django.core.exceptions import ValidationError
from base.tests import BaseTestCase
from company.tests.tests_models import get_or_create_company
from finance.models import (Currency, TaxReceipt, TaxReceiptAuthorization,
TaxReceiptNumber)
class CurrencyModelTes... |
# Copyright (c) 2012-2018 SoftBank Robotics. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the COPYING file.
""" Common parsers for qisrc actions """
import os
from collections import OrderedDict
import qisys.parsers
import qisys.worktree
import qisrc.workt... |
# Stubs for sys
# <NAME> <<EMAIL>>
# based on http://docs.python.org/3.2/library/sys.html
from typing import (
Undefined, List, Sequence, Any, Dict, Tuple, TextIO, overload
)
# ----- sys variables -----
abiflags = ''
argv = Undefined(List[str])
byteorder = ''
builtin_module_names = Undefined(Sequence[str]) # act... |
#######################################################################
# Copyright (C) 2017 <NAME>(<EMAIL>) #
# Permission given to modify the code as long as you keep this #
# declaration at the top #
##############################################################... |
# This file is part of the Reproducible and Reusable Data Analysis Workflow
# Server (flowServ).
#
# Copyright (C) 2019-2021 NYU.
#
# flowServ is free software; you can redistribute it and/or modify it under the
# terms of the MIT License; see LICENSE file for more details.
"""Declarations for file parameter values. A... |
import os
import h5py
import numpy as np
import dataloaders.nyu_transforms as transforms
from torch.utils.data import Dataset
# NYU and Kitti_odo
import dataloaders.nyu_transforms as nyu_transforms
from dataloaders.pert_nyu import ShiftDepth
iheight, iwidth = 480, 640 # raw image size
to_tensor = nyu_transforms.ToTen... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 7 20:39:33 2021
@author: <NAME>
You need intall Simplegui
You can see the code in action here:
https://py3.codeskulptor.org/#user306_sydC1JTW7UoWgaO.py
"""
# Implementation of classic arcade game Pong
import simplegui
import random
# initialize globals - pos and... |
# @AUTHOR: Piplopp <https://github.com/Piplopp>
# @DATE: 05/2017
#
# @DESC This script generates a blank template for translation of the fire emblem
# heroes unit names, weapons, assit, special and passive skills for the
# feh-inheritance-tool <https://github.com/arghblargh/feh-inheritance-tool>.
#
# It will parse the ... |
from .string_expr import StringExpression
from . import filepath_utils
from ..rfb_logger import rfb_log
from bpy.app.handlers import persistent
import bpy
import os
import re
PAD_FMT = ['%d', '%01d', '%02d', '%03d', '%04d']
__SCENE_STRING_CONVERTER__ = None
# FIXME: we should get the extensions from the display driver... |
"""
This module is used to query data in a follow up log for the Clinical Research Study Manager package
"""
import datetime
import pandas as pd
from clinical_research_study_manager.data_request_functions import get_date_info
from clinical_research_study_manager.stats_functions import create_dataframe_from_log
def ... |
from sacred import Experiment
from sacred.utils import apply_backspaces_and_linefeeds
from experiments.utils import get_observer
from experiments.evaluation import import_weights_into_network
from experiments.utils import ExperimentData
from xview.datasets import get_dataset
from xview.models import get_model, BayesFus... |
# -*- coding: utf-8 -*-
"""Tests for pybaselines.polynomial.
@author: <NAME>
Created on March 20, 2021
"""
from math import ceil
import numpy as np
from numpy.testing import assert_array_almost_equal
import pytest
from pybaselines import polynomial
from .conftest import get_data, AlgorithmTester
class TestPoly(... |
"""Wrap Model with a start_epoch arg."""
import os
import math
import numpy as np
from mindspore import context
from mindspore.train import Model
from mindspore.train.callback import RunContext
from mindspore.common import Tensor
from mindspore.parallel._ps_context import _is_role_pserver
def _transfer_tensor_to_tupl... |
"""
@author: <NAME>
@since: 13/08/2017
A BST holds the properties L < current < R.
The BST also must not contain duplicate values.
https://www.hackerrank.com/challenges/ctci-is-binary-search-tree/problem
An approach to each node upholds the BST property with it's direct children is not enough as a tree witht he fol... |
import os
from enum import Flag, auto
from io import BytesIO
from textwrap import wrap
import piexif
import requests
from PIL import Image, ImageFont, ImageDraw
BREAKPOINT_DIMENSION = 400 # 400px
MARGIN_RATIO = 0.04 # 4%
FONT_RATIO = 0.04 # 4%
FRAME_COLOR = '#fff' # White frame
TEXT_COLOR = '#000' # Black text
... |
import binascii
import os
import select
import sys
import time
import threading
from enum import IntEnum
from . import apdu
from . import usb
from .display import RENDER_METHOD
class SephTag(IntEnum):
BUTTON_PUSH_EVENT = 0x05
FINGER_EVENT = 0x0c
DISPLAY_PROCESSED_EVENT = 0x0d
... |
import netCDF4
def _get_metadata():
metadat = dict()
metadat['iscan'] = {'long_name': 'PR scan index', 'units': None}
metadat['iray'] = {'long_name': 'PR ray index', 'units': None}
metadat['itilt'] = {'long_name': 'GR tilt index', 'units': None}
metadat['x'] = {'long_name': 'W-E location w.r.t. ra... |
import warnings
import socket
import os
try:
import rpyc
from rpyc.utils.server import ThreadedServer
except ImportError:
warnings.warn("rpyc is needed to run the service")
from pyaedt.generic.rpyc_services import GlobalService
def server(port=18000):
"""Starts an rpyc servers an start listening on s... |
import json
from typing import List, Dict, Set
from deprecated import deprecated
from graphviz import Digraph
class State:
"""Transition System的状态类"""
loc: str = None # 来自PG的Loc
eval_var: Dict[str, int] = None # 所有Var的取值Eval(Var),这里用字典表示
def __init__(self, loc_: str, eval_var_: Dict):
"""构造... |
from unittest import mock
from framewirc.messages import build_message, ReceivedMessage
from framewirc.parsers import (
apply_kwargs_parser,
apply_message_parser,
is_channel,
nick,
privmsg,
)
class TestIsChannel:
"""Tests for the boolean function is_channel."""
def test_starts_with_ampers... |
#!/usr/bin/env python
import argparse
import itertools as itt
from collections import Counter
from copy import deepcopy
import gym
import pyro
import torch
from gym.wrappers import TimeLimit
from pyro.distributions import Categorical, Delta
from pyro.infer import EmpiricalMarginal, Importance
from tabulate import tab... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" timedcache.py
A cache that periodically resets and include its instantiation decorator function.
"""
# Package Header #
from ..__header__ import *
# Header #
__author__ = __author__
__credits__ = __credits__
__maintainer__ = __maintainer__
__email__ = __email__
# Imp... |
from __future__ import print_function
import os
import os.path
import errno
import numpy as np
import sys
import cv2
from PIL import Image
import torch.utils.data as data
from torchvision.datasets.utils import download_url, check_integrity
from torchvision.transforms import transforms
IMG_EXTENSIONS = [
'.jpg', ... |
"""cogeo-mosaic STAC backend."""
import json
import os
from typing import Any, Callable, Dict, List, Optional, Type
import attr
import requests
from cachetools import TTLCache, cached
from cachetools.keys import hashkey
from rio_tiler.io import STACReader
from cogeo_mosaic.backends.base import BaseBackend
from cogeo... |
import os
import pickle
import operator
import argparse
import numpy as np
from scipy.stats import entropy
def load_pickle_overall(pickle_path):
""""
pickle_path: pkl file path, which contains label and coordinates
"""
size = 13
row, col = 512, 640
with open(pickle_path, 'rb') as handle:
... |
from future.utils import PY3
import os
import os.path as op
import platform
import re
import logging
import xml.etree.ElementTree
from arcana.environment.requirement import ( # pylint: disable=unused-import
Version, CliRequirement, MatlabPackageRequirement,
PythonPackageRequirement, matlab_req)
from arcana.uti... |
"""
Functions related to BrokenModel.
edited: 6 August 2020.
# Changelog:
17 June 2020: Changed the imports, now importing tensorflow directly.
6 August 2020: Adapted remoteModel to run in TFv2.
28 September 2020: added code to rename cloud model and delete unconnected input layers.
5 February 2021: c... |
import numpy as np
'''Scenes - simple smooth transitions of a variable for making better animations'''
class Act:
def __init__(self, start, end, dt=1, met="lin", c=2.):
'Act - a variable starting at value start, changing to value end, after time dt, interpolating with method met'
self.start = start... |
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.shortcuts import render
from django.urls import reverse
from django.urls import reverse_lazy
from django.utils.translation import ugettext_lazy as _
from django.views.generic import CreateView
from django.views.gener... |
import json
import mimetypes
import traceback
from datetime import timedelta
import mock
from freezegun import freeze_time
from openprocurement.api.tests.base import BaseTestApp
from openprocurement.api.utils import get_now
from six import text_type
from uuid import UUID
from hashlib import md5
from webtest import f... |
import json
import pytest
import core.event
import core.config
import core.output
import core.module
class SampleModule(core.module.Module):
pass
@pytest.fixture(autouse=True)
def clear_events():
core.event.clear()
@pytest.fixture
def i3():
return core.output.i3()
@pytest.fixture
def module_a(mocke... |
'''
Testing of the BSE Curation CLI interface
'''
import os
import sys
import subprocess
import pytest
import shutil
from basis_set_exchange import fileio, curate
from .common_testvars import cli_dir, fake_data_dir, data_dir, curate_test_data_dir
def _test_curatecli_cmd(cmd):
# NOTE: We do not enforce any encod... |
import django
django.setup()
from core.bo.sistemas import get_estrutura_sistemas, get_estrutura_sistemas_dct
from core.models import EstruturaCurricular, OrganizacaoCurricular, ComponenteCurricular, Curso
def main():
print("Criando Organizações Modificadas - SuggestClasses ...!")
adicionar_componentes_pedagog... |
"""solution"""
INF: int = 10000
def get_line_belong(st_i, st_j, nexto):
"""Get line belong.
Get the name of line that connect station i and station j.
Args:
st_i: str, station name.
st_j: str, station name.
nexto: map, adjacency table of subway system.
Return:
the l... |
import pytest
import numpy as np
from orix.base import DimensionError, Object3d, check
@pytest.mark.xfail(strict=True, reason=ValueError)
def test_check_failing():
check(np.asarray([1, 1, 1, 1]), Object3d)
@pytest.fixture(
params=[
(2,),
(2, 2),
(4, 2),
(2, 3, 2),
(1... |
#*----------------------------------------------------------------------------*
#* Copyright (C) 2020 ETH Zurich, Switzerland *
#* SPDX-License-Identifier: Apache-2.0 *
#* *
... |
#!/usr/bin/env python3
import pytest
from itertools import cycle
DAY='13'
VERT='|'
HORIZ='-'
DIAGDU='/'
DIAGUD='\\'
INTER='+'
CARTUP='^'
CARTDOWN='v'
CARTLEFT='<'
CARTRIGHT='>'
CARTS =(CARTUP, CARTDOWN, CARTLEFT, CARTRIGHT)
CARTSL='L'
CARTSS='S'
CARTSR='R'
CARTSEQUENCE=(CARTSL, CARTSS, CARTSR)
CRASH='X'
class Cart()... |
from . import BatchSampler
from paddorch.utils.data import IterableDataset
import paddorch as torch
import math
import numpy as np
class WeightedRandomSampler(BatchSampler):
def __init__(self, weights,batch_size, num_samples=None, replacement=True):
if num_samples is None:
num_samples=len(weigh... |
import bottle
from ast import literal_eval as make_tuple
from model import *
SKRIVNOST = 'zelva'
DATOTETKA_S_STANJEM = 'stanje.json'
DATOTOEKA_S_SUDOKUJI = 'sudoku_in_resitve.txt'
sudoku = Sudoku(DATOTETKA_S_STANJEM, DATOTOEKA_S_SUDOKUJI)
@bottle.get('/')
def index():
return bottle.template('index.tpl')
@bottle... |
import sys
import aws
from aws import stderr, client
def ensure_allows(name, allows, preview):
if allows:
stderr('\nensure allows:')
for allow in allows:
action, resource = allow.split()
if preview:
stderr(' preview:', allow)
else:
... |
import argparse
import json
import os
import statistics
import numpy as np
from math import ceil, isinf, isnan
from Progress import progress
def gini(data):
x = [val[0] + val[1] for val in data]
sorted_x = np.sort(np.array(x))
n = len(x)
cumx = np.cumsum(sorted_x, dtype=float)
... |
"""Autocorrect, GUI
This module contains all the GUI components for the autocorrect/autocomplete text editor.
Copyright (c) 2021 <NAME> and <NAME>.
Licensed under the MIT License. See LICENSE in the project root for license information.
"""
import tkinter as tk
from backend import Backend
from bktree import make_bkt... |
import tensorflow as tf
from tensorflow_probability.python.distributions import Chi2
import matplotlib.pyplot as plt
class GAIA(tf.keras.Model):
"""a basic gaia class for tensorflow
Extends:
tf.keras.Model
"""
def __init__(self, d_prop_xg=1.0, g_prop_interp=1.0, **kwargs):
super(GAIA... |
'''
https://github.com/craston/MARS/blob/master/README.md
For HMDB51 and UCF101 datasets:
Code extracts frames from video at a rate of 25fps and scaling the
larger dimension of the frame is scaled to 256 pixels.
After extraction of all frames write a "done" file to signify proper completion
of frame extraction.
Usa... |
"""
Tests the plugin UI
Usage: python selenium_test.py <chrome driver path>
Assumes a Chrome driver is present in the sys path
"""
import boto3
import os
import time
import sys
import threading
import moto
import unittest
from notebook.notebookapp import NotebookApp
from tornado.ioloop import IOLoop
from unittest.mo... |
import torch as th
from secrets import SystemRandom
from secrets import randbits
from torch.distributions import Normal
from syft.frameworks.torch.he.fv.ciphertext import CipherText
from syft.frameworks.torch.he.fv.util.operations import poly_add_mod
from syft.frameworks.torch.he.fv.util.operations import poly_mul_mod... |
import fragmenter
import json
import cmiles
from openeye import oechem, oequacpac
import os
import warnings
def collect_wbos(molecule):
wbos = {}
for bond in molecule.GetBonds():
bond_key = (bond.GetBgn().GetMapIdx(), bond.GetEnd().GetMapIdx())
if 'WibergBondOrder' not in bond.GetData():
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.