text stringlengths 3.07k 12.6k |
|---|
#!/usr/bin/env python3
"""
Author : <NAME> <<EMAIL>>
Date : 2018-11-24
Purpose: K-Nearest Neighbors
"""
import argparse
import matplotlib
import os
#matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import numpy as np
import sys
from collections import Counter
from matplotlib.colors import ListedColormap
from ... |
import argparse
import os
import pickle
import boto3
from pyspark.sql import SparkSession
from pyspark.sql.functions import col, size, row_number, expr, array_join
from pyspark.sql.types import StructType, StructField, StringType
from pyspark.sql.window import Window
def list_s3_by_prefix(bucket, prefix, filter_func... |
# 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 use ... |
import argparse
import difflib
import os
import re
import sys
from typing import Callable, ClassVar, List, Tuple, Type, Union, cast
import libcst as cst
from libcst import MetadataDependent
from libcst.metadata import PositionProvider
class CodeInspector(MetadataDependent):
METADATA_DEPENDENCIES = (PositionProvi... |
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import numpy as np
from preshed.counter import PreshCounter
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA, Tru... |
from typing import Text
from collections import OrderedDict as odict
import traceback
import logging
import json
import ldap
from django.conf import settings
def json_default(obj): # nocv
error_obj = TypeError(f"{type(obj)} is not JSON serializable")
try:
if isinstance(obj, bytes):
retur... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 11 17:26:59 2019
@author: hxs1943
"""
import networkx as nx
import numpy as np
import sklearn.metrics
import json
def transitivity(b1, u1, b2, u2, oper_type='tp-min'):
if oper_type == 'tp-min':
if b1==b2:
u = max(u1, u2)
... |
import os
import shutil
import urllib.request as request
import zipfile
import numpy as np
import pandas as pd
import requests
from lxml import etree
import csv
from tqdm import tqdm
# Data list, you can add your data that just follow the same typing forms: name: url
data_list = {
'Activity recognition exp': 'htt... |
import json
import math
import os
import tensorflow as tf
from tensorflow.keras.callbacks import (
CSVLogger,
LearningRateScheduler,
ModelCheckpoint,
)
# TODO: switch to schedules version once it is moved out of nightly
from tensorflow.keras.experimental import CosineDecay
from tensorflow.keras.optimize... |
from lbrynet.core.StreamDescriptor import BlobStreamDescriptorWriter
from lbrynet.lbrylive.StreamDescriptor import get_sd_info
from lbrynet.cryptstream.CryptStreamCreator import CryptStreamCreator
from lbrynet.lbrylive.LiveBlob import LiveStreamBlobMaker
from lbrynet.core.cryptoutils import get_lbry_hash_obj, get_pub_k... |
from __future__ import print_function, absolute_import
import os.path as osp
import random
import numpy as np
from collections import namedtuple
from ..utils.data import Dataset
from ..utils.osutils import mkdir_if_missing
from ..utils.serialization import write_json, read_mat
from ..utils.dist_utils import synchroniz... |
"""
Copyright 2017 <NAME>
interpreter.py contains the interpreter class and its associated methods
"""
from soa import token, errors
import time
def get_register_value(register_tree):
"get_int_value uses a tree to find the value of the register"
register_token = register_tree["Tok"]
register_value = regi... |
from pymongo import MongoClient
from datetime import datetime
class MongoConfig:
HOME = 'YTML'
HOST = 'localhost'
PORT = 27017
SUPER = 'superroot'
USER = 'root'
PWD = '<PASSWORD>'
def mongo_connect(name: str,):
client = MongoClient(MongoConfig.HOST, MongoConfig.PORT)
if name.upper() ... |
from __future__ import division, print_function
from keras.layers import Input, Conv2D, Conv2DTranspose, Dense
from keras.layers import MaxPooling2D, Cropping2D, concatenate, UpSampling2D
from keras.layers import Lambda, Activation, BatchNormalization, Dropout
from keras.models import Model
from keras import backend a... |
# (C) Datadog, Inc. 2018-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
from copy import deepcopy
import mock
import pytest
from six import iteritems
from datadog_checks.base import AgentCheck
from datadog_checks.mesos_slave import MesosSlave
from .common import MESOS_SLAVE... |
# -*- coding: utf-8 -*-
'''
ROS module for Tobii Pro Glasses
Copyright 2017 Carnegie Mellon University. All Rights Reserved.
NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPR... |
"""Helper classes and wrappers to access Google Cloud.
Google Cloud API is encapsulated with these wrappers, so it's easier to
test the code with help of fake (declared in testing/fake_cloud_client.py).
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
i... |
import typing
from typing import Any, Dict, Iterable, List, NewType, Optional, Union
from hpc.autoscale import hpctypes as ht
from hpc.autoscale.codeanalysis import hpcwrapclass
from hpc.autoscale.node import nodemanager
from hpc.autoscale.node.constraints import get_constraints
from hpc.autoscale.results import Alloc... |
import json
from itertools import product
import requests
from utility.constants import (
ENUM,
TYPE,
DESCRIPTION,
DEFAULT,
MINIMUM,
MAXIMUM,
PROPERTIES,
SCATTER,
BAR,
HEATMAP,
CONTOUR,
BOX,
VIOLIN,
HISTOGRAM,
HISTOGRAM2D,
SCATTER3D,
MESH3D,
LAYO... |
import os
import sys
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.applications import VGG19
import time
from functools import partial
import numpy as np
import PIL
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # to suppress AVX2 warning
sys.path.append('../../..')
from ml import... |
#!/usr/bin/env python
import curses, time, calendar
import global_mod as g
from getstr import UserInput
import footer
def draw_window(state, window, rpc_queue=None):
window.clear()
window.refresh()
win_header = curses.newwin(5, g.x, 0, 0)
if 'browse_height' in state['blocks']:
height = str(st... |
"""Benchmark the accuracy of a set of rotomaps vs a reference."""
import numpy
import mel.cmd.error
import mel.lib.common
import mel.lib.image
import mel.rotomap.detectmoles
import mel.rotomap.mask
import mel.rotomap.moles
def setup_parser(parser):
parser.add_argument(
"FROM_FRAMES",
type=mel.r... |
"""
Functions to score specified data using specified ML models
"""
import sys
import pickle
import os
import numpy
import logging
#Append sys to base path to import the following modules
base_path = os.path.dirname(__file__)
sys.path.append(base_path)
#Depend on base path to be imported
from essay_set import EssayS... |
import os
import numpy as np
from tqdm import tqdm
import ersa_utils
import processBlock
def make_grid(tile_size, patch_size, overlap):
"""
Extract patches at fixed locations. Output coordinates for Y,X as a list (not two lists)
:param tile_size: size of the tile (input image)
:param patch_size: size ... |
import gdspy
import pyclipper
import numpy as np
import spira.all as spira
from copy import copy, deepcopy
from numpy.linalg import norm
from spira.yevon import constants
from spira.core.parameters.variables import *
from spira.yevon.geometry.coord import CoordParameter
from spira.core.parameters.descriptor import Fun... |
import numpy as np
import pandas as pd
from pandas.api.types import is_list_like
import staircase as sc
from staircase.core.ops.masking import clip
from staircase.core.stats.statistic import _get_stairs_method
from staircase.docstrings import slicing as docstrings
from staircase.util._decorators import Appender
clas... |
from __future__ import annotations
import functools
import inspect
import operator
from typing import (
Awaitable,
Callable,
Generic,
Optional,
Type,
TypeVar,
Union,
cast,
)
from telethon.events.common import EventBuilder
from _garnet.concurrency import to_thread
ET = TypeVar("ET")
F... |
# MIT License
#
# Copyright (c) 2018 Haoxintong
#
# 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, p... |
import os
from collections import OrderedDict
from typing import Dict, List, Optional
import ConfigSpace.hyperparameters as CSH
from ConfigSpace.configuration_space import ConfigurationSpace
import numpy as np
from autoPyTorch.datasets.base_dataset import BaseDatasetPropertiesType
from autoPyTorch.pipeline.component... |
from __future__ import absolute_import
import datetime
import logging
import pytz
from padre import channel as c
from padre import handler
from padre import matchers
from padre import slack_utils as su
from padre import utils
LOG = logging.getLogger(__name__)
UNKNOWN_STATUS = 255
UNKNOWN_EVENT_REGION = 'openstack-p... |
import logging
from typing import List, Optional, Set, Union, Tuple
import lss.util
from lss import SubstrMatch, Item, FileItem, SequenceStrParts
from lss.dataclass.base import Fileobj
from lss.error import SequenceError
log = logging.getLogger(__name__)
LazyItem = Union[str, Item]
def find_matching_frame_sub... |
import sys
sys.path.append('..')
from torch.utils.data import Dataset
import torch
import numpy as np
from rcnn.utils import hdf5_reader
from skimage.transform import resize
import cv2
from scipy.ndimage.interpolation import map_coordinates
from scipy.ndimage.filters import gaussian_filter
import random
class Trunc_a... |
"""
Tests for the spotify_api.py file
"""
from spotify_web_api.spotify_api import Spotify
import os
import pytest
@pytest.fixture
def spy():
return Spotify()
@pytest.fixture
def artists():
return ["<NAME>", "converge"]
@pytest.fixture
def artist_ids():
return ["3uHCTHxtg3IVAvhyrYsZvI", "7kHzfxMLtVHHb523... |
import json
import time
import re
import requests
from lxml import html
from pprint import pprint
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
from .worker import app
from celery.utils.log import get_task_logger
logger = get... |
# Copyright (c) 2016-2017, <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 of conditions and the foll... |
import requests
from .config import get_access_token_from_config
DEFAULT_API_BASE = "https://www.yuque.com/api/v2"
def _filter_none(d):
return {k: v for k, v in d.items() if v is not None}
class MethodGetter(object):
def __init__(self, inst, prefix):
self.inst = inst
self.prefix = prefix
... |
#!/usr/bin/env python3
import numpy as np
import struct
from collections import namedtuple
__all__ = ["DSOX3000", "decode_dsox3000_data"]
class DSOX3000(object):
"""
Rigol DL3000 command wrapper.
"""
def __init__(self, inst):
"""
Initialize the DL3000 wrapper with a specific PyVISA res... |
from tulius.forum.threads import mutations
from tulius.forum.threads import models
from tulius.forum.comments import signals
from tulius.forum.rights import mutations as right_mutations
class ThreadCommentAdd(mutations.Mutation):
with_parent = True
comment = None
def __init__(self, thread, comment, **kwa... |
from __future__ import print_function
import numpy as np
def read_speed(logfile):
print('filename: ', logfile)
try:
f = open(logfile, 'r')
except Exception as e:
print('file exception: ', e)
return 0, 0
speeds = []
num_of_layers = 0
for line in f.readlines():
if... |
# -*- coding: UTF-8 -*-
from configparser import ConfigParser
from elasticsearch import Elasticsearch
from elasticsearch import helpers
from src.logger import Logger
import MySQLdb
import datetime
import json
config = ConfigParser(allow_no_value=True)
config.read("config/prod.conf")
build_index_log = Logger(config.g... |
# Copyright (c) 2018 The Pooch Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
#
# This code is part of the Fatiando a Terra project (https://www.fatiando.org)
#
"""
Test the utility functions.
"""
import os
import shutil
import time
from pathlib import Pat... |
# -*- coding: utf-8 -*-
#
# Copyright 2012-2015 Spotify AB
# Modifications copyright (C) 2018 databand.ai
#
# 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/LI... |
import os.path
import requests_mock
from pyfakefs.fake_filesystem_unittest import TestCase
from abejacli.config import ABEJA_API_URL, FILE_READ_CHUNK_SIZE
from abejacli.datalake.process_file_job import (
FINISH_REPORT,
INITIALIZE_REPORT,
PROGRESS_REPORT,
RAISE_ERROR
)
from abejacli.datalake.upload_job... |
from airflow import DAG
from airflow.models import Variable
from airflow import AirflowException
from airflow.operators.python import PythonOperator
from airflow.operators.python_operator import BranchPythonOperator
from airflow.operators.dummy_operator import DummyOperator
from airflow.hooks.postgres_hook import Postg... |
'''
https://github.com/larchen/clevr-vqa/blob/master/bounding_box.py
'''
'''
Copyright 2017 <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... |
import abc
import attr
import numpy as np
import torch
from torch import nn
from naturalnets.brains.i_brain import IBrain, IBrainCfg
@attr.s(slots=True, auto_attribs=True, frozen=True, kw_only=True)
class IPytorchBrainCfg(IBrainCfg):
num_layers: int
hidden_size: int
use_bias: bool = False
class IPytorc... |
#!/usr/bin/python
import os
import json
from deriva.core import PollingErmrestCatalog, init_logging
import subprocess
import logging
import socket
import sys
import traceback
import argparse
from .worker import DerivaImagingWorker
from .client import get_configuration
# Loglevel dictionary
__LOGLEVEL = {
'critic... |
#*****************************************************************************
#
# Copyright (c) 2000 - 2014, Lawrence Livermore National Security, LLC
# Produced at the Lawrence Livermore National Laboratory
# LLNL-CODE-442911
# All rights reserved.
#
# This file is part of VisIt. For details, see https://visit.llnl... |
from django.db import models
from django.core.validators import validate_email
def profpicpath(instance, filename):
return '/'.join([instance.user.displayname, 'images/profile', filename])
# Create your models here.
class User(models.Model):
firstname = models.CharField(max_length=100)
middlename = mode... |
#########################################################################
# session module written by limodou(<EMAIL>) at 2009/08/25
# this module is inspired by beaker package
#
# storage class will ensure the sync when load and save a session from
# and to the storage.
###############################################... |
# -*- coding: utf-8 -*-
# Copyright 2018 <NAME> <<EMAIL>>
#
# 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 of conditions and th... |
import uuid
from secrets import token_urlsafe
from django.conf import settings
from django.db import models
from django.utils.translation import gettext_lazy as _
from djchoices import DjangoChoices, ChoiceItem
from model_utils.managers import SoftDeletableManagerMixin, SoftDeletableQuerySetMixin
from model_utils.mode... |
import numpy as np
from scipy.spatial.distance import cdist
from plaster.tools.image import imops
from plaster.tools.image.coord import YX, HW
from plaster.tools.schema import check
from plaster.tools.utils.stats import half_nanstd
from plaster.tools.zlog.zlog import spy
def pixel_peak_find_one_im(im, approx_psf):
... |
import logging
import random
# TODO add if inline mode is needed
# from uuid import uuid4
# from telegram import InlineQueryResultArticle, InputTextMessageContent, ParseMode
# from telegram.utils.helpers import escape_markdown
from model import Definition, Channel, User
from base import transactional, only_admin
from ... |
#!/usr/bin/env python3
import os
import sys
import warnings
import argparse
import numpy as np
from tqdm.auto import trange
from tqdm.std import tqdm
warnings.filterwarnings("ignore", message=r"Passing", category=FutureWarning)
import keras
from mivp_agent.manager import MissionManager
from mivp_agent.util.display im... |
"""Test the CityJSON class
"""
import pytest
import os.path
from click.testing import CliRunner
import copy
from cjio import cityjson, models
from cjio import cjio
from math import isclose
@pytest.fixture(scope='module')
def cm_zur_subset(zurich_subset):
zurich_subset.cityobjects = dict()
for co_id, co in zu... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 26 11:13:04 2016
@author: pavel
"""
import os
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GObject
import mconfig as conf
from sys import argv
def get_channels_list(channels_file):
channels = []
with open(ch... |
"""Lasagne layer implementing a variant of highway and residual networks.
"""
import numpy as np
import theano
import theano.tensor as T
import lasagne as nn
from deep_learning_layers import *
class MultiplicativeGatingLayer(nn.layers.MergeLayer):
"""
Generic layer that combines its 3 inputs t, h1,... |
#!/usr/bin/env python3
from Crypto.Cipher import AES
from Crypto.Hash import MD5
import logging
import binascii
import json
import struct
import os
import glob
from datetime import datetime
from optparse import OptionParser
class PBEWITHMD5AND128BITAES_CBC_OPENSSL:
def __init__(self, password, salt, iterations):
# ... |
from pathlib import Path
import string
import networkx as nx
import numpy as np
import ast
from tqdm import tqdm
from dbca.datasets.relational import RelationalSample
from dbca.sample_set import SampleSet
from dbca.storage import SampleStore
CONST_SEED = 1234
class GeneratedStory:
"""
Helper class to repres... |
import datetime
from typing import List, NoReturn
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from TrainInfoProcess import SEPERATOR, originStations
def generateTime2FlowDf(database: pd.DataFrame) -> pd.DataFrame:
"""生成购票时间与客流量相关的DataFrame
Args:
datab... |
import logging
import sys
from functools import partial
from pathlib import Path
from dateutil.parser import parse
import pytest
import trio
from pyskyq import EPG, XMLTVListing, Programme
from .http_server import http_server
from .mock_constants import (SERVICE_DETAIL_1, SERVICE_DETAIL_2,
... |
""" Simulate the stochastic evolution of a tumor """
from matplotlib import pyplot as plt
from matplotlib import animation
from read import read_into_dict
from tumor import Tumor
def animate_tumor_growth_base(initialCondition, parameterValues, number_of_frames, random_seed=None):
"""
Generate a matplotlib a... |
import torch
import random
import logging
import warnings
import numpy as np
import torch.nn.functional as F
formatter = logging.Formatter('[%(asctime)s] [%(name)s] [%(levelname)s] %(message)s')
warnings.filterwarnings("ignore", "(Possibly )?corrupt EXIF data", UserWarning)
def euclidean_d(X, Y=None, squared=True):
... |
# Copyright 2016 Datera
# 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 applic... |
# -*- coding: utf-8 -*-
"""
Manage Linux kernel packages on YUM-based systems
"""
from __future__ import absolute_import, print_function, unicode_literals
import functools
import logging
try:
# Import Salt libs
from salt.ext import six
from salt.utils.versions import LooseVersion as _LooseVersion
from... |
# This file is a part of ninfs.
#
# Copyright (c) 2017-2021 <NAME>
# This file is licensed under The MIT License (MIT).
# You can find the full license text in LICENSE.md in the root of this project.
"""
Mounts 3DSX Homebrew files, creating a virtual filesystem with the 3DSX's RomFS and SMDH.
"""
import logging
from ... |
import horovod.torch as hvd
import torch
from PIL import Image
from torch.utils.data import DataLoader
from torchvision.transforms import transforms
from prefetch_generator import BackgroundGenerator
from flambeau.engine import BaseEngine
from . import transforms as custom_transforms
class DataLoaderX(torch.utils.da... |
import requests
from pprint import pprint
url = 'http://localhost:8000'
def start(user, problem, count):
uri = url + '/start' + '/' + user + '/' + str(problem) + '/' + str(count)
print('start', user, problem, count, uri)
return requests.post(uri).json()
def oncalls(token):
uri = url + '/oncalls'
... |
#!/usr/bin/python3 -m unittest
#
# basic numpy ndarray
#
import unittest
import pymm
import numpy as np
import math
import torch
def colored(r, g, b, text):
return "\033[38;2;{};{};{}m{} \033[38;2;255;255;255m".format(r, g, b, text)
def print_error(*args):
print(colored(255,0,0,*args))
def log(*args):
pr... |
import tensorflow as tf
from sklearn.model_selection import train_test_split
from contextlib import redirect_stdout
import numpy as np
import pandas as pd
import watermodel
import datetime
import data_function as d_f
import create_data as cd
import logging
import time
import os
LR_SCHEDULE = [
# (epoch to start, ... |
import torch
import torch.fx
"""
In this example we are going do define a library of
"composite" operations. Composite operations are those
that are defined as callable functions that are composed
of several other operations in their implementation.
Composite operations allow you to choose at what level
of abstraction... |
#-----------------------------------
# Name : hdbscan.py
# Author : E.Taskesen
# Contact : <EMAIL>
# Licence : MIT
# Respect the autor and leave this here
#-----------------------------------------------
from sklearn import metrics
import numpy as np
from sklearn.preprocessing import StandardScaler... |
# -*- coding: utf-8 -*-
"""
All the functions in one place.
"""
import matplotlib.pyplot as plot
import matplotlib.gridspec as gridspec
import pickle
from config import *
from numpy import log, abs
def overview_plot(plotrange):
array=pickle.load(open(PICKLE_FILENAME,"rb" ))
plot.xlim(plotrange)
plot.axhl... |
# -*- coding: utf-8 -*-
# Copyright (c) 2013-2014 <NAME>
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
import logging
import sys
from .error_holder i... |
import logging
import numpy as np
import plotly
import plotly.graph_objs as pgo
import tqdm
from gamegym.algorithms import OutcomeMCCFR, exploitability, BestResponse
from gamegym.contrib.strategy_trace import StrategyTrace
from gamegym.games import DicePoker, Goofspiel, MatchingPennies, RockPaperScissors
from gamegym... |
# Copyright 2021 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at http://aws.amazon.com/apache2.0/
# or in the "LICENSE.txt" file accompa... |
# -*- coding: utf-8 -*-
"""
Flask Tests
~~~~~~~~~~~
Tests Flask itself. The majority of Flask is already tested
as part of Werkzeug.
:copyright: (c) 2010 by <NAME>.
:license: BSD, see LICENSE for more details.
"""
from __future__ import with_statement
import flask
import unittest
import tempf... |
"""
Unit tests of functions within :mod:`weaver.processes.wps_package`.
.. seealso::
- :mod:`tests.functional.wps_package`.
"""
import contextlib
import os
import shutil
import sys
import tempfile
import mock
import pytest
from pywps.app import WPSRequest
from weaver.datatype import Process
from weaver.exception... |
"""
Day 9 Solutions
"""
import re
# Lexing problem! Change state based on important characters.
# Start in group-parsing mode:
# See { - increment open-counter; continue group-parsing.
# See < - enter garbage-parsing mode
# See } - decrement open-counter; if counter = 0 exit, else continue group-parsing
# gar... |
# -*- test-case-name: txweb2.test.test_util -*-
##
# Copyright (c) 2005-2017 Apple Inc. All rights reserved.
#
# 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 w... |
import os
import pandas as pd
from pandas.core.frame import DataFrame
import plotly.graph_objects as go
import plotly.express as px
from plotly.subplots import make_subplots
from src.tree.node import NodeIdentifier
from src.graph_data import (
get_categorical_dict,
is_categorical_data,
rename_category_entr... |
import asyncio
from pygears import GearDone
from pygears.conf import PluginBase, registry, safe_bind
from pygears.core.port import InPort, OutPort
from pygears.core.sim_event import SimEvent
from pygears.typing.base import TypingMeta
def operator_func_from_namespace(cls, name):
def wrapper(self, *args, **kwargs)... |
""" Utility nn components, in particular handling activations, initializations, and normalization layers """
from functools import partial
import math
import torch
import torch.nn as nn
from einops import rearrange
from opt_einsum import contract
from src.models.nn.exprnn.orthogonal import modrelu
def Activation(act... |
import inspect
from flask_restless.helpers import get_related_association_proxy_model, primary_key_name
from sqlalchemy.ext.associationproxy import AssociationProxy
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.inspection import inspect as sqla_inspect
from sqlalchemy.orm.properties import ColumnPr... |
from argparse import Namespace
import torch
from sklearn import metrics
from sklearn.feature_extraction.text import TfidfVectorizer
import json
import math
import random
import time
train_tokens_file = './data/train_tokens.json'
train_topics_file = './data/train_topics.json'
test_tokens_file = './data/test_tokens.json... |
import time
import numpy
from w1thermsensor import W1ThermSensor
from chip_systems import ProjectSystem
from chip_systems import ADCS
import RPi.GPIO as GPIO
import spidev
import numpy
class AquaPiTemperature(ProjectSystem.ProjectSystem):
# Connect to Sensor
# Assuming a single sensor is connected
# Power is 3.3... |
import numpy as np
from flask import Flask, request, jsonify, render_template,url_for,abort,flash,redirect,send_file, send_from_directory
from werkzeug import secure_filename
import pickle
import pandas as pd
import os
from all import*
import xlrd
import csv
import webbrowser
from threading import Timer
#from waitress ... |
import argparse
import asyncio
import logging
import sys
from . import CommandCodes, CommandInvalidAtThisTime, SourceCodes, IncomingAudioFormat, IncomingAudioConfig, DecodeMode2CH, DecodeModeMCH, RC5Codes, CommandNotRecognised, _LOGGER, ResponsePacket, AnswerCodes
from .client import Client, ClientContext
from .server... |
import argparse
import os
from tqdm import tqdm
import json
import uuid
from dateutil.parser import isoparse
import re
from stix2 import MemoryStore, Filter
class CollectionToIndex:
@staticmethod
def generate_index(name, description, root_url, files=None, folders=None, sets=None):
"""generate a collec... |
import numpy as np
import gym
from collections import OrderedDict
import logging
from mprl.rl.envs.stratego.stratego_multiagent_env import STRATEGO_ENV
from mprl.utility_services.cloud_storage import upload_file, maybe_download_object, get_default_path_on_disk_for_minio_key
from mprl.utils import datetime_str
import os... |
"""Synthetic scores."""
import os
import tensorflow as tf
from mpi4py import MPI
from lm_human_preferences.language import trained_models, model
from lm_human_preferences.utils import core as utils
from lm_human_preferences.utils.core import Schema
# TODO: combine this with TrainedRewardModel
class RewardModelTrain... |
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... |
from __future__ import print_function
import urllib.parse
import subprocess
import os.path
import re
import io
import PyPDF2
import json
AUTH_TAG = "PPAU_AUTH_TAG"
PRINT_TAG = "PPAU_PRINT_TAG"
SOURCE_DIR = "Artwork"
auth_file = "auth_tag.txt"
manifest_file = "MANIFEST.json"
seddy = "/bin/sed"
inky = "/usr/bin/inkscap... |
import copy
from collections import defaultdict
from itertools import chain
from torch.nn.utils import clip_grad
from ..dist_utils import allreduce_grads
from ..fp16_utils import LossScaler, wrap_fp16_model
from .hook import HOOKS, Hook
@HOOKS.register_module()
class OptimizerHook(Hook):
def __init__(self, grad... |
import pytest
from urllib.parse import urlparse
from pilot.client import PilotClient
from pilot.exc import PilotInvalidProject
from tests.unit.mocks import MOCK_PROJECTS, MULTI_FILE_DIR
def test_get_index(mock_projects):
pc = PilotClient()
pc.project.current = 'foo-project'
assert pc.get_index() == 'foo-... |
from flask import render_template, redirect, url_for, abort, flash, request
from flask import current_app, Blueprint
from sqlalchemy import asc, desc
from sqlalchemy.orm import aliased
from flask.ext.paginate import Pagination
from .forms import CreateMonkeyForm, EditMonkeyForm
from .models import db, Monkey, friendshi... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division
import os
import torch
import numpy as np
import glob
from sklearn.metrics.cluster import (contingency_matrix,
normalized_mutual_info_score)
from sklearn.metrics import (precision_score, recall_score)
_... |
from __future__ import print_function
# Import standard modules
import os
import numpy as np
from scipy import ndimage
from scipy import misc
# Import astronomical modules
from astropy.io import fits
# This script rotates a FITS image around the center of the frame over an arbitrary angle.
# It updates the header ac... |
#!/usr/bin/env python3
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
import pathlib
import json
import urllib.request
import re
import subprocess
import sys
class L... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.