text stringlengths 2 999k |
|---|
"""Reducing Functions in Python
These are functions that recombine an iterable recursively, ending up with a single return value
Also called accumulators, aggregators, or folding functions
Example: Finding the maximum value in an iterable
a0, a1, a2, ...,, aN-1
max(a, b) _> maximum of a and b
result =a0
r... |
#!/usr/bin/env python
import os
import json
import torch
import pprint
import argparse
import matplotlib
matplotlib.use("Agg")
import cv2
from tqdm import tqdm
from config import system_configs
from nnet.py_factory import NetworkFactory
from db.datasets import datasets
import importlib
import json
from RuleGroup.Cls i... |
from .utils import encode_attr
from .control import Control
class SearchBox(Control):
def __init__(self, id=None, value=None, placeholder=None, underlined=None,
icon=None, icon_color=None, data=None, on_change=None, onsearch=None,
onclear=None, onescape=None, onchange=None,
widt... |
import os
from pynwb import load_namespaces, get_class
# Set path of the namespace.yaml file to the expected install location
ndx_beadl_specpath = os.path.join(
os.path.dirname(__file__),
'spec',
'ndx-beadl.namespace.yaml'
)
# If the extension has not been installed yet but we are running directly from
# ... |
# Copyright (c) 2015 Nicolas JOUANIN
#
# See the file license.txt for copying permission.
from hbmqtt.mqtt.packet import MQTTPacket, MQTTFixedHeader, CONNECT, MQTTVariableHeader, MQTTPayload
from hbmqtt.codecs import *
from hbmqtt.errors import HBMQTTException, NoDataException
from hbmqtt.adapters import ReaderAdapter
... |
with open("input.txt", "rt") as file:
text = file.read().splitlines()
size = len(text[0])
length = len(text)
ones = [0 for _ in range(size)]
for s in text:
for i, c in enumerate(s):
if c == '1':
ones[i] += 1
gamma = ""
epsilon = ""
for i in ones:
if i > (length/2):
gamma += ... |
# 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/.
#
# Copyright (c) 2014, Lars Asplund lars.anders.asplund@gmail.com
import unittest
from vunit.check_preprocessor import ... |
import os
import pandas as pd
import numpy as np
import sys
network = sys.argv[1]
print(f"Results for {network}")
if ('Surv' in network or 'nnet' in network):
names=[]
values_cv = []
values_ct = []
values_i = []
values_mean = []
values_std = []
values_t = []
results_dir = './'
for f... |
import random
from pathlib import Path
import yaml
from discord.ext.commands import Cog, Context, command
from bot.bot import Bot
class WonderTwins(Cog):
"""Cog for a Wonder Twins inspired command."""
def __init__(self):
with open(Path.cwd() / "bot" / "resources" / "fun" / "wonder_twins.yaml", "r",... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# django_amazon_translate documentation build configuration file, created by
# sphinx-quickstart on Fri Jun 9 13:47:02 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are prese... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
"""
Programa que simula un juego de dados usando la libreria random
"""
#Importamos la libreria random
import random
print("** JUEGO DE AZAR CON DADOS**")
#Creamos una varable llamada dinero
dinero = 0
#Le pedimos al usuario la entrada de un entero que en este caso sera el numero de intents
intentos = int(in... |
import app.message_queue.huey_tasks # pylint: disable=unused-import
from app import message_queue
if __name__ == '__main__':
message_queue.consumer.run()
|
from itertools import tee
from typing import Iterator, TypeVar, Optional, Tuple, Iterable, NamedTuple, Union
T = TypeVar('T')
OT = Optional[T]
Column = Iterator[T]
class zipalign(Iterator['zipalign.Row']):
"""
An iterator that detects differences between any number of input iterators as long as the input ite... |
#! /usr/bin/env python
# encoding: utf-8
# WARNING! Do not edit! http://waf.googlecode.com/git/docs/wafbook/single.html#_obtaining_the_waf_file
import os,re,sys,shutil
from waflib import Utils,Errors
exclude_regs='''
**/*~
**/#*#
**/.#*
**/%*%
**/._*
**/CVS
**/CVS/**
**/.cvsignore
**/SCCS
**/SCCS/**
**/vssver.scc
**/.... |
def pushZeroes(arr):
return [i for i in arr if i != 0] + [i for i in arr if i == 0]
print(pushZeroes([0, 1, 0, 3, 12]))
|
# coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
"""
This class implements definitions for various kinds of bonds. Typically used in
Molecule analysis.
"""
import os
import json
import collections
import warnings
from pymatgen.core.periodic_table import Ele... |
# -*- coding: utf-8 -*-
"""
The MIT License (MIT)
Copyright (c) 2015-2019 Rapptz
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 u... |
# -*- coding: utf-8 -*-
# Copyright 2018 IBM.
#
# 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... |
from django.db import models
import login
from django.conf import settings
# Create your models here.
class Student_Details(models.Model):
st_id = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,limit_choices_to={'is_staff': False})
first_name=models.CharField(max_length=50, help_text="Enter... |
import os
import sys
import pathlib
import coalpy.gpu as g
#print ("graphics devices:")
#[print("{}: {}".format(idx, nm)) for (idx, nm) in g.get_adapters()]
def _checkGpu(gpuInfo, substring):
(idx, nm) = gpuInfo
return substring in nm.lower()
##if we find an nvidia or amd gpu, the first one, we select it.
#... |
import random
import numpy as np
import torch
import torch.utils.data
import commons
from utils import load_wav_to_torch, load_filepaths_and_text
from text import text_to_sequence, cmudict, pinyin2phone
from text.symbols import symbols
class TextMelLoader(torch.utils.data.Dataset):
"""
1) loads audio,te... |
from typing import List
from unified_message_relay.Core.UMRType import ChatAttribute
from unified_message_relay.Core.UMRCommand import register_command, quick_reply
from unified_message_relay.Core.UMRMessageRelation import get_message_id
@register_command(cmd='id', description='get group id')
async def command(chat_a... |
"""Default configuration
Use env var to override
"""
import datetime
import os
DEBUG = os.getenv('DEBUG', True)
SECRET_KEY = os.getenv('SECRET_KEY', 'not_secret')
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL', 'sqlite:////tmp/insta_pic.db')
SQLALCHEMY_TRACK_MODIFICATIONS = False
JWT_BLACKLIST_ENABLED = True
JW... |
import configparser
import os
import click
from appdirs import user_config_dir
DEFAULT_CONFIG = {
"defaults": {
"exit": "<ctrl>+<alt>+e",
"url": "google",
"xsel": True,
},
"urls": {
"google": "https://www.google.com/search?q=",
"wordreference": "https://www.wordrefe... |
from Utility import selectMostConstrainedVariable, orderDomainValues, isConsistent, assign, unassign
#Supposes assignments, and then backtracks and tries again through the possibilities
#Uses recursion to test all possibilities until a solution is found or all possibilities have been tried and none exists
def backtrac... |
from security_monkey.tests import SecurityMonkeyTestCase
from security_monkey.auditor import Entity
from security_monkey.auditors.resource_policy_auditor import ResourcePolicyAuditor
from security_monkey import db
from security_monkey.watcher import ChangeItem
from security_monkey.datastore import Datastore
from securi... |
import builtins
import copyreg
import gc
import itertools
import math
import pickle
import random
import string
import sys
import types
import unittest
import warnings
import weakref
from copy import deepcopy
from test import support
try:
import _testcapi
except ImportError:
_testcapi = None
class Operators... |
#!/usr/bin/env python
# Copyright (c) 2009, Purdue University
# 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 notice, this
# lis... |
from .engine_base import EngineBase
from .sequential_engine import SequentialEngine
|
#!/usr/bin/env python
"""Functions for downloading and reading MNIST data."""
import gzip
import os
from six.moves.urllib.request import urlretrieve
import numpy
SOURCE_URL = 'http://yann.lecun.com/exdb/mnist/'
def maybe_download(filename, work_directory):
"""Download the data from Yann's website, unless it's al... |
# Copyright 2017 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... |
# coding: utf-8
from __future__ import unicode_literals
import sys
from abc import ABCMeta, abstractmethod
from six import add_metaclass
from boxsdk.pagination.page import Page
if sys.version_info >= (3, 3):
from collections.abc import Iterator # pylint:disable=no-name-in-module,import-error
else:
from co... |
import numpy as np
from typing import List, Dict
from pyserini.search.faiss import PRFDenseSearchResult, AnceQueryEncoder
from pyserini.search.lucene import LuceneSearcher
import json
class DenseVectorPrf:
def __init__(self):
pass
def get_prf_q_emb(self, **kwargs):
pass
def get_batch_prf... |
import pytest
from thefeck.rules.no_command import match, get_new_command
from thefeck.types import Command
@pytest.fixture(autouse=True)
def get_all_executables(mocker):
mocker.patch('thefeck.rules.no_command.get_all_executables',
return_value=['vim', 'fsck', 'git', 'go', 'python'])
@pytest.fi... |
from networks_new import Deep4Net_origin, ConvClfNet, TripletNet, FcClfNet
import networks_new as nets
from losses import TripletLoss_dev2, TripLoss, ContrastiveLoss_dk
from torch.optim import lr_scheduler
import torch.optim as optim
class dgnet():
# def __init__(self,gamma):
# margin = 1.0
# self... |
##################################################################################################
## License: Apache 2.0. See LICENSE file in root directory. ####
##################################################################################################
## Box... |
import os
from datetime import datetime, timedelta
import jwt
SECRET = os.getenv('JWT_SECRET')
def create_token(token_data, **timedelta_kwargs):
if not timedelta_kwargs:
timedelta_kwargs = {'days': 2}
current_time = datetime.utcnow()
payload = {
'data': token_data,
'exp': current_... |
"""infosbot_backend URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')... |
import simpleaudio as sa
import os
MODULE_PATH = os.path.dirname(__file__)
AUDIO_DIR = os.path.join(MODULE_PATH, "audio_data")
wave_dict = {
1:'coin.wav',
2:'does-not-compute.wav',
3:'error.wav',
4:'ping.wav',
5:'ready.wav',
6:'succ... |
import datetime
from django.test import TestCase
from django.utils import timezone
from .models import Question
Class QuestionModelTests(TestCase):
def test_was_published_recently_with_future_question(self):
time = timezone.now() + datetime.timedelta(days=30)
future_question = Question(pub_date=... |
import extract_msg
import json, os, re
from natsort import natsorted
from assemblyline_v4_service.common.base import ServiceBase
from assemblyline_v4_service.common.result import Result, ResultSection, BODY_FORMAT
class MsgParser(ServiceBase):
def __init__(self, config=None):
super(MsgParser, self).__init... |
import mypy, os
from typing import List, Tuple
from lib.Sequence import Sequence
###
# Data file manipulation: reading in sequence data and PDB file references.
###
def exe(name: str) -> str:
"""
For distribution, once I've merged into master: look for ROSETTA in
os.environ and return exe path based on... |
# Generated by Django 3.2.4 on 2021-07-02 14:36
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shop', '0005_contact'),
]
operations = [
migrations.AlterField(
model_name='contact',
name='phone',
fiel... |
# -*- coding: utf-8 -*-
"""WAV file IO functions
"""
import warnings
from os import path as op
import numpy as np
from scipy.io import wavfile
from .._utils import verbose_dec, logger, _has_scipy_version
@verbose_dec
def read_wav(fname, verbose=None):
"""Read in a WAV file
Parameters
----------
fn... |
from . import base
from .. import stats
from .. import items
from .. import dialogue
from .. import context
from .. import aibrain
from .. import effects
from .. import animobs
from .. import targetarea
from .. import invocations
from . import animals
from .. import enchantments
# *******************************
# *... |
from setuptools import setup
from setuptools import find_packages
from setuptools.command.test import test as TestCommand
import sys
version = '0.32.0.dev0'
# Please update tox.ini when modifying dependency version requirements
install_requires = [
# load_pem_private/public_key (>=0.6)
# rsa_recover_prime_fac... |
from setuptools import setup
import os
import py2exe
import matplotlib
includes = [
'sip',
'PyQt5',
'PyQt5.uic',
'PyQt5.QtCore',
'PyQt5.QtDesigner',
'PyQt5.QtGui',
'PyQt5.QtNetwork',
'PyQt5.QtMultimedia',
'PyQt5.QtPrintSupport',
'PyQt5.QtWebSockets',
'PyQt5.QtWidgets',
'PyQt5.QtXml',
'numpy',... |
#!/usr/bin/env python3
#-----------------------------------------------------------------------------
# Copyright (c) 2013-2021, PyInstaller Development Team.
#
# Distributed under the terms of the GNU General Public License (version 2
# or later) with exception for distributing the bootloader.
#
# The full license is ... |
# Copyright 2013 Donald Stufft
#
# 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, so... |
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
# Copyright (c) 2022 PaddlePaddle 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 appli... |
# Generated from \Python3.g4 by ANTLR 4.9
from antlr4 import *
from io import StringIO
from typing.io import TextIO
import sys
from antlr4.Token import CommonToken
import re
import importlib
# Allow languages to extend the lexer and parser, by loading the parser dynamically
module_path = __name__[:-5]
language_name ... |
import warnings
from .gfl import GFL
from .one_stage_detector import OneStageDetector
def build_model(model_cfg):
if model_cfg.arch.name == 'GFL':
warnings.warn("Model architecture name is changed to 'OneStageDetector'. "
"The name 'GFL' is deprecated, please change the model->arch->... |
from app import query_team_id
from unittest import mock, TestCase
class QueryTeamIdTests(TestCase):
@mock.patch('slack.WebClient')
def test_calls_slack_client_api_method(self, SlackClient):
mock_token = 'mock token'
mock_api_response = {'ok': True, 'team': {'id': 'T12345'}}
SlackClien... |
import torch
from torch.utils.data import Dataset, DataLoader
import numpy as np
class NumpyDataset(Dataset):
def __init__(self, data_path, labels_path, transform, three_channels=False):
"""
Loads image NumPy arrays and labels NumPy arrays and applies transforms to them in a memory-efficient manner... |
"""added public flag to collections
Revision ID: 5ea96c0a7508
Revises: 56fdb3b41c8f
Create Date: 2021-07-26 14:01:07.982002
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = "5ea96c0a7508"
down_revision = "56fdb3b41c8f"
branch... |
# -*- coding: utf-8 -*-
#
# pycpfcnpj documentation build configuration file, created by
# sphinx-quickstart on Thu Sep 26 13:44:08 2013.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
#... |
#!/usr/bin/env python
# encoding: utf-8
# Copyright 2016-2021 Alexander Mollberg
#
# 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 requ... |
s = '''
'\\<caret>''
'''
|
import logging
import re
import threading
import time
from typing import List
from brownie import chain
from eth_utils import encode_hex, event_abi_to_log_topic
from joblib import Parallel, delayed
from semantic_version.base import Version
from yearn import apy
from yearn.apy.common import ApySamples
from yearn.common... |
# Copyright (c) 2019, salesforce.com, inc.
# All rights reserved.
# SPDX-License-Identifier: MIT
# For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT
from .base import StochasticAgent
from agents.maze_agents.toy_maze.env import Env
from base.modules.generic import OneHo... |
"""Plot kde or histograms and values from MCMC samples."""
import warnings
from typing import Any, Callable, List, Mapping, Optional, Tuple, Union
from ..data import CoordSpec, InferenceData, convert_to_dataset
from ..rcparams import rcParams
from ..utils import _var_names, get_coords
from .plot_utils import KwargSpec... |
driver_type_hebrew_dict = dict(
professional_driver="נהג מקצועי", private_vehicle_driver="נהג פרטי", other_driver="לא ידוע"
)
head_on_collisions_comparison_dict = dict(
head_to_head_collision="התנגשות חזית בחזית", others="אחרות", head_to_head="חזיתיות"
)
english_accident_severity_dict = {1: "fatal", 2: "severe"... |
# Copyright 2014 Rackspace
#
# 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 t... |
import time
import typing
import json
import jsonpickle
import logging
import uuid
from dateutil import parser
from typing import List, Dict, Text, Any, Type, Optional
from rasa.core import utils
if typing.TYPE_CHECKING:
from rasa.core.trackers import DialogueStateTracker
logger = logging.getLogger(__name__)
... |
class Lesson1:
'''This class will contain examples for lesson one: Lists'''
listName = ''
listElements = []
#set and get name from the list
def setName(name):
self.listName = name
def getName():
return self.listName
#list functions
def addToList(item):
self.li... |
import os
import os.path
import re
import time
import json
import redis
import docker
import pytest
import commands
import tarfile
import StringIO
import subprocess
from datetime import datetime
from swsscommon import swsscommon
def ensure_system(cmd):
(rc, output) = commands.getstatusoutput(cmd)
if rc:
... |
import numpy as np
from scipy.special import lpmv, gammaln
from tqdm import tqdm
from dipy.align import Bunch
from dipy.tracking.local_tracking import (LocalTracking,
ParticleFilteringTracking)
import random
import math
def spherical_harmonics(m, n, theta, phi):
"""
... |
#####################################################################################
# MIT License #
# #
# Copyright (C) 2019 Charly Lamothe ... |
# python3
import sys
def compute_min_refills(distance, tank, stops):
if distance <= tank:
return 0
starting_point = 0
refuels = 0
# write your code here
for i in range(len(stops)):
hasStop = False
while stops[i] - starting_point <= tank:
i += 1
hasSt... |
# -*- coding: utf-8 -*-
###cluster.py
#导入相应的包
import scipy
import scipy.cluster.hierarchy as sch
from scipy.cluster.vq import vq,kmeans,whiten
import numpy as np
import matplotlib.pylab as plt
#生成待聚类的数据点,这里生成了20个点,每个点4维:
points=scipy.randn(20,4)
#1. 层次聚类
#生成点与点之间的距离矩阵,这里用的欧氏距离:
disMat = sch.distanc... |
from typing import Union, cast
REQUEST_ERROR_STATUS_CODE = 503
REQUEST_ERROR_MESSAGE = "Unknown request failure in dmapiclient"
class APIError(Exception):
def __init__(self, response=None, message=None):
self.response = response
self._message = message
@property
def message(self) -> Unio... |
from collections import OrderedDict
import numpy as np
import cv2
import pandas as pd
import torch
import torch.nn as nn
from dat import DAT
import matplotlib.pyplot as plt
import motmetrics as mm
from copy import deepcopy
def compare_dataframes(gts, ts):
accs = []
names = []
for k, tsacc in ts.items():
... |
from __future__ import annotations
import re, fnmatch, string
from enum import Enum
class TokenSlice(object):
"""represents string of tokens, separated by common character
can probably replace or merge with one of the objects below """
def __init__(self, s, sep="/"):
self.s = s
self.sep = sep
def __getitem__... |
from argparse import ArgumentParser, Namespace
import attr
from pathlib import Path
import subprocess
import sys
import typing
from kgtk.io.kgtkreader import KgtkReader
from kgtk.utils.argparsehelpers import optional_bool
@attr.s(slots=True, frozen=True)
class DocUpdater():
"""
This class updates KGTK Markdow... |
import importlib
import json
from nni.runtime.config import get_config_file
from .common_utils import print_error, print_green
_builtin_training_services = [
'local',
'remote',
'openpai', 'pai',
'aml',
'kubeflow',
'frameworkcontroller',
'adl',
]
def register(args):
if args.package in ... |
import pymongo
import math
import os
import sys
from datetime import datetime
from datetime import timedelta
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import utils
import meta
def trades(_trader: str = None, _asset_list: list = None,
_start: int = None, _end: int = None) -> list:
"""... |
#
# 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... |
#
# 771. Jewels and Stone
#
# You're given strings J representing the types of stones that are jewels, and
# S representing the stones you have.
#
# Each character in S is a type of stone you have. You want to know how many of
# the stones you have are also jewels.
#
# The letters in J are guaranteed distinct, and all ... |
import json
from typing import Type, Union, Dict
import webbrowser
from jose import jwt
from keycloak import KeycloakOpenID
class AuthenticationClient:
"""A facade for the some authentication implementation, currently keycloak."""
issuer = None
json_web_key_set: dict = {}
def __init__(self, conf:... |
# This script is used to parse BOOST special function test data into something
# we can easily import in numpy.
import re
import os
# Where to put the data (directory will be created)
DATA_DIR = 'scipy/special/tests/data/boost'
# Where to pull out boost data
BOOST_SRC = "boostmath/test"
CXX_COMMENT = re.compile(r'^\s... |
"""
Copyright (c) 2018 iCyP
Released under the MIT license
https://opensource.org/licenses/mit-license.php
"""
from .. import V_Types as VRM_Types
def bone(node) -> VRM_Types.Node:
v_node = VRM_Types.Node()
if "name" in node:
v_node.name = node["name"]
else:
v_node.name = "tmp"
v_nod... |
#!/usr/local/lib/mailinabox/env/bin/python
import argparse
import datetime
import gzip
import os.path
import re
import shutil
import tempfile
import textwrap
from collections import defaultdict, OrderedDict
import dateutil.parser
import time
from dateutil.relativedelta import relativedelta
import utils
LOG_FILES =... |
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
from django.utils import timezone
from datetime import datetime
from django.db import models
from django.db.models import Sum
from django.contrib.auth.models import (
User, Ab... |
#! /usr/bin/python
# -*- coding: utf-8 -*-
u"""
author: Atsushi Sakai
"""
import numpy as np
def solve_qp_with_ep_const(P, q, A, b):
"""
solve quadratic programming with only equality constraints
min 0.5*x*P*x + q.T*x
s.t Ax = b
"""
# input check
if not isinstance(P, np.matrix)... |
import os
import torch
from torch.utils.data import DataLoader, TensorDataset
import numpy as np
def get_table_data(batch_size, data_dir, dataset, oodclass_idx, fold_idx, **kwargs):
data_path = os.path.join(data_dir, dataset + '_preproc.npy')
features, labels, num_classes = np.load(data_path, allow_pickle=Tru... |
#!/usr/bin/env python
"""
Author: David Quail, September, 2017.
Description:
Creates the reinformement learning environment for taking actions, receiving state and rewards.
"""
import numpy
from CycleState import *
NUMBER_OF_STATES = 4
SPECIAL_STATE_INDEX = 0
RIGHT_REWARD = 0
LEFT_REWARD_NEGATIVE = -10
LEFT_REWARD... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020-2022 CERN.
# Copyright (C) 2020-2022 Northwestern University.
#
# Invenio-Records-Resources is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see LICENSE file for more
# details.
"""Service results."""
from abc import ABC, ab... |
# Generated by Django 2.0.5 on 2018-06-12 15:29
from django.conf import settings
from django.db import migrations, models
import wordrelaygame.models
class Migration(migrations.Migration):
dependencies = [
('wordrelaygame', '0003_auto_20180419_1536'),
]
operations = [
migrations.AlterFi... |
from rest_framework.fields import SerializerMethodField
from rest_framework.serializers import ModelSerializer, ReadOnlyField
from automation.serializers import PolicySerializer
from clients.serializers import ClientSerializer, SiteSerializer
from tacticalrmm.utils import get_default_timezone
from .models import Aler... |
# -*- coding: utf-8 -*-
'''
Support for reboot, shutdown, etc
'''
from __future__ import absolute_import
# Import python libs
import logging
import re
# Import salt libs
import salt.utils
# Set up logging
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'system'
def __virtual... |
# pylint: disable=g-bad-file-header
# Copyright 2019 DeepMind Technologies Limited. 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/... |
"""
Generalized Linear Models.
"""
# Author: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Fabian Pedregosa <fabian.pedregosa@inria.fr>
# Olivier Grisel <olivier.grisel@ensta.org>
# Vincent Michel <vincent.michel@inria.fr>
# Peter Prettenhofer <peter.prettenhofer@gmail.com>
# Mathieu Blond... |
import numpy as np
from constants import REACH_ZONE_R, REACHABLE_BUFFER, MAP_W
class Agent():
def __init__(self, runner=None, env=None, verbose=False, **kwargs):
self.env = env
self.runner = runner # TaskRunner (optional)
# State
self.loc = np.array([0.0, 0.0]) # Agent location... |
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... |
import matplotlib.pyplot as plt
from matplotlib import lines
import sys
from math import sqrt
def print_spanning_tree(points):
x_list = []
y_list = []
for (x, y) in points:
x_list.append(x)
y_list.append(y)
plt.plot(x_list, y_list, 'ro')
reached = []
unreached = [] + points
... |
"""
We aim at showing the current bias of classical ML and DL methods towards site by learning the site using:
- 5-fold CV stratified on age+sex+site scheme
- VBM, quasi-raw, FreeSurfer pre-processing
"""
import numpy as np
import os, logging
import sys
from copy import deepcopy
sys.path.extend(["../", ".", "../../"]... |
import sys
from collections import defaultdict
f = open(sys.argv[1])
data = f.read().strip().split('\n')
data = [x.split(' | ') for x in data]
part1 = 0
for pattern, output in data:
for p in output.split():
if len(p) == 2 or len(p) == 4 or len(p) == 3 or len(p) == 7:
part1 += 1
print(f'{part1 ... |
import importlib
from dataclasses import dataclass, field
from typing import Type, Iterable, Dict
from marshy.errors import MarshallError
from marshy.marshaller.marshaller_abc import MarshallerABC
@dataclass(frozen=True)
class TypeMarshaller(MarshallerABC[Type]):
"""
Marshaller for object types - allows sett... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.