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
3c1cb45bd08506dc66e4806a
train
function
def test_signature_from_ast(): signature = 'def func(a, b, *args, c=0, d="blah", **kwargs): pass' tree = ast.parse(signature) sig = inspect.signature_from_ast(tree.body[0]) assert list(sig.parameters.keys()) == ['a', 'b', 'args', 'c', 'd', 'kwargs'] assert sig.parameters['a'].name == 'a' assert ...
def test_signature_from_ast():
signature = 'def func(a, b, *args, c=0, d="blah", **kwargs): pass' tree = ast.parse(signature) sig = inspect.signature_from_ast(tree.body[0]) assert list(sig.parameters.keys()) == ['a', 'b', 'args', 'c', 'd', 'kwargs'] assert sig.parameters['a'].name == 'a' assert sig.parameters['a'].kind == Par...
', 'b', 'c'] assert sig.parameters['a'].kind == Parameter.POSITIONAL_ONLY assert sig.parameters['a'].default == Parameter.empty assert sig.parameters['b'].kind == Parameter.POSITIONAL_ONLY assert sig.parameters['b'].default == '0' assert sig.parameters['c'].kind == Parameter.POSITIONAL_OR_KEYWORD ...
117
118
394
6
112
rdt12/sphinx
tests/test_util_inspect.py
Python
test_signature_from_ast
test_signature_from_ast
384
413
384
384
941d81092316ceaf1523d548a02822243504bd13
bigcode/the-stack
train
39c6146cbb2b5d8f31a7c59b
train
function
@pytest.mark.sphinx(testroot='ext-autodoc') def test_isstaticmethod(app): from target.methods import Base, Inherited assert inspect.isstaticmethod(Base.staticmeth, Base, 'staticmeth') is True assert inspect.isstaticmethod(Base.meth, Base, 'meth') is False assert inspect.isstaticmethod(Inherited.staticm...
@pytest.mark.sphinx(testroot='ext-autodoc') def test_isstaticmethod(app):
from target.methods import Base, Inherited assert inspect.isstaticmethod(Base.staticmeth, Base, 'staticmeth') is True assert inspect.isstaticmethod(Base.meth, Base, 'meth') is False assert inspect.isstaticmethod(Inherited.staticmeth, Inherited, 'staticmeth') is True assert inspect.isstaticmethod(In...
classmethod(Base.classmeth) is True assert inspect.isclassmethod(Base.meth) is False assert inspect.isclassmethod(Inherited.classmeth) is True assert inspect.isclassmethod(Inherited.meth) is False @pytest.mark.sphinx(testroot='ext-autodoc') def test_isstaticmethod(app):
64
64
102
18
45
rdt12/sphinx
tests/test_util_inspect.py
Python
test_isstaticmethod
test_isstaticmethod
551
558
551
552
98ca6d349bbb152bf99e5bd2314841f3470c5f13
bigcode/the-stack
train
bf242034280037e6322fce70
train
function
def test_dict_customtype(): class CustomType: def __init__(self, value): self._value = value def __repr__(self): return "<CustomType(%r)>" % self._value dictionary = {CustomType(2): 2, CustomType(1): 1} description = inspect.object_description(dictionary) # Type...
def test_dict_customtype():
class CustomType: def __init__(self, value): self._value = value def __repr__(self): return "<CustomType(%r)>" % self._value dictionary = {CustomType(2): 2, CustomType(1): 1} description = inspect.object_description(dictionary) # Type is unsortable, just check t...
zenset_sorting_fallback(): frozenset_ = frozenset((None, 1)) description = inspect.object_description(frozenset_) assert description in ("frozenset({1, None})", "frozenset({None, 1})") def test_dict_customtype():
64
64
107
6
58
rdt12/sphinx
tests/test_util_inspect.py
Python
test_dict_customtype
test_dict_customtype
505
516
505
505
603adbff04af9ea410ac1c1fb4f16295887b2117
bigcode/the-stack
train
7a8f55f5f5b49d60763626dc
train
function
def test_frozenset_sorting(): frozenset_ = frozenset("gfedcba") description = inspect.object_description(frozenset_) assert description == "frozenset({'a', 'b', 'c', 'd', 'e', 'f', 'g'})"
def test_frozenset_sorting():
frozenset_ = frozenset("gfedcba") description = inspect.object_description(frozenset_) assert description == "frozenset({'a', 'b', 'c', 'd', 'e', 'f', 'g'})"
d', 'e', 'f', 'g'}" def test_set_sorting_fallback(): set_ = {None, 1} description = inspect.object_description(set_) assert description in ("{1, None}", "{None, 1}") def test_frozenset_sorting():
63
64
65
9
54
rdt12/sphinx
tests/test_util_inspect.py
Python
test_frozenset_sorting
test_frozenset_sorting
493
496
493
493
a0cbb668e9e49b48c3852ba3e11baee61c6fa4e0
bigcode/the-stack
train
5429dacfb7ca42278c2b8cb5
train
function
@pytest.mark.skipif(sys.version_info < (3, 8), reason='python-3.8 or above is required') def test_signature_from_str_positionaly_only_args(): sig = inspect.signature_from_str('(a, b=0, /, c=1)') assert list(sig.parameters.keys()) == ['a', 'b', 'c'] assert sig.parameters['a'].kind == Para...
@pytest.mark.skipif(sys.version_info < (3, 8), reason='python-3.8 or above is required') def test_signature_from_str_positionaly_only_args():
sig = inspect.signature_from_str('(a, b=0, /, c=1)') assert list(sig.parameters.keys()) == ['a', 'b', 'c'] assert sig.parameters['a'].kind == Parameter.POSITIONAL_ONLY assert sig.parameters['a'].default == Parameter.empty assert sig.parameters['b'].kind == Parameter.POSITIONAL_ONLY assert sig.pa...
assert sig.parameters['b'].kind == Parameter.KEYWORD_ONLY assert sig.parameters['b'].default == Parameter.empty @pytest.mark.skipif(sys.version_info < (3, 8), reason='python-3.8 or above is required') def test_signature_from_str_positionaly_only_args():
64
64
158
38
25
rdt12/sphinx
tests/test_util_inspect.py
Python
test_signature_from_str_positionaly_only_args
test_signature_from_str_positionaly_only_args
366
376
366
368
c23c0935c81774c5fa1b8d62d154ce5a19319516
bigcode/the-stack
train
b759b1b5256ac413d0a5cab3
train
function
def test_safe_getattr_with_property_exception(): class Foo: @property def bar(self): raise Exception obj = Foo() try: inspect.safe_getattr(obj, 'bar') except AttributeError as exc: assert exc.args[0] == 'bar' else: pytest.fail('AttributeError not...
def test_safe_getattr_with_property_exception():
class Foo: @property def bar(self): raise Exception obj = Foo() try: inspect.safe_getattr(obj, 'bar') except AttributeError as exc: assert exc.args[0] == 'bar' else: pytest.fail('AttributeError not raised')
, item): raise Exception obj = Foo() try: inspect.safe_getattr(obj, 'bar') except AttributeError as exc: assert exc.args[0] == 'bar' else: pytest.fail('AttributeError not raised') def test_safe_getattr_with_property_exception():
64
64
74
9
55
rdt12/sphinx
tests/test_util_inspect.py
Python
test_safe_getattr_with_property_exception
test_safe_getattr_with_property_exception
443
456
443
443
c787ee0a3ed29b847ef7d9e468a27cf858b5d0ca
bigcode/the-stack
train
e3fd0f0fceb7b58482c2413e
train
function
@pytest.mark.sphinx(testroot='ext-autodoc') def test_isclassmethod(app): from target.methods import Base, Inherited assert inspect.isclassmethod(Base.classmeth) is True assert inspect.isclassmethod(Base.meth) is False assert inspect.isclassmethod(Inherited.classmeth) is True assert inspect.isclassm...
@pytest.mark.sphinx(testroot='ext-autodoc') def test_isclassmethod(app):
from target.methods import Base, Inherited assert inspect.isclassmethod(Base.classmeth) is True assert inspect.isclassmethod(Base.meth) is False assert inspect.isclassmethod(Inherited.classmeth) is True assert inspect.isclassmethod(Inherited.meth) is False
None} assert inspect.getslots(Baz) == {'attr': 'docstring'} assert inspect.getslots(Qux) == {'attr': None} with pytest.raises(TypeError): inspect.getslots(Bar()) @pytest.mark.sphinx(testroot='ext-autodoc') def test_isclassmethod(app):
64
64
78
18
46
rdt12/sphinx
tests/test_util_inspect.py
Python
test_isclassmethod
test_isclassmethod
541
548
541
542
d3ecbbddc01c23eb980977af351205bd5ff2a894
bigcode/the-stack
train
e39554fbc175a5f569b53630
train
function
def test_set_sorting(): set_ = set("gfedcba") description = inspect.object_description(set_) assert description == "{'a', 'b', 'c', 'd', 'e', 'f', 'g'}"
def test_set_sorting():
set_ = set("gfedcba") description = inspect.object_description(set_) assert description == "{'a', 'b', 'c', 'd', 'e', 'f', 'g'}"
3, "a": 1, "d": 2, "b": 4} description = inspect.object_description(dictionary) assert description == "{'a': 1, 'b': 4, 'c': 3, 'd': 2}" def test_set_sorting():
63
64
52
6
57
rdt12/sphinx
tests/test_util_inspect.py
Python
test_set_sorting
test_set_sorting
481
484
481
481
5023d4401cf236d59916ad88438f65938ff4459e
bigcode/the-stack
train
f9163ffaf40c476881e1a016
train
function
def test_TypeAliasNamespace(): import logging.config type_alias = TypeAliasNamespace({'logging.Filter': 'MyFilter', 'logging.Handler': 'MyHandler', 'logging.handlers.SyslogHandler': 'MySyslogHandler'}) assert type_alias['logging'].Fi...
def test_TypeAliasNamespace():
import logging.config type_alias = TypeAliasNamespace({'logging.Filter': 'MyFilter', 'logging.Handler': 'MyHandler', 'logging.handlers.SyslogHandler': 'MySyslogHandler'}) assert type_alias['logging'].Filter == 'MyFilter' assert t...
: BSD, see LICENSE for details. """ import ast import datetime import functools import sys import types from inspect import Parameter import _testcapi import pytest from sphinx.util import inspect from sphinx.util.inspect import TypeAliasNamespace, stringify_signature def test_TypeAliasNamespace():
64
64
146
6
57
rdt12/sphinx
tests/test_util_inspect.py
Python
test_TypeAliasNamespace
test_TypeAliasNamespace
25
41
25
25
2c8862af124a9569a11261c20c2707365939c5ae
bigcode/the-stack
train
d1c9980b6100e5bb658dda00
train
function
def test_signature_from_str_annotations(): signature = '(a: int, *args: bytes, b: str = "blah", **kwargs: float) -> None' sig = inspect.signature_from_str(signature) assert list(sig.parameters.keys()) == ['a', 'args', 'b', 'kwargs'] assert sig.parameters['a'].annotation == "int" assert sig.parameter...
def test_signature_from_str_annotations():
signature = '(a: int, *args: bytes, b: str = "blah", **kwargs: float) -> None' sig = inspect.signature_from_str(signature) assert list(sig.parameters.keys()) == ['a', 'args', 'b', 'kwargs'] assert sig.parameters['a'].annotation == "int" assert sig.parameters['args'].annotation == "bytes" assert ...
assert sig.parameters['j'].default == 'lambda x, y: ...' assert sig.parameters['k'].default == 'None' assert sig.parameters['l'].default == 'object()' assert sig.parameters['m'].default == 'foo.bar.CONSTANT' def test_signature_from_str_annotations():
64
64
121
7
57
rdt12/sphinx
tests/test_util_inspect.py
Python
test_signature_from_str_annotations
test_signature_from_str_annotations
338
346
338
338
9d11df189194102b9e5888c194353bba319cf977
bigcode/the-stack
train
8c2a65a557d1961f35da0c69
train
function
def test_safe_getattr_with_exception(): class Foo: def __getattr__(self, item): raise Exception obj = Foo() try: inspect.safe_getattr(obj, 'bar') except AttributeError as exc: assert exc.args[0] == 'bar' else: pytest.fail('AttributeError not raised')
def test_safe_getattr_with_exception():
class Foo: def __getattr__(self, item): raise Exception obj = Foo() try: inspect.safe_getattr(obj, 'bar') except AttributeError as exc: assert exc.args[0] == 'bar' else: pytest.fail('AttributeError not raised')
Parameter.empty def test_safe_getattr_with_default(): class Foo: def __getattr__(self, item): raise Exception obj = Foo() result = inspect.safe_getattr(obj, 'bar', 'baz') assert result == 'baz' def test_safe_getattr_with_exception():
64
64
74
8
56
rdt12/sphinx
tests/test_util_inspect.py
Python
test_safe_getattr_with_exception
test_safe_getattr_with_exception
428
440
428
428
6c780df6a078d84b2f047da90bb1f870f9c73f5a
bigcode/the-stack
train
3fc910ebddb8d75ff23c9c58
train
function
def test_getslots(): class Foo: pass class Bar: __slots__ = ['attr'] class Baz: __slots__ = {'attr': 'docstring'} class Qux: __slots__ = 'attr' assert inspect.getslots(Foo) is None assert inspect.getslots(Bar) == {'attr': None} assert inspect.getslots(Baz)...
def test_getslots():
class Foo: pass class Bar: __slots__ = ['attr'] class Baz: __slots__ = {'attr': 'docstring'} class Qux: __slots__ = 'attr' assert inspect.getslots(Foo) is None assert inspect.getslots(Bar) == {'attr': None} assert inspect.getslots(Baz) == {'attr': 'docstri...
dictionary = {CustomType(2): 2, CustomType(1): 1} description = inspect.object_description(dictionary) # Type is unsortable, just check that it does not crash assert "<CustomType(2)>: 2" in description def test_getslots():
64
64
122
5
58
rdt12/sphinx
tests/test_util_inspect.py
Python
test_getslots
test_getslots
519
538
519
519
f98e75d8483192822a0c6b324e447b3826986d53
bigcode/the-stack
train
ffa8b9a60f10b0d7885cd59e
train
function
def test_safe_getattr_with___dict___override(): class Foo: @property def __dict__(self): raise Exception obj = Foo() try: inspect.safe_getattr(obj, 'bar') except AttributeError as exc: assert exc.args[0] == 'bar' else: pytest.fail('AttributeError...
def test_safe_getattr_with___dict___override():
class Foo: @property def __dict__(self): raise Exception obj = Foo() try: inspect.safe_getattr(obj, 'bar') except AttributeError as exc: assert exc.args[0] == 'bar' else: pytest.fail('AttributeError not raised')
): raise Exception obj = Foo() try: inspect.safe_getattr(obj, 'bar') except AttributeError as exc: assert exc.args[0] == 'bar' else: pytest.fail('AttributeError not raised') def test_safe_getattr_with___dict___override():
64
64
78
11
53
rdt12/sphinx
tests/test_util_inspect.py
Python
test_safe_getattr_with___dict___override
test_safe_getattr_with___dict___override
459
472
459
459
a7384949a2eceba59965eade3f7fc6bc57174d13
bigcode/the-stack
train
2287f58b4f3e3381bb8a3d71
train
function
def test_safe_getattr_with_default(): class Foo: def __getattr__(self, item): raise Exception obj = Foo() result = inspect.safe_getattr(obj, 'bar', 'baz') assert result == 'baz'
def test_safe_getattr_with_default():
class Foo: def __getattr__(self, item): raise Exception obj = Foo() result = inspect.safe_getattr(obj, 'bar', 'baz') assert result == 'baz'
['kwargs'].name == 'kwargs' assert sig.parameters['kwargs'].kind == Parameter.VAR_KEYWORD assert sig.parameters['kwargs'].default == Parameter.empty assert sig.parameters['kwargs'].annotation == Parameter.empty assert sig.return_annotation == Parameter.empty def test_safe_getattr_with_default():
64
64
53
8
55
rdt12/sphinx
tests/test_util_inspect.py
Python
test_safe_getattr_with_default
test_safe_getattr_with_default
416
425
416
416
99320633f23ee3e06c4e9a57945419993bee5dbc
bigcode/the-stack
train
c9d19c50c9d636321abf0049
train
class
class GrapheneUnshardedMeshSource(UnshardedLegacyPrecomputedMeshSource): def compute_filename(self, label): layer_id = self.meta.meta.decode_layer_id(label) chunk_block_shape = Vec(*self.meta.meta.mesh_chunk_size, dtype=np.int64) chunk_block_shape *= np.int64(self.meta.meta.fan_out ** max(0, layer_id - 2...
class GrapheneUnshardedMeshSource(UnshardedLegacyPrecomputedMeshSource):
def compute_filename(self, label): layer_id = self.meta.meta.decode_layer_id(label) chunk_block_shape = Vec(*self.meta.meta.mesh_chunk_size, dtype=np.int64) chunk_block_shape *= np.int64(self.meta.meta.fan_out ** max(0, layer_id - 2)) start = self.meta.meta.decode_chunk_position(label) start *= ch...
import six from collections import defaultdict import itertools import json import os import posixpath import re import requests import numpy as np from tqdm import tqdm from cloudfiles import CloudFiles from ....lib import red, toiter, Bbox, Vec, jsonify from ....mesh import Mesh from .... import paths from ....sc...
116
256
1,839
17
98
SridharJagannathan/cloud-volume
cloudvolume/datasource/graphene/mesh/unsharded.py
Python
GrapheneUnshardedMeshSource
GrapheneUnshardedMeshSource
24
232
24
25
4e7b0131905f3a8217ab27f486c09de95f30cd3a
bigcode/the-stack
train
ad40bd1aa5b43ab84376f95c
train
class
class InterfaceConfig(EntityWithNameModel): ACTIVE = 0 DISABLE = 1 num = db.Column(db.Integer(), nullable=True, comment='配置序号') name = db.Column(db.String(128), comment='配置名称') variables = db.Column(db.String(21000), comment='配置参数') func_address = db.Column(db.String(128), comment='配置函数') p...
class InterfaceConfig(EntityWithNameModel):
ACTIVE = 0 DISABLE = 1 num = db.Column(db.Integer(), nullable=True, comment='配置序号') name = db.Column(db.String(128), comment='配置名称') variables = db.Column(db.String(21000), comment='配置参数') func_address = db.Column(db.String(128), comment='配置函数') project_id = db.Column(db.Integer, comment='所...
from library.api.db import EntityWithNameModel, db class InterfaceConfig(EntityWithNameModel):
20
64
118
8
11
rainydaygit/testtcloudserver
apps/interface/models/interfaceconfig.py
Python
InterfaceConfig
InterfaceConfig
4
13
4
4
32b06e20bb917559f24bb32cf82c115a5df7cec7
bigcode/the-stack
train
285320df1bddb44684809a2b
train
function
@app.route("/get_google_api_code", methods=["GET"]) def route_get_google_api_code(): return jsonify({"google_api_code": os.environ["GOOGLE_API_CODE"]})
@app.route("/get_google_api_code", methods=["GET"]) def route_get_google_api_code():
return jsonify({"google_api_code": os.environ["GOOGLE_API_CODE"]})
"]) def route_delete_itinerary_from_user(): itinerary_id = request.form["itinerary_id"] user_id = request.form["user_id"] return jsonify(database.delete_itinerary_from_user(user_id, itinerary_id)) @app.route("/get_google_api_code", methods=["GET"]) def route_get_google_api_code():
64
64
36
19
45
jennyxue97/PathfinderBackend
app.py
Python
route_get_google_api_code
route_get_google_api_code
51
53
51
52
4fc5912513efcd08e59cf63405fed9092692ba0c
bigcode/the-stack
train
a071e910278ea8e7e5213f9f
train
function
@app.route("/get_itineraries_from_user", methods=["GET"]) def route_get_itinerary_from_user(): user_id = request.args["user_id"] return jsonify(database.get_itineraries_from_user(user_id))
@app.route("/get_itineraries_from_user", methods=["GET"]) def route_get_itinerary_from_user():
user_id = request.args["user_id"] return jsonify(database.get_itineraries_from_user(user_id))
= request.args.getlist("search_queries[]") location = request.args["location"] days = int(request.args["days"]) return jsonify(yelp.get_businesses(search_queries, location, days)) @app.route("/get_itineraries_from_user", methods=["GET"]) def route_get_itinerary_from_user():
64
64
45
22
42
jennyxue97/PathfinderBackend
app.py
Python
route_get_itinerary_from_user
route_get_itinerary_from_user
17
20
17
18
d737152f18ee995b76f91c603495b685aa3008aa
bigcode/the-stack
train
6239866006a6036057b156d1
train
function
@app.route("/get_businesses", methods=["GET"]) def route_get_businesses(): search_queries = request.args.getlist("search_queries[]") location = request.args["location"] days = int(request.args["days"]) return jsonify(yelp.get_businesses(search_queries, location, days))
@app.route("/get_businesses", methods=["GET"]) def route_get_businesses():
search_queries = request.args.getlist("search_queries[]") location = request.args["location"] days = int(request.args["days"]) return jsonify(yelp.get_businesses(search_queries, location, days))
from flask import Flask, request, jsonify from flask_cors import CORS import yelp, database import json import os app = Flask(__name__) CORS(app) @app.route("/get_businesses", methods=["GET"]) def route_get_businesses():
56
64
62
17
39
jennyxue97/PathfinderBackend
app.py
Python
route_get_businesses
route_get_businesses
10
15
10
11
5a0111b5390df7e70e6ab1e428442d3196cc5422
bigcode/the-stack
train
eca65a1fb8bf9ae25c784a6f
train
function
@app.route("/get_itinerary", methods=["GET"]) def route_get_itinerary(): user_id = request.args["user_id"] itinerary_id = request.args["itinerary_id"] return jsonify(database.get_itinerary(user_id, itinerary_id))
@app.route("/get_itinerary", methods=["GET"]) def route_get_itinerary():
user_id = request.args["user_id"] itinerary_id = request.args["itinerary_id"] return jsonify(database.get_itinerary(user_id, itinerary_id))
days)) @app.route("/get_itineraries_from_user", methods=["GET"]) def route_get_itinerary_from_user(): user_id = request.args["user_id"] return jsonify(database.get_itineraries_from_user(user_id)) @app.route("/get_itinerary", methods=["GET"]) def route_get_itinerary():
64
64
51
17
47
jennyxue97/PathfinderBackend
app.py
Python
route_get_itinerary
route_get_itinerary
22
26
22
23
9f41c47f4a72540815e9dbc4261bf7923f6d7807
bigcode/the-stack
train
98e7b108d6dcf2a44d5b7932
train
function
@app.route("/delete_itinerary_from_user", methods=["POST"]) def route_delete_itinerary_from_user(): itinerary_id = request.form["itinerary_id"] user_id = request.form["user_id"] return jsonify(database.delete_itinerary_from_user(user_id, itinerary_id))
@app.route("/delete_itinerary_from_user", methods=["POST"]) def route_delete_itinerary_from_user():
itinerary_id = request.form["itinerary_id"] user_id = request.form["user_id"] return jsonify(database.delete_itinerary_from_user(user_id, itinerary_id))
["itinerary_name"] user_id = request.form["user_id"] user_name = request.form["user_name"] return jsonify(database.post_itinerary_in_user(user_id, user_name, itinerary_name)) @app.route("/delete_itinerary_from_user", methods=["POST"]) def route_delete_itinerary_from_user():
64
64
57
21
43
jennyxue97/PathfinderBackend
app.py
Python
route_delete_itinerary_from_user
route_delete_itinerary_from_user
45
49
45
46
104336f38ad0433651e6343e11410262f9fd5840
bigcode/the-stack
train
43adcb62c1cb6afdd9fafc88
train
function
@app.route("/post_itinerary", methods=["POST"]) def route_post_itinerary(): itinerary_id = request.form["itinerary_id"] itinerary_name = request.form["itinerary_name"] user_id = request.form["user_id"] user_name = request.form["user_name"] itinerary = json.loads(request.form["itinerary"]) databa...
@app.route("/post_itinerary", methods=["POST"]) def route_post_itinerary():
itinerary_id = request.form["itinerary_id"] itinerary_name = request.form["itinerary_name"] user_id = request.form["user_id"] user_name = request.form["user_name"] itinerary = json.loads(request.form["itinerary"]) database.delete_itinerary(user_id, itinerary_id) return jsonify(database.post_...
inerary", methods=["GET"]) def route_get_itinerary(): user_id = request.args["user_id"] itinerary_id = request.args["itinerary_id"] return jsonify(database.get_itinerary(user_id, itinerary_id)) @app.route("/post_itinerary", methods=["POST"]) def route_post_itinerary():
63
64
102
17
46
jennyxue97/PathfinderBackend
app.py
Python
route_post_itinerary
route_post_itinerary
28
36
28
29
8cfe7070d43508b7574d5669475ca3c14df88b0c
bigcode/the-stack
train
fcd7fbd4d6afc9f189a893e5
train
function
@app.route("/post_itinerary_in_user", methods=["POST"]) def route_post_itinerary_in_user(): itinerary_name = request.form["itinerary_name"] user_id = request.form["user_id"] user_name = request.form["user_name"] return jsonify(database.post_itinerary_in_user(user_id, user_name, itinerary_name))
@app.route("/post_itinerary_in_user", methods=["POST"]) def route_post_itinerary_in_user():
itinerary_name = request.form["itinerary_name"] user_id = request.form["user_id"] user_name = request.form["user_name"] return jsonify(database.post_itinerary_in_user(user_id, user_name, itinerary_name))
itinerary = json.loads(request.form["itinerary"]) database.delete_itinerary(user_id, itinerary_id) return jsonify(database.post_itinerary(user_name, user_id, itinerary_name, itinerary_id, itinerary)) @app.route("/post_itinerary_in_user", methods=["POST"]) def route_post_itinerary_in_user():
64
64
70
21
43
jennyxue97/PathfinderBackend
app.py
Python
route_post_itinerary_in_user
route_post_itinerary_in_user
38
43
38
39
ba45fd9ecbbcd9d05df3f985a9b54838c98f95f6
bigcode/the-stack
train
aa198f38741dd0a889b2dbe5
train
class
class SMMHATestCase(HABaseTestCase): step_class = TakeSnapshotFromMaster @patch('physical.models.DatabaseInfra.get_driver') @patch('backup.tasks.make_instance_snapshot_backup') @patch('backup.tasks.BackupGroup') def test_volume_attr(self, backup_group_mock, make_snapshot_mock, ...
class SMMHATestCase(HABaseTestCase):
step_class = TakeSnapshotFromMaster @patch('physical.models.DatabaseInfra.get_driver') @patch('backup.tasks.make_instance_snapshot_backup') @patch('backup.tasks.BackupGroup') def test_volume_attr(self, backup_group_mock, make_snapshot_mock, get_driver_mock): get_dri...
.master_instance ) get_driver_mock().get_database_instances.return_value = [ self.master_instance ] make_snapshot_mock.return_value = self.snapshot backup_group_mock.return_value = self.backup_group self.step.do() self.assertEqual( make_sna...
88
88
295
13
75
perry-contribs/database-as-a-service
dbaas/workflow/tests/test_volume_provider_steps/test_take_snapshot_from_master.py
Python
SMMHATestCase
SMMHATestCase
33
71
33
33
5801f894e719c28625a2fdb7fd397162f649f390
bigcode/the-stack
train
24d8d27444416467f9ee8a83
train
class
class SMMSingleInstanceTestCase(SingleInstanceBaseTestCase): step_class = TakeSnapshotFromMaster @patch('physical.models.DatabaseInfra.get_driver') @patch('backup.tasks.make_instance_snapshot_backup') @patch('backup.tasks.BackupGroup') def test_volume_attr(self, backup_group_mock, make_snapshot_moc...
class SMMSingleInstanceTestCase(SingleInstanceBaseTestCase):
step_class = TakeSnapshotFromMaster @patch('physical.models.DatabaseInfra.get_driver') @patch('backup.tasks.make_instance_snapshot_backup') @patch('backup.tasks.BackupGroup') def test_volume_attr(self, backup_group_mock, make_snapshot_mock, get_driver_mock): get_dri...
from mock import patch from workflow.steps.util.volume_provider import ( TakeSnapshotFromMaster, VolumeProviderSnapshotHasWarningStatusError ) from .base import SingleInstanceBaseTestCase, HABaseTestCase class SMMSingleInstanceTestCase(SingleInstanceBaseTestCase):
58
64
164
14
43
perry-contribs/database-as-a-service
dbaas/workflow/tests/test_volume_provider_steps/test_take_snapshot_from_master.py
Python
SMMSingleInstanceTestCase
SMMSingleInstanceTestCase
10
30
10
10
5f6bb592b834ed64df90b10788589d34c16496d9
bigcode/the-stack
train
bd57cf41b700c616a86b2ac0
train
function
@edge_clustered_nodes_for_space.register(PN) def _edge_clustered_nodes_for_pn(space: PN, shape: Simplex): if not isinstance(shape, Simplex): raise NotImplementedError((type(space).__name__, type(shape).__name__)) if space.spatial_dim != shape.dim: raise ValueError("spatial dimensions of shape an...
@edge_clustered_nodes_for_space.register(PN) def _edge_clustered_nodes_for_pn(space: PN, shape: Simplex):
if not isinstance(shape, Simplex): raise NotImplementedError((type(space).__name__, type(shape).__name__)) if space.spatial_dim != shape.dim: raise ValueError("spatial dimensions of shape and space must match") if space.spatial_dim <= 3: return warp_and_blend_nodes(space.spatial_dim...
1)) else: return (np.array(node_tuples_for_space(space), dtype=np.float64) / space.order*2 - 1).T @edge_clustered_nodes_for_space.register(PN) def _edge_clustered_nodes_for_pn(space: PN, shape: Simplex):
64
64
121
29
34
inducer/modepy
modepy/nodes.py
Python
_edge_clustered_nodes_for_pn
_edge_clustered_nodes_for_pn
443
453
443
444
84100e7ba9d34070cacdca4895bfcddf75f6e799
bigcode/the-stack
train
262788f97532d49d9d87eeb2
train
function
@node_tuples_for_space.register(QN) def _node_tuples_for_qn(space: QN): from pytools import \ generate_nonnegative_integer_tuples_below as gnitb return tuple([ tp[::-1] for tp in gnitb(space.order + 1, space.spatial_dim) ])
@node_tuples_for_space.register(QN) def _node_tuples_for_qn(space: QN):
from pytools import \ generate_nonnegative_integer_tuples_below as gnitb return tuple([ tp[::-1] for tp in gnitb(space.order + 1, space.spatial_dim) ])
new_nodes] = new_nodes nnodes_obtained += nnew_nodes if nnodes_obtained == nnodes: return result # }}} # {{{ QN @node_tuples_for_space.register(QN) def _node_tuples_for_qn(space: QN):
64
64
71
23
40
inducer/modepy
modepy/nodes.py
Python
_node_tuples_for_qn
_node_tuples_for_qn
478
484
478
479
0c423c4b278a36a34ea1d99d54736214c5be91cf
bigcode/the-stack
train
1db432dd3bad3aa79b113cba
train
function
@node_tuples_for_space.register(PN) def _node_tuples_for_pn(space: PN): from pytools import \ generate_nonnegative_integer_tuples_summing_to_at_most as gnitsam return tuple(gnitsam(space.order, space.spatial_dim))
@node_tuples_for_space.register(PN) def _node_tuples_for_pn(space: PN):
from pytools import \ generate_nonnegative_integer_tuples_summing_to_at_most as gnitsam return tuple(gnitsam(space.order, space.spatial_dim))
numpy.ndarray` of shape `(dim, nnodes)` of random nodes in the reference *shape*. """ raise NotImplementedError(type(shape).__name__) # }}} # {{{ PN @node_tuples_for_space.register(PN) def _node_tuples_for_pn(space: PN):
64
64
61
22
41
inducer/modepy
modepy/nodes.py
Python
_node_tuples_for_pn
_node_tuples_for_pn
420
424
420
421
77c3895846bef3407a360babfd9f700045f5a5c3
bigcode/the-stack
train
29cd0988bbf76dd7b4d42fc0
train
function
def warp_and_blend_nodes_2d(n, node_tuples=None): try: alpha = _alpha_opt_2d[n-1] except IndexError: alpha = 5/3 space = PN(2, n) if node_tuples is None: node_tuples = node_tuples_for_space(space) else: if len(node_tuples) != space.space_dim: raise ValueE...
def warp_and_blend_nodes_2d(n, node_tuples=None):
try: alpha = _alpha_opt_2d[n-1] except IndexError: alpha = 5/3 space = PN(2, n) if node_tuples is None: node_tuples = node_tuples_for_space(space) else: if len(node_tuples) != space.space_dim: raise ValueError("'node_tuples' list does not have the correct...
1.2832, 1.3648, 1.4773, 1.4959, 1.5743, 1.5770, 1.6223, 1.6258] def warp_and_blend_nodes_2d(n, node_tuples=None):
64
64
209
16
48
inducer/modepy
modepy/nodes.py
Python
warp_and_blend_nodes_2d
warp_and_blend_nodes_2d
168
192
168
168
5eff1fe62470d9814b970efa09895642b26b7a76
bigcode/the-stack
train
3a78edb038a94180668b65d1
train
function
@singledispatch def equispaced_nodes_for_space(space: FunctionSpace, shape: Shape) -> np.ndarray: raise NotImplementedError((type(space).__name__, type(shape).__name__))
@singledispatch def equispaced_nodes_for_space(space: FunctionSpace, shape: Shape) -> np.ndarray:
raise NotImplementedError((type(space).__name__, type(shape).__name__))
{{{ space-based interface @singledispatch def node_tuples_for_space(space: FunctionSpace) -> Sequence[Tuple[int]]: raise NotImplementedError(type(space).__name__) @singledispatch def equispaced_nodes_for_space(space: FunctionSpace, shape: Shape) -> np.ndarray:
64
64
42
26
38
inducer/modepy
modepy/nodes.py
Python
equispaced_nodes_for_space
equispaced_nodes_for_space
393
395
393
394
41cdf66a3bff8715fb2f89ecf4a3fdb9010c8734
bigcode/the-stack
train
86a482f061e0a8f4f0cbc6b5
train
function
def warp_and_blend_nodes_3d(n, node_tuples=None): try: alpha = _alpha_opt_3d[n-1] except IndexError: alpha = 1. space = PN(3, n) if node_tuples is None: node_tuples = node_tuples_for_space(space) else: if len(node_tuples) != space.space_dim: raise ValueEr...
def warp_and_blend_nodes_3d(n, node_tuples=None):
try: alpha = _alpha_opt_3d[n-1] except IndexError: alpha = 1. space = PN(3, n) if node_tuples is None: node_tuples = node_tuples_for_space(space) else: if len(node_tuples) != space.space_dim: raise ValueError("'node_tuples' list does not have the correct ...
length") # shape: (2, nnodes) unit_nodes = (np.array(node_tuples, dtype=np.float64)/n*2 - 1).T from modepy.tools import ( unit_to_barycentric, barycentric_to_equilateral, equilateral_to_unit) bary = unit_to_barycentric(unit_nodes) return equilateral_to_unit( ...
221
221
738
16
205
inducer/modepy
modepy/nodes.py
Python
warp_and_blend_nodes_3d
warp_and_blend_nodes_3d
204
280
204
204
2acc7ee88e0b03dd486f05c9ddf920bb9d0cb771
bigcode/the-stack
train
d65213fefe2e64b730ddde12
train
function
def _2d_equilateral_shift(n, bary, alpha): from modepy.tools import EQUILATERAL_VERTICES equi_vertices = EQUILATERAL_VERTICES[2] result = np.zeros((2, bary.shape[1])) for i1 in range(3): i2, i3 = set(range(3)) - {i1} # Compute blending function at each node for each edge blend...
def _2d_equilateral_shift(n, bary, alpha):
from modepy.tools import EQUILATERAL_VERTICES equi_vertices = EQUILATERAL_VERTICES[2] result = np.zeros((2, bary.shape[1])) for i1 in range(3): i2, i3 = set(range(3)) - {i1} # Compute blending function at each node for each edge blend = 4*bary[i2]*bary[i3] # Amount of...
1.0-1.0e-10) sf = 1.0 - (zerof*output_nodes)**2 warp = warp/sf + warp*(zerof-1) return warp # {{{ 2D nodes def _2d_equilateral_shift(n, bary, alpha):
66
66
220
13
52
inducer/modepy
modepy/nodes.py
Python
_2d_equilateral_shift
_2d_equilateral_shift
137
161
137
137
851c1b988f0a0c8ba3a0c291921bad698db65d81
bigcode/the-stack
train
3b6d150af1257c08d190417f
train
function
@edge_clustered_nodes_for_space.register(QN) def _edge_clustered_nodes_for_qn(space: QN, shape: Hypercube): if not isinstance(shape, Hypercube): raise NotImplementedError((type(space).__name__, type(shape).__name__)) if space.spatial_dim != shape.dim: raise ValueError("spatial dimensions of shap...
@edge_clustered_nodes_for_space.register(QN) def _edge_clustered_nodes_for_qn(space: QN, shape: Hypercube):
if not isinstance(shape, Hypercube): raise NotImplementedError((type(space).__name__, type(shape).__name__)) if space.spatial_dim != shape.dim: raise ValueError("spatial dimensions of shape and space must match") return legendre_gauss_lobatto_tensor_product_nodes( space.spatial_...
T else: return (np.array(node_tuples_for_space(space), dtype=np.float64) / space.order*2 - 1).T @edge_clustered_nodes_for_space.register(QN) def _edge_clustered_nodes_for_qn(space: QN, shape: Hypercube):
64
64
102
30
33
inducer/modepy
modepy/nodes.py
Python
_edge_clustered_nodes_for_qn
_edge_clustered_nodes_for_qn
501
509
501
502
23d8b70ef817f5f6b95dcb3ff5864c2e5b44193d
bigcode/the-stack
train
fb6dafa3fcd0d0a754c1eadb
train
function
def warp_and_blend_nodes( dims: int, n: int, node_tuples: Optional[Sequence[Tuple[int, ...]]] = None) -> np.ndarray: """Return interpolation nodes as described in [warburton-nodes]_ .. [warburton-nodes] Warburton, T. "An Explicit Construction of Interpolation Nodes on the Simplex." ...
def warp_and_blend_nodes( dims: int, n: int, node_tuples: Optional[Sequence[Tuple[int, ...]]] = None) -> np.ndarray:
"""Return interpolation nodes as described in [warburton-nodes]_ .. [warburton-nodes] Warburton, T. "An Explicit Construction of Interpolation Nodes on the Simplex." Journal of Engineering Mathematics 56, no. 3 (2006): 247-262. http://dx.doi.org/10.1007/s10665-006-9086-6 :arg dims:...
(blend*warp2)[np.newaxis, :] * tangent2[:, np.newaxis] is_face = (l1 < tol) & ((l2 > tol) | (l3 > tol) | (l4 > tol)) # assign face warp separately shift[:, is_face] = ( + warp1[is_face][np.newaxis, :] * tangent1[:, np.newaxis] + warp2[is_face][np.newaxis, :] * ...
171
171
570
37
133
inducer/modepy
modepy/nodes.py
Python
warp_and_blend_nodes
warp_and_blend_nodes
287
340
287
289
2643f898d24e4370ef25009d3d41dedbace284a2
bigcode/the-stack
train
02af48b72506f0e4cd6c16cb
train
function
@random_nodes_for_shape.register(Simplex) def _random_nodes_for_simplex(shape: Simplex, nnodes: int, rng=None): if rng is None: rng = np.random result = np.zeros((shape.dim, nnodes)) nnodes_obtained = 0 while True: new_nodes = rng.uniform(-1.0, 1.0, size=(shape.dim, nnodes-nnodes_obtain...
@random_nodes_for_shape.register(Simplex) def _random_nodes_for_simplex(shape: Simplex, nnodes: int, rng=None):
if rng is None: rng = np.random result = np.zeros((shape.dim, nnodes)) nnodes_obtained = 0 while True: new_nodes = rng.uniform(-1.0, 1.0, size=(shape.dim, nnodes-nnodes_obtained)) new_nodes = new_nodes[:, new_nodes.sum(axis=0) < 2-shape.dim] nnew_nodes = new_nodes.shape[...
3: return warp_and_blend_nodes(space.spatial_dim, space.order) else: return equidistant_nodes(space.spatial_dim, space.order) @random_nodes_for_shape.register(Simplex) def _random_nodes_for_simplex(shape: Simplex, nnodes: int, rng=None):
64
64
176
29
35
inducer/modepy
modepy/nodes.py
Python
_random_nodes_for_simplex
_random_nodes_for_simplex
456
471
456
457
282ac258d0c0708f421835c67594dd09ab391b69
bigcode/the-stack
train
76894240157e89ada9181637
train
function
@singledispatch def edge_clustered_nodes_for_space(space: FunctionSpace, shape: Shape) -> np.ndarray: raise NotImplementedError((type(space).__name__, type(shape).__name__))
@singledispatch def edge_clustered_nodes_for_space(space: FunctionSpace, shape: Shape) -> np.ndarray:
raise NotImplementedError((type(space).__name__, type(shape).__name__))
def equispaced_nodes_for_space(space: FunctionSpace, shape: Shape) -> np.ndarray: raise NotImplementedError((type(space).__name__, type(shape).__name__)) @singledispatch def edge_clustered_nodes_for_space(space: FunctionSpace, shape: Shape) -> np.ndarray:
63
64
42
26
37
inducer/modepy
modepy/nodes.py
Python
edge_clustered_nodes_for_space
edge_clustered_nodes_for_space
398
400
398
399
694173693d041be7efab45ba8d1518e69af71c71
bigcode/the-stack
train
ea0bad2af59a35a25164ec99
train
function
@equispaced_nodes_for_space.register(PN) def _equispaced_nodes_for_pn(space: PN, shape: Simplex): if not isinstance(shape, Simplex): raise NotImplementedError((type(space).__name__, type(shape).__name__)) if space.spatial_dim != shape.dim: raise ValueError("spatial dimensions of shape and space ...
@equispaced_nodes_for_space.register(PN) def _equispaced_nodes_for_pn(space: PN, shape: Simplex):
if not isinstance(shape, Simplex): raise NotImplementedError((type(space).__name__, type(shape).__name__)) if space.spatial_dim != shape.dim: raise ValueError("spatial dimensions of shape and space must match") if space.order == 0: return ( np.mean(unit_vertices_for_...
import \ generate_nonnegative_integer_tuples_summing_to_at_most as gnitsam return tuple(gnitsam(space.order, space.spatial_dim)) @equispaced_nodes_for_space.register(PN) def _equispaced_nodes_for_pn(space: PN, shape: Simplex):
64
64
144
29
35
inducer/modepy
modepy/nodes.py
Python
_equispaced_nodes_for_pn
_equispaced_nodes_for_pn
427
440
427
428
5b9588c99610fbba022d29926f6d1138aec26e4f
bigcode/the-stack
train
8aeff9ee3651b9f281ca3082
train
function
@singledispatch def node_tuples_for_space(space: FunctionSpace) -> Sequence[Tuple[int]]: raise NotImplementedError(type(space).__name__)
@singledispatch def node_tuples_for_space(space: FunctionSpace) -> Sequence[Tuple[int]]:
raise NotImplementedError(type(space).__name__)
acobi_gauss import legendre_gauss_lobatto_nodes return tensor_product_nodes(dims, legendre_gauss_lobatto_nodes(n)) # }}} # {{{ space-based interface @singledispatch def node_tuples_for_space(space: FunctionSpace) -> Sequence[Tuple[int]]:
64
64
33
23
40
inducer/modepy
modepy/nodes.py
Python
node_tuples_for_space
node_tuples_for_space
388
390
388
389
3f2fa487f07d97a0a09785e15b1a13c599e68636
bigcode/the-stack
train
5a26ee8b182ec42777505d81
train
function
def warp_factor(n, output_nodes, scaled=True): """Compute warp function at order *n* and evaluate it at the nodes *output_nodes*. """ from modepy.quadrature.jacobi_gauss import legendre_gauss_lobatto_nodes warped_nodes = legendre_gauss_lobatto_nodes(n) equi_nodes = np.linspace(-1, 1, n+1) ...
def warp_factor(n, output_nodes, scaled=True):
"""Compute warp function at order *n* and evaluate it at the nodes *output_nodes*. """ from modepy.quadrature.jacobi_gauss import legendre_gauss_lobatto_nodes warped_nodes = legendre_gauss_lobatto_nodes(n) equi_nodes = np.linspace(-1, 1, n+1) from modepy.matrices import vandermonde fr...
return (np.mean(unit_vertices_for_shape(Simplex(dims)), axis=1) .reshape(-1, 1)) # shape: (dims, nnodes) return (np.array(node_tuples, dtype=np.float64)/n*2 - 1).T # }}} # {{{ warp and blend simplex nodes def warp_factor(n, output_nodes, scaled=True):
82
82
274
11
70
inducer/modepy
modepy/nodes.py
Python
warp_factor
warp_factor
106
132
106
106
3d05b1d65bc9d8ca60adc3c7570afb376c59b37e
bigcode/the-stack
train
9a5b6757d6965576595855ff
train
function
def tensor_product_nodes( dims_or_nodes: Union[int, Sequence[np.ndarray]], nodes_1d: Optional[np.ndarray] = None) -> np.ndarray: """ :returns: an array of shape ``(dims, nnodes_1d**dims)``. .. versionadded:: 2017.1 .. versionchanged:: 2020.3 The node ordering has changed and i...
def tensor_product_nodes( dims_or_nodes: Union[int, Sequence[np.ndarray]], nodes_1d: Optional[np.ndarray] = None) -> np.ndarray:
""" :returns: an array of shape ``(dims, nnodes_1d**dims)``. .. versionadded:: 2017.1 .. versionchanged:: 2020.3 The node ordering has changed and is no longer documented. """ if isinstance(dims_or_nodes, int): assert nodes_1d is not None nodes: Sequence[np.ndarray] = ...
(n, node_tuples) else: raise NotImplementedError("%d-dimensional node sets" % dims) # }}} # }}} # {{{ tensor product nodes def tensor_product_nodes( dims_or_nodes: Union[int, Sequence[np.ndarray]], nodes_1d: Optional[np.ndarray] = None) -> np.ndarray:
69
69
230
34
34
inducer/modepy
modepy/nodes.py
Python
tensor_product_nodes
tensor_product_nodes
349
376
349
351
dba850d746565498ebe9e17e07a2da450de5f243
bigcode/the-stack
train
ea992b9200287578c889f10d
train
function
def legendre_gauss_lobatto_tensor_product_nodes(dims: int, n: int) -> np.ndarray: from modepy.quadrature.jacobi_gauss import legendre_gauss_lobatto_nodes return tensor_product_nodes(dims, legendre_gauss_lobatto_nodes(n))
def legendre_gauss_lobatto_tensor_product_nodes(dims: int, n: int) -> np.ndarray:
from modepy.quadrature.jacobi_gauss import legendre_gauss_lobatto_nodes return tensor_product_nodes(dims, legendre_gauss_lobatto_nodes(n))
for d in range(dims): result[d] = nodes[dims-1-d].reshape((-1,) + (1,)*d) return result.reshape(dims, -1) def legendre_gauss_lobatto_tensor_product_nodes(dims: int, n: int) -> np.ndarray:
64
64
64
24
40
inducer/modepy
modepy/nodes.py
Python
legendre_gauss_lobatto_tensor_product_nodes
legendre_gauss_lobatto_tensor_product_nodes
379
381
379
379
5785a737c6f1bbe8b866aa03b0dd127471a0f8c8
bigcode/the-stack
train
a5eb3f73f79e644aafa1eb89
train
function
@equispaced_nodes_for_space.register(QN) def _equispaced_nodes_for_qn(space: QN, shape: Hypercube): if not isinstance(shape, Hypercube): raise NotImplementedError((type(space).__name__, type(shape).__name__)) if space.spatial_dim != shape.dim: raise ValueError("spatial dimensions of shape and sp...
@equispaced_nodes_for_space.register(QN) def _equispaced_nodes_for_qn(space: QN, shape: Hypercube):
if not isinstance(shape, Hypercube): raise NotImplementedError((type(space).__name__, type(shape).__name__)) if space.spatial_dim != shape.dim: raise ValueError("spatial dimensions of shape and space must match") if space.order == 0: return np.array(node_tuples_for_space(space), dty...
as gnitb return tuple([ tp[::-1] for tp in gnitb(space.order + 1, space.spatial_dim) ]) @equispaced_nodes_for_space.register(QN) def _equispaced_nodes_for_qn(space: QN, shape: Hypercube):
63
64
138
30
33
inducer/modepy
modepy/nodes.py
Python
_equispaced_nodes_for_qn
_equispaced_nodes_for_qn
487
498
487
488
99e0b34f7543f7ab64389be17db0c459f921352b
bigcode/the-stack
train
7d0e39629703cd0a7597d92f
train
function
@singledispatch def random_nodes_for_shape( shape: Shape, nnodes: int, rng: Optional[np.random.Generator] = None) -> np.ndarray: """ :arg rng: a :class:`numpy.random.Generator`. :returns: a :class:`numpy.ndarray` of shape `(dim, nnodes)` of random nodes in the reference *shape*. ...
@singledispatch def random_nodes_for_shape( shape: Shape, nnodes: int, rng: Optional[np.random.Generator] = None) -> np.ndarray:
""" :arg rng: a :class:`numpy.random.Generator`. :returns: a :class:`numpy.ndarray` of shape `(dim, nnodes)` of random nodes in the reference *shape*. """ raise NotImplementedError(type(shape).__name__)
, shape: Shape) -> np.ndarray: raise NotImplementedError((type(space).__name__, type(shape).__name__)) @singledispatch def random_nodes_for_shape( shape: Shape, nnodes: int, rng: Optional[np.random.Generator] = None) -> np.ndarray:
63
64
97
38
25
inducer/modepy
modepy/nodes.py
Python
random_nodes_for_shape
random_nodes_for_shape
403
413
403
406
ead78e303ccb612c2426929c8181ded9d30f5582
bigcode/the-stack
train
f018047d0a38cc86acc2162e
train
function
@random_nodes_for_shape.register(Hypercube) def _random_nodes_for_hypercube(shape: Hypercube, nnodes: int, rng=None): if rng is None: rng = np.random return rng.uniform(-1.0, 1.0, size=(shape.dim, nnodes))
@random_nodes_for_shape.register(Hypercube) def _random_nodes_for_hypercube(shape: Hypercube, nnodes: int, rng=None):
if rng is None: rng = np.random return rng.uniform(-1.0, 1.0, size=(shape.dim, nnodes))
("spatial dimensions of shape and space must match") return legendre_gauss_lobatto_tensor_product_nodes( space.spatial_dim, space.order) @random_nodes_for_shape.register(Hypercube) def _random_nodes_for_hypercube(shape: Hypercube, nnodes: int, rng=None):
64
64
65
31
33
inducer/modepy
modepy/nodes.py
Python
_random_nodes_for_hypercube
_random_nodes_for_hypercube
512
516
512
513
a7020b27cbcc8238972bf71582f87bd95d9bb2cb
bigcode/the-stack
train
a1498c88fb95e0b784128a24
train
function
def equidistant_nodes( dims: int, n: int, node_tuples: Optional[Sequence[Tuple[int, ...]]] = None ) -> np.ndarray: """ :arg dims: dimensionality of desired simplex (e.g. 1, 2 or 3, for interval, triangle or tetrahedron). :arg n: Desired maximum total polynomial degree to inte...
def equidistant_nodes( dims: int, n: int, node_tuples: Optional[Sequence[Tuple[int, ...]]] = None ) -> np.ndarray:
""" :arg dims: dimensionality of desired simplex (e.g. 1, 2 or 3, for interval, triangle or tetrahedron). :arg n: Desired maximum total polynomial degree to interpolate. :arg node_tuples: a list of tuples of integers indicating the node order. Use default order if *None*, see :fu...
np import numpy.linalg as la from functools import singledispatch, partial from modepy.shapes import Shape, Simplex, Hypercube, unit_vertices_for_shape from modepy.spaces import FunctionSpace, PN, QN # {{{ equidistant nodes def equidistant_nodes( dims: int, n: int, node_tuples: Optional[Sequence[Tu...
95
95
317
38
56
inducer/modepy
modepy/nodes.py
Python
equidistant_nodes
equidistant_nodes
70
99
70
73
d673e44cdf556e0a7177f71e284116085947f203
bigcode/the-stack
train
a02581ee5e1c72de703fc3f7
train
function
def gen_arg_specs(vars: Dict, required: bool = True) -> Dict: """ Generate an argspec for all vars in the given dict. """ return {k: gen_arg_spec(v, required=required) for k, v in vars.items()}
def gen_arg_specs(vars: Dict, required: bool = True) -> Dict:
""" Generate an argspec for all vars in the given dict. """ return {k: gen_arg_spec(v, required=required) for k, v in vars.items()}
len(arg_value) > 0: spec["options"] = gen_arg_specs(arg_value) # Add the default for require if required is False: spec["default"] = arg_value return spec def gen_arg_specs(vars: Dict, required: bool = True) -> Dict:
64
64
56
17
46
devon-mar/ansible-arg-spec-gen
gen_arg_spec.py
Python
gen_arg_specs
gen_arg_specs
60
64
60
60
9e618db03784cb0c96b9e9f69e784d26ae35d278
bigcode/the-stack
train
d4b2fbd53116649b8cc66b31
train
function
def gen_arg_spec(arg_value: Any, required: bool = True) -> Dict: """ Generate a arg spec for a single var. """ spec: Dict[str, Any] = {"type": get_type_str(arg_value)} if required is True: spec["required"] = True # Want description after required spec["description"] = '' if spec...
def gen_arg_spec(arg_value: Any, required: bool = True) -> Dict:
""" Generate a arg spec for a single var. """ spec: Dict[str, Any] = {"type": get_type_str(arg_value)} if required is True: spec["required"] = True # Want description after required spec["description"] = '' if spec["type"] == "list" and len(arg_value) > 0: spec["elements...
keys spec = gen_arg_specs(all_opts) # Update required for k, v in spec.items(): if is_required[k] is False: v.pop("required", None) return spec def gen_arg_spec(arg_value: Any, required: bool = True) -> Dict:
64
64
190
18
45
devon-mar/ansible-arg-spec-gen
gen_arg_spec.py
Python
gen_arg_spec
gen_arg_spec
35
57
35
35
d52c161ba210f4951bd08c8ba04ca90a84ab4211
bigcode/the-stack
train
52acbca442f000536c0101fc
train
function
def nested_options(vars: List[Dict[str, Any]]): all_opts: Dict[str, Any] = vars[0] is_required: Dict[str, bool] = {key: True for key in all_opts} for list_dict in vars[1:]: # Set keys as optional for key in is_required: if key not in list_dict: is_required[key] =...
def nested_options(vars: List[Dict[str, Any]]):
all_opts: Dict[str, Any] = vars[0] is_required: Dict[str, bool] = {key: True for key in all_opts} for list_dict in vars[1:]: # Set keys as optional for key in is_required: if key not in list_dict: is_required[key] = False # Add any other keys as optional ...
#!/usr/bin/env python3 import yaml import argparse from typing import Any, Dict, List def get_type_str(v: Any) -> str: return type(v).__name__ def nested_options(vars: List[Dict[str, Any]]):
53
64
183
13
40
devon-mar/ansible-arg-spec-gen
gen_arg_spec.py
Python
nested_options
nested_options
11
32
11
11
d92eb0df3c49ed0fe6b60f3a491005aa77fad859
bigcode/the-stack
train
b7b3c5cd6749e6b9b2b3408f
train
function
def get_type_str(v: Any) -> str: return type(v).__name__
def get_type_str(v: Any) -> str:
return type(v).__name__
#!/usr/bin/env python3 import yaml import argparse from typing import Any, Dict, List def get_type_str(v: Any) -> str:
33
64
18
11
21
devon-mar/ansible-arg-spec-gen
gen_arg_spec.py
Python
get_type_str
get_type_str
7
8
7
7
cace98b50714ae76af2142b225f2e078639ca24e
bigcode/the-stack
train
84b3ff4150b9456b2d009593
train
class
class HttpResponseNotImplemented(HttpResponse): status_code = 501
class HttpResponseNotImplemented(HttpResponse):
status_code = 501
import json from django.db.models.query import QuerySet from django.http import HttpResponse from django.core import serializers class HttpResponseNotImplemented(HttpResponse):
33
64
15
8
24
Octane5Devs/django-ios-notifications
ios_notifications/http.py
Python
HttpResponseNotImplemented
HttpResponseNotImplemented
8
9
8
8
85dbdc658a04ee7dcc989675b08acd5b881994a4
bigcode/the-stack
train
3fd113e3016ba7c59ede8d11
train
class
class JSONResponse(HttpResponse): """ A subclass of django.http.HttpResponse which serializes its content and returns a response with an application/json mimetype. """ def __init__(self, content=None, content_type=None, status=None, mimetype='application/json'): content = self.serialize(cont...
class JSONResponse(HttpResponse):
""" A subclass of django.http.HttpResponse which serializes its content and returns a response with an application/json mimetype. """ def __init__(self, content=None, content_type=None, status=None, mimetype='application/json'): content = self.serialize(content) if content is not None else '...
import json from django.db.models.query import QuerySet from django.http import HttpResponse from django.core import serializers class HttpResponseNotImplemented(HttpResponse): status_code = 501 class JSONResponse(HttpResponse):
46
64
165
6
39
Octane5Devs/django-ios-notifications
ios_notifications/http.py
Python
JSONResponse
JSONResponse
12
30
12
12
23f73237341a312cac7b2cfa4fb737b72ca9bb86
bigcode/the-stack
train
a9372e00fc8a86dd22e16815
train
function
def draw_meshes(): for m in meshes: m.draw()
def draw_meshes():
for m in meshes: m.draw()
and vector calculus. (c) 2017 Yann Thorimbert """ from __future__ import print_function, division import pygame from pygame.math import Vector2 as V2 import pygame.gfxdraw as gfx import physics import parameters #all physical quantities are defined here def draw_meshes():
64
64
15
5
58
YannThorimbert/RigidBodies2D
examplearbitrarymesh.py
Python
draw_meshes
draw_meshes
14
16
14
14
d5453ae9c6774d4368a4879fd1a2ac2ac7e31eb5
bigcode/the-stack
train
cbee81afbb84d7c5f08b742d
train
function
def refresh_physics(): for m in meshes: m.refresh_physics()
def refresh_physics():
for m in meshes: m.refresh_physics()
from __future__ import print_function, division import pygame from pygame.math import Vector2 as V2 import pygame.gfxdraw as gfx import physics import parameters #all physical quantities are defined here def draw_meshes(): for m in meshes: m.draw() def refresh_physics():
64
64
17
5
59
YannThorimbert/RigidBodies2D
examplearbitrarymesh.py
Python
refresh_physics
refresh_physics
18
20
18
18
a3f6297c3d6da9475486c41c990b4105073e18c0
bigcode/the-stack
train
fcff0acc06a57850578f5532
train
class
class DiskFileRouter(object): def __init__(self, *args, **kwargs): self.policy_to_manager = {} for policy in POLICIES: # create diskfile managers now to provoke any errors self.policy_to_manager[int(policy)] = \ policy.get_diskfile_manager(*args, **kwargs) ...
class DiskFileRouter(object):
def __init__(self, *args, **kwargs): self.policy_to_manager = {} for policy in POLICIES: # create diskfile managers now to provoke any errors self.policy_to_manager[int(policy)] = \ policy.get_diskfile_manager(*args, **kwargs) def __getitem__(self, policy...
.json" % auditor_type) remove_file(auditor_status) def strip_self(f): """ Wrapper to attach module level functions to base class. """ def wrapper(self, *args, **kwargs): return f(*args, **kwargs) return wrapper class DiskFileRouter(object):
64
64
86
6
57
scottwedge/OpenStack-Stein
swift-2.21.0/swift/obj/diskfile.py
Python
DiskFileRouter
DiskFileRouter
625
635
625
626
fd968260e4c53eac96767f74a422893d400b4ba4
bigcode/the-stack
train
bfba71b00bd079099c46bcac
train
function
def _encode_metadata(metadata): """ UTF8 encode any unicode keys or values in given metadata dict. :param metadata: a dict """ def encode_str(item): if isinstance(item, six.text_type): return item.encode('utf8') return item return dict(((encode_str(k), encode_str(v)...
def _encode_metadata(metadata):
""" UTF8 encode any unicode keys or values in given metadata dict. :param metadata: a dict """ def encode_str(item): if isinstance(item, six.text_type): return item.encode('utf8') return item return dict(((encode_str(k), encode_str(v)) for k, v in metadata.items()))...
to file name from a file descriptor or filename. :param fd: file descriptor or filename. :returns: the filename. """ if hasattr(fd, 'name'): # fd object return fd.name # fd is a filename return fd def _encode_metadata(metadata):
64
64
79
6
57
scottwedge/OpenStack-Stein
swift-2.21.0/swift/obj/diskfile.py
Python
_encode_metadata
_encode_metadata
150
161
150
150
f9a9081ef3469070423347d9945cadcc674b8c19
bigcode/the-stack
train
5dacd3925e461cb61c1420b7
train
class
class DiskFileManager(BaseDiskFileManager): diskfile_cls = DiskFile policy = REPL_POLICY def _process_ondisk_files(self, exts, results, **kwargs): """ Implement replication policy specific handling of .data files. :param exts: dict of lists of file info, keyed by extension ...
class DiskFileManager(BaseDiskFileManager):
diskfile_cls = DiskFile policy = REPL_POLICY def _process_ondisk_files(self, exts, results, **kwargs): """ Implement replication policy specific handling of .data files. :param exts: dict of lists of file info, keyed by extension :param results: a dict that may be updated w...
': timestamp.internal}) class DiskFileReader(BaseDiskFileReader): pass class DiskFileWriter(BaseDiskFileWriter): def put(self, metadata): """ Finalize writing the file on disk. :param metadata: dictionary of metadata to be associated with the object ...
158
158
529
9
148
scottwedge/OpenStack-Stein
swift-2.21.0/swift/obj/diskfile.py
Python
DiskFileManager
DiskFileManager
2,862
2,919
2,862
2,862
4d7533bcbe1f131f9fac05fc277f4e411aa481c4
bigcode/the-stack
train
983843100073425ba97a9c23
train
class
class ECDiskFileManager(BaseDiskFileManager): diskfile_cls = ECDiskFile policy = EC_POLICY def validate_fragment_index(self, frag_index, policy=None): """ Return int representation of frag_index, or raise a DiskFileError if frag_index is not a whole number. :param frag_inde...
class ECDiskFileManager(BaseDiskFileManager):
diskfile_cls = ECDiskFile policy = EC_POLICY def validate_fragment_index(self, frag_index, policy=None): """ Return int representation of frag_index, or raise a DiskFileError if frag_index is not a whole number. :param frag_index: a fragment archive index :param pol...
a tombstone or fragment from a handoff node after reverting it to its primary node. The hash will be invalidated, and if empty the hsh_path will be removed immediately. :param timestamp: the object timestamp, an instance of :class:`~swift.common.utils.Timesta...
256
256
3,416
11
245
scottwedge/OpenStack-Stein
swift-2.21.0/swift/obj/diskfile.py
Python
ECDiskFileManager
ECDiskFileManager
3,225
3,570
3,225
3,225
2a9c614084270706fcbe0e64938c9d6611f6e661
bigcode/the-stack
train
8672e2ea525195c8ad596209
train
function
def relink_paths(target_path, new_target_path, check_existing=False): """ Hard-links a file located in target_path using the second path new_target_path. Creates intermediate directories if required. :param target_path: current absolute filename :param new_target_path: new absolute filename for the...
def relink_paths(target_path, new_target_path, check_existing=False):
""" Hard-links a file located in target_path using the second path new_target_path. Creates intermediate directories if required. :param target_path: current absolute filename :param new_target_path: new absolute filename for the hardlink :param check_existing: if True, check whether the link i...
_INVALIDATIONS_FILE) if not isinstance(suffix, bytes): suffix = suffix.encode('utf-8') with lock_path(partition_dir), open(invalidations_file, 'ab') as inv_fh: inv_fh.write(suffix + b"\n") def relink_paths(target_path, new_target_path, check_existing=False):
72
72
242
15
57
scottwedge/OpenStack-Stein
swift-2.21.0/swift/obj/diskfile.py
Python
relink_paths
relink_paths
431
459
431
431
0baf2a719191128ab91b7db7438155c636f5655c
bigcode/the-stack
train
3a21c1e1814536885ccd7453
train
class
class BaseDiskFileManager(object): """ Management class for devices, providing common place for shared parameters and methods not provided by the DiskFile class (which primarily services the object server REST API layer). The `get_diskfile()` method is how this implementation creates a `DiskFile` ...
class BaseDiskFileManager(object):
""" Management class for devices, providing common place for shared parameters and methods not provided by the DiskFile class (which primarily services the object server REST API layer). The `get_diskfile()` method is how this implementation creates a `DiskFile` object. .. note:: ...
if logger: logger.warning(_('Cannot write %(auditor_status)s (%(err)s)') % {'auditor_status': auditor_status, 'err': e}) def clear_auditor_status(devices, datadir, auditor_type="ALL"): device_dirs = listdir(devices) for device in device_dirs: datadir_path...
255
256
8,624
7
248
scottwedge/OpenStack-Stein
swift-2.21.0/swift/obj/diskfile.py
Python
BaseDiskFileManager
BaseDiskFileManager
638
1,604
638
638
e98300b0db527689b25ea5e85a4594e808bc0df0
bigcode/the-stack
train
a9adc962e28aac8a361ad19a
train
class
class AuditLocation(object): """ Represents an object location to be audited. Other than being a bucket of data, the only useful thing this does is stringify to a filesystem path so the auditor's logs look okay. """ def __init__(self, path, device, partition, policy): self.path, self.d...
class AuditLocation(object):
""" Represents an object location to be audited. Other than being a bucket of data, the only useful thing this does is stringify to a filesystem path so the auditor's logs look okay. """ def __init__(self, path, device, partition, policy): self.path, self.device, self.partition, self.p...
_path, new_target_path) def get_part_path(dev_path, policy, partition): """ Given the device path, policy, and partition, returns the full path to the partition """ return os.path.join(dev_path, get_data_dir(policy), str(partition)) class AuditLocation(object):
64
64
100
5
59
scottwedge/OpenStack-Stein
swift-2.21.0/swift/obj/diskfile.py
Python
AuditLocation
AuditLocation
470
483
470
470
148ee067b61a7e1ffdfcd65584a44929d704a385
bigcode/the-stack
train
62aca885768e86e1838d40cc
train
class
class DiskFileWriter(BaseDiskFileWriter): def put(self, metadata): """ Finalize writing the file on disk. :param metadata: dictionary of metadata to be associated with the object """ super(DiskFileWriter, self)._put(metadata, True)
class DiskFileWriter(BaseDiskFileWriter):
def put(self, metadata): """ Finalize writing the file on disk. :param metadata: dictionary of metadata to be associated with the object """ super(DiskFileWriter, self)._put(metadata, True)
, only tests send in strings timestamp = Timestamp(timestamp) with self.create() as deleter: deleter._extension = '.ts' deleter.put({'X-Timestamp': timestamp.internal}) class DiskFileReader(BaseDiskFileReader): pass class DiskFileWriter(BaseDiskFileWriter):
64
64
60
9
54
scottwedge/OpenStack-Stein
swift-2.21.0/swift/obj/diskfile.py
Python
DiskFileWriter
DiskFileWriter
2,841
2,849
2,841
2,841
b649a0188d7b72630d9dc7d2c5cd19b8145582f6
bigcode/the-stack
train
64448af9a81a2f8d5ba2f0b8
train
class
class ECDiskFileWriter(BaseDiskFileWriter): def _finalize_durable(self, data_file_path, durable_data_file_path): exc = None new_data_file_path = new_durable_data_file_path = None if self.next_part_power: new_data_file_path = replace_partition_in_path( data_file_p...
class ECDiskFileWriter(BaseDiskFileWriter):
def _finalize_durable(self, data_file_path, durable_data_file_path): exc = None new_data_file_path = new_durable_data_file_path = None if self.next_part_power: new_data_file_path = replace_partition_in_path( data_file_path, self.next_part_power) new_du...
trigger the needful # error handling cleanup - failing to do so, and yet still failing # to deliver all promised bytes will hang the HTTP connection raise DiskFileQuarantined(msg) except ECDriverError as err: self._diskfile._logger.warn( _('Proble...
256
256
909
11
245
scottwedge/OpenStack-Stein
swift-2.21.0/swift/obj/diskfile.py
Python
ECDiskFileWriter
ECDiskFileWriter
2,998
3,094
2,998
2,999
f1db7f5df7329856ce3e9f76fb1bc2596e6c0342
bigcode/the-stack
train
392c8804bf5a841ae70f10b9
train
function
def clear_auditor_status(devices, datadir, auditor_type="ALL"): device_dirs = listdir(devices) for device in device_dirs: datadir_path = os.path.join(devices, device, datadir) auditor_status = os.path.join( datadir_path, "auditor_status_%s.json" % auditor_type) remove_file(au...
def clear_auditor_status(devices, datadir, auditor_type="ALL"):
device_dirs = listdir(devices) for device in device_dirs: datadir_path = os.path.join(devices, device, datadir) auditor_status = os.path.join( datadir_path, "auditor_status_%s.json" % auditor_type) remove_file(auditor_status)
except (OSError, IOError) as e: if logger: logger.warning(_('Cannot write %(auditor_status)s (%(err)s)') % {'auditor_status': auditor_status, 'err': e}) def clear_auditor_status(devices, datadir, auditor_type="ALL"):
64
64
82
17
47
scottwedge/OpenStack-Stein
swift-2.21.0/swift/obj/diskfile.py
Python
clear_auditor_status
clear_auditor_status
607
613
607
607
8506463af45c776c3199e09a5bf8c9ac4fcb45b1
bigcode/the-stack
train
34d3fa692260b1eacbfaa3ea
train
class
class BaseDiskFileWriter(object): """ Encapsulation of the write context for servicing PUT REST API requests. Serves as the context manager object for the :class:`swift.obj.diskfile.DiskFile` class's :func:`swift.obj.diskfile.DiskFile.create` method. .. note:: It is the responsibility ...
class BaseDiskFileWriter(object):
""" Encapsulation of the write context for servicing PUT REST API requests. Serves as the context manager object for the :class:`swift.obj.diskfile.DiskFile` class's :func:`swift.obj.diskfile.DiskFile.create` method. .. note:: It is the responsibility of the :func:`swift.obj.di...
suffix_path, suffix in suffixes: found_files = False for object_hash in self._listdir(suffix_path): object_path = os.path.join(suffix_path, object_hash) try: results = self.cleanup_ondisk_files( object_path, **kwargs) ...
256
256
2,350
7
249
scottwedge/OpenStack-Stein
swift-2.21.0/swift/obj/diskfile.py
Python
BaseDiskFileWriter
BaseDiskFileWriter
1,607
1,887
1,607
1,607
048cc2e7091c5bdd130917a04a754b4a28903cc8
bigcode/the-stack
train
0ccb54c09ff198f42089a29b
train
function
def read_hashes(partition_dir): """ Read the existing hashes.pkl :returns: a dict, the suffix hashes (if any), the key 'valid' will be False if hashes.pkl is corrupt, cannot be read or does not exist """ hashes_file = join(partition_dir, HASH_FILE) hashes = {'valid': False} tr...
def read_hashes(partition_dir):
""" Read the existing hashes.pkl :returns: a dict, the suffix hashes (if any), the key 'valid' will be False if hashes.pkl is corrupt, cannot be read or does not exist """ hashes_file = join(partition_dir, HASH_FILE) hashes = {'valid': False} try: with open(hashes_file...
.errno not in (errno.EEXIST, errno.ENOTEMPTY): raise to_dir = "%s-%s" % (to_dir, uuid.uuid4().hex) renamer(from_dir, to_dir, fsync=False) return to_dir def read_hashes(partition_dir):
64
64
213
8
55
scottwedge/OpenStack-Stein
swift-2.21.0/swift/obj/diskfile.py
Python
read_hashes
read_hashes
335
360
335
335
9fa99cfc994e828a437dbf8d20a1f8275f05380f
bigcode/the-stack
train
4ca08d4fcf3c3bcab29dfa09
train
function
def _get_filename(fd): """ Helper function to get to file name from a file descriptor or filename. :param fd: file descriptor or filename. :returns: the filename. """ if hasattr(fd, 'name'): # fd object return fd.name # fd is a filename return fd
def _get_filename(fd):
""" Helper function to get to file name from a file descriptor or filename. :param fd: file descriptor or filename. :returns: the filename. """ if hasattr(fd, 'name'): # fd object return fd.name # fd is a filename return fd
Policy`` instance, or an index (string or int); if None, the legacy Policy-0 is assumed. :returns: ``tmp`` or ``tmp-<N>`` as appropriate ''' return get_policy_string(TMP_BASE, policy_or_index) def _get_filename(fd):
64
64
71
6
58
scottwedge/OpenStack-Stein
swift-2.21.0/swift/obj/diskfile.py
Python
_get_filename
_get_filename
134
147
134
134
337d670d9c2adc137692648f904cc58173cfc8b7
bigcode/the-stack
train
7237930d466ed60a7c3ff898
train
function
def _decode_metadata(metadata): """ Given a metadata dict from disk, convert keys and values to native strings. :param metadata: a dict """ if six.PY2: def to_str(item): if isinstance(item, six.text_type): return item.encode('utf8') return item el...
def _decode_metadata(metadata):
""" Given a metadata dict from disk, convert keys and values to native strings. :param metadata: a dict """ if six.PY2: def to_str(item): if isinstance(item, six.text_type): return item.encode('utf8') return item else: def to_str(item): ...
:param metadata: a dict """ def encode_str(item): if isinstance(item, six.text_type): return item.encode('utf8') return item return dict(((encode_str(k), encode_str(v)) for k, v in metadata.items())) def _decode_metadata(metadata):
63
64
123
6
57
scottwedge/OpenStack-Stein
swift-2.21.0/swift/obj/diskfile.py
Python
_decode_metadata
_decode_metadata
164
181
164
164
a0da3341856b36f1b7c63f71a6f9d67595c1b28a
bigcode/the-stack
train
91dfb6d3036939a8996ed103
train
class
class ECDiskFileReader(BaseDiskFileReader): def __init__(self, fp, data_file, obj_size, etag, disk_chunk_size, keep_cache_size, device_path, logger, quarantine_hook, use_splice, pipe_size, diskfile, keep_cache=False): super(ECDiskFileReader, self).__init__(...
class ECDiskFileReader(BaseDiskFileReader):
def __init__(self, fp, data_file, obj_size, etag, disk_chunk_size, keep_cache_size, device_path, logger, quarantine_hook, use_splice, pipe_size, diskfile, keep_cache=False): super(ECDiskFileReader, self).__init__( fp, data_file, obj_size, etag, ...
""" Applies policy specific updates to the given dict of md5 hashes for the given ondisk_info. :param hashes: a dict of md5 hashes to be updated :param ondisk_info: a dict describing the state of ondisk files, as returned by get_ondisk_files """ ...
238
238
796
11
227
scottwedge/OpenStack-Stein
swift-2.21.0/swift/obj/diskfile.py
Python
ECDiskFileReader
ECDiskFileReader
2,922
2,995
2,922
2,922
5a1aa1bd56aaef00ab11f9b429443e1f220bef97
bigcode/the-stack
train
4f0b79aeddfb364a85df5c6f
train
function
def invalidate_hash(suffix_dir): """ Invalidates the hash for a suffix_dir in the partition's hashes file. :param suffix_dir: absolute path to suffix dir whose hash needs invalidating """ suffix = basename(suffix_dir) partition_dir = dirname(suffix_dir) invalidations...
def invalidate_hash(suffix_dir):
""" Invalidates the hash for a suffix_dir in the partition's hashes file. :param suffix_dir: absolute path to suffix dir whose hash needs invalidating """ suffix = basename(suffix_dir) partition_dir = dirname(suffix_dir) invalidations_file = join(partition_dir, HASH_...
es(partition_dir, hashes) # Now that all the invalidations are reflected in hashes.pkl, it's # safe to clear out the invalidations file. with open(invalidations_file, 'wb') as inv_fh: pass return hashes def invalidate_hash(suffix_dir):
64
64
131
7
56
scottwedge/OpenStack-Stein
swift-2.21.0/swift/obj/diskfile.py
Python
invalidate_hash
invalidate_hash
414
428
414
414
31327fad9a8cbe299edb9909ef9c894824f5e393
bigcode/the-stack
train
d1d48493300e0f72f15ce7a0
train
function
def get_auditor_status(datadir_path, logger, auditor_type): auditor_status = os.path.join( datadir_path, "auditor_status_%s.json" % auditor_type) status = {} try: if six.PY3: statusfile = open(auditor_status, encoding='utf8') else: statusfile = open(auditor_st...
def get_auditor_status(datadir_path, logger, auditor_type):
auditor_status = os.path.join( datadir_path, "auditor_status_%s.json" % auditor_type) status = {} try: if six.PY3: statusfile = open(auditor_status, encoding='utf8') else: statusfile = open(auditor_status, 'rb') with statusfile: status = st...
for hsh in hashes: hsh_path = os.path.join(suff_path, hsh) yield AuditLocation(hsh_path, device, partition, policy) update_auditor_status(datadir_path, logger, [], auditor_type) def get_auditor_status(datadir_path,...
69
69
230
15
54
scottwedge/OpenStack-Stein
swift-2.21.0/swift/obj/diskfile.py
Python
get_auditor_status
get_auditor_status
556
579
556
556
9e9942a3c3b715b1da144d72d5840167907b6f16
bigcode/the-stack
train
76e6666381c2c75941616dff
train
class
class ECDiskFile(BaseDiskFile): reader_cls = ECDiskFileReader writer_cls = ECDiskFileWriter def __init__(self, *args, **kwargs): super(ECDiskFile, self).__init__(*args, **kwargs) frag_index = kwargs.get('frag_index') self._frag_index = None if frag_index is not None: ...
class ECDiskFile(BaseDiskFile):
reader_cls = ECDiskFileReader writer_cls = ECDiskFileWriter def __init__(self, *args, **kwargs): super(ECDiskFile, self).__init__(*args, **kwargs) frag_index = kwargs.get('frag_index') self._frag_index = None if frag_index is not None: self._frag_index = self.man...
tpool.execute( self._finalize_durable, data_file_path, durable_data_file_path) def put(self, metadata): """ The only difference between this method and the replication policy DiskFileWriter method is adding the frag index to the metadata. :param metadata: dictio...
256
256
1,143
9
247
scottwedge/OpenStack-Stein
swift-2.21.0/swift/obj/diskfile.py
Python
ECDiskFile
ECDiskFile
3,097
3,222
3,097
3,098
a35d033ae9afebd449270a95cb04d77fd48b93dc
bigcode/the-stack
train
a69095f17f8c4d5b660d8db7
train
function
def read_metadata(fd, add_missing_checksum=False): """ Helper function to read the pickled metadata from an object file. :param fd: file descriptor or filename to load the metadata from :param add_missing_checksum: if set and checksum is missing, add it :returns: dictionary of metadata """ ...
def read_metadata(fd, add_missing_checksum=False):
""" Helper function to read the pickled metadata from an object file. :param fd: file descriptor or filename to load the metadata from :param add_missing_checksum: if set and checksum is missing, add it :returns: dictionary of metadata """ metadata = b'' key = 0 try: while ...
return item.encode('utf8') return item return dict(((encode_str(k), encode_str(v)) for k, v in metadata.items())) def _decode_metadata(metadata): """ Given a metadata dict from disk, convert keys and values to native strings. :param metadata: a dict """ if six.PY2: def to_st...
165
166
556
10
155
scottwedge/OpenStack-Stein
swift-2.21.0/swift/obj/diskfile.py
Python
read_metadata
read_metadata
184
240
184
184
8b47caa5365f2369c5bbbeb54ee7324ee82a860b
bigcode/the-stack
train
37d76d14904848436304e2c5
train
function
def get_data_dir(policy_or_index): ''' Get the data dir for the given policy. :param policy_or_index: ``StoragePolicy`` instance, or an index (string or int); if None, the legacy Policy-0 is assumed. :returns: ``objects`` or ``objects-<N>`` as appropriate ''' return ...
def get_data_dir(policy_or_index):
''' Get the data dir for the given policy. :param policy_or_index: ``StoragePolicy`` instance, or an index (string or int); if None, the legacy Policy-0 is assumed. :returns: ``objects`` or ``objects-<N>`` as appropriate ''' return get_policy_string(DATADIR_BASE, pol...
_UPDATE_AUDITOR_STATUS = 60 # This matches rsync tempfiles, like ".<timestamp>.data.Xy095a" RE_RSYNC_TEMPFILE = re.compile(r'^\..*\.([a-zA-Z0-9_]){6}$') def get_data_dir(policy_or_index):
64
64
89
8
56
scottwedge/OpenStack-Stein
swift-2.21.0/swift/obj/diskfile.py
Python
get_data_dir
get_data_dir
101
109
101
101
ff6f561ca32f4feaf2808e6eb9c25ad0f05acf47
bigcode/the-stack
train
643e41810257fd106af70982
train
function
def get_tmp_dir(policy_or_index): ''' Get the temp dir for the given policy. :param policy_or_index: ``StoragePolicy`` instance, or an index (string or int); if None, the legacy Policy-0 is assumed. :returns: ``tmp`` or ``tmp-<N>`` as appropriate ''' return get_polic...
def get_tmp_dir(policy_or_index):
''' Get the temp dir for the given policy. :param policy_or_index: ``StoragePolicy`` instance, or an index (string or int); if None, the legacy Policy-0 is assumed. :returns: ``tmp`` or ``tmp-<N>`` as appropriate ''' return get_policy_string(TMP_BASE, policy_or_index...
(string or int); if None, the legacy Policy-0 is assumed. :returns: ``async_pending`` or ``async_pending-<N>`` as appropriate ''' return get_policy_string(ASYNCDIR_BASE, policy_or_index) def get_tmp_dir(policy_or_index):
64
64
87
8
56
scottwedge/OpenStack-Stein
swift-2.21.0/swift/obj/diskfile.py
Python
get_tmp_dir
get_tmp_dir
123
131
123
123
10ec2189cc3ec3a494ae1e9742742022aa628437
bigcode/the-stack
train
13ce85fcc136f9ec4bd55a2b
train
function
def quarantine_renamer(device_path, corrupted_file_path): """ In the case that a file is corrupted, move it to a quarantined area to allow replication to fix it. :params device_path: The path to the device the corrupted file is on. :params corrupted_file_path: The path to the file you want quaranti...
def quarantine_renamer(device_path, corrupted_file_path):
""" In the case that a file is corrupted, move it to a quarantined area to allow replication to fix it. :params device_path: The path to the device the corrupted file is on. :params corrupted_file_path: The path to the file you want quarantined. :returns: path (str) of directory the file was m...
try: obj_portion = obj_path[obj_path.rindex(DATADIR_BASE):] obj_dirname = obj_portion[:obj_portion.index('/')] except Exception: return None try: base, policy = split_policy_string(obj_dirname) except PolicyError: return None return policy def quarantine_renamer(...
83
83
278
12
70
scottwedge/OpenStack-Stein
swift-2.21.0/swift/obj/diskfile.py
Python
quarantine_renamer
quarantine_renamer
304
332
304
304
772850934393035e9aec90c49404f7275ff9fd4c
bigcode/the-stack
train
73d97728dd8293c1aaf4f7a8
train
function
def consolidate_hashes(partition_dir): """ Take what's in hashes.pkl and hashes.invalid, combine them, write the result back to hashes.pkl, and clear out hashes.invalid. :param partition_dir: absolute path to partition dir containing hashes.pkl and hashes.invalid :returns...
def consolidate_hashes(partition_dir):
""" Take what's in hashes.pkl and hashes.invalid, combine them, write the result back to hashes.pkl, and clear out hashes.invalid. :param partition_dir: absolute path to partition dir containing hashes.pkl and hashes.invalid :returns: a dict, the suffix hashes (if any), t...
""" hashes_file = join(partition_dir, HASH_FILE) # 'valid' key should always be set by the caller; however, if there's a bug # setting invalid is most safe hashes.setdefault('valid', False) hashes['updated'] = time.time() write_pickle(hashes, hashes_file, partition_dir, PICKLE_PROTOCOL) def ...
84
84
282
8
76
scottwedge/OpenStack-Stein
swift-2.21.0/swift/obj/diskfile.py
Python
consolidate_hashes
consolidate_hashes
377
411
377
377
0d12585663656d565bcbe4212af88fa2b41abd60
bigcode/the-stack
train
938d524ad72e8ce0df4b8aa9
train
function
def write_hashes(partition_dir, hashes): """ Write hashes to hashes.pkl The updated key is added to hashes before it is written. """ hashes_file = join(partition_dir, HASH_FILE) # 'valid' key should always be set by the caller; however, if there's a bug # setting invalid is most safe ha...
def write_hashes(partition_dir, hashes):
""" Write hashes to hashes.pkl The updated key is added to hashes before it is written. """ hashes_file = join(partition_dir, HASH_FILE) # 'valid' key should always be set by the caller; however, if there's a bug # setting invalid is most safe hashes.setdefault('valid', False) hashe...
way in which the # input is invalid. pass # hashes.pkl w/o valid updated key is "valid" but "forever old" hashes.setdefault('valid', True) hashes.setdefault('updated', -1) return hashes def write_hashes(partition_dir, hashes):
64
64
108
10
53
scottwedge/OpenStack-Stein
swift-2.21.0/swift/obj/diskfile.py
Python
write_hashes
write_hashes
363
374
363
363
a29520a2327df25c105c469e9c1523d16f9b2539
bigcode/the-stack
train
81dd2c215581c9230aec2ee8
train
class
class DiskFileReader(BaseDiskFileReader): pass
class DiskFileReader(BaseDiskFileReader):
pass
`create()` method. """ # this is dumb, only tests send in strings timestamp = Timestamp(timestamp) with self.create() as deleter: deleter._extension = '.ts' deleter.put({'X-Timestamp': timestamp.internal}) class DiskFileReader(BaseDiskFileReader):
64
64
12
9
55
scottwedge/OpenStack-Stein
swift-2.21.0/swift/obj/diskfile.py
Python
DiskFileReader
DiskFileReader
2,837
2,838
2,837
2,837
6b8d84a4a6b5a7442d7c23ab438793e9e31bbdbd
bigcode/the-stack
train
ecda52f1933eaeba8570f767
train
function
def extract_policy(obj_path): """ Extracts the policy for an object (based on the name of the objects directory) given the device-relative path to the object. Returns None in the event that the path is malformed in some way. The device-relative path is everything after the mount point; for example:...
def extract_policy(obj_path):
""" Extracts the policy for an object (based on the name of the objects directory) given the device-relative path to the object. Returns None in the event that the path is malformed in some way. The device-relative path is everything after the mount point; for example: /srv/node/d42/objects-5/...
logging.exception(msg, _get_filename(fd)) raise DiskFileXattrNotSupported(e) elif e.errno in (errno.ENOSPC, errno.EDQUOT): msg = "No space left on device for %s" % _get_filename(fd) logging.exception(msg) raise DiskFileNoSpace() raise def extra...
78
78
263
6
71
scottwedge/OpenStack-Stein
swift-2.21.0/swift/obj/diskfile.py
Python
extract_policy
extract_policy
274
301
274
274
53bbcb15ff984d67e4439b81068919e8b63ac9c9
bigcode/the-stack
train
8679552ab56867cc9c663772
train
class
class DiskFile(BaseDiskFile): reader_cls = DiskFileReader writer_cls = DiskFileWriter def _get_ondisk_files(self, files, policy=None): self._ondisk_info = self.manager.get_ondisk_files( files, self._datadir, policy=policy) return self._ondisk_info
class DiskFile(BaseDiskFile):
reader_cls = DiskFileReader writer_cls = DiskFileWriter def _get_ondisk_files(self, files, policy=None): self._ondisk_info = self.manager.get_ondisk_files( files, self._datadir, policy=policy) return self._ondisk_info
Writer(BaseDiskFileWriter): def put(self, metadata): """ Finalize writing the file on disk. :param metadata: dictionary of metadata to be associated with the object """ super(DiskFileWriter, self)._put(metadata, True) class DiskFile(BaseDiskFile):
64
64
73
7
57
scottwedge/OpenStack-Stein
swift-2.21.0/swift/obj/diskfile.py
Python
DiskFile
DiskFile
2,852
2,859
2,852
2,852
235a266662004104f596fcf5d41c7f1473832fd2
bigcode/the-stack
train
20cc844cae486b5cc569936d
train
function
def get_part_path(dev_path, policy, partition): """ Given the device path, policy, and partition, returns the full path to the partition """ return os.path.join(dev_path, get_data_dir(policy), str(partition))
def get_part_path(dev_path, policy, partition):
""" Given the device path, policy, and partition, returns the full path to the partition """ return os.path.join(dev_path, get_data_dir(policy), str(partition))
(target_path) link_exists = (new_stat.st_ino == orig_stat.st_ino) except OSError: pass # if anything goes wrong, try anyway if not link_exists: os.link(target_path, new_target_path) def get_part_path(dev_path, policy, partition):
64
64
53
11
53
scottwedge/OpenStack-Stein
swift-2.21.0/swift/obj/diskfile.py
Python
get_part_path
get_part_path
462
467
462
462
a6693cfe6b2a9264b5c4400f1d46061ad8b74a47
bigcode/the-stack
train
cae5f1081c72406beb1728bb
train
function
def get_async_dir(policy_or_index): ''' Get the async dir for the given policy. :param policy_or_index: ``StoragePolicy`` instance, or an index (string or int); if None, the legacy Policy-0 is assumed. :returns: ``async_pending`` or ``async_pending-<N>`` as appropriate '...
def get_async_dir(policy_or_index):
''' Get the async dir for the given policy. :param policy_or_index: ``StoragePolicy`` instance, or an index (string or int); if None, the legacy Policy-0 is assumed. :returns: ``async_pending`` or ``async_pending-<N>`` as appropriate ''' return get_policy_string(ASYN...
or an index (string or int); if None, the legacy Policy-0 is assumed. :returns: ``objects`` or ``objects-<N>`` as appropriate ''' return get_policy_string(DATADIR_BASE, policy_or_index) def get_async_dir(policy_or_index):
64
64
92
8
56
scottwedge/OpenStack-Stein
swift-2.21.0/swift/obj/diskfile.py
Python
get_async_dir
get_async_dir
112
120
112
112
44f931b8d7a6f6688f1cd4ef6a37628092258644
bigcode/the-stack
train
f56bb19b4c7bfe50d58036ab
train
function
def update_auditor_status(datadir_path, logger, partitions, auditor_type): status = json.dumps({'partitions': partitions}) if six.PY3: status = status.encode('utf8') auditor_status = os.path.join( datadir_path, "auditor_status_%s.json" % auditor_type) try: mtime = os.stat(auditor...
def update_auditor_status(datadir_path, logger, partitions, auditor_type):
status = json.dumps({'partitions': partitions}) if six.PY3: status = status.encode('utf8') auditor_status = os.path.join( datadir_path, "auditor_status_%s.json" % auditor_type) try: mtime = os.stat(auditor_status).st_mtime except OSError: mtime = 0 recently_update...
logger.warning(_('Loading JSON from %(auditor_status)s failed' ' (%(err)s)') % {'auditor_status': auditor_status, 'err': e}) return listdir(datadir_path) return status['partitions'] def update_auditor_status(datadir_path, logger, partitions, auditor_type):
68
68
228
17
51
scottwedge/OpenStack-Stein
swift-2.21.0/swift/obj/diskfile.py
Python
update_auditor_status
update_auditor_status
582
604
582
582
c5bc15b671ee14e61d7a1cd1fa2c65776161f468
bigcode/the-stack
train
7aa8fc6f30c8716334de24cd
train
function
def object_audit_location_generator(devices, datadir, mount_check=True, logger=None, device_dirs=None, auditor_type="ALL"): """ Given a devices path (e.g. "/srv/node"), yield an AuditLocation for all objects stored under that directory ...
def object_audit_location_generator(devices, datadir, mount_check=True, logger=None, device_dirs=None, auditor_type="ALL"):
""" Given a devices path (e.g. "/srv/node"), yield an AuditLocation for all objects stored under that directory for the given datadir (policy), if device_dirs isn't set. If device_dirs is set, only yield AuditLocation for the objects under the entries in device_dirs. The AuditLocation only know...
policy, partition): """ Given the device path, policy, and partition, returns the full path to the partition """ return os.path.join(dev_path, get_data_dir(policy), str(partition)) class AuditLocation(object): """ Represents an object location to be audited. Other than being a bucket...
176
176
588
30
146
scottwedge/OpenStack-Stein
swift-2.21.0/swift/obj/diskfile.py
Python
object_audit_location_generator
object_audit_location_generator
486
553
486
488
dcad7847fb4cbe5a456d7c1ec57b2b9bd8b44d9b
bigcode/the-stack
train
3627b265188304f9ca2a16d8
train
function
def strip_self(f): """ Wrapper to attach module level functions to base class. """ def wrapper(self, *args, **kwargs): return f(*args, **kwargs) return wrapper
def strip_self(f):
""" Wrapper to attach module level functions to base class. """ def wrapper(self, *args, **kwargs): return f(*args, **kwargs) return wrapper
(devices) for device in device_dirs: datadir_path = os.path.join(devices, device, datadir) auditor_status = os.path.join( datadir_path, "auditor_status_%s.json" % auditor_type) remove_file(auditor_status) def strip_self(f):
64
64
44
5
59
scottwedge/OpenStack-Stein
swift-2.21.0/swift/obj/diskfile.py
Python
strip_self
strip_self
616
622
616
616
22d88287824f81da96c7d25685bcb1b7cd4be9d6
bigcode/the-stack
train
33bba29ddab1df773562a37b
train
function
def write_metadata(fd, metadata, xattr_size=65536): """ Helper function to write pickled metadata for an object file. :param fd: file descriptor or filename to write the metadata :param metadata: metadata to write """ metastr = pickle.dumps(_encode_metadata(metadata), PICKLE_PROTOCOL) metas...
def write_metadata(fd, metadata, xattr_size=65536):
""" Helper function to write pickled metadata for an object file. :param fd: file descriptor or filename to write the metadata :param metadata: metadata to write """ metastr = pickle.dumps(_encode_metadata(metadata), PICKLE_PROTOCOL) metastr_md5 = md5(metastr).hexdigest().encode('ascii') ...
8 encoded when written, but have not always been # (see https://bugs.launchpad.net/swift/+bug/1678018) so encode them again # when read if six.PY2: metadata = pickle.loads(metadata) else: metadata = pickle.loads(metadata, encoding='bytes') return _decode_metadata(metadata) def write_...
89
89
299
14
75
scottwedge/OpenStack-Stein
swift-2.21.0/swift/obj/diskfile.py
Python
write_metadata
write_metadata
243
271
243
243
02977e823876336b97c4a93c6c2bb59e6bc8afca
bigcode/the-stack
train
74cae01baf9add576e1490ed
train
class
class BaseDiskFile(object): """ Manage object files. This specific implementation manages object files on a disk formatted with a POSIX-compliant file system that supports extended attributes as metadata on a file or directory. .. note:: The arguments to the constructor are considered...
class BaseDiskFile(object):
""" Manage object files. This specific implementation manages object files on a disk formatted with a POSIX-compliant file system that supports extended attributes as metadata on a file or directory. .. note:: The arguments to the constructor are considered implementation spec...
does not match metadata: %s" % ( self._bytes_read, self._obj_size)) elif self._md5_of_sent_bytes and \ self._etag != self._md5_of_sent_bytes: self._quarantine( "ETag %s and file's md5 %s do not match" % ( self._etag, self._md5_...
256
256
5,388
6
250
scottwedge/OpenStack-Stein
swift-2.21.0/swift/obj/diskfile.py
Python
BaseDiskFile
BaseDiskFile
2,197
2,834
2,197
2,197
32755322acbbc682fcb174c8b332a0b85341d949
bigcode/the-stack
train
5f41e1b58d3462d684a5720d
train
class
class BaseDiskFileReader(object): """ Encapsulation of the WSGI read context for servicing GET REST API requests. Serves as the context manager object for the :class:`swift.obj.diskfile.DiskFile` class's :func:`swift.obj.diskfile.DiskFile.reader` method. .. note:: The quarantining beha...
class BaseDiskFileReader(object):
""" Encapsulation of the WSGI read context for servicing GET REST API requests. Serves as the context manager object for the :class:`swift.obj.diskfile.DiskFile` class's :func:`swift.obj.diskfile.DiskFile.reader` method. .. note:: The quarantining behavior of this method is considered ...
an additional cleanup of the relative dirs has to be done. Otherwise there might be some unused files left if a PUT or DELETE is done in the meantime :param cur_path: current full path to an object file :param new_path: recomputed path to an object file, based on the ...
256
256
2,675
7
249
scottwedge/OpenStack-Stein
swift-2.21.0/swift/obj/diskfile.py
Python
BaseDiskFileReader
BaseDiskFileReader
1,890
2,194
1,890
1,890
6aa791f048415f493dfba875b818a4a225eed0d0
bigcode/the-stack
train
3fee61c05031ecba79ca38a2
train
function
async def load_agent( model_path: Optional[Text] = None, model_server: Optional[EndpointConfig] = None, remote_storage: Optional[Text] = None, interpreter: Optional[NaturalLanguageInterpreter] = None, generator: Union[EndpointConfig, NaturalLanguageGenerator] = None, tracker_store: Optional[Trac...
async def load_agent( model_path: Optional[Text] = None, model_server: Optional[EndpointConfig] = None, remote_storage: Optional[Text] = None, interpreter: Optional[NaturalLanguageInterpreter] = None, generator: Union[EndpointConfig, NaturalLanguageGenerator] = None, tracker_store: Optional[Trac...
try: if model_server is not None: return await load_from_server( Agent( interpreter=interpreter, generator=generator, tracker_store=tracker_store, lock_store=lock_store, action_end...
, ) async def load_agent( model_path: Optional[Text] = None, model_server: Optional[EndpointConfig] = None, remote_storage: Optional[Text] = None, interpreter: Optional[NaturalLanguageInterpreter] = None, generator: Union[EndpointConfig, NaturalLanguageGenerator] = None, tracker_store: Optio...
106
106
356
103
3
cianclarke/rasa
rasa/core/agent.py
Python
load_agent
load_agent
226
281
226
235
67516ae44a98035d930f092c9adb4952f3957bba
bigcode/the-stack
train
ac9ce2e3b49c00dd4df2f46b
train
function
async def load_from_server(agent: "Agent", model_server: EndpointConfig) -> "Agent": """Load a persisted model from a server.""" # We are going to pull the model once first, and then schedule a recurring # job. the benefit of this approach is that we can be sure that there # is a model after this funct...
async def load_from_server(agent: "Agent", model_server: EndpointConfig) -> "Agent":
"""Load a persisted model from a server.""" # We are going to pull the model once first, and then schedule a recurring # job. the benefit of this approach is that we can be sure that there # is a model after this function completes -> allows to do proper # "is alive" check on a startup server's `/s...
_model, get_model, ) from rasa.nlu.utils import is_url from rasa.utils.common import update_sanic_log_level from rasa.utils.endpoints import EndpointConfig logger = logging.getLogger(__name__) async def load_from_server(agent: "Agent", model_server: EndpointConfig) -> "Agent":
64
64
206
20
44
cianclarke/rasa
rasa/core/agent.py
Python
load_from_server
load_from_server
55
72
55
55
c5125afa43730e208e81a0c7c39032314048c23e
bigcode/the-stack
train
22d61f8799129943c6cf036e
train
function
async def _pull_model_and_fingerprint( model_server: EndpointConfig, fingerprint: Optional[Text] ) -> Optional[Tuple[Text, Text]]: """Queries the model server. Returns the temporary model directory and value of the response's <ETag> header which contains the model hash. Returns `None` if no new model i...
async def _pull_model_and_fingerprint( model_server: EndpointConfig, fingerprint: Optional[Text] ) -> Optional[Tuple[Text, Text]]:
"""Queries the model server. Returns the temporary model directory and value of the response's <ETag> header which contains the model hash. Returns `None` if no new model is found. """ headers = {"If-None-Match": fingerprint} logger.debug(f"Requesting model from server {model_server.url}...")...
update the passed agent.""" if not is_url(model_server.url): raise aiohttp.InvalidURL(model_server.url) model_directory_and_fingerprint = await _pull_model_and_fingerprint( model_server, agent.fingerprint ) if model_directory_and_fingerprint: model_directory, new_model_fingerp...
139
140
469
32
107
cianclarke/rasa
rasa/core/agent.py
Python
_pull_model_and_fingerprint
_pull_model_and_fingerprint
131
196
131
133
76ca946c365cb8429f10bbbdae436880e0ec80a4
bigcode/the-stack
train
fa612c153b3935e6c8ac4547
train
function
async def schedule_model_pulling( model_server: EndpointConfig, wait_time_between_pulls: int, agent: "Agent" ): (await jobs.scheduler()).add_job( _run_model_pulling_worker, "interval", seconds=wait_time_between_pulls, args=[model_server, agent], id="pull-model-from-server...
async def schedule_model_pulling( model_server: EndpointConfig, wait_time_between_pulls: int, agent: "Agent" ):
(await jobs.scheduler()).add_job( _run_model_pulling_worker, "interval", seconds=wait_time_between_pulls, args=[model_server, agent], id="pull-model-from-server", replace_existing=True, )
logger.warning("Stopping model pulling (cancelled).") except Exception: logger.exception( "An exception was raised while fetching a model. Continuing anyways..." ) async def schedule_model_pulling( model_server: EndpointConfig, wait_time_between_pulls: int, agent: "Agent" ):
64
64
81
28
36
cianclarke/rasa
rasa/core/agent.py
Python
schedule_model_pulling
schedule_model_pulling
213
223
213
215
41737ce77e71df9c52c1d973c34c44054328d040
bigcode/the-stack
train
9ce4eb2c3bd74aef19ab7cd5
train
function
async def _run_model_pulling_worker( model_server: EndpointConfig, agent: "Agent" ) -> None: # noinspection PyBroadException try: await _update_model_from_server(model_server, agent) except CancelledError: logger.warning("Stopping model pulling (cancelled).") except Exception: ...
async def _run_model_pulling_worker( model_server: EndpointConfig, agent: "Agent" ) -> None: # noinspection PyBroadException
try: await _update_model_from_server(model_server, agent) except CancelledError: logger.warning("Stopping model pulling (cancelled).") except Exception: logger.exception( "An exception was raised while fetching a model. Continuing anyways..." )
server, but " "couldn't reach server. We'll retry later... " "Error: {}.".format(e) ) return None async def _run_model_pulling_worker( model_server: EndpointConfig, agent: "Agent" ) -> None: # noinspection PyBroadException
64
64
90
33
30
cianclarke/rasa
rasa/core/agent.py
Python
_run_model_pulling_worker
_run_model_pulling_worker
199
210
199
202
8843253c7f0fbc09973a3762bb34977678c9ea17
bigcode/the-stack
train
61b7f724f68e55e329f8b8a0
train
class
class Agent: """The Agent class provides a convenient interface for the most important Rasa functionality. This includes training, handling messages, loading a dialogue model, getting the next action, and handling a channel.""" def __init__( self, domain: Union[Text, Domain, Non...
class Agent:
"""The Agent class provides a convenient interface for the most important Rasa functionality. This includes training, handling messages, loading a dialogue model, getting the next action, and handling a channel.""" def __init__( self, domain: Union[Text, Domain, None] = None, ...
try: if model_server is not None: return await load_from_server( Agent( interpreter=interpreter, generator=generator, tracker_store=tracker_store, lock_store=lock_store, action_end...
256
256
5,048
3
252
cianclarke/rasa
rasa/core/agent.py
Python
Agent
Agent
284
965
284
284
70b627beefd9032560b21d60c41b5aee51d68bc3
bigcode/the-stack
train
b4857bcd420f08fc21b1b0b8
train
function
async def _update_model_from_server( model_server: EndpointConfig, agent: "Agent" ) -> None: """Load a zipped Rasa Core model from a URL and update the passed agent.""" if not is_url(model_server.url): raise aiohttp.InvalidURL(model_server.url) model_directory_and_fingerprint = await _pull_mod...
async def _update_model_from_server( model_server: EndpointConfig, agent: "Agent" ) -> None:
"""Load a zipped Rasa Core model from a URL and update the passed agent.""" if not is_url(model_server.url): raise aiohttp.InvalidURL(model_server.url) model_directory_and_fingerprint = await _pull_model_and_fingerprint( model_server, agent.fingerprint ) if model_directory_and_fing...
.debug("Finished updating agent to new model.") except Exception: logger.exception( "Failed to load policy and update agent. " "The previous model will stay loaded instead." ) async def _update_model_from_server( model_server: EndpointConfig, agent: "Agent" ) -> None:
64
64
144
24
40
cianclarke/rasa
rasa/core/agent.py
Python
_update_model_from_server
_update_model_from_server
113
128
113
115
bf491f02493fdfe0fcdc36a5a6e90f002f536c31
bigcode/the-stack
train
9cfdf9771668793584d767ef
train
function
def _load_and_set_updated_model( agent: "Agent", model_directory: Text, fingerprint: Text ): """Load the persisted model into memory and set the model on the agent.""" logger.debug(f"Found new model with fingerprint {fingerprint}. Loading...") core_path, nlu_path = get_model_subdirectories(model_direc...
def _load_and_set_updated_model( agent: "Agent", model_directory: Text, fingerprint: Text ):
"""Load the persisted model into memory and set the model on the agent.""" logger.debug(f"Found new model with fingerprint {fingerprint}. Loading...") core_path, nlu_path = get_model_subdirectories(model_directory) if nlu_path: from rasa.core.interpreter import RasaNLUInterpreter int...
_pulls", 100) if wait_time_between_pulls: # continuously pull the model every `wait_time_between_pulls` seconds await schedule_model_pulling(model_server, int(wait_time_between_pulls), agent) return agent def _load_and_set_updated_model( agent: "Agent", model_directory: Text, fingerprint: ...
76
76
254
24
51
cianclarke/rasa
rasa/core/agent.py
Python
_load_and_set_updated_model
_load_and_set_updated_model
75
110
75
77
c15fc522183389ab47b4712558fb1b1f97a9454e
bigcode/the-stack
train
9c568a80bb69ab8b149d2744
train
function
def format_progress_for_status(label: str, status: FunctionStatus): return format_progress(label, counts[status], code_size[status])
def format_progress_for_status(label: str, status: FunctionStatus):
return format_progress(label, counts[status], code_size[status])
, 3) size_percentage = round(100 * size / code_size_total, 3) return f"{num:>7d} {label}{Fore.RESET} ({percentage}% | size: {size_percentage}%)" def format_progress_for_status(label: str, status: FunctionStatus):
64
64
29
14
50
leoetlino/nx-decomp-tools
progress.py
Python
format_progress_for_status
format_progress_for_status
58
59
58
58
c7fa207c307aa457dabdfa8396e8175934ae17ee
bigcode/the-stack
train
07f60cfeb30bfa7faf18a310
train
function
def format_progress(label: str, num: int, size: int): percentage = round(100 * num / num_total, 3) size_percentage = round(100 * size / code_size_total, 3) return f"{num:>7d} {label}{Fore.RESET} ({percentage}% | size: {size_percentage}%)"
def format_progress(label: str, num: int, size: int):
percentage = round(100 * num / num_total, 3) size_percentage = round(100 * size / code_size_total, 3) return f"{num:>7d} {label}{Fore.RESET} ({percentage}% | size: {size_percentage}%)"
info.status == FunctionStatus.Wip: print( f"{Back.RED}{Style.BRIGHT}{Fore.WHITE} WIP {Style.RESET_ALL} {utils.format_symbol_name(info.decomp_name)}{Style.RESET_ALL}") def format_progress(label: str, num: int, size: int):
63
64
76
15
48
leoetlino/nx-decomp-tools
progress.py
Python
format_progress
format_progress
52
55
52
52
6d6b1aa9ad6abfcd44472ec273a5edd87bb609eb
bigcode/the-stack
train
295fa1a190b5b3b692f92867
train
function
def httpbin(*suffix): """Returns url for HTTPBIN resource.""" return HTTPBIN_URL + '/'.join(suffix)
def httpbin(*suffix):
"""Returns url for HTTPBIN resource.""" return HTTPBIN_URL + '/'.join(suffix)
post, head, put from requests.auth import HTTPBasicAuth, HTTPDigestAuth if 'HTTPBIN_URL' not in os.environ: os.environ['HTTPBIN_URL'] = 'http://httpbin.org/' HTTPBIN_URL = os.environ.get('HTTPBIN_URL') def httpbin(*suffix):
64
64
27
6
58
tzuryby/requests
tests/test_requests.py
Python
httpbin
httpbin
29
31
29
29
40f6d1c5d7681c401c5bb2fcbc46bead80628224
bigcode/the-stack
train
691949775b404200913ad1d0
train
class
class TestBaseMixin(object): def assertCookieHas(self, cookie, **kwargs): """Assert that a cookie has various specified properties.""" for attr, expected_value in kwargs.items(): cookie_attr = getattr(cookie, attr) message = 'Failed comparison for %s: %s != %s' % (attr, cook...
class TestBaseMixin(object):
def assertCookieHas(self, cookie, **kwargs): """Assert that a cookie has various specified properties.""" for attr, expected_value in kwargs.items(): cookie_attr = getattr(cookie, attr) message = 'Failed comparison for %s: %s != %s' % (attr, cookie_attr, expected_value) ...
Up(self): global _httpbin if (not 'HTTPBIN_URL' in os.environ) and not _httpbin: # c = envoy.connect('httpbin %s' % (PORT)) # time.sleep(1) _httpbin = True class TestBaseMixin(object):
64
64
86
6
57
tzuryby/requests
tests/test_requests.py
Python
TestBaseMixin
TestBaseMixin
54
61
54
55
cf41ff66b44dfc62bcad3c3d1fef788376c99801
bigcode/the-stack
train