input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
from __future__ import absolute_import, print_function, division
import os.path as osp
import time
import datetime
import numpy as np
import cv2
import torch
import torch.nn as nn
from torch.nn import functional as F
from torch.utils.tensorboard import SummaryWriter
from ..utils import (
MetricMeter, AverageMeter, ... | |
<filename>dataset_specific/hippocampus/generator/AugmentationGenerator.py
import os
import random as rn
from enum import Enum
import SimpleITK as sitk
import numpy as np
rn.seed(1235)
write_flag = False
OUTPUT_DIR = '/cache/suhita/'
reference_size = [48, 64, 48]
reference_spacing = [1.0, 1.0, 1.0]
dimension = 3
nrC... | |
<reponame>GKO95/quick_draw_cnn<gh_stars>1-10
import tensorflow as tf
import tensorflow.keras as keras
import matplotlib.pyplot as plt
import numpy as np
import random
import os
""" TRAINING DATASET:
np.load(os.path.join(DATAPATH, DATAFILE[INDEX])) =
[[0 0 0 ... 0 0 0] <- 0th INSTANCE (len: 784 = 28 * 28)
[0 0 0 .... | |
<filename>tests/test_wheel.py
# -*- coding: utf-8 -*-
#
# Copyright (C) 2013 <NAME>.
# Licensed to the Python Software Foundation under a contributor agreement.
# See LICENSE.txt and CONTRIBUTORS.txt.
#
from __future__ import unicode_literals
import io
import os
import re
import shutil
import subprocess
import sys
imp... | |
<reponame>wedebe/enigma2-plugins
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Advanced Movie Selection for Dreambox-Enigma2
#
# The plugin is developed on the basis from a lot of single plugins (thx for the code @ all)
# Coded by JackDaniel & cmikula(c)2011
# Support: www.i-have-a-dreambox.com
#
# This plugin is license... | |
import discord
from datetime import datetime
from discord.utils import get
async def msg(message, x, p, self):
msg = x
hasperms = False
cmd = message.split()
validcommands = [p + "hackban", p + "ban", p + "kick", p + "mute", p + "warn", p+ "clear", p+"unmute", p+ "approve"]
if not cmd[0].lower() in validcommands... | |
product_id, **kwargs):
"""
Get videos attached to product
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.... | |
values:
values = [value]
qb = SearchQueryBuilder()
for concept_id, value in zip(concept_ids, values):
term = OutputSearchTerm(concept_id=concept_id, value=value)
qb.add_term(term)
return self.search(qb, page, per_page, raw)
def send_search_feedback(self, input_id, feedback_info=None):
"""
Send feedback for... | |
<reponame>mbattistello/lambda_converters
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 2.0.10
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info
if version_info >= (3,0,0):
new_instancemet... | |
<gh_stars>0
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import json
import logging
import os
import tarfile
import warnings
import itertools
impo... | |
# Estadística para Datos Univariados
Datos univariados (o data univariada) son datos que se describen con una sola variable. Por ejemplo, las alturas de los compñaeros de clase son datos univariados. El propósito principal del análisis de datos univariados es la descripción de los datos.
El análisis de datos univari... | |
<filename>src/cuda4py/_impl/cudnn/_cffi.py
"""
Copyright (c) 2014, Samsung Electronics Co.,Ltd.
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 co... | |
<gh_stars>10-100
import argparse
import json
import sys
import tornado.httpserver
import tornado.ioloop
import tornado.web
from tornado.web import url
from tornado_swagger.setup import setup_swagger
from tornado_swagger.model import register_swagger_model
import database as db
def load_config_file(file_name):
wit... | |
queue.
mock_add_queue.mock_calls = []
response = self.testapp.get(
'/tasks/crawl_list?%s' % '&'.join(
['%s=%s' % (i[0], i[1]) for i in params.iteritems()]))
self.assertEqual(200, response.status_int)
self.assertTweetDbContents(['12', '10', '8', '3'], '123')
# Even though the original tweet '3' was not returned,... | |
def get_fdendrogram( self ):
return self.fdendrogram
class Heatmap:
datatype = 'heatmap'
bbcyr = {'red': ( (0.0, 0.0, 0.0),
(0.25, 0.0, 0.0),
(0.50, 0.0, 0.0),
(0.75, 1.0, 1.0),
(1.0, 1.0, 1.0)),
'green': ( (0.0, 0.0, 0.0),
(0.25, 0.0, 0.0),
(0.50, 1.0, 1.0),
(0.75, 1.0, 1.0),
(1.0, 0.0, 1.0)),
'blue':... | |
0, 0, 0, 0],
[1242, 4.796811, 0, 9999, -9999, 1.0, 100, 1, 27.074038, 0.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1243, 15.340649, 0, 9999, -9999, 1.0, 100, 1, 83.079842, 0.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1244, 184.554903, 0, 9999, -9999, 1.0, 100, 1, 323.472536, 0.0, 0, 0, 0, 0, 0... | |
<filename>linlp/algorithm/viterbiMat/prob_emit_place.py
prob_emit = {
'E': {
'店': -5.2632081894344687,
'顿': -4.19849745244204,
'基': -4.039432757812353,
'略': -5.6198831333732011,
'楼': -6.4671809937604046,
'南': -3.6537702770003686,
'花': -5.0808866326405138,
'港': -4.67542152453235,
'那': -6.4671809937604046,
'华': -7.565793... | |
"""
Globus Contents Manager
"""
import os
import json
import mimetypes
import tempfile
import time
from traitlets import (Unicode, Int)
import globus_sdk
from fair_research_login import NativeClient
from tornado.web import HTTPError
from datetime import datetime
from nbformat import from_dict, reads
try: #PY3
from bas... | |
points...
if out is True:
val = ((f.normal).normalized() * inset_amount)
else:
val = -((f.normal).normalized() * inset_amount)
p6 = angle_rotation(p, p + val, vec1, radians(90))
else:
# if the corner is an actual corner
val = ((f.normal).normalized() * h)
if out is True:
# this -(p - (vec2.normalized() * adj)... | |
self.tanhFM[NN1:NN] = RW.tanhF
self.omegaM[NN1:NN] = RW.omega
self.kiM[NN1:NN] = RW.ki
self.aiM[NN1:NN] = RW.ai
self.kDirM[NN1:NN,:] =RW.kDir[:,:]
self.phiM[NN1:NN] = RW.phi
for ij in range(3):
self.vDir_c[ij] = self.vDir[ij]
self.vDir_ = self.vDir_c
for ij in range(self.Nall):
for kk in range(3):
self.kDi... | |
+= offset_norm_criterion(pt_offset[pt_valid_index], gt_offset[pt_valid_index])
'''point offset dir loss'''
offset_dir_loss += compute_offset_dir_loss(
pt_offset, gt_offset, instance_labels, ignore_label=cfg.ignore_label)
loss_out['offset_norm_loss'] = (offset_norm_loss, (instance_labels != cfg.ignore_label).sum()... | |
# coding: utf-8
"""
InfluxDB OSS API Service.
The InfluxDB v2 API provides a programmatic interface for all interactions with InfluxDB. Access the InfluxDB API using the `/api/v2/` endpoint. # noqa: E501
OpenAPI spec version: 2.0.0
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_im... | |
#!/usr/bin/env python
from mpl_toolkits.basemap import Basemap, cm
# requires netcdf4-python (netcdf4-python.googlecode.com)
from netCDF4 import Dataset as NetCDFFile
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime as dt
from datetime import timedelta as td
import sys
from scipy import... | |
<gh_stars>1-10
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
"""RAMSES RF - a RAMSES-II protocol decoder & analyser."""
import logging
from random import randint, randrange
from types import SimpleNamespace
from typing import Dict, Optional
from .const import (
_000C_DEVICE,
_0005_ZONE,
ATTR_HEAT_DEMAND,
ATTR_... | |
await asyncio.shield(self.extract_rootfs())
log.info(f'Added expanded image to cache: {self.image_ref_str}, ID: {self.image_id}')
with self.step('pulling'):
await self.run_until_done_or_deleted(localize_rootfs)
with self.step('setting up overlay'):
await self.run_until_done_or_deleted(self.setup_overlay)
with ... | |
gradients of this loss function are scaled by factor `1/m`, where m is the number of regression outputs of a training example.
The parameter `grad_scale` can be used to change this scale to `grad_scale/m`.
Defined in ../src/operator/regression_output.cc:L152
Parameters
----------
data : Symbol
Input data to t... | |
<filename>trio_cdp/generated/css.py
# DO NOT EDIT THIS FILE!
#
# This code is generated off of PyCDP modules. If you need to make
# changes, edit the generator and regenerate all of the modules.
from __future__ import annotations
import typing
from ..context import get_connection_context, get_session_context
import ... | |
else had the book on hold, the
# book is now available for anyone to check out. If someone else
# had a hold, the license is now reserved for the next patron.
# If someone else had a hold, the license is now reserved for the
# next patron, and we need to update that hold.
_db = Session.object_session(hold)
licens... | |
== labels_mapping
else:
labels_mapping = spect_dict['labels_mapping']
if 'timebin_dur' in locals():
assert spect_dict['timebin_dur'] == timebin_dur
else:
timebin_dur = spect_dict['timebin_dur']
if 'spect_params' in locals():
assert spect_dict['spect_params'] == spect_params
else:
spect_params = ... | |
<filename>tests/test_operators.py
import pytest
from giving import give, given, giver, operators as op
TOLERANCE = 1e-6
def fib(n):
a = 0
b = 1
give(a, b)
for _ in range(n - 1):
a, b = b, a + b
give(a, b)
return b
def things(*values):
for a in values:
give(a)
def test_getitem():
with given() as gv:
r... | |
<reponame>tailoric/Pouty-Bot-Discord
from discord.ext import commands, tasks
from discord.utils import get
import discord
import json
import datetime
import logging
import traceback
from random import choice
import re
import asyncio
from .utils.dataIO import DataIO
from .utils.checks import is_owner_or_moderator
from c... | |
)
super().__init__(data=data, variables=variables)
self.alpha = alpha
self.legend = legend
def plot(self, ax, kws):
# Draw a test plot, using the passed in kwargs. The goal here is to
# honor both (a) the current state of the plot cycler and (b) the
# specified kwargs on all the lines we will draw, overridin... | |
self.input_dirs:
if not self.input_paths:
self.input_paths = self.input_dirs
else:
raise DistutilsOptionError(
'input-dirs and input-paths are mutually exclusive'
)
if self.no_default_keywords:
keywords = {}
else:
keywords = DEFAULT_KEYWORDS.copy()
keywords.update(parse_keywords(listify_value(self.keywords... | |
item in mnt['items']:
if 'urls' in item:
for url in item['urls']:
removeurls.append(url['url'])
if 'images' in item:
for uload in item['images']:
self.wc.grab_json_response(
'/data/set', 'RP_RemoveFile({0}, 0)'.format(
uload['slotId']))
for url in removeurls:
url = url.replace(':', '\:')
params = urllib.urle... | |
raise ValueError('Bond descriptor scaling is only possible if additional bond features are provided.')
# normalize target weights
if self.target_weights is not None:
avg_weight = sum(self.target_weights)/len(self.target_weights)
self.target_weights = [w/avg_weight for w in self.target_weights]
if min(self.target_... | |
<gh_stars>1-10
'''
Warehouse Class
Model Operations Processing System. Copyright <NAME> 2009-2010. Licenced under the EUPL.
You may not use this work except in compliance with the Licence. You may obtain a copy of the
Licence at http://ec.europa.eu/idabc/eupl or as attached with this application (see Licence fil... | |
<filename>ctdcal/process_bottle.py<gh_stars>1-10
"""Library to create SBE .btl equivalent files.
TODO: allow for variable bottle fire scans instead of SBE standard 36
ex: user doesn't know how to change the config for the cast to add more scans,
instead does it post-cast?
<NAME> SIO/ODF
Nov 7, 2016
"""
import csv
i... | |
<gh_stars>1-10
#!/usr/bin/env python3
original_print = print
from prompt_toolkit import print_formatted_text, Application
# from prompt_toolkit import print_formatted_text as print
from prompt_toolkit.formatted_text import HTML
import pathlib
from bs4 import BeautifulSoup
# http://www.grantjenks.com/docs/diskcache/... | |
<gh_stars>100-1000
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import math
import os
import sys
from logging import getLogger
import torch
from .pretrain import load_embe... | |
import GetTargetHttpsProxyRequest
from .types.compute import GetTargetInstanceRequest
from .types.compute import GetTargetPoolRequest
from .types.compute import GetTargetSslProxyRequest
from .types.compute import GetTargetTcpProxyRequest
from .types.compute import GetTargetVpnGatewayRequest
from .types.compute import G... | |
= 'ou=configuration,o=gluu'
ldap_conn.search(
search_base=dn,
search_scope=BASE,
search_filter='(objectclass=*)',
attributes=['oxIDPAuthentication']
)
oxIDPAuthentication = json.loads(ldap_conn.response[0]['attributes']['oxIDPAuthentication'][0])
oxIDPAuthentication['config']['servers'] = config_servers
o... | |
<filename>cryoorigami/origamiem.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Date : 2018-11-09 11:27:03
# @Author : <NAME> (<EMAIL>)
# @Link : http://example.org
# @Version : $Id$
import os
import re
import glob
import yaml
import numpy as np
import pandas as pd
import cryoorigami.utilities as util
import mrcf... | |
<reponame>pdn4kd/isochoric-expander<gh_stars>0
'''Plots of relative errors for the 5p fits. Both general and zoomed in on the most important features. Ideally also a 2-parameter plot for a vs m.'''
import numpy as np
import matplotlib.pyplot as plt
stars = np.genfromtxt("planetfits_matched.csv", delimiter=",", names=T... | |
= utils.random_unicode()
pub = utils.random_unicode()
priv = utils.random_unicode()
ep_dict = {"publicURL": pub, "privateURL": priv, "tenantId": "aa"}
rgn = "FOO"
clt = fakes.FakeClient()
ep = fakes.FakeEndpoint(ep_dict, svc, rgn, self.identity)
ep._get_client = Mock(return_value=clt)
ident.services[svc].endpoi... | |
[{}] updated"
.format(rsrc.id, subcloud_rsrc_id, ntpservers),
extra=self.log_extra)
def sync_snmp_trapdest(self, request, rsrc):
switcher = {
consts.OPERATION_TYPE_POST: self.snmp_trapdest_create,
consts.OPERATION_TYPE_CREATE: self.snmp_trapdest_create,
consts.OPERATION_TYPE_DELETE: self.snmp_trapdest_delete,
... | |
<filename>fairensics/methods/disparate_impact.py<gh_stars>10-100
"""Wrapper and functions for DisparateImpact remover from fair-classification.
The base class _DisparateImpact implements predict function for both methods.
The classes AccurateDisparateImpact and FairDisparateImpact inherit from
_DisparateImpact and im... | |
<reponame>koningrobot/blocks<gh_stars>0
import itertools
import unittest
from collections import OrderedDict
import numpy
import theano
from numpy.testing import assert_allclose, assert_raises
from theano import tensor
from theano.gof.graph import is_same_graph
from blocks.utils import is_shared_variable
from blocks.b... | |
tools we need
self.portal = DummySite(id='portal').__of__(self.app)
cpm = self._makeOne()
sm = getSiteManager()
sm.registerUtility(cpm, ICachingPolicyManager)
sm.registerUtility(DummyTool(), IMembershipTool)
sm.registerUtility(DummyTool(), ITypesTool)
# This is a FSPageTemplate that will be used as the View for... | |
self.title())
def get(self, force=False, *args):
if force or not hasattr(self, '_content'):
WikibasePage.get(self, force=force, *args)
self.type = self._content['datatype']
def getType(self):
"""
Returns the type that this item uses
Examples: item, commons media file, StringValue, NumericalValue
"""
if not ... | |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
This module contains all functions necessary
to run the pycovid module
"""
__version__ = '0.0.1'
__author__ = '<NAME>'
__email__ = '<EMAIL>'
__license__ = 'GPL'
__status__ = 'Development'
__date__ = '08/17/2020'
def commit_to_repo(repo, message=None, log=N... | |
#!/usr/bin/python
#
# Copyright 2017 University of Southern California
#
# 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 b... | |
logging.warning("Sending of notification failed!")
logging.warning("Exception type: %s" % (str(type(e))))
logging.warning(e)
if not resp.ok:
logging.error(
"Sending of notification data for %s failed: (%d, %s)"
% (model.installation_id, resp.status_code, resp.text)
)
logging.error("Request body:")
logging.erro... | |
from copy import deepcopy
import logging
import sys
import numpy as np
import pytest
from affine import Affine
import rasterio
from rasterio.enums import MergeAlg
from rasterio.errors import WindowError, ShapeSkipWarning
from rasterio.features import (
bounds, geometry_mask, geometry_window, is_valid_geom, rasterize... | |
"""
Set up the plot figures, axes, and items to be done for each frame.
This module is imported by the plotting routines and then the
function setplot is called to set the plot parameters.
"""
from __future__ import absolute_import
from __future__ import print_function
import numpy as np
import matplotlib.pyplot as... | |
<reponame>Ornamus/VillAInous<filename>monte.py
# This is a very simple Python 2.7 implementation of the Information Set Monte Carlo Tree Search algorithm.
# The function ISMCTS(rootstate, itermax, verbose = False) is towards the bottom of the code.
# It aims to have the clearest and simplest possible code, and for the ... | |
= set()
self.ns_prefix_ = node.prefix
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_, gds_collector_=gds_collector_)
return self
def buildAttributes(self, node, attrs, already_processed... | |
* x)
L1 += 0.00000000213 * mu.cost(0.21127914063 + 1505.28780909299 * x)
L1 += 0.00000000267 * mu.cost(5.16501015011 + 3205.54734666440 * x)
L1 += 0.00000000212 * mu.cost(4.26202838353 + 6546.15977336420 * x)
L1 += 0.00000000211 * mu.cost(6.21401684263 + 3253.30422216000 * x)
L1 += 0.00000000233 * mu.cost(3.720075... | |
text='Transylvania', command=self.Menu_Transylvania, width=14, height=3)
Button_Transylvania.grid(row=2, column=3, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_Tyrrell = tk.Button(master=back, text='Tyrrell', command=self.Menu_Tyrrell, width=14, height=3)
Button_Tyrrell.grid(row=2, column=4, sticky=tk.W+tk.E+t... | |
simulation ends either explicitly by
provided a trailing empty campaign or by deriving the end date from the crop calendar and timed events in the
last campaign. See also the section below on `end_date` property.
Each campaign is characterized by zero or one crop calendar, zero or more timed events and zero or more... | |
<reponame>chandu088/p
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import math
import os
import time
from tensorflow.contrib.learn.python.learn import export_strategy
from tensorflow.contrib.learn.python.learn.estimators import run_config
from tensorflow.python.framework im... | |
checked FIRST, then the number of stars
#is compared along with ZWARNING and the number of other QSOs.
#Failing these checks a QFLAG classification is assigned (meaning VI later).
if tQS_check >= 2:
out_Qflag = 'STAR'
elif ((tQS_check < 2) & (zw_in == 0)):
out_Qflag = 'QSO'
else:
out_Qflag = 'QFLAG'
#Send t... | |
from mongoengine import *
from mongoengine.connection import _get_db
from datetime import datetime
from bson import ObjectId
import csv
import collections
import helpers
import unittest
default_currency = "CAD"
# Connect the DB, just need to install mongoDB, might need to create the DB?
connect('ledger-simple-test2')... | |
import boto3
import json
import re
import math
import os.path
from datetime import *
import common
import compare_output
from . import ecs_compares
def main(text):
regionList = ['us-east-1', 'us-west-1', 'us-west-2', 'eu-west-1', 'ap-northeast-1', 'ap-southeast-2']
region = regionList[0]
cluster = ""
ret = ""
t... | |
"""Finds the values in the screen of input multimeter photo"""
import argparse
from datetime import datetime
import cv2
import numpy as np
from imutils import contours, is_cv2
from imutils.perspective import four_point_transform
PARSER = argparse.ArgumentParser()
PARSER.add_argument(
"-i", "--image", help="the input ... | |
of a transaction.<br/>Default value: YES<br/>Possible values = YES, NO.
"""
try :
return self._sendclosenotify
except Exception as e:
raise e
@sendclosenotify.setter
def sendclosenotify(self, sendclosenotify) :
ur"""Enable sending SSL Close-Notify at the end of a transaction.<br/>Default value: YES<br/... | |
""" $lic$
Copyright (C) 2016-2020 by Tsinghua University and The Board of Trustees of
Stanford University
This program is free software: you can redistribute it and/or modify it under
the terms of the Modified BSD-3 License as published by the Open Source
Initiative.
This program is distributed in the hope that it wi... | |
field must indicate the path of the resource. For
example,
``projects/example-project/locations/us-central1/registries/my-registry``.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.iot_v1.types.DeviceRegistry`
update_mask (Union[dict, ~google.cloud.iot_v1.types.Fi... | |
#
# Copyright The NOMAD Authors.
#
# This file is part of NOMAD.
# See https://nomad-lab.eu for further info.
#
# 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/license... | |
#!/usr/bin/env python
#
# Copyright (C) 2007 Lemur Consulting Ltd
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# ... | |
<reponame>shaminmeerankutty/connect-python-sdk
# coding: utf-8
"""
Copyright 2017 Square, 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
Unle... | |
- avg) ** 2 for xs in counts]) / var
pval = spc.gammaincc(1.0 * len(blocks) / 2, chisqr / 2)
return pval
def occurances(string, sub):
count=start=0
while True:
start=string.find(sub,start)+1
if start>0:
count+=1
else:
return count
def overlappingtemplatematchingtest(binin,mat="111111111",num=1032,numi=5):
'... | |
<reponame>akenmorris/ITK<filename>Wrapping/Generators/Python/Tests/extras.py
# ==========================================================================
#
# Copyright NumFOCUS
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You ma... | |
# encoding: utf-8
#
# Copyright (C) 2015-2019 ycmd contributors
#
# This file is part of ycmd.
#
# ycmd is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) an... | |
makeEvent( 'http://id.webbrick.co.uk/zones/heatsource', 'heatsource/2/dostop' )
evtHS2Stopped = makeEvent( 'http://id.webbrick.co.uk/zones/heatsource', 'heatsource/2/stopped' )
evtHS2Enable = makeEvent( 'http://id.webbrick.co.uk/events/config/get', 'zoneheatsource/2/enabled', {'val': 1} )
evtHS2Disable = makeEvent( ... | |
import getpass
from datetime import datetime
import collections
from PySide2 import QtWidgets, QtCore
from .. import constant as c
from ..core.history import Player as HistoryPlayer
from ..core.pgn import MOVES2PGN, PGN2MOVES
from ..core.engineer import Engine
from .widgets import (
BoardWidget,
OptionWidget,
... | |
axis=0))
v0 = vn[:, :-1]
v1 = vn[:, 1:]
cross = np.cross(v0.T, v1.T)
dot = np.sum(v0 * v1, axis=0)
ang = np.arctan2(cross, dot)
uneg = ang < 0
ang[uneg] = -ang[uneg] + np.pi
ang[~uneg] = np.pi - ang[~uneg]
if not inside:
ang = 2 * np.pi - ang
if unit == 'deg':
return upt, ang * 180 / np.pi
elif unit == '... | |
database
db_artist = await self.mass.music.artists.get_db_item_by_prov_id(
prov_artist_id, provider_id=self.id
)
if db_artist is None:
raise MediaNotFoundError(f"Artist not found: {prov_artist_id}")
# TODO: adjust to json query instead of text search
query = f"SELECT * FROM tracks WHERE artists LIKE '%\"{db_arti... | |
/>
<h5 class="text-center">Moving Averages</h5>
<div class="row">
<div class="col-sm">
<table class="table table-sm table-light table-hover table-striped">
<thead>
<th scope="col" colspan="3">15 Minutes</th>
</thead>
<thead>
<th scope="col">EMA12</th>
<th scope="col">EMA26</th>
<th scope="col">Status</th>
... | |
<filename>exoplanet_transit_snr/snr_estimate.py
# -*- coding: utf-8 -*-
from ctypes import c_long
from glob import glob
from itertools import combinations
from os import makedirs
from os.path import basename, dirname, join, realpath
from typing import Tuple, Union
import matplotlib.pyplot as plt
import numpy as np
imp... | |
23 1.1321
cf-cf-oh 86.7 116.85 SOURCE4_SOURCE5 19 1.5331
ce-cf-cy 62.2 137.58 SOURCE4_SOURCE5 18 1.4229
ce-cf-h4 49.3 122.95 SOURCE4_SOURCE5 18 1.1766
ce-cf-n1 90.5 119.94 SOURCE4_SOURCE5 7 1.8420
ce-cf-nh 87.3 121.38 SOURCE4_SOURCE5 27 1.6583
ch-cf-n2 87.9 121.14 SOURCE4_SOURCE5 8 0.9418
c -cf-oh 86.2 115.76 SOURCE4_S... | |
import abc
from collections import defaultdict
import collections.abc
import fnmatch
import os
from pathlib import Path, PosixPath, PurePosixPath, WindowsPath
from typing import Any, IO, Iterable, Optional, TYPE_CHECKING, Union
from urllib.parse import urlparse
from warnings import warn
from . import anypath
from .ex... | |
"in-law",
"continuation",
"violates",
"landlords",
"smokers",
"registering",
"seiji",
"oozing",
"buildup",
"avenging",
"etched",
"loon",
"paddling",
"keeler",
"whooshes",
"tenacity",
"wheelbarrow",
"giveaway",
"hazards",
"clinically",
"cubby",
"paroled",
"'not",
"indonesian",
"vidya",
"accumula... | |
occur. Please see
Cognitive Services Compliance and Privacy notes at https://aka.ms/cs-compliance for
additional details, and Microsoft Responsible AI principles at
https://www.microsoft.com/ai/responsible-ai.
"""
def __init__(self, **kwargs):
self.model_version = kwargs.get("model_version", "latest")
self.stri... | |
# --------------------------------------------------------------------------------------------------
# Model reduction tool functions
# <NAME>
# 5/11/2021
#
# Reference:
# Wang, Bin, <NAME>, and <NAME>. 2021. Power System Network Reduction for Power Hardware-in-the-Loop Simulation: Preprint.
# Golden, CO: Nation... | |
<reponame>peerschuett/lattice_net
import torch
from torch.autograd import Function
from torch import Tensor
import sys
from easypbr import Profiler
from latticenet import HashTable
from latticenet import Lattice
import numpy as np
import time
import math
import torch_scatter
from latticenet_py.lattice.lattice_wrapper ... | |
import random
#Lyrics from the top 100 songs of 2018
billboardtop = ["I've been me since Scarlett Road",
"I never knew you were the someone waiting for me",
"We got nothing but time",
"If it cost a million, that's me",
"I feel just like a rockstar",
"Can't really trust nobody with all this jewelry on you",
"You ... | |
as channel dimension,
# instead of the 2nd one.
# TH input shape: (samples, input_depth, rows, cols)
# TF input shape: (samples, rows, cols, input_depth)
x = x.dimshuffle((0, 3, 1, 2))
return x
def _preprocess_conv3d_input(x, data_format):
"""Transpose and cast the input before the conv3d.
# Arguments
x: inp... | |
from math import sqrt
from typing import Optional, Callable, Union, Dict, List
import dask.array as da
import dask.dataframe as dd
import numpy as np
import pandas as pd
import xarray as xr
from xarray import DataArray
from xrspatial.utils import ngjit
def _stats_count(data):
if isinstance(data, np.ndarray):
# nu... | |
<filename>class_hierarchy.py
import numpy as np
import types
from sklearn.metrics import average_precision_score
class ClassHierarchy(object):
""" Represents a class taxonomy and can be used to find Lowest Common Subsumers or to compute class similarities. """
def __init__(self, parents, children):
""" Initiali... | |
<gh_stars>100-1000
import inspect
import json
import uuid
from collections import Counter
from datetime import datetime
from io import StringIO
import mock
from django.contrib.admin.utils import NestedObjects
from django.db import transaction, IntegrityError
from django.db.models.signals import post_delete, post_save
... | |
from __future__ import print_function
import logging
import curses
import re
import sys
from config import *
from data import Span, span_compare_ge, span_compare_le
class View(object):
def __init__(self, window, cursor, linking_pos, datum, my_config, cnum, total_num, prev_view=None):
self.window = window
self.cur... | |
# -*- coding: utf-8 -*-
"""
Copyright (c) 2020, University of Southampton
All rights reserved.
Licensed under the BSD 3-Clause License.
See LICENSE.md file in the project root for full license information.
"""
import math
import unittest
from unittest.mock import patch
import numpy as np
from auv_cal.cone_fitting im... | |
flakey
tmpDict["detFail"] = 0
else:
# If 1st test passes
tmpDict["fail"] = 0
tmpDict["detFail"] = 0
# Store Info from this row
abstractTests[abstractTest] = tmpDict
countCT = countCT + 1
countRun = countRun + runNumber
# Handle data for full summary file
# Count unique AT
uniqueAT = len(abstractTests)
# ... | |
self.n + 1
#print "n = ", self.n
#print "clauseCount = ", self.clauseCount
total_vars_in_parity_constraints = 0
for i in range(0, m):
new_function = []
for atom in range(1, self.n + 1):
if random.random() < variable_probs[atom-1]:
new_function.append(atom)
total_vars_in_parity_constraints += 1
if len(new_... | |
defined custom resource have.
"""
additionalPrinterColumns = _messages.MessageField('CustomResourceColumnDefinition', 1, repeated=True)
deprecated = _messages.BooleanField(2)
deprecationWarning = _messages.StringField(3)
name = _messages.StringField(4)
schema = _messages.MessageField('CustomResourceValidation', ... | |
frames in
# the speech buffer. This value is used by the chosen 'playback' function()
# to stop playing the audio.
eos_index = SB_SAMPLE_SIZE
# The 'end of speech' (eos) flag. Used inside the `_capture_function()`
# this is set when it has detected the end of speech during the recording
# phase. If no end of speech is... | |
<filename>openamundsen/modules/snow/multilayermodel.py
import numpy as np
from numba import njit, prange
from openamundsen import constants, constants as c, heatconduction
from openamundsen.snowmodel import SnowModel
from . import snow
class MultilayerSnowModel(SnowModel):
def __init__(self, model):
self.model = mo... | |
__init__(self, link):
self.chrom1 = link[0]
self.start1 = int(link[1])
self.chrom2 = link[2]
self.start2 = int(link[3])
self.score = int(link[4])
#------------------------------------------------------------------------------#
# plot bedgraph class
#--------------------------------------------------------------... | |
# the prefix looks like "MCA1ROI:1:"
# and we want the 1 at the end
mcaroi_prefix_match = self.mcaroi_prefix_re.search(prefix)
if mcaroi_prefix_match is None:
raise ValueError(
f"mcaroi prefix '{prefix}' does not match the expected pattern `{self.mcaroi_prefix_re.pattern}`"
)
self.mcaroi_number = int(mcaroi_pref... | |
<filename>src/sorting_relevant_items_first_task.py
import operator
import numpy as np
from shared import config
from shared.indexes import Index
from shared import functions
class ReadDataFile:
def __init__(self, _type, first_n_items=20, echo=True):
self._dict = dict()
f = open(config.task_dataset_path + _type + ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.