input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
(self.oldest is None) or (mjd1 < self._entries[self.oldest]['mjd1'])
entry = (mjd1, mjd2, value, error) + aux_data
if self.full:
assert self.oldest is not None
if is_oldest:
# Ignore this since it is older than all existing entries.
return
self.last = self.oldest
self._entries[self.last] = entry
# Update the i... | |
libX11.XBlackPixelOfScreen
XBlackPixelOfScreen.restype = c_ulong
XBlackPixelOfScreen.argtypes = [POINTER(Screen)]
#~ extern unsigned long XWhitePixelOfScreen(
#~ Screen* /* screen */
#~ );
XWhitePixelOfScreen = libX11.XWhitePixelOfScreen
XWhitePixelOfScreen.restype = c_ulong
XWhitePixelOfScreen.argtypes = [POINTER(Sc... | |
<reponame>mb0rt/OpenCue<gh_stars>0
# Copyright Contributors to the OpenCue 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/licenses/LICENSE-2.0
#
# Unless re... | |
# will trigger even if single echo data is in medata folder. Should still
# be okay
for subdir in subdirs[1:]: # not including parent folder or /medata, run dcm2niix on non me data
try:
fobj = dicom.read_file(os.path.join(subdir, list(os.walk(subdir))[0][2][0]),
force=True) # first dicom file of the scan
scan_num... | |
AND datetime <= %s"""
if search_type is not None and search_type == 'stationvariable':
sql_string = """
SELECT station_id,
variable_id,
b.symbol,
b.name,
b.sampling_operation_id,
c.name,
c.symbol,
min_value,
max_value,
avg_value,
sum_value,
num_records,
datetime as data
FROM hourly_summary a
INNER JOI... | |
= isinstance(dorp, list)
# If this is a plan panel, it only renders plans
if (self.type == 'plan' or self.type == 'plan_summary') and \
not isinstance(dorp,Plan):
if is_list:
if any(not isinstance(item, Plan) for item in dorp):
return ''
else:
return ''
# Given a plan, it will render using the districts with... | |
import time
import weakref
import logging
import numpy as np
import wgpu.backends.rs
from .. import Renderer
from ...linalg import Matrix4, Vector3
from ...objects import (
id_provider,
KeyboardEvent,
RootEventHandler,
PointerEvent,
WheelEvent,
WindowEvent,
WorldObject,
)
from ...cameras import Camera
from ...... | |
NUMBER):
return TRUE
elif term.type == OBJECT:
return self
else:
return FALSE
class StringOp(Expression):
data_type = STRING
def __init__(self, term):
Expression.__init__(self, [term])
self.term = term
def __data__(self):
return {"string": self.term.__data__()}
def vars(self):
return self.term.vars()
... | |
hyperparameter_name)
elif hyperparameter_description['type'] == metadata_base.ArgumentType.PRIMITIVE:
if utils.is_sequence(hyperparameter_description['data']):
primitive_references = hyperparameter_description['data']
else:
primitive_references = typing.cast(typing.Sequence, [hyperparameter_description['data']])
... | |
<reponame>TopDeveloper-333/opentoontownsrc<filename>toontown/distributed/ToontownClientRepository.py<gh_stars>0
import types
import time
from pandac.PandaModules import *
from direct.distributed.ClockDelta import *
from direct.gui.DirectGui import *
from pandac.PandaModules import *
from direct.interval.IntervalGlobal ... | |
<reponame>saloniagarwal0403/SSCNN
# conda activate SurvivalAnalysis_January2021
# python Siamese_with_conv_parallel_processing_average_pooling_multiple__magnifications.py>Epoch_4_using_average.txt
import sklearn
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
from t... | |
# coding: utf-8
import os
import sys
import pymongo as mongo
import json
import pandas as pd
import numpy as np
from datetime import date, datetime
import time
from time import strftime, localtime
from QUANTAXIS.QAFetch import QATdx as tdx
from easyquant.easydealutils.easytime import EasyTime
import re
class MongoIo(ob... | |
<reponame>sjalloq/uvm-python<filename>src/uvm/base/uvm_objection.py
#
#//
#//----------------------------------------------------------------------
#// Copyright 2007-2011 Mentor Graphics Corporation
#// Copyright 2007-2011 Cadence Design Systems, Inc.
#// Copyright 2010-2011 Synopsys, Inc.
#// Copyright 2013 NVIDIA Co... | |
from django.test import TestCase, Client
from django.test import RequestFactory
from django.conf import settings
from ..annotations import Annotations, AnnotationCrud
from django.contrib.auth import get_user_model
from django.urls import reverse
from django.template import Context, Template
from django.core.serializers... | |
valid classification technique number for ct. It can only be from 1-3 as in Table 4 in the paper")
return
# The classifcation model which is a Pipeline of vectorizers and transformers for the
# features selection technique
classification_model = Pipeline([
('vectorizer', CountVectorizer(analyzer="word",
... | |
'mtn', 'p4']
if self.get('vc') and self.get('vc') not in vcs:
raise usage.UsageError("vc must be one of %s" % (', '.join(vcs)))
validateMasterOption(self.get('master'))
class TryOptions(base.SubcommandOptions):
subcommandFunction = "buildbot.scripts.trycmd.trycmd"
optParameters = [
["connect", "c", None,
"How... | |
"""
"""
# Created on 2014.05.31
#
# Author: <NAME>
#
# Copyright 2014 - 2020 <NAME>
#
# This file is part of ldap3.
#
# ldap3 is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the Lic... | |
# coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
"""
This module define a WulffShape class to generate the Wulff shape from
a lattice, a list of indices and their corresponding surface energies,
and the total area and volume of the wulff shape,the weighted su... | |
<filename>source_code/patent_tracker.py
import asyncio
import time
import os
from datetime import datetime, date, timedelta
import aiohttp
from bs4 import BeautifulSoup
from typing import Union, List, Tuple, Iterator, Iterable, Dict
import openpyxl
from default_style import info_style, field_style, record_style, sheet_... | |
redundancy e.g.
# Sunday...Increasing clouds.
# Sunday Night...Increasing clouds.
#
#If the previous period had increasing or decreasing wording, return 0
# Otherwise, return 1
# Check to see if previous period had increasing or decreasing wording
component = node.getComponent()
prevComp = component.getPrev()
... | |
# coding=utf-8
# Copyright (c) 2019 NVIDIA CORPORATION. All rights reserved.
# Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team.
#
# 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 o... | |
<filename>model.py
import os
import sys
import copy
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from modules import ISAB, PMA, SAB
class STN3d(nn.Module):
def __init__(self):
super(STN3d, self).__init__()
self.conv1 = torch.nn... | |
<gh_stars>0
import numpy
import operator
import pickle
from ..General.units import conversion_facs_position
from .Classes.general import Coordinate,Energy
from .Classes.atomic_orbital import AO,Atom,l_orient
from .Classes.molecular_orbital import MO
from .Classes.excitation import Excitation
from ..General.... | |
from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
from pyangbind.lib.base import PybindBase
from d... | |
4987 3163413 4987
3196064 3373 3197400 3373
3206308 3373 3207112 3373
3217753 13193 3218864 13193
3230901 13193 3231986 13193
3237244 167 3238306 167
3253064 167 3254003 167
3253064 167 3254147 167
3266552 167 3267780 167
3276436 9498 3277574 9498
3278061 9498 3279393 9498
3288266 9498 3289224 9498
3300144 ... | |
flag (f), or unflag (u) a location?`")
try:
msg = await self.client.wait_for(
"message", check=lambda m: m.channel == ctx.channel and m.author == ctx.author, timeout=120
)
except TimeoutError:
return await self.gameIdle(ctx, game, True)
decision = msg.content
if decision.casefold() == "quit" or decision.casefol... | |
shared_lib_paths is not None else []) + (import_lib_paths if import_lib_paths is not None else [])
if len(combined_paths) > 0:
self.apply_lib_based_uselib(pdb_filenames, combined_paths, "PDB", uselib_env_name, lib_source_path, False, True)
copy_extras = self.get_most_specific_entry("copy_extra", uselib_name, lib_co... | |
(eV)')
#ax.set_title(r'$T_2 = $' + str(t2))
# plt.colorbar(im)
# fig.subplots_adjust(hspace=0.0,wspace=0.0,bottom=0.14,left=0.0,top=0.95,right=0.98)
return S
def DQC_R1(evals, dip, omega1=None, omega2=[], omega3=None, tau1=None, tau3=None,\
g_idx=[0], e_idx=None, f_idx=None, gamma=None):
'''
Double quantum c... | |
<< 8)
self.log_load(address, data, 'half')
self.check_address(address)
return data
def load_byte(self, address):
self.flash_prefetch_hint(address)
self.local_addresses.seek(address)
if self.local_addresses.read(1) == '\xff':
self.local_data.seek(address)
return ord(self.local_data.read(1))
self.flush()
dat... | |
unescape:
string = unescape_name_str(raw_string)
if is_container_id(string):
return ([string] if multi else string)
if string in cached_project_names:
return ([cached_project_names[string]] if multi else cached_project_names[string])
try:
results = list(dxpy.find_projects(name=string, describe=True, level='VIE... | |
import tensorflow as tf
import numpy as np
import os
from voicepuppet.builder import ModelBuilder
from config.configure import YParams
os.environ["CUDA_VISIBLE_DEVICES"] = '0'
class PixFlowNet(ModelBuilder):
def __init__(self, config_path):
if (not os.path.exists(config_path)):
logger.error('config_path not exis... | |
"""
Classes to simplify and standardize the process of drawing samples from the posterior distribution in
Bayesian inference problems.
"""
import numpy as np
import scipy as sp
class Quad_Sampler(object):
"""
Class for drawing samples from an arbitrary one-dimensional probability distribution using numerica... | |
<gh_stars>0
"""
partitioner.py
"""
from copy import copy
import numpy as np
import psi4
from dataclasses import dataclass
from pydantic import validator, BaseModel
from dask.distributed import Client
from ..inverter import Inverter
from ..grid.grider import Grider
from ..fragment import Fragment
from .pdft_scf impo... | |
('nusseed', ''),
# ('nust2', ''),
# ('nustd', ''),
# ('nzp', ''),
# ('offset', ''),
# ('pacoil', ''),
# ('pc', ''),
# ('pexsel', ''),
# ('ph_mod', ''),
("phc0", "deg"),
("phc1", "deg"), # ('phlist', ''),
# ('pknl', ''),
# ('plstep', ''),
# ('plstrt', ''),
# ('plw', ''),
# ('plwmax', ''),
# ('pparmod', '... | |
# coding: utf-8
"""Utilities for installing Javascript extensions for JupyterLab"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
from __future__ import print_function
import os
import shutil
import sys
import tarfile
from os.path import join as pjoin, normpath
... | |
in (diskFiles - dbFiles):
fullPath = os.path.join(self.dataDir, path)
st = os.stat(longPathEnc(fullPath))
wikiWord = self._findNewWordForFile(path)
if wikiWord is not None:
fileSig = self.wikiDocument.getFileSignatureBlock(fullPath)
self.connWrap.execSql("insert into wikiwords(word, created, "
"m... | |
for k, v in df.groupby("ID")}
groupList = list(groups.keys())
# groupList = list(groups.groups)
pts = ['bbr_x','bbr_y','fbr_x','fbr_y','fbl_x','fbl_y','bbl_x', 'bbl_y']
n_car = len(groupList)
CX = np.ones((n_car, n_car)) * 999 # cone of X
loss = torch.nn.GaussianNLLLoss()
empty_id = set()
for i,c1 in enu... | |
| wget -i - -O /tmp/speedtestcheck.png"
testspeed =str(subprocess.call(testspeedcmd, shell = True,encoding='utf-8'))
bot.send_chat_action(config.tg, "upload_photo")
testspeedfile = open('/tmp/speedtestcheck.png', 'rb')
bot.send_photo(config.tg, testspeedfile, reply_markup=markupspeedtest)
except:
bot.send_message... | |
<reponame>AllenInstitute/OpenScope_CA_Analysis
"""
corr_analys.py
This script contains functions for USI correlation analysis.
Authors: <NAME>
Date: January, 2021
Note: this code uses python 3.7.
"""
import copy
import logging
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegressio... | |
for function pointers.
Returns
-------
pyx : str
Cython pyx header file as in-memory string.
"""
ts = ts or TypeSystem()
m = {'extra': mod.get('extra', ''),
'docstring': mod.get('docstring', "no docstring, please file a bug report!"),
"pyx_filename": mod.get("pyx_filename", "")}
attrs = []
import_tups = se... | |
"Define basic subroutines useful for all AI players"
from ..board import black, white, empty, Board, InvalidMoveError
import numpy as np
import unittest
class Playerlibrary(object):
"""
A library class that holds basic subroutines that are useful for all
kinds of artificial-intelligence-type (AI-type) players, e.g... | |
0, 0))))
self.assertTrue((2, 0, 1) in context._agent_manager._ghosted_agents)
ghosted_to_ranks = context._agent_manager._ghosted_agents[(2, 0, 1)].ghost_ranks
self.assertTrue(3 in ghosted_to_ranks)
self.assertTrue(g.graph.has_edge(context.ghost_agent((0, 0, 3)), context.agent((2, 0, 1))))
self.assertTrue(1 in gho... | |
<filename>gazoo_device/manager.py<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 ... | |
156, 213, 217);")
self.pushButton_10.setObjectName("pushButton_10")
self.textEdit_84 = QtWidgets.QTextEdit(self.frame_10)
self.textEdit_84.setGeometry(QtCore.QRect(0, 70, 561, 41))
self.textEdit_84.setStyleSheet("background-color: rgba(255, 255, 255, 0);\n"
"border:false;")
self.textEdit_84.setObjectName("textEdit... | |
V30 47 C 13.107 12.648 5.739 0\n',
'M V30 48 C 13.377 13.456 4.479 0\n',
'M V30 49 C 13.104 12.616 3.239 0\n',
'M V30 50 H 12.995 15.351 8.695 0\n',
'M V30 51 H 14.647 12.422 7.586 0\n',
'M V30 52 H 13.724 11.889 5.786 0\n',
'M V30 53 H 14.302 13.752 4.474 0\n',
'M V30 54 H 12.809 14.243 4.469 0\n',
'M V30 55 H... | |
If you specify nothing, the default is to assume the file is
located as follows: Output_Storage\Scenario_Name\sets\pysedsim_ref_set.ref, where output storage is named
appropriately in the input_file_name file.
:return:
'''
[num_scenarios, simulation_titles_list, imported_specs, main_input_files_dir, main_output_... | |
<reponame>artuchavez/ArtificialIntelligence
# MIT 6.034 Lab 9: Boosting (Adaboost)
from tester import make_test, get_tests
from utils import *
lab_number = 9 #for tester.py
F = Fraction #lazy alias
def initialize_2_getargs() : #TEST 1
return [["PointA"]]
initialize_2_expected = {"PointA":1}
def initialize_2_testan... | |
import os
import numpy
import scipy
import scipy.optimize
from cryspy.A_functions_base.symmetry_elements import \
calc_asymmetric_unit_cell_indexes
from cryspy.A_functions_base.mempy import \
calc_mem_col, \
calc_mem_chi, \
calc_symm_elem_points_by_index_points, \
get_uniform_density_col, \
renormailize_density... | |
from functools import reduce
from operator import __mul__
import pytest
from treevalue.tree import func_treelize, TreeValue, method_treelize, classmethod_treelize, delayed
# noinspection DuplicatedCode
@pytest.mark.unittest
class TestTreeFuncFunc:
def test_tree_value_type(self):
class _MyTreeValue(TreeValue):
pa... | |
<filename>composer/utils/_time_conversion.py<gh_stars>0
# Copyright 2021 MosaicML. All Rights Reserved.
import textwrap
import warnings
from typing import Optional, Union
from composer.core import Time, TimeUnit
def convert(
time: Union[str, Time],
unit: Union[TimeUnit, str],
*,
steps_per_epoch: Optional[int] =... | |
I1IiiI - iIii1I11I1II1
if ( OOo000 == LISP_DDT_ACTION_DELEGATION_HOLE ) :
lisp_send_negative_map_reply ( O0o00000o0O . lisp_sockets , OOoO . eid ,
OOoO . group , O0o00000o0O . nonce , O0o00000o0O . itr , O0o00000o0O . sport , 15 , None , False )
O0o00000o0O . dequeue_map_request ( )
if 1 - 1: O0 . Ii1I % Ii1I + II... | |
links:
if link.get('title', '') == 'Opendap':
opendap_url = link.get('href', None)
if not opendap_url:
continue
date_property = properties.get('date', None)
if date_property:
split_date = date_property.split('/')
# remove trailing symbols from times
start_time = datetime.strptime(split_date[0].split('.')[0].sp... | |
import copy
import datetime
import re
from wikibaseintegrator.wbi_config import config
from wikibaseintegrator.wbi_jsonparser import JsonParser
class BaseDataType:
"""
The base class for all Wikibase data types, they inherit from it
"""
DTYPE = 'base-data-type'
sparql_query = '''
SELECT * WHERE {... | |
<filename>fcts/servers.py
import typing
from utils import Zbot, MyContext
import time
import emoji
import copy
import discord
from discord.ext import commands
from math import ceil
roles_options = ["clear","slowmode","mute","kick","ban","warn","say","welcome_roles","muted_role",'partner_role','update_mentions','verifi... | |
ln_option_full = ln_option.replace( '?', line_number ).split()
command = [ editor, *ln_option_full, epath ]
po = subprocess.Popen( command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL )
po.wait()
if compressed:
with open( epath ) as ifd, gzip.open( path.as_posix(), 'wt' ) as ofd:
for line in ifd:
ofd.w... | |
#
# Copyright 2009-2015 <NAME>
#
# 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, so... | |
`1`") # noqa: E501
self._id = id
@property
def ifaces(self):
"""Gets the ifaces of this SubnetsSubnetPoolsPool. # noqa: E501
List of interface members in this pool. # noqa: E501
:return: The ifaces of this SubnetsSubnetPoolsPool. # noqa: E501
:rtype: list[SubnetsSubnetPoolIface]
"""
return self._ifaces
@... | |
<gh_stars>1-10
#!/usr/bin/env python
#############################################################################
##
# This file is part of Taurus
##
# http://taurus-scada.org
##
# Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain
##
# Taurus is free software: you can redistribute it and/or modify
# it under... | |
<gh_stars>0
import logging
import os
from decimal import Decimal
from time import sleep
import requests
from hexbytes import HexBytes
from web3 import Web3
from web3 import contract
from web3.contract import Contract
from config.constants import BASE_CURRENCIES
from config.constants import GAS_LIMITS
from config.cons... | |
from center of images.
Parameters
----------
crop_size : tuple, list or ndarray of int
(z,y,x)-shape of central crop along three axes(z,y,x order is used).
crop_mask : bool
if True, crop the mask in the same way.
Returns
-------
batch
"""
crop_size = np.asarray(crop_size).reshape(-1)
crop_halfsize = np.ri... | |
= open(self._manip_file, 'rb')
self._front = ABS_PATH + '/files/front.jpg'
self.front = open(self._front, 'rb')
self._side = ABS_PATH + '/files/side.jpg'
self.side = open(self._side, 'rb')
self._top = ABS_PATH + '/files/top.jpg'
self.top = open(self._top, 'rb')
self._choice0sm = ABS_PATH + '/files/choice0sm.... | |
from __future__ import absolute_import
from __future__ import print_function
__author__ = 'marafi'
import os
# from numba import jit
def ExtractGroundMotion(Folder_Location):
GMids = []
GMFiles = {}
GMData = {}
Dt = {}
NumPoints = {}
# for subdir, dirs, files in os.walk(Folder_Location, True):
files = [f for f... | |
<gh_stars>1-10
# coding: utf-8
import typing
import weakref
from math import floor
import pyglet
import time
from cocos.collision_model import AARectShape
from pyglet.window import mouse
import cocos
from cocos import collision_model
from cocos import euclid
from cocos.audio.pygame import mixer
from cocos.layer impo... | |
None:
# That tx finished. No current tx.
return None
assert tx.depth == 0
return tx
except IndexError:
return None
@property
def accounts(self):
return list(self._world_state.keys())
@property
def normal_accounts(self):
accs = []
for address in self.accounts:
if len(self.get_code(address)) == 0:
accs.a... | |
<reponame>dgerod/more-dmps
import numpy as np
from cs import CanonicalSystem
class TdwFormulation(object):
def __init__(self, ay=None, by=None):
# Parameters as defined in Schaal 2012
if ay is None: ay = 25.
self.ay = ay
if by is None: by = ay/4.
self.by = by
def acceleration(self, x, dx, start, goal, tau,... | |
<filename>batchgenerators/transforms/color_transforms.py<gh_stars>0
# Copyright 2017 Division of Medical Image Computing, German Cancer Research Center (DKFZ)
#
# 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... | |
<reponame>demirdogukan/InsiderPycraft
if not __name__ == "__main__":
print("Started <Pycraft_Settings>")
class GenerateSettings:
def __init__(self):
pass
def settings(self):
try:
self.Display.fill(self.BackgroundCol)
self.mod_Pygame__.display.flip()
self.mod_CaptionUtils__.GenerateCaptions.GetNormal... | |
ForegroundLayer = None
ItemIndexMethod = None
ItemLayer = None
NoIndex = None
SceneLayer = None
SceneLayers = None
__new__ = None
changed = None
focusItemChanged = None
sceneRectChanged = None
selectionChanged = None
staticMetaObject = None
class QFileIconProvi... | |
these to a non-empty value.
request = library.ListBooksRequest()
request.parent = 'parent/value'
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.list_books),
'__call__') as call:
call.return_value = library.ListBooksResponse()
client.list_books(... | |
baseclass.
"""
def __init__(self):
self._id = 1
self._store = {}
self._base = PEAKS_DICT
def iter_assigned(self):
"""
Iterate over all assigned peaks
:return: Assigned peak
:rtype: dict
"""
for peak_id, peak in self._store.items():
if self.is_assigned(peak_id):
yield peak_id, peak
def iter_no... | |
#!/usr/bin/env python
# Copyright (C) 2007 <NAME>' <<EMAIL>>.
# Use of this source code is governed by MIT license that can be
# found in the LICENSE file.
import contextlib
import errno
import select
import socket
import sys
import time
from pyftpdlib._compat import PY3
from pyftpdlib.ioloop import Acceptor
from py... | |
left and right names.
Just to make it easier for people, we generate a name
which is easy to display of the form "LEFT - RIGHT".
The individual properties are available if the user
wants to generate a more complex name.
>>> x = {}
>>> _make_joined_name(x)
>>> x
{}
>>> x = {'name:left':'Left'}
>>> _make_joi... | |
<reponame>sethsource/Draco
#-----------------------------*-python-*----------------------------------------#
# file config/application_unit_test.py
# author <NAME> <<EMAIL>>
# date Monday, August 12, 2016, 5:44 pm
# brief Provide a python class that aids in creating unit tests that run
# interactive user codes (i.e.: r... | |
<gh_stars>1-10
"""
Modules to Set default parameters:
<NAME> FMP Berlin
"""
import de.bruker.nmr.mfw.root as root
import sys
sys.path.append(root.UtilPath.getTopspinHome()+ '/exp/stan/nmr/py/BioPY/modules/')
import math
import TopCmds
import IntShape
import CPDtools
import TS_Version as Ver
#Parameter handling Bru v... | |
ae.associate('localhost', 11112)
assert not assoc.is_established
assert assoc.is_rejected
scp.shutdown()
def test_unknown_abort_source(self):
"""Test an unknown abort source handled correctly #561"""
def handle_req(event):
pdu = b"\x07\x00\x00\x00\x00\x04\x00\x00\x01\x00"
event.assoc.dul.socket.send(pdu)
# G... | |
'''
Functions for use
'''
import torch
from torch.autograd import Variable
import numpy as np
import itertools
import os
import random
import pickle
import torch as t
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from sklearn.model_selection import StratifiedShuffleSplit
from sklearn.model_... | |
import numpy as np
import scipy.sparse as spsp
from sklearn.preprocessing import StandardScaler
from scedar import utils
from scedar.eda.plot import regression_scatter
from scedar.eda.plot import hist_dens_plot
from scedar.eda import mtype
from scedar.eda import stats
class SampleFeatureMatrix(object):
"""
Samp... | |
# list of lists to set of tuples
cycles_copy = copy.deepcopy(cycles) # store cycles found before fixing
# fix cycles in current subset of edges
if len(cycles_copy)>0:
if verbose:
print '>>%d cycles found!'%len(cycles)
print '>>Finding edges to remove to break cycles in solution'
if fix_cycles_method == 'mip':
... | |
# read complete
fsm.If(rdata.rvalid, rdata.rready,
read_count == 0).goto_init()
def connect(self, index, ports, name):
if not self.noio:
raise ValueError('I/O ports can not be connected to others.')
ports = defaultdict(lambda: None, ports)
if '_'.join([name, 'awid']) in ports:
awid = ports['_'.join([name, 'a... | |
elif block_name == 'p':
if record_data:
element_type = ArticleElementType.PARAGRAPH
target_txt = format_text(child.text)
element_list.append(ArticleElement(type=element_type, content=target_txt))
elif block_name == 'div' and 'tables' in child_class:
if record_data:
element_type = ArticleElementType.TABLE
tbl = ... | |
handling #############################################
# see func_block_disable_msg.py test case for expected behaviour
def process_tokens(self, tokens):
"""Process tokens from the current module to search for module/block level
options."""
control_pragmas = {"disable", "enable"}
prev_line = None
saw_newline = ... | |
ids = torch.LongTensor(ids)
sids = torch.LongTensor(sids)
tids = torch.LongTensor(tids)
lids = torch.LongTensor(lids)
return ids, sids, tids, lids, cls_label
else:
# test
return bundle['context'], bundle['responses'], bundle['label']
def save(self):
if self.args['mode'] == 'train':
data = torch.save((self.da... | |
from django.test import TestCase
from tests.models import Invoice
from django_logic import Process, Transition
from django_logic.exceptions import TransitionNotAllowed
class User:
def __init__(self, is_allowed=True, is_staff=False):
self.is_allowed = is_allowed
self.is_staff = is_staff
def allowed(instance, us... | |
from the extension of the given filename.
>>> getFileType('test.cpp') == FILETYPE_CPP
True
>>> getFileType('path/file.h') == FILETYPE_CPP
True
>>> getFileType('test.dddoc') == FILETYPE_DDDOC
True
Args:
filename Filename to parse.
Returns:
One of {FILETYPE_CPP, FILETYPE_DDDOC, FILETYPE_OTHER}, depending
... | |
"_i" in first_layer or "_o" in first_layer:
mp_cost["Message Size"] += 0
else:
mp_cost["Message Size"] += first_node[first_layer]["ifmap"]
if "resnet" in spl["net_name"]:
end_name = None
if "resnet50" in spl["net_name"]:
start_name = 'conv2_1_a'
end_name = "conv5_3_c"
mp_cost["is_resnet"] = True
... | |
in text
)
def justify(
self, texts: Iterable[str], max_len: int, mode: str = "right"
) -> List[str]:
# re-calculate padding space per str considering East Asian Width
def _get_pad(t):
return max_len - self.len(t) + len(t)
if mode == "left":
return [x.ljust(_get_pad(x)) for x in texts]
elif mode == "center":... | |
<reponame>larrycameron80/libtaxii<filename>libtaxii/common.py<gh_stars>0
"""
Common utility classes and functions used throughout libtaxii.
"""
from operator import attrgetter
import random
import re
import sys
from uuid import uuid4
import dateutil.parser
from lxml import etree
import six
try:
import simplejson as... | |
"""
Contains the derived saveable search from GridSearchCV
"""
import numpy as np
import pickle
import os.path
import six
import time
import numbers
import warnings
from collections import defaultdict
from functools import partial
from joblib import Parallel, delayed, logger
from itertools import product
from scipy.sta... | |
<reponame>peigongdh/collection
#! /usr/bin/python
#======================================================================
#
# cavemake.py - cavemake routine
#
# HISTORY:
# May.8 2008 skywind - create this file with some basic interface
# May.19 2008 skywind - add file saving interface
# Apr.25 2008 skywind - ad... | |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from datetime import datetime
# import rasahub_google_calendar
from time import gmtime, time, strftime
import json
import locale
import logging
import math
import mysql.c... | |
if not cartopy_enabled():
raise RuntimeError("'cartopy' is not "
"installed or is disabled")
return self._cartopy()
def pyngl(self, geobounds, **kwargs):
"""Return a :class:`Ngl.Resources` object for the map projection.
Args:
geobounds (:class:`wrf.GeoBounds`, optional): The geobounds to
get the extents.... | |
"""
Hyperparameter Distributions
====================================
Here you'll find a few hyperparameter distributions. It's also possible to create yours by inheriting
from the base class. Each distribution must override the method ``rvs``, which will return a sampled value from
the distribution.
..
Copyright 201... | |
Hebrew calendar."""
return mod(h_year, 7) == 0
# see lines 1605-1617 in calendrica-3.0.cl
def last_day_of_hebrew_month(h_month, h_year):
"""Return last day of month h_month in Hebrew year h_year."""
if ((h_month in [IYYAR, TAMMUZ, ELUL, TEVET, ADARII])
or ((h_month == ADAR) and (not is_hebrew_leap_year(h_year)))
... | |
when calling `releases_availableToTester`") # noqa: E501
# verify the required parameter 'app_name' is set
if ('app_name' not in params or
params['app_name'] is None):
raise ValueError("Missing the required parameter `app_name` when calling `releases_availableToTester`") # noqa: E501
collection_formats = {}
pat... | |
the following:
'form-group has-error custom-class'
"""
classes = ['form-group']
if self.style == styles.BOOTSTRAP_4 and self.form_type == formtype.HORIZONTAL:
classes.append('row')
if self.error and self.style == styles.BOOTSTRAP_3:
classes.append('has-error')
if self.form_group_css_class:
classes.append(self... | |
<gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Reduces the number of points in SMLM images to a given maximum count or fraction.
This script takes a folder of SMLM files and, for each file, saves a copy of it up
to the specified maximum number of points in the output folder.
The number of points is g... | |
is None:
vmin = min_toplot
extend = _extend_mapping[vmin <= min_toplot, vmax >= max_toplot]
if pop_ids is not None:
data_pop_ids = model_pop_ids = resid_pop_ids = pop_ids
if len(pop_ids) != 2:
raise ValueError('pop_ids must be of length 2.')
else:
data_pop_ids = masked_data.pop_ids
model_pop_ids = masked_mode... | |
hasattr(weekly_schedule, "warnings"):
print_messages("Warning", weekly_schedule.warnings)
else:
print("Failed to create schedule {}".format(schedule_name))
def create_monthly_schedule(server, args):
monthly_interval = TSC.MonthlyInterval(start_time=time(args.start_hour, args.start_minute),
interval_value=args.mo... | |
'type': 'ViInt32',
'documentation': {
'description': 'Specifies the number of Script triggers supported by the device. Use this attribute when NIFGEN_ATTR_OUTPUT_MODE is set to NIFGEN_VAL_OUTPUT_SCRIPT.',
},
},
1150273: {
'access': 'read only',
'channel_based': 'False',
'lv_property': 'Instrument:Data Marker Event... | |
client_id, flow_id, next_needed_request=1)
self.assertEqual(requests_for_processing, {})
client_id, flow_id = self._SetupClientAndFlow(next_request_to_process=3)
for request_id in [1, 3, 4, 5, 7]:
request = rdf_flow_objects.FlowRequest(
client_id=client_id,
flow_id=flow_id,
request_id=request_id,
needs_proces... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.