input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
node))
val = 1 - self.agent.goal_f(self.condition, state)
for i in range(len(path)):
if path[i][1] is not None:
path[i][1].update_value(val)
path[i][0].success = max(val, path[i][0].success)
path[i][0].discount = 0.9**(len(path)-i-1)
path = [step[0] for step in path]
if len(path) and val > 1. - 1e-3:
print(('\... | |
the array of expected galaxy counts per bin.
SN_dist -- comoving distance to SN along line of sight.
OM -- matter density parameter. Defaults to 0.27.
"""
H0 = 1000 * 100 * h # km/s/Gpc
coeff = 3.0 * H0 ** 2 * OM / (2.0 * c ** 2)
sf_arr = 1.0 / (1.0 + zs)
k_i = coeff * chis * chi_widths * (SN_dist - chis) / SN_d... | |
shutil.rmtree('./index', ignore_errors=True)
os.mkdir('./index')
genoIndex = '%s/index/%s' % (os.getcwd(),fastaclean.rpartition('/')[-1].rpartition('.')[0]) ## Can be merged with genoIndex from earlier part if we use bowtie2 earlier
# genoIndex = './index/%s' % (fastaclean.rpartition('/')[-1].rpartition('.')[0]) ##... | |
#!/usr/bin/env python
"""lipid-martini-itp.py creates a customized Martini lipid topologies, use lipid-martini-itp.py -h for description"""
__author__ = "<NAME>, and <NAME>"
__status__ = "Development"
__version__ = "0.5"
__email__ = "<EMAIL>"
import sys,math
# Very simple option class
class Option:
def __init__(se... | |
WC("b", S(1)) * acoth(x_ * WC("c", S(1)))) ** WC("n", S(1))
/ (x_ * sqrt(d_ + x_ ** S(2) * WC("e", S(1)))),
x_,
),
cons2,
cons3,
cons8,
cons29,
cons50,
cons1739,
cons150,
cons1740,
)
rule6462 = ReplacementRule(pattern6462, replacement6462)
pattern6463 = Pattern(
Integral(
(WC("a", S(0)) + WC("b", S(1))... | |
<gh_stars>100-1000
import numpy as np
import math
# from mxnet import nd
from mxnet.gluon import nn
class Augmentation(nn.HybridBlock):
def __init__(self, angle_range, zoom_range, translation_range, target_shape, orig_shape, batch_size,
aspect_range = None, relative_angle = 0, relative_scale = (1, 1), relative_tran... | |
from collections import defaultdict
import numpy as np
import torch
from pytorch_points.network.operations import faiss_knn, dot_product, batch_svd, ball_query, group_knn
from pytorch_points.utils.pytorch_utils import save_grad, linear_loss_weight
from pytorch_points.network.model_loss import nndistance, labeled_nndist... | |
self.k.vehicle.get_position(veh_id)
dist = edge_len - relative_pos
return dist
def _convert_edge(self, edges):
"""Convert the string edge to a number.
Start at the bottom left vertical edge and going right and then up, so
the bottom left vertical edge is zero, the right edge beside it is 1.
The numbers are as... | |
import math
from collections import Counter, defaultdict
from datetime import datetime
import networkx as nx
import numpy as np
import pandas as pd
import plotly.graph_objects as go
import pyproj
from numpy import mean, nanmean
from cognite.power.data_classes import PowerAssetList
# unified plotting colors
_MARKER_E... | |
""" library to take autodiff and execute a computation graph """
from __future__ import absolute_import
from .BatchNorm import Batch_NormalizationOp
import numpy as np
from scipy.sparse import spmatrix, coo_matrix
from .. import ndarray
from .._base import DNNL_LIB
from ..cpu_links import array_set as cpu_array_set
fro... | |
# constants
PROBE_SPACING = 100000
MAX_HEIGHT = 4
ABERRATION_HEIGHTS = {
'DEL': -1.0,
'DUP': +1.0,
'TDUP': +1.5,
'IDUP': +0.5,
'INV': -0.5,
'INS': -1.5,
'BND': -2.0,
'TRA': -2.0,
}
# Hard-coded data about GRCh37 follows.
# Whenever GRCh38 becomes relevant, use external .fai and .bed files instead.
CONTIG_LENG... | |
try:
self._Reset()
if self._Scanbeam is None:
return True
botY = self._PopScanbeam()
while True:
self._InsertLocalMinimaIntoAEL(botY)
self._HorzJoins = None
self._ProcessHorizontals()
topY = self._PopScanbeam()
if not self._ProcessIntersections(botY, topY):
return False
self._ProcessEdgesAtTopOfScanbeam(top... | |
#!/usr/bin/env python3
import re
import sys
import os
import argparse
import logging
import itertools
import collections.abc
from collections import defaultdict
from lxml import etree
# Typing
import io
from typing import Sequence, Mapping, Iterator, Generic, AbstractSet, Callable
from typing import Any, List, Tuple... | |
len(self._group[name]) > 0:
if empty_only:
raise ValueError(f"Cannot remove non-empty group '{name}'.")
else:
print("Warning: Group to remove is not empty.")
self._group.pop(name)
def add_group_member(self, group, member, **kws):
"""Add a *member* to *group*, if *group* is new, add and update
*member* group on... | |
for x, y in walk_coords]
polygon = Polygon(*points, color = WHITE)
if self.color_foreground_not_background:
polygon.stroke_width = border_stroke_width
polygon.color_using_background_image(self.background_image_file)
total_run_time = len(points) * self.step_run_time
polygon_anim = ShowCreation(polygon, run_time = ... | |
journal = {CoRR},
volume = {abs/1903.04561},
year = {2019},
url = {http://arxiv.org/abs/1903.04561},
archivePrefix = {arXiv},
eprint = {1903.04561},
timestamp = {Sun, 31 Mar 2019 19:01:24 +0200},
biburl = {https://dblp.org/rec/bib/journals/corr/abs-1903-04561},
bibsource = {dblp computer science bibliography, h... | |
#@+node:ekr.20040306214401: *5* p.Status bits
def isDirty(self): return self.v.isDirty()
def isMarked(self): return self.v.isMarked()
def isOrphan(self): return self.v.isOrphan()
def isSelected(self): return self.v.isSelected()
def isTopBitSet(self): return self.v.isTopBitSet()
def isVisited(self): return se... | |
immutable once created. No mechanism is
provided for maintaining reference consistency if data in the alignment
are modified.
An Alignment is expected to be able to generate the following:
- Seqs: Sequence objects in the alignment, can turn themselves into
strings. These are usually thought of as "rows" in an
a... | |
<filename>bolt4ds/pipe/api.py
import copy
import os
import json
import ntpath
import shutil
import warnings
import logging
# logging.basicConfig(level=logging.DEBUG)
from abc import ABC
from pathlib import Path
import jwt
import bolt4ds.collect.collect as d6tcollect
from .http_client import client as python_http_cli... | |
bin_ix: numpy.ndarray
:param events: Set of photon events to check if they are near the detector
edge.
:type events: dict
:param verbose: Verbosity level, a value of 0 is minimum verbosity.
:type verbose: int
:param valid_detrad: The radius, in degrees, beyond which an edge warning is
raised.
:type valid_... | |
from __future__ import absolute_import, division, print_function
import tensorflow.compat.v1 as tf
import numpy as np
import time
from scipy.special import comb, perm
import argparse
import json
import os
import pprint
### self-defined module
import policy
from dataloader import *
import util
import tf... | |
# Copyright 2022 The Waymo Open Dataset Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... | |
self.osid_object.genus_type == NEW_TYPE
with pytest.raises(errors.IllegalState):
self.catalog.create_assessment_part_for_assessment_part(self.form)
with pytest.raises(errors.InvalidArgument):
self.catalog.create_assessment_part_for_assessment_part('I Will Break You!')
update_form = self.catalog.get_assessment_part... | |
<gh_stars>1-10
import numpy as np
import os
import pytest
import sys
from numpy import testing
from textwrap import dedent
from moflow.mf.name import Modflow
from moflow.mf.base import MFPackage
from moflow.mf.reader import MFFileReader
if sys.version_info[0] < 3:
from io import BytesIO
StringIO = BytesIO
else:
f... | |
01, 01 )
labelFolderOfPreference = '2014_custom'
presentSubject = Subject( initials, firstName, birthdate, standardFSID, labelFolderOfPreference )
presentProject = Project( 'feedback', subject = presentSubject, base_dir = os.path.join(this_project_folder, 'data') )
sessionID = 'feedback' + presentSubject.initials
... | |
#!/usr/bin/env python
"""
`htrc.volumes`
Contains functions to retrieve volumes from the HTRC Data API.
The functions in this package will not operate unless they are
executed from an HTRC Data Capsule in Secure Mode. The module
`htrc.mock.volumes` contains Patch objects for testing workflows.
"""
from __future__ ... | |
import os
import sys
import datetime
import numpy as np
import scipy.signal
import pandas as pd
import yfinance as yf
from contextlib import contextmanager
from src.utils_date import add_days
from src.utils_date import prev_weekday
#from pandas_datareader.nasdaq_trader import get_nasdaq_symbols
ERROR_NO_MINUTE_DATA_YT... | |
With
class _SpecialFunctionParameterTokenHitTests(_SimpleWordsTokenHitTests):
def __init__(self, func_name, gjs):
self.func_name = func_name
super(_SpecialFunctionParameterTokenHitTests, self).__init__(gjs)
def __within_target_function(self, token):
if token.parent and tu.is_parenthesis(token.parent):
tgtfun... | |
<filename>guild/commands/run_impl.py
# Copyright 2017-2022 RStudio, PBC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by a... | |
_preload_content: bool, optional
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:param _request_auth: set to override the auth_settings for an a single
request; this effectively igno... | |
be trouble reconciling regional + entire extent quivers
lon_qp = model.X[::skip_interval].values
lat_qp = model.Y[::skip_interval].values
# minshaft=.2; scale=250
for idx, pressure in enumerate(model.uwnd_vwnd_pressure_lvls):
print(f'Currently on {pressure}hpa...')
fig, gs_qp = create_multisubplot_axes(optimal_... | |
<filename>monitor_ed/ed_monitor.py
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 25 18:17:13 2021
@author: AndyWang
"""
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from datetime import datetime
from time import sleep
import pandas as ... | |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Li... | |
projector.brightness() == new_brightness
# Test the edge cases
brightness = projector.brightness(100)
assert brightness == 100
assert projector.brightness() == 100
brightness = projector.brightness(30)
assert brightness == 30
assert projector.brightness() == 30
# Test out of range values
with pytest.raises(P... | |
<reponame>Kyubravo/qassim-university-cs213-project
'''
This Project is by:
Name: <NAME>
ID: 391107963
Name: <NAME>
ID: 391108011
'''
import re
import csv
import matplotlib.pyplot as plt # For graphs
import tkinter as tk # for GUI
""" import pandas as pd
import matplotlib.pyplot as plt
import numpy as np """... | |
# type: ignore
from typing import Callable, Optional, Dict, Any, List
from radixlib.parsers.base_parser import ParserBase
import radixlib as radix
import dateparser
class DefaultParser(ParserBase):
""" A default parser used to parse the responses of the gateway API into a format that is easy
to query
"""
@classme... | |
u"light nucleus: production",
u"neutralino",
u"gluino: mass",
u"parton",
u"Higgs particle: leptonic decay",
u"electron: beam",
u"polarized target",
u"potential: static",
u"glueball",
u"symmetry: O(N)",
u"eta(958)",
u"tracking detector",
u"J-PARC Lab",
u"quark: flavor: 3",
u"parton: energy loss",
u"electr... | |
dataset.lower() == "kitti":
train_dataset = gdata.SIM10kDetection(root=args.train_root,
splits=args.train_split, min_dataset_size=args.min_dataset_size)
val_dataset = gdata.SIM10kDetection(root=args.val_root,
splits=args.val_split)
if args.target_split != "":
target_dataset = gdata.SIM10kDetection(root=args.targ... | |
import json
from enum import Enum
import requests
from requests import Response
import os
from crawler.crawler_bis.fdutils import string_or_path, web_downloader
try:
from urllib import quote # Python 2.X
except ImportError:
from urllib.parse import quote # Python 3+
class FlickrPrivacyFilter(Enum):
default = u""
... | |
<filename>src/quo/layout/containers.py
"""
Container for the layout.
(Containers can contain other containers or user interface controls.)
"""
from abc import ABCMeta, abstractmethod
from enum import Enum
from functools import partial
from typing import (
TYPE_CHECKING,
Callable,
Dict,
List,
Optional,
Sequence,
... | |
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 16 17:02:37 2018
@author: shenzx
"""
from __future__ import print_function
import warnings
import shutil
from os.path import join
import numpy as np
from ase.io.abacus import write_input_stru
from ase.calculators.calculator import FileIOCalculator
# copyright... | |
import json
import logging
import re
import time
import os
from threading import Semaphore, Thread, current_thread
try:
from bs4 import BeautifulSoup
import requests
inited = 1
except ImportError:
inited = 0
try:
import vim
except ImportError:
vim = None
LC_BASE = os.environ['LEETCODE_BASE_URL']
LC_CSRF = LC_... | |
+ fns)
rejection_fraction = tns / (tns + fps)
fprs = fps / (fps + tns)
return rejection_fraction, tprs, fprs, thresholds
def disp_multiple_learn_hist(locations,losslim=None,show=True,titles=None,best_only=False,leg_font=10,title_font=10):
'''
Plots a grid of learning histories.
Args:
locations ... list of path... | |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import builtins
import math
import warnings
import inspect
from functools import partial
import tensorflow as tf
from trident.backend.common import TensorShape
from trident.backend.tensorflow_backend import *
fr... | |
<reponame>jjisnow/pytube<gh_stars>0
""" Downloader of video website links.
Will download video and mux with audio, or audio only, or video with audio
already. It will also download and retime caption subtitles using pysrt.
Usage:
downloader.py [URL...] [--verbose | --quiet] [--itag value] [--lang string]
[--list] [-... | |
<filename>tests/test_travel.py
from .helpers import IFPTestCase
from intficpy.exceptions import IFPError
from intficpy.room import Room
from intficpy.things import Container, Surface, Lock
from intficpy.travel import (
travelN,
travelNE,
travelE,
travelSE,
travelS,
travelSW,
travelW,
travelNW,
travelU,
trave... | |
+= 'Avg AcceptedTx PerSec,'
line += 'ClocksPerSec,'
line += '# VERSION Msgs,'
line += 'Num VERSION PerSec,'
line += 'Avg VERSION PerSec,'
line += 'ClocksAvg VERSION,'
line += 'ClocksMax VERSION,'
line += 'BytesAvg VERSION,'
line += 'BytesMax VERSION,'
line += '# VERACK Msgs,'
line += 'Num VERACK PerSec,'
li... | |
self.buttonSample.bind('<Button-1>', self.setSample)
self.buttonShowA.bind('<Button-1>', self.setFeatA)
self.buttonShowB.bind('<Button-1>', self.setFeatB)
self.buttonSaveDatasets.bind('<Button-1>', self.saveDataset)
self.buttonGetFeat.bind('<Button-1>', self.getFeat)
self.comboBoxTestType.bind('<<ComboboxSelec... | |
<filename>main.py<gh_stars>1-10
import scipy.io as sio
import numpy as np
from scipy.sparse import csc_matrix
import scipy.sparse as sp
from sklearn.preprocessing import normalize
import scipy.sparse.linalg as LA
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import argpa... | |
<gh_stars>10-100
from __future__ import annotations
import io
from pathlib import Path
from typing import TYPE_CHECKING, BinaryIO, cast
import dask
import dask.array as da
import matplotlib.cm
import matplotlib.colors
import numpy as np
import xarray as xr
from dask.delayed import Delayed
from PIL import Image, Image... | |
CAS connection object.
model_table : string or dict or CAS table, optional
Specifies the CAS table to store the deep learning model.
batch_norm_first : bool, optional
Specifies whether to have batch normalization layer before the
convolution layer in the residual block. For a detailed discussion
about this, pleas... | |
<filename>google-cloud-sdk/lib/googlecloudsdk/third_party/apis/recommender/v1alpha2/recommender_v1alpha2_client.py<gh_stars>0
"""Generated client library for recommender version v1alpha2."""
# NOTE: This file is autogenerated and should not be edited by hand.
from apitools.base.py import base_api
from googlecloudsdk.th... | |
<reponame>tatsukichi108/cpython
"""Core implementation of path-based import.
This module is NOT meant to be directly imported! It has been designed such
that it can be bootstrapped into Python as the implementation of import. As
such it requires the injection of specific modules and attributes in order to
work. One sh... | |
C.f)
a = C()
a.f = 100
self.assertEqual(a.f, 100)
self.assertEqual(a.calls, 0)
del a.f
with self.assertRaises(AttributeError):
del a.f
self.assertEqual(a.f, 42)
self.assertEqual(a.calls, 1)
def test_cached_property_slot_subtype(self):
class C:
__slots__ = ("f",)
def f(self):
return 42
class my_cached_... | |
<reponame>astroumd/admit
""" .. _filter1D:
Filter1D --- 1-dimensional spectral filtering.
----------------------------------------------
This module defines the 1D filter methods.
"""
import numpy as np
import math
from copy import deepcopy
from collections import OrderedDict
class Filter1D(object):
""" This c... | |
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | |
<filename>python/foglamp/plugins/south/wind_turbine/wind_turbine.py
# -*- coding: utf-8 -*-
# FOGLAMP_BEGIN
# See: http://foglamp.readthedocs.io/
# FOGLAMP_END
""" Module for Phidget poll mode plugin
The following is intended as the south service plugin of Dianomic wind turbine demo of FogLAMP.
Phidget based senso... | |
def test_code_info_object(self):
self.assertRaises(TypeError, dis.code_info, object())
def test_pretty_flags_no_flags(self):
self.assertEqual(dis.pretty_flags(0), '0x0')
# Fodder for instruction introspection tests
# Editing any of these may require recalculating the expected output
def outer(a=1, b=2):
def f(c=... | |
<reponame>afontscd/openstacksdk<gh_stars>0
# 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 w... | |
= params.get("Uid")
self.GroupId = params.get("GroupId")
class GroupInfo(AbstractModel):
"""用户组信息
"""
def __init__(self):
"""
:param GroupId: 用户组 ID。
:type GroupId: int
:param GroupName: 用户组名称。
:type GroupName: str
:param CreateTime: 用户组创建时间。
:type CreateTime: str
:param Remark: 用户组描述。
:type Remark: st... | |
float('inf'),
QC_pw_min = float('-inf'), QC_pw_max = float('inf'),
QC_ph_min = float('-inf'), QC_ph_max = float('inf'),
QC_pb_min = float('-inf'), QC_pb_max = -15,
QC_lb_min = float('-inf'), QC_lb_max = float('inf'),
QC_rb_min = float('-inf'), QC_rb_max = float('inf')
)
# dmpag_vglut2_200716_c4_LDECE_OP_VC_clear... | |
# -*- coding: utf-8 -*-
# Copyright (c) 2016-2017 by University of Kassel and Fraunhofer Institute for Wind Energy and
# Energy System Technology (IWES), Kassel. All rights reserved. Use of this source code is governed
# by a BSD-style license that can be found in the LICENSE file.
import copy
import warnings
import... | |
# --------------------------------------------------------------------------- #
# SPEEDMETER Control wxPython IMPLEMENTATION
# Python Code By:
#
# <NAME>, @ 25 Sep 2005
# Latest Revision: 27 Dec 2012, 21.00 GMT
#
#
# TODO List/Caveats
#
# 1. Combination Of The Two Styles:
#
# SM_DRAW_PARTIAL_FILLER
# SM_DRAW_SECTORS
#
... | |
#!/usr/bin/env python3
# coding=utf-8
from itertools import cycle
from statistics import mean
from typing import Iterable
from .core import *
from ..simulator import Sim, SchedulingFailure
class SFF(object):
@Sim.register_reset_global_fields
class Props:
def __init__(self):
self.counter_packets_put_on_wire: int ... | |
<filename>build/docker/zap-baseline.py
#!/usr/bin/env python
# Zed Attack Proxy (ZAP) and its related class files.
#
# ZAP is an HTTP/HTTPS proxy for assessing web application security.
#
# Copyright 2016 ZAP Development Team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this fil... | |
d_model, pdrop, scale=scale, d_k=d_k)
self.ffn = FFN(d_model, activation_type, d_ff, ffn_pdrop, name="ffn")
self.ln1 = tf.keras.layers.LayerNormalization(epsilon=layer_norm_eps)
self.ln2 = tf.keras.layers.LayerNormalization(epsilon=layer_norm_eps)
self.dropout = tf.keras.layers.Dropout(pdrop)
def call(self, inpu... | |
0.25)
# The final RGB array :)
RGB = np.dstack([R, G, B])
ds["DayConvection"] = (("y", "x", "rgb"), RGB)
ds["rgb"] = ["R", "G", "B"]
ds["DayConvection"].attrs[
"Quick Guide"
] = "http://rammb.cira.colostate.edu/training/visit/quick_guides/QuickGuide_GOESR_DayConvectionRGB_final.pdf"
ds["DayConvection"].attrs[... | |
help='')
with self.argument_context('sites sitesonenotepagesparentnotebooksectionsparentsectiongroupsection copy-to-section-group') as c:
c.argument('site_id', type=str, help='key: id of site')
c.argument('onenote_page_id', type=str, help='key: id of onenotePage')
c.argument('onenote_section_id', type=str, he... | |
<reponame>noahwaterfieldprice/alphago<filename>alphago/alphago.py
from collections import OrderedDict
import numpy as np
from tqdm import tqdm
import tensorflow as tf
from .player import MCTSPlayer, RandomPlayer, OptimalPlayer
from .evaluator import evaluate
from .mcts_tree import MCTSNode, mcts
from .utilities impor... | |
<reponame>savi-dev/keystone
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 OpenStack LLC
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright 2010 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apac... | |
<reponame>chrisspen/homebot<filename>src/ros/src/ros_homebot/nodes/arduino_relay.py
#!/usr/bin/env python
from __future__ import print_function
#import time
from math import pi
# import traceback
import os
import sys
import time
import threading
# import cPickle as pickle
from functools import partial
#from math import... | |
self.am.get_active_char()
if char is not None:
try:
mc.setAttr( char + '.jointRadius', self.jointRadius.value() )
except:
pass
def set_joint_display(self):
mode = self.jointMode.currentIndex()
if self.char is not None:
try:
mc.setAttr ( self.char + '.display_Joint', mode )
except:
pass
def... | |
another aperture.
"""
# find the room and include the room shell geometry.
# include the rest of the scene except for indoor geometries for that room.
# here is a place that light-path is necessary to be able to know what is indoor
# and what is outdoor.
raise NotImplementedError()
def aperture_files(self, blac... | |
there are clean components, then
#do a "soft" denoising
else:
full_matrix_to_be_used = np.vstack((noise_comps_post_filter, clean_comps_post_filter))[:,good_timepoint_inds].transpose()
noise_comps_post_filter_T_to_be_used = noise_comps_post_filter[:,good_timepoint_inds].transpose()
XT_X_Neg1_XT = imaging_utils.ca... | |
<reponame>the-utkarshjain/GUI-for-Fortran<filename>gui_func.py
"""
@name
`gui_func.py`
@description
`src file for GUI Main class, subclass of <GUIBase>`
@package
`GUI for Fortran/C++ Application`
@official_repository
`https://github.com/the-utkarshjain/GUI-for-Fortran`
@contributors
* <NAME>... | |
import pandas as pd
from . import register_class, EXP_NAMESPACE
from ..container import Table, Row, Container, AbstractContainer
from ..utils import docval, popargs
class KeyTable(Table):
"""
A table for storing keys used to reference external resources
"""
__defaultname__ = 'keys'
__columns__ = (
{'name': '... | |
<gh_stars>1-10
'''
Function:
游戏进行中界面
Author:
Charles
微信公众号:
Charles的皮卡丘
'''
import json
import math
import random
import pygame
from ..sprites import Enemy
from ..sprites import Turret
from .....utils import QuitGame
from .pause import PauseInterface
from collections import namedtuple
'''游戏进行中界面'''
class GamingInt... | |
import argparse
import numpy as np
import csv
import pandas as pd
import json
import scipy.sparse as sp
from sparsebm import (
SBM,
LBM,
ModelSelection,
generate_LBM_dataset,
generate_SBM_dataset,
)
from sparsebm.utils import reorder_rows, ARI
import logging
logger = logging.getLogger(__name__)
try:
import cupy... | |
< r_br)
& (counts_df[c_tag] > c_tl) & (counts_df[c_tag] < c_br),:]
return overlapping_ref_df
# TODO adjust the registration with dots (triangulation)
def register_cpl(cpl, chunk_coords, experiment_fpath,
stitching_channel,
reference_round):
logger = selected_logger()
registration = {}
experiment_fpath = ... | |
'''
units.py
Module to work with S.I. units
History:
3/04/2018 : First version
4/04/2018 : Addition of non S.I. units and Physics constants
5/04/2018 : Modifications to work with numpy arrays
Connection with sympy
6/04/2018 : Connection with calc
9/04/2018 : Units as text in make* functions
10/04/2... | |
gauss_sigma, x)
lorentz_peak = cls._f_lorentz(offset, amplitude, lorentz_hwhm, x)
peak = frac_gauss*gauss_peak + (1-frac_gauss)*lorentz_peak
return peak
@classmethod
def _f_makep(cls, data, peaks, frac_gauss=None):
"""
Make a set of initial peak parameters for deconvolution.
:arg data: data to be fitte... | |
<reponame>ratschlab/immunopepper
import gzip
import os
import pickle
import pytest
import pysam
import numpy as np
from immunopepper.filter import junction_tuple_is_annotated
from immunopepper.io_ import convert_namedtuple_to_str
from immunopepper.io_ import gz_and_normal_open
from immunopepper.io_ import load_pickle... | |
mapping')
plt.show()
return image_tonemapped
def srgb_to_linear(image_srgb, verbose=False):
'''
---------------------------------------------------------------------------
Transform an image from sRGB color space to linear
---------------------------------------------------------------------------
T... | |
= None
) -> None:
self.email = email
super().__init__(
id=id,
version=version,
created_at=created_at,
last_modified_at=last_modified_at,
last_modified_by=last_modified_by,
created_by=created_by,
sequence_number=sequence_number,
resource=resource,
resource_version=resource_version,
type="CustomerEmailChange... | |
<filename>cube.py<gh_stars>0
""" cube
Original PyCube written by <NAME>
Based and modified from original version found at:
http://stackoverflow.com/questions/30745703/rotating-a-cube-using-quaternions-in-pyopengl
"""
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
import math
import numpy a... | |
test examples
'''
return self.sess.run(self.preds, feed_dict=self.all_test_feed_dict)
def print_model_eval(self):
'''
print the evaluation of the model related information, such as loss, gradients, norm of parameters, etc.
'''
params_val = self.sess.run(self.params)
if self.mini_batch == True:
gra... | |
arc tangent of two data arrays `x` and `y`. It is similar to calculating the arc tangent of `y/x`,
except that the signs of both arguments are used to determine the quadrant of the result. Works on radians only.
The no-data value np.nan is passed through and therefore gets propagated if any of the arguments is null.
... | |
number of points to sample at between the starting and stopping phase.
:param num_shots: The number of shots to average over for each data point.
:return: pandas DataFrame
'''
cz_expriment = []
rz_qubit = [] # this is the qubit to which the RZ is applied
for edge in edges:
qubit, other_qubit = edge
# first qu... | |
#!/usr/bin/python3.9
# Copyright (c) 2021 MobileCoin Inc.
# Copyright (c) 2021 The Forest Team
import argparse
import asyncio
import json
import logging
import os
import shutil
import socket
import sys
import time
from io import BytesIO
from pathlib import Path
from tarfile import TarFile
from typing import Any, Calla... | |
<filename>patcherex/techniques/simple_ptr_enc.py<gh_stars>100-1000
import string
import random
import logging
from collections import defaultdict
import networkx
import pyvex
from angr.sim_variable import SimConstantVariable, SimRegisterVariable, SimMemoryVariable
from angr import KnowledgeBase
from ..backends impor... | |
getHost(self, name):
"""Get information about a Host.
:param name: The name of the Host to find
:type name: str
:returns: host dict
:raises: :class:`~hpe3parclient.exceptions.HTTPNotFound`
- NON_EXISTENT_HOST - HOST doesn't exist
"""
response, body = self.http.get('/hosts/%s' % name)
return body... | |
<filename>src/copulabayesnet/cop_plot.py<gh_stars>0
# -*- coding: utf-8 -*-
"""
Created on 5-12-2019
@author: <NAME>
"""
import matplotlib.pyplot as plt
import matplotlib.animation as manimation
#from biokit.viz.scatter import ScatterHist # biokit is not working right now
#from biokit.viz import corrplot
import nump... | |
random_type == 'micro_multiply_by':
rule['how_many'] = random.choice([2, 3, 4, 5, 'size'])
elif random_type == 'macro_multiply_by':
rule['how_many'] = random.choice(['both', 'hor', 'ver'])
rule['rotates'] = [np.random.randint(1) for _ in range(4)]
rule['flips'] = [random.choice(['hor', 'ver', 'horver', 'no']) for... | |
mutually
exclusive. If not offset-related params are provided, offset
equals to 0.
:param Query query_set: Existing queryset. If provided, all queries
are applied to it instead of creating new queryset. Defaults
to None.
:param _count: When provided, only results number is returned as
integer.
:param _explain: ... | |
False
def export(self, write, level, namespace_='maecPackage:', name_='ObjectEquivalenceType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
showIndent(write, level, pretty_print)
write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_p... | |
<filename>storm_control/hal4000/settings/settings.py
#!/usr/bin/env python
"""
Handles all interaction / communication with the parameters widget.
This widget is responsible for keeping track of the various
different parameter files that the user has loaded as well as
editting and saving these parameters.
Unlike in P... | |
from __future__ import (
absolute_import,
unicode_literals,
)
import collections
import random
import sys
import uuid
import attr
import six
from pysoa.client.expander import (
ExpansionConverter,
ExpansionSettings,
)
from pysoa.client.settings import PolymorphicClientSettings
from pysoa.common.metrics import Ti... | |
"x", y_name: "y"}).sort_values(by="x") for t in list(data["table"])]
l = list(data["label"])
s = list(data["speed"])
lt = zip(l, tables, s)
for m in lt:
setattr(m[1], "label", m[0])
setattr(m[1], "speed", m[2])
return tables
def df_to_plot2(data, x_name, y_name):
tables = [data[[x_name, y_name]].rename(column... | |
in simulation:', sum_quantity, quantity, buy_rate])
sum_quantity = quantity
avg_price = buy_rate
# Real mode
else:
# Double-checking the quantity after we calculated the actual rate
if quantity > 0.0:
# Bitmex is a bit special (market making)
if robot.exchange == 'bitmex':
# Open a long or a short depending o... | |
# Copyright 2021 Canonical Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, soft... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.