id
int64 0
843k
| repository_name
stringlengths 7
55
| file_path
stringlengths 9
332
| class_name
stringlengths 3
290
| human_written_code
stringlengths 12
4.36M
| class_skeleton
stringlengths 19
2.2M
| total_program_units
int64 1
9.57k
| total_doc_str
int64 0
4.2k
| AvgCountLine
float64 0
7.89k
| AvgCountLineBlank
float64 0
300
| AvgCountLineCode
float64 0
7.89k
| AvgCountLineComment
float64 0
7.89k
| AvgCyclomatic
float64 0
130
| CommentToCodeRatio
float64 0
176
| CountClassBase
float64 0
48
| CountClassCoupled
float64 0
589
| CountClassCoupledModified
float64 0
581
| CountClassDerived
float64 0
5.37k
| CountDeclInstanceMethod
float64 0
4.2k
| CountDeclInstanceVariable
float64 0
299
| CountDeclMethod
float64 0
4.2k
| CountDeclMethodAll
float64 0
4.2k
| CountLine
float64 1
115k
| CountLineBlank
float64 0
9.01k
| CountLineCode
float64 0
94.4k
| CountLineCodeDecl
float64 0
46.1k
| CountLineCodeExe
float64 0
91.3k
| CountLineComment
float64 0
27k
| CountStmt
float64 1
93.2k
| CountStmtDecl
float64 0
46.1k
| CountStmtExe
float64 0
90.2k
| MaxCyclomatic
float64 0
759
| MaxInheritanceTree
float64 0
16
| MaxNesting
float64 0
34
| SumCyclomatic
float64 0
6k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1,000 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_fields.py
|
tests.test_fields.delimited_list_schema.DelimitedListSchema
|
class DelimitedListSchema(Schema):
ids = DelimitedList(fields.String, required=True)
|
class DelimitedListSchema(Schema):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 1 | 0 | 0 |
1,001 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_fields.py
|
tests.test_fields.delimited_list_as_string_schema.DelimitedListAsStringSchema
|
class DelimitedListAsStringSchema(Schema):
ids = DelimitedList(fields.String, as_string=True, required=True)
|
class DelimitedListAsStringSchema(Schema):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 1 | 0 | 0 |
1,002 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_decorators.py
|
tests.test_decorators.routes.WidgetView
|
class WidgetView(ModelView):
model = models["widget"]
@get_item_or_404
def get(self, item):
return str(item.id)
@get_item_or_404(create_transient_stub=True)
def put(self, item):
return str(item.id)
@get_item_or_404(with_for_update=True)
def patch(self, item):
return str(item.id)
|
class WidgetView(ModelView):
@get_item_or_404
def get(self, item):
pass
@get_item_or_404(create_transient_stub=True)
def put(self, item):
pass
@get_item_or_404(with_for_update=True)
def patch(self, item):
pass
| 7 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 3 | 0 | 3 | 58 | 14 | 3 | 11 | 8 | 4 | 0 | 8 | 5 | 4 | 1 | 3 | 0 | 3 |
1,003 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_composite_id.py
|
tests.test_composite_id.schemas.WidgetSchema
|
class WidgetSchema(Schema):
id_1 = fields.Integer(as_string=True)
id_2 = fields.Integer(as_string=True)
name = fields.String(required=True)
|
class WidgetSchema(Schema):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 4 | 0 | 4 | 4 | 3 | 0 | 4 | 4 | 3 | 0 | 1 | 0 | 0 |
1,004 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_composite_id.py
|
tests.test_composite_id.routes.WidgetViewBase
|
class WidgetViewBase(GenericModelView):
model = models["widget"]
schema = schemas["widget"]
id_fields = ("id_1", "id_2")
|
class WidgetViewBase(GenericModelView):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 | 0 | 0 | 0 | 61 | 4 | 0 | 4 | 4 | 3 | 0 | 4 | 4 | 3 | 0 | 4 | 0 | 0 |
1,005 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_composite_id.py
|
tests.test_composite_id.routes.WidgetView
|
class WidgetView(WidgetViewBase):
def get(self, id_1, id_2):
return self.retrieve((id_1, id_2))
def patch(self, id_1, id_2):
return self.update((id_1, id_2), partial=True)
def delete(self, id_1, id_2):
return self.destroy((id_1, id_2))
|
class WidgetView(WidgetViewBase):
def get(self, id_1, id_2):
pass
def patch(self, id_1, id_2):
pass
def delete(self, id_1, id_2):
pass
| 4 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 3 | 0 | 3 | 64 | 9 | 2 | 7 | 4 | 3 | 0 | 7 | 4 | 3 | 1 | 5 | 0 | 3 |
1,006 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_composite_id.py
|
tests.test_composite_id.models.Widget
|
class Widget(db.Model):
__tablename__ = "widgets"
id_1 = Column(Integer, primary_key=True)
id_2 = Column(Integer, primary_key=True)
name = Column(String, nullable=False)
|
class Widget(db.Model):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 | 1 | 5 | 5 | 4 | 0 | 5 | 5 | 4 | 0 | 1 | 0 | 0 |
1,007 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_basic.py
|
tests.test_basic.routes.WidgetView
|
class WidgetView(WidgetViewBase):
def get(self, id):
return self.retrieve(id)
def put(self, id):
return self.upsert(id)
def patch(self, id):
return self.update(id, partial=True)
def delete(self, id):
return self.destroy(id)
|
class WidgetView(WidgetViewBase):
def get(self, id):
pass
def put(self, id):
pass
def patch(self, id):
pass
def delete(self, id):
pass
| 5 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 4 | 0 | 4 | 65 | 12 | 3 | 9 | 5 | 4 | 0 | 9 | 5 | 4 | 1 | 5 | 0 | 4 |
1,008 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_basic.py
|
tests.test_basic.routes.WidgetListView
|
class WidgetListView(WidgetViewBase):
def get(self):
return self.list()
def post(self):
return self.create()
|
class WidgetListView(WidgetViewBase):
def get(self):
pass
def post(self):
pass
| 3 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 63 | 6 | 1 | 5 | 3 | 2 | 0 | 5 | 3 | 2 | 1 | 5 | 0 | 2 |
1,009 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_auth.py
|
tests.test_auth.schemas.WidgetSchema
|
class WidgetSchema(Schema):
id = fields.Integer(as_string=True)
owner_id = fields.String()
name = fields.String()
|
class WidgetSchema(Schema):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 4 | 0 | 4 | 3 | 3 | 0 | 4 | 3 | 3 | 0 | 1 | 0 | 0 |
1,010 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_auth.py
|
tests.test_auth.routes.WidgetViewBase
|
class WidgetViewBase(GenericModelView):
model = models["widget"]
schema = schemas["widget"]
authentication = auth["authentication"]
authorization = auth["authorization"]
|
class WidgetViewBase(GenericModelView):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 7 | 0 | 0 | 0 | 61 | 6 | 1 | 5 | 5 | 4 | 0 | 5 | 5 | 4 | 0 | 4 | 0 | 0 |
1,011 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_fields.py
|
tests.test_fields.single_schema.SingleSchema
|
class SingleSchema(Schema):
child = RelatedItem(related_schema_class, required=True)
|
class SingleSchema(Schema):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 1 | 0 | 0 |
1,012 |
4Catalyzer/flask-resty
|
4Catalyzer_flask-resty/flask_resty/api.py
|
flask_resty.api.FlaskRestyState
|
class FlaskRestyState:
def __init__(self, api):
self.api = api
|
class FlaskRestyState:
def __init__(self, api):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 3 | 0 | 3 | 3 | 1 | 0 | 3 | 3 | 1 | 1 | 0 | 0 | 1 |
1,013 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_auth.py
|
tests.test_auth.routes.WidgetCreateTransientStubView
|
class WidgetCreateTransientStubView(WidgetViewBase):
def get(self, id):
return self.retrieve(id, create_transient_stub=True)
def create_stub_item(self, id):
return self.create_item(
{"id": id, "owner_id": flask.request.args["owner_id"]}
)
|
class WidgetCreateTransientStubView(WidgetViewBase):
def get(self, id):
pass
def create_stub_item(self, id):
pass
| 3 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 63 | 8 | 1 | 7 | 3 | 4 | 0 | 5 | 3 | 2 | 1 | 5 | 0 | 2 |
1,014 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_auth.py
|
tests.test_auth.routes.WidgetBearerWithFallbackView
|
class WidgetBearerWithFallbackView(WidgetViewBase):
authentication = auth["bearer_with_fallback_authentication"]
authorization = HasAnyCredentialsAuthorization()
def get(self, id):
return self.retrieve(id)
|
class WidgetBearerWithFallbackView(WidgetViewBase):
def get(self, id):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 62 | 6 | 1 | 5 | 4 | 3 | 0 | 5 | 4 | 3 | 1 | 5 | 0 | 1 |
1,015 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_auth.py
|
tests.test_auth.routes.WidgetBearerView
|
class WidgetBearerView(WidgetViewBase):
authentication = HeaderAuthentication()
authorization = HasAnyCredentialsAuthorization()
def get(self, id):
return self.retrieve(id)
|
class WidgetBearerView(WidgetViewBase):
def get(self, id):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 62 | 6 | 1 | 5 | 4 | 3 | 0 | 5 | 4 | 3 | 1 | 5 | 0 | 1 |
1,016 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_auth.py
|
tests.test_auth.routes.WidgetAnyCredentialsView
|
class WidgetAnyCredentialsView(WidgetViewBase):
authorization = HasAnyCredentialsAuthorization()
def get(self, id):
return self.retrieve(id)
|
class WidgetAnyCredentialsView(WidgetViewBase):
def get(self, id):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 62 | 5 | 1 | 4 | 3 | 2 | 0 | 4 | 3 | 2 | 1 | 5 | 0 | 1 |
1,017 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_auth.py
|
tests.test_auth.models.Widget
|
class Widget(db.Model):
__tablename__ = "widgets"
id = Column(Integer, primary_key=True)
owner_id = Column(String)
name = Column(String)
|
class Widget(db.Model):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 | 1 | 5 | 4 | 4 | 0 | 5 | 4 | 4 | 0 | 1 | 0 | 0 |
1,018 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_auth.py
|
tests.test_auth.auth.UserAuthorization
|
class UserAuthorization(
AuthorizeModifyMixin, HasCredentialsAuthorizationBase
):
def filter_query(self, query, view):
return query.filter(
(view.model.owner_id == self.get_request_credentials())
| (view.model.owner_id == sql.null())
)
def authorize_create_item(self, item):
super().authorize_create_item(item)
if item.name == "Updated":
raise ApiError(403, {"code": "invalid_name"})
def authorize_modify_item(self, item, action):
if item.owner_id != self.get_request_credentials():
raise ApiError(403, {"code": "invalid_user"})
|
class UserAuthorization(
AuthorizeModifyMixin, HasCredentialsAuthorizationBase
):
def filter_query(self, query, view):
pass
def authorize_create_item(self, item):
pass
def authorize_modify_item(self, item, action):
pass
| 4 | 0 | 4 | 0 | 4 | 0 | 2 | 0 | 2 | 2 | 1 | 0 | 3 | 0 | 3 | 16 | 18 | 3 | 15 | 6 | 9 | 0 | 10 | 4 | 6 | 2 | 2 | 1 | 5 |
1,019 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_auth.py
|
tests.test_auth.auth.FakeAuthentication
|
class FakeAuthentication(AuthenticationBase):
def get_request_credentials(self):
return flask.request.args.get("user_id")
|
class FakeAuthentication(AuthenticationBase):
def get_request_credentials(self):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 3 | 3 | 0 | 3 | 2 | 1 | 0 | 3 | 2 | 1 | 1 | 1 | 0 | 1 |
1,020 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_auth.py
|
tests.test_auth.auth.BearerWithFallbackAuthentication
|
class BearerWithFallbackAuthentication(HeaderAuthentication):
credentials_arg = "secret"
|
class BearerWithFallbackAuthentication(HeaderAuthentication):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 7 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 3 | 0 | 0 |
1,021 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_args.py
|
tests.test_args.views.NameView
|
class NameView(ApiView):
args_schema = schemas["name"]
def get(self):
return self.make_response(self.request_args["name"])
|
class NameView(ApiView):
def get(self):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 25 | 5 | 1 | 4 | 3 | 2 | 0 | 4 | 3 | 2 | 1 | 2 | 0 | 1 |
1,022 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_args.py
|
tests.test_args.views.NameListView
|
class NameListView(ApiView):
args_schema = schemas["name_list"]
def get(self):
return self.make_response(self.request_args["names"])
|
class NameListView(ApiView):
def get(self):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 25 | 5 | 1 | 4 | 3 | 2 | 0 | 4 | 3 | 2 | 1 | 2 | 0 | 1 |
1,023 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_args.py
|
tests.test_args.views.NameDelimitedListView
|
class NameDelimitedListView(ApiView):
args_schema = schemas["name_delimited_list"]
def get(self):
return self.make_response(self.request_args["names"])
|
class NameDelimitedListView(ApiView):
def get(self):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 25 | 5 | 1 | 4 | 3 | 2 | 0 | 4 | 3 | 2 | 1 | 2 | 0 | 1 |
1,024 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_args.py
|
tests.test_args.views.NameDefaultView
|
class NameDefaultView(ApiView):
args_schema = schemas["name_default"]
def get(self):
return self.make_response(self.request_args["name"])
|
class NameDefaultView(ApiView):
def get(self):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 25 | 5 | 1 | 4 | 3 | 2 | 0 | 4 | 3 | 2 | 1 | 2 | 0 | 1 |
1,025 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_args.py
|
tests.test_args.schemas.NameSchema
|
class NameSchema(Schema):
name = fields.String(required=True)
|
class NameSchema(Schema):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 1 | 0 | 0 |
1,026 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_auth.py
|
tests.test_auth.routes.WidgetUpsertView
|
class WidgetUpsertView(WidgetViewBase):
def get(self, id):
return self.retrieve(id, create_transient_stub=True)
def put(self, id):
return self.upsert(id)
def create_stub_item(self, id):
return self.create_item(
{"id": id, "owner_id": flask.request.args["owner_id"]}
)
def get_location(self, item):
return None
|
class WidgetUpsertView(WidgetViewBase):
def get(self, id):
pass
def put(self, id):
pass
def create_stub_item(self, id):
pass
def get_location(self, item):
pass
| 5 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 4 | 0 | 4 | 65 | 14 | 3 | 11 | 5 | 6 | 0 | 9 | 5 | 4 | 1 | 5 | 0 | 4 |
1,027 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_filtering.py
|
tests.test_filtering.models.Widget
|
class Widget(db.Model):
__tablename__ = "widgets"
id = Column(Integer, primary_key=True)
color = Column(String)
size = Column(Integer)
|
class Widget(db.Model):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 | 1 | 5 | 4 | 4 | 0 | 5 | 4 | 4 | 0 | 1 | 0 | 0 |
1,028 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_filtering.py
|
tests.test_filtering.routes.WidgetColorCustomListView
|
class WidgetColorCustomListView(WidgetViewBase):
filtering = Filtering(color=filter_fields["color_custom"])
def get(self):
return self.list()
|
class WidgetColorCustomListView(WidgetViewBase):
def get(self):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 62 | 5 | 1 | 4 | 3 | 2 | 0 | 4 | 3 | 2 | 1 | 5 | 0 | 1 |
1,029 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_filtering.py
|
tests.test_filtering.routes.WidgetDefaultFiltersView
|
class WidgetDefaultFiltersView(WidgetViewBase):
filtering = Filtering(
color=ModelFilter(
fields.String(**{LOAD_DEFAULT_KWARG: "red"}),
lambda model, value: model.color == value,
),
size=ColumnFilter(operator.eq, missing=1),
)
def get(self):
return self.list()
|
class WidgetDefaultFiltersView(WidgetViewBase):
def get(self):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 62 | 11 | 1 | 10 | 3 | 8 | 0 | 4 | 3 | 2 | 1 | 5 | 0 | 1 |
1,030 |
4Catalyzer/flask-resty
|
4Catalyzer_flask-resty/example/views.py
|
example.views.BookView
|
class BookView(BookViewBase):
def get(self, id):
return self.retrieve(id)
def patch(self, id):
return self.update(id, partial=True)
def delete(self, id):
return self.destroy(id)
|
class BookView(BookViewBase):
def get(self, id):
pass
def patch(self, id):
pass
def delete(self, id):
pass
| 4 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 3 | 0 | 3 | 64 | 9 | 2 | 7 | 4 | 3 | 0 | 7 | 4 | 3 | 1 | 5 | 0 | 3 |
1,031 |
4Catalyzer/flask-resty
|
4Catalyzer_flask-resty/example/views.py
|
example.views.BookListView
|
class BookListView(BookViewBase):
def get(self):
return self.list()
def post(self):
return self.create()
|
class BookListView(BookViewBase):
def get(self):
pass
def post(self):
pass
| 3 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 63 | 6 | 1 | 5 | 3 | 2 | 0 | 5 | 3 | 2 | 1 | 5 | 0 | 2 |
1,032 |
4Catalyzer/flask-resty
|
4Catalyzer_flask-resty/example/views.py
|
example.views.AuthorViewBase
|
class AuthorViewBase(GenericModelView):
model = models.Author
schema = schemas.AuthorSchema()
authentication = NoOpAuthentication()
authorization = NoOpAuthorization()
pagination = PagePagination(page_size=10)
sorting = Sorting("created_at", default="-created_at")
|
class AuthorViewBase(GenericModelView):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 | 0 | 0 | 0 | 61 | 9 | 2 | 7 | 7 | 6 | 0 | 7 | 7 | 6 | 0 | 4 | 0 | 0 |
1,033 |
4Catalyzer/flask-resty
|
4Catalyzer_flask-resty/example/views.py
|
example.views.AuthorView
|
class AuthorView(AuthorViewBase):
def get(self, id):
return self.retrieve(id)
def patch(self, id):
return self.update(id, partial=True)
def delete(self, id):
return self.destroy(id)
|
class AuthorView(AuthorViewBase):
def get(self, id):
pass
def patch(self, id):
pass
def delete(self, id):
pass
| 4 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 3 | 0 | 3 | 64 | 9 | 2 | 7 | 4 | 3 | 0 | 7 | 4 | 3 | 1 | 5 | 0 | 3 |
1,034 |
4Catalyzer/flask-resty
|
4Catalyzer_flask-resty/example/views.py
|
example.views.AuthorListView
|
class AuthorListView(AuthorViewBase):
def get(self):
return self.list()
def post(self):
return self.create()
|
class AuthorListView(AuthorViewBase):
def get(self):
pass
def post(self):
pass
| 3 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 63 | 6 | 1 | 5 | 3 | 2 | 0 | 5 | 3 | 2 | 1 | 5 | 0 | 2 |
1,035 |
4Catalyzer/flask-resty
|
4Catalyzer_flask-resty/example/schemas.py
|
example.schemas.BookSchema
|
class BookSchema(Schema):
id = fields.Int(dump_only=True)
title = fields.String(required=True)
author_id = fields.Int(required=True)
published_at = fields.DateTime(required=True)
created_at = fields.DateTime(dump_only=True)
|
class BookSchema(Schema):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 | 0 | 6 | 5 | 5 | 0 | 6 | 5 | 5 | 0 | 1 | 0 | 0 |
1,036 |
4Catalyzer/flask-resty
|
4Catalyzer_flask-resty/example/schemas.py
|
example.schemas.AuthorSchema
|
class AuthorSchema(Schema):
id = fields.Int(dump_only=True)
name = fields.String(required=True)
created_at = fields.DateTime(dump_only=True)
|
class AuthorSchema(Schema):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 4 | 0 | 4 | 3 | 3 | 0 | 4 | 3 | 3 | 0 | 1 | 0 | 0 |
1,037 |
4Catalyzer/flask-resty
|
4Catalyzer_flask-resty/example/models.py
|
example.models.Book
|
class Book(db.Model):
__tablename__ = "example_books"
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.Text, nullable=False)
author_id = db.Column(db.Integer, db.ForeignKey(Author.id), nullable=False)
author = db.relationship(Author, backref=db.backref("books"))
published_at = db.Column(db.DateTime, nullable=False)
created_at = db.Column(
db.DateTime, default=dt.datetime.utcnow, nullable=False
)
|
class Book(db.Model):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 11 | 1 | 10 | 7 | 9 | 0 | 8 | 7 | 7 | 0 | 1 | 0 | 0 |
1,038 |
4Catalyzer/flask-resty
|
4Catalyzer_flask-resty/example/models.py
|
example.models.Author
|
class Author(db.Model):
__tablename__ = "example_authors"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text, nullable=False)
created_at = db.Column(
db.DateTime, default=dt.datetime.utcnow, nullable=False
)
|
class Author(db.Model):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 8 | 1 | 7 | 4 | 6 | 0 | 5 | 4 | 4 | 0 | 1 | 0 | 0 |
1,039 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_pagination.py
|
tests.test_pagination.routes.RelayCursorListView
|
class RelayCursorListView(WidgetListViewBase):
sorting = Sorting("id", "size", "is_cool", "name")
pagination = RelayCursorPagination(
2,
page_info_arg="page_info",
)
|
class RelayCursorListView(WidgetListViewBase):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 63 | 6 | 0 | 6 | 3 | 5 | 0 | 3 | 3 | 2 | 0 | 5 | 0 | 0 |
1,040 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_pagination.py
|
tests.test_pagination.routes.PageWidgetListView
|
class PageWidgetListView(WidgetListViewBase):
pagination = PagePagination(2)
|
class PageWidgetListView(WidgetListViewBase):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 63 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 5 | 0 | 0 |
1,041 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_pagination.py
|
tests.test_pagination.routes.MaxLimitWidgetListView
|
class MaxLimitWidgetListView(WidgetListViewBase):
pagination = MaxLimitPagination(2)
|
class MaxLimitWidgetListView(WidgetListViewBase):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 63 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 5 | 0 | 0 |
1,042 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_pagination.py
|
tests.test_pagination.routes.LimitOffsetWidgetListView
|
class LimitOffsetWidgetListView(WidgetListViewBase):
filtering = Filtering(size=operator.eq)
pagination = LimitOffsetPagination(2, 4)
|
class LimitOffsetWidgetListView(WidgetListViewBase):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 63 | 3 | 0 | 3 | 3 | 2 | 0 | 3 | 3 | 2 | 0 | 5 | 0 | 0 |
1,043 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_pagination.py
|
tests.test_pagination.models.Widget
|
class Widget(db.Model):
__tablename__ = "widgets"
id = Column(Integer, primary_key=True)
size = Column(Integer)
is_cool = Column(Boolean)
name = Column(Text)
|
class Widget(db.Model):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 | 1 | 6 | 5 | 5 | 0 | 6 | 5 | 5 | 0 | 1 | 0 | 0 |
1,044 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_misc.py
|
tests.test_misc.views.WidgetView
|
class WidgetView(WidgetViewBase):
def get(self, id):
return self.retrieve(id)
|
class WidgetView(WidgetViewBase):
def get(self, id):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 62 | 3 | 0 | 3 | 2 | 1 | 0 | 3 | 2 | 1 | 1 | 5 | 0 | 1 |
1,045 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_misc.py
|
tests.test_misc.views.WidgetListView
|
class WidgetListView(WidgetViewBase):
def get(self):
return self.list()
def post(self):
return self.create(allow_client_id=True)
|
class WidgetListView(WidgetViewBase):
def get(self):
pass
def post(self):
pass
| 3 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 63 | 6 | 1 | 5 | 3 | 2 | 0 | 5 | 3 | 2 | 1 | 5 | 0 | 2 |
1,046 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_misc.py
|
tests.test_misc.views.CustomWidgetView
|
class CustomWidgetView(WidgetViewBase):
def delete(self, id):
return self.destroy(id)
def update_item_raw(self, widget, data):
return self.model(id=9)
def delete_item_raw(self, widget):
return self.model(id=9)
def make_deleted_response(self, widget):
return self.make_item_response(widget)
|
class CustomWidgetView(WidgetViewBase):
def delete(self, id):
pass
def update_item_raw(self, widget, data):
pass
def delete_item_raw(self, widget):
pass
def make_deleted_response(self, widget):
pass
| 5 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 4 | 0 | 4 | 65 | 12 | 3 | 9 | 5 | 4 | 0 | 9 | 5 | 4 | 1 | 5 | 0 | 4 |
1,047 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_misc.py
|
tests.test_misc.schemas.WidgetSchema
|
class WidgetSchema(Schema):
id = fields.Integer(as_string=True)
|
class WidgetSchema(Schema):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 1 | 0 | 0 |
1,048 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_misc.py
|
tests.test_misc.models.Widget
|
class Widget(db.Model):
__tablename__ = "widgets"
id = Column(Integer, primary_key=True)
|
class Widget(db.Model):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 4 | 1 | 3 | 2 | 2 | 0 | 3 | 2 | 2 | 0 | 1 | 0 | 0 |
1,049 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_jwt.py
|
tests.test_jwt.TestJwt.auth.UserAuthorization
|
class UserAuthorization(HasAnyCredentialsAuthorization):
def filter_query(self, query, view):
return query.filter_by(
owner_id=self.get_request_credentials()["sub"]
)
|
class UserAuthorization(HasAnyCredentialsAuthorization):
def filter_query(self, query, view):
pass
| 2 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 15 | 5 | 0 | 5 | 2 | 3 | 0 | 3 | 2 | 1 | 1 | 3 | 0 | 1 |
1,050 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_jwt.py
|
tests.test_jwt.TestJwt
|
class TestJwt(AbstractTestJwt):
@pytest.fixture
def auth(self, app):
app.config.update(
{
"RESTY_JWT_DECODE_KEY": "secret",
"RESTY_JWT_DECODE_ALGORITHMS": ["HS256"],
}
)
authentication = JwtAuthentication(issuer="resty")
class UserAuthorization(HasAnyCredentialsAuthorization):
def filter_query(self, query, view):
return query.filter_by(
owner_id=self.get_request_credentials()["sub"]
)
return {
"authentication": authentication,
"authorization": UserAuthorization(),
}
@pytest.fixture
def token(self):
return "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJyZXN0eSIsInN1YiI6ImZvbyJ9.VTeYS-G0nJzYoWatqbHHNt0bFKPBuEoz0TFbPQEwTak"
@pytest.fixture(
params=(
pytest.param("foo", id="malformed"),
pytest.param(
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJyZXN0eSIsInN1YiI6ImZvbyJ9.qke42KAZLaqSJiTWntnxlcLpmlsWjx6G9lkrAlLSeGM",
id="key_mismatch",
),
pytest.param(
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJyZXN0eV8iLCJzdWIiOiJmb28ifQ.Y4upHw_3ZnQxm7eLb1Uda7jlIMNFQNsWWC80Vocj2MI",
id="iss_mismatch",
),
),
)
def invalid_token(self, request):
return request.param
|
class TestJwt(AbstractTestJwt):
@pytest.fixture
def auth(self, app):
pass
class UserAuthorization(HasAnyCredentialsAuthorization):
def filter_query(self, query, view):
pass
@pytest.fixture
def token(self):
pass
@pytest.fixture(
params=(
pytest.param("foo", id="malformed"),
pytest.param(
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJyZXN0eSIsInN1YiI6ImZvbyJ9.qke42KAZLaqSJiTWntnxlcLpmlsWjx6G9lkrAlLSeGM",
id="key_mismatch",
),
pytest.param(
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJyZXN0eV8iLCJzdWIiOiJmb28ifQ.Y4upHw_3ZnQxm7eLb1Uda7jlIMNFQNsWWC80Vocj2MI",
id="iss_mismatch",
),
),
)
def invalid_token(self, request):
pass
| 9 | 0 | 7 | 1 | 6 | 0 | 1 | 0 | 1 | 2 | 2 | 0 | 3 | 0 | 3 | 15 | 41 | 4 | 37 | 22 | 16 | 0 | 12 | 7 | 6 | 1 | 1 | 0 | 4 |
1,051 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_jwt.py
|
tests.test_jwt.TestJwkSet
|
class TestJwkSet(AbstractTestJwt):
@pytest.fixture(
params=(
pytest.param(
"tests/fixtures/testkey_rsa_pub.json", id="public_key"
),
pytest.param("tests/fixtures/testkey_rsa_cert.json", id="cert"),
),
)
def jwk_set(self, request):
with open(request.param) as rsa_pub_file:
return json.load(rsa_pub_file)
@pytest.fixture()
def auth(self, app, jwk_set):
app.config.update(
{
"RESTY_JWT_DECODE_JWK_SET": jwk_set,
"RESTY_JWT_DECODE_ALGORITHMS": ["RS256"],
}
)
authentication = JwkSetAuthentication(issuer="resty")
class UserAuthorization(HasAnyCredentialsAuthorization):
def filter_query(self, query, view):
return query.filter_by(
owner_id=self.get_request_credentials()["sub"]
)
return {
"authentication": authentication,
"authorization": UserAuthorization(),
}
@pytest.fixture
def token(self):
return "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6ImZvby5jb20ifQ.eyJpc3MiOiJyZXN0eSIsInN1YiI6ImZvbyJ9.0hkDQT1lnMoGjweZeJDeSfVMllhzlmYtSqErpeU5pp7TK5OkIoLeMCSHjqYdCOwwha8znK6hBxKO-LzT4PPuhe0LnNb_qZpEbtoX6ldN8LSkhCv3Jr8lwt_hs09-lHXxdrknuYmooICI6Q66QzOpTSF4j867UwUYtfVsMpfofxpiRCJOOvynpquYGbgXc59SGJjM5wPAgYo782uRErnRFX7YJmwt5wINjvsKhr0Ry512w_EC--jDGEpcWaNKMDXKL0UMQXWoOM5IlUMA7Kr2bF966X2xuUdRnJinVGnJvdK8yKyZg_qPA26OygLeJUqF-R4jVC-lYEfte7EOLpYBBQ"
@pytest.fixture(
params=(
pytest.param("foo", id="malformed"),
pytest.param(
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJyZXN0eSIsInN1YiI6ImZvbyJ9.qke42KAZLaqSJiTWntnxlcLpmlsWjx6G9lkrAlLSeGM",
id="key_mismatch",
),
pytest.param(
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6ImZvby5jb20ifQ.eyJpc3MiOiJyZXN0eV8iLCJzdWIiOiJmb28ifQ.zow1JvW0ExAT7hNld7CIi7xox372OcX2ZQn1MdZJVeCTPvwgJi9MkFZ76xJbl_b3_4PW40Hh5TwE8X5U_eTiv7mGeQkc7jOi4wnynHoBHkIO6vqNdrUdob93iePxkxn_xrUvQiR7ROfpQa7IREQ_i8infFKURl4xZR11A0OR6RTboXckfsq1uuOet0TuFCeuBUGbbDy6YNYxBou82qbFLYsFynaUhKBcbLGETM05X_NxTs1fsEXesKrtgdbiM-Lj0N9AeSd7dEH9O0zXcix8kEN4txmxmXrbzSTpWw2PhlMQULPAXpFKk2uiWBdpHlG2nPb2XKsAAXXuN4ZXQ0X1Sw",
id="iss_mismatch",
),
pytest.param(
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Im5vcGUifQ.eyJpc3MiOiJyZXN0eSIsInN1YiI6ImZvbyJ9.dUHYJ0SVum7ZY1z7CVivLWpCIPms2FS9dukXjOMKEc7FP85l3A3-HA98ma0UFDU4AlwrEqXYbf9QFO-CNeIoLkX6A5e73XJ1H_3-rGhJTivkX3ZHXXKCk9Tizd7TWk-J8ZLSxXjLusJJrZHg_l8k1Ego89r9MPnAdk2JjB45dhawS-8jc1zFczyEaNtpimRXw_eOGuzEFz0TDeASGuK-WjPMMOSTJoD9wp-dIYubhdO5RpXbcAcQu3x0UnJPjIbUzSntmt2GNTPOE2yxtF6_VKISUHJKThRHQtYx9ePTmDyFTlLOTRI8KCuOtUYOnIHZIAtNuUrjRoJ1RPcWpgkzwQ",
id="kid_mismatch",
),
pytest.param(
"eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIiwia2lkIjoiYmFyLmNvbSJ9.eyJpc3MiOiJyZXN0eSIsInN1YiI6ImZvbyJ9.0hkDQT1lnMoGjweZeJDeSfVMllhzlmYtSqErpeU5pp7TK5OkIoLeMCSHjqYdCOwwha8znK6hBxKO-LzT4PPuhe0LnNb_qZpEbtoX6ldN8LSkhCv3Jr8lwt_hs09-lHXxdrknuYmooICI6Q66QzOpTSF4j867UwUYtfVsMpfofxpiRCJOOvynpquYGbgXc59SGJjM5wPAgYo782uRErnRFX7YJmwt5wINjvsKhr0Ry512w_EC--jDGEpcWaNKMDXKL0UMQXWoOM5IlUMA7Kr2bF966X2xuUdRnJinVGnJvdK8yKyZg_qPA26OygLeJUqF-R4jVC-lYEfte7EOLpYBBQ",
id="alg_mismatch",
),
pytest.param(
"eyJ0eXAiOiJKV1QiLCJraWQiOiJmb28uY29tIn0=.eyJpc3MiOiJyZXN0eSIsInN1YiI6ImZvbyJ9.0hkDQT1lnMoGjweZeJDeSfVMllhzlmYtSqErpeU5pp7TK5OkIoLeMCSHjqYdCOwwha8znK6hBxKO-LzT4PPuhe0LnNb_qZpEbtoX6ldN8LSkhCv3Jr8lwt_hs09-lHXxdrknuYmooICI6Q66QzOpTSF4j867UwUYtfVsMpfofxpiRCJOOvynpquYGbgXc59SGJjM5wPAgYo782uRErnRFX7YJmwt5wINjvsKhr0Ry512w_EC--jDGEpcWaNKMDXKL0UMQXWoOM5IlUMA7Kr2bF966X2xuUdRnJinVGnJvdK8yKyZg_qPA26OygLeJUqF-R4jVC-lYEfte7EOLpYBBQ",
id="alg_missing",
),
),
)
def invalid_token(self, request):
return request.param
|
class TestJwkSet(AbstractTestJwt):
@pytest.fixture(
params=(
pytest.param(
"tests/fixtures/testkey_rsa_pub.json", id="public_key"
),
pytest.param("tests/fixtures/testkey_rsa_cert.json", id="cert"),
),
)
def jwk_set(self, request):
pass
@pytest.fixture()
def auth(self, app, jwk_set):
pass
class UserAuthorization(HasAnyCredentialsAuthorization):
def filter_query(self, query, view):
pass
@pytest.fixture
def token(self):
pass
@pytest.fixture(
params=(
pytest.param("foo", id="malformed"),
pytest.param(
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJyZXN0eSIsInN1YiI6ImZvbyJ9.qke42KAZLaqSJiTWntnxlcLpmlsWjx6G9lkrAlLSeGM",
id="key_mismatch",
),
pytest.param(
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6ImZvby5jb20ifQ.eyJpc3MiOiJyZXN0eV8iLCJzdWIiOiJmb28ifQ.zow1JvW0ExAT7hNld7CIi7xox372OcX2ZQn1MdZJVeCTPvwgJi9MkFZ76xJbl_b3_4PW40Hh5TwE8X5U_eTiv7mGeQkc7jOi4wnynHoBHkIO6vqNdrUdob93iePxkxn_xrUvQiR7ROfpQa7IREQ_i8infFKURl4xZR11A0OR6RTboXckfsq1uuOet0TuFCeuBUGbbDy6YNYxBou82qbFLYsFynaUhKBcbLGETM05X_NxTs1fsEXesKrtgdbiM-Lj0N9AeSd7dEH9O0zXcix8kEN4txmxmXrbzSTpWw2PhlMQULPAXpFKk2uiWBdpHlG2nPb2XKsAAXXuN4ZXQ0X1Sw",
id="iss_mismatch",
),
pytest.param(
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Im5vcGUifQ.eyJpc3MiOiJyZXN0eSIsInN1YiI6ImZvbyJ9.dUHYJ0SVum7ZY1z7CVivLWpCIPms2FS9dukXjOMKEc7FP85l3A3-HA98ma0UFDU4AlwrEqXYbf9QFO-CNeIoLkX6A5e73XJ1H_3-rGhJTivkX3ZHXXKCk9Tizd7TWk-J8ZLSxXjLusJJrZHg_l8k1Ego89r9MPnAdk2JjB45dhawS-8jc1zFczyEaNtpimRXw_eOGuzEFz0TDeASGuK-WjPMMOSTJoD9wp-dIYubhdO5RpXbcAcQu3x0UnJPjIbUzSntmt2GNTPOE2yxtF6_VKISUHJKThRHQtYx9ePTmDyFTlLOTRI8KCuOtUYOnIHZIAtNuUrjRoJ1RPcWpgkzwQ",
id="kid_mismatch",
),
pytest.param(
"eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIiwia2lkIjoiYmFyLmNvbSJ9.eyJpc3MiOiJyZXN0eSIsInN1YiI6ImZvbyJ9.0hkDQT1lnMoGjweZeJDeSfVMllhzlmYtSqErpeU5pp7TK5OkIoLeMCSHjqYdCOwwha8znK6hBxKO-LzT4PPuhe0LnNb_qZpEbtoX6ldN8LSkhCv3Jr8lwt_hs09-lHXxdrknuYmooICI6Q66QzOpTSF4j867UwUYtfVsMpfofxpiRCJOOvynpquYGbgXc59SGJjM5wPAgYo782uRErnRFX7YJmwt5wINjvsKhr0Ry512w_EC--jDGEpcWaNKMDXKL0UMQXWoOM5IlUMA7Kr2bF966X2xuUdRnJinVGnJvdK8yKyZg_qPA26OygLeJUqF-R4jVC-lYEfte7EOLpYBBQ",
id="alg_mismatch",
),
pytest.param(
"eyJ0eXAiOiJKV1QiLCJraWQiOiJmb28uY29tIn0=.eyJpc3MiOiJyZXN0eSIsInN1YiI6ImZvbyJ9.0hkDQT1lnMoGjweZeJDeSfVMllhzlmYtSqErpeU5pp7TK5OkIoLeMCSHjqYdCOwwha8znK6hBxKO-LzT4PPuhe0LnNb_qZpEbtoX6ldN8LSkhCv3Jr8lwt_hs09-lHXxdrknuYmooICI6Q66QzOpTSF4j867UwUYtfVsMpfofxpiRCJOOvynpquYGbgXc59SGJjM5wPAgYo782uRErnRFX7YJmwt5wINjvsKhr0Ry512w_EC--jDGEpcWaNKMDXKL0UMQXWoOM5IlUMA7Kr2bF966X2xuUdRnJinVGnJvdK8yKyZg_qPA26OygLeJUqF-R4jVC-lYEfte7EOLpYBBQ",
id="alg_missing",
),
),
)
def invalid_token(self, request):
pass
| 11 | 0 | 6 | 1 | 6 | 0 | 1 | 0 | 1 | 2 | 2 | 0 | 4 | 0 | 4 | 16 | 66 | 6 | 60 | 44 | 18 | 0 | 15 | 8 | 8 | 1 | 1 | 1 | 5 |
1,052 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_jwt.py
|
tests.test_jwt.AbstractTestJwt.schemas.WidgetSchema
|
class WidgetSchema(Schema):
id = fields.Integer(as_string=True)
owner_id = fields.String()
|
class WidgetSchema(Schema):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 0 | 3 | 2 | 2 | 0 | 3 | 2 | 2 | 0 | 1 | 0 | 0 |
1,053 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_jwt.py
|
tests.test_jwt.AbstractTestJwt.routes.WidgetListView
|
class WidgetListView(GenericModelView):
model = models["widget"]
schema = schemas["widget"]
authentication = auth["authentication"]
authorization = auth["authorization"]
def get(self):
return self.list()
|
class WidgetListView(GenericModelView):
def get(self):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 62 | 9 | 2 | 7 | 6 | 5 | 0 | 7 | 6 | 5 | 1 | 4 | 0 | 1 |
1,054 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_jwt.py
|
tests.test_jwt.AbstractTestJwt.models.Widget
|
class Widget(db.Model):
__tablename__ = "widgets"
id = Column(Integer, primary_key=True)
owner_id = Column(String)
|
class Widget(db.Model):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 5 | 1 | 4 | 3 | 3 | 0 | 4 | 3 | 3 | 0 | 1 | 0 | 0 |
1,055 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_filtering.py
|
tests.test_filtering.schemas.WidgetSchema
|
class WidgetSchema(Schema):
id = fields.Integer(as_string=True)
color = fields.String()
size = fields.Integer(validate=validate.Range(min=1))
|
class WidgetSchema(Schema):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 4 | 0 | 4 | 3 | 3 | 0 | 4 | 3 | 3 | 0 | 1 | 0 | 0 |
1,056 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_filtering.py
|
tests.test_filtering.routes.WidgetViewBase
|
class WidgetViewBase(GenericModelView):
model = models["widget"]
schema = schemas["widget"]
filtering = Filtering(
color=operator.eq,
color_allow_empty=ColumnFilter(
"color", operator.eq, allow_empty=True
),
size=ColumnFilter(operator.eq, separator="|"),
size_min=ColumnFilter("size", operator.ge),
size_divides=ColumnFilter(
"size", lambda size, value: size % value == 0
),
size_is_odd=ModelFilter(
fields.Boolean(),
lambda model, value: model.size % 2 == int(value),
),
size_min_unvalidated=ColumnFilter(
"size", operator.ge, validate=False
),
size_skip_invalid=ColumnFilter(
"size", operator.eq, skip_invalid=True
),
)
|
class WidgetViewBase(GenericModelView):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 4 | 0 | 0 | 0 | 61 | 25 | 1 | 24 | 4 | 23 | 0 | 4 | 4 | 3 | 0 | 4 | 0 | 0 |
1,057 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_filtering.py
|
tests.test_filtering.routes.WidgetSizeRequiredListView
|
class WidgetSizeRequiredListView(WidgetViewBase):
filtering = WidgetViewBase.filtering | Filtering(
size=ColumnFilter(operator.eq, required=True)
)
def get(self):
return self.list()
|
class WidgetSizeRequiredListView(WidgetViewBase):
def get(self):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 62 | 7 | 1 | 6 | 3 | 4 | 0 | 4 | 3 | 2 | 1 | 5 | 0 | 1 |
1,058 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_filtering.py
|
tests.test_filtering.routes.WidgetListView
|
class WidgetListView(WidgetViewBase):
def get(self):
return self.list()
|
class WidgetListView(WidgetViewBase):
def get(self):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 62 | 3 | 0 | 3 | 2 | 1 | 0 | 3 | 2 | 1 | 1 | 5 | 0 | 1 |
1,059 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_view_errors.py
|
tests.test_view_errors.views.WidgetViewBase
|
class WidgetViewBase(GenericModelView):
model = models["widget"]
schema = schemas["widget"]
|
class WidgetViewBase(GenericModelView):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 3 | 0 | 0 | 0 | 61 | 3 | 0 | 3 | 3 | 2 | 0 | 3 | 3 | 2 | 0 | 4 | 0 | 0 |
1,060 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_auth.py
|
tests.test_auth.routes.WidgetView
|
class WidgetView(WidgetViewBase):
def get(self, id):
return self.retrieve(id)
def patch(self, id):
return self.update(id, partial=True)
def delete(self, id):
return self.destroy(id)
|
class WidgetView(WidgetViewBase):
def get(self, id):
pass
def patch(self, id):
pass
def delete(self, id):
pass
| 4 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 3 | 0 | 3 | 64 | 9 | 2 | 7 | 4 | 3 | 0 | 7 | 4 | 3 | 1 | 5 | 0 | 3 |
1,061 |
4Catalyzer/flask-resty
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_pagination.py
|
tests.test_pagination.routes.OptionalLimitWidgetListView
|
class OptionalLimitWidgetListView(WidgetListViewBase):
filtering = Filtering(size=operator.eq)
pagination = LimitPagination()
|
class OptionalLimitWidgetListView(WidgetListViewBase):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 63 | 3 | 0 | 3 | 3 | 2 | 0 | 3 | 3 | 2 | 0 | 5 | 0 | 0 |
1,062 |
4Kaylum/Brickfront
|
4Kaylum_Brickfront/brickfront/theme.py
|
brickfront.theme.Theme
|
class Theme(object):
def __init__(self, data):
pass
|
class Theme(object):
def __init__(self, data):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 4 | 1 | 3 | 2 | 1 | 0 | 3 | 2 | 1 | 1 | 1 | 0 | 1 |
1,063 |
4Kaylum/Brickfront
|
4Kaylum_Brickfront/brickfront/review.py
|
brickfront.review.Review
|
class Review(object):
'''
A class holding data for a review.
:ivar author: The `str` name of the person who wrote the review.
:ivar datePosted: The `str` date that the review was posted.
:ivar overallRating: The `int` rating that was given.
:ivar parts: `int`
:ivar buildingExperience: `int`
:ivar playability: `int`
:ivar valueForMoney: `int`
:ivar title: `str`
:ivar review: `str`
:ivar HTML: `bool`
'''
def __init__(self, data):
self.author = data[0].text
self.datePosted = data[1].text
self.overallRating = int(data[2].text )
self.parts = int(data[3].text )
self.buildingExperience = int(data[4].text )
self.playability = int(data[5].text )
self.valueForMoney = int(data[6].text )
self.title = data[7].text
self.review = data[8].text
self.HTML = {
'true': True,
'false': False,
'True': True,
'False': False,
'1': True,
'0': False
}[data[9].text]
|
class Review(object):
'''
A class holding data for a review.
:ivar author: The `str` name of the person who wrote the review.
:ivar datePosted: The `str` date that the review was posted.
:ivar overallRating: The `int` rating that was given.
:ivar parts: `int`
:ivar buildingExperience: `int`
:ivar playability: `int`
:ivar valueForMoney: `int`
:ivar title: `str`
:ivar review: `str`
:ivar HTML: `bool`
'''
def __init__(self, data):
pass
| 2 | 1 | 18 | 0 | 18 | 0 | 1 | 0.68 | 1 | 1 | 0 | 0 | 1 | 10 | 1 | 1 | 34 | 2 | 19 | 12 | 17 | 13 | 12 | 12 | 10 | 1 | 1 | 0 | 1 |
1,064 |
4Kaylum/Brickfront
|
4Kaylum_Brickfront/brickfront/errors.py
|
brickfront.errors.InvalidSetID
|
class InvalidSetID(Exception):
'''
The set ID that was passed is invalid - eg it doesn't exist.
'''
pass
|
class InvalidSetID(Exception):
'''
The set ID that was passed is invalid - eg it doesn't exist.
'''
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 6 | 1 | 2 | 1 | 1 | 3 | 2 | 1 | 1 | 0 | 3 | 0 | 0 |
1,065 |
4Kaylum/Brickfront
|
4Kaylum_Brickfront/brickfront/errors.py
|
brickfront.errors.InvalidRequest
|
class InvalidRequest(Exception):
'''
The request that was sent to the server was invalid.
'''
pass
|
class InvalidRequest(Exception):
'''
The request that was sent to the server was invalid.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 6 | 1 | 2 | 1 | 1 | 3 | 2 | 1 | 1 | 0 | 3 | 0 | 0 |
1,066 |
4Kaylum/Brickfront
|
4Kaylum_Brickfront/brickfront/errors.py
|
brickfront.errors.InvalidLoginCredentials
|
class InvalidLoginCredentials(Exception):
'''
The login credentials used were invalid.
'''
pass
|
class InvalidLoginCredentials(Exception):
'''
The login credentials used were invalid.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 6 | 1 | 2 | 1 | 1 | 3 | 2 | 1 | 1 | 0 | 3 | 0 | 0 |
1,067 |
4Kaylum/Brickfront
|
4Kaylum_Brickfront/brickfront/errors.py
|
brickfront.errors.InvalidApiKey
|
class InvalidApiKey(Exception):
'''
The API key provided was invalid and cannot be used.
'''
pass
|
class InvalidApiKey(Exception):
'''
The API key provided was invalid and cannot be used.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 6 | 1 | 2 | 1 | 1 | 3 | 2 | 1 | 1 | 0 | 3 | 0 | 0 |
1,068 |
4Kaylum/Brickfront
|
4Kaylum_Brickfront/brickfront/client.py
|
brickfront.client.Client
|
class Client(object):
'''
A frontend authenticator for Brickset.com's API.
All endpoints require an API key.
:param str apiKey: The API key you got from Brickset.
:param bool raiseError: (optional) Whether or not you want an error to be raised on an invalid API key.
:raises brickfront.errors.InvalidApiKey: If the key provided is invalid.
'''
ENDPOINT = 'http://brickset.com/api/v2.asmx/{}'
def __init__(self, apiKey, raiseError=True):
self.apiKey = apiKey
self.userHash = '' # Would be None but is used elsewhere, so has to be a blank string
# Check the provided key
if not self.checkKey() and raiseError:
raise InvalidApiKey('The provided API key `{}` was invalid.'.format(apiKey))
@staticmethod
def checkResponse(request):
'''
Returns if a request has an okay error code, otherwise raises InvalidRequest.
'''
# Check the status code of the returned request
if str(request.status_code)[0] not in ['2', '3']:
w = str(request.text).split('\\r')[0][2:]
raise InvalidRequest(w)
return
def checkKey(self, key=None):
'''
Checks that an API key is valid.
:param str key: (optional) A key that you want to check the validity of. Defaults to the one provided on initialization.
:returns: If the key is valid, this method will return ``True``.
:rtype: `bool`
:raises: :class:`brickfront.errors.InvalidApiKey`
'''
# Get site
url = Client.ENDPOINT.format('checkKey')
if not key: key = self.apiKey
params = {
'apiKey': key or self.apiKey
}
returned = get(url, params=params)
self.checkResponse(returned)
# Parse and return
root = ET.fromstring(returned.text)
if root.text == 'OK':
return True
raise InvalidApiKey('The provided API key `{}` was invalid.'.format(key))
def login(self, username, password):
'''
Logs into Brickset as a user, returning a userhash, which can be used in other methods.
The user hash is stored inside the client (:attr:`userHash`).
:param str username: Your Brickset username.
:param str password: Your Brickset password.
:returns: If the login is valid, this will return ``True``.
:rtype: `bool`
:raises: :class:`brickfront.errors.InvalidLoginCredentials`
'''
# Get the site
url = Client.ENDPOINT.format('login')
params = {
'apiKey': self.apiKey,
'username': username,
'password': password,
}
returned = get(url, params=params)
self.checkResponse(returned)
root = ET.fromstring(returned.text)
# Determine whether they logged in correctly
if root.text.startswith('ERROR'):
self.userHash = ''
raise InvalidLoginCredentials('The provided username and password were unable to authenticate.')
self.userHash = root.text
return True
def getSets(self, **kwargs):
'''
A way to get different sets from a query.
All parameters are optional, but you should probably use some (so that you get results)
:param str query: The thing you're searching for.
:param str theme: The theme of the set.
:param str subtheme: The subtheme of the set.
:param str setNumber: The LEGO set number.
:param str year: The year in which the set came out.
:param int owned: Whether or not you own the set. Only works when logged in with :meth:`login`. Set to `1` to make true.
:param int wanted: Whether or not you want the set. Only works when logged in with :meth:`login`. Set to `1` to make true.
:param str orderBy: How you want the set ordered. Accepts 'Number', 'YearFrom', 'Pieces', 'Minifigs', 'Rating', 'UKRetailPrice', 'USRetailPrice', 'CARetailPrice', 'EURetailPrice', 'Theme', 'Subtheme', 'Name', 'Random'. Add 'DESC' to the end to sort descending, e.g. NameDESC. Case insensitive. Defaults to 'Number'.
:param int pageSize: How many results are on a page. Defaults to 20.
:param int pageNumber: The number of the page you're looking at. Defaults to 1.
:param str userName: The name of a user whose sets you want to search.
:returns: A list of :class:`brickfront.build.Build` objects.
:rtype: list
'''
# Generate a dictionary to send as parameters
params = {
'apiKey': self.apiKey,
'userHash': self.userHash,
'query': kwargs.get('query', ''),
'theme': kwargs.get('theme', ''),
'subtheme': kwargs.get('subtheme', ''),
'setNumber': kwargs.get('setNumber', ''),
'year': kwargs.get('year', ''),
'owned': kwargs.get('owned', ''),
'wanted': kwargs.get('wanted', ''),
'orderBy': kwargs.get('orderBy', 'Number'),
'pageSize': kwargs.get('pageSize', '20'),
'pageNumber': kwargs.get('pageNumber', '1'),
'userName': kwargs.get('userName', '')
}
url = Client.ENDPOINT.format('getSets')
returned = get(url, params=params)
self.checkResponse(returned)
# Construct the build objects and return them graciously
root = ET.fromstring(returned.text)
return [Build(i, self) for i in root]
def getSet(self, setID):
'''
Gets the information of one specific build using its Brickset set ID.
:param str setID: The ID of the build from Brickset.
:returns: A single Build object.
:rtype: :class:`brickfront.build.Build`
:raises brickfront.errors.InvalidSetID: If no sets exist by that ID.
'''
params = {
'apiKey': self.apiKey,
'userHash': self.userHash,
'setID': setID
}
url = Client.ENDPOINT.format('getSet')
returned = get(url, params=params)
self.checkResponse(returned)
# Put it into a Build class
root = ET.fromstring(returned.text)
v = [Build(i, self) for i in root]
# Return to user
try:
return v[0]
except IndexError:
raise InvalidSetID('There is no set with the ID of `{}`.'.format(setID))
def getRecentlyUpdatedSets(self, minutesAgo):
'''
Gets the information of recently updated sets.
:param int minutesAgo: The amount of time ago that the set was updated.
:returns: A list of Build instances that were updated within the given time.
:rtype: list
.. warning:: An empty list will be returned if there are no sets in the given time limit.
'''
params = {
'apiKey': self.apiKey,
'minutesAgo': minutesAgo
}
url = Client.ENDPOINT.format('getRecentlyUpdatedSets')
returned = get(url, params=params)
self.checkResponse(returned)
# Parse them in to build objects
root = ET.fromstring(returned.text)
return [Build(i, self) for i in root]
def getAdditionalImages(self, setID):
'''
Gets a list of URLs containing images of the set.
:param str setID: The ID of the set you want to grab the images for.
:returns: A list of URL strings.
:rtype: list
.. warning:: An empty list will be returned if there are no additional images, or if the set ID is invalid.
'''
params = {
'apiKey': self.apiKey,
'setID': setID
}
url = Client.ENDPOINT.format('getAdditionalImages')
returned = get(url, params=params)
self.checkResponse(returned)
# I really fuckin hate XML
root = ET.fromstring(returned.text)
urlList = []
for imageHolder in root:
urlList.append(imageHolder[-1].text)
return urlList
def getReviews(self, setID):
'''
Get the reviews for a set.
:param str setID: The ID of the set you want to get the reviews of.
:returns: A list of reviews.
:rtype: List[:class:`brickfront.review.Review`]
.. warning:: An empty list will be returned if there are no reviews, or if the set ID is invalid.
'''
params = {
'apiKey': self.apiKey,
'setID': setID
}
url = Client.ENDPOINT.format('getReviews')
returned = get(url, params=params)
self.checkResponse(returned)
# Parse into review objects
root = ET.fromstring(returned.text)
return [Review(i) for i in root]
def getInstructions(self, setID):
'''
Get the instructions for a set.
:param str setID: The ID for the set you want to get the instructions of.
:returns: A list of URLs to instructions.
:rtype: List[`dict`]
.. warning:: An empty list will be returned if there are no instructions, or if the set ID is invalid.
'''
params = {
'apiKey': self.apiKey,
'setID': setID
}
url = Client.ENDPOINT.format('getInstructions')
returned = get(url, params=params)
self.checkResponse(returned)
# Parse into review objects
root = ET.fromstring(returned.text)
return [i[0].text for i in [o for o in root]]
|
class Client(object):
'''
A frontend authenticator for Brickset.com's API.
All endpoints require an API key.
:param str apiKey: The API key you got from Brickset.
:param bool raiseError: (optional) Whether or not you want an error to be raised on an invalid API key.
:raises brickfront.errors.InvalidApiKey: If the key provided is invalid.
'''
def __init__(self, apiKey, raiseError=True):
pass
@staticmethod
def checkResponse(request):
'''
Returns if a request has an okay error code, otherwise raises InvalidRequest.
'''
pass
def checkKey(self, key=None):
'''
Checks that an API key is valid.
:param str key: (optional) A key that you want to check the validity of. Defaults to the one provided on initialization.
:returns: If the key is valid, this method will return ``True``.
:rtype: `bool`
:raises: :class:`brickfront.errors.InvalidApiKey`
'''
pass
def login(self, username, password):
'''
Logs into Brickset as a user, returning a userhash, which can be used in other methods.
The user hash is stored inside the client (:attr:`userHash`).
:param str username: Your Brickset username.
:param str password: Your Brickset password.
:returns: If the login is valid, this will return ``True``.
:rtype: `bool`
:raises: :class:`brickfront.errors.InvalidLoginCredentials`
'''
pass
def getSets(self, **kwargs):
'''
A way to get different sets from a query.
All parameters are optional, but you should probably use some (so that you get results)
:param str query: The thing you're searching for.
:param str theme: The theme of the set.
:param str subtheme: The subtheme of the set.
:param str setNumber: The LEGO set number.
:param str year: The year in which the set came out.
:param int owned: Whether or not you own the set. Only works when logged in with :meth:`login`. Set to `1` to make true.
:param int wanted: Whether or not you want the set. Only works when logged in with :meth:`login`. Set to `1` to make true.
:param str orderBy: How you want the set ordered. Accepts 'Number', 'YearFrom', 'Pieces', 'Minifigs', 'Rating', 'UKRetailPrice', 'USRetailPrice', 'CARetailPrice', 'EURetailPrice', 'Theme', 'Subtheme', 'Name', 'Random'. Add 'DESC' to the end to sort descending, e.g. NameDESC. Case insensitive. Defaults to 'Number'.
:param int pageSize: How many results are on a page. Defaults to 20.
:param int pageNumber: The number of the page you're looking at. Defaults to 1.
:param str userName: The name of a user whose sets you want to search.
:returns: A list of :class:`brickfront.build.Build` objects.
:rtype: list
'''
pass
def getSets(self, **kwargs):
'''
Gets the information of one specific build using its Brickset set ID.
:param str setID: The ID of the build from Brickset.
:returns: A single Build object.
:rtype: :class:`brickfront.build.Build`
:raises brickfront.errors.InvalidSetID: If no sets exist by that ID.
'''
pass
def getRecentlyUpdatedSets(self, minutesAgo):
'''
Gets the information of recently updated sets.
:param int minutesAgo: The amount of time ago that the set was updated.
:returns: A list of Build instances that were updated within the given time.
:rtype: list
.. warning:: An empty list will be returned if there are no sets in the given time limit.
'''
pass
def getAdditionalImages(self, setID):
'''
Gets a list of URLs containing images of the set.
:param str setID: The ID of the set you want to grab the images for.
:returns: A list of URL strings.
:rtype: list
.. warning:: An empty list will be returned if there are no additional images, or if the set ID is invalid.
'''
pass
def getReviews(self, setID):
'''
Get the reviews for a set.
:param str setID: The ID of the set you want to get the reviews of.
:returns: A list of reviews.
:rtype: List[:class:`brickfront.review.Review`]
.. warning:: An empty list will be returned if there are no reviews, or if the set ID is invalid.
'''
pass
def getInstructions(self, setID):
'''
Get the instructions for a set.
:param str setID: The ID for the set you want to get the instructions of.
:returns: A list of URLs to instructions.
:rtype: List[`dict`]
.. warning:: An empty list will be returned if there are no instructions, or if the set ID is invalid.
'''
pass
| 12 | 10 | 23 | 3 | 12 | 9 | 2 | 0.78 | 1 | 8 | 6 | 0 | 9 | 2 | 10 | 10 | 260 | 49 | 119 | 51 | 107 | 93 | 83 | 50 | 72 | 3 | 1 | 1 | 17 |
1,069 |
4Kaylum/Brickfront
|
4Kaylum_Brickfront/brickfront/build.py
|
brickfront.build.Build
|
class Build(object):
'''
A class holding the information of a LEGO set. Some attributes may be ``None``.
There is no need to create an instance of a ``Build`` object yourself - it won't go well.
:ivar int setID: The set ID, as used on Brickset.
:ivar str number: The LEGO ID number of the set.
:ivar int variant: The variant of the set, as used on Brickset.
:ivar str name: The name of the set.
:ivar str year: The year the set was released.
:ivar str theme: The theme of the set.
:ivar str themeGroup: The theme group, as used on /browse/sets
:ivar str subtheme: The subtheme of the set.
:ivar int pieces: How many pieces the set has.
:ivar int minifigs: The amount of minifigs what come with the set.
:ivar str imageURL: A URL to an image of the set.
:ivar str bricksetURL: The URL to the page for the set on Brickset.
:ivar bool released: Whether or not the set is released.
:ivar bool owned: Whether or not own the set. Only works when logged in.
:ivar bool wanted: Whether or not you want the set. Only works when logged in.
:ivar int quantityOwned: The number of these that you own. Only works when logged in.
:ivar int ACMDataCount: Number of ACM records you have modified for this set.
:ivar str userNotes: The notes that you have on the product. Only works when logged in.
:ivar int ownedByTotal: The number of people who own this set.
:ivar int wantedByTotal: The number of people who want this set.
:ivar str priceUK: The price of the set.
:ivar str priceUS: The price of the set.
:ivar str priceCA: The price of the set.
:ivar str priceEU: The price of the set.
:ivar datetime.datetime dateAddedToStore: The date that the set was added to the US LEGO store website.
:ivar datetime.datetime dateRemovedFromStore: The date that the set was removed from the US LEGO store website. If ``None``, then the set is still available.
:ivar float rating: The overall rating of the set on Brickset.
:ivar int reviewCount: How many reviews the set has on Brickset.
:ivar str packagingType: How the set is packaged
:ivar str availability: Where the set is available.
:ivar int instructionsCount: How many sets of instructions the set has.
:ivar int additionalImageCount: How many additional images the set has.
:ivar str EAN: The standard barcode number of the set.
:ivar str UPC: The standard barcode number of the set.
:ivar str description: The description of the set.
:ivar datetime.datetime lastUpdated: When the set was last updated on Brickset.
:ivar list additionalImages: The URLs to the additional images of the set.
:ivar list reviews: A list of :class:`brickfront.review.Review` objects for the reviews of the set.
'''
def __init__(self, data, client):
self.raw = data
self._client = client
# Set up the attributes of this class
applicableTags = [
'setID',
'number',
['numberVariant', 'variant'],
'name',
'year',
'theme',
'themeGroup',
'subtheme',
'pieces',
'minifigs',
'imageURL',
'bricksetURL',
'released',
'owned',
'wanted',
['qtyOwned', 'quantityOwned'],
'ACMDataCount',
'userNotes',
'ownedByTotal',
'wantedByTotal',
['UKRetailPrice', 'priceUK'],
['USRetailPrice', 'priceUS'],
['CARetailPrice', 'priceCA'],
['EURetailPrice', 'priceEU'],
['USDateAddedToSAH', 'dateAddedToStore'],
['USDateRemovedFromSAH', 'dateRemovedFromStore'],
'rating',
'reviewCount',
'packagingType',
'availability',
'instructionsCount',
'additionalImageCount',
'EAN',
'UPC',
'description',
'lastUpdated',
]
# Iterate through the XML
for i in data:
tag = i.tag.split('}')[-1]
# Rename the tag if necessary
try:
applicableTags.index(tag)
applicableTags.remove(tag)
except ValueError:
for o in applicableTags:
if type(o) == list:
if tag == o[0]:
tag = o[1]
applicableTags.remove(o)
break
# Set the attribute
setattr(self, tag, i.text)
# Determine which values haven't been set, and set them to None
for i in applicableTags:
tag = i
if type(i) == list:
tag = i[1]
setattr(self, tag, None)
# Set up tag translations, from one type into another via functions/lambdas
toInt = lambda x: 0 if x is None else int(x)
toBool = lambda x: {'true':True,'false':False,'0':False,'1':True}.get(x.lower(), x)
toDate = lambda x: datetime.strptime(x, '%Y-%m-%dT%H:%M:%S.%f')
translationTags = [
['setID', int],
['variant', int],
['pieces', int],
['minifigs', toInt],
['reviewCount', toInt],
['instructionsCount', toInt],
['additionalImageCount', toInt],
['released', toBool],
['owned', toBool],
['wanted', toBool],
['rating', float],
['ACMDataCount', int],
['quantityOwned', int],
['dateAddedToStore', toDate],
['dateRemovedFromStore', toDate],
['lastUpdated', toDate],
]
# Format the tags into the right format
for i in translationTags:
x = getattr(self, i[0])
try:
setattr(self, i[0], i[1](x))
except Exception as e:
pass
# A simple cache of these items - defaulting to nonexistent
self._additionalImages = None
self._reviews = None
self._instructions = None
def __repr__(self):
return '<{0.__class__.__name__} object with name="{0.name}">'.format(self)
def getAdditionalImages(self):
'''
The same as calling ``client.getAdditionalImages(build.setID)``.
:returns: A list of URL strings.
:rtype: list
'''
self._additionalImages = self._client.getAdditionalImages(self.setID)
return self._additionalImages
@property
def additionalImages(self):
if self._additionalImages is None:
self._additionalImages = self.getAdditionalImages()
return self._additionalImages
def getReviews(self):
'''
The same as calling ``client.getReviews(build.setID)``.
:returns: A list of :class:`brickfront.review.Review` objects.
:rtype: list
'''
self._reviews = self._client.getReviews(self.setID)
return self._reviews
@property
def reviews(self):
if self._reviews is None:
self._reviews = self.getReviews()
return self._reviews
def getInstructions(self):
'''
The same as calling ``client.getInstructions(build.setID)``
:returns: A list of instructions.
:rtype: list
'''
self._instructions = self._client.getInstructions(self.setID)
return self._instructions
@property
def instructions(self):
if self._instructions is None:
self._instructions = self.getInstructions()
return self._instructions
|
class Build(object):
'''
A class holding the information of a LEGO set. Some attributes may be ``None``.
There is no need to create an instance of a ``Build`` object yourself - it won't go well.
:ivar int setID: The set ID, as used on Brickset.
:ivar str number: The LEGO ID number of the set.
:ivar int variant: The variant of the set, as used on Brickset.
:ivar str name: The name of the set.
:ivar str year: The year the set was released.
:ivar str theme: The theme of the set.
:ivar str themeGroup: The theme group, as used on /browse/sets
:ivar str subtheme: The subtheme of the set.
:ivar int pieces: How many pieces the set has.
:ivar int minifigs: The amount of minifigs what come with the set.
:ivar str imageURL: A URL to an image of the set.
:ivar str bricksetURL: The URL to the page for the set on Brickset.
:ivar bool released: Whether or not the set is released.
:ivar bool owned: Whether or not own the set. Only works when logged in.
:ivar bool wanted: Whether or not you want the set. Only works when logged in.
:ivar int quantityOwned: The number of these that you own. Only works when logged in.
:ivar int ACMDataCount: Number of ACM records you have modified for this set.
:ivar str userNotes: The notes that you have on the product. Only works when logged in.
:ivar int ownedByTotal: The number of people who own this set.
:ivar int wantedByTotal: The number of people who want this set.
:ivar str priceUK: The price of the set.
:ivar str priceUS: The price of the set.
:ivar str priceCA: The price of the set.
:ivar str priceEU: The price of the set.
:ivar datetime.datetime dateAddedToStore: The date that the set was added to the US LEGO store website.
:ivar datetime.datetime dateRemovedFromStore: The date that the set was removed from the US LEGO store website. If ``None``, then the set is still available.
:ivar float rating: The overall rating of the set on Brickset.
:ivar int reviewCount: How many reviews the set has on Brickset.
:ivar str packagingType: How the set is packaged
:ivar str availability: Where the set is available.
:ivar int instructionsCount: How many sets of instructions the set has.
:ivar int additionalImageCount: How many additional images the set has.
:ivar str EAN: The standard barcode number of the set.
:ivar str UPC: The standard barcode number of the set.
:ivar str description: The description of the set.
:ivar datetime.datetime lastUpdated: When the set was last updated on Brickset.
:ivar list additionalImages: The URLs to the additional images of the set.
:ivar list reviews: A list of :class:`brickfront.review.Review` objects for the reviews of the set.
'''
def __init__(self, data, client):
pass
def __repr__(self):
pass
def getAdditionalImages(self):
'''
The same as calling ``client.getAdditionalImages(build.setID)``.
:returns: A list of URL strings.
:rtype: list
'''
pass
@property
def additionalImages(self):
pass
def getReviews(self):
'''
The same as calling ``client.getReviews(build.setID)``.
:returns: A list of :class:`brickfront.review.Review` objects.
:rtype: list
'''
pass
@property
def reviews(self):
pass
def getInstructions(self):
'''
The same as calling ``client.getInstructions(build.setID)``
:returns: A list of instructions.
:rtype: list
'''
pass
@property
def instructions(self):
pass
| 12 | 4 | 19 | 2 | 14 | 3 | 3 | 0.56 | 1 | 7 | 0 | 0 | 8 | 5 | 8 | 8 | 212 | 31 | 116 | 27 | 104 | 65 | 59 | 23 | 50 | 10 | 1 | 5 | 20 |
1,070 |
4degrees/clique
|
4degrees_clique/source/clique/error.py
|
clique.error.CollectionError
|
class CollectionError(Exception):
'''Raise when a collection error occurs.'''
|
class CollectionError(Exception):
'''Raise when a collection error occurs.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 2 | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 3 | 0 | 0 |
1,071 |
4degrees/clique
|
4degrees_clique/source/clique/descriptor.py
|
clique.descriptor.Unsettable
|
class Unsettable(object):
'''Prevent standard setting of property.
Example::
>>> class Foo(object):
...
... x = Unsettable('x')
...
... def __init__(self):
... self.__dict__['x'] = True
...
>>> foo = Foo()
>>> print foo.x
True
>>> foo.x = False
AttributeError: Cannot set attribute defined as unsettable.
'''
def __init__(self, label):
'''Initialise descriptor with property *label*.
*label* should match the name of the property being described::
x = Unsettable('x')
'''
self.label = label
super(Unsettable, self).__init__()
def __get__(self, instance, owner):
'''Return value of property for *instance*.'''
return instance.__dict__.get(self.label)
def __set__(self, instance, value):
'''Set *value* for *instance* property.'''
raise AttributeError('Cannot set attribute defined as unsettable.')
|
class Unsettable(object):
'''Prevent standard setting of property.
Example::
>>> class Foo(object):
...
... x = Unsettable('x')
...
... def __init__(self):
... self.__dict__['x'] = True
...
>>> foo = Foo()
>>> print foo.x
True
>>> foo.x = False
AttributeError: Cannot set attribute defined as unsettable.
'''
def __init__(self, label):
'''Initialise descriptor with property *label*.
*label* should match the name of the property being described::
x = Unsettable('x')
'''
pass
def __get__(self, instance, owner):
'''Return value of property for *instance*.'''
pass
def __set__(self, instance, value):
'''Set *value* for *instance* property.'''
pass
| 4 | 4 | 5 | 1 | 2 | 2 | 1 | 2.63 | 1 | 2 | 0 | 0 | 3 | 1 | 3 | 3 | 38 | 9 | 8 | 5 | 4 | 21 | 8 | 5 | 4 | 1 | 1 | 0 | 3 |
1,072 |
4degrees/clique
|
4degrees_clique/source/clique/collection.py
|
clique.collection.Collection
|
class Collection(object):
'''Represent group of items that differ only by numerical component.'''
indexes = clique.descriptor.Unsettable('indexes')
def __init__(self, head, tail, padding, indexes=None):
'''Initialise collection.
*head* is the leading common part whilst *tail* is the trailing
common part.
*padding* specifies the "width" of the numerical component. An index
will be padded with zeros to fill this width. A *padding* of zero
implies no padding and width may be any size so long as no leading
zeros are present.
*indexes* can specify a set of numerical indexes to initially populate
the collection with.
.. note::
After instantiation, the ``indexes`` attribute cannot be set to a
new value using assignment::
>>> collection.indexes = [1, 2, 3]
AttributeError: Cannot set attribute defined as unsettable.
Instead, manipulate it directly::
>>> collection.indexes.clear()
>>> collection.indexes.update([1, 2, 3])
'''
super(Collection, self).__init__()
self.__dict__['indexes'] = clique.sorted_set.SortedSet()
self._head = head
self._tail = tail
self.padding = padding
self._update_expression()
if indexes is not None:
self.indexes.update(indexes)
@property
def head(self):
'''Return common leading part.'''
return self._head
@head.setter
def head(self, value):
'''Set common leading part to *value*.'''
self._head = value
self._update_expression()
@property
def tail(self):
'''Return common trailing part.'''
return self._tail
@tail.setter
def tail(self, value):
'''Set common trailing part to *value*.'''
self._tail = value
self._update_expression()
def _update_expression(self):
'''Update internal expression.'''
self._expression = re.compile(
'^{0}(?P<index>(?P<padding>0*)\d+?){1}$'
.format(re.escape(self.head), re.escape(self.tail))
)
def __str__(self):
'''Return string represenation.'''
return self.format()
def __repr__(self):
'''Return representation.'''
return '<{0} "{1}">'.format(self.__class__.__name__, self)
def __iter__(self):
'''Return iterator over items in collection.'''
for index in self.indexes:
formatted_index = '{0:0{1}d}'.format(index, self.padding)
item = '{0}{1}{2}'.format(self.head, formatted_index, self.tail)
yield item
def __contains__(self, item):
'''Return whether *item* is present in collection.'''
match = self.match(item)
if not match:
return False
if not int(match.group('index')) in self.indexes:
return False
return True
def __eq__(self, other):
'''Return whether *other* collection is equal.'''
if not isinstance(other, Collection):
return NotImplemented
return all([
other.head == self.head,
other.tail == self.tail,
other.padding == self.padding,
other.indexes == self.indexes
])
def __ne__(self, other):
'''Return whether *other* collection is not equal.'''
result = self.__eq__(other)
if result is NotImplemented:
return result
return not result
def __gt__(self, other):
'''Return whether *other* collection is greater than.'''
if not isinstance(other, Collection):
return NotImplemented
a = (self.head, self.tail, self.padding, len(self.indexes))
b = (other.head, other.tail, other.padding, len(other.indexes))
return a > b
def __lt__(self, other):
'''Return whether *other* collection is less than.'''
result = self.__gt__(other)
if result is NotImplemented:
return result
return not result
def __ge__(self, other):
'''Return whether *other* collection is greater than or equal.'''
result = self.__eq__(other)
if result is NotImplemented:
return result
if result is False:
result = self.__gt__(other)
return result
def __le__(self, other):
'''Return whether *other* collection is less than or equal.'''
result = self.__eq__(other)
if result is NotImplemented:
return result
if result is False:
result = self.__lt__(other)
return result
def match(self, item):
'''Return whether *item* matches this collection expression.
If a match is successful return data about the match otherwise return
None.
'''
match = self._expression.match(item)
if not match:
return None
index = match.group('index')
padded = False
if match.group('padding'):
padded = True
if self.padding == 0:
if padded:
return None
elif len(index) != self.padding:
return None
return match
def add(self, item):
'''Add *item* to collection.
raise :py:class:`~clique.error.CollectionError` if *item* cannot be
added to the collection.
'''
match = self.match(item)
if match is None:
raise clique.error.CollectionError(
'Item does not match collection expression.'
)
self.indexes.add(int(match.group('index')))
def remove(self, item):
'''Remove *item* from collection.
raise :py:class:`~clique.error.CollectionError` if *item* cannot be
removed from the collection.
'''
match = self.match(item)
if match is None:
raise clique.error.CollectionError(
'Item not present in collection.'
)
index = int(match.group('index'))
try:
self.indexes.remove(index)
except KeyError:
raise clique.error.CollectionError(
'Item not present in collection.'
)
def format(self, pattern='{head}{padding}{tail} [{ranges}]'):
'''Return string representation as specified by *pattern*.
Pattern can be any format accepted by Python's standard format function
and will receive the following keyword arguments as context:
* *head* - Common leading part of the collection.
* *tail* - Common trailing part of the collection.
* *padding* - Padding value in ``%0d`` format.
* *range* - Total range in the form ``start-end``
* *ranges* - Comma separated ranges of indexes.
* *holes* - Comma separated ranges of missing indexes.
'''
data = {}
data['head'] = self.head
data['tail'] = self.tail
if self.padding:
data['padding'] = '%0{0}d'.format(self.padding)
else:
data['padding'] = '%d'
if '{holes}' in pattern:
data['holes'] = self.holes().format('{ranges}')
if '{range}' in pattern or '{ranges}' in pattern:
indexes = list(self.indexes)
indexes_count = len(indexes)
if indexes_count == 0:
data['range'] = ''
elif indexes_count == 1:
data['range'] = '{0}'.format(indexes[0])
else:
data['range'] = '{0}-{1}'.format(
indexes[0], indexes[-1]
)
if '{ranges}' in pattern:
separated = self.separate()
if len(separated) > 1:
ranges = [collection.format('{range}')
for collection in separated]
else:
ranges = [data['range']]
data['ranges'] = ', '.join(ranges)
return pattern.format(**data)
def is_contiguous(self):
'''Return whether entire collection is contiguous.'''
previous = None
for index in self.indexes:
if previous is None:
previous = index
continue
if index != (previous + 1):
return False
previous = index
return True
def holes(self):
'''Return holes in collection.
Return :py:class:`~clique.collection.Collection` of missing indexes.
'''
missing = set([])
previous = None
for index in self.indexes:
if previous is None:
previous = index
continue
if index != (previous + 1):
missing.update(range(previous + 1, index))
previous = index
return Collection(self.head, self.tail, self.padding, indexes=missing)
def is_compatible(self, collection):
'''Return whether *collection* is compatible with this collection.
To be compatible *collection* must have the same head, tail and padding
properties as this collection.
'''
return all([
isinstance(collection, Collection),
collection.head == self.head,
collection.tail == self.tail,
collection.padding == self.padding
])
def merge(self, collection):
'''Merge *collection* into this collection.
If the *collection* is compatible with this collection then update
indexes with all indexes in *collection*.
raise :py:class:`~clique.error.CollectionError` if *collection* is not
compatible with this collection.
'''
if not self.is_compatible(collection):
raise clique.error.CollectionError('Collection is not compatible '
'with this collection.')
self.indexes.update(collection.indexes)
def separate(self):
'''Return contiguous parts of collection as separate collections.
Return as list of :py:class:`~clique.collection.Collection` instances.
'''
collections = []
start = None
end = None
for index in self.indexes:
if start is None:
start = index
end = start
continue
if index != (end + 1):
collections.append(
Collection(self.head, self.tail, self.padding,
indexes=set(range(start, end + 1)))
)
start = index
end = index
if start is None:
collections.append(
Collection(self.head, self.tail, self.padding)
)
else:
collections.append(
Collection(self.head, self.tail, self.padding,
indexes=range(start, end + 1))
)
return collections
|
class Collection(object):
'''Represent group of items that differ only by numerical component.'''
def __init__(self, head, tail, padding, indexes=None):
'''Initialise collection.
*head* is the leading common part whilst *tail* is the trailing
common part.
*padding* specifies the "width" of the numerical component. An index
will be padded with zeros to fill this width. A *padding* of zero
implies no padding and width may be any size so long as no leading
zeros are present.
*indexes* can specify a set of numerical indexes to initially populate
the collection with.
.. note::
After instantiation, the ``indexes`` attribute cannot be set to a
new value using assignment::
>>> collection.indexes = [1, 2, 3]
AttributeError: Cannot set attribute defined as unsettable.
Instead, manipulate it directly::
>>> collection.indexes.clear()
>>> collection.indexes.update([1, 2, 3])
'''
pass
@property
def head(self):
'''Return common leading part.'''
pass
@head.setter
def head(self):
'''Set common leading part to *value*.'''
pass
@property
def tail(self):
'''Return common trailing part.'''
pass
@tail.setter
def tail(self):
'''Set common trailing part to *value*.'''
pass
def _update_expression(self):
'''Update internal expression.'''
pass
def __str__(self):
'''Return string represenation.'''
pass
def __repr__(self):
'''Return representation.'''
pass
def __iter__(self):
'''Return iterator over items in collection.'''
pass
def __contains__(self, item):
'''Return whether *item* is present in collection.'''
pass
def __eq__(self, other):
'''Return whether *other* collection is equal.'''
pass
def __ne__(self, other):
'''Return whether *other* collection is not equal.'''
pass
def __gt__(self, other):
'''Return whether *other* collection is greater than.'''
pass
def __lt__(self, other):
'''Return whether *other* collection is less than.'''
pass
def __ge__(self, other):
'''Return whether *other* collection is greater than or equal.'''
pass
def __le__(self, other):
'''Return whether *other* collection is less than or equal.'''
pass
def match(self, item):
'''Return whether *item* matches this collection expression.
If a match is successful return data about the match otherwise return
None.
'''
pass
def add(self, item):
'''Add *item* to collection.
raise :py:class:`~clique.error.CollectionError` if *item* cannot be
added to the collection.
'''
pass
def remove(self, item):
'''Remove *item* from collection.
raise :py:class:`~clique.error.CollectionError` if *item* cannot be
removed from the collection.
'''
pass
def format(self, pattern='{head}{padding}{tail} [{ranges}]'):
'''Return string representation as specified by *pattern*.
Pattern can be any format accepted by Python's standard format function
and will receive the following keyword arguments as context:
* *head* - Common leading part of the collection.
* *tail* - Common trailing part of the collection.
* *padding* - Padding value in ``%0d`` format.
* *range* - Total range in the form ``start-end``
* *ranges* - Comma separated ranges of indexes.
* *holes* - Comma separated ranges of missing indexes.
'''
pass
def is_contiguous(self):
'''Return whether entire collection is contiguous.'''
pass
def holes(self):
'''Return holes in collection.
Return :py:class:`~clique.collection.Collection` of missing indexes.
'''
pass
def is_compatible(self, collection):
'''Return whether *collection* is compatible with this collection.
To be compatible *collection* must have the same head, tail and padding
properties as this collection.
'''
pass
def merge(self, collection):
'''Merge *collection* into this collection.
If the *collection* is compatible with this collection then update
indexes with all indexes in *collection*.
raise :py:class:`~clique.error.CollectionError` if *collection* is not
compatible with this collection.
'''
pass
def separate(self):
'''Return contiguous parts of collection as separate collections.
Return as list of :py:class:`~clique.collection.Collection` instances.
'''
pass
| 30 | 26 | 14 | 3 | 8 | 3 | 3 | 0.35 | 1 | 8 | 2 | 0 | 25 | 4 | 25 | 25 | 374 | 93 | 208 | 65 | 178 | 73 | 167 | 61 | 141 | 8 | 1 | 2 | 63 |
1,073 |
4degrees/clique
|
4degrees_clique/source/clique/sorted_set.py
|
clique.sorted_set.SortedSet
|
class SortedSet(collections.MutableSet):
'''Maintain sorted collection of unique items.'''
def __init__(self, iterable=None):
'''Initialise with items from *iterable*.'''
super(SortedSet, self).__init__()
self._members = []
if iterable:
self.update(iterable)
def __str__(self):
'''Return string representation.'''
return str(self._members)
def __repr__(self):
'''Return representation.'''
return '<{0} "{1}">'.format(self.__class__.__name__, self)
def __contains__(self, item):
'''Return whether *item* is present.'''
return self._index(item) >= 0
def __len__(self):
'''Return number of items.'''
return len(self._members)
def __iter__(self):
'''Return iterator over items.'''
return iter(self._members)
def add(self, item):
'''Add *item*.'''
if not item in self:
index = bisect.bisect_right(self._members, item)
self._members.insert(index, item)
def discard(self, item):
'''Remove *item*.'''
index = self._index(item)
if index >= 0:
del self._members[index]
def update(self, iterable):
'''Update items with those from *iterable*.'''
for item in iterable:
self.add(item)
def _index(self, item):
'''Return index of *item* in member list or -1 if not present.'''
index = bisect.bisect_left(self._members, item)
if index != len(self) and self._members[index] == item:
return index
return -1
|
class SortedSet(collections.MutableSet):
'''Maintain sorted collection of unique items.'''
def __init__(self, iterable=None):
'''Initialise with items from *iterable*.'''
pass
def __str__(self):
'''Return string representation.'''
pass
def __repr__(self):
'''Return representation.'''
pass
def __contains__(self, item):
'''Return whether *item* is present.'''
pass
def __len__(self):
'''Return number of items.'''
pass
def __iter__(self):
'''Return iterator over items.'''
pass
def add(self, item):
'''Add *item*.'''
pass
def discard(self, item):
'''Remove *item*.'''
pass
def update(self, iterable):
'''Update items with those from *iterable*.'''
pass
def _index(self, item):
'''Return index of *item* in member list or -1 if not present.'''
pass
| 11 | 11 | 4 | 0 | 3 | 1 | 2 | 0.34 | 1 | 2 | 0 | 0 | 10 | 1 | 10 | 10 | 54 | 11 | 32 | 16 | 21 | 11 | 32 | 16 | 21 | 2 | 1 | 1 | 15 |
1,074 |
4degrees/riffle
|
4degrees_riffle/source/riffle/browser.py
|
riffle.browser.FilesystemBrowser
|
class FilesystemBrowser(QtGui.QDialog):
'''FilesystemBrowser dialog.'''
def __init__(self, root='', parent=None, iconFactory=None):
'''Initialise browser with *root* path.
Use an empty *root* path to specify the computer.
*parent* is the optional owner of this UI element.
*iconFactory* specifies the optional factory to pass to the model for
customising icons.
'''
super(FilesystemBrowser, self).__init__(parent=parent)
self._root = root
self._iconFactory = iconFactory
self._selected = []
self._construct()
self._postConstruction()
def _construct(self):
'''Construct widget.'''
self.setLayout(QtGui.QVBoxLayout())
self._headerLayout = QtGui.QHBoxLayout()
self._locationWidget = QtGui.QComboBox()
self._headerLayout.addWidget(self._locationWidget, stretch=1)
self._upButton = QtGui.QToolButton()
self._upButton.setIcon(QtGui.QIcon(':riffle/icon/up'))
self._headerLayout.addWidget(self._upButton)
self.layout().addLayout(self._headerLayout)
self._contentSplitter = QtGui.QSplitter()
self._bookmarksWidget = QtGui.QListView()
self._contentSplitter.addWidget(self._bookmarksWidget)
self._filesystemWidget = QtGui.QTableView()
self._filesystemWidget.setSelectionBehavior(
self._filesystemWidget.SelectRows
)
self._filesystemWidget.setSelectionMode(
self._filesystemWidget.SingleSelection
)
self._filesystemWidget.verticalHeader().hide()
self._contentSplitter.addWidget(self._filesystemWidget)
proxy = riffle.model.FilesystemSortProxy(self)
model = riffle.model.Filesystem(
path=self._root, parent=self, iconFactory=self._iconFactory
)
proxy.setSourceModel(model)
proxy.setDynamicSortFilter(True)
self._filesystemWidget.setModel(proxy)
self._filesystemWidget.setSortingEnabled(True)
self._contentSplitter.setStretchFactor(1, 1)
self.layout().addWidget(self._contentSplitter)
self._footerLayout = QtGui.QHBoxLayout()
self._footerLayout.addStretch(1)
self._cancelButton = QtGui.QPushButton('Cancel')
self._footerLayout.addWidget(self._cancelButton)
self._acceptButton = QtGui.QPushButton('Choose')
self._footerLayout.addWidget(self._acceptButton)
self.layout().addLayout(self._footerLayout)
def _postConstruction(self):
'''Perform post-construction operations.'''
self.setWindowTitle('Filesystem Browser')
self._filesystemWidget.sortByColumn(0, QtCore.Qt.AscendingOrder)
# TODO: Remove once bookmarks widget implemented.
self._bookmarksWidget.hide()
self._acceptButton.setDefault(True)
self._acceptButton.setDisabled(True)
self._acceptButton.clicked.connect(self.accept)
self._cancelButton.clicked.connect(self.reject)
self._configureShortcuts()
self.setLocation(self._root)
self._filesystemWidget.horizontalHeader().setResizeMode(
QtGui.QHeaderView.ResizeToContents
)
self._filesystemWidget.horizontalHeader().setResizeMode(
0, QtGui.QHeaderView.Stretch
)
self._upButton.clicked.connect(self._onNavigateUpButtonClicked)
self._locationWidget.currentIndexChanged.connect(
self._onNavigate
)
self._filesystemWidget.activated.connect(self._onActivateItem)
selectionModel = self._filesystemWidget.selectionModel()
selectionModel.currentRowChanged.connect(self._onSelectItem)
def _configureShortcuts(self):
'''Add keyboard shortcuts to navigate the filesystem.'''
self._upShortcut = QtGui.QShortcut(
QtGui.QKeySequence('Backspace'), self
)
self._upShortcut.setAutoRepeat(False)
self._upShortcut.activated.connect(self._onNavigateUpButtonClicked)
def _onActivateItem(self, index):
'''Handle activation of item in listing.'''
item = self._filesystemWidget.model().item(index)
if not isinstance(item, riffle.model.File):
self._acceptButton.setDisabled(True)
self.setLocation(item.path, interactive=True)
def _onSelectItem(self, selection, previousSelection):
'''Handle selection of item in listing.'''
self._acceptButton.setEnabled(True)
del self._selected[:]
item = self._filesystemWidget.model().item(selection)
self._selected.append(item.path)
def _onNavigate(self, index):
'''Handle selection of path segment.'''
if index > 0:
self.setLocation(
self._locationWidget.itemData(index), interactive=True
)
def _onNavigateUpButtonClicked(self):
'''Navigate up a directory on button click.'''
index = self._locationWidget.currentIndex()
self._onNavigate(index + 1)
def _segmentPath(self, path):
'''Return list of valid *path* segments.'''
parts = []
model = self._filesystemWidget.model()
# Separate root path from remainder.
remainder = path
while True:
if remainder == model.root.path:
break
if remainder:
parts.append(remainder)
head, tail = os.path.split(remainder)
if head == remainder:
break
remainder = head
parts.append(model.root.path)
return parts
def setLocation(self, path, interactive=False):
'''Set current location to *path*.
*path* must be the same as root or under the root.
.. note::
Comparisons are case-sensitive. If you set the root as 'D:/' then
location can be set as 'D:/folder' *not* 'd:/folder'.
If *interactive* is True, catch any exception occurring and display an
appropriate warning dialog to the user. Otherwise allow exceptions to
bubble up as normal.
'''
try:
self._setLocation(path)
except Exception as error:
if not interactive:
raise
else:
warning_dialog = QtGui.QMessageBox(
QtGui.QMessageBox.Warning,
'Location is not available',
'{0} is not accessible.'.format(path),
QtGui.QMessageBox.Ok,
self
)
warning_dialog.setDetailedText(str(error))
warning_dialog.exec_()
def _setLocation(self, path):
'''Set current location to *path*.
*path* must be the same as root or under the root.
.. note::
Comparisons are case-sensitive. If you set the root as 'D:/' then
location can be set as 'D:/folder' *not* 'd:/folder'.
'''
model = self._filesystemWidget.model()
if not path.startswith(model.root.path):
raise ValueError('Location must be root or under root.')
# Ensure children for each segment in path are loaded.
segments = self._segmentPath(path)
for segment in reversed(segments):
pathIndex = model.pathIndex(segment)
model.fetchMore(pathIndex)
self._filesystemWidget.setRootIndex(model.pathIndex(path))
self._locationWidget.clear()
# Add history entry for each segment.
for segment in segments:
index = model.pathIndex(segment)
if not index.isValid():
# Root item.
icon = model.iconFactory.icon(
riffle.icon_factory.IconType.Computer
)
self._locationWidget.addItem(
icon, model.root.path or model.root.name, model.root.path
)
else:
icon = model.icon(index)
self._locationWidget.addItem(icon, segment, segment)
if self._locationWidget.count() > 1:
self._upButton.setEnabled(True)
self._upShortcut.setEnabled(True)
else:
self._upButton.setEnabled(False)
self._upShortcut.setEnabled(False)
def selected(self):
'''Return selected paths.'''
return self._selected[:]
|
class FilesystemBrowser(QtGui.QDialog):
'''FilesystemBrowser dialog.'''
def __init__(self, root='', parent=None, iconFactory=None):
'''Initialise browser with *root* path.
Use an empty *root* path to specify the computer.
*parent* is the optional owner of this UI element.
*iconFactory* specifies the optional factory to pass to the model for
customising icons.
'''
pass
def _construct(self):
'''Construct widget.'''
pass
def _postConstruction(self):
'''Perform post-construction operations.'''
pass
def _configureShortcuts(self):
'''Add keyboard shortcuts to navigate the filesystem.'''
pass
def _onActivateItem(self, index):
'''Handle activation of item in listing.'''
pass
def _onSelectItem(self, selection, previousSelection):
'''Handle selection of item in listing.'''
pass
def _onNavigate(self, index):
'''Handle selection of path segment.'''
pass
def _onNavigateUpButtonClicked(self):
'''Navigate up a directory on button click.'''
pass
def _segmentPath(self, path):
'''Return list of valid *path* segments.'''
pass
def setLocation(self, path, interactive=False):
'''Set current location to *path*.
*path* must be the same as root or under the root.
.. note::
Comparisons are case-sensitive. If you set the root as 'D:/' then
location can be set as 'D:/folder' *not* 'd:/folder'.
If *interactive* is True, catch any exception occurring and display an
appropriate warning dialog to the user. Otherwise allow exceptions to
bubble up as normal.
'''
pass
def _setLocation(self, path):
'''Set current location to *path*.
*path* must be the same as root or under the root.
.. note::
Comparisons are case-sensitive. If you set the root as 'D:/' then
location can be set as 'D:/folder' *not* 'd:/folder'.
'''
pass
def selected(self):
'''Return selected paths.'''
pass
| 13 | 13 | 20 | 4 | 13 | 3 | 2 | 0.23 | 1 | 5 | 0 | 0 | 12 | 13 | 12 | 12 | 249 | 59 | 154 | 44 | 141 | 36 | 125 | 43 | 112 | 6 | 1 | 2 | 25 |
1,075 |
4degrees/riffle
|
4degrees_riffle/setup.py
|
setup.PyTest
|
class PyTest(TestCommand):
'''Pytest command.'''
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
'''Import pytest and run.'''
import pytest
errno = pytest.main(self.test_args)
raise SystemExit(errno)
|
class PyTest(TestCommand):
'''Pytest command.'''
def finalize_options(self):
pass
def run_tests(self):
'''Import pytest and run.'''
pass
| 3 | 2 | 5 | 0 | 4 | 1 | 1 | 0.22 | 1 | 1 | 0 | 0 | 2 | 2 | 2 | 2 | 13 | 2 | 9 | 7 | 5 | 2 | 9 | 7 | 5 | 1 | 1 | 0 | 2 |
1,076 |
4degrees/riffle
|
4degrees_riffle/setup.py
|
setup.Clean
|
class Clean(CleanCommand):
'''Custom clean to remove built resources and distributions.'''
def run(self):
'''Run clean.'''
relative_resource_path = os.path.relpath(
RESOURCE_TARGET_PATH, ROOT_PATH
)
if os.path.exists(relative_resource_path):
os.remove(relative_resource_path)
else:
distutils.log.warn(
'\'{0}\' does not exist -- can\'t clean it'
.format(relative_resource_path)
)
relative_compiled_resource_path = relative_resource_path + 'c'
if os.path.exists(relative_compiled_resource_path):
os.remove(relative_compiled_resource_path)
else:
distutils.log.warn(
'\'{0}\' does not exist -- can\'t clean it'
.format(relative_compiled_resource_path)
)
CleanCommand.run(self)
|
class Clean(CleanCommand):
'''Custom clean to remove built resources and distributions.'''
def run(self):
'''Run clean.'''
pass
| 2 | 2 | 22 | 1 | 20 | 1 | 3 | 0.1 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 34 | 25 | 2 | 21 | 4 | 19 | 2 | 11 | 4 | 9 | 3 | 2 | 1 | 3 |
1,077 |
4degrees/riffle
|
4degrees_riffle/setup.py
|
setup.BuildResources
|
class BuildResources(Command):
'''Build additional resources.'''
user_options = []
def initialize_options(self):
'''Configure default options.'''
def finalize_options(self):
'''Finalize options to be used.'''
self.resource_source_path = os.path.join(RESOURCE_PATH, 'resource.qrc')
self.resource_target_path = RESOURCE_TARGET_PATH
def run(self):
'''Run build.'''
if ON_READ_THE_DOCS:
# PySide not available.
return
try:
pyside_rcc_command = 'pyside-rcc'
# On Windows, pyside-rcc is not automatically available on the
# PATH so try to find it manually.
if sys.platform == 'win32':
import PySide
pyside_rcc_command = os.path.join(
os.path.dirname(PySide.__file__),
'pyside-rcc.exe'
)
subprocess.check_call([
pyside_rcc_command,
'-o',
self.resource_target_path,
self.resource_source_path
])
except (subprocess.CalledProcessError, OSError):
print(
'Error compiling resource.py using pyside-rcc. Possibly '
'pyside-rcc could not be found. You might need to manually add '
'it to your PATH.'
)
raise SystemExit()
|
class BuildResources(Command):
'''Build additional resources.'''
def initialize_options(self):
'''Configure default options.'''
pass
def finalize_options(self):
'''Finalize options to be used.'''
pass
def run(self):
'''Run build.'''
pass
| 4 | 4 | 12 | 1 | 9 | 2 | 2 | 0.23 | 1 | 3 | 0 | 0 | 3 | 2 | 3 | 42 | 44 | 7 | 30 | 9 | 25 | 7 | 18 | 9 | 13 | 4 | 2 | 2 | 6 |
1,078 |
4degrees/riffle
|
4degrees_riffle/setup.py
|
setup.Build
|
class Build(BuildCommand):
'''Custom build to pre-build resources.'''
def run(self):
'''Run build ensuring build_resources called first.'''
self.run_command('build_resources')
BuildCommand.run(self)
|
class Build(BuildCommand):
'''Custom build to pre-build resources.'''
def run(self):
'''Run build ensuring build_resources called first.'''
pass
| 2 | 2 | 4 | 0 | 3 | 1 | 1 | 0.5 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 38 | 7 | 1 | 4 | 2 | 2 | 2 | 4 | 2 | 2 | 1 | 2 | 0 | 1 |
1,079 |
4degrees/riffle
|
4degrees_riffle/source/riffle/model.py
|
riffle.model.Mount
|
class Mount(Directory):
'''Represent mount point.'''
@property
def type(self):
'''Return type of item as string.'''
return 'Mount'
@property
def size(self):
'''Return size of item.'''
return None
@property
def modified(self):
'''Return last modified date of item.'''
return None
|
class Mount(Directory):
'''Represent mount point.'''
@property
def type(self):
'''Return type of item as string.'''
pass
@property
def size(self):
'''Return size of item.'''
pass
@property
def modified(self):
'''Return last modified date of item.'''
pass
| 7 | 4 | 3 | 0 | 2 | 1 | 1 | 0.4 | 1 | 0 | 0 | 0 | 3 | 0 | 3 | 19 | 17 | 3 | 10 | 7 | 3 | 4 | 7 | 4 | 3 | 1 | 3 | 0 | 3 |
1,080 |
4degrees/riffle
|
4degrees_riffle/source/riffle/model.py
|
riffle.model.Item
|
class Item(object):
'''Represent filesystem item.'''
def __init__(self, path):
'''Initialise item with *path*.'''
super(Item, self).__init__()
self.path = path
self.children = []
self.parent = None
self._fetched = False
def __repr__(self):
'''Return representation.'''
return '<{0} {1}>'.format(self.__class__.__name__, self.path)
@property
def name(self):
'''Return name of item.'''
return os.path.basename(self.path) or self.path
@property
def size(self):
'''Return size of item.'''
return os.path.getsize(self.path)
@property
def type(self):
'''Return type of item as string.'''
return ''
@property
def modified(self):
'''Return last modified date of item.'''
return datetime.fromtimestamp(os.path.getmtime(self.path))
@property
def row(self):
'''Return index of this item in its parent or 0 if no parent.'''
if self.parent:
return self.parent.children.index(self)
return 0
def addChild(self, item):
'''Add *item* as child of this item.'''
if item.parent and item.parent != self:
item.parent.removeChild(item)
self.children.append(item)
item.parent = self
def removeChild(self, item):
'''Remove *item* from children.'''
item.parent = None
self.children.remove(item)
def canFetchMore(self):
'''Return whether more items can be fetched under this one.'''
if not self._fetched:
if self.mayHaveChildren():
return True
return False
def mayHaveChildren(self):
'''Return whether item may have children.'''
return True
def fetchChildren(self):
'''Fetch and return new children.
Will only fetch children whilst canFetchMore is True.
.. note::
It is the caller's responsibility to add each fetched child to this
parent if desired using :py:meth:`Item.addChild`.
'''
if not self.canFetchMore():
return []
children = self._fetchChildren()
self._fetched = True
return children
def _fetchChildren(self):
'''Fetch and return new child items.
Override in subclasses to fetch actual children and return list of
*unparented* :py:class:`Item` instances.
'''
return []
def refetch(self):
'''Reload children.'''
# Reset children
for child in self.children[:]:
self.removeChild(child)
# Enable children fetching
self._fetched = False
|
class Item(object):
'''Represent filesystem item.'''
def __init__(self, path):
'''Initialise item with *path*.'''
pass
def __repr__(self):
'''Return representation.'''
pass
@property
def name(self):
'''Return name of item.'''
pass
@property
def size(self):
'''Return size of item.'''
pass
@property
def type(self):
'''Return type of item as string.'''
pass
@property
def modified(self):
'''Return last modified date of item.'''
pass
@property
def row(self):
'''Return index of this item in its parent or 0 if no parent.'''
pass
def addChild(self, item):
'''Add *item* as child of this item.'''
pass
def removeChild(self, item):
'''Remove *item* from children.'''
pass
def canFetchMore(self):
'''Return whether more items can be fetched under this one.'''
pass
def mayHaveChildren(self):
'''Return whether item may have children.'''
pass
def fetchChildren(self):
'''Fetch and return new children.
Will only fetch children whilst canFetchMore is True.
.. note::
It is the caller's responsibility to add each fetched child to this
parent if desired using :py:meth:`Item.addChild`.
'''
pass
def _fetchChildren(self):
'''Fetch and return new child items.
Override in subclasses to fetch actual children and return list of
*unparented* :py:class:`Item` instances.
'''
pass
def refetch(self):
'''Reload children.'''
pass
| 20 | 15 | 6 | 1 | 3 | 2 | 1 | 0.47 | 1 | 2 | 0 | 4 | 14 | 4 | 14 | 14 | 105 | 27 | 53 | 26 | 33 | 25 | 48 | 21 | 33 | 3 | 1 | 2 | 20 |
1,081 |
4degrees/riffle
|
4degrees_riffle/source/riffle/model.py
|
riffle.model.FilesystemSortProxy
|
class FilesystemSortProxy(QSortFilterProxyModel):
'''Sort directories before files.'''
def lessThan(self, left, right):
'''Return ordering of *left* vs *right*.'''
sourceModel = self.sourceModel()
if sourceModel:
leftItem = sourceModel.item(left)
rightItem = sourceModel.item(right)
if (isinstance(leftItem, Directory)
and not isinstance(rightItem, Directory)):
return self.sortOrder() == Qt.AscendingOrder
elif (not isinstance(leftItem, Directory)
and isinstance(rightItem, Directory)):
return self.sortOrder() == Qt.DescendingOrder
return super(FilesystemSortProxy, self).lessThan(left, right)
@property
def root(self):
'''Return root of model.'''
sourceModel = self.sourceModel()
if not sourceModel:
return None
return sourceModel.root
@property
def iconFactory(self):
'''Return iconFactory of model.'''
sourceModel = self.sourceModel()
if not sourceModel:
return None
return sourceModel.iconFactory
def pathIndex(self, path):
'''Return index of item with *path*.'''
sourceModel = self.sourceModel()
if not sourceModel:
return QModelIndex()
return self.mapFromSource(sourceModel.pathIndex(path))
def item(self, index):
'''Return item at *index*.'''
sourceModel = self.sourceModel()
if not sourceModel:
return None
return sourceModel.item(self.mapToSource(index))
def icon(self, index):
'''Return icon for index.'''
sourceModel = self.sourceModel()
if not sourceModel:
return None
return sourceModel.icon(self.mapToSource(index))
def hasChildren(self, index):
'''Return if *index* has children.'''
sourceModel = self.sourceModel()
if not sourceModel:
return False
return sourceModel.hasChildren(self.mapToSource(index))
def canFetchMore(self, index):
'''Return if more data available for *index*.'''
sourceModel = self.sourceModel()
if not sourceModel:
return False
return sourceModel.canFetchMore(self.mapToSource(index))
def fetchMore(self, index):
'''Fetch additional data under *index*.'''
sourceModel = self.sourceModel()
if not sourceModel:
return False
return sourceModel.fetchMore(self.mapToSource(index))
|
class FilesystemSortProxy(QSortFilterProxyModel):
'''Sort directories before files.'''
def lessThan(self, left, right):
'''Return ordering of *left* vs *right*.'''
pass
@property
def root(self):
'''Return root of model.'''
pass
@property
def iconFactory(self):
'''Return iconFactory of model.'''
pass
def pathIndex(self, path):
'''Return index of item with *path*.'''
pass
def item(self, index):
'''Return item at *index*.'''
pass
def iconFactory(self):
'''Return icon for index.'''
pass
def hasChildren(self, index):
'''Return if *index* has children.'''
pass
def canFetchMore(self, index):
'''Return if more data available for *index*.'''
pass
def fetchMore(self, index):
'''Fetch additional data under *index*.'''
pass
| 12 | 10 | 8 | 2 | 6 | 1 | 2 | 0.18 | 1 | 2 | 1 | 0 | 9 | 0 | 9 | 9 | 89 | 24 | 55 | 23 | 43 | 10 | 50 | 21 | 40 | 4 | 1 | 2 | 20 |
1,082 |
4degrees/riffle
|
4degrees_riffle/source/riffle/model.py
|
riffle.model.Filesystem
|
class Filesystem(QAbstractItemModel):
'''Model representing filesystem.'''
ITEM_ROLE = Qt.UserRole + 1
def __init__(self, path='', parent=None, iconFactory=None):
'''Initialise with root *path*.'''
super(Filesystem, self).__init__(parent=parent)
self.root = ItemFactory(path)
self.columns = ['Name', 'Size', 'Type', 'Date Modified']
if iconFactory is None:
# Local import to circumvent circular dependency.
import riffle.icon_factory
iconFactory = riffle.icon_factory.IconFactory()
self.iconFactory = iconFactory
def rowCount(self, parent):
'''Return number of children *parent* index has.'''
if parent.column() > 0:
return 0
if parent.isValid():
item = parent.internalPointer()
else:
item = self.root
return len(item.children)
def columnCount(self, parent):
'''Return amount of data *parent* index has.'''
return len(self.columns)
def flags(self, index):
'''Return flags for *index*.'''
if not index.isValid():
return Qt.NoItemFlags
return Qt.ItemIsEnabled | Qt.ItemIsSelectable
def index(self, row, column, parent):
'''Return index for *row* and *column* under *parent*.'''
if not self.hasIndex(row, column, parent):
return QModelIndex()
if not parent.isValid():
item = self.root
else:
item = parent.internalPointer()
try:
child = item.children[row]
except IndexError:
return QModelIndex()
else:
return self.createIndex(row, column, child)
def pathIndex(self, path):
'''Return index of item with *path*.'''
if path == self.root.path:
return QModelIndex()
if not path.startswith(self.root.path):
return QModelIndex()
parts = []
while True:
if path == self.root.path:
break
head, tail = os.path.split(path)
if head == path:
if path:
parts.append(path)
break
parts.append(tail)
path = head
parts.reverse()
if parts:
item = self.root
count = 0
for count, part in enumerate(parts):
matched = False
for child in item.children:
if child.name == part:
item = child
matched = True
break
if not matched:
break
if count + 1 == len(parts):
return self.createIndex(item.row, 0, item)
return QModelIndex()
def parent(self, index):
'''Return parent of *index*.'''
if not index.isValid():
return QModelIndex()
item = index.internalPointer()
if not item:
return QModelIndex()
parent = item.parent
if not parent or parent == self.root:
return QModelIndex()
return self.createIndex(parent.row, 0, parent)
def item(self, index):
'''Return item at *index*.'''
return self.data(index, role=self.ITEM_ROLE)
def icon(self, index):
'''Return icon for index.'''
return self.data(index, role=Qt.DecorationRole)
def data(self, index, role):
'''Return data for *index* according to *role*.'''
if not index.isValid():
return None
column = index.column()
item = index.internalPointer()
if role == self.ITEM_ROLE:
return item
elif role == Qt.DisplayRole:
if column == 0:
return item.name
elif column == 1:
if item.size:
return item.size
elif column == 2:
return item.type
elif column == 3:
if item.modified is not None:
return item.modified.strftime('%c')
elif role == Qt.DecorationRole:
if column == 0:
return self.iconFactory.icon(item)
elif role == Qt.TextAlignmentRole:
if column == 1:
return Qt.AlignRight
else:
return Qt.AlignLeft
return None
def headerData(self, section, orientation, role):
'''Return label for *section* according to *orientation* and *role*.'''
if orientation == Qt.Horizontal:
if section < len(self.columns):
column = self.columns[section]
if role == Qt.DisplayRole:
return column
return None
def hasChildren(self, index):
'''Return if *index* has children.
Optimised to avoid loading children at this stage.
'''
if not index.isValid():
item = self.root
else:
item = index.internalPointer()
if not item:
return False
return item.mayHaveChildren()
def canFetchMore(self, index):
'''Return if more data available for *index*.'''
if not index.isValid():
item = self.root
else:
item = index.internalPointer()
return item.canFetchMore()
def fetchMore(self, index):
'''Fetch additional data under *index*.'''
if not index.isValid():
item = self.root
else:
item = index.internalPointer()
if item.canFetchMore():
startIndex = len(item.children)
additionalChildren = item.fetchChildren()
endIndex = startIndex + len(additionalChildren) - 1
if endIndex >= startIndex:
self.beginInsertRows(index, startIndex, endIndex)
for newChild in additionalChildren:
item.addChild(newChild)
self.endInsertRows()
def reset(self):
'''Reset model'''
self.beginResetModel()
self.root.refetch()
self.endResetModel()
|
class Filesystem(QAbstractItemModel):
'''Model representing filesystem.'''
def __init__(self, path='', parent=None, iconFactory=None):
'''Initialise with root *path*.'''
pass
def rowCount(self, parent):
'''Return number of children *parent* index has.'''
pass
def columnCount(self, parent):
'''Return amount of data *parent* index has.'''
pass
def flags(self, index):
'''Return flags for *index*.'''
pass
def index(self, row, column, parent):
'''Return index for *row* and *column* under *parent*.'''
pass
def pathIndex(self, path):
'''Return index of item with *path*.'''
pass
def parent(self, index):
'''Return parent of *index*.'''
pass
def item(self, index):
'''Return item at *index*.'''
pass
def icon(self, index):
'''Return icon for index.'''
pass
def data(self, index, role):
'''Return data for *index* according to *role*.'''
pass
def headerData(self, section, orientation, role):
'''Return label for *section* according to *orientation* and *role*.'''
pass
def hasChildren(self, index):
'''Return if *index* has children.
Optimised to avoid loading children at this stage.
'''
pass
def canFetchMore(self, index):
'''Return if more data available for *index*.'''
pass
def fetchMore(self, index):
'''Fetch additional data under *index*.'''
pass
def reset(self):
'''Reset model'''
pass
| 16 | 16 | 13 | 2 | 10 | 1 | 4 | 0.13 | 1 | 4 | 1 | 0 | 15 | 3 | 15 | 15 | 217 | 49 | 149 | 43 | 132 | 19 | 137 | 43 | 120 | 14 | 1 | 4 | 60 |
1,083 |
4degrees/riffle
|
4degrees_riffle/source/riffle/model.py
|
riffle.model.File
|
class File(Item):
'''Represent file.'''
@property
def type(self):
'''Return type of item as string.'''
return 'File'
def mayHaveChildren(self):
'''Return whether item may have children.'''
return False
|
class File(Item):
'''Represent file.'''
@property
def type(self):
'''Return type of item as string.'''
pass
def mayHaveChildren(self):
'''Return whether item may have children.'''
pass
| 4 | 3 | 3 | 0 | 2 | 1 | 1 | 0.5 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 16 | 11 | 2 | 6 | 4 | 2 | 3 | 5 | 3 | 2 | 1 | 2 | 0 | 2 |
1,084 |
4degrees/riffle
|
4degrees_riffle/source/riffle/model.py
|
riffle.model.Directory
|
class Directory(Item):
'''Represent directory.'''
@property
def type(self):
'''Return type of item as string.'''
return 'Directory'
def _fetchChildren(self):
'''Fetch and return new child items.'''
children = []
# List paths under this directory.
paths = []
for name in os.listdir(self.path):
paths.append(os.path.normpath(os.path.join(self.path, name)))
# Handle collections.
collections, remainder = clique.assemble(
paths, [clique.PATTERNS['frames']]
)
for path in remainder:
try:
child = ItemFactory(path)
except ValueError:
pass
else:
children.append(child)
for collection in collections:
children.append(Collection(collection))
return children
|
class Directory(Item):
'''Represent directory.'''
@property
def type(self):
'''Return type of item as string.'''
pass
def _fetchChildren(self):
'''Fetch and return new child items.'''
pass
| 4 | 3 | 15 | 3 | 10 | 2 | 3 | 0.23 | 1 | 2 | 1 | 1 | 2 | 0 | 2 | 16 | 34 | 7 | 22 | 11 | 18 | 5 | 19 | 10 | 16 | 5 | 2 | 2 | 6 |
1,085 |
4degrees/riffle
|
4degrees_riffle/source/riffle/model.py
|
riffle.model.Computer
|
class Computer(Item):
'''Represent root.'''
def __init__(self):
'''Initialise item.'''
super(Computer, self).__init__('')
@property
def name(self):
'''Return name of item.'''
return 'Computer'
@property
def type(self):
'''Return type of item as string.'''
return 'Root'
def _fetchChildren(self):
'''Fetch and return new child items.'''
children = []
for entry in QDir.drives():
path = os.path.normpath(entry.canonicalFilePath())
children.append(Mount(path))
return children
|
class Computer(Item):
'''Represent root.'''
def __init__(self):
'''Initialise item.'''
pass
@property
def name(self):
'''Return name of item.'''
pass
@property
def type(self):
'''Return type of item as string.'''
pass
def _fetchChildren(self):
'''Fetch and return new child items.'''
pass
| 7 | 5 | 4 | 0 | 3 | 1 | 1 | 0.33 | 1 | 2 | 1 | 0 | 4 | 0 | 4 | 18 | 25 | 5 | 15 | 10 | 8 | 5 | 13 | 8 | 8 | 2 | 2 | 1 | 5 |
1,086 |
4degrees/riffle
|
4degrees_riffle/source/riffle/model.py
|
riffle.model.Collection
|
class Collection(Item):
'''Represent collection.'''
def __init__(self, collection):
'''Initialise item with *collection*.
*collection* should be an instance of :py:class:`clique.Collection`.
'''
self._collection = collection
super(Collection, self).__init__(self._collection.format())
@property
def type(self):
'''Return type of item as string.'''
return 'Collection'
@property
def size(self):
'''Return size of item.'''
return None
@property
def modified(self):
'''Return last modified date of item.'''
return None
def _fetchChildren(self):
'''Fetch and return new child items.'''
children = []
for path in self._collection:
try:
child = ItemFactory(path)
except ValueError:
pass
else:
children.append(child)
return children
|
class Collection(Item):
'''Represent collection.'''
def __init__(self, collection):
'''Initialise item with *collection*.
*collection* should be an instance of :py:class:`clique.Collection`.
'''
pass
@property
def type(self):
'''Return type of item as string.'''
pass
@property
def size(self):
'''Return size of item.'''
pass
@property
def modified(self):
'''Return last modified date of item.'''
pass
def _fetchChildren(self):
'''Fetch and return new child items.'''
pass
| 9 | 6 | 6 | 1 | 4 | 1 | 1 | 0.35 | 1 | 2 | 0 | 0 | 5 | 1 | 5 | 19 | 39 | 8 | 23 | 13 | 14 | 8 | 20 | 10 | 14 | 3 | 2 | 2 | 7 |
1,087 |
4degrees/riffle
|
4degrees_riffle/source/riffle/icon_factory.py
|
riffle.icon_factory.IconType
|
class IconType(object):
'''Icon types.'''
Computer = 'Computer',
File = 'File',
Directory = 'Directory',
Mount = 'Mount',
Collection = 'Collection'
Unknown = 'Unknown'
|
class IconType(object):
'''Icon types.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.14 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 9 | 1 | 7 | 7 | 6 | 1 | 7 | 7 | 6 | 0 | 1 | 0 | 0 |
1,088 |
4degrees/riffle
|
4degrees_riffle/setup.py
|
setup.Install
|
class Install(InstallCommand):
'''Custom install to pre-build resources.'''
def do_egg_install(self):
'''Run install ensuring build_resources called first.
.. note::
`do_egg_install` used rather than `run` as sometimes `run` is not
called at all by setuptools.
'''
self.run_command('build_resources')
InstallCommand.do_egg_install(self)
|
class Install(InstallCommand):
'''Custom install to pre-build resources.'''
def do_egg_install(self):
'''Run install ensuring build_resources called first.
.. note::
`do_egg_install` used rather than `run` as sometimes `run` is not
called at all by setuptools.
'''
pass
| 2 | 2 | 11 | 3 | 3 | 5 | 1 | 1.5 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 58 | 14 | 4 | 4 | 2 | 2 | 6 | 4 | 2 | 2 | 1 | 3 | 0 | 1 |
1,089 |
4degrees/riffle
|
4degrees_riffle/source/riffle/icon_factory.py
|
riffle.icon_factory.IconFactory
|
class IconFactory(object):
'''Icon provider.'''
def icon(self, specification):
'''Return appropriate icon for *specification*.
*specification* should be either:
* An instance of :py:class:`riffle.model.Item`
* One of the defined icon types (:py:class:`IconType`)
'''
if isinstance(specification, riffle.model.Item):
specification = self.type(specification)
icon = None
if specification == IconType.Computer:
icon = QtGui.QIcon(':riffle/icon/computer')
elif specification == IconType.Mount:
icon = QtGui.QIcon(':riffle/icon/drive')
elif specification == IconType.Directory:
icon = QtGui.QIcon(':riffle/icon/folder')
elif specification == IconType.File:
icon = QtGui.QIcon(':riffle/icon/file')
elif specification == IconType.Collection:
icon = QtGui.QIcon(':riffle/icon/collection')
return icon
def type(self, item):
'''Return appropriate icon type for *item*.'''
iconType = IconType.Unknown
if isinstance(item, riffle.model.Computer):
iconType = IconType.Computer
elif isinstance(item, riffle.model.Mount):
iconType = IconType.Mount
elif isinstance(item, riffle.model.Directory):
iconType = IconType.Directory
elif isinstance(item, riffle.model.File):
iconType = IconType.File
elif isinstance(item, riffle.model.Collection):
iconType = IconType.Collection
return iconType
|
class IconFactory(object):
'''Icon provider.'''
def icon(self, specification):
'''Return appropriate icon for *specification*.
*specification* should be either:
* An instance of :py:class:`riffle.model.Item`
* One of the defined icon types (:py:class:`IconType`)
'''
pass
def type(self, item):
'''Return appropriate icon type for *item*.'''
pass
| 3 | 3 | 25 | 8 | 14 | 3 | 7 | 0.24 | 1 | 7 | 7 | 0 | 2 | 0 | 2 | 2 | 54 | 18 | 29 | 5 | 26 | 7 | 21 | 5 | 18 | 7 | 1 | 1 | 13 |
1,090 |
50onRed/smr
|
50onRed_smr/smr/config.py
|
smr.config.DefaultConfig
|
class DefaultConfig(object):
def __init__(self):
self.paramiko_log_level = "warning"
self.workers = 8
self.output_job_progress = True
self.aws_access_key = None
self.aws_secret_key = None
self.aws_ec2_region = "us-east-1"
self.aws_ec2_ami = "ami-30837058"
self.aws_ec2_instance_type = "m3.large"
self.aws_ec2_security_group = ["default"]
self.aws_ec2_ssh_username = "ubuntu"
self.aws_ec2_workers = 1
self.aws_ec2_remote_config_path = "/tmp/smr_config.py"
self.aws_ec2_initialization_commands = [
"sudo apt-get update",
"sudo apt-get -q -y install python-pip python-dev gcc build-essential libssl-dev libffi-dev",
#"sudo apt-get -q -y install python-pip python-dev git",
"sudo pip install smr=={}".format(__version__)
#"sudo pip install git+git://github.com/idyedov/smr.git"
]
self.aws_iam_profile = None
self.cpu_usage_interval = 0.1
self.screen_refresh_interval = 1.0
self.date_range = None
self.start_date = None
self.end_date = None
|
class DefaultConfig(object):
def __init__(self):
pass
| 2 | 0 | 26 | 0 | 24 | 2 | 1 | 0.08 | 1 | 0 | 0 | 0 | 1 | 19 | 1 | 1 | 27 | 0 | 25 | 21 | 23 | 2 | 21 | 21 | 19 | 1 | 1 | 0 | 1 |
1,091 |
5j9/flake8-invalid-escape-sequences
|
5j9_flake8-invalid-escape-sequences/tests/test.py
|
test.PluginTest
|
class PluginTest(TestCase):
"""Test the plugin."""
def test_plugin(self):
"""Run the plugin on test_case.py."""
# Fist see that the plugin actually exists
popen = Popen(
args=['python', '-m', 'flake8', '--version'],
stdout=PIPE,
universal_newlines=True,
)
stdout_data, stderr_data = popen.communicate()
assert stderr_data is None
self.assertIn(
'flake8-invalid-escape-sequences',
stdout_data,
'it seems that flake8-invalid-escape-sequences is not installed',
)
popen = Popen(
args=[
'python', '-m', 'flake8', '--select=IES', '--ignore=H,E,D,N,F',
'test_case.py'
],
stdout=PIPE,
universal_newlines=True,
)
stdout_data, stderr_data = popen.communicate()
assert stderr_data is None
self.assertEqual(
stdout_data,
'test_case.py:5:12: IES: invalid escape sequence \\[\n'
'test_case.py:6:12: IES: invalid escape sequence \\[\n'
'test_case.py:7:12: IES: invalid escape sequence \\[\n'
'test_case.py:8:12: IES: invalid escape sequence \\[\n'
'test_case.py:9:12: IES: invalid escape sequence \\[\n'
'test_case.py:10:12: IES: invalid escape sequence \\[\n'
'test_case.py:11:12: IES: invalid escape sequence \\[\n'
)
|
class PluginTest(TestCase):
'''Test the plugin.'''
def test_plugin(self):
'''Run the plugin on test_case.py.'''
pass
| 2 | 2 | 35 | 0 | 33 | 2 | 1 | 0.09 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 73 | 39 | 2 | 34 | 4 | 32 | 3 | 10 | 4 | 8 | 1 | 2 | 0 | 1 |
1,092 |
5j9/wikitextparser
|
wikitextparser/_wikitext.py
|
wikitextparser._wikitext.DeadIndex
|
class DeadIndex(int):
"""Do not allow adding to another integer but allow usage in a slice.
Addition of indices is the main operation during mutation of WikiText
objects.
"""
__slots__ = ()
def __add__(self, o):
raise DeadIndexError(
'this usually means that the object has died '
'(overwritten or deleted) and cannot be mutated'
)
__radd__ = __add__
def __repr__(self):
return 'DeadIndex()'
|
class DeadIndex(int):
'''Do not allow adding to another integer but allow usage in a slice.
Addition of indices is the main operation during mutation of WikiText
objects.
'''
def __add__(self, o):
pass
def __repr__(self):
pass
| 3 | 1 | 4 | 0 | 4 | 0 | 1 | 0.4 | 1 | 1 | 1 | 0 | 2 | 0 | 2 | 57 | 19 | 5 | 10 | 5 | 7 | 4 | 7 | 5 | 4 | 1 | 2 | 0 | 2 |
1,093 |
5j9/wikitextparser
|
wikitextparser/_comment_bold_italic.py
|
wikitextparser._comment_bold_italic.Comment
|
class Comment(SubWikiText):
__slots__ = ()
@property
def contents(self) -> str:
"""Return contents of this comment."""
s = self.string
if s[-3:] == '-->':
return s[4:-3]
return s[4:]
@property
def comments(self) -> list[Comment]:
return []
|
class Comment(SubWikiText):
@property
def contents(self) -> str:
'''Return contents of this comment.'''
pass
@property
def comments(self) -> list[Comment]:
pass
| 5 | 1 | 4 | 0 | 4 | 1 | 2 | 0.09 | 1 | 2 | 0 | 0 | 2 | 0 | 2 | 56 | 14 | 2 | 11 | 7 | 6 | 1 | 9 | 5 | 6 | 2 | 2 | 1 | 3 |
1,094 |
5j9/wikitextparser
|
wikitextparser/_comment_bold_italic.py
|
wikitextparser._comment_bold_italic.Italic
|
class Italic(BoldItalic):
__slots__ = ('end_token',)
def __init__(
self,
string: str | MutableSequence[str],
_type_to_spans: TypeToSpans | None = None,
_span: list[int] | None = None,
_type: str | int | None = None,
end_token: bool = True,
):
"""Initialize the Italic object.
:param end_token: set to True if the italic object ends with a '' token
False otherwise.
"""
super().__init__(string, _type_to_spans, _span, _type)
self.end_token = end_token
@property
def _match(self) -> Match[str]:
if self.end_token:
return ITALIC_FULLMATCH(self.string) # type: ignore
return ITALIC_NOEND_FULLMATCH(self.string)
|
class Italic(BoldItalic):
def __init__(
self,
string: str | MutableSequence[str],
_type_to_spans: TypeToSpans | None = None,
_span: list[int] | None = None,
_type: str | int | None = None,
end_token: bool = True,
):
'''Initialize the Italic object.
:param end_token: set to True if the italic object ends with a '' token
False otherwise.
'''
pass
@property
def _match(self) -> Match[str]:
pass
| 4 | 1 | 10 | 1 | 7 | 3 | 2 | 0.35 | 1 | 5 | 0 | 0 | 2 | 1 | 2 | 60 | 24 | 3 | 17 | 13 | 6 | 6 | 9 | 5 | 6 | 2 | 3 | 1 | 3 |
1,095 |
5j9/wikitextparser
|
wikitextparser/_externallink.py
|
wikitextparser._externallink.ExternalLink
|
class ExternalLink(SubWikiText):
__slots__ = ()
@property
def url(self) -> str:
"""URL of the current ExternalLink object.
getter: Return the URL.
setter: Set a new value for URL. Convert add brackets for bare
external links.
"""
if self(0) == '[':
return self(1, URL_MATCH(self._ext_link_shadow, 1).end())
return self.string
@url.setter
def url(self, newurl: str) -> None:
if self(0) == '[':
self[1 : len('[' + self.url)] = newurl
else:
self[0 : len(self.url)] = newurl
@property
def text(self) -> str | None:
"""The text part (the part after the url).
getter: Return None if this is a bare link or has no associated text.
setter: Automatically put the ExternalLink in brackets if it's not
already.
deleter: Delete self.text, including the space before it.
"""
string = self.string
if string[0] == '[':
url_end = URL_MATCH(self._ext_link_shadow, 1).end()
end_char = string[url_end]
if end_char == ']':
return None
if end_char == ' ':
return string[url_end + 1 : -1]
return string[url_end:-1]
@text.setter
def text(self, newtext: str) -> None:
string = self.string
if string[0] == '[':
text = self.text
if text:
self[-len(text) - 1 : -1] = newtext
return
self.insert(-1, ' ' + newtext)
return
self.insert(len(string), ' ' + newtext + ']')
self.insert(0, '[')
@text.deleter
def text(self) -> None:
string = self.string
if string[0] != '[':
return
text = self.text
if text:
del self[-len(text) - 2 : -1]
@property
def in_brackets(self) -> bool:
"""Return true if the ExternalLink is in brackets. False otherwise."""
return self(0) == '['
@property
def external_links(self) -> list[ExternalLink]:
return []
|
class ExternalLink(SubWikiText):
@property
def url(self) -> str:
'''URL of the current ExternalLink object.
getter: Return the URL.
setter: Set a new value for URL. Convert add brackets for bare
external links.
'''
pass
@url.setter
def url(self) -> str:
pass
@property
def text(self) -> str | None:
'''The text part (the part after the url).
getter: Return None if this is a bare link or has no associated text.
setter: Automatically put the ExternalLink in brackets if it's not
already.
deleter: Delete self.text, including the space before it.
'''
pass
@text.setter
def text(self) -> str | None:
pass
@text.deleter
def text(self) -> str | None:
pass
@property
def in_brackets(self) -> bool:
'''Return true if the ExternalLink is in brackets. False otherwise.'''
pass
@property
def external_links(self) -> list[ExternalLink]:
pass
| 15 | 3 | 8 | 0 | 6 | 2 | 2 | 0.24 | 1 | 3 | 0 | 0 | 7 | 0 | 7 | 61 | 71 | 9 | 50 | 23 | 35 | 12 | 42 | 16 | 34 | 4 | 2 | 2 | 16 |
1,096 |
5j9/wikitextparser
|
wikitextparser/_parameter.py
|
wikitextparser._parameter.Parameter
|
class Parameter(SubWikiText):
__slots__ = ()
@property
def name(self) -> str:
"""Current parameter's name.
getter: Return current parameter's name.
setter: set a new name for the current parameter.
"""
pipe = self._shadow.find(124)
if pipe == -1:
return self(3, -3)
return self(3, pipe)
@name.setter
def name(self, newname: str) -> None:
pipe = self._shadow.find(124)
if pipe == -1:
self[3:-3] = newname
return
self[3:pipe] = newname
@property
def pipe(self) -> str:
"""Return `|` if there is a pipe (default value) in the Parameter.
Return '' otherwise.
"""
return '|' if self._shadow.find(124) != -1 else ''
@property
def default(self) -> str | None:
"""The default value of current parameter.
getter: Return None if there is no default.
setter: Set a new default value.
deleter: Delete the default value, including the pipe character.
"""
pipe = self._shadow.find(124)
if pipe == -1:
return None
return self(pipe + 1, -3)
@default.setter
def default(self, newdefault: str) -> None:
pipe = self._shadow.find(124)
if pipe == -1:
self.insert(-3, '|' + newdefault)
return
self[pipe + 1 : -3] = newdefault
@default.deleter
def default(self) -> None:
pipe = self._shadow.find(124)
if pipe == -1:
return
del self[pipe:-3]
def append_default(self, new_default_name: str) -> None:
"""Append a new default parameter in the appropriate place.
Add the new default to the innter-most parameter.
If the parameter already exists among defaults, don't change anything.
Example:
>>> p = Parameter('{{{p1|{{{p2|}}}}}}')
>>> p.append_default('p3')
>>> p
Parameter("'{{{p1|{{{p2|{{{p3|}}}}}}}}}'")
"""
stripped_default_name = new_default_name.strip(WS)
if stripped_default_name == self.name.strip(WS):
return
dig = True
innermost_param = self
while dig:
dig = False
default = innermost_param.default
for p in innermost_param.parameters:
if p.string == default:
if stripped_default_name == p.name.strip(WS):
return
innermost_param = p
dig = True
innermost_default = innermost_param.default
if innermost_default is None:
innermost_param.insert(-3, '|{{{' + new_default_name + '}}}')
else:
name = innermost_param.name
innermost_param[
len('{{{' + name + '|') : len(
'{{{' + name + '|' + innermost_default
)
] = '{{{' + new_default_name + '|' + innermost_default + '}}}'
@property
def parameters(self) -> list[Parameter]:
return super().parameters[1:]
@property
def _content_span(self) -> tuple[int, int]:
return 3, -3
|
class Parameter(SubWikiText):
@property
def name(self) -> str:
'''Current parameter's name.
getter: Return current parameter's name.
setter: set a new name for the current parameter.
'''
pass
@name.setter
def name(self) -> str:
pass
@property
def pipe(self) -> str:
'''Return `|` if there is a pipe (default value) in the Parameter.
Return '' otherwise.
'''
pass
@property
def default(self) -> str | None:
'''The default value of current parameter.
getter: Return None if there is no default.
setter: Set a new default value.
deleter: Delete the default value, including the pipe character.
'''
pass
@default.setter
def default(self) -> str | None:
pass
@default.deleter
def default(self) -> str | None:
pass
def append_default(self, new_default_name: str) -> None:
'''Append a new default parameter in the appropriate place.
Add the new default to the innter-most parameter.
If the parameter already exists among defaults, don't change anything.
Example:
>>> p = Parameter('{{{p1|{{{p2|}}}}}}')
>>> p.append_default('p3')
>>> p
Parameter("'{{{p1|{{{p2|{{{p3|}}}}}}}}}'")
'''
pass
@property
def parameters(self) -> list[Parameter]:
pass
@property
def _content_span(self) -> tuple[int, int]:
pass
| 18 | 4 | 9 | 1 | 6 | 2 | 2 | 0.31 | 1 | 5 | 0 | 0 | 9 | 0 | 9 | 63 | 103 | 14 | 68 | 31 | 50 | 21 | 55 | 23 | 45 | 7 | 2 | 4 | 21 |
1,097 |
5j9/wikitextparser
|
wikitextparser/_parser_function.py
|
wikitextparser._parser_function.SubWikiTextWithArgs
|
class SubWikiTextWithArgs(SubWikiText):
"""Define common attributes for `Template` and `ParserFunction`."""
__slots__ = ()
_name_args_matcher = NotImplemented
_first_arg_sep = 0
@property
def _content_span(self) -> tuple[int, int]:
return 2, -2
@property
def nesting_level(self) -> int:
"""Return the nesting level of self.
The minimum nesting_level is 0. Being part of any Template or
ParserFunction increases the level by one.
"""
return self._nesting_level(('Template', 'ParserFunction'))
@property
def arguments(self) -> list[Argument]:
"""Parse template content. Create self.name and self.arguments."""
shadow = self._shadow
split_spans = self._name_args_matcher(shadow, 2, -2).spans('arg')
if not split_spans:
return []
arguments = []
arguments_append = arguments.append
type_to_spans = self._type_to_spans
ss, se, _, _ = span = self._span_data
type_ = id(span)
lststr = self._lststr
arg_spans = type_to_spans.setdefault(type_, [])
span_tuple_to_span_get = {(s[0], s[1]): s for s in arg_spans}.get
for arg_self_start, arg_self_end in split_spans:
# todo: add byte array
s, e, _, _ = arg_span = [
ss + arg_self_start,
ss + arg_self_end,
None,
None,
]
old_span = span_tuple_to_span_get((s, e))
if old_span is None:
insort(arg_spans, arg_span)
else:
arg_span = old_span
arg = Argument(lststr, type_to_spans, arg_span, type_, self)
arg._span_data[3] = shadow[arg_self_start:arg_self_end]
arguments_append(arg)
return arguments
def get_lists(
self, pattern: str | Iterable[str] = (r'\#', r'\*', '[:;]')
) -> list[WikiList]:
"""Return the lists in all arguments.
For performance reasons it is usually preferred to get a specific
Argument and use the `get_lists` method of that argument instead.
"""
return [
lst
for arg in self.arguments
for lst in arg.get_lists(pattern)
if lst
]
@property
def name(self) -> str:
"""Template's name (includes whitespace).
getter: Return the name.
setter: Set a new name.
"""
sep = self._shadow.find(self._first_arg_sep)
if sep == -1:
return self(2, -2)
return self(2, sep)
@name.setter
def name(self, newname: str) -> None:
self[2 : 2 + len(self.name)] = newname
|
class SubWikiTextWithArgs(SubWikiText):
'''Define common attributes for `Template` and `ParserFunction`.'''
@property
def _content_span(self) -> tuple[int, int]:
pass
@property
def nesting_level(self) -> int:
'''Return the nesting level of self.
The minimum nesting_level is 0. Being part of any Template or
ParserFunction increases the level by one.
'''
pass
@property
def arguments(self) -> list[Argument]:
'''Parse template content. Create self.name and self.arguments.'''
pass
def get_lists(
self, pattern: str | Iterable[str] = (r'\#', r'\*', '[:;]')
) -> list[WikiList]:
'''Return the lists in all arguments.
For performance reasons it is usually preferred to get a specific
Argument and use the `get_lists` method of that argument instead.
'''
pass
@property
def name(self) -> str:
'''Template's name (includes whitespace).
getter: Return the name.
setter: Set a new name.
'''
pass
@name.setter
def name(self) -> str:
pass
| 12 | 5 | 11 | 1 | 8 | 3 | 2 | 0.28 | 1 | 6 | 2 | 2 | 6 | 0 | 6 | 60 | 84 | 11 | 58 | 33 | 44 | 16 | 40 | 25 | 33 | 4 | 2 | 2 | 10 |
1,098 |
5j9/wikitextparser
|
wikitextparser/_section.py
|
wikitextparser._section.Section
|
class Section(SubWikiText):
__slots__ = '_header_match_cache'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._header_match_cache = None, None
@property
def _header_match(self):
cached_match, cached_shadow = self._header_match_cache
shadow = self._shadow
if cached_shadow == shadow:
return cached_match
m = HEADER_MATCH(shadow)
self._header_match_cache = m, shadow
return m
@property
def level(self) -> int:
"""The level of this section.
getter: Return level which as an int in range(1,7) or 0 for the lead
section.
setter: Change the level.
"""
m = self._header_match
if m:
return len(m[1])
return 0
@level.setter
def level(self, value: int) -> None:
m = self._header_match
level_diff = len(m[1]) - value
if level_diff == 0:
return
if level_diff < 0:
new_equals = '=' * -level_diff
self.insert(0, new_equals)
self.insert(m.end(2) - level_diff, new_equals)
return
del self[:level_diff]
del self[m.end(2) : m.end(2) + level_diff]
@property
def title(self) -> str | None:
"""The title of this section.
getter: Return the title or None for lead sections or sections that
don't have any title.
setter: Set a new title.
deleter: Remove the title, including the equal sign and the newline
after it.
"""
m = self._header_match
if m is None:
return None
return self(m.start(2), m.end(2))
@title.setter
def title(self, value: str) -> None:
m = self._header_match
if m is None:
raise RuntimeError(
"Can't set title for a lead section. "
'Try adding it to contents.'
)
self[m.start(2) : m.end(2)] = value
@title.deleter
def title(self) -> None:
m = self._header_match
if m is None:
return
del self[m.start() : m.end()]
@property
def contents(self) -> str:
"""Contents of this section.
getter: return the contents
setter: Set contents to a new string value.
"""
m = self._header_match
if m is None:
return self(0, None)
return self(m.end(), None)
@contents.setter
def contents(self, value: str) -> None:
m = self._header_match
if m is None:
self[:] = value
return
self[m.end() :] = value
|
class Section(SubWikiText):
def __init__(self, *args, **kwargs):
pass
@property
def _header_match(self):
pass
@property
def level(self) -> int:
'''The level of this section.
getter: Return level which as an int in range(1,7) or 0 for the lead
section.
setter: Change the level.
'''
pass
@level.setter
def level(self) -> int:
pass
@property
def title(self) -> str | None:
'''The title of this section.
getter: Return the title or None for lead sections or sections that
don't have any title.
setter: Set a new title.
deleter: Remove the title, including the equal sign and the newline
after it.
'''
pass
@title.setter
def title(self) -> str | None:
pass
@title.deleter
def title(self) -> str | None:
pass
@property
def contents(self) -> str:
'''Contents of this section.
getter: return the contents
setter: Set contents to a new string value.
'''
pass
@contents.setter
def contents(self) -> str:
pass
| 18 | 3 | 8 | 0 | 6 | 2 | 2 | 0.24 | 1 | 4 | 0 | 0 | 9 | 1 | 9 | 63 | 95 | 12 | 67 | 32 | 49 | 16 | 56 | 24 | 46 | 3 | 2 | 1 | 18 |
1,099 |
5j9/wikitextparser
|
wikitextparser/_comment_bold_italic.py
|
wikitextparser._comment_bold_italic.BoldItalic
|
class BoldItalic(SubWikiText):
__slots__ = ()
@property
def _match(self) -> Match[str]: ...
@property
def text(self) -> str:
"""Return text value of self (without triple quotes)."""
# noinspection PyUnresolvedReferences
return self._match[1]
@text.setter
def text(self, s: str):
# noinspection PyUnresolvedReferences
b, e = self._match.span(1)
self[b:e] = s
@property
def _content_span(self) -> tuple[int, int]:
# noinspection PyUnresolvedReferences
return self._match.span(1)
|
class BoldItalic(SubWikiText):
@property
def _match(self) -> Match[str]:
pass
@property
def text(self) -> str:
'''Return text value of self (without triple quotes).'''
pass
@text.setter
def text(self) -> str:
pass
@property
def _content_span(self) -> tuple[int, int]:
pass
| 9 | 1 | 3 | 0 | 2 | 1 | 1 | 0.29 | 1 | 3 | 0 | 2 | 4 | 0 | 4 | 58 | 22 | 4 | 14 | 11 | 6 | 4 | 11 | 7 | 6 | 1 | 2 | 0 | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.