input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
import gammalib
import math
import numpy as np
from ctadmtool.dmspectrum.dmspectra import dmspectrum
from ctadmtool.tools.misc import ValidValue , ValidString
from tqdm import tqdm
import warnings
ALLOWED_FERMIONS = ('Majorana', 'Dirac')
ALLOWED_CHANNELS = ('eL', 'eR', 'e',
'MuL', 'MuR', 'Mu', 'TauL', 'TauR', 'Tau'... | |
divided by zero (since some
# voxels are zeros in the template)
noise_temporal[np.isnan(noise_temporal)] = 0
return noise_temporal
def mask_brain(volume,
template_name=None,
mask_threshold=None,
mask_self=0,
):
""" Mask the simulated volume
This creates a mask specifying the likelihood (kind of) a voxel is
... | |
= {
}
def Get(self, request, global_params=None):
"""Read is given a SourceContext and path, and returns.
file or directory information about that path.
Args:
request: (SourceProjectsReposWorkspacesFilesGetRequest) input message
global_params: (StandardQueryParameters, default: None) global arguments
Returns:
... | |
#from gluon.sql import *
#from gluon.validators import *
if 0:
from gluon.sql import Field,IS_IN_DB,DAL
'''This handles biosql dbs '''
# standard modules
from time import gmtime, strftime
import copy
import warnings
# biopython
from Bio import Alphabet
from Bio.SeqUtils.CheckSum import crc64
from Bio import... | |
'vt', 'v']:
self.coordinate = coordinate.reshape(self.xstep_number, self.ystep_number, 2)
self.coordinate = np.flip(self.coordinate, axis=1).transpose((1, 0, 2))
elif self.scan_direction in ['vbl', 'vb']:
self.coordinate = coordinate.reshape(self.xstep_number, self.ystep_number, 2)
self.coordinate = self.coordinat... | |
<gh_stars>1-10
#!/usr/bin/env python
"""Create DeepCpG input data from incomplete methylation profiles.
Takes as input incomplete CpG methylation profiles of multiple cells, extracts
neighboring CpG sites and/or DNA sequences windows, and writes data chunk files
to output directory. Output data can than be used for m... | |
$aggregation_window
seconds. After $aggregation_reset seconds without a message, aggregation stops.
For a static plan, "steps" should be a list of arrays of JSON objects defining "priority",
"repeat", "role", "target", "template", and "wait". Each array of objects represents a step
in the plan, with the JSON objec... | |
> 1)
if candidate_attempt[sorted_candidates[0]] > candidate_attempt[sorted_candidates[1]]:
candidates = [sorted_candidates[0]]
# check if we have any candidate left
if candidates is None or len(candidates) == 0:
self.logger.warning("Anchor function - %s: Failed to find a match", self._src_functions_list[src_ancho... | |
<filename>mlpug/evaluation.py<gh_stars>1-10
import sys
import abc
import math
import numpy as np
from mlpug.base import Base
import basics.base_utils as _
from mlpug.mlpug_exceptions import BatchNotChunkableException, InvalidParametersException
from mlpug.utils import *
def forward_loss(loss, **kwargs):
return l... | |
<reponame>jpconsuegra/ehealthkd-2020
import os
import warnings
from typing import Dict
import torch
import torch.nn as nn
import torch.optim as optim
from kdtools.datasets import (
BILUOVSentencesDS,
DependencyTreeDS,
FocusOnEntityDS,
SelectedDS,
from_biluov,
match_tokens_to_entities,
to_biluov,
)
from kdtools.... | |
:type select: str
:param orderby: OrderBy clause. One or more comma-separated
expressions with an optional "asc" (the default) or "desc" depending
on the order you'd like the values sorted, e.g.
Categories?$orderby=CategoryName desc. Optional.
:type orderby: str
:param count: The Boolean value of true or false to... | |
import sqlite3
import pandas as pd
from sqlite3 import Error
class DBConnection:
""" Connect and play with database
"""
def __init__(self, filename = "data/csgo.db"):
""" Initialize DBConnection object
"""
self.filename = filename
def create_connection(self):
""" Create a database connection to a SQLite dat... | |
<reponame>Travus/Travus_Bot_Base
import logging
from asyncio import sleep as asleep # For waiting asynchronously.
from os import listdir # To check files on disk.
from asyncpg import IntegrityConstraintViolationError # To check for database conflicts.
from discord import Embed, Activity, ActivityType # For bot status
... | |
#!/bin/python3
from contextlib import contextmanager
# pip3 install datetime
import datetime
import errno
import time
import shutil
import sys
import tempfile
from os import sep as os_sep
from os import listdir
from os.path import isdir, join
# local imports
import consts
from args import Arguments, UpdateType
from g... | |
et al, Chem. Eur. J. 2013, 19, 16431-16452,
DOI: 10.1002/chem.201301381
""",
)
entry(
index = 1106,
label = "O2s-CsH",
group =
"""
1 * O2s u0 {2,S} {3,S}
2 Cs u0 {1,S}
3 H u0 {1,S}
""",
thermo = ThermoData(
Tdata = ([300,400,500,600,800,1000,1500],'K'),
Cpdata = ([19.07,19.8,20.85,22.07,24.57,26.95,31.66],'J/(m... | |
includes the starting state)
goals = [0] + [j + 1 for j in goalindices[i]] + \
[len(self.CriticalStates) - 1]
# Compute the costs
costs = sum([self.CostMatrix[goals[j - 1], goals[j]]
for j in range(1, len(goals))])
if self.Method == "Discount":
# Get all the rewards, and then discount the organic ones.
rewards ... | |
<gh_stars>1-10
import torch
from torch import nn
from torch.autograd import Variable
import torch.nn.functional as F
from torch import optim
import numpy as np
import basenets
from agents.Agent import Agent
from torch.nn.utils.convert_parameters import vector_to_parameters, parameters_to_vector
import copy
from .config... | |
mapVersion = None
elif mapspec.endswith('.p'):
mapgraph = pickle.load(open(mapspec,'rb'))
mapVersion = None
elif '.bin:' in mapspec:
mapParts = mapspec.partition(':')
mapfile = mapParts[0]
rangeVals = mapParts[2].split(',')
lat_range = (float(rangeVals[0]),float(rangeVals[1]))
lon_range = (float(rangeVals[2]),... | |
#%%
import matplotlib
import numpy
import os
import pandas
import random
import sklearn
import statsmodels.api as sm
from patsy import dmatrices
from sklearn import linear_model
from sklearn.linear_model import LogisticRegression
from sklearn import model_selection
from sklearn.model_selection import train_test_split... | |
<gh_stars>0
#!/usr/bin/env python
u"""
geocenter.py
Written by <NAME> (12/2021)
Data class for reading and processing geocenter data
PYTHON DEPENDENCIES:
numpy: Scientific Computing Tools For Python
https://numpy.org
dateutil: powerful extensions to datetime
https://dateutil.readthedocs.io/en/stable/
netCDF4: Pyt... | |
from .base import BaseNewsvendor, DataDrivenMixin
from ..utils.validation import check_cu_co
import pulp
import numpy as np
from abc import ABC, abstractmethod
from sklearn.ensemble import RandomForestRegressor
from sklearn.neighbors import NearestNeighbors
from sklearn.utils.validation import check_is_fitted, check_ar... | |
<reponame>cosmic-cortex/neural-networks-from-scratch<gh_stars>10-100
import numpy as np
from math import sqrt
from itertools import product
from .utils import zero_pad
class Function:
"""
Abstract model of a differentiable function.
"""
def __init__(self, *args, **kwargs):
# initializing cache for intermediat... | |
<gh_stars>0
#!/usr/bin/env python
#-*- coding: utf-8 -*-
#pylint: disable=C0301,R0903,R0912,W0703,C0103,R0914,W0603,R0902,R0913
"""
Basic interface to CERN ActiveMQ via stomp
"""
from __future__ import print_function
from __future__ import division
import os
import json
import time
import socket
import random
import l... | |
(-1)*self.compare_tuples_lex(f.reversed(),g.reversed())
def compare_tuples_negdeglex(self,f,g):
"""
Compares two exponent tuples with respect to the negative degree
lexicographical term order.
INPUT:
- ``f`` - exponent tuple
- ``g`` - exponent tuple
EXAMPLE::
sage: P.<x,y> = PolynomialRing(QQbar, 2, orde... | |
<gh_stars>0
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | |
# coding: utf-8
import io
import os
import sys
import unittest
import copy
import pickle
from itertools import permutations
from ast import literal_eval
from monty.serialization import dumpfn, loadfn
from networkx.readwrite import json_graph
from pymatgen.util.testing import PymatgenTest
from pymatgen.core.structure ... | |
import json
import logging
import csv
from datetime import date
from StringIO import StringIO
from zipfile import ZipFile
from django import forms
from django.core import mail
from django.core.urlresolvers import reverse
from django.utils.unittest import skip
from vumi.message import TransportUserMessage
import go.b... | |
<gh_stars>1-10
import json
import csv
import urllib.request, urllib.parse
import http.server
import socketserver
from time import sleep
entityId = 0
def getData(filename):
data = []
with open(filename) as f:
for line in f:
data.append(json.loads(line))
return data
def sendSpamTraining(filename, accessKey, ... | |
from numpy import pi, array, linspace, zeros
from os.path import join
import matplotlib.pyplot as plt
from multiprocessing import cpu_count
import pytest
from Tests import save_validation_path as save_path
from pyleecan.Classes.OPdq import OPdq
from pyleecan.Classes.Simu1 import Simu1
from pyleecan.Classes.InputCurren... | |
must be implemented if
``supports_authorization_query()`` is ``true``.*
"""
if proxy is None:
raise NullArgument()
raise Unimplemented()
def get_authorization_query_session_for_vault(self, vault_id=None, proxy=None):
"""Gets the ``OsidSession`` associated with the authorization query service for the given vaul... | |
# -*- coding: utf-8 -*-
"""
mosaicRaster.py
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 ... | |
def internal_paging(next_link=None, raw=False):
if not next_link:
# Construct URL
url = self.list_available_sizes.metadata['url']
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'vmName': self._serialize.url("vm_name", vm_name, 'str'),
'subs... | |
= None
if args.fp16:
if args.fp16_backend == "auto":
self.fp16_backend = "amp" if _is_native_amp_available else "apex"
else:
self.fp16_backend = args.fp16_backend
logger.info(f"Using {self.fp16_backend} fp16 backend")
if args.fp16 and not args.deepspeed: # deepspeed manages its own fp16
if self.fp16_backend =... | |
+= "!"
return rname
class ArmRegScalarOper(ArmRegOper):
def __init__(self, reg, index, va=0, oflags=0):
self.index = index
ArmRegOper.__init__(self, reg, va, oflags)
def __eq__(self, oper):
if not isinstance(oper, self.__class__):
return False
if self.reg != oper.reg:
return False
if self.oflags != oper.ofl... | |
# coding=utf-8
"""A district is the voter population of a constituency or geographical area."""
import itertools as itls
import math as m
import random as rd
from .utils import generate_voter_groups, sort_dict_desc, make_table
from .candidate import Candidate
from .party import Party
from .voter_group import VoterGro... | |
from stackapi import StackAPI, StackAPIError
from colorama import Fore, Back
import regex as re
import random
import os
import PostFilters as PF
import Dictionary
import Utils
randomNameCoefficient = str(random.randint(-1e6, 1e6))
# We introduce a tiny bit of randomness into the placeholders to reduce the probabili... | |
'_ORA',
database_id = 'OB_ORA_SYS_DATABASE_ID',
table_id = '25161',
table_type = 'SYSTEM_VIEW',
rowkey_columns = [],
normal_columns = [],
gm_columns = [],
in_tenant_space = True,
view_definition = """
SELECT OBJECT_NAME, ORIGINAL_NAME, OPERATION, TYPE, CAST(TABLESPACE_NAME AS VARCHAR2(30)) AS TS_NAME, CREATETI... | |
<reponame>MaastrichtU-IDS/translator-openpredict
import logging
import os
from datetime import datetime
import numbers
import re
import numpy as np
import pandas as pd
from sklearn import model_selection, tree, ensemble, svm, linear_model, neighbors, metrics
from sklearn.model_selection import GroupKFold, StratifiedKF... | |
date(t.year, 1, 1).toordinal() + 1)
self.assertEqual(tt.tm_isdst, -1)
def test_more_strftime(self):
# This tests fields beyond those tested by the TestDate.test_strftime.
t = self.theclass(2004, 12, 31, 6, 22, 33, 47)
self.assertEqual(t.strftime("%m %d %y %f %S %M %H %j"),
"12 31 04 000047 33 22 06 366")
... | |
# coding: utf-8
"""
Xero Payroll UK
This is the Xero Payroll API for orgs in the UK region. # noqa: E501
OpenAPI spec version: 2.3.4
Contact: <EMAIL>
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
from xero_python.models import BaseModel
class Deduction(BaseModel):
"""NOTE: This c... | |
= urllib2.urlopen(req)
return data.read()
def is_installed(url, path):
"Check if already installed a package for given URL"
fname = os.path.join(path, '.packages')
if os.path.isfile(fname):
with open(fname, 'r') as packages:
for line in packages.readlines():
if url == line.replace('\n', ''):
return True
retur... | |
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
import numpy as np
from matplotlib.widgets import Slider,CheckButtons,Button
from robolink import *
fig, ax = plt.subplots()
plt.subplots_adjust(left=0,bottom=0.28,right=1,top=1)
ax = plt.axes(projection = "3d")
def mmatrix(*matrices):
n=0
... | |
cathedral is one of the most important gothic buildings in Austria",
"references": ["The cathedral is one of the most important Gothic buildings in Austria", "The cathedral is one of the most important Gothic buildings in Austria"]
},
{
"translation": "Parts of the late Romanesque predecessor building from 1230/40 ... | |
# -*- coding: utf-8 -*-
# this file is released under public domain and you can use without limitations
#########################################################################
## This scaffolding model makes your app work on Google App Engine too
######################################################################... | |
<filename>fairseq/models/hubert/hubert.py
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
from typing import Dict, List, Optional, Tuple
import numpy as np
import torch
impo... | |
import numpy as np
######import tensorflow as tf
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
##from tensorflow.keras.engine.topology import Layer
##from tensorflow.keras import backend as K
from retro_contest.local import make
import gym_remote.exceptions as gre
import gym_remote.client as grc
#fr... | |
with pytest.raises(ValueError):
bond_exchange.executeOrder.transact(_order_id, _amount, 'True', {'from': _trader})
with pytest.raises(ValueError):
bond_exchange.executeOrder.transact(_order_id, _amount, 111, {'from': _trader})
# エラー系4
# 指定した注文IDが直近の注文IDを超えている場合
def test_executeOrder_error_4(users,
bond_exchange,... | |
<reponame>yijiangh/conmech<filename>tests/python/test_stiffness_checker.py
from __future__ import print_function
import os
import pytest
from termcolor import cprint
import numpy as np
from numpy.linalg import norm, multi_dot
import random
from copy import copy
import time
from numpy.testing import assert_equal, asser... | |
E, is defined such that :math:`H(z) = H_0 E`.
It is not necessary to override this method, but if de_density_scale
takes a particularly simple form, it may be advantageous to.
"""
if isiterable(z):
z = np.asarray(z)
Om0, Ode0, Ok0 = self._Om0, self._Ode0, self._Ok0
if self._massivenu:
Or = self._Ogamma0 * (1... | |
<reponame>realitix/cvulkan
'''Module containing custom jinj2 filters
All the shit is here man! The rest is heaven compared to this garbage.
I have hiden the conversion functions here (c_to_py py_to_c) because
it can't be made beautiful.
Enjoy the pain!
'''
__all__ = ['join_comma', 'kwlist', 'parse_tuple_and_keywords'... | |
None:
stats=statfind(pioner)
adm=admins.find_one({'name':stats})
if adm == None:
bot.send_message(441399484, stats)
return
if adm['controller'] != None:
controller = adm['controller']
if m.from_user.id == controller['id']:
if m.reply_to_message == None:
try:
bot.delete_message(m.chat.id, m.message_id)
exce... | |
<gh_stars>1000+
import asyncio
import json
import re
import pandas as pd
import hummingbot.connector.derivative.bybit_perpetual.bybit_perpetual_utils as bybit_utils
from aioresponses import aioresponses
from collections import deque
from decimal import Decimal
from unittest import TestCase
from unittest.mock import p... | |
None:
cmdline += [ arg, value ]
# we do this because in flash_start() we need to add
# --operation as we find images we are supposed to flash
self.cmdline_orig = cmdline
flash_shell_cmd_c.__init__(self, cmdline, cwd = '%(file_path)s',
**kwargs)
if name == None:
name = "Intel Quartus PGM %s" % device_id
self.... | |
window type requested: %s" % kind)
if np.mod(N, 2) == 0:
raise ValueError("Window size must be odd")
# Creating the window.
if kind == "kaiser": # If the window kind is kaiser (beta is required).
wstr = "np.kaiser(N, beta)"
# If the window kind is hann, hamming, blackman or bartlett (beta is not
# required).
... | |
<filename>proxy/sproxy/checkProxies.py
#!/usr/bin/env python3
"""
check instances with installed proxies; terminate some that appear unusable
"""
# standard library modules
import argparse
import csv
#import datetime
import json
import logging
import os
#import subprocess
import sys
import urllib3
# third-party module... | |
"brand": "zara",
"precio": 1540
}
},
{
"id": 850,
"atrr": {
"color": "amarillo",
"size": "xxl",
"brand": "nike",
"precio": 4447
}
},
{
"id": 851,
"atrr": {
"color": "rojo",
"size": "l",
"brand": "adidas",
"precio": 1540
}
},
{
"id": 852,
"atrr": {
"color": "rojo",
"size": "xs",
"brand": "polo... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" XMLModelDescBuilder
XML格式的模型描述建造者
"""
import basebuilder
import autotools
import os
import re
import time
import xml.etree.cElementTree as xmllib
import xml.dom.minidom as minidom
pother = re.compile(r'^([^_]+)[_]([^_]+)[_]([^.]+)[.]xls\w*')
class X... | |
<reponame>wesley1001/trading-momentum-transformer<filename>mom_trans/model_inputs.py
"""Model Inputs"""
# import mom_trans.utils as utils
import numpy as np
import sklearn.preprocessing
import pandas as pd
import datetime as dt
import enum
from sklearn.preprocessing import MinMaxScaler
# Type defintions
class DataTyp... | |
bar .foo {
a: b; }
''' == render('''@mixin foo {
.foo {a: b}}
bar {
@include foo;
c: d; }
''')
assert '''bar {
a: b;
c: d; }
''' == render('''@mixin foo {a: b}
bar {
@include foo;
c: d; }
''')
def test_mixins_with_empty_args():
assert '''.foo {
a: b; }
''' == render('''@mixin foo() {a: b}
.foo {@include ... | |
<filename>FLife/tools.py<gh_stars>1-10
import numpy as np
from scipy import stats
import tkinter as tk
from tkinter.filedialog import asksaveasfilename
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
import time
def relative_error(value, value_... | |
<filename>pioreactor/tests/test_growth_rate_calculating.py<gh_stars>1-10
# -*- coding: utf-8 -*-
from __future__ import annotations
import json
import time
import numpy as np
import pytest
from msgspec.json import encode
from numpy.testing import assert_array_equal
from pioreactor import structs
from pioreactor.back... | |
mode = os.environ.get(GPOS_COMPACT_MODE_ENV_KEY, GPOS_COMPACT_MODE_DEFAULT)
if mode and mode != "0":
log.info("Compacting GPOS...")
compact_lookup(self.font, mode, lookup)
return lookup
class SinglePosBuilder(LookupBuilder):
"""Builds a Single Positioning (GPOS1) lookup.
Attributes:
font (``fontTools.TTLib.T... | |
<reponame>MarcoMuellner/soccerbot
import requests
import json
from typing import Dict, List, Callable, Union
from dateutil import parser
import re
import xml.etree.ElementTree as ET
from unidecode import unidecode
from database.models import Federation,Competition,Association,Match,Season,Team,Player
class ApiCalls:... | |
z_dim=512, device=cyc_con.device)
# optimizer_6 = optim.Adam(filter(lambda p: p.requires_grad, cyc_con.parameters()), lr=1e-4, weight_decay=1e-4)
if pipeline == 'push_to_all':
[r_data_loader, r_label_loader, r_pred_loader, r_res_loader] = pos_loader
[w_data_loader, w_label_loader, w_pred_loader, w_res_loade... | |
<gh_stars>0
write_single_value_template = ''' subroutine hdf_write_dataset_{ftype_name}_0(loc_id, dset_name, array, chunks, filter, processor, axis)
integer(HID_T), intent(in) :: loc_id ! local id in file
character(len=*), intent(in) :: dset_name ! name of dataset
{declaration}
integer, optional, intent(in) :: chu... | |
#!/usr/bin/python
# Copyright (C) 2014 Belledonne Communications SARL
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.... | |
if decision_category is None:
category_candidates = DecisionCategory.query.filter_by(
protocoltype_id=protocol.protocoltype.id).all()
category_names = [
"'{}'".format(category.name)
for category in category_candidates
]
return _make_error(
protocol, "Parsing", "Unknown decision category",
"The decision in line... | |
<gh_stars>1-10
# views.py
import os, re
import json
import hashlib
from django.utils import timezone
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import ListView, DetailView
from django.views.generic.base import TemplateV... | |
# -*- coding: utf-8 -*-
"""
This module contains a collection of functions for reading and parsing xml
files output by the TrackMate ImageJ plugin.
Written by <NAME> (UCSF)
"""
import os
import numpy as np
import pandas as pd
import warnings
import matplotlib.pylab as plt
from lxml import etree
import glob
def pa... | |
# adapted from https://github.com/tannewt/agohunterdouglas/agohunterdouglas.py
# license from that project included in this repo as well
import socket
import re
import logging
import asyncio
logging.basicConfig(level=logging.DEBUG)
class HunterDouglasPlatinumHub:
"""
Hub class for the Hunter Douglas Platinum - for... | |
<filename>dynamic_ensemble_singleWeight.py
__author__ = 'renhao.cui'
import random
import operator
def normalization(scoreList):
outputList = []
total = sum(scoreList)
for score in scoreList:
outputList.append(score/total)
return outputList
def getInitialList(num):
if num == 2:
dist = random.random(0.001, 0.9... | |
z)
return np.array(points_matrix_coords_3d), points_matrix
def revolute(points_matrix_coords, rev=360, res=4, exclude_axis=True, axis='z'):
def rotation_matrix(theta, axis='z'):
if axis == 'z':
return np.array([
[np.cos(theta), np.sin(theta), 0],
[-np.sin(theta), np.cos(theta), 0],
[0, 0, 1],
... | |
<reponame>IAWG-CSBC-PSON/hack2022-03-virtual-if<gh_stars>0
## Evironment: python=3.9.7, torch=1.10.2, zarr=2.10.3, numpy=1.21.3, dask2022.2.0, tiler=0.5.6, tifffile=2022.2.9
import torch
from torchvision.transforms import Compose, ToTensor, Resize, Normalize
from torchvision.transforms import InterpolationMode
from to... | |
from __future__ import absolute_import, unicode_literals
import sys
from collections import OrderedDict
from inspect import getmro
import param
from panel.pane import PaneBase
from panel.layout import Row, Tabs
from panel.util import param_name
from .core import DynamicMap, HoloMap, ViewableElement, Element, Layou... | |
<reponame>kaitj/snakebids<filename>snakebids/tests/test_generate_inputs.py
from __future__ import absolute_import
import filecmp
import itertools as it
import keyword
import os
import re
import shutil
import tempfile
from collections import defaultdict
from pathlib import Path
from typing import Dict, Iterable, List, ... | |
actions = ActionChains(driver)
actions.move_to_element(scroller)
actions.click()
actions.perform()
# Use number_days_to_go_back to get the date to target.
date = datetime.datetime.today()-datetime.timedelta(number_days_to_go_back)
date = date.strftime("%m/%d/%y")
# While the date has not been found, keep scrol... | |
<reponame>Geode-solutions/OpenGeode
# -*- coding: utf-8 -*-
# Copyright (c) 2019 - 2021 Geode-solutions
#
# 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... | |
import itertools
import os
import pickle
import shutil
import tempfile
import warnings
from collections import defaultdict
from typing import Any, Dict, Iterable, Iterator, List, Optional, Tuple, Union
import pandas as pd
from podium.field import Field, unpack_fields
from .dataset import DatasetBase, _pandas_to_exam... | |
<filename>djb_toolkit/tf_model.py
"""TF Model superclass"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from os.path import join
import math
from datetime import datetime
from time import time
import tensorflow as tf
from numpy import ones, a... | |
#!/usr/bin/env python3
import argparse
import os
import sys
import re
import math
import warnings
import time
import struct
from collections import defaultdict
import pandas as pd
import numpy as np
import hicstraw
import cooler
from scipy.stats import expon
from scipy.ndimage import gaussian_filter
from scipy.ndimag... | |
<reponame>chenzhaiyu/abspy<filename>abspy/complex.py
"""
complex.py
----------
Cell complex from planar primitive arrangement.
A linear cell complex is constructed from planar primitives
with adaptive binary space partitioning: upon insertion of a primitive
only the local cells that are intersecting it will be update... | |
0, 0
return x, y
def sammys_viz():
df = load()
df_sig = load2()
df_main = load3()
states = alt.topo_feature(data.us_10m.url, 'states')
source = 'https://raw.githubusercontent.com/sammyhajomar/test/main/altair-dataset1.csv'
variables = ['State','acres','id']
# US states background
background = alt.Chart(sta... | |
"""
To run the test cases below make sure you have following environment variables set:
TEST_API_KEY -- API Key for your organization
TEST_LINK_ID -- any link_id string
TEST_ENTITY_ID -- any entity id which you have created before using any of our APIs / libraries before under the above organization
with link_id as a... | |
## Copyright (c) <NAME>, <NAME>. All rights reserved.
## See LICENSE file for details.
## This software is distributed WITHOUT ANY WARRANTY; without even
## the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
## PURPOSE. See the above copyright notices for more information.
import functools
from scip... | |
<reponame>dkirkby/desietcimg
"""General purpose utilities for imaging analysis.
"""
import os
import re
import pathlib
import logging
import numpy as np
import scipy.signal
import scipy.stats
import scipy.ndimage
import fitsio
def downsample(data, downsampling, summary=np.sum, allow_trim=False):
"""Downsample a 2... | |
df['delta'].values / np.timedelta64(1, 's')
del df['delta']
## we identify the beginning of new visits
df['is_gap'] = df['delta_sec'] > timeGap
del df['delta_sec']
## an ind change has the same effect as a gap
# all we need to do is to cut the sequence at that point anyway
# we also need to insure not to throw... | |
# keeps track on whether there is actually any work to be done here
needs_combining = False
# iterate over combined iterator of starts/ends to avoid instantiating self._blocks
for block_start, block_end in zip(self._starts, self._ends):
# don't include empty blocks
if block_end - block_start == 0:
needs_combining... | |
<reponame>urchinpro/L2-forms
import sys
from datetime import datetime, date
from dateutil.relativedelta import relativedelta
import simplejson
from django.core.management.base import OutputWrapper
from django.db import models
import slog.models as slog
TESTING = 'test' in sys.argv[1:] or 'jenkins' in sys.argv[1:]
... | |
@property
@pulumi.getter(name="initializeWithReadme")
def initialize_with_readme(self) -> Optional[pulumi.Input[bool]]:
"""
Create main branch with first commit containing a README.md file.
"""
return pulumi.get(self, "initialize_with_readme")
@initialize_with_readme.setter
def initialize_with_readme(self, val... | |
take is to down-weight the times where the data does not appear as either Guassian noise or Gaussian noise + our template. We can do this be combining the SNR time series and our $\chi^2_r$ time series as follows. This is a method used to re-weight SNR since initial LIGO, and has been employed in the first two Advanced... | |
<filename>regenerator/stream.py<gh_stars>1-10
'''Reentrant generator (ReGenerator) stream.
'''
import functools, itertools, random
class Stream:
'''A ReGenerator `Stream` is an iterable container class that is designed to permit
lazy processing of data in a streaming fashion. The data items produced by a stream
can... | |
"Punch of Yellow": 0xECD086,
"Punch Out Glove": 0x6888FC,
"Punchit Purple": 0x56414D,
"Punctuate": 0x856B71,
"Punga": 0x534931,
"Punk Rock Pink": 0x8811FF,
"Punk Rock Purple": 0xBB11AA,
"Punky Pink": 0xB2485B,
"Puppeteers": 0x79CCB3,
"Puppy": 0xBCAEA0,
"Puppy Love": 0xE2BABF,
"Pure Apple": 0x6AB54B,
"Pure B... | |
Binary (not a set type). If the target attribute of the comparison is of type String, then the operator checks for a substring match. If the target attribute of the comparison is of type Binary, then the operator looks for a subsequence of the target that matches the input. If the target attribute of the comparison is ... | |
<gh_stars>0
# -*- coding: utf-8 -*-
""" S3 Data Objects API
@copyright: 2009-2013 (c) Sahana Software Foundation
@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
restr... | |
Returns:
(numpy array): |S|xL array of state marginals in log space
(numpy array): |S|x|A|xL array of state-action marginals in log space
(numpy array): |S|x|A|x|S|xL array of state-action-state marginals in log space
"""
if rsa is None:
rsa = np.zeros((t_mat.shape[0], t_mat.shape[1]))
if rsas is None:
rsas = ... | |
self._get_node_q():
q = node_q
cache.set(cache_key, q)
return q
def get_parent_q(self):
if self.min_inputs == 1:
return self.get_single_parent_q()
raise NotImplementedError("You need to implement a non-default 'get_parent_q' if you have more than 1 parent")
@property
def use_cache(self):
""" At the moment w... | |
the url that refers to the thumbnail's source image
thumb_source_url = urlparse.urlunparse((
self._bundle.shotgun.config.scheme, self._bundle.shotgun.config.server,
"/thumbnail/full/%s/%s" % (
urllib.quote(str(entity_type)),
urllib.quote(str(entity_id))
), None, None, None
))
return self.request_thumbnail(
th... | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 27 13:50:02 2018
@author: anonymous
"""
import math
import torch
from torch import nn
import torch.nn.functional as F
from .models import FFPolicy, orthogonal, Lin_View, weights_init
from .distributions import Categorical
class NeuralMapPolicy(... | |
import struct
from ryu.lib.pack_utils import msg_pack_into
from ryu.ofproto.ofproto_parser import StringifyMixin, MsgBase, msg_str_attr
import ryu.ofproto.ofproto_v1_3_parser as ofproto_parser
import ryu.ofproto.ofproto_v1_3 as ofproto
import ryu.ofproto.openstate_v1_0 as osproto
def OFPExpActionSetState(state, table_... | |
+ m.b241 - m.b251 <= 0)
m.c4387 = Constraint(expr= - m.b235 + m.b242 - m.b252 <= 0)
m.c4388 = Constraint(expr= - m.b235 + m.b243 - m.b253 <= 0)
m.c4389 = Constraint(expr= - m.b235 + m.b244 - m.b254 <= 0)
m.c4390 = Constraint(expr= - m.b235 + m.b245 - m.b255 <= 0)
m.c4391 = Constraint(expr= - m.b236 + m.b237 - m.b2... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.