input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
f"{cls.__name__}_{t_names}"
key = "key"
parameters0 = f"key:{t[0].__name__}, "
if len(t) == 2:
parameters = parameters0 + f"value:{t[1].__name__}"
value = "value"
else:
parameters = parameters0 + ", ".join(f"value{i}:{ti.__name__}" for i, ti in enumerate(t[1:], 1))
value = "(" + ", ".join(f"value{i}" for i in r... | |
<reponame>wwxFromTju/hierarchical-marl
"""Implementation of hierarchical cooperative multi-agent RL with skill discovery.
High-level Q-function Q(s,\zbf) is trained with QMIX (with decentralized execution)
using global environment reward
Low-level policies are either
1. parameterized as policy networks pi(a^n|o^n,z^... | |
import optparse
import time
import numpy as np
from numpy.lib import recfunctions # to append fields to rec arrays
import matplotlib.pyplot as plt
from matplotlib.ticker import AutoMinorLocator
from matplotlib.offsetbox import AnchoredText
from matplotlib.backends.backend_pdf import PdfPages
import katpoint
from katp... | |
<reponame>tpeng/magnitude
#!/usr/bin/env python
# See the accompanying LICENSE file.
import os
import sys
import shlex
import glob
import re
import time
import zipfile
import tarfile
try:
if not os.environ.get("APSW_FORCE_DISTUTILS"):
from setuptools import setup, Extension, Command
else:
raise ImportError()
exc... | |
from collections import OrderedDict
import cPickle
import os
def prototype_state():
state = {}
# ----- CONSTANTS -----
# Random seed
state['seed'] = 1234
# Logging level
state['level'] = 'DEBUG'
# Out-of-vocabulary token string
state['oov'] = '<unk>'
# These are end-of-sequence marks
state['end_sym_utt... | |
<reponame>gnosis/gnosisdb<gh_stars>10-100
from time import mktime
from django.conf import settings
from django.test import TestCase
from django_eth_events.utils import normalize_address_without_0x
from django_eth_events.web3_service import Web3Service, Web3ServiceProvider
from eth_tester import EthereumTester
from res... | |
<gh_stars>1-10
# This file was generated automatically by generate_protocols.py
from nintendo.nex import common, streams
import logging
logger = logging.getLogger(__name__)
class ClearCondition:
NORMAL = 0
COLLECT_COINS = 4116396131
KILL_SKIPSQUEAKS = 4042480826
class CourseDifficulty:
EASY = 0
STANDARD = 1... | |
axis, but stops moving towards
the collision. Then update the robot's position. If the robot isn't receiving input to move
forward, decelerate velocities.
"""
# Check if a collision has occurred, and zero the velocity axis associated with it.
_collision_side = self.collision_detector()
self.collision_list.append(... | |
<gh_stars>1-10
# 作者:Forec
# 最后修改日期:2016-12-20
# 邮箱:<EMAIL>
# 关于此文件:此文件包含了服务器除认证外的所有的界面入口,包括首页、云盘界面、
# 文件操作、下载、聊天模块、管理员界面等。
# 蓝本:main
import os, random, shutil, zipfile, os.path
from config import basedir
from datetime import datetime, timedelta
from sqlalchemy import or_, and_, text
from flask import render... | |
<reponame>robinson96/GRAPE<gh_stars>1-10
import os
import subprocess
import utility
import ConfigParser
import grapeConfig
import StringIO
class GrapeGitError(Exception):
# arguments must be kept as keywords to allow pickling
def __init__(self, errmsg='', returnCode=-1, gitOutput='', gitCommand='', cwd=os.getcwd())... | |
<reponame>Tanneguydv/Pythonocc-nodes-for-Ryven
from ryven.NENV import *
widgets = import_widgets(__file__)
from OCC.Core.ChFi2d import \
ChFi2d_AnaFilletAlgo
from OCC.Core.gp import \
gp_Pnt, \
gp_Vec, \
gp_Dir, \
gp_Ax2, \
gp_Pln, \
gp_Trsf, \
gp_DX, \
gp_DY, \
gp_DZ, \
gp_Circ, \
gp_XOY, \
gp_YOZ, \
... | |
while True:
element = route_prefix_parts[index]
parts.append(element)
index += 1
if index == limit:
break
parts.append('/')
continue
def _rebuild_path_parameter(parameter_type, parameter_name):
"""
Rebuilds a typed path part from it's type identifier and from it's name.
Parameters
----------
parameter_... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from itertools import combinations
from collections import Counter
import os.path
import numpy as np
from scipy.stats import mode
from scipy.linalg import orth
from numpy.linalg import svd, lstsq, inv, pinv, multi_dot
from scipy.special import logit
from sklearn.b... | |
"servers_update_addresses")})
def test_instance_details_volume_sorting(self):
server = self.servers.first()
volumes = self.volumes.list()[1:3]
api.nova.server_get(IsA(http.HttpRequest), server.id).AndReturn(server)
api.network.servers_update_addresses(IsA(http.HttpRequest),
IgnoreArg())
api.nova.instance_volume... | |
return np.argmin(np.abs(converted_dataset['lev'] - pres).values)
def convert_lev_to_pres(dataset, pmid, pedge, lev_type='pmid'):
"""
Convert lev dimension to pressure in a GEOS-Chem dataset
Args:
dataset: xarray Dataset
GEOS-Chem dataset
pmid: np.array
Midpoint pressure values
pedge: np.array
Edge pressure ... | |
<gh_stars>0
"""
This is the script of modality prediction of all 4 subtasks
Dependencies:
pip: scikit-learn, anndata, scanpy, numpy
"""
import os
import sys
import logging
import anndata as ad
import numpy as np
import torch
from torch.utils.data import DataLoader
from scipy.sparse import csc_matrix
from sklearn.dec... | |
== 2 else self.username)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def validate(self):
return
def __repr__(self):
L = ['%s=%r' % (key, value)
for key, value in self.__dict__.items()]
return '%s(%s)' % (self.__class__.__name__, ', '.join(L))
def __eq__(self, other):
return isinsta... | |
#!/usr/bin/env python3
import argparse
import base64
import contextlib
import io
import json
import logging
import os
import sys
import tarfile
import time
import docker
from ..common import PatchStatus
from ..database import Db
l = logging.getLogger("patchbot")
def bin_diff(byte_arr1, byte_arr2):
byte_diff = 0
... | |
"<< miljardiin[ >>];",
"(2000000000, 999999999999)": "<< miljardiin[ >>];",
"(1000000000000, 1999999999999)": "<< biljoonaan[ >>];",
"(2000000000000, 999999999999999999)": "<< biljoonaan[ >>];",
"(1000000000000000000, 'inf')": "=#,##0=;"
},
"%spellout-cardinal-illative-plural": {
"0": "nolliin;",
"1": "yksiin;"... | |
install pysam on your system. Please install LLVM compiler first."
doInstall=False
if doInstall:
# dont set static building libs on OSX, sseems to cause compile issues for jellyfish
os.environ["CFLAGS"] = oldCFlags
os.environ["CPPFLAGS"] = oldCPPFlags
os.environ["CXXFLAGS"] = oldCXXFlags
os.environ["LDFLAGS"] = ... | |
which will usually be the case when respective field in database is blank
# these are hopefully legacy cases which are from before this extensive check was introduced (13/01/2017)
advice = ( 'The pandda model of '+xtal+' was changed, but it was already refined! '
'This is most likely because this was done with an ol... | |
#
# Copyright <NAME> 2009
#
"""
Code to implement a test harness.
"""
import corebio.seq_io.fasta_io, os, logging, hmm, cPickle, numpy as N, sys, numpy.random as R
from hmm.pssm import seq_to_numpy, numpy_to_seq
from optparse import OptionParser
from cookbook.dicts import DictOf
from itertools import imap, cycle
_l... | |
<reponame>KriSun95/sunxspex
"""
The following code is for instrument specific classes each using their own methods to create and edit their `_loaded_spec_data` attrbutes.
Tips that I have been following:
* None of the instrument loaders should have public attributes; ie., all attributes should be preceded with `_`
*... | |
<reponame>temelkirci/Motion_Editor<filename>venv/Lib/site-packages/astropy/units/core.py
# -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Core units classes and functions
"""
import inspect
import operator
import textwrap
import warnings
import numpy as np
from ..utils.de... | |
<reponame>jlevy44/JoshuaTree2<filename>scaffolding_tool_bin/old_scripts/genomeScaffolding.py
import subprocess, os, sys
from collections import defaultdict, OrderedDict
import numpy as np
from multiprocessing import Pool, Queue, Process
from threading import Thread
import subprocess,shutil
from pybedtools import BedToo... | |
"b", "c"),
new_field_name="new_field",
expected={"a": {"b": {"c": [7, 3, 5]}, "new_field": [7, 3, 5]}}),
dict(
testcase_name="repeated_repeated_scalar_repeated2",
st=[{"a": [{"b": {"c": [[7, 3], [17]]}}, {"b": {"c": [[3, 13]]}}]},
{"a": [{"b": {"c": [[5, 15]]}}]}],
source_path=("a", "b", "c"),
new_field_name="n... | |
stored in a ValueMap
process.PassingCicVeryLoose = cms.EDProducer("BtagGsfElectronSelector",
input = cms.InputTag( ELECTRON_COLL ),
selection = cms.InputTag('eidVeryLoose'),
cut = cms.double(14.5) ### 15== passing all iso,id,tip cuts
)
process.PassingCicLoose = process.PassingCicVeryLoose.clone()
process.PassingCicL... | |
* a / 27.0 - a * b / 3.0 + c
det = q * q / 4.0 + p * p * p / 27.0
# The model changes behaviours when the discriminant equates to zero. From this point we need a different root
# resolution mechanism.
sol = np.zeros(det.shape)
mask = det >= 0
sqrt_det = np.sqrt(det[mask])
t1 = -q[mask] * 0.5 + sqrt_det
t2 = -... | |
hd == 0:
cols = cols + ['zeroHdistance_genes']
writing_data = writing_data + [gene]
if hd < hd_2:
cols = cols + ['below2Hdistance_genes']
writing_data = writing_data + [gene]
if hd < hd_3:
cols = cols + ['below3Hdistance_genes']
writing_data = writing_data + [gene]
self.barcoded_fov_df.loc[self.barcoded_fov... | |
<filename>02_neural_networks/2-6_sentiment_analysis/2-6_orig/network_v4.py
'''
NOTE: this is a reduced project file, it does not contain all the steps from the nanodegree lecture
'''
######### parameters
min_count = 100
polarity_cutoff = 0.2
####### Lesson: Curate a Dataset
def pretty_print_review_and_label(i):
p... | |
<reponame>phistuck/chromium-dashboard
# TODO(ericbidelman): generate this file from
# http://src.chromium.org/viewvc/blink/trunk/Source/core/frame/UseCounter.cpp
CSS_PROPERTY_BUCKETS = {
# 1 was reserved for number of CSS Pages Visited
2: 'color',
3: 'direction',
4: 'display',
5: 'font',
6: 'font-family',
7: 'f... | |
value of the nematic order parameter (between 0 and 1), or number of neighbors
"""
# local nematic order parameter: average 1/2 (3 cos^2(theta) - 1), where theta = angle diff btw neighbors
p1 = self.particles[type][layer][id]
pos1 = self.trajectory[time][type][layer][id]
if not pos1:
return 0
if pos1.nematic:
... | |
pattern.match(unicode_desc)
# Grapheme's unicode description is non-standard
if(not match_obj):
# Underscore, dash, hastag have special meaning
if(graph in ("_", "-", "#")):
graph_dict = {
'CHAR_TYPE': 'LINK',
'SYMBOL': graph,
'NAME': graph
}
# The grapheme is whitespace
elif(unicode_desc in ("ZERO WIDTH S... | |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from builtins import int
from builtins import range
from past.builtins import basestring
from builtins import object
from ctypes import c_char, c_c... | |
interpreted as face-relative and each pair of entries
will be taken as a (face, triangle) pair to be considered for
intersection. Thus, the face-triangle pair (10, 0) means the first
triangle on face 10. If neither faceIds nor triIds is given, then
all face-triangles in the mesh will be considered.
The maxParam ... | |
HTTPHeader(HelmYaml):
"""
:param name: The header field name
:param value: The header field value
"""
def __init__(self, name: str, value: str):
self.name = name
self.value = value
class HTTPGetAction(HelmYaml):
"""
:param path: Path to access on the HTTP server.
:param port: Name or number of the port to ... | |
<filename>download/xml_pickle/xml_pickle-0.30.py
"""Store Python objects to (pickle-like) XML Documents
Note 0:
See http://gnosis.cx/publish/programming/xml_matters_1.txt
for a detailed discussion of this module.
Note 1:
The XML-SIG distribution is changed fairly frequently while
it is in beta versions. The cha... | |
with self.assertRaises(InvalidSpec) as cm:
specs_to_ir([('test.stone', text)])
self.assertEqual(
"Symbol 'S' already defined (test.stone:3).",
cm.exception.msg)
self.assertEqual(cm.exception.lineno, 6)
# Test name from two specs that are part of the same namespace
text1 = textwrap.dedent("""\
namespace test
... | |
'.matplotlib')
if os.path.exists(p):
if not _is_writable_dir(p):
raise RuntimeError("'%s' is not a writable dir; you must set %s/.matplotlib to be a writable dir. You can also set environment variable MPLCONFIGDIR to any writable directory where you want matplotlib data stored "% (h, h))
else:
if not _is_writable... | |
other services.
:param pulumi.Input[Union[str, 'MoveCost']] default_move_cost: Specifies the move cost for the service.
:param pulumi.Input[int] min_instance_count: MinInstanceCount is the minimum number of instances that must be up to meet the EnsureAvailability safety check during operations like upgrade or deactiv... | |
<filename>examples/file_proof/file_proof.py<gh_stars>10-100
#!/bin/sh
""":" .
exec python "$0" "$@"
"""
# -*- coding: utf-8 -*-
"""
Copyright (c) 2017 beyond-blockchain.org.
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 ... | |
this code on Pangeo I needed to NOT flip the elevation values here and then switch the bounding box y value order
# Not entirely sure what's going on, but need to be aware of this!!
# print("Note: check for proper orientation of results depending on compute environment. Pangeo results were upside down.")
elev_copy =... | |
from __future__ import annotations
import argparse
import http.server
import json
import threading
from pathlib import Path
from typing import List, Optional, Any
import jinja2
import requests_cache
ENCODING = "utf-8"
URL = "url"
LEVELS = "levels"
CACHE = "cache"
URL_DEFAULT = "https://hub.zebr0.io"
LEVELS_DEFAULT... | |
<reponame>dani3l125/torchprune<gh_stars>10-100
"""A module for all helper functions pertaining to files and parameters."""
import copy
import os
import pathlib
import datetime
import time
import re
import torch
import yaml
import numpy as np
import matplotlib.colors as mcolors
def write_parameters(param, dir, file="... | |
any point before the SSH transport layer
has finished key exchange (ie, gotten to the point where we may attempt
to authenticate), the L{Deferred} returned by
L{SSHCommandClientEndpoint.connect} fires with a L{Failure} wrapping
the reason for the lost connection.
"""
endpoint = SSHCommandClientEndpoint.newConnect... | |
tentar criar arquivo, sha1 nao confere. arquivo:'+File['name'])
consoleShow( _T+'Termino do processo...'+_N, None)
def opt_install_obj ():
execute = consoleShow(_A+'Efetuar as includes para objeto utilizado'+_N, 'YesOrNo')
if execute:
installObjInFiles()
consoleShow( _T+'Fim das alterações...'+_N, None)
... | |
# \brief Gets whether the narrowband DDCs on the radio are tunable.
#
# \copydetails CyberRadioDriver::IRadio::isNbddcTunable()
@classmethod
def isNbddcTunable(cls):
return False if cls.nbddcType is None else cls.nbddcType.tunable
##
# \brief Gets whether the narrowband DDCs on the radio have selectable
# sou... | |
' (c) NOT including this file ... ', iFilename, aTokens[iFilename], iBarcode, aTokens[iBarcode], iYes, aTokens[iYes], zPlat, otherInfo
includeFlag = 0
# if this is the SNP platform, we're only keeping tumor samples ...
# (which means they can be 01, 02, 06 ... I think anything that starts with a '0' basically)
if ... | |
import time
import json
import pandas as pd
import numpy as np
from sklearn import preprocessing
from sklearn.cluster import KMeans
from sklearn import metrics
import seaborn as sns
import matplotlib.pyplot as plt
from itertools import cycle
import apr_constants
import common_functions
def plot_correlation_matr... | |
import numpy as np
from pathlib import Path
import os
import h5py
import json
import pyHMT2D
from ..__common__ import gVerbose
import logging
class Calibrator(object):
"""Calibrator class to handle calibration process
A calibrator is constructed from its configuration file in JSON format. The configuration
spe... | |
<filename>preprocessing/fap.py
# -*- coding: utf-8 -*-
import numpy as np
import scipy.signal
from scipy.signal import peak_widths
import matplotlib.pyplot as plt
import utils
import peakutils
import pandas as pd
from sklearn.preprocessing import StandardScaler, MinMaxScaler
def faps_slide_subplot(faps_feat_df,sbj,la... | |
"vacation_correction" only)
User is allowed to create contract_type (Create for "contract_type" only)
User is allowed to create leave_submission (Create for "leave_submission" only)
User is allowed to create vacation_correction (Create for "vacation_correction" only)
User is allowed to edit contract_type (Edit for ... | |
'''
Classes for extracting "decodable features" from various types of neural signal sources.
Examples include spike rate estimation, LFP power, and EMG amplitude.
'''
import numpy as np
import time
from scipy.signal import butter, lfilter
import math
import os
import nitime.algorithms as tsa
from riglib.ripple.pyns im... | |
the first actual value in the score tuples
# produced by the recommender (note that hybrid recommenders use the first
# position to indicate the algorithm number)
if recommender.is_hybrid():
start_index = 1
else:
start_index = 0
recommendations = recommender.recommend(100)
nose.tools.ok_(len(recommendations) >... | |
import ast
import collections
import contextlib
import inspect
import numpy
from ..utils.list import EventedList
from ..utils.event import EmitterGroup, Event
class RunList(EventedList):
"""
A list of BlueskyRuns.
"""
__slots__ = ()
def __contains__(self, run):
uid = run.metadata["start"]["uid"]
for run_ i... | |
# -*- coding: utf-8 -*-
"""
Copyright (c) Microsoft Open Technologies (Shanghai) Co. Ltd. All rights reserved.
The MIT License (MIT)
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 res... | |
"""
Python job scheduling for humans.
An in-process scheduler for periodic jobs that uses the builder pattern
for configuration. Schedule lets you run Python functions (or any other
callable) periodically at pre-determined intervals using a simple,
human-friendly syntax.
Inspired by <NAME>' article "Rethinking Cron" ... | |
($lib.layer.get().pack())')
size = info.get('totalsize')
self.gt(size, 1)
# Verify we're showing actual disk usage and not just apparent
self.lt(size, 1000000000)
# Try to create an invalid layer
mesgs = await core.stormlist('$lib.layer.add(ldef=$lib.dict(lockmemory=(42)))')
# Create a new layer
newlayr = aw... | |
'''
CHypre (Complex Hypre)
CHypreVec : ParVector
CHypreMat : ParCSR
container object to support complex using
real value hypre
it should work with pure real or pure imaginary
case too.
it follows the mathod naming convetion used
in scipy.sparse. However, since it inherits the list
object, __setitem__ can ... | |
zone
Parameters
-----------
p1 : np.array
p2 : np.array
tol :
al1 :
al2 :
quadsel : 0 all quadrant
2 1
3 4
Returns
-------
edgelist
"""
x = self.pt[0, :]
y = self.pt[1, :]
#
# selection du quadran
#
if (quadsel == 0):
u0 = np.arange(self.Np)
if (quadsel == 1):
u0 = np.nonzero((y > p1[1]) & ... | |
-> edgedb.AsyncIOConnection:
conn_args = self.get_connect_args(**kwargs)
return await tconn.async_connect_test_client(**conn_args)
async def connect_test_protocol(self, **kwargs):
conn_args = self.get_connect_args(**kwargs)
conn = await test_protocol.new_connection(**conn_args)
await conn.connect()
return conn
... | |
#!/usr/bin/python
# -----------------------------------------------------------------------------
#
# Copyright 2013-2019 lispers.net - <NAME> <<EMAIL>>
#
# 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 ... | |
from tkinter import *
from tkinter import ttk
from pickle import dump, load
from PIL import Image, ImageTk
from cryptography.fernet import Fernet
import pyperclip as p
from random import randint
from os import remove, rename, popen
from time import ctime
import pyqrcode
import png
import webbrowser
def copied_display... | |
) -> List[DockerParameter]:
"""Formats extra flags for running docker. Will be added in the format
`["--%s=%s" % (e['key'], e['value']) for e in list]` to the `docker run` command
Note: values must be strings
:param with_labels: Whether to build docker parameters with or without labels
:returns: A list of paramet... | |
import matplotlib.pyplot as plt
import numpy as np
import os
from constants import OUTPUT_DIR, COLOURS_DARK_BLUE, COLOURS_DARK_BLUE_YELLOW, X_DARK, Z_DARK, BLUE
from data_io import read_matrix_data_and_idx_vals, read_mfpt_heuristic, read_fpt_and_params, read_varying_mean_sd_fpt_and_params
from firstpassage import fpt_... | |
TOOLBAR_BOTTOM = 2
class ButtonsWidget(QWidget):
buttons_mode = ButtonsMode.INTERNAL
qt_css_class = "ButtonsWidget"
qt_css_extra = ""
def __init__(self) -> None:
super().__init__()
self.buttons: List[QAbstractButton] = []
def resizeButtons(self) -> None:
frame_width = self.style().pixelMetric(QStyle.PixelM... | |
for el in remove_list:
equal_imm_blocks_present_for_migration.remove(el)
# iterate through the blocks and find the best one
for block_to_migrate_to in equal_imm_blocks_present_for_migration:
# skip yourself
if block_to_migrate_to == hot_blck_synced:
continue
block_metric_attr = self.get_block_attr(selected_met... | |
self.draw_groupid()
"""
把当前处理好的结果存储下来,并打开下一张图片和加载相应的检测信息
"""
def open_next(self, event):
if self.cur < len(self.imageList) - 1:
self.save()
self.clear_bbox()
self.cur += 1
self.load_image(self.imageDirPathBuffer + '/' + self.imageList[self.cur], event)
else:
self.save()
messagebox.showinfo(title='',message... | |
map_root['id'], map_version_id, layer_id], GetXmlFeatures)
except (SyntaxError, urlfetch.DownloadError):
pass
return features
def SetDistanceOnFeatures(features, center):
for f in features:
f.distance = EarthDistance(center, f.location)
def FilterFeatures(features, radius, max_count):
# TODO(kpy): A top-k sel... | |
import json
import struct
import os
import sys
import base64
import math
import maya.cmds
import maya.OpenMaya as OpenMaya
import shutil
import time
try:
from PySide.QtGui import QImage, QColor, qRed, qGreen, qBlue, QImageWriter
except ImportError:
from PySide2.QtGui import QImage, QColor, qRed, qGreen, qBlue, QImage... | |
<reponame>daukantas/REACT-CODE-_ANALYZING-
# -*- coding: utf-8 -*-
import numpy as np
from scipy.sparse import csr_matrix
import networkx as nx
from scipy.optimize import brentq,bisect
from sys import version_info
from scipy import __version__ as vers_scipy
from warnings import warn
class NetworkFormatError(Except... | |
<reponame>yrtf/QuantLib-SWIG<filename>Python/test/fdm.py<gh_stars>100-1000
"""
Copyright (C) 2020 <NAME>
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
... | |
import os
import glob
import torch
import random
import numpy as np
from tqdm import tqdm
import torch.nn as nn
from PIL import Image
from skimage import io
import torch.optim as optim
from torchvision import models
import torch.nn.functional as F
import pydensecrf.densecrf as dcrf
from torchvision import transforms
fr... | |
<filename>code/train_models.py
dev = False
## command-line args
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('-r', dest='resume', type=int)
parser.add_argument('-e', dest='epochs', type=int, default=10)
parser.add_argument('-g', dest='gpu', type=int, defau... | |
<filename>setup/gcp_setup_runner.py
#!/usr/bin/env python
#
# Copyright 2018 - The Android Open Source Project
#
# 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/licens... | |
<reponame>jfigui/pyrad
"""
pyrad.graph.plots_vol
=====================
Functions to plot radar volume data
.. autosummary::
:toctree: generated/
plot_ray
plot_ppi
plot_ppi_map
plot_rhi
plot_bscope
plot_time_range
plot_fixed_rng
plot_fixed_rng_span
plot_fixed_rng_sun
plot_cappi
plot_traj
plot_rhi_contour... | |
"""Testing creation and manipulation of DataFrameSchema objects."""
# pylint: disable=too-many-lines,redefined-outer-name
import copy
from functools import partial
from typing import (
Any,
Callable,
Dict,
Iterable,
List,
Optional,
Tuple,
Type,
Union,
)
import numpy as np
import pandas as pd
import pytest
f... | |
whole number of samples so we have to interpolate.
xp = sample_interval * np.arange(count)
rsf = int(count * resample_factor[sample_interval])
yp = resample_interval * np.arange(rsf)
interp_f = interp1d(xp, this_data[:,0:count], kind='previous', axis=1,
bounds_error=False, fill_value=np.nan, assume_sorted=True)
t... | |
+ str(self.constant_repulsion) + '\n')
log.write(' -- VELOCITY WEIGHT COEFFICIENT: ' + str(self.VELOCITY_WEIGHT) + '\n')
log.write(' -- BOUNDARY REPULSION: ' + str(self.BOUNDARY_REPULSION) + '\n')
log.write(' -- AGING COEFFICIENT: ' + str(self.LOSING_CONFIDENCE_RATE) + '\n')
log.write(' -- INPUT TIME: ' + ... | |
<filename>core/modules/nginx.py
# -*- coding: utf-8 -*-
#
# Copyright (c) 2017 - 2019, doudoudzj
# Copyright (c) 2012 - 2016, VPSMate development team
# All rights reserved.
#
# InPanel is distributed under the terms of the (new) BSD License.
# The full license can be found in 'LICENSE'.
'''Module for Nginx M... | |
"pinhole"
dist_model = "radtan4"
params = np.block([*proj_params, *dist_params])
cls.cam1 = camera_params_setup(1, res, proj_model, dist_model, params)
cls.cam1.fix = True
# Setup camera extrinsics
# -- cam0
T_BC0 = cls.dataset.cam0_data.config.T_BS
cls.cam0_exts = extrinsics_setup(T_BC0)
cls.cam0_exts.fix = ... | |
#!/usr/bin/env python
"""
<Program Name>
test_util.py
<Author>
<NAME>.
<Started>
February 1, 2013.
<Copyright>
See LICENSE for licensing information.
<Purpose>
Unit test for 'util.py'
"""
# Help with Python 3 compatibility, where the print statement is a function, an
# implicit relative import is invalid, an... | |
one=0)
self.redis.zadd('foo', two=0)
self.redis.zadd('bar', one=1)
self.redis.zadd('bar', two=2)
self.redis.zadd('bar', three=3)
self.redis.zunionstore('baz', ['foo', 'bar'], aggregate='MAX')
self.assertEqual(self.redis.zrange('baz', 0, -1, withscores=True),
[(b'one', 1), (b'two', 2), (b'three', 3)])
def test_... | |
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2021 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide :pep:`484`- and :pep:`585`-compliant **dual type hint utilities**
(i.e., callables generically applicable to both :pep:`484`- and
:pep:`585`-com... | |
at which `value` should be inserted into
`array`.
Example:
>>> sorted_index([1, 2, 2, 3, 4], 2)
1
.. versionadded:: 1.0.0
.. versionchanged:: 4.0.0
Move iteratee support to :func:`sorted_index_by`.
"""
return sorted_index_by(array, value)
def sorted_index_by(array, value, iteratee=None):
"""This method ... | |
from __future__ import unicode_literals
from future.builtins import int, str
from json import dumps
from django.contrib.auth.decorators import login_required
from django.contrib.messages import info
from django.urls import reverse
from django.db.models import Sum
from django.http import Http404, HttpResponse
from dja... | |
_beamformer.delete_DOAEstimatorSRPDSBLAPtr
__del__ = lambda self: None
def next(self, frame_no=-5):
return _beamformer.DOAEstimatorSRPDSBLAPtr_next(self, frame_no)
def reset(self):
return _beamformer.DOAEstimatorSRPDSBLAPtr_reset(self)
def set_array_geometry(self, positions):
return _beamformer.DOAEstimatorSR... | |
"""Roles utils"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import re
from itertools import chain
from sqlalchemy import func
from tornado.log import app_log
from . import orm
from . import scopes
def get_default_roles():
"""Returns:
default roles (list):... | |
relative to the root of the source directory."""
return self.__name
def dot(self, marks):
"""Print a dot representation of this node build graph."""
if self in marks:
return True
marks[self] = None
print(' node_%s [label="%s"]' % (self.uid, self.__name))
if self.builder is not None:
if self.builder.dot(marks)... | |
# Copyright 2019 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd
"""Unittests for monorail.feature.alert2issue."""
from __future__ import print_function
from __... | |
# Copyright 2019 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, soft... | |
""" This module implements the definition of the different configuration.
NOTE: Make sure to run the function 'save_common_default_template'
to save the default config after altering CompleteConfiguration.
Write the default raw configuration template
>>> import muteria.configmanager.configurations as mcc
>>> mcc.s... | |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'commu... | |
state with a Boolean statement later on.'''
last_epoch = self.data[self.data.State == 1].Epoch.max()
if time_dependent_covariates == False:
'''This option will produce data appropriate for construction of
Nelson-Aalen cumulative incidence functions and to produce the state
tables.
This option is not appropriate... | |
None and tail > 5000:
table = html.Div([
html.H5(children='Please enter number less than 5000 into tail',
style={'color': 'red', 'font-size': '20px', 'padding-left': '20px'})])
elif str(type(head)) == "<class 'float'>":
table = html.Div([
html.H5(children='Please enter positive integer into head',
style={'color'... | |
that the wildcards are matched against the file with absolute path, so to
# exclude all test directories for example use the pattern */test/*
EXCLUDE_PATTERNS =
# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names
# (namespaces, classes, functions, etc.) that should be excluded from the
# output.... | |
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['Basic Authentication', 'Token Authentication'] # noqa: E501
response_type = 'FlowLog'
if 'response_type' in kwargs:
response_type = kwargs['response_type']
return self.... | |
## hexcontrol is a class whose objects have methods for working with a completed hex tree
from __future__ import print_function
import world
import fileinput
import hexagon
import world
import math
import pylab
import os
import random
import numpy
class hexcontrol:
def __init__(self,hexagon,my_wo... | |
(`pulumi.Input[str]`) - (string)
* `domainId` (`pulumi.Input[str]`) - Required if `domain_name` not provided. (string)
* `domainName` (`pulumi.Input[str]`) - Required if `domain_id` not provided. (string)
* `password` (`pulumi.Input[str]`) - Registry password (string)
* `region` (`pulumi.Input[str]`) - The AWS Regi... | |
self.height + self.SPACER)
qp = QtGui.QPainter()
qp.begin(self.newPix)
qp.setWindow(-50, 0, self.COLUMNS * self.fontWidth, self.ROWS * self.fontHeight)
qp.drawPixmap(0, 0, self.qpix)
# self.transformationEngine.decorateText()
# highlight selected text
self.selector.highlightText()
# draw other selections
s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.