input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
"""Various utility functions for the ``jwql`` project.
Authors
-------
- <NAME>
- <NAME>
Use
---
This module can be imported as such:
>>> import utils
settings = get_config()
References
----------
Filename parser modified from <NAME>:
https://gist.github.com/jhunkeler/f08783ca2da7bfd1f8e9ee1d207da5ff
Va... | |
places=12)
self.assertAlmostEqual(c[1], 1.2, places=12)
self.assertAlmostEqual(c[2], -2.5, places=12)
def test_cpv(self):
pv = ((0.3,1.2,-2.5),
(-0.5,3.1,0.9))
c = erfa.cpv(pv)
self.assertAlmostEqual(c[0][0], 0.3, 0.0,)
self.assertAlmostEqual(c[0][1], 1.2, 0.0,)
self.assertAlmostEqual(c[0][2], -2.5, 0.0,)
... | |
<reponame>linklab/link_rl
import time
import math
import random
import gym
from gym import spaces
import numpy as np
import grpc
# MQTT Topic for RIP
from codes.b_environments.quanser_rotary_inverted_pendulum import quanser_service_pb2_grpc
from codes.b_environments.quanser_rotary_inverted_pendulum import blender_serv... | |
from datetime import datetime
import json
import glob
import os
from pathlib import Path
from multiprocessing.pool import ThreadPool
from typing import Dict
import numpy as np
import pandas as pd
from scipy.stats.mstats import gmean
import torch
from torch import nn
from torch.utils.data import DataLoader
ON_KAGGLE:... | |
Insights app.
:type name: str
:param region: Required. The Azure region of the Application Insights app.
:type region: str
:param related: The related metadata items for the Application Insights app.
:type related: ~monitor_query_client.models.MetadataApplicationRelated
"""
_validation = {
'id': {'required': T... | |
<reponame>tombrereton/threematch
"""
This is the file for the game logic of three match.
"""
import os
from copy import deepcopy
from itertools import product
from operator import itemgetter
from random import randint, choice
from time import time
from events.event_manager import EventManager
from events.events import... | |
is returned.
Parameters
----------
url : str
The full or partial URL to validate
Returns
-------
The complete URL
Examples
--------
>>> url = self._validate_file_url('https://webserver.net/path/to/file')
'https://webserver.net/path/to/file'
>>> url = self._validate_file_url('path/to/file')
'https://webs... | |
def requestImage(self, *args, **kwargs): # real signature unknown
pass
def requestPixmap(self, *args, **kwargs): # real signature unknown
pass
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from... | |
[11],
)
await self.assert_query_result(
r'''
SELECT ddlf_14(<int32>10, f := '11');
''',
[12],
)
finally:
await self.con.execute("""
DROP FUNCTION ddlf_14(a: int64, NAMED ONLY f: int64);
DROP FUNCTION ddlf_14(a: int32, NAMED ONLY f: str);
""")
async def test_edgeql_ddl_function_15(self):
with self.assertR... | |
"confidential_instance_config", confidential_instance_config)
if description is not None:
pulumi.set(__self__, "description", description)
if disks is not None:
pulumi.set(__self__, "disks", disks)
if enable_display is not None:
pulumi.set(__self__, "enable_display", enable_display)
if guest_accelerators is not ... | |
<filename>gdsfactory/simulation/gtidy3d/get_simulation_grating_coupler.py
"""Returns tidy3d simulation from gdsfactory Component."""
import warnings
from typing import Dict, Optional
import matplotlib.pyplot as plt
import numpy as np
import tidy3d as td
import gdsfactory as gf
from gdsfactory.component import Compone... | |
<reponame>qilei123/DAFNe<gh_stars>0
from detectron2.data.datasets import register_coco_instances
from dafne.utils.sort_corners import sort_quadrilateral
from detectron2.utils.colormap import colormap
from detectron2.data.datasets.coco import load_coco_json
from detectron2.data import (
DatasetCatalog,
MetadataCatalog... | |
True
# truning the model into tranining mode triggers obscure problem:
# incorrect validation performance due to BatchNorm. We do automatic
# differentiation in evaluation mode instead.
#model.train()
for iteration in range(maxiter):
# >> prepare optimizer for SGD
optim = th.optim.SGD(model.parameters(), lr=1.... | |
#!/usr/bin/env python
# coding: utf-8
# <div class="alert alert-block alert-info">
# <b><h1>ENGR 1330 Computational Thinking with Data Science </h1></b>
# </div>
#
# Copyright © 2021 <NAME> and <NAME>
#
# Last GitHub Commit Date:
#
# # 30: Regression using Exponential, Logarithmic, and Power-Law Models
# - Loga... | |
<reponame>awacha/cct
import datetime
import enum
import logging
import multiprocessing
import os
import pickle
import time
from typing import Dict, Optional, Any, List
import numpy as np
from PyQt5 import QtCore
from .component import Component
from .devicemanager import DeviceManager
from .io import IO
from ...datac... | |
<filename>src/network-manager/azext_network_manager/vendored_sdks/models/_models_py3.py
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for licens... | |
<reponame>guardicore/open_pension
import os
import glob
from django.utils import timezone
from django.core.management import BaseCommand
import dateutil.parser
from pension.models import Quarter, Instrument
managing_body_dict = {
'amitim': 'AMT',
'as': 'AS',
'clal': 'CLL',
'ds': 'MTD',
'yl': 'YL',
'fnx': 'FNX'... | |
# MIT License
#
# Copyright (c) 2018 Pyjcsx, 2021 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including withou... | |
<reponame>xyproto/duckling<gh_stars>0
#!/usr/bin/python2
# -*- coding: utf-8 -*-
#vim: set enc=utf8:
#
# The advantage of sending the entire buffer to each sprite,
# instead of each sprite returning a small image,
# is that a sprite may, for instance, blur the whole screen.
# Or make fire-trails after oneself. Or shake... | |
"""
This module implements a modular input consisting of a web-server that handles incoming Webhooks.
"""
try:
# Python 2
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from urlparse import parse_qs
except:
# Python 3
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse im... | |
<reponame>mukobi/VRITS-Python-Game<filename>Polygonner/game.py
"""
game.py - <NAME> - 2019 04 18
A simple pygame game where the player avoids larger polygons
to stay alive and eats smaller polygons to grow.
"""
import math
from math import sqrt, sin, cos
import sys
import random
from dataclasses import dataclass, fiel... | |
from logging import info, debug, error, warning
import logging
import os
from os.path import join, isfile, isdir, isabs, abspath, dirname, realpath
import re
import sys
import shutil
import signal
from subprocess import Popen, PIPE, STDOUT
import subprocess
import time
import yaml
class bcolors:
HEADER = '\033[95m'
... | |
Range 7 Upper Limit',
'pyname': u'dewpoint_temperature_range_7_upper_limit',
'maximum': 70.0,
'required-field': False,
'autosizable': False,
'minimum': -70.0,
'autocalculatable': False,
'type': u'real',
'unit': u'C'}),
(u'range 7 equipment list name',
{'name': u'Range 7 Equipment List Name',
'pyname': u'rang... | |
<filename>Roku Network Remote.indigoPlugin/Contents/Server Plugin/RPFramework/dataAccess/indigosql.py
#! /usr/bin/env python
#/////////////////////////////////////////////////////////////////////////////////////////
#/////////////////////////////////////////////////////////////////////////////////////////
# IndigoSql b... | |
<filename>sfcollector/solidfire_graphite_collector.py
#!/usr/bin/env python
# solidfire_graphite_collector.py
#
# Version 1.0.5
#
# Original authors: <NAME>, <NAME>
# Contributors: <NAME>, <NAME>, scaleoutSean
#
# Copyright (c) 2020 NetApp, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (t... | |
time window
- productType (string): The product type to fetch events for. This parameter is required for networks with multiple device types. Valid types are wireless, appliance, switch, systemsManager, camera, cellularGateway, and environmental
- includedEventTypes (array): A list of event types. The returned events... | |
import tensorflow as tf
from layers import initializer, regularizer, residual_block, highway, conv, mask_logits, \
trilinear, total_params, optimized_trilinear_for_attention, multihead_attention, \
biLSTM_layer_op
class Model(object):
def __init__(self, config, batch, word_mat=None, char_mat=None, trainable=True, op... | |
column to remove
Returns:
None
.. note::
If the column name does not exist, a warning is issued.
'''
try:
del self.data[name]
except (ValueError, KeyError):
import warnings
warnings.warn("Unable to find column '%s' in data source" % name)
def stream(self, new_data, rollover=None):
''' Efficiently update... | |
VPC when initially creating a private zone...
# The rest have to be added (one-by-one) later in a separate step.
if len(fixed_vpcs) > 1:
add_vpcs = fixed_vpcs[1:]
fixed_vpcs = fixed_vpcs[:1]
CallerReference = CallerReference if CallerReference else str(uuid.uuid4())
else:
# Currently the only modifiable traits a... | |
import numbers
import tempfile
import imageio
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import numpy.linalg as linalg
import seaborn as sns
import pandas as pd
from matplotlib.colors import ListedColormap, to_hex
from matplotlib.patches import Ellipse, Rectangle, FancyArrowPatch
from sc... | |
from CommonServerPython import *
''' IMPORTS '''
import urllib3
import traceback
from typing import List, Dict, Any, Tuple, Union
from requests.exceptions import MissingSchema, InvalidSchema
# Disable insecure warnings
urllib3.disable_warnings()
''' CONSTANTS '''
INTEGRATION_NAME = 'RiskIQ Digital Footprint'
COMMA... | |
"""
This module of SYMORO package provides geometric models' computation.
The core symbolic library is sympy.
Needed modules: symoro.py
ECN - ARIA1 2013
"""
from sympy import Matrix, zeros, eye, sin, cos
from symoro import Symoro, Init, hat
Z_AXIS = Matrix([0, 0, 1])
class Transform():
@classmethod
def sna(sel... | |
<reponame>JesperMjornman/FlakyReporter
from flakyreporter.util import bcolors as Color
import sys, inspect, collections, os, traceback, linecache
import json, pytest, platform, datetime, threading, re, glob
class LogHandler():
"""
Represents a logging object that handles logging the tracing and test results.
"""
de... | |
return SkimWrapper(self, orig_key, dest_key)
def wrap_3d(self, orig_key, dest_key, dim3_key):
"""
return a SkimWrapper for self
"""
return Skim3dWrapper(self, orig_key, dest_key, dim3_key)
class SkimWrapper(object):
"""
A SkimWrapper object is an access wrapper around a SkimDict of multiple skim objects,
wh... | |
# -----------------------------------------------------------------------------------------------------
#
# Copyright 2020 <NAME> <EMAIL>
#
# 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 witho... | |
# -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-22 12:47
import logging
import math
import os
from typing import List
import numpy as np
import tensorflow as tf
from elit.components.parsers.parse_alg import unique_root, adjust_root_score, chu_liu_edmonds
from elit.layers.transformers.loader_tf import build_tra... | |
inc
template = Template(template.safe_substitute(rock=tmp))
tmp = ''
if 'aquifers' in self.components:
tmp += "INCLUDE\n'${} '/\n/\n\n".format('aquifers_file')
inc = os.path.join('INCLUDE', 'aquifers.inc')
self.aquifers.dump(os.path.join(dir_path, inc))
fill_values['aquifers_file'] = inc
template = Template(te... | |
from __future__ import annotations
import json
import pickle
from copy import copy
from datetime import date, datetime
from pathlib import Path, PurePath
from typing import Any, ByteString, Callable, Mapping, Optional, Sequence
from typing import Tuple as Tup
from typing import Type, TypeVar, Union
import orjson
impo... | |
has unknown position to work with other than 'before', 'after', 'inside', 'replace'
* if some tag other than 'position' is found in parent view
:raise Invalid ArchitectureError: if there is view type other than form, tree, calendar, search etc defined on the structure
"""
self.check_access_rights('read')
view = se... | |
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Callable, Dict, Iterator, List, Optional, Set, Tuple, Union
from darwin.path_utils import construct_full_path
Point = Dict[str, float]
BoundingBox = Dict[str, float]
Polygon = List[Point]
ComplexPolygon = List[Polygon]
Node = Di... | |
as an additional NXST_FLOW_MONITOR reply with xid 0.
*
* When multiple outstanding monitors match a single change, only a single
* notification is sent. This merged notification includes the information
* requested in any of the individual monitors. That is, if any of the
* matching monitors requests actions (NXFM... | |
params, prefix='gru_cond',
nin=None, dim=None, dimctx=None,
nin_nonlin=None, dim_nonlin=None):
if nin is None:
nin = options['dim']
if dim is None:
dim = options['dim']
if dimctx is None:
dimctx = options['dim']
if nin_nonlin is None:
nin_nonlin = nin
if dim_nonlin is None:
dim_nonlin = dim
W = numpy.conc... | |
"""The vowpal module contains classes to make it easier to interact with pyvw."""
import re
import collections
from os import devnull
from itertools import repeat
from numbers import Number
from typing_extensions import Literal
from typing import Any, Dict, Union, Sequence, overload, cast, Optional, Tuple
from coba.... | |
["plastic"],
"salientMaterials": ["plastic"],
}],
"attributes": ["moveable", "pickupable", "stackTarget"],
"dimensions": {
"x": 0.106,
"y": 0.098,
"z": 0.106
},
"offset": {
"x": 0,
"y": 0.046,
"z": 0
},
"position_y": 0.005,
"scale": {
"x": 1,
"y": 1,
"z": 1
}
}, {
"type": "plate_1",
"info": ["tiny"... | |
With each entry, the validity and range of the date is also checked, and done accordingly.
If the order is not correct, then the user is instructed to enter two dates in correct order, until the dates are in
correct order.
The in-order tuple, '(start_date, end_date)' is returned.
"""
while (int(start_date[-4:]) ... | |
<gh_stars>0
import shutil
from pathlib import Path
from tempfile import TemporaryDirectory
from typing import Mapping
import pytest
from _pytest.capture import CaptureFixture
from _pytest.tmpdir import TempdirFactory
from freezegun import freeze_time
from prance import ValidationError
from datamodel_code_generator.__... | |
<reponame>hmhyau/rl-intention<gh_stars>1-10
from abc import ABC, abstractmethod
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from gym.spaces import Discrete, Tuple, Box
from collections import defaultdict
from utils import convert_to_onehot, as_list, mkdir_if_not_exist
from layers... | |
removes them all.
@type client: C{GanetiRapiClientWrapper}
@param client: A wrapped RAPI client.
"""
instances = client.GetInstances()
for inst in instances:
Finish(client, client.DeleteInstance, inst)
instances = client.GetInstances()
assert len(instances) == 0
def TestSingleInstance(client, instance_name... | |
<reponame>truwl/capanno-utils
# Classes to represent metadata for command line tools.
from pathlib import Path
from collections import OrderedDict
from abc import abstractmethod
import re
import uuid
from ruamel.yaml import safe_load
from capanno_utils.repo_config import *
from capanno_utils.exceptions import InIndexEr... | |
+ \
(agents[i, A_HOUSEHOLD_Y] - agents[j, A_HOUSEHOLD_Y]) ** 2
dij = dij ** 0.5
if dij > SMALL_ERROR:
# If agents i and j don't share household, then skip
continue
num_infectious_hh += 1 # agent j shares household with agent i and is also infectious
# Probability of infection spread inside household for agent... | |
value
@property
def maximum_table_output(self):
"""field `Maximum Table Output`
| Specify the maximum value calculated by this curve object
| Units are based on field `A13`
Args:
value (float): value for IDD Field `Maximum Table Output`
Raises:
ValueError: if `value` is not a valid value
Returns:
float:... | |
<gh_stars>1-10
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import pandas
from pandas.api.types import (is_scalar, is_list_like, is_bool)
from pandas.core.dtypes.common import is_integer
from pandas.core.indexing import IndexingError
import numpy as np
i... | |
QtGui.QBrush(QtGui.QColor(117, 0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(235, 0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush)... | |
| x x x |
/ 4 2 \ C1*|- --- + -- - -- + 1|
| x x | \ 720 24 2 / / 6\
f(x) = C2*|--- - -- + 1| + ------------------------ + O\x /
\120 6 / x
References
==========
- <NAME>, "Differential Equations with Applications and
Historical Notes", p.p 176 - 184
"""
x = func.args[0]
f = func.func
C0, C1 = get_number... | |
contrast.
contrast : str
Contrast specification: see Notes.
match : Factor
Match cases for a repeated measures test.
sub : index
Perform the test with a subset of the data.
ds : None | Dataset
If a Dataset is specified, all data-objects can be specified as
names of Dataset variables.
tail : 0 | 1 | -1
Which ... | |
<filename>utils/lfutils.py
# <NAME> @IPVS
# 180919
from __future__ import print_function
import numpy as np
import math
import scipy
import matplotlib.image as mpimg
import scipy.ndimage
def disp_scaling(disp,new_shape):
return scipy.misc.imresize(disp,new_shape,
interp="bicubic",mode="F")
def img_scaling(img,new... | |
<reponame>Sayyad828/ByteTrack
from collections import deque
import torch
import numpy as np
from utils.kalman_filter import KalmanFilter
from utils.log import logger
from models import *
from tracker import matching
from .basetrack import BaseTrack, TrackState
class STrack(BaseTrack):
def __init__(self, tlwh, scor... | |
# Copyright (c) 2020, MD2K Center of Excellence
# - <NAME> <<EMAIL>>
# 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, th... | |
<reponame>Glee1018/PhaseNet
# Modified by Lijie
# Email:<EMAIL>
# Date Modified: 2019-03-20 21:54
################################################################################
# MIT License
#
# Copyright (c) 2018 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this soft... | |
<reponame>felipesch92/projeto_kivy<filename>venv/lib/python3.8/site-packages/kivy/tests/async_common.py
"""
.. warning::
The classes in this file are internal and may well be removed to an
external kivy-pytest package or similar in the future. Use at your own
risk.
"""
import random
import time
import math
import o... | |
= [1, 35, 35, 288] # out: [1, 17, 17, 384]
kernel_shape = [3, 3, 288, 384]
strides = [1, 2, 2, 1]
dilations = [1, 3, 3, 1]
x_val = np.arange(1, 1 + np.prod(x_shape)).astype("float32").reshape(x_shape)
kernel_val = np.arange(1, 1 + np.prod(kernel_shape)).astype("float32").reshape(kernel_shape)
self._conv_test(x_va... | |
/ h)
# value at boundary = A*cells + b
M = self.boundary_face_scalar_integral
A = M @ A
b = M @ b
return A, b
@property
def cell_gradient_BC(self):
"""
Boundary conditions matrix for the cell gradient operator (Deprecated)
"""
warnings.warn("cell_gradient_BC is deprecated and is not longer used. See cell... | |
more accurate results than mm=25, try 19 or 13.'
'* The smallest allowed patch size is 5.'
'* You may want stop at a larger patch size (say 7 or 9) and use'
'the -Qfinal option to run that final level with quintic warps,'
'which might run faster and provide the same degree of warp detail.'
'* Trying to make two di... | |
from __future__ import print_function
import json
import getpass
from cloudmesh_client.common.Shell import Shell
from cloudmesh_client.cloud.vm import Vm
from cloudmesh_client.cloud.group import Group
from cloudmesh_client.shell.command import command
from cloudmesh_client.shell.console import Console
from cloudmesh_... | |
<filename>_build/jupyter_execute/curriculum-notebooks/Science/LightOpticalSystems/light-optical-systems.py<gh_stars>1-10

<a href="https://hub.callysto.ca/jupyter/hub/user-redirect/git-pull?repo... | |
h, w = os.popen('stty size', 'r').read().split()
w = int(w)
line = '{}{}{}'.format(
left, ' ' * (w - left_size - right_size - 2 * margin), right)
printNicely('')
printNicely(line)
printNicely('')
# Print messages
for m in messages:
if m['sender_screen_name'] == me_nick:
print_right_message(m)
elif m['recipie... | |
<gh_stars>0
# ----------------------------------------------------------------------------
# This software is in the public domain, furnished "as is", without technical
# support, and with no warranty, express or implied, as to its usefulness for
# any purpose.
#
# InlandFloodThreat
#
# Author: lefebvre,santos
# Last M... | |
<reponame>ddingding/coevolution_mechanism
'''
tools for dealing with stan and the models
functions for
1) formatting read data into dictionaries that can be fed into the stan model for inference
2) analysing/summarizing stan inferred data
3) calculating posterior predictive checks
4) simulating synthetic datasets to c... | |
""" Interface to :mod:`~pySPACE.environments.chains.node_chain` using the :class:`~pySPACE.environments.chains.node_chain.BenchmarkNodeChain`
.. image:: ../../graphics/node_chain.png
:width: 500
A process consists of applying
the given `node_chain` on an input for a certain parameters setting.
Factory methods are p... | |
from __future__ import absolute_import
import json
from datetime import datetime
import numpy
import xarray
from affine import Affine
from rasterio.io import MemoryFile
from rasterio.warp import Resampling
from skimage.draw import polygon as skimg_polygon
from itertools import chain
import re
import datacube
from da... | |
coords, fill = self.colors[curve.curve_color], dash = self.linestyles[curve.curve_style], width = self.curve_lineweight, name = curve.name)
elif (py[i] == py[i + 1]):
coords = [self.axes_left, self.to_canvas_y(py[i], curve.yaxis),
self.axes_right, self.to_canvas_y(py[i], curve.yaxis)]
self.draw_line(coords = coord... | |
import gc
import resource
import itertools
import matplotlib
matplotlib.use('Agg') # required if X11 display is not present
import matplotlib.pyplot as plt
import pickle
import pysam
import re
import os
import numpy as np
from bisect import bisect_left
from collections import defaultdict
from math import floor
# Hure... | |
<gh_stars>1-10
import torch
import torch.nn as nn
from torch.nn import init
import torch.nn.functional as F
import functools
from torch.optim import lr_scheduler
from memcnn.models.revop import ReversibleBlock
from torch.nn import Parameter
import numpy as np
import re
#################################################... | |
the ones we need to collect. But this almost certainly means
# that only one thread will end up downloading the data if the
# data is sorted. So shuffle it.
shuffle(exposureSet)
return exposureSet
def downloadExposures(exposureSet, useMonsta = True):
"""downloadExposures.
Args:
exposureSet:
useMonsta:
"""
... | |
<filename>dmvr/modalities.py
# Copyright 2021 DeepMind Technologies Limited.
#
# 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 require... | |
hid_t iss, hid_t s, RMF::HDF5::FloatTraitsBase::Type v)"""
return _RMF_HDF5._FloatTraitsBaseClass_write_value_dataset(d, iss, s, v)
write_value_dataset = staticmethod(write_value_dataset)
def read_value_dataset(d, iss, sp):
"""read_value_dataset(hid_t d, hid_t iss, hid_t sp) -> RMF::HDF5::FloatTraitsBase::T... | |
bool = True
) -> Tuple[torch.Tensor, torch.Tensor]:
"""Scattering values over an `n`-dimensional canvas
In the case of projecting values to an image-type canvas (`n`=2), i.e. projecting
height values to a top-down height map, the shape of the canvas is (b..., d1, d2)
or we say (b..., h, w), where `b...` is the bat... | |
# Import a whole load of stuff
from System.IO import *
from System.Drawing import *
from System.Runtime.Remoting import *
from System.Threading import *
from System.Windows.Forms import *
from System.Xml.Serialization import *
from System import *
from Analysis.EDM import *
from DAQ.Environment import *
from EDMConfi... | |
else:
msj = "[ERROR] Se esperaba formato json"
print (msj)
return response_({})
@app.route('/turno/update', methods = ['POST'])
def api_turno_update():
print("api_turno_update")
if request.headers['Content-Type'] == 'application/json':
# Se recuperan datos.
datos = request.json['datos']
# Turno.
... | |
(float(time()) - float(timecheckG)))
print(" Setting types...", end = '')
themesDF = themesDF.astype({'V1Themes' : pd.StringDtype()},
copy = False)
print("\n GKG Themes-normalized DataFrame .info():\n")
print(themesDF.info())
print(" Setting index to 'GKGRECORDID'...")
themesDF.set_index(keys='GKGRECO... | |
<gh_stars>10-100
#!/usr/bin/env python
import argparse
import json
import numpy as np
import os
import pandas as pd
import time
class Game:
# Initialize the game.
def __init__(self, uid1, uid2,
house, target_obj, start_pano, end_panos, max_seconds_per_turn):
print("Game: initializing with users %s, %s" % (uid1, ... | |
#
# Autogenerated by Thrift Compiler (0.9.2)
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
#
# options string: py:twisted
#
from thrift.Thrift import TType, TMessageType, TException, TApplicationException
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol, TProt... | |
in ebunch:
ne=len(e)
if ne==3:
u,v,dd = e
elif ne==2:
u,v = e
dd = {}
else:
raise NetworkXError(\
"Edge tuple %s must be a 2-tuple or 3-tuple."%(e,))
if u not in self.node:
self.adj[u] = {}
self.node[u] = {}
if v not in self.node:
self.adj[v] = {}
self.node[v] = {}
datadict=self.adj[u].get(v,{})
datadi... | |
* 101}
res = self.app.delete_json_api(self.url, new_payload,
auth=self.user_one.auth, expect_errors=True, bulk=True)
assert_equal(res.status_code, 400)
assert_equal(res.json['errors'][0]['detail'], 'Bulk operation limit is 100, got 101.')
assert_equal(res.json['errors'][0]['source']['pointer'], '/data')
def test... | |
grads['dW2']
self.W_e['B1'] += -self.learning_rate * grads['dB1']
self.W_e['B2'] += -self.learning_rate * grads['dB2']
self.learning_rate *= 0.9999
def evaluate(self):
plt.plot(self.loss, color = 'orange')
plt.xlabel(' # of Epochs')
plt.ylabel('Loss')
plt.title('Training Loss versus Epochs')
plt.legend([f... | |
from discord.ext import commands
from discord import Embed, colour, File
from pyrez.exceptions import NotFound, MatchException
from PIL import Image, ImageFont, ImageDraw, ImageOps
from io import BytesIO
import my_utils as helper
class MatchCog(commands.Cog, name="Match Command"):
"""Match Cog"""
def __init__(se... | |
<gh_stars>10-100
import sys
# sys.path.append("..")
# sys.path.append("../..")
import torch
import numpy as np
from torch import nn, optim
import core_models.utils as utils
from sklearn.metrics import roc_auc_score as auc_compute
from sklearn.metrics import average_precision_score as avpr_compute
from core_models.ut... | |
<gh_stars>10-100
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2014 IBM Corporation
# Copyright 2015-2019 Lenovo
#
# 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.apac... | |
Domains resource to be passed as the request body.
"""
customer = _messages.StringField(1, required=True)
domains = _messages.MessageField('Domains', 2)
class DirectoryDomainsListRequest(_messages.Message):
r"""A DirectoryDomainsListRequest object.
Fields:
customer: Immutable ID of the G Suite account.
"""
... | |
# Author: <NAME> at Harvard Medical School. The code draws some lines from <NAME> Jr.'s SSVEP code for openBCI from GitHub
#
# Made with PsychoPy Version 1.84.2
# Date: May-June 2017...ah, fun times.
from psychopy import visual, core, event, gui, logging
import os
import sys
import random
import math
import csv
import... | |
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 26 18:07:47 2021
@author: <NAME>
Cestimii.
Compute curvature estimations on point clouds using integral invariants.
This file contains all methods that have something to do with the
initialization, construction, splitting or merging of occupancy grids or
occupancy grid... | |
event_scope: typing.Optional['libioc.events.Scope']=None,
dependant_jails_seen: typing.List['JailGenerator']=[],
start_dependant_jails: bool=True
) -> typing.Generator['libioc.events.IocEvent', None, None]:
"""
Start the jail.
Args:
quick (bool):
Skip several operations that are not required when a jail
was... | |
irc.reply(text)
unmorse = wrap(unmorse, ['text'])
@internationalizeDocstring
def morse(self, irc, msg, args, text):
"""<text>
Gives the Morse code equivalent of a given string.
"""
L = []
for c in text.upper():
L.append(self._morseCode.get(c, c))
irc.reply(' '.join(L))
morse = wrap(morse, ['text'])
@inte... | |
"""
This script contains code to estimate an appropriate initial condition of the spatial COVID-19 SEIQRD model on March 15th-17th, 2020.
Two initial conditions are saved: 1) for the "virgin" model (COVID19_SEIQRD_spatial) and 2) for the stratified vaccination model (COVID19_SEIQRD_spatial_stratified_vacc)
The model i... | |
is degenerate."))
return "elements", data
node = self.elem_branch.add(shape=circ, type="elem ellipse")
node.stroke = Color("black")
self.set_emphasis([node])
node.focus()
if data is None:
data = list()
data.append(node)
return "elements", data
@self.console_argument("x_pos", type=Length)
@self.console_argum... | |
import os
import shutil
import datetime
import random
from pathlib import Path
from midiutil import MIDIFile
class FileHandler(object):
"""
Note Notation:
List of lists of lists, each inner-most list in the form (Midi Note Number, Duration as 'beat').
The next inner-most lists are considered 'NoteUnits', or gro... | |
# region [Imports]
# * Standard Library Imports ---------------------------------------------------------------------------->
import os
import asyncio
from io import BytesIO
from pathlib import Path
from datetime import datetime
from tempfile import TemporaryDirectory
from textwrap import dedent
# * Third Party Impo... | |
"""
Copyright (c) 2019-2022 Intel Corporation
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 writin... | |
"""API for console manipulation using ANSI Escape sequences in Python.
"""
import logging
from itertools import chain
from pyansiescapes.enums import ANSICommands, TextAttributes, ColorDrawingLevel, Colors
from pyansiescapes import utils
import pyansiescapes._types as t
import emojis
_logger = logging.getLogger(__file... | |
not None \
and elapsed_time + 5 / 60 > args.max_inference_hours:
train_time = (time.time() - epoch_start_time) / 60. / 60. # in hours
prev_partial_epoch = getattr(args, "partial_epoch", 0.)
logger.info(f"Epoch {epoch - 1 + prev_partial_epoch:.2f} batch {batch_num} of "
f"{len(t_batch)} ({partial_epoch*100:.1f}%) q... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.