uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
64ac112cc0f20a8cbade335d | train | class | class EnsembleCalibrationAssertions(IrisTest):
"""Additional assertions, specifically for usage in the
ensemble calibration unit tests."""
def assertEMOSCoefficientsAlmostEqual(self, first, second):
"""Overriding of the assertArrayAlmostEqual method to check whether
array are matching to 4... | class EnsembleCalibrationAssertions(IrisTest):
| """Additional assertions, specifically for usage in the
ensemble calibration unit tests."""
def assertEMOSCoefficientsAlmostEqual(self, first, second):
"""Overriding of the assertArrayAlmostEqual method to check whether
array are matching to 4 decimal places. This is specifically
fo... | iris
from iris.coords import AuxCoord, DimCoord
from iris.cube import Cube
from iris.tests import IrisTest
import numpy as np
from improver.tests.set_up_test_cubes import set_up_variable_cube
from improver.utilities.cube_metadata import extract_diagnostic_name
from improver.utilities.warnings_handler import ManageWar... | 100 | 100 | 336 | 8 | 92 | TomekTrzeciak/improver | lib/improver/tests/ensemble_calibration/ensemble_calibration/helper_functions.py | Python | EnsembleCalibrationAssertions | EnsembleCalibrationAssertions | 52 | 87 | 52 | 53 | 8548f01f83d92202670bacecf29e070f32ad0055 | bigcode/the-stack | train |
cd6ff453c5fd65a7dac5554f | train | function | def set_up_probability_above_threshold_temperature_cube():
"""
Create a cube with metadata and values suitable for air temperature.
"""
data = np.array([[[[1.0, 0.9, 1.0],
[0.8, 0.9, 0.5],
[0.5, 0.2, 0.0]]],
[[[1.0, 0.5, 1.0],
... | def set_up_probability_above_threshold_temperature_cube():
| """
Create a cube with metadata and values suitable for air temperature.
"""
data = np.array([[[[1.0, 0.9, 1.0],
[0.8, 0.9, 0.5],
[0.5, 0.2, 0.0]]],
[[[1.0, 0.5, 1.0],
[0.5, 0.5, 0.3],
[0.2, ... | , x_dimension_length,
dtype=np.float32),
'longitude', units='degrees'), 3)
cube.coord(
var_name="threshold").attributes["spp__relative_to_threshold"] = (
spp__relative_to_threshold)
return cube
def set_up_probability... | 64 | 64 | 215 | 10 | 53 | TomekTrzeciak/improver | lib/improver/tests/ensemble_calibration/ensemble_calibration/helper_functions.py | Python | set_up_probability_above_threshold_temperature_cube | set_up_probability_above_threshold_temperature_cube | 185 | 201 | 185 | 185 | 7bcef20ee4156e50dcefa6e64752ce45d7ea7329 | bigcode/the-stack | train |
22457eed2be4fbf8d599c485 | train | class | class Google(Resource):
decorators = [rbac.allow(["anonymous"], ["GET", "POST"])]
def __init__(self):
self.reqparse = reqparse.RequestParser()
super(Google, self).__init__()
def get(self):
return self.post()
def post(self):
if "google" not in current_app.config.get("ACT... | class Google(Resource):
| decorators = [rbac.allow(["anonymous"], ["GET", "POST"])]
def __init__(self):
self.reqparse = reqparse.RequestParser()
super(Google, self).__init__()
def get(self):
return self.post()
def post(self):
if "google" not in current_app.config.get("ACTIVE_PROVIDERS"):
... | )
self.reqparse.add_argument('id_token', type=str, required=True)
self.reqparse.add_argument('state', type=str, required=False, default=default_state)
args = self.reqparse.parse_args()
client_id = args['state'].split(',')[1]
redirect_uri = args['state'].split(',')[3]
ret... | 243 | 243 | 813 | 4 | 239 | alvaroaleman/security_monkey | security_monkey/sso/views.py | Python | Google | Google | 223 | 309 | 223 | 223 | 9c7f7733a8960967ccbaa8c20ba3cbd122d37eec | bigcode/the-stack | train |
46381bbae605f50d66426be3 | train | class | class Ping(Resource):
"""
This class serves as an example of how one might implement an SSO provider for use with Security Monkey. In
this example we use a OpenIDConnect authentication flow, that is essentially OAuth2 underneath.
"""
decorators = [rbac.allow(["anonymous"], ["GET", "POST"])]
def ... | class Ping(Resource):
| """
This class serves as an example of how one might implement an SSO provider for use with Security Monkey. In
this example we use a OpenIDConnect authentication flow, that is essentially OAuth2 underneath.
"""
decorators = [rbac.allow(["anonymous"], ["GET", "POST"])]
def __init__(self):
... | for more
:license: Apache, see LICENSE for more details.
.. moduleauthor:: Patrick Kelley <patrick@netflix.com>
"""
import jwt
import base64
import requests
from flask import Blueprint, current_app, redirect, request
from flask_restful import reqparse, Resource, Api
from flask_principal import Identity, identity... | 256 | 256 | 890 | 4 | 251 | alvaroaleman/security_monkey | security_monkey/sso/views.py | Python | Ping | Ping | 42 | 138 | 42 | 42 | f9e3948799ab6848a1e385532e7d089ecc2bfb78 | bigcode/the-stack | train |
c6571c53cc5a6171bfa04494 | train | class | class OneLogin(Resource):
decorators = [rbac.allow(["anonymous"], ["GET", "POST"])]
def __init__(self):
self.reqparse = reqparse.RequestParser()
self.req = OneLogin.prepare_from_flask_request(request)
super(OneLogin, self).__init__()
@staticmethod
def prepare_from_flask_request(... | class OneLogin(Resource):
| decorators = [rbac.allow(["anonymous"], ["GET", "POST"])]
def __init__(self):
self.reqparse = reqparse.RequestParser()
self.req = OneLogin.prepare_from_flask_request(request)
super(OneLogin, self).__init__()
@staticmethod
def prepare_from_flask_request(req):
url_data = u... | _data.get('hd')
if token_hd != google_hosted_domain:
current_app.logger.debug('Verification failed: %s != %s' % (token_hd, google_hosted_domain))
return dict(message='Token is invalid %s' % token), 403
current_app.logger.debug('Verification passed')
# Ste... | 221 | 221 | 737 | 5 | 216 | alvaroaleman/security_monkey | security_monkey/sso/views.py | Python | OneLogin | OneLogin | 312 | 400 | 312 | 312 | 5d03496a0dea6119007f28d67a113767fce579ee | bigcode/the-stack | train |
fb18e0ec23fb9353aa3f1088 | train | class | class Providers(Resource):
decorators = [rbac.allow(["anonymous"], ["GET"])]
def __init__(self):
super(Providers, self).__init__()
def get(self):
active_providers = []
nonce = uuid.uuid4().hex
for provider in current_app.config.get("ACTIVE_PROVIDERS"):
provider... | class Providers(Resource):
| decorators = [rbac.allow(["anonymous"], ["GET"])]
def __init__(self):
super(Providers, self).__init__()
def get(self):
active_providers = []
nonce = uuid.uuid4().hex
for provider in current_app.config.get("ACTIVE_PROVIDERS"):
provider = provider.lower()
... | _app._get_current_object(), identity=Identity(user.id))
login_user(user)
db.session.commit()
db.session.refresh(user)
self_url = OneLogin_Saml2_Utils.get_self_url(self.req)
if 'RelayState' in request.form and self_url != request.form['Rela... | 160 | 160 | 535 | 4 | 156 | alvaroaleman/security_monkey | security_monkey/sso/views.py | Python | Providers | Providers | 403 | 463 | 403 | 403 | 0db0d04422b7fb4a2f61534975d507d0fa9219a6 | bigcode/the-stack | train |
8574d3760787a38c89b0a3ac | train | class | class AzureAD(Resource):
"""
This class serves as an example of how one might implement an SSO provider for use with Security Monkey. In
this example we use a OpenIDConnect authentication flow, that is essentially OAuth2 underneath.
"""
decorators = [rbac.allow(["anonymous"], ["GET", "POST"])]
d... | class AzureAD(Resource):
| """
This class serves as an example of how one might implement an SSO provider for use with Security Monkey. In
this example we use a OpenIDConnect authentication flow, that is essentially OAuth2 underneath.
"""
decorators = [rbac.allow(["anonymous"], ["GET", "POST"])]
def __init__(self):
... | the key it was signed with
try:
jwt.decode(id_token, secret.decode('utf-8'), algorithms=[algo], audience=client_id)
except jwt.DecodeError:
return dict(message='Token is invalid'), 403
except jwt.ExpiredSignatureError:
return dict(message='Token has expired')... | 229 | 229 | 765 | 5 | 224 | alvaroaleman/security_monkey | security_monkey/sso/views.py | Python | AzureAD | AzureAD | 141 | 220 | 141 | 141 | 36390dae3347db8dea4706e816932064fa3cb58e | bigcode/the-stack | train |
f6f67b8f978e52b570168bc4 | train | function | def determine_read_noise(ifc):
log.info('Determining read noise')
buf = args.trimpix
bias_type_names = ['bias', 'dark', 'zero', 'bias frame', 'dark frame']
if args.darkfilter is not "None":
bias_type_names.append('light frame')
bias_match = (ifc.summary[args.exptime] < 1)
bias_match &= ... | def determine_read_noise(ifc):
| log.info('Determining read noise')
buf = args.trimpix
bias_type_names = ['bias', 'dark', 'zero', 'bias frame', 'dark frame']
if args.darkfilter is not "None":
bias_type_names.append('light frame')
bias_match = (ifc.summary[args.exptime] < 1)
bias_match &= np.array([t.lower() in bias_typ... | Handler(LogConsoleHandler)
## Set up file output
# LogFileName = None
# LogFileHandler = logging.FileHandler(LogFileName)
# LogFileHandler.setLevel(logging.DEBUG)
# LogFileHandler.setFormatter(LogFormat)
# log.addHandler(LogFileHandler)
##-------------------------------------------------------------------------
## get... | 256 | 256 | 1,241 | 7 | 250 | joshwalawender/CharacterizeDetector | characterize_detector.py | Python | determine_read_noise | determine_read_noise | 135 | 243 | 135 | 135 | b6858ec8d1ac59654f9f9e2d9a30b80ffec65e02 | bigcode/the-stack | train |
44a2b31028941331e2651b0c | train | function | def determine_dark_current(ifc, master_bias):
log.info('Determining dark current')
buf = args.trimpix
dark_type_names = ['dark', 'dark frame']
if args.darkfilter is not "None":
dark_type_names.append('light frame')
dark_match = (ifc.summary[args.exptime] > 0)
dark_match &= np.array([t.... | def determine_dark_current(ifc, master_bias):
| log.info('Determining dark current')
buf = args.trimpix
dark_type_names = ['dark', 'dark frame']
if args.darkfilter is not "None":
dark_type_names.append('light frame')
dark_match = (ifc.summary[args.exptime] > 0)
dark_match &= np.array([t.lower() in dark_type_names\
... |
log.info(f'Generating plot for master bias')
data = master_bias.data[buf:ny-buf,buf:nx-buf]
std = np.std(data)
binwidth = int(20*std)
binsize = 1
med = np.median(data)
bins = [x+med for x in range(-binwidth,binwidth,binsize)]
norm = ImageNormalize(data, i... | 256 | 256 | 956 | 10 | 247 | joshwalawender/CharacterizeDetector | characterize_detector.py | Python | determine_dark_current | determine_dark_current | 249 | 327 | 249 | 250 | c4d78ba0533d466779cf5b82568b41e9727c52f6 | bigcode/the-stack | train |
04105cedbf13a5626f4745a7 | train | function | def main():
files = [Path(f) for f in args.files]
keywords = [args.exptime, args.imtype, args.ccdtemp]
if args.darkfilter is not "None":
keywords.append(args.darkfilter)
ifc = IFC(location=files[0].parent, filenames=files, keywords=keywords,
ext=args.ext)
if args.exptimefactor... | def main():
| files = [Path(f) for f in args.files]
keywords = [args.exptime, args.imtype, args.ccdtemp]
if args.darkfilter is not "None":
keywords.append(args.darkfilter)
ifc = IFC(location=files[0].parent, filenames=files, keywords=keywords,
ext=args.ext)
if args.exptimefactor != 1:
... | -fit)/counts]')
# plt.ylim(np.floor(min(decrements)), np.ceil(max(decrements)))
ax.grid()
plot_file = Path(ifc.location).joinpath(f'Linearity.png')
plt.savefig(plot_file, bbox_inches='tight', pad_inches=0.10)
return g
##---------------------------------------------------... | 76 | 76 | 256 | 3 | 74 | joshwalawender/CharacterizeDetector | characterize_detector.py | Python | main | main | 497 | 522 | 497 | 497 | 5a3f807bf362c3af19c810bd8a923940ac5a8933 | bigcode/the-stack | train |
afbec61d859afbf38af91e8f | train | function | def determine_gain(ifc, master_bias, RN):
log.info('Determining gain')
buf = args.trimpix
flat_type_names = ['light', 'light frame', 'flat', 'intflat', 'domeflat', 'twiflat']
flat_match = (ifc.summary[args.exptime] > 0)
flat_match &= np.array([t.lower() in flat_type_names
... | def determine_gain(ifc, master_bias, RN):
| log.info('Determining gain')
buf = args.trimpix
flat_type_names = ['light', 'light frame', 'flat', 'intflat', 'domeflat', 'twiflat']
flat_match = (ifc.summary[args.exptime] > 0)
flat_match &= np.array([t.lower() in flat_type_names
for t in ifc.summary[args.imtype]])
... | .plot(dark_table['exptime'], dark_table['mean'], 'ko', alpha=1.0,
label='mean count level in ADU')
ax.plot([0, longest_exptime], [dc_fit(0), dc_fit(longest_exptime)],
'k-', alpha=0.3,
label=f'dark current = {dark_stats[0].value:.2f} ADU/s')
plt.xlim(-0.02*... | 256 | 256 | 1,917 | 11 | 246 | joshwalawender/CharacterizeDetector | characterize_detector.py | Python | determine_gain | determine_gain | 333 | 489 | 333 | 334 | b0d7b025d8cc49057409b9a0a5d2b4bd989d08ba | bigcode/the-stack | train |
7ea3e71acf8fb0fac0d59ec2 | train | function | def get_mode(im):
'''
Return mode of image. Assumes int values (ADU), so uses binsize of one.
'''
if type(im) == ccdproc.CCDData:
data = im.data.ravel()
elif type(im) == fits.HDUList:
data = im[0].data.ravel()
else:
data = im
bmin = np.floor(min(data)) - 1./2.
... | def get_mode(im):
| '''
Return mode of image. Assumes int values (ADU), so uses binsize of one.
'''
if type(im) == ccdproc.CCDData:
data = im.data.ravel()
elif type(im) == fits.HDUList:
data = im[0].data.ravel()
else:
data = im
bmin = np.floor(min(data)) - 1./2.
bmax = np.ceil(... | ## Set up file output
# LogFileName = None
# LogFileHandler = logging.FileHandler(LogFileName)
# LogFileHandler.setLevel(logging.DEBUG)
# LogFileHandler.setFormatter(LogFormat)
# log.addHandler(LogFileHandler)
##-------------------------------------------------------------------------
## get_mode
##-------------------... | 64 | 64 | 176 | 5 | 60 | joshwalawender/CharacterizeDetector | characterize_detector.py | Python | get_mode | get_mode | 111 | 129 | 111 | 111 | 05ce704fd7183e38e37f114405811699751c18b2 | bigcode/the-stack | train |
17b8a09889f6aa5bcf27be62 | train | class | class StreamerManager:
discord = None
streamers = {}
confstreamers = []
def __init__(self, discord=None):
self.discord = discord
self.loadConfig()
def Add(self, name, channelId):
config = self.addToManager(name, channelId)
if config != False:
self.addToC... | class StreamerManager:
| discord = None
streamers = {}
confstreamers = []
def __init__(self, discord=None):
self.discord = discord
self.loadConfig()
def Add(self, name, channelId):
config = self.addToManager(name, channelId)
if config != False:
self.addToConfig(config)
... | import logging
import Discord
import config
import Streamer
class StreamerManager:
| 18 | 256 | 1,045 | 5 | 12 | AceDroidX/vtuber-rebroadcast | LiveStreams.py | Python | StreamerManager | StreamerManager | 7 | 129 | 7 | 7 | 20cafeac94de43463442717cd60138ee00199216 | bigcode/the-stack | train |
8a2811408f73892b5464bc76 | train | class | class StatusTestCase(PluginTestCase):
plugins = ('Status',)
def testNet(self):
self.assertNotError('net')
def testCpu(self):
m = self.assertNotError('status cpu')
self.failIf('kB kB' in m.args[1])
self.failIf('None' in m.args[1], 'None in cpu output: %r.' % m)
for s ... | class StatusTestCase(PluginTestCase):
| plugins = ('Status',)
def testNet(self):
self.assertNotError('net')
def testCpu(self):
m = self.assertNotError('status cpu')
self.failIf('kB kB' in m.args[1])
self.failIf('None' in m.args[1], 'None in cpu output: %r.' % m)
for s in ['linux', 'freebsd', 'openbsd', 'ne... | OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
###
from supybot.test imp... | 93 | 93 | 311 | 9 | 83 | MicrohexHQ/supybot_fixes | plugins/Status/test.py | Python | StatusTestCase | StatusTestCase | 36 | 75 | 36 | 36 | 55acaa32d3eda405296048101c557ca9330a175d | bigcode/the-stack | train |
eed0e9272a9d19c92955cbad | train | class | class SignatureClassifier(BaseClassifier):
"""Classification module using signature-based features.
This simply initialises the SignatureTransformer class which builds
the feature extraction pipeline, then creates a new pipeline by
appending a classifier after the feature extraction step.
The defa... | class SignatureClassifier(BaseClassifier):
| """Classification module using signature-based features.
This simply initialises the SignatureTransformer class which builds
the feature extraction pipeline, then creates a new pipeline by
appending a classifier after the feature extraction step.
The default parameters are set to best practice par... | # -*- coding: utf-8 -*-
"""Implementation of a SignatureClassifier.
Utilises the signature method of feature extraction.
This method was built according to the best practices
and methodologies described in the paper:
"A Generalised Signature Method for Time Series"
[arxiv](https://arxiv.org/pdf/2006.00873.pdf)... | 147 | 256 | 1,442 | 6 | 141 | BINAYKUMAR943/sktime | sktime/classification/feature_based/_signature_classifier.py | Python | SignatureClassifier | SignatureClassifier | 23 | 214 | 23 | 23 | aa60508bbea8318b8e3a45029b90046f399c0f9f | bigcode/the-stack | train |
b10d6bf267d6f686a9b0d45a | train | class | class Driver(GDALBase):
"Wraps an OGR Data Source Driver."
# Case-insensitive aliases for OGR Drivers.
_alias = {'esri' : 'ESRI Shapefile',
'shp' : 'ESRI Shapefile',
'shape' : 'ESRI Shapefile',
'tiger' : 'TIGER',
'tiger/line' : 'TIGER',
... | class Driver(GDALBase):
| "Wraps an OGR Data Source Driver."
# Case-insensitive aliases for OGR Drivers.
_alias = {'esri' : 'ESRI Shapefile',
'shp' : 'ESRI Shapefile',
'shape' : 'ESRI Shapefile',
'tiger' : 'TIGER',
'tiger/line' : 'TIGER',
}
def __init__(self... | # prerequisites imports
from ctypes import c_void_p
from django.contrib.gis.gdal.base import GDALBase
from django.contrib.gis.gdal.error import OGRException
from django.contrib.gis.gdal.prototypes import ds as capi
from django.utils import six
# For more information, see the OGR C API source code:
# http://www.gdal.... | 110 | 140 | 469 | 6 | 104 | kix/django | django/contrib/gis/gdal/driver.py | Python | Driver | Driver | 13 | 67 | 13 | 13 | f21ab50a04c5afe554a7b1f3d70bd4208d019ec5 | bigcode/the-stack | train |
d4cc0ec2787155e6d9378f3b | train | class | class BucketTreeTest(unittest.TestCase):
"""
BucketTree.find_node(key)
BucketTree.find_nodes(key)
BucketTree.add_node(node)
"""
def get_new_tree(self):
""" Helper function to get a new BucketTree. """
tree = BucketTree(SelfNode('0', '127.0.0.1', '9999'))
assert len(tree.... | class BucketTreeTest(unittest.TestCase):
| """
BucketTree.find_node(key)
BucketTree.find_nodes(key)
BucketTree.add_node(node)
"""
def get_new_tree(self):
""" Helper function to get a new BucketTree. """
tree = BucketTree(SelfNode('0', '127.0.0.1', '9999'))
assert len(tree.bucket_node_list) == 3
return tre... | import unittest
from dht import settings
from dht.bucket import NodeAlreadyAddedException, BucketIsFullException
from dht.node import Node, SelfNode
from dht.routing import BucketTree, BucketNode
from dht.utils import hash_string
class BucketTreeTest(unittest.TestCase):
| 61 | 231 | 771 | 8 | 52 | leonkoens/dht | tests/test_routing.py | Python | BucketTreeTest | BucketTreeTest | 11 | 114 | 11 | 11 | 217319b9c0b5dd307c58d3f4be9dfdb6a70a8c8d | bigcode/the-stack | train |
521ae4c01ed6166012e67e45 | train | class | class BucketNodeTest(unittest.TestCase):
def test_split(self):
bucket_node = BucketNode()
self.assertTrue(bucket_node.bucket is not None)
self.assertEqual(bucket_node.left, None)
self.assertEqual(bucket_node.right, None)
left, right = bucket_node.split()
self.ass... | class BucketNodeTest(unittest.TestCase):
| def test_split(self):
bucket_node = BucketNode()
self.assertTrue(bucket_node.bucket is not None)
self.assertEqual(bucket_node.left, None)
self.assertEqual(bucket_node.right, None)
left, right = bucket_node.split()
self.assertEqual(left.parent, bucket_node)
... | self = 20.
self.assertEqual(len(nodes), 20)
tree.add_node(Node(hash_string('more than 20'), None, None))
nodes = tree.find_nodes(hash_string('test'))
# 20 other nodes + self = 20 because of the bucket size.
self.assertEqual(len(nodes), 20)
class BucketNodeTest(unittest.TestCas... | 78 | 78 | 263 | 8 | 70 | leonkoens/dht | tests/test_routing.py | Python | BucketNodeTest | BucketNodeTest | 117 | 158 | 117 | 118 | c8bedd659271a5ebe41eb933f458b3aae9765175 | bigcode/the-stack | train |
d7e52ffe8296a6d8e28207f0 | train | function | def design_partial_factorial(k: int, res: int) -> DataFrame:
"""
design_partial_factorial
This function helps design 2 level partial factorial experiments. These experiments are often
described using the syntax l**(k-p) where l represents the level of each factor, k represents
the total number of f... | def design_partial_factorial(k: int, res: int) -> DataFrame:
| """
design_partial_factorial
This function helps design 2 level partial factorial experiments. These experiments are often
described using the syntax l**(k-p) where l represents the level of each factor, k represents
the total number of factors considered, and p represents a scaling factor relative... | to design a
full factorial experiment once the factors and levels have been specified, this is more of a
convenience function.
Parameters
----------
factors : List[List]
a list of lists representing factors and levels
factor_names : List[str], optional
a list of names for the f... | 256 | 256 | 1,017 | 17 | 239 | James-Montgomery/lind | lind/design/factorial.py | Python | design_partial_factorial | design_partial_factorial | 110 | 206 | 110 | 110 | 2dff4618a940acec06c29d24b107f88ba44e0d79 | bigcode/the-stack | train |
c139ded81c6f011dddf0cdc3 | train | function | def fetch_partial_factorial_design(design_name: str = "toc") -> DataFrame:
"""
fetch_partial_factorial_design
The function design_partial_factorial auto generates partial factorial designs using an
algorithm. We validate that algorithm in our unit tests by comparing against known designs
from popul... | def fetch_partial_factorial_design(design_name: str = "toc") -> DataFrame:
| """
fetch_partial_factorial_design
The function design_partial_factorial auto generates partial factorial designs using an
algorithm. We validate that algorithm in our unit tests by comparing against known designs
from popular experimental design textbooks. For those that want to use the designs fr... | for i in j.split(":")]
for j in [i for i in factors.split(" ") if i and ":" in i]
]
design = "+".join(full_factorial_design.columns.tolist() + [":".join(i) for i in interactions])
partial_factorial_design = dmatrix(design, full_factorial_design, return_type='dataframe').drop(
columns=["Int... | 145 | 146 | 487 | 19 | 126 | James-Montgomery/lind | lind/design/factorial.py | Python | fetch_partial_factorial_design | fetch_partial_factorial_design | 212 | 267 | 212 | 212 | 05fcdc83542410a34bcb4ec840824cb7ff1a2aff | bigcode/the-stack | train |
217974783ff1dc7596f2e70a | train | function | def design_full_factorial(factors: List[List],
factor_names: Optional[List[str]] = None) -> DataFrame:
"""
design_full_factorial
This function helps create a full factorial experiment design. Given how easy it is to design a
full factorial experiment once the factors and level... | def design_full_factorial(factors: List[List],
factor_names: Optional[List[str]] = None) -> DataFrame:
| """
design_full_factorial
This function helps create a full factorial experiment design. Given how easy it is to design a
full factorial experiment once the factors and levels have been specified, this is more of a
convenience function.
Parameters
----------
factors : List[List]
... | res + 1, k),
arange(res - 1, k, 1)
).sum() + k
_k_combo_vec = vectorize(_k_combo, excluded=['res'],
doc="The number of combinations of k factors given a specific resolution")
####################################################################################################
de... | 85 | 86 | 289 | 26 | 59 | James-Montgomery/lind | lind/design/factorial.py | Python | design_full_factorial | design_full_factorial | 74 | 107 | 74 | 75 | 6d87b3b8029d16867864546b089c9a97048c70a7 | bigcode/the-stack | train |
d709f709b01a218cbdbdb438 | train | function | def _k_combo(k: int, res: int) -> int:
"""The number of combinations of k factors given a specific resolution"""
return binom(
full(k - res + 1, k),
arange(res - 1, k, 1)
).sum() + k
| def _k_combo(k: int, res: int) -> int:
| """The number of combinations of k factors given a specific resolution"""
return binom(
full(k - res + 1, k),
arange(res - 1, k, 1)
).sum() + k
|
def _array_to_string(arr_like: Union[List, ndarray]) -> ndarray:
"""Utility for converting experiment design string into an array of factors"""
return array_str(asarray(arr_like)).replace("[", "").replace("]", "")
def _k_combo(k: int, res: int) -> int:
| 63 | 64 | 65 | 15 | 48 | James-Montgomery/lind | lind/design/factorial.py | Python | _k_combo | _k_combo | 59 | 64 | 59 | 59 | f6d3269ab372918bb33f11bf8c771920b50d201e | bigcode/the-stack | train |
44586c1a224d9495de639b43 | train | function | def _array_to_string(arr_like: Union[List, ndarray]) -> ndarray:
"""Utility for converting experiment design string into an array of factors"""
return array_str(asarray(arr_like)).replace("[", "").replace("]", "")
| def _array_to_string(arr_like: Union[List, ndarray]) -> ndarray:
| """Utility for converting experiment design string into an array of factors"""
return array_str(asarray(arr_like)).replace("[", "").replace("]", "")
| .getLogger(__name__)
# define public functions (ignored by jupyter notebooks)
__all__ = [
'design_full_factorial',
'design_partial_factorial',
'fetch_partial_factorial_design'
]
####################################################################################################
def _array_to_string(arr_li... | 63 | 64 | 47 | 16 | 47 | James-Montgomery/lind | lind/design/factorial.py | Python | _array_to_string | _array_to_string | 54 | 56 | 54 | 54 | 68b00fecf455661de3177ef37d261c6b240f8f3a | bigcode/the-stack | train |
666982c392f2706e226e86c4 | train | function | def _realign_dfs():
idx_len = 0
idx = None
for df in shared._DFS.values():
if len(df) > idx_len:
idx_len = len(df)
idx = df.index
for key in shared._DFS.keys():
try:
shared._DFS[key] = _pd.DataFrame(
index=idx, data=shared._DFS[key]).... | def _realign_dfs():
| idx_len = 0
idx = None
for df in shared._DFS.values():
if len(df) > idx_len:
idx_len = len(df)
idx = df.index
for key in shared._DFS.keys():
try:
shared._DFS[key] = _pd.DataFrame(
index=idx, data=shared._DFS[key]).drop_duplicates()
... | ._DFS.values(), axis=1,
keys=shared._DFS.keys())
if group_by == 'column':
data.columns = data.columns.swaplevel(0, 1)
data.sort_index(level=0, axis=1, inplace=True)
return data
def _realign_dfs():
| 64 | 64 | 163 | 7 | 56 | EatEmAll/yfinance | yfinance/multi.py | Python | _realign_dfs | _realign_dfs | 142 | 162 | 142 | 142 | f5949486b160f6abfc9d881b4cb29957025ee50d | bigcode/the-stack | train |
bbf6237295b193c5e4e6d022 | train | function | @_multitasking.task
def _download_one_threaded(ticker, start=None, end=None,
auto_adjust=False, back_adjust=False,
actions=False, progress=True, period="max",
interval="1d", prepost=False, proxy=None,
rounding=Fa... | @_multitasking.task
def _download_one_threaded(ticker, start=None, end=None,
auto_adjust=False, back_adjust=False,
actions=False, progress=True, period="max",
interval="1d", prepost=False, proxy=None,
rounding=Fa... | data = _download_one(ticker, start, end, auto_adjust, back_adjust,
actions, period, interval, prepost, proxy, rounding)
shared._DFS[ticker.upper()] = data
if progress:
shared._PROGRESS_BAR.animate()
| keep='last')]
@_multitasking.task
def _download_one_threaded(ticker, start=None, end=None,
auto_adjust=False, back_adjust=False,
actions=False, progress=True, period="max",
interval="1d", prepost=False, proxy=None,
... | 63 | 64 | 115 | 59 | 4 | EatEmAll/yfinance | yfinance/multi.py | Python | _download_one_threaded | _download_one_threaded | 165 | 176 | 165 | 171 | 0941bfcab92158574ec753611b8d31977369bbdd | bigcode/the-stack | train |
79d75924a1a394d05ef0b154 | train | function | def download(tickers, start=None, end=None, actions=False, threads=True,
group_by='column', auto_adjust=False, back_adjust=False,
progress=True, period="max", show_errors=True, interval="1d", prepost=False,
proxy=None, rounding=False, **kwargs):
"""Download yahoo tickers
:... | def download(tickers, start=None, end=None, actions=False, threads=True,
group_by='column', auto_adjust=False, back_adjust=False,
progress=True, period="max", show_errors=True, interval="1d", prepost=False,
proxy=None, rounding=False, **kwargs):
| """Download yahoo tickers
:Parameters:
tickers : str, list
List of tickers to download
period : str
Valid periods: 1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max
Either Use period parameter or use start and end
interval : str
Valid intervals: 1m,2m... | finance
#
# Copyright 2017-2019 Ran Aroussi
#
# 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 ... | 256 | 256 | 951 | 62 | 194 | EatEmAll/yfinance | yfinance/multi.py | Python | download | download | 35 | 139 | 35 | 38 | 619f4d889fc532eb61453014be80c9b18705c47e | bigcode/the-stack | train |
a1b18a83705cffb6cd882f94 | train | function | @cache
def _download_one(ticker, start=None, end=None,
auto_adjust=False, back_adjust=False,
actions=False, period="max", interval="1d",
prepost=False, proxy=None, rounding=False):
return Ticker(ticker).history(period=period, interval=interval,
... | @cache
def _download_one(ticker, start=None, end=None,
auto_adjust=False, back_adjust=False,
actions=False, period="max", interval="1d",
prepost=False, proxy=None, rounding=False):
| return Ticker(ticker).history(period=period, interval=interval,
start=start, end=end, prepost=prepost,
actions=actions, auto_adjust=auto_adjust,
back_adjust=back_adjust, proxy=proxy,
... | = data
if progress:
shared._PROGRESS_BAR.animate()
@cache
def _download_one(ticker, start=None, end=None,
auto_adjust=False, back_adjust=False,
actions=False, period="max", interval="1d",
prepost=False, proxy=None, rounding=False):
| 64 | 64 | 109 | 49 | 15 | EatEmAll/yfinance | yfinance/multi.py | Python | _download_one | _download_one | 179 | 189 | 179 | 184 | 6f992b4ef56db11e6ae452ca3566165fbd079246 | bigcode/the-stack | train |
d59d595627b19be208db5b15 | train | function | @shared_task
def send_email_activate(username, receive, u_token):
subject = '%s AXF Activate' % username
from_email = EMAIL_HOST_USER
recipient_list = [receive, ]
data = {
'username': username,
'activate_url': 'http://{}/axf/activate/?u_token={}'.format(SERVER_HOST, u_token)
}
... | @shared_task
def send_email_activate(username, receive, u_token):
| subject = '%s AXF Activate' % username
from_email = EMAIL_HOST_USER
recipient_list = [receive, ]
data = {
'username': username,
'activate_url': 'http://{}/axf/activate/?u_token={}'.format(SERVER_HOST, u_token)
}
html_message = loader.get_template('user/activate.html').render(... | from celery import shared_task
from django.core.mail import send_mail
from django.template import loader
from axf.settings import EMAIL_HOST_USER, SERVER_HOST
@shared_task
def send_email_activate(username, receive, u_token):
| 47 | 64 | 125 | 15 | 31 | xuaman/axf | App/tasks.py | Python | send_email_activate | send_email_activate | 7 | 23 | 7 | 9 | bde8498ec4152f18033157cf24f50faaebc59b09 | bigcode/the-stack | train |
58773cc389997cdcda0e9f0c | train | function | def map_gradients(gradient_map, gis, length):
index_tensor = tf.reshape(tf.concat([
tf.reshape(tf.tile(tf.expand_dims(gis, 1), [1, 3]), [length * 3, 1]),
tf.expand_dims(tf.tile(tf.range(0, limit=3), [length]), 1)
], 1), [length, 3, 2])
return tf.gather_nd(gradient_map, index_tensor)
| def map_gradients(gradient_map, gis, length):
| index_tensor = tf.reshape(tf.concat([
tf.reshape(tf.tile(tf.expand_dims(gis, 1), [1, 3]), [length * 3, 1]),
tf.expand_dims(tf.tile(tf.range(0, limit=3), [length]), 1)
], 1), [length, 3, 2])
return tf.gather_nd(gradient_map, index_tensor)
| ], [-1, 0, -1],
[0, 1, 1], [0, -1, 1], [0, 1, -1], [0, -1, -1]], dtype=np.float32)
def map_gradients(gradient_map, gis, length):
| 64 | 64 | 98 | 12 | 52 | yyuting/FastImageProcessing | CAN24_AN/tf_map_gradient.py | Python | map_gradients | map_gradients | 13 | 18 | 13 | 13 | 2d47eebc5e83d14638319028765a35a4d64c4176 | bigcode/the-stack | train |
369a15a88ba82085c4191bb2 | train | class | class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question_text']}),
('Date information', {'fields': ['pub_date']}),
]
inlines = [ChoiceInline]
list_display = ('question_text', 'pub_date', 'was_published_recently')
list_filter = ['pub_date']
search_fields =... | class QuestionAdmin(admin.ModelAdmin):
| fieldsets = [
(None, {'fields': ['question_text']}),
('Date information', {'fields': ['pub_date']}),
]
inlines = [ChoiceInline]
list_display = ('question_text', 'pub_date', 'was_published_recently')
list_filter = ['pub_date']
search_fields = ['question_text']
| from django.contrib import admin
from .models import *
class ChoiceInline(admin.TabularInline):
model = Choice
extra = 3
class QuestionAdmin(admin.ModelAdmin):
| 37 | 64 | 82 | 7 | 29 | Honzama/django-tutorials | django_tutorial/polls/admin.py | Python | QuestionAdmin | QuestionAdmin | 11 | 19 | 11 | 11 | d642c31c4f7f1520a07214681a9a441d45c82dc2 | bigcode/the-stack | train |
331b690ad35bc87b0097cd19 | train | class | class ChoiceInline(admin.TabularInline):
model = Choice
extra = 3
| class ChoiceInline(admin.TabularInline):
| model = Choice
extra = 3
| from django.contrib import admin
from .models import *
class ChoiceInline(admin.TabularInline):
| 19 | 64 | 19 | 8 | 11 | Honzama/django-tutorials | django_tutorial/polls/admin.py | Python | ChoiceInline | ChoiceInline | 6 | 8 | 6 | 6 | 68a48eb6ac9039cf6aea9fc2a66adf3ebaf5c6ae | bigcode/the-stack | train |
26734eb13dbf1a6dceccdf7d | train | function | def main():
module_args = oci_common_utils.get_common_arg_spec()
module_args.update(
dict(
notebook_session_id=dict(aliases=["id"], type="str"),
compartment_id=dict(type="str"),
project_id=dict(type="str"),
display_name=dict(aliases=["name"], type="str"),
... | def main():
| module_args = oci_common_utils.get_common_arg_spec()
module_args.update(
dict(
notebook_session_id=dict(aliases=["id"], type="str"),
compartment_id=dict(type="str"),
project_id=dict(type="str"),
display_name=dict(aliases=["name"], type="str"),
... | return oci_common_utils.list_all_resources(
self.client.list_notebook_sessions,
compartment_id=self.module.params.get("compartment_id"),
**optional_kwargs
)
DataScienceNotebookSessionFactsHelperCustom = get_custom_class(
"DataScienceNotebookSessionFactsHelperCus... | 90 | 90 | 301 | 3 | 86 | A7rMtWE57x/oci-ansible-collection | plugins/modules/oci_data_science_notebook_session_facts.py | Python | main | main | 292 | 339 | 292 | 292 | 648e2267b42ee0279b6a3ae33bc33cbdb3546570 | bigcode/the-stack | train |
2d63aaa0b005814631e53f54 | train | class | class DataScienceNotebookSessionFactsHelperGen(OCIResourceFactsHelperBase):
"""Supported operations: get, list"""
def get_required_params_for_get(self):
return [
"notebook_session_id",
]
def get_required_params_for_list(self):
return [
"compartment_id",
... | class DataScienceNotebookSessionFactsHelperGen(OCIResourceFactsHelperBase):
| """Supported operations: get, list"""
def get_required_params_for_get(self):
return [
"notebook_session_id",
]
def get_required_params_for_list(self):
return [
"compartment_id",
]
def get_resource(self):
return oci_common_utils.call_with... | OCIResourceFactsHelperBase,
get_custom_class,
)
try:
from oci.data_science import DataScienceClient
HAS_OCI_PY_SDK = True
except ImportError:
HAS_OCI_PY_SDK = False
class DataScienceNotebookSessionFactsHelperGen(OCIResourceFactsHelperBase):
| 68 | 68 | 227 | 15 | 52 | A7rMtWE57x/oci-ansible-collection | plugins/modules/oci_data_science_notebook_session_facts.py | Python | DataScienceNotebookSessionFactsHelperGen | DataScienceNotebookSessionFactsHelperGen | 240 | 277 | 240 | 240 | 5bfbb02c75644ff798b6999f3b57e1cf83a3f900 | bigcode/the-stack | train |
9e86906c26793de6a4beaf0e | train | class | class ResourceFactsHelper(
DataScienceNotebookSessionFactsHelperCustom,
DataScienceNotebookSessionFactsHelperGen,
):
pass
| class ResourceFactsHelper(
DataScienceNotebookSessionFactsHelperCustom,
DataScienceNotebookSessionFactsHelperGen,
):
| pass
| _id=self.module.params.get("compartment_id"),
**optional_kwargs
)
DataScienceNotebookSessionFactsHelperCustom = get_custom_class(
"DataScienceNotebookSessionFactsHelperCustom"
)
class ResourceFactsHelper(
DataScienceNotebookSessionFactsHelperCustom,
DataScienceNotebookSessionFactsHelpe... | 64 | 64 | 27 | 24 | 40 | A7rMtWE57x/oci-ansible-collection | plugins/modules/oci_data_science_notebook_session_facts.py | Python | ResourceFactsHelper | ResourceFactsHelper | 285 | 289 | 285 | 288 | 280bf64ea1a7fffe17d43dd3aa5c0f6d7eed7d0a | bigcode/the-stack | train |
b755e1cb15e60e1bb20040cb | train | class | class FlowTableChangeEvent(Event):
def __init__(self, happening_sw_, happening_time_, seg_path_id_, new_next_sw_, fl_tbl_type_):
Event.__init__(self, constants.CHANGING_FLOW_EVENT, happening_sw_, happening_time_)
self.seg_path_id = seg_path_id_
self.next_sw = new_next_sw_
self.fl_tbl... | class FlowTableChangeEvent(Event):
| def __init__(self, happening_sw_, happening_time_, seg_path_id_, new_next_sw_, fl_tbl_type_):
Event.__init__(self, constants.CHANGING_FLOW_EVENT, happening_sw_, happening_time_)
self.seg_path_id = seg_path_id_
self.next_sw = new_next_sw_
self.fl_tbl_type = fl_tbl_type_
def __str... | init__(self, constants.CHANGING_FLOW_EVENT, happening_sw_, happening_time_)
self.seg_path_id = seg_path_id_
def __str__(self):
return "event_type=FlowChange, happening_sw=%s, happening_time=%s, seg_path_id=%s" \
% (self.happening_sw, self.time, self.seg_path_id)
def __repr__(sel... | 97 | 97 | 325 | 7 | 91 | faywh/read_ez | simulator/domain/events.py | Python | FlowTableChangeEvent | FlowTableChangeEvent | 66 | 98 | 66 | 66 | b653f9323d734cbc1dc1530c3c9204d7bf640586 | bigcode/the-stack | train |
d4438c879c6df5e47408d1ff | train | class | class MessageSendingEvent(Event):
def __init__(self, happening_sw_, dst_sw, happening_time_, msg_type_,
receiving_time_, seg_path_id_, split_vol_):
Event.__init__(self, constants.SENDING_MSG_EVENT, happening_sw_, happening_time_)
self.dst_sw = dst_sw
self.receiving_time = re... | class MessageSendingEvent(Event):
| def __init__(self, happening_sw_, dst_sw, happening_time_, msg_type_,
receiving_time_, seg_path_id_, split_vol_):
Event.__init__(self, constants.SENDING_MSG_EVENT, happening_sw_, happening_time_)
self.dst_sw = dst_sw
self.receiving_time = receiving_time_
self.seg_pat... | _time_
self.text = text_
self.dt = 1
def __str__(self):
return "event_type=%d, happening_sw=%s, happening_time=%s" \
% (self.event_type, self.happening_sw, self.time)
def __repr__(self):
return self.__str__()
def to_string(self):
pass
class MessageSe... | 85 | 85 | 286 | 6 | 78 | faywh/read_ez | simulator/domain/events.py | Python | MessageSendingEvent | MessageSendingEvent | 24 | 52 | 24 | 24 | 7aba7741ce7183e4c7ec645d43eafad7c8252e48 | bigcode/the-stack | train |
3bfa6335ed255e9c0df5d5b5 | train | class | class Event:
def __init__(self, type_, happening_sw_, happening_time_, text_=""):
self.event_type = type_
self.happening_sw = happening_sw_
self.time = happening_time_
self.text = text_
self.dt = 1
def __str__(self):
return "event_type=%d, happening_sw=%s, happen... | class Event:
| def __init__(self, type_, happening_sw_, happening_time_, text_=""):
self.event_type = type_
self.happening_sw = happening_sw_
self.time = happening_time_
self.text = text_
self.dt = 1
def __str__(self):
return "event_type=%d, happening_sw=%s, happening_time=%s" ... | from misc import constants
from time import time
class Event:
| 13 | 64 | 123 | 3 | 9 | faywh/read_ez | simulator/domain/events.py | Python | Event | Event | 5 | 21 | 5 | 5 | 18273400e9579521ebbc60da17feaa33b99a35a5 | bigcode/the-stack | train |
75fffa7dd60b8a003d2ee042 | train | class | class FlowChangeEvent(Event):
def __init__(self, happening_sw_, happening_time_, seg_path_id_):
Event.__init__(self, constants.CHANGING_FLOW_EVENT, happening_sw_, happening_time_)
self.seg_path_id = seg_path_id_
def __str__(self):
return "event_type=FlowChange, happening_sw=%s, happenin... | class FlowChangeEvent(Event):
| def __init__(self, happening_sw_, happening_time_, seg_path_id_):
Event.__init__(self, constants.CHANGING_FLOW_EVENT, happening_sw_, happening_time_)
self.seg_path_id = seg_path_id_
def __str__(self):
return "event_type=FlowChange, happening_sw=%s, happening_time=%s, seg_path_id=%s" \
... | if self.msg_type == constants.GOOD_TO_MOVE_MSG:
return "GOOD_TO_MOVE"
if self.msg_type == constants.REMOVING_MSG:
return "REMOVING"
if self.msg_type == constants.COHERENT_MSG:
return "COHERENT"
class FlowChangeEvent(Event):
| 64 | 64 | 117 | 6 | 58 | faywh/read_ez | simulator/domain/events.py | Python | FlowChangeEvent | FlowChangeEvent | 54 | 64 | 54 | 54 | a23761cf5e62b5743ff354a502b727d814d85573 | bigcode/the-stack | train |
04e4c06ef45ccb8b60ae98fe | train | class | class AngleNbSetWeight(NbSetWeight):
SHORT_NAME = 'AngleWeight'
def __init__(self, aa=1.0):
self.aa = aa
if self.aa == 1.0:
self.aw = self.angle_sum
else:
self.aw = self.angle_sumn
def weight(self, nb_set, structure_environments, cn_map=None, additional_inf... | class AngleNbSetWeight(NbSetWeight):
| SHORT_NAME = 'AngleWeight'
def __init__(self, aa=1.0):
self.aa = aa
if self.aa == 1.0:
self.aw = self.angle_sum
else:
self.aw = self.angle_sumn
def weight(self, nb_set, structure_environments, cn_map=None, additional_info=None):
return self.aw(nb_set... | BCMeta):
@abc.abstractmethod
def as_dict(self):
"""
A JSON serializable dict representation of this neighbors set weight.
"""
pass
@abc.abstractmethod
def weight(self, nb_set, structure_environments, cn_map=None, additional_info=None):
pass
class AngleNbSetWeigh... | 74 | 74 | 248 | 10 | 63 | oxana-a/pymatgen | pymatgen/analysis/chemenv/coordination_environments/chemenv_strategies.py | Python | AngleNbSetWeight | AngleNbSetWeight | 829 | 863 | 829 | 830 | f3d6aaae3a6c5c2a332233382d65febd203227fe | bigcode/the-stack | train |
89d7face98947a35167df32d | train | class | class SimplestChemenvStrategy(AbstractChemenvStrategy):
"""
Simplest ChemenvStrategy using fixed angle and distance parameters for the definition of neighbors in the
Voronoi approach. The coordination environment is then given as the one with the lowest continuous symmetry measure
"""
# Default val... | class SimplestChemenvStrategy(AbstractChemenvStrategy):
| """
Simplest ChemenvStrategy using fixed angle and distance parameters for the definition of neighbors in the
Voronoi approach. The coordination environment is then given as the one with the lowest continuous symmetry measure
"""
# Default values for the distance and angle cutoffs
DEFAULT_DISTA... | )))
out += ' Description :\n {}\n'.format('-'*13)
out += self.STRATEGY_DESCRIPTION
out += '\n\n'
out += ' Options :\n {}\n'.format('-'*9)
for option_name, option_dict in self.STRATEGY_OPTIONS.items():
out += ' - {} : {}\n'.format(option_name, str(getattr(self, o... | 256 | 256 | 2,436 | 13 | 243 | oxana-a/pymatgen | pymatgen/analysis/chemenv/coordination_environments/chemenv_strategies.py | Python | SimplestChemenvStrategy | SimplestChemenvStrategy | 365 | 585 | 365 | 365 | 2708c8b976c5f7e26779151239b97e280d8d5a83 | bigcode/the-stack | train |
9e41d49d46d76a7307832da3 | train | class | class DistanceNbSetWeight(NbSetWeight):
SHORT_NAME = 'DistanceNbSetWeight'
def __init__(self, weight_function=None, nbs_source='voronoi'):
if weight_function is None:
self.weight_function = {'function': 'smootherstep', 'options': {'lower': 1.2, 'upper': 1.3}}
else:
self... | class DistanceNbSetWeight(NbSetWeight):
| SHORT_NAME = 'DistanceNbSetWeight'
def __init__(self, weight_function=None, nbs_source='voronoi'):
if weight_function is None:
self.weight_function = {'function': 'smootherstep', 'options': {'lower': 1.2, 'upper': 1.3}}
else:
self.weight_function = weight_function
... | _rf = RatioFunction.from_dict(self.weight_function)
def weight(self, nb_set, structure_environments, cn_map=None, additional_info=None):
return self.weight_rf.eval(nb_set.angle_plateau())
def __eq__(self, other):
return self.__class__ == other.__class__
def __ne__(self, other):
re... | 167 | 168 | 563 | 10 | 157 | oxana-a/pymatgen | pymatgen/analysis/chemenv/coordination_environments/chemenv_strategies.py | Python | DistanceNbSetWeight | DistanceNbSetWeight | 1,482 | 1,533 | 1,482 | 1,483 | 60a85c25a0b1e8e0164ca2aa0af815ea16c69288 | bigcode/the-stack | train |
f8517d716f41b1673ce01ef6 | train | class | class SimpleAbundanceChemenvStrategy(AbstractChemenvStrategy):
"""
Simple ChemenvStrategy using the neighbors that are the most "abundant" in the grid of angle and distance
parameters for the definition of neighbors in the Voronoi approach.
The coordination environment is then given as the one with the ... | class SimpleAbundanceChemenvStrategy(AbstractChemenvStrategy):
| """
Simple ChemenvStrategy using the neighbors that are the most "abundant" in the grid of angle and distance
parameters for the definition of neighbors in the Voronoi approach.
The coordination environment is then given as the one with the lowest continuous symmetry measure
"""
DEFAULT_MAX_DIS... | -serializable dict representation of the SimplestChemenvStrategy object.
"""
return {"@module": self.__class__.__module__,
"@class": self.__class__.__name__,
"distance_cutoff": float(self._distance_cutoff),
"angle_cutoff": float(self._angle_cutoff),
... | 255 | 256 | 1,258 | 14 | 241 | oxana-a/pymatgen | pymatgen/analysis/chemenv/coordination_environments/chemenv_strategies.py | Python | SimpleAbundanceChemenvStrategy | SimpleAbundanceChemenvStrategy | 588 | 699 | 588 | 588 | 2eccb8883a9f3981fedc9fb44fd5a58bee2e3a37 | bigcode/the-stack | train |
1943bda09580c7238cf7054f | train | class | class AdditionalConditionInt(int, StrategyOption):
allowed_values = 'Integer amongst :\n'
for integer, description in AdditionalConditions.CONDITION_DESCRIPTION.items():
allowed_values += ' - {:d} for "{}"\n'.format(integer, description)
def __new__(cls, integer):
if str(int(integer)) != s... | class AdditionalConditionInt(int, StrategyOption):
| allowed_values = 'Integer amongst :\n'
for integer, description in AdditionalConditions.CONDITION_DESCRIPTION.items():
allowed_values += ' - {:d} for "{}"\n'.format(integer, description)
def __new__(cls, integer):
if str(int(integer)) != str(integer):
raise ValueError("Additiona... |
def as_dict(self):
return {'@module': self.__class__.__module__,
'@class': self.__class__.__name__,
'value': self}
@classmethod
def from_dict(cls, d):
return cls(d['value'])
class AdditionalConditionInt(int, StrategyOption):
| 63 | 64 | 185 | 9 | 54 | oxana-a/pymatgen | pymatgen/analysis/chemenv/coordination_environments/chemenv_strategies.py | Python | AdditionalConditionInt | AdditionalConditionInt | 122 | 143 | 122 | 123 | 47d2823508b1913f1ff367b9c11b53db3f7a133d | bigcode/the-stack | train |
aaa9033b9bf9e7ce46ab2209 | train | class | class DeltaDistanceNbSetWeight(NbSetWeight):
SHORT_NAME = 'DeltaDistanceNbSetWeight'
def __init__(self, weight_function=None, nbs_source='voronoi'):
if weight_function is None:
self.weight_function = {'function': 'smootherstep', 'options': {'lower': 0.1, 'upper': 0.2}}
else:
... | class DeltaDistanceNbSetWeight(NbSetWeight):
| SHORT_NAME = 'DeltaDistanceNbSetWeight'
def __init__(self, weight_function=None, nbs_source='voronoi'):
if weight_function is None:
self.weight_function = {'function': 'smootherstep', 'options': {'lower': 0.1, 'upper': 0.2}}
else:
self.weight_function = weight_function
... | oi[inb]['normalized_distance'] for inb in all_nbs_indices_except_nb_set]
if len(normalized_distances) == 0:
return 1.0
return self.weight_rf.eval(min(normalized_distances))
def __eq__(self, other):
return self.__class__ == other.__class__
def __ne__(self, other):
re... | 180 | 181 | 605 | 11 | 169 | oxana-a/pymatgen | pymatgen/analysis/chemenv/coordination_environments/chemenv_strategies.py | Python | DeltaDistanceNbSetWeight | DeltaDistanceNbSetWeight | 1,536 | 1,590 | 1,536 | 1,537 | 68a3160b613ca7d72594c407cbb17b3b64938b3c | bigcode/the-stack | train |
2aee9c30e8f17ef724cdd2a4 | train | function | def get_effective_csm(nb_set, cn_map, structure_environments, additional_info,
symmetry_measure_type, max_effective_csm, effective_csm_estimator_ratio_function):
try:
effective_csm = additional_info['effective_csms'][nb_set.isite][cn_map]
except KeyError:
site_ce_list = str... | def get_effective_csm(nb_set, cn_map, structure_environments, additional_info,
symmetry_measure_type, max_effective_csm, effective_csm_estimator_ratio_function):
| try:
effective_csm = additional_info['effective_csms'][nb_set.isite][cn_map]
except KeyError:
site_ce_list = structure_environments.ce_list[nb_set.isite]
site_chemenv = site_ce_list[cn_map[0]][cn_map[1]]
if site_chemenv is None:
effective_csm = 100.0
else:
... | nb_set)
return self.eval(fda_list=fda_list)
def gweight(self, fda_list):
return gmean(fda_list)
def aweight(self, fda_list):
return np.mean(fda_list)
def get_effective_csm(nb_set, cn_map, structure_environments, additional_info,
symmetry_measure_type, max_effectiv... | 88 | 88 | 295 | 38 | 50 | oxana-a/pymatgen | pymatgen/analysis/chemenv/coordination_environments/chemenv_strategies.py | Python | get_effective_csm | get_effective_csm | 962 | 982 | 962 | 963 | d10c566a853402ee343248b3d0cdd611c0f0275d | bigcode/the-stack | train |
63f8a6b0e209329f5032e187 | train | class | class AbstractChemenvStrategy(MSONable, metaclass=abc.ABCMeta):
"""
Class used to define a Chemenv strategy for the neighbors and coordination environment to be applied to a
StructureEnvironments object
"""
AC = AdditionalConditions()
STRATEGY_OPTIONS = OrderedDict()
STRATEGY_DESCRIPTION = N... | class AbstractChemenvStrategy(MSONable, metaclass=abc.ABCMeta):
| """
Class used to define a Chemenv strategy for the neighbors and coordination environment to be applied to a
StructureEnvironments object
"""
AC = AdditionalConditions()
STRATEGY_OPTIONS = OrderedDict()
STRATEGY_DESCRIPTION = None
STRATEGY_INFO_FIELDS = []
DEFAULT_SYMMETRY_MEASURE_T... | as_dict(self):
return {'@module': self.__class__.__module__,
'@class': self.__class__.__name__,
'value': self}
@classmethod
def from_dict(cls, d):
return cls(d['value'])
class AdditionalConditionInt(int, StrategyOption):
allowed_values = 'Integer amongst ... | 255 | 256 | 2,257 | 18 | 237 | oxana-a/pymatgen | pymatgen/analysis/chemenv/coordination_environments/chemenv_strategies.py | Python | AbstractChemenvStrategy | AbstractChemenvStrategy | 146 | 362 | 146 | 146 | 90368eab7099e226fc6c9ec1126523f20eda5154 | bigcode/the-stack | train |
ce6868ee9e0aa57788ed14d3 | train | class | class WeightedNbSetChemenvStrategy(AbstractChemenvStrategy):
"""
WeightedNbSetChemenvStrategy
"""
STRATEGY_DESCRIPTION = ' WeightedNbSetChemenvStrategy'
DEFAULT_CE_ESTIMATOR = {'function': 'power2_inverse_power2_decreasing',
'options': {'max_csm': 8.0}}
def __init... | class WeightedNbSetChemenvStrategy(AbstractChemenvStrategy):
| """
WeightedNbSetChemenvStrategy
"""
STRATEGY_DESCRIPTION = ' WeightedNbSetChemenvStrategy'
DEFAULT_CE_ESTIMATOR = {'function': 'power2_inverse_power2_decreasing',
'options': {'max_csm': 8.0}}
def __init__(self, structure_environments=None,
additi... | all_nbs_indices_except_nb_set = all_nbs_voro_indices.difference(nb_set.site_voronoi_indices)
normalized_distances = [voronoi[inb]['normalized_distance'] for inb in all_nbs_indices_except_nb_set]
if len(normalized_distances) == 0:
return 1.0
if len(nb_set) == 0:
return 0.... | 255 | 256 | 2,383 | 14 | 241 | oxana-a/pymatgen | pymatgen/analysis/chemenv/coordination_environments/chemenv_strategies.py | Python | WeightedNbSetChemenvStrategy | WeightedNbSetChemenvStrategy | 1,593 | 1,800 | 1,593 | 1,593 | fe3c746bb026323913ce8ddc32d577532fb16018 | bigcode/the-stack | train |
158792634eacc4c70f9f6302 | train | class | class MultiWeightsChemenvStrategy(WeightedNbSetChemenvStrategy):
"""
MultiWeightsChemenvStrategy
"""
STRATEGY_DESCRIPTION = ' Multi Weights ChemenvStrategy'
# STRATEGY_INFO_FIELDS = ['cn_map_surface_fraction', 'cn_map_surface_weight',
# 'cn_map_mean_csm', 'cn_map_csm_w... | class MultiWeightsChemenvStrategy(WeightedNbSetChemenvStrategy):
| """
MultiWeightsChemenvStrategy
"""
STRATEGY_DESCRIPTION = ' Multi Weights ChemenvStrategy'
# STRATEGY_INFO_FIELDS = ['cn_map_surface_fraction', 'cn_map_surface_weight',
# 'cn_map_mean_csm', 'cn_map_csm_weight',
# 'cn_map_delta_csm', 'cn_map... | WeightedNbSetChemenvStrategy object.
:return: Bson-serializable dict representation of the WeightedNbSetChemenvStrategy object.
"""
return {"@module": self.__class__.__module__,
"@class": self.__class__.__name__,
"additional_condition": self._additional_condition... | 255 | 256 | 1,819 | 16 | 239 | oxana-a/pymatgen | pymatgen/analysis/chemenv/coordination_environments/chemenv_strategies.py | Python | MultiWeightsChemenvStrategy | MultiWeightsChemenvStrategy | 1,803 | 1,964 | 1,803 | 1,803 | c648f950cdbdccf2c0fbbad015abeb5b7f1c541a | bigcode/the-stack | train |
fc0e99834677dbb878daedf4 | train | class | class CSMFloat(float, StrategyOption):
allowed_values = 'Real number between 0.0 and 100.0'
def __new__(cls, myfloat):
flt = float.__new__(cls, myfloat)
if flt < 0.0 or flt > 100.0:
raise ValueError("Continuous symmetry measure limits should be between 0.0 and 100.0")
retur... | class CSMFloat(float, StrategyOption):
| allowed_values = 'Real number between 0.0 and 100.0'
def __new__(cls, myfloat):
flt = float.__new__(cls, myfloat)
if flt < 0.0 or flt > 100.0:
raise ValueError("Continuous symmetry measure limits should be between 0.0 and 100.0")
return flt
def as_dict(self):
re... |
def as_dict(self):
return {'@module': self.__class__.__module__,
'@class': self.__class__.__name__,
'value': self}
@classmethod
def from_dict(cls, d):
return cls(d['value'])
class CSMFloat(float, StrategyOption):
| 63 | 64 | 148 | 9 | 54 | oxana-a/pymatgen | pymatgen/analysis/chemenv/coordination_environments/chemenv_strategies.py | Python | CSMFloat | CSMFloat | 102 | 119 | 102 | 103 | b5ae8c21e416170621143d55a899125d9f977efd | bigcode/the-stack | train |
55157dfe48a3b44e64882ef0 | train | class | class CNBiasNbSetWeight(NbSetWeight):
SHORT_NAME = 'CNBiasWeight'
def __init__(self, cn_weights, initialization_options):
self.cn_weights = cn_weights
self.initialization_options = initialization_options
def weight(self, nb_set, structure_environments, cn_map=None, additional_info=None):
... | class CNBiasNbSetWeight(NbSetWeight):
| SHORT_NAME = 'CNBiasWeight'
def __init__(self, cn_weights, initialization_options):
self.cn_weights = cn_weights
self.initialization_options = initialization_options
def weight(self, nb_set, structure_environments, cn_map=None, additional_info=None):
return self.cn_weights[len(nb_s... | return {"@module": self.__class__.__module__,
"@class": self.__class__.__name__,
"effective_csm_estimator": self.effective_csm_estimator,
"weight_estimator": self.weight_estimator,
"delta_cn_weight_estimators": self.delta_cn_weight_estimators,
... | 205 | 206 | 687 | 11 | 194 | oxana-a/pymatgen | pymatgen/analysis/chemenv/coordination_environments/chemenv_strategies.py | Python | CNBiasNbSetWeight | CNBiasNbSetWeight | 1,182 | 1,246 | 1,182 | 1,183 | 4eeb61ec21e21d8b7beec81edc57d0abfcced4a4 | bigcode/the-stack | train |
9ef99e337e50760e2288d07f | train | class | class AnglePlateauNbSetWeight(NbSetWeight):
SHORT_NAME = 'AnglePlateauWeight'
def __init__(self, angle_function=None, weight_function=None):
if angle_function is None:
self.angle_function = {'type': 'normalized_angle'}
else:
self.angle_function = angle_function
... | class AnglePlateauNbSetWeight(NbSetWeight):
| SHORT_NAME = 'AnglePlateauWeight'
def __init__(self, angle_function=None, weight_function=None):
if angle_function is None:
self.angle_function = {'type': 'normalized_angle'}
else:
self.angle_function = angle_function
if weight_function is None:
self.... | @module": self.__class__.__module__,
"@class": self.__class__.__name__,
"distance_function": self.distance_function,
"weight_function": self.weight_function
}
@classmethod
def from_dict(cls, dd):
return cls(distance_function=dd['distance_f... | 82 | 83 | 279 | 12 | 70 | oxana-a/pymatgen | pymatgen/analysis/chemenv/coordination_environments/chemenv_strategies.py | Python | AnglePlateauNbSetWeight | AnglePlateauNbSetWeight | 1,446 | 1,479 | 1,446 | 1,447 | 8df38b4427cbf7e3bfff525f504cca0b1a465da4 | bigcode/the-stack | train |
65f3e3c45f064c57e9bd5077 | train | class | class DistanceAngleAreaNbSetWeight(NbSetWeight):
SHORT_NAME = 'DistAngleAreaWeight'
AC = AdditionalConditions()
DEFAULT_SURFACE_DEFINITION = {'type': 'standard_elliptic',
'distance_bounds': {'lower': 1.2, 'upper': 1.8},
'angle_bounds': {'... | class DistanceAngleAreaNbSetWeight(NbSetWeight):
| SHORT_NAME = 'DistAngleAreaWeight'
AC = AdditionalConditions()
DEFAULT_SURFACE_DEFINITION = {'type': 'standard_elliptic',
'distance_bounds': {'lower': 1.2, 'upper': 1.8},
'angle_bounds': {'lower': 0.1, 'upper': 0.8}}
def __init__(self... | cn_weights = {cn: weight_cn1 * np.power(factor, cn - 1) for cn in range(1, 14)}
return cls(cn_weights=cn_weights, initialization_options=initialization_options)
@classmethod
def explicit(cls, cn_weights):
initialization_options = {'type': 'explicit'}
if set(cn_weights.keys()) != set(r... | 255 | 256 | 1,737 | 12 | 243 | oxana-a/pymatgen | pymatgen/analysis/chemenv/coordination_environments/chemenv_strategies.py | Python | DistanceAngleAreaNbSetWeight | DistanceAngleAreaNbSetWeight | 1,249 | 1,407 | 1,249 | 1,250 | 6d7250ca251dc55fe66051d3be613bb46e92b4ac | bigcode/the-stack | train |
52663dd986f5a3ea84a3bb3b | train | class | class TargettedPenaltiedAbundanceChemenvStrategy(SimpleAbundanceChemenvStrategy):
"""
Simple ChemenvStrategy using the neighbors that are the most "abundant" in the grid of angle and distance
parameters for the definition of neighbors in the Voronoi approach, with a bias for a given list of target
envir... | class TargettedPenaltiedAbundanceChemenvStrategy(SimpleAbundanceChemenvStrategy):
| """
Simple ChemenvStrategy using the neighbors that are the most "abundant" in the grid of angle and distance
parameters for the definition of neighbors in the Voronoi approach, with a bias for a given list of target
environments. This can be useful in the case of, e.g. connectivity search of some given... | faces(isite=isite,
surface_calculation_type=surface_calculation_type,
max_dist=self.DEFAULT_MAX_DIST)
def __eq__(self, other):
return (self.__class__.__name__ == other._... | 255 | 256 | 1,345 | 20 | 235 | oxana-a/pymatgen | pymatgen/analysis/chemenv/coordination_environments/chemenv_strategies.py | Python | TargettedPenaltiedAbundanceChemenvStrategy | TargettedPenaltiedAbundanceChemenvStrategy | 702 | 812 | 702 | 702 | da07dc19cafa8364b67c8083c42c4f1725e6eba7 | bigcode/the-stack | train |
2e3feb9ed7161a3d779e35d8 | train | function | def set_info(additional_info, field, isite, cn_map, value):
try:
additional_info[field][isite][cn_map] = value
except KeyError:
try:
additional_info[field][isite] = {cn_map: value}
except KeyError:
additional_info[field] = {isite: {cn_map: value}}
| def set_info(additional_info, field, isite, cn_map, value):
| try:
additional_info[field][isite][cn_map] = value
except KeyError:
try:
additional_info[field][isite] = {cn_map: value}
except KeyError:
additional_info[field] = {isite: {cn_map: value}}
| imator(csms)
set_info(additional_info=additional_info, field='effective_csms',
isite=nb_set.isite, cn_map=cn_map, value=effective_csm)
return effective_csm
def set_info(additional_info, field, isite, cn_map, value):
| 64 | 64 | 75 | 17 | 46 | oxana-a/pymatgen | pymatgen/analysis/chemenv/coordination_environments/chemenv_strategies.py | Python | set_info | set_info | 985 | 992 | 985 | 985 | 76a31770b62d047f16b28de7e7f0d629d6d1b83c | bigcode/the-stack | train |
bfc82aced7d42d036823691c | train | class | class SelfCSMNbSetWeight(NbSetWeight):
SHORT_NAME = 'SelfCSMWeight'
DEFAULT_EFFECTIVE_CSM_ESTIMATOR = {'function': 'power2_inverse_decreasing',
'options': {'max_csm': 8.0}}
DEFAULT_WEIGHT_ESTIMATOR = {'function': 'power2_decreasing_exp',
... | class SelfCSMNbSetWeight(NbSetWeight):
| SHORT_NAME = 'SelfCSMWeight'
DEFAULT_EFFECTIVE_CSM_ESTIMATOR = {'function': 'power2_inverse_decreasing',
'options': {'max_csm': 8.0}}
DEFAULT_WEIGHT_ESTIMATOR = {'function': 'power2_decreasing_exp',
'options': {'max_csm': 8.0,
... | mp_symbol, ce_dict in mingeoms
if ce_dict['other_symmetry_measures'][symmetry_measure_type] <= max_effective_csm]
effective_csm = effective_csm_estimator_ratio_function.mean_estimator(csms)
set_info(additional_info=additional_info, field='effective_csms',
... | 181 | 182 | 608 | 12 | 169 | oxana-a/pymatgen | pymatgen/analysis/chemenv/coordination_environments/chemenv_strategies.py | Python | SelfCSMNbSetWeight | SelfCSMNbSetWeight | 995 | 1,048 | 995 | 996 | 0beb2f878f1671b3a2f2e0b1ec8feacf792faf05 | bigcode/the-stack | train |
e3a9e156011aba213425781a | train | class | class AngleCutoffFloat(float, StrategyOption):
allowed_values = 'Real number between 0.0 and 1.0'
def __new__(cls, myfloat):
flt = float.__new__(cls, myfloat)
if flt < 0.0 or flt > 1.0:
raise ValueError("Angle cutoff should be between 0.0 and 1.0")
return flt
def as_di... | class AngleCutoffFloat(float, StrategyOption):
| allowed_values = 'Real number between 0.0 and 1.0'
def __new__(cls, myfloat):
flt = float.__new__(cls, myfloat)
if flt < 0.0 or flt > 1.0:
raise ValueError("Angle cutoff should be between 0.0 and 1.0")
return flt
def as_dict(self):
return {'@module': self.__clas... | def as_dict(self):
return {'@module': self.__class__.__module__,
'@class': self.__class__.__name__,
'value': self}
@classmethod
def from_dict(cls, d):
return cls(d['value'])
class AngleCutoffFloat(float, StrategyOption):
| 63 | 64 | 147 | 10 | 53 | oxana-a/pymatgen | pymatgen/analysis/chemenv/coordination_environments/chemenv_strategies.py | Python | AngleCutoffFloat | AngleCutoffFloat | 82 | 99 | 82 | 83 | 6c03d9eb68f115e98047015dbde65053acc45b05 | bigcode/the-stack | train |
14b1184bb352b38573d31f2e | train | class | class DistanceCutoffFloat(float, StrategyOption):
allowed_values = 'Real number between 1.0 and +infinity'
def __new__(cls, myfloat):
flt = float.__new__(cls, myfloat)
if flt < 1.0:
raise ValueError("Distance cutoff should be between 1.0 and +infinity")
return flt
def ... | class DistanceCutoffFloat(float, StrategyOption):
| allowed_values = 'Real number between 1.0 and +infinity'
def __new__(cls, myfloat):
flt = float.__new__(cls, myfloat)
if flt < 1.0:
raise ValueError("Distance cutoff should be between 1.0 and +infinity")
return flt
def as_dict(self):
return {'@module': self.__cl... | ies()
class StrategyOption(MSONable, metaclass=abc.ABCMeta):
allowed_values = None
@abc.abstractmethod
def as_dict(self):
"""
A JSON serializable dict representation of this strategy option.
"""
pass
class DistanceCutoffFloat(float, StrategyOption):
| 64 | 64 | 137 | 10 | 53 | oxana-a/pymatgen | pymatgen/analysis/chemenv/coordination_environments/chemenv_strategies.py | Python | DistanceCutoffFloat | DistanceCutoffFloat | 62 | 79 | 62 | 63 | 503ff674c358a2063b19b04060cb94f757b7edca | bigcode/the-stack | train |
7ebdf789e32c13e93706e688 | train | class | class NormalizedAngleDistanceNbSetWeight(NbSetWeight):
SHORT_NAME = 'NormAngleDistWeight'
def __init__(self, average_type, aa, bb):
self.average_type = average_type
if self.average_type == 'geometric':
self.eval = self.gweight
elif self.average_type == 'arithmetic':
... | class NormalizedAngleDistanceNbSetWeight(NbSetWeight):
| SHORT_NAME = 'NormAngleDistWeight'
def __init__(self, average_type, aa, bb):
self.average_type = average_type
if self.average_type == 'geometric':
self.eval = self.gweight
elif self.average_type == 'arithmetic':
self.eval = self.aweight
else:
... | Weight'
def __init__(self, aa=1.0):
self.aa = aa
if self.aa == 1.0:
self.aw = self.angle_sum
else:
self.aw = self.angle_sumn
def weight(self, nb_set, structure_environments, cn_map=None, additional_info=None):
return self.aw(nb_set=nb_set)
def angle... | 245 | 246 | 820 | 13 | 232 | oxana-a/pymatgen | pymatgen/analysis/chemenv/coordination_environments/chemenv_strategies.py | Python | NormalizedAngleDistanceNbSetWeight | NormalizedAngleDistanceNbSetWeight | 866 | 959 | 866 | 867 | 47c88c46cb5d26094484faa972ee43fa5b005248 | bigcode/the-stack | train |
7657585337ff61bc722182e1 | train | class | class StrategyOption(MSONable, metaclass=abc.ABCMeta):
allowed_values = None
@abc.abstractmethod
def as_dict(self):
"""
A JSON serializable dict representation of this strategy option.
"""
pass
| class StrategyOption(MSONable, metaclass=abc.ABCMeta):
| allowed_values = None
@abc.abstractmethod
def as_dict(self):
"""
A JSON serializable dict representation of this strategy option.
"""
pass
|
from collections import OrderedDict
module_dir = os.path.dirname(os.path.abspath(__file__))
MPSYMBOL_TO_CN = AllCoordinationGeometries().get_symbol_cn_mapping()
ALLCG = AllCoordinationGeometries()
class StrategyOption(MSONable, metaclass=abc.ABCMeta):
| 64 | 64 | 52 | 15 | 49 | oxana-a/pymatgen | pymatgen/analysis/chemenv/coordination_environments/chemenv_strategies.py | Python | StrategyOption | StrategyOption | 50 | 59 | 50 | 51 | 39db04b2c2febdbf7d5914c3185f5e36d6f2b8d2 | bigcode/the-stack | train |
89689e2d3758245d3d9ff5d6 | train | class | class DistancePlateauNbSetWeight(NbSetWeight):
SHORT_NAME = 'DistancePlateauWeight'
def __init__(self, distance_function=None, weight_function=None):
if distance_function is None:
self.distance_function = {'type': 'normalized_distance'}
else:
self.distance_function = di... | class DistancePlateauNbSetWeight(NbSetWeight):
| SHORT_NAME = 'DistancePlateauWeight'
def __init__(self, distance_function=None, weight_function=None):
if distance_function is None:
self.distance_function = {'type': 'normalized_distance'}
else:
self.distance_function = distance_function
if weight_function is No... | ": self.additional_condition}
@classmethod
def from_dict(cls, dd):
return cls(weight_type=dd['weight_type'], surface_definition=dd['surface_definition'],
nb_sets_from_hints=dd['nb_sets_from_hints'], other_nb_sets=dd['other_nb_sets'],
additional_condition=dd['additi... | 82 | 83 | 279 | 12 | 70 | oxana-a/pymatgen | pymatgen/analysis/chemenv/coordination_environments/chemenv_strategies.py | Python | DistancePlateauNbSetWeight | DistancePlateauNbSetWeight | 1,410 | 1,443 | 1,410 | 1,411 | 17fdc4313ea7c28974da0a4047eb47ebfd336425 | bigcode/the-stack | train |
bff5875bc5150f31560f3ac5 | train | class | class NbSetWeight(MSONable, metaclass=abc.ABCMeta):
@abc.abstractmethod
def as_dict(self):
"""
A JSON serializable dict representation of this neighbors set weight.
"""
pass
@abc.abstractmethod
def weight(self, nb_set, structure_environments, cn_map=None, additional_inf... | class NbSetWeight(MSONable, metaclass=abc.ABCMeta):
@abc.abstractmethod
| def as_dict(self):
"""
A JSON serializable dict representation of this neighbors set weight.
"""
pass
@abc.abstractmethod
def weight(self, nb_set, structure_environments, cn_map=None, additional_info=None):
pass
| abundant=d["max_nabundant"],
target_environments=d["target_environments"],
target_penalty_type=d["target_penalty_type"],
max_csm=d["max_csm"])
class NbSetWeight(MSONable, metaclass=abc.ABCMeta):
@abc.abstractmethod
| 63 | 64 | 77 | 22 | 41 | oxana-a/pymatgen | pymatgen/analysis/chemenv/coordination_environments/chemenv_strategies.py | Python | NbSetWeight | NbSetWeight | 815 | 826 | 815 | 817 | 90f13302cf036cb96143ee6614a5d207869f202d | bigcode/the-stack | train |
4b89a8dbd89bf2df0ef560aa | train | class | class DeltaCSMNbSetWeight(NbSetWeight):
SHORT_NAME = 'DeltaCSMWeight'
DEFAULT_EFFECTIVE_CSM_ESTIMATOR = {'function': 'power2_inverse_decreasing',
'options': {'max_csm': 8.0}}
DEFAULT_SYMMETRY_MEASURE_TYPE = 'csm_wcs_ctwcc'
DEFAULT_WEIGHT_ESTIMATOR = {'function': ... | class DeltaCSMNbSetWeight(NbSetWeight):
| SHORT_NAME = 'DeltaCSMWeight'
DEFAULT_EFFECTIVE_CSM_ESTIMATOR = {'function': 'power2_inverse_decreasing',
'options': {'max_csm': 8.0}}
DEFAULT_SYMMETRY_MEASURE_TYPE = 'csm_wcs_ctwcc'
DEFAULT_WEIGHT_ESTIMATOR = {'function': 'smootherstep',
... | .weight_estimator_rf.evaluate(effective_csm)
set_info(additional_info=additional_info, field='self_csms_weights', isite=nb_set.isite,
cn_map=cn_map, value=weight)
return weight
def __eq__(self, other):
return (self.effective_csm_estimator == other.effective_csm_estimator an... | 255 | 256 | 1,652 | 12 | 243 | oxana-a/pymatgen | pymatgen/analysis/chemenv/coordination_environments/chemenv_strategies.py | Python | DeltaCSMNbSetWeight | DeltaCSMNbSetWeight | 1,051 | 1,179 | 1,051 | 1,052 | 3f757c71f3f6047f98793cc2aed1cecac636bf04 | bigcode/the-stack | train |
d89532e3da06395a9841dd24 | train | class | class CqlConnector:
def __init__(self, connection, tableName, pk, exactlyOnceTableName=None):
self.connection = connection
self.tableName = tableName
self.pk = pk
self.exactlyOnceTableName = exactlyOnceTableName
self.exactlyOnceLastId = None
self.shouldCompareId = Tru... | class CqlConnector:
| def __init__(self, connection, tableName, pk, exactlyOnceTableName=None):
self.connection = connection
self.tableName = tableName
self.pk = pk
self.exactlyOnceTableName = exactlyOnceTableName
self.exactlyOnceLastId = None
self.shouldCompareId = True if self.exactlyOnc... | property
def password(self):
return self._password() if callable(self._password) else self._password
@property
def db(self):
return self._db() if callable(self._db) else self._db
@property
def keyspace(self):
return self._keyspace() if callable(self._keyspace) else self._ke... | 256 | 256 | 1,016 | 5 | 250 | shankai/rgsync | rgsync/Connectors/cql_connector.py | Python | CqlConnector | CqlConnector | 48 | 150 | 48 | 48 | de1c41debdddbc2dc483514ad34bb0b70a4ba2f9 | bigcode/the-stack | train |
94bf55fafedde82bfb5d20f1 | train | class | class CqlConnection():
def __init__(self, user, password, db, keyspace):
self._user = user
self._password = password
self._db = db
self._keyspace = keyspace
@property
def user(self):
return self._user() if callable(self._user) else self._user
@property
def p... | class CqlConnection():
| def __init__(self, user, password, db, keyspace):
self._user = user
self._password = password
self._db = db
self._keyspace = keyspace
@property
def user(self):
return self._user() if callable(self._user) else self._user
@property
def password(self):
... | from rgsync.common import *
from redisgears import getMyHashTag as hashtag
import json
class CqlConnection():
| 27 | 99 | 330 | 5 | 21 | shankai/rgsync | rgsync/Connectors/cql_connector.py | Python | CqlConnection | CqlConnection | 5 | 45 | 5 | 5 | 788338df196fec06a744bf428b96c0a225ac2e99 | bigcode/the-stack | train |
860001340cb6fcc73f5d7dcd | train | class | class Test_HalfspaceIntersection:
def assert_unordered_allclose(self, arr1, arr2, rtol=1e-7):
"""Check that every line in arr1 is only once in arr2"""
assert_equal(arr1.shape, arr2.shape)
truths = np.zeros((arr1.shape[0],), dtype=bool)
for l1 in arr1:
indexes = np.nonzer... | class Test_HalfspaceIntersection:
| def assert_unordered_allclose(self, arr1, arr2, rtol=1e-7):
"""Check that every line in arr1 is only once in arr2"""
assert_equal(arr1.shape, arr2.shape)
truths = np.zeros((arr1.shape[0],), dtype=bool)
for l1 in arr1:
indexes = np.nonzero((abs(arr2 - l1) < rtol).all(axis... | incremental map
for objx in obj, obj3:
vertex_map = {-1: -1}
for i, v in enumerate(objx.vertices):
for j, v2 in enumerate(obj2.vertices):
if np.allclose(v, v2):
vertex_map[i] = j
def remap(x):
if ha... | 256 | 256 | 1,749 | 7 | 248 | jcampbell/scipy | scipy/spatial/tests/test_qhull.py | Python | Test_HalfspaceIntersection | Test_HalfspaceIntersection | 999 | 1,142 | 999 | 999 | 70977d036d893cca5e0b75f9515e63cccdd9d282 | bigcode/the-stack | train |
57fecf13c8a701a5f66bb041 | train | class | class TestVoronoi:
def test_masked_array_fails(self):
masked_array = np.ma.masked_all(1)
assert_raises(ValueError, qhull.Voronoi, masked_array)
def test_simple(self):
# Simple case with known Voronoi diagram
points = [(0, 0), (0, 1), (0, 2),
(1, 0), (1, 1), (1,... | class TestVoronoi:
| def test_masked_array_fails(self):
masked_array = np.ma.masked_all(1)
assert_raises(ValueError, qhull.Voronoi, masked_array)
def test_simple(self):
# Simple case with known Voronoi diagram
points = [(0, 0), (0, 1), (0, 2),
(1, 0), (1, 1), (1, 2),
... | _options='QG4')
expected = np.array([False, False, False, False], dtype=bool)
actual = hull.good
assert_equal(actual, expected)
@pytest.mark.parametrize("incremental", [False, True])
def test_good3d(self, incremental):
# Make sure the QGn option gives the correct value of "good"... | 256 | 256 | 1,830 | 6 | 250 | jcampbell/scipy | scipy/spatial/tests/test_qhull.py | Python | TestVoronoi | TestVoronoi | 797 | 994 | 797 | 797 | 6db93b23c1c1b5335b0f286c779302600f280a51 | bigcode/the-stack | train |
b890425136004188efe165a2 | train | class | class TestUtilities:
"""
Check that utility functions work.
"""
def test_find_simplex(self):
# Simple check that simplex finding works
points = np.array([(0,0), (0,1), (1,1), (1,0)], dtype=np.double)
tri = qhull.Delaunay(points)
# +---+
# |\ 0|
# | \ |
... | class TestUtilities:
| """
Check that utility functions work.
"""
def test_find_simplex(self):
# Simple check that simplex finding works
points = np.array([(0,0), (0,1), (1,1), (1,0)], dtype=np.double)
tri = qhull.Delaunay(points)
# +---+
# |\ 0|
# | \ |
# |1 \|
... | ], xd2[2], tpl=sorted_tuple)
assert_unordered_tuple_list_equal(xd[3], xd2[3], tpl=sorted_tuple)
assert_array_equal(xd[4], xd2[4])
assert_allclose(yd[0], yd2[0])
assert_unordered_tuple_list_equal(yd[1], yd2[1], tpl=sorted_tuple)
assert_unordered_tuple_list_equal(yd[2], yd2[2], tp... | 256 | 256 | 2,408 | 4 | 252 | jcampbell/scipy | scipy/spatial/tests/test_qhull.py | Python | TestUtilities | TestUtilities | 172 | 383 | 172 | 172 | 3c95d4accc81111fa8c2f8b53158adccdf7f9941 | bigcode/the-stack | train |
ec34b845d8287c7dadf38bcc | train | function | def assert_unordered_tuple_list_equal(a, b, tpl=tuple):
if isinstance(a, np.ndarray):
a = a.tolist()
if isinstance(b, np.ndarray):
b = b.tolist()
a = list(map(tpl, a))
a.sort()
b = list(map(tpl, b))
b.sort()
assert_equal(a, b)
| def assert_unordered_tuple_list_equal(a, b, tpl=tuple):
| if isinstance(a, np.ndarray):
a = a.tolist()
if isinstance(b, np.ndarray):
b = b.tolist()
a = list(map(tpl, a))
a.sort()
b = list(map(tpl, b))
b.sort()
assert_equal(a, b)
|
from scipy.spatial import cKDTree as KDTree
from scipy.spatial import Voronoi
import itertools
def sorted_tuple(x):
return tuple(sorted(x))
def sorted_unique_tuple(x):
return tuple(np.unique(x))
def assert_unordered_tuple_list_equal(a, b, tpl=tuple):
| 64 | 64 | 78 | 15 | 49 | jcampbell/scipy | scipy/spatial/tests/test_qhull.py | Python | assert_unordered_tuple_list_equal | assert_unordered_tuple_list_equal | 24 | 33 | 24 | 24 | 9dbfb59096abb22e050e9372f4b82507f596c24e | bigcode/the-stack | train |
d36ef04603cdc7c154264b11 | train | class | class TestVertexNeighborVertices:
def _check(self, tri):
expected = [set() for j in range(tri.points.shape[0])]
for s in tri.simplices:
for a in s:
for b in s:
if a != b:
expected[a].add(b)
indptr, indices = tri.vertex_... | class TestVertexNeighborVertices:
| def _check(self, tri):
expected = [set() for j in range(tri.points.shape[0])]
for s in tri.simplices:
for a in s:
for b in s:
if a != b:
expected[a].add(b)
indptr, indices = tri.vertex_neighbor_vertices
got = [... | self._check_barycentric_transforms(tri, err_msg=err_msg,
unit_cube=True,
unit_cube_tol=2*eps)
# Check with duplicated data
tri = qhull.Delaunay(np.r_[grid, grid])
self._check_barycentric_t... | 92 | 92 | 307 | 6 | 86 | jcampbell/scipy | scipy/spatial/tests/test_qhull.py | Python | TestVertexNeighborVertices | TestVertexNeighborVertices | 386 | 416 | 386 | 386 | 9219f8f9874b32d7d6a0da1d2b14cc22a2285b47 | bigcode/the-stack | train |
ecdf7673bfb52a3ce5c8b5c1 | train | class | class TestDelaunay:
"""
Check that triangulation works.
"""
def test_masked_array_fails(self):
masked_array = np.ma.masked_all(1)
assert_raises(ValueError, qhull.Delaunay, masked_array)
def test_array_with_nans_fails(self):
points_with_nan = np.array([(0,0), (0,1), (1,1), (... | class TestDelaunay:
| """
Check that triangulation works.
"""
def test_masked_array_fails(self):
masked_array = np.ma.masked_all(1)
assert_raises(ValueError, qhull.Delaunay, masked_array)
def test_array_with_nans_fails(self):
points_with_nan = np.array([(0,0), (0,1), (1,1), (1,np.nan)], dtype=np... | :
expected[a].add(b)
indptr, indices = tri.vertex_neighbor_vertices
got = [set(map(int, indices[indptr[j]:indptr[j+1]]))
for j in range(tri.points.shape[0])]
assert_equal(got, expected, err_msg="%r != %r" % (got, expected))
def test_triangle(self):
... | 256 | 256 | 1,341 | 6 | 250 | jcampbell/scipy | scipy/spatial/tests/test_qhull.py | Python | TestDelaunay | TestDelaunay | 419 | 551 | 419 | 419 | 6e4f559b7659434a4b634dc0661b7b1218a158b1 | bigcode/the-stack | train |
ea590c550f05a30bbf06d0f4 | train | function | def sorted_unique_tuple(x):
return tuple(np.unique(x))
| def sorted_unique_tuple(x):
| return tuple(np.unique(x))
| pytest
from pytest import raises as assert_raises
import scipy.spatial._qhull as qhull
from scipy.spatial import cKDTree as KDTree
from scipy.spatial import Voronoi
import itertools
def sorted_tuple(x):
return tuple(sorted(x))
def sorted_unique_tuple(x):
| 64 | 64 | 13 | 6 | 58 | jcampbell/scipy | scipy/spatial/tests/test_qhull.py | Python | sorted_unique_tuple | sorted_unique_tuple | 20 | 21 | 20 | 20 | 5e1041a075635e8802ef7d5330add1b9370955d6 | bigcode/the-stack | train |
d8c54a0d38c7108832a615b8 | train | class | class TestConvexHull:
def test_masked_array_fails(self):
masked_array = np.ma.masked_all(1)
assert_raises(ValueError, qhull.ConvexHull, masked_array)
def test_array_with_nans_fails(self):
points_with_nan = np.array([(0,0), (1,1), (2,np.nan)], dtype=np.double)
assert_raises(Value... | class TestConvexHull:
| def test_masked_array_fails(self):
masked_array = np.ma.masked_all(1)
assert_raises(ValueError, qhull.ConvexHull, masked_array)
def test_array_with_nans_fails(self):
points_with_nan = np.array([(0,0), (1,1), (2,np.nan)], dtype=np.double)
assert_raises(ValueError, qhull.ConvexHul... | = np.array([-t[1], t[0]]) # normal
# check that the two line segments are parallel
# to the same line
c1 = np.dot(n, points[b] - points[ap])
c2 = np.dot(n, points[a] - points[ap])
if not np.allclose(np.dot(c1, n), 0):
... | 256 | 256 | 2,073 | 6 | 250 | jcampbell/scipy | scipy/spatial/tests/test_qhull.py | Python | TestConvexHull | TestConvexHull | 609 | 795 | 609 | 609 | aba3bb03a8223efdaaabe52e86a589427aa21dbd | bigcode/the-stack | train |
50e9b60160c47bd0d5dba579 | train | function | def sorted_tuple(x):
return tuple(sorted(x))
| def sorted_tuple(x):
| return tuple(sorted(x))
| assert_, assert_allclose, assert_array_equal)
import pytest
from pytest import raises as assert_raises
import scipy.spatial._qhull as qhull
from scipy.spatial import cKDTree as KDTree
from scipy.spatial import Voronoi
import itertools
def sorted_tuple(x):
| 64 | 64 | 11 | 5 | 58 | jcampbell/scipy | scipy/spatial/tests/test_qhull.py | Python | sorted_tuple | sorted_tuple | 16 | 17 | 16 | 16 | b7fddd9ad9e9e2cdbc8367861014cbcf2dcab35c | bigcode/the-stack | train |
b7396c623cefe8e1ffce585c | train | function | def _add_inc_data(name, chunksize):
"""
Generate incremental datasets from basic data sets
"""
points = DATASETS[name]
ndim = points.shape[1]
opts = None
nmin = ndim + 2
if name == 'some-points':
# since Qz is not allowed, use QJ
opts = 'QJ Pp'
elif name == 'patholo... | def _add_inc_data(name, chunksize):
| """
Generate incremental datasets from basic data sets
"""
points = DATASETS[name]
ndim = points.shape[1]
opts = None
nmin = ndim + 2
if name == 'some-points':
# since Qz is not allowed, use QJ
opts = 'QJ Pp'
elif name == 'pathological-1':
# include enough p... | ological-2': pathological_data_2
}
INCREMENTAL_DATASETS = {
'bug-2850': (bug_2850_chunks, None),
'bug-2850-2': (bug_2850_chunks_2, None),
}
def _add_inc_data(name, chunksize):
| 64 | 64 | 192 | 10 | 54 | jcampbell/scipy | scipy/spatial/tests/test_qhull.py | Python | _add_inc_data | _add_inc_data | 97 | 120 | 97 | 97 | 9f35b56862e7fe120ddc35a13e800e39aff9456f | bigcode/the-stack | train |
bbace5c96bcdd34a0d1a2807 | train | function | def assert_hulls_equal(points, facets_1, facets_2):
# Check that two convex hulls constructed from the same point set
# are equal
facets_1 = set(map(sorted_tuple, facets_1))
facets_2 = set(map(sorted_tuple, facets_2))
if facets_1 != facets_2 and points.shape[1] == 2:
# The direct check fai... | def assert_hulls_equal(points, facets_1, facets_2):
# Check that two convex hulls constructed from the same point set
# are equal
| facets_1 = set(map(sorted_tuple, facets_1))
facets_2 = set(map(sorted_tuple, facets_2))
if facets_1 != facets_2 and points.shape[1] == 2:
# The direct check fails for the pathological cases
# --- then the convex hull from Delaunay differs (due
# to rounding error etc.) from the hull... | assert_unordered_tuple_list_equal(obj2.simplices, obj3.simplices,
tpl=sorted_tuple)
def test_vertices_deprecation(self):
tri = qhull.Delaunay([(0, 0), (0, 1), (1, 0)])
msg = ("Delaunay attribute 'vertices' is deprecated in favour of "
"'simp... | 149 | 149 | 498 | 35 | 113 | jcampbell/scipy | scipy/spatial/tests/test_qhull.py | Python | assert_hulls_equal | assert_hulls_equal | 554 | 606 | 554 | 557 | 85f1af0087d14f60cb9f67e2a63c4f6b1aaad8ec | bigcode/the-stack | train |
d1923b8f32bc5fe9e31b0c18 | train | class | class Test_Qhull:
def test_swapping(self):
# Check that Qhull state swapping works
x = qhull._Qhull(b'v',
np.array([[0,0],[0,1],[1,0],[1,1.],[0.5,0.5]]),
b'Qz')
xd = copy.deepcopy(x.get_voronoi_diagram())
y = qhull._Qhull(b'v',
... | class Test_Qhull:
| def test_swapping(self):
# Check that Qhull state swapping works
x = qhull._Qhull(b'v',
np.array([[0,0],[0,1],[1,0],[1,1.],[0.5,0.5]]),
b'Qz')
xd = copy.deepcopy(x.get_voronoi_diagram())
y = qhull._Qhull(b'v',
... | = 'QJ Pp'
elif name == 'pathological-1':
# include enough points so that we get different x-coordinates
nmin = 12
chunks = [points[:nmin]]
for j in range(nmin, len(points), chunksize):
chunks.append(points[j:j+chunksize])
new_name = "%s-chunk-%d" % (name, chunksize)
assert... | 152 | 152 | 507 | 6 | 146 | jcampbell/scipy | scipy/spatial/tests/test_qhull.py | Python | Test_Qhull | Test_Qhull | 128 | 169 | 128 | 128 | 889786c379a9153c1272a5455d7406bebee7b738 | bigcode/the-stack | train |
4be9bde8e468c853977791e4 | train | function | def ret_sum_ln(params,time,flux,yerr):
(period, T0, rprs, impact,
alb,occ,ell,ecosw, esinw,
lnnoiseA1, lnnoiseW1,
lnnoiseA2, lnnoiseW2 )= params
M = LCModel()
M.add_star(rho=0.0073,ld1=0.5,ld2=0.4)
M.add_planet(T0=T0,period=period,
impact=impact,rprs=rprs,
alb=alb... | def ret_sum_ln(params,time,flux,yerr):
| (period, T0, rprs, impact,
alb,occ,ell,ecosw, esinw,
lnnoiseA1, lnnoiseW1,
lnnoiseA2, lnnoiseW2 )= params
M = LCModel()
M.add_star(rho=0.0073,ld1=0.5,ld2=0.4)
M.add_planet(T0=T0,period=period,
impact=impact,rprs=rprs,
alb=alb,occ=occ,ell=ell,
ecosw=ecosw, ... | (kernel)
lnlike = 0.
for i in np.arange(len(time) // 1000)[0:10]:
section = np.arange(i*1000,i*1000 + 1000)
gp.compute(time[section], yerr[section])
lnlike += gp.lnlikelihood(resid[section])
return -lnlike
def ret_sum_ln(params,time,flux,yerr):
| 88 | 88 | 296 | 11 | 76 | mrtommyb/GP_model_Kepler_data | code/section_gp_fit.py | Python | ret_sum_ln | ret_sum_ln | 77 | 98 | 77 | 77 | b8e3cf85f12ef2c4ec457b29aa314512d9f8ef0d | bigcode/the-stack | train |
d07c5afac5fb9aee8ff913f9 | train | function | def ret_product(params,time,flux,yerr):
(period, T0, rprs, impact, noiseA1, noiseW1,
noiseA2, noiseW2, noiseM2) = params
M = LCModel()
M.add_star(rho=0.0073,ld1=0.5,ld2=0.4)
M.add_planet(T0=T0,period=period,
impact=impact,rprs=rprs)
M.add_data(time=time)
resid = flux - M.transitm... | def ret_product(params,time,flux,yerr):
| (period, T0, rprs, impact, noiseA1, noiseW1,
noiseA2, noiseW2, noiseM2) = params
M = LCModel()
M.add_star(rho=0.0073,ld1=0.5,ld2=0.4)
M.add_planet(T0=T0,period=period,
impact=impact,rprs=rprs)
M.add_data(time=time)
resid = flux - M.transitmodel
kernel = (((noiseA1 * ExpSquare... | (time) // 1000)[0:10]:
section = np.arange(i*1000,i*1000 + 1000)
gp.compute(time[section], yerr[section])
lnlike += gp.lnlikelihood(resid[section])
return -lnlike
def ret_product(params,time,flux,yerr):
| 71 | 71 | 239 | 10 | 60 | mrtommyb/GP_model_Kepler_data | code/section_gp_fit.py | Python | ret_product | ret_product | 35 | 52 | 35 | 35 | 43165825537a4af247471526ba7603ec89050817 | bigcode/the-stack | train |
fd06c6b18f7e0ba7e76792de | train | function | def ret_simplest(params,time,flux,yerr,fixed):
(period, T0, rprs, impact,
alb,occ,ell,ecosw, esinw) = fixed
(noiseA1, noiseW1)= params
M = LCModel()
M.add_star(rho=0.0073,ld1=0.5,ld2=0.4)
M.add_planet(T0=T0,period=period,
impact=impact,rprs=rprs,
alb=alb,occ=occ,ell=ell,
... | def ret_simplest(params,time,flux,yerr,fixed):
| (period, T0, rprs, impact,
alb,occ,ell,ecosw, esinw) = fixed
(noiseA1, noiseW1)= params
M = LCModel()
M.add_star(rho=0.0073,ld1=0.5,ld2=0.4)
M.add_planet(T0=T0,period=period,
impact=impact,rprs=rprs,
alb=alb,occ=occ,ell=ell,
ecosw=ecosw, esinw=esinw)
M.add_dat... | .
for i in np.arange(len(time) // 300):
section = np.arange(i*300,i*300 + 300)
gp.compute(time[section], yerr[section])
lnlike += gp.lnlikelihood(resid[section])
return -lnlike
def ret_simplest(params,time,flux,yerr,fixed):
| 75 | 75 | 250 | 14 | 60 | mrtommyb/GP_model_Kepler_data | code/section_gp_fit.py | Python | ret_simplest | ret_simplest | 142 | 161 | 142 | 142 | 5f16ac880ebe66e620a2f55b28677bb2af705204 | bigcode/the-stack | train |
3ffdd33e2fa1d666b577f24f | train | function | def ret_simple_ln(params,time,flux,yerr):
(period, T0, rprs, impact,
alb,occ,ell,ecosw, esinw,
lnnoiseA1, lnnoiseW1)= params
M = LCModel()
M.add_star(rho=0.0073,ld1=0.5,ld2=0.4)
M.add_planet(T0=T0,period=period,
impact=impact,rprs=rprs,
alb=alb,occ=occ,ell=ell,
ec... | def ret_simple_ln(params,time,flux,yerr):
| (period, T0, rprs, impact,
alb,occ,ell,ecosw, esinw,
lnnoiseA1, lnnoiseW1)= params
M = LCModel()
M.add_star(rho=0.0073,ld1=0.5,ld2=0.4)
M.add_planet(T0=T0,period=period,
impact=impact,rprs=rprs,
alb=alb,occ=occ,ell=ell,
ecosw=ecosw, esinw=esinw)
M.add_data(tim... | in np.arange(len(time) // 1000)[0:10]:
section = np.arange(i*1000,i*1000 + 1000)
gp.compute(time[section], yerr[section])
lnlike += gp.lnlikelihood(resid[section])
return -lnlike
def ret_simple_ln(params,time,flux,yerr):
| 76 | 76 | 256 | 11 | 64 | mrtommyb/GP_model_Kepler_data | code/section_gp_fit.py | Python | ret_simple_ln | ret_simple_ln | 100 | 119 | 100 | 100 | ca0d562ffd90c7f2b0130c56862d30ae28358ab2 | bigcode/the-stack | train |
7d619a2fa79acf846e50c4d2 | train | function | def ret_simple(params,time,flux,yerr):
(period, T0, rprs, impact,
alb,occ,ell,ecosw, esinw,
noiseA1, noiseW1)= params
M = LCModel()
M.add_star(rho=0.0073,ld1=0.5,ld2=0.4)
M.add_planet(T0=T0,period=period,
impact=impact,rprs=rprs,
alb=alb,occ=occ,ell=ell,
ecosw=eco... | def ret_simple(params,time,flux,yerr):
| (period, T0, rprs, impact,
alb,occ,ell,ecosw, esinw,
noiseA1, noiseW1)= params
M = LCModel()
M.add_star(rho=0.0073,ld1=0.5,ld2=0.4)
M.add_planet(T0=T0,period=period,
impact=impact,rprs=rprs,
alb=alb,occ=occ,ell=ell,
ecosw=ecosw, esinw=esinw)
M.add_data(time=ti... | i in np.arange(len(time) // 1000):
section = np.arange(i*1000,i*1000 + 1000)
gp.compute(time[section], yerr[section])
lnlike += gp.lnlikelihood(resid[section])
return -lnlike
def ret_simple(params,time,flux,yerr):
| 72 | 72 | 242 | 10 | 61 | mrtommyb/GP_model_Kepler_data | code/section_gp_fit.py | Python | ret_simple | ret_simple | 121 | 140 | 121 | 121 | e141b4299709bfc8a10f2009ba3b727a55aa2fb3 | bigcode/the-stack | train |
21f282692acaae9d348976a4 | train | function | def ret_opt(params,time,flux,yerr):
period, T0, rprs, impact, noiseA, noiseW = params
M = LCModel()
M.add_star(rho=0.0073,ld1=0.5,ld2=0.4)
M.add_planet(T0=T0,period=period,
impact=impact,rprs=rprs)
M.add_data(time=time)
resid = flux - M.transitmodel
kernel = noiseA * ExpSquaredKernel... | def ret_opt(params,time,flux,yerr):
| period, T0, rprs, impact, noiseA, noiseW = params
M = LCModel()
M.add_star(rho=0.0073,ld1=0.5,ld2=0.4)
M.add_planet(T0=T0,period=period,
impact=impact,rprs=rprs)
M.add_data(time=time)
resid = flux - M.transitmodel
kernel = noiseA * ExpSquaredKernel(noiseW)
gp = george.GaussianPro... | division, print_function
import os
import sys
import numpy as np
import matplotlib.pyplot as plt
import george
from george.kernels import ExpSquaredKernel, RBFKernel
from ktransit import LCModel, FitTransit
from scipy import optimize
def ret_opt(params,time,flux,yerr):
| 64 | 64 | 199 | 10 | 53 | mrtommyb/GP_model_Kepler_data | code/section_gp_fit.py | Python | ret_opt | ret_opt | 18 | 33 | 18 | 18 | f72e3719e8b291fae99bdb518d6cccefc0bf1b0f | bigcode/the-stack | train |
8c82180ec94757359a84ef36 | train | function | def ret_sum(params,time,flux,yerr):
(period, T0, rprs, impact,
alb,occ,ell,ecosw, esinw,
noiseA1, noiseW1,
noiseA2, noiseW2 )= params
M = LCModel()
M.add_star(rho=0.0073,ld1=0.5,ld2=0.4)
M.add_planet(T0=T0,period=period,
impact=impact,rprs=rprs,
alb=alb,occ=occ,el... | def ret_sum(params,time,flux,yerr):
| (period, T0, rprs, impact,
alb,occ,ell,ecosw, esinw,
noiseA1, noiseW1,
noiseA2, noiseW2 )= params
M = LCModel()
M.add_star(rho=0.0073,ld1=0.5,ld2=0.4)
M.add_planet(T0=T0,period=period,
impact=impact,rprs=rprs,
alb=alb,occ=occ,ell=ell,
ecosw=ecosw, esinw=es... | like = 0.
for i in np.arange(len(time) // 1000)[0:10]:
section = np.arange(i*1000,i*1000 + 1000)
gp.compute(time[section], yerr[section])
lnlike += gp.lnlikelihood(resid[section])
return -lnlike
def ret_sum(params,time,flux,yerr):
| 83 | 83 | 277 | 10 | 72 | mrtommyb/GP_model_Kepler_data | code/section_gp_fit.py | Python | ret_sum | ret_sum | 54 | 75 | 54 | 54 | 1e21dbccad8df495c254a434800400e1e4ccec4a | bigcode/the-stack | train |
7287cee96bf92cf64ff446e8 | train | class | class XRSTimeSeries(GenericTimeSeries):
"""
GOES XRS Time Series.
Each GOES satellite there are two X-ray Sensors (XRS) which provide solar X ray fluxes
for the wavelength bands of 0.5 to 4 Å (short channel) sand 1 to 8 Å (long channel).
Most recent data is usually available one or two days late.... | class XRSTimeSeries(GenericTimeSeries):
| """
GOES XRS Time Series.
Each GOES satellite there are two X-ray Sensors (XRS) which provide solar X ray fluxes
for the wavelength bands of 0.5 to 4 Å (short channel) sand 1 to 8 Å (long channel).
Most recent data is usually available one or two days late.
Data is available starting on 1981... | """
This module provies GOES XRS `~sunpy.timeseries.TimeSeries` source.
"""
from pathlib import Path
from collections import OrderedDict
import h5netcdf
import matplotlib.dates as mdates
import matplotlib.ticker as mticker
import numpy as np
import packaging.version
from matplotlib import pyplot as plt
from pandas imp... | 188 | 256 | 2,947 | 9 | 179 | akash5100/sunpy | sunpy/timeseries/sources/goes.py | Python | XRSTimeSeries | XRSTimeSeries | 30 | 317 | 30 | 30 | efb239132d699bb056c844b4b535b85608691930 | bigcode/the-stack | train |
e8776dd7143fa746ad6ea016 | train | function | def parse_args():
parser = argparse.ArgumentParser(
description='Convert MMSegmentation models from ONNX to TensorRT')
parser.add_argument('config', help='Config file of the model')
parser.add_argument(
'model_type',
help='what kind of model the config belong to.',
choices=['... | def parse_args():
| parser = argparse.ArgumentParser(
description='Convert MMSegmentation models from ONNX to TensorRT')
parser.add_argument('config', help='Config file of the model')
parser.add_argument(
'model_type',
help='what kind of model the config belong to.',
choices=['inpainting', 'matt... | , 2, 0)
trt_visualize = np.clip(trt_visualize, 0, 1)[:, :, ::-1]
cv2.imshow('ONNXRuntime', onnx_visualize)
cv2.imshow('TensorRT', trt_visualize)
cv2.waitKey()
np.testing.assert_allclose(
onnx_output, trt_output, rtol=1e-03, atol=1e-05)
print(... | 113 | 114 | 381 | 4 | 109 | whplh/mmediting | tools/onnx2tensorrt.py | Python | parse_args | parse_args | 173 | 218 | 173 | 173 | b6980577e70cdca50dbdd19f3cdb01a2abb54726 | bigcode/the-stack | train |
6fd970a7e08f69863c65b801 | train | function | def onnx2tensorrt(onnx_file: str,
trt_file: str,
config: dict,
input_config: dict,
model_type: str,
img_path: str,
fp16: bool = False,
verify: bool = False,
show: bool = False,... | def onnx2tensorrt(onnx_file: str,
trt_file: str,
config: dict,
input_config: dict,
model_type: str,
img_path: str,
fp16: bool = False,
verify: bool = False,
show: bool = False,... | """Convert ONNX model to TensorRT model
Args:
onnx_file (str): the path of the input ONNX file.
trt_file (str): the path to output the TensorRT file.
config (dict): MMCV configuration.
input_config (dict): contains min_shape, max_shape and \
input image path.
... | meta_keys'].remove(key)
# build the data pipeline
test_pipeline = Compose(config.test_pipeline)
# prepare data
if model_type == 'mattor':
raise RuntimeError('Invalid model_type!', model_type)
if model_type == 'restorer':
data = dict(lq_path=img_path)
data = test_pipeline(data)
... | 256 | 256 | 887 | 83 | 172 | whplh/mmediting | tools/onnx2tensorrt.py | Python | onnx2tensorrt | onnx2tensorrt | 83 | 170 | 83 | 93 | 23902803df402b39d97ab47635597ffa9dbfe71c | bigcode/the-stack | train |
608557793a25e35829b57bf9 | train | function | def _prepare_input_img(model_type: str,
img_path: str,
config: dict,
rescale_shape: Optional[Iterable] = None) -> dict:
"""Prepare the input image
Args:
model_type (str): which kind of model config belong to, \
one of ['in... | def _prepare_input_img(model_type: str,
img_path: str,
config: dict,
rescale_shape: Optional[Iterable] = None) -> dict:
| """Prepare the input image
Args:
model_type (str): which kind of model config belong to, \
one of ['inpainting', 'mattor', 'restorer', 'synthesizer'].
img_path (str): image path to show or verify.
config (dict): MMCV config, determined by the inpupt config file.
resc... | Iterable, Optional
import cv2
import mmcv
import numpy as np
import onnxruntime as ort
import torch
from mmcv.ops import get_onnxruntime_op_path
from mmcv.tensorrt import (TRTWraper, is_tensorrt_plugin_loaded, onnx2trt,
save_trt_engine)
from mmedit.datasets.pipelines import Compose
def g... | 146 | 146 | 489 | 36 | 110 | whplh/mmediting | tools/onnx2tensorrt.py | Python | _prepare_input_img | _prepare_input_img | 24 | 80 | 24 | 27 | b4ecf5297cd73cd48c754b9bcae2f2ebe9326ac3 | bigcode/the-stack | train |
16a7b3077400c0ea697f8990 | train | function | def get_GiB(x: int):
"""return x GiB."""
return x * (1 << 30)
| def get_GiB(x: int):
| """return x GiB."""
return x * (1 << 30)
| cv.ops import get_onnxruntime_op_path
from mmcv.tensorrt import (TRTWraper, is_tensorrt_plugin_loaded, onnx2trt,
save_trt_engine)
from mmedit.datasets.pipelines import Compose
def get_GiB(x: int):
| 64 | 64 | 26 | 9 | 54 | whplh/mmediting | tools/onnx2tensorrt.py | Python | get_GiB | get_GiB | 19 | 21 | 19 | 19 | 3f13833376295dd72c07a31465484e4d7d59d82a | bigcode/the-stack | train |
29986ad75c94f7ebdfcf40f4 | train | class | class CreateSecurityGroupRuleRequest:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensi... | class CreateSecurityGroupRuleRequest:
| """
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
openapi_types = {
... | # coding: utf-8
import pprint
import re
import six
class CreateSecurityGroupRuleRequest:
| 23 | 171 | 572 | 7 | 15 | wuchen-huawei/huaweicloud-sdk-python-v3 | huaweicloud-sdk-vpc/huaweicloudsdkvpc/v3/model/create_security_group_rule_request.py | Python | CreateSecurityGroupRuleRequest | CreateSecurityGroupRuleRequest | 12 | 108 | 12 | 14 | 275c7d13a711f6160636942ec6b497ce26756513 | bigcode/the-stack | train |
b4cb219493ceadf046bf3c19 | train | class | class WorkerRushBot(sc2.BotAI):
async def on_step(self, iteration):
if iteration == 0:
for worker in self.workers:
self.do(worker.attack(self.enemy_start_locations[0]))
| class WorkerRushBot(sc2.BotAI):
| async def on_step(self, iteration):
if iteration == 0:
for worker in self.workers:
self.do(worker.attack(self.enemy_start_locations[0]))
| import sc2
from sc2 import run_game, maps, Race, Difficulty
from sc2.player import Bot, Computer
class WorkerRushBot(sc2.BotAI):
| 35 | 64 | 45 | 9 | 25 | tweakimp/python-sc2 | examples/worker_rush.py | Python | WorkerRushBot | WorkerRushBot | 5 | 9 | 5 | 5 | 2c7dca81303719c46fc7f5632ae354dfe9d2d9f7 | bigcode/the-stack | train |
9765226ec32fc1f3c0fde3c0 | train | function | def main():
run_game(maps.get("Abyssal Reef LE"), [
Bot(Race.Zerg, WorkerRushBot()),
Computer(Race.Protoss, Difficulty.Medium)
], realtime=True)
| def main():
| run_game(maps.get("Abyssal Reef LE"), [
Bot(Race.Zerg, WorkerRushBot()),
Computer(Race.Protoss, Difficulty.Medium)
], realtime=True)
| , maps, Race, Difficulty
from sc2.player import Bot, Computer
class WorkerRushBot(sc2.BotAI):
async def on_step(self, iteration):
if iteration == 0:
for worker in self.workers:
self.do(worker.attack(self.enemy_start_locations[0]))
def main():
| 64 | 64 | 46 | 3 | 61 | tweakimp/python-sc2 | examples/worker_rush.py | Python | main | main | 11 | 15 | 11 | 11 | 5fb28ad01e56c4e4cd7213c5bc7c5824cf2817e2 | bigcode/the-stack | train |
2b223cba71509cfe4b94e040 | train | function | def _rename_basic_resnet_weights(layer_keys):
layer_keys = [k.replace("_", ".") for k in layer_keys]
layer_keys = [k.replace(".w", ".weight") for k in layer_keys]
layer_keys = [k.replace(".bn", "_bn") for k in layer_keys]
layer_keys = [k.replace(".b", ".bias") for k in layer_keys]
layer_keys = [k.re... | def _rename_basic_resnet_weights(layer_keys):
| layer_keys = [k.replace("_", ".") for k in layer_keys]
layer_keys = [k.replace(".w", ".weight") for k in layer_keys]
layer_keys = [k.replace(".bn", "_bn") for k in layer_keys]
layer_keys = [k.replace(".b", ".bias") for k in layer_keys]
layer_keys = [k.replace("_bn.s", "_bn.scale") for k in layer_key... | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import logging
import pickle
from collections import OrderedDict
import torch
from mega_core.utils.model_serialization import load_state_dict
from mega_core.utils.registry import Registry
def _rename_basic_resnet_weights(layer_keys):
| 62 | 253 | 845 | 10 | 51 | hanranCode/mega.pytorch | mega_core/utils/c2_model_loading.py | Python | _rename_basic_resnet_weights | _rename_basic_resnet_weights | 12 | 62 | 12 | 12 | 91e412fa33e021e8b2247169cb0170bb028e784e | bigcode/the-stack | train |
4fbd36711138ee06d8c04c44 | train | function | @C2_FORMAT_LOADER.register("R-50-C4")
@C2_FORMAT_LOADER.register("R-50-C5")
@C2_FORMAT_LOADER.register("R-101-C4")
@C2_FORMAT_LOADER.register("R-101-C5")
@C2_FORMAT_LOADER.register("R-50-FPN")
@C2_FORMAT_LOADER.register("R-50-FPN-RETINANET")
@C2_FORMAT_LOADER.register("R-101-FPN")
@C2_FORMAT_LOADER.register("R-101-FPN-... | @C2_FORMAT_LOADER.register("R-50-C4")
@C2_FORMAT_LOADER.register("R-50-C5")
@C2_FORMAT_LOADER.register("R-101-C4")
@C2_FORMAT_LOADER.register("R-101-C5")
@C2_FORMAT_LOADER.register("R-50-FPN")
@C2_FORMAT_LOADER.register("R-50-FPN-RETINANET")
@C2_FORMAT_LOADER.register("R-101-FPN")
@C2_FORMAT_LOADER.register("R-101-FPN-... | state_dict = _load_c2_pickled_weights(f)
conv_body = cfg.MODEL.BACKBONE.CONV_BODY
arch = conv_body.replace("-C4", "").replace("-C5", "").replace("-FPN", "")
arch = arch.replace("-RETINANET", "")
stages = _C2_STAGE_NAMES[arch]
state_dict = _rename_weights_for_resnet(state_dict, stages)
# ****... | @C2_FORMAT_LOADER.register("R-50-C4")
@C2_FORMAT_LOADER.register("R-50-C5")
@C2_FORMAT_LOADER.register("R-101-C4")
@C2_FORMAT_LOADER.register("R-101-C5")
@C2_FORMAT_LOADER.register("R-50-FPN")
@C2_FORMAT_LOADER.register("R-50-FPN-RETINANET")
@C2_FORMAT_LOADER.register("R-101-FPN")
@C2_FORMAT_LOADER.register("R-101-FPN-... | 147 | 84 | 280 | 147 | 0 | hanranCode/mega.pytorch | mega_core/utils/c2_model_loading.py | Python | load_resnet_c2_format | load_resnet_c2_format | 182 | 202 | 182 | 191 | 65f87fbf22b14e46074d581afb587a7528ffea8e | bigcode/the-stack | train |
c4dcf635952892e3252bda39 | train | function | def load_c2_format(cfg, f):
return C2_FORMAT_LOADER[cfg.MODEL.BACKBONE.CONV_BODY](cfg, f)
| def load_c2_format(cfg, f):
| return C2_FORMAT_LOADER[cfg.MODEL.BACKBONE.CONV_BODY](cfg, f)
| _rename_weights_for_resnet(state_dict, stages)
# ***********************************
# for deformable convolutional layer
state_dict = _rename_conv_weights_for_deformable_conv_layers(state_dict, cfg)
# ***********************************
return dict(model=state_dict)
def load_c2_format(cfg, f):
| 64 | 64 | 32 | 9 | 55 | hanranCode/mega.pytorch | mega_core/utils/c2_model_loading.py | Python | load_c2_format | load_c2_format | 205 | 206 | 205 | 205 | 5c9ba939dda7b9d96fba2e81d1005d47d6f2836e | bigcode/the-stack | train |
793a988c5788e7e3936ff67d | train | function | def _rename_fpn_weights(layer_keys, stage_names):
for mapped_idx, stage_name in enumerate(stage_names, 1):
suffix = ""
if mapped_idx < 4:
suffix = ".lateral"
layer_keys = [
k.replace("fpn.inner.layer{}.sum{}".format(stage_name, suffix), "fpn_inner{}".format(mapped_idx... | def _rename_fpn_weights(layer_keys, stage_names):
| for mapped_idx, stage_name in enumerate(stage_names, 1):
suffix = ""
if mapped_idx < 4:
suffix = ".lateral"
layer_keys = [
k.replace("fpn.inner.layer{}.sum{}".format(stage_name, suffix), "fpn_inner{}".format(mapped_idx)) for k in layer_keys
]
layer_key... | ", "downsample.1.weight") \
for k in layer_keys]
layer_keys = [k.replace("downsample.0.gn.bias", "downsample.1.bias") \
for k in layer_keys]
return layer_keys
def _rename_fpn_weights(layer_keys, stage_names):
| 64 | 64 | 210 | 12 | 51 | hanranCode/mega.pytorch | mega_core/utils/c2_model_loading.py | Python | _rename_fpn_weights | _rename_fpn_weights | 64 | 81 | 64 | 64 | 3c361a7ec8f575c3d37cc2383ece0efd4a567e8c | bigcode/the-stack | train |
3ab571e5611811051c8416b0 | train | function | def _load_c2_pickled_weights(file_path):
with open(file_path, "rb") as f:
if torch._six.PY3:
data = pickle.load(f, encoding="latin1")
else:
data = pickle.load(f)
if "blobs" in data:
weights = data["blobs"]
else:
weights = data
return weights
| def _load_c2_pickled_weights(file_path):
| with open(file_path, "rb") as f:
if torch._six.PY3:
data = pickle.load(f, encoding="latin1")
else:
data = pickle.load(f)
if "blobs" in data:
weights = data["blobs"]
else:
weights = data
return weights
| -1, 1, 1)
logger.info("C2 name: {: <{}} mapped name: {}".format(k, max_c2_key_size, key_map[k]))
new_weights[key_map[k]] = w
return new_weights
def _load_c2_pickled_weights(file_path):
| 64 | 64 | 83 | 11 | 52 | hanranCode/mega.pytorch | mega_core/utils/c2_model_loading.py | Python | _load_c2_pickled_weights | _load_c2_pickled_weights | 133 | 143 | 133 | 133 | 9311566afb07ef763c68a69e0fc412ebfd692187 | bigcode/the-stack | train |
a302202935979394988c0106 | train | function | def _rename_weights_for_resnet(weights, stage_names):
original_keys = sorted(weights.keys())
layer_keys = sorted(weights.keys())
# for X-101, rename output to fc1000 to avoid conflicts afterwards
layer_keys = [k if k != "pred_b" else "fc1000_b" for k in layer_keys]
layer_keys = [k if k != "pred_w" ... | def _rename_weights_for_resnet(weights, stage_names):
| original_keys = sorted(weights.keys())
layer_keys = sorted(weights.keys())
# for X-101, rename output to fc1000 to avoid conflicts afterwards
layer_keys = [k if k != "pred_b" else "fc1000_b" for k in layer_keys]
layer_keys = [k if k != "pred_w" else "fc1000_w" for k in layer_keys]
# performs b... | (stage_name, suffix), "fpn_inner{}".format(mapped_idx)) for k in layer_keys
]
layer_keys = [k.replace("fpn.layer{}.sum".format(stage_name), "fpn_layer{}".format(mapped_idx)) for k in layer_keys]
layer_keys = [k.replace("rpn.conv.fpn2", "rpn.conv") for k in layer_keys]
layer_keys = [k.replace("... | 159 | 159 | 530 | 12 | 146 | hanranCode/mega.pytorch | mega_core/utils/c2_model_loading.py | Python | _rename_weights_for_resnet | _rename_weights_for_resnet | 84 | 130 | 84 | 84 | 3d81b7d04e7dbafab7faeb7f05421bcba2a742bd | bigcode/the-stack | train |
572cdf0967e2dc4b5ee745f5 | train | function | def _rename_conv_weights_for_deformable_conv_layers(state_dict, cfg):
import re
logger = logging.getLogger(__name__)
logger.info("Remapping conv weights for deformable conv weights")
layer_keys = sorted(state_dict.keys())
for ix, stage_with_dcn in enumerate(cfg.MODEL.RESNETS.STAGE_WITH_DCN, 1):
... | def _rename_conv_weights_for_deformable_conv_layers(state_dict, cfg):
| import re
logger = logging.getLogger(__name__)
logger.info("Remapping conv weights for deformable conv weights")
layer_keys = sorted(state_dict.keys())
for ix, stage_with_dcn in enumerate(cfg.MODEL.RESNETS.STAGE_WITH_DCN, 1):
if not stage_with_dcn:
continue
for old_key in... | Y3:
data = pickle.load(f, encoding="latin1")
else:
data = pickle.load(f)
if "blobs" in data:
weights = data["blobs"]
else:
weights = data
return weights
def _rename_conv_weights_for_deformable_conv_layers(state_dict, cfg):
| 70 | 70 | 236 | 16 | 53 | hanranCode/mega.pytorch | mega_core/utils/c2_model_loading.py | Python | _rename_conv_weights_for_deformable_conv_layers | _rename_conv_weights_for_deformable_conv_layers | 146 | 170 | 146 | 146 | 01d7c12ed07b2e5a4de02a6d55858a0b7097edb0 | bigcode/the-stack | train |
c81a903914e809bcd8f27971 | train | function | def get_outer_set(list_train_filename,list_valid_filename,list_test_filename,no_outer):
list_train,list_valid,list_test,list_outer_valid,list_outer_test=[],[],[],[],[]
outer_subjects=[]
while(len(outer_subjects)<no_outer):
file_name=random.choice(list_test_filename)
subject_name=file_name.sp... | def get_outer_set(list_train_filename,list_valid_filename,list_test_filename,no_outer):
| list_train,list_valid,list_test,list_outer_valid,list_outer_test=[],[],[],[],[]
outer_subjects=[]
while(len(outer_subjects)<no_outer):
file_name=random.choice(list_test_filename)
subject_name=file_name.split("/")[2].split("_")[0]
if subject_name not in outer_subjects:
out... | :
list_valid_filename.append(filename)
continue
''' Add to test set '''
count=0
for test_instance in list_test_filename:
if subject_name in test_instance:
count+=1
if count<5:
list_test_filename.append(filename)
... | 96 | 96 | 321 | 16 | 79 | manhhabui/personalized-breath | src/utils/process_dataset.py | Python | get_outer_set | get_outer_set | 32 | 67 | 32 | 32 | 880f9897ddb56fea1ce0174287d4b987c1efb46d | bigcode/the-stack | train |
f75ad2328fd5853d282d0b07 | train | function | def split_train_valid_test_set(list_filename):
random.shuffle(list_filename)
list_test_filename=[]
list_valid_filename=[]
list_train_filename=[]
for filename in list_filename:
subject_name=filename.split("/")[2]
''' Add to valid set '''
count=0
for valid_intance in li... | def split_train_valid_test_set(list_filename):
| random.shuffle(list_filename)
list_test_filename=[]
list_valid_filename=[]
list_train_filename=[]
for filename in list_filename:
subject_name=filename.split("/")[2]
''' Add to valid set '''
count=0
for valid_intance in list_valid_filename:
if subject_name ... | import random
def split_train_valid_test_set(list_filename):
| 12 | 64 | 168 | 9 | 2 | manhhabui/personalized-breath | src/utils/process_dataset.py | Python | split_train_valid_test_set | split_train_valid_test_set | 3 | 30 | 3 | 3 | aade4c0afd53318bff7dbd795e98e432b7fdbc14 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.