input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
<reponame>Cyberface/nrutils_dev<filename>nrutils/handlers/bam.py
#
from nrutils.core.basics import *
from glob import glob as ls
from os.path import getctime
from numpy import array,cross,zeros,dot,abs,sqrt,sign
from numpy.linalg import inv, norm
from numpy import sum as asum
# Determine whether the folder containing... | |
0x0d, 2), (IDX_2, 0x0f, 2), (IDX_2, 0x09, 2), (IDX_2, 0x03, 2),
(IDX_2, 0x0d, 2), (IDX_2, 0x0a, 2), (IDX_8, 0x24, 8), (IDX_2, 0x08, 2), (IDX_3, 0x06, 3),
]
# --------------------------------------------------------------------------------------------------
if __name__ == "__main__":
s = Solver() # our z3 solver
x_... | |
import tensorflow as tf
import tensorflow.contrib.slim as slim
from tensorflow.contrib.slim.nets import resnet_v1
import numpy as np
class MultiModal(object):
def __init__(self, mode, learning_rate=0.0001):
self.mode = mode
self.learning_rate = learning_rate
self.hidden_repr_size = 128
self.no_classes = 19
d... | |
import numpy as np
from skimage.draw import line
from scipy.interpolate import splprep, splev
from skimage.morphology import skeletonize
from scipy import ndimage
from scipy.ndimage import map_coordinates
import random
def extractHRFrontsGen(filename, classes, lonOff, latOff):
fronts = [[] for _ in range(len(classes)... | |
<gh_stars>0
import numpy as np
import pandas as pd
import xarray as xr
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.lines import Line2D
from matplotlib.patches import Patch, Ellipse, Circle
from matplotlib.legend_handler import HandlerPatch
import matplotlib... | |
of priors.
Properly initialized, an object of type "FuFPrior"
is callable. On call, it expects a dictionary with
the names and values of the parameters as first
argument and the name of the parameter under consideration
as second argument. The return value should be the
(natural) logarithm of the associated prio... | |
<reponame>Zadigo/zineb
import copy
import os
import re
from collections import OrderedDict
from functools import cached_property
from itertools import chain
from typing import Dict, Generator, List, NoReturn, Tuple, Union
from bs4 import BeautifulSoup
from bs4.element import ResultSet, Tag
from w3lib.html import safe_... | |
<gh_stars>0
from .connections import connections
from .search import Search
from .exceptions import IllegalOperation
class Index(object):
def __init__(self, name, using='default'):
"""
:arg name: name of the index
:arg using: connection alias to use, defaults to ``'default'``
"""
self._name = name
self._doc_typ... | |
<reponame>jayvdb/pypi_librarian
# coding=utf-8
"""
Build tasks
"""
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import glob
import json
import os
import subprocess
import sys
from pynt import task
from pyntcontrib import execute, safe_cd
from semantic_v... | |
<reponame>Bingyan-Liu/DDSC-NET<filename>evaluation_metrics_for_segmentation.py
import numpy as np
from scipy import misc
from os import path, makedirs
from utils.file_management import get_filenames, save_csv_mean_segmentation_performance, save_csv_segmentation_table
EPS = 1e-7
def dice_coefficient_1(binary_segment... | |
= ht.ones((m), split=0)
b = ht.ones((j, k), split=1)
b[0] = ht.arange(1, k + 1)
b[:, 0] = ht.arange(1, j + 1)
ret00 = ht.matmul(a, b)
ret_comp = ht.array(a_torch @ b_torch, split=None)
self.assertTrue(ht.equal(ret00, ret_comp))
self.assertIsInstance(ret00, ht.DNDarray)
self.assertEqual(ret00.shape, (k,))
self... | |
#######################################################################
# This file is part of Pyblosxom.
#
# Copyright (C) 2003-2011 by the Pyblosxom team. See AUTHORS.
#
# Pyblosxom is distributed under the MIT license. See the file
# LICENSE for distribution details.
#################################################... | |
<gh_stars>0
# Copyright 2018 The TensorFlow 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 ... | |
request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_login_theme_css_using_post(async_req=True)
>>> result = thread.get()
:param async_req bool
:param PaletteSettings body:
:param bool dark_foreground: Dark foreground enabled flag
:return: str
If the method ... | |
'''
scriptname = 'eutester_diskpart_script'
self.sys('(echo rescan && echo list disk ) > ' + str(scriptname), code=0)
self.sys('diskpart /s ' + str(scriptname), code=0, timeout=timeout)
def get_diskdrive_for_volume(self, volume):
if not self.is_volume_attached_to_this_instance(volume):
return None
ret_disk = N... | |
%.2f +/- %.2f Myr \n'%(np.median(mega_df[w3].age), med_age_sigma3))
f.write('Unassociated median age: %.2f +/- %.2f Myr \n'%(np.median(mega_df[w0].age), med_age_sigma0))
f.write('\n')
f.close()
""" now do things by environmental mask locations
simple environmental masks cheatsheet
1 = center (small bulge, nucl... | |
from types import *
from types_gc import *
import compilerLib, library
import symtable
import re
import numpy as np
import inspect
from collections import OrderedDict
SPDZ = 0
GC = 1
LOCAL = 2
class Params(object):
intp = 64
f = 32
k = 64
@classmethod
def set_params(cls, int_precision=32, f=32, k=64, parallelis... | |
<filename>glance/store/swift.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010-2011 OpenStack Foundation
# 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
... | |
provider.
:type well_known_open_id_configuration: str
"""
_attribute_map = {
'authorization_endpoint': {'key': 'authorizationEndpoint', 'type': 'str'},
'token_endpoint': {'key': 'tokenEndpoint', 'type': 'str'},
'issuer': {'key': 'issuer', 'type': 'str'},
'certification_uri': {'key': 'certificationUri', 'type': ... | |
<gh_stars>0
#
# Project:
# glideinWMS
#
# File Version:
#
# Description:
# This module implements classes to query the condor daemons
# and manipulate the results
# Please notice that it also converts \" into "
#
# Author:
# <NAME> (Aug 30th 2006)
#
import condorExe
import condorSecurity
import os
import string
impor... | |
code: 200",
"Total identifiers registered with this collection: 201",
"Entries on this page: 1",
" The Green Mouse",
] == test_result.result
assert True == test_result.success
# Next, test failure.
response = mock_response(url, auth, 401, "An error message.")
test_result = SelfTestResult("failure")
assert Fal... | |
be go to create ?
fogapp_name = status['create_fn']['fogapp_name']
fogapp_image = spec['template']['spec']['containers'][0]['image']
fogapp_replicas = spec['replicas']
fogapp_cpu_request = int(spec['template']['spec']['containers'][0]['resources']['requests']['cpu'][:-1])
# fogapp_cpu_limit = spec['template']['sp... | |
1; size: 30; search: "
await app(get_example_scope("GET", "/", query=b"page=2"), mock_receive(), mock_send)
response = app.response
content = await response.text()
assert response.status == 200
assert content == "Page: 2; size: 30; search: "
await app(
get_example_scope("GET", "/", query=b"page=2&size=50"),
... | |
<gh_stars>1-10
# -*- coding: utf-8 -*-
"""
Created on Fri May 10 13:30:43 2019
@author: Darin
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import PolyCollection
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import scipy.sparse as sparse
import Material
import Update
cl... | |
handles categorical colors / legends better.
Parameters
----------
data : array-like, shape=[n_samples, n_features]
Input data. Only the first two components will be used.
c : list-like or None, optional (default: None)
Color vector. Can be a single color value (RGB, RGBA, or named
matplotlib colors), an array ... | |
Counter(flines)
for k in counts.keys():
if k != "N.N.N.N":
r = labels.index(k)
abmat[r,c] += counts[k]
df = pd.DataFrame(abmat, index=labels, columns=samples)
fname = os.path.join(aa_dir,'raw_counts.tsv')
df.to_csv(fname,sep='\t',index=True,header=True)
return 0
# Carnelian features
#def transl... | |
("prop", "1918:397"): "metadataonly",
("prop", "1918:398"): "metadataonly",
("prop", "1918:399"): "metadataonly",
("prop", "1918:4"): "metadataonly",
("prop", "1918:40"): "metadataonly",
("prop", "1918:400"): "metadataonly",
("prop", "1918:401"): "metadataonly",
("prop", "1918:402"): "metadataonly",
("prop", "1... | |
"""
Aqualink API documentation
The Aqualink public API documentation # noqa: E501
The version of the OpenAPI document: 1.0.0
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401
from aqualink_sdk.api_client import ApiClient, Endpoint as _Endpoint
from aqualink_sdk.mod... | |
elif which == 'tick1':
# for cartesian projection, this is bottom spine
return self.spines['bottom'].get_spine_transform()
elif which == 'tick2':
# for cartesian projection, this is top spine
return self.spines['top'].get_spine_transform()
else:
raise ValueError('unknown value for which')
def get_xaxis_text1_t... | |
<reponame>iagcl/data_pipeline
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the... | |
import random
import numpy as np
import scipy
import time
import json
import os
import pdb
import pickle
import pandas
from progressbar import *
from keras.layers import Input, Dense, LSTM, Lambda, concatenate, add, Dot
from keras.models import Sequential, load_model, Model
from keras.optimizers import RM... | |
components[1][:-2]
return components[1];
#isConstructorOrDestructor: string, list
#A variant of the constructor/ destructor check designed to simplify nesting issues
#This requires less strict matching, but I find it difficult to think of non contrived
#examples in the data where this will fail.
def isConstruct... | |
tey ]
# # [ 0 0 1 ][ 1 ] = [ 1 ]
# # or
# # [ x y 1 0 0 0 ] [ A11 ] = [ tex ]
# # [ 0 0 0 x y 1 ] [ A12 ] = [ tey ]
# # [ A13 ]
# # [ A21 ]
# # [ A22 ]
# # [ A23 ]
# # With rows repeated for each point.
# # Solve for Axx values from the known coordinates
# # Then substitute the 2D intersection coordinates as... | |
#!/usr/bin/env python
import struct
from .gdsPrimitives import *
class Gds2reader:
"""Class to read in a file in GDSII format and populate a layout class with it"""
## Based on info from http://www.rulabinsky.com/cavd/text/chapc.html
global offset
offset=0
def __init__(self,layoutObject,debugToTerminal = 0):
se... | |
<reponame>vinc3PO/PubChemPy<filename>pubchempy/compound.py<gh_stars>1-10
import json
from .functions import get_json, request, _parse_prop, request_SDS
from .decorators import deprecated, memoized_property
from .mapper import ELEMENTS, CoordinateType, BondType
from .errors import ResponseParseError, NotFoundError
from ... | |
<reponame>JacobMSD/ef_python<filename>SpatialMesh.py
import sys
import h5py
import numpy as np
from math import ceil
from Vec3d import Vec3d
from common import production_assert
class SpatialMesh():
def __init__( self ):
pass
@classmethod
def init_from_config( cls, conf ):
new_obj = cls()
new_obj.check_correct... | |
bot = ty[i][0]
if top-bot < 0.1:
frac = 0.5
else:
frac = 0.8
arrowheights.append(top - (top-bot)*frac)
for i in range(2*numpops-1):
period = lastperiod[i]
arrowheight = max(popbox[i][0][1],arrowheights[period] -periodposcount[period]*2*arrowheightinc)
head = [confint[i][0],arrowheight]
tail = [pop... | |
<filename>Converse/dialog_tree/tree_manager.py
# Copyright (c) 2020, salesforce.com, inc.
# All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
# For full license text, see the LICENSE file in the repo root
# or https://opensource.org/licenses/BSD-3-Clause
import logging
from collections import deque
from Co... | |
<reponame>hyperion-ml/hyperion
"""
Copyright 2019 Johns Hopkins University (Author: <NAME>)
Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""
import logging
import numpy as np
import torch
import torch.nn as nn
from torch.nn import Conv1d, Linear, BatchNorm1d
from ..layers import ActivationFactory as AF
... | |
# Monitoring provides basic "is it up?" insight, along with performance data about how an installation is running.
# Note: Do NOT return a 'error' state when a 'warning' state would do.
# The system is coded to block on errors during starts / restarts. So, if the number of
# messages in a queue is astronomically high... | |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2019 <NAME> <<EMAIL>>
# All rights reserved.
#
# This code is licensed under the MIT License.
#
# 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 withou... | |
= None
floor: Optional[float] = None
refPeriodStart: Optional[Date] = None
refPeriodEnd: Optional[Date] = None
dayCounter: Optional[DayCounter] = None
isInArrears: Optional[bool] = None
exCouponDate: Optional[Date] = None
class CmsCoupon(BaseModel):
resource_name: Optional[Literal["CmsCoupon"]] = "CmsCoupon"
... | |
%gum %gum\n" % (x1, y1, x2, y2)
fout.write(cmd_str)
cmd_str = "paint %s \n" % (M1_LAYER)
fout.write(cmd_str)
x2 = x_center + PITCH/2 - CHANNEL_LENGTH/2 - 0.31
y2 = y_center + PITCH/2 - CHANNEL_LENGTH/2 - 0.31
cmd_str = "box %gum %gum %gum %gum\n" % (x1, y1, x2, y2)
fout.write(cmd_str)
cmd_st... | |
<gh_stars>1-10
#!/usr/bin/env python
import configparser
import copy
import importlib
import logging
import re
from abc import ABC, abstractmethod
from pathlib import Path
from typing import List, Optional
# import deepdiff
from javus.gppw import GlobalPlatformProWrapper
from javus.settings import PROJECT_ROOT
from j... | |
#
# Copyright (c) 2008-2015 Citrix Systems, Inc.
#
# 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 ... | |
return _FSO_Comm_swig.Geometric_Loss_ff_sptr_LinkLen(self)
def set_Rx_Dia(self, Rx_Dia):
"""
set_Rx_Dia(Geometric_Loss_ff_sptr self, float Rx_Dia)
Set geometric loss receiver aperture diameter.
"""
return _FSO_Comm_swig.Geometric_Loss_ff_sptr_set_Rx_Dia(self, Rx_Dia)
def Rx_Dia(self):
"""
Rx_Dia(Geometric... | |
1
# Main part of the encryption algorithm, the number cruncher :)
def __des_crypt(self, block, crypt_type):
"""Crypt the block of data through DES bit-manipulation"""
block = self.__permutate(des.__ip, block)
Bn = [0] * 32
self.L = block[:32]
self.R = block[32:]
# Encryption starts from Kn[1] through to Kn[16... | |
= CFUNCTYPE(None, GLenum, GLenum, POINTER(GLint)) # GL/glext.h:5223
PFNGLPIXELTRANSFORMPARAMETERFVEXTPROC = CFUNCTYPE(None, GLenum, GLenum, POINTER(GLfloat)) # GL/glext.h:5224
# EXT_pixel_transform_color_table (GL/glext.h:5227)
GL_EXT_pixel_transform_color_table = 1 # GL/glext.h:5228
# EXT_shared_texture_palette (GL... | |
the string cannot be converted to a numeric value, the Stata
system missing value is returned.
"""
return _stp._st_getrealofstring(s)
@staticmethod
def getTempFile():
"""
Get a valid Stata temporary filename.
Returns
-------
str
The filename, including its path.
"""
return _stp._st_gettempfile()
@stat... | |
elem in lc_result_final],
}
)
if method == "efficiency":
X = result["n"]
Y = [
[
[
result[metric][i] - std_coeff * result[metric + "_std"][i]
for i in range(len(sizes))
],
result[metric],
[
result[metric][i] + std_coeff * result[metric + "_std"][i]
for i in range(len(sizes))
],
],
[
[
result[metric +... | |
= self.predictions(sequence_output)
seq_relationship_score = self.seq_relationship(pooled_output)
return prediction_scores, seq_relationship_score
class BertPreTrainedModel(PreTrainedModel):
""" An abstract class to handle weights initialization and
a simple interface for downloading and loading pretrained mod... | |
<gh_stars>0
from django.test import TestCase, override_settings
from django.db.models.signals import pre_delete
from unittest.mock import MagicMock
from django.apps import apps
from django.utils.crypto import get_random_string
from django.contrib.auth.models import User
from django.core.files.uploadedfile import Simple... | |
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Callable, Dict, Iterator, List, Optional, Set, Tuple, Union
from darwin.path_utils import construct_full_path
Point = Dict[str, float]
BoundingBox = Dict[str, float]
Polygon = List[Point]
ComplexPolygon = List[Polygon]
Node = Di... | |
import functools
import struct
def compressed_unimplemented_instruction(word, **kwargs):
return {
'cmd': 'Undefined',
'word': word,
'size': 2,
}
def uncompressed_unimplemented_instruction(word, **kwargs):
return {
'cmd': 'Undefined',
'word': word,
'size': 4,
}
def c_j(word, **kwargs):
# C.J performs an unc... | |
### All utility function to obtain perturbation mask
import numpy as np
import itertools
import random
import math
from utils import *
import os
import time
import scipy.io as scio
import datetime
import re
import matplotlib.pyplot as plt
import pylab
import os
import csv
from skimage import transform, filters
from ... | |
<filename>project/apps/salesforce/models.py<gh_stars>10-100
import json
# Third-Party
from model_utils import Choices
from distutils.util import strtobool
# Local
from apps.bhs.models import Convention, Award, Chart, Group, Person
from apps.registration.models import Contest, Session, Assignment, Entry
class SfConve... | |
0.00435488,
'Renaming Unit/Int Front End RAT/Subthreshold Leakage with power gating': 0.00248228,
'Renaming Unit/Peak Dynamic': 3.58947,
'Renaming Unit/Runtime Dynamic': 0.274562,
'Renaming Unit/Subthreshold Leakage': 0.0552466,
'Renaming Unit/Subthreshold Leakage with power gating': 0.0276461,
'Runtime Dynamic':... | |
self.cfg["word_embedding"]
self.sess, self.saver = None, None
# Add placeholder
self.words = tf.placeholder(tf.int32, shape=[None, None], name="words") # shape = (batch_size, max_time)
self.labels = tf.placeholder(tf.int32, shape=[None, None], name="label") # shape = (batch_size, max_time - 1)
self.seq_le... | |
class LeagueRecom:
"""
A LeagueRecom object holds information about the rankings and results of a couple of seasons
from a certain league
Parameters
----------
games : list
A list with Game objects stored in it
rankings : list
A list with Ranking objects stored in it
w_points : int
The amount of points a fo... | |
"""
Connection pooling and host management.
"""
import logging
import time
from threading import Lock, RLock, Condition
import weakref
try:
from weakref import WeakSet
except ImportError:
from cassandra.util import WeakSet # NOQA
from cassandra import AuthenticationFailed
from cassandra.connection import MAX_STREAM... | |
0)
m.e98 = Constraint(expr= m.x413 == 0)
m.e99 = Constraint(expr= m.x414 == 0)
m.e100 = Constraint(expr= m.x127 - m.x397 - m.x400 == 0)
m.e101 = Constraint(expr= m.x128 - m.x398 - m.x401 == 0)
m.e102 = Constraint(expr= m.x129 - m.x399 - m.x402 == 0)
m.e103 = Constraint(expr= m.x133 - m.x409 - m.x412 == 0)
m.e104 = Cons... | |
import argparse
import os
import shutil
import time
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils.data
from Utils import load
from Models import apolo_resnet
import torchvision.transforms as transforms
import torchvision.datasets ... | |
from __future__ import annotations
import pyqtgraph as pg
from pyqtgraph import colormap as cmap
from typing import Generic, Iterator, Sequence, TypeVar, overload, MutableSequence
import numpy as np
from ._utils import convert_color_code, to_rgba
from .components import Legend, Region, ScaleBar, TextItem
from .graph_i... | |
<reponame>verilylifesciences/analysis-py-utils
# Copyright 2019 Verily Life Sciences Inc. 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/licens... | |
used are::
network_id -- string -- TODO: type description here.
Example:
profile_id -- string -- TODO: type description here.
Example:
Returns:
mixed: Response from the API. Successful operation
Raises:
APIException: When an error occurs while fetching the data from
the remote API. This except... | |
<filename>src/isle/h5io.py
r"""!\file
Routines for working with HDF5.
"""
from logging import getLogger
from pathlib import Path
from itertools import chain
import yaml
import h5py as h5
import numpy as np
from . import Vector, isleVersion, pythonVersion, blazeVersion, pybind11Version
from .random import readStateH5... | |
server
def test_vsis3_opendir():
if gdaltest.webserver_port == 0:
pytest.skip()
# Unlimited depth
handler = webserver.SequentialHandler()
handler.add('GET', '/vsis3_opendir/', 200, {'Content-type': 'application/xml'},
"""<?xml version="1.0" encoding="UTF-8"?>
<ListBucketResult>
<Prefix/>
<Marker/>
<Conten... | |
hasattr(self, 'bgp_cer_cidr') and self.bgp_cer_cidr is not None:
_dict['bgp_cer_cidr'] = self.bgp_cer_cidr
if hasattr(self, 'bgp_ibm_asn') and self.bgp_ibm_asn is not None:
_dict['bgp_ibm_asn'] = self.bgp_ibm_asn
if hasattr(self, 'bgp_ibm_cidr') and self.bgp_ibm_cidr is not None:
_dict['bgp_ibm_cidr'] = self.bgp_i... | |
(delem[profile]['members'] is None):
intf["interfaces"][0]["nvPairs"]["MEMBER_INTERFACES"] = ""
else:
intf["interfaces"][0]["nvPairs"]["MEMBER_INTERFACES"] = ",".join(delem[profile]['members'])
intf["interfaces"][0]["nvPairs"]["PC_MODE"] = delem[profile]['pc_mode']
intf["interfaces"][0]["nvPairs"]["INTF_VRF"] = de... | |
"""
Module: LMR_verify_gridPRCP.py
Purpose: Generates spatial verification statistics of LMR gridded precipitation
against various gridded historical instrumental precipitation datasets
and precipitation from reanalyses.
Originator: <NAME>, U. of Washington, March 2016
Revisions:
"""
import matplotlib
# need t... | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#=======================================================================
#
# xchacha.py
# ----------
# Simple model of the XChaCha stream cipher. Used as a reference for
# the HW implementation. Also used as part of the TRNG Python model.
# The code follows the structure o... | |
self.de_acti3(self.de_conv3(self.de_padd3(self.de_upbi3(d3))))
d5 = self.de_conv4(self.de_padd4(d4))
d5_1 = self.de_acti4_1(self.de_conv4_1(self.de_padd4_1(d4)))
lr_x = lr2
lr_x2 = lr_x * self.down(msk) + self.down(rimg) * (1.0 - self.down(msk))
compltd_img = d5
compltd_img = compltd_img * msk + rimg ... | |
path == fileobj.name or fd == fileobj.fileno():
break
else:
self.fail("no file found; files=%s" % repr(p.open_files()))
self.assertEqual(path, fileobj.name)
if WINDOWS:
self.assertEqual(fd, -1)
else:
self.assertEqual(fd, fileobj.fileno())
# test positions
ntuple = p.open_files()[0]
self.assertEqual(ntuple[0]... | |
TX'},
'1512407':{'en': 'Austin, TX'},
'1512414':{'en': 'Austin, TX'},
'1512416':{'en': 'Austin, TX'},
'1512418':{'en': 'Austin, TX'},
'1512419':{'en': 'Austin, TX'},
'1512420':{'en': 'Austin, TX'},
'151244':{'en': 'Austin, TX'},
'1512446':{'en': 'Rockdale, TX'},
'151245':{'en': 'Austin, TX'},
'1512462':{'en':... | |
'node': self._primary_key,
'description_new': self.description,
'description_original': original
},
auth=auth,
save=False,
)
if save:
self.save()
return None
def update_search(self):
from website import search
try:
search.search.update_node(self)
except search.exceptions.SearchUnavailableError as e:
log... | |
<filename>dse_simulation/test/test_information_filter.py
#!/usr/bin/env python
from __future__ import print_function
import roslib
import os
import sys
import unittest
import rospy
import rostest
from optparse import OptionParser
import numpy as np
import datetime
import time
from dse_msgs.msg import PoseMarkers
from ... | |
other functions to work with the new field.
global u, v, arrows, stacks, polar_tracker, dyn_coord
# take inputs and globally update them
update_variables()
# set radial tracker
polar_tracker = False
# take all these values, and the input from field component bnoxes to set up the field:
u, v = eq_to_comps(string_... | |
``ResourcePool``. When methods return a value of this class as a
return value, the attribute will be an identifier for the resource
type: ``ResourcePool``.
If attribute is None, the system will use the resource pool of the
source virtual machine. If this results in a conflict due to other
placement parameters, the... | |
p2sec2))
ax.set_title(f"{abf.abfID} Pulse 1 [{timeNote}]")
addComments(abf)
ax.set_ylabel(abf.sweepLabelY)
ax.set_xlabel(abf.sweepLabelX)
plotFigSave(abf, tag=f"generic-paired-pulses", labelAxes=False)
# RATIO
plotFigNew(abf)
ax = plt.gcf().add_subplot(1, 1, 1) # pulse2/pulse1 ratio
ratioAvg = sweepAvgs2/swee... | |
"""
Evaluation function of an individual
"""
from __future__ import division
import os
import pandas as pd
import numpy as np
from cea.optimization.master import generation
from cea.optimization.master import summarize_network
from cea.optimization.constants import *
from cea.optimization.master import cost_model
fro... | |
"""Module for launching MAPDL locally or connecting to a remote instance with gRPC."""
import platform
from glob import glob
import re
import warnings
import os
import appdirs
import tempfile
import socket
import time
import subprocess
from ansys.mapdl import core as pymapdl
from ansys.mapdl.core.misc import is_float... | |
<reponame>jonathanj/mantissa<filename>xmantissa/test/test_interstore.py
"""
Tests for inter-store messaging module, L{xmantissa.messaging}.
This module contains tests for persistent messaging between different accounts.
"""
import gc
from datetime import timedelta
from zope.interface import implements
from twist... | |
# - *- coding: utf-8 -*-
from unittest import TestCase
from nose.tools import ok_, eq_
from datetime import date
from daynextprev import (
prev_month,
next_month,
is_less_ym,
months,
months_backward,
is_leapyear,
days_of_month,
next_day,
prev_day,
days,
days_backward,
this_week,
next_week,
prev_week,
W... | |
"""
Unit tests for meta/networks/splitting/multi_splitting_base.py.
"""
import math
import random
from itertools import product
from typing import Dict, Any, List
import numpy as np
from scipy import stats
import torch
import torch.nn.functional as F
from gym.spaces import Box
from meta.networks.utils import init_ba... | |
"""Test the SSDP integration."""
import asyncio
from datetime import timedelta
from ipaddress import IPv4Address, IPv6Address
from unittest.mock import patch
import aiohttp
from async_upnp_client.search import SSDPListener
from async_upnp_client.utils import CaseInsensitiveDict
import pytest
from homeassistant import... | |
<filename>src/skmultiflow/meta/classifier_chains.py
import numpy as np
import copy
from skmultiflow.core.base import StreamModel
from sklearn.linear_model import LogisticRegression, SGDClassifier
from skmultiflow.utils import check_random_state
class ClassifierChain(StreamModel):
""" Classifier Chains for multi-labe... | |
= self._main_grid.get_mid_point(self.get_grid_coord_from_points_coords(start_point),
self.get_grid_coord_from_points_coords(end_point))
return list(filter(lambda x: x > 1, self._main_grid.get_adjacent_values(mid_point)))
def get_compartments_for_line_duplicates(self, line):
'''
Finding the compartment connected ... | |
<reponame>lkusch/Kratos<filename>applications/SwimmingDEMApplication/python_scripts/daitche_quadrature/quadrature.py
import math
import cmath
import mpmath
import matplotlib.pyplot as plt
from bigfloat import *
import sys
# **********************************************************************************************... | |
#@+leo-ver=5-thin
#@+node:ekr.20211021200745.1: * @file ../plugins/picture_viewer.py
#@+<< docstring (picture_viewer.py) >>
#@+node:ekr.20211021202710.1: ** << docstring (picture_viewer.py) >>
"""
Display image files in a directory tree as a slide show.
This plugin will display all files in a directory tree that have ... | |
model.item_input: item_input[i][:, None],
# model.labels: labels[i][:, None]}
# train_loss += sess.run(model.loss, feed_dict)
# else:
# for i in range(len(labels)):
# feed_dict = {model.user_input: user_input[i][:, None],
# model.item_input: item_input[i],
# model.labels: labels[i][:, None]}
# loss = sess.run(m... | |
noqa
correct_cb3 = """
{# correct_cb3 #}
{% set version = "1.14.5" %}
{% set build_number = 1 %}
{% set variant = "openblas" %}
{% set build_number = build_number + 200 %}
package:
name: numpy
version: {{ version }}
source:
url: https://github.com/numpy/numpy/releases/download/v{{ version }}/numpy-{{ version }}.... | |
manager
#doc.AddUndo(UNDO_BITS, obj)
doc.SetActiveObject(obj, c4d.SELECTION_ADD)
def SelectObjects(objs):
for obj in objs:
Select(obj)
def DeselectAll(inObjMngr=False):
""" Not the same as ``BaseSelect.DeselectAll()``.
:param bool inObjMngr: if True, run the deselect command for the
Object Manager, else t... | |
TBI - Shadow projection type? Matrix value?
new_projection = MappingProjection(sender=correct_sender,
receiver=input_port)
self.add_projection(new_projection, sender=correct_sender, receiver=input_port)
return original_senders
def _update_shadow_projections(self, context=None):
for node in self.nodes:
for input... | |
# output cif files for incorrect space groups
if check is True:
if check_struct_group(rand_crystal, sg, dim=3):
pass
else:
t += " xxxxx"
# rand_crystal.to_file("poscar", "1.vasp")
# import sys
# sys.exit()
outstructs.append(rand_crystal.to_pymatgen())
outstrings.append(str("3D_Molecular_" + str(sg) + ".vasp")... | |
<filename>zippy/benchmarks/src/benchmarks/whoosh/tests/test_parse_plugins.py
from __future__ import with_statement
import inspect
from datetime import datetime
from whoosh import analysis, fields, formats, qparser, query
from whoosh.compat import u, text_type, xrange
from whoosh.filedb.filestore import RamStorage
from... | |
<reponame>wuli133144/video_parse
"""
mp4 support parse maintain tools
"""
import os
import sys
import math
from Mp4.stream_file import *
from Mp4.ftypbox import *
from Mp4.define import *
from Mp4.freebox import *
from Mp4.mdatbox import *
from Mp4.moovbox import *
from Mp4.mvhd_box import *
from Mp4.track import... | |
import numpy as np
import os
def parse_automesh(file):
if os.path.exists(file):
lines = open(file, 'r').readlines()
return lines
def parse_sfo(filename, verbose=False):
"""
Master parser for the SFO file.
Returns the output dict.
"""
groups = parse_sfo_into_groups(filename)
d = {
'wall_segments':[]... | |
'spiderwebs',
'spiel',
'spiffy',
'spikan',
'spikanor',
'spike',
'spikes',
'spiko',
'spill',
'spilled',
'spilling',
'spills',
'spin',
'spin-out',
'spin-to-win',
'spinach',
'spines',
'spinner',
'spinning',
'spins',
'spiral',
'spirit',
'spirited',
'spiriting',
'spirits',
'spit',
'spiteful',
'spi... | |
at (-1, 1, -1, 1),
A vertex at (-1, -1, -1, 1),
A vertex at (-1, -1, -1, -1))
You can use the
:meth:`~sage.geometry.polyhedron.representation.PolyhedronRepresentation.index`
method to enumerate vertices and inequalities::
sage: def get_idx(rep): return rep.index()
sage: [get_idx(_) for _ in face.ambient_Hrepre... | |
from random import random
import subprocess
from time import time
from random import randint, random
from tqdm import trange
import matplotlib.pyplot as plt
from math import sqrt, exp
pattern_num = 5
index_num = 38
'''
translate_raw = [
[0, 1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14, 15], [16, 17, 18, 19, 20, 2... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.