text stringlengths 3.07k 12.6k |
|---|
from __future__ import absolute_import, division, print_function, unicode_literals
from base64 import b64encode
import json
from aspen.http.request import Request
from aspen.http.response import Response
from environment import Environment
from gratipay import wireup
from gratipay.security import csrf
from gratipay.... |
from urllib.parse import urlparse
from google.cloud import storage
from core_data_modules.logging import Logger
from requests import ConnectionError, Timeout
import socket
log = Logger(__name__)
def _blob_at_url(storage_client, blob_url):
parsed_blob_url = urlparse(blob_url)
assert parsed_blob_url.scheme ==... |
import numpy as np
import pandas as pd
import gemmi
from reciprocalspaceship import DataSet
from reciprocalspaceship.dtypes.base import MTZDtype
def from_gemmi(gemmi_mtz):
"""
Construct DataSet from gemmi.Mtz object
If the gemmi.Mtz object contains an M/ISYM column and contains duplicated
Miller i... |
# ########### ###########
# Author: <NAME>
# Affiliation: Zhejiang University
# Copyright: 2018
# ########### ###########
from __future__ import print_function
from __future__ import division
import numpy as np
def nested_to_vector(list_of_weights_list):
list_of_shape_list=[]
weights_vec_list=[]
... |
# Copyright 2019 DeepMind Technologies Ltd. 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 appl... |
#!/usr/bin/env python3
# Adds a (retextured) item into the game. Will need to be modified slightly
# to add items other than armor. Remember to use dumpxdt.py (and make it read
# the generated _new TableData!) so your server allows you to spawn the
# new items. Will also need to be modified to work with girls' or unis... |
import copy
import numpy as np
import sys
import torch
from graph_dataset import DataSet
from sklearn.metrics import accuracy_score as acc, precision_score as pr, recall_score as rc, f1_score as f1
from tqdm import tqdm
from tsne import plot_embedding
from models import MetricLearningModel
def train(model, dataset,... |
from typing import List, Iterable, Optional
import os.path
import glob
import re
import tempfile
import tarfile
import zipfile
import numpy as np
from datetime import datetime, timedelta
from netCDF4 import Dataset, MFDataset, Variable
data_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)), "data")
def r... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import abc
import re
from typing import Dict, Optional, Type
import attr
import numpy as np
import quaternion
import h... |
import os
import re
from datetime import date, timedelta
from pathlib import Path
from urllib import request
from zipfile import ZipFile
import pandas as pd
import requests
from urlpath import URL
import airportdata
import flightdata
import weatherparser
def iter_days(start_date: date, end_date: date):
cur = st... |
# TensorFlow and tf.keras
import tensorflow as tf
# Helper libraries
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import random
import pathlib
# 配置
AUTOTUNE = tf.data.experimental.AUTOTUNE
# 32: 0.514
# 64: 0.532 (1*OOM)
# 128: 0.5228 (2*OOM)
BATCH_SIZE = 32
# (96, 128, 160, 192, 224)
# 1... |
import images
import special_obstacles
import objects, pygame
from rubato import Math, Vector
shownChunks = []
map=[
[0,0,1,1,1,1,6,6,6,6,6,6,6,6,6],
[0,0,1,1,1,1,6,6,6,6,6,6,6,6,6],
[1,1,1,1,1,1,6,6,6,6,6,6,6,6,6],
[4,1,1,1,1,1,1,1,3,3,3,3,3,3,3],
[4,4,4,1,1,9,9,9,3,3,3,3,3,2,3],
[4,4,4,4,4,9,... |
#!/usr/bin/env python
# coding: utf-8
# In[22]:
import pandas as pd
import os
import numpy
import MySQLdb
import omdtfn as odt
#conn= MySQLdb.connect("localhost","root","admin","omdb")
#df_mysql = pd.read_sql("select * from sitedb",conn)
omdb = os.getcwd() + "\\" + "OMDB.csv"
single = os.getcwd() + "\\" + "SingleCl... |
from copy import deepcopy
from collections import deque
import cv2
cv2.ocl.setUseOpenCL(False)
import gym
from mushroom.environments import Environment, MDPInfo
from mushroom.utils.spaces import *
class MaxAndSkip(gym.Wrapper):
def __init__(self, env, skip, max_pooling=True):
gym.Wrapper.__init__(self, ... |
import itertools
import json
from xml.sax.saxutils import quoteattr as quo
import lit.Test
def by_suite_and_test_path(test):
# Suite names are not necessarily unique. Include object identity in sort
# key to avoid mixing tests of different suites.
return (test.suite.name, id(test.suite), test.path_in_s... |
from PyQt5.QtWidgets import (QFrame, QHBoxLayout, QVBoxLayout,
QGroupBox, QPushButton, QComboBox, QStackedWidget,
QFormLayout, QLabel, QSlider, QDoubleSpinBox, QFileDialog)
from PyQt5.QtCore import pyqtSignal, pyqtSlot
from os.path import join
from simulator im... |
"""Netlist"""
import io
import pathlib
import re
from circuits import (
Resistor,
Capacitor,
Inductor,
VoltageSource,
Circuit,
Opamp,
ResistorNetwork,
)
from circuits.common import singleton
SUFFIXES = {
"f": "-15",
"p": "-12",
"n": "-9",
"u": "-6",
"m": "-3",
"k": "... |
import numpy as np
import glob, os
from utils import binvox_rw
from utils import globals as g
from PIL import Image
def read_voxel_data(model_path):
with open(model_path, 'rb') as f:
model = binvox_rw.read_as_3d_array(f)
return model.data
def write_binvox_file(pred, filename):
with open(file... |
from typing import List
def get_mentioned_string(user: str) -> str:
"""Get mentioned format of a user: @username
Args:
user (str): user id
Return:
mentioned_user_string (str): mentioned string
"""
return f"<@{user}>"
kinds = {
"s": ":spades:",
"h": ":hearts:",
"c": ... |
"""
east.module
===========
East class definition - East object allows defining API routes,
validating request parameters and generating API documentation
:copyright: (c) 2016 by <NAME>
:license: MIT
"""
import inspect
import os
from functools import wraps
from flask import request, send_from... |
# ----------------------------------
# CLEES MQTT
# Author : Tompa
# ----------------------------------
# ------------------ General libs --------------
import paho.mqtt.client as mqtt
# ------------------ Private Libs --------------
import clees_settings
import clees_log
import clees_objects... |
# <NAME> <<EMAIL>>
# Licensed under LGPLv3 Or Later (2020)
from datetime import datetime, timedelta
from io import BytesIO
from random import randint
def simple_math() -> tuple:
"""
This will generate a simple captcha where the user has to either +,-,*,/
two numbers. For division it is actually the answer / numb... |
from adminsortable2.admin import SortableInlineAdminMixin
from django import forms
from django.conf.urls import url
from django.contrib import admin
from django.contrib.admin import SimpleListFilter
from django.contrib.contenttypes.admin import GenericTabularInline
from django.contrib.postgres.fields import JSONField
f... |
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 8 11:59:14 2019
@author: GW778XR
"""
"""
Thanks to the webscraping technique, data is more than accessible.
This technique (and the powerful Beautiful Soup package) allows to
automatically extract large amounts of data from a website.
This exercice shows h... |
#
# Copyright (C) 2020 Arm Mbed. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
"""Defines a USB Identifier."""
import re
from enum import Enum
from typing import Optional, Pattern, Any, List, cast
from mbed_tools.devices._internal.utils.python_helpers import named_tuple_with_defaults
from mbed_tools.de... |
import os
import sys
import numpy as np
import pandas as pd
from sklearn.neighbors import KNeighborsClassifier
from sklearn.decomposition import PCA, KernelPCA
from sklearn.decomposition import TruncatedSVD, MiniBatchDictionaryLearning
from imgaug import augmenters as iaa
from sklearn.svm import SVC
from GPyOpt.methods... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# Author: kerlomz <<EMAIL>>
import tensorflow as tf
from tensorflow.contrib.slim import nets
from network.utils import NetworkUtils, RunMode
from constants import LossFunction
from config import ModelConfig
slim = tf.contrib.slim
class ResNetUtils(object):
def __in... |
from __future__ import unicode_literals
import copy
import random
import string
from functools import wraps
from asgiref.inmemory import ChannelLayer as InMemoryChannelLayer
from django.test.testcases import TestCase, TransactionTestCase
from .. import DEFAULT_CHANNEL_LAYER
from ..asgi import ChannelLayerWrapper, ch... |
import os
import sys
import numpy as np
import h5py
from contextlib import contextmanager
from tempfile import NamedTemporaryFile
from skimage import io
import imageio as iio
### Image IO
imread = io.imread
def imread(fn, discard_alpha=True, **kwargs):
"""Read an image, but discard alpha if it is present.
... |
import layoutparser as lp
import os
import fitz
from PIL import Image
from io import BytesIO
from ParseServer.model_control.rectangle_box_opt import inter_rec, neighbor_rec
import numpy as np
def init_model():
model = lp.Detectron2LayoutModel(
os.path.join(os.getcwd(), 'code/ParseServer/models/PubLayNet/f... |
"""Analyze the root verbs used in the actions."""
import json
import logging
import click
import numpy as np
from scipy import stats
import spacy
from statsmodels.stats.multitest import multipletests
import tqdm
from .... import settings
logger = logging.getLogger(__name__)
# constants
N_SAMPLES = 100000
"""The... |
#!/usr/bin/python3
import time
import robin_stocks
import configparser
import json
import requests
import os
from barchart import Barchart
from new_finviz import FinViz
from work_sql import Track_Buys
from figure_std import Find_SLP
from yahoo_analysts import Yahoo_Analysts
barchart = Barchart()
config = configparser... |
"""
Tools for working with alpha shapes.
"""
__all__ = ['alphashape']
import itertools
import logging
from shapely.ops import unary_union, polygonize
from shapely.geometry import MultiPoint, MultiLineString
from scipy.spatial import Delaunay
import numpy as np
from typing import Union, Tuple, List
try:
import geo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2020 Confluent 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 requi... |
# coding=UTF-8
from django import forms
from django.shortcuts import redirect
from trybar.core import render, slugify
from trybar.account import must_be_logged
from trybar.bar.models import Bar, BAR_OPEN_HOURS_FROM
from trybar.barevent.models import Event, EventMeta, EventArtist
from trybar.core.fixtures import VOIVO... |
import torch
import torch.nn as nn
from torch.autograd import Variable
from gans.spectral_norm import SNConv2d
def upblock(in_channel, out_channel, mode, bias, batch_norm,
stride=2, padding=1, last_layer=False):
"""Convolution block that up-scales the input by a factor 2."""
if mode == 'convtran... |
# ----------------------------------------------------------------------------
# Copyright (c) 2020, <NAME>.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# -----------------------------------------------------------------------... |
from styx_msgs.msg import TrafficLight
import tensorflow as tf
from tensorflow.contrib.layers import flatten
import numpy as np
import cv2
def tl_Model(x, train_flag):
#parameter
mu = 0 #parameter of initial value
sigma = 0.05 #parameter of initial value
# Layer 1: Convolutional. Inp... |
import random
import os
from flask import Flask, request
from pymessenger2.bot import Bot
from octorest import OctoRest
class ChatBot(Flask):
def __init__(self, fb_access_tok='Your<PASSWORD>',
fb_verify_tok="<PASSWORD>",
octo_url="http://octopi.local",
octo_apikey=... |
from tkinter import *
root =Tk()
root.title("Calculator")
######################## Display #########################
screen = Entry(root, width=35, borderwidth=2, justify="right")
screen.grid(row=0, column=0, columnspan=4, pady=0)
###################### Definitions #######################
lst_num = [] # List of in... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author: <NAME>
# Last update: 2019.05.13
# First create: 2019.05.13
# Description;
#
import os
import sys
root_path = "/".join(os.path.realpath(__file__).split("/")[:-3])
if root_path not in sys.path:
sys.path.insert(0, root_path)
import torch
from t... |
"""
Base Spout classes.
"""
from __future__ import absolute_import, print_function, unicode_literals
from collections import Counter
from .component import Component
class Spout(Component):
"""Base class for all pystorm spouts.
For more information on spouts, consult Storm's
`Concepts documentation <h... |
"""Public API for the HMC Kernel"""
from typing import Callable, NamedTuple, Optional, Tuple
import jax
import blackjax.mcmc.integrators as integrators
import blackjax.mcmc.metrics as metrics
import blackjax.mcmc.proposal as proposal
import blackjax.mcmc.trajectory as trajectory
from blackjax.types import Array, PRNG... |
import ast
import importlib
import inspect
import re
import runpy
from pathlib import Path
from types import ModuleType
from typing import Any, Callable, Deque, Dict, List, Optional, Tuple, Union
from hookpy import loader
def parse_source_path(
source_path: Union[Path, str]) -> Tuple[ast.AST, List[str]]:
... |
import argparse
import os
import pickle
import numpy as np
from egta.experiments.utils import ALGORITHMS, REGEN_RATES, SEEDS, N_EPISODES, MAX_N_STEPS, N_AGENTS, \
DEFECTORS_COUNT, ROOT_DATA_FOLDER
# file structure for each type (actions, rewards, observations)
# { 'algo': {regen_rate: {'seed:Array of shape (N_E... |
# 给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。
# 请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。
# 你可以假设 nums1 和 nums2 不会同时为空。
# 示例 1:
# nums1 = [1, 3]
# nums2 = [2]
# 则中位数是 2.0
# 示例 2:
# nums1 = [1, 2]
# nums2 = [3, 4]
# 则中位数是 (2 + 3)/2 = 2.5
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com/problems/media... |
import sys
from metatlas import metatlas_objects as metob
import metatlas.helpers.metatlas_get_data_helper_fun as ma_data
import os
from IPython.display import display
import matplotlib.pyplot as plt
try:
import ipywidgets as widgets
except ImportError:
from IPython.html import widgets
try:
import traitl... |
# Copyright 2014 Cisco Systems, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... |
"""
Tests whether RowLineage works
"""
from inspect import cleandoc
import pandas
import numpy as np
from pandas import DataFrame
from mlinspect._pipeline_inspector import PipelineInspector
from mlinspect.inspections import RowLineage
from mlinspect.inspections._lineage import LineageId
def test_row_lineage_merge()... |
import numpy as np
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
import torchvision
import torch.optim as optim
from torchvision import transforms
from tqdm import *
import matplotlib.pyplot as plt
import pickle
from skimage import transform, data
import random
f... |
from __future__ import division
import math
from collections import OrderedDict
from bokeh.io import curdoc
from bokeh.plotting import Figure
from bokeh.models import ColumnDataSource, CustomJS
from bokeh.tile_providers import STAMEN_TONER
from bokeh.models import VBox, HBox, Paragraph, Select
from bokeh.palettes im... |
# Copyright (c) 2013-2015 Siphon Contributors.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""Test that Radar Server access works properly."""
from datetime import datetime
import pytest
from requests import HTTPError
from siphon.radarserver import (BadQueryErro... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2018, KubeVirt Team <@kubevirt>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',... |
'''
configpilot
~~~~~~~~~~~
https://github.com/ValentinBELYN/configpilot
:copyright: Copyright 2017-2020 <NAME>.
:license: MIT, see the LICENSE for details.
~~~~~~~~~~~
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated do... |
#!/usr/bin/env python3
import argparse
import json
import logging
import os
import subprocess
from typing import List, Dict, Tuple
from github import Github
from clickhouse_helper import ClickHouseHelper, prepare_tests_results_for_clickhouse
from commit_status_helper import post_commit_status
from env_helper import ... |
import tensorflow as tf
import numpy as np
import sys
from sklearn.metrics import mean_squared_error
sys.path.append('/Users/davidlaredorazo/Documents/University_of_California/Research/Projects')
# Data handlers
from ann_framework.data_handlers.data_handler_Oscillator import OscillatorDataHandler
import aux_functio... |
import io
import logging
import os
import pathlib
import re
import shutil
import subprocess
import tarfile
import tempfile
import typing
import click
import parver
import requests
IANA_LATEST_LOCATION = "https://www.iana.org/time-zones/repository/tzdata-latest.tar.gz"
SOURCE = "https://data.iana.org/time-zones/releas... |
#
# Copyright 2017 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 applicable law or agreed to in writing... |
from typing import List, Dict
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.responses import HTMLResponse
import json
from log import logger
from database import Database
activated = 0
db: Database = Database('server.db')
app = FastAPI()
class ConnectionManager:
def __init__(self):
... |
import subprocess
import sys
from os import path, makedirs
try: # python 2
from StringIO import StringIO
except ImportError:
from io import StringIO
import psutil
import pytest
from spawny import InstanceDefinition, run_object
THIS_DIR = path.dirname(path.abspath(__file__))
# @pytest.fixture(scope='sess... |
import pkg_resources
from lyrebird.mock import handlers
from collections import OrderedDict, namedtuple
import traceback
from jinja2 import Environment, PackageLoader
from flask import send_from_directory
import sys
import os
import inspect
import codecs
import json
from types import FunctionType
from pathlib import Pa... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
'''
NNI example for quick start of pruning.
In this example, we use level pruner to prune the LeNet on MNIST.
'''
import argparse
import tensorflow as tf
from tensorflow.keras import Model
from tensorflow.keras.layers import (Conv2D, Dense, Dro... |
# Lint as: python2, python3
# Copyright 2019 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
#
... |
from __future__ import print_function
import json
import os
import subprocess
import uuid
from wes_service.util import WESBackend
class Workflow(object):
def __init__(self, run_id):
super(Workflow, self).__init__()
self.run_id = run_id
self.workdir = os.path.join(os.getcwd(), "workflows",... |
#!/usr/bin/env python3
import sys
import random
import socket
import time
import base64
import json
ENCODING = 'utf-8'
REGISTRATION = b'1\n'
QUERY = b'2\n'
SUBMISSION = b'3\n'
SUPPORT = b'4\n'
room_map = {
'Living room': '1',
'Dining room': '2',
'Sex dungeon': '3',
'Flag room': '4',
'Test room': ... |
import multiprocessing
import cv2
import numpy as np
import tensorflow as tf
from joblib import Parallel, delayed
from sklearn.feature_extraction.image import extract_patches_2d
NUM_CORES = multiprocessing.cpu_count()
def _ssd(disparity, patches_left, patches_right, apply_dist, penalty, shape):
'''
Aux func... |
# Copyright 2020 University of Groningen
#
# 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 i... |
import csv
import logging
import os
from collections import OrderedDict, defaultdict
import numpy as np
import torch
from yarr.agents.agent import Summary, ScalarSummary, HistogramSummary, ImageSummary, \
VideoSummary
from multiprocessing import Lock
from typing import List
from yarr.utils.transition import Rep... |
# MIT License
#
# Copyright (c) 2022 <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
# to use, copy, modify, merge, pu... |
from __future__ import absolute_import, division, print_function
import os
import pytest
import dxtbx
from dxtbx.model.experiment_list import ExperimentListFactory
from dxtbx.format.FormatCBFCspad import FormatCBFCspadInMemory
from dxtbx.imageset import ImageSet, ImageSetData, MemReader
from libtbx import easy_run
f... |
"""
.. _l-example-torch-ort-factory:
ONNX in a torch function
========================
The ONNX graph used in this example is not really
interesting but it shows how to create a custom autograd function
following torch API (`Extending Pytorch
<https://pytorch.org/docs/stable/notes/extending.html>`_).
Methods forward ... |
from __future__ import annotations
from typing import TYPE_CHECKING
import numpy as np
import h5py
from .h5_utils import read_basic_element
if TYPE_CHECKING:
from pyNastran.bdf.bdf import BDF
def read_ctube(name: str, group: h5py._hl.dataset.Dataset, geom_model: BDF) -> None:
#('EID', 'PID', 'G', 'DOMAIN_ID')
... |
import sys
import torch
import numpy as np
from torchvision.models import vgg16, resnet50
from model.region_proposal_network import RegionProposalNetwork
from model.faster_rcnn import FasterRCNN
from model.roi_module import RoIPooling2D
from roi_align.functions.roi_align import RoIAlignFunction
from utils.config import... |
# /media/luka/Portable Disk/Datasets/embeddings_alignment/hr-sl.txt/OpenSubtitles.hr-sl.hr.lemmatized
import argparse
import os
import stanfordnlp
def match_pars_opensubtitles(ali1):
# matches paragraphs from file ali1 with those from ali2, based on alignfile and outputs them
# as generator, tab separated. s... |
import ast
import copy
import json
import os
from hashlib import md5
from tempfile import TemporaryDirectory
import yaml
from git import InvalidGitRepositoryError, Repo
from contextlib import contextmanager
@contextmanager
def prepare_variables(*, config_directory, reference_directory=None):
"""create a new upda... |
# This is the code of the worker part of the Sink Operation. Here the user needs to write most of the code in order to
# define the Operation's functionality.
# <editor-fold desc="The following 6 lines of code are required to allow Heron to be able to see the Operation without
# package installation. Do not change.">
... |
"""
Helper module for loading and building CHP queries.
"""
import json
from jsonschema import ValidationError
from trapi_model.query import Query
from trapi_model.message import Message
from trapi_model.biolink.constants import *
from chp_client.exceptions import *
SUBJECT_TO_OBJECT_PREDICATE_MAP = {
BIOLI... |
import re
from datetime import datetime, timedelta
import commonmark
import ujson as json
from babel.dates import format_datetime, get_timezone
from werkzeug.wrappers import Response
def render_markdown(filename):
parser = commonmark.Parser()
renderer = commonmark.HtmlRenderer()
with open(filename) as f:... |
# 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 regex as re
from collections import OrderedDict
from ..rank import Rank, NomCode
# Matches all dots ("."), underscores ("_") and dashes ("-").
NORMALIZE_RANK_MARKER = re.compile(r"(?:[._ -]+|\bnotho)")
def buildRankMarkerMap(ranks, additions=None):
map_ = {}
for r in ranks:
map_[r.value.repl... |
"""
A basic monitor that provides a more convenient use of the process Groups.
"""
import multiprocessing
import time
from shelljob import proc
"""
Manages a Group by collecting output and displaying feedback. This is an abstract
class which provides the basic mechanism.
"""
class Monitor(object):
def __init__(... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from collections import namedtuple
from contextlib import closing
import numpy as np
import socket
import time
import torch
import torch.nn as nn
def train(train_iterator, model, criterion, optimizer):
""... |
import inspect
from typing import Any, Callable, Dict, List, Optional
import numpy as np
from ax.core.arm import Arm
from ax.core.base_trial import BaseTrial, TrialStatus
from ax.core.batch_trial import BatchTrial
from ax.core.data import Data
from ax.core.experiment import Experiment
from ax.core.metric impo... |
import os, sys
import argparse
import pickle
from numpy import random
from Task import Task
from PrecedenceGraph import PrecedenceGraph, Node
from Robot import Robot
from Logger import Logger, LogLevel
class DataSet:
def __init__(self, p_graphs, robots, beta, bid_alpha, cost_alpha):
self.p_graphs = p_grap... |
import torchvision.datasets as dset
from torch.utils.data import DataLoader
import torch
from torchvision.transforms import transforms
from data import SiameseNetworkDataset
from helpers import Config, show_plot
from models import SiameseNetwork, SoftMaxLoss
class Trainer():
def __init__(self):
train_fold... |
#!/usr/bin/env python3
# Copyright 2020 The Emscripten Authors. All rights reserved.
# Emscripten is available under two separate licenses, the MIT license and the
# University of Illinois/NCSA Open Source License. Both these licenses can be
# found in the LICENSE file.
"""Updates the python binaries that we cache s... |
'''
This package has the database schemas for the :mod:`experiments` app.
The main kinds of experiments are going to be mRNAseq and microarray data.
In both cases there is "raw" data and analysed data.
This package contains the main :class:`~experiments.models.Experiment` objects as well as the associated metadata ob... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Usage: %(scriptName) <repository_path> <bug_reports.json> <data_prefix>
"""
import datetime
import json
import pickle
import subprocess
import sys
from joblib import Parallel, delayed
from date_utils import convert_commit_date
from multiprocessing import Pool
from o... |
import os
import unittest
from TweetViz import app, db
from TweetViz.analyze import *
from nltk.sentiment.vader import SentimentIntensityAnalyzer
from datetime import datetime
TEST_DB = 'test.db'
class Place:
def __init__(self, name):
self.name = name
class Tweet:
def __init__(self, full_text="", ... |
#!/usr/bin/python
# Copyright [2021] [<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 applicable law or agre... |
# Copyright 2019 Quantapix 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 l... |
import inspect
from operator import methodcaller
from typing import (
TYPE_CHECKING,
Type,
Mapping,
Tuple,
Optional,
Set,
Dict,
Any,
)
from typic.checks import ismappingtype, isiterabletype, isliteral
from typic.compat import lru_cache
from typic.gen import Block, Keyword, ParameterKind... |
from .interfaces.backend import QuantumBackend
from .interfaces.ansatz import Ansatz
from .interfaces.estimator import Estimator
from .interfaces.functions import function_with_gradient, StoreArtifact
from .circuit import combine_ansatz_params, Circuit
from .gradients import finite_differences_gradient
from .estimator ... |
import numpy as np
from sklearn import svm, linear_model
import torch
def all_metrics(dsprites_loader, model):
latents, classes = get_all_repr(dsprites_loader, model)
bvae = beta_vae_metric(latents, classes)
fact = dis_by_fact_metric(latents, classes)
sap = compute_sap_score(latents, classes)
retu... |
from os.path import exists
from os.path import join
from os.path import os
CUDACONFIG = None
def find_in_path(name, path):
"""
Find a file in a search path
adapted fom
http://code.activestate.com/recipes/52224-find-a-file-given-a-search-path/
"""
for dir in path.split(os.pathsep):
bin... |
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------------
# Copyright © 2020- Spyder Project Contributors
#
# Released under the terms of the MIT License
# ----------------------------------------------------------------------------
"""Tests for the execution of pylint."""
... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
# Copyright (c) 2020 ASMlover. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright... |
"""Codemux configurator. Monitors slice attributes and configures CoDemux to mux port 80 based on HOST field in HTTP request. Forwards to localhost port belonging to configured slice."""
import logger
import os
from config import Config
import slivermanager
CODEMUXCONF="/etc/codemux/codemux.conf"
def start():
... |
import json
import logging
import re
import time
import requests
from urllib.parse import urljoin
from inspire_etf_validator.constants import (
INSPIRE_ETF_API_VERSION,
SERVICE_TEST_IDS,
METADATA_TEST_IDS,
USER_AGENT,
PDOK_EMAIL,
SLEEP_TIME_IN_SECONDS,
)
logger = logging.getLogger(__name__)
... |
from sqlite_utils import Database
from sqlite_utils import cli
from click.testing import CliRunner
import pytest
def test_enable_counts_specific_table(fresh_db):
foo = fresh_db["foo"]
assert fresh_db.table_names() == []
for i in range(10):
foo.insert({"name": "item {}".format(i)})
assert fresh... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.