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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6,000 |
AnthonyBloomer/daftlistings
|
AnthonyBloomer_daftlistings/daftlistings/enums.py
|
AnthonyBloomer_daftlistings.daftlistings.enums.AddedSince
|
class AddedSince(enum.Enum):
DAYS_3 = "now-3d/d"
DAYS_7 = "now-7d/d"
DAYS_14 = "now-14d/d"
DAYS_30 = "now-30d/d"
|
class AddedSince(enum.Enum):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 49 | 5 | 0 | 5 | 5 | 4 | 0 | 5 | 5 | 4 | 0 | 4 | 0 | 0 |
6,001 |
AnthonyBloomer/daftlistings
|
AnthonyBloomer_daftlistings/daftlistings/enums.py
|
AnthonyBloomer_daftlistings.daftlistings.enums.Ber
|
class Ber(enum.Enum):
A1 = 0
A2 = 1
A3 = 2
B1 = 3
B2 = 4
B3 = 5
C1 = 6
C2 = 7
C3 = 8
D1 = 9
D2 = 10
E1 = 11
E2 = 12
F = 13
G = 14
|
class Ber(enum.Enum):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 49 | 16 | 0 | 16 | 16 | 15 | 0 | 16 | 16 | 15 | 0 | 4 | 0 | 0 |
6,002 |
AnthonyBloomer/daftlistings
|
AnthonyBloomer_daftlistings/daftlistings/enums.py
|
AnthonyBloomer_daftlistings.daftlistings.enums.SortType
|
class SortType(enum.Enum):
PUBLISH_DATE_DESC = "publishDateDesc"
PRICE_ASC = "priceAsc"
PRICE_DESC = "priceDesc"
|
class SortType(enum.Enum):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 49 | 4 | 0 | 4 | 4 | 3 | 0 | 4 | 4 | 3 | 0 | 4 | 0 | 0 |
6,003 |
AnthonyBloomer/daftlistings
|
AnthonyBloomer_daftlistings/daftlistings/enums.py
|
AnthonyBloomer_daftlistings.daftlistings.enums.Facility
|
class Facility(enum.Enum):
def __new__(cls, *args, **kwargs):
obj = object.__new__(cls)
obj._value_ = args[0]
return obj
def __init__(self, _, valid_types):
self.valid_types = valid_types
ALARM = (
"alarm",
[
SearchType.RESIDENTIAL_SALE,
SearchType.RESIDENTIAL_RENT,
SearchType.COMMERCIAL_SALE,
SearchType.COMMERCIAL_RENT,
SearchType.SHARING,
SearchType.STUDENT_ACCOMMODATION,
],
)
CENTRAL_HEATING_GAS = ("gas-fired-central-heating", [SearchType.RESIDENTIAL_SALE])
CENTRAL_HEATING_OIL = ("oil-fired-central-heating", [SearchType.RESIDENTIAL_SALE])
PARKING = (
"parking",
[
SearchType.RESIDENTIAL_SALE,
SearchType.RESIDENTIAL_RENT,
SearchType.COMMERCIAL_SALE,
SearchType.COMMERCIAL_RENT,
SearchType.SHARING,
SearchType.STUDENT_ACCOMMODATION,
],
)
WHEELCHAIR_ACCESS = (
"wheelchair-access",
[
SearchType.RESIDENTIAL_SALE,
SearchType.RESIDENTIAL_RENT,
SearchType.SHARING,
SearchType.STUDENT_ACCOMMODATION,
],
)
WIRED_FOR_CABLE_TELEVISION = (
"wired-for-cable-television",
[SearchType.RESIDENTIAL_SALE],
)
CABLE_TELEVISION = (
"cable-television",
[
SearchType.RESIDENTIAL_RENT,
SearchType.SHARING,
SearchType.STUDENT_ACCOMMODATION,
],
)
DISHWASHER = (
"dishwasher",
[
SearchType.RESIDENTIAL_RENT,
SearchType.SHARING,
SearchType.STUDENT_ACCOMMODATION,
],
)
GARDEN_PATIO_BALCONY = (
"garden-patio-balcony",
[
SearchType.RESIDENTIAL_RENT,
SearchType.SHARING,
SearchType.STUDENT_ACCOMMODATION,
],
)
CENTRAL_HEATING = (
"central-heating",
[
SearchType.RESIDENTIAL_RENT,
SearchType.SHARING,
SearchType.STUDENT_ACCOMMODATION,
],
)
INTERNET = (
"internet",
[
SearchType.RESIDENTIAL_RENT,
SearchType.SHARING,
SearchType.STUDENT_ACCOMMODATION,
],
)
MICROWAVE = (
"microwave",
[
SearchType.RESIDENTIAL_RENT,
SearchType.SHARING,
SearchType.STUDENT_ACCOMMODATION,
],
)
PETS_ALLOWED = (
"pets-allowed",
[
SearchType.RESIDENTIAL_RENT,
SearchType.SHARING,
SearchType.STUDENT_ACCOMMODATION,
],
)
SMOKING = (
"smoking",
[
SearchType.RESIDENTIAL_RENT,
SearchType.SHARING,
SearchType.STUDENT_ACCOMMODATION,
],
)
SERVICED_PROPERTY = (
"serviced-property",
[
SearchType.RESIDENTIAL_RENT,
SearchType.SHARING,
SearchType.STUDENT_ACCOMMODATION,
],
)
DRYER = (
"dryer",
[
SearchType.RESIDENTIAL_RENT,
SearchType.SHARING,
SearchType.STUDENT_ACCOMMODATION,
],
)
WASHING_MACHINE = (
"washing-machine",
[
SearchType.RESIDENTIAL_RENT,
SearchType.SHARING,
SearchType.STUDENT_ACCOMMODATION,
],
)
ENSUITE = ("ensuite", [SearchType.SHARING, SearchType.STUDENT_ACCOMMODATION])
CAT_5_CABLING = (
"cat-5-cabling",
[SearchType.COMMERCIAL_SALE, SearchType.COMMERCIAL_RENT],
)
CAT_6_CABLING = (
"cat-6-data-cabling",
[SearchType.COMMERCIAL_SALE, SearchType.COMMERCIAL_RENT],
)
KITCHEN_AREA = (
"kitchen-area",
[SearchType.COMMERCIAL_SALE, SearchType.COMMERCIAL_RENT],
)
MEETING_ROOMS = (
"meeting-rooms",
[SearchType.COMMERCIAL_SALE, SearchType.COMMERCIAL_RENT],
)
RECEPTION = ("reception", [SearchType.COMMERCIAL_SALE, SearchType.COMMERCIAL_RENT])
PHONE_LINES = (
"phone-lines",
[SearchType.COMMERCIAL_SALE, SearchType.COMMERCIAL_RENT],
)
TOILETS = ("toilets", [SearchType.COMMERCIAL_SALE, SearchType.COMMERCIAL_RENT])
|
class Facility(enum.Enum):
def __new__(cls, *args, **kwargs):
pass
def __init__(self, _, valid_types):
pass
| 3 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 2 | 1 | 2 | 51 | 157 | 2 | 155 | 30 | 152 | 0 | 32 | 30 | 29 | 1 | 4 | 0 | 2 |
6,004 |
AnthonyBloomer/daftlistings
|
AnthonyBloomer_daftlistings/daftlistings/enums.py
|
AnthonyBloomer_daftlistings.daftlistings.enums.Distance
|
class Distance(enum.Enum):
KM0 = ""
KM1 = "_1000"
KM3 = "_3000"
KM5 = "_5000"
KM10 = "_10000"
KM20 = "_20000"
|
class Distance(enum.Enum):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 49 | 7 | 0 | 7 | 7 | 6 | 0 | 7 | 7 | 6 | 0 | 4 | 0 | 0 |
6,005 |
AnthonyBloomer/daftlistings
|
AnthonyBloomer_daftlistings/setup.py
|
AnthonyBloomer_daftlistings.setup.PublishCommand
|
class PublishCommand(Command):
"""Support setup.py publish."""
description = "Build and publish the package."
user_options = []
@staticmethod
def status(s):
"""Prints things in bold."""
print("\033[1m{0}\033[0m".format(s))
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
try:
self.status("Removing previous builds…")
rmtree(os.path.join(here, "dist"))
except:
pass
self.status("Building Source and Wheel (universal) distribution…")
os.system("{0} setup.py sdist bdist_wheel --universal".format(sys.executable))
self.status("Uploading the package to PyPi via Twine…")
os.system("twine upload dist/*")
sys.exit()
|
class PublishCommand(Command):
'''Support setup.py publish.'''
@staticmethod
def status(s):
'''Prints things in bold.'''
pass
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
pass
| 6 | 2 | 5 | 1 | 4 | 0 | 1 | 0.1 | 1 | 0 | 0 | 0 | 3 | 0 | 4 | 43 | 31 | 8 | 21 | 8 | 15 | 2 | 20 | 7 | 15 | 2 | 2 | 1 | 5 |
6,006 |
AnthonyBloomer/daftlistings
|
AnthonyBloomer_daftlistings/daftlistings/daft.py
|
AnthonyBloomer_daftlistings.daftlistings.daft.Daft
|
class Daft:
_ENDPOINT = "https://gateway.daft.ie/old/v1/listings"
_HEADER = {
"User-Agent": "",
"Content-Type": "application/json",
"brand": "daft",
"platform": "web",
}
_PAGE_SZ = 50
_PAGE_0 = {"from": "0", "pagesize": str(_PAGE_SZ)}
def __init__(self):
self._section = None
self._filters = list()
self._andFilters = list()
self._ranges = list()
self._geoFilter = dict()
self._sort_filter = dict()
self._total_results = 0
@property
def total_results(self):
return self._total_results
def _set_range_to(self, name: str, to: str):
if self._ranges:
for r in self._ranges:
if r["name"] == name:
r["to"] = to
return
self._ranges.append({"name": name, "from": "0", "to": to})
def _set_range_from(self, name: str, _from: str):
if self._ranges:
for r in self._ranges:
if r["name"] == name:
r["from"] = _from
return
self._ranges.append({"name": name, "from": _from, "to": str(10e8)})
def _add_filter(self, name: str, value: Union[str, bool]):
if self._filters:
for f in self._filters:
if f["name"] == name:
if value not in f["values"]:
f["values"].append(value)
return
self._filters.append({"name": name, "values": [value]})
def _add_and_filter(self, name: str, value: str):
if self._andFilters:
for f in self._andFilters:
if f["name"] == name:
if value not in f["values"]:
f["values"].append(value)
return
self._andFilters.append({"name": name, "values": [value]})
def _add_sort_filter(self, sort_filter: str):
self._sort_filter = sort_filter
def _add_geo_filter(self, id: str):
if self._geoFilter:
ids = self._geoFilter["storedShapeIds"]
if id not in ids:
self._geoFilter["storedShapeIds"].append(id)
return
self._geoFilter = {"storedShapeIds": [id], "geoSearchType": "STORED_SHAPES"}
def set_search_type(self, search_type: SearchType):
if not isinstance(search_type, SearchType):
raise TypeError("Argument must be enums.SearchType.")
self._section = search_type.value
def set_property_type(self, property_type: PropertyType):
if not isinstance(property_type, PropertyType):
raise TypeError("Argument must be enums.PropertyType.")
self._add_filter("propertyType", property_type.value)
def set_min_beds(self, min_beds: int):
self._set_range_from("numBeds", str(min_beds))
def set_max_beds(self, max_beds: int):
self._set_range_to("numBeds", str(max_beds))
def set_min_baths(self, min_baths: int):
self._set_range_from("numBaths", str(min_baths))
def set_max_baths(self, max_baths: int):
self._set_range_to("numBaths", str(max_baths))
def set_min_price(self, min_price: int):
if not self._section:
raise ValueError("Must set search_type before price.")
if self._section in (
SearchType.RESIDENTIAL_RENT.value,
SearchType.COMMERCIAL_RENT.value,
SearchType.SHARING.value,
SearchType.STUDENT_ACCOMMODATION.value,
):
self._set_range_from("rentalPrice", str(min_price))
else:
self._set_range_from("salePrice", str(min_price))
def set_max_price(self, max_price: int):
if not self._section:
raise ValueError("Must set search_type before price.")
if self._section in (
SearchType.RESIDENTIAL_RENT.value,
SearchType.COMMERCIAL_RENT.value,
SearchType.SHARING.value,
SearchType.STUDENT_ACCOMMODATION.value,
):
self._set_range_to("rentalPrice", str(max_price))
else:
self._set_range_to("salePrice", str(max_price))
def set_suitability(self, suitability: SuitableFor):
if not isinstance(suitability, SuitableFor):
raise TypeError("Argument must be enums.SuitableFor.")
self._add_filter("suitableFor", suitability.value)
def set_owner_occupied(self, owner_occupied: bool):
self._add_filter("ownerOccupied", owner_occupied)
def set_min_tenants(self, num_tenants: int):
self._set_range_from("numTenants", str(num_tenants))
def set_max_tenants(self, num_tenants: int):
self._set_range_to("numTenants", str(num_tenants))
def set_min_lease(self, min_lease: int):
# Measured in months
self._set_range_from("leaseLength", str(min_lease))
def set_max_lease(self, max_lease: int):
# Measured in months
self._set_range_to("leaseLength", str(max_lease))
def set_min_floor_size(self, min_floor_size: int):
self._set_range_from("floorSize", str(min_floor_size))
def set_max_floor_size(self, max_floor_size: int):
self._set_range_to("floorSize", str(max_floor_size))
def set_added_since(self, added_since: AddedSince):
if not isinstance(added_since, AddedSince):
raise TypeError("Argument must be enums.AddedSince.")
self._set_range_from("firstPublishDate", added_since.value)
self._set_range_to("firstPublishDate", "")
def set_min_ber(self, ber: Ber):
if not isinstance(ber, Ber):
raise TypeError("Argument must be enums.Ber.")
self._set_range_from("ber", str(ber.value))
def set_max_ber(self, ber: Ber):
if not isinstance(ber, Ber):
raise TypeError("Argument must be enums.Ber.")
self._set_range_to("ber", str(ber.value))
def set_location(
self,
location: Union[Location, str, List[Union[Location, str]]],
distance: Distance = Distance.KM0,
):
if isinstance(location, Location):
self._add_geo_filter(location.value["id"] + distance.value)
elif isinstance(location, str):
best_match = self._get_best_match(location)
self._add_geo_filter(best_match.value["id"] + distance.value)
elif isinstance(location, List):
for area in location:
if isinstance(area, Location):
self._add_geo_filter(area.value["id"] + distance.value)
elif isinstance(area, str):
best_match = self._get_best_match(area)
self._add_geo_filter(best_match.value["id"] + distance.value)
else:
raise TypeError(
"List values must be of type location.Location or string."
)
else:
raise TypeError("Argument must be location.Location, list, or string.")
def set_facility(self, facility: Facility):
if self._section == None:
raise ValueError("SearchType must be set before Facility")
else:
if isinstance(facility, Facility):
if self._section in [s.value for s in facility.valid_types]:
self._add_and_filter("facilities", facility.value)
else:
search_type = [
(name, member)
for name, member in SearchType.__members__.items()
if member.value == self._section
][0]
compatible_facilities = [
f.name for f in Facility if search_type[1] in f.valid_types
]
raise ValueError(
f"Facility {facility.name} incompatible with SearchType {search_type[0]}\nThe following facilities are compatible with this SearchType:\n{compatible_facilities}"
)
else:
raise TypeError("Argument must be of type Facility")
def set_sort_type(self, sort_type: SortType):
if isinstance(sort_type, SortType):
self._add_sort_filter(sort_type.value)
else:
raise TypeError("Argument must be of type SortType")
@staticmethod
def _get_best_match(location: str) -> Location:
regex = re.compile(r"(?ui)\W") # Remove non-alphanumeric
search_term = regex.sub(" ", location)
best_score, best_match = 0, None
for loc in Location:
sm = SequenceMatcher(
None, search_term, regex.sub(" ", loc.value["displayValue"])
)
if sm.ratio() > best_score:
best_score, best_match = sm.ratio(), loc
return best_match
def _make_payload(self) -> Dict:
payload = dict()
if self._section:
payload["section"] = self._section
if self._filters:
payload["filters"] = self._filters
if self._andFilters:
payload["andFilters"] = self._andFilters
if self._ranges:
payload["ranges"] = self._ranges
if self._geoFilter:
payload["geoFilter"] = self._geoFilter
if self._sort_filter:
payload["sort"] = self._sort_filter
payload["paging"] = deepcopy(self._PAGE_0)
return payload
def search(self, max_pages: Optional[int] = None) -> List[Listing]:
print("Searching...")
_payload = self._make_payload()
r = requests.post(self._ENDPOINT, headers=self._HEADER, json=_payload)
listings = r.json()["listings"]
results_count = r.json()["paging"]["totalResults"]
total_pages = ceil(results_count / self._PAGE_SZ)
limit = min(max_pages, total_pages) if max_pages else total_pages
for page in range(1, limit):
_payload["paging"]["from"] = page * self._PAGE_SZ
r = requests.post(self._ENDPOINT, headers=self._HEADER, json=_payload)
listings = listings + r.json()["listings"]
# expand out grouped listings as individual listings, commercial searches do not give the necessary information to do this
expanded_listings = []
for l in listings:
# the information contained in the key 'prs' for most searches is instead contained in 'newHome' for newHome type searches
if "newHome" in l["listing"].keys():
if "subUnits" in l["listing"]["newHome"].keys():
l["listing"]["prs"] = l["listing"].pop("newHome")
try:
num_subUnits = len(l["listing"]["prs"]["subUnits"])
for i in range(num_subUnits):
copy = deepcopy(l)
for key in copy["listing"]["prs"]["subUnits"][i].keys():
copy["listing"][key] = copy["listing"]["prs"]["subUnits"][i][
key
]
# studios do not have a 'numBedrooms' so set it separately
if copy["listing"]["propertyType"] == "Studio":
copy["listing"]["numBedrooms"] = "1 bed"
expanded_listings.append(copy)
except:
# above only sets studio 'numBedrooms' for grouped listings, do ungrouped here
if "propertyType" in l["listing"].keys():
if l["listing"]["propertyType"] == "Studio":
l["listing"]["numBedrooms"] = "1 bed"
expanded_listings.append(l)
listings = expanded_listings
self._total_results = len(listings)
print(f"Search complete. Found {self.total_results} listings.")
return [Listing(l) for l in listings]
|
class Daft:
def __init__(self):
pass
@property
def total_results(self):
pass
def _set_range_to(self, name: str, to: str):
pass
def _set_range_from(self, name: str, _from: str):
pass
def _add_filter(self, name: str, value: Union[str, bool]):
pass
def _add_and_filter(self, name: str, value: str):
pass
def _add_sort_filter(self, sort_filter: str):
pass
def _add_geo_filter(self, id: str):
pass
def set_search_type(self, search_type: SearchType):
pass
def set_property_type(self, property_type: PropertyType):
pass
def set_min_beds(self, min_beds: int):
pass
def set_max_beds(self, max_beds: int):
pass
def set_min_baths(self, min_baths: int):
pass
def set_max_baths(self, max_baths: int):
pass
def set_min_price(self, min_price: int):
pass
def set_max_price(self, max_price: int):
pass
def set_suitability(self, suitability: SuitableFor):
pass
def set_owner_occupied(self, owner_occupied: bool):
pass
def set_min_tenants(self, num_tenants: int):
pass
def set_max_tenants(self, num_tenants: int):
pass
def set_min_lease(self, min_lease: int):
pass
def set_max_lease(self, max_lease: int):
pass
def set_min_floor_size(self, min_floor_size: int):
pass
def set_max_floor_size(self, max_floor_size: int):
pass
def set_added_since(self, added_since: AddedSince):
pass
def set_min_ber(self, ber: Ber):
pass
def set_max_ber(self, ber: Ber):
pass
def set_location(
self,
location: Union[Location, str, List[Union[Location, str]]],
distance: Distance = Distance.KM0,
):
pass
def set_facility(self, facility: Facility):
pass
def set_sort_type(self, sort_type: SortType):
pass
@staticmethod
def _get_best_match(location: str) -> Location:
pass
def _make_payload(self) -> Dict:
pass
def search(self, max_pages: Optional[int] = None) -> List[Listing]:
pass
| 36 | 0 | 7 | 0 | 7 | 0 | 3 | 0.03 | 0 | 19 | 10 | 0 | 32 | 7 | 33 | 33 | 292 | 41 | 245 | 79 | 205 | 7 | 199 | 73 | 165 | 12 | 0 | 4 | 88 |
6,007 |
AnthonyBloomer/daftlistings
|
AnthonyBloomer_daftlistings/daftlistings/map_visualization.py
|
AnthonyBloomer_daftlistings.daftlistings.map_visualization.MapVisualization
|
class MapVisualization:
"""
This class takes a crawled daft dataset which consists of
price, longitute, latitude, number of bedrooms, number of bathrooms
with price in asending order then generate a folium map object"""
def __init__(self, dataset):
self.df = dataset
self.map = self.create_map()
self.color_names = [
"darkblue",
"blue",
"lightblue",
"orange",
"lightred",
"red",
"darkred",
] # 7 types of color
self.color_codes = [
"#0065a1",
"#36a6d8",
"#86d9ff",
"#f1932e",
"#ff8a7a",
"#ca3c2a",
"#9f3236",
]
self.index = self.generate_color_bins()
def generate_color_bins(self):
"""Generate color bins based on the price at 1%, 4%, 14% ... percentiles"""
prices = self.df.monthly_price
percentiles = [0.01, 0.04, 0.14, 0.30, 0.56, 0.70, 0.84, 1.00]
return [prices.quantile(p) for p in percentiles]
def create_map(self):
"""Creat the initial folium map with the location of the first record"""
lat_of_first_record = self.df.iloc[0]["latitude"]
lon_of_first_record = self.df.iloc[0]["longitude"]
return folium.Map(
location=[lat_of_first_record, lon_of_first_record],
zoom_start=12,
control_scale=True,
)
def color_dispatcher(self, price):
for i in range(len(self.index) - 1):
if price <= self.index[i + 1]:
return self.color_names[i]
def marker_icon(self, price):
return folium.Icon(color=self.color_dispatcher(price))
def add_markers(self):
markers_dict = {}
for index, row in self.df.iterrows():
lat, lon, price = row["latitude"], row["longitude"], row["monthly_price"]
beds, baths = row["bedrooms"], row["bathrooms"]
popup_name = (
"<p>"
+ "Bedrooms: "
+ str(beds)
+ "</p>"
+ "<p>"
+ "Bathrooms: "
+ str(baths)
+ "</p>"
)
popup_name += '<a href=" {0} "target="_blank"> link </a>'.format(
row["daft_link"]
)
icon = self.marker_icon(price)
marker = folium.Marker(
[lat, lon], popup=popup_name, tooltip=price, icon=icon
)
if (lat, lon) in markers_dict.keys():
markers_dict[(lat, lon)].append(marker)
else:
markers_dict[(lat, lon)] = [marker]
for key, item in markers_dict.items():
if len(item) == 1:
item[0].add_to(self.map)
else:
marker_cluster = MarkerCluster().add_to(self.map)
for i in range(len(item)):
item[i].add_to(marker_cluster)
def add_colorbar(self):
"""add a colorbar at the top right corner of the map"""
vmin, vmax = (
self.df["monthly_price"].quantile(0.005),
self.df["monthly_price"].max(),
)
# set vmin to price.min() will screw the colorbar scale
colormap = cm.StepColormap(
self.color_codes, index=self.index, vmin=vmin, vmax=vmax
)
colormap.caption = "Monthly rent (€)"
self.map.add_child(colormap)
def save(self, file):
self.map.save(file)
|
class MapVisualization:
'''
This class takes a crawled daft dataset which consists of
price, longitute, latitude, number of bedrooms, number of bathrooms
with price in asending order then generate a folium map object'''
def __init__(self, dataset):
pass
def generate_color_bins(self):
'''Generate color bins based on the price at 1%, 4%, 14% ... percentiles'''
pass
def create_map(self):
'''Creat the initial folium map with the location of the first record'''
pass
def color_dispatcher(self, price):
pass
def marker_icon(self, price):
pass
def add_markers(self):
pass
def add_colorbar(self):
'''add a colorbar at the top right corner of the map'''
pass
def save(self, file):
pass
| 9 | 4 | 11 | 0 | 11 | 2 | 2 | 0.19 | 0 | 2 | 0 | 0 | 8 | 5 | 8 | 8 | 103 | 9 | 86 | 31 | 77 | 16 | 46 | 31 | 37 | 6 | 0 | 3 | 15 |
6,008 |
AnthonyMRios/pymetamap
|
AnthonyMRios_pymetamap/pymetamap/ConceptLite.py
|
pymetamap.ConceptLite.CorpusLite
|
class CorpusLite(list):
@classmethod
def load(this_class, stream):
stream = iter(stream)
corpus = this_class()
for line in stream:
fields = line.split('|')
if fields[1] == 'MMI':
corpus.append(ConceptLiteMMI.from_mmi(line))
else:
print("THISIS A TEST:",line)
assert False, "Implemented only for MMI"
return corpus
|
class CorpusLite(list):
@classmethod
def load(this_class, stream):
pass
| 3 | 0 | 12 | 1 | 11 | 0 | 3 | 0 | 1 | 1 | 1 | 0 | 0 | 0 | 1 | 34 | 14 | 1 | 13 | 6 | 10 | 0 | 11 | 5 | 9 | 3 | 2 | 2 | 3 |
6,009 |
AnthonyMRios/pymetamap
|
AnthonyMRios_pymetamap/pymetamap/Concept.py
|
pymetamap.Concept.ConceptAA
|
class ConceptAA(namedtuple('Concept', FIELD_NAMES_AA)):
def __repr__(self):
items = [(field, getattr(self, field, None)) for field in FIELD_NAMES_AA]
fields = ['%s=%r' % (k, v) for k, v in items if v is not None]
return '%s(%s)' % (self.__class__.__name__, ', '.join(fields))
def as_mmi(self):
return '|'.join([get(field) for field in FIELD_NAMES_AA])
@classmethod
def from_mmi(this_class, line):
fields = line.split('|')
return this_class(**dict(zip(FIELD_NAMES_AA, fields)))
|
class ConceptAA(namedtuple('Concept', FIELD_NAMES_AA)):
def __repr__(self):
pass
def as_mmi(self):
pass
@classmethod
def from_mmi(this_class, line):
pass
| 5 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 2 | 0 | 0 | 2 | 0 | 3 | 8 | 13 | 2 | 11 | 8 | 6 | 0 | 10 | 7 | 6 | 1 | 1 | 0 | 3 |
6,010 |
AnthonyMRios/pymetamap
|
AnthonyMRios_pymetamap/pymetamap/ConceptLite.py
|
pymetamap.ConceptLite.ConceptLiteMMI
|
class ConceptLiteMMI(namedtuple('Concept', FIELD_NAMES_MMI)):
def __repr__(self):
items = [(field, getattr(self, field, None)) for field in FIELD_NAMES_MMI]
fields = ['%s=%r' % (k, v) for k, v in items if v is not None]
return '%s(%s)' % (self.__class__.__name__, ', '.join(fields))
def as_mmi(self):
return '|'.join([get(field) for field in FIELD_NAMES_MMI])
@classmethod
def from_mmi(this_class, line):
fields = line.split('|')
return this_class(**dict(zip(FIELD_NAMES_MMI, fields)))
|
class ConceptLiteMMI(namedtuple('Concept', FIELD_NAMES_MMI)):
def __repr__(self):
pass
def as_mmi(self):
pass
@classmethod
def from_mmi(this_class, line):
pass
| 5 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 2 | 0 | 0 | 2 | 0 | 3 | 8 | 13 | 2 | 11 | 8 | 6 | 0 | 10 | 7 | 6 | 1 | 1 | 0 | 3 |
6,011 |
AnthonyMRios/pymetamap
|
AnthonyMRios_pymetamap/pymetamap/SubprocessBackend.py
|
pymetamap.SubprocessBackend.SubprocessBackend
|
class SubprocessBackend(MetaMap):
def __init__(self, metamap_filename, version=None):
""" Interface to MetaMap using subprocess. This creates a
command line call to a specified metamap process.
"""
MetaMap.__init__(self, metamap_filename, version)
def extract_concepts(self,
sentences=None,
ids=None,
composite_phrase=4,
filename=None,
file_format='sldi',
allow_acronym_variants=False,
word_sense_disambiguation=False,
allow_large_n=False,
strict_model=False,
relaxed_model=False,
allow_overmatches=False,
allow_concept_gaps=False,
term_processing=False,
no_derivational_variants=False,
derivational_variants=False,
ignore_word_order=False,
unique_acronym_variants=False,
prefer_multiple_concepts=False,
ignore_stop_phrases=False,
compute_all_mappings=False,
prune=False,
mm_data_version=False,
exclude_sources=[],
restrict_to_sources=[],
restrict_to_sts=[],
exclude_sts=[],
no_nums=[]):
""" extract_concepts takes a list of sentences and ids(optional)
then returns a list of Concept objects extracted via
MetaMap.
Supported Options:
Composite Phrase -Q
Word Sense Disambiguation -y
use strict model -A
use relaxed model -C
allow large N -l
allow overmatches -o
allow concept gaps -g
term processing -z
No Derivational Variants -d
All Derivational Variants -D
Ignore Word Order -i
Allow Acronym Variants -a
Unique Acronym Variants -u
Prefer Multiple Concepts -Y
Ignore Stop Phrases -K
Compute All Mappings -b
MM Data Version -V
Exclude Sources -e
Restrict to Sources -R
Restrict to Semantic Types -J
Exclude Semantic Types -k
Suppress Numerical Concepts --no_nums
For information about the available options visit
http://metamap.nlm.nih.gov/.
Note: If an error is encountered the process will be closed
and whatever was processed, if anything, will be
returned along with the error found.
"""
if allow_acronym_variants and unique_acronym_variants:
raise ValueError("You can't use both allow_acronym_variants and unique_acronym_variants.")
if (sentences is not None and filename is not None) or \
(sentences is None and filename is None):
raise ValueError("You must either pass a list of sentences OR a filename.")
if file_format not in ['sldi', 'sldiID']:
raise ValueError("file_format must be either sldi or sldiID")
input_file = None
output_file = None
error = None
try:
command = list()
command.append(self.metamap_filename)
command.append('-N')
command.append('-Q')
command.append(str(composite_phrase))
if mm_data_version is not False:
if mm_data_version not in ['Base', 'USAbase', 'NLM']:
raise ValueError("mm_data_version must be Base, USAbase, or NLM.")
command.append('-V')
command.append(str(mm_data_version))
if word_sense_disambiguation:
command.append('-y')
if strict_model:
command.append('-A')
if prune is not False:
command.append('--prune')
command.append(str(prune))
if relaxed_model:
command.append('-C')
if allow_large_n:
command.append('-l')
if allow_overmatches:
command.append('-o')
if allow_concept_gaps:
command.append('-g')
if term_processing:
command.append('-z')
if no_derivational_variants:
command.append('-d')
if derivational_variants:
command.append('-D')
if ignore_word_order:
command.append('-i')
if allow_acronym_variants:
command.append('-a')
if unique_acronym_variants:
command.append('-u')
if prefer_multiple_concepts:
command.append('-Y')
if ignore_stop_phrases:
command.append('-K')
if compute_all_mappings:
command.append('-b')
if len(exclude_sources) > 0:
command.append('-e')
command.append(str(','.join(exclude_sources)))
if len(restrict_to_sources) > 0:
command.append('-R')
command.append(str(','.join(restrict_to_sources)))
if len(restrict_to_sts) > 0:
command.append('-J')
command.append(str(','.join(restrict_to_sts)))
if len(exclude_sts) > 0:
command.append('-k')
command.append(str(','.join(exclude_sts)))
if len(no_nums) > 0:
command.append('--no_nums')
command.append(str(','.join(no_nums)))
if ids is not None or (file_format == 'sldiID' and sentences is None):
command.append('--sldiID')
else:
command.append('--sldi')
command.append('--silent')
if sentences is not None:
input_text = None
if ids is not None:
for identifier, sentence in zip(ids, sentences):
if input_text is None:
input_text = '{0!r}|{1!r}\n'.format(identifier, sentence).encode('utf8')
else:
input_text += '{0!r}|{1!r}\n'.format(identifier, sentence).encode('utf8')
else:
for sentence in sentences:
if input_text is None:
input_text = '{0!r}\n'.format(sentence).encode('utf8')
else:
input_text += '{0!r}\n'.format(sentence).encode('utf8')
input_command = list()
input_command.append('echo')
input_command.append('-e')
input_command.append(input_text)
input_process = subprocess.Popen(input_command, stdout=subprocess.PIPE)
metamap_process = subprocess.Popen(command, stdout=subprocess.PIPE, stdin=input_process.stdout)
output, error = metamap_process.communicate()
if sys.version_info[0] > 2:
if isinstance(output, bytes):
output = output.decode()
# "Processing" sentences are returned as stderr. Hence success/failure of metamap_process needs to be
# checked by its returncode.
if metamap_process.returncode == 0:
# Initial line(s) of output contains MetaMap command and MetaMap details.
# Even on using --silent option, MetaMap command is sent to stdout.
# Hence pre-processing is required to segregate these from MetaMap output in stdout.
prev_new_line = -1
while (prev_new_line + 1) < len(output):
next_new_line = output.find('\n', prev_new_line + 1)
if next_new_line < 0:
next_new_line = len(output)
# Check if the current line is in MMI output format i.e. fields separated by '|'
fields = output[prev_new_line + 1:next_new_line].split('|')
# https://metamap.nlm.nih.gov/Docs/MMI_Output_2016.pdf
# This document explains the various fields in MMI output.
if len(fields) > 1 and fields[1] in ['MMI', 'AA', 'UA']:
break
else:
prev_new_line = next_new_line
output = output[prev_new_line + 1:]
else:
error = "ERROR: MetaMap failed"
else:
input_file = open(filename, 'r')
output_file = tempfile.NamedTemporaryFile(mode="r", delete=False)
command.append(input_file.name)
command.append(output_file.name)
metamap_process = subprocess.Popen(command, stdout=subprocess.PIPE)
while metamap_process.poll() is None:
stdout = str(metamap_process.stdout.readline())
if 'ERROR' in stdout:
metamap_process.terminate()
error = stdout.rstrip()
output = str(output_file.read())
finally:
if sentences is not None:
# os.remove(input_file.name)
pass
else:
input_file.close()
os.remove(output_file.name)
concepts = Corpus.load(output.splitlines())
return (concepts, error)
|
class SubprocessBackend(MetaMap):
def __init__(self, metamap_filename, version=None):
''' Interface to MetaMap using subprocess. This creates a
command line call to a specified metamap process.
'''
pass
def extract_concepts(self,
sentences=None,
ids=None,
composite_phrase=4,
filename=None,
file_format='sldi',
allow_acronym_variants=False,
word_sense_disambiguation=False,
allow_large_n=False,
strict_model=False,
relaxed_model=False,
allow_overmatches=False,
allow_concept_gaps=False,
term_processing=False,
no_derivational_variants=False,
derivational_variants=False,
ignore_word_order=False,
unique_acronym_variants=False,
prefer_multiple_concepts=False,
ignore_stop_phrases=False,
compute_all_mappings=False,
prune=False,
mm_data_version=False,
exclude_sources=[],
restrict_to_sources=[],
restrict_to_sts=[],
exclude_sts=[],
no_nums=[]):
''' extract_concepts takes a list of sentences and ids(optional)
then returns a list of Concept objects extracted via
MetaMap.
Supported Options:
Composite Phrase -Q
Word Sense Disambiguation -y
use strict model -A
use relaxed model -C
allow large N -l
allow overmatches -o
allow concept gaps -g
term processing -z
No Derivational Variants -d
All Derivational Variants -D
Ignore Word Order -i
Allow Acronym Variants -a
Unique Acronym Variants -u
Prefer Multiple Concepts -Y
Ignore Stop Phrases -K
Compute All Mappings -b
MM Data Version -V
Exclude Sources -e
Restrict to Sources -R
Restrict to Semantic Types -J
Exclude Semantic Types -k
Suppress Numerical Concepts --no_nums
For information about the available options visit
http://metamap.nlm.nih.gov/.
Note: If an error is encountered the process will be closed
and whatever was processed, if anything, will be
returned along with the error found.
'''
pass
| 3 | 2 | 111 | 8 | 81 | 22 | 22 | 0.27 | 1 | 7 | 1 | 0 | 2 | 0 | 2 | 5 | 224 | 17 | 163 | 45 | 133 | 44 | 126 | 18 | 123 | 43 | 1 | 5 | 44 |
6,012 |
AnthonyMRios/pymetamap
|
AnthonyMRios_pymetamap/pymetamap/SubprocessBackendLite.py
|
pymetamap.SubprocessBackendLite.SubprocessBackendLite
|
class SubprocessBackendLite(MetaMapLite):
def __init__(self, metamap_home):
""" Interface to MetaMap using subprocess. This creates a
command line call to a specified metamap process.
"""
MetaMapLite.__init__(self, metamap_home=metamap_home)
def extract_concepts(self, sentences=None, ids=None, filename=None,
restrict_to_sts=None, restrict_to_sources=None):
""" extract_concepts takes a list of sentences and ids(optional)
then returns a list of Concept objects extracted via
MetaMapLite.
Supported Options:
Restrict to Semantic Types --restrict_to_sts
Restrict to Sources --restrict_to_sources
For information about the available options visit
http://metamap.nlm.nih.gov/.
Note: If an error is encountered the process will be closed
and whatever was processed, if anything, will be
returned along with the error found.
"""
if (sentences is not None and filename is not None) or \
(sentences is None and filename is None):
raise ValueError("You must either pass a list of sentences "
"OR a filename.")
input_file = None
if sentences is not None:
input_file = tempfile.NamedTemporaryFile(mode="wb", delete=False, suffix='.mmi')
else:
input_file = open(filename, 'r')
# Unlike MetaMap, MetaMapLite does not take an output filename as a parameter.
# It creates a new output file at same location as "input_file" with the default file extension ".mmi".
# output_file = tempfile.NamedTemporaryFile(mode="r", delete=False)
output_file_name = None
error = None
try:
if sentences is not None:
if ids is not None:
for identifier, sentence in zip(ids, sentences):
input_file.write('{0!r}|{1}\n'.format(identifier, sentence).encode('utf8'))
else:
for sentence in sentences:
input_file.write('{0!r}\n'.format(sentence).encode('utf8'))
input_file.flush()
input_file.close()
command = ["bash", os.path.join(self.metamap_home, "metamaplite.sh")]
if restrict_to_sts:
if isinstance(restrict_to_sts, str):
restrict_to_sts = [restrict_to_sts]
if len(restrict_to_sts) > 0:
command.append('--restrict_to_sts={}'.format(str(','.join(restrict_to_sts))))
#command.append(str(','.join(restrict_to_sts)))
if restrict_to_sources:
if isinstance(restrict_to_sources, str):
restrict_to_sources = [restrict_to_sources]
if len(restrict_to_sources) > 0:
command.append('--restrict_to_sources')
command.append(str(','.join(restrict_to_sources)))
if ids is not None:
command.append('--inputformat=sldiwi')
command.append(input_file.name)
command.append('--overwrite')
#command.append('--indexdir={}data/ivf/2020AA/USAbase'.format(self.metamap_home))
#command.append('--specialtermsfile={}data/specialterms.txt'.format(self.metamap_home))
# command.append(output_file.name)
output_file_name, file_extension = os.path.splitext(input_file.name)
output_file_name += "." + "mmi"
output_file_name, file_extension = os.path.splitext(input_file.name)
output_file_name += "." + "mmi"
# output = str(output_file.read())
metamap_process = subprocess.Popen(command, stdout=subprocess.PIPE)
while metamap_process.poll() is None:
stdout = str(metamap_process.stdout.readline())
if 'ERROR' in stdout:
metamap_process.terminate()
error = stdout.rstrip()
# print("input file name: {0}".format(input_file.name))
output_file_name, file_extension = os.path.splitext(input_file.name)
output_file_name += "." + "mmi"
# print("output_file_name: {0}".format(output_file_name))
with open(output_file_name) as fd:
output = fd.read()
# output = str(output_file.read())
# print("output: {0}".format(output))
except:
pass
concepts = CorpusLite.load(output.splitlines())
return concepts, error
|
class SubprocessBackendLite(MetaMapLite):
def __init__(self, metamap_home):
''' Interface to MetaMap using subprocess. This creates a
command line call to a specified metamap process.
'''
pass
def extract_concepts(self, sentences=None, ids=None, filename=None,
restrict_to_sts=None, restrict_to_sources=None):
''' extract_concepts takes a list of sentences and ids(optional)
then returns a list of Concept objects extracted via
MetaMapLite.
Supported Options:
Restrict to Semantic Types --restrict_to_sts
Restrict to Sources --restrict_to_sources
For information about the available options visit
http://metamap.nlm.nih.gov/.
Note: If an error is encountered the process will be closed
and whatever was processed, if anything, will be
returned along with the error found.
'''
pass
| 3 | 2 | 50 | 7 | 30 | 14 | 9 | 0.45 | 1 | 5 | 1 | 0 | 2 | 0 | 2 | 5 | 101 | 14 | 60 | 15 | 56 | 27 | 55 | 13 | 52 | 17 | 1 | 4 | 18 |
6,013 |
AnthonyMRios/pymetamap
|
AnthonyMRios_pymetamap/pymetamap/Concept.py
|
pymetamap.Concept.Corpus
|
class Corpus(list):
@classmethod
def load(this_class, stream):
stream = iter(stream)
corpus = this_class()
for line in stream:
fields = line.split('|')
if fields[1] == 'MMI':
corpus.append(ConceptMMI.from_mmi(line))
elif fields[1] == 'AA':
corpus.append(ConceptAA.from_mmi(line))
else:
corpus.append(ConceptUA.from_mmi(line))
return corpus
|
class Corpus(list):
@classmethod
def load(this_class, stream):
pass
| 3 | 0 | 13 | 1 | 12 | 0 | 4 | 0 | 1 | 3 | 3 | 0 | 0 | 0 | 1 | 34 | 15 | 1 | 14 | 6 | 11 | 0 | 11 | 5 | 9 | 4 | 2 | 2 | 4 |
6,014 |
AnthonyMRios/pymetamap
|
AnthonyMRios_pymetamap/pymetamap/Concept.py
|
pymetamap.Concept.ConceptUA
|
class ConceptUA(namedtuple('Concept', FIELD_NAMES_UA)):
def __repr__(self):
items = [(field, getattr(self, field, None)) for field in FIELD_NAMES_UA]
fields = ['%s=%r' % (k, v) for k, v in items if v is not None]
return '%s(%s)' % (self.__class__.__name__, ', '.join(fields))
def as_mmi(self):
return '|'.join([get(field) for field in FIELD_NAMES_UA])
@classmethod
def from_mmi(this_class, line):
fields = line.split('|')
return this_class(**dict(zip(FIELD_NAMES_UA, fields)))
|
class ConceptUA(namedtuple('Concept', FIELD_NAMES_UA)):
def __repr__(self):
pass
def as_mmi(self):
pass
@classmethod
def from_mmi(this_class, line):
pass
| 5 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 2 | 0 | 0 | 2 | 0 | 3 | 8 | 13 | 2 | 11 | 8 | 6 | 0 | 10 | 7 | 6 | 1 | 1 | 0 | 3 |
6,015 |
AnthonyMRios/pymetamap
|
AnthonyMRios_pymetamap/pymetamap/Concept.py
|
pymetamap.Concept.ConceptMMI
|
class ConceptMMI(namedtuple('Concept', FIELD_NAMES_MMI)):
def __repr__(self):
items = [(field, getattr(self, field, None)) for field in FIELD_NAMES_MMI]
fields = ['%s=%r' % (k, v) for k, v in items if v is not None]
return '%s(%s)' % (self.__class__.__name__, ', '.join(fields))
def as_mmi(self):
return '|'.join([get(field) for field in FIELD_NAMES_MMI])
@classmethod
def from_mmi(this_class, line):
fields = line.split('|')
return this_class(**dict(zip(FIELD_NAMES_MMI, fields)))
|
class ConceptMMI(namedtuple('Concept', FIELD_NAMES_MMI)):
def __repr__(self):
pass
def as_mmi(self):
pass
@classmethod
def from_mmi(this_class, line):
pass
| 5 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 2 | 0 | 0 | 2 | 0 | 3 | 8 | 13 | 2 | 11 | 8 | 6 | 0 | 10 | 7 | 6 | 1 | 1 | 0 | 3 |
6,016 |
Antojitos/guacamole-cli
|
Antojitos_guacamole-cli/tests/main.py
|
tests.main.GuacamoleCMDTest
|
class GuacamoleCMDTest(unittest.TestCase):
def setUp(self):
self.endpoint = 'http://localhost/files/'
self.filename = 'test-image.jpg'
self.filepath = 'tests/fixtures/%s' % self.filename
self.shortener = 'http://localhost/api/v1/urls'
def test_cmd_without_options(self):
with self.assertRaises(SystemExit) as cm:
guacamole_cmd()
self.assertEqual(cm.exception.code, 2)
def test_cmd_help(self):
with self.assertRaises(SystemExit) as cm:
args = ['--help']
guacamole_cmd(args)
self.assertEqual(cm.exception.code, 0)
self.assertIn('show this help message and exit', sys.stdout.getvalue())
def test_cmd_endpoit_fail(self):
args = ['--endpoint', self.endpoint, self.filepath]
output = guacamole_cmd(args)
self.assertIn('something wrong with the endpoint', output)
def test_cmd_shortener_fail(self):
with requests_mock.Mocker() as m:
text = '{"uri": "h/a/s/h/%s"}' % self.filename
m.post(self.endpoint, text=text)
text = 'Error 500'
m.post(self.shortener, text=text)
args = ['--shortener', self.shortener,
'--endpoint', self.endpoint,
self.filepath]
output = guacamole_cmd(args)
self.assertIn('something wrong with the URL shortener service',
output)
|
class GuacamoleCMDTest(unittest.TestCase):
def setUp(self):
pass
def test_cmd_without_options(self):
pass
def test_cmd_help(self):
pass
def test_cmd_endpoit_fail(self):
pass
def test_cmd_shortener_fail(self):
pass
| 6 | 0 | 6 | 0 | 6 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 5 | 4 | 5 | 77 | 38 | 6 | 32 | 19 | 26 | 0 | 29 | 16 | 23 | 1 | 2 | 1 | 5 |
6,017 |
Antojitos/guacamole-cli
|
Antojitos_guacamole-cli/src/guacamole_cli/client.py
|
guacamole_cli.client.TamalesClient
|
class TamalesClient():
def __init__(self, endpoint):
self.endpoint = endpoint
def shorten(self, url):
data = json.dumps({'url': url})
headers = {'Content-type': 'application/json'}
try:
request = requests.post(self.endpoint, data=data, headers=headers)
except requests.exceptions.RequestException:
return
try:
response = request.json()
except ValueError:
return
if 'short_url' in response:
return response['short_url']
|
class TamalesClient():
def __init__(self, endpoint):
pass
def shorten(self, url):
pass
| 3 | 0 | 9 | 2 | 8 | 0 | 3 | 0 | 0 | 1 | 0 | 0 | 2 | 1 | 2 | 2 | 20 | 4 | 16 | 8 | 13 | 0 | 16 | 8 | 13 | 4 | 0 | 1 | 5 |
6,018 |
Antojitos/guacamole-cli
|
Antojitos_guacamole-cli/tests/main.py
|
tests.main.GuacamoleClientTest
|
class GuacamoleClientTest(unittest.TestCase):
def setUp(self):
self.endpoint = 'http://localhost/files/'
self.filename = 'test-image.jpg'
self.filepath = 'tests/fixtures/%s' % self.filename
self.client = GuacamoleClient(self.endpoint)
def test_client_send(self):
with requests_mock.Mocker() as m:
m.post(self.endpoint, text='{"uri": "h/a/s/h/%s"}' % self.filename)
expected_url = 'http://localhost/files/h/a/s/h/test-image.jpg'
received_url = self.client.send(self.filepath)
self.assertEqual(expected_url, received_url)
|
class GuacamoleClientTest(unittest.TestCase):
def setUp(self):
pass
def test_client_send(self):
pass
| 3 | 0 | 6 | 1 | 6 | 0 | 1 | 0 | 1 | 1 | 1 | 0 | 2 | 4 | 2 | 74 | 15 | 3 | 12 | 10 | 9 | 0 | 12 | 9 | 9 | 1 | 2 | 1 | 2 |
6,019 |
Antojitos/guacamole-cli
|
Antojitos_guacamole-cli/tests/main.py
|
tests.main.TamalesClientTest
|
class TamalesClientTest(unittest.TestCase):
def setUp(self):
self.endpoint = 'http://localhost/api/v1/urls'
self.url = 'http://example.com/'
self.client = TamalesClient(self.endpoint)
def test_client_shorten(self):
with requests_mock.Mocker() as m:
text = '{"long_url": "%s", "short_url": "http://localhost/A"}' \
% self.url
m.post(self.endpoint, text=text)
expected_url = 'http://localhost/A'
received_url = self.client.shorten(self.url)
self.assertEqual(expected_url, received_url)
|
class TamalesClientTest(unittest.TestCase):
def setUp(self):
pass
def test_client_shorten(self):
pass
| 3 | 0 | 7 | 1 | 6 | 0 | 1 | 0 | 1 | 1 | 1 | 0 | 2 | 3 | 2 | 74 | 16 | 3 | 13 | 10 | 10 | 0 | 12 | 9 | 9 | 1 | 2 | 1 | 2 |
6,020 |
Antojitos/guacamole-cli
|
Antojitos_guacamole-cli/src/guacamole_cli/client.py
|
guacamole_cli.client.GuacamoleClient
|
class GuacamoleClient():
def __init__(self, endpoint):
self.endpoint = endpoint
def send(self, filename):
files = {'file': open(filename, 'rb')}
try:
request = requests.post(self.endpoint, files=files)
except requests.exceptions.RequestException:
return
response = request.json()
if 'uri' in response:
return '{0}{1}'.format(self.endpoint, response['uri'])
|
class GuacamoleClient():
def __init__(self, endpoint):
pass
def send(self, filename):
pass
| 3 | 0 | 6 | 1 | 6 | 0 | 2 | 0 | 0 | 0 | 0 | 0 | 2 | 1 | 2 | 2 | 14 | 2 | 12 | 7 | 9 | 0 | 12 | 7 | 9 | 3 | 0 | 1 | 4 |
6,021 |
AoiKuiyuyou/AoikI18n
|
AoiKuiyuyou_AoikI18n/src/aoiki18n/aoiki18n_.py
|
aoiki18n.aoiki18n_.I18n
|
class I18n(object):
#/
I18N_CLS_NOT_ALLOW_CREATING_OBJ_ERR = U('9x8Q3un')
LOAD_LOCALE_TT_FILE_ERR = U('3wLeaR5')
LOAD_LOCALE_FALLBACK_TT_FILE_ERR = U('8cyKaFE')
#/
TT_FILE_EXT_STXT = '.yml'
TT_FILE_EXT_UTXT = U('.yml')
#/
TT_FILE_K_SYNONYM = 'SYNONYM'
TT_FILE_K_TT = 'tt'
#/
DFT = type(None)
def __init__(self):
"""
Prevent client code from creating object of this class.
"""
msg = U('Can not create object of class I18n. Use class I18nObj instead.')
raisex(AssertionError(I18n.I18N_CLS_NOT_ALLOW_CREATING_OBJ_ERR, msg))
@staticmethod
def yaml_force_unicode():
"""
Force pyyaml to return unicode values.
"""
#/
## modified from |http://stackoverflow.com/a/2967461|
if sys.version_info[0] == 2:
def construct_func(self, node):
return self.construct_scalar(node)
yaml.Loader.add_constructor(U('tag:yaml.org,2002:str'), construct_func)
yaml.SafeLoader.add_constructor(U('tag:yaml.org,2002:str'), construct_func)
@staticmethod
def get_locale_hints():
"""
Get a list of locale hints,
guessed according to Python's default locale info.
"""
#/
lang, encoding = locale.getdefaultlocale()
## can both be None
#/
if lang and '_' in lang:
lang3, _, lang2 = lang.partition('_')
else:
lang3 = None
lang2 = None
#/
ll_s = [encoding, lang, lang2, lang3]
## Encoding comes before lang intentionally, e.g.
## lang |en_US| with encoding |cp936|, |cp936| takes priority.
#/
ll_s_unique = []
for ll in ll_s:
if ll:
ll = ll.lower()
if ll not in ll_s_unique:
ll_s_unique.append(ll)
#/
return ll_s_unique
@staticmethod
def get_locale_choices(locale_dir):
"""
Get a list of locale file names in the given locale dir.
"""
#/
file_name_s = os.listdir(locale_dir)
#/
choice_s = []
for file_name in file_name_s:
if file_name.endswith(I18n.TT_FILE_EXT_STXT):
file_name_noext, _ = os.path.splitext(file_name)
if file_name_noext:
choice_s.append(file_name_noext)
#/
choice_s = sorted(choice_s)
#/
return choice_s
|
class I18n(object):
def __init__(self):
'''
Prevent client code from creating object of this class.
'''
pass
@staticmethod
def yaml_force_unicode():
'''
Force pyyaml to return unicode values.
'''
pass
def construct_func(self, node):
pass
@staticmethod
def get_locale_hints():
'''
Get a list of locale hints,
guessed according to Python's default locale info.
'''
pass
@staticmethod
def get_locale_choices(locale_dir):
'''
Get a list of locale file names in the given locale dir.
'''
pass
| 9 | 4 | 15 | 2 | 7 | 5 | 3 | 0.67 | 1 | 1 | 0 | 0 | 1 | 0 | 4 | 4 | 96 | 19 | 46 | 27 | 37 | 31 | 42 | 24 | 36 | 5 | 1 | 3 | 13 |
6,022 |
AoiKuiyuyou/AoikI18n
|
AoiKuiyuyou_AoikI18n/src/aoiki18n/aoiki18n_.py
|
aoiki18n.aoiki18n_.I18nObj
|
class I18nObj(object):
def __init__(self, locale, locale2=None,
path_func=None,
file_encoding=None,
load_file=False,
):
#/
self.tt_dd = {}
## |tt| means text transform.
##
## |dd| means a dict of dicts.
## The primary dict is indexed by locale keys.
## The secondary dicts are indexed by tt keys.
#/ main locale
self.locale = locale
#/ fallback locale
self.locale2 = locale2
#/ locale file path func
self.path_func = path_func
#/ locale file encoding
self.file_encoding = file_encoding or 'utf-8'
#/
if load_file:
try:
self.locale = self.load_tt_file(
locale=self.locale,
path_func=self.path_func,
encoding=self.file_encoding,
)
## |load_tt_file| returns the true locale name
## in case the original locale file is in synonym format
except Exception as e:
reraisex(AssertionError(I18n.LOAD_LOCALE_TT_FILE_ERR, e))
#/
if self.locale2 and self.locale2 != self.locale:
try:
self.locale2 = self.load_tt_file(
locale=self.locale2,
path_func=self.path_func,
encoding=self.file_encoding,
)
## |load_tt_file| returns the true locale name
## in case the original locale file is in synonym format
except Exception as e:
reraisex(AssertionError(I18n.LOAD_LOCALE_FALLBACK_TT_FILE_ERR, e))
def load_tt_dict(self, locale, tt_d):
"""
Load a tt dict into |self.tt_dd|.
|tt| means text transform.
locale: key into |self.tt_dd|.
tt_d: a tt dict.
"""
#/ get the old tt dict of the locale
tt_d_old = self.tt_dd.get(locale, None)
#/ if has old tt dict
## N
if tt_d_old is None:
#/ use the new tt dict
self.tt_dd[locale] = tt_d
## Y
else:
#/ update the old tt dict
tt_d_old.update(tt_d)
def load_tt_file(self, locale, path_func=None, encoding=None):
"""
Load a tt file's tt dict into |self.tt_dd|.
|tt| means text transform.
locale: locale key into |self.tt_dd|.
path_func: tt file path func
encoding: tt file encoding
"""
#/
path_func = path_func or self.path_func
encoding = encoding or self.file_encoding
#/ get path
path = path_func(locale)
#/ load dict from locale file
tt_file_d = yaml.load(codecs.open(path, mode='r', encoding=encoding))
#/
target_locale = tt_file_d.get(I18n.TT_FILE_K_SYNONYM, None)
#/ if the locale file is in synonym format
## Y
if target_locale:
#/ load the target locale file instead
return self.load_tt_file(locale=target_locale, path_func=path_func, encoding=encoding)
## N
#/ get the tt dict from the file dict
tt_d = tt_file_d[I18n.TT_FILE_K_TT]
#/ add to
self.load_tt_dict(locale=locale, tt_d=tt_d)
#/ return the true locale
## this is useful in case the original locale file is in synonym format
return locale
def tt(self, key, locale=None, locale2=None, default=I18n.DFT):
"""
|tt| means text transform.
key: tt key.
locale: main locale key into |self.tt_dd|. Default to |self.locale|
locale2: fallback locale key into |self.tt_dd|. Default to |self.locale2|
default: a default value in case tt value is not found. Default to raise KeyError.
"""
#/
locale = locale or self.locale
locale2 = locale2 or self.locale2
#/ get tt dict of the locale
tt_d = self.tt_dd.get(locale, None)
if tt_d is not None:
#/
val = tt_d.get(key, I18n.DFT)
#/ if tt value is found
if val is not I18n.DFT:
return val
#/ tt value is not found
#/ if has locale2
## Y
if locale2 and locale2 != locale:
#/ fall back to locale2
return self.tt(key, locale=locale2, default=default)
## N
else:
#/ if default is specified
## N
if default is I18n.DFT:
raise KeyError(key)
## Y
else:
return default
|
class I18nObj(object):
def __init__(self, locale, locale2=None,
path_func=None,
file_encoding=None,
load_file=False,
):
pass
def load_tt_dict(self, locale, tt_d):
'''
Load a tt dict into |self.tt_dd|.
|tt| means text transform.
locale: key into |self.tt_dd|.
tt_d: a tt dict.
'''
pass
def load_tt_file(self, locale, path_func=None, encoding=None):
'''
Load a tt file's tt dict into |self.tt_dd|.
|tt| means text transform.
locale: locale key into |self.tt_dd|.
path_func: tt file path func
encoding: tt file encoding
'''
pass
def tt(self, key, locale=None, locale2=None, default=I18n.DFT):
'''
|tt| means text transform.
key: tt key.
locale: main locale key into |self.tt_dd|. Default to |self.locale|
locale2: fallback locale key into |self.tt_dd|. Default to |self.locale2|
default: a default value in case tt value is not found. Default to raise KeyError.
'''
pass
| 5 | 3 | 38 | 7 | 15 | 17 | 4 | 1.08 | 1 | 4 | 1 | 0 | 4 | 5 | 4 | 4 | 158 | 31 | 61 | 22 | 52 | 66 | 46 | 17 | 41 | 5 | 1 | 3 | 14 |
6,023 |
AoiKuiyuyou/AoikImportUtil-Python
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AoiKuiyuyou_AoikImportUtil-Python/tools/waf/aoikwafutil.py
|
aoikwafutil.build_ctx._noarg_decorator._BuildContext
|
class _BuildContext(BuildContext):
# Set command name for the context class
cmd = func.__name__
# Set function name for the context class
fun = func.__name__
|
class _BuildContext(BuildContext):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0.67 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 | 1 | 3 | 3 | 2 | 2 | 3 | 3 | 2 | 0 | 1 | 0 | 0 |
6,024 |
AoiKuiyuyou/AoikImportUtil-Python
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AoiKuiyuyou_AoikImportUtil-Python/tools/waf/aoikwafutil.py
|
aoikwafutil.config_ctx._ConfigurationContext
|
class _ConfigurationContext(ConfigurationContext):
# Set command name for the context class
cmd = func.__name__
# Set function name for the context class
fun = func.__name__
|
class _ConfigurationContext(ConfigurationContext):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0.67 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 | 1 | 3 | 3 | 2 | 2 | 3 | 3 | 2 | 0 | 1 | 0 | 0 |
6,025 |
AoiKuiyuyou/AoikImportUtil-Python
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AoiKuiyuyou_AoikImportUtil-Python/tools/pip/get-pip.py
|
get-pip.bootstrap.CertInstallCommand
|
class CertInstallCommand(InstallCommand):
def parse_args(self, args):
# If cert isn't specified in config or environment, we provide our
# own certificate through defaults.
# This allows user to specify custom cert anywhere one likes:
# config, environment variable or argv.
if not self.parser.get_default_values().cert:
self.parser.defaults["cert"] = cert_path # calculated below
return super(CertInstallCommand, self).parse_args(args)
|
class CertInstallCommand(InstallCommand):
def parse_args(self, args):
pass
| 2 | 0 | 8 | 0 | 4 | 5 | 2 | 1 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 1 | 9 | 0 | 5 | 2 | 3 | 5 | 5 | 2 | 3 | 2 | 1 | 1 | 2 |
6,026 |
AoiKuiyuyou/AoikImportUtil-Python
|
AoiKuiyuyou_AoikImportUtil-Python/tools/waf/aoikwafutil.py
|
aoikwafutil._ItemWrapper
|
class _ItemWrapper(object):
"""
Wrap given item for special handling later.
"""
def __init__(self, type, item):
"""
Constructor.
:param type: Wrapper type.
Allowed values:
- 'path': Given item is relative path relative to top
directory.
- 'input': Given item should be added to task as input target.
- 'output': Given item should be added to task as output
target.
:param item: Item to wrap.
:return: None.
"""
# If given type is not valid
if type not in ('path', 'input', 'output'):
# Get error message
msg = 'Error (6VYQM): Type is not valid: {0}.'.format(type)
# Raise error
raise ValueError(msg)
# If given type is valid.
# Store wrapper type
self._type = type
# Store given item
self._item = item
def type(self):
"""
Get wrapper type.
:return: Wrapper type.
"""
# Return wrapper type
return self._type
def item(self):
"""
Get wrapped item.
:return: Wrapped item.
"""
# Return wrapped item
return self._item
|
class _ItemWrapper(object):
'''
Wrap given item for special handling later.
'''
def __init__(self, type, item):
'''
Constructor.
:param type: Wrapper type.
Allowed values:
- 'path': Given item is relative path relative to top
directory.
- 'input': Given item should be added to task as input target.
- 'output': Given item should be added to task as output
target.
:param item: Item to wrap.
:return: None.
'''
pass
def type(self):
'''
Get wrapper type.
:return: Wrapper type.
'''
pass
def item(self):
'''
Get wrapped item.
:return: Wrapped item.
'''
pass
| 4 | 4 | 17 | 4 | 3 | 9 | 1 | 2.82 | 1 | 1 | 0 | 0 | 3 | 2 | 3 | 3 | 57 | 15 | 11 | 7 | 7 | 31 | 11 | 7 | 7 | 2 | 1 | 1 | 4 |
6,027 |
AoiKuiyuyou/AoikImportUtil-Python
|
AoiKuiyuyou_AoikImportUtil-Python/tools/waf/aoikwafutil.py
|
aoikwafutil.CmdTask
|
class CmdTask(Task):
"""
Task that runs command.
"""
def __init__(
self,
ctx,
parts,
task_name=None,
*args,
**kwargs
):
"""
Constructor.
:param ctx: BuildContext object.
:param parts: Command parts list.
:param task_name: Task name for display purpose.
:param \\*args: Other arguments passed to parent constructor.
:param \\*\\*kwargs: Other keyword arguments passed to parent
constructor.
:return: None.
"""
# Call parent constructor
Task.__init__(self, *args, **kwargs)
# Ensure given context object is BuildContext object
_ensure_build_context(ctx)
# Store context object
self._ctx = ctx
# Store command parts
self._parts = parts
# Store task name
self._task_name = task_name
# Get task title for display purpose
self._task_name_title = 'CmdTask: {}'.format(self._task_name) \
if self._task_name else 'CmdTask'
# Get working directory. Default is current Python's working directory.
self._cwd = kwargs.get('cwd', os.getcwd())
def run(self):
"""
Run command.
:return: Command exit code.
"""
# Print task title
print_title(self._task_name_title)
# Get context object
ctx = self._ctx
# Get command parts
cmd_part_s = self._parts
# Print title
print_title('Find program')
# Get program path from command parts
program_path = cmd_part_s[0]
# If the program path ends with one of the file extensions below
if program_path.endswith(('.exe', '.com', '.bat', '.cmd')):
# Remove the file extension.
# This is because `Waf`'s `find_binary` function adds each of the
# file extensions when finding the program.
program_path = program_path[:-4]
# Print info
print_text('Find program: {0}'.format(program_path))
#
try:
# Find program
found_program_path_s = ctx.find_program(program_path, quiet=True)
# If program paths are not found
except ConfigurationError:
# Get error message
msg = 'Error (2D7VS): Program is not found: {0}'.format(
program_path
)
# Raise error
raise ValueError(msg)
# If program paths are found.
# If program paths are found.
# Use the first program path found.
# If program paths are not found. (Should not happen.)
# Use given program path.
found_program_path = found_program_path_s[0] \
if found_program_path_s else program_path
# Use the program path found as the first command part
cmd_part_s[0] = found_program_path
# Print info
print_text('Use program: {0}'.format(found_program_path))
# Print end title
print_title('Find program', is_end=True)
# Print title
print_title('PATH')
# Print environment variable PATH's value, one part per line
print_text('\n'.join(os.environ.get('PATH', '').split(os.pathsep)))
# Print end title
print_title('PATH', is_end=True)
# Print title
print_title('PYTHONPATH')
# Print environment variable PYTHONPATH's value, one part per line
print_text(
'\n'.join(os.environ.get('PYTHONPATH', '').split(os.pathsep))
)
# Print end title
print_title('PYTHONPATH', is_end=True)
# Print title
print_title('DIR')
# Print working directory
print_text(self._cwd)
# Print end title
print_title('DIR', is_end=True)
# Print title
print_title('CMD')
# Print the command in multi-line format
print_text(_format_multi_line_command(cmd_part_s))
# Print end title
print_title('CMD', is_end=True)
# Print title
print_title('RUN')
# Run the command in the working directory
exit_code = self.exec_command(cmd_part_s, cwd=self._cwd)
# Print the command's exit code
print_text('Exit code: {0}'.format(exit_code))
# Print end title
print_title('RUN', is_end=True)
# Print task end title
print_title(self._task_name_title, True)
# Return the exit code
return exit_code
|
class CmdTask(Task):
'''
Task that runs command.
'''
def __init__(
self,
ctx,
parts,
task_name=None,
*args,
**kwargs
):
'''
Constructor.
:param ctx: BuildContext object.
:param parts: Command parts list.
:param task_name: Task name for display purpose.
:param \*args: Other arguments passed to parent constructor.
:param \*\*kwargs: Other keyword arguments passed to parent
constructor.
:return: None.
'''
pass
def run(self):
'''
Run command.
:return: Command exit code.
'''
pass
| 3 | 3 | 82 | 23 | 29 | 31 | 3 | 1.12 | 1 | 1 | 0 | 0 | 2 | 5 | 2 | 2 | 170 | 47 | 58 | 22 | 48 | 65 | 45 | 15 | 42 | 4 | 1 | 1 | 6 |
6,028 |
AoiKuiyuyou/AoikLiveReload
|
AoiKuiyuyou_AoikLiveReload/src/aoiklivereload/aoiklivereload.py
|
aoiklivereload.aoiklivereload.LiveReloader
|
class LiveReloader(FileSystemEventHandler):
"""
Live reloader that detects module file changes and reloads the program.
"""
# Reload mode constants
RELOAD_MODE_V_EXEC = 'exec'
RELOAD_MODE_V_SPAWN_EXIT = 'spawn_exit'
RELOAD_MODE_V_SPAWN_WAIT = 'spawn_wait'
RELOAD_MODE_VALUES = (
RELOAD_MODE_V_EXEC,
RELOAD_MODE_V_SPAWN_EXIT,
RELOAD_MODE_V_SPAWN_WAIT,
)
def __init__(
self,
reload_mode=None,
force_exit=False,
extra_paths=None,
interval=1,
):
"""
Constructor.
:param reload_mode:
Reload mode.
Default is 'spawn_wait' for Windows and 'exec' otherwise.
Notice `exec` reload mode will crash on Windows.
Allowed values:
- 'exec': Replace the current process with a new process.
- 'spawn_exit': Spawn a subprocess, the current process exits.
- 'spawn_wait': Spawn a subprocess, the current process waits.
:param force_exit:
In `spawn_exit` mode, whether call `os._exit` to force the \
current process to terminate immediately. Default is not.
:param extra_paths:
Extra file paths to watch for changes.
:param interval:
Sleep interval between two change checks, in seconds.
:return:
None.
"""
# If reload mode is not given
if reload_mode is None:
# If in Windows
if sys.platform == 'win32':
# Use default `spawn_wait`
reload_mode = self.RELOAD_MODE_V_SPAWN_WAIT
# If not in Windows
else:
# Use default `exec`
reload_mode = self.RELOAD_MODE_V_EXEC
# If reload mode is not valid
if reload_mode not in self.RELOAD_MODE_VALUES:
# Get error message
error_msg = 'Invalid reload mode: {}.'.format(repr(reload_mode))
# Raise error
raise ValueError(error_msg)
# Store reload mode
self._reload_mode = reload_mode
# Store whether force exit
self._force_exit = bool(force_exit)
# Convert given extra paths to absolute
self._extra_paths = set(
os.path.abspath(x) for x in (extra_paths or ())
)
# Store check interval
self._interval = interval
# Set of watch paths
self._watch_paths = set()
# Whether the watcher thread should stop
self._watcher_to_stop = False
def start_watcher_thread(self):
"""
Start watcher thread.
:return:
Watcher thread object.
"""
# Create watcher thread
watcher_thread = threading.Thread(target=self.run_watcher)
# If the reload mode is `spawn_wait`
if self._reload_mode == self.RELOAD_MODE_V_SPAWN_WAIT:
# Use non-daemon thread
daemon = False
# If the reload mode is not `spawn_wait`
else:
# Use daemon thread
daemon = True
# Set whether the thread is daemon
watcher_thread.setDaemon(daemon)
# Start watcher thread
watcher_thread.start()
# Return watcher thread
return watcher_thread
def run_watcher(self):
"""
Watcher thread's function.
:return:
None.
"""
# Create observer
observer = Observer()
# Start observer
observer.start()
# Dict that maps file path to `watch object`
watche_obj_map = {}
# Run change check in a loop
while not self._watcher_to_stop:
# Get current watch paths
old_watch_path_s = set(watche_obj_map)
# Get new watch paths
new_watch_path_s = self._find_watch_paths()
# For each new watch path
for new_watch_path in new_watch_path_s:
# Remove from the old watch paths if exists
old_watch_path_s.discard(new_watch_path)
# If the new watch path was not watched
if new_watch_path not in watche_obj_map:
try:
# Schedule a watch
watch_obj = observer.schedule(
# 2KGRW
# `FileSystemEventHandler` instance
self,
# File path to watch
new_watch_path,
# Whether recursive
recursive=True,
)
# Store the watch obj
watche_obj_map[new_watch_path] = watch_obj
# If have error
except OSError:
# Set the watch object be None
watche_obj_map[new_watch_path] = None
# For each old watch path that is not in the new watch paths
for old_watch_path in old_watch_path_s:
# Get watch object
watch_obj = watche_obj_map.pop(old_watch_path, None)
# If have watch object
if watch_obj is not None:
# Unschedule the watch
observer.unschedule(watch_obj)
# Store new watch paths
self._watch_paths = new_watch_path_s
# Sleep before next check
time.sleep(self._interval)
def _find_watch_paths(self):
"""
Find paths to watch.
:return:
Paths to watch.
"""
# Add directory paths in `sys.path` to watch paths
watch_path_s = set(os.path.abspath(x) for x in sys.path)
# For each extra path
for extra_path in self._extra_paths or ():
# Get the extra path's directory path
extra_dir_path = os.path.dirname(os.path.abspath(extra_path))
# Add to watch paths
watch_path_s.add(extra_dir_path)
# For each module in `sys.modules`
for module in list(sys.modules.values()):
# Get module file path
module_path = getattr(module, '__file__', None)
# If have module file path
if module_path is not None:
# Get module directory path
module_dir_path = os.path.dirname(os.path.abspath(module_path))
# Add to watch paths
watch_path_s.add(module_dir_path)
# Find short paths of these watch paths.
# E.g. if both `/home` and `/home/aoik` exist, only keep `/home`.
watch_path_s = self._find_short_paths(watch_path_s)
# Return the watch paths
return watch_path_s
def _find_short_paths(self, paths):
"""
Find short paths of given paths.
E.g. if both `/home` and `/home/aoik` exist, only keep `/home`.
:param paths:
Paths.
:return:
Set of short paths.
"""
# Split each path to parts.
# E.g. '/home/aoik' to ['', 'home', 'aoik']
path_parts_s = [path.split(os.path.sep) for path in paths]
# Root node
root_node = {}
# Sort these path parts by length, with the longest being the first.
#
# Longer paths appear first so that their extra parts are discarded
# when a shorter path is found at 5TQ8L.
#
# Then for each path's parts.
for parts in sorted(path_parts_s, key=len, reverse=True):
# Start from the root node
node = root_node
# For each part of the path
for part in parts:
# Create node of the path
node = node.setdefault(part, {})
# 5TQ8L
# Clear the last path part's node's child nodes.
#
# This aims to keep only the shortest path that needs be watched.
#
node.clear()
# Short paths
short_path_s = set()
# Collect leaf paths
self._collect_leaf_paths(
node=root_node,
path_parts=(),
leaf_paths=short_path_s,
)
# Return short paths
return short_path_s
def _collect_leaf_paths(self, node, path_parts, leaf_paths):
"""
Collect paths of leaf nodes.
:param node:
Starting node. Type is dict.
Key is child node's path part. Value is child node.
:param path_parts:
The starting node's path parts. Type is tuple.
:param leaf_paths:
Leaf path list.
:return:
None.
"""
# If the node is leaf node
if not node:
# Get node path
node_path = '/'.join(path_parts)
# Add to list
leaf_paths.add(node_path)
# If the node is not leaf node
else:
# For each child node
for child_path_part, child_node in node.items():
# Get the child node's path parts
child_path_part_s = path_parts + (child_path_part,)
# Visit the child node
self._collect_leaf_paths(
node=child_node,
path_parts=child_path_part_s,
leaf_paths=leaf_paths,
)
def dispatch(self, event):
"""
Dispatch file system event.
Callback called when there is a file system event. Hooked at 2KGRW.
This function overrides `FileSystemEventHandler.dispatch`.
:param event:
File system event object.
:return:
None.
"""
# Get file path
file_path = event.src_path
# If the file path is in extra paths
if file_path in self._extra_paths:
# Call `reload`
self.reload()
# If the file path ends with `.pyc` or `.pyo`
if file_path.endswith(('.pyc', '.pyo')):
# Get `.py` file path
file_path = file_path[:-1]
# If the file path ends with `.py`
if file_path.endswith('.py'):
# Get the file's directory path
file_dir = os.path.dirname(file_path)
# If the file's directory path starts with any of the watch paths
if file_dir.startswith(tuple(self._watch_paths)):
# Call `reload`
self.reload()
def reload(self):
"""
Reload the program.
:return:
None.
"""
# Get reload mode
reload_mode = self._reload_mode
# If reload mode is `exec`
if self._reload_mode == self.RELOAD_MODE_V_EXEC:
# Call `reload_using_exec`
self.reload_using_exec()
# If reload mode is `spawn_exit`
elif self._reload_mode == self.RELOAD_MODE_V_SPAWN_EXIT:
# Call `reload_using_spawn_exit`
self.reload_using_spawn_exit()
# If reload mode is `spawn_wait`
elif self._reload_mode == self.RELOAD_MODE_V_SPAWN_WAIT:
# Call `reload_using_spawn_wait`
self.reload_using_spawn_wait()
# If reload mode is none of above
else:
# Get error message
error_msg = 'Invalid reload mode: {}.'.format(repr(reload_mode))
# Raise error
raise ValueError(error_msg)
def reload_using_exec(self):
"""
Reload the program process.
:return:
None.
"""
# Create command parts
cmd_parts = [sys.executable] + sys.argv
# Get env dict copy
env_copy = os.environ.copy()
# Reload the program process
os.execvpe(
# Program file path
sys.executable,
# Command parts
cmd_parts,
# Env dict
env_copy,
)
def reload_using_spawn_exit(self):
"""
Spawn a subprocess and exit the current process.
:return:
None.
"""
# Create command parts
cmd_parts = [sys.executable] + sys.argv
# Get env dict copy
env_copy = os.environ.copy()
# Spawn subprocess
subprocess.Popen(cmd_parts, env=env_copy, close_fds=True)
# If need force exit
if self._force_exit:
# Force exit
os._exit(0) # pylint: disable=protected-access
# If not need force exit
else:
# Send interrupt to main thread
interrupt_main()
# Set the flag
self._watcher_to_stop = True
# Exit the watcher thread
sys.exit(0)
def reload_using_spawn_wait(self):
"""
Spawn a subprocess and wait until it finishes.
:return:
None.
"""
# Create command parts
cmd_parts = [sys.executable] + sys.argv
# Get env dict copy
env_copy = os.environ.copy()
# Send interrupt to main thread
interrupt_main()
# Spawn subprocess and wait until it finishes
subprocess.call(cmd_parts, env=env_copy, close_fds=True)
# Exit the watcher thread
sys.exit(0)
|
class LiveReloader(FileSystemEventHandler):
'''
Live reloader that detects module file changes and reloads the program.
'''
def __init__(
self,
reload_mode=None,
force_exit=False,
extra_paths=None,
interval=1,
):
'''
Constructor.
:param reload_mode:
Reload mode.
Default is 'spawn_wait' for Windows and 'exec' otherwise.
Notice `exec` reload mode will crash on Windows.
Allowed values:
- 'exec': Replace the current process with a new process.
- 'spawn_exit': Spawn a subprocess, the current process exits.
- 'spawn_wait': Spawn a subprocess, the current process waits.
:param force_exit:
In `spawn_exit` mode, whether call `os._exit` to force the current process to terminate immediately. Default is not.
:param extra_paths:
Extra file paths to watch for changes.
:param interval:
Sleep interval between two change checks, in seconds.
:return:
None.
'''
pass
def start_watcher_thread(self):
'''
Start watcher thread.
:return:
Watcher thread object.
'''
pass
def run_watcher(self):
'''
Watcher thread's function.
:return:
None.
'''
pass
def _find_watch_paths(self):
'''
Find paths to watch.
:return:
Paths to watch.
'''
pass
def _find_short_paths(self, paths):
'''
Find short paths of given paths.
E.g. if both `/home` and `/home/aoik` exist, only keep `/home`.
:param paths:
Paths.
:return:
Set of short paths.
'''
pass
def _collect_leaf_paths(self, node, path_parts, leaf_paths):
'''
Collect paths of leaf nodes.
:param node:
Starting node. Type is dict.
Key is child node's path part. Value is child node.
:param path_parts:
The starting node's path parts. Type is tuple.
:param leaf_paths:
Leaf path list.
:return:
None.
'''
pass
def dispatch(self, event):
'''
Dispatch file system event.
Callback called when there is a file system event. Hooked at 2KGRW.
This function overrides `FileSystemEventHandler.dispatch`.
:param event:
File system event object.
:return:
None.
'''
pass
def reload(self):
'''
Reload the program.
:return:
None.
'''
pass
def reload_using_exec(self):
'''
Reload the program process.
:return:
None.
'''
pass
def reload_using_spawn_exit(self):
'''
Spawn a subprocess and exit the current process.
:return:
None.
'''
pass
def reload_using_spawn_wait(self):
'''
Spawn a subprocess and wait until it finishes.
:return:
None.
'''
pass
| 12 | 12 | 40 | 8 | 13 | 19 | 3 | 1.41 | 1 | 8 | 0 | 0 | 11 | 6 | 11 | 11 | 466 | 105 | 150 | 63 | 132 | 212 | 115 | 57 | 103 | 7 | 1 | 4 | 36 |
6,029 |
AoiKuiyuyou/AoikLiveReload
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AoiKuiyuyou_AoikLiveReload/tools/waf/aoikwafutil.py
|
aoikwafutil.config_ctx._ConfigurationContext
|
class _ConfigurationContext(ConfigurationContext):
# Set command name for the context class
cmd = func.__name__
# Set function name for the context class
fun = func.__name__
|
class _ConfigurationContext(ConfigurationContext):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0.67 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 | 1 | 3 | 3 | 2 | 2 | 3 | 3 | 2 | 0 | 1 | 0 | 0 |
6,030 |
AoiKuiyuyou/AoikLiveReload
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AoiKuiyuyou_AoikLiveReload/tools/pip/get-pip.py
|
get-pip.bootstrap.CertInstallCommand
|
class CertInstallCommand(InstallCommand):
def parse_args(self, args):
# If cert isn't specified in config or environment, we provide our
# own certificate through defaults.
# This allows user to specify custom cert anywhere one likes:
# config, environment variable or argv.
if not self.parser.get_default_values().cert:
self.parser.defaults["cert"] = cert_path # calculated below
return super(CertInstallCommand, self).parse_args(args)
|
class CertInstallCommand(InstallCommand):
def parse_args(self, args):
pass
| 2 | 0 | 8 | 0 | 4 | 5 | 2 | 1 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 1 | 9 | 0 | 5 | 2 | 3 | 5 | 5 | 2 | 3 | 2 | 1 | 1 | 2 |
6,031 |
AoiKuiyuyou/AoikLiveReload
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AoiKuiyuyou_AoikLiveReload/tools/waf/aoikwafutil.py
|
aoikwafutil.build_ctx._noarg_decorator._BuildContext
|
class _BuildContext(BuildContext):
# Set command name for the context class
cmd = func.__name__
# Set function name for the context class
fun = func.__name__
|
class _BuildContext(BuildContext):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0.67 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 | 1 | 3 | 3 | 2 | 2 | 3 | 3 | 2 | 0 | 1 | 0 | 0 |
6,032 |
AoiKuiyuyou/AoikLiveReload
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AoiKuiyuyou_AoikLiveReload/src/aoiklivereload/demo/tornado_demo.py
|
aoiklivereload.demo.tornado_demo.main.HelloHandler
|
class HelloHandler(tornado.web.RequestHandler):
"""
Request handler class.
"""
def get(self):
"""
Request handler.
:return:
None.
"""
# Write response body
self.write('hello')
|
class HelloHandler(tornado.web.RequestHandler):
'''
Request handler class.
'''
def get(self):
'''
Request handler.
:return:
None.
'''
pass
| 2 | 2 | 9 | 1 | 2 | 6 | 1 | 3 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 82 | 14 | 2 | 3 | 2 | 1 | 9 | 3 | 2 | 1 | 1 | 2 | 0 | 1 |
6,033 |
Ape/samsungctl
|
Ape_samsungctl/samsungctl/exceptions.py
|
samsungctl.exceptions.AccessDenied
|
class AccessDenied(Exception):
"""Connection was denied."""
pass
|
class AccessDenied(Exception):
'''Connection was denied.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 3 | 0 | 2 | 1 | 1 | 1 | 2 | 1 | 1 | 0 | 3 | 0 | 0 |
6,034 |
Ape/samsungctl
|
Ape_samsungctl/samsungctl/exceptions.py
|
samsungctl.exceptions.ConnectionClosed
|
class ConnectionClosed(Exception):
"""Connection was closed."""
pass
|
class ConnectionClosed(Exception):
'''Connection was closed.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 3 | 0 | 2 | 1 | 1 | 1 | 2 | 1 | 1 | 0 | 3 | 0 | 0 |
6,035 |
Ape/samsungctl
|
Ape_samsungctl/samsungctl/exceptions.py
|
samsungctl.exceptions.UnhandledResponse
|
class UnhandledResponse(Exception):
"""Received unknown response."""
pass
|
class UnhandledResponse(Exception):
'''Received unknown response.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 3 | 0 | 2 | 1 | 1 | 1 | 2 | 1 | 1 | 0 | 3 | 0 | 0 |
6,036 |
Ape/samsungctl
|
Ape_samsungctl/samsungctl/remote_websocket.py
|
samsungctl.remote_websocket.RemoteWebsocket
|
class RemoteWebsocket():
"""Object for remote control connection."""
def __init__(self, config):
import websocket
if not config["port"]:
config["port"] = 8001
if config["timeout"] == 0:
config["timeout"] = None
url = URL_FORMAT.format(config["host"], config["port"],
self._serialize_string(config["name"]))
self.connection = websocket.create_connection(url, config["timeout"])
self._read_response()
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self.close()
def close(self):
"""Close the connection."""
if self.connection:
self.connection.close()
self.connection = None
logging.debug("Connection closed.")
def control(self, key):
"""Send a control command."""
if not self.connection:
raise exceptions.ConnectionClosed()
payload = json.dumps({
"method": "ms.remote.control",
"params": {
"Cmd": "Click",
"DataOfCmd": key,
"Option": "false",
"TypeOfRemote": "SendRemoteKey"
}
})
logging.info("Sending control command: %s", key)
self.connection.send(payload)
time.sleep(self._key_interval)
_key_interval = 0.5
def _read_response(self):
response = self.connection.recv()
response = json.loads(response)
if response["event"] != "ms.channel.connect":
self.close()
raise exceptions.UnhandledResponse(response)
logging.debug("Access granted.")
@staticmethod
def _serialize_string(string):
if isinstance(string, str):
string = str.encode(string)
return base64.b64encode(string).decode("utf-8")
|
class RemoteWebsocket():
'''Object for remote control connection.'''
def __init__(self, config):
pass
def __enter__(self):
pass
def __exit__(self, type, value, traceback):
pass
def close(self):
'''Close the connection.'''
pass
def control(self, key):
'''Send a control command.'''
pass
def _read_response(self):
pass
@staticmethod
def _serialize_string(string):
pass
| 9 | 3 | 8 | 1 | 6 | 0 | 2 | 0.06 | 0 | 3 | 2 | 0 | 6 | 1 | 7 | 7 | 69 | 18 | 48 | 15 | 38 | 3 | 38 | 14 | 29 | 3 | 0 | 1 | 13 |
6,037 |
Ape/samsungctl
|
Ape_samsungctl/samsungctl/exceptions.py
|
samsungctl.exceptions.UnknownMethod
|
class UnknownMethod(Exception):
"""Unknown method."""
pass
|
class UnknownMethod(Exception):
'''Unknown method.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 3 | 0 | 2 | 1 | 1 | 1 | 2 | 1 | 1 | 0 | 3 | 0 | 0 |
6,038 |
Ape/samsungctl
|
Ape_samsungctl/samsungctl/remote_legacy.py
|
samsungctl.remote_legacy.RemoteLegacy
|
class RemoteLegacy():
"""Object for remote control connection."""
def __init__(self, config):
if not config["port"]:
config["port"] = 55000
"""Make a new connection."""
self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if config["timeout"]:
self.connection.settimeout(config["timeout"])
self.connection.connect((config["host"], config["port"]))
payload = b"\x64\x00" \
+ self._serialize_string(config["description"]) \
+ self._serialize_string(config["id"]) \
+ self._serialize_string(config["name"])
packet = b"\x00\x00\x00" + self._serialize_string(payload, True)
logging.info("Sending handshake.")
self.connection.send(packet)
self._read_response(True)
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self.close()
def close(self):
"""Close the connection."""
if self.connection:
self.connection.close()
self.connection = None
logging.debug("Connection closed.")
def control(self, key):
"""Send a control command."""
if not self.connection:
raise exceptions.ConnectionClosed()
payload = b"\x00\x00\x00" + self._serialize_string(key)
packet = b"\x00\x00\x00" + self._serialize_string(payload, True)
logging.info("Sending control command: %s", key)
self.connection.send(packet)
self._read_response()
time.sleep(self._key_interval)
_key_interval = 0.2
def _read_response(self, first_time=False):
header = self.connection.recv(3)
tv_name_len = int.from_bytes(header[1:3],
byteorder="little")
tv_name = self.connection.recv(tv_name_len)
if first_time:
logging.debug("Connected to '%s'.", tv_name.decode())
response_len = int.from_bytes(self.connection.recv(2),
byteorder="little")
response = self.connection.recv(response_len)
if len(response) == 0:
self.close()
raise exceptions.ConnectionClosed()
if response == b"\x64\x00\x01\x00":
logging.debug("Access granted.")
return
elif response == b"\x64\x00\x00\x00":
raise exceptions.AccessDenied()
elif response[0:1] == b"\x0a":
if first_time:
logging.warning("Waiting for authorization...")
return self._read_response()
elif response[0:1] == b"\x65":
logging.warning("Authorization cancelled.")
raise exceptions.AccessDenied()
elif response == b"\x00\x00\x00\x00":
logging.debug("Control accepted.")
return
raise exceptions.UnhandledResponse(response)
@staticmethod
def _serialize_string(string, raw=False):
if isinstance(string, str):
string = str.encode(string)
if not raw:
string = base64.b64encode(string)
return bytes([len(string)]) + b"\x00" + string
|
class RemoteLegacy():
'''Object for remote control connection.'''
def __init__(self, config):
pass
def __enter__(self):
pass
def __exit__(self, type, value, traceback):
pass
def close(self):
'''Close the connection.'''
pass
def control(self, key):
'''Send a control command.'''
pass
def _read_response(self, first_time=False):
pass
@staticmethod
def _serialize_string(string, raw=False):
pass
| 9 | 3 | 12 | 2 | 10 | 0 | 3 | 0.06 | 0 | 7 | 3 | 0 | 6 | 1 | 7 | 7 | 97 | 22 | 71 | 20 | 62 | 4 | 61 | 19 | 53 | 9 | 0 | 2 | 21 |
6,039 |
Ape/samsungctl
|
Ape_samsungctl/samsungctl/remote.py
|
samsungctl.remote.Remote
|
class Remote:
def __init__(self, config):
if config["method"] == "legacy":
self.remote = RemoteLegacy(config)
elif config["method"] == "websocket":
self.remote = RemoteWebsocket(config)
else:
raise exceptions.UnknownMethod()
def __enter__(self):
return self.remote.__enter__()
def __exit__(self, type, value, traceback):
self.remote.__exit__(type, value, traceback)
def close(self):
return self.remote.close()
def control(self, key):
return self.remote.control(key)
|
class Remote:
def __init__(self, config):
pass
def __enter__(self):
pass
def __exit__(self, type, value, traceback):
pass
def close(self):
pass
def control(self, key):
pass
| 6 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 0 | 3 | 3 | 0 | 5 | 1 | 5 | 5 | 20 | 4 | 16 | 7 | 10 | 0 | 14 | 7 | 8 | 3 | 0 | 1 | 7 |
6,040 |
Aperture-py/aperture-lib
|
Aperture-py_aperture-lib/tests/aperturelib_test_helper.py
|
tests.aperturelib_test_helper.ApertureLibTest
|
class ApertureLibTest(unittest.TestCase):
"""An extension of the unittest TestCase base class to provide
helper methods or test fixtures (i.e. Pillow) to be used in aperturelib
tests.
"""
def setUp(self):
"""Setup test fixtures before each ApertureLibTest."""
# Give each test a copy of pillow
self.pillow = pillow
|
class ApertureLibTest(unittest.TestCase):
'''An extension of the unittest TestCase base class to provide
helper methods or test fixtures (i.e. Pillow) to be used in aperturelib
tests.
'''
def setUp(self):
'''Setup test fixtures before each ApertureLibTest.'''
pass
| 2 | 2 | 5 | 1 | 2 | 2 | 1 | 2 | 1 | 0 | 0 | 1 | 1 | 1 | 1 | 73 | 11 | 2 | 3 | 3 | 1 | 6 | 3 | 3 | 1 | 1 | 2 | 0 | 1 |
6,041 |
Aperture-py/aperture-lib
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Aperture-py_aperture-lib/tests/watermark_test.py
|
tests.watermark_test.WatermarkTest
|
class WatermarkTest(aperturelib_test_helper.ApertureLibTest):
@unittest.skip('need to implement watermark test')
def test_watermark(self):
"""Test for the watermark function.
"""
return None
|
class WatermarkTest(aperturelib_test_helper.ApertureLibTest):
@unittest.skip('need to implement watermark test')
def test_watermark(self):
'''Test for the watermark function.
'''
pass
| 3 | 1 | 4 | 0 | 2 | 2 | 1 | 0.5 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 74 | 7 | 1 | 4 | 3 | 1 | 2 | 3 | 2 | 1 | 1 | 3 | 0 | 1 |
6,042 |
Aperture-py/aperture-lib
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Aperture-py_aperture-lib/tests/resize_test.py
|
tests.resize_test.ResizeTest
|
class ResizeTest(aperturelib_test_helper.ApertureLibTest):
@unittest.skip('need to implement resize test')
def test_resize(self):
"""Test for the resize function.
Things to test:
- The resizing actually works
- Aspect ratios are preserved by default
- Aspect ratios are not preserved if default is overriden
"""
return None
|
class ResizeTest(aperturelib_test_helper.ApertureLibTest):
@unittest.skip('need to implement resize test')
def test_resize(self):
'''Test for the resize function.
Things to test:
- The resizing actually works
- Aspect ratios are preserved by default
- Aspect ratios are not preserved if default is overriden
'''
pass
| 3 | 1 | 9 | 1 | 2 | 6 | 1 | 1.5 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 12 | 2 | 4 | 3 | 1 | 6 | 3 | 2 | 1 | 1 | 1 | 0 | 1 |
6,043 |
Apitax/Apitax
|
Apitax_Apitax/apitax/api/models/script_rename.py
|
apitax.api.models.script_rename.ScriptRename
|
class ScriptRename(Model):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, original=None, new=None): # noqa: E501
"""ScriptRename - a model defined in Swagger
:param original: The original of this ScriptRename. # noqa: E501
:type original: Script
:param new: The new of this ScriptRename. # noqa: E501
:type new: Script
"""
self.swagger_types = {
'original': Script,
'new': Script
}
self.attribute_map = {
'original': 'original',
'new': 'new'
}
self._original = original
self._new = new
@classmethod
def from_dict(cls, dikt):
"""Returns the dict as a model
:param dikt: A dict.
:type: dict
:return: The script_rename of this ScriptRename. # noqa: E501
:rtype: ScriptRename
"""
return util.deserialize_model(dikt, cls)
@property
def original(self):
"""Gets the original of this ScriptRename.
:return: The original of this ScriptRename.
:rtype: Script
"""
return self._original
@original.setter
def original(self, original):
"""Sets the original of this ScriptRename.
:param original: The original of this ScriptRename.
:type original: Script
"""
if original is None:
raise ValueError("Invalid value for `original`, must not be `None`") # noqa: E501
self._original = original
@property
def new(self):
"""Gets the new of this ScriptRename.
:return: The new of this ScriptRename.
:rtype: Script
"""
return self._new
@new.setter
def new(self, new):
"""Sets the new of this ScriptRename.
:param new: The new of this ScriptRename.
:type new: Script
"""
if new is None:
raise ValueError("Invalid value for `new`, must not be `None`") # noqa: E501
self._new = new
|
class ScriptRename(Model):
'''NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
'''
def __init__(self, original=None, new=None):
'''ScriptRename - a model defined in Swagger
:param original: The original of this ScriptRename. # noqa: E501
:type original: Script
:param new: The new of this ScriptRename. # noqa: E501
:type new: Script
'''
pass
@classmethod
def from_dict(cls, dikt):
'''Returns the dict as a model
:param dikt: A dict.
:type: dict
:return: The script_rename of this ScriptRename. # noqa: E501
:rtype: ScriptRename
'''
pass
@property
def original(self):
'''Gets the original of this ScriptRename.
:return: The original of this ScriptRename.
:rtype: Script
'''
pass
@original.setter
def original(self):
'''Sets the original of this ScriptRename.
:param original: The original of this ScriptRename.
:type original: Script
'''
pass
@property
def new(self):
'''Gets the new of this ScriptRename.
:return: The new of this ScriptRename.
:rtype: Script
'''
pass
@new.setter
def new(self):
'''Sets the new of this ScriptRename.
:param new: The new of this ScriptRename.
:type new: Script
'''
pass
| 12 | 7 | 11 | 2 | 4 | 5 | 1 | 1.1 | 1 | 2 | 1 | 0 | 5 | 4 | 6 | 12 | 83 | 21 | 31 | 16 | 19 | 34 | 20 | 11 | 13 | 2 | 2 | 1 | 8 |
6,044 |
Apitax/Apitax
|
Apitax_Apitax/apitax/api/models/script_save.py
|
apitax.api.models.script_save.ScriptSave
|
class ScriptSave(Model):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, script=None): # noqa: E501
"""ScriptSave - a model defined in Swagger
:param script: The script of this ScriptSave. # noqa: E501
:type script: Script
"""
self.swagger_types = {
'script': Script
}
self.attribute_map = {
'script': 'script'
}
self._script = script
@classmethod
def from_dict(cls, dikt):
"""Returns the dict as a model
:param dikt: A dict.
:type: dict
:return: The script_save of this ScriptSave. # noqa: E501
:rtype: ScriptSave
"""
return util.deserialize_model(dikt, cls)
@property
def script(self):
"""Gets the script of this ScriptSave.
:return: The script of this ScriptSave.
:rtype: Script
"""
return self._script
@script.setter
def script(self, script):
"""Sets the script of this ScriptSave.
:param script: The script of this ScriptSave.
:type script: Script
"""
if script is None:
raise ValueError("Invalid value for `script`, must not be `None`") # noqa: E501
self._script = script
|
class ScriptSave(Model):
'''NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
'''
def __init__(self, script=None):
'''ScriptSave - a model defined in Swagger
:param script: The script of this ScriptSave. # noqa: E501
:type script: Script
'''
pass
@classmethod
def from_dict(cls, dikt):
'''Returns the dict as a model
:param dikt: A dict.
:type: dict
:return: The script_save of this ScriptSave. # noqa: E501
:rtype: ScriptSave
'''
pass
@property
def script(self):
'''Gets the script of this ScriptSave.
:return: The script of this ScriptSave.
:rtype: Script
'''
pass
@script.setter
def script(self):
'''Sets the script of this ScriptSave.
:param script: The script of this ScriptSave.
:type script: Script
'''
pass
| 8 | 5 | 11 | 2 | 4 | 5 | 1 | 1.15 | 1 | 2 | 1 | 0 | 3 | 3 | 4 | 10 | 55 | 14 | 20 | 11 | 12 | 23 | 13 | 8 | 8 | 2 | 2 | 1 | 5 |
6,045 |
Apitax/Apitax
|
Apitax_Apitax/apitax/api/models/user.py
|
apitax.api.models.user.User
|
class User(Model):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, username=None, password=None, role=None): # noqa: E501
"""User - a model defined in Swagger
:param username: The username of this User. # noqa: E501
:type username: str
:param password: The password of this User. # noqa: E501
:type password: str
:param role: The role of this User. # noqa: E501
:type role: str
"""
self.swagger_types = {
'username': str,
'password': str,
'role': str
}
self.attribute_map = {
'username': 'username',
'password': 'password',
'role': 'role'
}
self._username = username
self._password = password
self._role = role
@classmethod
def from_dict(cls, dikt):
"""Returns the dict as a model
:param dikt: A dict.
:type: dict
:return: The User of this User. # noqa: E501
:rtype: User
"""
return util.deserialize_model(dikt, cls)
@property
def username(self):
"""Gets the username of this User.
:return: The username of this User.
:rtype: str
"""
return self._username
@username.setter
def username(self, username):
"""Sets the username of this User.
:param username: The username of this User.
:type username: str
"""
self._username = username
@property
def password(self):
"""Gets the password of this User.
:return: The password of this User.
:rtype: str
"""
return self._password
@password.setter
def password(self, password):
"""Sets the password of this User.
:param password: The password of this User.
:type password: str
"""
self._password = password
@property
def role(self):
"""Gets the role of this User.
:return: The role of this User.
:rtype: str
"""
return self._role
@role.setter
def role(self, role):
"""Sets the role of this User.
:param role: The role of this User.
:type role: str
"""
self._role = role
|
class User(Model):
'''NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
'''
def __init__(self, username=None, password=None, role=None):
'''User - a model defined in Swagger
:param username: The username of this User. # noqa: E501
:type username: str
:param password: The password of this User. # noqa: E501
:type password: str
:param role: The role of this User. # noqa: E501
:type role: str
'''
pass
@classmethod
def from_dict(cls, dikt):
'''Returns the dict as a model
:param dikt: A dict.
:type: dict
:return: The User of this User. # noqa: E501
:rtype: User
'''
pass
@property
def username(self):
'''Gets the username of this User.
:return: The username of this User.
:rtype: str
'''
pass
@username.setter
def username(self):
'''Sets the username of this User.
:param username: The username of this User.
:type username: str
'''
pass
@property
def password(self):
'''Gets the password of this User.
:return: The password of this User.
:rtype: str
'''
pass
@password.setter
def password(self):
'''Sets the password of this User.
:param password: The password of this User.
:type password: str
'''
pass
@property
def role(self):
'''Gets the role of this User.
:return: The role of this User.
:rtype: str
'''
pass
@role.setter
def role(self):
'''Sets the role of this User.
:param role: The role of this User.
:type role: str
'''
pass
| 16 | 9 | 11 | 2 | 4 | 5 | 1 | 1.17 | 1 | 1 | 0 | 0 | 7 | 5 | 8 | 14 | 105 | 28 | 36 | 21 | 20 | 42 | 21 | 14 | 12 | 1 | 2 | 0 | 8 |
6,046 |
Apitax/Apitax
|
Apitax_Apitax/apitax/api/models/user_auth.py
|
apitax.api.models.user_auth.UserAuth
|
class UserAuth(Model):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, username=None, password=None, api_token=None, extra=None): # noqa: E501
"""UserAuth - a model defined in Swagger
:param username: The username of this UserAuth. # noqa: E501
:type username: str
:param password: The password of this UserAuth. # noqa: E501
:type password: str
:param api_token: The api_token of this UserAuth. # noqa: E501
:type api_token: str
:param extra: The extra of this UserAuth. # noqa: E501
:type extra: object
"""
self.swagger_types = {
'username': str,
'password': str,
'api_token': str,
'extra': object
}
self.attribute_map = {
'username': 'username',
'password': 'password',
'api_token': 'api_token',
'extra': 'extra'
}
self._username = username
self._password = password
self._api_token = api_token
self._extra = extra
@classmethod
def from_dict(cls, dikt):
"""Returns the dict as a model
:param dikt: A dict.
:type: dict
:return: The UserAuth of this UserAuth. # noqa: E501
:rtype: UserAuth
"""
return util.deserialize_model(dikt, cls)
@property
def username(self):
"""Gets the username of this UserAuth.
:return: The username of this UserAuth.
:rtype: str
"""
return self._username
@username.setter
def username(self, username):
"""Sets the username of this UserAuth.
:param username: The username of this UserAuth.
:type username: str
"""
self._username = username
@property
def password(self):
"""Gets the password of this UserAuth.
:return: The password of this UserAuth.
:rtype: str
"""
return self._password
@password.setter
def password(self, password):
"""Sets the password of this UserAuth.
:param password: The password of this UserAuth.
:type password: str
"""
self._password = password
@property
def api_token(self):
"""Gets the api_token of this UserAuth.
:return: The api_token of this UserAuth.
:rtype: str
"""
return self._api_token
@api_token.setter
def api_token(self, api_token):
"""Sets the api_token of this UserAuth.
:param api_token: The api_token of this UserAuth.
:type api_token: str
"""
self._api_token = api_token
@property
def extra(self):
"""Gets the extra of this UserAuth.
:return: The extra of this UserAuth.
:rtype: object
"""
return self._extra
@extra.setter
def extra(self, extra):
"""Sets the extra of this UserAuth.
:param extra: The extra of this UserAuth.
:type extra: object
"""
self._extra = extra
|
class UserAuth(Model):
'''NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
'''
def __init__(self, username=None, password=None, api_token=None, extra=None):
'''UserAuth - a model defined in Swagger
:param username: The username of this UserAuth. # noqa: E501
:type username: str
:param password: The password of this UserAuth. # noqa: E501
:type password: str
:param api_token: The api_token of this UserAuth. # noqa: E501
:type api_token: str
:param extra: The extra of this UserAuth. # noqa: E501
:type extra: object
'''
pass
@classmethod
def from_dict(cls, dikt):
'''Returns the dict as a model
:param dikt: A dict.
:type: dict
:return: The UserAuth of this UserAuth. # noqa: E501
:rtype: UserAuth
'''
pass
@property
def username(self):
'''Gets the username of this UserAuth.
:return: The username of this UserAuth.
:rtype: str
'''
pass
@username.setter
def username(self):
'''Sets the username of this UserAuth.
:param username: The username of this UserAuth.
:type username: str
'''
pass
@property
def password(self):
'''Gets the password of this UserAuth.
:return: The password of this UserAuth.
:rtype: str
'''
pass
@password.setter
def password(self):
'''Sets the password of this UserAuth.
:param password: The password of this UserAuth.
:type password: str
'''
pass
@property
def api_token(self):
'''Gets the api_token of this UserAuth.
:return: The api_token of this UserAuth.
:rtype: str
'''
pass
@api_token.setter
def api_token(self):
'''Sets the api_token of this UserAuth.
:param api_token: The api_token of this UserAuth.
:type api_token: str
'''
pass
@property
def extra(self):
'''Gets the extra of this UserAuth.
:return: The extra of this UserAuth.
:rtype: object
'''
pass
@extra.setter
def extra(self):
'''Sets the extra of this UserAuth.
:param extra: The extra of this UserAuth.
:type extra: object
'''
pass
| 20 | 11 | 11 | 2 | 4 | 5 | 1 | 1.16 | 1 | 1 | 0 | 0 | 9 | 6 | 10 | 16 | 131 | 35 | 45 | 26 | 25 | 52 | 26 | 17 | 15 | 1 | 2 | 0 | 10 |
6,047 |
Apitax/Apitax
|
Apitax_Apitax/apitax/api/models/user_create.py
|
apitax.api.models.user_create.UserCreate
|
class UserCreate(Model):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, script=None): # noqa: E501
"""UserCreate - a model defined in Swagger
:param script: The script of this UserCreate. # noqa: E501
:type script: User
"""
self.swagger_types = {
'script': User
}
self.attribute_map = {
'script': 'script'
}
self._script = script
@classmethod
def from_dict(cls, dikt):
"""Returns the dict as a model
:param dikt: A dict.
:type: dict
:return: The user_create of this UserCreate. # noqa: E501
:rtype: UserCreate
"""
return util.deserialize_model(dikt, cls)
@property
def script(self):
"""Gets the script of this UserCreate.
:return: The script of this UserCreate.
:rtype: User
"""
return self._script
@script.setter
def script(self, script):
"""Sets the script of this UserCreate.
:param script: The script of this UserCreate.
:type script: User
"""
if script is None:
raise ValueError("Invalid value for `script`, must not be `None`") # noqa: E501
self._script = script
|
class UserCreate(Model):
'''NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
'''
def __init__(self, script=None):
'''UserCreate - a model defined in Swagger
:param script: The script of this UserCreate. # noqa: E501
:type script: User
'''
pass
@classmethod
def from_dict(cls, dikt):
'''Returns the dict as a model
:param dikt: A dict.
:type: dict
:return: The user_create of this UserCreate. # noqa: E501
:rtype: UserCreate
'''
pass
@property
def script(self):
'''Gets the script of this UserCreate.
:return: The script of this UserCreate.
:rtype: User
'''
pass
@script.setter
def script(self):
'''Sets the script of this UserCreate.
:param script: The script of this UserCreate.
:type script: User
'''
pass
| 8 | 5 | 11 | 2 | 4 | 5 | 1 | 1.15 | 1 | 2 | 1 | 0 | 3 | 3 | 4 | 10 | 55 | 14 | 20 | 11 | 12 | 23 | 13 | 8 | 8 | 2 | 2 | 1 | 5 |
6,048 |
Apitax/Apitax
|
Apitax_Apitax/apitax/api/models/user_delete.py
|
apitax.api.models.user_delete.UserDelete
|
class UserDelete(Model):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, script=None): # noqa: E501
"""UserDelete - a model defined in Swagger
:param script: The script of this UserDelete. # noqa: E501
:type script: User
"""
self.swagger_types = {
'script': User
}
self.attribute_map = {
'script': 'script'
}
self._script = script
@classmethod
def from_dict(cls, dikt):
"""Returns the dict as a model
:param dikt: A dict.
:type: dict
:return: The user_delete of this UserDelete. # noqa: E501
:rtype: UserDelete
"""
return util.deserialize_model(dikt, cls)
@property
def script(self):
"""Gets the script of this UserDelete.
:return: The script of this UserDelete.
:rtype: User
"""
return self._script
@script.setter
def script(self, script):
"""Sets the script of this UserDelete.
:param script: The script of this UserDelete.
:type script: User
"""
if script is None:
raise ValueError("Invalid value for `script`, must not be `None`") # noqa: E501
self._script = script
|
class UserDelete(Model):
'''NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
'''
def __init__(self, script=None):
'''UserDelete - a model defined in Swagger
:param script: The script of this UserDelete. # noqa: E501
:type script: User
'''
pass
@classmethod
def from_dict(cls, dikt):
'''Returns the dict as a model
:param dikt: A dict.
:type: dict
:return: The user_delete of this UserDelete. # noqa: E501
:rtype: UserDelete
'''
pass
@property
def script(self):
'''Gets the script of this UserDelete.
:return: The script of this UserDelete.
:rtype: User
'''
pass
@script.setter
def script(self):
'''Sets the script of this UserDelete.
:param script: The script of this UserDelete.
:type script: User
'''
pass
| 8 | 5 | 11 | 2 | 4 | 5 | 1 | 1.15 | 1 | 2 | 1 | 0 | 3 | 3 | 4 | 10 | 55 | 14 | 20 | 11 | 12 | 23 | 13 | 8 | 8 | 2 | 2 | 1 | 5 |
6,049 |
Apitax/Apitax
|
Apitax_Apitax/apitax/api/models/user_save.py
|
apitax.api.models.user_save.UserSave
|
class UserSave(Model):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, script=None): # noqa: E501
"""UserSave - a model defined in Swagger
:param script: The script of this UserSave. # noqa: E501
:type script: User
"""
self.swagger_types = {
'script': User
}
self.attribute_map = {
'script': 'script'
}
self._script = script
@classmethod
def from_dict(cls, dikt):
"""Returns the dict as a model
:param dikt: A dict.
:type: dict
:return: The user_save of this UserSave. # noqa: E501
:rtype: UserSave
"""
return util.deserialize_model(dikt, cls)
@property
def script(self):
"""Gets the script of this UserSave.
:return: The script of this UserSave.
:rtype: User
"""
return self._script
@script.setter
def script(self, script):
"""Sets the script of this UserSave.
:param script: The script of this UserSave.
:type script: User
"""
if script is None:
raise ValueError("Invalid value for `script`, must not be `None`") # noqa: E501
self._script = script
|
class UserSave(Model):
'''NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
'''
def __init__(self, script=None):
'''UserSave - a model defined in Swagger
:param script: The script of this UserSave. # noqa: E501
:type script: User
'''
pass
@classmethod
def from_dict(cls, dikt):
'''Returns the dict as a model
:param dikt: A dict.
:type: dict
:return: The user_save of this UserSave. # noqa: E501
:rtype: UserSave
'''
pass
@property
def script(self):
'''Gets the script of this UserSave.
:return: The script of this UserSave.
:rtype: User
'''
pass
@script.setter
def script(self):
'''Sets the script of this UserSave.
:param script: The script of this UserSave.
:type script: User
'''
pass
| 8 | 5 | 11 | 2 | 4 | 5 | 1 | 1.15 | 1 | 2 | 1 | 0 | 3 | 3 | 4 | 10 | 55 | 14 | 20 | 11 | 12 | 23 | 13 | 8 | 8 | 2 | 2 | 1 | 5 |
6,050 |
Apitax/Apitax
|
Apitax_Apitax/apitax/drivers/builtin/BasicAuth.py
|
apitax.drivers.builtin.BasicAuth.BasicAuth
|
class BasicAuth(Driver):
def __init__(self):
super().__init__()
self.users = read(getPath(State.paths['root'] + "/app/users.json"))
def getDriverName(self) -> str:
return "Basic Auth"
def getDriverDescription(self) -> str:
return "Provides out of the box authentication"
def getDriverHelpEndpoint(self) -> str:
return "coming soon"
def getDriverTips(self) -> str:
return "coming soon"
def isDriverAuthenticatable(self) -> bool:
return True
def isApitaxAuthBasedOnApiAuth(self) -> bool:
return False
def authenticateApitax(self, credentials: Credentials = None) -> str:
try:
if credentials.password == self.users[credentials.username]['password']:
return self.users[credentials.username]['role']
except:
return None
return None
|
class BasicAuth(Driver):
def __init__(self):
pass
def getDriverName(self) -> str:
pass
def getDriverDescription(self) -> str:
pass
def getDriverHelpEndpoint(self) -> str:
pass
def getDriverTips(self) -> str:
pass
def isDriverAuthenticatable(self) -> bool:
pass
def isApitaxAuthBasedOnApiAuth(self) -> bool:
pass
def authenticateApitax(self, credentials: Credentials = None) -> str:
pass
| 9 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 3 | 0 | 0 | 8 | 1 | 8 | 8 | 30 | 7 | 23 | 10 | 14 | 0 | 23 | 10 | 14 | 3 | 1 | 2 | 10 |
6,051 |
Apitax/Apitax
|
Apitax_Apitax/apitax/api/test/test_api_controller.py
|
apitax.api.test.test_api_controller.TestApiController
|
class TestApiController(BaseTestCase):
"""ApiController integration test stubs"""
def test_get_driver_api_catalog(self):
"""Test case for get_driver_api_catalog
Retrieve the api catalog
"""
response = self.client.open(
'/apitax/2/drivers/{driver}/api/catalog'.format(driver='driver_example'),
method='GET',
content_type='application/json')
self.assert200(response,
'Response body is : ' + response.data.decode('utf-8'))
def test_get_driver_api_status(self):
"""Test case for get_driver_api_status
Retrieve the status of an api backing a driver
"""
response = self.client.open(
'/apitax/2/drivers/{driver}/api/status'.format(driver='driver_example'),
method='GET')
self.assert200(response,
'Response body is : ' + response.data.decode('utf-8'))
|
class TestApiController(BaseTestCase):
'''ApiController integration test stubs'''
def test_get_driver_api_catalog(self):
'''Test case for get_driver_api_catalog
Retrieve the api catalog
'''
pass
def test_get_driver_api_status(self):
'''Test case for get_driver_api_status
Retrieve the status of an api backing a driver
'''
pass
| 3 | 3 | 11 | 1 | 7 | 3 | 1 | 0.5 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 3 | 25 | 4 | 14 | 5 | 11 | 7 | 7 | 5 | 4 | 1 | 2 | 0 | 2 |
6,052 |
Apitax/Apitax
|
Apitax_Apitax/apitax/api/models/script.py
|
apitax.api.models.script.Script
|
class Script(Model):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, content=None, name=None): # noqa: E501
"""Script - a model defined in Swagger
:param content: The content of this Script. # noqa: E501
:type content: str
:param name: The name of this Script. # noqa: E501
:type name: str
"""
self.swagger_types = {
'content': str,
'name': str
}
self.attribute_map = {
'content': 'content',
'name': 'name'
}
self._content = content
self._name = name
@classmethod
def from_dict(cls, dikt):
"""Returns the dict as a model
:param dikt: A dict.
:type: dict
:return: The Script of this Script. # noqa: E501
:rtype: Script
"""
return util.deserialize_model(dikt, cls)
@property
def content(self):
"""Gets the content of this Script.
:return: The content of this Script.
:rtype: str
"""
return self._content
@content.setter
def content(self, content):
"""Sets the content of this Script.
:param content: The content of this Script.
:type content: str
"""
self._content = content
@property
def name(self):
"""Gets the name of this Script.
:return: The name of this Script.
:rtype: str
"""
return self._name
@name.setter
def name(self, name):
"""Sets the name of this Script.
:param name: The name of this Script.
:type name: str
"""
self._name = name
|
class Script(Model):
'''NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
'''
def __init__(self, content=None, name=None):
'''Script - a model defined in Swagger
:param content: The content of this Script. # noqa: E501
:type content: str
:param name: The name of this Script. # noqa: E501
:type name: str
'''
pass
@classmethod
def from_dict(cls, dikt):
'''Returns the dict as a model
:param dikt: A dict.
:type: dict
:return: The Script of this Script. # noqa: E501
:rtype: Script
'''
pass
@property
def content(self):
'''Gets the content of this Script.
:return: The content of this Script.
:rtype: str
'''
pass
@content.setter
def content(self):
'''Sets the content of this Script.
:param content: The content of this Script.
:type content: str
'''
pass
@property
def name(self):
'''Gets the name of this Script.
:return: The name of this Script.
:rtype: str
'''
pass
@name.setter
def name(self):
'''Sets the name of this Script.
:param name: The name of this Script.
:type name: str
'''
pass
| 12 | 7 | 11 | 2 | 4 | 5 | 1 | 1.19 | 1 | 1 | 0 | 0 | 5 | 4 | 6 | 12 | 79 | 21 | 27 | 16 | 15 | 32 | 16 | 11 | 9 | 1 | 2 | 0 | 6 |
6,053 |
Apitax/Apitax
|
Apitax_Apitax/apitax/api/models/response.py
|
apitax.api.models.response.Response
|
class Response(Model):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, status=None, message=None, body=None, log=None): # noqa: E501
"""Response - a model defined in Swagger
:param status: The status of this Response. # noqa: E501
:type status: int
:param message: The message of this Response. # noqa: E501
:type message: str
:param body: The body of this Response. # noqa: E501
:type body: object
:param log: The log of this Response. # noqa: E501
:type log: str
"""
self.swagger_types = {
'status': int,
'message': str,
'body': object,
'log': str
}
self.attribute_map = {
'status': 'status',
'message': 'message',
'body': 'body',
'log': 'log'
}
self._status = status
self._message = message
self._body = body
self._log = log
@classmethod
def from_dict(cls, dikt):
"""Returns the dict as a model
:param dikt: A dict.
:type: dict
:return: The Response of this Response. # noqa: E501
:rtype: Response
"""
return util.deserialize_model(dikt, cls)
@property
def status(self):
"""Gets the status of this Response.
:return: The status of this Response.
:rtype: int
"""
return self._status
@status.setter
def status(self, status):
"""Sets the status of this Response.
:param status: The status of this Response.
:type status: int
"""
if status is None:
raise ValueError("Invalid value for `status`, must not be `None`") # noqa: E501
self._status = status
@property
def message(self):
"""Gets the message of this Response.
:return: The message of this Response.
:rtype: str
"""
return self._message
@message.setter
def message(self, message):
"""Sets the message of this Response.
:param message: The message of this Response.
:type message: str
"""
self._message = message
@property
def body(self):
"""Gets the body of this Response.
:return: The body of this Response.
:rtype: object
"""
return self._body
@body.setter
def body(self, body):
"""Sets the body of this Response.
:param body: The body of this Response.
:type body: object
"""
if body is None:
raise ValueError("Invalid value for `body`, must not be `None`") # noqa: E501
self._body = body
@property
def log(self):
"""Gets the log of this Response.
:return: The log of this Response.
:rtype: str
"""
return self._log
@log.setter
def log(self, log):
"""Sets the log of this Response.
:param log: The log of this Response.
:type log: str
"""
self._log = log
|
class Response(Model):
'''NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
'''
def __init__(self, status=None, message=None, body=None, log=None):
'''Response - a model defined in Swagger
:param status: The status of this Response. # noqa: E501
:type status: int
:param message: The message of this Response. # noqa: E501
:type message: str
:param body: The body of this Response. # noqa: E501
:type body: object
:param log: The log of this Response. # noqa: E501
:type log: str
'''
pass
@classmethod
def from_dict(cls, dikt):
'''Returns the dict as a model
:param dikt: A dict.
:type: dict
:return: The Response of this Response. # noqa: E501
:rtype: Response
'''
pass
@property
def status(self):
'''Gets the status of this Response.
:return: The status of this Response.
:rtype: int
'''
pass
@status.setter
def status(self):
'''Sets the status of this Response.
:param status: The status of this Response.
:type status: int
'''
pass
@property
def message(self):
'''Gets the message of this Response.
:return: The message of this Response.
:rtype: str
'''
pass
@message.setter
def message(self):
'''Sets the message of this Response.
:param message: The message of this Response.
:type message: str
'''
pass
@property
def body(self):
'''Gets the body of this Response.
:return: The body of this Response.
:rtype: object
'''
pass
@body.setter
def body(self):
'''Sets the body of this Response.
:param body: The body of this Response.
:type body: object
'''
pass
@property
def log(self):
'''Gets the log of this Response.
:return: The log of this Response.
:rtype: str
'''
pass
@log.setter
def log(self):
'''Sets the log of this Response.
:param log: The log of this Response.
:type log: str
'''
pass
| 20 | 11 | 11 | 2 | 4 | 5 | 1 | 1.1 | 1 | 3 | 0 | 0 | 9 | 6 | 10 | 16 | 135 | 35 | 49 | 26 | 29 | 54 | 30 | 17 | 19 | 2 | 2 | 1 | 12 |
6,054 |
Apitax/Apitax
|
Apitax_Apitax/apitax/api/models/execute.py
|
apitax.api.models.execute.Execute
|
class Execute(Model):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, command=None, auth=None): # noqa: E501
"""Execute - a model defined in Swagger
:param command: The command of this Execute. # noqa: E501
:type command: Command
:param auth: The auth of this Execute. # noqa: E501
:type auth: UserAuth
"""
self.swagger_types = {
'command': Command,
'auth': UserAuth
}
self.attribute_map = {
'command': 'command',
'auth': 'auth'
}
self._command = command
self._auth = auth
@classmethod
def from_dict(cls, dikt):
"""Returns the dict as a model
:param dikt: A dict.
:type: dict
:return: The execute of this Execute. # noqa: E501
:rtype: Execute
"""
return util.deserialize_model(dikt, cls)
@property
def command(self):
"""Gets the command of this Execute.
:return: The command of this Execute.
:rtype: Command
"""
return self._command
@command.setter
def command(self, command):
"""Sets the command of this Execute.
:param command: The command of this Execute.
:type command: Command
"""
if command is None:
raise ValueError("Invalid value for `command`, must not be `None`") # noqa: E501
self._command = command
@property
def auth(self):
"""Gets the auth of this Execute.
:return: The auth of this Execute.
:rtype: UserAuth
"""
return self._auth
@auth.setter
def auth(self, auth):
"""Sets the auth of this Execute.
:param auth: The auth of this Execute.
:type auth: UserAuth
"""
self._auth = auth
|
class Execute(Model):
'''NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
'''
def __init__(self, command=None, auth=None):
'''Execute - a model defined in Swagger
:param command: The command of this Execute. # noqa: E501
:type command: Command
:param auth: The auth of this Execute. # noqa: E501
:type auth: UserAuth
'''
pass
@classmethod
def from_dict(cls, dikt):
'''Returns the dict as a model
:param dikt: A dict.
:type: dict
:return: The execute of this Execute. # noqa: E501
:rtype: Execute
'''
pass
@property
def command(self):
'''Gets the command of this Execute.
:return: The command of this Execute.
:rtype: Command
'''
pass
@command.setter
def command(self):
'''Sets the command of this Execute.
:param command: The command of this Execute.
:type command: Command
'''
pass
@property
def auth(self):
'''Gets the auth of this Execute.
:return: The auth of this Execute.
:rtype: UserAuth
'''
pass
@auth.setter
def auth(self):
'''Sets the auth of this Execute.
:param auth: The auth of this Execute.
:type auth: UserAuth
'''
pass
| 12 | 7 | 11 | 2 | 4 | 5 | 1 | 1.14 | 1 | 3 | 2 | 0 | 5 | 4 | 6 | 12 | 81 | 21 | 29 | 16 | 17 | 33 | 18 | 11 | 11 | 2 | 2 | 1 | 7 |
6,055 |
Apitax/Apitax
|
Apitax_Apitax/apitax/api/models/error_response.py
|
apitax.api.models.error_response.ErrorResponse
|
class ErrorResponse(Model):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, status=None, message=None, state=None): # noqa: E501
"""ErrorResponse - a model defined in Swagger
:param status: The status of this ErrorResponse. # noqa: E501
:type status: int
:param message: The message of this ErrorResponse. # noqa: E501
:type message: str
:param state: The state of this ErrorResponse. # noqa: E501
:type state: str
"""
self.swagger_types = {
'status': int,
'message': str,
'state': str
}
self.attribute_map = {
'status': 'status',
'message': 'message',
'state': 'state'
}
self._status = status
self._message = message
self._state = state
@classmethod
def from_dict(cls, dikt):
"""Returns the dict as a model
:param dikt: A dict.
:type: dict
:return: The ErrorResponse of this ErrorResponse. # noqa: E501
:rtype: ErrorResponse
"""
return util.deserialize_model(dikt, cls)
@property
def status(self):
"""Gets the status of this ErrorResponse.
:return: The status of this ErrorResponse.
:rtype: int
"""
return self._status
@status.setter
def status(self, status):
"""Sets the status of this ErrorResponse.
:param status: The status of this ErrorResponse.
:type status: int
"""
if status is None:
raise ValueError("Invalid value for `status`, must not be `None`") # noqa: E501
self._status = status
@property
def message(self):
"""Gets the message of this ErrorResponse.
:return: The message of this ErrorResponse.
:rtype: str
"""
return self._message
@message.setter
def message(self, message):
"""Sets the message of this ErrorResponse.
:param message: The message of this ErrorResponse.
:type message: str
"""
if message is None:
raise ValueError("Invalid value for `message`, must not be `None`") # noqa: E501
self._message = message
@property
def state(self):
"""Gets the state of this ErrorResponse.
:return: The state of this ErrorResponse.
:rtype: str
"""
return self._state
@state.setter
def state(self, state):
"""Sets the state of this ErrorResponse.
:param state: The state of this ErrorResponse.
:type state: str
"""
self._state = state
|
class ErrorResponse(Model):
'''NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
'''
def __init__(self, status=None, message=None, state=None):
'''ErrorResponse - a model defined in Swagger
:param status: The status of this ErrorResponse. # noqa: E501
:type status: int
:param message: The message of this ErrorResponse. # noqa: E501
:type message: str
:param state: The state of this ErrorResponse. # noqa: E501
:type state: str
'''
pass
@classmethod
def from_dict(cls, dikt):
'''Returns the dict as a model
:param dikt: A dict.
:type: dict
:return: The ErrorResponse of this ErrorResponse. # noqa: E501
:rtype: ErrorResponse
'''
pass
@property
def status(self):
'''Gets the status of this ErrorResponse.
:return: The status of this ErrorResponse.
:rtype: int
'''
pass
@status.setter
def status(self):
'''Sets the status of this ErrorResponse.
:param status: The status of this ErrorResponse.
:type status: int
'''
pass
@property
def message(self):
'''Gets the message of this ErrorResponse.
:return: The message of this ErrorResponse.
:rtype: str
'''
pass
@message.setter
def message(self):
'''Sets the message of this ErrorResponse.
:param message: The message of this ErrorResponse.
:type message: str
'''
pass
@property
def state(self):
'''Gets the state of this ErrorResponse.
:return: The state of this ErrorResponse.
:rtype: str
'''
pass
@state.setter
def state(self):
'''Sets the state of this ErrorResponse.
:param state: The state of this ErrorResponse.
:type state: str
'''
pass
| 16 | 9 | 11 | 2 | 4 | 5 | 1 | 1.1 | 1 | 3 | 0 | 0 | 7 | 5 | 8 | 14 | 109 | 28 | 40 | 21 | 24 | 44 | 25 | 14 | 16 | 2 | 2 | 1 | 10 |
6,056 |
Apitax/Apitax
|
Apitax_Apitax/apitax/api/models/command.py
|
apitax.api.models.command.Command
|
class Command(Model):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, parameters=None, options=None, command=None): # noqa: E501
"""Command - a model defined in Swagger
:param parameters: The parameters of this Command. # noqa: E501
:type parameters: object
:param options: The options of this Command. # noqa: E501
:type options: object
:param command: The command of this Command. # noqa: E501
:type command: str
"""
self.swagger_types = {
'parameters': object,
'options': object,
'command': str
}
self.attribute_map = {
'parameters': 'parameters',
'options': 'options',
'command': 'command'
}
self._parameters = parameters
self._options = options
self._command = command
@classmethod
def from_dict(cls, dikt):
"""Returns the dict as a model
:param dikt: A dict.
:type: dict
:return: The Command of this Command. # noqa: E501
:rtype: Command
"""
return util.deserialize_model(dikt, cls)
@property
def parameters(self):
"""Gets the parameters of this Command.
:return: The parameters of this Command.
:rtype: object
"""
return self._parameters
@parameters.setter
def parameters(self, parameters):
"""Sets the parameters of this Command.
:param parameters: The parameters of this Command.
:type parameters: object
"""
self._parameters = parameters
@property
def options(self):
"""Gets the options of this Command.
:return: The options of this Command.
:rtype: object
"""
return self._options
@options.setter
def options(self, options):
"""Sets the options of this Command.
:param options: The options of this Command.
:type options: object
"""
if options is None:
raise ValueError("Invalid value for `options`, must not be `None`") # noqa: E501
self._options = options
@property
def command(self):
"""Gets the command of this Command.
:return: The command of this Command.
:rtype: str
"""
return self._command
@command.setter
def command(self, command):
"""Sets the command of this Command.
:param command: The command of this Command.
:type command: str
"""
if command is None:
raise ValueError("Invalid value for `command`, must not be `None`") # noqa: E501
self._command = command
|
class Command(Model):
'''NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
'''
def __init__(self, parameters=None, options=None, command=None):
'''Command - a model defined in Swagger
:param parameters: The parameters of this Command. # noqa: E501
:type parameters: object
:param options: The options of this Command. # noqa: E501
:type options: object
:param command: The command of this Command. # noqa: E501
:type command: str
'''
pass
@classmethod
def from_dict(cls, dikt):
'''Returns the dict as a model
:param dikt: A dict.
:type: dict
:return: The Command of this Command. # noqa: E501
:rtype: Command
'''
pass
@property
def parameters(self):
'''Gets the parameters of this Command.
:return: The parameters of this Command.
:rtype: object
'''
pass
@parameters.setter
def parameters(self):
'''Sets the parameters of this Command.
:param parameters: The parameters of this Command.
:type parameters: object
'''
pass
@property
def options(self):
'''Gets the options of this Command.
:return: The options of this Command.
:rtype: object
'''
pass
@options.setter
def options(self):
'''Sets the options of this Command.
:param options: The options of this Command.
:type options: object
'''
pass
@property
def command(self):
'''Gets the command of this Command.
:return: The command of this Command.
:rtype: str
'''
pass
@command.setter
def command(self):
'''Sets the command of this Command.
:param command: The command of this Command.
:type command: str
'''
pass
| 16 | 9 | 11 | 2 | 4 | 5 | 1 | 1.1 | 1 | 2 | 0 | 0 | 7 | 5 | 8 | 14 | 109 | 28 | 40 | 21 | 24 | 44 | 25 | 14 | 16 | 2 | 2 | 1 | 10 |
6,057 |
Apitax/Apitax
|
Apitax_Apitax/apitax/api/models/base_model_.py
|
apitax.api.models.base_model_.Model
|
class Model(object):
# swaggerTypes: The key is attribute name and the
# value is attribute type.
swagger_types = {}
# attributeMap: The key is attribute name and the
# value is json key in definition.
attribute_map = {}
@classmethod
def from_dict(cls, dikt):
"""Returns the dict as a model"""
return util.deserialize_model(dikt, cls)
def to_dict(self):
"""Returns the model properties as a dict
:rtype: dict
"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model
:rtype: str
"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
class Model(object):
@classmethod
def from_dict(cls, dikt):
'''Returns the dict as a model'''
pass
def to_dict(self):
'''Returns the model properties as a dict
:rtype: dict
'''
pass
def to_str(self):
'''Returns the string representation of the model
:rtype: str
'''
pass
def __repr__(self):
'''For `print` and `pprint`'''
pass
def __eq__(self, other):
'''Returns true if both objects are equal'''
pass
def __ne__(self, other):
'''Returns true if both objects are not equal'''
pass
| 8 | 6 | 7 | 1 | 5 | 2 | 2 | 0.41 | 1 | 3 | 0 | 15 | 5 | 0 | 6 | 6 | 59 | 11 | 34 | 13 | 26 | 14 | 23 | 12 | 16 | 5 | 1 | 2 | 10 |
6,058 |
Apitax/Apitax
|
Apitax_Apitax/apitax/api/models/auth_response.py
|
apitax.api.models.auth_response.AuthResponse
|
class AuthResponse(Model):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, status=None, message=None, access_token=None, refresh_token=None, auth=None): # noqa: E501
"""AuthResponse - a model defined in Swagger
:param status: The status of this AuthResponse. # noqa: E501
:type status: int
:param message: The message of this AuthResponse. # noqa: E501
:type message: str
:param access_token: The access_token of this AuthResponse. # noqa: E501
:type access_token: str
:param refresh_token: The refresh_token of this AuthResponse. # noqa: E501
:type refresh_token: str
:param auth: The auth of this AuthResponse. # noqa: E501
:type auth: UserAuth
"""
self.swagger_types = {
'status': int,
'message': str,
'access_token': str,
'refresh_token': str,
'auth': UserAuth
}
self.attribute_map = {
'status': 'status',
'message': 'message',
'access_token': 'access_token',
'refresh_token': 'refresh_token',
'auth': 'auth'
}
self._status = status
self._message = message
self._access_token = access_token
self._refresh_token = refresh_token
self._auth = auth
@classmethod
def from_dict(cls, dikt):
"""Returns the dict as a model
:param dikt: A dict.
:type: dict
:return: The AuthResponse of this AuthResponse. # noqa: E501
:rtype: AuthResponse
"""
return util.deserialize_model(dikt, cls)
@property
def status(self):
"""Gets the status of this AuthResponse.
:return: The status of this AuthResponse.
:rtype: int
"""
return self._status
@status.setter
def status(self, status):
"""Sets the status of this AuthResponse.
:param status: The status of this AuthResponse.
:type status: int
"""
if status is None:
raise ValueError("Invalid value for `status`, must not be `None`") # noqa: E501
self._status = status
@property
def message(self):
"""Gets the message of this AuthResponse.
:return: The message of this AuthResponse.
:rtype: str
"""
return self._message
@message.setter
def message(self, message):
"""Sets the message of this AuthResponse.
:param message: The message of this AuthResponse.
:type message: str
"""
if message is None:
raise ValueError("Invalid value for `message`, must not be `None`") # noqa: E501
self._message = message
@property
def access_token(self):
"""Gets the access_token of this AuthResponse.
:return: The access_token of this AuthResponse.
:rtype: str
"""
return self._access_token
@access_token.setter
def access_token(self, access_token):
"""Sets the access_token of this AuthResponse.
:param access_token: The access_token of this AuthResponse.
:type access_token: str
"""
self._access_token = access_token
@property
def refresh_token(self):
"""Gets the refresh_token of this AuthResponse.
:return: The refresh_token of this AuthResponse.
:rtype: str
"""
return self._refresh_token
@refresh_token.setter
def refresh_token(self, refresh_token):
"""Sets the refresh_token of this AuthResponse.
:param refresh_token: The refresh_token of this AuthResponse.
:type refresh_token: str
"""
self._refresh_token = refresh_token
@property
def auth(self):
"""Gets the auth of this AuthResponse.
:return: The auth of this AuthResponse.
:rtype: UserAuth
"""
return self._auth
@auth.setter
def auth(self, auth):
"""Sets the auth of this AuthResponse.
:param auth: The auth of this AuthResponse.
:type auth: UserAuth
"""
self._auth = auth
|
class AuthResponse(Model):
'''NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
'''
def __init__(self, status=None, message=None, access_token=None, refresh_token=None, auth=None):
'''AuthResponse - a model defined in Swagger
:param status: The status of this AuthResponse. # noqa: E501
:type status: int
:param message: The message of this AuthResponse. # noqa: E501
:type message: str
:param access_token: The access_token of this AuthResponse. # noqa: E501
:type access_token: str
:param refresh_token: The refresh_token of this AuthResponse. # noqa: E501
:type refresh_token: str
:param auth: The auth of this AuthResponse. # noqa: E501
:type auth: UserAuth
'''
pass
@classmethod
def from_dict(cls, dikt):
'''Returns the dict as a model
:param dikt: A dict.
:type: dict
:return: The AuthResponse of this AuthResponse. # noqa: E501
:rtype: AuthResponse
'''
pass
@property
def status(self):
'''Gets the status of this AuthResponse.
:return: The status of this AuthResponse.
:rtype: int
'''
pass
@status.setter
def status(self):
'''Sets the status of this AuthResponse.
:param status: The status of this AuthResponse.
:type status: int
'''
pass
@property
def message(self):
'''Gets the message of this AuthResponse.
:return: The message of this AuthResponse.
:rtype: str
'''
pass
@message.setter
def message(self):
'''Sets the message of this AuthResponse.
:param message: The message of this AuthResponse.
:type message: str
'''
pass
@property
def access_token(self):
'''Gets the access_token of this AuthResponse.
:return: The access_token of this AuthResponse.
:rtype: str
'''
pass
@access_token.setter
def access_token(self):
'''Sets the access_token of this AuthResponse.
:param access_token: The access_token of this AuthResponse.
:type access_token: str
'''
pass
@property
def refresh_token(self):
'''Gets the refresh_token of this AuthResponse.
:return: The refresh_token of this AuthResponse.
:rtype: str
'''
pass
@refresh_token.setter
def refresh_token(self):
'''Sets the refresh_token of this AuthResponse.
:param refresh_token: The refresh_token of this AuthResponse.
:type refresh_token: str
'''
pass
@property
def auth(self):
'''Gets the auth of this AuthResponse.
:return: The auth of this AuthResponse.
:rtype: UserAuth
'''
pass
@auth.setter
def auth(self):
'''Sets the auth of this AuthResponse.
:param auth: The auth of this AuthResponse.
:type auth: UserAuth
'''
pass
| 24 | 13 | 11 | 2 | 4 | 5 | 1 | 1.1 | 1 | 4 | 1 | 0 | 11 | 7 | 12 | 18 | 161 | 42 | 58 | 31 | 34 | 64 | 35 | 20 | 22 | 2 | 2 | 1 | 14 |
6,059 |
Apitax/Apitax
|
Apitax_Apitax/apitax/api/encoder.py
|
apitax.api.encoder.JSONEncoder
|
class JSONEncoder(FlaskJSONEncoder):
include_nulls = False
def default(self, o):
if isinstance(o, Model):
dikt = {}
for attr, _ in six.iteritems(o.swagger_types):
value = getattr(o, attr)
if value is None and not self.include_nulls:
continue
attr = o.attribute_map[attr]
dikt[attr] = value
return dikt
return FlaskJSONEncoder.default(self, o)
|
class JSONEncoder(FlaskJSONEncoder):
def default(self, o):
pass
| 2 | 0 | 11 | 0 | 11 | 0 | 4 | 0 | 1 | 1 | 1 | 0 | 1 | 0 | 1 | 1 | 14 | 1 | 13 | 6 | 11 | 0 | 13 | 6 | 11 | 4 | 1 | 3 | 4 |
6,060 |
Apitax/Apitax
|
Apitax_Apitax/apitax/api/models/script_delete.py
|
apitax.api.models.script_delete.ScriptDelete
|
class ScriptDelete(Model):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, script=None): # noqa: E501
"""ScriptDelete - a model defined in Swagger
:param script: The script of this ScriptDelete. # noqa: E501
:type script: Script
"""
self.swagger_types = {
'script': Script
}
self.attribute_map = {
'script': 'script'
}
self._script = script
@classmethod
def from_dict(cls, dikt):
"""Returns the dict as a model
:param dikt: A dict.
:type: dict
:return: The script_delete of this ScriptDelete. # noqa: E501
:rtype: ScriptDelete
"""
return util.deserialize_model(dikt, cls)
@property
def script(self):
"""Gets the script of this ScriptDelete.
:return: The script of this ScriptDelete.
:rtype: Script
"""
return self._script
@script.setter
def script(self, script):
"""Sets the script of this ScriptDelete.
:param script: The script of this ScriptDelete.
:type script: Script
"""
if script is None:
raise ValueError("Invalid value for `script`, must not be `None`") # noqa: E501
self._script = script
|
class ScriptDelete(Model):
'''NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
'''
def __init__(self, script=None):
'''ScriptDelete - a model defined in Swagger
:param script: The script of this ScriptDelete. # noqa: E501
:type script: Script
'''
pass
@classmethod
def from_dict(cls, dikt):
'''Returns the dict as a model
:param dikt: A dict.
:type: dict
:return: The script_delete of this ScriptDelete. # noqa: E501
:rtype: ScriptDelete
'''
pass
@property
def script(self):
'''Gets the script of this ScriptDelete.
:return: The script of this ScriptDelete.
:rtype: Script
'''
pass
@script.setter
def script(self):
'''Sets the script of this ScriptDelete.
:param script: The script of this ScriptDelete.
:type script: Script
'''
pass
| 8 | 5 | 11 | 2 | 4 | 5 | 1 | 1.15 | 1 | 2 | 1 | 0 | 3 | 3 | 4 | 10 | 55 | 14 | 20 | 11 | 12 | 23 | 13 | 8 | 8 | 2 | 2 | 1 | 5 |
6,061 |
Apitax/Apitax
|
Apitax_Apitax/app/Project.py
|
app.Project.Project
|
class Project(BaseProject):
def setup(self):
from apitaxcore.models.State import State
State.paths['root'] = 'D:/Programming/Projects/Apitax/Apitax' # just /app for docker
State.paths['config'] = State.paths['root'] + '/app/config.txt'
State.paths['log'] = None
def loadDrivers(self):
from apitaxcore.drivers.Drivers import Drivers
from apitaxdrivers.Github import GithubDriver
Drivers.add("github", GithubDriver())
|
class Project(BaseProject):
def setup(self):
pass
def loadDrivers(self):
pass
| 3 | 0 | 5 | 0 | 5 | 1 | 1 | 0.1 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 6 | 11 | 1 | 10 | 6 | 4 | 1 | 10 | 6 | 4 | 1 | 1 | 0 | 2 |
6,062 |
Apitax/Apitax
|
Apitax_Apitax/apitax/flow/Setup.py
|
apitax.flow.Setup.Setup
|
class Setup:
def __init__(self, passedArgs: list = []):
if len(passedArgs) == 0:
self.args = sys.argv[1:]
else:
self.args = passedArgs
self.usage = 'cli'
self.debug = False
self.sensitive = False
self.reloader = False
self.watcher = False
self.username = ''
self.password = ''
self.command = ''
self.script = ''
self.build = True
self.doLog = True
if State.paths['log'] != "":
self.logPath = State.paths['log']
else:
self.logPath = '/logs/apitax.log'
self.logColorize = True
self.logPrefixes = True
self.logHumanReadable = False
# print(getRootPath('/config.txt'))
if State.paths['config'] != "":
configFile = State.paths['config']
else:
configFile = getRoot('/config.txt')
self.config = ConfigConsumer.read()
self.config.path = str(Path(os.path.dirname(os.path.abspath(inspect.stack()[0][1]))).resolve())
# print(getRootPath())
if self.config.has('default-mode'):
self.usage = self.config.get('default-mode')
if self.config.has('log'):
self.doLog = self.config.get('log')
if self.config.has('log-file'):
self.logPath = self.config.get('log-file')
if self.config.has('log-colorize'):
self.logColorize = self.config.get('log-colorize')
if self.config.has('log-human-readable'):
self.logHumanReadable = self.config.get('log-human-readable')
if self.config.has('log-prefixes'):
self.logPrefixes = self.config.get('log-prefixes')
if self.logPath[:1] != '/':
self.logPath = '/' + self.logPath
# self.logPath = getRootPath(self.logPath)
if self.config.has('log-buffered') and self.config.get('log-buffered'):
logDriver = BufferedLog()
else:
logDriver = StandardLog()
self.log = Log(logDriver, logFile=self.logPath, doLog=self.doLog, logColorize=self.logColorize,
logPrefixes=self.logPrefixes,
logHumanReadable=self.logHumanReadable)
self.log.log('')
self.log.log('')
self.log.log(">>> Apitax - Combining the power of Commandtax and Scriptax")
self.log.log('')
self.log.log('')
if '--cli' in self.args:
self.usage = 'cli'
elif '--api' in self.args:
self.usage = 'api'
elif '--grammar-test' in self.args:
self.usage = 'grammar-test'
elif '--feature-test' in self.args:
self.usage = 'feature-test'
if '--debug' in self.args:
self.debug = True
if '--sensitive' in self.args:
self.sensitive = True
if '--reloader' in self.args:
self.reloader = True
if '-u' in self.args:
self.username = self.args[self.args.index('-u') + 1]
if '-p' in self.args:
self.password = click.prompt('Enter Your Password', hide_input=True)
if '-s' in self.args:
self.script = self.args[self.args.index('-s') + 1]
if '-r' in self.args:
self.command = self.args[self.args.index('-r') + 1]
elif self.script == '' and self.usage == 1:
self.command = click.prompt('R')
# This is to turn the '-s' flag into a command behind the scenes
if self.script != '':
self.command = 'script ' + self.script
self.options = Options(debug=self.debug, sensitive=self.sensitive)
self.loggingSettings = self.log.getLoggerSettings()
self.log.log('>> Runtime Settings:')
self.log.log(' * Paths')
self.log.log(' * Root: ' + State.paths['root'])
self.log.log(' * Config: ' + configFile)
self.log.log(' * Log: ' + str(self.loggingSettings.get('path')))
self.log.log(' * Apitax: ' + State.paths['apitax'])
self.log.log(' * Debug: ' + str(self.debug))
self.log.log(' * Sensitive: ' + str(self.sensitive))
self.log.log(' * Operating out of: ' + str(self.config.path))
self.log.log(' * Logging: ' + str(self.loggingSettings.get('doLog')))
if self.loggingSettings.get('doLog'):
self.log.log(' * Colorize CLI: ' + str(self.loggingSettings.get('colorize')))
self.log.log('')
self.log.log('')
if self.options.debug:
self.log.log('>> Setting up AppState')
self.log.log('')
self.log.log('')
# Setup App State
State.config = self.config
State.options = self.options
State.log = self.log
if State.paths['log'] == "":
State.paths['log'] = self.logPath
if State.paths['root'] == "":
State.paths['root'] = getRoot()
if State.paths['apitax'] == "":
State.paths['apitax'] = str(Path(os.path.dirname(os.path.abspath(inspect.stack()[0][1]))).resolve())
if State.paths['config'] == "":
State.paths['config'] = configFile
if (self.options.debug):
self.log.log('>> Loading Drivers')
self.log.log('')
self.log.getLoggerDriver().outputLog()
def load(self):
drivers = []
if self.config.has('drivers-use'):
drivers += self.config.getAsList('drivers-use')
for driver in drivers:
LoadedDrivers.load(driver)
if self.options.debug:
self.log.log('>> Finished Loading Drivers')
self.log.log('')
self.log.log('')
self.log.getLoggerDriver().outputLog()
|
class Setup:
def __init__(self, passedArgs: list = []):
pass
def load(self):
pass
| 3 | 0 | 91 | 25 | 64 | 3 | 18 | 0.04 | 0 | 3 | 0 | 0 | 2 | 20 | 2 | 2 | 184 | 51 | 128 | 27 | 125 | 5 | 118 | 27 | 115 | 32 | 0 | 1 | 36 |
6,063 |
Apitax/Apitax
|
Apitax_Apitax/apitax/flow/Project.py
|
apitax.flow.Project.Project
|
class Project:
def isDev(self):
return True
def isDebug(self):
return True
def setup(self):
from apitaxcore.models.State import State
#State.paths['root'] = 'D:/Programming/Projects/Apitax/Apitax' # just /app for docker
#State.paths['config'] = State.paths['root'] + '/config.txt'
#State.paths['log'] = None
def loadDrivers(self):
from apitaxcore.drivers.Drivers import Drivers
|
class Project:
def isDev(self):
pass
def isDebug(self):
pass
def setup(self):
pass
def loadDrivers(self):
pass
| 5 | 0 | 2 | 0 | 2 | 0 | 1 | 0.33 | 0 | 0 | 0 | 1 | 4 | 0 | 4 | 4 | 15 | 3 | 9 | 7 | 2 | 3 | 9 | 7 | 2 | 1 | 0 | 0 | 4 |
6,064 |
Apitax/Apitax
|
Apitax_Apitax/apitax/drivers/builtin/Apitax.py
|
apitax.drivers.builtin.Apitax.Apitax
|
class Apitax(Api):
def getDriverName(self) -> str:
return "Apitax"
def getDriverDescription(self) -> str:
return "Provides out of the box commandtax support for the Apitax API"
def getDriverHelpEndpoint(self) -> str:
return "coming soon"
def getDriverTips(self) -> str:
return "coming soon"
def isDriverCommandable(self) -> bool:
return True
def handleDriverCommand(self, command: Command) -> ApitaxResponse:
return super().handleDriverCommand(command)
|
class Apitax(Api):
def getDriverName(self) -> str:
pass
def getDriverDescription(self) -> str:
pass
def getDriverHelpEndpoint(self) -> str:
pass
def getDriverTips(self) -> str:
pass
def isDriverCommandable(self) -> bool:
pass
def handleDriverCommand(self, command: Command) -> ApitaxResponse:
pass
| 7 | 0 | 2 | 0 | 2 | 0 | 1 | 0.08 | 1 | 3 | 0 | 0 | 6 | 0 | 6 | 6 | 18 | 5 | 13 | 7 | 6 | 1 | 13 | 7 | 6 | 1 | 1 | 0 | 6 |
6,065 |
Apitax/Apitax
|
Apitax_Apitax/apitax/catalog/EndpointCatalog.py
|
apitax.catalog.EndpointCatalog.EndpointCatalog
|
class EndpointCatalog(Catalog):
def __init__(self):
super().__init__("endpoints")
def add(self, name, label, value, summary='', help='', driver='', examples=[]):
item = {name: {'label': label, 'value': value, 'summary': summary, 'help': help, 'driver': driver,
'examples': examples}}
super().add(item)
|
class EndpointCatalog(Catalog):
def __init__(self):
pass
def add(self, name, label, value, summary='', help='', driver='', examples=[]):
pass
| 3 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 2 | 0 | 2 | 2 | 9 | 2 | 7 | 4 | 4 | 0 | 6 | 4 | 3 | 1 | 1 | 0 | 2 |
6,066 |
Apitax/Apitax
|
Apitax_Apitax/apitax/authentication/ApitaxAuthentication.py
|
apitax.authentication.ApitaxAuthentication.ApitaxAuthentication
|
class ApitaxAuthentication:
@staticmethod
def getBasicHttp(credentials: Credentials):
temp = credentials.username + ':' + credentials.password
return {'Authorization': 'Basic ' + base64.b64encode(temp.encode('utf-8'))}
@staticmethod
def getBearerHttp(credentials: Credentials):
return {'Authorization': 'Bearer ' + credentials.token}
@staticmethod
def login(credentials):
driver: Driver = LoadedDrivers.getAuthDriver()
role = None
if not driver.isDriverAuthenticatable():
return None
if driver.isApitaxAuthBasedOnApiAuth():
# apiDriver = LoadedDrivers.getPrimaryDriver()
apiDriver: Driver = driver
if 'driver' in credentials.extra:
apiDriver = LoadedDrivers.getDriver(credentials.extra['driver'])
result: ApitaxResponse = apiDriver.authenticateApi(credentials)
if not result.isStatusSuccess():
return None
role = driver.authenticateApitax(result.getResponseBody()['credentials'])
if apiDriver.isApiTokenable():
credentials.token = apiDriver.getApiToken(result)
else:
role = driver.authenticateApitax(credentials)
if not role:
return None
return {"role": role, "credentials": credentials}
|
class ApitaxAuthentication:
@staticmethod
def getBasicHttp(credentials: Credentials):
pass
@staticmethod
def getBearerHttp(credentials: Credentials):
pass
@staticmethod
def login(credentials):
pass
| 7 | 0 | 10 | 1 | 8 | 0 | 3 | 0.03 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 3 | 37 | 7 | 29 | 12 | 22 | 1 | 25 | 9 | 21 | 7 | 0 | 2 | 9 |
6,067 |
Apitax/Apitax
|
Apitax_Apitax/apitax/api/test/test_scriptax_controller.py
|
apitax.api.test.test_scriptax_controller.TestScriptaxController
|
class TestScriptaxController(BaseTestCase):
"""ScriptaxController integration test stubs"""
def test_create_driver_script(self):
"""Test case for create_driver_script
Create a new script
"""
script_create = ScriptCreate()
response = self.client.open(
'/apitax/2/drivers/{driver}/scriptax/scripts'.format(driver='driver_example'),
method='POST',
data=json.dumps(script_create),
content_type='application/json')
self.assert200(response,
'Response body is : ' + response.data.decode('utf-8'))
def test_delete_driver_script(self):
"""Test case for delete_driver_script
Delete a script
"""
script_delete = ScriptDelete()
response = self.client.open(
'/apitax/2/drivers/{driver}/scriptax/scripts'.format(driver='driver_example'),
method='DELETE',
data=json.dumps(script_delete),
content_type='application/json')
self.assert200(response,
'Response body is : ' + response.data.decode('utf-8'))
def test_get_driver_script(self):
"""Test case for get_driver_script
Retrieve the contents of a script
"""
query_string = [('script', 'script_example')]
response = self.client.open(
'/apitax/2/drivers/{driver}/scriptax/scripts'.format(driver='driver_example'),
method='GET',
content_type='application/json',
query_string=query_string)
self.assert200(response,
'Response body is : ' + response.data.decode('utf-8'))
def test_get_driver_script_catalog(self):
"""Test case for get_driver_script_catalog
Retrieve the script catalog
"""
response = self.client.open(
'/apitax/2/drivers/{driver}/scriptax/catalog'.format(driver='driver_example'),
method='GET')
self.assert200(response,
'Response body is : ' + response.data.decode('utf-8'))
def test_rename_driver_script(self):
"""Test case for rename_driver_script
Rename a script
"""
script_rename = ScriptRename()
response = self.client.open(
'/apitax/2/drivers/{driver}/scriptax/scripts'.format(driver='driver_example'),
method='PATCH',
data=json.dumps(script_rename),
content_type='application/json')
self.assert200(response,
'Response body is : ' + response.data.decode('utf-8'))
def test_save_driver_script(self):
"""Test case for save_driver_script
Save a script
"""
script_save = ScriptSave()
response = self.client.open(
'/apitax/2/drivers/{driver}/scriptax/scripts'.format(driver='driver_example'),
method='PUT',
data=json.dumps(script_save),
content_type='application/json')
self.assert200(response,
'Response body is : ' + response.data.decode('utf-8'))
|
class TestScriptaxController(BaseTestCase):
'''ScriptaxController integration test stubs'''
def test_create_driver_script(self):
'''Test case for create_driver_script
Create a new script
'''
pass
def test_delete_driver_script(self):
'''Test case for delete_driver_script
Delete a script
'''
pass
def test_get_driver_script(self):
'''Test case for get_driver_script
Retrieve the contents of a script
'''
pass
def test_get_driver_script_catalog(self):
'''Test case for get_driver_script_catalog
Retrieve the script catalog
'''
pass
def test_rename_driver_script(self):
'''Test case for rename_driver_script
Rename a script
'''
pass
def test_save_driver_script(self):
'''Test case for save_driver_script
Save a script
'''
pass
| 7 | 7 | 13 | 1 | 9 | 3 | 1 | 0.37 | 1 | 4 | 4 | 0 | 6 | 0 | 6 | 7 | 83 | 12 | 52 | 18 | 45 | 19 | 24 | 18 | 17 | 1 | 2 | 0 | 6 |
6,068 |
Apitax/Apitax
|
Apitax_Apitax/apitax/api/test/test_drivers_controller.py
|
apitax.api.test.test_drivers_controller.TestDriversController
|
class TestDriversController(BaseTestCase):
"""DriversController integration test stubs"""
def test_get_driver_blacklist(self):
"""Test case for get_driver_blacklist
Retrieve the blacklist in the driver
"""
response = self.client.open(
'/apitax/2/drivers/{driver}/blacklist'.format(driver='driver_example'),
method='GET')
self.assert200(response,
'Response body is : ' + response.data.decode('utf-8'))
def test_get_driver_config(self):
"""Test case for get_driver_config
Retrieve the config of a loaded driver
"""
response = self.client.open(
'/apitax/2/drivers/{driver}/config'.format(driver='driver_example'),
method='GET')
self.assert200(response,
'Response body is : ' + response.data.decode('utf-8'))
def test_get_driver_list(self):
"""Test case for get_driver_list
Retrieve the catalog of drivers
"""
response = self.client.open(
'/apitax/2/drivers',
method='GET')
self.assert200(response,
'Response body is : ' + response.data.decode('utf-8'))
def test_get_driver_status(self):
"""Test case for get_driver_status
Retrieve the status of a loaded driver
"""
response = self.client.open(
'/apitax/2/drivers/{driver}/status'.format(driver='driver_example'),
method='GET')
self.assert200(response,
'Response body is : ' + response.data.decode('utf-8'))
def test_get_driver_whitelist(self):
"""Test case for get_driver_whitelist
Retrieve the whitelist in the driver
"""
response = self.client.open(
'/apitax/2/drivers/{driver}/whitelist'.format(driver='driver_example'),
method='GET')
self.assert200(response,
'Response body is : ' + response.data.decode('utf-8'))
|
class TestDriversController(BaseTestCase):
'''DriversController integration test stubs'''
def test_get_driver_blacklist(self):
'''Test case for get_driver_blacklist
Retrieve the blacklist in the driver
'''
pass
def test_get_driver_config(self):
'''Test case for get_driver_config
Retrieve the config of a loaded driver
'''
pass
def test_get_driver_list(self):
'''Test case for get_driver_list
Retrieve the catalog of drivers
'''
pass
def test_get_driver_status(self):
'''Test case for get_driver_status
Retrieve the status of a loaded driver
'''
pass
def test_get_driver_whitelist(self):
'''Test case for get_driver_whitelist
Retrieve the whitelist in the driver
'''
pass
| 6 | 6 | 10 | 1 | 6 | 3 | 1 | 0.52 | 1 | 0 | 0 | 0 | 5 | 0 | 5 | 6 | 57 | 10 | 31 | 11 | 25 | 16 | 16 | 11 | 10 | 1 | 2 | 0 | 5 |
6,069 |
Apitax/Apitax
|
Apitax_Apitax/apitax/api/test/test_commandtax_controller.py
|
apitax.api.test.test_commandtax_controller.TestCommandtaxController
|
class TestCommandtaxController(BaseTestCase):
"""CommandtaxController integration test stubs"""
def test_command(self):
"""Test case for command
Execute a Command
"""
execute = Execute()
response = self.client.open(
'/apitax/2/drivers/{driver}/commandtax/command'.format(driver='driver_example'),
method='POST',
data=json.dumps(execute),
content_type='application/json')
self.assert200(response,
'Response body is : ' + response.data.decode('utf-8'))
|
class TestCommandtaxController(BaseTestCase):
'''CommandtaxController integration test stubs'''
def test_command(self):
'''Test case for command
Execute a Command
'''
pass
| 2 | 2 | 13 | 1 | 9 | 3 | 1 | 0.4 | 1 | 1 | 1 | 0 | 1 | 0 | 1 | 2 | 16 | 2 | 10 | 4 | 8 | 4 | 5 | 4 | 3 | 1 | 2 | 0 | 1 |
6,070 |
Apitax/Apitax
|
Apitax_Apitax/apitax/api/test/test_apitax_controller.py
|
apitax.api.test.test_apitax_controller.TestApitaxController
|
class TestApitaxController(BaseTestCase):
"""ApitaxController integration test stubs"""
def test_authenticate(self):
"""Test case for authenticate
Authenticate
"""
user = UserAuth()
response = self.client.open(
'/apitax/2/apitax/auth',
method='POST',
data=json.dumps(user),
content_type='application/json')
self.assert200(response,
'Response body is : ' + response.data.decode('utf-8'))
def test_create_user(self):
"""Test case for create_user
Create a new user
"""
user_create = UserCreate()
response = self.client.open(
'/apitax/2/drivers/{driver}/apitax/users/{user}'.format(user='user_example', driver='driver_example'),
method='POST',
data=json.dumps(user_create),
content_type='application/json')
self.assert200(response,
'Response body is : ' + response.data.decode('utf-8'))
def test_delete_user(self):
"""Test case for delete_user
Delete a user
"""
user_delete = UserDelete()
response = self.client.open(
'/apitax/2/drivers/{driver}/apitax/users/{user}'.format(user='user_example', driver='driver_example'),
method='DELETE',
data=json.dumps(user_delete),
content_type='application/json')
self.assert200(response,
'Response body is : ' + response.data.decode('utf-8'))
def test_get_config(self):
"""Test case for get_config
Retrieve the system config
"""
response = self.client.open(
'/apitax/2/apitax/config',
method='GET')
self.assert200(response,
'Response body is : ' + response.data.decode('utf-8'))
def test_get_log(self):
"""Test case for get_log
Retrieve the logs
"""
response = self.client.open(
'/apitax/2/apitax/logs/{log}'.format(log='log_example'),
method='GET')
self.assert200(response,
'Response body is : ' + response.data.decode('utf-8'))
def test_get_user(self):
"""Test case for get_user
Retrieve a user
"""
response = self.client.open(
'/apitax/2/drivers/{driver}/apitax/users/{user}'.format(user='user_example', driver='driver_example'),
method='GET',
content_type='application/json')
self.assert200(response,
'Response body is : ' + response.data.decode('utf-8'))
def test_get_user_list(self):
"""Test case for get_user_list
Retrieve a list of users
"""
response = self.client.open(
'/apitax/2/drivers/{driver}/apitax/users'.format(driver='driver_example'),
method='GET',
content_type='application/json')
self.assert200(response,
'Response body is : ' + response.data.decode('utf-8'))
def test_refresh_token(self):
"""Test case for refresh_token
Refreshes login token using refresh token
"""
response = self.client.open(
'/apitax/2/apitax/auth/refresh',
method='POST')
self.assert200(response,
'Response body is : ' + response.data.decode('utf-8'))
def test_save_user(self):
"""Test case for save_user
Save a user
"""
user_save = UserSave()
response = self.client.open(
'/apitax/2/drivers/{driver}/apitax/users/{user}'.format(user='user_example', driver='driver_example'),
method='PUT',
data=json.dumps(user_save),
content_type='application/json')
self.assert200(response,
'Response body is : ' + response.data.decode('utf-8'))
def test_system_status(self):
"""Test case for system_status
Retrieve the system status
"""
response = self.client.open(
'/apitax/2/apitax/status',
method='GET')
self.assert200(response,
'Response body is : ' + response.data.decode('utf-8'))
|
class TestApitaxController(BaseTestCase):
'''ApitaxController integration test stubs'''
def test_authenticate(self):
'''Test case for authenticate
Authenticate
'''
pass
def test_create_user(self):
'''Test case for create_user
Create a new user
'''
pass
def test_delete_user(self):
'''Test case for delete_user
Delete a user
'''
pass
def test_get_config(self):
'''Test case for get_config
Retrieve the system config
'''
pass
def test_get_log(self):
'''Test case for get_log
Retrieve the logs
'''
pass
def test_get_user(self):
'''Test case for get_user
Retrieve a user
'''
pass
def test_get_user_list(self):
'''Test case for get_user_list
Retrieve a list of users
'''
pass
def test_refresh_token(self):
'''Test case for refresh_token
Refreshes login token using refresh token
'''
pass
def test_save_user(self):
'''Test case for save_user
Save a user
'''
pass
def test_system_status(self):
'''Test case for system_status
Retrieve the system status
'''
pass
| 11 | 11 | 11 | 1 | 7 | 3 | 1 | 0.41 | 1 | 4 | 4 | 0 | 10 | 0 | 10 | 11 | 126 | 20 | 75 | 25 | 64 | 31 | 35 | 25 | 24 | 1 | 2 | 0 | 10 |
6,071 |
Apitax/Apitax
|
Apitax_Apitax/apitax/api/test/__init__.py
|
apitax.api.test.BaseTestCase
|
class BaseTestCase(TestCase):
def create_app(self):
logging.getLogger('connexion.operation').setLevel('ERROR')
app = connexion.App(__name__, specification_dir='../swagger/')
app.app.json_encoder = JSONEncoder
app.add_api('swagger.yaml')
return app.app
|
class BaseTestCase(TestCase):
def create_app(self):
pass
| 2 | 0 | 6 | 0 | 6 | 0 | 1 | 0 | 1 | 1 | 1 | 5 | 1 | 0 | 1 | 1 | 8 | 1 | 7 | 3 | 5 | 0 | 7 | 3 | 5 | 1 | 1 | 0 | 1 |
6,072 |
Apitax/Apitax
|
Apitax_Apitax/apitax/api/models/script_create.py
|
apitax.api.models.script_create.ScriptCreate
|
class ScriptCreate(Model):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, script=None): # noqa: E501
"""ScriptCreate - a model defined in Swagger
:param script: The script of this ScriptCreate. # noqa: E501
:type script: Script
"""
self.swagger_types = {
'script': Script
}
self.attribute_map = {
'script': 'script'
}
self._script = script
@classmethod
def from_dict(cls, dikt):
"""Returns the dict as a model
:param dikt: A dict.
:type: dict
:return: The script_create of this ScriptCreate. # noqa: E501
:rtype: ScriptCreate
"""
return util.deserialize_model(dikt, cls)
@property
def script(self):
"""Gets the script of this ScriptCreate.
:return: The script of this ScriptCreate.
:rtype: Script
"""
return self._script
@script.setter
def script(self, script):
"""Sets the script of this ScriptCreate.
:param script: The script of this ScriptCreate.
:type script: Script
"""
if script is None:
raise ValueError("Invalid value for `script`, must not be `None`") # noqa: E501
self._script = script
|
class ScriptCreate(Model):
'''NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
'''
def __init__(self, script=None):
'''ScriptCreate - a model defined in Swagger
:param script: The script of this ScriptCreate. # noqa: E501
:type script: Script
'''
pass
@classmethod
def from_dict(cls, dikt):
'''Returns the dict as a model
:param dikt: A dict.
:type: dict
:return: The script_create of this ScriptCreate. # noqa: E501
:rtype: ScriptCreate
'''
pass
@property
def script(self):
'''Gets the script of this ScriptCreate.
:return: The script of this ScriptCreate.
:rtype: Script
'''
pass
@script.setter
def script(self):
'''Sets the script of this ScriptCreate.
:param script: The script of this ScriptCreate.
:type script: Script
'''
pass
| 8 | 5 | 11 | 2 | 4 | 5 | 1 | 1.15 | 1 | 2 | 1 | 0 | 3 | 3 | 4 | 10 | 55 | 14 | 20 | 11 | 12 | 23 | 13 | 8 | 8 | 2 | 2 | 1 | 5 |
6,073 |
Aplopio/django_rip
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Aplopio_django_rip/tests/integration_tests/test_view_resource.py
|
tests.integration_tests.test_view_resource.TestViewResource
|
class TestViewResource(unittest.TestCase):
def test_view_returns_value(self):
resource = DummyResource()
response = resource.read(request_factory.get_request(user=object()))
assert_that(response.data, equal_to({'name': 'dummy'}))
@patch.object(DummyViewActions, 'view')
def test_when_view_returns_bad_schema(self, mocked_view):
mocked_view.return_value = {'foo': 'bar'}
resource = DummyResource()
with (self.assertRaises(AttributeError)):
resource.read(request_factory.get_request(user=object()))
@patch.object(DummyAuthorization, 'authorize_read')
def test_when_authorization_fails(self, mocked_authorize_read):
mocked_authorize_read.return_value = Response(is_success=False,
reason=error_types.ActionForbidden,
data={'foo': 'bar'})
response = DummyResource().read(request=request_factory.get_request(user=object()))
assert_that(response.is_success, equal_to(False))
assert_that(response.reason, equal_to(error_types.ActionForbidden))
assert_that(response.data, equal_to({'foo': 'bar'}))
@patch.object(DummyAuthentication, 'authenticate')
def test_when_authentication_fails(self, mocked_authenticate):
mocked_authenticate.return_value = Response(is_success=False,
reason=error_types.AuthenticationFailed,
data={'foo': 'bar'})
response = DummyResource().read(request=request_factory.get_request(user=object()))
assert_that(response.is_success, equal_to(False))
assert_that(response.reason, equal_to(
error_types.AuthenticationFailed))
assert_that(response.data, equal_to({'foo': 'bar'}))
@patch_class_field(DummyResource, 'allowed_actions', [])
def test_when_method_not_allowed(self):
response = DummyResource().read(request=request_factory.get_request(user=object()))
assert_that(response.is_success, equal_to(False))
assert_that(response.reason, equal_to(error_types.MethodNotAllowed))
@patch.object(DummyViewActions, 'view')
@patch_class_field(DummyResource, 'filter_by_fields', {'foo': (EQUALS,)})
def test_with_equals_filter(self, mock_view):
mock_view.return_value = {'name': 'foo'}
request = request_factory.get_request(
user=object(), request_params={'foo': 'bar'})
response = DummyResource().read(request=request)
assert_that(response.is_success, equal_to(True))
assert_that(response.data, equal_to({'name': 'foo'}))
mock_view.assert_called_once_with(request, **({'foo': 'bar'}))
@patch.object(DummyViewActions, 'view')
@patch_class_field(DummyResource, 'filter_by_fields', {'foo': (LT, GT), 'bar': (GT, LT)})
def test_with_gt_lt_filter(self, mock_view):
mock_view.return_value = {'name': 'foo'}
request = request_factory.get_request(user=object(),
request_params={'foo__gt': 'bar',
'bar__lt': 'foo'})
response = DummyResource().read(request=request)
assert_that(response.is_success, equal_to(True))
assert_that(response.data, equal_to({'name': 'foo'}))
mock_view.assert_called_once_with(
request, **({'foo__gt': 'bar', 'bar__lt': 'foo'}))
|
class TestViewResource(unittest.TestCase):
def test_view_returns_value(self):
pass
@patch.object(DummyViewActions, 'view')
def test_when_view_returns_bad_schema(self, mocked_view):
pass
@patch.object(DummyAuthorization, 'authorize_read')
def test_when_authorization_fails(self, mocked_authorize_read):
pass
@patch.object(DummyAuthentication, 'authenticate')
def test_when_authentication_fails(self, mocked_authenticate):
pass
@patch_class_field(DummyResource, 'allowed_actions', [])
def test_when_method_not_allowed(self):
pass
@patch.object(DummyViewActions, 'view')
@patch_class_field(DummyResource, 'filter_by_fields', {'foo': (EQUALS,)})
def test_with_equals_filter(self, mock_view):
pass
@patch.object(DummyViewActions, 'view')
@patch_class_field(DummyResource, 'filter_by_fields', {'foo': (LT, GT), 'bar': (GT, LT)})
def test_with_gt_lt_filter(self, mock_view):
pass
| 16 | 0 | 8 | 2 | 6 | 0 | 1 | 0 | 1 | 3 | 2 | 0 | 7 | 0 | 7 | 79 | 72 | 18 | 54 | 24 | 38 | 0 | 40 | 18 | 32 | 1 | 2 | 1 | 7 |
6,074 |
Aplopio/django_rip
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Aplopio_django_rip/tests/integration_tests/person_resource.py
|
tests.integration_tests.person_resource.CompanySchema.Meta
|
class Meta:
schema_name = 'companies'
|
class Meta:
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 0 | 0 | 0 |
6,075 |
Aplopio/django_rip
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Aplopio_django_rip/tests/unit_tests/django_adapter/test_django_http_handler.py
|
tests.unit_tests.django_adapter.test_django_http_handler.DjangoHttpHandler
|
class DjangoHttpHandler(unittest.TestCase):
@patch.object(api_request_builder, 'build_request')
@patch.object(django_response_builder, 'build_http_response')
@patch.object(action_resolver, 'resolve_action')
@patch.object(action_resolver, 'is_valid_resource')
def test_handle_api_call_for_unhandled_action(self,
mock_is_valid_resource,
mock_resolve_action,
mock_build_response,
mock_build_request):
mock_is_valid_resource.return_value = True
mock_resolve_action.return_value = None
mock_http_request = MagicMock()
mock_api = MagicMock()
response = django_http_handler.handle_api_call(
mock_http_request, 'test_endpoint', mock_api)
mock_is_valid_resource.assert_called_once_with('test_endpoint',
mock_api)
mock_resolve_action.assert_called_once_with(mock_http_request,
'test_endpoint', mock_api)
self.assertIsInstance(response, HttpResponseNotAllowed)
@patch.object(api_request_builder, 'build_request_data')
@patch.object(action_resolver, 'resolve_action')
@patch.object(action_resolver, 'is_valid_resource')
def test_handle_api_call_for_bad_json_data(self,
mock_is_valid_resource,
mock_resolve_action,
mock_build_request_data):
mock_is_valid_resource.return_value = True
mock_resolve_action.return_value = MagicMock()
mock_build_request_data.return_value = expected_request_data = {
'error_message': 'Expected } at line 3'}
mock_http_request = MagicMock()
mock_api = MagicMock()
mock_http_request.META = http_request_meta = MagicMock()
mock_http_request.read.return_value = request_body = MagicMock()
response = django_http_handler.handle_api_call(
mock_http_request, 'test_endpoint', mock_api)
mock_is_valid_resource.assert_called_once_with('test_endpoint',
mock_api)
mock_resolve_action.assert_called_once_with(mock_http_request,
'test_endpoint', mock_api)
mock_build_request_data.assert_called_once_with(
request_body, http_request_meta)
self.assertIsInstance(response, HttpResponseBadRequest)
assert json.loads(response.content) == expected_request_data
@patch.object(api_request_builder, 'build_request_data')
@patch.object(api_request_builder, 'build_request')
@patch.object(django_response_builder, 'build_http_response')
@patch.object(action_resolver, 'resolve_action')
@patch.object(action_resolver, 'is_valid_resource')
def test_handle_api_call(self,
mock_is_valid_resource,
mock_resolve_action,
mock_build_response,
mock_build_request,
mock_build_request_data):
mock_is_valid_resource.return_value = True
mock_resolve_action.return_value = expected_action = MagicMock()
expected_action.return_value = expected_response = MagicMock()
mock_build_request.return_value = expected_request = MagicMock()
mock_build_response.return_value = expected_http_response = MagicMock()
mock_build_request_data.return_value = expected_request_data = {}
mock_http_request = MagicMock()
mock_http_request.read.return_value = request_body = MagicMock()
mock_api = MagicMock()
url = 'test_endpoint'
http_response = django_http_handler.handle_api_call(
mock_http_request, url, mock_api)
mock_is_valid_resource.assert_called_once_with('test_endpoint',
mock_api)
mock_resolve_action.assert_called_once_with(mock_http_request,
'test_endpoint',
mock_api)
mock_build_request.assert_called_once_with(
http_request=mock_http_request,
url=url, api=mock_api, request_data=expected_request_data,
request_body=request_body)
expected_action.assert_called_once_with(expected_request)
assert_that(http_response, equal_to(expected_http_response))
mock_build_response.assert_called_once_with(mock_http_request,
expected_response)
|
class DjangoHttpHandler(unittest.TestCase):
@patch.object(api_request_builder, 'build_request')
@patch.object(django_response_builder, 'build_http_response')
@patch.object(action_resolver, 'resolve_action')
@patch.object(action_resolver, 'is_valid_resource')
def test_handle_api_call_for_unhandled_action(self,
mock_is_valid_resource,
mock_resolve_action,
mock_build_response,
mock_build_request):
pass
@patch.object(api_request_builder, 'build_request_data')
@patch.object(action_resolver, 'resolve_action')
@patch.object(action_resolver, 'is_valid_resource')
def test_handle_api_call_for_bad_json_data(self,
mock_is_valid_resource,
mock_resolve_action,
mock_build_request_data):
pass
@patch.object(api_request_builder, 'build_request_data')
@patch.object(api_request_builder, 'build_request')
@patch.object(django_response_builder, 'build_http_response')
@patch.object(action_resolver, 'resolve_action')
@patch.object(action_resolver, 'is_valid_resource')
def test_handle_api_call_for_unhandled_action(self,
mock_is_valid_resource,
mock_resolve_action,
mock_build_response,
mock_build_request):
pass
| 16 | 0 | 26 | 3 | 23 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 3 | 0 | 3 | 3 | 92 | 11 | 81 | 38 | 53 | 0 | 42 | 14 | 38 | 1 | 1 | 0 | 3 |
6,076 |
Aplopio/django_rip
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Aplopio_django_rip/tests/unit_tests/generic_steps/test_default_schema_validation.py
|
tests.unit_tests.generic_steps.test_default_schema_validation.TestSchemaFullValidation.setUp.RelatedSchema
|
class RelatedSchema(ApiSchema):
email = StringField(max_length=10)
|
class RelatedSchema(ApiSchema):
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 | 2 | 0 | 0 |
6,077 |
Aplopio/django_rip
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Aplopio_django_rip/tests/unit_tests/schema/test_schema_field.py
|
tests.unit_tests.schema.test_schema_field.TestSchemaField.setUp.TestEntity
|
class TestEntity(object):
def __init__(self, name, surname):
self.name = name
self.surname = surname
|
class TestEntity(object):
def __init__(self, name, surname):
pass
| 2 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 2 | 1 | 1 | 4 | 0 | 4 | 4 | 2 | 0 | 4 | 4 | 2 | 1 | 1 | 0 | 1 |
6,078 |
Aplopio/django_rip
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Aplopio_django_rip/tests/unit_tests/schema/test_schema_field.py
|
tests.unit_tests.schema.test_schema_field.TestSchemaField.setUp.TestSchema.Meta
|
class Meta:
schema_name = 'test_schema'
|
class Meta:
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 0 | 0 | 0 |
6,079 |
Aplopio/django_rip
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Aplopio_django_rip/tests/unit_tests/schema/test_schema_field.py
|
tests.unit_tests.schema.test_schema_field.TestSchemaField.test_should_serialize_with_overridden_serializer.TestSerializer
|
class TestSerializer(DefaultEntitySerializer):
def serialize_entity(self, request, entity):
return {'name': entity.surname}
|
class TestSerializer(DefaultEntitySerializer):
def serialize_entity(self, request, entity):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 9 | 3 | 0 | 3 | 2 | 1 | 0 | 3 | 2 | 1 | 1 | 2 | 0 | 1 |
6,080 |
Aplopio/django_rip
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Aplopio_django_rip/tests/unit_tests/schema/test_schema_field.py
|
tests.unit_tests.schema.test_schema_field.TestSchemaField.test_should_validate_with_overridden_validator.TestValidator
|
class TestValidator(DefaultSchemaValidation):
def __init__(self, schema_cls):
super(TestValidator, self).__init__(schema_cls)
def validate_data(self, data, fields_to_validate=None):
return {'name': 'Custom Validation Failed'}
|
class TestValidator(DefaultSchemaValidation):
def __init__(self, schema_cls):
pass
def validate_data(self, data, fields_to_validate=None):
pass
| 3 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 2 | 0 | 2 | 6 | 6 | 1 | 5 | 3 | 2 | 0 | 5 | 3 | 2 | 1 | 2 | 0 | 2 |
6,081 |
Aplopio/django_rip
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Aplopio_django_rip/tests/unit_tests/django_adapter/test_api_request_builder.py
|
tests.unit_tests.django_adapter.test_api_request_builder.TestBuildApiRequest
|
class TestBuildApiRequest(unittest.TestCase):
def setUp(self):
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.test_settings'
@patch.object(conf, 'settings')
@patch.object(metadata_factory, 'api_breadcrumb_filters')
@patch.object(metadata_factory, 'api_breadcrumbs')
def test_create_request_with_right_request_params(self,
parent_breadcrumbs_from,
breadcrumb_filters,
settings):
http_request = MagicMock()
mock_api = MagicMock()
mock_api.name = 'api_name'
mock_api.version = '1.0.0.1'
mock_user = http_request.user
request_body = MagicMock()
http_request.user.is_anonymous.return_value = False
breadcrumb_filters.return_value = expected_req_params = {'bar': 'baz'}
request = api_request_builder.build_request(http_request=http_request,
url='candidates',
api=mock_api,
request_data={},
request_body=request_body)
assert_that(request.user, equal_to(mock_user))
assert_that(request.request_params, equal_to(expected_req_params))
@patch.object(conf, 'settings')
@patch.object(metadata_factory, 'api_breadcrumb_filters')
@patch.object(metadata_factory, 'api_breadcrumbs')
def test_create_request_with_right_context_params(self,
parent_breadcrumbs_from,
api_breadcrumb_filters,
settings):
http_request = MagicMock()
mock_api = MagicMock()
mock_api.name = 'api_name'
mock_api.version = '1.0.0.1'
http_request.user.is_anonymous.return_value = False
request_body = MagicMock()
settings.TIME_ZONE = expected_timezone = MagicMock()
request = api_request_builder.build_request(http_request=http_request,
url='candidates',
api=mock_api,
request_data={},
request_body=request_body)
assert_that(request.context_params, has_entry('protocol', 'http'))
assert_that(request.context_params, has_entry('url', 'candidates'))
assert_that(request.context_params,
has_entry('timezone', expected_timezone))
assert_that(request.context_params,
has_entry('api_version', mock_api.version))
assert_that(request.context_params,
has_entry('api_name', mock_api.name))
@patch.object(conf, 'settings')
@patch.object(metadata_factory, 'api_breadcrumb_filters')
@patch.object(metadata_factory, 'api_breadcrumbs')
def test_create_request_with_anonymous_user(self,
parent_breadcrumbs_from,
api_breadcrumb_filters,
settings):
http_request = MagicMock()
mock_api = MagicMock()
http_request.user.is_anonymous.return_value = True
request_body = MagicMock()
request = api_request_builder.build_request(http_request=http_request,
url='candidates',
api=mock_api,
request_data={},
request_body=request_body)
assert_that(request.user, equal_to(None))
def test_create_request_with_custom_headers(self):
http_request = MagicMock()
mock_api = MagicMock()
meta = dict(HTTP_CUSTOM_HEADER='custom_value')
http_request.META = meta
request_body = MagicMock()
request = api_request_builder.build_request(http_request=http_request,
url='candidates',
api=mock_api,
request_data={},
request_body=request_body)
assert_that(request.request_headers, has_entry('HTTP_CUSTOM_HEADER',
'custom_value'))
def test_create_request_with_request_body(self):
http_request = MagicMock()
mock_api = MagicMock()
request_body = 'abcd'
request = api_request_builder.build_request(http_request=http_request,
url='candidates',
api=mock_api,
request_data={},
request_body=request_body)
assert_that(request.request_body, equal_to('abcd'))
def test_build_request_data_when_request_body_is_emtpty(self):
# the call
request_data = api_request_builder.build_request_data(
request_body='', request_meta={})
assert request_data == {}
|
class TestBuildApiRequest(unittest.TestCase):
def setUp(self):
pass
@patch.object(conf, 'settings')
@patch.object(metadata_factory, 'api_breadcrumb_filters')
@patch.object(metadata_factory, 'api_breadcrumbs')
def test_create_request_with_right_request_params(self,
parent_breadcrumbs_from,
breadcrumb_filters,
settings):
pass
@patch.object(conf, 'settings')
@patch.object(metadata_factory, 'api_breadcrumb_filters')
@patch.object(metadata_factory, 'api_breadcrumbs')
def test_create_request_with_right_context_params(self,
parent_breadcrumbs_from,
api_breadcrumb_filters,
settings):
pass
@patch.object(conf, 'settings')
@patch.object(metadata_factory, 'api_breadcrumb_filters')
@patch.object(metadata_factory, 'api_breadcrumbs')
def test_create_request_with_anonymous_user(self,
parent_breadcrumbs_from,
api_breadcrumb_filters,
settings):
pass
def test_create_request_with_custom_headers(self):
pass
def test_create_request_with_request_body(self):
pass
def test_build_request_data_when_request_body_is_emtpty(self):
pass
| 17 | 0 | 13 | 1 | 12 | 0 | 1 | 0.01 | 1 | 1 | 0 | 0 | 7 | 0 | 7 | 79 | 111 | 13 | 97 | 46 | 70 | 1 | 54 | 32 | 45 | 1 | 2 | 0 | 7 |
6,082 |
Aplopio/django_rip
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Aplopio_django_rip/tests/unit_tests/test_api.py
|
tests.unit_tests.test_api.TestApi.setUp.TestResource
|
class TestResource(CrudResource):
action1 = self.action1
action2 = self.action2
schema_cls = TestSchema
|
class TestResource(CrudResource):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 11 | 5 | 1 | 4 | 4 | 3 | 0 | 4 | 4 | 3 | 0 | 2 | 0 | 0 |
6,083 |
Aplopio/django_rip
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Aplopio_django_rip/tests/unit_tests/test_api.py
|
tests.unit_tests.test_api.TestApi.setUp.TestViewResource_1
|
class TestViewResource_1(ViewResource):
schema_cls = TestSchema
|
class TestViewResource_1(ViewResource):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 5 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 2 | 0 | 0 |
6,084 |
Aplopio/django_rip
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Aplopio_django_rip/tests/unit_tests/test_api.py
|
tests.unit_tests.test_api.TestApi.setUp.TestViewResource_2
|
class TestViewResource_2(ViewResource):
schema_cls = TestSchema
|
class TestViewResource_2(ViewResource):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 5 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 2 | 0 | 0 |
6,085 |
Aplopio/django_rip
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Aplopio_django_rip/tests/unit_tests/test_api_schema_construction.py
|
tests.unit_tests.test_api_schema_construction.TestApiSchemaConstruction.setUp.TestSchema.Meta
|
class Meta:
schema_name = 'asdf'
|
class Meta:
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 0 | 0 | 0 |
6,086 |
Aplopio/django_rip
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Aplopio_django_rip/tests/unit_tests/test_api_schema_construction.py
|
tests.unit_tests.test_api_schema_construction.TestApiSchemaConstruction.test_should_inherit_fields.NewSchema
|
class NewSchema(self.TestSchema):
new_field = EmailField(max_length=20)
|
class NewSchema(self.TestSchema):
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 |
6,087 |
Aplopio/django_rip
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Aplopio_django_rip/tests/unit_tests/test_api_schema_construction.py
|
tests.unit_tests.test_api_schema_construction.TestApiSchemaConstruction.test_should_raise_exception_for_missing_name.NameLessSchema
|
class NameLessSchema(ApiSchema):
email = EmailField(max_length=50)
char = StringField(required=True, max_length=100)
boolean = BooleanField()
|
class NameLessSchema(ApiSchema):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 7 | 4 | 0 | 4 | 4 | 3 | 0 | 4 | 4 | 3 | 0 | 2 | 0 | 0 |
6,088 |
Aplopio/django_rip
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Aplopio_django_rip/tests/unit_tests/test_pipeline_composer.py
|
tests.unit_tests.test_pipeline_composer.TestComposePipeline
|
class TestComposePipeline(unittest.TestCase):
@mock_patch.object(pipeline_composer, 'PipelineComposer')
def test_compose_pipeline_calls_pipeline_composer(self, PipelineComposer):
pipeline_composer.compose_pipeline(name='asdf', pipeline=['asdf'])
PipelineComposer.assertCalledOnceWith(name='asdf', pipeline=['asdf'])
|
class TestComposePipeline(unittest.TestCase):
@mock_patch.object(pipeline_composer, 'PipelineComposer')
def test_compose_pipeline_calls_pipeline_composer(self, PipelineComposer):
pass
| 3 | 0 | 4 | 1 | 3 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 73 | 6 | 1 | 5 | 3 | 2 | 0 | 4 | 2 | 2 | 1 | 2 | 0 | 1 |
6,089 |
Aplopio/django_rip
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Aplopio_django_rip/tests/unit_tests/test_api.py
|
tests.unit_tests.test_api.TestApi.setUp.TestSchema.Meta
|
class Meta:
schema_name = 'test_objs'
|
class Meta:
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 0 | 0 | 0 |
6,090 |
Aplopio/django_rip
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Aplopio_django_rip/tests/integration_tests/person_resource.py
|
tests.integration_tests.person_resource.AddressSchema.Meta
|
class Meta:
schema_name = 'Person_Address'
|
class Meta:
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 0 | 0 | 0 |
6,091 |
Aplopio/django_rip
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Aplopio_django_rip/tests/unit_tests/crud/test_crud_resource.py
|
tests.unit_tests.crud.test_crud_resource.TestMethodNotAllowed.setUp.TestResource
|
class TestResource(CrudResource):
schema_cls = MagicMock()
allowed_actions = ()
|
class TestResource(CrudResource):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 11 | 3 | 0 | 3 | 3 | 2 | 0 | 3 | 3 | 2 | 0 | 2 | 0 | 0 |
6,092 |
Aplopio/django_rip
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Aplopio_django_rip/tests/unit_tests/crud/test_crud_resource.py
|
tests.unit_tests.crud.test_crud_resource.TestCrudResourceConstruction.test_read_detail.DefaultTestResource
|
class DefaultTestResource(CrudResource):
schema_cls = self.schema
authentication_cls = custom_auth
|
class DefaultTestResource(CrudResource):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 11 | 3 | 0 | 3 | 3 | 2 | 0 | 3 | 3 | 2 | 0 | 2 | 0 | 0 |
6,093 |
Aplopio/django_rip
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Aplopio_django_rip/tests/integration_tests/person_resource.py
|
tests.integration_tests.person_resource.FriendSchema.Meta
|
class Meta:
schema_name = 'friends'
|
class Meta:
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 0 | 0 | 0 |
6,094 |
Aplopio/django_rip
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Aplopio_django_rip/tests/integration_tests/person_resource.py
|
tests.integration_tests.person_resource.PersonSchema.Meta
|
class Meta:
schema_name = 'persons'
|
class Meta:
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 0 | 0 | 0 |
6,095 |
Aplopio/django_rip
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Aplopio_django_rip/tests/integration_tests/test_create_detail.py
|
tests.integration_tests.test_create_detail.CreateCrudResourceIntegrationTest
|
class CreateCrudResourceIntegrationTest(PersonResourceBaseTestCase):
@patch.object(PersonResource.entity_actions_cls, 'create_entity')
def test_should_create(self, create_person_entity):
resource = PersonResource()
expected_entity = PersonEntity(name='John', email="foo@bar.com",
phone='1234',
address={'city': 'bangalore',
'country': 'India'},
nick_names=['Johnny', 'Papa'])
create_person_entity.return_value = expected_entity
request = request_factory.get_request(user=object(),
data=expected_entity.__dict__)
response = resource.create_detail(request)
assert_that(response.is_success, equal_to(True))
expected_data = expected_entity.__dict__
expected_data.update(friends=[])
expected_data.update(company=None)
assert_that(response.data, equal_to(expected_data))
expected_update_kwargs = dict(name='John',
email="foo@bar.com",
address={'country': 'India'},
nick_names=['Johnny', 'Papa']
)
create_person_entity.assert_called_once_with(
request,
**expected_update_kwargs)
def test_create_with_missing_required_fields(self):
resource = PersonResource()
request = request_factory.get_request(user=object(),
data={'email': 'foo@bar.com'})
response = resource.create_detail(request)
assert_that(response.is_success, equal_to(False))
assert_that(response.data, has_entry('name', 'This field is required'))
def test_create_with_blank_fields(self):
resource = BlankTestResource()
request = request_factory.get_request(user=object(),
data={'name': ''})
response = resource.create_detail(request)
assert response.is_success is False
assert response.data['name'] == 'This field is required'
def test_create_with_null_for_non_nullable_field(self):
resource = PersonResource()
request = request_factory.get_request(user=object(),
data={'name': None})
response = resource.create_detail(request)
assert_that(response.is_success, equal_to(False))
assert_that(response.data,
has_entry('name', 'null is not a valid value'))
@patch.object(PersonResource.entity_actions_cls, 'create_entity')
def test_readonly_fields_are_skipped_when_calling_create_entity(
self,
create_person_entity):
resource = PersonResource()
expected_entity = PersonEntity(name='John', email="foo@bar.com",
phone='1234',
address={'city': 'bangalore',
'country': 'India'},
company='foo company',
nick_names=['Johnny', 'Papa'])
create_person_entity.return_value = expected_entity
request = request_factory.get_request(user=object(),
data=expected_entity.__dict__)
response = resource.create_detail(request)
assert_that(response.is_success, equal_to(True))
expected_update_kwargs = dict(name='John',
email="foo@bar.com",
address={'country': 'India'},
nick_names=['Johnny', 'Papa'])
create_person_entity.assert_called_once_with(
request,
**expected_update_kwargs)
|
class CreateCrudResourceIntegrationTest(PersonResourceBaseTestCase):
@patch.object(PersonResource.entity_actions_cls, 'create_entity')
def test_should_create(self, create_person_entity):
pass
def test_create_with_missing_required_fields(self):
pass
def test_create_with_blank_fields(self):
pass
def test_create_with_null_for_non_nullable_field(self):
pass
@patch.object(PersonResource.entity_actions_cls, 'create_entity')
def test_readonly_fields_are_skipped_when_calling_create_entity(
self,
create_person_entity):
pass
| 8 | 0 | 16 | 3 | 14 | 0 | 1 | 0 | 1 | 4 | 3 | 0 | 5 | 0 | 5 | 78 | 88 | 17 | 71 | 30 | 61 | 0 | 41 | 26 | 35 | 1 | 3 | 0 | 5 |
6,096 |
Aplopio/django_rip
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Aplopio_django_rip/tests/integration_tests/test_delete_detail.py
|
tests.integration_tests.test_delete_detail.DeleteCrudResourceIntegrationTest
|
class DeleteCrudResourceIntegrationTest(PersonResourceBaseTestCase):
@patch.object(PersonResource.entity_actions_cls, 'delete_entity')
@patch.object(PersonResource.entity_actions_cls, 'get_entity_list')
def test_should_delete(self, get_person_entity_list, delete_person_entity):
resource = PersonResource()
expected_entity = PersonEntity(name='John', email="foo@bar.com",
phone='1234',
address={'city': 'bangalore',
'country': 'India'})
get_person_entity_list.return_value = [expected_entity]
request = request_factory.get_request(user=object(),
request_params={'name': 'John'})
response = resource.delete_detail(request)
assert_that(response.is_success, equal_to(True))
expected_delete_kwargs = dict(name='John')
delete_person_entity.assert_called_once_with(
request, expected_entity)
@patch.object(PersonResource.entity_actions_cls, 'delete_entity')
@patch.object(PersonResource.entity_actions_cls, 'get_entity_list')
def test_should_return_NotFound_for_non_existing_object(
self,
get_person_entity_list, delete_person_entity):
resource = PersonResource()
get_person_entity_list.return_value = []
request = request_factory.get_request(user=object(),
request_params={'name': 'John'})
response = resource.delete_detail(request)
assert_that(response.is_success, equal_to(False))
assert_that(response.reason, error_types.ObjectNotFound)
|
class DeleteCrudResourceIntegrationTest(PersonResourceBaseTestCase):
@patch.object(PersonResource.entity_actions_cls, 'delete_entity')
@patch.object(PersonResource.entity_actions_cls, 'get_entity_list')
def test_should_delete(self, get_person_entity_list, delete_person_entity):
pass
@patch.object(PersonResource.entity_actions_cls, 'delete_entity')
@patch.object(PersonResource.entity_actions_cls, 'get_entity_list')
def test_should_return_NotFound_for_non_existing_object(
self,
get_person_entity_list, delete_person_entity):
pass
| 7 | 0 | 15 | 3 | 12 | 0 | 1 | 0 | 1 | 3 | 2 | 0 | 2 | 0 | 2 | 75 | 35 | 6 | 29 | 15 | 20 | 0 | 17 | 11 | 14 | 1 | 3 | 0 | 2 |
6,097 |
Aplopio/django_rip
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Aplopio_django_rip/tests/integration_tests/test_read_detail.py
|
tests.integration_tests.test_read_detail.GetCrudResourceIntegrationTest
|
class GetCrudResourceIntegrationTest(PersonResourceBaseTestCase):
def test_should_get_fields(self):
resource = PersonResource()
entity_actions = resource.configuration['entity_actions']
expected_entities = [PersonEntity(name='John', email=None, phone='1234',
address={'city': 'bangalore',
'country': 'India'},
company=None,
nick_names=['Johnny', 'Papa'])]
entity_actions.get_entity_list.return_value = expected_entities
request = request_factory.get_request(user=object())
response = resource.read_detail(request, )
assert_that(response.is_success, equal_to(True))
expected_data = expected_entities[0].__dict__
expected_data.update(friends=[])
assert_that(response.data, equal_to(expected_data))
def test_should_get_by_allowed_filters(self):
resource = PersonResource()
entity_actions = resource.configuration['entity_actions']
expected_entities = [PersonEntity(name='John', email=None, phone='1234',
address={'city': 'bangalore',
'country': 'India'},
company=None,
nick_names=['Johnny', 'Papa'])]
entity_actions.get_entity_list.return_value = expected_entities
request = request_factory.get_request(user=object(),
request_params={'name': 'bar'})
response = resource.read_detail(request)
assert_that(response.is_success, equal_to(True))
entity_actions.get_entity_list.assert_called_once_with(request,
name='bar')
@patch.object(CompanyResource.entity_actions_cls, 'get_entity_list')
def test_should_get_sub_resource(self, company_entity_list):
resource = PersonResource()
entity_actions = resource.configuration['entity_actions']
expected_entities = [
PersonEntity(
name='John', email=None, phone='1234',
address={'city': 'bangalore',
'country': 'India'}, nick_names=['Johnny', 'Papa'])
]
expected_company = {
'name': 'Acme', 'registration_number': 12,
'resource_uri': '/api/v2/persons/John/companies/Acme/'}
expected_companies = [expected_company]
company_entity_list.return_value = expected_companies
entity_actions.get_entity_list.return_value = expected_entities
request = request_factory.get_request(user=object())
response = resource.read_detail(request)
assert_that(response.is_success, equal_to(True))
assert_that(response.data['company'], equal_to(expected_company))
@patch.object(FriendResource.entity_actions_cls, 'get_entity_list')
@patch.object(FriendResource.entity_actions_cls,
'get_entity_list_total_count')
def test_should_get_list_sub_resource(self, friend_entity_count,
friend_entity_list):
resource = PersonResource()
entity_actions = resource.configuration['entity_actions']
expected_persons = [
dict(name='John', email=None, phone='1234', address=None,
nick_names=['Johnny', 'Papa'])]
friend1 = dict(name='friend1', relationship_type='platonic')
friend2 = dict(name='friend2', relationship_type='girlfriend')
friend_entity_list.return_value = [friend1, friend2]
friend_entity_count.return_value = 2
entity_actions.get_entity_list.return_value = expected_persons
request = request_factory.get_request(user=object())
response = resource.read_detail(request)
assert_that(response.is_success, equal_to(True))
friend1.update(resource_uri=u'/api/v2/persons/John/friends/friend1/')
friend2.update(resource_uri=u'/api/v2/persons/John/friends/friend2/')
expected_friends = [friend1, friend2]
assert_that(response.data['friends'], equal_to(expected_friends))
def test_should_get_none_for_nullable_schema_field(self):
resource = PersonResource()
entity_actions = resource.configuration['entity_actions']
expected_entities = [PersonEntity(name='John', email=None,
phone='1234',
address=None, company=None,
nick_names=['Johnny', 'Papa'])]
entity_actions.get_entity_list.return_value = expected_entities
request = request_factory.get_request(user=object())
response = resource.read_detail(request, )
assert_that(response.is_success, equal_to(True))
expected_data = expected_entities[0].__dict__
expected_data.update(friends=[])
assert_that(response.data, equal_to(expected_data))
|
class GetCrudResourceIntegrationTest(PersonResourceBaseTestCase):
def test_should_get_fields(self):
pass
def test_should_get_by_allowed_filters(self):
pass
@patch.object(CompanyResource.entity_actions_cls, 'get_entity_list')
def test_should_get_sub_resource(self, company_entity_list):
pass
@patch.object(FriendResource.entity_actions_cls, 'get_entity_list')
@patch.object(FriendResource.entity_actions_cls,
'get_entity_list_total_count')
def test_should_get_list_sub_resource(self, friend_entity_count,
friend_entity_list):
pass
def test_should_get_none_for_nullable_schema_field(self):
pass
| 9 | 0 | 19 | 2 | 16 | 0 | 1 | 0 | 1 | 3 | 2 | 0 | 5 | 0 | 5 | 78 | 104 | 17 | 87 | 41 | 76 | 0 | 60 | 38 | 54 | 1 | 3 | 0 | 5 |
6,098 |
Aplopio/django_rip
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Aplopio_django_rip/tests/integration_tests/test_view_resource_end_to_end.py
|
tests.integration_tests.test_view_resource_end_to_end.DummySchema.Meta
|
class Meta:
schema_name = 'dummy'
|
class Meta:
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 0 | 0 | 0 |
6,099 |
Aplopio/django_rip
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Aplopio_django_rip/tests/unit_tests/crud/test_crud_resource.py
|
tests.unit_tests.crud.test_crud_resource.TestCrudResourceConstruction.test_update_detail.DefaultTestResource
|
class DefaultTestResource(CrudResource):
schema_cls = self.schema
authentication_cls = custom_auth
allowed_actions = [CrudActions.UPDATE_DETAIL]
|
class DefaultTestResource(CrudResource):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 11 | 4 | 0 | 4 | 4 | 3 | 0 | 4 | 4 | 3 | 0 | 2 | 0 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.