text stringlengths 2 999k |
|---|
import rdflib
import pytest
from project import graph_utils
my_graph = graph_utils.get_graph_info("travel")
def test_name():
assert my_graph[0] == "travel"
def test_nodes():
assert my_graph[1] == 131
def test_edges():
assert my_graph[2] == 277
def test_labels():
assert my_graph[3] == {
... |
"""baseline_pa dataset."""
import tensorflow_datasets as tfds
from . import baseline_pa
class BaselinePaTest(tfds.testing.DatasetBuilderTestCase):
"""Tests for baseline_pa dataset."""
# TODO(baseline_pa):
DATASET_CLASS = baseline_pa.BaselinePa
SPLITS = {
'train': 3, # Number of fake train example
... |
from django.contrib import admin
from django.conf.urls import include, url
from django.views.generic import TemplateView
from . import views
admin.autodiscover()
urlpatterns = [
url(r'^$', views.DemoView.as_view(template_name="index.html"), {},
name="index"),
url(r'^success/$', TemplateView.as_view(... |
import numpy as np
import random
x=np.load("G:\\learning_material\\lab\\2048\\2048-api\\data\\x.npy")
y=np.load("G:\\learning_material\\lab\\2048\\2048-api\\data\\y.npy")
#altogether 419966 samples
#x is a 419966*4*4*11 array
#y is a 419966*4 array
index=[i for i in range(len(x))]
random.shuffle(index)
x=x[index]
y=y[... |
# -*- coding: utf-8 -*-
#
# Copyright © 2009-2010 Pierre Raybaut
# Licensed under the terms of the MIT License
# (see spyderlib/__init__.py for details)
"""Miscellaneous utilities"""
import os
import os.path as osp
import sys
import stat
def __remove_pyc_pyo(fname):
"""Eventually remove .pyc and .pyo files asso... |
#!/usr/bin/env python
""" generated source for module SimpleSolver """
from __future__ import print_function
#
# * Copyright (C) 2008-12 Bernhard Hobiger
# *
# * This file is part of HoDoKu.
# *
# * HoDoKu is free software: you can redistribute it and/or modify
# * it under the terms of the GNU General Pu... |
import os
import tempfile
import hashlib
import subprocess
import pkg_resources
import biom
import skbio
import qiime2.util
import pandas as pd
import q2templates
# We used the q2-breakaway/q2_breakaway/_alphas.py to learn how to make a R script to be triggered by a python command. So thank you Amy Willis
TEMPLATES... |
"""This module contains deprecations that could not stay in their original
module for some reason.
Such reasons include:
- Original module had to be removed.
- Adding @deprecated to a declaration caused an import cycle.
Since no modules in SymPy ever depend on deprecated code, SymPy always imports
this last, after al... |
import pytest
def pytest_addoption(parser):
parser.addoption("--remote", action="store_true",
help="run tests requiring internet")
parser.addoption("--slow", action="store_true",
help="run tests that are slow")
def pytest_configure(config):
config.addinivalue_l... |
# MIT licensed
# Copyright (c) 2013-2017 lilydjwg <lilydjwg@gmail.com>, et al.
import json
from urllib.parse import urlencode
from tornado.httpclient import AsyncHTTPClient, HTTPRequest, HTTPResponse
from tornado.httpclient import HTTPError
from tornado.platform.asyncio import AsyncIOMainLoop, to_asyncio_future
Async... |
from unittest import TestCase
from stanford_nlp_train_test import Util
class TestLoadConf(TestCase):
def test_load_conf(self):
Util.load_conf('./conf/properties.json')
self.assertEqual(len(Util.conf), 13)
|
from django.shortcuts import render
from .models import Post
def home(request):
context = {
"posts": Post.objects.all(),
}
return render(request, 'blog/home.html', context)
def about(request):
return render(request, 'blog/about.html')
|
"""
ASGI config for myServer project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETT... |
import matplotlib.pyplot as plt
import numpy as np
def subplots():
"Custom subplots with axes throught the origin"
fig, ax = plt.subplots()
# Set the axes through the origin
for spine in ['left', 'bottom']:
ax.spines[spine].set_position('zero')
for spine in ['right', 'top']:
ax.sp... |
baseDir ='AF_SOL_881/'
readFile1 = baseDir + 'Undetermined_S0_L001_R1_001.fastq'
readFile2 = baseDir + 'Undetermined_S0_L001_R2_001.fastq'
indexFile1 = baseDir + 'Undetermined_S0_L001_I1_001.fastq'
indexFile2 = baseDir + 'Undetermined_S0_L001_I2_001.fastq'
D701='ATTACTCG'
D702='TCCGGAGA'
D703='CGCTCATT'
D70... |
from ...googleServices.GoogleService import GoogleService
from ...resources import feed
sheets_service = GoogleService().get_sheets_service()
database_index = feed.get_symbols_info()
class StockDataFeed:
""" Class to provide stock data. """
def get_data(self, symbol_list):
data = {}
for symb... |
from __future__ import print_function
import sys
import ast
import functools
import pytest
from peval.core.function import Function
from peval import partial_eval, partial_apply, specialize_on, getsource, inline
from peval.tools import unindent
from tests.utils import assert_ast_equal, function_from_source
def as... |
l1 = [(1, 'a'), (2, 'b'), (3, 'c')]
d1 = dict(l1)
print(d1)
|
from chalky import bg, fg, hex, rgb, sty
# compose some styles together
print(fg.red & sty.bold | "Bold and red text")
print(bg.blue & fg.white & sty.italic | "White italic text on a blue background")
# store a style for later use
success_style = fg.green
print(success_style | "Success message")
print(success_style &... |
from dataclasses import dataclass, field
from typing import Set
@dataclass(unsafe_hash=True)
class AlignedWordPair:
@classmethod
def parse(cls, alignments: str, invert: bool = False) -> Set["AlignedWordPair"]:
result: Set[AlignedWordPair] = set()
for token in alignments.split():
da... |
# pylint: disable=redefined-outer-name
import time
import pytest
import asyncio
DEFAULT_MAX_LATENCY = 10 * 1000
@pytest.mark.asyncio
async def test_slow_server(host):
if not pytest.enable_microbatch:
pytest.skip()
A, B = 0.2, 1
data = '{"a": %s, "b": %s}' % (A, B)
time_start = time.time()... |
# Copyright (c) 2018 Science and Technology Facilities Council
# All rights reserved.
# Modifications made as part of the fparser project are distributed
# under the following license:
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following condi... |
#!/usr/local/bin/python3.7
# -*- coding: utf-8 -*-
class MinStack:
def __init__(self):
"""
最小栈:
1. 当一个元素要入栈时,我们取当前辅助栈的栈顶存储的最小值,与当前元素比较得出最小值,将这个最小值插入辅助栈中;
2. 当一个元素要出栈时,我们把辅助栈的栈顶元素也一并弹出
最大栈:
1. 当一个元素要入栈时,我们取当前辅助栈的栈顶存储的最大值,与当前元素比较得出最大值,将这个最大值插入辅助栈中;
... |
# -*- encoding: utf-8 -*-
from django.apps import AppConfig
class MyConfig(AppConfig):
name = 'cfg'
|
class HashProcessor():
def __init__(self):
self.HashCounts = HashCounts()
self.STOPHASHES = ["#job", "#hiring", "#job?"]
def process(self, tweet):
text = tweet['text']
hashtags = self._return_hashtags_in_text(text)
for tag in hashtags:
if tag not in self.STO... |
import braille
import time
usbport = '/dev/tty.usbmodem141101'
a = braille.braille(90,30,97,37,90,30,90,150,90,157,100,167,usbport,[1,2,3,4,5,6])
a.AllUp()
time.sleep(2)
a.AllDown()
time.sleep(1)
# a.WriteStr('Hello Rags')
|
from mesh.standard import *
from scheme import *
from platoon.resources.task import Task
__all__ = ('SubscribedTask',)
class SubscribedTask(Task):
"""A subscribed task."""
name = 'subscribedtask'
version = 1
requests = 'create delete get put query update'
class schema:
topic = Token(non... |
#------------------------------------------------------------------------------
# Copyright (c) 2013-2017, Nucleic Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#--------------------------------------------... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import copy
import os
import warnings
from dataclasses import dataclass, field
from textwrap import dedent
from typing import Callable, Dict, List, Optional, Set, Tuple, Union
from omegaconf import DictConfig, OmegaConf
from hydra import MissingC... |
import os
import sys
sys.path.append(os.path.split(os.path.dirname(os.path.abspath(__file__)))[0])
from Tools.Thread import Thread
from Test.ProxyTest import ProxyTest
from Tools.Log import Log as logger
from Tools.GeneralTool import GeneralTool
class Scheduler():
_database = GeneralTool.getDataBaseObject()... |
from pegasus.service import db, tests, users
from pegasus.service.users import User
from sqlalchemy.exc import IntegrityError
class TestUsers(tests.TestCase):
def test_validate_password(self):
self.assertRaises(users.InvalidPassword, users.validate_password, None)
self.assertRaises(users.InvalidPa... |
import asyncio
import os
import random
import re
import string
import discord
from discord.ext import commands
from utils.functions import read_file
class MadLibs(commands.Cog):
"""The classic [madlibs game](https://en.wikipedia.org/wiki/Mad_Libs)"""
def __init__(self, bot):
self.bot = bot
... |
"""
Part of the ProbLog distribution.
Copyright 2015 KU Leuven, DTAI Research Group
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required ... |
# Copyright 2018 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, ... |
import numpy as np
class dropout:
def __init__(self, keep_prob=0.5):
self.keep_prob = keep_prob
def forward(self, A):
D = np.random.rand(A.shape[0], A.shape[1])
D = D < self.keep_prob
A = np.multiply(A, D)
A /= self.keep_prob
return A, D
def ba... |
import os
bamfile = open('bam_files.txt')
paths = []
files = []
count_files = 0
for line in bamfile:
full_path = line.strip()
path, file = os.path.split(full_path)
if path not in paths:
paths.append(path)
print len(paths)
print len(files)
print count_files
output_path = 'merged_bams'
for path i... |
#!/usr/local/bin/python3
import os
from setuptools import find_packages, setup
VERSION='0.0.3'
PYTHON_REQUIRES='3.7'
packagedata=dict()
packagedata['include_package_data']=True
packagedata['name']="snowshu"
packagedata['version']=VERSION
packagedata['author']="Health Union Data Team"
packagedata['author_email']='d... |
"""
Quotes API For Digital Portals
The quotes API combines endpoints for retrieving security end-of-day, delayed, and realtime prices with performance key figures and basic reference data on the security and market level. The API supports over 20 different price types for each quote and comes with basic searc... |
#
# Copyright (c) 2014 by the Werkzeug Team, see AUTHORS for more details.
#
# 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
# notice, this ... |
# IMPORTATION STANDARD
# IMPORTATION THIRDPARTY
import pandas as pd
import pytest
# IMPORTATION INTERNAL
from openbb_terminal.economy import finnhub_model
@pytest.fixture(scope="module")
def vcr_config():
return {
"filter_query_parameters": [("token", "MOCK_TOKEN")],
}
@pytest.mark.vcr(record_mode... |
# under jina root dir
# python scripts/get-last-release-note.py
# result in root/tmp.md
with open('CHANGELOG.md') as fp:
n = []
for v in fp:
if v.startswith('## Release Note'):
n.clear()
n.append(v)
with open('tmp.md', 'w') as fp:
fp.writelines(n)
|
import json
import tarfile
import ttk
from Tkinter import *
import tkFileDialog
import os
import sys
import boto3
from boto3.s3.transfer import S3Transfer
import collections
import pandas as pd
import tkMessageBox
import tkSimpleDialog
import pandastable
import csv
import webbrowser
import requests
import tempfile
impo... |
# Copyright Contributors to the Amundsen project.
# SPDX-License-Identifier: Apache-2.0
import distutils.util
import os
from typing import Callable, Dict, List, Optional, Set # noqa: F401
import boto3
from amundsen_gremlin.config import LocalGremlinConfig
from flask import Flask # noqa: F401
from metadata_service.... |
"""Miscellaneous utilities.
"""
import os
from http import HTTPStatus
empty_response = ("", HTTPStatus.NO_CONTENT)
def boolstr(s):
"""Interpret string s as a Boolean.
This is intended for interpreting HTTP query parameters. "False",
"no" or "off" in any case and any representation of the
integer 0 c... |
#code based on example found at:
#http://www.pyimagesearch.com/2015/09/14/ball-tracking-with-opencv/
# import the necessary packages
from collections import deque
import numpy as np
import argparse
import imutils
import cv2
import time as t
# construct the argument parse and parse the arguments
ap = argparse.ArgumentP... |
'''
A training routine for tf.keras models written in the low-level TensorFlow API.
Copyright (C) 2019 Pierluigi Ferrari
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/li... |
import os
import sys
import glob
import json
import fnmatch
import logging
import pathlib
import argparse
import pandas as pd
from datetime import datetime
from datetime import timedelta
from google.cloud import storage
from google.cloud.exceptions import NotFound
def readLog(logPath):
"""Reads a file containing ... |
import sys, re
from passport import passports_from_input
def part1(input):
number_valid = 0
for p in passports:
number_valid += p.validate_simple()
return number_valid
def part2(input):
number_valid = 0
for p in passports:
number_valid += p.validate()
return number_valid
assert len(sys.argv) == 2... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
"""Base class for neural network modules.
This also contains modules for fully-connected and convolution layers.
"""
import abc
import lbann
from lbann.util import make_iterable
class Module(abc.ABC):
"""Base class for neural network modules.
A module is a pattern of layers that can be added to a layer
... |
# import warnings
# warnings.filterwarnings('ignore')
import copy, logging
import pandas as pd
logger = logging.getLogger(__name__)
# TODO: currently is buggy
class FeaturePruner:
def __init__(self, model_base, threshold_baseline=0.004, is_fit=False):
self.model_base = model_base
self.threshold_b... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import logging
import numpy as np
import astropy.units as u
from astropy.io import fits
from astropy.table import Table
from gammapy.maps import MapAxes, MapAxis
from gammapy.utils.integrate import trapz_loglog
from gammapy.utils.nddata import NDDataArray
... |
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import brewer2mpl
from utils import *
import systems_utils
from systems_utils import get_colors, HATCH_DICT
import matplotlib.patheffects as path_effects
import matplotlib as mpl
import fire
mpl.rcParams["h... |
from unittest2 import TestCase
from raven.utils.wsgi import get_headers, get_host, get_environ
class GetHeadersTest(TestCase):
def test_tuple_as_key(self):
result = dict(get_headers({
('a', 'tuple'): 'foo',
}))
self.assertEquals(result, {})
def test_coerces_http_name(self)... |
import datetime
from detectron2.data import MetadataCatalog
COCO_CATEGORIES = [
{"color": [220, 20, 60], "isthing": 1, "id": 1, "name": "person"},
{"color": [119, 11, 32], "isthing": 1, "id": 2, "name": "bicycle"},
{"color": [0, 0, 142], "isthing": 1, "id": 3, "name": "car"},
{"color": [0, 0, 230], "is... |
# CPU: 0.20 s
while True:
no_of_lines = int(input())
if no_of_lines == 0:
break
lower_bound = 1
upper_bound = float("inf")
divisibility = []
for _ in range(no_of_lines):
*words, num = input().split()
num = int(num)
# min and max functions are key points to pass all test cases!
if words[0] == "less":
... |
# coding: utf-8
# Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... |
#!/usr/bin/env python3
"""Three philosophers thinking and eating dumplings - deadlock happens"""
import time
from threading import Thread
from deadlock.lock_with_name import LockWithName
THREAD_DELAY = 1
dumplings = 20
class Philosopher(Thread):
def __init__(self, name: str, left_chopstick: LockWithName, right... |
# Copyright 2021, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in complianc... |
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
\brief Code to train DLDL
\copyright Copyright (c) 2021 Visual Computing group of Ulm University,
Germany. See the LICENSE file at the top-level directory of
this distribution.
''''''''''''''''''''... |
from django.shortcuts import render, get_object_or_404
from util.tool import login_required
from .models import SchedulerHost
from django.db.models import Q
from ratelimit.decorators import ratelimit # 限速
from ratelimit import ALL
from util.rate import rate, key
import requests
import urllib3
import json
import tr... |
from django.core.management.base import BaseCommand
from salt_observer.models import Minion
from . import ApiCommand
import json
class Command(ApiCommand, BaseCommand):
help = 'Fetch and save mount points data'
def save_packages(self, api):
mount_point_devices = api.get('ps.disk_partition_usage')
... |
import yaml, os
path = os.getcwd()
from util import log
class LoginPage:
def __init__(self, driver): #
self.driver = driver
self.logs = log.LogMessage()
self.file = open(path + "\\data\\page_data.yaml", "r", encoding="utf-8")
self.data = yaml.load(self.file)
self.file.clo... |
import distutils
def mod1test():
return dir(distutils)
|
import copy
import logging
import re
from collections import defaultdict
from rasa.core.trackers import DialogueStateTracker
from typing import Text, Any, Dict, Optional, List
from rasa.core.nlg.generator import NaturalLanguageGenerator
logger = logging.getLogger(__name__)
class TemplatedNaturalLanguageGenerator(N... |
from __future__ import absolute_import
from django.conf import settings
from django.core.urlresolvers import reverse
from six.moves.urllib.parse import urlparse, quote
from sentry import options
from sentry.plugins import plugins
from sentry.plugins.bases.notify import NotifyPlugin
from sentry.utils.http import absol... |
import json
from monday.utils import python_json_stringify
# Eventually I will organize this file better but you know what today is not that day.
# ITEM RESOURCE QUERIES
def mutate_item_query(board, group, item, column_values):
if column_values is None:
column_values = {}
query = '''mutation
{
... |
""" pyprobables module """
from .blooms import (
BloomFilter,
BloomFilterOnDisk,
CountingBloomFilter,
ExpandingBloomFilter,
RotatingBloomFilter,
)
from .countminsketch import (
CountMeanMinSketch,
CountMeanSketch,
CountMinSketch,
HeavyHitters,
StreamThreshold,
)
from .cuckoo imp... |
from discord.ext import commands
from discordTogether import DiscordTogether
class Activities(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.togetherControl = DiscordTogether(bot)
@commands.Cog.listener()
async def on_ready(self):
print(f"{self.__class__.__name__} Cog... |
from utils import config, parse_midas_data, sample_utils, diversity_utils, core_gene_utils, substitution_rates_utils, clade_utils
import os.path, sys, gzip
import numpy
min_coverage = config.min_median_coverage
alpha = 0.5 # Confidence interval range for rate estimates
low_pi_threshold = 1e-03
low_divergence_threshold... |
# This is the solution for Greedy algorithms > MaxNonoverlappingSegments
# The problem is equivalent to the Activity Selection Problem,
# where you have to choose the maximum non overlapping tasks.
#
# This is marked as PAINLESS difficulty
def solution(A, B):
last_end_segment = -1
chosen_count = 0
for i in... |
from pypom import Region
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as expected
from pages.desktop.base import Base
class Categories(Base):
URL_TEMPLATE = 'extensions/categories/'
_categories_locator = (By.CLASS_NAME, 'Categories-item')
_mobil... |
import torch
import torch.nn as nn
# m = nn.LogSoftmax(dim=1)
# loss = nn.NLLLoss()
# # input is of size N x C = 1 x 3
# input = torch.tensor([[1,0,0]], requires_grad=True, dtype=torch.float)
# # each element in target has to have 0 <= value < C
# target = torch.tensor([1])
# output = loss(m(input), target)
# print(m... |
from allauth.account.views import confirm_email as confirm_email_view
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import include, path, re_path
from django.views import defaults as default_views
from django.views.generic import TemplateVi... |
# coding: utf-8
from __future__ import unicode_literals
from .prosiebensat1 import ProSiebenSat1BaseIE
from ..utils import (
unified_strdate,
parse_duration,
compat_str,
)
class Puls4IE(ProSiebenSat1BaseIE):
_VALID_URL = r'https?://(?:www\.)?puls4\.com/(?P<id>[^?#&]+)'
_TESTS = [{
... |
import numpy as np
import random
import time
from itertools import product
import sys
_BIRTH = 3
_SUSTAIN = (2, 3)
_LONELY = (0, 1)
_CROWDED = 4
class Game:
'''Generate game oobject'''
def __init__(self, **kwargs):
'''Initiate new game'''
self.x_size = kwargs.get('size', 10)
self.y_size = kwargs.get('size'... |
# coding: utf-8
"""
Copyright 2015 SmartBear Software
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applica... |
from .approx_vertex_cover import approx_vertex_cover_solver
from .vertex_cover import vertex_cover_solver
from .weighted_vertex_cover import weighted_vertex_cover_solver
|
#!/usr/bin/env python
#
# @license Apache-2.0
#
# Copyright (c) 2018 The Stdlib Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# ... |
# Copyright 2018 VMware, 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 required by a... |
from distutils.core import setup
setup(
name='pwlf',
version=open('pwlf/VERSION').read().strip(),
author='Charles Jekel',
author_email='cjekel@gmail.com',
packages=['pwlf'],
package_data={'pwlf': ['VERSION']},
url='https://github.com/cjekel/piecewise_linear_fit_py',
license='MIT License'... |
# This file is Copyright 2019 Volatility Foundation and licensed under the Volatility Software License 1.0
# which is available at https://www.volatilityfoundation.org/license/vsl-v1.0
#
import logging
from volatility.framework import renderers
from volatility.framework.configuration import requirements
from volatili... |
""" Contains controlling logic for the ICA.
"""
import logging
from copy import deepcopy
import numpy as np
import mne
from meggie.utilities.compare import compare_raws
def compute_ica(raw, n_components, method, max_iter, random_state):
""" Computes ICA using MNE implementation.
"""
ica = mne.preproc... |
/usr/local/lib/python3.6/locale.py |
"""
This file contains an implementation of our method
With Baysian optimization and agreement of observed constraints
"""
import numpy as np
import utils.constraint as constraint
from utils.utils import print_verbose
from utils.optimizer import CombinationKernelOptimizer
def kernel_clustering(kernels, cluster... |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivat... |
from pyxbos.driver import *
from pyxbos import weather_station_pb2
import os,sys
import json
import requests
import yaml
import argparse
class DarkSkyPredictionDriver(Driver):
def setup(self, cfg):
self.baseurl = cfg['darksky']['url']
self.apikey = cfg['darksky']['apikey']
self.coords = cf... |
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... |
# -*- coding: utf-8 -*-
# Copyright (c) 2015-2016, Camptocamp SA
# 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
#... |
import os
import sys
PROJECT_DIR = os.path.dirname(os.path.realpath(__file__))
DATA_DIR = os.path.join(PROJECT_DIR, "train_data") # labelled data
CNF_DIR = os.path.join(PROJECT_DIR, "cnf_data") # unlabelled CNF files for evaluation
TOOLS_DIR = os.path.join(PROJECT_DIR, "tools")
CADICAL_PATH = "cadical"
|
"""
Prime Developer Trial
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: v1
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401
from fds.sdk.B... |
from cupy import core
from cupy.core import fusion
def argmax(a, axis=None, dtype=None, out=None, keepdims=False):
"""Returns the indices of the maximum along an axis.
Args:
a (cupy.ndarray): Array to take argmax.
axis (int): Along which axis to find the maximum. ``a`` is flattened by
... |
from rx.core.typing import Disposable
from rxbp.observable import Observable
from rxbp.observer import Observer
from rxbp.observerinfo import ObserverInfo
from rxbp.indexed.selectors.selectnext import select_next
from rxbp.indexed.selectors.selectcompleted import select_completed
from rxbp.typing import ElementType
... |
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from network import NN
def read_data(fpath):
iris = pd.read_csv(fpath)
iris.loc[iris['species'] == 'virginica', 'species'] = 0
iris.loc[iris['species'] == 'versicolor', 'species'] = 1
iris.loc[iris['species'] == 'setosa', 'species... |
import netCDF4
import defopt
import sys
import datetime
def main(*, tfile: str='',
ufile: str='',
vfile: str='',
outputdir: str='./', jmin: int, jmax: int, imin: int, imax: int):
"""
subset nemo data
:param tfile: name of the netCDF file containing T cell grid data
:param u... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2012-2019 SoftBank Robotics. All rights reserved.
# Use of this source code is governed by a BSD-style license (see the COPYING file).
""" Install the given python project """
from __future__ import absolute_import
from __future__ import unicode_literals
fro... |
import os
from functools import lru_cache
from .utils import logger
@lru_cache(maxsize=1000)
def get_git_revision(dirpath):
try:
return _get_git_revision(dirpath)
except (OSError, IOError) as err:
logger.error("get_git_revision failed: %s", err)
return None
def _get_git_revision(dir... |
import numpy as np
from sklearn.base import BaseEstimator
from chemprop.conformal.nonconformist import *
# class MCP:
# def __init__(self,
# y_calibrate: np.array,
# y_calibrate_hat: np.array,
# calibrate_error_estimated: np.array,
# p=0.9):
... |
"""
Support for Vera locks.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/lock.vera/
"""
import logging
from homeassistant.components.lock import LockDevice
from homeassistant.const import (STATE_LOCKED, STATE_UNLOCKED)
from homeassistant.components.ve... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.