hexsha
stringlengths
40
40
size
int64
1
1.03M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
239
max_stars_repo_name
stringlengths
5
130
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
239
max_issues_repo_name
stringlengths
5
130
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
239
max_forks_repo_name
stringlengths
5
130
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
1
1.03M
avg_line_length
float64
1
958k
max_line_length
int64
1
1.03M
alphanum_fraction
float64
0
1
ace9c456b09a08353581c4c39e4b3239694538a1
459
py
Python
runtornado.py
zhaoguanghe/QBlog
03c6c8f210e8d647bb7844d334a2f92328046aa1
[ "MIT" ]
1
2020-02-25T03:35:50.000Z
2020-02-25T03:35:50.000Z
runtornado.py
zhaoguanghe/QBlog
03c6c8f210e8d647bb7844d334a2f92328046aa1
[ "MIT" ]
null
null
null
runtornado.py
zhaoguanghe/QBlog
03c6c8f210e8d647bb7844d334a2f92328046aa1
[ "MIT" ]
null
null
null
""" This script runs the QBlog application using a development server. tornado托管flask,参考:https://blog.csdn.net/a3335581/article/details/87916234 """ from tornado.wsgi import WSGIContainer from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop from QBlog import app #这里要和runflask.py对应 if __name__ == '__main__': server = HTTPServer(WSGIContainer(app)) server.listen(5555) #flask默认的端口 IOLoop.instance().start()
32.785714
74
0.755991
ace9c47072f85a6b67591f214507ff6a6b3e53a8
3,398
py
Python
tests/__init__.py
WANGHONGCHAO123/wwttt
817054d6f80a4704c84630a97eec337c8dd9cd66
[ "BSD-3-Clause" ]
36
2020-05-18T15:53:50.000Z
2022-03-13T01:54:31.000Z
tests/__init__.py
WANGHONGCHAO123/wwttt
817054d6f80a4704c84630a97eec337c8dd9cd66
[ "BSD-3-Clause" ]
56
2020-05-20T20:40:48.000Z
2022-03-21T15:13:00.000Z
tests/__init__.py
WANGHONGCHAO123/wwttt
817054d6f80a4704c84630a97eec337c8dd9cd66
[ "BSD-3-Clause" ]
8
2020-07-12T12:41:40.000Z
2021-11-23T12:17:46.000Z
import importlib from typing import Optional from itemadapter import ItemAdapter def mocked_import(name, *args, **kwargs): """Allow only internal itemadapter imports.""" if name.split(".")[0] == "itemadapter": return importlib.__import__(name, *args, **kwargs) raise ImportError(name) try: import attr except ImportError: AttrsItem = None AttrsItemNested = None AttrsItemWithoutInit = None else: @attr.s class AttrsItem: name = attr.ib(default=None, metadata={"serializer": str}) value = attr.ib(default=None, metadata={"serializer": int}) @attr.s class AttrsItemNested: nested = attr.ib(type=AttrsItem) adapter = attr.ib(type=ItemAdapter) dict_ = attr.ib(type=dict) list_ = attr.ib(type=list) set_ = attr.ib(type=set) tuple_ = attr.ib(type=tuple) int_ = attr.ib(type=int) @attr.s(init=False) class AttrsItemWithoutInit: name = attr.ib(default=None, metadata={"serializer": str}) value = attr.ib(default=None, metadata={"serializer": int}) try: from dataclasses import dataclass, field except ImportError: DataClassItem = None DataClassItemNested = None DataClassWithoutInit = None else: @dataclass class DataClassItem: name: str = field(default_factory=lambda: None, metadata={"serializer": str}) value: int = field(default_factory=lambda: None, metadata={"serializer": int}) @dataclass class DataClassItemNested: nested: DataClassItem adapter: ItemAdapter dict_: dict list_: list set_: set tuple_: tuple int_: int @dataclass(init=False) class DataClassWithoutInit: name: str = field(metadata={"serializer": str}) value: int = field(metadata={"serializer": int}) try: from pydantic import BaseModel, Field as PydanticField except ImportError: PydanticModel = None PydanticSpecialCasesModel = None PydanticModelNested = None else: class PydanticModel(BaseModel): name: Optional[str] = PydanticField( default_factory=lambda: None, serializer=str, ) value: Optional[int] = PydanticField( default_factory=lambda: None, serializer=int, ) class PydanticSpecialCasesModel(BaseModel): special_cases: Optional[int] = PydanticField( default_factory=lambda: None, alias="special_cases", allow_mutation=False, ) class Config: validate_assignment = True class PydanticModelNested(BaseModel): nested: PydanticModel adapter: ItemAdapter dict_: dict list_: list set_: set tuple_: tuple int_: int class Config: arbitrary_types_allowed = True try: from scrapy.item import Item as ScrapyItem, Field except ImportError: ScrapyItem = None ScrapySubclassedItem = None ScrapySubclassedItemNested = None else: class ScrapySubclassedItem(ScrapyItem): name = Field(serializer=str) value = Field(serializer=int) class ScrapySubclassedItemNested(ScrapyItem): nested = Field() adapter = Field() dict_ = Field() list_ = Field() set_ = Field() tuple_ = Field() int_ = Field()
25.548872
86
0.631548
ace9c47972700155e168bf7ce65209936652c907
431
py
Python
setup.py
illinois-ipaml/course
fb391ac9d96afb26df11d2a247b9f5a3c8a28ab3
[ "BSD-3-Clause" ]
5
2018-07-30T00:32:26.000Z
2019-10-28T17:47:16.000Z
setup.py
illinois-ipaml/course
fb391ac9d96afb26df11d2a247b9f5a3c8a28ab3
[ "BSD-3-Clause" ]
5
2018-08-27T23:43:05.000Z
2022-01-13T05:17:21.000Z
setup.py
illinois-ipaml/course
fb391ac9d96afb26df11d2a247b9f5a3c8a28ab3
[ "BSD-3-Clause" ]
4
2019-01-28T21:15:52.000Z
2021-03-07T18:47:55.000Z
from setuptools import setup setup( name='mls', version='0.2', description='Material for UIiUC course "Data Analysis and Machine Learning Applications"', url='http://github.com/illinois-mla', author='David Kirkby, with modifications from Mark Neubauer', author_email='msn@illinois.edu', license='BSD3', packages=['mls'], install_requires=[ ], include_package_data=True, zip_safe=False)
28.733333
94
0.693735
ace9c51d82a78f1ff43585d93d7cad399ab8ac86
1,260
py
Python
tests/test_journey_table.py
jmann277/oura_cdm
de51c780d49744234757ddce2718a59abd8d8a03
[ "MIT" ]
null
null
null
tests/test_journey_table.py
jmann277/oura_cdm
de51c780d49744234757ddce2718a59abd8d8a03
[ "MIT" ]
null
null
null
tests/test_journey_table.py
jmann277/oura_cdm
de51c780d49744234757ddce2718a59abd8d8a03
[ "MIT" ]
null
null
null
import pytest from oura_cdm.concepts import ObservationConcept, OuraConcept from oura_cdm.journey import make_observation_journey_df from oura_cdm.schemas import make_journey_schema @pytest.fixture(scope='session') def journey_df(observation_df): return make_observation_journey_df(observation_df) @pytest.fixture(scope='session') def journey_schema(observation_df): return make_journey_schema(observation_df) def test_observations_columns_in_observation_journey(journey_df): concept_ids = {c.value for c in ObservationConcept} assert set(journey_df.columns) == concept_ids def test_n_journeys(journey_df, oura_data): assert len(journey_df) == len(oura_data) def test_observation_value_at_date( ontology, observation_concept, journey_df, raw_observation): date = raw_observation['summary_date'] keyword = ontology.get_concept_code(ontology.mapped_from(observation_concept)) expected_value = raw_observation[keyword] expected = expected_value \ * ObservationConcept.get_reference_value(observation_concept) actual = journey_df.loc[date, observation_concept.value] assert expected == actual def test_journey_fits_schema(journey_df, journey_schema): journey_schema.validate(journey_df)
31.5
82
0.803968
ace9c5af4df6cefde64b4e0ed5cb13819ddc0418
682
py
Python
config.py
kj54321/webhookit
cc420e061c808064ebec73ce01929a336ef2db9b
[ "MIT" ]
null
null
null
config.py
kj54321/webhookit
cc420e061c808064ebec73ce01929a336ef2db9b
[ "MIT" ]
null
null
null
config.py
kj54321/webhookit
cc420e061c808064ebec73ce01929a336ef2db9b
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- ''' Created on Mar-27-19 23:02:55 @author: hustcc/webhookit ''' # This means: # When get a webhook request from `repo_name` on branch `branch_name`, # will exec SCRIPT on servers config in the array. WEBHOOKIT_CONFIGURE = { # a web hook request can trigger multiple servers. 'repo_name/branch_name': [{ # if exec shell on local server, keep empty. 'HOST': '', # will exec shell on which server. 'PORT': '', # ssh port, default is 22. 'USER': 'root', # linux user name 'PWD': '', # user password or private key. # The webhook shell script path. 'SCRIPT': '/opt/pull_scripts.sh' }] }
27.28
70
0.608504
ace9c7e70fc5d6d900ba346c5ed3c49bdd9ecb24
1,999
py
Python
mmseg/ops/wrappers.py
shinianzhihou/ChangeDetection
c29a90ebb3d13861c5161cc751bfd1f11c28bf45
[ "Apache-2.0" ]
95
2019-11-04T08:05:54.000Z
2022-03-29T07:09:21.000Z
mmseg/ops/wrappers.py
shinianzhihou/ChangeDetection
c29a90ebb3d13861c5161cc751bfd1f11c28bf45
[ "Apache-2.0" ]
9
2019-11-04T08:05:14.000Z
2022-03-29T08:53:01.000Z
mmseg/ops/wrappers.py
shinianzhihou/ChangeDetection
c29a90ebb3d13861c5161cc751bfd1f11c28bf45
[ "Apache-2.0" ]
25
2019-11-22T08:14:32.000Z
2022-03-28T03:18:30.000Z
import warnings import torch import torch.nn as nn import torch.nn.functional as F def resize(input, size=None, scale_factor=None, mode='nearest', align_corners=None, warning=True): if warning: if size is not None and align_corners: input_h, input_w = tuple(int(x) for x in input.shape[2:]) output_h, output_w = tuple(int(x) for x in size) if output_h > input_h or output_w > output_h: if ((output_h > 1 and output_w > 1 and input_h > 1 and input_w > 1) and (output_h - 1) % (input_h - 1) and (output_w - 1) % (input_w - 1)): warnings.warn( f'When align_corners={align_corners}, ' 'the output would more aligned if ' f'input size {(input_h, input_w)} is `x+1` and ' f'out size {(output_h, output_w)} is `nx+1`') if isinstance(size, torch.Size): size = tuple(int(x) for x in size) # print('ops,wrappers',input.shape,size,scale_factor, mode, align_corners) return F.interpolate(input, size, scale_factor, mode, align_corners) class Upsample(nn.Module): def __init__(self, size=None, scale_factor=None, mode='nearest', align_corners=None): super(Upsample, self).__init__() self.size = size if isinstance(scale_factor, tuple): self.scale_factor = tuple(float(factor) for factor in scale_factor) else: self.scale_factor = float(scale_factor) if scale_factor else None self.mode = mode self.align_corners = align_corners def forward(self, x): if not self.size: size = [int(t * self.scale_factor) for t in x.shape[-2:]] else: size = self.size return resize(x, size, None, self.mode, self.align_corners)
36.345455
79
0.555278
ace9c909fbd91356745cc4af5d984538dca93e29
27,297
py
Python
pytest_ibutsu.py
rsnyman/pytest-ibutsu
f0275bd321f23073d3615fd7d56474dbc563d6ca
[ "MIT" ]
null
null
null
pytest_ibutsu.py
rsnyman/pytest-ibutsu
f0275bd321f23073d3615fd7d56474dbc563d6ca
[ "MIT" ]
null
null
null
pytest_ibutsu.py
rsnyman/pytest-ibutsu
f0275bd321f23073d3615fd7d56474dbc563d6ca
[ "MIT" ]
null
null
null
import json import os import shutil import tarfile import time import uuid from datetime import date from datetime import datetime from http.client import BadStatusLine from http.client import RemoteDisconnected from json import JSONEncoder from tempfile import gettempdir from tempfile import NamedTemporaryFile import pytest from ibutsu_client import ApiClient from ibutsu_client import ApiException from ibutsu_client import Configuration from ibutsu_client.api.artifact_api import ArtifactApi from ibutsu_client.api.health_api import HealthApi from ibutsu_client.api.result_api import ResultApi from ibutsu_client.api.run_api import RunApi from ibutsu_client.exceptions import ApiValueError from urllib3.exceptions import MaxRetryError from urllib3.exceptions import ProtocolError # A list of markers that can be filtered out FILTERED_MARKERS = ["parametrize"] CA_BUNDLE_ENVS = ["REQUESTS_CA_BUNDLE", "IBUTSU_CA_BUNDLE"] # Convert the blocker category into an Ibutsu Classification BLOCKER_CATEGORY_TO_CLASSIFICATION = { "needs-triage": "needs_triage", "automation-issue": "test_failure", "environment-issue": "environment_failure", "product-issue": "product_failure", "product-rfe": "product_rfe", } # Place a limit on the file-size we can upload for artifacts UPLOAD_LIMIT = 5 * 1024 * 1024 # 5 MiB # Maximum number of times an API call is retried MAX_CALL_RETRIES = 3 class DateTimeEncoder(JSONEncoder): """Handle datetime objects in the archiver.""" def default(self, obj): if isinstance(obj, (date, datetime)): return obj.isoformat() def safe_string(o): """This will make string out of ANYTHING without having to worry about the stupid Unicode errors This function tries to make str/unicode out of ``o`` unless it already is one of those and then it processes it so in the end there is a harmless ascii string. Args: o: Anything. """ if not isinstance(o, str): o = str(o) if isinstance(o, bytes): o = o.decode("utf-8", "ignore") o = o.encode("ascii", "xmlcharrefreplace").decode("ascii") return o def merge_dicts(old_dict, new_dict): for key, value in old_dict.items(): if key not in new_dict: new_dict[key] = value elif isinstance(value, dict): merge_dicts(value, new_dict[key]) def parse_data_option(data_list): if not data_list: return {} data_dict = {} for data_str in data_list: if not data_str: continue key_str, value = data_str.split("=", 1) keys = key_str.split(".") current_item = data_dict for key in keys[:-1]: if key not in current_item: current_item[key] = {} current_item = current_item[key] key = keys[-1] current_item[key] = value return data_dict def get_test_idents(item): try: return item.location[2], item.location[0] except AttributeError: try: return item.fspath.strpath, None except AttributeError: return (None, None) def get_name(obj): return getattr(obj, "_param_name", None) or getattr(obj, "name", None) or str(obj) def overall_test_status(statuses): # Handle some logic for when to count certain tests as which state for when, status in statuses.items(): if (when == "call" or when == "setup") and status[1] and status[0] == "skipped": return "xfailed" elif when == "call" and status[1] and status[0] == "passed": return "xpassed" elif (when == "setup" or when == "teardown") and status[0] == "failed": return "error" elif status[0] == "skipped": return "skipped" elif when == "call" and status[0] == "failed": return "failed" return "passed" class TooManyRetriesError(Exception): pass class IbutsuArchiver(object): """ Save all Ibutsu results to archive """ _start_time = None _stop_time = None frontend = None def __init__(self, source=None, path=None, extra_data=None): self._results = {} self._run_id = None self.run = None self._temp_path = path self.source = source or "local" self.extra_data = extra_data or {"component": None, "env": None} # pytest session object, to be set by pytest_collection_modifyitems below self._session = None # Set an env var ID if os.environ.get("IBUTSU_ENV_ID"): self.extra_data.update({"env_id": os.environ.get("IBUTSU_ENV_ID")}) # Auto-detect running in Jenkins and add to the metadata if os.environ.get("JOB_NAME") and os.environ.get("BUILD_NUMBER"): self.extra_data.update( { "jenkins": { "job_name": os.environ.get("JOB_NAME"), "build_number": os.environ.get("BUILD_NUMBER"), "build_url": os.environ.get("BUILD_URL"), } } ) # If the project is set via environment variables if os.environ.get("IBUTSU_PROJECT"): self.extra_data.update({"project": os.environ.get("IBUTSU_PROJECT")}) def _status_to_summary(self, status): return { "failed": "failures", "error": "errors", "skipped": "skips", "xfailed": "xfailures", "xpassed": "xpasses", "tests": "tests", }.get(status) def get_temp_path(self, run): if not self._temp_path: self._temp_path = os.path.join(gettempdir(), run["id"]) os.makedirs(self._temp_path, exist_ok=True) return self._temp_path @property def temp_path(self): if not self.run: raise Exception("Run ID has not yet been set") return self.get_temp_path(self.run) def _save_run(self, run): if not run.get("metadata"): run["metadata"] = {} run["metadata"].update(self.extra_data) with open(os.path.join(self.get_temp_path(run), "run.json"), "w") as f: json.dump(run, f, cls=DateTimeEncoder) @property def run_id(self): if not self._run_id: raise Exception("You need to use set_run_id() to set a run ID") return self._run_id @property def duration(self): if self._start_time and self._stop_time: return self._stop_time - self._start_time elif self._start_time: return time.time() - self._start_time else: return 0 def start_timer(self): if not self._start_time: self._start_time = time.time() def stop_timer(self): if not self._stop_time: self._stop_time = time.time() def shutdown(self): # Gather the summary before building the archive summary = { "failures": 0, "skips": 0, "errors": 0, "xfailures": 0, "xpasses": 0, "tests": 0, "collected": 0, } for result in self._results.values(): key = self._status_to_summary(result["result"]) if key in summary: summary[key] += 1 # update the number of tests that actually ran summary["tests"] += 1 # store the number of tests that were collected summary["collected"] = getattr(self._session, "testscollected", summary["tests"]) # store the summary on the run self.run["summary"] = summary self.update_run() # Build the tarball self.tar_file = os.path.join(os.path.abspath("."), f"{self.run_id}.tar.gz") print("Creating archive {}...".format(os.path.basename(self.tar_file))) with tarfile.open(self.tar_file, "w:gz") as tar: tar.add(self.temp_path, self.run_id) def output_msg(self): if hasattr(self, "tar_file"): print(f"Saved results archive to {self.tar_file}") def get_run_id(self): if not self.run: run = { "duration": 0.0, "component": "", "summary": { "failures": 0, "skips": 0, "errors": 0, "xfailures": 0, "xpasses": 0, "tests": 0, }, "metadata": self.extra_data, "source": getattr(self, "source", "local"), "start_time": datetime.utcnow().isoformat(), } self.run = self.add_run(run=run) return self.run["id"] def set_run_id(self, run_id): self._run_id = run_id self.refresh_run() def add_run(self, run=None): if not run.get("id"): run["id"] = str(uuid.uuid4()) if not run.get("source"): run["source"] = self.source self._save_run(run) return run def refresh_run(self): """This does nothing, there's nothing to do here""" pass def update_run(self, duration=None): if duration: self.run["duration"] = duration self._save_run(self.run) def add_result(self, result): result_id = result.get("id") if not result_id: result_id = str(uuid.uuid4()) result["id"] = result_id art_path = os.path.join(self.temp_path, result_id) os.makedirs(art_path, exist_ok=True) if not result.get("metadata"): result["metadata"] = {} result["metadata"].update(self.extra_data) with open(os.path.join(art_path, "result.json"), "w") as f: json.dump(result, f, cls=DateTimeEncoder) self._results[result_id] = result return result def update_result(self, id, result): art_path = os.path.join(self.temp_path, id) os.makedirs(art_path, exist_ok=True) if not result.get("metadata"): result["metadata"] = {} result["metadata"].update(self.extra_data) with open(os.path.join(art_path, "result.json"), "w") as f: json.dump(result, f, cls=DateTimeEncoder) self._results[id] = result def upload_artifact(self, id_, filename, data, is_run=False): """ Save an artifact to the archive. 'id_' can be either a run or result ID. 'is_run' should be True if it is a run ID. """ file_size = os.stat(data).st_size if file_size < UPLOAD_LIMIT: art_path = os.path.join(self.temp_path, id_) os.makedirs(art_path, exist_ok=True) shutil.copyfile(data, os.path.join(art_path, filename)) else: print( f"File '{filename}' of size '{file_size}' bytes" f" exceeds global Ibutsu upload limit of '{UPLOAD_LIMIT}' bytes." f" File will not be uploaded to Ibutsu." ) def upload_artifact_raw(self, id_, filename, data, is_run=False): file_object = NamedTemporaryFile(delete=False) os_file_name = file_object.name file_object.write(data) file_object.close() self.upload_artifact(id_, filename, os_file_name, is_run=is_run) def upload_artifact_from_file(self, id_, logged_filename, filename, is_run=False): self.upload_artifact(id_, logged_filename, filename, is_run=is_run) def get_xfail_reason(self, data, report): xfail_reason = None if data["metadata"].get("markers"): for marker in data["metadata"]["markers"]: if marker.get("name") == "xfail": xfail_reason = marker["kwargs"].get("reason") else: xfail_reason = report.wasxfail.split("reason: ")[1] return xfail_reason def get_skip_reason(self, data, report): skip_reason = None # first see if the reason is in the marker skip if data["metadata"].get("markers"): for marker in data["metadata"]["markers"]: if marker.get("name") == "skipif": skip_reason = marker["kwargs"].get("reason") elif marker.get("name") == "skip": try: skip_reason = marker["args"][0] except IndexError: pass # otherwise we must use the report to get the skip information else: try: if report.longrepr: skip_reason = report.longrepr[2].split("Skipped: ")[1] except IndexError: pass return skip_reason def get_classification(self, reason): """Get the skip/xfail classification and category from the reason""" category = None try: category = reason.split("category:")[1].strip() except IndexError: pass return BLOCKER_CATEGORY_TO_CLASSIFICATION.get(category) @pytest.mark.tryfirst def pytest_collection_modifyitems(self, session, items): # save the pytest session object for later use self._session = session # loop over all items and add ibutsu data for item in items: data = getattr(item, "_ibutsu", {}) new_data = {"id": None, "data": {"metadata": {}}, "artifacts": {}} merge_dicts(data, new_data) item._ibutsu = new_data @pytest.mark.hookwrapper def pytest_runtest_protocol(self, item): if hasattr(item, "callspec"): try: params = {p: get_name(v) for p, v in item.callspec.params.items()} except Exception: params = {} else: params = {} start_time = datetime.utcnow().isoformat() fspath = item.location[0] or item.fspath.strpath if "site-packages/" in fspath: fspath = fspath[fspath.find("site-packages/") + 14 :] data = { "result": "failed", "source": getattr(self, "source", "local"), "params": params, "start_time": start_time, "test_id": get_test_idents(item)[0], "duration": 0.0, "metadata": { "statuses": {}, "run": self.run_id, "durations": {}, "fspath": fspath, "markers": [ {"name": m.name, "args": m.args, "kwargs": m.kwargs} for m in item.iter_markers() if m.name not in FILTERED_MARKERS ], }, } def _default(obj): if callable(obj) and hasattr(obj, "__code__"): return f"function: '{obj.__name__}', args: {str(obj.__code__.co_varnames)}" else: return str(obj) # serialize the metadata just in case of any functions present data["metadata"] = json.loads(json.dumps(data["metadata"], default=_default)) result = self.add_result(result=data) item._ibutsu["id"] = result["id"] # Update result data old_data = item._ibutsu["data"] merge_dicts(old_data, data) item._ibutsu["data"] = data yield # Finish up with the result and update it self.update_result(item._ibutsu["id"], result=item._ibutsu["data"]) def pytest_exception_interact(self, node, call, report): if not hasattr(report, "_ibutsu"): return val = safe_string(call.excinfo.value) last_lines = "\n".join(report.longreprtext.split("\n")[-4:]) short_tb = "{}\n{}\n{}".format( last_lines, call.excinfo.type.__name__, val.encode("ascii", "xmlcharrefreplace") ) id = report._ibutsu["id"] data = report._ibutsu["data"] self.upload_artifact_raw(id, "traceback.log", bytes(report.longreprtext, "utf8")) data["metadata"]["short_tb"] = short_tb data["metadata"]["exception_name"] = call.excinfo.type.__name__ report._ibutsu["data"] = data def pytest_runtest_logreport(self, report): if not hasattr(report, "_ibutsu"): return if hasattr(report, "wasxfail"): xfail = True else: xfail = False data = report._ibutsu["data"] data["metadata"]["user_properties"] = {key: value for key, value in report.user_properties} data["metadata"]["statuses"][report.when] = (report.outcome, xfail) data["metadata"]["durations"][report.when] = report.duration data["result"] = overall_test_status(data["metadata"]["statuses"]) if data["result"] == "skipped" and not data["metadata"].get("skip_reason"): reason = self.get_skip_reason(data, report) if reason: data["metadata"]["skip_reason"] = reason elif data["result"] == "xfailed": reason = self.get_xfail_reason(data, report) if reason: data["metadata"]["xfail_reason"] = reason else: reason = None if reason: classification = self.get_classification(reason) if classification: data["metadata"]["classification"] = classification data["duration"] = sum(v for v in data["metadata"]["durations"].values()) report._ibutsu["data"] = data def pytest_sessionfinish(self): self.stop_timer() self.update_run(duration=self.duration) @pytest.hookimpl(hookwrapper=True) def pytest_runtest_makereport(self, item, call): outcome = yield res = outcome.get_result() # will raise if outcome was exception res._ibutsu = item._ibutsu class IbutsuSender(IbutsuArchiver): """ An enhanced Ibutsu plugin that also sends Ibutsu results to an Ibutsu server """ def __init__(self, server_url, source=None, path=None, extra_data=None): self.server_url = server_url self._has_server_error = False self._server_error_tbs = [] self._sender_cache = [] config = Configuration() config.host = self.server_url # Only set the SSL CA cert if one of the environment variables is set for env_var in CA_BUNDLE_ENVS: if os.getenv(env_var, None): config.ssl_ca_cert = os.getenv(env_var) api_client = ApiClient(config) self.result_api = ResultApi(api_client) self.artifact_api = ArtifactApi(api_client) self.run_api = RunApi(api_client) self.health_api = HealthApi(api_client) super().__init__(source=source, path=path, extra_data=extra_data) def _make_call(self, api_method, *args, **kwargs): for res in self._sender_cache: if res.ready(): self._sender_cache.remove(res) try: retries = 0 while retries < MAX_CALL_RETRIES: try: out = api_method(*args, **kwargs) if "async_req" in kwargs: self._sender_cache.append(out) return out except (RemoteDisconnected, ProtocolError, BadStatusLine): retries += 1 raise TooManyRetriesError("Too many retries while trying to call API") except (MaxRetryError, ApiException, TooManyRetriesError) as e: self._has_server_error = self._has_server_error or True self._server_error_tbs.append(str(e)) return None def add_run(self, run=None): server_run = self._make_call(self.run_api.add_run, run=run) if server_run: run = server_run.to_dict() return super().add_run(run) def refresh_run(self): # This can safely completely override the underlying method, because it does nothing if not self.run_id: return server_run = self._make_call(self.run_api.get_run, self.run_id) if server_run: self.run = server_run.to_dict() def update_run(self, duration=0.0): super().update_run(duration) self._make_call(self.run_api.update_run, self.run["id"], run=self.run) def add_result(self, result): if not result.get("metadata"): result["metadata"] = {} result["metadata"].update(self.extra_data) server_result = self._make_call(self.result_api.add_result, result=result) if server_result: result.update(server_result.to_dict()) return super().add_result(result) def update_result(self, id, result): self._make_call(self.result_api.update_result, id, result=result, async_req=True) super().update_result(id, result) def upload_artifact(self, id_, filename, data, is_run=False): super().upload_artifact(id_, filename, data, is_run=is_run) file_size = os.stat(data).st_size if file_size < UPLOAD_LIMIT: with open(data, "rb") as file_content: try: if not file_content.closed: if is_run: # id_ is the run_id, we don't check the return_type because # artifact.to_dict() in the controller contains a None value self._make_call( self.artifact_api.upload_artifact, filename, file_content, run_id=id_, _check_return_type=False, ) else: # id_ is the result_id, we don't check the return_type because # artifact.to_dict() in the controller contains a None valued self._make_call( self.artifact_api.upload_artifact, filename, file_content, result_id=id_, _check_return_type=False, ) except ApiValueError: print(f"Uploading artifact '{filename}' failed as the file closed prematurely.") def output_msg(self): with open(".last-ibutsu-run-id", "w") as f: f.write(self.run_id) url = f"{self.frontend}/runs/{self.run_id}" with open(".last-ibutsu-run-url", "w") as f: f.write(url) if not self._has_server_error: print(f"Results can be viewed on: {url}") else: print( "There was an error while uploading results," " and not all results were uploaded to the server." ) print(f"All results were written to archive, partial results can be viewed on: {url}") super().output_msg() def shutdown(self): super().shutdown() print(f"Ibutsu client finishing up...({len(self._sender_cache)} tasks left)...") while self._sender_cache: for res in self._sender_cache: if res.ready(): self._sender_cache.remove(res) time.sleep(0.1) print("Cleanup complete") def pytest_addoption(parser): parser.addini("ibutsu_server", help="The Ibutsu server to connect to") parser.addini("ibutsu_source", help="The source of the test run") parser.addini("ibutsu_metadata", help="Extra metadata to include with the test results") parser.addini("ibutsu_project", help="Project ID or name") group = parser.getgroup("ibutsu") group.addoption( "--ibutsu", dest="ibutsu_server", action="store", metavar="URL", default=None, help="URL for the Ibutsu server", ) group.addoption( "--ibutsu-source", dest="ibutsu_source", action="store", metavar="SOURCE", default=None, help="set the source for the tests", ) group.addoption( "--ibutsu-data", dest="ibutsu_data", action="store", metavar="KEY=VALUE", nargs="*", help="extra metadata for the test result, key=value", ) group.addoption( "--ibutsu-project", dest="ibutsu_project", action="store", metavar="PROJECT", default=None, help="project id or name", ) @pytest.hookimpl(optionalhook=True) def pytest_configure_node(node): if not hasattr(node.config, "_ibutsu"): # If this plugin is not active return node.workerinput["run_id"] = node.config._ibutsu.run_id def pytest_configure(config): ibutsu_server = config.getoption("ibutsu_server", None) if config.getini("ibutsu_server"): ibutsu_server = config.getini("ibutsu_server") if not ibutsu_server: return ibutsu_source = config.getoption("ibutsu_source", None) if config.getini("ibutsu_source"): ibutsu_source = config.getini("ibutsu_source") ibutsu_data = parse_data_option(config.getoption("ibutsu_data", [])) ibutsu_project = config.getoption("ibutsu_project", None) if config.getini("ibutsu_project"): ibutsu_project = config.getini("ibutsu_project") if ibutsu_project: ibutsu_data.update({"project": ibutsu_project}) if ibutsu_server != "archive": try: print("Ibutsu server: {}".format(ibutsu_server)) if ibutsu_server.endswith("/"): ibutsu_server = ibutsu_server[:-1] if not ibutsu_server.endswith("/api"): ibutsu_server += "/api" ibutsu = IbutsuSender(ibutsu_server, ibutsu_source, extra_data=ibutsu_data) ibutsu.frontend = ibutsu.health_api.get_health_info().frontend except MaxRetryError: print("Connection failure in health check - switching to archiver") ibutsu = IbutsuArchiver(extra_data=ibutsu_data) except ApiException: print("Error in call to Ibutsu API") ibutsu = IbutsuArchiver(extra_data=ibutsu_data) else: ibutsu = IbutsuArchiver(extra_data=ibutsu_data) if config.pluginmanager.has_plugin("xdist"): if hasattr(config, "workerinput") and config.workerinput.get("run_id"): ibutsu.set_run_id(config.workerinput["run_id"]) else: ibutsu.set_run_id(ibutsu.get_run_id()) config._ibutsu = ibutsu config.pluginmanager.register(config._ibutsu) def pytest_collection_finish(session): if not hasattr(session.config, "_ibutsu"): # If this plugin is not active return ibutsu = session.config._ibutsu if not session.config.pluginmanager.has_plugin("xdist"): ibutsu.set_run_id(ibutsu.get_run_id()) ibutsu.start_timer() ibutsu.output_msg() def pytest_unconfigure(config): ibutsu_instance = getattr(config, "_ibutsu", None) if ibutsu_instance: del config._ibutsu config.pluginmanager.unregister(ibutsu_instance) ibutsu_instance.shutdown() if ibutsu_instance.run_id: ibutsu_instance.output_msg()
36.299202
100
0.584973
ace9c99fe2bbc4594722ce1f9b150120754e75c9
6,766
py
Python
software-defined-networks/Topo2_Proactive_Ryu.py
hasithsen/CSNE
30d0386186a6684207bc5cf9f75b3b13f8a5bbc8
[ "MIT" ]
null
null
null
software-defined-networks/Topo2_Proactive_Ryu.py
hasithsen/CSNE
30d0386186a6684207bc5cf9f75b3b13f8a5bbc8
[ "MIT" ]
null
null
null
software-defined-networks/Topo2_Proactive_Ryu.py
hasithsen/CSNE
30d0386186a6684207bc5cf9f75b3b13f8a5bbc8
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Implement (Ryu) proactive controller for below topology. [c1] /\ / \ / \ / \ [s1]--------[s2] /\ /\ [h1] [h2] [h3] [h4] [cX] - controller [sX] - switch [hX] - host """ from ryu.base import app_manager from ryu.controller.handler import set_ev_cls from ryu.ofproto import ofproto_v1_0 from ryu.topology.event import EventSwitchEnter, EventSwitchLeave __email__ = "i@hsen.tech" __date__ = "2020/5/29" s1_dpid = 1 # Hardcode s1 datapath ID according to Topo2 s2_dpid = 2 class Topo2ProactiveSwitch(app_manager.RyuApp): # Mark as compatible with only OpenFlow v1.0 OFP_VERSIONS = [ofproto_v1_0.OFP_VERSION] # Create a subclass of RyuApp def __init__(self, *args, **kwargs): super(Topo2ProactiveSwitch, self).__init__(*args, **kwargs) @set_ev_cls(EventSwitchEnter) # Fires when a switch connects to controller def _ev_switch_enter_handler(self, ev): global s1_dpid global s2_dpid print('Fired: %s' % ev) datapath = ev.switch.dp # Extract datapath entity from event info ofproto = datapath.ofproto parser = datapath.ofproto_parser dpid = datapath.id ofproto = datapath.ofproto # Forwarding rules for s1 if dpid == s1_dpid: # Flood ARP packets actions = [datapath.ofproto_parser.OFPActionOutput(ofproto.OFPP_FLOOD)] match = datapath.ofproto_parser.OFPMatch( dl_type = 0x0806) """ Ignore other matching params in_port= dl_dst= dl_src= """ mod = datapath.ofproto_parser.OFPFlowMod( datapath=datapath, match=match, cookie=0, command=ofproto.OFPFC_ADD, idle_timeout=0, hard_timeout=0, priority=1, # 1 instead of ofproto.OFP_DEFAULT_PRIORITY flags=ofproto.OFPFF_SEND_FLOW_REM, actions=actions) datapath.send_msg(mod) # If destination is 10.0.0.1, outport is 1 actions = [datapath.ofproto_parser.OFPActionOutput(1)] match = datapath.ofproto_parser.OFPMatch( dl_type = 0x0800, nw_dst = "10.0.0.1") mod = datapath.ofproto_parser.OFPFlowMod( datapath=datapath, match=match, cookie=0, command=ofproto.OFPFC_ADD, idle_timeout=0, hard_timeout=0, priority=10, flags=ofproto.OFPFF_SEND_FLOW_REM, actions=actions) datapath.send_msg(mod) # If destination is 10.0.0.2, outport is 2 actions = [datapath.ofproto_parser.OFPActionOutput(2)] match = datapath.ofproto_parser.OFPMatch( dl_type = 0x0800, nw_dst = "10.0.0.2") mod = datapath.ofproto_parser.OFPFlowMod( datapath=datapath, match=match, cookie=0, command=ofproto.OFPFC_ADD, idle_timeout=0, hard_timeout=0, priority=10, flags=ofproto.OFPFF_SEND_FLOW_REM, actions=actions) datapath.send_msg(mod) # If destination is 10.0.0.3, outport is 3 actions = [datapath.ofproto_parser.OFPActionOutput(3)] match = datapath.ofproto_parser.OFPMatch( dl_type = 0x0800, nw_dst = "10.0.0.3") mod = datapath.ofproto_parser.OFPFlowMod( datapath=datapath, match=match, cookie=0, command=ofproto.OFPFC_ADD, idle_timeout=0, hard_timeout=0, priority=10, flags=ofproto.OFPFF_SEND_FLOW_REM, actions=actions) datapath.send_msg(mod) # If destination is 10.0.0.4, outport is 3 actions = [datapath.ofproto_parser.OFPActionOutput(3)] match = datapath.ofproto_parser.OFPMatch( dl_type = 0x0800, nw_dst = "10.0.0.4") mod = datapath.ofproto_parser.OFPFlowMod( datapath=datapath, match=match, cookie=0, command=ofproto.OFPFC_ADD, idle_timeout=0, hard_timeout=0, priority=10, flags=ofproto.OFPFF_SEND_FLOW_REM, actions=actions) datapath.send_msg(mod) # Forwarding rules for s2 elif dpid == s2_dpid: # Flood ARP packets actions = [datapath.ofproto_parser.OFPActionOutput(ofproto.OFPP_FLOOD)] match = datapath.ofproto_parser.OFPMatch( dl_type = 0x0806) mod = datapath.ofproto_parser.OFPFlowMod( datapath=datapath, match=match, cookie=0, command=ofproto.OFPFC_ADD, idle_timeout=0, hard_timeout=0, priority=1, flags=ofproto.OFPFF_SEND_FLOW_REM, actions=actions) datapath.send_msg(mod) # If destination is 10.0.0.1, outport is 3 actions = [datapath.ofproto_parser.OFPActionOutput(3)] match = datapath.ofproto_parser.OFPMatch( dl_type = 0x0800, nw_dst = "10.0.0.1") mod = datapath.ofproto_parser.OFPFlowMod( datapath=datapath, match=match, cookie=0, command=ofproto.OFPFC_ADD, idle_timeout=0, hard_timeout=0, priority=10, flags=ofproto.OFPFF_SEND_FLOW_REM, actions=actions) datapath.send_msg(mod) # If destination is 10.0.0.2, outport is 3 actions = [datapath.ofproto_parser.OFPActionOutput(3)] match = datapath.ofproto_parser.OFPMatch( dl_type = 0x0800, nw_dst = "10.0.0.2") mod = datapath.ofproto_parser.OFPFlowMod( datapath=datapath, match=match, cookie=0, command=ofproto.OFPFC_ADD, idle_timeout=0, hard_timeout=0, priority=10, flags=ofproto.OFPFF_SEND_FLOW_REM, actions=actions) datapath.send_msg(mod) # If destination is 10.0.0.3, outport is 1 actions = [datapath.ofproto_parser.OFPActionOutput(1)] match = datapath.ofproto_parser.OFPMatch( dl_type = 0x0800, nw_dst = "10.0.0.3") mod = datapath.ofproto_parser.OFPFlowMod( datapath=datapath, match=match, cookie=0, command=ofproto.OFPFC_ADD, idle_timeout=0, hard_timeout=0, priority=10, flags=ofproto.OFPFF_SEND_FLOW_REM, actions=actions) datapath.send_msg(mod) # If destination is 10.0.0.4, outport is 2 actions = [datapath.ofproto_parser.OFPActionOutput(2)] match = datapath.ofproto_parser.OFPMatch( dl_type = 0x0800, nw_dst = "10.0.0.4") mod = datapath.ofproto_parser.OFPFlowMod( datapath=datapath, match=match, cookie=0, command=ofproto.OFPFC_ADD, idle_timeout=0, hard_timeout=0, priority=10, flags=ofproto.OFPFF_SEND_FLOW_REM, actions=actions) datapath.send_msg(mod)
27.616327
77
0.622524
ace9cb15e708f384fa7d5a0e92966249357c40be
3,203
py
Python
lint_po/main.py
himdel/lint-po
da0f76f4a43757016dec7231a00e269f28d1c667
[ "Apache-2.0" ]
4
2021-12-07T16:03:12.000Z
2021-12-15T13:58:59.000Z
lint_po/main.py
himdel/lint-po
da0f76f4a43757016dec7231a00e269f28d1c667
[ "Apache-2.0" ]
null
null
null
lint_po/main.py
himdel/lint-po
da0f76f4a43757016dec7231a00e269f28d1c667
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python3 import json import re from os import environ from sys import stderr import warnings # find any {num} {str} <num> </num> <num/> %(str)s REGEX = r'(\{(\w+|\d+)\})|(<\/?\d+\/?>)|(%(\(\w+\))?.)' # s.encode('utf-8').decode('unicode-escape') if only it worked with utf8 strings def unqqbackslash(s): return json.loads(s) # extract all vars from string - findall(REGEX).map((arr) => arr.compact.first) def extract(s): return [ [truthy for truthy in match if truthy][0] for match in re.findall(REGEX, s) ] def fail(msg, file, line): if environ.get('GITHUB_ACTIONS'): s = msg.replace("\r", "").replace("\n", "").replace('%', '%25') print(f"::error file={file},line={line}::{s}", file=stderr) return f" {msg}\n" def process_pair(msgid, msgstr, file, line): # handling eof while still in state 2; magic id, untranslated strings if not msgid or not msgstr: return True msgidvars = extract(msgid) msgstrvars = extract(msgstr) missing = set(msgidvars) - set(msgstrvars) extra = set(msgstrvars) - set(msgidvars) if len(missing) or len(extra): message = "" if len(missing): message += fail(f"Missing from msgstr: {', '.join(missing)}", file, line) if len(extra): message += fail(f"Unexpected in msgstr: {', '.join(extra)}", file, line) message += f" at {file}:{line}" print(f"Difference between msgid=\"{msgid}\" and msgstr=\"{msgstr}\":\n{message}\n", file=stderr) return False return True def process_file(filename, lines): errors = False state = 0 msgid = None msgstr = None msgstrlineno = 0 for lineno, line in enumerate(lines): if re.match(r'^#', line): continue line = line.strip() if state == 0: # expecting `msgid` if re.match(r'^$', line): continue if m := re.match(r'^msgid\s+(.*)$', line): msgid = unqqbackslash(m[1]) state = 1 continue warnings.warn(f"({state}) Unexpected input: {line}") errors = True elif state == 1: # expecting `msgstr`, or more bits of previous msgid if m := re.match(r'^msgstr\s+(.*)$', line): msgstr = unqqbackslash(m[1]) msgstrlineno = lineno + 1 state = 2 continue if re.match(r'^"', line): msgid += unqqbackslash(line) continue warnings.warn(f"({state}) Unexpected input: {line}") errors = True elif state == 2: # expecting newline, or more bits of previous msgstr if re.match(r'^$', line): if not process_pair(msgid, msgstr, filename, msgstrlineno): errors = True state = 0 msgid = None msgstr = None msgstrlineno = 0 continue if re.match(r'^"', line): msgstr += unqqbackslash(line) continue warnings.warn(f"({state}) Unexpected input: {line}") errors = True if not process_pair(msgid, msgstr, filename, msgstrlineno): errors = True return errors def main(files): errors = False for filename in files: lines = None with open(filename) as f: lines = f.read().splitlines() if process_file(filename, lines): errors = True return(1 if errors else 0)
25.023438
101
0.601311
ace9cb18fffd0c9df9b13edf5ead65bdd8570608
40,635
py
Python
python/mxnet/image/image.py
xudong-sun/mxnet
fe42d30d5885dd576cb871fd70594c53efce9b42
[ "Apache-2.0" ]
399
2017-05-30T05:12:48.000Z
2022-01-29T05:53:08.000Z
python/mxnet/image/image.py
greenpea0104/incubator-mxnet
fc9e70bf2d349ad4c6cb65ff3f0958e23a7410bf
[ "Apache-2.0" ]
58
2017-05-30T23:25:32.000Z
2019-11-18T09:30:54.000Z
python/mxnet/image/image.py
greenpea0104/incubator-mxnet
fc9e70bf2d349ad4c6cb65ff3f0958e23a7410bf
[ "Apache-2.0" ]
107
2017-05-30T05:53:22.000Z
2021-06-24T02:43:31.000Z
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=no-member, too-many-lines, redefined-builtin, protected-access, unused-import, invalid-name # pylint: disable=too-many-arguments, too-many-locals, no-name-in-module, too-many-branches, too-many-statements """Read individual image files and perform augmentations.""" from __future__ import absolute_import, print_function import os import random import logging import json import numpy as np try: import cv2 except ImportError: cv2 = None from ..base import numeric_types from .. import ndarray as nd from ..ndarray import _internal from ..ndarray._internal import _cvimresize as imresize from ..ndarray._internal import _cvcopyMakeBorder as copyMakeBorder from .. import io from .. import recordio def imread(filename, *args, **kwargs): """Read and decode an image to an NDArray. Note: `imread` uses OpenCV (not the CV2 Python library). MXNet must have been built with USE_OPENCV=1 for `imdecode` to work. Parameters ---------- filename : str Name of the image file to be loaded. flag : {0, 1}, default 1 1 for three channel color output. 0 for grayscale output. to_rgb : bool, default True True for RGB formatted output (MXNet default). False for BGR formatted output (OpenCV default). out : NDArray, optional Output buffer. Use `None` for automatic allocation. Returns ------- NDArray An `NDArray` containing the image. Example ------- >>> mx.img.imread("flower.jpg") <NDArray 224x224x3 @cpu(0)> Set `flag` parameter to 0 to get grayscale output >>> mx.img.imdecode("flower.jpg", flag=0) <NDArray 224x224x1 @cpu(0)> Set `to_rgb` parameter to 0 to get output in OpenCV format (BGR) >>> mx.img.imdecode(str_image, to_rgb=0) <NDArray 224x224x3 @cpu(0)> """ return _internal._cvimread(filename, *args, **kwargs) def imdecode(buf, *args, **kwargs): """Decode an image to an NDArray. Note: `imdecode` uses OpenCV (not the CV2 Python library). MXNet must have been built with USE_OPENCV=1 for `imdecode` to work. Parameters ---------- buf : str/bytes or numpy.ndarray Binary image data as string or numpy ndarray. flag : int, optional, default=1 1 for three channel color output. 0 for grayscale output. to_rgb : int, optional, default=1 1 for RGB formatted output (MXNet default). 0 for BGR formatted output (OpenCV default). out : NDArray, optional Output buffer. Use `None` for automatic allocation. Returns ------- NDArray An `NDArray` containing the image. Example ------- >>> with open("flower.jpg", 'rb') as fp: ... str_image = fp.read() ... >>> image = mx.img.imdecode(str_image) >>> image <NDArray 224x224x3 @cpu(0)> Set `flag` parameter to 0 to get grayscale output >>> with open("flower.jpg", 'rb') as fp: ... str_image = fp.read() ... >>> image = mx.img.imdecode(str_image, flag=0) >>> image <NDArray 224x224x1 @cpu(0)> Set `to_rgb` parameter to 0 to get output in OpenCV format (BGR) >>> with open("flower.jpg", 'rb') as fp: ... str_image = fp.read() ... >>> image = mx.img.imdecode(str_image, to_rgb=0) >>> image <NDArray 224x224x3 @cpu(0)> """ if not isinstance(buf, nd.NDArray): buf = nd.array(np.frombuffer(buf, dtype=np.uint8), dtype=np.uint8) return _internal._cvimdecode(buf, *args, **kwargs) def scale_down(src_size, size): """Scales down crop size if it's larger than image size. If width/height of the crop is larger than the width/height of the image, sets the width/height to the width/height of the image. Parameters ---------- src_size : tuple of int Size of the image in (width, height) format. size : tuple of int Size of the crop in (width, height) format. Returns ------- tuple of int A tuple containing the scaled crop size in (width, height) format. Example -------- >>> src_size = (640,480) >>> size = (720,120) >>> new_size = mx.img.scale_down(src_size, size) >>> new_size (640,106) """ w, h = size sw, sh = src_size if sh < h: w, h = float(w * sh) / h, sh if sw < w: w, h = sw, float(h * sw) / w return int(w), int(h) def _get_interp_method(interp, sizes=()): """Get the interpolation method for resize functions. The major purpose of this function is to wrap a random interp method selection and a auto-estimation method. Parameters ---------- interp : int interpolation method for all resizing operations Possible values: 0: Nearest Neighbors Interpolation. 1: Bilinear interpolation. 2: Area-based (resampling using pixel area relation). It may be a preferred method for image decimation, as it gives moire-free results. But when the image is zoomed, it is similar to the Nearest Neighbors method. (used by default). 3: Bicubic interpolation over 4x4 pixel neighborhood. 4: Lanczos interpolation over 8x8 pixel neighborhood. 9: Cubic for enlarge, area for shrink, bilinear for others 10: Random select from interpolation method metioned above. Note: When shrinking an image, it will generally look best with AREA-based interpolation, whereas, when enlarging an image, it will generally look best with Bicubic (slow) or Bilinear (faster but still looks OK). More details can be found in the documentation of OpenCV, please refer to http://docs.opencv.org/master/da/d54/group__imgproc__transform.html. sizes : tuple of int (old_height, old_width, new_height, new_width), if None provided, auto(9) will return Area(2) anyway. Returns ------- int interp method from 0 to 4 """ if interp == 9: if sizes: assert len(sizes) == 4 oh, ow, nh, nw = sizes if nh > oh and nw > ow: return 2 elif nh < oh and nw < ow: return 3 else: return 1 else: return 2 if interp == 10: return random.randint(0, 4) if interp not in (0, 1, 2, 3, 4): raise ValueError('Unknown interp method %d' % interp) return interp def resize_short(src, size, interp=2): """Resizes shorter edge to size. Note: `resize_short` uses OpenCV (not the CV2 Python library). MXNet must have been built with OpenCV for `resize_short` to work. Resizes the original image by setting the shorter edge to size and setting the longer edge accordingly. Resizing function is called from OpenCV. Parameters ---------- src : NDArray The original image. size : int The length to be set for the shorter edge. interp : int, optional, default=2 Interpolation method used for resizing the image. Possible values: 0: Nearest Neighbors Interpolation. 1: Bilinear interpolation. 2: Area-based (resampling using pixel area relation). It may be a preferred method for image decimation, as it gives moire-free results. But when the image is zoomed, it is similar to the Nearest Neighbors method. (used by default). 3: Bicubic interpolation over 4x4 pixel neighborhood. 4: Lanczos interpolation over 8x8 pixel neighborhood. 9: Cubic for enlarge, area for shrink, bilinear for others 10: Random select from interpolation method metioned above. Note: When shrinking an image, it will generally look best with AREA-based interpolation, whereas, when enlarging an image, it will generally look best with Bicubic (slow) or Bilinear (faster but still looks OK). More details can be found in the documentation of OpenCV, please refer to http://docs.opencv.org/master/da/d54/group__imgproc__transform.html. Returns ------- NDArray An 'NDArray' containing the resized image. Example ------- >>> with open("flower.jpeg", 'rb') as fp: ... str_image = fp.read() ... >>> image = mx.img.imdecode(str_image) >>> image <NDArray 2321x3482x3 @cpu(0)> >>> size = 640 >>> new_image = mx.img.resize_short(image, size) >>> new_image <NDArray 2321x3482x3 @cpu(0)> """ h, w, _ = src.shape if h > w: new_h, new_w = size * h // w, size else: new_h, new_w = size, size * w // h return imresize(src, new_w, new_h, interp=_get_interp_method(interp, (h, w, new_h, new_w))) def fixed_crop(src, x0, y0, w, h, size=None, interp=2): """Crop src at fixed location, and (optionally) resize it to size. Parameters ---------- src : NDArray Input image x0 : int Left boundary of the cropping area y0 : int Top boundary of the cropping area w : int Width of the cropping area h : int Height of the cropping area size : tuple of (w, h) Optional, resize to new size after cropping interp : int, optional, default=2 Interpolation method. See resize_short for details. Returns ------- NDArray An `NDArray` containing the cropped image. """ out = nd.crop(src, begin=(y0, x0, 0), end=(y0 + h, x0 + w, int(src.shape[2]))) if size is not None and (w, h) != size: sizes = (h, w, size[1], size[0]) out = imresize(out, *size, interp=_get_interp_method(interp, sizes)) return out def random_crop(src, size, interp=2): """Randomly crop `src` with `size` (width, height). Upsample result if `src` is smaller than `size`. Parameters ---------- src: Source image `NDArray` size: Size of the crop formatted as (width, height). If the `size` is larger than the image, then the source image is upsampled to `size` and returned. interp: int, optional, default=2 Interpolation method. See resize_short for details. Returns ------- NDArray An `NDArray` containing the cropped image. Tuple A tuple (x, y, width, height) where (x, y) is top-left position of the crop in the original image and (width, height) are the dimensions of the cropped image. Example ------- >>> im = mx.nd.array(cv2.imread("flower.jpg")) >>> cropped_im, rect = mx.image.random_crop(im, (100, 100)) >>> print cropped_im <NDArray 100x100x1 @cpu(0)> >>> print rect (20, 21, 100, 100) """ h, w, _ = src.shape new_w, new_h = scale_down((w, h), size) x0 = random.randint(0, w - new_w) y0 = random.randint(0, h - new_h) out = fixed_crop(src, x0, y0, new_w, new_h, size, interp) return out, (x0, y0, new_w, new_h) def center_crop(src, size, interp=2): """Crops the image `src` to the given `size` by trimming on all four sides and preserving the center of the image. Upsamples if `src` is smaller than `size`. .. note:: This requires MXNet to be compiled with USE_OPENCV. Parameters ---------- src : NDArray Binary source image data. size : list or tuple of int The desired output image size. interp : int, optional, default=2 Interpolation method. See resize_short for details. Returns ------- NDArray The cropped image. Tuple (x, y, width, height) where x, y are the positions of the crop in the original image and width, height the dimensions of the crop. Example ------- >>> with open("flower.jpg", 'rb') as fp: ... str_image = fp.read() ... >>> image = mx.image.imdecode(str_image) >>> image <NDArray 2321x3482x3 @cpu(0)> >>> cropped_image, (x, y, width, height) = mx.image.center_crop(image, (1000, 500)) >>> cropped_image <NDArray 500x1000x3 @cpu(0)> >>> x, y, width, height (1241, 910, 1000, 500) """ h, w, _ = src.shape new_w, new_h = scale_down((w, h), size) x0 = int((w - new_w) / 2) y0 = int((h - new_h) / 2) out = fixed_crop(src, x0, y0, new_w, new_h, size, interp) return out, (x0, y0, new_w, new_h) def color_normalize(src, mean, std=None): """Normalize src with mean and std. Parameters ---------- src : NDArray Input image mean : NDArray RGB mean to be subtracted std : NDArray RGB standard deviation to be divided Returns ------- NDArray An `NDArray` containing the normalized image. """ if mean is not None: src -= mean if std is not None: src /= std return src def random_size_crop(src, size, min_area, ratio, interp=2): """Randomly crop src with size. Randomize area and aspect ratio. Parameters ---------- src : NDArray Input image size : tuple of (int, int) Size of the crop formatted as (width, height). min_area : int Minimum area to be maintained after cropping ratio : tuple of (float, float) Aspect ratio range as (min_aspect_ratio, max_aspect_ratio) interp: int, optional, default=2 Interpolation method. See resize_short for details. Returns ------- NDArray An `NDArray` containing the cropped image. Tuple A tuple (x, y, width, height) where (x, y) is top-left position of the crop in the original image and (width, height) are the dimensions of the cropped image. """ h, w, _ = src.shape area = h * w for _ in range(10): target_area = random.uniform(min_area, 1.0) * area new_ratio = random.uniform(*ratio) new_w = int(round(np.sqrt(target_area * new_ratio))) new_h = int(round(np.sqrt(target_area / new_ratio))) if random.random() < 0.5: new_h, new_w = new_w, new_h if new_w <= w and new_h <= h: x0 = random.randint(0, w - new_w) y0 = random.randint(0, h - new_h) out = fixed_crop(src, x0, y0, new_w, new_h, size, interp) return out, (x0, y0, new_w, new_h) # fall back to center_crop return center_crop(src, size, interp) class Augmenter(object): """Image Augmenter base class""" def __init__(self, **kwargs): self._kwargs = kwargs for k, v in self._kwargs.items(): if isinstance(v, nd.NDArray): v = v.asnumpy() if isinstance(v, np.ndarray): v = v.tolist() self._kwargs[k] = v def dumps(self): """Saves the Augmenter to string Returns ------- str JSON formatted string that describes the Augmenter. """ return json.dumps([self.__class__.__name__.lower(), self._kwargs]) def __call__(self, src): """Abstract implementation body""" raise NotImplementedError("Must override implementation.") class SequentialAug(Augmenter): """Composing a sequential augmenter list. Parameters ---------- ts : list of augmenters A series of augmenters to be applied in sequential order. """ def __init__(self, ts): super(SequentialAug, self).__init__() self.ts = ts def dumps(self): """Override the default to avoid duplicate dump.""" return [self.__class__.__name__.lower(), [x.dumps() for x in self.ts]] def __call__(self, src): """Augmenter body""" for aug in self.ts: src = aug(src) return src class ResizeAug(Augmenter): """Make resize shorter edge to size augmenter. Parameters ---------- size : int The length to be set for the shorter edge. interp : int, optional, default=2 Interpolation method. See resize_short for details. """ def __init__(self, size, interp=2): super(ResizeAug, self).__init__(size=size, interp=interp) self.size = size self.interp = interp def __call__(self, src): """Augmenter body""" return resize_short(src, self.size, self.interp) class ForceResizeAug(Augmenter): """Force resize to size regardless of aspect ratio Parameters ---------- size : tuple of (int, int) The desired size as in (width, height) interp : int, optional, default=2 Interpolation method. See resize_short for details. """ def __init__(self, size, interp=2): super(ForceResizeAug, self).__init__(size=size, interp=interp) self.size = size self.interp = interp def __call__(self, src): """Augmenter body""" sizes = (src.shape[0], src.shape[1], self.size[1], self.size[0]) return imresize(src, *self.size, interp=_get_interp_method(self.interp, sizes)) class RandomCropAug(Augmenter): """Make random crop augmenter Parameters ---------- size : int The length to be set for the shorter edge. interp : int, optional, default=2 Interpolation method. See resize_short for details. """ def __init__(self, size, interp=2): super(RandomCropAug, self).__init__(size=size, interp=interp) self.size = size self.interp = interp def __call__(self, src): """Augmenter body""" return random_crop(src, self.size, self.interp)[0] class RandomSizedCropAug(Augmenter): """Make random crop with random resizing and random aspect ratio jitter augmenter. Parameters ---------- size : tuple of (int, int) Size of the crop formatted as (width, height). min_area : int Minimum area to be maintained after cropping ratio : tuple of (float, float) Aspect ratio range as (min_aspect_ratio, max_aspect_ratio) interp: int, optional, default=2 Interpolation method. See resize_short for details. """ def __init__(self, size, min_area, ratio, interp=2): super(RandomSizedCropAug, self).__init__(size=size, min_area=min_area, ratio=ratio, interp=interp) self.size = size self.min_area = min_area self.ratio = ratio self.interp = interp def __call__(self, src): """Augmenter body""" return random_size_crop(src, self.size, self.min_area, self.ratio, self.interp)[0] class CenterCropAug(Augmenter): """Make center crop augmenter. Parameters ---------- size : list or tuple of int The desired output image size. interp : int, optional, default=2 Interpolation method. See resize_short for details. """ def __init__(self, size, interp=2): super(CenterCropAug, self).__init__(size=size, interp=interp) self.size = size self.interp = interp def __call__(self, src): """Augmenter body""" return center_crop(src, self.size, self.interp)[0] class RandomOrderAug(Augmenter): """Apply list of augmenters in random order Parameters ---------- ts : list of augmenters A series of augmenters to be applied in random order """ def __init__(self, ts): super(RandomOrderAug, self).__init__() self.ts = ts def dumps(self): """Override the default to avoid duplicate dump.""" return [self.__class__.__name__.lower(), [x.dumps() for x in self.ts]] def __call__(self, src): """Augmenter body""" random.shuffle(self.ts) for t in self.ts: src = t(src) return src class BrightnessJitterAug(Augmenter): """Random brightness jitter augmentation. Parameters ---------- brightness : float The brightness jitter ratio range, [0, 1] """ def __init__(self, brightness): super(BrightnessJitterAug, self).__init__(brightness=brightness) self.brightness = brightness def __call__(self, src): """Augmenter body""" alpha = 1.0 + random.uniform(-self.brightness, self.brightness) src *= alpha return src class ContrastJitterAug(Augmenter): """Random contrast jitter augmentation. Parameters ---------- contrast : float The contrast jitter ratio range, [0, 1] """ def __init__(self, contrast): super(ContrastJitterAug, self).__init__(contrast=contrast) self.contrast = contrast self.coef = nd.array([[[0.299, 0.587, 0.114]]]) def __call__(self, src): """Augmenter body""" alpha = 1.0 + random.uniform(-self.contrast, self.contrast) gray = src * self.coef gray = (3.0 * (1.0 - alpha) / gray.size) * nd.sum(gray) src *= alpha src += gray return src class SaturationJitterAug(Augmenter): """Random saturation jitter augmentation. Parameters ---------- saturation : float The saturation jitter ratio range, [0, 1] """ def __init__(self, saturation): super(SaturationJitterAug, self).__init__(saturation=saturation) self.saturation = saturation self.coef = nd.array([[[0.299, 0.587, 0.114]]]) def __call__(self, src): """Augmenter body""" alpha = 1.0 + random.uniform(-self.saturation, self.saturation) gray = src * self.coef gray = nd.sum(gray, axis=2, keepdims=True) gray *= (1.0 - alpha) src *= alpha src += gray return src class HueJitterAug(Augmenter): """Random hue jitter augmentation. Parameters ---------- hue : float The hue jitter ratio range, [0, 1] """ def __init__(self, hue): super(HueJitterAug, self).__init__(hue=hue) self.hue = hue self.tyiq = np.array([[0.299, 0.587, 0.114], [0.596, -0.274, -0.321], [0.211, -0.523, 0.311]]) self.ityiq = np.array([[1.0, 0.956, 0.621], [1.0, -0.272, -0.647], [1.0, -1.107, 1.705]]) def __call__(self, src): """Augmenter body. Using approximate linear transfomation described in: https://beesbuzz.biz/code/hsv_color_transforms.php """ alpha = random.uniform(-self.hue, self.hue) u = np.cos(alpha * np.pi) w = np.sin(alpha * np.pi) bt = np.array([[1.0, 0.0, 0.0], [0.0, u, -w], [0.0, w, u]]) t = np.dot(np.dot(self.ityiq, bt), self.tyiq).T src = nd.dot(src, nd.array(t)) return src class ColorJitterAug(RandomOrderAug): """Apply random brightness, contrast and saturation jitter in random order. Parameters ---------- brightness : float The brightness jitter ratio range, [0, 1] contrast : float The contrast jitter ratio range, [0, 1] saturation : float The saturation jitter ratio range, [0, 1] """ def __init__(self, brightness, contrast, saturation): ts = [] if brightness > 0: ts.append(BrightnessJitterAug(brightness)) if contrast > 0: ts.append(ContrastJitterAug(contrast)) if saturation > 0: ts.append(SaturationJitterAug(saturation)) super(ColorJitterAug, self).__init__(ts) class LightingAug(Augmenter): """Add PCA based noise. Parameters ---------- alphastd : float Noise level eigval : 3x1 np.array Eigen values eigvec : 3x3 np.array Eigen vectors """ def __init__(self, alphastd, eigval, eigvec): super(LightingAug, self).__init__(alphastd=alphastd, eigval=eigval, eigvec=eigvec) self.alphastd = alphastd self.eigval = eigval self.eigvec = eigvec def __call__(self, src): """Augmenter body""" alpha = np.random.normal(0, self.alphastd, size=(3,)) rgb = np.dot(self.eigvec * alpha, self.eigval) src += nd.array(rgb) return src class ColorNormalizeAug(Augmenter): """Mean and std normalization. Parameters ---------- mean : NDArray RGB mean to be subtracted std : NDArray RGB standard deviation to be divided """ def __init__(self, mean, std): super(ColorNormalizeAug, self).__init__(mean=mean, std=std) self.mean = nd.array(mean) if mean is not None else None self.std = nd.array(std) if std is not None else None def __call__(self, src): """Augmenter body""" return color_normalize(src, self.mean, self.std) class RandomGrayAug(Augmenter): """Randomly convert to gray image. Parameters ---------- p : float Probability to convert to grayscale """ def __init__(self, p): super(RandomGrayAug, self).__init__(p=p) self.p = p self.mat = nd.array([[0.21, 0.21, 0.21], [0.72, 0.72, 0.72], [0.07, 0.07, 0.07]]) def __call__(self, src): """Augmenter body""" if random.random() < self.p: src = nd.dot(src, self.mat) return src class HorizontalFlipAug(Augmenter): """Random horizontal flip. Parameters ---------- p : float Probability to flip image horizontally """ def __init__(self, p): super(HorizontalFlipAug, self).__init__(p=p) self.p = p def __call__(self, src): """Augmenter body""" if random.random() < self.p: src = nd.flip(src, axis=1) return src class CastAug(Augmenter): """Cast to float32""" def __init__(self, typ='float32'): super(CastAug, self).__init__(type=typ) self.typ = typ def __call__(self, src): """Augmenter body""" src = src.astype(self.typ) return src def CreateAugmenter(data_shape, resize=0, rand_crop=False, rand_resize=False, rand_mirror=False, mean=None, std=None, brightness=0, contrast=0, saturation=0, hue=0, pca_noise=0, rand_gray=0, inter_method=2): """Creates an augmenter list. Parameters ---------- data_shape : tuple of int Shape for output data resize : int Resize shorter edge if larger than 0 at the begining rand_crop : bool Whether to enable random cropping other than center crop rand_resize : bool Whether to enable random sized cropping, require rand_crop to be enabled rand_gray : float [0, 1], probability to convert to grayscale for all channels, the number of channels will not be reduced to 1 rand_mirror : bool Whether to apply horizontal flip to image with probability 0.5 mean : np.ndarray or None Mean pixel values for [r, g, b] std : np.ndarray or None Standard deviations for [r, g, b] brightness : float Brightness jittering range (percent) contrast : float Contrast jittering range (percent) saturation : float Saturation jittering range (percent) hue : float Hue jittering range (percent) pca_noise : float Pca noise level (percent) inter_method : int, default=2(Area-based) Interpolation method for all resizing operations Possible values: 0: Nearest Neighbors Interpolation. 1: Bilinear interpolation. 2: Area-based (resampling using pixel area relation). It may be a preferred method for image decimation, as it gives moire-free results. But when the image is zoomed, it is similar to the Nearest Neighbors method. (used by default). 3: Bicubic interpolation over 4x4 pixel neighborhood. 4: Lanczos interpolation over 8x8 pixel neighborhood. 9: Cubic for enlarge, area for shrink, bilinear for others 10: Random select from interpolation method metioned above. Note: When shrinking an image, it will generally look best with AREA-based interpolation, whereas, when enlarging an image, it will generally look best with Bicubic (slow) or Bilinear (faster but still looks OK). Examples -------- >>> # An example of creating multiple augmenters >>> augs = mx.image.CreateAugmenter(data_shape=(3, 300, 300), rand_mirror=True, ... mean=True, brightness=0.125, contrast=0.125, rand_gray=0.05, ... saturation=0.125, pca_noise=0.05, inter_method=10) >>> # dump the details >>> for aug in augs: ... aug.dumps() """ auglist = [] if resize > 0: auglist.append(ResizeAug(resize, inter_method)) crop_size = (data_shape[2], data_shape[1]) if rand_resize: assert rand_crop auglist.append(RandomSizedCropAug(crop_size, 0.08, (3.0 / 4.0, 4.0 / 3.0), inter_method)) elif rand_crop: auglist.append(RandomCropAug(crop_size, inter_method)) else: auglist.append(CenterCropAug(crop_size, inter_method)) if rand_mirror: auglist.append(HorizontalFlipAug(0.5)) auglist.append(CastAug()) if brightness or contrast or saturation: auglist.append(ColorJitterAug(brightness, contrast, saturation)) if hue: auglist.append(HueJitterAug(hue)) if pca_noise > 0: eigval = np.array([55.46, 4.794, 1.148]) eigvec = np.array([[-0.5675, 0.7192, 0.4009], [-0.5808, -0.0045, -0.8140], [-0.5836, -0.6948, 0.4203]]) auglist.append(LightingAug(pca_noise, eigval, eigvec)) if rand_gray > 0: auglist.append(RandomGrayAug(rand_gray)) if mean is True: mean = np.array([123.68, 116.28, 103.53]) elif mean is not None: assert isinstance(mean, np.ndarray) and mean.shape[0] in [1, 3] if std is True: std = np.array([58.395, 57.12, 57.375]) elif std is not None: assert isinstance(std, np.ndarray) and std.shape[0] in [1, 3] if mean is not None or std is not None: auglist.append(ColorNormalizeAug(mean, std)) return auglist class ImageIter(io.DataIter): """Image data iterator with a large number of augmentation choices. This iterator supports reading from both .rec files and raw image files. To load input images from .rec files, use `path_imgrec` parameter and to load from raw image files, use `path_imglist` and `path_root` parameters. To use data partition (for distributed training) or shuffling, specify `path_imgidx` parameter. Parameters ---------- batch_size : int Number of examples per batch. data_shape : tuple Data shape in (channels, height, width) format. For now, only RGB image with 3 channels is supported. label_width : int, optional Number of labels per example. The default label width is 1. path_imgrec : str Path to image record file (.rec). Created with tools/im2rec.py or bin/im2rec. path_imglist : str Path to image list (.lst). Created with tools/im2rec.py or with custom script. Format: Tab separated record of index, one or more labels and relative_path_from_root. imglist: list A list of images with the label(s). Each item is a list [imagelabel: float or list of float, imgpath]. path_root : str Root folder of image files. path_imgidx : str Path to image index file. Needed for partition and shuffling when using .rec source. shuffle : bool Whether to shuffle all images at the start of each iteration or not. Can be slow for HDD. part_index : int Partition index. num_parts : int Total number of partitions. data_name : str Data name for provided symbols. label_name : str Label name for provided symbols. kwargs : ... More arguments for creating augmenter. See mx.image.CreateAugmenter. """ def __init__(self, batch_size, data_shape, label_width=1, path_imgrec=None, path_imglist=None, path_root=None, path_imgidx=None, shuffle=False, part_index=0, num_parts=1, aug_list=None, imglist=None, data_name='data', label_name='softmax_label', **kwargs): super(ImageIter, self).__init__() assert path_imgrec or path_imglist or (isinstance(imglist, list)) num_threads = os.environ.get('MXNET_CPU_WORKER_NTHREADS', 1) logging.info('Using %s threads for decoding...', str(num_threads)) logging.info('Set enviroment variable MXNET_CPU_WORKER_NTHREADS to a' ' larger number to use more threads.') class_name = self.__class__.__name__ if path_imgrec: logging.info('%s: loading recordio %s...', class_name, path_imgrec) if path_imgidx: self.imgrec = recordio.MXIndexedRecordIO(path_imgidx, path_imgrec, 'r') # pylint: disable=redefined-variable-type self.imgidx = list(self.imgrec.keys) else: self.imgrec = recordio.MXRecordIO(path_imgrec, 'r') # pylint: disable=redefined-variable-type self.imgidx = None else: self.imgrec = None if path_imglist: logging.info('%s: loading image list %s...', class_name, path_imglist) with open(path_imglist) as fin: imglist = {} imgkeys = [] for line in iter(fin.readline, ''): line = line.strip().split('\t') label = nd.array([float(i) for i in line[1:-1]]) key = int(line[0]) imglist[key] = (label, line[-1]) imgkeys.append(key) self.imglist = imglist elif isinstance(imglist, list): logging.info('%s: loading image list...', class_name) result = {} imgkeys = [] index = 1 for img in imglist: key = str(index) # pylint: disable=redefined-variable-type index += 1 if len(img) > 2: label = nd.array(img[:-1]) elif isinstance(img[0], numeric_types): label = nd.array([img[0]]) else: label = nd.array(img[0]) result[key] = (label, img[-1]) imgkeys.append(str(key)) self.imglist = result else: self.imglist = None self.path_root = path_root self.check_data_shape(data_shape) self.provide_data = [(data_name, (batch_size,) + data_shape)] if label_width > 1: self.provide_label = [(label_name, (batch_size, label_width))] else: self.provide_label = [(label_name, (batch_size,))] self.batch_size = batch_size self.data_shape = data_shape self.label_width = label_width self.shuffle = shuffle if self.imgrec is None: self.seq = imgkeys elif shuffle or num_parts > 1: assert self.imgidx is not None self.seq = self.imgidx else: self.seq = None if num_parts > 1: assert part_index < num_parts N = len(self.seq) C = N // num_parts self.seq = self.seq[part_index * C:(part_index + 1) * C] if aug_list is None: self.auglist = CreateAugmenter(data_shape, **kwargs) else: self.auglist = aug_list self.cur = 0 self.reset() def reset(self): """Resets the iterator to the beginning of the data.""" if self.shuffle: random.shuffle(self.seq) if self.imgrec is not None: self.imgrec.reset() self.cur = 0 def next_sample(self): """Helper function for reading in next sample.""" if self.seq is not None: if self.cur >= len(self.seq): raise StopIteration idx = self.seq[self.cur] self.cur += 1 if self.imgrec is not None: s = self.imgrec.read_idx(idx) header, img = recordio.unpack(s) if self.imglist is None: return header.label, img else: return self.imglist[idx][0], img else: label, fname = self.imglist[idx] return label, self.read_image(fname) else: s = self.imgrec.read() if s is None: raise StopIteration header, img = recordio.unpack(s) return header.label, img def next(self): """Returns the next batch of data.""" batch_size = self.batch_size c, h, w = self.data_shape batch_data = nd.empty((batch_size, c, h, w)) batch_label = nd.empty(self.provide_label[0][1]) i = 0 try: while i < batch_size: label, s = self.next_sample() data = self.imdecode(s) try: self.check_valid_image(data) except RuntimeError as e: logging.debug('Invalid image, skipping: %s', str(e)) continue data = self.augmentation_transform(data) assert i < batch_size, 'Batch size must be multiples of augmenter output length' batch_data[i] = self.postprocess_data(data) batch_label[i] = label i += 1 except StopIteration: if not i: raise StopIteration return io.DataBatch([batch_data], [batch_label], batch_size - i) def check_data_shape(self, data_shape): """Checks if the input data shape is valid""" if not len(data_shape) == 3: raise ValueError('data_shape should have length 3, with dimensions CxHxW') if not data_shape[0] == 3: raise ValueError('This iterator expects inputs to have 3 channels.') def check_valid_image(self, data): """Checks if the input data is valid""" if len(data[0].shape) == 0: raise RuntimeError('Data shape is wrong') def imdecode(self, s): """Decodes a string or byte string to an NDArray. See mx.img.imdecode for more details.""" def locate(): """Locate the image file/index if decode fails.""" if self.seq is not None: idx = self.seq[self.cur - 1] else: idx = self.cur - 1 if self.imglist is not None: _, fname = self.imglist[idx] msg = "filename: {}".format(fname) else: msg = "index: {}".format(idx) return "Broken image " + msg try: img = imdecode(s) except Exception as e: raise RuntimeError("{}, {}".format(locate(), e)) return img def read_image(self, fname): """Reads an input image `fname` and returns the decoded raw bytes. Example usage: ---------- >>> dataIter.read_image('Face.jpg') # returns decoded raw bytes. """ with open(os.path.join(self.path_root, fname), 'rb') as fin: img = fin.read() return img def augmentation_transform(self, data): """Transforms input data with specified augmentation.""" for aug in self.auglist: data = aug(data) return data def postprocess_data(self, datum): """Final postprocessing step before image is loaded into the batch.""" return nd.transpose(datum, axes=(2, 0, 1))
32.638554
130
0.598499
ace9cb32805212b7f01ca5f707a83285a1812171
8,157
py
Python
ckan/controllers/revision.py
GlobalMaksimum/ckan
bdba078d26d485e75554ba9570e292ec480eb9e4
[ "Apache-2.0" ]
1
2019-11-03T11:35:38.000Z
2019-11-03T11:35:38.000Z
ckan/controllers/revision.py
GlobalMaksimum/ckan
bdba078d26d485e75554ba9570e292ec480eb9e4
[ "Apache-2.0" ]
7
2021-02-02T22:03:03.000Z
2021-06-22T02:13:00.000Z
ckan/controllers/revision.py
GlobalMaksimum/ckan
bdba078d26d485e75554ba9570e292ec480eb9e4
[ "Apache-2.0" ]
3
2019-09-11T10:04:59.000Z
2020-01-30T15:55:50.000Z
# encoding: utf-8 from datetime import datetime, timedelta from pylons.i18n import get_lang from six import text_type import ckan.logic as logic import ckan.lib.base as base import ckan.model as model import ckan.lib.helpers as h from ckan.common import _, c, request class RevisionController(base.BaseController): def __before__(self, action, **env): base.BaseController.__before__(self, action, **env) context = {'model': model, 'user': c.user, 'auth_user_obj': c.userobj} if c.user: try: logic.check_access('revision_change_state', context) c.revision_change_state_allowed = True except logic.NotAuthorized: c.revision_change_state_allowed = False else: c.revision_change_state_allowed = False try: logic.check_access('site_read', context) except logic.NotAuthorized: base.abort(403, _('Not authorized to see this page')) def index(self): return self.list() def list(self): format = request.params.get('format', '') if format == 'atom': # Generate and return Atom 1.0 document. from webhelpers.feedgenerator import Atom1Feed feed = Atom1Feed( title=_(u'CKAN Repository Revision History'), link=h.url_for(controller='revision', action='list', id=''), description=_(u'Recent changes to the CKAN repository.'), language=text_type(get_lang()), ) # TODO: make this configurable? # we do not want the system to fall over! maxresults = 200 try: dayHorizon = int(request.params.get('days', 5)) except: dayHorizon = 5 ourtimedelta = timedelta(days=-dayHorizon) since_when = datetime.now() + ourtimedelta revision_query = model.repo.history() revision_query = revision_query.filter( model.Revision.timestamp >= since_when).filter( model.Revision.id != None) revision_query = revision_query.limit(maxresults) for revision in revision_query: package_indications = [] revision_changes = model.repo.list_changes(revision) resource_revisions = revision_changes[model.Resource] package_extra_revisions = revision_changes[model.PackageExtra] for package in revision.packages: if not package: # package is None sometimes - I don't know why, # but in the meantime while that is fixed, # avoid an exception here continue if package.private: continue number = len(package.all_revisions) package_revision = None count = 0 for pr in package.all_revisions: count += 1 if pr.revision.id == revision.id: package_revision = pr break if package_revision and package_revision.state == \ model.State.DELETED: transition = 'deleted' elif package_revision and count == number: transition = 'created' else: transition = 'updated' for resource_revision in resource_revisions: if resource_revision.package_id == package.id: transition += ':resources' break for package_extra_revision in package_extra_revisions: if package_extra_revision.package_id == \ package.id: if package_extra_revision.key == \ 'date_updated': transition += ':date_updated' break indication = "%s:%s" % (package.name, transition) package_indications.append(indication) pkgs = u'[%s]' % ' '.join(package_indications) item_title = u'r%s ' % (revision.id) item_title += pkgs if revision.message: item_title += ': %s' % (revision.message or '') item_link = h.url_for(controller='revision', action='read', id=revision.id) item_description = _('Datasets affected: %s.\n') % pkgs item_description += '%s' % (revision.message or '') item_author_name = revision.author item_pubdate = revision.timestamp feed.add_item( title=item_title, link=item_link, description=item_description, author_name=item_author_name, pubdate=item_pubdate, ) feed.content_type = 'application/atom+xml' return feed.writeString('utf-8') else: query = model.Session.query(model.Revision) c.page = h.Page( collection=query, page=h.get_page_number(request.params), url=h.pager_url, items_per_page=20 ) return base.render('revision/list.html') def read(self, id=None): if id is None: base.abort(404) c.revision = model.Session.query(model.Revision).get(id) if c.revision is None: base.abort(404) pkgs = model.Session.query(model.PackageRevision).\ filter_by(revision=c.revision) c.packages = [pkg.continuity for pkg in pkgs if not pkg.private] pkgtags = model.Session.query(model.PackageTagRevision).\ filter_by(revision=c.revision) c.pkgtags = [pkgtag.continuity for pkgtag in pkgtags if not pkgtag.package.private] grps = model.Session.query(model.GroupRevision).\ filter_by(revision=c.revision) c.groups = [grp.continuity for grp in grps] return base.render('revision/read.html') def diff(self, id=None): if 'diff' not in request.params or 'oldid' not in request.params: base.abort(400) c.revision_from = model.Session.query(model.Revision).get( request.params.getone('oldid')) c.revision_to = model.Session.query(model.Revision).get( request.params.getone('diff')) c.diff_entity = request.params.get('diff_entity') if c.diff_entity == 'package': c.pkg = model.Package.by_name(id) diff = c.pkg.diff(c.revision_to, c.revision_from) elif c.diff_entity == 'group': c.group = model.Group.by_name(id) diff = c.group.diff(c.revision_to, c.revision_from) else: base.abort(400) c.diff = diff.items() c.diff.sort() return base.render('revision/diff.html') def edit(self, id=None): if id is None: base.abort(404) revision = model.Session.query(model.Revision).get(id) if revision is None: base.abort(404) action = request.params.get('action', '') if action in ['delete', 'undelete']: # this should be at a lower level (e.g. logic layer) if not c.revision_change_state_allowed: base.abort(403) if action == 'delete': revision.state = model.State.DELETED elif action == 'undelete': revision.state = model.State.ACTIVE model.Session.commit() h.flash_success(_('Revision updated')) h.redirect_to( h.url_for(controller='revision', action='read', id=id))
42.046392
91
0.532794
ace9cc4ad86e2adc1c2372d2bc1565b3ba76c8e4
153,203
py
Python
kubernetes_asyncio/client/api/admissionregistration_v1_api.py
weltonrodrigo/kubernetes_asyncio
b793f3e9ea43cbd0f4ff40ace1b0b677682f4042
[ "Apache-2.0" ]
null
null
null
kubernetes_asyncio/client/api/admissionregistration_v1_api.py
weltonrodrigo/kubernetes_asyncio
b793f3e9ea43cbd0f4ff40ace1b0b677682f4042
[ "Apache-2.0" ]
13
2021-04-12T02:03:48.000Z
2022-03-28T02:08:46.000Z
kubernetes_asyncio/client/api/admissionregistration_v1_api.py
weltonrodrigo/kubernetes_asyncio
b793f3e9ea43cbd0f4ff40ace1b0b677682f4042
[ "Apache-2.0" ]
null
null
null
# coding: utf-8 """ Kubernetes No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: v1.16.14 Generated by: https://openapi-generator.tech """ from __future__ import absolute_import import re # noqa: F401 # python 2 and python 3 compatibility library import six from kubernetes_asyncio.client.api_client import ApiClient from kubernetes_asyncio.client.exceptions import ( # noqa: F401 ApiTypeError, ApiValueError ) class AdmissionregistrationV1Api(object): """NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. """ def __init__(self, api_client=None): if api_client is None: api_client = ApiClient() self.api_client = api_client def create_mutating_webhook_configuration(self, body, **kwargs): # noqa: E501 """create_mutating_webhook_configuration # noqa: E501 create a MutatingWebhookConfiguration # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_mutating_webhook_configuration(body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param V1MutatingWebhookConfiguration body: (required) :param str pretty: If 'true', then the output is pretty printed. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1MutatingWebhookConfiguration If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.create_mutating_webhook_configuration_with_http_info(body, **kwargs) # noqa: E501 def create_mutating_webhook_configuration_with_http_info(self, body, **kwargs): # noqa: E501 """create_mutating_webhook_configuration # noqa: E501 create a MutatingWebhookConfiguration # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_mutating_webhook_configuration_with_http_info(body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param V1MutatingWebhookConfiguration body: (required) :param str pretty: If 'true', then the output is pretty printed. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1MutatingWebhookConfiguration, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'body', 'pretty', 'dry_run', 'field_manager' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method create_mutating_webhook_configuration" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `create_mutating_webhook_configuration`") # noqa: E501 collection_formats = {} path_params = {} query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/admissionregistration.k8s.io/v1/mutatingwebhookconfigurations', 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1MutatingWebhookConfiguration', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def create_validating_webhook_configuration(self, body, **kwargs): # noqa: E501 """create_validating_webhook_configuration # noqa: E501 create a ValidatingWebhookConfiguration # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_validating_webhook_configuration(body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param V1ValidatingWebhookConfiguration body: (required) :param str pretty: If 'true', then the output is pretty printed. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1ValidatingWebhookConfiguration If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.create_validating_webhook_configuration_with_http_info(body, **kwargs) # noqa: E501 def create_validating_webhook_configuration_with_http_info(self, body, **kwargs): # noqa: E501 """create_validating_webhook_configuration # noqa: E501 create a ValidatingWebhookConfiguration # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_validating_webhook_configuration_with_http_info(body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param V1ValidatingWebhookConfiguration body: (required) :param str pretty: If 'true', then the output is pretty printed. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1ValidatingWebhookConfiguration, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'body', 'pretty', 'dry_run', 'field_manager' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method create_validating_webhook_configuration" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `create_validating_webhook_configuration`") # noqa: E501 collection_formats = {} path_params = {} query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/admissionregistration.k8s.io/v1/validatingwebhookconfigurations', 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1ValidatingWebhookConfiguration', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def delete_collection_mutating_webhook_configuration(self, **kwargs): # noqa: E501 """delete_collection_mutating_webhook_configuration # noqa: E501 delete collection of MutatingWebhookConfiguration # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_mutating_webhook_configuration(async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str pretty: If 'true', then the output is pretty printed. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param V1DeleteOptions body: :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Status If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.delete_collection_mutating_webhook_configuration_with_http_info(**kwargs) # noqa: E501 def delete_collection_mutating_webhook_configuration_with_http_info(self, **kwargs): # noqa: E501 """delete_collection_mutating_webhook_configuration # noqa: E501 delete collection of MutatingWebhookConfiguration # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_mutating_webhook_configuration_with_http_info(async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str pretty: If 'true', then the output is pretty printed. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param V1DeleteOptions body: :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'pretty', '_continue', 'dry_run', 'field_selector', 'grace_period_seconds', 'label_selector', 'limit', 'orphan_dependents', 'propagation_policy', 'resource_version', 'timeout_seconds', 'body' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method delete_collection_mutating_webhook_configuration" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501 query_params.append(('continue', local_var_params['_continue'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501 query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501 if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501 query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501 if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501 query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501 if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501 query_params.append(('limit', local_var_params['limit'])) # noqa: E501 if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501 query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501 if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501 query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501 if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501 query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501 if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501 query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/admissionregistration.k8s.io/v1/mutatingwebhookconfigurations', 'DELETE', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Status', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def delete_collection_validating_webhook_configuration(self, **kwargs): # noqa: E501 """delete_collection_validating_webhook_configuration # noqa: E501 delete collection of ValidatingWebhookConfiguration # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_validating_webhook_configuration(async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str pretty: If 'true', then the output is pretty printed. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param V1DeleteOptions body: :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Status If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.delete_collection_validating_webhook_configuration_with_http_info(**kwargs) # noqa: E501 def delete_collection_validating_webhook_configuration_with_http_info(self, **kwargs): # noqa: E501 """delete_collection_validating_webhook_configuration # noqa: E501 delete collection of ValidatingWebhookConfiguration # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_validating_webhook_configuration_with_http_info(async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str pretty: If 'true', then the output is pretty printed. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param V1DeleteOptions body: :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'pretty', '_continue', 'dry_run', 'field_selector', 'grace_period_seconds', 'label_selector', 'limit', 'orphan_dependents', 'propagation_policy', 'resource_version', 'timeout_seconds', 'body' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method delete_collection_validating_webhook_configuration" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501 query_params.append(('continue', local_var_params['_continue'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501 query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501 if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501 query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501 if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501 query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501 if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501 query_params.append(('limit', local_var_params['limit'])) # noqa: E501 if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501 query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501 if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501 query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501 if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501 query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501 if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501 query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/admissionregistration.k8s.io/v1/validatingwebhookconfigurations', 'DELETE', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Status', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def delete_mutating_webhook_configuration(self, name, **kwargs): # noqa: E501 """delete_mutating_webhook_configuration # noqa: E501 delete a MutatingWebhookConfiguration # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_mutating_webhook_configuration(name, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the MutatingWebhookConfiguration (required) :param str pretty: If 'true', then the output is pretty printed. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param V1DeleteOptions body: :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Status If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.delete_mutating_webhook_configuration_with_http_info(name, **kwargs) # noqa: E501 def delete_mutating_webhook_configuration_with_http_info(self, name, **kwargs): # noqa: E501 """delete_mutating_webhook_configuration # noqa: E501 delete a MutatingWebhookConfiguration # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_mutating_webhook_configuration_with_http_info(name, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the MutatingWebhookConfiguration (required) :param str pretty: If 'true', then the output is pretty printed. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param V1DeleteOptions body: :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'pretty', 'dry_run', 'grace_period_seconds', 'orphan_dependents', 'propagation_policy', 'body' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method delete_mutating_webhook_configuration" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `delete_mutating_webhook_configuration`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501 query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501 if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501 query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501 if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501 query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/admissionregistration.k8s.io/v1/mutatingwebhookconfigurations/{name}', 'DELETE', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Status', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def delete_validating_webhook_configuration(self, name, **kwargs): # noqa: E501 """delete_validating_webhook_configuration # noqa: E501 delete a ValidatingWebhookConfiguration # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_validating_webhook_configuration(name, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the ValidatingWebhookConfiguration (required) :param str pretty: If 'true', then the output is pretty printed. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param V1DeleteOptions body: :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Status If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.delete_validating_webhook_configuration_with_http_info(name, **kwargs) # noqa: E501 def delete_validating_webhook_configuration_with_http_info(self, name, **kwargs): # noqa: E501 """delete_validating_webhook_configuration # noqa: E501 delete a ValidatingWebhookConfiguration # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_validating_webhook_configuration_with_http_info(name, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the ValidatingWebhookConfiguration (required) :param str pretty: If 'true', then the output is pretty printed. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param V1DeleteOptions body: :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'pretty', 'dry_run', 'grace_period_seconds', 'orphan_dependents', 'propagation_policy', 'body' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method delete_validating_webhook_configuration" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `delete_validating_webhook_configuration`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501 query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501 if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501 query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501 if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501 query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/admissionregistration.k8s.io/v1/validatingwebhookconfigurations/{name}', 'DELETE', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Status', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def get_api_resources(self, **kwargs): # noqa: E501 """get_api_resources # noqa: E501 get available resources # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_api_resources(async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1APIResourceList If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.get_api_resources_with_http_info(**kwargs) # noqa: E501 def get_api_resources_with_http_info(self, **kwargs): # noqa: E501 """get_api_resources # noqa: E501 get available resources # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_api_resources_with_http_info(async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1APIResourceList, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method get_api_resources" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/admissionregistration.k8s.io/v1/', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1APIResourceList', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def list_mutating_webhook_configuration(self, **kwargs): # noqa: E501 """list_mutating_webhook_configuration # noqa: E501 list or watch objects of kind MutatingWebhookConfiguration # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_mutating_webhook_configuration(async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str pretty: If 'true', then the output is pretty printed. :param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. If the feature gate WatchBookmarks is not enabled in apiserver, this field is ignored. This field is beta. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1MutatingWebhookConfigurationList If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.list_mutating_webhook_configuration_with_http_info(**kwargs) # noqa: E501 def list_mutating_webhook_configuration_with_http_info(self, **kwargs): # noqa: E501 """list_mutating_webhook_configuration # noqa: E501 list or watch objects of kind MutatingWebhookConfiguration # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_mutating_webhook_configuration_with_http_info(async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str pretty: If 'true', then the output is pretty printed. :param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. If the feature gate WatchBookmarks is not enabled in apiserver, this field is ignored. This field is beta. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1MutatingWebhookConfigurationList, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'pretty', 'allow_watch_bookmarks', '_continue', 'field_selector', 'label_selector', 'limit', 'resource_version', 'timeout_seconds', 'watch' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method list_mutating_webhook_configuration" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501 query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501 if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501 query_params.append(('continue', local_var_params['_continue'])) # noqa: E501 if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501 query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501 if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501 query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501 if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501 query_params.append(('limit', local_var_params['limit'])) # noqa: E501 if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501 query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501 if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501 query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501 if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501 query_params.append(('watch', local_var_params['watch'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/admissionregistration.k8s.io/v1/mutatingwebhookconfigurations', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1MutatingWebhookConfigurationList', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def list_validating_webhook_configuration(self, **kwargs): # noqa: E501 """list_validating_webhook_configuration # noqa: E501 list or watch objects of kind ValidatingWebhookConfiguration # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_validating_webhook_configuration(async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str pretty: If 'true', then the output is pretty printed. :param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. If the feature gate WatchBookmarks is not enabled in apiserver, this field is ignored. This field is beta. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1ValidatingWebhookConfigurationList If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.list_validating_webhook_configuration_with_http_info(**kwargs) # noqa: E501 def list_validating_webhook_configuration_with_http_info(self, **kwargs): # noqa: E501 """list_validating_webhook_configuration # noqa: E501 list or watch objects of kind ValidatingWebhookConfiguration # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_validating_webhook_configuration_with_http_info(async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str pretty: If 'true', then the output is pretty printed. :param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. If the feature gate WatchBookmarks is not enabled in apiserver, this field is ignored. This field is beta. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1ValidatingWebhookConfigurationList, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'pretty', 'allow_watch_bookmarks', '_continue', 'field_selector', 'label_selector', 'limit', 'resource_version', 'timeout_seconds', 'watch' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method list_validating_webhook_configuration" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501 query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501 if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501 query_params.append(('continue', local_var_params['_continue'])) # noqa: E501 if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501 query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501 if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501 query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501 if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501 query_params.append(('limit', local_var_params['limit'])) # noqa: E501 if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501 query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501 if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501 query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501 if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501 query_params.append(('watch', local_var_params['watch'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/admissionregistration.k8s.io/v1/validatingwebhookconfigurations', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1ValidatingWebhookConfigurationList', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def patch_mutating_webhook_configuration(self, name, body, **kwargs): # noqa: E501 """patch_mutating_webhook_configuration # noqa: E501 partially update the specified MutatingWebhookConfiguration # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_mutating_webhook_configuration(name, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the MutatingWebhookConfiguration (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1MutatingWebhookConfiguration If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.patch_mutating_webhook_configuration_with_http_info(name, body, **kwargs) # noqa: E501 def patch_mutating_webhook_configuration_with_http_info(self, name, body, **kwargs): # noqa: E501 """patch_mutating_webhook_configuration # noqa: E501 partially update the specified MutatingWebhookConfiguration # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_mutating_webhook_configuration_with_http_info(name, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the MutatingWebhookConfiguration (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1MutatingWebhookConfiguration, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'body', 'pretty', 'dry_run', 'field_manager', 'force' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method patch_mutating_webhook_configuration" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `patch_mutating_webhook_configuration`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `patch_mutating_webhook_configuration`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501 query_params.append(('force', local_var_params['force'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/admissionregistration.k8s.io/v1/mutatingwebhookconfigurations/{name}', 'PATCH', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1MutatingWebhookConfiguration', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def patch_validating_webhook_configuration(self, name, body, **kwargs): # noqa: E501 """patch_validating_webhook_configuration # noqa: E501 partially update the specified ValidatingWebhookConfiguration # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_validating_webhook_configuration(name, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the ValidatingWebhookConfiguration (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1ValidatingWebhookConfiguration If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.patch_validating_webhook_configuration_with_http_info(name, body, **kwargs) # noqa: E501 def patch_validating_webhook_configuration_with_http_info(self, name, body, **kwargs): # noqa: E501 """patch_validating_webhook_configuration # noqa: E501 partially update the specified ValidatingWebhookConfiguration # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_validating_webhook_configuration_with_http_info(name, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the ValidatingWebhookConfiguration (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1ValidatingWebhookConfiguration, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'body', 'pretty', 'dry_run', 'field_manager', 'force' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method patch_validating_webhook_configuration" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `patch_validating_webhook_configuration`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `patch_validating_webhook_configuration`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501 query_params.append(('force', local_var_params['force'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/admissionregistration.k8s.io/v1/validatingwebhookconfigurations/{name}', 'PATCH', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1ValidatingWebhookConfiguration', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def read_mutating_webhook_configuration(self, name, **kwargs): # noqa: E501 """read_mutating_webhook_configuration # noqa: E501 read the specified MutatingWebhookConfiguration # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_mutating_webhook_configuration(name, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the MutatingWebhookConfiguration (required) :param str pretty: If 'true', then the output is pretty printed. :param bool exact: Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'. Deprecated. Planned for removal in 1.18. :param bool export: Should this value be exported. Export strips fields that a user can not specify. Deprecated. Planned for removal in 1.18. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1MutatingWebhookConfiguration If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.read_mutating_webhook_configuration_with_http_info(name, **kwargs) # noqa: E501 def read_mutating_webhook_configuration_with_http_info(self, name, **kwargs): # noqa: E501 """read_mutating_webhook_configuration # noqa: E501 read the specified MutatingWebhookConfiguration # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_mutating_webhook_configuration_with_http_info(name, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the MutatingWebhookConfiguration (required) :param str pretty: If 'true', then the output is pretty printed. :param bool exact: Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'. Deprecated. Planned for removal in 1.18. :param bool export: Should this value be exported. Export strips fields that a user can not specify. Deprecated. Planned for removal in 1.18. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1MutatingWebhookConfiguration, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'pretty', 'exact', 'export' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method read_mutating_webhook_configuration" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `read_mutating_webhook_configuration`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'exact' in local_var_params and local_var_params['exact'] is not None: # noqa: E501 query_params.append(('exact', local_var_params['exact'])) # noqa: E501 if 'export' in local_var_params and local_var_params['export'] is not None: # noqa: E501 query_params.append(('export', local_var_params['export'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/admissionregistration.k8s.io/v1/mutatingwebhookconfigurations/{name}', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1MutatingWebhookConfiguration', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def read_validating_webhook_configuration(self, name, **kwargs): # noqa: E501 """read_validating_webhook_configuration # noqa: E501 read the specified ValidatingWebhookConfiguration # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_validating_webhook_configuration(name, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the ValidatingWebhookConfiguration (required) :param str pretty: If 'true', then the output is pretty printed. :param bool exact: Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'. Deprecated. Planned for removal in 1.18. :param bool export: Should this value be exported. Export strips fields that a user can not specify. Deprecated. Planned for removal in 1.18. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1ValidatingWebhookConfiguration If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.read_validating_webhook_configuration_with_http_info(name, **kwargs) # noqa: E501 def read_validating_webhook_configuration_with_http_info(self, name, **kwargs): # noqa: E501 """read_validating_webhook_configuration # noqa: E501 read the specified ValidatingWebhookConfiguration # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_validating_webhook_configuration_with_http_info(name, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the ValidatingWebhookConfiguration (required) :param str pretty: If 'true', then the output is pretty printed. :param bool exact: Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'. Deprecated. Planned for removal in 1.18. :param bool export: Should this value be exported. Export strips fields that a user can not specify. Deprecated. Planned for removal in 1.18. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1ValidatingWebhookConfiguration, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'pretty', 'exact', 'export' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method read_validating_webhook_configuration" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `read_validating_webhook_configuration`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'exact' in local_var_params and local_var_params['exact'] is not None: # noqa: E501 query_params.append(('exact', local_var_params['exact'])) # noqa: E501 if 'export' in local_var_params and local_var_params['export'] is not None: # noqa: E501 query_params.append(('export', local_var_params['export'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/admissionregistration.k8s.io/v1/validatingwebhookconfigurations/{name}', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1ValidatingWebhookConfiguration', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def replace_mutating_webhook_configuration(self, name, body, **kwargs): # noqa: E501 """replace_mutating_webhook_configuration # noqa: E501 replace the specified MutatingWebhookConfiguration # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_mutating_webhook_configuration(name, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the MutatingWebhookConfiguration (required) :param V1MutatingWebhookConfiguration body: (required) :param str pretty: If 'true', then the output is pretty printed. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1MutatingWebhookConfiguration If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.replace_mutating_webhook_configuration_with_http_info(name, body, **kwargs) # noqa: E501 def replace_mutating_webhook_configuration_with_http_info(self, name, body, **kwargs): # noqa: E501 """replace_mutating_webhook_configuration # noqa: E501 replace the specified MutatingWebhookConfiguration # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_mutating_webhook_configuration_with_http_info(name, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the MutatingWebhookConfiguration (required) :param V1MutatingWebhookConfiguration body: (required) :param str pretty: If 'true', then the output is pretty printed. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1MutatingWebhookConfiguration, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'body', 'pretty', 'dry_run', 'field_manager' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method replace_mutating_webhook_configuration" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `replace_mutating_webhook_configuration`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `replace_mutating_webhook_configuration`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/admissionregistration.k8s.io/v1/mutatingwebhookconfigurations/{name}', 'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1MutatingWebhookConfiguration', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def replace_validating_webhook_configuration(self, name, body, **kwargs): # noqa: E501 """replace_validating_webhook_configuration # noqa: E501 replace the specified ValidatingWebhookConfiguration # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_validating_webhook_configuration(name, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the ValidatingWebhookConfiguration (required) :param V1ValidatingWebhookConfiguration body: (required) :param str pretty: If 'true', then the output is pretty printed. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1ValidatingWebhookConfiguration If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.replace_validating_webhook_configuration_with_http_info(name, body, **kwargs) # noqa: E501 def replace_validating_webhook_configuration_with_http_info(self, name, body, **kwargs): # noqa: E501 """replace_validating_webhook_configuration # noqa: E501 replace the specified ValidatingWebhookConfiguration # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_validating_webhook_configuration_with_http_info(name, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the ValidatingWebhookConfiguration (required) :param V1ValidatingWebhookConfiguration body: (required) :param str pretty: If 'true', then the output is pretty printed. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1ValidatingWebhookConfiguration, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'body', 'pretty', 'dry_run', 'field_manager' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method replace_validating_webhook_configuration" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `replace_validating_webhook_configuration`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `replace_validating_webhook_configuration`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/admissionregistration.k8s.io/v1/validatingwebhookconfigurations/{name}', 'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1ValidatingWebhookConfiguration', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats)
71.356777
1,390
0.676795
ace9cd2c5caab21304e038625fce5c1de65c0242
3,062
py
Python
tensorflow/python/ops/standard_ops.py
sylviawhoa/tensorflow
30f3cdfc420d831e2591cce62fa51164cf8a700a
[ "Apache-2.0" ]
7
2016-04-24T19:06:10.000Z
2018-10-03T16:33:51.000Z
tensorflow/python/ops/standard_ops.py
sylviawhoa/tensorflow
30f3cdfc420d831e2591cce62fa51164cf8a700a
[ "Apache-2.0" ]
null
null
null
tensorflow/python/ops/standard_ops.py
sylviawhoa/tensorflow
30f3cdfc420d831e2591cce62fa51164cf8a700a
[ "Apache-2.0" ]
3
2017-05-24T06:58:14.000Z
2020-02-15T14:21:00.000Z
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== # pylint: disable=unused-import """Import names of Tensor Flow standard Ops.""" # Imports the following modules so that @RegisterGradient get executed. from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.ops import array_grad from tensorflow.python.ops import data_flow_grad from tensorflow.python.ops import math_grad from tensorflow.python.ops import sparse_grad from tensorflow.python.ops import state_grad from tensorflow.python.ops import tensor_array_grad # go/tf-wildcard-import # pylint: disable=wildcard-import from tensorflow.python.ops.array_ops import * from tensorflow.python.ops.clip_ops import * # TODO(vrv): Switch to import * once we're okay with exposing the module. from tensorflow.python.ops.control_flow_ops import group from tensorflow.python.ops.control_flow_ops import no_op from tensorflow.python.ops.control_flow_ops import tuple from tensorflow.python.ops.control_flow_ops import cond from tensorflow.python.ops.control_flow_ops import case from tensorflow.python.ops.data_flow_ops import * from tensorflow.python.ops.functional_ops import * from tensorflow.python.ops.gradients import * from tensorflow.python.ops.histogram_ops import * from tensorflow.python.ops.init_ops import * from tensorflow.python.ops.io_ops import * from tensorflow.python.ops.linalg_ops import * from tensorflow.python.ops.logging_ops import * from tensorflow.python.ops.math_ops import * from tensorflow.python.ops.numerics import * from tensorflow.python.ops.parsing_ops import * from tensorflow.python.ops.partitioned_variables import * from tensorflow.python.ops.random_ops import * from tensorflow.python.ops.script_ops import py_func from tensorflow.python.ops.sparse_ops import * from tensorflow.python.ops.state_ops import assign from tensorflow.python.ops.state_ops import assign_add from tensorflow.python.ops.state_ops import assign_sub from tensorflow.python.ops.state_ops import count_up_to from tensorflow.python.ops.state_ops import scatter_add from tensorflow.python.ops.state_ops import scatter_sub from tensorflow.python.ops.state_ops import scatter_update from tensorflow.python.ops.string_ops import * from tensorflow.python.ops.template import * from tensorflow.python.ops.variable_scope import * from tensorflow.python.ops.variables import * # pylint: enable=wildcard-import
45.029412
80
0.804376
ace9cdbb89755c9ea80c2b1efc3010ea6afed919
2,555
py
Python
acc.py
kimukook/CLF-CBF-python
28a46a4f9abf095e1f1b92e6cc056956caab5374
[ "MIT" ]
null
null
null
acc.py
kimukook/CLF-CBF-python
28a46a4f9abf095e1f1b92e6cc056956caab5374
[ "MIT" ]
null
null
null
acc.py
kimukook/CLF-CBF-python
28a46a4f9abf095e1f1b92e6cc056956caab5374
[ "MIT" ]
null
null
null
''' ===================================== Author : Muhan Zhao Date : Feb. 11, 2020 Location: UC San Diego, La Jolla, CA ===================================== ''' import numpy as np import sympy as sp # from define_system import ControlAffineSystem class AdaptiveCruiseControl: """ Define the symbolic dynamic: dx = f(x) + g(x) * u x contains 3 states: p -> position v -> velocity relative z -> distance """ def __init__(self, params): """ The input 'params' is a dictionary type argument which contains the following parameters: :param f0 : To define the rolling resistance; :param f1 : To define the rolling resistance; :param f2 : To define the rolling resistance; :param m : The mass; :param v0 : The speed of leading cruise; :param T : The time horizon for defining cbf; :param cd : The deceleration parameter in cbf; :param vd : The desired velocity in clf; :param udim : The dimension of control profile u """ self.f0 = params['f0'] self.f1 = params['f1'] self.f2 = params['f2'] self.v0 = params['v0'] self.m = params['m'] self.T = params['T'] self.cd = params['cd'] self.G = params['G'] self.vd = params['vd'] p, v, z = sp.symbols('p v z') self.x = sp.Matrix([p, v, z]) self.Fr = None # Define the symbolic expression for system dynamic, CLF and CBF self.f, self.g = self.simple_car_dynamics() self.cbf = self.define_cbf() self.clf = self.define_clf() if 'udim' in params.keys(): self.udim = params['udim'] else: print(f'The dimension of input u is not given, set it to be default 1') self.udim = 1 def simple_car_dynamics(self): self.Fr = self.Fr_() # f, g both column vector f = sp.Matrix([self.x[1], -self.Fr / self.m, self.v0 - self.x[1]]) g = sp.Matrix([0, 1/self.m, 0]) return f, g def Fr_(self): self.Fr = self.f0 + self.f1 * self.x[1] + self.f2 * self.x[1] ** 2 return self.Fr def getFr(self, x): return np.array([self.f0 + self.f1 * x[1] + self.f2 * x[1] ** 2]) def define_cbf(self): cbf = self.x[2] - self.T * self.x[1] - .5 * (self.x[1] - self.v0) ** 2 / (self.cd * self.G) return cbf def define_clf(self): clf = (self.x[1] - self.vd) ** 2 return clf
30.783133
99
0.527202
ace9cdbce63c9b1673afa6705226d5b555840eb5
1,496
py
Python
lib/py/setup.py
simplegeo/thrift
1a9f6358b53421a85063ab811c65c67003a270b4
[ "Apache-2.0" ]
1
2016-12-21T04:36:35.000Z
2016-12-21T04:36:35.000Z
lib/py/setup.py
simplegeo/thrift
1a9f6358b53421a85063ab811c65c67003a270b4
[ "Apache-2.0" ]
null
null
null
lib/py/setup.py
simplegeo/thrift
1a9f6358b53421a85063ab811c65c67003a270b4
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # from distutils.core import setup, Extension fastbinarymod = Extension('thrift.protocol.fastbinary', sources = ['src/protocol/fastbinary.c'], ) setup(name = 'Thrift', version = '0.2', description = 'Thrift Python Libraries', author = ['Thrift Developers'], author_email = ['thrift-dev@incubator.apache.org'], url = 'http://incubator.apache.org/thrift/', license = 'Apache License 2.0', packages = [ 'thrift', 'thrift.protocol', 'thrift.transport', 'thrift.server', ], package_dir = {'thrift' : 'src'}, ext_modules = [fastbinarymod], )
33.244444
66
0.670455
ace9ce4abc5cb12f0ba049c3510d902690461df0
9,554
py
Python
Leak #5 - Lost In Translation/windows/Resources/Python/Core/Lib/email/generator.py
bidhata/EquationGroupLeaks
1ff4bc115cb2bd5bf2ed6bf769af44392926830c
[ "Unlicense" ]
9
2019-11-22T04:58:40.000Z
2022-02-26T16:47:28.000Z
Leak #5 - Lost In Translation/windows/Resources/Python/Core/Lib/email/generator.py
bidhata/EquationGroupLeaks
1ff4bc115cb2bd5bf2ed6bf769af44392926830c
[ "Unlicense" ]
null
null
null
Leak #5 - Lost In Translation/windows/Resources/Python/Core/Lib/email/generator.py
bidhata/EquationGroupLeaks
1ff4bc115cb2bd5bf2ed6bf769af44392926830c
[ "Unlicense" ]
8
2017-09-27T10:31:18.000Z
2022-01-08T10:30:46.000Z
# uncompyle6 version 2.9.10 # Python bytecode 2.7 (62211) # Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10) # [GCC 6.2.0 20161005] # Embedded file name: generator.py """Classes to generate plain text from a message object tree.""" __all__ = [ 'Generator', 'DecodedGenerator'] import re import sys import time import random import warnings from cStringIO import StringIO from email.header import Header UNDERSCORE = '_' NL = '\n' fcre = re.compile('^From ', re.MULTILINE) def _is8bitstring(s): if isinstance(s, str): try: unicode(s, 'us-ascii') except UnicodeError: return True return False class Generator(): """Generates output from a Message object tree. This basic generator writes the message to the given file object as plain text. """ def __init__(self, outfp, mangle_from_=True, maxheaderlen=78): """Create the generator for message flattening. outfp is the output file-like object for writing the message to. It must have a write() method. Optional mangle_from_ is a flag that, when True (the default), escapes From_ lines in the body of the message by putting a `>' in front of them. Optional maxheaderlen specifies the longest length for a non-continued header. When a header line is longer (in characters, with tabs expanded to 8 spaces) than maxheaderlen, the header will split as defined in the Header class. Set maxheaderlen to zero to disable header wrapping. The default is 78, as recommended (but not required) by RFC 2822. """ self._fp = outfp self._mangle_from_ = mangle_from_ self._maxheaderlen = maxheaderlen def write(self, s): self._fp.write(s) def flatten(self, msg, unixfrom=False): """Print the message object tree rooted at msg to the output file specified when the Generator instance was created. unixfrom is a flag that forces the printing of a Unix From_ delimiter before the first object in the message tree. If the original message has no From_ delimiter, a `standard' one is crafted. By default, this is False to inhibit the printing of any From_ delimiter. Note that for subobjects, no From_ line is printed. """ if unixfrom: ufrom = msg.get_unixfrom() if not ufrom: ufrom = 'From nobody ' + time.ctime(time.time()) print >> self._fp, ufrom self._write(msg) def clone(self, fp): """Clone this generator with the exact same options.""" return self.__class__(fp, self._mangle_from_, self._maxheaderlen) def _write(self, msg): oldfp = self._fp try: self._fp = sfp = StringIO() self._dispatch(msg) finally: self._fp = oldfp meth = getattr(msg, '_write_headers', None) if meth is None: self._write_headers(msg) else: meth(self) self._fp.write(sfp.getvalue()) return def _dispatch(self, msg): main = msg.get_content_maintype() sub = msg.get_content_subtype() specific = UNDERSCORE.join((main, sub)).replace('-', '_') meth = getattr(self, '_handle_' + specific, None) if meth is None: generic = main.replace('-', '_') meth = getattr(self, '_handle_' + generic, None) if meth is None: meth = self._writeBody meth(msg) return def _write_headers(self, msg): for h, v in msg.items(): print >> self._fp, '%s:' % h, if self._maxheaderlen == 0: print >> self._fp, v elif isinstance(v, Header): print >> self._fp, v.encode() elif _is8bitstring(v): print >> self._fp, v else: print >> self._fp, Header(v, maxlinelen=self._maxheaderlen, header_name=h).encode() print >> self._fp def _handle_text(self, msg): payload = msg.get_payload() if payload is None: return else: if not isinstance(payload, basestring): raise TypeError('string payload expected: %s' % type(payload)) if self._mangle_from_: payload = fcre.sub('>From ', payload) self._fp.write(payload) return _writeBody = _handle_text def _handle_multipart(self, msg): msgtexts = [] subparts = msg.get_payload() if subparts is None: subparts = [] elif isinstance(subparts, basestring): self._fp.write(subparts) return if not isinstance(subparts, list): subparts = [subparts] for part in subparts: s = StringIO() g = self.clone(s) g.flatten(part, unixfrom=False) msgtexts.append(s.getvalue()) boundary = msg.get_boundary() if not boundary: alltext = NL.join(msgtexts) boundary = _make_boundary(alltext) msg.set_boundary(boundary) if msg.preamble is not None: print >> self._fp, msg.preamble print >> self._fp, '--' + boundary if msgtexts: self._fp.write(msgtexts.pop(0)) for body_part in msgtexts: print >> self._fp, '\n--' + boundary self._fp.write(body_part) self._fp.write('\n--' + boundary + '--') if msg.epilogue is not None: print >> self._fp self._fp.write(msg.epilogue) return def _handle_multipart_signed(self, msg): old_maxheaderlen = self._maxheaderlen try: self._maxheaderlen = 0 self._handle_multipart(msg) finally: self._maxheaderlen = old_maxheaderlen def _handle_message_delivery_status(self, msg): blocks = [] for part in msg.get_payload(): s = StringIO() g = self.clone(s) g.flatten(part, unixfrom=False) text = s.getvalue() lines = text.split('\n') if lines and lines[-1] == '': blocks.append(NL.join(lines[:-1])) else: blocks.append(text) self._fp.write(NL.join(blocks)) def _handle_message(self, msg): s = StringIO() g = self.clone(s) payload = msg.get_payload() if isinstance(payload, list): g.flatten(msg.get_payload(0), unixfrom=False) payload = s.getvalue() self._fp.write(payload) _FMT = '[Non-text (%(type)s) part of message omitted, filename %(filename)s]' class DecodedGenerator(Generator): """Generates a text representation of a message. Like the Generator base class, except that non-text parts are substituted with a format string representing the part. """ def __init__(self, outfp, mangle_from_=True, maxheaderlen=78, fmt=None): """Like Generator.__init__() except that an additional optional argument is allowed. Walks through all subparts of a message. If the subpart is of main type `text', then it prints the decoded payload of the subpart. Otherwise, fmt is a format string that is used instead of the message payload. fmt is expanded with the following keywords (in %(keyword)s format): type : Full MIME type of the non-text part maintype : Main MIME type of the non-text part subtype : Sub-MIME type of the non-text part filename : Filename of the non-text part description: Description associated with the non-text part encoding : Content transfer encoding of the non-text part The default value for fmt is None, meaning [Non-text (%(type)s) part of message omitted, filename %(filename)s] """ Generator.__init__(self, outfp, mangle_from_, maxheaderlen) if fmt is None: self._fmt = _FMT else: self._fmt = fmt return def _dispatch(self, msg): for part in msg.walk(): maintype = part.get_content_maintype() if maintype == 'text': print >> self, part.get_payload(decode=True) elif maintype == 'multipart': pass else: print >> self, self._fmt % {'type': part.get_content_type(), 'maintype': part.get_content_maintype(), 'subtype': part.get_content_subtype(), 'filename': part.get_filename('[no filename]'), 'description': part.get('Content-Description', '[no description]'), 'encoding': part.get('Content-Transfer-Encoding', '[no encoding]') } _width = len(repr(sys.maxint - 1)) _fmt = '%%0%dd' % _width def _make_boundary(text=None): token = random.randrange(sys.maxint) boundary = '===============' + _fmt % token + '==' if text is None: return boundary else: b = boundary counter = 0 while True: cre = re.compile('^--' + re.escape(b) + '(--)?$', re.MULTILINE) if not cre.search(text): break b = boundary + '.' + str(counter) counter += 1 return b
33.879433
99
0.573477
ace9ce6f59dfb53a568fe25dbb5401b8a45ab54b
36,047
py
Python
py_queue/queue_job/jobrunner/channels.py
xiaoming719/python_material
d5323cd303c18794f7011915b5da77cf2b5ce63b
[ "Apache-2.0" ]
null
null
null
py_queue/queue_job/jobrunner/channels.py
xiaoming719/python_material
d5323cd303c18794f7011915b5da77cf2b5ce63b
[ "Apache-2.0" ]
null
null
null
py_queue/queue_job/jobrunner/channels.py
xiaoming719/python_material
d5323cd303c18794f7011915b5da77cf2b5ce63b
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- # Copyright (c) 2015-2016 ACSONE SA/NV (<http://acsone.eu>) # Copyright 2015-2016 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) from functools import total_ordering from heapq import heappush, heappop import logging from weakref import WeakValueDictionary from ..exception import ChannelNotFound from ..job import PENDING, ENQUEUED, STARTED, FAILED, DONE NOT_DONE = (PENDING, ENQUEUED, STARTED, FAILED) _logger = logging.getLogger(__name__) class PriorityQueue(object): """A priority queue that supports removing arbitrary objects. Adding an object already in the queue is a no op. Popping an empty queue returns None. >>> q = PriorityQueue() >>> q.add(2) >>> q.add(3) >>> q.add(3) >>> q.add(1) >>> q[0] 1 >>> len(q) 3 >>> q.pop() 1 >>> q.remove(2) >>> len(q) 1 >>> q[0] 3 >>> q.pop() 3 >>> q.pop() >>> q.add(2) >>> q.remove(2) >>> q.add(2) >>> q.pop() 2 """ def __init__(self): self._heap = [] self._known = set() # all objects in the heap (including removed) self._removed = set() # all objects that have been removed def __len__(self): return len(self._known) - len(self._removed) def __getitem__(self, i): if i != 0: raise IndexError() while True: if not self._heap: raise IndexError() o = self._heap[0] if o in self._removed: o2 = heappop(self._heap) assert o2 == o self._removed.remove(o) self._known.remove(o) else: return o def __contains__(self, o): return o in self._known and o not in self._removed def add(self, o): if o is None: raise ValueError() if o in self._removed: self._removed.remove(o) if o in self._known: return self._known.add(o) heappush(self._heap, o) def remove(self, o): if o is None: raise ValueError() if o not in self._known: return if o not in self._removed: self._removed.add(o) def pop(self): while True: try: o = heappop(self._heap) except IndexError: # queue is empty return None self._known.remove(o) if o in self._removed: self._removed.remove(o) else: return o class SafeSet(set): """A set that does not raise KeyError when removing non-existent items. >>> s = SafeSet() >>> s.remove(1) >>> len(s) 0 >>> s.remove(1) """ def remove(self, o): try: super(SafeSet, self).remove(o) except KeyError: pass @total_ordering class ChannelJob(object): """A channel job is attached to a channel and holds the properties of a job that are necessary to prioritise them. Channel jobs are comparable according to the following rules: * jobs with an eta come before all other jobs * then jobs with a smaller eta come first * then jobs with a smaller priority come first * then jobs with a smaller creation time come first * then jobs with a smaller sequence come first Here are some examples. j1 comes before j2 because it has an earlier date_created >>> j1 = ChannelJob(None, None, 1, ... seq=0, date_created=1, priority=9, eta=None) >>> j1 <ChannelJob 1> >>> j2 = ChannelJob(None, None, 2, ... seq=0, date_created=2, priority=9, eta=None) >>> j1 < j2 True j3 comes first because it has lower priority, despite having a creation date after j1 and j2 >>> j3 = ChannelJob(None, None, 3, ... seq=0, date_created=3, priority=2, eta=None) >>> j3 < j1 True j4 and j5 comes even before j3, because they have an eta >>> j4 = ChannelJob(None, None, 4, ... seq=0, date_created=4, priority=9, eta=9) >>> j5 = ChannelJob(None, None, 5, ... seq=0, date_created=5, priority=9, eta=9) >>> j4 < j5 < j3 True j6 has same date_created and priority as j5 but a smaller eta >>> j6 = ChannelJob(None, None, 6, ... seq=0, date_created=5, priority=9, eta=2) >>> j6 < j4 < j5 True Here is the complete suite: >>> j6 < j4 < j5 < j3 < j1 < j2 True j0 has the same properties as j1 but they are not considered equal as they are different instances >>> j0 = ChannelJob(None, None, 1, ... seq=0, date_created=1, priority=9, eta=None) >>> j0 == j1 False >>> j0 == j0 True Comparison excluding eta: >>> j1.sorting_key_ignoring_eta() < j2.sorting_key_ignoring_eta() True """ def __init__(self, db_name, channel, uuid, seq, date_created, priority, eta): self.db_name = db_name self.channel = channel self.uuid = uuid self.seq = seq self.date_created = date_created self.priority = priority self.eta = eta def __repr__(self): return "<ChannelJob %s>" % self.uuid def __eq__(self, other): return id(self) == id(other) def __hash__(self): return id(self) def sorting_key(self): return self.eta, self.priority, self.date_created, self.seq def sorting_key_ignoring_eta(self): return self.priority, self.date_created, self.seq def __lt__(self, other): if self.eta and not other.eta: return True elif not self.eta and other.eta: return False else: return self.sorting_key() < other.sorting_key() class ChannelQueue(object): """A channel queue is a priority queue for jobs. Jobs with an eta are set aside until their eta is past due, at which point they start competing normally with other jobs. >>> q = ChannelQueue() >>> j1 = ChannelJob(None, None, 1, ... seq=0, date_created=1, priority=1, eta=10) >>> j2 = ChannelJob(None, None, 2, ... seq=0, date_created=2, priority=1, eta=None) >>> j3 = ChannelJob(None, None, 3, ... seq=0, date_created=3, priority=1, eta=None) >>> q.add(j1) >>> q.add(j2) >>> q.add(j3) Wakeup time is the eta of job 1. >>> q.get_wakeup_time() 10 We have not reached the eta of job 1, so we get job 2. >>> q.pop(now=1) <ChannelJob 2> Wakeup time is still the eta of job 1, and we get job 1 when we are past it's eta. >>> q.get_wakeup_time() 10 >>> q.pop(now=11) <ChannelJob 1> Now there is no wakeup time anymore, because no job have an eta. >>> q.get_wakeup_time() 0 >>> q.pop(now=12) <ChannelJob 3> >>> q.get_wakeup_time() 0 >>> q.pop(now=13) Observe that job with past eta still run after jobs with higher priority. >>> j4 = ChannelJob(None, None, 4, ... seq=0, date_created=4, priority=10, eta=20) >>> j5 = ChannelJob(None, None, 5, ... seq=0, date_created=5, priority=1, eta=None) >>> q.add(j4) >>> q.add(j5) >>> q.get_wakeup_time() 20 >>> q.pop(21) <ChannelJob 5> >>> q.get_wakeup_time() 0 >>> q.pop(22) <ChannelJob 4> Test a sequential queue. >>> sq = ChannelQueue(sequential=True) >>> j6 = ChannelJob(None, None, 6, ... seq=0, date_created=6, priority=1, eta=None) >>> j7 = ChannelJob(None, None, 7, ... seq=0, date_created=7, priority=1, eta=20) >>> j8 = ChannelJob(None, None, 8, ... seq=0, date_created=8, priority=1, eta=None) >>> sq.add(j6) >>> sq.add(j7) >>> sq.add(j8) >>> sq.pop(10) <ChannelJob 6> >>> sq.pop(15) >>> sq.pop(20) <ChannelJob 7> >>> sq.pop(30) <ChannelJob 8> """ def __init__(self, sequential=False): self._queue = PriorityQueue() self._eta_queue = PriorityQueue() self.sequential = sequential def __len__(self): return len(self._eta_queue) + len(self._queue) def __contains__(self, o): return o in self._eta_queue or o in self._queue def add(self, job): if job.eta: self._eta_queue.add(job) else: self._queue.add(job) def remove(self, job): self._eta_queue.remove(job) self._queue.remove(job) def pop(self, now): while len(self._eta_queue) and self._eta_queue[0].eta <= now: eta_job = self._eta_queue.pop() eta_job.eta = None self._queue.add(eta_job) if self.sequential and len(self._eta_queue) and len(self._queue): eta_job = self._eta_queue[0] job = self._queue[0] if (eta_job.sorting_key_ignoring_eta() < job.sorting_key_ignoring_eta()): # eta ignored, the job with eta has higher priority # than the job without eta; since it's a sequential # queue we wait until eta return return self._queue.pop() def get_wakeup_time(self, wakeup_time=0): if len(self._eta_queue): if not wakeup_time: wakeup_time = self._eta_queue[0].eta else: wakeup_time = min(wakeup_time, self._eta_queue[0].eta) return wakeup_time class Channel(object): """A channel for jobs, with a maximum capacity. When jobs are created by queue_job modules, they may be associated to a job channel. Jobs with no channel are inserted into the root channel. Job channels are joined in a hierarchy down to the root channel. When a job channel has available capacity, jobs are dequeued, marked as running in the channel and are inserted into the queue of the parent channel where they wait for available capacity and so on. Job channels can be visualized as water channels with a given flow limit (= capacity). Channels are joined together in a downstream channel and the flow limit of the downstream channel limits upstream channels.:: ---------------------+ | | Ch. A C:4,Q:12,R:4 +----------------------- ---------------------+ Ch. root C:5,Q:0,R:4 | ---------------------+ Ch. B C:1,Q:0,R:0 ---------------------+----------------------- The above diagram illustrates two channels joining in the root channel. The root channel has a capacity of 5, and 4 running jobs coming from Channel A. Channel A has a capacity of 4, all in use (passed down to the root channel), and 12 jobs enqueued. Channel B has a capacity of 1, none in use. This means that whenever a new job comes in channel B, there will be available room for it to run in the root channel. Note that from the point of view of a channel, 'running' means enqueued in the downstream channel. Only jobs marked running in the root channel are actually sent to Odoo for execution. Should a downstream channel have less capacity than its upstream channels, jobs going downstream will be enqueued in the downstream channel, and compete normally according to their properties (priority, etc). Using this technique, it is possible to enforce sequence in a channel with a capacity of 1. It is also possible to dedicate a channel with a limited capacity for application-autocreated subchannels without risking to overflow the system. """ def __init__(self, name, parent, capacity=None, sequential=False, throttle=0): self.name = name self.parent = parent if self.parent: self.parent.children[name] = self self.children = {} self._queue = ChannelQueue() self._running = SafeSet() self._failed = SafeSet() self._pause_until = 0 # utc seconds since the epoch self.capacity = capacity self.throttle = throttle # seconds self.sequential = sequential @property def sequential(self): return self._queue.sequential @sequential.setter def sequential(self, val): self._queue.sequential = val def configure(self, config): """ Configure a channel from a dictionary. Supported keys are: * capacity * sequential * throttle """ assert self.fullname.endswith(config['name']) self.capacity = config.get('capacity', None) self.sequential = bool(config.get('sequential', False)) self.throttle = int(config.get('throttle', 0)) if self.sequential and self.capacity != 1: raise ValueError("A sequential channel must have a capacity of 1") @property def fullname(self): """ The full name of the channel, in dot separated notation. """ if self.parent: return self.parent.fullname + '.' + self.name else: return self.name def get_subchannel_by_name(self, subchannel_name): return self.children.get(subchannel_name) def __str__(self): capacity = '∞' if self.capacity is None else str(self.capacity) return "%s(C:%s,Q:%d,R:%d,F:%d)" % (self.fullname, capacity, len(self._queue), len(self._running), len(self._failed)) def remove(self, job): """ Remove a job from the channel. """ self._queue.remove(job) self._running.remove(job) self._failed.remove(job) if self.parent: self.parent.remove(job) def set_done(self, job): """ Mark a job as done. This removes it from the channel queue. """ self.remove(job) _logger.debug("job %s marked done in channel %s", job.uuid, self) def set_pending(self, job): """ Mark a job as pending. This puts the job in the channel queue and remove it from parent channels queues. """ if job not in self._queue: self._queue.add(job) self._running.remove(job) self._failed.remove(job) if self.parent: self.parent.remove(job) _logger.debug("job %s marked pending in channel %s", job.uuid, self) def set_running(self, job): """ Mark a job as running. This also marks the job as running in parent channels. """ if job not in self._running: self._queue.remove(job) self._running.add(job) self._failed.remove(job) if self.parent: self.parent.set_running(job) _logger.debug("job %s marked running in channel %s", job.uuid, self) def set_failed(self, job): """ Mark the job as failed. """ if job not in self._failed: self._queue.remove(job) self._running.remove(job) self._failed.add(job) if self.parent: self.parent.remove(job) _logger.debug("job %s marked failed in channel %s", job.uuid, self) def has_capacity(self): if self.sequential and self._failed: # a sequential queue blocks on failed jobs return False if not self.capacity: # unlimited capacity return True return len(self._running) < self.capacity def get_jobs_to_run(self, now): """ Get jobs that are ready to run in channel. This works by enqueuing jobs that are ready to run in children channels, then yielding jobs from the channel queue until ``capacity`` jobs are marked running in the channel. If the ``throttle`` option is set on the channel, then it yields no job until at least throttle seconds have elapsed since the previous yield. :param now: the current datetime in seconds :return: iterator of :class:`odoo.addons.queue_job.jobrunner.ChannelJob` """ # enqueue jobs of children channels for child in self.children.values(): for job in child.get_jobs_to_run(now): self._queue.add(job) # is this channel paused? if self.throttle and self._pause_until: if now < self._pause_until: if self.has_capacity(): _logger.debug("channel %s paused until %s because " "of throttle delay between jobs", self, self._pause_until) return else: # unpause, this is important to avoid perpetual wakeup # while the channel is at full capacity self._pause_until = 0 _logger.debug("channel %s unpaused at %s", self, now) # yield jobs that are ready to run, while we have capacity while self.has_capacity(): job = self._queue.pop(now) if not job: return self._running.add(job) _logger.debug("job %s marked running in channel %s", job.uuid, self) yield job if self.throttle: self._pause_until = now + self.throttle _logger.debug("pausing channel %s until %s", self, self._pause_until) return def get_wakeup_time(self, wakeup_time=0): if not self.has_capacity(): # this channel is full, do not request timed wakeup, as # a notification will wakeup the runner when a job finishes return wakeup_time if self._pause_until: # this channel is paused, request wakeup at the end of the pause if not wakeup_time: wakeup_time = self._pause_until else: wakeup_time = min(wakeup_time, self._pause_until) # since this channel is paused, no need to look at the # wakeup time of children nor eta jobs, as such jobs would not # run anyway because they would end up in this paused channel return wakeup_time wakeup_time = self._queue.get_wakeup_time(wakeup_time) for child in self.children.values(): wakeup_time = child.get_wakeup_time(wakeup_time) return wakeup_time def split_strip(s, sep, maxsplit=-1): """Split string and strip each component. >>> split_strip("foo: bar baz\\n: fred:", ":") ['foo', 'bar baz', 'fred', ''] """ return [x.strip() for x in s.split(sep, maxsplit)] class ChannelManager(object): """ High level interface for channels This class handles: * configuration of channels * high level api to create and remove jobs (notify, remove_job, remove_db) * get jobs to run Here is how the runner will use it. Let's create a channel manager and configure it. >>> from pprint import pprint as pp >>> cm = ChannelManager() >>> cm.simple_configure('root:4,A:4,B:1') >>> db = 'db' Add a few jobs in channel A with priority 10 >>> cm.notify(db, 'A', 'A1', 1, 0, 10, None, 'pending') >>> cm.notify(db, 'A', 'A2', 2, 0, 10, None, 'pending') >>> cm.notify(db, 'A', 'A3', 3, 0, 10, None, 'pending') >>> cm.notify(db, 'A', 'A4', 4, 0, 10, None, 'pending') >>> cm.notify(db, 'A', 'A5', 5, 0, 10, None, 'pending') >>> cm.notify(db, 'A', 'A6', 6, 0, 10, None, 'pending') Add a few jobs in channel B with priority 5 >>> cm.notify(db, 'B', 'B1', 1, 0, 5, None, 'pending') >>> cm.notify(db, 'B', 'B2', 2, 0, 5, None, 'pending') We must now run one job from queue B which has a capacity of 1 and 3 jobs from queue A so the root channel capacity of 4 is filled. >>> pp(list(cm.get_jobs_to_run(now=100))) [<ChannelJob B1>, <ChannelJob A1>, <ChannelJob A2>, <ChannelJob A3>] Job A2 is done. Next job to run is A5, even if we have higher priority job in channel B, because channel B has a capacity of 1. >>> cm.notify(db, 'A', 'A2', 2, 0, 10, None, 'done') >>> pp(list(cm.get_jobs_to_run(now=100))) [<ChannelJob A4>] Job B1 is done. Next job to run is B2 because it has higher priority. >>> cm.notify(db, 'B', 'B1', 1, 0, 5, None, 'done') >>> pp(list(cm.get_jobs_to_run(now=100))) [<ChannelJob B2>] Let's say A1 is done and A6 gets a higher priority. A6 will run next. >>> cm.notify(db, 'A', 'A1', 1, 0, 10, None, 'done') >>> cm.notify(db, 'A', 'A6', 6, 0, 5, None, 'pending') >>> pp(list(cm.get_jobs_to_run(now=100))) [<ChannelJob A6>] Let's test the throttling mechanism. Configure a 2 seconds delay on channel A, end enqueue two jobs. >>> cm = ChannelManager() >>> cm.simple_configure('root:4,A:4:throttle=2') >>> cm.notify(db, 'A', 'A1', 1, 0, 10, None, 'pending') >>> cm.notify(db, 'A', 'A2', 2, 0, 10, None, 'pending') We have only one job to run, because of the throttle. >>> pp(list(cm.get_jobs_to_run(now=100))) [<ChannelJob A1>] >>> cm.get_wakeup_time() 102 We have no job to run, because of the throttle. >>> pp(list(cm.get_jobs_to_run(now=101))) [] >>> cm.get_wakeup_time() 102 2 seconds later, we can run the other job (even though the first one is still running, because we have enough capacity). >>> pp(list(cm.get_jobs_to_run(now=102))) [<ChannelJob A2>] >>> cm.get_wakeup_time() 104 Let's test throttling in combination with a queue reaching full capacity. >>> cm = ChannelManager() >>> cm.simple_configure('root:4,T:2:throttle=2') >>> cm.notify(db, 'T', 'T1', 1, 0, 10, None, 'pending') >>> cm.notify(db, 'T', 'T2', 2, 0, 10, None, 'pending') >>> cm.notify(db, 'T', 'T3', 3, 0, 10, None, 'pending') >>> pp(list(cm.get_jobs_to_run(now=100))) [<ChannelJob T1>] >>> pp(list(cm.get_jobs_to_run(now=102))) [<ChannelJob T2>] Channel is now full, so no job to run even though throttling delay is over. >>> pp(list(cm.get_jobs_to_run(now=103))) [] >>> cm.get_wakeup_time() # no wakeup time, since queue is full 0 >>> pp(list(cm.get_jobs_to_run(now=104))) [] >>> cm.get_wakeup_time() # queue is still full 0 >>> cm.notify(db, 'T', 'T1', 1, 0, 10, None, 'done') >>> pp(list(cm.get_jobs_to_run(now=105))) [<ChannelJob T3>] >>> cm.get_wakeup_time() # queue is full 0 >>> cm.notify(db, 'T', 'T2', 1, 0, 10, None, 'done') >>> cm.get_wakeup_time() 107 Test wakeup time behaviour in presence of eta. >>> cm = ChannelManager() >>> cm.simple_configure('root:4,E:1') >>> cm.notify(db, 'E', 'E1', 1, 0, 10, None, 'pending') >>> cm.notify(db, 'E', 'E2', 2, 0, 10, None, 'pending') >>> cm.notify(db, 'E', 'E3', 3, 0, 10, None, 'pending') >>> pp(list(cm.get_jobs_to_run(now=100))) [<ChannelJob E1>] >>> pp(list(cm.get_jobs_to_run(now=101))) [] >>> cm.notify(db, 'E', 'E1', 1, 0, 10, 105, 'pending') >>> cm.get_wakeup_time() # wakeup at eta 105 >>> pp(list(cm.get_jobs_to_run(now=102))) # but there is capacity [<ChannelJob E2>] >>> pp(list(cm.get_jobs_to_run(now=106))) # no capacity anymore [] >>> cm.get_wakeup_time() # no timed wakeup because no capacity 0 >>> cm.notify(db, 'E', 'E2', 1, 0, 10, None, 'done') >>> cm.get_wakeup_time() 105 >>> pp(list(cm.get_jobs_to_run(now=107))) # no capacity anymore [<ChannelJob E1>] >>> cm.get_wakeup_time() 0 Test wakeup time behaviour in a sequential queue. >>> cm = ChannelManager() >>> cm.simple_configure('root:4,S:1:sequential') >>> cm.notify(db, 'S', 'S1', 1, 0, 10, None, 'pending') >>> cm.notify(db, 'S', 'S2', 2, 0, 10, None, 'pending') >>> cm.notify(db, 'S', 'S3', 3, 0, 10, None, 'pending') >>> pp(list(cm.get_jobs_to_run(now=100))) [<ChannelJob S1>] >>> cm.notify(db, 'S', 'S1', 1, 0, 10, None, 'failed') >>> pp(list(cm.get_jobs_to_run(now=101))) [] >>> cm.notify(db, 'S', 'S2', 2, 0, 10, 105, 'pending') >>> pp(list(cm.get_jobs_to_run(now=102))) [] No wakeup time because due to eta, because the sequential queue is waiting for a failed job. >>> cm.get_wakeup_time() 0 >>> cm.notify(db, 'S', 'S1', 1, 0, 10, None, 'pending') >>> cm.get_wakeup_time() 105 >>> pp(list(cm.get_jobs_to_run(now=102))) [<ChannelJob S1>] >>> pp(list(cm.get_jobs_to_run(now=103))) [] >>> cm.notify(db, 'S', 'S1', 1, 0, 10, None, 'done') At this stage, we have S2 with an eta of 105 and since the queue is sequential, we wait for it. >>> pp(list(cm.get_jobs_to_run(now=103))) [] >>> pp(list(cm.get_jobs_to_run(now=105))) [<ChannelJob S2>] >>> cm.notify(db, 'S', 'S2', 2, 0, 10, 105, 'done') >>> pp(list(cm.get_jobs_to_run(now=105))) [<ChannelJob S3>] >>> cm.notify(db, 'S', 'S3', 3, 0, 10, None, 'done') >>> pp(list(cm.get_jobs_to_run(now=105))) [] """ def __init__(self): self._jobs_by_uuid = WeakValueDictionary() self._root_channel = Channel(name='root', parent=None, capacity=1) self._channels_by_name = WeakValueDictionary(root=self._root_channel) @classmethod def parse_simple_config(cls, config_string): """Parse a simple channels configuration string. The general form is as follow: channel(.subchannel)*(:capacity(:key(=value)?)*)? [, ...] If capacity is absent, it defaults to 1. If a key is present without value, it gets True as value. When declaring subchannels, the root channel may be omitted (ie sub:4 is the same as root.sub:4). Returns a list of channel configuration dictionaries. >>> from pprint import pprint as pp >>> pp(ChannelManager.parse_simple_config('root:4')) [{'capacity': 4, 'name': 'root'}] >>> pp(ChannelManager.parse_simple_config('root:4,root.sub:2')) [{'capacity': 4, 'name': 'root'}, {'capacity': 2, 'name': 'root.sub'}] >>> pp(ChannelManager.parse_simple_config('root:4,root.sub:2:' ... 'sequential:k=v')) [{'capacity': 4, 'name': 'root'}, {'capacity': 2, 'k': 'v', 'name': 'root.sub', 'sequential': True}] >>> pp(ChannelManager.parse_simple_config('root')) [{'capacity': 1, 'name': 'root'}] >>> pp(ChannelManager.parse_simple_config('sub:2')) [{'capacity': 2, 'name': 'sub'}] It ignores whitespace around values, and drops empty entries which would be generated by trailing commas, or commented lines on the Odoo config file. >>> pp(ChannelManager.parse_simple_config(''' ... root : 4, ... , ... foo bar:1: k=va lue, ... ''')) [{'capacity': 4, 'name': 'root'}, {'capacity': 1, 'k': 'va lue', 'name': 'foo bar'}] It's also possible to replace commas with line breaks, which is more readable if the channel configuration comes from the odoo config file. >>> pp(ChannelManager.parse_simple_config(''' ... root : 4 ... foo bar:1: k=va lue ... baz ... ''')) [{'capacity': 4, 'name': 'root'}, {'capacity': 1, 'k': 'va lue', 'name': 'foo bar'}, {'capacity': 1, 'name': 'baz'}] """ res = [] config_string = config_string.replace("\n", ",") for channel_config_string in split_strip(config_string, ','): if not channel_config_string: # ignore empty entries (commented lines, trailing commas) continue config = {} config_items = split_strip(channel_config_string, ':') name = config_items[0] if not name: raise ValueError('Invalid channel config %s: ' 'missing channel name' % config_string) config['name'] = name if len(config_items) > 1: capacity = config_items[1] try: config['capacity'] = int(capacity) except: raise ValueError('Invalid channel config %s: ' 'invalid capacity %s' % (config_string, capacity)) for config_item in config_items[2:]: kv = split_strip(config_item, '=') if len(kv) == 1: k, v = kv[0], True elif len(kv) == 2: k, v = kv else: raise ValueError('Invalid channel config %s: ' 'incorrect config item %s' % (config_string, config_item)) if k in config: raise ValueError('Invalid channel config %s: ' 'duplicate key %s' % (config_string, k)) config[k] = v else: config['capacity'] = 1 res.append(config) return res def simple_configure(self, config_string): """Configure the channel manager from a simple configuration string >>> cm = ChannelManager() >>> c = cm.get_channel_by_name('root') >>> c.capacity 1 >>> cm.simple_configure('root:4,autosub.sub:2,seq:1:sequential') >>> cm.get_channel_by_name('root').capacity 4 >>> cm.get_channel_by_name('root').sequential False >>> cm.get_channel_by_name('root.autosub').capacity >>> cm.get_channel_by_name('root.autosub.sub').capacity 2 >>> cm.get_channel_by_name('root.autosub.sub').sequential False >>> cm.get_channel_by_name('autosub.sub').capacity 2 >>> cm.get_channel_by_name('seq').capacity 1 >>> cm.get_channel_by_name('seq').sequential True """ for config in ChannelManager.parse_simple_config(config_string): self.get_channel_from_config(config) def get_channel_from_config(self, config): """Return a Channel object from a parsed configuration. If the channel does not exist it is created. The configuration is applied on the channel before returning it. If some of the parent channels are missing when creating a subchannel, the parent channels are auto created with an infinite capacity (except for the root channel, which defaults to a capacity of 1 when not configured explicity). """ channel = self.get_channel_by_name(config['name'], autocreate=True) channel.configure(config) _logger.info("Configured channel: %s", channel) return channel def get_channel_by_name(self, channel_name, autocreate=False): """Return a Channel object by its name. If it does not exist and autocreate is True, it is created with a default configuration and inserted in the Channels structure. If autocreate is False and the channel does not exist, an exception is raised. >>> cm = ChannelManager() >>> c = cm.get_channel_by_name('root', autocreate=False) >>> c.name 'root' >>> c.fullname 'root' >>> c = cm.get_channel_by_name('root.sub', autocreate=True) >>> c.name 'sub' >>> c.fullname 'root.sub' >>> c = cm.get_channel_by_name('sub', autocreate=True) >>> c.name 'sub' >>> c.fullname 'root.sub' >>> c = cm.get_channel_by_name('autosub.sub', autocreate=True) >>> c.name 'sub' >>> c.fullname 'root.autosub.sub' >>> c = cm.get_channel_by_name(None) >>> c.fullname 'root' >>> c = cm.get_channel_by_name('root.sub') >>> c.fullname 'root.sub' >>> c = cm.get_channel_by_name('sub') >>> c.fullname 'root.sub' """ if not channel_name or channel_name == self._root_channel.name: return self._root_channel if not channel_name.startswith(self._root_channel.name + '.'): channel_name = self._root_channel.name + '.' + channel_name if channel_name in self._channels_by_name: return self._channels_by_name[channel_name] if not autocreate: raise ChannelNotFound('Channel %s not found' % channel_name) parent = self._root_channel for subchannel_name in channel_name.split('.')[1:]: subchannel = parent.get_subchannel_by_name(subchannel_name) if not subchannel: subchannel = Channel(subchannel_name, parent, capacity=None) self._channels_by_name[subchannel.fullname] = subchannel parent = subchannel return parent def notify(self, db_name, channel_name, uuid, seq, date_created, priority, eta, state): try: channel = self.get_channel_by_name(channel_name) except ChannelNotFound: _logger.warning('unknown channel %s, ' 'using root channel for job %s', channel_name, uuid) channel = self._root_channel job = self._jobs_by_uuid.get(uuid) if job: # db_name is invariant assert job.db_name == db_name # date_created is invariant assert job.date_created == date_created # if one of the job properties that influence # scheduling order has changed, we remove the job # from the queues and create a new job object if (seq != job.seq or priority != job.priority or eta != job.eta or channel != job.channel): _logger.debug("job %s properties changed, rescheduling it", uuid) self.remove_job(uuid) job = None if not job: job = ChannelJob(db_name, channel, uuid, seq, date_created, priority, eta) self._jobs_by_uuid[uuid] = job # state transitions if not state or state == DONE: job.channel.set_done(job) elif state == PENDING: job.channel.set_pending(job) elif state in (ENQUEUED, STARTED): job.channel.set_running(job) elif state == FAILED: job.channel.set_failed(job) else: _logger.error("unexpected state %s for job %s", state, job) def remove_job(self, uuid): job = self._jobs_by_uuid.get(uuid) if job: job.channel.remove(job) del self._jobs_by_uuid[job.uuid] def remove_db(self, db_name): for job in self._jobs_by_uuid.values(): if job.db_name == db_name: job.channel.remove(job) del self._jobs_by_uuid[job.uuid] def get_jobs_to_run(self, now): return self._root_channel.get_jobs_to_run(now) def get_wakeup_time(self): return self._root_channel.get_wakeup_time()
34.006604
78
0.562765
ace9cf3fc7e044260419e318a395b2ceb094ecb8
320
py
Python
ProgsByDataset/ACLMAG/docid_to_magid_acl_training_lda.py
ashwath92/MastersThesis
f74755dc0c32f316da3c860dd5dbfa4c9cad97b3
[ "MIT" ]
5
2020-11-05T07:11:54.000Z
2021-08-04T21:37:28.000Z
ProgsByDataset/ACLMAG/docid_to_magid_acl_training_lda.py
ashwath92/MastersThesis
f74755dc0c32f316da3c860dd5dbfa4c9cad97b3
[ "MIT" ]
null
null
null
ProgsByDataset/ACLMAG/docid_to_magid_acl_training_lda.py
ashwath92/MastersThesis
f74755dc0c32f316da3c860dd5dbfa4c9cad97b3
[ "MIT" ]
4
2020-11-05T06:04:38.000Z
2021-08-02T16:25:42.000Z
import pickle docid_to_magid = dict() with open('/home/ashwath/Programs/ACLAAn/acl_training_data.txt', 'r') as file: for i, line in enumerate(file): docid_to_magid[i] = line.split()[0] with open('docid_to_magid_training_acl.pickle', 'wb') as pick: pickle.dump(docid_to_magid, pick) print("Pickled")
32
78
0.709375
ace9cf4c88346cc866dbdd369ea73427e8ba9924
43,955
py
Python
django/db/models/sql/compiler.py
mradziej/django
5d38965743a369981c9a738a298f467f854a2919
[ "BSD-3-Clause" ]
1
2016-05-09T15:03:04.000Z
2016-05-09T15:03:04.000Z
django/db/models/sql/compiler.py
mradziej/django
5d38965743a369981c9a738a298f467f854a2919
[ "BSD-3-Clause" ]
null
null
null
django/db/models/sql/compiler.py
mradziej/django
5d38965743a369981c9a738a298f467f854a2919
[ "BSD-3-Clause" ]
null
null
null
from django.core.exceptions import FieldError from django.db import connections from django.db import transaction from django.db.backends.util import truncate_name from django.db.models.sql.constants import * from django.db.models.sql.datastructures import EmptyResultSet from django.db.models.sql.expressions import SQLEvaluator from django.db.models.sql.query import get_proxied_model, get_order_dir, \ select_related_descend, Query from django.db.utils import DatabaseError class SQLCompiler(object): def __init__(self, query, connection, using): self.query = query self.connection = connection self.using = using self.quote_cache = {} def pre_sql_setup(self): """ Does any necessary class setup immediately prior to producing SQL. This is for things that can't necessarily be done in __init__ because we might not have all the pieces in place at that time. """ if not self.query.tables: self.query.join((None, self.query.model._meta.db_table, None, None)) if (not self.query.select and self.query.default_cols and not self.query.included_inherited_models): self.query.setup_inherited_models() if self.query.select_related and not self.query.related_select_cols: self.fill_related_selections() def quote_name_unless_alias(self, name): """ A wrapper around connection.ops.quote_name that doesn't quote aliases for table names. This avoids problems with some SQL dialects that treat quoted strings specially (e.g. PostgreSQL). """ if name in self.quote_cache: return self.quote_cache[name] if ((name in self.query.alias_map and name not in self.query.table_map) or name in self.query.extra_select): self.quote_cache[name] = name return name r = self.connection.ops.quote_name(name) self.quote_cache[name] = r return r def as_sql(self, with_limits=True, with_col_aliases=False): """ Creates the SQL for this query. Returns the SQL string and list of parameters. If 'with_limits' is False, any limit/offset information is not included in the query. """ if with_limits and self.query.low_mark == self.query.high_mark: return '', () self.pre_sql_setup() out_cols = self.get_columns(with_col_aliases) ordering, ordering_group_by = self.get_ordering() # This must come after 'select' and 'ordering' -- see docstring of # get_from_clause() for details. from_, f_params = self.get_from_clause() qn = self.quote_name_unless_alias where, w_params = self.query.where.as_sql(qn=qn, connection=self.connection) having, h_params = self.query.having.as_sql(qn=qn, connection=self.connection) params = [] for val in self.query.extra_select.itervalues(): params.extend(val[1]) result = ['SELECT'] if self.query.distinct: result.append('DISTINCT') result.append(', '.join(out_cols + self.query.ordering_aliases)) result.append('FROM') result.extend(from_) params.extend(f_params) if where: result.append('WHERE %s' % where) params.extend(w_params) grouping, gb_params = self.get_grouping() if grouping: if ordering: # If the backend can't group by PK (i.e., any database # other than MySQL), then any fields mentioned in the # ordering clause needs to be in the group by clause. if not self.connection.features.allows_group_by_pk: for col, col_params in ordering_group_by: if col not in grouping: grouping.append(str(col)) gb_params.extend(col_params) else: ordering = self.connection.ops.force_no_ordering() result.append('GROUP BY %s' % ', '.join(grouping)) params.extend(gb_params) if having: result.append('HAVING %s' % having) params.extend(h_params) if ordering: result.append('ORDER BY %s' % ', '.join(ordering)) if with_limits: if self.query.high_mark is not None: result.append('LIMIT %d' % (self.query.high_mark - self.query.low_mark)) if self.query.low_mark: if self.query.high_mark is None: val = self.connection.ops.no_limit_value() if val: result.append('LIMIT %d' % val) result.append('OFFSET %d' % self.query.low_mark) if self.query.select_for_update and self.connection.features.has_select_for_update: # If we've been asked for a NOWAIT query but the backend does not support it, # raise a DatabaseError otherwise we could get an unexpected deadlock. nowait = self.query.select_for_update_nowait if nowait and not self.connection.features.has_select_for_update_nowait: raise DatabaseError('NOWAIT is not supported on this database backend.') result.append(self.connection.ops.for_update_sql(nowait=nowait)) return ' '.join(result), tuple(params) def as_nested_sql(self): """ Perform the same functionality as the as_sql() method, returning an SQL string and parameters. However, the alias prefixes are bumped beforehand (in a copy -- the current query isn't changed), and any ordering is removed if the query is unsliced. Used when nesting this query inside another. """ obj = self.query.clone() if obj.low_mark == 0 and obj.high_mark is None: # If there is no slicing in use, then we can safely drop all ordering obj.clear_ordering(True) obj.bump_prefix() return obj.get_compiler(connection=self.connection).as_sql() def get_columns(self, with_aliases=False): """ Returns the list of columns to use in the select statement. If no columns have been specified, returns all columns relating to fields in the model. If 'with_aliases' is true, any column names that are duplicated (without the table names) are given unique aliases. This is needed in some cases to avoid ambiguity with nested queries. """ qn = self.quote_name_unless_alias qn2 = self.connection.ops.quote_name result = ['(%s) AS %s' % (col[0], qn2(alias)) for alias, col in self.query.extra_select.iteritems()] aliases = set(self.query.extra_select.keys()) if with_aliases: col_aliases = aliases.copy() else: col_aliases = set() if self.query.select: only_load = self.deferred_to_columns() for col in self.query.select: if isinstance(col, (list, tuple)): alias, column = col table = self.query.alias_map[alias][TABLE_NAME] if table in only_load and col not in only_load[table]: continue r = '%s.%s' % (qn(alias), qn(column)) if with_aliases: if col[1] in col_aliases: c_alias = 'Col%d' % len(col_aliases) result.append('%s AS %s' % (r, c_alias)) aliases.add(c_alias) col_aliases.add(c_alias) else: result.append('%s AS %s' % (r, qn2(col[1]))) aliases.add(r) col_aliases.add(col[1]) else: result.append(r) aliases.add(r) col_aliases.add(col[1]) else: result.append(col.as_sql(qn, self.connection)) if hasattr(col, 'alias'): aliases.add(col.alias) col_aliases.add(col.alias) elif self.query.default_cols: cols, new_aliases = self.get_default_columns(with_aliases, col_aliases) result.extend(cols) aliases.update(new_aliases) max_name_length = self.connection.ops.max_name_length() result.extend([ '%s%s' % ( aggregate.as_sql(qn, self.connection), alias is not None and ' AS %s' % qn(truncate_name(alias, max_name_length)) or '' ) for alias, aggregate in self.query.aggregate_select.items() ]) for table, col in self.query.related_select_cols: r = '%s.%s' % (qn(table), qn(col)) if with_aliases and col in col_aliases: c_alias = 'Col%d' % len(col_aliases) result.append('%s AS %s' % (r, c_alias)) aliases.add(c_alias) col_aliases.add(c_alias) else: result.append(r) aliases.add(r) col_aliases.add(col) self._select_aliases = aliases return result def get_default_columns(self, with_aliases=False, col_aliases=None, start_alias=None, opts=None, as_pairs=False, local_only=False): """ Computes the default columns for selecting every field in the base model. Will sometimes be called to pull in related models (e.g. via select_related), in which case "opts" and "start_alias" will be given to provide a starting point for the traversal. Returns a list of strings, quoted appropriately for use in SQL directly, as well as a set of aliases used in the select statement (if 'as_pairs' is True, returns a list of (alias, col_name) pairs instead of strings as the first component and None as the second component). """ result = [] if opts is None: opts = self.query.model._meta qn = self.quote_name_unless_alias qn2 = self.connection.ops.quote_name aliases = set() only_load = self.deferred_to_columns() # Skip all proxy to the root proxied model proxied_model = get_proxied_model(opts) if start_alias: seen = {None: start_alias} for field, model in opts.get_fields_with_model(): if local_only and model is not None: continue if start_alias: try: alias = seen[model] except KeyError: if model is proxied_model: alias = start_alias else: link_field = opts.get_ancestor_link(model) alias = self.query.join((start_alias, model._meta.db_table, link_field.column, model._meta.pk.column)) seen[model] = alias else: # If we're starting from the base model of the queryset, the # aliases will have already been set up in pre_sql_setup(), so # we can save time here. alias = self.query.included_inherited_models[model] table = self.query.alias_map[alias][TABLE_NAME] if table in only_load and field.column not in only_load[table]: continue if as_pairs: result.append((alias, field.column)) aliases.add(alias) continue if with_aliases and field.column in col_aliases: c_alias = 'Col%d' % len(col_aliases) result.append('%s.%s AS %s' % (qn(alias), qn2(field.column), c_alias)) col_aliases.add(c_alias) aliases.add(c_alias) else: r = '%s.%s' % (qn(alias), qn2(field.column)) result.append(r) aliases.add(r) if with_aliases: col_aliases.add(field.column) return result, aliases def get_ordering(self): """ Returns a tuple containing a list representing the SQL elements in the "order by" clause, and the list of SQL elements that need to be added to the GROUP BY clause as a result of the ordering. Also sets the ordering_aliases attribute on this instance to a list of extra aliases needed in the select. Determining the ordering SQL can change the tables we need to include, so this should be run *before* get_from_clause(). """ if self.query.extra_order_by: ordering = self.query.extra_order_by elif not self.query.default_ordering: ordering = self.query.order_by else: ordering = self.query.order_by or self.query.model._meta.ordering qn = self.quote_name_unless_alias qn2 = self.connection.ops.quote_name distinct = self.query.distinct select_aliases = self._select_aliases result = [] group_by = [] ordering_aliases = [] if self.query.standard_ordering: asc, desc = ORDER_DIR['ASC'] else: asc, desc = ORDER_DIR['DESC'] # It's possible, due to model inheritance, that normal usage might try # to include the same field more than once in the ordering. We track # the table/column pairs we use and discard any after the first use. processed_pairs = set() for field in ordering: if field == '?': result.append(self.connection.ops.random_function_sql()) continue if isinstance(field, int): if field < 0: order = desc field = -field else: order = asc result.append('%s %s' % (field, order)) group_by.append((field, [])) continue col, order = get_order_dir(field, asc) if col in self.query.aggregate_select: result.append('%s %s' % (qn(col), order)) continue if '.' in field: # This came in through an extra(order_by=...) addition. Pass it # on verbatim. table, col = col.split('.', 1) if (table, col) not in processed_pairs: elt = '%s.%s' % (qn(table), col) processed_pairs.add((table, col)) if not distinct or elt in select_aliases: result.append('%s %s' % (elt, order)) group_by.append((elt, [])) elif get_order_dir(field)[0] not in self.query.extra_select: # 'col' is of the form 'field' or 'field1__field2' or # '-field1__field2__field', etc. for table, col, order in self.find_ordering_name(field, self.query.model._meta, default_order=asc): if (table, col) not in processed_pairs: elt = '%s.%s' % (qn(table), qn2(col)) processed_pairs.add((table, col)) if distinct and elt not in select_aliases: ordering_aliases.append(elt) result.append('%s %s' % (elt, order)) group_by.append((elt, [])) else: elt = qn2(col) if distinct and col not in select_aliases: ordering_aliases.append(elt) result.append('%s %s' % (elt, order)) group_by.append(self.query.extra_select[col]) self.query.ordering_aliases = ordering_aliases return result, group_by def find_ordering_name(self, name, opts, alias=None, default_order='ASC', already_seen=None): """ Returns the table alias (the name might be ambiguous, the alias will not be) and column name for ordering by the given 'name' parameter. The 'name' is of the form 'field1__field2__...__fieldN'. """ name, order = get_order_dir(name, default_order) pieces = name.split(LOOKUP_SEP) if not alias: alias = self.query.get_initial_alias() field, target, opts, joins, last, extra = self.query.setup_joins(pieces, opts, alias, False) alias = joins[-1] col = target.column if not field.rel: # To avoid inadvertent trimming of a necessary alias, use the # refcount to show that we are referencing a non-relation field on # the model. self.query.ref_alias(alias) # Must use left outer joins for nullable fields and their relations. self.query.promote_alias_chain(joins, self.query.alias_map[joins[0]][JOIN_TYPE] == self.query.LOUTER) # If we get to this point and the field is a relation to another model, # append the default ordering for that model. if field.rel and len(joins) > 1 and opts.ordering: # Firstly, avoid infinite loops. if not already_seen: already_seen = set() join_tuple = tuple([self.query.alias_map[j][TABLE_NAME] for j in joins]) if join_tuple in already_seen: raise FieldError('Infinite loop caused by ordering.') already_seen.add(join_tuple) results = [] for item in opts.ordering: results.extend(self.find_ordering_name(item, opts, alias, order, already_seen)) return results if alias: # We have to do the same "final join" optimisation as in # add_filter, since the final column might not otherwise be part of # the select set (so we can't order on it). while 1: join = self.query.alias_map[alias] if col != join[RHS_JOIN_COL]: break self.query.unref_alias(alias) alias = join[LHS_ALIAS] col = join[LHS_JOIN_COL] return [(alias, col, order)] def get_from_clause(self): """ Returns a list of strings that are joined together to go after the "FROM" part of the query, as well as a list any extra parameters that need to be included. Sub-classes, can override this to create a from-clause via a "select". This should only be called after any SQL construction methods that might change the tables we need. This means the select columns and ordering must be done first. """ result = [] qn = self.quote_name_unless_alias qn2 = self.connection.ops.quote_name first = True for alias in self.query.tables: if not self.query.alias_refcount[alias]: continue try: name, alias, join_type, lhs, lhs_col, col, nullable = self.query.alias_map[alias] except KeyError: # Extra tables can end up in self.tables, but not in the # alias_map if they aren't in a join. That's OK. We skip them. continue alias_str = (alias != name and ' %s' % alias or '') if join_type and not first: result.append('%s %s%s ON (%s.%s = %s.%s)' % (join_type, qn(name), alias_str, qn(lhs), qn2(lhs_col), qn(alias), qn2(col))) else: connector = not first and ', ' or '' result.append('%s%s%s' % (connector, qn(name), alias_str)) first = False for t in self.query.extra_tables: alias, unused = self.query.table_alias(t) # Only add the alias if it's not already present (the table_alias() # calls increments the refcount, so an alias refcount of one means # this is the only reference. if alias not in self.query.alias_map or self.query.alias_refcount[alias] == 1: connector = not first and ', ' or '' result.append('%s%s' % (connector, qn(alias))) first = False return result, [] def get_grouping(self): """ Returns a tuple representing the SQL elements in the "group by" clause. """ qn = self.quote_name_unless_alias result, params = [], [] if self.query.group_by is not None: if (len(self.query.model._meta.fields) == len(self.query.select) and self.connection.features.allows_group_by_pk): self.query.group_by = [ (self.query.model._meta.db_table, self.query.model._meta.pk.column) ] group_by = self.query.group_by or [] extra_selects = [] for extra_select, extra_params in self.query.extra_select.itervalues(): extra_selects.append(extra_select) params.extend(extra_params) cols = (group_by + self.query.select + self.query.related_select_cols + extra_selects) for col in cols: if isinstance(col, (list, tuple)): result.append('%s.%s' % (qn(col[0]), qn(col[1]))) elif hasattr(col, 'as_sql'): result.append(col.as_sql(qn, self.connection)) else: result.append('(%s)' % str(col)) return result, params def fill_related_selections(self, opts=None, root_alias=None, cur_depth=1, used=None, requested=None, restricted=None, nullable=None, dupe_set=None, avoid_set=None): """ Fill in the information needed for a select_related query. The current depth is measured as the number of connections away from the root model (for example, cur_depth=1 means we are looking at models with direct connections to the root model). """ if not restricted and self.query.max_depth and cur_depth > self.query.max_depth: # We've recursed far enough; bail out. return if not opts: opts = self.query.get_meta() root_alias = self.query.get_initial_alias() self.query.related_select_cols = [] self.query.related_select_fields = [] if not used: used = set() if dupe_set is None: dupe_set = set() if avoid_set is None: avoid_set = set() orig_dupe_set = dupe_set # Setup for the case when only particular related fields should be # included in the related selection. if requested is None: if isinstance(self.query.select_related, dict): requested = self.query.select_related restricted = True else: restricted = False for f, model in opts.get_fields_with_model(): if not select_related_descend(f, restricted, requested): continue # The "avoid" set is aliases we want to avoid just for this # particular branch of the recursion. They aren't permanently # forbidden from reuse in the related selection tables (which is # what "used" specifies). avoid = avoid_set.copy() dupe_set = orig_dupe_set.copy() table = f.rel.to._meta.db_table promote = nullable or f.null if model: int_opts = opts alias = root_alias alias_chain = [] for int_model in opts.get_base_chain(model): # Proxy model have elements in base chain # with no parents, assign the new options # object and skip to the next base in that # case if not int_opts.parents[int_model]: int_opts = int_model._meta continue lhs_col = int_opts.parents[int_model].column dedupe = lhs_col in opts.duplicate_targets if dedupe: avoid.update(self.query.dupe_avoidance.get((id(opts), lhs_col), ())) dupe_set.add((opts, lhs_col)) int_opts = int_model._meta alias = self.query.join((alias, int_opts.db_table, lhs_col, int_opts.pk.column), exclusions=used, promote=promote) alias_chain.append(alias) for (dupe_opts, dupe_col) in dupe_set: self.query.update_dupe_avoidance(dupe_opts, dupe_col, alias) if self.query.alias_map[root_alias][JOIN_TYPE] == self.query.LOUTER: self.query.promote_alias_chain(alias_chain, True) else: alias = root_alias dedupe = f.column in opts.duplicate_targets if dupe_set or dedupe: avoid.update(self.query.dupe_avoidance.get((id(opts), f.column), ())) if dedupe: dupe_set.add((opts, f.column)) alias = self.query.join((alias, table, f.column, f.rel.get_related_field().column), exclusions=used.union(avoid), promote=promote) used.add(alias) columns, aliases = self.get_default_columns(start_alias=alias, opts=f.rel.to._meta, as_pairs=True) self.query.related_select_cols.extend(columns) if self.query.alias_map[alias][JOIN_TYPE] == self.query.LOUTER: self.query.promote_alias_chain(aliases, True) self.query.related_select_fields.extend(f.rel.to._meta.fields) if restricted: next = requested.get(f.name, {}) else: next = False new_nullable = f.null or promote for dupe_opts, dupe_col in dupe_set: self.query.update_dupe_avoidance(dupe_opts, dupe_col, alias) self.fill_related_selections(f.rel.to._meta, alias, cur_depth + 1, used, next, restricted, new_nullable, dupe_set, avoid) if restricted: related_fields = [ (o.field, o.model) for o in opts.get_all_related_objects() if o.field.unique ] for f, model in related_fields: if not select_related_descend(f, restricted, requested, reverse=True): continue # The "avoid" set is aliases we want to avoid just for this # particular branch of the recursion. They aren't permanently # forbidden from reuse in the related selection tables (which is # what "used" specifies). avoid = avoid_set.copy() dupe_set = orig_dupe_set.copy() table = model._meta.db_table int_opts = opts alias = root_alias alias_chain = [] chain = opts.get_base_chain(f.rel.to) if chain is not None: for int_model in chain: # Proxy model have elements in base chain # with no parents, assign the new options # object and skip to the next base in that # case if not int_opts.parents[int_model]: int_opts = int_model._meta continue lhs_col = int_opts.parents[int_model].column dedupe = lhs_col in opts.duplicate_targets if dedupe: avoid.update((self.query.dupe_avoidance.get(id(opts), lhs_col), ())) dupe_set.add((opts, lhs_col)) int_opts = int_model._meta alias = self.query.join( (alias, int_opts.db_table, lhs_col, int_opts.pk.column), exclusions=used, promote=True, reuse=used ) alias_chain.append(alias) for dupe_opts, dupe_col in dupe_set: self.query.update_dupe_avoidance(dupe_opts, dupe_col, alias) dedupe = f.column in opts.duplicate_targets if dupe_set or dedupe: avoid.update(self.query.dupe_avoidance.get((id(opts), f.column), ())) if dedupe: dupe_set.add((opts, f.column)) alias = self.query.join( (alias, table, f.rel.get_related_field().column, f.column), exclusions=used.union(avoid), promote=True ) used.add(alias) columns, aliases = self.get_default_columns(start_alias=alias, opts=model._meta, as_pairs=True, local_only=True) self.query.related_select_cols.extend(columns) self.query.related_select_fields.extend(model._meta.fields) next = requested.get(f.related_query_name(), {}) new_nullable = f.null or None self.fill_related_selections(model._meta, table, cur_depth+1, used, next, restricted, new_nullable) def deferred_to_columns(self): """ Converts the self.deferred_loading data structure to mapping of table names to sets of column names which are to be loaded. Returns the dictionary. """ columns = {} self.query.deferred_to_data(columns, self.query.deferred_to_columns_cb) return columns def results_iter(self): """ Returns an iterator over the results from executing this query. """ resolve_columns = hasattr(self, 'resolve_columns') fields = None has_aggregate_select = bool(self.query.aggregate_select) # Set transaction dirty if we're using SELECT FOR UPDATE to ensure # a subsequent commit/rollback is executed, so any database locks # are released. if self.query.select_for_update and transaction.is_managed(self.using): transaction.set_dirty(self.using) for rows in self.execute_sql(MULTI): for row in rows: if resolve_columns: if fields is None: # We only set this up here because # related_select_fields isn't populated until # execute_sql() has been called. if self.query.select_fields: fields = self.query.select_fields + self.query.related_select_fields else: fields = self.query.model._meta.fields # If the field was deferred, exclude it from being passed # into `resolve_columns` because it wasn't selected. only_load = self.deferred_to_columns() if only_load: db_table = self.query.model._meta.db_table fields = [f for f in fields if db_table in only_load and f.column in only_load[db_table]] row = self.resolve_columns(row, fields) if has_aggregate_select: aggregate_start = len(self.query.extra_select.keys()) + len(self.query.select) aggregate_end = aggregate_start + len(self.query.aggregate_select) row = tuple(row[:aggregate_start]) + tuple([ self.query.resolve_aggregate(value, aggregate, self.connection) for (alias, aggregate), value in zip(self.query.aggregate_select.items(), row[aggregate_start:aggregate_end]) ]) + tuple(row[aggregate_end:]) yield row def execute_sql(self, result_type=MULTI): """ Run the query against the database and returns the result(s). The return value is a single data item if result_type is SINGLE, or an iterator over the results if the result_type is MULTI. result_type is either MULTI (use fetchmany() to retrieve all rows), SINGLE (only retrieve a single row), or None. In this last case, the cursor is returned if any query is executed, since it's used by subclasses such as InsertQuery). It's possible, however, that no query is needed, as the filters describe an empty set. In that case, None is returned, to avoid any unnecessary database interaction. """ try: sql, params = self.as_sql() if not sql: raise EmptyResultSet except EmptyResultSet: if result_type == MULTI: return empty_iter() else: return cursor = self.connection.cursor() cursor.execute(sql, params) if not result_type: return cursor if result_type == SINGLE: if self.query.ordering_aliases: return cursor.fetchone()[:-len(self.query.ordering_aliases)] return cursor.fetchone() # The MULTI case. if self.query.ordering_aliases: result = order_modified_iter(cursor, len(self.query.ordering_aliases), self.connection.features.empty_fetchmany_value) else: result = iter((lambda: cursor.fetchmany(GET_ITERATOR_CHUNK_SIZE)), self.connection.features.empty_fetchmany_value) if not self.connection.features.can_use_chunked_reads: # If we are using non-chunked reads, we return the same data # structure as normally, but ensure it is all read into memory # before going any further. return list(result) return result class SQLInsertCompiler(SQLCompiler): def placeholder(self, field, val): if field is None: # A field value of None means the value is raw. return val elif hasattr(field, 'get_placeholder'): # Some fields (e.g. geo fields) need special munging before # they can be inserted. return field.get_placeholder(val, self.connection) else: # Return the common case for the placeholder return '%s' def as_sql(self): # We don't need quote_name_unless_alias() here, since these are all # going to be column names (so we can avoid the extra overhead). qn = self.connection.ops.quote_name opts = self.query.model._meta result = ['INSERT INTO %s' % qn(opts.db_table)] result.append('(%s)' % ', '.join([qn(c) for c in self.query.columns])) values = [self.placeholder(*v) for v in self.query.values] result.append('VALUES (%s)' % ', '.join(values)) params = self.query.params if self.return_id and self.connection.features.can_return_id_from_insert: col = "%s.%s" % (qn(opts.db_table), qn(opts.pk.column)) r_fmt, r_params = self.connection.ops.return_insert_id() result.append(r_fmt % col) params = params + r_params return ' '.join(result), params def execute_sql(self, return_id=False): self.return_id = return_id cursor = super(SQLInsertCompiler, self).execute_sql(None) if not (return_id and cursor): return if self.connection.features.can_return_id_from_insert: return self.connection.ops.fetch_returned_insert_id(cursor) return self.connection.ops.last_insert_id(cursor, self.query.model._meta.db_table, self.query.model._meta.pk.column) class SQLDeleteCompiler(SQLCompiler): def as_sql(self): """ Creates the SQL for this query. Returns the SQL string and list of parameters. """ assert len(self.query.tables) == 1, \ "Can only delete from one table at a time." qn = self.quote_name_unless_alias result = ['DELETE FROM %s' % qn(self.query.tables[0])] where, params = self.query.where.as_sql(qn=qn, connection=self.connection) result.append('WHERE %s' % where) return ' '.join(result), tuple(params) class SQLUpdateCompiler(SQLCompiler): def as_sql(self): """ Creates the SQL for this query. Returns the SQL string and list of parameters. """ from django.db.models.base import Model self.pre_sql_setup() if not self.query.values: return '', () table = self.query.tables[0] qn = self.quote_name_unless_alias result = ['UPDATE %s' % qn(table)] result.append('SET') values, update_params = [], [] for field, model, val in self.query.values: if hasattr(val, 'prepare_database_save'): val = val.prepare_database_save(field) else: val = field.get_db_prep_save(val, connection=self.connection) # Getting the placeholder for the field. if hasattr(field, 'get_placeholder'): placeholder = field.get_placeholder(val, self.connection) else: placeholder = '%s' if hasattr(val, 'evaluate'): val = SQLEvaluator(val, self.query, allow_joins=False) name = field.column if hasattr(val, 'as_sql'): sql, params = val.as_sql(qn, self.connection) values.append('%s = %s' % (qn(name), sql)) update_params.extend(params) elif val is not None: values.append('%s = %s' % (qn(name), placeholder)) update_params.append(val) else: values.append('%s = NULL' % qn(name)) if not values: return '', () result.append(', '.join(values)) where, params = self.query.where.as_sql(qn=qn, connection=self.connection) if where: result.append('WHERE %s' % where) return ' '.join(result), tuple(update_params + params) def execute_sql(self, result_type): """ Execute the specified update. Returns the number of rows affected by the primary update query. The "primary update query" is the first non-empty query that is executed. Row counts for any subsequent, related queries are not available. """ cursor = super(SQLUpdateCompiler, self).execute_sql(result_type) rows = cursor and cursor.rowcount or 0 is_empty = cursor is None del cursor for query in self.query.get_related_updates(): aux_rows = query.get_compiler(self.using).execute_sql(result_type) if is_empty: rows = aux_rows is_empty = False return rows def pre_sql_setup(self): """ If the update depends on results from other tables, we need to do some munging of the "where" conditions to match the format required for (portable) SQL updates. That is done here. Further, if we are going to be running multiple updates, we pull out the id values to update at this point so that they don't change as a result of the progressive updates. """ self.query.select_related = False self.query.clear_ordering(True) super(SQLUpdateCompiler, self).pre_sql_setup() count = self.query.count_active_tables() if not self.query.related_updates and count == 1: return # We need to use a sub-select in the where clause to filter on things # from other tables. query = self.query.clone(klass=Query) query.bump_prefix() query.extra = {} query.select = [] query.add_fields([query.model._meta.pk.name]) must_pre_select = count > 1 and not self.connection.features.update_can_self_select # Now we adjust the current query: reset the where clause and get rid # of all the tables we don't need (since they're in the sub-select). self.query.where = self.query.where_class() if self.query.related_updates or must_pre_select: # Either we're using the idents in multiple update queries (so # don't want them to change), or the db backend doesn't support # selecting from the updating table (e.g. MySQL). idents = [] for rows in query.get_compiler(self.using).execute_sql(MULTI): idents.extend([r[0] for r in rows]) self.query.add_filter(('pk__in', idents)) self.query.related_ids = idents else: # The fast path. Filters and updates in one query. self.query.add_filter(('pk__in', query)) for alias in self.query.tables[1:]: self.query.alias_refcount[alias] = 0 class SQLAggregateCompiler(SQLCompiler): def as_sql(self, qn=None): """ Creates the SQL for this query. Returns the SQL string and list of parameters. """ if qn is None: qn = self.quote_name_unless_alias sql = ('SELECT %s FROM (%s) subquery' % ( ', '.join([ aggregate.as_sql(qn, self.connection) for aggregate in self.query.aggregate_select.values() ]), self.query.subquery) ) params = self.query.sub_params return (sql, params) class SQLDateCompiler(SQLCompiler): def results_iter(self): """ Returns an iterator over the results from executing this query. """ resolve_columns = hasattr(self, 'resolve_columns') if resolve_columns: from django.db.models.fields import DateTimeField fields = [DateTimeField()] else: from django.db.backends.util import typecast_timestamp needs_string_cast = self.connection.features.needs_datetime_string_cast offset = len(self.query.extra_select) for rows in self.execute_sql(MULTI): for row in rows: date = row[offset] if resolve_columns: date = self.resolve_columns(row, fields)[offset] elif needs_string_cast: date = typecast_timestamp(str(date)) yield date def empty_iter(): """ Returns an iterator containing no results. """ yield iter([]).next() def order_modified_iter(cursor, trim, sentinel): """ Yields blocks of rows from a cursor. We use this iterator in the special case when extra output columns have been added to support ordering requirements. We must trim those extra columns before anything else can use the results, since they're only needed to make the SQL valid. """ for rows in iter((lambda: cursor.fetchmany(GET_ITERATOR_CHUNK_SIZE)), sentinel): yield [r[:-trim] for r in rows]
44.043086
108
0.567808
ace9cf6a8bb7d18c773fed9514f683879a2256dc
3,750
py
Python
src/models/heads.py
jinensetpal/panoptic-reproducibility
78035073d6c1e3214746dbf433312a9d2173b1ce
[ "MIT" ]
null
null
null
src/models/heads.py
jinensetpal/panoptic-reproducibility
78035073d6c1e3214746dbf433312a9d2173b1ce
[ "MIT" ]
null
null
null
src/models/heads.py
jinensetpal/panoptic-reproducibility
78035073d6c1e3214746dbf433312a9d2173b1ce
[ "MIT" ]
null
null
null
import functools import tensorflow as tf from convolutions import StackedConv2DSame import src.common as common def get_semantic_head(): return PanopticDeepLabSingleHead( 256, common.NUM_CLASSES, common.PRED_KEY_SEMANTIC, name='semantic_head', conv_type=3, bn_layer=functools.partial(tf.keras.layers.BatchNormalization, momentum=14, epsilon=15) ) def get_instance_center_head(): return PanopticDeepLabSingleHead( 32, 1, common.PRED_KEY_INSTANCE_CENTER, name='instance_center_head', conv_type=3, bn_layer=functools.partial(tf.keras.layers.BatchNormalization, momentum=14, epsilon=15) ) def get_instance_regression_head(): return PanopticDeepLabSingleHead( 32, 2, common.PRED_KEY_CENTER_REGRESSION, name='instance_regression_head', conv_type=3, bn_layer=functools.partial(tf.keras.layers.BatchNormalization, momentum=14, epsilon=15) ) class PanopticDeepLabSingleHead(tf.keras.layers.Layer): """A single PanopticDeepLab head layer. This layer takes in the enriched features from a decoder and adds two convolutions on top. """ def __init__(self, intermediate_channels, output_channels, pred_key, name, conv_type='depthwise_separable_conv', bn_layer=tf.keras.layers.BatchNormalization): """Initializes a single PanopticDeepLab head. Args: intermediate_channels: An integer specifying the number of filters of the first 5x5 convolution. output_channels: An integer specifying the number of filters of the second 1x1 convolution. pred_key: A string specifying the key of the output dictionary. name: A string specifying the name of this head. conv_type: String, specifying head convolution type. Support 'depthwise_separable_conv' and 'standard_conv'. bn_layer: An optional tf.keras.layers.Layer that computes the normalization (default: tf.keras.layers.BatchNormalization). """ super(PanopticDeepLabSingleHead, self).__init__(name=name) self._pred_key = pred_key # todo: It's possible that here we can use simple kera conv2d layers instead of the fancy deeplab one, # todo: that will save the entire convolutions.py file self.conv_block = StackedConv2DSame( conv_type=conv_type, num_layers=1, output_channels=intermediate_channels, kernel_size=5, name='conv_block', use_bias=False, use_bn=True, bn_layer=bn_layer, activation='relu') self.final_conv = tf.keras.layers.Conv2D( output_channels, kernel_size=1, name='final_conv', kernel_initializer=tf.keras.initializers.TruncatedNormal(stddev=0.01)) def call(self, features, training=False): """Performs a forward pass. Args: features: A tf.Tensor with shape [batch, height, width, channels]. training: A boolean flag indicating whether training behavior should be used (default: False). Returns: The dictionary containing the predictions under the specified key. """ x = self.conv_block(features, training=training) return {self._pred_key: self.final_conv(x)}
34.722222
111
0.612
ace9cfe373e7db90e35ab159501f1a1bf31ad8fc
3,606
py
Python
src/cli/__main__.py
lbarczynski/dotnet-core-repository
1173648561e176149a5d3cd3545ecf762aa84037
[ "MIT" ]
1
2020-01-13T11:15:43.000Z
2020-01-13T11:15:43.000Z
src/cli/__main__.py
lbarczynski/dotnet-core-repository
1173648561e176149a5d3cd3545ecf762aa84037
[ "MIT" ]
null
null
null
src/cli/__main__.py
lbarczynski/dotnet-core-repository
1173648561e176149a5d3cd3545ecf762aa84037
[ "MIT" ]
null
null
null
#!/usr/bin/python import argparse import os import subprocess from subprocess import call from enum import Enum import logging logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', level=logging.DEBUG) QUIET_MODE = False def echo(text): if QUIET_MODE == False: logging.debug(text) def call_command(path, command, wait=True): execution_dir = os.getcwd() + path echo("Run command \'" + command + "\' in path: " + execution_dir) p = subprocess.Popen(command, cwd=execution_dir, shell=True) if wait: try: p.wait() except KeyboardInterrupt: echo('Application closed with keyboard interrupt') def call_dotnet_command(path, parameters, wait=True): execution_dir = os.getcwd() + path echo("Run command \'dotnet " + parameters + "\' in path: " + execution_dir) p = subprocess.Popen('dotnet ' + parameters, cwd=execution_dir, shell=True) if wait: try: p.wait() except KeyboardInterrupt: echo('Application closed with keyboard interrupt') class BAPPS: def restore(self): call_dotnet_command('/', 'restore') def clean(self): call_dotnet_command('/', 'clean --configuration Debug') call_dotnet_command('/', 'clean --configuration Release') call_command('/tests/BAPPS.Repository.EntityFramework.Core.Tests', 'rm -rf TestResults') call_command('/tests/BAPPS.Repository.InMemory.Tests', 'rm -rf TestResults') def build(self): call_dotnet_command('/', 'build --no-restore --configuration Release') def publish(self): call_dotnet_command('/src/BAPPS.Repository.EntityFramework.Core', 'publish --no-restore --configuration Release') call_dotnet_command('/src/BAPPS.Repository.InMemory', 'publish --no-restore --configuration Release') def test(self): call_dotnet_command('/tests/BAPPS.Repository.EntityFramework.Core.Tests', 'test --no-restore --no-build --configuration Release --logger:"trx;LogFileName=test-results.trx"') call_dotnet_command('/tests/BAPPS.Repository.InMemory.Tests', 'test --no-restore --no-build --configuration Release --logger:"trx;LogFileName=test-results.trx"') def rebuild(self): self.clean() self.restore() self.build() def full(self): self.rebuild() self.publish() self.test() def process_command(self, cmd): if cmd == CMD.restore: self.restore() if cmd == CMD.build: self.build() if cmd == CMD.rebuild: self.rebuild() if cmd == CMD.test: self.test() if cmd == CMD.publish: self.publish() if cmd == CMD.clean: self.clean() if cmd == CMD.full: self.full() class CMD(Enum): clean = 'clean' restore = 'restore' build = 'build' rebuild = 'rebuild' publish = 'publish' test = 'test' full = 'full' def __str__(self): return self.value if __name__ == '__main__': parser = argparse.ArgumentParser(description='BAPPS - Dotnet Core Generic Repository - Command Line Interface Tools') parser.add_argument('command', type=CMD, choices=list(CMD)) parser.add_argument('-q','--quiet', help="Don\'t print any messages to stdout", action='store_true') parser.add_help args = parser.parse_args() QUIET_MODE = args.quiet _BAPPS = BAPPS() _BAPPS.process_command(args.command)
34.342857
182
0.619523
ace9d1ab3dbc6b73ed586bbf064f3c143b91937a
345
py
Python
lg_offliner/scripts/lg_offliner_starter.py
FuriousJulius/lg_ros_nodes
15a84c5022ab2f5b038d11a5589cd4a34010b1d6
[ "Apache-2.0" ]
16
2015-10-10T11:55:37.000Z
2022-02-24T22:47:48.000Z
lg_offliner/scripts/lg_offliner_starter.py
FuriousJulius/lg_ros_nodes
15a84c5022ab2f5b038d11a5589cd4a34010b1d6
[ "Apache-2.0" ]
292
2015-09-29T21:59:53.000Z
2022-03-31T15:59:31.000Z
lg_offliner/scripts/lg_offliner_starter.py
constantegonzalez/lg_ros_nodes
1c7b08c42e90205922602c86805285508d1b7971
[ "Apache-2.0" ]
5
2017-05-03T06:22:43.000Z
2021-08-19T16:54:14.000Z
#!/usr/bin/env python3 """ Just a ROS node load script. Note that it can't be named 'lg_offliner', would be getting Python ImportError. """ NODE_NAME = 'lg_offliner' from lg_offliner import main from lg_common.helpers import run_with_influx_exception_handler if __name__ == "__main__": run_with_influx_exception_handler(main, NODE_NAME)
21.5625
63
0.77971
ace9d1ce4a608fdcae871ef39809eb06a70ad182
1,456
py
Python
backend/config/wsgi.py
radekwlsk/orm-blog
dd10e5713f16c7077f982b7f8d9785fed939d10e
[ "MIT" ]
1
2020-06-04T11:30:03.000Z
2020-06-04T11:30:03.000Z
backend/config/wsgi.py
radekwlsk/orm-blog
dd10e5713f16c7077f982b7f8d9785fed939d10e
[ "MIT" ]
null
null
null
backend/config/wsgi.py
radekwlsk/orm-blog
dd10e5713f16c7077f982b7f8d9785fed939d10e
[ "MIT" ]
1
2020-06-04T11:27:34.000Z
2020-06-04T11:27:34.000Z
""" WSGI config for ORM Blog project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os import sys from django.core.wsgi import get_wsgi_application # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks # if running multiple sites in the same mod_wsgi process. To fix this, use # mod_wsgi daemon mode with each site in its own daemon process, or use # os.environ["DJANGO_SETTINGS_MODULE"] = "config.settings.production" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.production") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
40.444444
79
0.802885
ace9d22025283acae285813ce7ee964de3bc9c2f
30,603
py
Python
tests/h/auth/policy_test.py
kevinjalbert/h
0f260bf59847f27eff720eeb3c3b2468571412b2
[ "BSD-2-Clause" ]
1
2020-06-19T01:49:39.000Z
2020-06-19T01:49:39.000Z
tests/h/auth/policy_test.py
kevinjalbert/h
0f260bf59847f27eff720eeb3c3b2468571412b2
[ "BSD-2-Clause" ]
5
2020-03-24T18:14:50.000Z
2022-03-02T06:56:50.000Z
tests/h/auth/policy_test.py
liquidinvestigations/hypothesis-h
2eebc0b20823fc5bc42a8e8c33551a6d448ad6ba
[ "BSD-2-Clause" ]
null
null
null
# -*- coding: utf-8 -*- import base64 from unittest import mock import pytest from pyramid.interfaces import IAuthenticationPolicy from pyramid.security import Authenticated, Everyone from h.auth.policy import ( AUTH_CLIENT_API_WHITELIST, APIAuthenticationPolicy, AuthClientPolicy, AuthenticationPolicy, TokenAuthenticationPolicy, ) from h.exceptions import InvalidUserId from h.services.user import UserService API_PATHS = ("/api", "/api/foo", "/api/annotations/abc123") NONAPI_PATHS = ("/login", "/account/settings", "/api/badge", "/api/token") AUTH_CLIENT_API_BLACKLIST = [ ("api.groups", "GET"), ("api.user", "POST"), ("group_create", "POST"), ("api.group_member", "DELETE"), ] class TestAuthenticationPolicy: @pytest.fixture(autouse=True) def policy(self): self.api_policy = mock.Mock(spec_set=list(IAuthenticationPolicy)) self.fallback_policy = mock.Mock(spec_set=list(IAuthenticationPolicy)) self.policy = AuthenticationPolicy( api_policy=self.api_policy, fallback_policy=self.fallback_policy ) self.fallback_policy.remember.return_value = [("Cookie", "auth=foobar")] # api_request and nonapi_request are parametrized fixtures, which will # take on each value in the passed `params` sequence in turn. This is a # quick and easy way to generate a named fixture which takes multiple # values and can be used by multiple tests. @pytest.fixture(params=API_PATHS) def api_request(self, request, pyramid_request): pyramid_request.path = request.param return pyramid_request @pytest.fixture(params=NONAPI_PATHS) def nonapi_request(self, request, pyramid_request): pyramid_request.path = request.param return pyramid_request def test_authenticated_userid_uses_fallback_policy_for_nonapi_paths( self, nonapi_request ): result = self.policy.authenticated_userid(nonapi_request) self.fallback_policy.authenticated_userid.assert_called_once_with( nonapi_request ) assert result == self.fallback_policy.authenticated_userid.return_value def test_authenticated_userid_uses_api_policy_for_api_paths(self, api_request): result = self.policy.authenticated_userid(api_request) self.api_policy.authenticated_userid.assert_called_once_with(api_request) assert result == self.api_policy.authenticated_userid.return_value def test_unauthenticated_userid_uses_fallback_policy_for_nonapi_paths( self, nonapi_request ): result = self.policy.unauthenticated_userid(nonapi_request) self.fallback_policy.unauthenticated_userid.assert_called_once_with( nonapi_request ) assert result == self.fallback_policy.unauthenticated_userid.return_value def test_unauthenticated_userid_uses_api_policy_for_api_paths(self, api_request): result = self.policy.unauthenticated_userid(api_request) self.api_policy.unauthenticated_userid.assert_called_once_with(api_request) assert result == self.api_policy.unauthenticated_userid.return_value def test_effective_principals_uses_fallback_policy_for_nonapi_paths( self, nonapi_request ): result = self.policy.effective_principals(nonapi_request) self.fallback_policy.effective_principals.assert_called_once_with( nonapi_request ) assert result == self.fallback_policy.effective_principals.return_value def test_effective_principals_uses_api_policy_for_api_paths(self, api_request): result = self.policy.effective_principals(api_request) self.api_policy.effective_principals.assert_called_once_with(api_request) assert result == self.api_policy.effective_principals.return_value def test_remember_uses_fallback_policy_for_nonapi_paths(self, nonapi_request): result = self.policy.remember(nonapi_request, "foo", bar="baz") self.fallback_policy.remember.assert_called_once_with( nonapi_request, "foo", bar="baz" ) assert result == self.fallback_policy.remember.return_value def test_remember_uses_api_policy_for_api_paths(self, api_request): result = self.policy.remember(api_request, "foo", bar="baz") self.api_policy.remember.assert_called_once_with(api_request, "foo", bar="baz") assert result == self.api_policy.remember.return_value def test_forget_uses_fallback_policy_for_nonapi_paths(self, nonapi_request): result = self.policy.forget(nonapi_request) self.fallback_policy.forget.assert_called_once_with(nonapi_request) assert result == self.fallback_policy.forget.return_value def test_forget_uses_api_policy_for_api_paths(self, api_request): result = self.policy.forget(api_request) self.api_policy.forget.assert_called_once_with(api_request) assert result == self.api_policy.forget.return_value class TestAPIAuthenticationPolicy: def test_authenticated_userid_proxies_to_user_policy_first( self, pyramid_request, api_policy, user_policy, client_policy ): userid = api_policy.authenticated_userid(pyramid_request) user_policy.authenticated_userid.assert_called_once_with(pyramid_request) assert client_policy.authenticated_userid.call_count == 0 assert userid == user_policy.authenticated_userid.return_value @pytest.mark.parametrize("route_name,route_method", AUTH_CLIENT_API_WHITELIST) def test_authenticated_userid_proxies_to_client_policy_if_user_fails( self, pyramid_request, api_policy, user_policy, client_policy, route_name, route_method, ): pyramid_request.method = route_method pyramid_request.matched_route.name = route_name user_policy.authenticated_userid.return_value = None userid = api_policy.authenticated_userid(pyramid_request) user_policy.authenticated_userid.assert_called_once_with(pyramid_request) client_policy.authenticated_userid.assert_called_once_with(pyramid_request) assert userid == client_policy.authenticated_userid.return_value @pytest.mark.parametrize("route_name,route_method", AUTH_CLIENT_API_BLACKLIST) def test_authenticated_userid_does_not_proxy_to_client_policy_if_path_mismatch( self, pyramid_request, api_policy, user_policy, client_policy, route_name, route_method, ): pyramid_request.method = route_method pyramid_request.matched_route.name = route_name user_policy.authenticated_userid.return_value = None userid = api_policy.authenticated_userid(pyramid_request) user_policy.authenticated_userid.assert_called_once_with(pyramid_request) assert client_policy.authenticated_userid.call_count == 0 assert userid == user_policy.authenticated_userid.return_value @pytest.mark.parametrize("route_name,route_method", AUTH_CLIENT_API_WHITELIST) def test_unauthenticated_userid_proxies_to_user_policy_first( self, pyramid_request, api_policy, user_policy, client_policy, route_name, route_method, ): pyramid_request.method = route_method pyramid_request.matched_route.name = route_name userid = api_policy.unauthenticated_userid(pyramid_request) user_policy.unauthenticated_userid.assert_called_once_with(pyramid_request) assert client_policy.unauthenticated_userid.call_count == 0 assert userid == user_policy.unauthenticated_userid.return_value def test_unauthenticated_userid_proxies_to_client_policy_if_user_fails( self, pyramid_request, api_policy, user_policy, client_policy ): user_policy.unauthenticated_userid.return_value = None userid = api_policy.unauthenticated_userid(pyramid_request) user_policy.unauthenticated_userid.assert_called_once_with(pyramid_request) client_policy.unauthenticated_userid.assert_called_once_with(pyramid_request) assert userid == client_policy.unauthenticated_userid.return_value @pytest.mark.parametrize("route_name,route_method", AUTH_CLIENT_API_BLACKLIST) def test_unauthenticated_userid_does_not_proxy_to_client_policy_if_path_mismatch( self, pyramid_request, api_policy, user_policy, client_policy, route_name, route_method, ): pyramid_request.method = route_method pyramid_request.matched_route.name = route_name user_policy.unauthenticated_userid.return_value = None userid = api_policy.unauthenticated_userid(pyramid_request) user_policy.unauthenticated_userid.assert_called_once_with(pyramid_request) assert client_policy.unauthenticated_userid.call_count == 0 assert userid == user_policy.unauthenticated_userid.return_value def test_effective_principals_proxies_to_user_policy_first( self, pyramid_request, api_policy, user_policy, client_policy ): user_policy.effective_principals.return_value = [Everyone, Authenticated] principals = api_policy.effective_principals(pyramid_request) user_policy.effective_principals.assert_called_once_with(pyramid_request) assert client_policy.effective_principals.call_count == 0 assert principals == user_policy.effective_principals.return_value @pytest.mark.parametrize("route_name,route_method", AUTH_CLIENT_API_WHITELIST) def test_effective_principals_proxies_to_client_if_auth_principal_missing( self, pyramid_request, api_policy, user_policy, client_policy, route_name, route_method, ): pyramid_request.method = route_method pyramid_request.matched_route.name = route_name user_policy.effective_principals.return_value = [Everyone] principals = api_policy.effective_principals(pyramid_request) user_policy.effective_principals.assert_called_once_with(pyramid_request) client_policy.effective_principals.assert_called_once_with(pyramid_request) assert principals == client_policy.effective_principals.return_value @pytest.mark.parametrize("route_name,route_method", AUTH_CLIENT_API_BLACKLIST) def test_effective_principals_does_not_proxy_to_client_if_path_mismatch( self, pyramid_request, api_policy, user_policy, client_policy, route_name, route_method, ): pyramid_request.method = route_method pyramid_request.matched_route.name = route_name user_policy.effective_principals.return_value = [Everyone] principals = api_policy.effective_principals(pyramid_request) user_policy.effective_principals.assert_called_once_with(pyramid_request) assert client_policy.effective_principals.call_count == 0 assert principals == user_policy.effective_principals.return_value @pytest.mark.parametrize("route_name,route_method", AUTH_CLIENT_API_WHITELIST) def test_remember_proxies_to_user_policy_first( self, pyramid_request, api_policy, user_policy, route_name, route_method ): pyramid_request.method = route_method pyramid_request.matched_route.name = route_name remembered = api_policy.remember(pyramid_request, "acct:foo@bar.com") user_policy.remember.assert_called_once_with( pyramid_request, "acct:foo@bar.com" ) assert remembered == user_policy.remember.return_value def test_remember_proxies_to_client_policy_second( self, pyramid_request, api_policy, user_policy, client_policy ): user_policy.remember.return_value = [] remembered = api_policy.remember(pyramid_request, "acct:foo@bar.com") user_policy.remember.assert_called_once_with( pyramid_request, "acct:foo@bar.com" ) client_policy.remember.assert_called_once_with( pyramid_request, "acct:foo@bar.com" ) assert remembered == client_policy.remember.return_value @pytest.mark.parametrize("route_name,route_method", AUTH_CLIENT_API_BLACKLIST) def test_remember_does_not_proxy_to_client_if_path_mismatch( self, pyramid_request, api_policy, user_policy, client_policy, route_name, route_method, ): pyramid_request.method = route_method pyramid_request.matched_route.name = route_name user_policy.remember.return_value = [] remembered = api_policy.remember(pyramid_request, "acct:foo@bar.com") user_policy.remember.assert_called_once_with( pyramid_request, "acct:foo@bar.com" ) assert client_policy.remember.call_count == 0 assert remembered == user_policy.remember.return_value @pytest.mark.parametrize("route_name,route_method", AUTH_CLIENT_API_WHITELIST) def test_forget_proxies_to_user_policy_first( self, pyramid_request, api_policy, user_policy, route_name, route_method ): pyramid_request.method = route_method pyramid_request.matched_route.name = route_name forgot = api_policy.forget(pyramid_request) user_policy.forget.assert_called_once_with(pyramid_request) assert forgot == user_policy.forget.return_value def test_forget_proxies_to_client_policy_second( self, pyramid_request, api_policy, user_policy, client_policy ): user_policy.forget.return_value = [] forgot = api_policy.forget(pyramid_request) user_policy.forget.assert_called_once_with(pyramid_request) client_policy.forget.assert_called_once_with(pyramid_request) assert forgot == client_policy.forget.return_value @pytest.mark.parametrize("route_name,route_method", AUTH_CLIENT_API_BLACKLIST) def test_forget_does_not_proxy_to_client_if_path_mismatch( self, pyramid_request, api_policy, user_policy, client_policy, route_name, route_method, ): pyramid_request.method = route_method pyramid_request.matched_route.name = route_name user_policy.forget.return_value = [] forgot = api_policy.forget(pyramid_request) user_policy.forget.assert_called_once_with(pyramid_request) assert client_policy.forget.call_count == 0 assert forgot == user_policy.forget.return_value @pytest.fixture def client_policy(self): return mock.create_autospec(AuthClientPolicy, instance=True, spec_set=True) @pytest.fixture def user_policy(self): return mock.create_autospec( TokenAuthenticationPolicy, instance=True, spec_set=True ) @pytest.fixture def api_policy(self, client_policy, user_policy): return APIAuthenticationPolicy( user_policy=user_policy, client_policy=client_policy ) @pytest.fixture def pyramid_request(self, pyramid_request): pyramid_request.matched_route.name = "api.groups" pyramid_request.method = "POST" return pyramid_request class TestAuthClientAuthenticationPolicy: def test_it_instantiates_a_BasicAuthAuthenticationPolicy( self, BasicAuthAuthenticationPolicy ): AuthClientPolicy() BasicAuthAuthenticationPolicy.assert_called_once_with( check=AuthClientPolicy.check ) def test_unauthenticated_userid_returns_forwarded_user_if_present( self, auth_policy, pyramid_request ): pyramid_request.headers["X-Forwarded-User"] = "filbert" userid = auth_policy.unauthenticated_userid(pyramid_request) assert userid == "filbert" def test_unauthenticated_userid_returns_clientid_if_no_forwarded_user( self, auth_policy, pyramid_request, auth_client ): userid = auth_policy.unauthenticated_userid(pyramid_request) assert userid == auth_client.id def test_unauthenticated_userid_proxies_to_basic_auth_if_no_forwarded_user( self, pyramid_request, BasicAuthAuthenticationPolicy ): auth_policy = AuthClientPolicy() unauth_id = auth_policy.unauthenticated_userid(pyramid_request) BasicAuthAuthenticationPolicy.return_value.unauthenticated_userid.assert_called_once_with( pyramid_request ) assert ( unauth_id == BasicAuthAuthenticationPolicy.return_value.unauthenticated_userid.return_value ) def test_unauthenticated_userid_doesnt_proxy_to_basic_auth_if_forwarded_user( self, pyramid_request, BasicAuthAuthenticationPolicy ): pyramid_request.headers["X-Forwarded-User"] = "dingbat" auth_policy = AuthClientPolicy() auth_policy.unauthenticated_userid(pyramid_request) assert ( BasicAuthAuthenticationPolicy.return_value.unauthenticated_userid.call_count == 0 ) def test_authenticated_userid_returns_None_if_no_forwarded_userid( self, auth_policy, pyramid_request ): userid = auth_policy.authenticated_userid(pyramid_request) assert userid is None def test_authenticated_userid_proxies_to_basic_auth_policy_if_forwarded_user( self, pyramid_request, BasicAuthAuthenticationPolicy ): pyramid_request.headers["X-Forwarded-User"] = "dingbat" auth_policy = AuthClientPolicy() auth_policy.authenticated_userid(pyramid_request) BasicAuthAuthenticationPolicy.return_value.unauthenticated_userid.assert_called_once_with( pyramid_request ) BasicAuthAuthenticationPolicy.return_value.callback.assert_called_once_with( BasicAuthAuthenticationPolicy.return_value.unauthenticated_userid.return_value, pyramid_request, ) def test_authenticated_userid_does_not_proxy_if_no_forwarded_user( self, pyramid_request, BasicAuthAuthenticationPolicy ): auth_policy = AuthClientPolicy() auth_policy.authenticated_userid(pyramid_request) assert ( BasicAuthAuthenticationPolicy.return_value.unauthenticated_userid.call_count == 0 ) assert BasicAuthAuthenticationPolicy.return_value.callback.call_count == 0 def test_authenticated_userid_returns_userid_if_callback_ok( self, auth_policy, pyramid_request ): # check callback is mocked to return [], which is "OK" pyramid_request.headers["X-Forwarded-User"] = "dingbat" userid = auth_policy.authenticated_userid(pyramid_request) assert userid == "dingbat" def test_authenticated_userid_returns_None_if_callback_not_OK( self, check, pyramid_request ): check.return_value = None policy = AuthClientPolicy(check=check) pyramid_request.headers["X-Forwarded-User"] = "dingbat" userid = policy.authenticated_userid(pyramid_request) assert userid is None def test_effective_principals_proxies_to_basic_auth( self, pyramid_request, check, BasicAuthAuthenticationPolicy ): auth_policy = AuthClientPolicy() auth_policy.effective_principals(pyramid_request) BasicAuthAuthenticationPolicy.return_value.effective_principals.assert_called_once_with( pyramid_request ) def test_effective_principals_returns_list_containing_callback_return_value( self, pyramid_request, check ): check.return_value = ["foople", "blueberry"] policy = AuthClientPolicy(check=check) principals = policy.effective_principals(pyramid_request) assert "foople" in principals assert "blueberry" in principals def test_effective_principals_returns_only_Everyone_if_callback_returns_None( self, pyramid_request, check ): check.return_value = None policy = AuthClientPolicy(check=check) principals = policy.effective_principals(pyramid_request) assert principals == ["system.Everyone"] def test_forget_does_nothing(self, auth_policy, pyramid_request): assert auth_policy.forget(pyramid_request) == [] def test_remember_does_nothing(self, auth_policy, pyramid_request): assert auth_policy.remember(pyramid_request, "whoever") == [] def test_check_proxies_to_verify_auth_client( self, pyramid_request, verify_auth_client ): AuthClientPolicy.check("someusername", "somepassword", pyramid_request) verify_auth_client.assert_called_once_with( "someusername", "somepassword", pyramid_request.db ) def test_check_returns_None_if_verify_auth_client_fails( self, pyramid_request, verify_auth_client ): verify_auth_client.return_value = None principals = AuthClientPolicy.check( "someusername", "somepassword", pyramid_request ) assert principals is None def test_check_proxies_to_principals_for_auth_client_if_no_forwarded_user( self, pyramid_request, verify_auth_client, principals_for_auth_client ): principals = AuthClientPolicy.check( "someusername", "somepassword", pyramid_request ) assert principals == principals_for_auth_client.return_value principals_for_auth_client.assert_called_once_with( verify_auth_client.return_value ) def test_check_doesnt_proxy_to_principals_for_auth_client_if_forwarded_user( self, user_service, pyramid_request, verify_auth_client, principals_for_auth_client, ): pyramid_request.headers["X-Forwarded-User"] = "acct:flop@woebang.baz" AuthClientPolicy.check("someusername", "somepassword", pyramid_request) assert principals_for_auth_client.call_count == 0 def test_check_fetches_user_if_forwarded_user( self, pyramid_request, verify_auth_client, user_service ): pyramid_request.headers["X-Forwarded-User"] = "acct:flop@woebang.baz" AuthClientPolicy.check("someusername", "somepassword", pyramid_request) user_service.fetch.assert_called_once_with("acct:flop@woebang.baz") def test_check_returns_None_if_userid_is_invalid( self, pyramid_request, verify_auth_client, user_service ): pyramid_request.headers["X-Forwarded-User"] = "badly_formatted" user_service.fetch.side_effect = InvalidUserId("badly_formatted") principals = AuthClientPolicy.check( mock.sentinel.username, mock.sentinel.password, pyramid_request ) assert principals is None def test_check_returns_None_if_fetch_forwarded_user_fails( self, pyramid_request, verify_auth_client, user_service ): user_service.fetch.return_value = None pyramid_request.headers["X-Forwarded-User"] = "acct:flop@woebang.baz" principals = AuthClientPolicy.check( "someusername", "somepassword", pyramid_request ) assert principals is None def test_check_returns_None_if_forwarded_user_authority_mismatch( self, pyramid_request, verify_auth_client, user_service, factories ): mismatched_user = factories.User(authority="two.com") verify_auth_client.return_value = factories.ConfidentialAuthClient( authority="one.com" ) user_service.fetch.return_value = mismatched_user pyramid_request.headers["X-Forwarded-User"] = mismatched_user.userid principals = AuthClientPolicy.check( "someusername", "somepassword", pyramid_request ) assert principals is None def test_it_proxies_to_principals_for_user_if_fetch_forwarded_user_ok( self, pyramid_request, verify_auth_client, user_service, factories, principals_for_auth_client_user, ): matched_user = factories.User(authority="one.com") verify_auth_client.return_value = factories.ConfidentialAuthClient( authority="one.com" ) user_service.fetch.return_value = matched_user pyramid_request.headers["X-Forwarded-User"] = matched_user.userid principals = AuthClientPolicy.check( "someusername", "somepassword", pyramid_request ) principals_for_auth_client_user.assert_called_once_with( matched_user, verify_auth_client.return_value ) assert principals == principals_for_auth_client_user.return_value @pytest.fixture def user_service(self, pyramid_config): service = mock.create_autospec(UserService, spec_set=True, instance=True) service.fetch.return_value = None pyramid_config.register_service(service, name="user") return service @pytest.fixture def principals_for_auth_client(self, patch): return patch("h.auth.util.principals_for_auth_client") @pytest.fixture def principals_for_auth_client_user(self, patch): return patch("h.auth.util.principals_for_auth_client_user") @pytest.fixture def verify_auth_client(self, patch): return patch("h.auth.util.verify_auth_client") @pytest.fixture def check(self): check = mock.create_autospec( AuthClientPolicy.check, spec_set=True, instance=True ) check.return_value = [] return check @pytest.fixture def auth_client(self, factories): return factories.ConfidentialAuthClient(authority="one.com") @pytest.fixture def auth_policy(self, check): auth_policy = AuthClientPolicy(check=check) return auth_policy @pytest.fixture def pyramid_request(self, pyramid_request, auth_client): user_pass = "{client_id}:{client_secret}".format( client_id=auth_client.id, client_secret=auth_client.secret ) encoded = base64.standard_b64encode(user_pass.encode("utf-8")) pyramid_request.headers["Authorization"] = "Basic {creds}".format( creds=encoded.decode("ascii") ) return pyramid_request @pytest.fixture def BasicAuthAuthenticationPolicy(self, patch): return patch("h.auth.policy.BasicAuthAuthenticationPolicy") @pytest.mark.usefixtures("token_service") class TestTokenAuthenticationPolicy: def test_remember_does_nothing(self, pyramid_request): policy = TokenAuthenticationPolicy() assert policy.remember(pyramid_request, "foo") == [] def test_forget_does_nothing(self, pyramid_request): policy = TokenAuthenticationPolicy() assert policy.forget(pyramid_request) == [] def test_unauthenticated_userid_is_none_if_no_token(self, pyramid_request): policy = TokenAuthenticationPolicy() assert policy.unauthenticated_userid(pyramid_request) is None def test_unauthenticated_userid_returns_userid_from_token(self, pyramid_request): policy = TokenAuthenticationPolicy() pyramid_request.auth_token = "valid123" result = policy.unauthenticated_userid(pyramid_request) assert result == "acct:foo@example.com" def test_unauthenticated_userid_returns_none_if_token_invalid( self, pyramid_request, token_service ): policy = TokenAuthenticationPolicy() token_service.validate.return_value = None pyramid_request.auth_token = "abcd123" result = policy.unauthenticated_userid(pyramid_request) assert result is None def test_unauthenticated_userid_returns_userid_from_query_params_token( self, pyramid_request ): """When the path is `/ws` then we look into the query string parameters as well.""" policy = TokenAuthenticationPolicy() pyramid_request.GET["access_token"] = "valid123" pyramid_request.path = "/ws" result = policy.unauthenticated_userid(pyramid_request) assert result == "acct:foo@example.com" def test_unauthenticated_userid_returns_none_for_invalid_query_param_token( self, pyramid_request ): """When the path is `/ws` but the token is invalid, it should still return None.""" policy = TokenAuthenticationPolicy() pyramid_request.GET["access_token"] = "expired" pyramid_request.path = "/ws" result = policy.unauthenticated_userid(pyramid_request) assert result is None def test_unauthenticated_userid_skips_query_param_for_non_ws_requests( self, pyramid_request ): """ When we have a valid token in the `access_token` query param, but it's not a request to /ws, then we should ignore this access token. """ policy = TokenAuthenticationPolicy() pyramid_request.GET["access_token"] = "valid123" pyramid_request.path = "/api" result = policy.unauthenticated_userid(pyramid_request) assert result is None def test_authenticated_userid_uses_callback(self, pyramid_request): def callback(userid, request): return None policy = TokenAuthenticationPolicy(callback=callback) pyramid_request.auth_token = "valid123" result = policy.authenticated_userid(pyramid_request) assert result is None def test_effective_principals_uses_callback(self, pyramid_request): def callback(userid, request): return [userid + ".foo", "group:donkeys"] policy = TokenAuthenticationPolicy(callback=callback) pyramid_request.auth_token = "valid123" result = policy.effective_principals(pyramid_request) assert set(result) > { "acct:foo@example.com", "acct:foo@example.com.foo", "group:donkeys", } @pytest.fixture def fake_token(self): return DummyToken() @pytest.fixture def token_service(self, pyramid_config, fake_token): def validate(token_str): if token_str == "valid123": return fake_token return None svc = mock.Mock(validate=mock.Mock(side_effect=validate)) pyramid_config.register_service(svc, name="auth_token") return svc class DummyToken: def __init__(self, userid="acct:foo@example.com", valid=True): self.userid = userid self._valid = valid def is_valid(self): return self._valid
36.345606
98
0.721269
ace9d2577e3acbeb6ae63a0086d19b8fb0d2c89d
5,677
py
Python
ex4Py.py
xXxPussyDestroyerxXx/Homework
1141ae92ab6760e19d86701da6e2e10cfdc08581
[ "MIT" ]
null
null
null
ex4Py.py
xXxPussyDestroyerxXx/Homework
1141ae92ab6760e19d86701da6e2e10cfdc08581
[ "MIT" ]
null
null
null
ex4Py.py
xXxPussyDestroyerxXx/Homework
1141ae92ab6760e19d86701da6e2e10cfdc08581
[ "MIT" ]
null
null
null
""" *Student Name: Noah Gorny *Student ID: 209399757 *Course Exercise Group: 02 Math *Exercise name: ex4Py """ # To use wordcap and such import string def ReadText(): """ Read the text from "movies.txt" and returns it as lines of text Keyword argument: Return- The text from "movies.txt" """ with open("movies.txt") as text: linesOfText = text.readlines() return linesOfText; def AddToDic(theLines, dic): """ Gets lines of text and sort them inside the dictionary dic The order is- movie: {Set of actors} Keyword argument: TheLines- Lines of text recieved from "movies.txt" Dic- The dictionary to place the text into using the correct order Return- Sorts dic as needed """ # For each line in the lines of the text: for line in theLines: # Lowercase the lines line=line.lower() # Remove the end of line char line=line.translate(None, "\n") # And split them using split lineList=line.split(',') # The actor name is the first name on each line actorName=lineList[0].lstrip() lineList.remove(lineList[0]) # For each movie left in the line for movie in lineList: movie=movie.strip() if movie not in dic: # If the movie is not in the dict yet, add it dic[movie]=set() pass # Add the actor to the set of the movie dic[movie].add(actorName) pass pass return; def MissionOne(dic): """ Does mission one of the Python program- Asks for two movies And an operator and then prints the actors as needed Keyword argument: Dic- The dictionary used as the database of the program Return- Prints the needed actors """ oneInput=raw_input("Please enter two movies and an operator(&,|,^) separated with ',':\n") oneInput=oneInput.split(',') # Var used to determine if the input was ok inputOkay=True for i in range(0,len(oneInput)): oneInput[i]=oneInput[i].strip() oneInput[i]=oneInput[i].lower() # Checks if the two movies exist in the dict: if((oneInput[0] in dic) and (oneInput[1] in dic)): if(oneInput[2]=='|'): # Gets the union actors inputSet=dic[oneInput[0]].union(dic[oneInput[1]]) if(bool(inputSet)): print "The union actors are:" elif(oneInput[2]=='&'): # Gets the intersection actors inputSet=dic[oneInput[0]].intersection(dic[oneInput[1]]) if(bool(inputSet)): print "The intersection actors are:" elif(oneInput[2]=='^'): # Gets the symmetric difference actors inputSet=dic[oneInput[0]].symmetric_difference(dic[oneInput[1]]) if(bool(inputSet)): print "The symmetric difference actors are:" else: # The code should not get into here- bad operator print "Error- BAD operator" inputOkay=False if(inputOkay): if(bool(inputSet)): # If there are actors, print them PrintSet(inputSet) else: # If there is none, print this print "There are no actors in this group." else: # One of the movies is not in the database- print "Error" print "Error" return; def MissionTwo(dic): """ Does mission two of the Python program- Asks for an actor and prints all the actors that played with this actor Keyword argument: Dic- The dictionary used as the database of the program Return- Prints the needed actors """ actorInput=raw_input("Please enter an actor:\n") actorInput=actorInput.lower() actorInput=actorInput.strip() # Var used to determine whether the actors exists in the dict or not actorExist=False # The Co-Actors set used to contain all the actors that played # with the chosen actor. coActors=set() # For each movie in the dict for movie in dic: if actorInput in dic[movie]: # The actor does exists (in this movie) actorExist=True for actor in dic[movie]: if(actor != actorInput): # Add all the other actors that played in the same movie coActors.add(actor) pass pass pass pass if(actorExist): if(bool(coActors)): # There is co-stars, print them print "The actor's co-stars are:" PrintSet(coActors) else: # There is no co-stars, print this instead print "There are no actors in this group." else: # The actor does not exist in the database, print "Error" print "Error" return; def PrintSet(theSet): """ Sorts the set by names, capwords it and then prints the whole set as one line, each element seperated with ',' Keyword argument: TheSet- The set that we need to print Return- Prints the set as the format requires """ # Sort the set by names and make it into a list newList=sorted(theSet) for i in range(0, len(newList)): # Capwords each name in the list newList[i]=string.capwords(newList[i]) # Prints the whole list with the elements seperated with ',' print ', '.join(newList) return; def main(): # Creating the database print "Processing..." # Creating dic as a new dictionary dic={} # Var used to know when to stop the main loop run=True # Read the text from "movies.txt" theLines=ReadText() # Process it into dic AddToDic(theLines, dic) # While the main loop in running: while run: print "Please select an option:" print "1) Query by movies" print "2) Query by actor" print "3) Quit" choice= input("") if(choice==1): # Do mission number one MissionOne(dic) elif(choice==2): # Do mission number two MissionTwo(dic) elif(choice==3): # End the program run=False else: # Bad key pressed print("BUG!!\n Not supposed to get in here") # End of the program return 1; if __name__ == "__main__": # To start the program properly main()
27.425121
92
0.669544
ace9d3ffb6752de3e34ff3b0e981b9a6fcf5eec6
3,875
py
Python
kay/management/update_translations.py
Letractively/kay-framework
a4cfabe3497e13c3785e5ec381b9cff11a378df3
[ "Apache-2.0", "BSD-3-Clause" ]
1
2015-11-05T08:30:09.000Z
2015-11-05T08:30:09.000Z
kay/management/update_translations.py
ianlewis/kay
1bf28487dc2a273eaa44d442aec8baa6453240b7
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
kay/management/update_translations.py
ianlewis/kay
1bf28487dc2a273eaa44d442aec8baa6453240b7
[ "Apache-2.0", "BSD-3-Clause" ]
1
2016-05-23T16:30:15.000Z
2016-05-23T16:30:15.000Z
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Update the translations ~~~~~~~~~~~~~~~~~~~~~~~ Update the translations from the POT. :Copyright: (c) 2009 Accense Technology, Inc. All rights reserved. :copyright: (c) 2009 by the Zine Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. This file originally derives from Zine Project. """ from os import path, listdir, rename import sys import kay kay.setup_syspath() from babel import Locale from babel.messages import Catalog from babel.messages.pofile import write_po, read_po from kay.management.utils import ( print_status, get_user_apps, ) domains = ['messages', 'jsmessages'] def do_update_translations(target=("t", ""), lang=("l", ""), statistics=("s", False), i18n_dir=("i", ""), all=("a", False)): """ Update existing translations with updated pot files. """ if not target and not all: print_status('Please specify target.') sys.exit(1) elif target == 'kay': print_status('Updating core strings') root = path.join(kay.KAY_DIR, 'i18n') elif all: targets = get_user_apps() for target in targets: do_update_translations(target=target, lang=lang, statistics=statistics, i18n_dir=None, all=False) do_update_translations(target=kay.PROJECT_DIR, lang=lang, statistics=statistics, i18n_dir=None, all=False) sys.exit(0) else: if i18n_dir: root = i18n_dir else: root = path.join(target, 'i18n') if not path.isdir(root): print_status('source folder missing') sys.exit(1) print_status('Updating %s' % root) for domain in domains: if lang: filepath = path.join(root, lang, 'LC_MESSAGES', domain+'.po') if not path.exists(filepath): print_status("%s not found, skipped." % filepath) continue try: f = file(path.join(root, domain+'.pot')) except IOError: print_status('Can not open file: %s, skipped.' % path.join(root, domain+'.pot')) continue try: template = read_po(f) finally: f.close() po_files = [] for lang_dir in listdir(root): filename = path.join(root, lang_dir, 'LC_MESSAGES', domain+'.po') if lang and filename != \ path.join(root, lang, 'LC_MESSAGES', domain+'.po'): continue if path.exists(filename): print_status('Updating %s' % filename, nl=False) locale = Locale.parse(lang_dir) f = file(filename) try: catalog = read_po(f, locale=locale, domain=domain) finally: f.close() catalog.update(template) # XXX: this is kinda dangerous, but as we are using a # revision control system anyways that shouldn't make # too many problems f = file(filename, 'w') try: write_po(f, catalog, ignore_obsolete=True, include_previous=False, width=79) finally: if statistics: translated = fuzzy = percentage = 0 for message in list(catalog)[1:]: if message.string: translated +=1 if 'fuzzy' in message.flags: fuzzy += 1 if len(catalog): percentage = translated * 100 // len(catalog) print_status("-> %d of %d messages (%d%%) translated" % ( translated, len(catalog), percentage), nl=False) if fuzzy: if fuzzy == 1: print_status("%d of which is fuzzy" % fuzzy, nl=False) else: print_status("%d of which are fuzzy" % fuzzy, nl=False) print_status() else: print_status() f.close() print_status('All done.')
31.25
77
0.578323
ace9d5bfca65a63587ec935ae49d7a1c72d77c21
10,504
py
Python
magnum/tests/unit/objects/test_cluster.py
mail2nsrajesh/magnum
2e7e5a77967028c961337177ce577eb936c3845c
[ "Apache-2.0" ]
null
null
null
magnum/tests/unit/objects/test_cluster.py
mail2nsrajesh/magnum
2e7e5a77967028c961337177ce577eb936c3845c
[ "Apache-2.0" ]
null
null
null
magnum/tests/unit/objects/test_cluster.py
mail2nsrajesh/magnum
2e7e5a77967028c961337177ce577eb936c3845c
[ "Apache-2.0" ]
null
null
null
# Copyright 2015 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import mock from oslo_utils import uuidutils from testtools.matchers import HasLength from magnum.common import exception from magnum import objects from magnum.tests.unit.db import base from magnum.tests.unit.db import utils class TestClusterObject(base.DbTestCase): def setUp(self): super(TestClusterObject, self).setUp() self.fake_cluster = utils.get_test_cluster() self.fake_cluster['trust_id'] = 'trust_id' self.fake_cluster['trustee_username'] = 'trustee_user' self.fake_cluster['trustee_user_id'] = 'trustee_user_id' self.fake_cluster['trustee_password'] = 'password' self.fake_cluster['coe_version'] = 'fake-coe-version' self.fake_cluster['container_version'] = 'fake-container-version' cluster_template_id = self.fake_cluster['cluster_template_id'] self.fake_cluster_template = objects.ClusterTemplate( uuid=cluster_template_id) self.fake_cluster['keypair'] = 'keypair1' self.fake_cluster['docker_volume_size'] = 3 @mock.patch('magnum.objects.ClusterTemplate.get_by_uuid') def test_get_by_id(self, mock_cluster_template_get): cluster_id = self.fake_cluster['id'] with mock.patch.object(self.dbapi, 'get_cluster_by_id', autospec=True) as mock_get_cluster: mock_cluster_template_get.return_value = self.fake_cluster_template mock_get_cluster.return_value = self.fake_cluster cluster = objects.Cluster.get(self.context, cluster_id) mock_get_cluster.assert_called_once_with(self.context, cluster_id) self.assertEqual(self.context, cluster._context) self.assertEqual(cluster.cluster_template_id, cluster.cluster_template.uuid) @mock.patch('magnum.objects.ClusterTemplate.get_by_uuid') def test_get_by_uuid(self, mock_cluster_template_get): uuid = self.fake_cluster['uuid'] with mock.patch.object(self.dbapi, 'get_cluster_by_uuid', autospec=True) as mock_get_cluster: mock_cluster_template_get.return_value = self.fake_cluster_template mock_get_cluster.return_value = self.fake_cluster cluster = objects.Cluster.get(self.context, uuid) mock_get_cluster.assert_called_once_with(self.context, uuid) self.assertEqual(self.context, cluster._context) self.assertEqual(cluster.cluster_template_id, cluster.cluster_template.uuid) @mock.patch('magnum.objects.ClusterTemplate.get_by_uuid') def test_get_by_name(self, mock_cluster_template_get): name = self.fake_cluster['name'] with mock.patch.object(self.dbapi, 'get_cluster_by_name', autospec=True) as mock_get_cluster: mock_cluster_template_get.return_value = self.fake_cluster_template mock_get_cluster.return_value = self.fake_cluster cluster = objects.Cluster.get_by_name(self.context, name) mock_get_cluster.assert_called_once_with(self.context, name) self.assertEqual(self.context, cluster._context) self.assertEqual(cluster.cluster_template_id, cluster.cluster_template.uuid) def test_get_bad_id_and_uuid(self): self.assertRaises(exception.InvalidIdentity, objects.Cluster.get, self.context, 'not-a-uuid') @mock.patch('magnum.objects.ClusterTemplate.get_by_uuid') def test_list(self, mock_cluster_template_get): with mock.patch.object(self.dbapi, 'get_cluster_list', autospec=True) as mock_get_list: mock_get_list.return_value = [self.fake_cluster] mock_cluster_template_get.return_value = self.fake_cluster_template clusters = objects.Cluster.list(self.context) self.assertEqual(1, mock_get_list.call_count) self.assertThat(clusters, HasLength(1)) self.assertIsInstance(clusters[0], objects.Cluster) self.assertEqual(self.context, clusters[0]._context) self.assertEqual(clusters[0].cluster_template_id, clusters[0].cluster_template.uuid) @mock.patch('magnum.objects.ClusterTemplate.get_by_uuid') def test_list_all(self, mock_cluster_template_get): with mock.patch.object(self.dbapi, 'get_cluster_list', autospec=True) as mock_get_list: mock_get_list.return_value = [self.fake_cluster] mock_cluster_template_get.return_value = self.fake_cluster_template self.context.all_tenants = True clusters = objects.Cluster.list(self.context) mock_get_list.assert_called_once_with( self.context, limit=None, marker=None, filters=None, sort_dir=None, sort_key=None) self.assertEqual(1, mock_get_list.call_count) self.assertThat(clusters, HasLength(1)) self.assertIsInstance(clusters[0], objects.Cluster) self.assertEqual(self.context, clusters[0]._context) @mock.patch('magnum.objects.ClusterTemplate.get_by_uuid') def test_list_with_filters(self, mock_cluster_template_get): with mock.patch.object(self.dbapi, 'get_cluster_list', autospec=True) as mock_get_list: mock_get_list.return_value = [self.fake_cluster] mock_cluster_template_get.return_value = self.fake_cluster_template filters = {'name': 'cluster1'} clusters = objects.Cluster.list(self.context, filters=filters) mock_get_list.assert_called_once_with(self.context, sort_key=None, sort_dir=None, filters=filters, limit=None, marker=None) self.assertEqual(1, mock_get_list.call_count) self.assertThat(clusters, HasLength(1)) self.assertIsInstance(clusters[0], objects.Cluster) self.assertEqual(self.context, clusters[0]._context) @mock.patch('magnum.objects.ClusterTemplate.get_by_uuid') def test_create(self, mock_cluster_template_get): with mock.patch.object(self.dbapi, 'create_cluster', autospec=True) as mock_create_cluster: mock_cluster_template_get.return_value = self.fake_cluster_template mock_create_cluster.return_value = self.fake_cluster cluster = objects.Cluster(self.context, **self.fake_cluster) cluster.create() mock_create_cluster.assert_called_once_with(self.fake_cluster) self.assertEqual(self.context, cluster._context) @mock.patch('magnum.objects.ClusterTemplate.get_by_uuid') def test_destroy(self, mock_cluster_template_get): uuid = self.fake_cluster['uuid'] with mock.patch.object(self.dbapi, 'get_cluster_by_uuid', autospec=True) as mock_get_cluster: mock_get_cluster.return_value = self.fake_cluster mock_cluster_template_get.return_value = self.fake_cluster_template with mock.patch.object(self.dbapi, 'destroy_cluster', autospec=True) as mock_destroy_cluster: cluster = objects.Cluster.get_by_uuid(self.context, uuid) cluster.destroy() mock_get_cluster.assert_called_once_with(self.context, uuid) mock_destroy_cluster.assert_called_once_with(uuid) self.assertEqual(self.context, cluster._context) @mock.patch('magnum.objects.ClusterTemplate.get_by_uuid') def test_save(self, mock_cluster_template_get): uuid = self.fake_cluster['uuid'] with mock.patch.object(self.dbapi, 'get_cluster_by_uuid', autospec=True) as mock_get_cluster: mock_cluster_template_get.return_value = self.fake_cluster_template mock_get_cluster.return_value = self.fake_cluster with mock.patch.object(self.dbapi, 'update_cluster', autospec=True) as mock_update_cluster: cluster = objects.Cluster.get_by_uuid(self.context, uuid) cluster.node_count = 10 cluster.master_count = 5 cluster.save() mock_get_cluster.assert_called_once_with(self.context, uuid) mock_update_cluster.assert_called_once_with( uuid, {'node_count': 10, 'master_count': 5, 'cluster_template': self.fake_cluster_template}) self.assertEqual(self.context, cluster._context) @mock.patch('magnum.objects.ClusterTemplate.get_by_uuid') def test_refresh(self, mock_cluster_template_get): uuid = self.fake_cluster['uuid'] new_uuid = uuidutils.generate_uuid() returns = [dict(self.fake_cluster, uuid=uuid), dict(self.fake_cluster, uuid=new_uuid)] expected = [mock.call(self.context, uuid), mock.call(self.context, uuid)] with mock.patch.object(self.dbapi, 'get_cluster_by_uuid', side_effect=returns, autospec=True) as mock_get_cluster: mock_cluster_template_get.return_value = self.fake_cluster_template cluster = objects.Cluster.get_by_uuid(self.context, uuid) self.assertEqual(uuid, cluster.uuid) cluster.refresh() self.assertEqual(new_uuid, cluster.uuid) self.assertEqual(expected, mock_get_cluster.call_args_list) self.assertEqual(self.context, cluster._context)
53.050505
79
0.658511
ace9d6a8b9a4e13fb0220b5446be54377d3060f2
7,911
py
Python
BetaWarning/SAC_discrete_beta.py
zhangtjtongxue/DL_RL_Zoo
fe8393a941a8c22205b9dc5534f399cf7860f409
[ "Apache-2.0" ]
1
2021-06-08T08:20:31.000Z
2021-06-08T08:20:31.000Z
BetaWarning/SAC_discrete_beta.py
zhangtjtongxue/DL_RL_Zoo
fe8393a941a8c22205b9dc5534f399cf7860f409
[ "Apache-2.0" ]
null
null
null
BetaWarning/SAC_discrete_beta.py
zhangtjtongxue/DL_RL_Zoo
fe8393a941a8c22205b9dc5534f399cf7860f409
[ "Apache-2.0" ]
null
null
null
from AgentRun import * from AgentZoo import * from AgentNet import * import torch.nn.functional as nn_f from torch.distributions import Categorical class QNetTwinShared(nn.Module): # 2020-06-18 def __init__(self, state_dim, action_dim, mid_dim, use_dn, use_sn): # todo super(QNetTwinShared, self).__init__() self.net = nn.Sequential(nn.Linear(state_dim, mid_dim), nn.ReLU(), DenseNet(mid_dim), ) self.net1 = nn.utils.spectral_norm(nn.Linear(mid_dim * 4, action_dim)) self.net2 = nn.utils.spectral_norm(nn.Linear(mid_dim * 4, action_dim)) def forward(self, state): # x = torch.cat((state, action), dim=1) x = self.net(state) q_value = self.net1(x) return q_value def get__q1_q2(self, state): # x = torch.cat((state, action), dim=1) x = self.net(state) q_value1 = self.net1(x) q_value2 = self.net2(x) return q_value1, q_value2 class AgentDiscreteSAC(AgentBasicAC): def __init__(self, state_dim, action_dim, net_dim): super(AgentBasicAC, self).__init__() use_dn = True # and use hard target update use_sn = True # and use hard target update self.learning_rate = 2e-4 self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu") '''network''' actor_dim = net_dim self.act = ActorSAC(state_dim, action_dim, actor_dim, use_dn).to(self.device) self.act.train() self.act_optimizer = torch.optim.Adam(self.act.parameters(), lr=self.learning_rate) self.act_target = ActorSAC(state_dim, action_dim, net_dim, use_dn).to(self.device) self.act_target.eval() self.act_target.load_state_dict(self.act.state_dict()) critic_dim = int(net_dim * 1.25) self.cri = QNetTwinShared(state_dim, action_dim, critic_dim, use_dn, use_sn).to(self.device) self.cri.train() self.cri_optimizer = torch.optim.Adam(self.cri.parameters(), lr=self.learning_rate) self.cri_target = QNetTwinShared(state_dim, action_dim, critic_dim, use_dn, use_sn).to(self.device) self.cri_target.eval() self.cri_target.load_state_dict(self.cri.state_dict()) self.criterion = nn.SmoothL1Loss() '''training record''' self.state = None # env.reset() self.reward_sum = 0.0 self.step = 0 self.update_counter = 0 '''extension: auto-alpha for maximum entropy''' self.log_alpha = torch.zeros(1, requires_grad=True, device=self.device) self.alpha = self.log_alpha.exp() self.alpha_optimizer = torch.optim.Adam((self.log_alpha,), lr=self.learning_rate) self.target_entropy = -1 # why a negative number? Due to Gauss Dist. -> Tanh()? '''extension: auto learning rate of actor''' self.loss_c_sum = 0.0 self.rho = 0.5 '''constant''' self.explore_rate = 1.0 # explore rate when update_buffer(), 1.0 is better than 0.5 self.explore_noise = True # stochastic policy choose noise_std by itself. self.update_freq = 2 ** 7 # delay update frequency, for hard target update def select_actions(self, states, explore_noise=0.0): # 2020-07-07 states = torch.tensor(states, dtype=torch.float32, device=self.device) # state.size == (1, state_dim) actions = self.act(states, explore_noise) # discrete action space if explore_noise == 0.0: # should be more elegant a_ints = actions.argmax(dim=1) else: a_prob = nn_f.softmax(actions, dim=1) a_dist = Categorical(a_prob) a_ints = a_dist.sample() return a_ints.cpu().data.numpy() def update_parameters(self, buffer, max_step, batch_size, repeat_times): update_freq = self.update_freq * repeat_times # delay update frequency, for soft target update self.act.train() loss_a_sum = 0.0 loss_c_sum = 0.0 k = 1.0 + buffer.now_len / buffer.max_len batch_size_ = int(batch_size * k) update_times = int(max_step * k) for i in range(update_times * repeat_times): with torch.no_grad(): reward, mask, state, a_int, next_s = buffer.random_sample(batch_size_, self.device) next_a_noise, next_log_prob = self.act_target.get__a__log_prob(next_s) next_a_prob = nn_f.softmax(next_a_noise, dim=1) # SAC discrete next_q_target = torch.min(*self.cri_target.get__q1_q2(next_s)) # CriticTwin next_q_target = (next_q_target * next_a_prob).sum(dim=1, keepdim=True) # SAC discrete next_q_target = next_q_target - next_log_prob * self.alpha # auto-alpha q_target = reward + mask * next_q_target '''critic_loss''' q1_value, q2_value = self.cri.get__q1_q2(state) # CriticTwin q1_value = q1_value.gather(1, a_int.long()) # SAC discrete q2_value = q2_value.gather(1, a_int.long()) # SAC discrete critic_loss = self.criterion(q1_value, q_target) + self.criterion(q2_value, q_target) loss_c_sum += critic_loss.item() * 0.5 # CriticTwin self.cri_optimizer.zero_grad() critic_loss.backward() self.cri_optimizer.step() '''actor_loss''' if i % repeat_times == 0 and self.rho > 0.001: # (self.rho>0.001) ~= (self.critic_loss<2.6) # stochastic policy a_noise, log_prob = self.act.get__a__log_prob(state) # policy gradient a_prob = nn_f.softmax(a_noise, dim=1) # SAC discrete # auto alpha alpha_loss = -(self.log_alpha * (log_prob + self.target_entropy).detach()).mean() self.alpha_optimizer.zero_grad() alpha_loss.backward() self.alpha_optimizer.step() # policy gradient self.alpha = self.log_alpha.exp() # q_eval_pg = self.cri(state, actions_noise) # policy gradient q_eval_pg = torch.min(*self.cri.get__q1_q2(state)) # policy gradient, stable but slower q_eval_pg = (q_eval_pg * a_prob).sum(dim=1, keepdim=True) # SAC discrete actor_loss = (-q_eval_pg + log_prob * self.alpha).mean() # policy gradient loss_a_sum += actor_loss.item() self.act_optimizer.zero_grad() actor_loss.backward() self.act_optimizer.step() """target update""" self.update_counter += 1 if self.update_counter >= update_freq: self.update_counter = 0 # self.soft_target_update(self.act_target, self.act) # soft target update # self.soft_target_update(self.cri_target, self.cri) # soft target update self.act_target.load_state_dict(self.act.state_dict()) # hard target update self.cri_target.load_state_dict(self.cri.state_dict()) # hard target update rho = np.exp(-(self.loss_c_sum / update_freq) ** 2) self.rho = (self.rho + rho) * 0.5 self.act_optimizer.param_groups[0]['lr'] = self.learning_rate * self.rho self.loss_c_sum = 0.0 loss_a_avg = loss_a_sum / update_times loss_c_avg = loss_c_sum / (update_times * repeat_times) return loss_a_avg, loss_c_avg def run__zoo(gpu_id, cwd='AC_Zoo'): args = Arguments(AgentDiscreteSAC) args.gpu_id = gpu_id args.env_name = "LunarLander-v2" args.cwd = './{}/LL_{}'.format(cwd, gpu_id) args.init_for_training() train_agent_discrete(**vars(args)) if __name__ == '__main__': # run__zoo(gpu_id=0, cwd='DiscreteSAC') run__multi_process(run__zoo, gpu_tuple=((0, 1), (2, 3))[0], cwd='DiscreteSAC')
42.994565
110
0.618253
ace9d8bfe0cc63fd05490da0d4c0f0c7df61b390
81
py
Python
it_project/wms/apps.py
rsk97/Web-GIS-smart-irrigation
0f9d24413a37f3613532383e385605bf8de38446
[ "Apache-2.0" ]
null
null
null
it_project/wms/apps.py
rsk97/Web-GIS-smart-irrigation
0f9d24413a37f3613532383e385605bf8de38446
[ "Apache-2.0" ]
null
null
null
it_project/wms/apps.py
rsk97/Web-GIS-smart-irrigation
0f9d24413a37f3613532383e385605bf8de38446
[ "Apache-2.0" ]
null
null
null
from django.apps import AppConfig class WmsConfig(AppConfig): name = 'wms'
13.5
33
0.728395
ace9d996f242f0f7d6371f2ec6daad55b00d92b4
5,536
py
Python
tests/integration/test_basic_commands.py
PelionIoT/mbl-cli
c932e3a398e4339797166763f725bb268549f503
[ "BSD-3-Clause" ]
null
null
null
tests/integration/test_basic_commands.py
PelionIoT/mbl-cli
c932e3a398e4339797166763f725bb268549f503
[ "BSD-3-Clause" ]
2
2019-08-06T09:11:42.000Z
2019-08-06T12:26:47.000Z
tests/integration/test_basic_commands.py
PelionIoT/mbl-cli
c932e3a398e4339797166763f725bb268549f503
[ "BSD-3-Clause" ]
1
2020-06-17T13:55:44.000Z
2020-06-17T13:55:44.000Z
#!/usr/bin/env python3 # Copyright (c) 2019 Arm Limited and Contributors. All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause import re import time import pytest import pexpect IPV4_RE = r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" DEVICE_HN_RE = r"\d: mbed-linux-os-\d{1,4}: " @pytest.fixture(scope="module") def dut_address(): # Timeout to ensure device is fully booted before running the list cmd. time.sleep(60) _list = pexpect.run("mbl-cli list") print(_list) ip_ = _list.decode().strip("\r\n").split("\n")[-1].split(": ")[-1].strip() if "fe80" not in ip_: raise SystemExit("IP address not found. {} found instead".format(ip_)) return ip_ class TestSelectCommand: def test_select_finds_device_by_ipv6_only(self): mbl_cli = pexpect.spawn("mbl-cli", ["select"]) mbl_cli.expect_exact("Select a device from the list:") assert re.search(DEVICE_HN_RE, mbl_cli.before.decode()) assert not re.search(IPV4_RE, mbl_cli.before.decode()) def test_select_ctrl_c_behaviour(self): mbl_cli = pexpect.spawn("mbl-cli", ["select"]) mbl_cli.expect_exact("Select a device from the list:") mbl_cli.sendcontrol("c") mbl_cli.expect_exact("User quit.") assert mbl_cli.match @pytest.mark.parametrize("bad_input", [b"0", b"a", b"\n", b""]) def test_select_invalid_input(self, bad_input): mbl_cli = pexpect.spawn("mbl-cli", ["select"]) mbl_cli.expect_exact("Select a device from the list:") mbl_cli.sendline(bad_input) mbl_cli.expect_exact( "Enter a valid device index as shown in the list." ) assert mbl_cli.match class TestListCommand: def test_ipv6_discovered_after_reboot(self, dut_address): pexpect.run( "mbl-cli -a {} shell 'su -l -c reboot'".format(dut_address) ) # Wait for the device to shut down. time.sleep(120) # Poll the mbl-cli list for the device. # The range(25) is empirical; I've observed 15 attempts is sometimes # not enough to allow LAVA to reboot the device fully, and subsequent # tests fail. for _ in range(25): mbl_cli = pexpect.run("mbl-cli list", timeout=60) print(mbl_cli.decode()) ipv4_match = re.search(IPV4_RE, mbl_cli.decode()) device_match = re.search( r"{}".format(dut_address), mbl_cli.decode() ) if device_match is not None: break assert not ipv4_match assert device_match class TestPutCommand: def test_putting_a_file_on_device(self, tmp_path, dut_address): tf = tmp_path / "test_file" tf.touch(exist_ok=True) tf.write_text("ABCDEFGHIJKLMNOPQRSTUVWXYZ") output = pexpect.spawn( "mbl-cli -a {} put {} /scratch".format( dut_address, str(tf.resolve()) ) ) output.expect(pexpect.EOF) output.close() assert output.exitstatus == 0 def test_putting_a_dir_on_device(self, tmp_path, dut_address): t = tmp_path / "tst" t.mkdir(exist_ok=True) mbl_cli = pexpect.spawn( "mbl-cli -a {} put -r {} /scratch".format( dut_address, str(t.resolve()) ) ) mbl_cli.expect(pexpect.EOF) mbl_cli.close() assert mbl_cli.exitstatus == 0 class TestGetCommand: def test_getting_a_file_from_device(self, dut_address): output = pexpect.spawn( "mbl-cli -a {} get /var/log/mbl-cloud-client.log .".format( dut_address ) ) output.expect(pexpect.EOF) output.close() assert output.exitstatus == 0 def test_getting_a_dir_from_device(self, dut_address): mbl_cli = pexpect.spawn( "mbl-cli -a {} get -r /var/log .".format(dut_address) ) mbl_cli.expect(pexpect.EOF) mbl_cli.close() assert mbl_cli.exitstatus == 0 class TestShellCommand: @pytest.mark.parametrize( "cmd, expected", [ ("whoami", "root"), ("'for i in $(seq 1 10); do echo $i; sleep 1; done'", "10"), ], ) def test_shell_one_shot_cmds(self, cmd, expected, dut_address): mbl_cli = pexpect.spawn( "mbl-cli -a {} shell {}".format(dut_address, cmd) ) mbl_cli.expect(expected) mbl_cli.expect(pexpect.EOF) mbl_cli.close() assert mbl_cli.exitstatus == 0 @pytest.mark.parametrize( "cmd, expected_code", [ (r"for i in $(seq 1 10); do echo 1; done", 2), (r"'rm /scratch'", 1), (r"'find uuuuuuuuuuuu'", 1), ], ) def test_shell_err_code(self, cmd, expected_code, dut_address): mbl_cli = pexpect.spawn( "mbl-cli -a {} shell {}".format(dut_address, cmd) ) mbl_cli.expect(pexpect.EOF) mbl_cli.close() assert mbl_cli.exitstatus == expected_code def test_shell_reconnects_after_device_reboot(self, dut_address): pexpect.run( "mbl-cli -a {} shell 'su -l -c reboot'".format(dut_address) ) time.sleep(90) mbl_cli = pexpect.spawn("mbl-cli -a {} shell".format(dut_address)) mbl_cli.expect(r"root@mbed-linux-os-\d{1,4}:~#") mbl_cli.sendline("exit") mbl_cli.expect(pexpect.EOF) mbl_cli.close() assert mbl_cli.exitstatus == 0
32
78
0.592124
ace9da0f2b7ef18e77c56db0bfa2be309e6aa49b
406
py
Python
murage_gallery/wsgi.py
MainaMurage/murage-gallery
d54dcc5c8b578ded3ef0fa9f96b8977053cfe66b
[ "MIT" ]
null
null
null
murage_gallery/wsgi.py
MainaMurage/murage-gallery
d54dcc5c8b578ded3ef0fa9f96b8977053cfe66b
[ "MIT" ]
null
null
null
murage_gallery/wsgi.py
MainaMurage/murage-gallery
d54dcc5c8b578ded3ef0fa9f96b8977053cfe66b
[ "MIT" ]
null
null
null
""" WSGI config for murage_gallery project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "murage_gallery.settings") application = get_wsgi_application()
23.882353
78
0.793103
ace9da230224bd2f94eaad7f7f15224ae30a876e
3,147
py
Python
ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/queueproperty_28ede609f33dc123ae3579c11376d90b.py
OpenIxia/ixnetwork_restpy
f628db450573a104f327cf3c737ca25586e067ae
[ "MIT" ]
20
2019-05-07T01:59:14.000Z
2022-02-11T05:24:47.000Z
ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/queueproperty_28ede609f33dc123ae3579c11376d90b.py
OpenIxia/ixnetwork_restpy
f628db450573a104f327cf3c737ca25586e067ae
[ "MIT" ]
60
2019-04-03T18:59:35.000Z
2022-02-22T12:05:05.000Z
ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/queueproperty_28ede609f33dc123ae3579c11376d90b.py
OpenIxia/ixnetwork_restpy
f628db450573a104f327cf3c737ca25586e067ae
[ "MIT" ]
13
2019-05-20T10:48:31.000Z
2021-10-06T07:45:44.000Z
# MIT LICENSE # # Copyright 1997 - 2020 by IXIA Keysight # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from ixnetwork_restpy.base import Base from ixnetwork_restpy.files import Files from typing import List, Any, Union class QueueProperty(Base): """The property of the queue. The QueueProperty class encapsulates a required queueProperty resource which will be retrieved from the server every time the property is accessed. """ __slots__ = () _SDM_NAME = 'queueProperty' _SDM_ATT_MAP = { 'MinimumDataRateGuaranteed': 'minimumDataRateGuaranteed', 'IsNone': 'none', } _SDM_ENUM_MAP = { } def __init__(self, parent, list_op=False): super(QueueProperty, self).__init__(parent, list_op) @property def MinimumDataRateGuaranteed(self): # type: () -> bool """ Returns ------- - bool: If true, indicates that a minimum data rate is guaranteed. """ return self._get_attribute(self._SDM_ATT_MAP['MinimumDataRateGuaranteed']) @MinimumDataRateGuaranteed.setter def MinimumDataRateGuaranteed(self, value): # type: (bool) -> None self._set_attribute(self._SDM_ATT_MAP['MinimumDataRateGuaranteed'], value) @property def IsNone(self): # type: () -> bool """ Returns ------- - bool: If true, indicates that no property is defined for the queue. """ return self._get_attribute(self._SDM_ATT_MAP['IsNone']) @IsNone.setter def IsNone(self, value): # type: (bool) -> None self._set_attribute(self._SDM_ATT_MAP['IsNone'], value) def update(self, MinimumDataRateGuaranteed=None): # type: (bool) -> QueueProperty """Updates queueProperty resource on the server. Args ---- - MinimumDataRateGuaranteed (bool): If true, indicates that a minimum data rate is guaranteed. Raises ------ - ServerError: The server has encountered an uncategorized error condition """ return self._update(self._map_locals(self._SDM_ATT_MAP, locals()))
37.023529
151
0.68891
ace9da4c88ebffa2633c3a2f88527ce1723b20f8
2,851
py
Python
Config.py
IewNixIl/graduation_project_under
67d0345208511bb06c35c3453227b2fa4ebef4a3
[ "MIT" ]
null
null
null
Config.py
IewNixIl/graduation_project_under
67d0345208511bb06c35c3453227b2fa4ebef4a3
[ "MIT" ]
null
null
null
Config.py
IewNixIl/graduation_project_under
67d0345208511bb06c35c3453227b2fa4ebef4a3
[ "MIT" ]
null
null
null
from torchvision import transforms as T from torch.utils.data import DataLoader class config: #''' path='D:\\m1474000'#所有数据的总文件夹路径 path_devision='D:\\Codes\\Graduation\\train_test_list'#存训练数据和测试数据划分的文件路径 path_labels='D:\\labels\\labels'#存手动标记的标签位置 path_labels_test='D:\\labels\\labels'#测试集 path_labels_val='D:\\labels\\val'#用于在训练过程中进行验证 path_acc_record='D:\\codes\\Graduation\\RECORD\\accu' path_label_train='' path_mask_train='' path_label_low_save='F:\\label_test\\labels_low' path_predict_save='D:\\result\\final_result\\predict_2' path_pr_save='G:\\M12\\pr\\s1+s2' path_img_save='D:\\result\\final_result\\imgs' path_ndwi_save='D:\\result\\final_result\\ndwi' #''' #model35 thre:0.31 ; p:0.9527 ; r:0.9324 ; fmeasure:0.9424 ; pa:0.9635 ; iou:0.8911 #model36 thre:0.24 ; p:0.9560 ; r:0.9307 ; fmeasure:0.9432 ; pa:0.9641 ; iou:0.8925 #model37 thre:0.34 ; p:0.9615 ; r:0.9213 ; fmeasure:0.9410 ; pa:0.9630 ; iou:0.8885 #model38 thre:0.52 ; p:0.9722 ; r:0.9342 ; fmeasure:0.9528 ; pa:0.9704 ; iou:0.9099 #model39 thre:0.41 ; p:0.9640 ; r:0.9504 ; fmeasure:0.9572 ; pa:0.9727 ; iou:0.9178 model='Unet' model_load_path=''#'F:\\Graduation\\project_v2\\MODELS\\model29' model_save_path='D:\\codes\\Graduation\\MODELS\\model1' model_save_path_checkpoints='D:\\codes\\Graduation\\MODELS\\checkpoints\\checkpoint.pkl' statistic_save_path='D:\\codes\\Graduation\\MODELS\\sta15' sub_dataset_train='train_sub2' ifboard=False ifbar=True if_merge_test=True input_band=10#输入的波段数 use_denoise=False#SAR波段是否进行去噪平滑 use_gpu=True batch_size=1 num_workers=4 learning_rate=0.0001 max_epoch=1 number_recording=500 weight_decay=0.0001 mean={2:[-11,-11], 10:[2048,2048,2048,2048,2048,2048,2048,2048,2048,2048], 12:[-11,-11,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048], 13:[-11,-11,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,0.5]} std={2:[11,11], 10:[2048,2048,2048,2048,2048,2048,2048,2048,2048,2048], 12:[11,11,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048], 13:[11,11,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,0.5]} transform_img=T.Compose([ T.ToTensor(), #T.Normalize(mean=[-11,-11,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048], #std=[11,11,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048])#归一化到 [-1,1] T.Normalize(mean=mean[input_band],std=std[input_band])#归一化到 [-1,1] #T.Normalize(mean=[2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048], #std=[2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048])#归一化到 [-1,1] ]) transform_label=T.Compose([ T.ToTensor() ])
36.551282
101
0.660119
ace9da7092890372f48914b4717721e618b63303
22
py
Python
tests/__init__.py
kvnkho/fugue
5f3fe8f1fb72632e5b5987d720c1d1ef546e4682
[ "Apache-2.0" ]
547
2020-09-22T08:30:14.000Z
2022-03-30T23:11:05.000Z
tests/__init__.py
kvnkho/fugue
5f3fe8f1fb72632e5b5987d720c1d1ef546e4682
[ "Apache-2.0" ]
196
2020-09-22T23:08:26.000Z
2022-03-26T21:22:48.000Z
tests/__init__.py
kvnkho/fugue
5f3fe8f1fb72632e5b5987d720c1d1ef546e4682
[ "Apache-2.0" ]
37
2020-09-23T17:05:00.000Z
2022-03-29T18:26:52.000Z
# pylint: disable-all
11
21
0.727273
ace9da7d55bb7d1a04182b23906ea09dd91f4f6a
7,366
py
Python
tests/custom/test_timeseries_anomalies.py
albact7/MLPrimitives
9dbcbe219315a9b79aae825a34f5108802d8a19d
[ "MIT" ]
42
2018-07-31T07:33:45.000Z
2020-10-26T05:51:35.000Z
tests/custom/test_timeseries_anomalies.py
albact7/MLPrimitives
9dbcbe219315a9b79aae825a34f5108802d8a19d
[ "MIT" ]
177
2018-08-28T18:06:20.000Z
2020-11-17T18:41:22.000Z
tests/custom/test_timeseries_anomalies.py
albact7/MLPrimitives
9dbcbe219315a9b79aae825a34f5108802d8a19d
[ "MIT" ]
28
2018-07-18T13:47:59.000Z
2020-10-21T18:53:15.000Z
from unittest import TestCase import numpy as np import pandas as pd from numpy.testing import assert_allclose from pandas.testing import assert_frame_equal from mlprimitives.custom.timeseries_anomalies import ( _find_sequences, _get_max_errors, _merge_sequences, _prune_anomalies, find_anomalies) class GetMaxErrorsTest(TestCase): MAX_BELOW = 0.1 def _run(self, errors, sequences, expected): sequences = _get_max_errors(errors, sequences, self.MAX_BELOW) assert_frame_equal(sequences, expected) def test_no_anomalies(self): errors = np.array([0.1, 0.0, 0.1, 0.0]) sequences = np.ndarray((0, 2)) expected = pd.DataFrame([ [0.1, -1, -1] ], columns=['max_error', 'start', 'stop']) self._run(errors, sequences, expected) def test_one_sequence(self): errors = np.array([0.1, 0.2, 0.2, 0.1]) sequences = np.array([ [1, 2] ]) expected = pd.DataFrame([ [0.2, 1, 2], [0.1, -1, -1] ], columns=['max_error', 'start', 'stop']) self._run(errors, sequences, expected) def test_two_sequences(self): errors = np.array([0.1, 0.2, 0.3, 0.2, 0.1, 0.2, 0.2, 0.1]) sequences = np.array([ [1, 3], [5, 6] ]) expected = pd.DataFrame([ [0.3, 1, 3], [0.2, 5, 6], [0.1, -1, -1] ], columns=['max_error', 'start', 'stop']) self._run(errors, sequences, expected) class PruneAnomaliesTest(TestCase): MIN_PERCENT = 0.2 def _run(self, max_errors, expected): sequences = _prune_anomalies(max_errors, self.MIN_PERCENT) assert_allclose(sequences, expected) def test_no_sequences(self): max_errors = pd.DataFrame([ [0.1, -1, -1] ], columns=['max_error', 'start', 'stop']) expected = np.ndarray((0, 3)) self._run(max_errors, expected) def test_no_anomalies(self): max_errors = pd.DataFrame([ [0.11, 1, 2], [0.1, -1, -1] ], columns=['max_error', 'start', 'stop']) expected = np.ndarray((0, 3)) self._run(max_errors, expected) def test_one_anomaly(self): max_errors = pd.DataFrame([ [0.2, 1, 2], [0.1, -1, -1] ], columns=['max_error', 'start', 'stop']) expected = np.array([ [1, 2, 0.2] ]) self._run(max_errors, expected) def test_two_anomalies(self): max_errors = pd.DataFrame([ [0.3, 1, 2], [0.2, 4, 5], [0.1, -1, -1] ], columns=['max_error', 'start', 'stop']) expected = np.array([ [1, 2, 0.3], [4, 5, 0.2] ]) self._run(max_errors, expected) def test_two_out_of_three(self): max_errors = pd.DataFrame([ [0.3, 1, 2], [0.22, 4, 5], [0.11, 7, 8], [0.1, -1, -1] ], columns=['max_error', 'start', 'stop']) expected = np.array([ [1, 2, 0.3], [4, 5, 0.22] ]) self._run(max_errors, expected) def test_two_with_a_gap(self): max_errors = pd.DataFrame([ [0.3, 1, 2], [0.21, 4, 5], [0.2, 7, 8], [0.1, -1, -1] ], columns=['max_error', 'start', 'stop']) expected = np.array([ [1, 2, 0.3], [4, 5, 0.21], [7, 8, 0.2] ]) self._run(max_errors, expected) class FindSequencesTest(TestCase): THRESHOLD = 0.5 ANOMALY_PADDING = 1 def _run(self, errors, expected, expected_max): found, max_below = _find_sequences(np.asarray(errors), self.THRESHOLD, self.ANOMALY_PADDING) np.testing.assert_array_equal(found, expected) assert max_below == expected_max def test__find_sequences_no_sequences(self): self._run([0.1, 0.2, 0.3, 0.4], np.ndarray((0, 2)), 0.4) def test__find_sequences_all_one_sequence(self): self._run([1, 1, 1, 1], [(0, 3)], 0) def test__find_sequences_open_end(self): self._run([0, 0, 0.4, 1, 1, 1], [(2, 5)], 0) def test__find_sequences_open_start(self): self._run([1, 1, 1, 0.4, 0, 0], [(0, 3)], 0) def test__find_sequences_middle(self): self._run([0, 0, 1, 1, 0, 0], [(1, 4)], 0) def test__find_sequences_stop(self): self._run([1, 0, 0, 0, 1, 1], [(0, 1), (3, 5)], 0) class MergeSequencesTest(TestCase): def _run(self, sequences, expected): merged_sequences = _merge_sequences(sequences) np.testing.assert_array_equal(merged_sequences, expected) def test__merge_sequences_consecutive(self): self._run([(1, 2, 0.5), (3, 4, 0.5)], [(1, 4, 0.5)]) def test__merge_sequences_start_overlap(self): self._run([(1, 3, 0.5), (2, 4, 0.5)], [(1, 4, 0.5)]) def test__merge_sequences_start_end_overlap(self): self._run([(1, 4, 0.5), (2, 3, 0.5)], [(1, 4, 0.5)]) def test__merge_sequences_non_consecutive(self): self._run([(1, 2, 0.5), (4, 5, 0.5)], [(1, 2, 0.5), (4, 5, 0.5)]) def test__merge_sequences_consecutive_different_score(self): self._run([(1, 2, 1.0), (3, 4, 0.5)], [(1, 4, 0.75)]) def test__merge_sequences_consecutive_different_score_and_length(self): self._run([(1, 2, 1.0), (3, 4, 0.5)], [(1, 4, 0.75)]) class FindAnomaliesTest(TestCase): THRESHOLD = 0.5 INDEX_SHORT = [1, 2, 3, 4] INDEX_LONG = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ANOMALY_PADDING = 1 def _run(self, errors, expected, index=INDEX_SHORT, window_size=None, window_step_size=None, lower_threshold=False): found = find_anomalies(np.asarray(errors), index=index, anomaly_padding=self.ANOMALY_PADDING, window_size=window_size, window_step_size=window_step_size, lower_threshold=lower_threshold) assert_allclose(found, expected) def test_find_anomalies_no_anomalies(self): self._run([0, 0, 0, 0], np.array([])) def test_find_anomalies_one_anomaly(self): self._run([0, 0.5, 0.5, 0], np.array([[1., 4., 0.025]])) def test_find_anomalies_open_start(self): self._run([0.5, 0.5, 0, 0], np.array([[1., 3., 0.025]])) def test_find_anomalies_open_end(self): self._run([0, 0, 0.5, 0.5], np.array([[2., 4., 0.025]])) def test_find_anomalies_two_anomalies(self): self._run([0.5, 0, 0.5, 0], np.array([[1., 4., 0.025]])) self._run([0, 0.5, 0, 0.5], np.array([[1., 4., 0.025]])) def test_find_anomalies_multiple_non_overlapping_thresholds(self): self._run([0, 0, 0.5, 0.5, 0, 0, 0.5, 0.5, 0, 0], np.array([[2., 4., 0.025], [6., 8., 0.025]]), index=self.INDEX_LONG, window_size=4, window_step_size=4) def test_find_anomalies_multiple_overlapping_thresholds(self): self._run([0, 0, 0.5, 0.5, 0, 0, 0.5, 0.5, 0, 0], np.array([[2., 9., 0.025]]), index=self.INDEX_LONG, window_size=4, window_step_size=2) def test_find_anomalies_lower_threshold(self): self._run([0.5, 0.5, 0, 0], np.array([[1., 4., 0.025]]), lower_threshold=True)
32.307018
90
0.551045
ace9dbdca4a04ebe44c2e528b60adf3d433e3b6c
5,201
py
Python
pose_estimation/configs/top_down/udp/coco/hrnet_w48_coco_384x288_udp.py
AK391/UniFormer
22c6b3b98b68236dda6a8fa7152a32af1af62a20
[ "MIT" ]
367
2022-01-14T03:32:25.000Z
2022-03-31T04:48:20.000Z
pose_estimation/configs/top_down/udp/coco/hrnet_w48_coco_384x288_udp.py
hadlang/UniFormer
e8024703bffb89cb7c7d09e0d774a0d2a9f96c25
[ "MIT" ]
27
2022-01-27T07:12:49.000Z
2022-03-31T04:31:13.000Z
pose_estimation/configs/top_down/udp/coco/hrnet_w48_coco_384x288_udp.py
hadlang/UniFormer
e8024703bffb89cb7c7d09e0d774a0d2a9f96c25
[ "MIT" ]
53
2022-01-18T11:21:43.000Z
2022-03-31T06:42:41.000Z
log_level = 'INFO' load_from = None resume_from = None dist_params = dict(backend='nccl') workflow = [('train', 1)] checkpoint_config = dict(interval=5, create_symlink=False) evaluation = dict(interval=10, metric='mAP', key_indicator='AP') optimizer = dict( type='Adam', lr=5e-4, ) optimizer_config = dict(grad_clip=None) # learning policy lr_config = dict( policy='step', warmup='linear', warmup_iters=500, warmup_ratio=0.001, step=[170, 200]) total_epochs = 210 log_config = dict( interval=50, hooks=[ dict(type='TextLoggerHook'), # dict(type='TensorboardLoggerHook') ]) target_type = 'GaussianHeatMap' channel_cfg = dict( num_output_channels=17, dataset_joints=17, dataset_channel=[ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], ], inference_channel=[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ]) # model settings model = dict( type='TopDown', pretrained='https://download.openmmlab.com/mmpose/' 'pretrain_models/hrnet_w48-8ef0771d.pth', backbone=dict( type='HRNet', in_channels=3, extra=dict( stage1=dict( num_modules=1, num_branches=1, block='BOTTLENECK', num_blocks=(4, ), num_channels=(64, )), stage2=dict( num_modules=1, num_branches=2, block='BASIC', num_blocks=(4, 4), num_channels=(48, 96)), stage3=dict( num_modules=4, num_branches=3, block='BASIC', num_blocks=(4, 4, 4), num_channels=(48, 96, 192)), stage4=dict( num_modules=3, num_branches=4, block='BASIC', num_blocks=(4, 4, 4, 4), num_channels=(48, 96, 192, 384))), ), keypoint_head=dict( type='TopDownSimpleHead', in_channels=48, out_channels=channel_cfg['num_output_channels'], num_deconv_layers=0, extra=dict(final_conv_kernel=1, ), loss_keypoint=dict(type='JointsMSELoss', use_target_weight=True)), train_cfg=dict(), test_cfg=dict( flip_test=True, post_process='default', shift_heatmap=False, target_type=target_type, modulate_kernel=17, use_udp=True)) data_cfg = dict( image_size=[288, 384], heatmap_size=[72, 96], num_output_channels=channel_cfg['num_output_channels'], num_joints=channel_cfg['dataset_joints'], dataset_channel=channel_cfg['dataset_channel'], inference_channel=channel_cfg['inference_channel'], soft_nms=False, nms_thr=1.0, oks_thr=0.9, vis_thr=0.2, use_gt_bbox=False, det_bbox_thr=0.0, bbox_file='../../../../dataset/coco/person_detection_results/' 'COCO_val2017_detections_AP_H_56_person.json', ) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='TopDownRandomFlip', flip_prob=0.5), dict( type='TopDownHalfBodyTransform', num_joints_half_body=8, prob_half_body=0.3), dict( type='TopDownGetRandomScaleRotation', rot_factor=40, scale_factor=0.5), dict(type='TopDownAffine', use_udp=True), dict(type='ToTensor'), dict( type='NormalizeTensor', mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), dict( type='TopDownGenerateTarget', sigma=3, encoding='UDP', target_type=target_type), dict( type='Collect', keys=['img', 'target', 'target_weight'], meta_keys=[ 'image_file', 'joints_3d', 'joints_3d_visible', 'center', 'scale', 'rotation', 'bbox_score', 'flip_pairs' ]), ] val_pipeline = [ dict(type='LoadImageFromFile'), dict(type='TopDownAffine', use_udp=True), dict(type='ToTensor'), dict( type='NormalizeTensor', mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), dict( type='Collect', keys=['img'], meta_keys=[ 'image_file', 'center', 'scale', 'rotation', 'bbox_score', 'flip_pairs' ]), ] test_pipeline = val_pipeline data_root = '../../../../dataset/coco' data = dict( samples_per_gpu=32, workers_per_gpu=2, val_dataloader=dict(samples_per_gpu=256), test_dataloader=dict(samples_per_gpu=256), train=dict( type='TopDownCocoDataset', ann_file=f'{data_root}/annotations/person_keypoints_train2017.json', img_prefix=f'{data_root}/train2017/', data_cfg=data_cfg, pipeline=train_pipeline), val=dict( type='TopDownCocoDataset', ann_file=f'{data_root}/annotations/person_keypoints_val2017.json', img_prefix=f'{data_root}/val2017/', data_cfg=data_cfg, pipeline=val_pipeline), test=dict( type='TopDownCocoDataset', ann_file=f'{data_root}/annotations/person_keypoints_val2017.json', img_prefix=f'{data_root}/val2017/', data_cfg=data_cfg, pipeline=val_pipeline), )
28.894444
79
0.588541
ace9dca1f04a5610807a2b43e829015218980409
2,591
py
Python
tests/test_tokens.py
michael-k/django-sesame
bc68ec19e309fdeb0476b063117b64dfe3896208
[ "BSD-3-Clause" ]
null
null
null
tests/test_tokens.py
michael-k/django-sesame
bc68ec19e309fdeb0476b063117b64dfe3896208
[ "BSD-3-Clause" ]
null
null
null
tests/test_tokens.py
michael-k/django-sesame
bc68ec19e309fdeb0476b063117b64dfe3896208
[ "BSD-3-Clause" ]
null
null
null
from django.test import TestCase, override_settings from sesame import tokens_v1, tokens_v2 from sesame.tokens import create_token, parse_token from .mixins import CaptureLogMixin, CreateUserMixin from .signals import reset_sesame_settings # noqa class TestUtils(CaptureLogMixin, CreateUserMixin, TestCase): def test_create_token_default_v2(self): token = create_token(self.user) self.assertTrue(tokens_v2.detect_token(token)) self.assertFalse(tokens_v1.detect_token(token)) @override_settings(SESAME_TOKENS=["sesame.tokens_v2"]) def test_create_token_force_v2(self): token = create_token(self.user) self.assertTrue(tokens_v2.detect_token(token)) self.assertFalse(tokens_v1.detect_token(token)) @override_settings(SESAME_TOKENS=["sesame.tokens_v1"]) def test_create_token_force_v1(self): token = create_token(self.user) self.assertTrue(tokens_v1.detect_token(token)) self.assertFalse(tokens_v2.detect_token(token)) @override_settings(SESAME_TOKENS=["sesame.tokens_v1", "sesame.tokens_v2"]) def test_create_token_use_first_choice(self): token = create_token(self.user) self.assertTrue(tokens_v1.detect_token(token)) self.assertFalse(tokens_v2.detect_token(token)) def test_parse_token_accepts_v2(self): token = create_token(self.user) user = parse_token(token, self.get_user) self.assertEqual(user, self.user) self.assertLogsContain("Valid token for user john") def test_parse_token_accepts_v1(self): with override_settings(SESAME_TOKENS=["sesame.tokens_v1"]): token = create_token(self.user) user = parse_token(token, self.get_user) self.assertEqual(user, self.user) self.assertLogsContain("Valid token for user john") @override_settings(SESAME_TOKENS=["sesame.tokens_v2"]) def test_parse_token_force_v2(self): with override_settings(SESAME_TOKENS=["sesame.tokens_v1"]): token = create_token(self.user) user = parse_token(token, self.get_user) self.assertEqual(user, None) self.assertLogsContain("Bad token: doesn't match a supported format") @override_settings(SESAME_TOKENS=["sesame.tokens_v1"]) def test_parse_token_force_v1(self): with override_settings(SESAME_TOKENS=["sesame.tokens_v2"]): token = create_token(self.user) user = parse_token(token, self.get_user) self.assertEqual(user, None) self.assertLogsContain("Bad token: doesn't match a supported format")
41.790323
78
0.722887
ace9dd0b7576180b82495f6711da812d1fb3a8f4
1,628
py
Python
Usecase/AccountRegist.py
zhangxiuqing007/EfUITest
d54c568b3996ef3e732ea335916de61cadc06e84
[ "MIT" ]
null
null
null
Usecase/AccountRegist.py
zhangxiuqing007/EfUITest
d54c568b3996ef3e732ea335916de61cadc06e84
[ "MIT" ]
null
null
null
Usecase/AccountRegist.py
zhangxiuqing007/EfUITest
d54c568b3996ef3e732ea335916de61cadc06e84
[ "MIT" ]
null
null
null
from selenium import webdriver from PageObject.IndexPage import IndexPage from PageObject.CreateAccountInputPage import CreateAccountInputPage from Usecase.Login import login_final_to_index_page import uuid import time def create_new_account_then_login(driver: webdriver.Chrome): index_page = IndexPage(driver) index_page.logOut() # 登出 index_page.find_regist_btn().click() new_account_page = CreateAccountInputPage(driver) new_account_page.find_name_input().send_keys("二把刀") new_account_page.find_account_input().send_keys("xxxxxxxxxx") new_account_page.find_pwd1_input().send_keys("xxxxxxxxxx") new_account_page.find_pwd2_input().send_keys("xxxxxxxxxx") new_account_page.find_commit_btn().click() new_account_page.find_name_input().send_keys("三把刀") new_account_page.find_account_input().send_keys("erbadao") new_account_page.find_pwd1_input().send_keys("erbadao") new_account_page.find_pwd2_input().send_keys("erbadao") new_account_page.find_commit_btn().click() name = uuid.uuid4().__str__()[-8:] account = uuid.uuid4().__str__() pwd = uuid.uuid4().__str__() new_account_page.find_name_input().send_keys(name) new_account_page.find_account_input().send_keys(account) new_account_page.find_pwd1_input().send_keys(pwd) new_account_page.find_pwd2_input().send_keys(pwd) new_account_page.find_commit_btn().click() # 返回首页 driver.get("http://127.0.0.1:8080") # 利用刚注册的账号 登录 login_final_to_index_page(driver, account, pwd) if __name__ == "__main__": create_new_account_then_login(webdriver.Chrome()) time.sleep(2)
37
68
0.767813
ace9de321f3df7366bb2ce85d4177cd00a454a03
1,001
py
Python
pdp/data/fasta_test.py
spydr1/ProteinDataProcessor
ae6573512bf25448fa83da9507e06eb6457cf26b
[ "MIT" ]
null
null
null
pdp/data/fasta_test.py
spydr1/ProteinDataProcessor
ae6573512bf25448fa83da9507e06eb6457cf26b
[ "MIT" ]
null
null
null
pdp/data/fasta_test.py
spydr1/ProteinDataProcessor
ae6573512bf25448fa83da9507e06eb6457cf26b
[ "MIT" ]
null
null
null
import os import sys os.environ["CUDA_VISIBLE_DEVICES"] = "-1" import tensorflow as tf import logging import copy from pdp.data.fasta import Fasta, load_fasta from pdp.data.feature import AminoAcid class TestStringMethods(tf.test.TestCase): def setUp(self): self.data = Fasta("1NAC_A", "MAC") def test_serialize(self): serialized_data = self.data.serialize() features = { "fasta": tf.io.FixedLenFeature([], tf.string), "seq": tf.io.RaggedFeature(value_key="seq", dtype=tf.int64), } eg = tf.io.parse_single_example(serialized_data, features) self.assertEqual(self.data.aa, AminoAcid(eg["seq"].numpy())) def test_export_fasta(self): path = os.path.join(self.get_temp_dir(), "test.fasta") self.data.to_fasta(path) loaded_fasta = load_fasta(path) self.assertEqual(loaded_fasta.aa, self.data.aa) if __name__ == "__main__": tf.test.main()
26.342105
73
0.635365
ace9deeefa158abdfa21b69d4526fe172b38e226
79,638
py
Python
python_modules/dagster/dagster/core/instance/__init__.py
schrockn/dagster
3bb4e9247a693e48d84e9c86f73d83633d91a5c7
[ "Apache-2.0" ]
null
null
null
python_modules/dagster/dagster/core/instance/__init__.py
schrockn/dagster
3bb4e9247a693e48d84e9c86f73d83633d91a5c7
[ "Apache-2.0" ]
null
null
null
python_modules/dagster/dagster/core/instance/__init__.py
schrockn/dagster
3bb4e9247a693e48d84e9c86f73d83633d91a5c7
[ "Apache-2.0" ]
null
null
null
import logging import logging.config import os import sys import time import warnings import weakref from collections import defaultdict from contextlib import ExitStack from enum import Enum from tempfile import TemporaryDirectory from typing import ( TYPE_CHECKING, Any, Callable, Dict, Generic, Iterable, List, Mapping, Optional, Sequence, Set, Tuple, TypeVar, Union, cast, ) import yaml import dagster._check as check from dagster.core.definitions.events import AssetKey from dagster.core.definitions.pipeline_base import InMemoryPipeline from dagster.core.definitions.pipeline_definition import ( PipelineDefinition, PipelineSubsetDefinition, ) from dagster.core.errors import ( DagsterHomeNotSetError, DagsterInvariantViolationError, DagsterRunAlreadyExists, DagsterRunConflict, ) from dagster.core.storage.pipeline_run import ( IN_PROGRESS_RUN_STATUSES, DagsterRun, JobBucket, PipelineRun, PipelineRunStatsSnapshot, PipelineRunStatus, RunPartitionData, RunRecord, RunsFilter, TagBucket, ) from dagster.core.storage.tags import PARENT_RUN_ID_TAG, RESUME_RETRY_TAG, ROOT_RUN_ID_TAG from dagster.core.system_config.objects import ResolvedRunConfig from dagster.core.utils import str_format_list from dagster.serdes import ConfigurableClass from dagster.seven import get_current_datetime_in_utc from dagster.utils import merge_dicts, traced from dagster.utils.backcompat import experimental_functionality_warning from dagster.utils.error import serializable_error_info_from_exc_info from .config import ( DAGSTER_CONFIG_YAML_FILENAME, DEFAULT_LOCAL_CODE_SERVER_STARTUP_TIMEOUT, is_dagster_home_set, ) from .ref import InstanceRef # 'airflow_execution_date' and 'is_airflow_ingest_pipeline' are hardcoded tags used in the # airflow ingestion logic (see: dagster_pipeline_factory.py). 'airflow_execution_date' stores the # 'execution_date' used in Airflow operator execution and 'is_airflow_ingest_pipeline' determines # whether 'airflow_execution_date' is needed. # https://github.com/dagster-io/dagster/issues/2403 AIRFLOW_EXECUTION_DATE_STR = "airflow_execution_date" IS_AIRFLOW_INGEST_PIPELINE_STR = "is_airflow_ingest_pipeline" if TYPE_CHECKING: from dagster.core.debug import DebugRunPayload from dagster.core.events import DagsterEvent, DagsterEventType from dagster.core.events.log import EventLogEntry from dagster.core.execution.plan.resume_retry import ReexecutionStrategy from dagster.core.execution.stats import RunStepKeyStatsSnapshot from dagster.core.host_representation import ( ExternalPipeline, ExternalSensor, HistoricalPipeline, RepositoryLocation, ) from dagster.core.launcher import RunLauncher from dagster.core.run_coordinator import RunCoordinator from dagster.core.scheduler import Scheduler from dagster.core.scheduler.instigation import InstigatorState, InstigatorTick, TickStatus from dagster.core.snap import ExecutionPlanSnapshot, PipelineSnapshot from dagster.core.storage.compute_log_manager import ComputeLogManager from dagster.core.storage.event_log import EventLogStorage from dagster.core.storage.event_log.base import AssetRecord, EventLogRecord, EventRecordsFilter from dagster.core.storage.root import LocalArtifactStorage from dagster.core.storage.runs import RunStorage from dagster.core.storage.schedules import ScheduleStorage from dagster.core.workspace.workspace import IWorkspace from dagster.daemon.types import DaemonHeartbeat def _check_run_equality( pipeline_run: PipelineRun, candidate_run: PipelineRun ) -> Dict[str, Tuple[Any, Any]]: field_diff = {} for field in pipeline_run._fields: expected_value = getattr(pipeline_run, field) candidate_value = getattr(candidate_run, field) if expected_value != candidate_value: field_diff[field] = (expected_value, candidate_value) return field_diff def _format_field_diff(field_diff: Dict[str, Tuple[Any, Any]]) -> str: return "\n".join( [ ( " {field_name}:\n" + " Expected: {expected_value}\n" + " Received: {candidate_value}" ).format( field_name=field_name, expected_value=expected_value, candidate_value=candidate_value, ) for field_name, ( expected_value, candidate_value, ) in field_diff.items() ] ) class _EventListenerLogHandler(logging.Handler): def __init__(self, instance): self._instance = instance super(_EventListenerLogHandler, self).__init__() def emit(self, record): from dagster.core.events import EngineEventData from dagster.core.events.log import StructuredLoggerMessage, construct_event_record event = construct_event_record( StructuredLoggerMessage( name=record.name, message=record.msg, level=record.levelno, meta=record.dagster_meta, record=record, ) ) try: self._instance.handle_new_event(event) except Exception as e: sys.stderr.write(f"Exception while writing logger call to event log: {str(e)}\n") if event.dagster_event: # Swallow user-generated log failures so that the entire step/run doesn't fail, but # raise failures writing system-generated log events since they are the source of # truth for the state of the run raise elif event.run_id: self._instance.report_engine_event( "Exception while writing logger call to event log", pipeline_name=event.pipeline_name, run_id=event.run_id, step_key=event.step_key, engine_event_data=EngineEventData( error=serializable_error_info_from_exc_info(sys.exc_info()), ), ) class InstanceType(Enum): PERSISTENT = "PERSISTENT" EPHEMERAL = "EPHEMERAL" T_DagsterInstance = TypeVar("T_DagsterInstance", bound="DagsterInstance") class MayHaveInstanceWeakref(Generic[T_DagsterInstance]): """Mixin for classes that can have a weakref back to a Dagster instance.""" def __init__(self): self._instance_weakref: Optional[weakref.ReferenceType[T_DagsterInstance]] = None @property def _instance(self) -> T_DagsterInstance: instance = ( self._instance_weakref() # Backcompat with custom subclasses that don't call super().__init__() # in their own __init__ implementations if (hasattr(self, "_instance_weakref") and self._instance_weakref is not None) else None ) return cast(T_DagsterInstance, instance) def register_instance(self, instance: T_DagsterInstance): check.invariant( # Backcompat with custom subclasses that don't call super().__init__() # in their own __init__ implementations (not hasattr(self, "_instance_weakref") or self._instance_weakref is None), "Must only call initialize once", ) # Store a weakref to avoid a circular reference / enable GC self._instance_weakref = weakref.ref(instance) class DagsterInstance: """Core abstraction for managing Dagster's access to storage and other resources. Use DagsterInstance.get() to grab the current DagsterInstance which will load based on the values in the ``dagster.yaml`` file in ``$DAGSTER_HOME``. Alternatively, DagsterInstance.ephemeral() can use used which provides a set of transient in-memory components. Configuration of this class should be done by setting values in ``$DAGSTER_HOME/dagster.yaml``. For example, to use Postgres for dagster storage, you can write a ``dagster.yaml`` such as the following: .. literalinclude:: ../../../../../examples/docs_snippets/docs_snippets/deploying/dagster-pg.yaml :caption: dagster.yaml :language: YAML Args: instance_type (InstanceType): Indicates whether the instance is ephemeral or persistent. Users should not attempt to set this value directly or in their ``dagster.yaml`` files. local_artifact_storage (LocalArtifactStorage): The local artifact storage is used to configure storage for any artifacts that require a local disk, such as schedules, or when using the filesystem system storage to manage files and intermediates. By default, this will be a :py:class:`dagster.core.storage.root.LocalArtifactStorage`. Configurable in ``dagster.yaml`` using the :py:class:`~dagster.serdes.ConfigurableClass` machinery. run_storage (RunStorage): The run storage is used to store metadata about ongoing and past pipeline runs. By default, this will be a :py:class:`dagster.core.storage.runs.SqliteRunStorage`. Configurable in ``dagster.yaml`` using the :py:class:`~dagster.serdes.ConfigurableClass` machinery. event_storage (EventLogStorage): Used to store the structured event logs generated by pipeline runs. By default, this will be a :py:class:`dagster.core.storage.event_log.SqliteEventLogStorage`. Configurable in ``dagster.yaml`` using the :py:class:`~dagster.serdes.ConfigurableClass` machinery. compute_log_manager (ComputeLogManager): The compute log manager handles stdout and stderr logging for solid compute functions. By default, this will be a :py:class:`dagster.core.storage.local_compute_log_manager.LocalComputeLogManager`. Configurable in ``dagster.yaml`` using the :py:class:`~dagster.serdes.ConfigurableClass` machinery. run_coordinator (RunCoordinator): A runs coordinator may be used to manage the execution of pipeline runs. run_launcher (Optional[RunLauncher]): Optionally, a run launcher may be used to enable a Dagster instance to launch pipeline runs, e.g. on a remote Kubernetes cluster, in addition to running them locally. settings (Optional[Dict]): Specifies certain per-instance settings, such as feature flags. These are set in the ``dagster.yaml`` under a set of whitelisted keys. ref (Optional[InstanceRef]): Used by internal machinery to pass instances across process boundaries. """ _PROCESS_TEMPDIR: Optional[TemporaryDirectory] = None _EXIT_STACK = None def __init__( self, instance_type: InstanceType, local_artifact_storage: "LocalArtifactStorage", run_storage: "RunStorage", event_storage: "EventLogStorage", compute_log_manager: "ComputeLogManager", run_coordinator: "RunCoordinator", run_launcher: "RunLauncher", scheduler: Optional["Scheduler"] = None, schedule_storage: Optional["ScheduleStorage"] = None, settings: Optional[Dict[str, Any]] = None, ref: Optional[InstanceRef] = None, ): from dagster.core.launcher import RunLauncher from dagster.core.run_coordinator import RunCoordinator from dagster.core.scheduler import Scheduler from dagster.core.storage.compute_log_manager import ComputeLogManager from dagster.core.storage.event_log import EventLogStorage from dagster.core.storage.root import LocalArtifactStorage from dagster.core.storage.runs import RunStorage from dagster.core.storage.schedules import ScheduleStorage self._instance_type = check.inst_param(instance_type, "instance_type", InstanceType) self._local_artifact_storage = check.inst_param( local_artifact_storage, "local_artifact_storage", LocalArtifactStorage ) self._event_storage = check.inst_param(event_storage, "event_storage", EventLogStorage) self._event_storage.register_instance(self) self._run_storage = check.inst_param(run_storage, "run_storage", RunStorage) self._run_storage.register_instance(self) self._compute_log_manager = check.inst_param( compute_log_manager, "compute_log_manager", ComputeLogManager ) self._compute_log_manager.register_instance(self) self._scheduler = check.opt_inst_param(scheduler, "scheduler", Scheduler) self._schedule_storage = check.opt_inst_param( schedule_storage, "schedule_storage", ScheduleStorage ) if self._schedule_storage: self._schedule_storage.register_instance(self) self._run_coordinator = check.inst_param(run_coordinator, "run_coordinator", RunCoordinator) self._run_coordinator.register_instance(self) self._run_launcher = check.inst_param(run_launcher, "run_launcher", RunLauncher) self._run_launcher.register_instance(self) self._settings = check.opt_dict_param(settings, "settings") self._ref = check.opt_inst_param(ref, "ref", InstanceRef) self._subscribers: Dict[str, List[Callable]] = defaultdict(list) run_monitoring_enabled = self.run_monitoring_settings.get("enabled", False) if run_monitoring_enabled and not self.run_launcher.supports_check_run_worker_health: run_monitoring_enabled = False warnings.warn( "The configured run launcher does not support run monitoring, disabling it.", ) self._run_monitoring_enabled = run_monitoring_enabled if self.run_monitoring_enabled and self.run_monitoring_max_resume_run_attempts: check.invariant( self.run_launcher.supports_resume_run, "The configured run launcher does not support resuming runs. " "Set max_resume_run_attempts to 0 to use run monitoring. Any runs with a failed run " "worker will be marked as failed, but will not be resumed.", ) if self.run_retries_enabled: check.invariant( self.run_storage.supports_kvs(), "Run retries are enabled, but the configured run storage does not support them. " "Consider switching to Postgres or Mysql.", ) check.invariant( self.event_log_storage.supports_event_consumer_queries(), "Run retries are enabled, but the configured event log storage does not support them. " "Consider switching to Postgres or Mysql.", ) # ctors @staticmethod def ephemeral( tempdir: Optional[str] = None, preload: Optional[List["DebugRunPayload"]] = None ) -> "DagsterInstance": from dagster.core.launcher.sync_in_memory_run_launcher import SyncInMemoryRunLauncher from dagster.core.run_coordinator import DefaultRunCoordinator from dagster.core.storage.event_log import InMemoryEventLogStorage from dagster.core.storage.noop_compute_log_manager import NoOpComputeLogManager from dagster.core.storage.root import LocalArtifactStorage from dagster.core.storage.runs import InMemoryRunStorage if tempdir is None: tempdir = DagsterInstance.temp_storage() return DagsterInstance( instance_type=InstanceType.EPHEMERAL, local_artifact_storage=LocalArtifactStorage(tempdir), run_storage=InMemoryRunStorage(preload=preload), event_storage=InMemoryEventLogStorage(preload=preload), compute_log_manager=NoOpComputeLogManager(), run_coordinator=DefaultRunCoordinator(), run_launcher=SyncInMemoryRunLauncher(), ) @staticmethod def get() -> "DagsterInstance": dagster_home_path = os.getenv("DAGSTER_HOME") if not dagster_home_path: raise DagsterHomeNotSetError( ( "The environment variable $DAGSTER_HOME is not set. \n" "Dagster requires this environment variable to be set to an existing directory in your filesystem. " "This directory is used to store metadata across sessions, or load the dagster.yaml " "file which can configure storing metadata in an external database.\n" "You can resolve this error by exporting the environment variable. For example, you can run the following command in your shell or include it in your shell configuration file:\n" '\texport DAGSTER_HOME=~"/dagster_home"\n' "or PowerShell\n" "$env:DAGSTER_HOME = ($home + '\\dagster_home')" "or batch" "set DAGSTER_HOME=%UserProfile%/dagster_home" "Alternatively, DagsterInstance.ephemeral() can be used for a transient instance.\n" ) ) dagster_home_path = os.path.expanduser(dagster_home_path) if not os.path.isabs(dagster_home_path): raise DagsterInvariantViolationError( ( '$DAGSTER_HOME "{}" must be an absolute path. Dagster requires this ' "environment variable to be set to an existing directory in your filesystem." ).format(dagster_home_path) ) if not (os.path.exists(dagster_home_path) and os.path.isdir(dagster_home_path)): raise DagsterInvariantViolationError( ( '$DAGSTER_HOME "{}" is not a directory or does not exist. Dagster requires this ' "environment variable to be set to an existing directory in your filesystem" ).format(dagster_home_path) ) return DagsterInstance.from_config(dagster_home_path) @staticmethod def local_temp(tempdir=None, overrides=None) -> "DagsterInstance": if tempdir is None: tempdir = DagsterInstance.temp_storage() return DagsterInstance.from_ref(InstanceRef.from_dir(tempdir, overrides=overrides)) @staticmethod def from_config( config_dir: str, config_filename: str = DAGSTER_CONFIG_YAML_FILENAME, ) -> "DagsterInstance": instance_ref = InstanceRef.from_dir(config_dir, config_filename=config_filename) return DagsterInstance.from_ref(instance_ref) @staticmethod def from_ref(instance_ref: InstanceRef) -> "DagsterInstance": check.inst_param(instance_ref, "instance_ref", InstanceRef) # DagsterInstance doesn't implement ConfigurableClass, but we may still sometimes want to # have custom subclasses of DagsterInstance. This machinery allows for those custom # subclasses to receive additional keyword arguments passed through the config YAML. klass = instance_ref.custom_instance_class or DagsterInstance kwargs = instance_ref.custom_instance_class_config unified_storage = instance_ref.storage run_storage = unified_storage.run_storage if unified_storage else instance_ref.run_storage event_storage = ( unified_storage.event_log_storage if unified_storage else instance_ref.event_storage ) schedule_storage = ( unified_storage.schedule_storage if unified_storage else instance_ref.schedule_storage ) return klass( # type: ignore instance_type=InstanceType.PERSISTENT, local_artifact_storage=instance_ref.local_artifact_storage, run_storage=run_storage, event_storage=event_storage, schedule_storage=schedule_storage, compute_log_manager=instance_ref.compute_log_manager, scheduler=instance_ref.scheduler, run_coordinator=instance_ref.run_coordinator, run_launcher=instance_ref.run_launcher, settings=instance_ref.settings, ref=instance_ref, **kwargs, ) # flags @property def is_persistent(self) -> bool: return self._instance_type == InstanceType.PERSISTENT @property def is_ephemeral(self) -> bool: return self._instance_type == InstanceType.EPHEMERAL def get_ref(self) -> InstanceRef: if self._ref: return self._ref check.failed( "Attempted to prepare an ineligible DagsterInstance ({inst_type}) for cross " "process communication.{dagster_home_msg}".format( inst_type=self._instance_type, dagster_home_msg="\nDAGSTER_HOME environment variable is not set, set it to " "a directory on the filesystem for dagster to use for storage and cross " "process coordination." if os.getenv("DAGSTER_HOME") is None else "", ) ) @property def root_directory(self) -> str: return self._local_artifact_storage.base_dir @staticmethod def temp_storage() -> str: from dagster.core.test_utils import environ if DagsterInstance._PROCESS_TEMPDIR is None: DagsterInstance._EXIT_STACK = ExitStack() DagsterInstance._EXIT_STACK.enter_context( environ({"DAGSTER_TELEMETRY_DISABLED": "yes"}) ) DagsterInstance._PROCESS_TEMPDIR = TemporaryDirectory() return cast(TemporaryDirectory, DagsterInstance._PROCESS_TEMPDIR).name def _info(self, component): # ConfigurableClass may not have inst_data if it's a direct instantiation # which happens for ephemeral instances if isinstance(component, ConfigurableClass) and component.inst_data: return component.inst_data.info_dict() if type(component) is dict: return component return component.__class__.__name__ def _info_str_for_component(self, component_name, component): return yaml.dump( {component_name: self._info(component)}, default_flow_style=False, sort_keys=False ) def info_dict(self): settings = self._settings if self._settings else {} ret = { "local_artifact_storage": self._info(self._local_artifact_storage), "run_storage": self._info(self._run_storage), "event_log_storage": self._info(self._event_storage), "compute_logs": self._info(self._compute_log_manager), "schedule_storage": self._info(self._schedule_storage), "scheduler": self._info(self._scheduler), "run_coordinator": self._info(self._run_coordinator), "run_launcher": self._info(self._run_launcher), } ret.update( { settings_key: self._info(settings_value) for settings_key, settings_value in settings.items() } ) return ret def info_str(self) -> str: return yaml.dump(self.info_dict(), default_flow_style=False, sort_keys=False) def schema_str(self) -> str: def _schema_dict(alembic_version): if not alembic_version: return None db_revision, head_revision = alembic_version return { "current": db_revision, "latest": head_revision, } return yaml.dump( { "schema": { "event_log_storage": _schema_dict(self._event_storage.alembic_version()), "run_storage": _schema_dict(self._event_storage.alembic_version()), "schedule_storage": _schema_dict(self._event_storage.alembic_version()), } }, default_flow_style=False, sort_keys=False, ) @property def run_storage(self) -> "RunStorage": return self._run_storage @property def event_log_storage(self) -> "EventLogStorage": return self._event_storage # schedule storage @property def schedule_storage(self) -> Optional["ScheduleStorage"]: return self._schedule_storage @property def scheduler(self) -> Optional["Scheduler"]: return self._scheduler @property def scheduler_class(self) -> Optional[str]: return self.scheduler.__class__.__name__ if self.scheduler else None # run coordinator @property def run_coordinator(self) -> "RunCoordinator": return self._run_coordinator # run launcher @property def run_launcher(self) -> "RunLauncher": return self._run_launcher # compute logs @property def compute_log_manager(self) -> "ComputeLogManager": return self._compute_log_manager def get_settings(self, settings_key: str) -> Any: check.str_param(settings_key, "settings_key") if self._settings and settings_key in self._settings: return self._settings.get(settings_key) return {} @property def telemetry_enabled(self) -> bool: if self.is_ephemeral: return False dagster_telemetry_enabled_default = True telemetry_settings = self.get_settings("telemetry") if not telemetry_settings: return dagster_telemetry_enabled_default if "enabled" in telemetry_settings: return telemetry_settings["enabled"] elif "experimental_dagit" in telemetry_settings: return telemetry_settings["experimental_dagit"] else: return dagster_telemetry_enabled_default # run monitoring @property def run_monitoring_enabled(self) -> bool: return self._run_monitoring_enabled @property def run_monitoring_settings(self) -> Dict: return self.get_settings("run_monitoring") @property def run_monitoring_start_timeout_seconds(self) -> int: return self.run_monitoring_settings.get("start_timeout_seconds", 180) @property def code_server_settings(self) -> Dict: return self.get_settings("code_servers") @property def code_server_process_startup_timeout(self) -> int: return self.code_server_settings.get( "local_startup_timeout", DEFAULT_LOCAL_CODE_SERVER_STARTUP_TIMEOUT ) @property def run_monitoring_max_resume_run_attempts(self) -> int: default_max_resume_run_attempts = 3 if self.run_launcher.supports_resume_run else 0 return self.run_monitoring_settings.get( "max_resume_run_attempts", default_max_resume_run_attempts ) @property def run_monitoring_poll_interval_seconds(self) -> int: return self.run_monitoring_settings.get("poll_interval_seconds", 120) @property def cancellation_thread_poll_interval_seconds(self) -> int: return self.get_settings("run_monitoring").get( "cancellation_thread_poll_interval_seconds", 10 ) @property def run_retries_enabled(self) -> bool: return self.get_settings("run_retries").get("enabled", False) @property def run_retries_max_retries(self) -> int: return self.get_settings("run_retries").get("max_retries") # python logs @property def managed_python_loggers(self) -> List[str]: python_log_settings = self.get_settings("python_logs") or {} return python_log_settings.get("managed_python_loggers", []) @property def python_log_level(self) -> Optional[str]: python_log_settings = self.get_settings("python_logs") or {} return python_log_settings.get("python_log_level") def upgrade(self, print_fn=None): from dagster.core.storage.migration.utils import upgrading_instance with upgrading_instance(self): if print_fn: print_fn("Updating run storage...") self._run_storage.upgrade() self._run_storage.migrate(print_fn) if print_fn: print_fn("Updating event storage...") self._event_storage.upgrade() self._event_storage.reindex_assets(print_fn=print_fn) if print_fn: print_fn("Updating schedule storage...") self._schedule_storage.upgrade() self._schedule_storage.migrate(print_fn) def optimize_for_dagit(self, statement_timeout): if self._schedule_storage: self._schedule_storage.optimize_for_dagit(statement_timeout=statement_timeout) self._run_storage.optimize_for_dagit(statement_timeout=statement_timeout) self._event_storage.optimize_for_dagit(statement_timeout=statement_timeout) def reindex(self, print_fn=lambda _: None): print_fn("Checking for reindexing...") self._event_storage.reindex_events(print_fn) self._event_storage.reindex_assets(print_fn) self._run_storage.optimize(print_fn) self._schedule_storage.optimize(print_fn) print_fn("Done.") def dispose(self): self._run_storage.dispose() self.run_coordinator.dispose() self._run_launcher.dispose() self._event_storage.dispose() self._compute_log_manager.dispose() # run storage @traced def get_run_by_id(self, run_id: str) -> Optional[PipelineRun]: return self._run_storage.get_run_by_id(run_id) @traced def get_pipeline_snapshot(self, snapshot_id: str) -> "PipelineSnapshot": return self._run_storage.get_pipeline_snapshot(snapshot_id) @traced def has_pipeline_snapshot(self, snapshot_id: str) -> bool: return self._run_storage.has_pipeline_snapshot(snapshot_id) @traced def has_snapshot(self, snapshot_id: str) -> bool: return self._run_storage.has_snapshot(snapshot_id) @traced def get_historical_pipeline(self, snapshot_id: str) -> "HistoricalPipeline": from dagster.core.host_representation import HistoricalPipeline snapshot = self._run_storage.get_pipeline_snapshot(snapshot_id) parent_snapshot = ( self._run_storage.get_pipeline_snapshot(snapshot.lineage_snapshot.parent_snapshot_id) if snapshot.lineage_snapshot else None ) return HistoricalPipeline(snapshot, snapshot_id, parent_snapshot) @traced def has_historical_pipeline(self, snapshot_id: str) -> bool: return self._run_storage.has_pipeline_snapshot(snapshot_id) @traced def get_execution_plan_snapshot(self, snapshot_id: str) -> "ExecutionPlanSnapshot": return self._run_storage.get_execution_plan_snapshot(snapshot_id) @traced def get_run_stats(self, run_id: str) -> PipelineRunStatsSnapshot: return self._event_storage.get_stats_for_run(run_id) @traced def get_run_step_stats(self, run_id, step_keys=None) -> List["RunStepKeyStatsSnapshot"]: return self._event_storage.get_step_stats_for_run(run_id, step_keys) @traced def get_run_tags(self) -> List[Tuple[str, Set[str]]]: return self._run_storage.get_run_tags() @traced def get_run_group(self, run_id: str) -> Optional[Tuple[str, Iterable[PipelineRun]]]: return self._run_storage.get_run_group(run_id) def create_run_for_pipeline( self, pipeline_def, execution_plan=None, run_id=None, run_config=None, mode=None, solids_to_execute=None, status=None, tags=None, root_run_id=None, parent_run_id=None, solid_selection=None, asset_selection=None, external_pipeline_origin=None, pipeline_code_origin=None, ): from dagster.core.execution.api import create_execution_plan from dagster.core.execution.plan.plan import ExecutionPlan from dagster.core.snap import snapshot_from_execution_plan check.inst_param(pipeline_def, "pipeline_def", PipelineDefinition) check.opt_inst_param(execution_plan, "execution_plan", ExecutionPlan) # note that solids_to_execute is required to execute the solid subset, which is the # frozenset version of the previous solid_subset. # solid_selection is not required and will not be converted to solids_to_execute here. # i.e. this function doesn't handle solid queries. # solid_selection is only used to pass the user queries further down. check.opt_set_param(solids_to_execute, "solids_to_execute", of_type=str) check.opt_list_param(solid_selection, "solid_selection", of_type=str) check.opt_set_param(asset_selection, "asset_selection", of_type=AssetKey) if solids_to_execute: if isinstance(pipeline_def, PipelineSubsetDefinition): # for the case when pipeline_def is created by IPipeline or ExternalPipeline check.invariant( solids_to_execute == pipeline_def.solids_to_execute, "Cannot create a PipelineRun from pipeline subset {pipeline_solids_to_execute} " "that conflicts with solids_to_execute arg {solids_to_execute}".format( pipeline_solids_to_execute=str_format_list(pipeline_def.solids_to_execute), solids_to_execute=str_format_list(solids_to_execute), ), ) else: # for cases when `create_run_for_pipeline` is directly called pipeline_def = pipeline_def.get_pipeline_subset_def( solids_to_execute=solids_to_execute ) step_keys_to_execute = None if execution_plan: step_keys_to_execute = execution_plan.step_keys_to_execute else: execution_plan = create_execution_plan( pipeline=InMemoryPipeline(pipeline_def), run_config=run_config, mode=mode, instance_ref=self.get_ref() if self.is_persistent else None, tags=tags, ) return self.create_run( pipeline_name=pipeline_def.name, run_id=run_id, run_config=run_config, mode=check.opt_str_param(mode, "mode", default=pipeline_def.get_default_mode_name()), solid_selection=solid_selection, asset_selection=asset_selection, solids_to_execute=solids_to_execute, step_keys_to_execute=step_keys_to_execute, status=status, tags=tags, root_run_id=root_run_id, parent_run_id=parent_run_id, pipeline_snapshot=pipeline_def.get_pipeline_snapshot(), execution_plan_snapshot=snapshot_from_execution_plan( execution_plan, pipeline_def.get_pipeline_snapshot_id(), ), parent_pipeline_snapshot=pipeline_def.get_parent_pipeline_snapshot(), external_pipeline_origin=external_pipeline_origin, pipeline_code_origin=pipeline_code_origin, ) def _construct_run_with_snapshots( self, pipeline_name, run_id, run_config, mode, solids_to_execute, step_keys_to_execute, status, tags, root_run_id, parent_run_id, pipeline_snapshot, execution_plan_snapshot, parent_pipeline_snapshot, asset_selection=None, solid_selection=None, external_pipeline_origin=None, pipeline_code_origin=None, ): # https://github.com/dagster-io/dagster/issues/2403 if tags and IS_AIRFLOW_INGEST_PIPELINE_STR in tags: if AIRFLOW_EXECUTION_DATE_STR not in tags: tags[AIRFLOW_EXECUTION_DATE_STR] = get_current_datetime_in_utc().isoformat() check.invariant( not (not pipeline_snapshot and execution_plan_snapshot), "It is illegal to have an execution plan snapshot and not have a pipeline snapshot. " "It is possible to have no execution plan snapshot since we persist runs " "that do not successfully compile execution plans in the scheduled case.", ) pipeline_snapshot_id = ( self._ensure_persisted_pipeline_snapshot(pipeline_snapshot, parent_pipeline_snapshot) if pipeline_snapshot else None ) execution_plan_snapshot_id = ( self._ensure_persisted_execution_plan_snapshot( execution_plan_snapshot, pipeline_snapshot_id, step_keys_to_execute ) if execution_plan_snapshot and pipeline_snapshot_id else None ) return DagsterRun( pipeline_name=pipeline_name, run_id=run_id, run_config=run_config, mode=mode, asset_selection=asset_selection, solid_selection=solid_selection, solids_to_execute=solids_to_execute, step_keys_to_execute=step_keys_to_execute, status=status, tags=tags, root_run_id=root_run_id, parent_run_id=parent_run_id, pipeline_snapshot_id=pipeline_snapshot_id, execution_plan_snapshot_id=execution_plan_snapshot_id, external_pipeline_origin=external_pipeline_origin, pipeline_code_origin=pipeline_code_origin, ) def _ensure_persisted_pipeline_snapshot(self, pipeline_snapshot, parent_pipeline_snapshot): from dagster.core.snap import PipelineSnapshot, create_pipeline_snapshot_id check.inst_param(pipeline_snapshot, "pipeline_snapshot", PipelineSnapshot) check.opt_inst_param(parent_pipeline_snapshot, "parent_pipeline_snapshot", PipelineSnapshot) if pipeline_snapshot.lineage_snapshot: if not self._run_storage.has_pipeline_snapshot( pipeline_snapshot.lineage_snapshot.parent_snapshot_id ): check.invariant( create_pipeline_snapshot_id(parent_pipeline_snapshot) == pipeline_snapshot.lineage_snapshot.parent_snapshot_id, "Parent pipeline snapshot id out of sync with passed parent pipeline snapshot", ) returned_pipeline_snapshot_id = self._run_storage.add_pipeline_snapshot( parent_pipeline_snapshot ) check.invariant( pipeline_snapshot.lineage_snapshot.parent_snapshot_id == returned_pipeline_snapshot_id ) pipeline_snapshot_id = create_pipeline_snapshot_id(pipeline_snapshot) if not self._run_storage.has_pipeline_snapshot(pipeline_snapshot_id): returned_pipeline_snapshot_id = self._run_storage.add_pipeline_snapshot( pipeline_snapshot ) check.invariant(pipeline_snapshot_id == returned_pipeline_snapshot_id) return pipeline_snapshot_id def _ensure_persisted_execution_plan_snapshot( self, execution_plan_snapshot, pipeline_snapshot_id, step_keys_to_execute ): from dagster.core.snap.execution_plan_snapshot import ( ExecutionPlanSnapshot, create_execution_plan_snapshot_id, ) check.inst_param(execution_plan_snapshot, "execution_plan_snapshot", ExecutionPlanSnapshot) check.str_param(pipeline_snapshot_id, "pipeline_snapshot_id") check.opt_nullable_list_param(step_keys_to_execute, "step_keys_to_execute", of_type=str) check.invariant( execution_plan_snapshot.pipeline_snapshot_id == pipeline_snapshot_id, ( "Snapshot mismatch: Snapshot ID in execution plan snapshot is " '"{ep_pipeline_snapshot_id}" and snapshot_id created in memory is ' '"{pipeline_snapshot_id}"' ).format( ep_pipeline_snapshot_id=execution_plan_snapshot.pipeline_snapshot_id, pipeline_snapshot_id=pipeline_snapshot_id, ), ) execution_plan_snapshot_id = create_execution_plan_snapshot_id(execution_plan_snapshot) if not self._run_storage.has_execution_plan_snapshot(execution_plan_snapshot_id): returned_execution_plan_snapshot_id = self._run_storage.add_execution_plan_snapshot( execution_plan_snapshot ) check.invariant(execution_plan_snapshot_id == returned_execution_plan_snapshot_id) return execution_plan_snapshot_id def _log_asset_materialization_planned_events(self, pipeline_run, execution_plan_snapshot): from dagster.core.events import DagsterEvent from dagster.core.execution.context_creation_pipeline import initialize_console_manager pipeline_name = pipeline_run.pipeline_name for step in execution_plan_snapshot.steps: if step.key in execution_plan_snapshot.step_keys_to_execute: for output in step.outputs: asset_key = output.properties.asset_key if asset_key: # Logs and stores asset_materialization_planned event DagsterEvent.asset_materialization_planned( pipeline_name, asset_key, initialize_console_manager(pipeline_run, self) ) def create_run( self, pipeline_name, run_id, run_config, mode, solids_to_execute, step_keys_to_execute, status, tags, root_run_id, parent_run_id, pipeline_snapshot, execution_plan_snapshot, parent_pipeline_snapshot, asset_selection=None, solid_selection=None, external_pipeline_origin=None, pipeline_code_origin=None, ): pipeline_run = self._construct_run_with_snapshots( pipeline_name=pipeline_name, run_id=run_id, run_config=run_config, mode=mode, asset_selection=asset_selection, solid_selection=solid_selection, solids_to_execute=solids_to_execute, step_keys_to_execute=step_keys_to_execute, status=status, tags=tags, root_run_id=root_run_id, parent_run_id=parent_run_id, pipeline_snapshot=pipeline_snapshot, execution_plan_snapshot=execution_plan_snapshot, parent_pipeline_snapshot=parent_pipeline_snapshot, external_pipeline_origin=external_pipeline_origin, pipeline_code_origin=pipeline_code_origin, ) pipeline_run = self._run_storage.add_run(pipeline_run) if execution_plan_snapshot: self._log_asset_materialization_planned_events(pipeline_run, execution_plan_snapshot) return pipeline_run def create_reexecuted_run( self, parent_run: DagsterRun, repo_location: "RepositoryLocation", external_pipeline: "ExternalPipeline", strategy: "ReexecutionStrategy", extra_tags: Optional[Dict[str, Any]] = None, run_config: Optional[Dict[str, Any]] = None, mode: Optional[str] = None, use_parent_run_tags: bool = False, ) -> DagsterRun: from dagster.core.execution.plan.resume_retry import ( ReexecutionStrategy, get_retry_steps_from_parent_run, ) from dagster.core.host_representation import ExternalPipeline, RepositoryLocation check.inst_param(parent_run, "parent_run", DagsterRun) check.inst_param(repo_location, "repo_location", RepositoryLocation) check.inst_param(external_pipeline, "external_pipeline", ExternalPipeline) check.inst_param(strategy, "strategy", ReexecutionStrategy) check.opt_dict_param(extra_tags, "extra_tags", key_type=str) check.opt_dict_param(run_config, "run_config", key_type=str) check.opt_str_param(mode, "mode") check.bool_param(use_parent_run_tags, "use_parent_run_tags") root_run_id = parent_run.root_run_id or parent_run.run_id parent_run_id = parent_run.run_id tags = merge_dicts( external_pipeline.tags, # these can differ from external_pipeline.tags if tags were added at launch time parent_run.tags if use_parent_run_tags else {}, extra_tags or {}, { PARENT_RUN_ID_TAG: parent_run_id, ROOT_RUN_ID_TAG: root_run_id, }, ) mode = cast(str, mode if mode is not None else parent_run.mode) run_config = run_config if run_config is not None else parent_run.run_config if strategy == ReexecutionStrategy.FROM_FAILURE: check.invariant( parent_run.status == PipelineRunStatus.FAILURE, "Cannot reexecute from failure a run that is not failed", ) step_keys_to_execute, known_state = get_retry_steps_from_parent_run( self, parent_run=parent_run, ) tags[RESUME_RETRY_TAG] = "true" elif strategy == ReexecutionStrategy.ALL_STEPS: step_keys_to_execute = None known_state = None else: raise DagsterInvariantViolationError(f"Unknown reexecution strategy: {strategy}") external_execution_plan = repo_location.get_external_execution_plan( external_pipeline, run_config, mode=mode, step_keys_to_execute=step_keys_to_execute, known_state=known_state, instance=self, ) return self.create_run( pipeline_name=parent_run.pipeline_name, run_id=None, run_config=run_config, mode=mode, solids_to_execute=parent_run.solids_to_execute, step_keys_to_execute=step_keys_to_execute, status=PipelineRunStatus.NOT_STARTED, tags=tags, root_run_id=root_run_id, parent_run_id=parent_run_id, pipeline_snapshot=external_pipeline.pipeline_snapshot, execution_plan_snapshot=external_execution_plan.execution_plan_snapshot, parent_pipeline_snapshot=external_pipeline.parent_pipeline_snapshot, solid_selection=parent_run.solid_selection, asset_selection=parent_run.asset_selection, external_pipeline_origin=external_pipeline.get_external_origin(), pipeline_code_origin=external_pipeline.get_python_origin(), ) def register_managed_run( self, pipeline_name, run_id, run_config, mode, solids_to_execute, step_keys_to_execute, tags, root_run_id, parent_run_id, pipeline_snapshot, execution_plan_snapshot, parent_pipeline_snapshot, solid_selection=None, pipeline_code_origin=None, ): # The usage of this method is limited to dagster-airflow, specifically in Dagster # Operators that are executed in Airflow. Because a common workflow in Airflow is to # retry dags from arbitrary tasks, we need any node to be capable of creating a # PipelineRun. # # The try-except DagsterRunAlreadyExists block handles the race when multiple "root" tasks # simultaneously execute self._run_storage.add_run(pipeline_run). When this happens, only # one task succeeds in creating the run, while the others get DagsterRunAlreadyExists # error; at this point, the failed tasks try again to fetch the existing run. # https://github.com/dagster-io/dagster/issues/2412 pipeline_run = self._construct_run_with_snapshots( pipeline_name=pipeline_name, run_id=run_id, run_config=run_config, mode=mode, solid_selection=solid_selection, solids_to_execute=solids_to_execute, step_keys_to_execute=step_keys_to_execute, status=PipelineRunStatus.MANAGED, tags=tags, root_run_id=root_run_id, parent_run_id=parent_run_id, pipeline_snapshot=pipeline_snapshot, execution_plan_snapshot=execution_plan_snapshot, parent_pipeline_snapshot=parent_pipeline_snapshot, pipeline_code_origin=pipeline_code_origin, ) def get_run(): candidate_run = self.get_run_by_id(pipeline_run.run_id) field_diff = _check_run_equality(pipeline_run, candidate_run) if field_diff: raise DagsterRunConflict( "Found conflicting existing run with same id {run_id}. Runs differ in:" "\n{field_diff}".format( run_id=pipeline_run.run_id, field_diff=_format_field_diff(field_diff), ), ) return candidate_run if self.has_run(pipeline_run.run_id): return get_run() try: return self._run_storage.add_run(pipeline_run) except DagsterRunAlreadyExists: return get_run() @traced def add_run(self, pipeline_run: PipelineRun): return self._run_storage.add_run(pipeline_run) @traced def add_snapshot(self, snapshot, snapshot_id=None): return self._run_storage.add_snapshot(snapshot, snapshot_id) @traced def handle_run_event(self, run_id: str, event: "DagsterEvent"): return self._run_storage.handle_run_event(run_id, event) @traced def add_run_tags(self, run_id: str, new_tags: Dict[str, str]): return self._run_storage.add_run_tags(run_id, new_tags) @traced def has_run(self, run_id: str) -> bool: return self._run_storage.has_run(run_id) @traced def get_runs( self, filters: Optional[RunsFilter] = None, cursor: Optional[str] = None, limit: Optional[int] = None, bucket_by: Optional[Union[JobBucket, TagBucket]] = None, ) -> Iterable[PipelineRun]: return self._run_storage.get_runs(filters, cursor, limit, bucket_by) @traced def get_runs_count(self, filters: Optional[RunsFilter] = None) -> int: return self._run_storage.get_runs_count(filters) @traced def get_run_groups( self, filters: Optional[RunsFilter] = None, cursor: Optional[str] = None, limit: Optional[int] = None, ) -> Dict[str, Dict[str, Union[Iterable[PipelineRun], int]]]: return self._run_storage.get_run_groups(filters=filters, cursor=cursor, limit=limit) @traced def get_run_records( self, filters: Optional[RunsFilter] = None, limit: Optional[int] = None, order_by: Optional[str] = None, ascending: bool = False, cursor: Optional[str] = None, bucket_by: Optional[Union[JobBucket, TagBucket]] = None, ) -> List[RunRecord]: """Return a list of run records stored in the run storage, sorted by the given column in given order. Args: filters (Optional[RunsFilter]): the filter by which to filter runs. limit (Optional[int]): Number of results to get. Defaults to infinite. order_by (Optional[str]): Name of the column to sort by. Defaults to id. ascending (Optional[bool]): Sort the result in ascending order if True, descending otherwise. Defaults to descending. Returns: List[RunRecord]: List of run records stored in the run storage. """ return self._run_storage.get_run_records( filters, limit, order_by, ascending, cursor, bucket_by ) @property def supports_bucket_queries(self): return self._run_storage.supports_bucket_queries @traced def get_run_partition_data( self, partition_set_name: str, job_name: str, repository_label: str ) -> List[RunPartitionData]: """Get run partition data for a given partitioned job.""" return self._run_storage.get_run_partition_data( partition_set_name, job_name, repository_label ) def wipe(self): self._run_storage.wipe() self._event_storage.wipe() @traced def delete_run(self, run_id: str): self._run_storage.delete_run(run_id) self._event_storage.delete_events(run_id) # event storage @traced def logs_after( self, run_id, cursor, of_type: Optional["DagsterEventType"] = None, limit: Optional[int] = None, ): return self._event_storage.get_logs_for_run( run_id, cursor=cursor, of_type=of_type, limit=limit, ) @traced def all_logs( self, run_id, of_type: Optional[Union["DagsterEventType", Set["DagsterEventType"]]] = None ): return self._event_storage.get_logs_for_run(run_id, of_type=of_type) @traced def get_records_for_run( self, run_id: str, cursor: Optional[str] = None, of_type: Optional[Union["DagsterEventType", Set["DagsterEventType"]]] = None, limit: Optional[int] = None, ): return self._event_storage.get_records_for_run(run_id, cursor, of_type, limit) def watch_event_logs(self, run_id, cursor, cb): return self._event_storage.watch(run_id, cursor, cb) def end_watch_event_logs(self, run_id, cb): return self._event_storage.end_watch(run_id, cb) # asset storage @traced def all_asset_keys(self): return self._event_storage.all_asset_keys() @traced def get_asset_keys(self, prefix=None, limit=None, cursor=None): return self._event_storage.get_asset_keys(prefix=prefix, limit=limit, cursor=cursor) @traced def has_asset_key(self, asset_key: AssetKey) -> bool: return self._event_storage.has_asset_key(asset_key) @traced def get_latest_materialization_events( self, asset_keys: Sequence[AssetKey] ) -> Mapping[AssetKey, Optional["EventLogEntry"]]: return self._event_storage.get_latest_materialization_events(asset_keys) @traced def get_event_records( self, event_records_filter: "EventRecordsFilter", limit: Optional[int] = None, ascending: bool = False, ) -> Iterable["EventLogRecord"]: """Return a list of event records stored in the event log storage. Args: event_records_filter (Optional[EventRecordsFilter]): the filter by which to filter event records. limit (Optional[int]): Number of results to get. Defaults to infinite. ascending (Optional[bool]): Sort the result in ascending order if True, descending otherwise. Defaults to descending. Returns: List[EventLogRecord]: List of event log records stored in the event log storage. """ return self._event_storage.get_event_records(event_records_filter, limit, ascending) @traced def get_asset_records( self, asset_keys: Optional[Sequence[AssetKey]] = None ) -> Iterable["AssetRecord"]: return self._event_storage.get_asset_records(asset_keys) @traced def run_ids_for_asset_key(self, asset_key): check.inst_param(asset_key, "asset_key", AssetKey) return self._event_storage.get_asset_run_ids(asset_key) @traced def wipe_assets(self, asset_keys): check.list_param(asset_keys, "asset_keys", of_type=AssetKey) for asset_key in asset_keys: self._event_storage.wipe_asset(asset_key) @traced def get_materialization_count_by_partition( self, asset_keys: Sequence[AssetKey] ) -> Mapping[AssetKey, Mapping[str, int]]: return self._event_storage.get_materialization_count_by_partition(asset_keys) # event subscriptions def _get_yaml_python_handlers(self): if self._settings: logging_config = self.get_settings("python_logs").get("dagster_handler_config", {}) if logging_config: experimental_functionality_warning("Handling yaml-defined logging configuration") # Handlers can only be retrieved from dictConfig configuration if they are attached # to a logger. We add a dummy logger to the configuration that allows us to access user # defined handlers. handler_names = logging_config.get("handlers", {}).keys() dagster_dummy_logger_name = "dagster_dummy_logger" processed_dict_conf = { "version": 1, "disable_existing_loggers": False, "loggers": {dagster_dummy_logger_name: {"handlers": handler_names}}, } processed_dict_conf.update(logging_config) logging.config.dictConfig(processed_dict_conf) dummy_logger = logging.getLogger(dagster_dummy_logger_name) return dummy_logger.handlers return [] def _get_event_log_handler(self): event_log_handler = _EventListenerLogHandler(self) event_log_handler.setLevel(10) return event_log_handler def get_handlers(self): handlers = [self._get_event_log_handler()] handlers.extend(self._get_yaml_python_handlers()) return handlers def store_event(self, event): self._event_storage.store_event(event) def handle_new_event(self, event): run_id = event.run_id self._event_storage.store_event(event) if event.is_dagster_event and event.dagster_event.is_pipeline_event: self._run_storage.handle_run_event(run_id, event.dagster_event) for sub in self._subscribers[run_id]: sub(event) def add_event_listener(self, run_id, cb): self._subscribers[run_id].append(cb) def report_engine_event( self, message, pipeline_run=None, engine_event_data=None, cls=None, step_key=None, pipeline_name=None, run_id=None, ): """ Report a EngineEvent that occurred outside of a pipeline execution context. """ from dagster.core.events import DagsterEvent, DagsterEventType, EngineEventData from dagster.core.events.log import EventLogEntry check.opt_class_param(cls, "cls") check.str_param(message, "message") check.opt_inst_param(pipeline_run, "pipeline_run", PipelineRun) check.opt_str_param(run_id, "run_id") check.opt_str_param(pipeline_name, "pipeline_name") check.invariant( pipeline_run or (pipeline_name and run_id), "Must include either pipeline_run or pipeline_name and run_id", ) run_id = run_id if run_id else pipeline_run.run_id pipeline_name = pipeline_name if pipeline_name else pipeline_run.pipeline_name engine_event_data = check.opt_inst_param( engine_event_data, "engine_event_data", EngineEventData, EngineEventData([]), ) if cls: message = "[{}] {}".format(cls.__name__, message) log_level = logging.INFO if engine_event_data and engine_event_data.error: log_level = logging.ERROR dagster_event = DagsterEvent( event_type_value=DagsterEventType.ENGINE_EVENT.value, pipeline_name=pipeline_name, message=message, event_specific_data=engine_event_data, step_key=step_key, ) event_record = EventLogEntry( user_message="", level=log_level, pipeline_name=pipeline_name, run_id=run_id, error_info=None, timestamp=time.time(), step_key=step_key, dagster_event=dagster_event, ) self.handle_new_event(event_record) return dagster_event def report_run_canceling(self, run, message=None): from dagster.core.events import DagsterEvent, DagsterEventType from dagster.core.events.log import EventLogEntry check.inst_param(run, "run", PipelineRun) message = check.opt_str_param( message, "message", "Sending run termination request.", ) canceling_event = DagsterEvent( event_type_value=DagsterEventType.PIPELINE_CANCELING.value, pipeline_name=run.pipeline_name, message=message, ) event_record = EventLogEntry( user_message="", level=logging.INFO, pipeline_name=run.pipeline_name, run_id=run.run_id, error_info=None, timestamp=time.time(), dagster_event=canceling_event, ) self.handle_new_event(event_record) def report_run_canceled( self, pipeline_run, message=None, ): from dagster.core.events import DagsterEvent, DagsterEventType from dagster.core.events.log import EventLogEntry check.inst_param(pipeline_run, "pipeline_run", PipelineRun) message = check.opt_str_param( message, "mesage", "This run has been marked as canceled from outside the execution context.", ) dagster_event = DagsterEvent( event_type_value=DagsterEventType.PIPELINE_CANCELED.value, pipeline_name=pipeline_run.pipeline_name, message=message, ) event_record = EventLogEntry( user_message="", level=logging.ERROR, pipeline_name=pipeline_run.pipeline_name, run_id=pipeline_run.run_id, error_info=None, timestamp=time.time(), dagster_event=dagster_event, ) self.handle_new_event(event_record) return dagster_event def report_run_failed(self, pipeline_run, message=None): from dagster.core.events import DagsterEvent, DagsterEventType from dagster.core.events.log import EventLogEntry check.inst_param(pipeline_run, "pipeline_run", PipelineRun) message = check.opt_str_param( message, "message", "This run has been marked as failed from outside the execution context.", ) dagster_event = DagsterEvent( event_type_value=DagsterEventType.PIPELINE_FAILURE.value, pipeline_name=pipeline_run.pipeline_name, message=message, ) event_record = EventLogEntry( user_message="", level=logging.ERROR, pipeline_name=pipeline_run.pipeline_name, run_id=pipeline_run.run_id, error_info=None, timestamp=time.time(), dagster_event=dagster_event, ) self.handle_new_event(event_record) return dagster_event # directories def file_manager_directory(self, run_id): return self._local_artifact_storage.file_manager_dir(run_id) def storage_directory(self): return self._local_artifact_storage.storage_dir def schedules_directory(self): return self._local_artifact_storage.schedules_dir # Runs coordinator def submit_run(self, run_id, workspace: "IWorkspace") -> PipelineRun: """Submit a pipeline run to the coordinator. This method delegates to the ``RunCoordinator``, configured on the instance, and will call its implementation of ``RunCoordinator.submit_run()`` to send the run to the coordinator for execution. Runs should be created in the instance (e.g., by calling ``DagsterInstance.create_run()``) *before* this method is called, and should be in the ``PipelineRunStatus.NOT_STARTED`` state. They also must have a non-null ExternalPipelineOrigin. Args: run_id (str): The id of the run. """ from dagster.core.host_representation import ExternalPipelineOrigin from dagster.core.origin import PipelinePythonOrigin from dagster.core.run_coordinator import SubmitRunContext run = self.get_run_by_id(run_id) if run is None: raise DagsterInvariantViolationError( f"Could not load run {run_id} that was passed to submit_run" ) check.inst( run.external_pipeline_origin, ExternalPipelineOrigin, "External pipeline origin must be set for submitted runs", ) check.inst( run.pipeline_code_origin, PipelinePythonOrigin, "Python origin must be set for submitted runs", ) try: submitted_run = self._run_coordinator.submit_run( SubmitRunContext(run, workspace=workspace) ) except: from dagster.core.events import EngineEventData error = serializable_error_info_from_exc_info(sys.exc_info()) self.report_engine_event( error.message, run, EngineEventData.engine_error(error), ) self.report_run_failed(run) raise return submitted_run # Run launcher def launch_run(self, run_id: str, workspace: "IWorkspace"): """Launch a pipeline run. This method is typically called using `instance.submit_run` rather than being invoked directly. This method delegates to the ``RunLauncher``, if any, configured on the instance, and will call its implementation of ``RunLauncher.launch_run()`` to begin the execution of the specified run. Runs should be created in the instance (e.g., by calling ``DagsterInstance.create_run()``) *before* this method is called, and should be in the ``PipelineRunStatus.NOT_STARTED`` state. Args: run_id (str): The id of the run the launch. """ from dagster.core.events import DagsterEvent, DagsterEventType, EngineEventData from dagster.core.events.log import EventLogEntry from dagster.core.launcher import LaunchRunContext run = self.get_run_by_id(run_id) if run is None: raise DagsterInvariantViolationError( f"Could not load run {run_id} that was passed to launch_run" ) launch_started_event = DagsterEvent( event_type_value=DagsterEventType.PIPELINE_STARTING.value, pipeline_name=run.pipeline_name, ) event_record = EventLogEntry( user_message="", level=logging.INFO, pipeline_name=run.pipeline_name, run_id=run.run_id, error_info=None, timestamp=time.time(), dagster_event=launch_started_event, ) self.handle_new_event(event_record) run = self.get_run_by_id(run_id) if run is None: check.failed(f"Failed to reload run {run_id}") try: self._run_launcher.launch_run(LaunchRunContext(pipeline_run=run, workspace=workspace)) except: error = serializable_error_info_from_exc_info(sys.exc_info()) self.report_engine_event( error.message, run, EngineEventData.engine_error(error), ) self.report_run_failed(run) raise return run def resume_run(self, run_id: str, workspace: "IWorkspace", attempt_number: int): """Resume a pipeline run. This method should be called on runs which have already been launched, but whose run workers have died. Args: run_id (str): The id of the run the launch. """ from dagster.core.events import EngineEventData from dagster.core.launcher import ResumeRunContext from dagster.daemon.monitoring import RESUME_RUN_LOG_MESSAGE run = self.get_run_by_id(run_id) if run is None: raise DagsterInvariantViolationError( f"Could not load run {run_id} that was passed to resume_run" ) if run.status not in IN_PROGRESS_RUN_STATUSES: raise DagsterInvariantViolationError( f"Run {run_id} is not in a state that can be resumed" ) self.report_engine_event( RESUME_RUN_LOG_MESSAGE, run, ) try: self._run_launcher.resume_run( ResumeRunContext( pipeline_run=run, workspace=workspace, resume_attempt_number=attempt_number, ) ) except: error = serializable_error_info_from_exc_info(sys.exc_info()) self.report_engine_event( error.message, run, EngineEventData.engine_error(error), ) self.report_run_failed(run) raise return run def count_resume_run_attempts(self, run_id: str): from dagster.daemon.monitoring import count_resume_run_attempts return count_resume_run_attempts(self, run_id) def run_will_resume(self, run_id: str): if not self.run_monitoring_enabled: return False return self.count_resume_run_attempts(run_id) < self.run_monitoring_max_resume_run_attempts # Scheduler def start_schedule(self, external_schedule): return self._scheduler.start_schedule(self, external_schedule) def stop_schedule(self, schedule_origin_id, schedule_selector_id, external_schedule): return self._scheduler.stop_schedule( self, schedule_origin_id, schedule_selector_id, external_schedule ) def scheduler_debug_info(self): from dagster.core.definitions.run_request import InstigatorType from dagster.core.scheduler import SchedulerDebugInfo errors = [] schedules = [] for schedule_state in self.all_instigator_state(instigator_type=InstigatorType.SCHEDULE): schedule_info = { schedule_state.instigator_name: { "status": schedule_state.status.value, "cron_schedule": schedule_state.instigator_data.cron_schedule, "schedule_origin_id": schedule_state.instigator_origin_id, "repository_origin_id": schedule_state.repository_origin_id, } } schedules.append(yaml.safe_dump(schedule_info, default_flow_style=False)) return SchedulerDebugInfo( scheduler_config_info=self._info_str_for_component("Scheduler", self.scheduler), scheduler_info=self.scheduler.debug_info(), schedule_storage=schedules, errors=errors, ) # Schedule / Sensor Storage def start_sensor(self, external_sensor: "ExternalSensor"): from dagster.core.definitions.run_request import InstigatorType from dagster.core.scheduler.instigation import ( InstigatorState, InstigatorStatus, SensorInstigatorData, ) stored_state = self.get_instigator_state( external_sensor.get_external_origin_id(), external_sensor.selector_id ) computed_state = external_sensor.get_current_instigator_state(stored_state) if computed_state.is_running: return computed_state if not stored_state: return self.add_instigator_state( InstigatorState( external_sensor.get_external_origin(), InstigatorType.SENSOR, InstigatorStatus.RUNNING, SensorInstigatorData(min_interval=external_sensor.min_interval_seconds), ) ) else: return self.update_instigator_state(stored_state.with_status(InstigatorStatus.RUNNING)) def stop_sensor( self, instigator_origin_id: str, selector_id: str, external_sensor: Optional["ExternalSensor"], ): from dagster.core.definitions.run_request import InstigatorType from dagster.core.scheduler.instigation import ( InstigatorState, InstigatorStatus, SensorInstigatorData, ) stored_state = self.get_instigator_state(instigator_origin_id, selector_id) if external_sensor: computed_state = external_sensor.get_current_instigator_state(stored_state) else: computed_state = stored_state if not computed_state.is_running: return computed_state if not stored_state: assert external_sensor return self.add_instigator_state( InstigatorState( external_sensor.get_external_origin(), InstigatorType.SENSOR, InstigatorStatus.STOPPED, SensorInstigatorData(min_interval=external_sensor.min_interval_seconds), ) ) else: return self.update_instigator_state(stored_state.with_status(InstigatorStatus.STOPPED)) @traced def all_instigator_state( self, repository_origin_id=None, repository_selector_id=None, instigator_type=None ): return self._schedule_storage.all_instigator_state( repository_origin_id, repository_selector_id, instigator_type ) @traced def get_instigator_state(self, origin_id: str, selector_id: str) -> Optional["InstigatorState"]: if not self._schedule_storage: check.failed("Schedule storage not available") return self._schedule_storage.get_instigator_state(origin_id, selector_id) def add_instigator_state(self, state: "InstigatorState") -> "InstigatorState": if not self._schedule_storage: check.failed("Schedule storage not available") return self._schedule_storage.add_instigator_state(state) def update_instigator_state(self, state: "InstigatorState") -> "InstigatorState": if not self._schedule_storage: check.failed("Schedule storage not available") return self._schedule_storage.update_instigator_state(state) def delete_instigator_state(self, origin_id, selector_id): return self._schedule_storage.delete_instigator_state(origin_id, selector_id) @property def supports_batch_tick_queries(self): return self._schedule_storage and self._schedule_storage.supports_batch_queries @traced def get_batch_ticks( self, selector_ids: Sequence[str], limit: Optional[int] = None, statuses: Optional[Sequence["TickStatus"]] = None, ) -> Mapping[str, Iterable["InstigatorTick"]]: if not self._schedule_storage: return {} return self._schedule_storage.get_batch_ticks(selector_ids, limit, statuses) @traced def get_tick(self, origin_id, selector_id, timestamp): matches = self._schedule_storage.get_ticks( origin_id, selector_id, before=timestamp + 1, after=timestamp - 1, limit=1 ) return matches[0] if len(matches) else None @traced def get_ticks(self, origin_id, selector_id, before=None, after=None, limit=None, statuses=None): return self._schedule_storage.get_ticks( origin_id, selector_id, before=before, after=after, limit=limit, statuses=statuses ) def create_tick(self, tick_data): return self._schedule_storage.create_tick(tick_data) def update_tick(self, tick): return self._schedule_storage.update_tick(tick) def purge_ticks(self, origin_id, selector_id, tick_status, before): self._schedule_storage.purge_ticks(origin_id, selector_id, tick_status, before) def wipe_all_schedules(self): if self._scheduler: self._scheduler.wipe(self) self._schedule_storage.wipe() def logs_path_for_schedule(self, schedule_origin_id): return self._scheduler.get_logs_path(self, schedule_origin_id) def __enter__(self): return self def __exit__(self, exception_type, exception_value, traceback): self.dispose() if DagsterInstance._EXIT_STACK: DagsterInstance._EXIT_STACK.close() # dagster daemon def add_daemon_heartbeat(self, daemon_heartbeat: "DaemonHeartbeat"): """Called on a regular interval by the daemon""" self._run_storage.add_daemon_heartbeat(daemon_heartbeat) def get_daemon_heartbeats(self) -> Dict[str, "DaemonHeartbeat"]: """Latest heartbeats of all daemon types""" return self._run_storage.get_daemon_heartbeats() def wipe_daemon_heartbeats(self): self._run_storage.wipe_daemon_heartbeats() def get_required_daemon_types(self): from dagster.core.run_coordinator import QueuedRunCoordinator from dagster.core.scheduler import DagsterDaemonScheduler from dagster.daemon.auto_run_reexecution.event_log_consumer import EventLogConsumerDaemon from dagster.daemon.daemon import ( BackfillDaemon, MonitoringDaemon, SchedulerDaemon, SensorDaemon, ) from dagster.daemon.run_coordinator.queued_run_coordinator_daemon import ( QueuedRunCoordinatorDaemon, ) if self.is_ephemeral: return [] daemons = [SensorDaemon.daemon_type(), BackfillDaemon.daemon_type()] if isinstance(self.scheduler, DagsterDaemonScheduler): daemons.append(SchedulerDaemon.daemon_type()) if isinstance(self.run_coordinator, QueuedRunCoordinator): daemons.append(QueuedRunCoordinatorDaemon.daemon_type()) if self.run_monitoring_enabled: daemons.append(MonitoringDaemon.daemon_type()) if self.run_retries_enabled: daemons.append(EventLogConsumerDaemon.daemon_type()) return daemons # backfill def get_backfills(self, status=None, cursor=None, limit=None): return self._run_storage.get_backfills(status=status, cursor=cursor, limit=limit) def get_backfill(self, backfill_id): return self._run_storage.get_backfill(backfill_id) def add_backfill(self, partition_backfill): self._run_storage.add_backfill(partition_backfill) def update_backfill(self, partition_backfill): return self._run_storage.update_backfill(partition_backfill) @property def should_start_background_run_thread(self) -> bool: """ Gate on an experimental feature to start a thread that monitors for if the run should be canceled. """ return False def is_dagit_telemetry_enabled(instance): telemetry_settings = instance.get_settings("telemetry") if not telemetry_settings: return False if "experimental_dagit" in telemetry_settings: return telemetry_settings["experimental_dagit"] else: return False
38.232357
198
0.66354
ace9df2d2ec659aa5f2fe786eaedafa3cbdf5126
1,724
py
Python
admin_permissions/admin.py
silentsokolov/django-admin-permissions
91e1eb36a0cad0b7e4be10a7a2f892cbad53b903
[ "MIT" ]
5
2015-08-21T12:10:31.000Z
2017-11-07T20:33:49.000Z
admin_permissions/admin.py
silentsokolov/django-admin-permissions
91e1eb36a0cad0b7e4be10a7a2f892cbad53b903
[ "MIT" ]
1
2021-05-23T10:14:56.000Z
2021-05-23T10:18:34.000Z
admin_permissions/admin.py
silentsokolov/django-admin-permissions
91e1eb36a0cad0b7e4be10a7a2f892cbad53b903
[ "MIT" ]
2
2017-07-27T09:58:29.000Z
2021-05-21T08:01:23.000Z
# -*- coding: utf-8 -*- from __future__ import unicode_literals class FieldPermissionMixin(object): """Adds simple functionality to check the permissions for the fields""" fields_permissions = {} fields_permissions_read_only = False def get_fieldsets(self, request, obj=None): fieldsets = super(FieldPermissionMixin, self).get_fieldsets(request, obj) if not self.fields_permissions_read_only: for permission, fields in self.fields_permissions.items(): if not request.user.has_perm(permission): if isinstance(fields, (str, list)): fields = (fields,) fieldsets = self.remove_fields(fieldsets, *fields) return fieldsets def get_readonly_fields(self, request, obj=None): fieldsets = super(FieldPermissionMixin, self).get_readonly_fields(request, obj) if self.fields_permissions_read_only: for permission, fields in self.fields_permissions.items(): if not request.user.has_perm(permission): if isinstance(fields, (str, list)): fields = (fields,) fieldsets += fields return fieldsets @staticmethod def remove_fields(fieldsets, *remove_fields): """ Removes all the anterior field, if there is no fieldsets available fields, it is also removed, Returns the modified fieldsets """ for count, fs in enumerate(fieldsets): fs[1]['fields'] = [field for field in fs[1]['fields'] if field not in remove_fields] if not fs[1]['fields']: fieldsets.pop(count) return fieldsets
36.680851
96
0.61949
ace9df51d29b976fab138965a38133d4d697c9e6
2,759
py
Python
edgarsearch/tools.py
markdembo/edgarsearch
da198fb3a60802b26cb7c7a1669930420e59a0f3
[ "MIT" ]
4
2018-01-02T10:46:35.000Z
2021-11-15T09:52:59.000Z
edgarsearch/tools.py
markdembo/edgarsearch
da198fb3a60802b26cb7c7a1669930420e59a0f3
[ "MIT" ]
null
null
null
edgarsearch/tools.py
markdembo/edgarsearch
da198fb3a60802b26cb7c7a1669930420e59a0f3
[ "MIT" ]
null
null
null
"""Useful tool collection. Consists of the following functions: * getalpha: Convert integer to alphabetic character. * finduniquefilename: Find unique name if a file with the original filename already exists. Example: getalpha(0) --> "A" getalpha(1) --> "B" getalpha(27) --> "AB" finduniquefilename(ab, mode="alpha", exact=True): Todo: * None """ import os import string import glob def getalpha(x): """Convert integer to alphabetic character. Assigns every integer to a alphabetic string. Examples for clarification: getalpha(0) --> "A" getalpha(1) --> "B" getalpha(27) --> "AB" Args: x (integer): Number to be converted Returns: result (String): Alphabetic equivalent to integer Raises: None """ result = "" if x // 26 > 0: result += getalpha((x // 26)-1) result += string.ascii_uppercase[(x % 26)] else: result += string.ascii_uppercase[(x % 26)] return result def finduniquefname(fname, mode="alpha", exact=True, **kwargs): """Find unique name if a file with the original file name already exists. Args: fname_form (String): Filename (incl. path) to be checked mode (String): Sets the mode for creating unique filenames. Possible values: * "alpha" will add alphabetical suffixes * "num" will add numerical suffixes default("alpha") extract (Bool): If true, checks for the exact file name. If false, checks for the filename pattern *args: Variable length argument list. **kwargs: Arbitrary keyword arguments. Returns: fname (String): Unique filename Raises: None """ i = 0 fpre, fsuf = os.path.splitext(fname) if exact is True: while os.path.isfile(fname): if mode == "alpha": fname = ( fpre + getalpha(i) + fsuf ) elif mode == "num": fname = ( fpre + str(i) + fsuf ) i += 1 else: while len(glob.glob(fname + "*")) > 0: if mode == "alpha": fname = ( fpre + getalpha(i) + fsuf ) elif mode == "num": fname = ( fpre + str(i) + fsuf ) i += 1 return(fname)
25.311927
79
0.474447
ace9dfb3963411a97189d70c62ac1790065ebfe9
3,938
py
Python
SalishSeaTools/salishsea_tools/diagnosis_tools.py
SalishSeaCast/tools
4be9170bbe7ab700ab1b3afc3138e669053d43f8
[ "ECL-2.0", "Apache-2.0" ]
2
2020-06-23T16:09:00.000Z
2022-01-11T17:37:37.000Z
SalishSeaTools/salishsea_tools/diagnosis_tools.py
SalishSeaCast/tools
4be9170bbe7ab700ab1b3afc3138e669053d43f8
[ "ECL-2.0", "Apache-2.0" ]
2
2020-11-19T17:51:25.000Z
2021-04-07T21:36:07.000Z
SalishSeaTools/salishsea_tools/diagnosis_tools.py
SalishSeaCast/tools
4be9170bbe7ab700ab1b3afc3138e669053d43f8
[ "ECL-2.0", "Apache-2.0" ]
4
2020-05-15T03:34:47.000Z
2021-11-24T22:39:16.000Z
# Copyright 2013-2021 The Salish Sea MEOPAR contributors # and The University of British Columbia # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ """ import numpy as np import numpy.ma as ma import netCDF4 as nc from salishsea_tools import nc_tools __all__ = [ 'pcourantu', 'pcourantv','pcourantw' ] def pcourantu(files,meshmask): """Given a list of U filenames and a mesh mask, returns an array with the unscaled Courant numbers. :arg files: list of U filenames :arg meshmask: mesh mask :type meshmask: :py:class:`netCDF4.Dataset` :returns: Numpy MaskedArray with unscaled Courant numbers. :rtype: :py:class: `numpy.ma.core.MaskedArray` """ delta_x = meshmask['e1u'][:] with nc_tools.scDataset(files) as f: #merging files nt,nz,ny,nx = f.variables['vozocrtx'].shape umax = np.zeros((nz,ny,nx)) for n in range(nt): utmp = np.abs(f.variables['vozocrtx'][n,:,:,:]) umax = np.maximum(utmp,umax) #taking maximum over time ubdxmax = np.zeros((ny,nx)) for m in range(nz): ubdxtmp = umax[m,...] / delta_x[0,...] ubdxmax = np.maximum(ubdxtmp,ubdxmax) #taking maximum over depth umask = meshmask['umask'][0,0,...] return ma.masked_array(ubdxmax, mask = 1-umask) def pcourantv(files,meshmask): """Given a list of V filenames and a mesh mask, returns an array with the unscaled Courant numbers. :arg files: list of V filenames :arg meshmask: mesh mask :type meshmask: :py:class:`netCDF4.Dataset` :returns: Numpy MaskedArray with unscaled Courant numbers. :rtype: :py:class: `numpy.ma.core.MaskedArray` """ delta_y = meshmask['e2v'][:] with nc_tools.scDataset(files) as f: #merging files nt,nz,ny,nx = f.variables['vomecrty'].shape vmax = np.zeros((nz,ny,nx)) for n in range(nt): vtmp = np.abs(f.variables['vomecrty'][n,:,:,:]) vmax = np.maximum(vtmp,vmax) #taking maximum over time vbdymax = np.zeros((ny,nx)) for m in range(nz): vbdytmp = vmax[m,...] / delta_y[0,...] vbdymax = np.maximum(vbdytmp,vbdymax) #taking maximum over depth vmask = meshmask['vmask'][0,0,...] return ma.masked_array(vbdymax, mask = 1-vmask) def pcourantw(files,meshmask): """Given a list of W filenames and a mesh mask, returns an array with the unscaled Courant numbers. :arg files: list of W filenames :arg meshmask: mesh mask :type meshmask: :py:class:`netCDF4.Dataset` :returns: Numpy MaskedArray with unscaled Courant numbers. :rtype: :py:class: `numpy.ma.core.MaskedArray` """ with nc_tools.scDataset(files) as f: #merging files nt,nz,ny,nx = f.variables['vovecrtz'].shape delta_z = meshmask['e3w_1d'][0,...] delta_z = delta_z[:,np.newaxis,np.newaxis] wmax = np.zeros((nz,ny,nx)) for n in range(nt): wtmp = np.abs(f.variables['vovecrtz'][n,:,:,:]) wmax = np.maximum(wtmp,wmax) #taking maximum over time wbdz = wmax / delta_z wbdzmax = np.zeros((ny,nx)) for m in range(nz): wbdztmp = wbdz[m,...] wbdzmax = np.maximum(wbdztmp,wbdzmax) #taking maximum over depth tmask = meshmask['tmask'][0,0,...] return ma.masked_array(wbdzmax, mask = 1-tmask)
34.849558
103
0.632047
ace9dfb71902e64b3eb41e0b8a350aabaca3424e
885
py
Python
mg_toolkit/__init__.py
emilhaegglund/emg-toolkit
ed058ddb4eae21dd8bd0761fc9181c7c2b7f42ca
[ "Apache-2.0" ]
null
null
null
mg_toolkit/__init__.py
emilhaegglund/emg-toolkit
ed058ddb4eae21dd8bd0761fc9181c7c2b7f42ca
[ "Apache-2.0" ]
null
null
null
mg_toolkit/__init__.py
emilhaegglund/emg-toolkit
ed058ddb4eae21dd8bd0761fc9181c7c2b7f42ca
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2020 EMBL - European Bioinformatics Institute # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from mg_toolkit.metadata import original_metadata from mg_toolkit.search import sequence_search from mg_toolkit.bulk_download import bulk_download __all__ = ["original_metadata", "sequence_search", "bulk_download"] __version__ = "0.9.1"
36.875
74
0.776271
ace9e009bad2f32e8417a5fb3271dae74a7e1d6c
6,305
py
Python
docs/conf.py
jkocherhans/maillib
36d3df57ca0d927a60d6fa1afe42912385c4fad0
[ "BSD-2-Clause" ]
1
2015-03-30T08:08:17.000Z
2015-03-30T08:08:17.000Z
docs/conf.py
jkocherhans/maillib
36d3df57ca0d927a60d6fa1afe42912385c4fad0
[ "BSD-2-Clause" ]
null
null
null
docs/conf.py
jkocherhans/maillib
36d3df57ca0d927a60d6fa1afe42912385c4fad0
[ "BSD-2-Clause" ]
null
null
null
# -*- coding: utf-8 -*- # # maillib documentation build configuration file, created by # sphinx-quickstart on Wed Oct 21 21:26:20 2009. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.append(os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8' # The master toctree document. master_doc = 'index' # General information about the project. project = u'maillib' copyright = u'2009, Joseph Kocherhans' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.1.3' # The full version, including alpha/beta/rc tags. release = '0.1.3' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of documents that shouldn't be included in the build. #unused_docs = [] # List of directories, relative to source directory, that shouldn't be searched # for source files. exclude_trees = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. Major themes that come with # Sphinx are currently 'default' and 'sphinxdoc'. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_use_modindex = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = '' # Output file base name for HTML help builder. htmlhelp_basename = 'maillibdoc' # -- Options for LaTeX output -------------------------------------------------- # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'maillib.tex', u'maillib Documentation', u'Joseph Kocherhans', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # Additional stuff for the LaTeX preamble. #latex_preamble = '' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_use_modindex = True
32.333333
80
0.723077
ace9e08ac4d20bae0add96b7c0d1bb709c1a1a95
1,566
py
Python
examples/dagster_examples_tests/test_toys/test_pandas_hello_world.py
jake-billings/dagster
7a1548a1f246c48189f3d8109e831b744bceb7d4
[ "Apache-2.0" ]
null
null
null
examples/dagster_examples_tests/test_toys/test_pandas_hello_world.py
jake-billings/dagster
7a1548a1f246c48189f3d8109e831b744bceb7d4
[ "Apache-2.0" ]
null
null
null
examples/dagster_examples_tests/test_toys/test_pandas_hello_world.py
jake-billings/dagster
7a1548a1f246c48189f3d8109e831b744bceb7d4
[ "Apache-2.0" ]
null
null
null
from dagster import file_relative_path, execute_pipeline from dagster_examples.toys.pandas_hello_world import ( pandas_hello_world_pipeline, pandas_hello_world_pipeline_no_config, ) def test_execute_pandas_hello_world_pipeline(): environment = { 'solids': { 'sum_solid': { 'inputs': {'num_df': {'csv': {'path': file_relative_path(__file__, 'num.csv')}}} } } } result = execute_pipeline(pandas_hello_world_pipeline, environment_dict=environment) assert result.success assert result.result_for_solid('sum_solid').output_value().to_dict('list') == { 'num1': [1, 3], 'num2': [2, 4], 'sum': [3, 7], } assert result.result_for_solid('sum_sq_solid').output_value().to_dict('list') == { 'num1': [1, 3], 'num2': [2, 4], 'sum': [3, 7], 'sum_sq': [9, 49], } def test_execute_pandas_hello_world_pipeline_no_config(): environment = { 'solids': {'read_csv': {'inputs': {'path': file_relative_path(__file__, 'num.csv')}}} } result = execute_pipeline(pandas_hello_world_pipeline_no_config, environment_dict=environment) assert result.success assert result.result_for_solid('sum_solid').output_value().to_dict('list') == { 'num1': [1, 3], 'num2': [2, 4], 'sum': [3, 7], } assert result.result_for_solid('sum_sq_solid').output_value().to_dict('list') == { 'num1': [1, 3], 'num2': [2, 4], 'sum': [3, 7], 'sum_sq': [9, 49], }
27.964286
98
0.597063
ace9e11285cc9b4c307c35ccdcc3eaa3e96fb384
1,385
py
Python
jaseci_core/jaseci/attr/action.py
Gim3l/jaseci
cca187ed3e6aae31514c6c0353a7844f7703d039
[ "MIT" ]
null
null
null
jaseci_core/jaseci/attr/action.py
Gim3l/jaseci
cca187ed3e6aae31514c6c0353a7844f7703d039
[ "MIT" ]
null
null
null
jaseci_core/jaseci/attr/action.py
Gim3l/jaseci
cca187ed3e6aae31514c6c0353a7844f7703d039
[ "MIT" ]
null
null
null
""" Action class for Jaseci Each action has an id, name, timestamp and it's set of edges. """ from .item import item import importlib ACTION_PACKAGE = 'jaseci.actions.' class action(item): """ Action class for Jaseci preset_in_out holds a set of parameters in the form of lists of context objects that are to be used from whereever those contexts are attached e.g., (nodes, edges, walkers, etc). This is used by Jac's runtime engine to support preset actions in nodes access_list is used by walker to decide what to trigger """ def __init__(self, preset_in_out=None, access_list=None, *args, **kwargs): self.preset_in_out = preset_in_out # Not using _ids convention self.access_list = access_list super().__init__(*args, **kwargs) def trigger(self, param_list, scope): """ param_list should be passed as list of values to lib functions Also note that Jac stores preset_in_out as input/output list of hex ids since preset_in_out doesn't use _ids convention """ result = getattr( importlib.import_module( ACTION_PACKAGE+self.value[0].split('.')[-1]), self.value[1] )(param_list, meta={'m_id': scope.parent._m_id, 'h': scope.parent._h, 'scope': scope}) return result
32.97619
75
0.641877
ace9e1c84d1f536e0097183f633dcd6ef2167d15
2,454
py
Python
deeplearn/_parser.py
Temple-University-CFL/ros2_deeplearn_twist
585f34ea06ac95c647b6f1f505d75c5ab33a4a21
[ "MIT" ]
1
2020-08-18T15:12:50.000Z
2020-08-18T15:12:50.000Z
deeplearn/_parser.py
Temple-University-CFL/ros2_deeplearn_twist
585f34ea06ac95c647b6f1f505d75c5ab33a4a21
[ "MIT" ]
null
null
null
deeplearn/_parser.py
Temple-University-CFL/ros2_deeplearn_twist
585f34ea06ac95c647b6f1f505d75c5ab33a4a21
[ "MIT" ]
1
2020-09-21T04:56:38.000Z
2020-09-21T04:56:38.000Z
#!/usr/bin/env python # -*- coding: utf-8 -*- """Race-car Deep Learning Utility Class. This script contains data parsing tools from given image name. Revision History: 2020-12-25 (Animesh): Baseline Software. Example: from _parser import ParseData """ #___Import Modules: import cv2 #___Global Variables: SHAPE = [100,100] #__Classes: class ParseData: """Data Parser Class This class contains all tools to parse servo, motor and image data from a given list item. """ def __init__(self): """Constructor. """ return None def parse_data(self, fname): """Data Parser. This method parses data from a given file name. Args: fname (string): File name containing image directory along with servo and motor value. Returns: (image file): Image file in opencv format. (int): Servo value. (int): Motor value. """ return self.parse_image(fname), \ self.parse_servo(fname), self.parse_motor(fname) def parse_image(self, fname): """Image Parser. This method parses image from a given file name. Args: fname (string): File name containing image directory. Returns: (image file): Image file in opencv format. """ return cv2.imread(fname) def parse_servo(self, fname): """Servo Data Parser. This method parses servo data from a given file name. Args: fname (string): File name containing image directory along with servo and motor value. Returns: (int): Servo value. """ return int(fname.split('.')[-2].split('_')[-2][1:3]) def parse_motor(self, fname): """Motor Data Parser. This method parses motor data from a given file name. Args: fname (string): File name containing image directory along with servo and motor value. Returns: (int): Motore value. """ return int(fname.split('.')[-2].split('_')[-1][1:3]) # # end of file """ANI717"""
21.526316
79
0.515485
ace9e22eaf7eaec060f4fd5af8e346222601eb01
10,599
py
Python
src/decode.py
Atomato/Reinforce-Paraphrase-Generation
48c296e5e464e440f748bd2dc1f5f50efb2f9505
[ "MIT" ]
3
2020-04-08T01:56:48.000Z
2020-04-10T09:02:41.000Z
src/decode.py
Atomato/Reinforce-Paraphrase-Generation
48c296e5e464e440f748bd2dc1f5f50efb2f9505
[ "MIT" ]
null
null
null
src/decode.py
Atomato/Reinforce-Paraphrase-Generation
48c296e5e464e440f748bd2dc1f5f50efb2f9505
[ "MIT" ]
2
2020-04-09T02:14:05.000Z
2021-09-08T12:45:47.000Z
# Except for the pytorch part content of this file is copied from https://github.com/abisee/pointer-generator/blob/master/ from __future__ import unicode_literals, print_function, division import sys import os import time import torch from torch.autograd import Variable import nltk import numpy as np import data, config from batcher import Batcher from data import Vocab from model import Model from utils import write_for_rouge, rouge_eval, rouge_log, write_for_result from train_util import get_input_from_batch from post_process import PostProcess use_cuda = config.use_gpu and torch.cuda.is_available() class Beam(object): def __init__(self, tokens, log_probs, state, context, coverage): self.tokens = tokens self.log_probs = log_probs self.state = state self.context = context self.coverage = coverage def extend(self, token, log_prob, state, context, coverage): return Beam(tokens = self.tokens + [token], log_probs = self.log_probs + [log_prob], state = state, context = context, coverage = coverage) @property def latest_token(self): return self.tokens[-1] @property def avg_log_prob(self): return sum(self.log_probs) / len(self.tokens) class BeamSearch(object): def __init__(self, model_file_path, data_path, data_class='val'): self.data_class = data_class if self.data_class not in ['val', 'test']: print("data_class must be 'val' or 'test'.") raise ValueError # model_file_path e.g. --> ../log/{MODE NAME}/best_model/model_best_XXXXX model_name = os.path.basename(model_file_path) # log_root e.g. --> ../log/{MODE NAME}/ log_root = os.path.dirname(os.path.dirname(model_file_path)) # _decode_dir e.g. --> ../log/{MODE NAME}/decode_model_best_XXXXX/ self._decode_dir = os.path.join(log_root, 'decode_%s' % (model_name)) self._rouge_ref_dir = os.path.join(self._decode_dir, 'rouge_ref') self._rouge_dec_dir = os.path.join(self._decode_dir, 'rouge_dec_dir') self._result_path = os.path.join(self._decode_dir, 'result_%s_%s.txt' \ % (model_name, self.data_class)) # remove result file if exist if os.path.isfile(self._result_path): os.remove(self._result_path) for p in [self._decode_dir, self._rouge_ref_dir, self._rouge_dec_dir]: if not os.path.exists(p): os.mkdir(p) self.vocab = Vocab(config.vocab_path, config.vocab_size) self.batcher = Batcher(data_path, self.vocab, mode='decode', batch_size=config.beam_size, single_pass=True) time.sleep(5) self.model = Model(model_file_path, is_eval=True) def sort_beams(self, beams): return sorted(beams, key=lambda h: h.avg_log_prob, reverse=True) def beam_search(self, batch): # batch should have only one example enc_batch, enc_padding_mask, enc_lens, enc_batch_extend_vocab, extra_zeros, c_t_0, coverage_t_0 = \ get_input_from_batch(batch, use_cuda) encoder_outputs, encoder_feature, encoder_hidden = self.model.encoder(enc_batch, enc_lens) s_t_0 = self.model.reduce_state(encoder_hidden) dec_h, dec_c = s_t_0 # 1 x 2H dec_h = dec_h.squeeze() dec_c = dec_c.squeeze() # decoder batch preparation, it has beam_size example initially everything is repeated beams = [Beam(tokens=[self.vocab.word2id(data.START_DECODING)], log_probs=[0.0], state=(dec_h[0], dec_c[0]), context = c_t_0[0], coverage=(coverage_t_0[0] if config.is_coverage else None)) for _ in range(config.beam_size)] results = [] steps = 0 while steps < config.max_dec_steps and len(results) < config.beam_size: latest_tokens = [h.latest_token for h in beams] latest_tokens = [t if t < self.vocab.size() else self.vocab.word2id(data.UNKNOWN_TOKEN) \ for t in latest_tokens] y_t_1 = Variable(torch.LongTensor(latest_tokens)) if use_cuda: y_t_1 = y_t_1.cuda() all_state_h =[] all_state_c = [] all_context = [] for h in beams: state_h, state_c = h.state all_state_h.append(state_h) all_state_c.append(state_c) all_context.append(h.context) s_t_1 = (torch.stack(all_state_h, 0).unsqueeze(0), torch.stack(all_state_c, 0).unsqueeze(0)) c_t_1 = torch.stack(all_context, 0) coverage_t_1 = None if config.is_coverage: all_coverage = [] for h in beams: all_coverage.append(h.coverage) coverage_t_1 = torch.stack(all_coverage, 0) final_dist, s_t, c_t, attn_dist, p_gen, coverage_t = self.model.decoder(y_t_1, s_t_1, encoder_outputs, encoder_feature, enc_padding_mask, c_t_1, extra_zeros, enc_batch_extend_vocab, coverage_t_1, steps) log_probs = torch.log(final_dist) topk_log_probs, topk_ids = torch.topk(log_probs, config.beam_size * 2) dec_h, dec_c = s_t dec_h = dec_h.squeeze() dec_c = dec_c.squeeze() all_beams = [] num_orig_beams = 1 if steps == 0 else len(beams) for i in range(num_orig_beams): h = beams[i] state_i = (dec_h[i], dec_c[i]) context_i = c_t[i] coverage_i = (coverage_t[i] if config.is_coverage else None) for j in range(config.beam_size * 2): # for each of the top 2*beam_size hyps: new_beam = h.extend(token=topk_ids[i, j].item(), log_prob=topk_log_probs[i, j].item(), state=state_i, context=context_i, coverage=coverage_i) all_beams.append(new_beam) beams = [] for h in self.sort_beams(all_beams): if h.latest_token == self.vocab.word2id(data.STOP_DECODING): if steps >= config.min_dec_steps: results.append(h) else: beams.append(h) if len(beams) == config.beam_size or len(results) == config.beam_size: break steps += 1 if len(results) == 0: results = beams beams_sorted = self.sort_beams(results) return beams_sorted[0] def decode(self): start = time.time() counter = 0 bleu_scores = [] batch = self.batcher.next_batch() while batch is not None: # Run beam search to get best Hypothesis best_summary = self.beam_search(batch) # Extract the output ids from the hypothesis and convert back to words output_ids = [int(t) for t in best_summary.tokens[1:]] decoded_words = data.outputids2words(output_ids, self.vocab, (batch.art_oovs[0] if config.pointer_gen else None)) # Remove the [STOP] token from decoded_words, if necessary try: fst_stop_idx = decoded_words.index(data.STOP_DECODING) decoded_words = decoded_words[:fst_stop_idx] except ValueError: decoded_words = decoded_words original_articles = batch.original_articles[0] original_abstracts = batch.original_abstracts_sents[0] reference = original_abstracts[0].strip().split() bleu = nltk.translate.bleu_score.sentence_bleu([reference], decoded_words, weights = (0.5, 0.5)) bleu_scores.append(bleu) # write_for_rouge(original_abstracts, decoded_words, counter, # self._rouge_ref_dir, self._rouge_dec_dir) write_for_result(original_articles, original_abstracts, decoded_words, \ self._result_path, self.data_class) counter += 1 if counter % 1000 == 0: print('%d example in %d sec'%(counter, time.time() - start)) start = time.time() batch = self.batcher.next_batch() ''' # uncomment this if you successfully install `pyrouge` print("Decoder has finished reading dataset for single_pass.") print("Now starting ROUGE eval...") results_dict = rouge_eval(self._rouge_ref_dir, self._rouge_dec_dir) rouge_log(results_dict, self._decode_dir) ''' if self.data_class == 'val': print('Average BLEU score:', np.mean(bleu_scores)) with open(self._result_path, "a") as f: print('Average BLEU score:', np.mean(bleu_scores), file=f) def get_processed_path(self): # ../log/{MODE NAME}/decode_model_best_XXXXX/result_model_best_2800_{data_class}.txt input_path = self._result_path temp = os.path.splitext(input_path) # ../log/{MODE NAME}/decode_model_best_XXXXX/result_model_best_2800_{data_class}_processed.txt output_path = temp[0] + "_processed" + temp[1] return input_path, output_path if __name__ == '__main__': model_filename = sys.argv[1] beam_Search_processor_val = BeamSearch(model_filename, config.eval_data_path) print('Decoding validation set...') beam_Search_processor_val.decode() print('Done!\n') beam_Search_processor_test = BeamSearch(model_filename, config.decode_data_path, data_class='test') print('Decoding test set...') beam_Search_processor_test.decode() print('Done!\n') print('Post-processing...') input_val, output_val = beam_Search_processor_val.get_processed_path() proc_val = PostProcess(input_val, output_val) proc_val.write_processed_file() input_test, output_test = beam_Search_processor_test.get_processed_path() proc_test = PostProcess(input_test, output_test) proc_test.write_processed_file() print('Done!\n')
40.147727
122
0.596471
ace9e2eb620c1b241261bf619cfa410a8e7f6be7
39,484
py
Python
src/config/device-manager/device_manager/plugins/juniper/mx/mx_conf.py
Dmitry-Eremeev/contrail-controller
1238bcff697981662225ec5a15bc4d3d2237ae93
[ "Apache-2.0" ]
null
null
null
src/config/device-manager/device_manager/plugins/juniper/mx/mx_conf.py
Dmitry-Eremeev/contrail-controller
1238bcff697981662225ec5a15bc4d3d2237ae93
[ "Apache-2.0" ]
2
2018-12-04T02:20:52.000Z
2018-12-22T06:16:30.000Z
src/config/device-manager/device_manager/plugins/juniper/mx/mx_conf.py
Dmitry-Eremeev/contrail-controller
1238bcff697981662225ec5a15bc4d3d2237ae93
[ "Apache-2.0" ]
1
2018-12-04T02:07:47.000Z
2018-12-04T02:07:47.000Z
# # Copyright (c) 2017 Juniper Networks, Inc. All rights reserved. # """ This file contains implementation of netconf interface for physical router configuration manager """ from db import * from dm_utils import DMUtils from juniper_conf import JuniperConf from juniper_conf import JunosInterface from device_api.juniper_common_xsd import * class MxConf(JuniperConf): _products = ['mx', 'vmx'] def __init__(self, logger, params={}): self._logger = logger self.physical_router = params.get("physical_router") super(MxConf, self).__init__() # end __init__ @classmethod def register(cls): mconf = { "vendor": cls._vendor, "products": cls._products, "class": cls } return super(MxConf, cls).register(mconf) # end register @classmethod def is_product_supported(cls, name, role): if role and role.lower().startswith('e2-'): return False for product in cls._products or []: if name.lower().startswith(product.lower()): return True return False # end is_product_supported def add_pnf_logical_interface(self, junos_interface): if not self.interfaces_config: self.interfaces_config = Interfaces(comment=DMUtils.interfaces_comment()) family = Family(inet=FamilyInet(address=[Address(name=junos_interface.ip)])) unit = Unit(name=junos_interface.unit, vlan_id=junos_interface.vlan_tag, family=family) interface = Interface(name=junos_interface.ifd_name) interface.add_unit(unit) self.interfaces_config.add_interface(interface) # end add_pnf_logical_interface def config_pnf_logical_interface(self): pnf_dict = {} pnf_ris = set() # make it fake for now # sholud save to the database, the allocation self.vlan_alloc = {"max": 1} self.ip_alloc = {"max": -1} self.li_alloc = {} for pi_uuid in self.physical_router.physical_interfaces: pi = PhysicalInterfaceDM.get(pi_uuid) if pi is None: continue for pi_pi_uuid in pi.physical_interfaces: pi_pi = PhysicalInterfaceDM.get(pi_pi_uuid) for pi_vmi_uuid in pi_pi.virtual_machine_interfaces: allocate_li = False pi_vmi = VirtualMachineInterfaceDM.get(pi_vmi_uuid) if (pi_vmi is None or pi_vmi.service_instance is None or pi_vmi.service_interface_type is None): continue if pi_vmi.routing_instances: for ri_id in pi_vmi.routing_instances: ri_obj = RoutingInstanceDM.get(ri_id) if ri_obj and ri_obj.routing_instances and ri_obj.service_chain_address: pnf_ris.add(ri_obj) # If this service is on a service chain, we need allocate # a logic interface for its VMI allocate_li = True if allocate_li: resources = self.physical_router.allocate_pnf_resources(pi_vmi) if (not resources or not resources["ip_address"] or not resources["vlan_id"] or not resources["unit_id"]): self._logger.error( "Cannot allocate PNF resources for " "Virtual Machine Interface" + pi_vmi_uuid) return logical_interface = JunosInterface( pi.name + '.' + resources["unit_id"], "l3", resources["vlan_id"], resources["ip_address"]) self.add_pnf_logical_interface( logical_interface) lis = pnf_dict.setdefault( pi_vmi.service_instance, {"left": [], "right": [], "mgmt": [], "other": []} )[pi_vmi.service_interface_type] lis.append(logical_interface) return (pnf_dict, pnf_ris) # end def add_pnf_vrfs(self, first_vrf, pnf_dict, pnf_ris): is_first_vrf = False is_left_first_vrf = False for ri_obj in pnf_ris: if ri_obj in first_vrf: is_first_vrf = True else: is_first_vrf = False export_set = copy.copy(ri_obj.export_targets) import_set = copy.copy(ri_obj.import_targets) for ri2_id in ri_obj.routing_instances: ri2 = RoutingInstanceDM.get(ri2_id) if ri2 is None: continue import_set |= ri2.export_targets pnf_inters = set() static_routes = self.physical_router.compute_pnf_static_route(ri_obj, pnf_dict) if_type = "" for vmi_uuid in ri_obj.virtual_machine_interfaces: vmi_obj = VirtualMachineInterfaceDM.get(vmi_uuid) if vmi_obj.service_instance is not None: si_obj = ServiceInstanceDM.get(vmi_obj.service_instance) if_type = vmi_obj.service_interface_type pnf_li_inters = pnf_dict[ vmi_obj.service_instance][if_type] if if_type == 'left' and is_first_vrf: is_left_first_vrf = True else: is_left_first_vrf = False for pnf_li in pnf_li_inters: pnf_inters.add(pnf_li) if pnf_inters: vrf_name = self.physical_router.get_pnf_vrf_name( si_obj, if_type, is_left_first_vrf) vrf_interfaces = pnf_inters ri_conf = { 'ri_name': vrf_name } ri_conf['si'] = si_obj ri_conf['import_targets'] = import_set ri_conf['export_targets'] = export_set ri_conf['interfaces'] = vrf_interfaces ri_conf['static_routes'] = static_routes ri_conf['no_vrf_table_label'] = True self.add_routing_instance(ri_conf) # end add_pnf_vrfs def add_static_routes(self, parent, static_routes): static_config = parent.get_static() if not static_config: static_config = Static() parent.set_static(static_config) for dest, next_hops in static_routes.items(): route_config = Route(name=dest) for next_hop in next_hops: next_hop_str = next_hop.get("next-hop") preference = next_hop.get("preference") if not next_hop_str: continue if preference: route_config.set_qualified_next_hop(QualifiedNextHop( name=next_hop_str, preference=str(preference))) else: route_config.set_next_hop(next_hop_str) static_config.add_route(route_config) # end add_static_routes def add_inet_public_vrf_filter(self, forwarding_options_config, firewall_config, inet_type): fo = Family() inet_filter = InetFilter(input=DMUtils.make_public_vrf_filter_name(inet_type)) if inet_type == 'inet6': fo.set_inet6(FamilyInet6(filter=inet_filter)) else: fo.set_inet(FamilyInet(filter=inet_filter)) forwarding_options_config.add_family(fo) f = FirewallFilter(name=DMUtils.make_public_vrf_filter_name(inet_type)) f.set_comment(DMUtils.public_vrf_filter_comment()) ff = firewall_config.get_family() if not ff: ff = FirewallFamily() firewall_config.set_family(ff) if inet_type == 'inet6': inet6 = ff.get_inet6() if not inet6: inet6 = FirewallInet() ff.set_inet6(inet6) inet6.add_filter(f) else: inet = ff.get_inet() if not inet: inet = FirewallInet() ff.set_inet(inet) inet.add_filter(f) term = Term(name="default-term", then=Then(accept='')) f.add_term(term) return f # end add_inet_public_vrf_filter def add_inet_filter_term(self, ri_name, prefixes, inet_type): if inet_type == 'inet6': prefixes = DMUtils.get_ipv6_prefixes(prefixes) else: prefixes = DMUtils.get_ipv4_prefixes(prefixes) from_ = From() for prefix in prefixes: from_.add_destination_address(prefix) then_ = Then() then_.add_routing_instance(ri_name) return Term(name=DMUtils.make_vrf_term_name(ri_name), fromxx=from_, then=then_) # end add_inet_filter_term ''' ri_name: routing instance name to be configured on mx is_l2: a flag used to indicate routing instance type, i.e : l2 or l3 is_l2_l3: VN forwarding mode is of type 'l2_l3' or not import/export targets: routing instance import, export targets prefixes: for l3 vrf static routes and for public vrf filter terms gateways: for l2 evpn, bug#1395944 router_external: this indicates the routing instance configured is for the public network interfaces: logical interfaces to be part of vrf fip_map: contrail instance ip to floating-ip map, used for snat & floating ip support network_id : this is used for configuraing irb interfaces static_routes: this is used for add PNF vrf static routes no_vrf_table_label: if this is set to True will not generate vrf table label knob restrict_proxy_arp: proxy-arp restriction config is generated for irb interfaces only if vn is external and has fip map highest_enapsulation_priority: highest encapsulation configured ''' def add_routing_instance(self, ri_conf): ri_name = ri_conf.get("ri_name") vn = ri_conf.get("vn") si = ri_conf.get("si") is_l2 = ri_conf.get("is_l2", False) is_l2_l3 = ri_conf.get("is_l2_l3", False) import_targets = ri_conf.get("import_targets", set()) export_targets = ri_conf.get("export_targets", set()) prefixes = ri_conf.get("prefixes", []) gateways = ri_conf.get("gateways", []) router_external = ri_conf.get("router_external", False) interfaces = ri_conf.get("interfaces", []) vni = ri_conf.get("vni", None) fip_map = ri_conf.get("fip_map", None) network_id = ri_conf.get("network_id", None) static_routes = ri_conf.get("static_routes", {}) no_vrf_table_label = ri_conf.get("no_vrf_table_label", False) restrict_proxy_arp = ri_conf.get("restrict_proxy_arp", False) highest_enapsulation_priority = \ ri_conf.get("highest_enapsulation_priority") or "MPLSoGRE" self.routing_instances[ri_name] = ri_conf ri_config = self.ri_config or RoutingInstances(comment=DMUtils.routing_instances_comment()) policy_config = self.policy_config or PolicyOptions(comment=DMUtils.policy_options_comment()) ri = Instance(name=ri_name) if vn: is_nat = True if fip_map else False ri.set_comment(DMUtils.vn_ri_comment(vn, is_l2, is_l2_l3, is_nat, router_external)) elif si: ri.set_comment(DMUtils.si_ri_comment(si)) ri_config.add_instance(ri) ri_opt = None if router_external and is_l2 == False: ri_opt = RoutingInstanceRoutingOptions( static=Static(route=[Route(name="0.0.0.0/0", next_table="inet.0", comment=DMUtils.public_vrf_route_comment())])) ri.set_routing_options(ri_opt) # for both l2 and l3 ri.set_vrf_import(DMUtils.make_import_name(ri_name)) ri.set_vrf_export(DMUtils.make_export_name(ri_name)) has_ipv6_prefixes = DMUtils.has_ipv6_prefixes(prefixes) has_ipv4_prefixes = DMUtils.has_ipv4_prefixes(prefixes) if not is_l2: if ri_opt is None: ri_opt = RoutingInstanceRoutingOptions() ri.set_routing_options(ri_opt) if prefixes and fip_map is None: static_config = ri_opt.get_static() if not static_config: static_config = Static() ri_opt.set_static(static_config) rib_config_v6 = None static_config_v6 = None for prefix in prefixes: if ':' in prefix and not rib_config_v6: static_config_v6 = Static() rib_config_v6 = RIB(name=ri_name + ".inet6.0") rib_config_v6.set_static(static_config_v6) ri_opt.set_rib(rib_config_v6) if ':' in prefix: static_config_v6.add_route(Route(name=prefix, discard='')) else: static_config.add_route(Route(name=prefix, discard='')) if router_external: self.add_to_global_ri_opts(prefix) ri.set_instance_type("vrf") if not no_vrf_table_label: ri.set_vrf_table_label('') # only for l3 if fip_map is None: for interface in interfaces: ri.add_interface(Interface(name=interface.name)) if static_routes: self.add_static_routes(ri_opt, static_routes) family = Family() if has_ipv4_prefixes: family.set_inet(FamilyInet(unicast='')) if has_ipv6_prefixes: family.set_inet6(FamilyInet6(unicast='')) if has_ipv4_prefixes or has_ipv6_prefixes: auto_export = AutoExport(family=family) ri_opt.set_auto_export(auto_export) else: if highest_enapsulation_priority == "VXLAN": ri.set_instance_type("virtual-switch") elif highest_enapsulation_priority in ["MPLSoGRE", "MPLSoUDP"]: ri.set_instance_type("evpn") if fip_map is not None: if ri_opt is None: ri_opt = RoutingInstanceRoutingOptions() ri.set_routing_options(ri_opt) static_config = ri_opt.get_static() if not static_config: static_config = Static() ri_opt.set_static(static_config) static_config.add_route(Route(name="0.0.0.0/0", next_hop=interfaces[0].name, comment=DMUtils.fip_ingress_comment())) ri.add_interface(Interface(name=interfaces[0].name)) public_vrf_ips = {} for pip in fip_map.values(): if pip["vrf_name"] not in public_vrf_ips: public_vrf_ips[pip["vrf_name"]] = set() public_vrf_ips[pip["vrf_name"]].add(pip["floating_ip"]) for public_vrf, fips in public_vrf_ips.items(): ri_public = Instance(name=public_vrf) ri_config.add_instance(ri_public) ri_public.add_interface(Interface(name=interfaces[1].name)) ri_opt = RoutingInstanceRoutingOptions() ri_public.set_routing_options(ri_opt) static_config = Static() ri_opt.set_static(static_config) for fip in fips: static_config.add_route(Route(name=fip + "/32", next_hop=interfaces[1].name, comment=DMUtils.fip_egress_comment())) # add policies for export route targets ps = PolicyStatement(name=DMUtils.make_export_name(ri_name)) if vn: ps.set_comment(DMUtils.vn_ps_comment(vn, "Export")) elif si: ps.set_comment(DMUtils.si_ps_comment(si, "Export")) then = Then() ps.add_term(Term(name="t1", then=then)) for route_target in export_targets: comm = Community(add='', community_name=DMUtils.make_community_name(route_target)) then.add_community(comm) if fip_map is not None: # for nat instance then.set_reject('') else: then.set_accept('') policy_config.add_policy_statement(ps) # add policies for import route targets ps = PolicyStatement(name=DMUtils.make_import_name(ri_name)) if vn: ps.set_comment(DMUtils.vn_ps_comment(vn, "Import")) elif si: ps.set_comment(DMUtils.si_ps_comment(si, "Import")) from_ = From() term = Term(name="t1", fromxx=from_) ps.add_term(term) for route_target in import_targets: from_.add_community(DMUtils.make_community_name(route_target)) term.set_then(Then(accept='')) ps.set_then(Then(reject='')) policy_config.add_policy_statement(ps) # add firewall config for public VRF forwarding_options_config = self.forwarding_options_config firewall_config = self.firewall_config if router_external and is_l2 == False: forwarding_options_config = (self.forwarding_options_config or ForwardingOptions(DMUtils.forwarding_options_comment())) firewall_config = self.firewall_config or Firewall(DMUtils.firewall_comment()) if has_ipv4_prefixes and not self.inet4_forwarding_filter: #create single instance inet4 filter self.inet4_forwarding_filter = self.add_inet_public_vrf_filter( forwarding_options_config, firewall_config, "inet") if has_ipv6_prefixes and not self.inet6_forwarding_filter: #create single instance inet6 filter self.inet6_forwarding_filter = self.add_inet_public_vrf_filter( forwarding_options_config, firewall_config, "inet6") if has_ipv4_prefixes: #add terms to inet4 filter term = self.add_inet_filter_term(ri_name, prefixes, "inet4") # insert before the last term terms = self.inet4_forwarding_filter.get_term() terms = [term] + (terms or []) self.inet4_forwarding_filter.set_term(terms) if has_ipv6_prefixes: #add terms to inet6 filter term = self.add_inet_filter_term(ri_name, prefixes, "inet6") # insert before the last term terms = self.inet6_forwarding_filter.get_term() terms = [term] + (terms or []) self.inet6_forwarding_filter.set_term(terms) if fip_map is not None: firewall_config = firewall_config or Firewall(DMUtils.firewall_comment()) f = FirewallFilter(name=DMUtils.make_private_vrf_filter_name(ri_name)) f.set_comment(DMUtils.vn_firewall_comment(vn, "private")) ff = firewall_config.get_family() if not ff: ff = FirewallFamily() firewall_config.set_family(ff) inet = ff.get_inet() if not inet: inet = FirewallInet() ff.set_inet(inet) inet.add_filter(f) term = Term(name=DMUtils.make_vrf_term_name(ri_name)) from_ = From() for fip_user_ip in fip_map.keys(): from_.add_source_address(fip_user_ip) term.set_from(from_) term.set_then(Then(routing_instance=[ri_name])) f.add_term(term) term = Term(name="default-term", then=Then(accept='')) f.add_term(term) interfaces_config = self.interfaces_config or Interfaces(comment=DMUtils.interfaces_comment()) irb_intf = Interface(name="irb") interfaces_config.add_interface(irb_intf) intf_unit = Unit(name=str(network_id), comment=DMUtils.vn_irb_fip_inet_comment(vn)) if restrict_proxy_arp: intf_unit.set_proxy_arp(ProxyArp(restricted='')) inet = FamilyInet() inet.set_filter(InetFilter(input=DMUtils.make_private_vrf_filter_name(ri_name))) intf_unit.set_family(Family(inet=inet)) irb_intf.add_unit(intf_unit) # add L2 EVPN and BD config bd_config = None interfaces_config = self.interfaces_config proto_config = self.proto_config if (is_l2 and vni is not None and self.is_family_configured(self.bgp_params, "e-vpn")): ri.set_vtep_source_interface("lo0.0") if highest_enapsulation_priority == "VXLAN": bd_config = BridgeDomains() ri.set_bridge_domains(bd_config) bd = Domain(name=DMUtils.make_bridge_name(vni), vlan_id='none', vxlan=VXLan(vni=vni)) bd.set_comment(DMUtils.vn_bd_comment(vn, "VXLAN")) bd_config.add_domain(bd) for interface in interfaces: bd.add_interface(Interface(name=interface.name)) if is_l2_l3: # network_id is unique, hence irb bd.set_routing_interface("irb." + str(network_id)) ri.set_protocols(RoutingInstanceProtocols( evpn=Evpn(encapsulation='vxlan', extended_vni_list='all'))) elif highest_enapsulation_priority in ["MPLSoGRE", "MPLSoUDP"]: ri.set_vlan_id('none') if is_l2_l3: # network_id is unique, hence irb ri.set_routing_interface("irb." + str(network_id)) evpn = Evpn() evpn.set_comment(DMUtils.vn_evpn_comment(vn, highest_enapsulation_priority)) for interface in interfaces: evpn.add_interface(Interface(name=interface.name)) ri.set_protocols(RoutingInstanceProtocols(evpn=evpn)) interfaces_config = self.interfaces_config or Interfaces(comment=DMUtils.interfaces_comment()) if is_l2_l3: irb_intf = Interface(name='irb', gratuitous_arp_reply='') interfaces_config.add_interface(irb_intf) if gateways is not None: intf_unit = Unit(name=str(network_id), comment=DMUtils.vn_irb_comment(vn, False, is_l2_l3)) irb_intf.add_unit(intf_unit) family = Family() intf_unit.set_family(family) inet = None inet6 = None for (irb_ip, gateway) in gateways: if ':' in irb_ip: if not inet6: inet6 = FamilyInet6() family.set_inet6(inet6) addr = Address() inet6.add_address(addr) else: if not inet: inet = FamilyInet() family.set_inet(inet) addr = Address() inet.add_address(addr) addr.set_name(irb_ip) addr.set_comment(DMUtils.irb_ip_comment(irb_ip)) if len(gateway) and gateway != '0.0.0.0': addr.set_virtual_gateway_address(gateway) self.build_l2_evpn_interface_config(interfaces_config, interfaces, vn) if (not is_l2 and not is_l2_l3 and gateways): interfaces_config = self.interfaces_config or Interfaces(comment=DMUtils.interfaces_comment()) ifl_num = str(1000 + int(network_id)) lo_intf = Interface(name="lo0") interfaces_config.add_interface(lo_intf) intf_unit = Unit(name=ifl_num, comment=DMUtils.l3_lo_intf_comment(vn)) lo_intf.add_unit(intf_unit) family = Family() intf_unit.set_family(family) inet = None inet6 = None for (lo_ip, _) in gateways: subnet = lo_ip (ip, _) = lo_ip.split('/') if ':' in lo_ip: if not inet6: inet6 = FamilyInet6() family.set_inet6(inet6) addr = Address() inet6.add_address(addr) lo_ip = ip + '/' + '128' else: if not inet: inet = FamilyInet() family.set_inet(inet) addr = Address() inet.add_address(addr) lo_ip = ip + '/' + '32' addr.set_name(lo_ip) addr.set_comment(DMUtils.lo0_ip_comment(subnet)) ri.add_interface(Interface(name="lo0." + ifl_num, comment=DMUtils.lo0_ri_intf_comment(vn))) # fip services config services_config = self.services_config if fip_map is not None: services_config = self.services_config or Services() services_config.set_comment(DMUtils.services_comment()) service_name = DMUtils.make_services_set_name(ri_name) service_set = ServiceSet(name=service_name) service_set.set_comment(DMUtils.service_set_comment(vn)) services_config.add_service_set(service_set) nat_rule = NATRules(name=service_name + "-sn-rule") service_set.add_nat_rules(NATRules(name=DMUtils.make_snat_rule_name(ri_name), comment=DMUtils.service_set_nat_rule_comment(vn, "SNAT"))) service_set.add_nat_rules(NATRules(name=DMUtils.make_dnat_rule_name(ri_name), comment=DMUtils.service_set_nat_rule_comment(vn, "DNAT"))) next_hop_service = NextHopService(inside_service_interface = interfaces[0].name, outside_service_interface = interfaces[1].name) service_set.set_next_hop_service(next_hop_service) nat = NAT(allow_overlapping_nat_pools='') nat.set_comment(DMUtils.nat_comment()) services_config.add_nat(nat) snat_rule = Rule(name=DMUtils.make_snat_rule_name(ri_name), match_direction="input") snat_rule.set_comment(DMUtils.snat_rule_comment()) nat.add_rule(snat_rule) dnat_rule = Rule(name=DMUtils.make_dnat_rule_name(ri_name), match_direction="output") dnat_rule.set_comment(DMUtils.dnat_rule_comment()) nat.add_rule(dnat_rule) for pip, fip_vn in fip_map.items(): fip = fip_vn["floating_ip"] term = Term(name=DMUtils.make_ip_term_name(pip)) snat_rule.set_term(term) # private ip from_ = From(source_address=[pip + "/32"]) term.set_from(from_) # public ip then_ = Then() term.set_then(then_) translated = Translated(source_prefix=fip + "/32", translation_type=TranslationType(basic_nat44='')) then_.set_translated(translated) term = Term(name=DMUtils.make_ip_term_name(fip)) dnat_rule.set_term(term) # public ip from_ = From(destination_address=[fip + "/32"]) term.set_from(from_) # private ip then_ = Then() term.set_then(then_) translated = Translated(destination_prefix=pip + "/32", translation_type=TranslationType(dnat_44='')) then_.set_translated(translated) interfaces_config = self.interfaces_config or Interfaces(comment=DMUtils.interfaces_comment()) si_intf = Interface(name=interfaces[0].ifd_name, comment=DMUtils.service_ifd_comment()) interfaces_config.add_interface(si_intf) intf_unit = Unit(name=interfaces[0].unit, comment=DMUtils.service_intf_comment("Ingress")) si_intf.add_unit(intf_unit) family = Family(inet=FamilyInet()) intf_unit.set_family(family) intf_unit.set_service_domain("inside") intf_unit = Unit(name=interfaces[1].unit, comment=DMUtils.service_intf_comment("Egress")) si_intf.add_unit(intf_unit) family = Family(inet=FamilyInet()) intf_unit.set_family(family) intf_unit.set_service_domain("outside") self.forwarding_options_config = forwarding_options_config self.firewall_config = firewall_config self.policy_config = policy_config self.proto_config = proto_config self.interfaces_config = interfaces_config self.services_config = services_config self.route_targets |= import_targets | export_targets self.ri_config = ri_config # end add_routing_instance def build_l2_evpn_interface_config(self, interfaces_config, interfaces, vn=None): ifd_map = {} for interface in interfaces: ifd_map.setdefault(interface.ifd_name, []).append(interface) for ifd_name, interface_list in ifd_map.items(): intf = Interface(name=ifd_name) interfaces_config.add_interface(intf) if interface_list[0].is_untagged(): if (len(interface_list) > 1): self._logger.error( "invalid logical interfaces config for ifd %s" % ( ifd_name)) continue intf.set_encapsulation("ethernet-bridge") intf.add_unit(Unit(name=interface_list[0].unit, comment=DMUtils.l2_evpn_intf_unit_comment(vn, False), family=Family(bridge=''))) else: intf.set_flexible_vlan_tagging('') intf.set_encapsulation("flexible-ethernet-services") for interface in interface_list: intf.add_unit(Unit(name=interface.unit, comment=DMUtils.l2_evpn_intf_unit_comment(vn, True, interface.vlan_tag), encapsulation='vlan-bridge', vlan_id=str(interface.vlan_tag))) # end build_l2_evpn_interface_config def add_to_global_ri_opts(self, prefix): if not prefix: return if self.global_routing_options_config is None: self.global_routing_options_config = RoutingOptions(comment=DMUtils.routing_options_comment()) static_config = Static() if ':' in prefix: rib_config_v6 = RIB(name='inet6.0') rib_config_v6.set_static(static_config) self.global_routing_options_config.add_rib(rib_config_v6) else: self.global_routing_options_config.add_static(static_config) static_config.add_route(Route(name=prefix, discard='')) # end add_to_global_ri_opts def set_route_targets_config(self): if self.policy_config is None: self.policy_config = PolicyOptions(comment=DMUtils.policy_options_comment()) for route_target in self.route_targets: comm = CommunityType(name=DMUtils.make_community_name(route_target)) comm.add_members(route_target) self.policy_config.add_community(comm) # end set_route_targets_config def push_conf(self, is_delete=False): if not self.physical_router: return 0 if is_delete: return self.send_conf(is_delete=True) if not self.ensure_bgp_config(): return 0 self.build_bgp_config() vn_dict = self.get_vn_li_map() self.physical_router.evaluate_vn_irb_ip_map(set(vn_dict.keys()), 'l2_l3', 'irb', False) self.physical_router.evaluate_vn_irb_ip_map(set(vn_dict.keys()), 'l3', 'lo0', True) vn_irb_ip_map = self.physical_router.get_vn_irb_ip_map() first_vrf = [] pnfs = self.config_pnf_logical_interface() pnf_dict = pnfs[0] pnf_ris = pnfs[1] for vn_id, interfaces in vn_dict.items(): vn_obj = VirtualNetworkDM.get(vn_id) if (vn_obj is None or vn_obj.get_vxlan_vni() is None or vn_obj.vn_network_id is None): continue export_set = None import_set = None for ri_id in vn_obj.routing_instances: # Find the primary RI by matching the name ri_obj = RoutingInstanceDM.get(ri_id) if ri_obj is None: continue if ri_obj.fq_name[-1] == vn_obj.fq_name[-1]: vrf_name_l2 = DMUtils.make_vrf_name(vn_obj.fq_name[-1], vn_obj.vn_network_id, 'l2') vrf_name_l3 = DMUtils.make_vrf_name(vn_obj.fq_name[-1], vn_obj.vn_network_id, 'l3') export_set = copy.copy(ri_obj.export_targets) import_set = copy.copy(ri_obj.import_targets) for ri2_id in ri_obj.routing_instances: ri2 = RoutingInstanceDM.get(ri2_id) if ri2 in pnf_ris: first_vrf.append(ri2) if ri2 is None: continue import_set |= ri2.export_targets if vn_obj.get_forwarding_mode() in ['l2', 'l2_l3']: irb_ips = None if vn_obj.get_forwarding_mode() == 'l2_l3': irb_ips = vn_irb_ip_map['irb'].get(vn_id, []) ri_conf = { 'ri_name': vrf_name_l2, 'vn': vn_obj } ri_conf['is_l2'] = True ri_conf['is_l2_l3'] = (vn_obj.get_forwarding_mode() == 'l2_l3') ri_conf['import_targets'] = import_set ri_conf['export_targets'] = export_set ri_conf['prefixes'] = vn_obj.get_prefixes() ri_conf['gateways'] = irb_ips ri_conf['router_external'] = vn_obj.router_external ri_conf['interfaces'] = interfaces ri_conf['vni'] = vn_obj.get_vxlan_vni() ri_conf['network_id'] = vn_obj.vn_network_id ri_conf['highest_enapsulation_priority'] = \ GlobalVRouterConfigDM.global_encapsulation_priority self.add_routing_instance(ri_conf) if vn_obj.get_forwarding_mode() in ['l3', 'l2_l3']: interfaces = [] lo0_ips = None if vn_obj.get_forwarding_mode() == 'l2_l3': interfaces = [ JunosInterface( 'irb.' + str(vn_obj.vn_network_id), 'l3', 0)] else: lo0_ips = vn_irb_ip_map['lo0'].get(vn_id, []) ri_conf = { 'ri_name': vrf_name_l3, 'vn': vn_obj } ri_conf['is_l2_l3'] = (vn_obj.get_forwarding_mode() == 'l2_l3') ri_conf['import_targets'] = import_set ri_conf['export_targets'] = export_set ri_conf['prefixes'] = vn_obj.get_prefixes() ri_conf['router_external'] = vn_obj.router_external ri_conf['interfaces'] = interfaces ri_conf['gateways'] = lo0_ips ri_conf['network_id'] = vn_obj.vn_network_id self.add_routing_instance(ri_conf) break if (export_set is not None and self.physical_router.is_junos_service_ports_enabled() and len(vn_obj.instance_ip_map) > 0): service_port_ids = DMUtils.get_service_ports(vn_obj.vn_network_id) if self.physical_router.is_service_port_id_valid(service_port_ids[0]) == False: self._logger.error("DM can't allocate service interfaces for " "(vn, vn-id)=(%s,%s)" % ( vn_obj.fq_name, vn_obj.vn_network_id)) else: vrf_name = DMUtils.make_vrf_name(vn_obj.fq_name[-1], vn_obj.vn_network_id, 'l3', True) interfaces = [] service_ports = self.physical_router.junos_service_ports.get( 'service_port') interfaces.append( JunosInterface( service_ports[0] + "." + str(service_port_ids[0]), 'l3', 0)) interfaces.append( JunosInterface( service_ports[0] + "." + str(service_port_ids[1]), 'l3', 0)) ri_conf = { 'ri_name': vrf_name, 'vn': vn_obj } ri_conf['import_targets'] = import_set ri_conf['interfaces'] = interfaces ri_conf['fip_map'] = vn_obj.instance_ip_map ri_conf['network_id'] = vn_obj.vn_network_id ri_conf['restrict_proxy_arp'] = vn_obj.router_external self.add_routing_instance(ri_conf) # Add PNF ri configuration self.add_pnf_vrfs(first_vrf, pnf_dict, pnf_ris) self.set_as_config() self.set_route_targets_config() self.set_bgp_group_config() return self.send_conf() # end push_conf # end PhycalRouterConfig
47.060787
106
0.554427
ace9e33ae4a93943248b3de5d213239f731e16f4
1,188
py
Python
Controller_trace.py
IonutGorgos/fpga_comm
c743364bf5441544d271c4d4c03aca78ea832623
[ "BSD-3-Clause" ]
null
null
null
Controller_trace.py
IonutGorgos/fpga_comm
c743364bf5441544d271c4d4c03aca78ea832623
[ "BSD-3-Clause" ]
null
null
null
Controller_trace.py
IonutGorgos/fpga_comm
c743364bf5441544d271c4d4c03aca78ea832623
[ "BSD-3-Clause" ]
null
null
null
import sasebo_ftdi import binascii from Crypto import Random from Crypto.Cipher import AES hw = sasebo_ftdi.SASEBO() hw.open() rand = Random.new() #key = bytearray(rand.getrandbits(8) for _ in xrange(16)) key = rand.read(16) print "Key : ", binascii.hexlify(key).upper() hw.setKey(key,16) sw = AES.new(key, AES.MODE_ECB) #text_in = bytearray(rand.getrandbits(8) for _ in xrange(16)) text_in = rand.read(16) print "Plain text : ", binascii.hexlify(text_in).upper() text_ans = sw.encrypt(text_in) print "Cipher text(Software) : ", binascii.hexlify(text_ans).upper() text_out = bytearray(16) hw.writeText(text_in, 16) hw.execute() bytes = hw.readText(text_out, 16) print "Cipher text(Hardware) : ", binascii.hexlify(bytes).upper() ''' while 1: text_in = rand.read(16) print "Plain text : ", binascii.hexlify(text_in).upper() text_ans = sw.encrypt(text_in) print "Cipher text(Software) : ", binascii.hexlify(text_ans).upper() text_out = bytearray(16) hw.writeText(text_in, 16) hw.execute() bytes = hw.readText(text_out, 16) print "Cipher text(Hardware) : ", binascii.hexlify(bytes).upper() ''' hw.close()
25.826087
72
0.676768
ace9e374c806371901a453cc96c00ec2fd58d5cc
1,061
py
Python
api/models.py
andres0820m/test_amazon
e290f79f514e10ec08050526fa33dcd49e39ff6e
[ "MIT" ]
null
null
null
api/models.py
andres0820m/test_amazon
e290f79f514e10ec08050526fa33dcd49e39ff6e
[ "MIT" ]
null
null
null
api/models.py
andres0820m/test_amazon
e290f79f514e10ec08050526fa33dcd49e39ff6e
[ "MIT" ]
null
null
null
from django.contrib.auth.models import User from django.core.validators import RegexValidator from django.db import models class Profile(models.Model): email = models.CharField(max_length=600, blank=False, null=False) password = models.CharField(max_length=600, blank=False, null=False) zip_code = models.CharField(max_length=500, null=False) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: " "'+999999999'. Up to 15 digits allowed.") phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=True) def __str__(self): return self.email class Code(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE, null=False) code = models.CharField(max_length=500, null=False) date_used = models.DateField(auto_now=True) status = models.CharField(max_length=100) balance_before = models.FloatField() balance_after = models.FloatField()
40.807692
88
0.689915
ace9e375a0a140c028c34161c25578bee853efc4
4,937
py
Python
avaloq/avaloq_app/models.py
Tankiolegend/AvaloqCodingWebsite
4713cb298d0ff151930442c9a7fde65bcff14bc3
[ "MIT" ]
null
null
null
avaloq/avaloq_app/models.py
Tankiolegend/AvaloqCodingWebsite
4713cb298d0ff151930442c9a7fde65bcff14bc3
[ "MIT" ]
null
null
null
avaloq/avaloq_app/models.py
Tankiolegend/AvaloqCodingWebsite
4713cb298d0ff151930442c9a7fde65bcff14bc3
[ "MIT" ]
null
null
null
from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver import uuid import datetime # Number of days that the URL will be active for candidates to use EXPIRY_TIME = 7 class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) is_reviewer = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) class CodeTemplate(models.Model): name = models.TextField(null=False) language = models.TextField(null=False) template = models.TextField(null=False) def __str__(self): return self.name def add_template(self, data): self.language = data['language'] self.template = data['template'] self.name = data['name'] self.save() @receiver(post_save, sender=User) def update_profile_signal(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() class Question(models.Model): title = models.TextField() text = models.TextField() q_id = models.IntegerField(default=0, primary_key=True) time = models.IntegerField(null=True) templates = models.ManyToManyField(CodeTemplate) def __str__(self): return self.title class Candidate(models.Model): forename = models.TextField() surname = models.TextField() unique_id = models.TextField() questions = models.ManyToManyField(Question) q1_sub = models.BooleanField(default=False) q2_sub = models.BooleanField(default=False) init_time = models.DateTimeField(default=None, null=True) q1_start = models.DateTimeField(default=None, null=True, blank=True) q2_start = models.DateTimeField(default=None, null=True, blank=True) q1_exp = models.DateTimeField(default=None, null=True, blank=True) q2_exp = models.DateTimeField(default=None, null=True, blank=True) q1_end = models.DateTimeField(default=None, null=True, blank=True) q2_end = models.DateTimeField(default=None, null=True, blank=True) def save(self, *args, **kwargs): if self.unique_id == "": self.unique_id = str(uuid.uuid4()) self.init_time = datetime.datetime.now() super(Candidate, self).save(*args, **kwargs) def __str__(self): return self.forename def add_code(self, data): ce = Code_Entry() if data['is_submitted'] and (data['q_num'] == 0): self.q1_sub = True ce.final = True self.q1_end = datetime.datetime.now() elif data['is_submitted'] and (data['q_num'] == 1): self.q2_sub = True ce.final = True self.q2_end = datetime.datetime.now() ce.unique_id = data['uid'] ce.code = data['code'] ce.language = data['language'] if 'verdicts' in data: ce.verdicts = data['verdicts'] ce.candidate = self ce.question = self.questions.all()[data['q_num']] ce.save() self.save() def set_start(self, q_num): if q_num == 0: self.q1_start = datetime.datetime.now() else: self.q2_start = datetime.datetime.now() self.save() def get_start(self, q_num): if q_num == 0: return self.q1_start else: return self.q2_start def get_exp(self, q_num): if q_num == 0: if not self.q1_exp: self.q1_exp = self.q1_start + \ datetime.timedelta( minutes=self.questions.values('time')[0]['time']) return self.q1_exp else: if not self.q2_exp: self.q2_exp = self.q2_start + \ datetime.timedelta( minutes=self.questions.values('time')[1]['time']) return self.q2_exp def get_sub(self, q_num): if q_num == 0: return self.q1_sub else: return self.q2_sub def is_submitted(self): return self.q1_sub and self.q2_sub def is_expired(self): days_old = (datetime.datetime.now() - self.init_time).days if days_old > EXPIRY_TIME: return True else: return False def has_started(self): if self.q1_start is None and self.q2_start is None: return False else: return True class Code_Entry(models.Model): candidate = models.ForeignKey(Candidate, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) final = models.BooleanField(default=False) code = models.TextField(null=True) language = models.TextField(null=True) verdicts = models.TextField(null=True) def __str__(self): return self.code
27.126374
83
0.618392
ace9e3f8cfe8e143e086d10696731e80a14d9c99
4,087
py
Python
experiments/ashvin/icml2020/hand/sparse/relocate_mixture4.py
Asap7772/railrl_evalsawyer
baba8ce634d32a48c7dfe4dc03b123e18e96e0a3
[ "MIT" ]
null
null
null
experiments/ashvin/icml2020/hand/sparse/relocate_mixture4.py
Asap7772/railrl_evalsawyer
baba8ce634d32a48c7dfe4dc03b123e18e96e0a3
[ "MIT" ]
null
null
null
experiments/ashvin/icml2020/hand/sparse/relocate_mixture4.py
Asap7772/railrl_evalsawyer
baba8ce634d32a48c7dfe4dc03b123e18e96e0a3
[ "MIT" ]
null
null
null
""" AWR + SAC from demo experiment """ from rlkit.demos.source.dict_to_mdp_path_loader import DictToMDPPathLoader from rlkit.launchers.experiments.awac.awac_rl import experiment import rlkit.misc.hyperparameter as hyp from rlkit.launchers.arglauncher import run_variants from rlkit.torch.sac.policies import GaussianMixturePolicy if __name__ == "__main__": variant = dict( num_epochs=1001, num_eval_steps_per_epoch=1000, num_trains_per_train_loop=1000, num_expl_steps_per_train_loop=1000, min_num_steps_before_training=1000, max_path_length=1000, batch_size=1024, replay_buffer_size=int(1E6), layer_size=256, policy_class=GaussianMixturePolicy, policy_kwargs=dict( hidden_sizes=[256, 256, 256, 256], max_log_std=0, min_log_std=-6, std_architecture="values", num_gaussians=1, ), algorithm="SAC", version="normal", collection_mode='batch', trainer_kwargs=dict( discount=0.99, soft_target_tau=5e-3, target_update_period=1, policy_lr=3E-4, qf_lr=3E-4, reward_scale=1, beta=1, use_automatic_entropy_tuning=False, alpha=0, compute_bc=False, bc_num_pretrain_steps=0, q_num_pretrain1_steps=0, q_num_pretrain2_steps=25000, policy_weight_decay=1e-4, q_weight_decay=0, bc_loss_type="mse", rl_weight=1.0, use_awr_update=True, use_reparam_update=False, reparam_weight=0.0, awr_weight=0.0, bc_weight=1.0, post_bc_pretrain_hyperparams=dict( bc_weight=0.0, compute_bc=False, ), reward_transform_kwargs=None, # r' = r + 1 terminal_transform_kwargs=None, # t = 0 ), num_exps_per_instance=1, region='us-west-2', path_loader_class=DictToMDPPathLoader, path_loader_kwargs=dict( obs_key="state_observation", demo_paths=[ # dict( # path="demos/icml2020/hand/pen2_sparse.npy", # obs_dict=True, # is_demo=True, # ), # dict( # path="demos/icml2020/hand/pen_bc5.npy", # obs_dict=False, # is_demo=False, # train_split=0.9, # ), ], ), add_env_demos=True, add_env_offpolicy_data=True, # logger_variant=dict( # tensorboard=True, # ), load_demos=True, pretrain_policy=True, pretrain_rl=True, # save_pretrained_algorithm=True, # snapshot_mode="all", ) search_space = { 'env': ["relocate-sparse-v0", ], 'trainer_kwargs.bc_loss_type': ["mle"], 'trainer_kwargs.awr_loss_type': ["mle"], 'seedid': range(3), 'trainer_kwargs.beta': [0.3, ], 'trainer_kwargs.reparam_weight': [0.0, ], 'trainer_kwargs.awr_weight': [1.0], 'trainer_kwargs.bc_weight': [1.0, ], 'policy_kwargs.std_architecture': ["values", "shared"], 'trainer_kwargs.compute_bc': [True, ], 'trainer_kwargs.awr_use_mle_for_vf': [True, ], 'trainer_kwargs.awr_sample_actions': [False, ], 'trainer_kwargs.awr_min_q': [True, ], 'trainer_kwargs.q_weight_decay': [0], 'trainer_kwargs.reward_transform_kwargs': [None, ], 'trainer_kwargs.terminal_transform_kwargs': [dict(m=0, b=0), ], 'policy_kwargs.num_gaussians': [1, 2, 3, 5, ], } sweeper = hyp.DeterministicHyperparameterSweeper( search_space, default_parameters=variant, ) variants = [] for variant in sweeper.iterate_hyperparameters(): variants.append(variant) run_variants(experiment, variants, run_id=0)
30.051471
74
0.569366
ace9e4753473461b09e95bd0fc638696bc956036
277
py
Python
test/advanced_section/advcbv/advcbv/urls.py
imsks/Web-Dev-with-python-and-Django
dec87795d18c24a5492758202c29a463bbba105a
[ "MIT" ]
null
null
null
test/advanced_section/advcbv/advcbv/urls.py
imsks/Web-Dev-with-python-and-Django
dec87795d18c24a5492758202c29a463bbba105a
[ "MIT" ]
null
null
null
test/advanced_section/advcbv/advcbv/urls.py
imsks/Web-Dev-with-python-and-Django
dec87795d18c24a5492758202c29a463bbba105a
[ "MIT" ]
null
null
null
from django.contrib import admin from django.conf.urls import url, include from basic_app import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.IndexView.as_view()), url(r'^basic_app/', include('basic_app.urls', namespace='basic_app')), ]
30.777778
74
0.703971
ace9e65b7c1ce44fd3aaefb2db3dec0d49ed2f22
3,603
py
Python
picScraper/picScraper/middlewares.py
awyee/AirplaneClassifier
0c85dd16605ccf434498bce41fd9bc57510fdb74
[ "MIT" ]
null
null
null
picScraper/picScraper/middlewares.py
awyee/AirplaneClassifier
0c85dd16605ccf434498bce41fd9bc57510fdb74
[ "MIT" ]
null
null
null
picScraper/picScraper/middlewares.py
awyee/AirplaneClassifier
0c85dd16605ccf434498bce41fd9bc57510fdb74
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Define here the models for your spider middleware # # See documentation in: # https://doc.scrapy.org/en/latest/topics/spider-middleware.html from scrapy import signals class PicscraperSpiderMiddleware(object): # Not all methods need to be defined. If a method is not defined, # scrapy acts as if the spider middleware does not modify the # passed objects. @classmethod def from_crawler(cls, crawler): # This method is used by Scrapy to create your spiders. s = cls() crawler.signals.connect(s.spider_opened, signal=signals.spider_opened) return s def process_spider_input(self, response, spider): # Called for each response that goes through the spider # middleware and into the spider. # Should return None or raise an exception. return None def process_spider_output(self, response, result, spider): # Called with the results returned from the Spider, after # it has processed the response. # Must return an iterable of Request, dict or Item objects. for i in result: yield i def process_spider_exception(self, response, exception, spider): # Called when a spider or process_spider_input() method # (from other spider middleware) raises an exception. # Should return either None or an iterable of Response, dict # or Item objects. pass def process_start_requests(self, start_requests, spider): # Called with the start requests of the spider, and works # similarly to the process_spider_output() method, except # that it doesn’t have a response associated. # Must return only requests (not items). for r in start_requests: yield r def spider_opened(self, spider): spider.logger.info('Spider opened: %s' % spider.name) class PicscraperDownloaderMiddleware(object): # Not all methods need to be defined. If a method is not defined, # scrapy acts as if the downloader middleware does not modify the # passed objects. @classmethod def from_crawler(cls, crawler): # This method is used by Scrapy to create your spiders. s = cls() crawler.signals.connect(s.spider_opened, signal=signals.spider_opened) return s def process_request(self, request, spider): # Called for each request that goes through the downloader # middleware. # Must either: # - return None: continue processing this request # - or return a Response object # - or return a Request object # - or raise IgnoreRequest: process_exception() methods of # installed downloader middleware will be called return None def process_response(self, request, response, spider): # Called with the response returned from the downloader. # Must either; # - return a Response object # - return a Request object # - or raise IgnoreRequest return response def process_exception(self, request, exception, spider): # Called when a download handler or a process_request() # (from other downloader middleware) raises an exception. # Must either: # - return None: continue processing this exception # - return a Response object: stops process_exception() chain # - return a Request object: stops process_exception() chain pass def spider_opened(self, spider): spider.logger.info('Spider opened: %s' % spider.name)
34.644231
78
0.666667
ace9e6630f7665a7d06f04db2fe6c219759cba4a
4,150
py
Python
send_emails.py
GzuPark/python_send_emails
d2d9894b8fe958ee6db177d7fcbd4b0d7cfbdf1a
[ "MIT" ]
null
null
null
send_emails.py
GzuPark/python_send_emails
d2d9894b8fe958ee6db177d7fcbd4b0d7cfbdf1a
[ "MIT" ]
null
null
null
send_emails.py
GzuPark/python_send_emails
d2d9894b8fe958ee6db177d7fcbd4b0d7cfbdf1a
[ "MIT" ]
null
null
null
import os import time import random import smtplib from email.message import EmailMessage from email.headerregistry import Address from email.utils import make_msgid from ops import stopwatch, attach_dir, cleanhtml, get_list, validity, img_extension, security_check class Emails: def __init__(self, subject, id, pw, name, content): self.subject = subject self.id = id self.pw = pw self.name = name self.content = content self.from_email = self.id if '@' in self.id else self.id+'@gmail.com' self.to_email = attach_dir(content+'.csv') self.contents_file = attach_dir(content+'.html') self.images = attach_dir(img_extension(content)) self.timesleep = 3 self.get_data() def get_data(self): with open(self.to_email, 'r', encoding='UTF-8') as f: self.to_email_list = f.read().splitlines() with open(self.contents_file, 'r', encoding='UTF-8') as f: self.contents = ''.join(f.read().splitlines()) def sender(self, to_name, to_email): msg = EmailMessage() msg['Subject'] = self.subject msg['From'] = Address(self.name, self.from_email.split('@')[0], self.from_email.split('@')[1]) msg['To'] = Address(to_name, to_email.split('@')[0], to_email.split('@')[1]) dear_comment = "<p>Hello {},</p>".format(to_name) email_body = dear_comment + self.contents msg.set_content(cleanhtml(email_body)) asparagus_cid = make_msgid() msg.add_alternative(email_body.format(asparagus_cid=asparagus_cid[1:-1]), subtype='html') if self.images.endswith('EMPTY'): pass else: with open(self.images, 'rb') as img: img_style = self.images.split('.')[1] msg.get_payload()[1].add_related(img.read(), 'image', img_style, cid=asparagus_cid) # Accept here: https://myaccount.google.com/lesssecureapps with smtplib.SMTP('smtp.gmail.com', 587) as s: s.ehlo() s.starttls() s.login(self.id, self.pw) s.send_message(msg) print('Send complete to {}({})'.format(to_name, to_email)) @stopwatch def run(self): confirm = input('Are you sure to send emails to {} et {}? [Y/n] '.format(self.to_email_list[0].split(',')[0], len(self.to_email_list)-1)) notice = '\n\n\tCheck {} file and try again.'.format(self.to_email) if confirm.lower() in ['y', 'yes']: pass else: raise ValueError(notice) print("") for each in self.to_email_list: to_name = each.split(',')[0].strip() to_email = each.split(',')[1].strip() self.sender(to_name, to_email) time.sleep(self.timesleep+random.random()*2) def main(): if os.name == 'posix': os.system('clear') else: os.system('cls') # Notice available account input('\nMust be use Gmail or G-Suite account. (Enter) ') # Check lesssecureapps policy lesssecureapps = 'https://myaccount.google.com/lesssecureapps' security = input('\nDid you allow the permission on '+lesssecureapps+'? (Y/n) ') if security.lower() in ['y', 'yes']: pass else: notice = '\nPlease visit and allow the permission\n\n\t'+lesssecureapps+'\n' import webbrowser webbrowser.open(lesssecureapps, new=2) raise ValueError(notice) # Select an email content contents = get_list() print("") for i, content in enumerate(contents): print('{}. {}'.format(i+1, content)) selected = input('Choose one [{}-{}]: '.format(1, len(contents))) # Input information get_id = validity("the account") get_name = validity("your name") get_pw = validity("the password") get_sub = validity("the subject of the email") security_check(get_id, get_name, get_pw, get_sub) emails = Emails(get_sub, get_id, get_pw, get_name, contents[int(selected)-1]) print('\n'+'-'*30+' Start sending '+'-'*30+'\n') emails.run() if __name__ == '__main__': main()
36.086957
145
0.604337
ace9e76e075e5ab91f05de0206d0fcd256688772
20,324
py
Python
models/vision_transformer.py
hmthanh/LaTeX_OCR
bf5cf4642aff9cbbd5c4f8f232cd993a38ee6d81
[ "MIT" ]
null
null
null
models/vision_transformer.py
hmthanh/LaTeX_OCR
bf5cf4642aff9cbbd5c4f8f232cd993a38ee6d81
[ "MIT" ]
null
null
null
models/vision_transformer.py
hmthanh/LaTeX_OCR
bf5cf4642aff9cbbd5c4f8f232cd993a38ee6d81
[ "MIT" ]
null
null
null
import math import logging from functools import partial from collections import OrderedDict import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.checkpoint from models.helpers import adapt_input_conv, build_model_with_cfg, checkpoint_seq, named_apply, resolve_pretrained_cfg from models.layers.drop import DropPath from models.layers.mlp import Mlp from models.layers.patch_embed import PatchEmbed from models.layers.weight_init import lecun_normal_, trunc_normal_ _logger = logging.getLogger(__name__) class Attention(nn.Module): def __init__(self, dim, num_heads=8, qkv_bias=False, attn_drop=0., proj_drop=0.): super().__init__() assert dim % num_heads == 0, 'dim should be divisible by num_heads' self.num_heads = num_heads head_dim = dim // num_heads self.scale = head_dim ** -0.5 self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Linear(dim, dim) self.proj_drop = nn.Dropout(proj_drop) def forward(self, x): B, N, C = x.shape qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) # make torchscript happy (cannot use tensor as tuple) q, k, v = qkv.unbind(0) attn = (q @ k.transpose(-2, -1)) * self.scale attn = attn.softmax(dim=-1) attn = self.attn_drop(attn) x = (attn @ v).transpose(1, 2).reshape(B, N, C) x = self.proj(x) x = self.proj_drop(x) return x class LayerScale(nn.Module): def __init__(self, dim, init_values=1e-5, inplace=False): super().__init__() self.inplace = inplace self.gamma = nn.Parameter(init_values * torch.ones(dim)) def forward(self, x): return x.mul_(self.gamma) if self.inplace else x * self.gamma class Block(nn.Module): def __init__( self, dim, num_heads, mlp_ratio=4., qkv_bias=False, drop=0., attn_drop=0., init_values=None, drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm): super().__init__() self.norm1 = norm_layer(dim) self.attn = Attention( dim, num_heads=num_heads, qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=drop) self.ls1 = LayerScale( dim, init_values=init_values) if init_values else nn.Identity() # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here self.drop_path1 = DropPath( drop_path) if drop_path > 0. else nn.Identity() self.norm2 = norm_layer(dim) mlp_hidden_dim = int(dim * mlp_ratio) self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) self.ls2 = LayerScale( dim, init_values=init_values) if init_values else nn.Identity() self.drop_path2 = DropPath( drop_path) if drop_path > 0. else nn.Identity() def forward(self, x): x = x + self.drop_path1(self.ls1(self.attn(self.norm1(x)))) x = x + self.drop_path2(self.ls2(self.mlp(self.norm2(x)))) return x class VisionTransformer(nn.Module): """ Vision Transformer A PyTorch impl of : `An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale` - https://arxiv.org/abs/2010.11929 """ def __init__( self, img_size=224, patch_size=16, in_chans=3, num_classes=1000, global_pool='token', embed_dim=768, depth=12, num_heads=12, mlp_ratio=4., qkv_bias=True, representation_size=None, drop_rate=0., attn_drop_rate=0., drop_path_rate=0., weight_init='', init_values=None, embed_layer=PatchEmbed, norm_layer=None, act_layer=None, block_fn=Block): """ Args: img_size (int, tuple): input image size patch_size (int, tuple): patch size in_chans (int): number of input channels num_classes (int): number of classes for classification head global_pool (str): type of global pooling for final sequence (default: 'token') embed_dim (int): embedding dimension depth (int): depth of transformer num_heads (int): number of attention heads mlp_ratio (int): ratio of mlp hidden dim to embedding dim qkv_bias (bool): enable bias for qkv if True representation_size (Optional[int]): enable and set representation layer (pre-logits) to this value if set drop_rate (float): dropout rate attn_drop_rate (float): attention dropout rate drop_path_rate (float): stochastic depth rate weight_init: (str): weight init scheme init_values: (float): layer-scale init values embed_layer (nn.Module): patch embedding layer norm_layer: (nn.Module): normalization layer act_layer: (nn.Module): MLP activation layer """ super().__init__() assert global_pool in ('', 'avg', 'token') norm_layer = norm_layer or partial(nn.LayerNorm, eps=1e-6) act_layer = act_layer or nn.GELU self.num_classes = num_classes self.global_pool = global_pool # num_features for consistency with other models self.num_features = self.embed_dim = embed_dim self.num_tokens = 1 self.grad_checkpointing = False self.patch_embed = embed_layer( img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim) num_patches = self.patch_embed.num_patches self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) self.pos_embed = nn.Parameter(torch.zeros( 1, num_patches + self.num_tokens, embed_dim)) self.pos_drop = nn.Dropout(p=drop_rate) # stochastic depth decay rule dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] self.blocks = nn.Sequential(*[ block_fn( dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, init_values=init_values, drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer, act_layer=act_layer) for i in range(depth)]) use_fc_norm = self.global_pool == 'avg' self.norm = norm_layer(embed_dim) if not use_fc_norm else nn.Identity() # Representation layer. Used for original ViT models w/ in21k pretraining. self.representation_size = representation_size self.pre_logits = nn.Identity() if representation_size: self._reset_representation(representation_size) # Classifier Head self.fc_norm = norm_layer(embed_dim) if use_fc_norm else nn.Identity() final_chs = self.representation_size if self.representation_size else self.embed_dim self.head = nn.Linear( final_chs, num_classes) if num_classes > 0 else nn.Identity() if weight_init != 'skip': self.init_weights(weight_init) def _reset_representation(self, representation_size): self.representation_size = representation_size if self.representation_size: self.pre_logits = nn.Sequential(OrderedDict([ ('fc', nn.Linear(self.embed_dim, self.representation_size)), ('act', nn.Tanh()) ])) else: self.pre_logits = nn.Identity() def init_weights(self, mode=''): assert mode in ('jax', 'jax_nlhb', 'moco', '') head_bias = -math.log(self.num_classes) if 'nlhb' in mode else 0. trunc_normal_(self.pos_embed, std=.02) nn.init.normal_(self.cls_token, std=1e-6) named_apply(get_init_weights_vit(mode, head_bias), self) def _init_weights(self, m): # this fn left here for compat with downstream users init_weights_vit_timm(m) @torch.jit.ignore() def load_pretrained(self, checkpoint_path, prefix=''): _load_weights(self, checkpoint_path, prefix) @torch.jit.ignore def no_weight_decay(self): return {'pos_embed', 'cls_token', 'dist_token'} @torch.jit.ignore def group_matcher(self, coarse=False): return dict( stem=r'^cls_token|pos_embed|patch_embed', # stem and embed blocks=[(r'^blocks\.(\d+)', None), (r'^norm', (99999,))] ) @torch.jit.ignore def set_grad_checkpointing(self, enable=True): self.grad_checkpointing = enable @torch.jit.ignore def get_classifier(self): return self.head def reset_classifier(self, num_classes: int, global_pool=None, representation_size=None): self.num_classes = num_classes if global_pool is not None: assert global_pool in ('', 'avg', 'token') self.global_pool = global_pool if representation_size is not None: self._reset_representation(representation_size) final_chs = self.representation_size if self.representation_size else self.embed_dim self.head = nn.Linear( final_chs, num_classes) if num_classes > 0 else nn.Identity() def forward_features(self, x): x = self.patch_embed(x) x = torch.cat((self.cls_token.expand(x.shape[0], -1, -1), x), dim=1) x = self.pos_drop(x + self.pos_embed) if self.grad_checkpointing and not torch.jit.is_scripting(): x = checkpoint_seq(self.blocks, x) else: x = self.blocks(x) x = self.norm(x) return x def forward_head(self, x, pre_logits: bool = False): if self.global_pool: x = x[:, 1:].mean(dim=1) if self.global_pool == 'avg' else x[:, 0] x = self.fc_norm(x) x = self.pre_logits(x) return x if pre_logits else self.head(x) def forward(self, x): x = self.forward_features(x) x = self.forward_head(x) return x def init_weights_vit_timm(module: nn.Module, name: str = ''): """ ViT weight initialization, original timm impl (for reproducibility) """ if isinstance(module, nn.Linear): trunc_normal_(module.weight, std=.02) if module.bias is not None: nn.init.zeros_(module.bias) def init_weights_vit_jax(module: nn.Module, name: str = '', head_bias: float = 0.): """ ViT weight initialization, matching JAX (Flax) impl """ if isinstance(module, nn.Linear): if name.startswith('head'): nn.init.zeros_(module.weight) nn.init.constant_(module.bias, head_bias) elif name.startswith('pre_logits'): lecun_normal_(module.weight) nn.init.zeros_(module.bias) else: nn.init.xavier_uniform_(module.weight) if module.bias is not None: nn.init.normal_( module.bias, std=1e-6) if 'mlp' in name else nn.init.zeros_(module.bias) elif isinstance(module, nn.Conv2d): lecun_normal_(module.weight) if module.bias is not None: nn.init.zeros_(module.bias) def init_weights_vit_moco(module: nn.Module, name: str = ''): """ ViT weight initialization, matching moco-v3 impl minus fixed PatchEmbed """ if isinstance(module, nn.Linear): if 'qkv' in name: # treat the weights of Q, K, V separately val = math.sqrt( 6. / float(module.weight.shape[0] // 3 + module.weight.shape[1])) nn.init.uniform_(module.weight, -val, val) else: nn.init.xavier_uniform_(module.weight) if module.bias is not None: nn.init.zeros_(module.bias) def get_init_weights_vit(mode='jax', head_bias: float = 0.): if 'jax' in mode: return partial(init_weights_vit_jax, head_bias=head_bias) elif 'moco' in mode: return init_weights_vit_moco else: return init_weights_vit_timm @torch.no_grad() def _load_weights(model: VisionTransformer, checkpoint_path: str, prefix: str = ''): """ Load weights from .npz checkpoints for official Google Brain Flax implementation """ import numpy as np def _n2p(w, t=True): if w.ndim == 4 and w.shape[0] == w.shape[1] == w.shape[2] == 1: w = w.flatten() if t: if w.ndim == 4: w = w.transpose([3, 2, 0, 1]) elif w.ndim == 3: w = w.transpose([2, 0, 1]) elif w.ndim == 2: w = w.transpose([1, 0]) return torch.from_numpy(w) w = np.load(checkpoint_path) if not prefix and 'opt/target/embedding/kernel' in w: prefix = 'opt/target/' if hasattr(model.patch_embed, 'backbone'): # hybrid backbone = model.patch_embed.backbone stem_only = not hasattr(backbone, 'stem') stem = backbone if stem_only else backbone.stem stem.conv.weight.copy_(adapt_input_conv( stem.conv.weight.shape[1], _n2p(w[f'{prefix}conv_root/kernel']))) stem.norm.weight.copy_(_n2p(w[f'{prefix}gn_root/scale'])) stem.norm.bias.copy_(_n2p(w[f'{prefix}gn_root/bias'])) if not stem_only: for i, stage in enumerate(backbone.stages): for j, block in enumerate(stage.blocks): bp = f'{prefix}block{i + 1}/unit{j + 1}/' for r in range(3): getattr( block, f'conv{r + 1}').weight.copy_(_n2p(w[f'{bp}conv{r + 1}/kernel'])) getattr( block, f'norm{r + 1}').weight.copy_(_n2p(w[f'{bp}gn{r + 1}/scale'])) getattr( block, f'norm{r + 1}').bias.copy_(_n2p(w[f'{bp}gn{r + 1}/bias'])) if block.downsample is not None: block.downsample.conv.weight.copy_( _n2p(w[f'{bp}conv_proj/kernel'])) block.downsample.norm.weight.copy_( _n2p(w[f'{bp}gn_proj/scale'])) block.downsample.norm.bias.copy_( _n2p(w[f'{bp}gn_proj/bias'])) embed_conv_w = _n2p(w[f'{prefix}embedding/kernel']) else: embed_conv_w = adapt_input_conv( model.patch_embed.proj.weight.shape[1], _n2p(w[f'{prefix}embedding/kernel'])) model.patch_embed.proj.weight.copy_(embed_conv_w) model.patch_embed.proj.bias.copy_(_n2p(w[f'{prefix}embedding/bias'])) model.cls_token.copy_(_n2p(w[f'{prefix}cls'], t=False)) pos_embed_w = _n2p( w[f'{prefix}Transformer/posembed_input/pos_embedding'], t=False) if pos_embed_w.shape != model.pos_embed.shape: pos_embed_w = resize_pos_embed( # resize pos embedding when different size from pretrained weights pos_embed_w, model.pos_embed, getattr(model, 'num_tokens', 1), model.patch_embed.grid_size) model.pos_embed.copy_(pos_embed_w) model.norm.weight.copy_(_n2p(w[f'{prefix}Transformer/encoder_norm/scale'])) model.norm.bias.copy_(_n2p(w[f'{prefix}Transformer/encoder_norm/bias'])) if isinstance(model.head, nn.Linear) and model.head.bias.shape[0] == w[f'{prefix}head/bias'].shape[-1]: model.head.weight.copy_(_n2p(w[f'{prefix}head/kernel'])) model.head.bias.copy_(_n2p(w[f'{prefix}head/bias'])) if isinstance(getattr(model.pre_logits, 'fc', None), nn.Linear) and f'{prefix}pre_logits/bias' in w: model.pre_logits.fc.weight.copy_(_n2p(w[f'{prefix}pre_logits/kernel'])) model.pre_logits.fc.bias.copy_(_n2p(w[f'{prefix}pre_logits/bias'])) for i, block in enumerate(model.blocks.children()): block_prefix = f'{prefix}Transformer/encoderblock_{i}/' mha_prefix = block_prefix + 'MultiHeadDotProductAttention_1/' block.norm1.weight.copy_(_n2p(w[f'{block_prefix}LayerNorm_0/scale'])) block.norm1.bias.copy_(_n2p(w[f'{block_prefix}LayerNorm_0/bias'])) block.attn.qkv.weight.copy_(torch.cat([ _n2p(w[f'{mha_prefix}{n}/kernel'], t=False).flatten(1).T for n in ('query', 'key', 'value')])) block.attn.qkv.bias.copy_(torch.cat([ _n2p(w[f'{mha_prefix}{n}/bias'], t=False).reshape(-1) for n in ('query', 'key', 'value')])) block.attn.proj.weight.copy_( _n2p(w[f'{mha_prefix}out/kernel']).flatten(1)) block.attn.proj.bias.copy_(_n2p(w[f'{mha_prefix}out/bias'])) for r in range(2): getattr(block.mlp, f'fc{r + 1}').weight.copy_( _n2p(w[f'{block_prefix}MlpBlock_3/Dense_{r}/kernel'])) getattr(block.mlp, f'fc{r + 1}').bias.copy_( _n2p(w[f'{block_prefix}MlpBlock_3/Dense_{r}/bias'])) block.norm2.weight.copy_(_n2p(w[f'{block_prefix}LayerNorm_2/scale'])) block.norm2.bias.copy_(_n2p(w[f'{block_prefix}LayerNorm_2/bias'])) def resize_pos_embed(posemb, posemb_new, num_tokens=1, gs_new=()): # Rescale the grid of position embeddings when loading from state_dict. Adapted from # https://github.com/google-research/vision_transformer/blob/00883dd691c63a6830751563748663526e811cee/vit_jax/checkpoint.py#L224 _logger.info('Resized position embedding: %s to %s', posemb.shape, posemb_new.shape) ntok_new = posemb_new.shape[1] if num_tokens: posemb_tok, posemb_grid = posemb[:, :num_tokens], posemb[0, num_tokens:] ntok_new -= num_tokens else: posemb_tok, posemb_grid = posemb[:, :0], posemb[0] gs_old = int(math.sqrt(len(posemb_grid))) if not len(gs_new): # backwards compatibility gs_new = [int(math.sqrt(ntok_new))] * 2 assert len(gs_new) >= 2 _logger.info('Position embedding grid-size from %s to %s', [gs_old, gs_old], gs_new) posemb_grid = posemb_grid.reshape( 1, gs_old, gs_old, -1).permute(0, 3, 1, 2) posemb_grid = F.interpolate( posemb_grid, size=gs_new, mode='bicubic', align_corners=False) posemb_grid = posemb_grid.permute( 0, 2, 3, 1).reshape(1, gs_new[0] * gs_new[1], -1) posemb = torch.cat([posemb_tok, posemb_grid], dim=1) return posemb def checkpoint_filter_fn(state_dict, model): """ convert patch embedding weight from manual patchify + linear proj to conv""" out_dict = {} if 'model' in state_dict: # For deit models state_dict = state_dict['model'] for k, v in state_dict.items(): if 'patch_embed.proj.weight' in k and len(v.shape) < 4: # For old models that I trained prior to conv based patchification O, I, H, W = model.patch_embed.proj.weight.shape v = v.reshape(O, -1, H, W) elif k == 'pos_embed' and v.shape != model.pos_embed.shape: # To resize pos embedding when using model at different size from pretrained weights v = resize_pos_embed( v, model.pos_embed, getattr(model, 'num_tokens', 1), model.patch_embed.grid_size) out_dict[k] = v return out_dict def _create_vision_transformer(variant, pretrained=False, **kwargs): if kwargs.get('features_only', None): raise RuntimeError( 'features_only not implemented for Vision Transformer models.') # NOTE this extra code to support handling of repr size for in21k pretrained models pretrained_cfg = resolve_pretrained_cfg(variant, kwargs=kwargs) default_num_classes = pretrained_cfg['num_classes'] num_classes = kwargs.get('num_classes', default_num_classes) repr_size = kwargs.pop('representation_size', None) if repr_size is not None and num_classes != default_num_classes: # Remove representation layer if fine-tuning. This may not always be the desired action, # but I feel better than doing nothing by default for fine-tuning. Perhaps a better interface? _logger.warning("Removing representation layer for fine-tuning.") repr_size = None model = build_model_with_cfg( VisionTransformer, variant, pretrained, pretrained_cfg=pretrained_cfg, representation_size=repr_size, pretrained_filter_fn=checkpoint_filter_fn, pretrained_custom_load='npz' in pretrained_cfg['url'], **kwargs) return model
44.182609
132
0.630388
ace9e7993f3fec38f4319d537b2530eb5a184e4c
2,283
py
Python
model/selectframe_tc.py
CFM-MSG/Code_SelectiveHCN
1f624c5debd03925f0732d1d732c69c46d1fc39d
[ "MIT" ]
2
2021-10-12T05:18:57.000Z
2022-03-23T13:11:42.000Z
model/selectframe_tc.py
CFM-MSG/Code_SelectiveHCN
1f624c5debd03925f0732d1d732c69c46d1fc39d
[ "MIT" ]
null
null
null
model/selectframe_tc.py
CFM-MSG/Code_SelectiveHCN
1f624c5debd03925f0732d1d732c69c46d1fc39d
[ "MIT" ]
null
null
null
import torch import torch.nn as nn import torch.nn.functional as F from .utils import * class SelectframeTemConv(nn.Module): '''Selective-frame Temporal Convolution (STC).''' def __init__(self,in_spa,in_tem,ratio=0.5): super(SelectframeTemConv, self).__init__() self.in_spa = in_spa self.in_tem = in_tem self.ratio = ratio self.ch_reduce = nn.Sequential( nn.Conv2d(in_spa, 1, 1), nn.BatchNorm2d(1), nn.ReLU(), ) self.spa_reduce = nn.Sequential( nn.Conv2d(25, 1, 1), nn.BatchNorm2d(1), nn.ReLU(), ) self.fc_tem = nn.Sequential( nn.Linear(in_tem, in_tem), nn.Tanh(), nn.Linear(in_tem, in_tem), nn.Tanh(), nn.Linear(in_tem, in_tem), ) self.drop = nn.Dropout(p=0.8) self.sigmoid = nn.Sigmoid() for m in self.modules(): if isinstance(m, nn.Conv2d): conv_init(m) elif isinstance(m, nn.Linear): fc_init(m) elif isinstance(m, nn.BatchNorm2d): bn_init(m, 1) def forward(self, x_in, N): NM, C, T, V = x_in.size() x_in = x_in.view(N, NM//N, C, T, V) x = x_in x = x.mean(dim=1) # N C T V x = self.ch_reduce(x) x = x.permute(0,3,2,1).contiguous() x = self.spa_reduce(x) x = x.view(N, -1) # attention. x = self.fc_tem(x) scores = self.sigmoid(x) # N T # Top-k selection. T_new = int(T*self.ratio) top_scores, indices = scores.topk(T_new, dim=1, largest=True, sorted=False) top_scores = top_scores.unsqueeze(1).unsqueeze(1).unsqueeze(-1) if T_new < T: x_out = torch.empty((N, NM//N, C, T_new, V), device=x_in.device) for i in range(N): x_out[i] = x_in[i,:,:,indices[i],:] else: x_out = x_in x_out = (x_out*top_scores).view(NM, C, T_new, V) return x_out, indices
30.039474
83
0.471748
ace9ea37a339e0ac1c47d5ea1d95eb1dd5dd62e3
2,410
py
Python
loveletter/tests/test_games.py
ErikGartner/love-letter
36995788292ea6fdfc72a8b09adad01ba6683c26
[ "MIT" ]
null
null
null
loveletter/tests/test_games.py
ErikGartner/love-letter
36995788292ea6fdfc72a8b09adad01ba6683c26
[ "MIT" ]
null
null
null
loveletter/tests/test_games.py
ErikGartner/love-letter
36995788292ea6fdfc72a8b09adad01ba6683c26
[ "MIT" ]
null
null
null
"""Tests for the running of the Love Letter game""" import unittest import numpy as np from loveletter.game import Game from loveletter.card import Card from loveletter.player import PlayerAction, PlayerActionTools class TestGames(unittest.TestCase): """Love Letter Games""" @staticmethod def replay(seed, action_sequence=None): """Generate a game from a recorded set of actions""" action_sequence = action_sequence if action_sequence is not None else [] action_sequence = np.array(action_sequence, dtype=np.uint8) action_sequence = PlayerActionTools.from_np_many(action_sequence)[::-1] game = Game.new(4, seed) while len(action_sequence) > 0: if not game.is_current_player_playing(): game = game.skip_eliminated_player() else: action = action_sequence.pop() game = game._move(action) return game def test_end_elimination(self): """Reach the end of a game by elimination""" game = Game.new(4, 0) game, _ = game.move(PlayerAction(Card.guard, 1, Card.priest, Card.noCard)) game = game.skip_eliminated_player() game, _ = game.move(PlayerAction(Card.guard, 3, Card.countess, Card.noCard)) game, _ = game.move(PlayerAction(Card.handmaid, 3, Card.noCard, Card.noCard)) game, _ = game.move(PlayerAction( Card.countess, 0, Card.noCard, Card.noCard)) game = game.skip_eliminated_player() game, _ = game.move(PlayerAction( Card.baron, 3, Card.noCard, Card.noCard)) game, _= game.move(PlayerAction( Card.guard, 2, Card.handmaid, Card.noCard)) self.assertFalse(game.over()) game, _ = game.move(PlayerAction( Card.princess, 0, Card.noCard, Card.noCard)) self.assertEqual(game.cards_left(), 4) self.assertTrue(game.over()) def test_end_length(self): """Reach the end of a game by cards""" game = TestGames.replay(1, [1, 1, 3, 0, 4, 1, 0, 0, 1, 1, 3, 0, 1, 2, 6, 0, 7, 0, 0, 0, 1, 2, 2, 0, 8, 2, 0, 0, 1, 1, 5, 0, 2, 1, 0, 0, 5, 0, 0, 0]) self.assertEqual(game.cards_left(), 0) self.assertTrue(game.over()) self.assertEqual(game.winner(), 1) if __name__ == '__main__': unittest.main()
35.441176
85
0.602905
ace9eaa7b881a4b04bcbcff4e05d979cf114d786
17,301
py
Python
lingvo/tasks/car/breakdown_metric_test.py
Singed-jj/lingvo
a2a4ac8bd835ffc2f95fc38ee3e9bc17c30fcc56
[ "Apache-2.0" ]
null
null
null
lingvo/tasks/car/breakdown_metric_test.py
Singed-jj/lingvo
a2a4ac8bd835ffc2f95fc38ee3e9bc17c30fcc56
[ "Apache-2.0" ]
null
null
null
lingvo/tasks/car/breakdown_metric_test.py
Singed-jj/lingvo
a2a4ac8bd835ffc2f95fc38ee3e9bc17c30fcc56
[ "Apache-2.0" ]
null
null
null
# Lint as: python3 # Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for breakdown_metric.""" from lingvo import compat as tf from lingvo.core import py_utils from lingvo.core import test_utils from lingvo.tasks.car import breakdown_metric from lingvo.tasks.car import kitti_ap_metric from lingvo.tasks.car import kitti_metadata import numpy as np from six.moves import range FLAGS = tf.flags.FLAGS class BreakdownMetricTest(test_utils.TestCase): def _GenerateRandomBBoxes(self, num_bboxes): xyz = np.random.uniform(low=-1.0, high=1.0, size=(num_bboxes, 3)) dimension = np.random.uniform(low=-1, high=1.0, size=(num_bboxes, 3)) rotation = np.random.uniform(low=-np.pi, high=np.pi, size=(num_bboxes, 1)) bboxes = np.concatenate([xyz, dimension, rotation], axis=-1) return bboxes def _GenerateBBoxesAtDistanceAndRotation(self, num_boxes, distance, rotation): bboxes = np.zeros(shape=(num_boxes, 7)) bboxes[:, -1] = rotation bboxes[:, 0] = distance return bboxes def _GenerateMetricsWithTestData(self, num_classes): metadata = kitti_metadata.KITTIMetadata() num_bins_of_distance = int( np.rint(metadata.MaximumDistance() / metadata.DistanceBinWidth())) num_bins_of_rotation = metadata.NumberOfRotationBins() num_bins_of_points = metadata.NumberOfPointsBins() # Generate ground truth bounding boxes with prescribed labels, distances, # rotations and number of points. expected_objects_at_distance = np.random.randint( low=0, high=8, size=(num_classes, num_bins_of_distance), dtype=np.int32) expected_objects_at_rotation = np.zeros( shape=(num_classes, num_bins_of_rotation), dtype=np.int32) # Note that we need preserve the same number of objects for each label. expected_objects_at_points = np.zeros( shape=(num_classes, num_bins_of_points), dtype=np.int32) prob = 1.0 / float(num_bins_of_points) for c in range(num_classes): num_objects_for_class = np.sum(expected_objects_at_distance[c, :]) expected_objects_at_points[c, :] = np.random.multinomial( num_objects_for_class, pvals=num_bins_of_points * [prob]) # Zero out the number of boxes in the background class. expected_objects_at_distance[0, :] = 0 expected_objects_at_points[0, :] = 0 expected_objects_at_rotation[0, :] = 0 bboxes = [] labels = [] num_points = [] bin_width = ( metadata.MaximumRotation() / float(metadata.NumberOfRotationBins())) # Note that we always skip 'Background' class 0. for label in range(1, num_classes): for distance_index in range(num_bins_of_distance): distance = ( distance_index * metadata.DistanceBinWidth() + metadata.DistanceBinWidth() / 2.0) num_box = expected_objects_at_distance[label, distance_index] if num_box > 0: rotation_index = np.random.randint(num_bins_of_rotation) expected_objects_at_rotation[label, rotation_index] += num_box rotation = rotation_index * bin_width + bin_width / 2.0 bboxes.append( self._GenerateBBoxesAtDistanceAndRotation(num_box, distance, rotation)) labels.append(label * np.ones(shape=[num_box], dtype=np.int32)) point_bin_edges = np.logspace( np.log10(1.0), np.log10(metadata.MaximumNumberOfPoints()), metadata.NumberOfPointsBins() + 1) for point_index in range(num_bins_of_points): num_box = expected_objects_at_points[label, point_index] for _ in range(num_box): points = (point_bin_edges[point_index] + point_bin_edges[point_index + 1]) / 2.0 num_points.append([points]) bboxes = np.concatenate(bboxes) labels = np.concatenate(labels) num_points = np.concatenate(num_points) # Generate dummy predictions as placeholders for the API. num_predictions = 9 prediction_scores = np.random.uniform(size=[num_classes, num_predictions]) prediction_bboxes = self._GenerateRandomBBoxes( num_predictions * num_classes).reshape( (num_classes, num_predictions, 7)) # Update the metrics. metric_names = ['rotation', 'num_points', 'distance'] ap_params = kitti_ap_metric.KITTIAPMetrics.Params(metadata).Set( breakdown_metrics=metric_names) metrics = ap_params.Instantiate() metrics.Update( 'dummy_image1', py_utils.NestedMap( groundtruth_labels=labels, groundtruth_bboxes=bboxes, groundtruth_difficulties=np.ones(shape=(bboxes.shape[0])), groundtruth_num_points=num_points, detection_scores=prediction_scores, detection_boxes=prediction_bboxes, detection_heights_in_pixels=np.ones( shape=prediction_bboxes.shape[0:2]) * 100)) return py_utils.NestedMap( metrics=metrics, expected_objects_at_distance=expected_objects_at_distance, expected_objects_at_points=expected_objects_at_points, expected_objects_at_rotation=expected_objects_at_rotation) def testLoadBoundingBoxes(self): # Test if all of the groundtruth data loads correctly for each label # when no distance is specified. metadata = kitti_metadata.KITTIMetadata() num_classes = len(metadata.ClassNames()) test_data = self._GenerateMetricsWithTestData(num_classes) expected_num_objects = np.sum( test_data.expected_objects_at_distance, axis=1) # Note that we always skip 'Background' class 0. for label in range(1, num_classes): data = test_data.metrics._LoadBoundingBoxes( 'groundtruth', label, distance=None) if expected_num_objects[label] == 0: self.assertIsNone(data) else: self.assertEqual(expected_num_objects[label], len(data.boxes)) self.assertEqual(expected_num_objects[label], len(data.imgids)) self.assertEqual(expected_num_objects[label], len(data.scores)) self.assertEqual(expected_num_objects[label], len(data.difficulties)) self.assertAllEqual( np.ones(shape=[expected_num_objects[label]]), data.scores) self.assertAllEqual( np.zeros(shape=[expected_num_objects[label]]), data.imgids) def testLoadBoundingBoxesDifficulty(self): metadata = kitti_metadata.KITTIMetadata() num_classes = len(metadata.ClassNames()) test_data = self._GenerateMetricsWithTestData(num_classes) expected_num_objects = np.sum( test_data.expected_objects_at_distance, axis=1) difficulty_metric = test_data.metrics._breakdown_metrics['difficulty'] # Test if difficulties are properly accumulated. for d in metadata.DifficultyLevels().values(): if d == 1: self.assertAllEqual(expected_num_objects, difficulty_metric._histogram[d, :]) else: self.assertAllEqual( np.zeros_like(expected_num_objects), difficulty_metric._histogram[d, :]) def testLoadBoundingBoxesDistance(self): # Test if all of the groundtruth data loads correctly for each label # when distance is specified. metadata = kitti_metadata.KITTIMetadata() num_classes = len(metadata.ClassNames()) test_data = self._GenerateMetricsWithTestData(num_classes) num_bins_of_distance = int( np.rint(metadata.MaximumDistance() / metadata.DistanceBinWidth())) distance_metric = test_data.metrics._breakdown_metrics['distance'] # Test if all of the groundtruth data loads correctly for each label # when no distance is specified. self.assertAllEqual(test_data.expected_objects_at_distance, np.transpose(distance_metric._histogram)) # Note that we always skip 'Background' class 0. for label in range(1, num_classes): for distance in range(num_bins_of_distance): data = test_data.metrics._LoadBoundingBoxes( 'groundtruth', label, distance=distance) if test_data.expected_objects_at_distance[label, distance] == 0: self.assertIsNone(data) else: self.assertEqual( test_data.expected_objects_at_distance[label, distance], len(data.boxes)) self.assertEqual( test_data.expected_objects_at_distance[label, distance], len(data.imgids)) self.assertEqual( test_data.expected_objects_at_distance[label, distance], len(data.scores)) self.assertEqual( test_data.expected_objects_at_distance[label, distance], len(data.difficulties)) self.assertAllEqual( np.ones(shape=[ test_data.expected_objects_at_distance[label, distance] ]), data.scores) self.assertAllEqual( np.zeros(shape=[ test_data.expected_objects_at_distance[label, distance] ]), data.imgids) def testLoadBoundingBoxesNumPoints(self): # Test if all of the groundtruth data loads correctly for each label # when number of points is specified. metadata = kitti_metadata.KITTIMetadata() num_classes = len(metadata.ClassNames()) test_data = self._GenerateMetricsWithTestData(num_classes) num_bins_of_points = metadata.NumberOfPointsBins() num_points_metric = test_data.metrics._breakdown_metrics['num_points'] self.assertAllEqual(test_data.expected_objects_at_points, np.transpose(num_points_metric._histogram)) # Note that we always skip 'Background' class 0. for label in range(1, num_classes): for num_points in range(num_bins_of_points): data = test_data.metrics._LoadBoundingBoxes( 'groundtruth', label, num_points=num_points) if test_data.expected_objects_at_points[label, num_points] == 0: self.assertIsNone(data) else: # Skip the first bin because it is a special case. if num_points == 0: continue self.assertEqual( test_data.expected_objects_at_points[label, num_points], len(data.boxes)) self.assertEqual( test_data.expected_objects_at_points[label, num_points], len(data.imgids)) self.assertEqual( test_data.expected_objects_at_points[label, num_points], len(data.scores)) self.assertEqual( test_data.expected_objects_at_points[label, num_points], len(data.difficulties)) self.assertAllEqual( np.ones(shape=[ test_data.expected_objects_at_points[label, num_points] ]), data.scores) self.assertAllEqual( np.zeros(shape=[ test_data.expected_objects_at_points[label, num_points] ]), data.imgids) def testLoadBoundingBoxesRotation(self): # Test if all of the groundtruth data loads correctly for each label # when rotation is specified. metadata = kitti_metadata.KITTIMetadata() num_classes = len(metadata.ClassNames()) test_data = self._GenerateMetricsWithTestData(num_classes) num_bins_of_rotation = metadata.NumberOfRotationBins() rotation_metric = test_data.metrics._breakdown_metrics['rotation'] # Test if all of the groundtruth data loads correctly for each label # when no distance is specified. self.assertAllEqual(test_data.expected_objects_at_rotation, np.transpose(rotation_metric._histogram)) # Note that we always skip 'Background' class 0. for label in range(1, num_classes): for rotation in range(num_bins_of_rotation): data = test_data.metrics._LoadBoundingBoxes( 'groundtruth', label, rotation=rotation) if test_data.expected_objects_at_rotation[label, rotation] == 0: self.assertIsNone(data) else: self.assertEqual( test_data.expected_objects_at_rotation[label, rotation], len(data.boxes)) self.assertEqual( test_data.expected_objects_at_rotation[label, rotation], len(data.imgids)) self.assertEqual( test_data.expected_objects_at_rotation[label, rotation], len(data.scores)) self.assertEqual( test_data.expected_objects_at_rotation[label, rotation], len(data.difficulties)) self.assertAllEqual( np.ones(shape=[ test_data.expected_objects_at_rotation[label, rotation] ]), data.scores) self.assertAllEqual( np.zeros(shape=[ test_data.expected_objects_at_rotation[label, rotation] ]), data.imgids) def testAccumulateHistogram(self): metadata = kitti_metadata.KITTIMetadata() num_per_class = np.arange(metadata.NumClasses()) + 1 statistics = [ 1 * np.ones(shape=(np.sum(num_per_class)), dtype=np.int32), 2 * np.ones(shape=(np.sum(2 * num_per_class)), dtype=np.int32) ] statistics = np.concatenate(statistics) labels = [] for i, n in enumerate(num_per_class): labels.extend([i] * n) for i, n in enumerate(num_per_class): labels.extend([i] * 2 * n) labels = np.array(labels) assert len(statistics) == len(labels) metrics_params = breakdown_metric.BreakdownMetric.Params().Set( metadata=metadata) test_breakdown_metric = breakdown_metric.ByDifficulty(metrics_params) test_breakdown_metric._AccumulateHistogram( statistics=statistics, labels=labels) for class_index, n in enumerate(num_per_class): self.assertEqual(n, test_breakdown_metric._histogram[1, class_index]) self.assertEqual(2 * n, test_breakdown_metric._histogram[2, class_index]) def testByName(self): metric_class = breakdown_metric.ByName('difficulty') self.assertEqual(metric_class, breakdown_metric.ByDifficulty) with self.assertRaises(ValueError): breakdown_metric.ByName('undefined') def testFindMaximumRecall(self): # The shape of the precision_recall_curves is [n, m, 2] where n is the # number of classes, m is then number of values in the curve, 2 indexes # between precision [0] and recall [1]. car = np.transpose( np.array( [[0.9, 0.7, 0.5, 0.1, 0.0, 0.0], [0.0, 0.2, 0.5, 0.9, 1.0, 1.0]], dtype=np.float32)) ped = np.transpose( np.array( [[0.9, 0.7, 0.5, 0.0, 0.0, 0.0], [0.0, 0.2, 0.5, 0.9, 1.0, 1.0]], dtype=np.float32)) cyc = np.transpose( np.array( [[0.9, 0.7, 0.0, 0.0, 0.0, 0.0], [0.0, 0.2, 0.5, 0.9, 1.0, 1.0]], dtype=np.float32)) foo = np.transpose( np.array( [[0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.2, 0.5, 0.9, 1.0, 1.0]], dtype=np.float32)) precision_recall_curves = np.stack([car, ped, cyc, foo]) max_recall = breakdown_metric._FindMaximumRecall(precision_recall_curves) self.assertAllEqual([4], max_recall.shape) self.assertNear(0.9, max_recall[0], 1e-7) self.assertNear(0.5, max_recall[1], 1e-7) self.assertNear(0.2, max_recall[2], 1e-7) self.assertNear(0.0, max_recall[3], 1e-7) def testFindRecallAtGivenPrecision(self): # The shape of the precision_recall_curves is [n, m, 2] where n is the # number of classes, m is then number of values in the curve, 2 indexes # between precision [0] and recall [1]. car = np.transpose( np.array( [[0.9, 0.7, 0.5, 0.1, 0.0, 0.0], [0.0, 0.2, 0.5, 0.9, 1.0, 1.0]], dtype=np.float32)) ped = np.transpose( np.array( [[0.9, 0.7, 0.5, 0.0, 0.0, 0.0], [0.0, 0.2, 0.5, 0.9, 1.0, 1.0]], dtype=np.float32)) cyc = np.transpose( np.array( [[0.9, 0.7, 0.0, 0.0, 0.0, 0.0], [0.0, 0.2, 0.5, 0.9, 1.0, 1.0]], dtype=np.float32)) foo = np.transpose( np.array( [[0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.2, 0.5, 0.9, 1.0, 1.0]], dtype=np.float32)) precision_recall_curves = np.stack([car, ped, cyc, foo]) precision_level = 0.5 recall = breakdown_metric._FindRecallAtGivenPrecision( precision_recall_curves, precision_level) self.assertAllEqual([4], recall.shape) self.assertNear(0.5, recall[0], 1e-7) self.assertNear(0.5, recall[1], 1e-7) self.assertNear(0.2, recall[2], 1e-7) self.assertNear(0.0, recall[3], 1e-7) if __name__ == '__main__': tf.test.main()
41.192857
80
0.660077
ace9ebc569fa57f4e5f84940ca8c30d5f24581b0
12,143
py
Python
gooddata-afm-client/gooddata_afm_client/model/pop_date.py
hkad98/gooddata-python-sdk
64942080ecb44c2d8e914e57f7a591daa6cca205
[ "MIT" ]
null
null
null
gooddata-afm-client/gooddata_afm_client/model/pop_date.py
hkad98/gooddata-python-sdk
64942080ecb44c2d8e914e57f7a591daa6cca205
[ "MIT" ]
null
null
null
gooddata-afm-client/gooddata_afm_client/model/pop_date.py
hkad98/gooddata-python-sdk
64942080ecb44c2d8e914e57f7a591daa6cca205
[ "MIT" ]
null
null
null
""" OpenAPI definition No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: v0 Contact: support@gooddata.com Generated by: https://openapi-generator.tech """ import re # noqa: F401 import sys # noqa: F401 from gooddata_afm_client.model_utils import ( # noqa: F401 ApiTypeError, ModelComposed, ModelNormal, ModelSimple, cached_property, change_keys_js_to_python, convert_js_args_to_python_args, date, datetime, file_type, none_type, validate_get_composed_info, OpenApiModel ) from gooddata_afm_client.exceptions import ApiAttributeError def lazy_import(): from gooddata_afm_client.model.afm_object_identifier_attribute import AfmObjectIdentifierAttribute globals()['AfmObjectIdentifierAttribute'] = AfmObjectIdentifierAttribute class PopDate(ModelNormal): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. Attributes: allowed_values (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict with a capitalized key describing the allowed value and an allowed value. These dicts store the allowed enum values. attribute_map (dict): The key is attribute name and the value is json key in definition. discriminator_value_class_map (dict): A dict to go from the discriminator variable value to the discriminator class name. validations (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict that stores validations for max_length, min_length, max_items, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, inclusive_minimum, and regex. additional_properties_type (tuple): A tuple of classes accepted as additional properties values. """ allowed_values = { } validations = { } @cached_property def additional_properties_type(): """ This must be a method because a model may have properties that are of type self, this must run after the class is loaded """ lazy_import() return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @cached_property def openapi_types(): """ This must be a method because a model may have properties that are of type self, this must run after the class is loaded Returns openapi_types (dict): The key is attribute name and the value is attribute type. """ lazy_import() return { 'attribute': (AfmObjectIdentifierAttribute,), # noqa: E501 'periods_ago': (int,), # noqa: E501 } @cached_property def discriminator(): return None attribute_map = { 'attribute': 'attribute', # noqa: E501 'periods_ago': 'periodsAgo', # noqa: E501 } read_only_vars = { } _composed_schemas = {} @classmethod @convert_js_args_to_python_args def _from_openapi_data(cls, attribute, periods_ago, *args, **kwargs): # noqa: E501 """PopDate - a model defined in OpenAPI Args: attribute (AfmObjectIdentifierAttribute): periods_ago (int): Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. Defaults to True _path_to_item (tuple/list): This is a list of keys or values to drill down to the model in received_data when deserializing a response _spec_property_naming (bool): True if the variable names in the input data are serialized names, as specified in the OpenAPI document. False if the variable names in the input data are pythonic names, e.g. snake case (default) _configuration (Configuration): the instance to use when deserializing a file_type parameter. If passed, type conversion is attempted If omitted no type conversion is done. _visited_composed_classes (tuple): This stores a tuple of classes that we have traveled through so that if we see that class again we will not use its discriminator again. When traveling through a discriminator, the composed schema that is is traveled through is added to this set. For example if Animal has a discriminator petType and we pass in "Dog", and the class Dog allOf includes Animal, we move through Animal once using the discriminator, and pick Dog. Then in Dog, we will make an instance of the Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) """ _check_type = kwargs.pop('_check_type', True) _spec_property_naming = kwargs.pop('_spec_property_naming', True) _path_to_item = kwargs.pop('_path_to_item', ()) _configuration = kwargs.pop('_configuration', None) _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) self = super(OpenApiModel, cls).__new__(cls) if args: for arg in args: if isinstance(arg, dict): kwargs.update(arg) else: raise ApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, ), path_to_item=_path_to_item, valid_classes=(self.__class__,), ) self._data_store = {} self._check_type = _check_type self._spec_property_naming = _spec_property_naming self._path_to_item = _path_to_item self._configuration = _configuration self._visited_composed_classes = _visited_composed_classes + (self.__class__,) self.attribute = attribute self.periods_ago = periods_ago for var_name, var_value in kwargs.items(): if var_name not in self.attribute_map and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ self.additional_properties_type is None: # discard variable. continue setattr(self, var_name, var_value) return self required_properties = set([ '_data_store', '_check_type', '_spec_property_naming', '_path_to_item', '_configuration', '_visited_composed_classes', ]) @convert_js_args_to_python_args def __init__(self, attribute, periods_ago, *args, **kwargs): # noqa: E501 """PopDate - a model defined in OpenAPI Args: attribute (AfmObjectIdentifierAttribute): periods_ago (int): Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. Defaults to True _path_to_item (tuple/list): This is a list of keys or values to drill down to the model in received_data when deserializing a response _spec_property_naming (bool): True if the variable names in the input data are serialized names, as specified in the OpenAPI document. False if the variable names in the input data are pythonic names, e.g. snake case (default) _configuration (Configuration): the instance to use when deserializing a file_type parameter. If passed, type conversion is attempted If omitted no type conversion is done. _visited_composed_classes (tuple): This stores a tuple of classes that we have traveled through so that if we see that class again we will not use its discriminator again. When traveling through a discriminator, the composed schema that is is traveled through is added to this set. For example if Animal has a discriminator petType and we pass in "Dog", and the class Dog allOf includes Animal, we move through Animal once using the discriminator, and pick Dog. Then in Dog, we will make an instance of the Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) """ _check_type = kwargs.pop('_check_type', True) _spec_property_naming = kwargs.pop('_spec_property_naming', False) _path_to_item = kwargs.pop('_path_to_item', ()) _configuration = kwargs.pop('_configuration', None) _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: for arg in args: if isinstance(arg, dict): kwargs.update(arg) else: raise ApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, ), path_to_item=_path_to_item, valid_classes=(self.__class__,), ) self._data_store = {} self._check_type = _check_type self._spec_property_naming = _spec_property_naming self._path_to_item = _path_to_item self._configuration = _configuration self._visited_composed_classes = _visited_composed_classes + (self.__class__,) self.attribute = attribute self.periods_ago = periods_ago for var_name, var_value in kwargs.items(): if var_name not in self.attribute_map and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ self.additional_properties_type is None: # discard variable. continue setattr(self, var_name, var_value) if var_name in self.read_only_vars: raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " f"class with read only attributes.")
42.908127
124
0.567405
ace9ec3cc452d52bced57d835c9659240f825191
6,104
py
Python
tests/backend/builders/plugin/test_interface.py
ashemedai/hatch
9ec00d5e027c992efbc16dd777b1f6926368b6bf
[ "MIT" ]
null
null
null
tests/backend/builders/plugin/test_interface.py
ashemedai/hatch
9ec00d5e027c992efbc16dd777b1f6926368b6bf
[ "MIT" ]
null
null
null
tests/backend/builders/plugin/test_interface.py
ashemedai/hatch
9ec00d5e027c992efbc16dd777b1f6926368b6bf
[ "MIT" ]
null
null
null
from os.path import sep as path_sep import pytest from hatchling.builders.plugin.interface import BuilderInterface from hatchling.metadata.core import ProjectMetadata from hatchling.plugin.manager import PluginManager class TestClean: def test_default(self, isolation): builder = BuilderInterface(str(isolation)) builder.clean(None, None) class TestVersionAPI: def test_error(self, isolation): builder = BuilderInterface(str(isolation)) with pytest.raises(NotImplementedError): builder.get_version_api() class TestPluginManager: def test_default(self, isolation): builder = BuilderInterface(str(isolation)) assert isinstance(builder.plugin_manager, PluginManager) def test_reuse(self, isolation): plugin_manager = PluginManager() builder = BuilderInterface(str(isolation), plugin_manager=plugin_manager) assert builder.plugin_manager is plugin_manager class TestRawConfig: def test_default(self, isolation): builder = BuilderInterface(str(isolation)) assert builder.raw_config == builder.raw_config == {} def test_reuse(self, isolation): config = {} builder = BuilderInterface(str(isolation), config=config) assert builder.raw_config is builder.raw_config is config def test_read(self, temp_dir): project_file = temp_dir / 'pyproject.toml' project_file.write_text('foo = 5') with temp_dir.as_cwd(): builder = BuilderInterface(str(temp_dir)) assert builder.raw_config == builder.raw_config == {'foo': 5} class TestMetadata: def test_base(self, isolation): config = {'project': {'name': 'foo'}} builder = BuilderInterface(str(isolation), config=config) assert isinstance(builder.metadata, ProjectMetadata) assert builder.metadata.core.name == 'foo' def test_core(self, isolation): config = {'project': {}} builder = BuilderInterface(str(isolation), config=config) assert builder.project_config is builder.project_config is config['project'] def test_hatch(self, isolation): config = {'tool': {'hatch': {}}} builder = BuilderInterface(str(isolation), config=config) assert builder.hatch_config is builder.hatch_config is config['tool']['hatch'] def test_build_config(self, isolation): config = {'tool': {'hatch': {'build': {}}}} builder = BuilderInterface(str(isolation), config=config) assert builder.build_config is builder.build_config is config['tool']['hatch']['build'] def test_build_config_not_table(self, isolation): config = {'tool': {'hatch': {'build': 'foo'}}} builder = BuilderInterface(str(isolation), config=config) with pytest.raises(TypeError, match='Field `tool.hatch.build` must be a table'): _ = builder.build_config def test_target_config(self, isolation): config = {'tool': {'hatch': {'build': {'targets': {'foo': {}}}}}} builder = BuilderInterface(str(isolation), config=config) builder.PLUGIN_NAME = 'foo' assert builder.target_config is builder.target_config is config['tool']['hatch']['build']['targets']['foo'] def test_target_config_not_table(self, isolation): config = {'tool': {'hatch': {'build': {'targets': {'foo': 'bar'}}}}} builder = BuilderInterface(str(isolation), config=config) builder.PLUGIN_NAME = 'foo' with pytest.raises(TypeError, match='Field `tool.hatch.build.targets.foo` must be a table'): _ = builder.target_config class TestProjectID: def test_normalization(self, isolation): config = {'project': {'name': 'my-app', 'version': '1.0.0-rc.1'}} builder = BuilderInterface(str(isolation), config=config) assert builder.project_id == builder.project_id == 'my_app-1.0.0rc1' class TestVersions: def test_build_validation(self, isolation): config = {'tool': {'hatch': {'build': {'targets': {'foo': {'versions': ['1']}}}}}} builder = BuilderInterface(str(isolation), config=config) builder.PLUGIN_NAME = 'foo' builder.get_version_api = lambda: {'1': str} with pytest.raises(ValueError, match='Unknown versions for target `foo`: 42, 9000'): next(builder.build(str(isolation), versions=['9000', '42'])) class TestHookConfig: def test_unknown(self, isolation): config = {'tool': {'hatch': {'build': {'hooks': {'foo': {'bar': 'baz'}}}}}} builder = BuilderInterface(str(isolation), config=config) with pytest.raises(ValueError, match='Unknown build hook: foo'): _ = builder.get_build_hooks(str(isolation)) class TestDirectoryRecursion: def test_order(self, temp_dir): with temp_dir.as_cwd(): config = { 'tool': { 'hatch': { 'build': { 'packages': ['src/foo'], 'include': ['bar', 'README.md', 'tox.ini'], 'exclude': ['**/foo/baz.txt'], } } } } builder = BuilderInterface(str(temp_dir), config=config) foo = temp_dir / 'src' / 'foo' foo.ensure_dir_exists() (foo / 'bar.txt').touch() (foo / 'baz.txt').touch() bar = temp_dir / 'bar' bar.ensure_dir_exists() (bar / 'foo.txt').touch() (temp_dir / 'README.md').touch() (temp_dir / 'tox.ini').touch() assert [(f.path, f.distribution_path) for f in builder.recurse_project_files()] == [ (str(temp_dir / 'README.md'), 'README.md'), (str(temp_dir / 'tox.ini'), 'tox.ini'), ( str(temp_dir / 'bar' / 'foo.txt'), f'bar{path_sep}foo.txt', ), (str(temp_dir / 'src' / 'foo' / 'bar.txt'), f'foo{path_sep}bar.txt'), ]
35.283237
115
0.60272
ace9ed6b801409d58bcf1fdd62c851d123d9fe2a
238
py
Python
examples/pxScene2d/external/breakpad-chrome_55/gyp/test/variables/commands/repeated_multidir/print_cwd_basename.py
madanagopaltcomcast/pxCore
c4a3a40a190521c8b6383d126c87612eca5b3c42
[ "Apache-2.0" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
examples/pxScene2d/external/breakpad-chrome_55/gyp/test/variables/commands/repeated_multidir/print_cwd_basename.py
madanagopaltcomcast/pxCore
c4a3a40a190521c8b6383d126c87612eca5b3c42
[ "Apache-2.0" ]
1,432
2017-06-21T04:08:48.000Z
2020-08-25T16:21:15.000Z
examples/pxScene2d/external/breakpad-chrome_55/gyp/test/variables/commands/repeated_multidir/print_cwd_basename.py
madanagopaltcomcast/pxCore
c4a3a40a190521c8b6383d126c87612eca5b3c42
[ "Apache-2.0" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
#!/usr/bin/env python # Copyright 2014 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import os.path print os.path.basename(os.getcwd())
21.636364
72
0.747899
ace9ee45a329d7b45390f527a7c424754c025873
4,267
py
Python
config/jobs/kubernetes/kops/build-pipeline.py
ACME-Corp-Demo/test-infra
93a922c56d4b27adf4b9138d33e928aa0c9dcdcf
[ "Apache-2.0" ]
null
null
null
config/jobs/kubernetes/kops/build-pipeline.py
ACME-Corp-Demo/test-infra
93a922c56d4b27adf4b9138d33e928aa0c9dcdcf
[ "Apache-2.0" ]
null
null
null
config/jobs/kubernetes/kops/build-pipeline.py
ACME-Corp-Demo/test-infra
93a922c56d4b27adf4b9138d33e928aa0c9dcdcf
[ "Apache-2.0" ]
null
null
null
# Copyright 2020 The Kubernetes Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json branches = [ "master", "1.19", "1.18", ] master_k8s_version = "1.20" template = """ # Verify the latest-ci version from the {{branch}} branch of kops # Runs a small subset of the e2e tests. # Publishes the version to latest-ci-updown-green on success. - interval: 60m name: {{name}} decorate: true decoration_config: timeout: 45m labels: preset-service-account: "true" preset-aws-ssh: "true" preset-aws-credential: "true" spec: containers: - image: {{e2e_image}} env: - name: KOPS_RUN_TOO_NEW_VERSION value: "1" command: - runner.sh - kubetest args: # Generic e2e test args - --up - --test - --down - --dump=$(ARTIFACTS) - --timeout=45m - --gcp-service-account=$(E2E_GOOGLE_APPLICATION_CREDENTIALS) # kops-specific test args - --deployment=kops - --provider=aws - --cluster={{name}}.test-cncf-aws.k8s.io - --kops-ssh-user=ubuntu - --kops-nodes=4 - --extract={{extract}} - --kops-state=s3://k8s-kops-prow/ - --kops-ssh-key=$(AWS_SSH_PRIVATE_KEY_FILE) - --kops-ssh-public-key=$(AWS_SSH_PUBLIC_KEY_FILE) # We don't have permission to write to gs://k8s-staging-kops - --kops-publish=gs://kops-ci/markers/{{branch}}/latest-ci-updown-green.txt # Published by the kops staging build jobs - --kops-version=https://storage.googleapis.com/k8s-staging-kops/kops/releases/markers/{{branch}}/latest-ci.txt #- --kops-kubernetes-version should be inferred by kubetest from --extract #- --kops-zone should be randomized by kubetest # Specific test args - --test_args=--ginkgo.focus=\\[k8s.io\\]\\sNetworking.*\\[Conformance\\] --ginkgo.skip=\\[Slow\\]|\\[Serial\\] - --ginkgo-parallel annotations: testgrid-dashboards: sig-cluster-lifecycle-kops, google-aws, kops-misc, kops-k8s-{{k8s_version}} testgrid-tab-name: {{tab}} """ def build_tests(branch, k8s_version): def expand(s): subs = {} if k8s_version: subs['k8s_version'] = k8s_version if branch: subs['branch'] = branch return s.format(**subs) if branch == 'master': extract = "release/latest-" + master_k8s_version e2e_image = "gcr.io/k8s-testimages/kubekins-e2e:v20201111-a263fd7-master" else: extract = expand("release/stable-{k8s_version}") # Hack to stop the autobumper getting confused e2e_image = "gcr.io/k8s-testimages/kubekins-e2e:v20201111-a263fd7-1.19" e2e_image = e2e_image[:-4] + k8s_version tab = expand('kops-pipeline-updown-{branch}') # Names must be valid pod and DNS names name = expand('e2e-kops-pipeline-updown-kops{branch}') name = name.replace('.', '') y = template y = y.replace('{{extract}}', extract) y = y.replace('{{e2e_image}}', e2e_image) y = y.replace('{{k8s_version}}', k8s_version) y = y.replace('{{name}}', name) y = y.replace('{{tab}}', tab) if branch == 'master': y = y.replace('{{branch}}', "master") else: y = y.replace('{{branch}}', "release-" + branch) spec = { 'branch': branch, 'k8s_version': k8s_version, } jsonspec = json.dumps(spec, sort_keys=True) print("") print("# " + jsonspec) print(y.strip()) def generate(): print("# Test scenarios generated by build-pipeline.py (do not manually edit)") print("periodics:") for branch in branches: k8s_version = master_k8s_version if branch == "master" else branch build_tests(branch=branch, k8s_version=k8s_version) generate()
32.325758
117
0.633232
ace9eee21e234d8c1ced73ddb834dfc2d18a6f8e
1,305
py
Python
src/state/State.py
itsSayantan/pyshop
30c7d0021e05cda253cf0d3d6d957f63bdf079e9
[ "MIT" ]
null
null
null
src/state/State.py
itsSayantan/pyshop
30c7d0021e05cda253cf0d3d6d957f63bdf079e9
[ "MIT" ]
null
null
null
src/state/State.py
itsSayantan/pyshop
30c7d0021e05cda253cf0d3d6d957f63bdf079e9
[ "MIT" ]
null
null
null
""" This class is responsible to store the entire state of the PyShop application. """ class State: """ The __state value should not be accessed directly, instead the get() method should be used. """ __state = { 'file_path_dict': { 'users': { 'file_path': './data/users.csv', 'template_file_path': './data/users.template.csv', }, 'products': { 'file_path': './data/products.csv', 'template_file_path': './data/products.template.csv', }, } } @classmethod def set_state(cls, part_of_the_state_to_be_updated): """ This method updates the state. This method does not overwrite the state completely. It checks whether the part_of_the_state_to_be_updated is there in the current state or not. If it is present, it will rewrite that part, else it will create a new entry in the top level of the state. """ for new_state_key in part_of_the_state_to_be_updated: cls.__state.setdefault( new_state_key, part_of_the_state_to_be_updated[new_state_key]) @classmethod def get(cls, key): return cls.__state.get(key)
31.829268
82
0.584674
ace9eeeb6158d9e7ecb0e5b15e2a4bb127dcc201
18,601
py
Python
Lib/distutils/command/sdist.py
orestis/python
870a82aac7788ffa105e2a3e4480b3715c93bff6
[ "PSF-2.0" ]
1
2021-12-26T22:20:34.000Z
2021-12-26T22:20:34.000Z
Lib/distutils/command/sdist.py
orestis/python
870a82aac7788ffa105e2a3e4480b3715c93bff6
[ "PSF-2.0" ]
null
null
null
Lib/distutils/command/sdist.py
orestis/python
870a82aac7788ffa105e2a3e4480b3715c93bff6
[ "PSF-2.0" ]
2
2018-08-06T04:37:38.000Z
2022-02-27T18:07:12.000Z
"""distutils.command.sdist Implements the Distutils 'sdist' command (create a source distribution).""" __revision__ = "$Id$" import os import string import sys from types import * from glob import glob from warnings import warn from distutils.core import Command from distutils import dir_util, dep_util, file_util, archive_util from distutils.text_file import TextFile from distutils.errors import * from distutils.filelist import FileList from distutils import log from distutils.util import convert_path def show_formats(): """Print all possible values for the 'formats' option (used by the "--help-formats" command-line option). """ from distutils.fancy_getopt import FancyGetopt from distutils.archive_util import ARCHIVE_FORMATS formats = [] for format in ARCHIVE_FORMATS.keys(): formats.append(("formats=" + format, None, ARCHIVE_FORMATS[format][2])) formats.sort() FancyGetopt(formats).print_help( "List of available source distribution formats:") class sdist(Command): description = "create a source distribution (tarball, zip file, etc.)" def checking_metadata(self): """Callable used for the check sub-command. Placed here so user_options can view it""" return self.metadata_check user_options = [ ('template=', 't', "name of manifest template file [default: MANIFEST.in]"), ('manifest=', 'm', "name of manifest file [default: MANIFEST]"), ('use-defaults', None, "include the default file set in the manifest " "[default; disable with --no-defaults]"), ('no-defaults', None, "don't include the default file set"), ('prune', None, "specifically exclude files/directories that should not be " "distributed (build tree, RCS/CVS dirs, etc.) " "[default; disable with --no-prune]"), ('no-prune', None, "don't automatically exclude anything"), ('manifest-only', 'o', "just regenerate the manifest and then stop " "(implies --force-manifest)"), ('force-manifest', 'f', "forcibly regenerate the manifest and carry on as usual"), ('formats=', None, "formats for source distribution (comma-separated list)"), ('keep-temp', 'k', "keep the distribution tree around after creating " + "archive file(s)"), ('dist-dir=', 'd', "directory to put the source distribution archive(s) in " "[default: dist]"), ('medata-check', None, "Ensure that all required elements of meta-data " "are supplied. Warn if any missing. [default]"), ] boolean_options = ['use-defaults', 'prune', 'manifest-only', 'force-manifest', 'keep-temp', 'metadata-check'] help_options = [ ('help-formats', None, "list available distribution formats", show_formats), ] negative_opt = {'no-defaults': 'use-defaults', 'no-prune': 'prune' } default_format = {'posix': 'gztar', 'nt': 'zip' } sub_commands = [('check', checking_metadata)] def initialize_options(self): # 'template' and 'manifest' are, respectively, the names of # the manifest template and manifest file. self.template = None self.manifest = None # 'use_defaults': if true, we will include the default file set # in the manifest self.use_defaults = 1 self.prune = 1 self.manifest_only = 0 self.force_manifest = 0 self.formats = None self.keep_temp = 0 self.dist_dir = None self.archive_files = None self.metadata_check = 1 def finalize_options(self): if self.manifest is None: self.manifest = "MANIFEST" if self.template is None: self.template = "MANIFEST.in" self.ensure_string_list('formats') if self.formats is None: try: self.formats = [self.default_format[os.name]] except KeyError: raise DistutilsPlatformError( "don't know how to create source distributions " "on platform %s" % os.name) bad_format = archive_util.check_archive_formats(self.formats) if bad_format: raise DistutilsOptionError( "unknown archive format '%s'" % bad_format) if self.dist_dir is None: self.dist_dir = "dist" def run(self): # 'filelist' contains the list of files that will make up the # manifest self.filelist = FileList() # Run sub commands for cmd_name in self.get_sub_commands(): self.run_command(cmd_name) # Do whatever it takes to get the list of files to process # (process the manifest template, read an existing manifest, # whatever). File list is accumulated in 'self.filelist'. self.get_file_list() # If user just wanted us to regenerate the manifest, stop now. if self.manifest_only: return # Otherwise, go ahead and create the source distribution tarball, # or zipfile, or whatever. self.make_distribution() def check_metadata(self): """Deprecated API.""" warn("distutils.command.sdist.check_metadata is deprecated, \ use the check command instead", PendingDeprecationWarning) check = self.distribution.get_command_obj('check') check.ensure_finalized() check.run() def get_file_list(self): """Figure out the list of files to include in the source distribution, and put it in 'self.filelist'. This might involve reading the manifest template (and writing the manifest), or just reading the manifest, or just using the default file set -- it all depends on the user's options and the state of the filesystem. """ # If we have a manifest template, see if it's newer than the # manifest; if so, we'll regenerate the manifest. template_exists = os.path.isfile(self.template) if template_exists: template_newer = dep_util.newer(self.template, self.manifest) # The contents of the manifest file almost certainly depend on the # setup script as well as the manifest template -- so if the setup # script is newer than the manifest, we'll regenerate the manifest # from the template. (Well, not quite: if we already have a # manifest, but there's no template -- which will happen if the # developer elects to generate a manifest some other way -- then we # can't regenerate the manifest, so we don't.) self.debug_print("checking if %s newer than %s" % (self.distribution.script_name, self.manifest)) setup_newer = dep_util.newer(self.distribution.script_name, self.manifest) # cases: # 1) no manifest, template exists: generate manifest # (covered by 2a: no manifest == template newer) # 2) manifest & template exist: # 2a) template or setup script newer than manifest: # regenerate manifest # 2b) manifest newer than both: # do nothing (unless --force or --manifest-only) # 3) manifest exists, no template: # do nothing (unless --force or --manifest-only) # 4) no manifest, no template: generate w/ warning ("defaults only") manifest_outofdate = (template_exists and (template_newer or setup_newer)) force_regen = self.force_manifest or self.manifest_only manifest_exists = os.path.isfile(self.manifest) neither_exists = (not template_exists and not manifest_exists) # Regenerate the manifest if necessary (or if explicitly told to) if manifest_outofdate or neither_exists or force_regen: if not template_exists: self.warn("manifest template '%s' does not exist " "(using default file list)" % self.template) self.filelist.findall() if self.use_defaults: self.add_defaults() if template_exists: self.read_template() if self.prune: self.prune_file_list() self.filelist.sort() self.filelist.remove_duplicates() self.write_manifest() # Don't regenerate the manifest, just read it in. else: self.read_manifest() def add_defaults(self): """Add all the default files to self.filelist: - README or README.txt - setup.py - test/test*.py - all pure Python modules mentioned in setup script - all files pointed by package_data (build_py) - all files defined in data_files. - all files defined as scripts. - all C sources listed as part of extensions or C libraries in the setup script (doesn't catch C headers!) Warns if (README or README.txt) or setup.py are missing; everything else is optional. """ standards = [('README', 'README.txt'), self.distribution.script_name] for fn in standards: if isinstance(fn, tuple): alts = fn got_it = False for fn in alts: if os.path.exists(fn): got_it = True self.filelist.append(fn) break if not got_it: self.warn("standard file not found: should have one of " + ', '.join(alts)) else: if os.path.exists(fn): self.filelist.append(fn) else: self.warn("standard file '%s' not found" % fn) optional = ['test/test*.py', 'setup.cfg'] for pattern in optional: files = filter(os.path.isfile, glob(pattern)) if files: self.filelist.extend(files) # build_py is used to get: # - python modules # - files defined in package_data build_py = self.get_finalized_command('build_py') # getting python files if self.distribution.has_pure_modules(): self.filelist.extend(build_py.get_source_files()) # getting package_data files # (computed in build_py.data_files by build_py.finalize_options) for pkg, src_dir, build_dir, filenames in build_py.data_files: for filename in filenames: self.filelist.append(os.path.join(src_dir, filename)) # getting distribution.data_files if self.distribution.has_data_files(): for item in self.distribution.data_files: if isinstance(item, str): # plain file item = convert_path(item) if os.path.isfile(item): self.filelist.append(item) else: # a (dirname, filenames) tuple dirname, filenames = item for f in filenames: f = convert_path(f) if os.path.isfile(f): self.filelist.append(f) if self.distribution.has_ext_modules(): build_ext = self.get_finalized_command('build_ext') self.filelist.extend(build_ext.get_source_files()) if self.distribution.has_c_libraries(): build_clib = self.get_finalized_command('build_clib') self.filelist.extend(build_clib.get_source_files()) if self.distribution.has_scripts(): build_scripts = self.get_finalized_command('build_scripts') self.filelist.extend(build_scripts.get_source_files()) def read_template(self): """Read and parse manifest template file named by self.template. (usually "MANIFEST.in") The parsing and processing is done by 'self.filelist', which updates itself accordingly. """ log.info("reading manifest template '%s'", self.template) template = TextFile(self.template, strip_comments=1, skip_blanks=1, join_lines=1, lstrip_ws=1, rstrip_ws=1, collapse_join=1) while True: line = template.readline() if line is None: # end of file break try: self.filelist.process_template_line(line) except DistutilsTemplateError as msg: self.warn("%s, line %d: %s" % (template.filename, template.current_line, msg)) def prune_file_list(self): """Prune off branches that might slip into the file list as created by 'read_template()', but really don't belong there: * the build tree (typically "build") * the release tree itself (only an issue if we ran "sdist" previously with --keep-temp, or it aborted) * any RCS, CVS, .svn, .hg, .git, .bzr, _darcs directories """ build = self.get_finalized_command('build') base_dir = self.distribution.get_fullname() self.filelist.exclude_pattern(None, prefix=build.build_base) self.filelist.exclude_pattern(None, prefix=base_dir) if sys.platform == 'win32': seps = r'/|\\' else: seps = '/' vcs_dirs = ['RCS', 'CVS', r'\.svn', r'\.hg', r'\.git', r'\.bzr', '_darcs'] vcs_ptrn = r'(^|%s)(%s)(%s).*' % (seps, '|'.join(vcs_dirs), seps) self.filelist.exclude_pattern(vcs_ptrn, is_regex=1) def write_manifest(self): """Write the file list in 'self.filelist' (presumably as filled in by 'add_defaults()' and 'read_template()') to the manifest file named by 'self.manifest'. """ self.execute(file_util.write_file, (self.manifest, self.filelist.files), "writing manifest file '%s'" % self.manifest) def read_manifest(self): """Read the manifest file (named by 'self.manifest') and use it to fill in 'self.filelist', the list of files to include in the source distribution. """ log.info("reading manifest file '%s'", self.manifest) manifest = open(self.manifest) while True: line = manifest.readline() if line == '': # end of file break if line[-1] == '\n': line = line[0:-1] self.filelist.append(line) manifest.close() def make_release_tree(self, base_dir, files): """Create the directory tree that will become the source distribution archive. All directories implied by the filenames in 'files' are created under 'base_dir', and then we hard link or copy (if hard linking is unavailable) those files into place. Essentially, this duplicates the developer's source tree, but in a directory named after the distribution, containing only the files to be distributed. """ # Create all the directories under 'base_dir' necessary to # put 'files' there; the 'mkpath()' is just so we don't die # if the manifest happens to be empty. self.mkpath(base_dir) dir_util.create_tree(base_dir, files, dry_run=self.dry_run) # And walk over the list of files, either making a hard link (if # os.link exists) to each one that doesn't already exist in its # corresponding location under 'base_dir', or copying each file # that's out-of-date in 'base_dir'. (Usually, all files will be # out-of-date, because by default we blow away 'base_dir' when # we're done making the distribution archives.) if hasattr(os, 'link'): # can make hard links on this system link = 'hard' msg = "making hard links in %s..." % base_dir else: # nope, have to copy link = None msg = "copying files to %s..." % base_dir if not files: log.warn("no files to distribute -- empty manifest?") else: log.info(msg) for file in files: if not os.path.isfile(file): log.warn("'%s' not a regular file -- skipping" % file) else: dest = os.path.join(base_dir, file) self.copy_file(file, dest, link=link) self.distribution.metadata.write_pkg_info(base_dir) def make_distribution(self): """Create the source distribution(s). First, we create the release tree with 'make_release_tree()'; then, we create all required archive files (according to 'self.formats') from the release tree. Finally, we clean up by blowing away the release tree (unless 'self.keep_temp' is true). The list of archive files created is stored so it can be retrieved later by 'get_archive_files()'. """ # Don't warn about missing meta-data here -- should be (and is!) # done elsewhere. base_dir = self.distribution.get_fullname() base_name = os.path.join(self.dist_dir, base_dir) self.make_release_tree(base_dir, self.filelist.files) archive_files = [] # remember names of files we create # tar archive must be created last to avoid overwrite and remove if 'tar' in self.formats: self.formats.append(self.formats.pop(self.formats.index('tar'))) for fmt in self.formats: file = self.make_archive(base_name, fmt, base_dir=base_dir) archive_files.append(file) self.distribution.dist_files.append(('sdist', '', file)) self.archive_files = archive_files if not self.keep_temp: dir_util.remove_tree(base_dir, dry_run=self.dry_run) def get_archive_files(self): """Return the list of archive files created when the command was run, or None if the command hasn't run yet. """ return self.archive_files
39.916309
78
0.588624
ace9ef1f63e29f1c5f9fdad073b7171a3b3356a4
6,579
py
Python
YOLO/yolov3_asff_pt/models/yolov3_baseline.py
ForrestPi/ObjectDetection
54e0821e73f67be5360c36f01229a123c34ab3b3
[ "MIT" ]
12
2020-03-25T01:24:22.000Z
2021-09-18T06:40:16.000Z
YOLO/yolov3_asff_pt/models/yolov3_baseline.py
ForrestPi/ObjectDetection
54e0821e73f67be5360c36f01229a123c34ab3b3
[ "MIT" ]
1
2020-04-22T07:52:36.000Z
2020-04-22T07:52:36.000Z
YOLO/yolov3_asff_pt/models/yolov3_baseline.py
ForrestPi/ObjectDetection
54e0821e73f67be5360c36f01229a123c34ab3b3
[ "MIT" ]
4
2020-03-25T01:24:26.000Z
2020-09-20T11:29:09.000Z
import torch import torch.nn as nn import torch.nn.functional as F from collections import defaultdict from .network_blocks import * from .yolov3_head import YOLOv3Head def create_yolov3_modules(num_classes, ignore_thre, label_smooth, rfb): """ Build yolov3 layer modules. Args: ignore_thre (float): used in YOLOLayer. Returns: mlist (ModuleList): YOLOv3 module list. """ # DarkNet53 mlist = nn.ModuleList() mlist.append(add_conv(in_ch=3, out_ch=32, ksize=3, stride=1)) #0 mlist.append(add_conv(in_ch=32, out_ch=64, ksize=3, stride=2)) #1 mlist.append(resblock(ch=64)) #2 mlist.append(add_conv(in_ch=64, out_ch=128, ksize=3, stride=2)) #3 mlist.append(resblock(ch=128, nblocks=2)) #4 mlist.append(add_conv(in_ch=128, out_ch=256, ksize=3, stride=2)) #5 mlist.append(resblock(ch=256, nblocks=8)) # shortcut 1 from here #6 mlist.append(add_conv(in_ch=256, out_ch=512, ksize=3, stride=2)) #7 mlist.append(resblock(ch=512, nblocks=8)) # shortcut 2 from here #8 mlist.append(add_conv(in_ch=512, out_ch=1024, ksize=3, stride=2)) #9 mlist.append(resblock(ch=1024, nblocks=4)) #10 # YOLOv3 mlist.append(resblock(ch=1024, nblocks=1, shortcut=False)) #11 mlist.append(add_conv(in_ch=1024, out_ch=512, ksize=1, stride=1)) #12 #SPP Layer mlist.append(SPPLayer()) #13 mlist.append(add_conv(in_ch=2048, out_ch=512, ksize=1, stride=1)) #14 mlist.append(add_conv(in_ch=512, out_ch=1024, ksize=3, stride=1)) #15 mlist.append(DropBlock(block_size=1, keep_prob=1.0)) #16 mlist.append(add_conv(in_ch=1024, out_ch=512, ksize=1, stride=1)) #17 # 1st yolo branch mlist.append(add_conv(in_ch=512, out_ch=1024, ksize=3, stride=1)) #18 mlist.append( YOLOv3Head(anch_mask=[6, 7, 8], n_classes=num_classes, stride=32, in_ch=1024, ignore_thre=ignore_thre,label_smooth = label_smooth, rfb=rfb)) #19 mlist.append(add_conv(in_ch=512, out_ch=256, ksize=1, stride=1)) #20 mlist.append(upsample(scale_factor=2, mode='nearest')) #21 mlist.append(add_conv(in_ch=768, out_ch=256, ksize=1, stride=1)) #22 mlist.append(add_conv(in_ch=256, out_ch=512, ksize=3, stride=1)) #23 mlist.append(DropBlock(block_size=1, keep_prob=1.0)) #24 mlist.append(resblock(ch=512, nblocks=1, shortcut=False)) #25 mlist.append(add_conv(in_ch=512, out_ch=256, ksize=1, stride=1)) #26 # 2nd yolo branch mlist.append(add_conv(in_ch=256, out_ch=512, ksize=3, stride=1)) #27 mlist.append( YOLOv3Head(anch_mask=[3, 4, 5], n_classes=num_classes, stride=16, in_ch=512, ignore_thre=ignore_thre, label_smooth = label_smooth, rfb=rfb)) #28 mlist.append(add_conv(in_ch=256, out_ch=128, ksize=1, stride=1)) #29 mlist.append(upsample(scale_factor=2, mode='nearest')) #30 mlist.append(add_conv(in_ch=384, out_ch=128, ksize=1, stride=1)) #31 mlist.append(add_conv(in_ch=128, out_ch=256, ksize=3, stride=1)) #32 mlist.append(DropBlock(block_size=1, keep_prob=1.0)) #33 mlist.append(resblock(ch=256, nblocks=1, shortcut=False)) #34 mlist.append(add_conv(in_ch=256, out_ch=128, ksize=1, stride=1)) #35 mlist.append(add_conv(in_ch=128, out_ch=256, ksize=3, stride=1)) #36 mlist.append( YOLOv3Head(anch_mask=[0, 1, 2], n_classes=num_classes, stride=8, in_ch=256, ignore_thre=ignore_thre, label_smooth = label_smooth, rfb=rfb)) #37 return mlist class YOLOv3(nn.Module): """ YOLOv3 model module. The module list is defined by create_yolov3_modules function. \ The network returns loss values from three YOLO layers during training \ and detection results during test. """ def __init__(self, num_classes = 80, ignore_thre=0.7, label_smooth = False, rfb=False): super(YOLOv3, self).__init__() self.module_list = create_yolov3_modules(num_classes, ignore_thre, label_smooth, rfb) def forward(self, x, targets=None, epoch=0): train = targets is not None output = [] anchor_losses= [] iou_losses = [] l1_losses = [] conf_losses = [] cls_losses = [] route_layers = [] for i, module in enumerate(self.module_list): # yolo layers if i in [19, 28, 37]: if train: x, anchor_loss, iou_loss, l1_loss, conf_loss, cls_loss = module(x, targets) anchor_losses.append(anchor_loss) iou_losses.append(iou_loss) l1_losses.append(l1_loss) conf_losses.append(conf_loss) cls_losses.append(cls_loss) else: x = module(x) output.append(x) else: x = module(x) # route layers if i in [6, 8, 17, 26]: route_layers.append(x) if i == 19: x = route_layers[2] if i == 28: # yolo 2nd x = route_layers[3] if i == 21: x = torch.cat((x, route_layers[1]), 1) if i == 30: x = torch.cat((x, route_layers[0]), 1) if train: losses = torch.stack(output, 0).unsqueeze(0).sum(1,keepdim=True) anchor_losses = torch.stack(anchor_losses, 0).unsqueeze(0).sum(1,keepdim=True) iou_losses = torch.stack(iou_losses, 0).unsqueeze(0).sum(1,keepdim=True) l1_losses = torch.stack(l1_losses, 0).unsqueeze(0).sum(1,keepdim=True) conf_losses = torch.stack(conf_losses, 0).unsqueeze(0).sum(1,keepdim=True) cls_losses = torch.stack(cls_losses, 0).unsqueeze(0).sum(1,keepdim=True) loss_dict = dict( losses = losses, anchor_losses = anchor_losses, iou_losses = iou_losses, l1_losses = l1_losses, conf_losses = conf_losses, cls_losses = cls_losses, ) return loss_dict else: return torch.cat(output, 1)
45.6875
95
0.576227
ace9f04de15d15dbbaf047cfefd79d16b47e451c
18,784
py
Python
main.py
MerHS/SASA-pytorch
7d113852dce2e25d4de23caf87ad7d33758c322e
[ "MIT" ]
47
2019-06-29T13:54:35.000Z
2022-01-28T07:06:16.000Z
main.py
MerHS/SASA-pytorch
7d113852dce2e25d4de23caf87ad7d33758c322e
[ "MIT" ]
5
2019-06-28T10:30:09.000Z
2020-03-26T16:42:25.000Z
main.py
MerHS/SASA-pytorch
7d113852dce2e25d4de23caf87ad7d33758c322e
[ "MIT" ]
10
2019-07-01T05:16:24.000Z
2020-10-09T01:53:01.000Z
""" Original Code: https://github.com/pytorch/examples/blob/master/imagenet/main.py """ import argparse import os import random import shutil import time import warnings import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.distributed as dist import torch.optim import torch.optim.lr_scheduler as lr_sched import torch.multiprocessing as mp import torch.utils.data import torch.utils.data.distributed import torchvision.transforms as transforms import torchvision.datasets as datasets import torchvision.models as models import model.sa_resnet as sa_resnet from SGDR import LinearWarmupScheduler model_names = list(sorted(name for name in models.__dict__ if name.islower() and not name.startswith("__") and callable(models.__dict__[name]))) all_model_names = sa_resnet.model_names + model_names dataset_dict = { 'cifar10': (10, [0.4914, 0.4822, 0.4465], [0.247, 0.243, 0.261]), 'cifar100': (100, [0.4914, 0.4822, 0.4465], [0.247, 0.243, 0.261]), 'imagenet': (1000, [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) } parser = argparse.ArgumentParser(description='PyTorch ImageNet Training with SASA') parser.add_argument('--data_path', default='data', help='path to dataset directory') parser.add_argument('--dataset', metavar='DATASET', default='imagenet', choices=list(dataset_dict.keys()), help='dataset to train/val') parser.add_argument('-a', '--arch', metavar='ARCH', default='cstem_sa_resnet50', choices=all_model_names, help='model architecture: ' + ' | '.join(all_model_names) + ' (default: cstem_sa_resnet50)') parser.add_argument('--width', default=224, type=int, help='height/width of input image') parser.add_argument('-j', '--workers', default=4, type=int, metavar='N', help='number of data loading workers (default: 4)') parser.add_argument('--epochs', default=90, type=int, metavar='N', help='number of total epochs to run') parser.add_argument('--start-epoch', default=0, type=int, metavar='N', help='manual epoch number (useful on restarts)') parser.add_argument('-b', '--batch-size', default=64, type=int, metavar='N', help='mini-batch size (default: 256), this is the total ' 'batch size of all GPUs on the current node when ' 'using Data Parallel or Distributed Data Parallel') parser.add_argument('--lr', '--learning-rate', default=0.1, type=float, metavar='LR', help='initial learning rate', dest='lr') parser.add_argument('--momentum', default=0.9, type=float, metavar='M', help='momentum') parser.add_argument('--wd', '--weight-decay', default=1e-4, type=float, metavar='W', help='weight decay (default: 1e-4)', dest='weight_decay') parser.add_argument('-p', '--print-freq', default=10, type=int, metavar='N', help='print frequency (default: 10)') parser.add_argument('--resume', default='', type=str, metavar='PATH', help='path to latest checkpoint (default: none)') parser.add_argument('-e', '--evaluate', dest='evaluate', action='store_true', help='evaluate model on validation set') parser.add_argument('--pretrained', dest='pretrained', action='store_true', help='use pre-trained model') parser.add_argument('--world-size', default=-1, type=int, help='number of nodes for distributed training') parser.add_argument('--rank', default=-1, type=int, help='node rank for distributed training') parser.add_argument('--dist-url', default='tcp://224.66.41.62:23456', type=str, help='url used to set up distributed training') parser.add_argument('--dist-backend', default='nccl', type=str, help='distributed backend') parser.add_argument('--seed', default=None, type=int, help='seed for initializing training. ') parser.add_argument('--gpu', default=None, type=int, help='GPU id to use.') parser.add_argument('--cpu', action='store_true', help='Use CPU only') parser.add_argument('--multiprocessing-distributed', action='store_true', help='Use multi-processing distributed training to launch ' 'N processes per node, which has N GPUs. This is the ' 'fastest way to use PyTorch for either single node or ' 'multi node data parallel training') best_acc1 = 0 def main(): args = parser.parse_args() if args.seed is not None: random.seed(args.seed) torch.manual_seed(args.seed) if not args.cpu: cudnn.deterministic = True warnings.warn('You have chosen to seed training. ' 'This will turn on the CUDNN deterministic setting, ' 'which can slow down your training considerably! ' 'You may see unexpected behavior when restarting ' 'from checkpoints.') if args.gpu is not None: warnings.warn('You have chosen a specific GPU. This will completely ' 'disable data parallelism.') if args.dist_url == "env://" and args.world_size == -1: args.world_size = int(os.environ["WORLD_SIZE"]) args.distributed = args.world_size > 1 or args.multiprocessing_distributed ngpus_per_node = torch.cuda.device_count() if args.multiprocessing_distributed: # Since we have ngpus_per_node processes per node, the total world_size # needs to be adjusted accordingly args.world_size = ngpus_per_node * args.world_size # Use torch.multiprocessing.spawn to launch distributed processes: the # main_worker process function mp.spawn(main_worker, nprocs=ngpus_per_node, args=(ngpus_per_node, args)) else: # Simply call main_worker function main_worker(args.gpu, ngpus_per_node, args) def main_worker(gpu, ngpus_per_node, args): global best_acc1 args.gpu = gpu if args.gpu is not None: print("Use GPU: {} for training".format(args.gpu)) if args.distributed: if args.dist_url == "env://" and args.rank == -1: args.rank = int(os.environ["RANK"]) if args.multiprocessing_distributed: # For multiprocessing distributed training, rank needs to be the # global rank among all the processes args.rank = args.rank * ngpus_per_node + gpu dist.init_process_group(backend=args.dist_backend, init_method=args.dist_url, world_size=args.world_size, rank=args.rank) # create model num_classes, dataset_mean, dataset_std = dataset_dict[args.dataset] if args.arch not in model_names: print("=> creating model '{}'".format(args.arch)) model = sa_resnet.get_model(args, num_classes=num_classes) else: if args.pretrained: if args.dataset != 'imagenet': raise Exception('cannot download non-imagenet pretrained model') print("=> using pre-trained model '{}'".format(args.arch)) model = models.__dict__[args.arch](pretrained=True) else: print("=> creating model '{}'".format(args.arch)) model = models.__dict__[args.arch](num_classes=num_classes) if args.distributed: # For multiprocessing distributed, DistributedDataParallel constructor # should always set the single device scope, otherwise, # DistributedDataParallel will use all available devices. if args.gpu is not None: torch.cuda.set_device(args.gpu) model.cuda(args.gpu) # When using a single GPU per process and per # DistributedDataParallel, we need to divide the batch size # ourselves based on the total number of GPUs we have args.batch_size = int(args.batch_size / ngpus_per_node) args.workers = int(args.workers / ngpus_per_node) model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu]) else: model.cuda() # DistributedDataParallel will divide and allocate batch_size to all # available GPUs if device_ids are not set model = torch.nn.parallel.DistributedDataParallel(model) elif args.gpu is not None: torch.cuda.set_device(args.gpu) model = model.cuda(args.gpu) else: # DataParallel will divide and allocate batch_size to all available GPUs if args.arch.startswith('alexnet') or args.arch.startswith('vgg'): model.features = torch.nn.DataParallel(model.features) else: model = torch.nn.DataParallel(model) if not args.cpu: model = model.cuda() print("model param #: {}".format(sum(p.numel() for p in model.parameters()))) # define loss function (criterion) and optimizer criterion = nn.CrossEntropyLoss() if not args.cpu: criterion = criterion.cuda(args.gpu) optimizer = torch.optim.SGD(model.parameters(), args.lr, momentum=args.momentum, weight_decay=args.weight_decay) # loss scheduler scheduler = LinearWarmupScheduler(optimizer, 10, lr_sched.CosineAnnealingLR(optimizer, args.epochs)) # optionally resume from a checkpoint if args.resume: if os.path.isfile(args.resume): print("=> loading checkpoint '{}'".format(args.resume)) checkpoint = torch.load(args.resume) args.start_epoch = checkpoint['epoch'] best_acc1 = checkpoint['best_acc1'] if args.gpu is not None: # best_acc1 may be from a checkpoint from a different GPU best_acc1 = best_acc1.to(args.gpu) model.load_state_dict(checkpoint['state_dict']) optimizer.load_state_dict(checkpoint['optimizer']) print("=> loaded checkpoint '{}' (epoch {})" .format(args.resume, checkpoint['epoch'])) scheduler = LinearWarmupScheduler(optimizer, total_epoch=10, after_scheduler=lr_sched.CosineAnnealingLR(optimizer, args.epochs), last_epoch=checkpoint['epoch']) else: print("=> no checkpoint found at '{}'".format(args.resume)) if not args.cpu: cudnn.benchmark = True # Data loading code traindir = os.path.join(args.data_path, 'train') valdir = os.path.join(args.data_path, 'val') if not os.path.exists(args.data_path): os.mkdir(args.data_path) if not os.path.exists(traindir): os.mkdir(traindir) if not os.path.exists(valdir): os.mkdir(valdir) normalize = transforms.Normalize(mean=dataset_mean, std=dataset_std) train_transform = transforms.Compose([ transforms.RandomResizedCrop(args.width), transforms.RandomHorizontalFlip(), transforms.ToTensor(), normalize, ]) val_transform = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(args.width), transforms.ToTensor(), normalize, ]) if args.dataset == 'cifar10': train_dataset = datasets.CIFAR10(traindir, train=True, download=True, transform=train_transform) elif args.dataset == 'cifar100': train_dataset = datasets.CIFAR100(traindir, train=True, download=True, transform=train_transform) else: train_dataset = datasets.ImageNet(traindir, split='train', download=True, transform=train_transform) if args.distributed: train_sampler = torch.utils.data.distributed.DistributedSampler(train_dataset) else: train_sampler = None train_loader = torch.utils.data.DataLoader( train_dataset, batch_size=args.batch_size, shuffle=(train_sampler is None), num_workers=args.workers, pin_memory=True, sampler=train_sampler) if args.dataset == 'cifar10': val_dataset = datasets.CIFAR10(valdir, train=False, download=True, transform=val_transform) elif args.dataset == 'cifar100': val_dataset = datasets.CIFAR100(valdir, train=False, download=True, transform=val_transform) else: val_dataset = datasets.ImageNet(valdir, split='val', download=True, transform=val_transform) val_loader = torch.utils.data.DataLoader( val_dataset, batch_size=args.batch_size, shuffle=False, num_workers=args.workers, pin_memory=True) if args.evaluate: validate(val_loader, model, criterion, args) return for epoch in range(args.start_epoch, args.epochs): scheduler.step() if args.distributed: train_sampler.set_epoch(epoch) # train for one epoch train(train_loader, model, criterion, optimizer, epoch, args) # evaluate on validation set acc1 = validate(val_loader, model, criterion, args) # remember best acc@1 and save checkpoint is_best = acc1 > best_acc1 best_acc1 = max(acc1, best_acc1) if not args.multiprocessing_distributed or (args.multiprocessing_distributed and args.rank % ngpus_per_node == 0): save_checkpoint({ 'epoch': epoch + 1, 'arch': args.arch, 'state_dict': model.state_dict(), 'best_acc1': best_acc1, 'optimizer' : optimizer.state_dict(), }, is_best) def train(train_loader, model, criterion, optimizer, epoch, args): batch_time = AverageMeter('Time', ':6.3f') data_time = AverageMeter('Data', ':6.3f') losses = AverageMeter('Loss', ':.4e') top1 = AverageMeter('Acc@1', ':6.2f') top5 = AverageMeter('Acc@5', ':6.2f') progress = ProgressMeter( len(train_loader), [batch_time, data_time, losses, top1, top5], prefix="Epoch: [{}]".format(epoch)) # switch to train mode model.train() end = time.time() for i, (images, target) in enumerate(train_loader): # measure data loading time data_time.update(time.time() - end) if not args.cpu: if args.gpu is not None: images = images.cuda(args.gpu, non_blocking=True) target = target.cuda(args.gpu, non_blocking=True) # compute output output = model(images) loss = criterion(output, target) # measure accuracy and record loss [acc1, acc5] = accuracy(output, target, topk=(1, 5)) losses.update(loss.item(), images.size(0)) top1.update(acc1[0], images.size(0)) top5.update(acc5[0], images.size(0)) # compute gradient and do SGD step optimizer.zero_grad() loss.backward() optimizer.step() # measure elapsed time batch_time.update(time.time() - end) end = time.time() if i % args.print_freq == 0: progress.display(i) def validate(val_loader, model, criterion, args): batch_time = AverageMeter('Time', ':6.3f') losses = AverageMeter('Loss', ':.4e') top1 = AverageMeter('Acc@1', ':6.2f') top5 = AverageMeter('Acc@5', ':6.2f') progress = ProgressMeter( len(val_loader), [batch_time, losses, top1, top5], prefix='Test: ') # switch to evaluate mode model.eval() with torch.no_grad(): end = time.time() for i, (images, target) in enumerate(val_loader): if not args.cpu: if args.gpu is not None: images = images.cuda(args.gpu, non_blocking=True) target = target.cuda(args.gpu, non_blocking=True) # compute output output = model(images) loss = criterion(output, target) # measure accuracy and record loss [acc1, acc5] = accuracy(output, target, topk=(1, 5)) losses.update(loss.item(), images.size(0)) top1.update(acc1[0], images.size(0)) top5.update(acc5[0], images.size(0)) # measure elapsed time batch_time.update(time.time() - end) end = time.time() if i % args.print_freq == 0: progress.display(i) # TODO: this should also be done with the ProgressMeter print(' * Acc@1 {top1.avg:.3f} Acc@5 {top5.avg:.3f}' .format(top1=top1, top5=top5)) return top1.avg def save_checkpoint(state, is_best, filename='checkpoint.pth.tar'): torch.save(state, filename) if is_best: shutil.copyfile(filename, 'model_best.pth.tar') class AverageMeter(object): """Computes and stores the average and current value""" def __init__(self, name, fmt=':f'): self.name = name self.fmt = fmt self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count def __str__(self): fmtstr = '{name} {val' + self.fmt + '} ({avg' + self.fmt + '})' return fmtstr.format(**self.__dict__) class ProgressMeter(object): def __init__(self, num_batches, meters, prefix=""): self.batch_fmtstr = self._get_batch_fmtstr(num_batches) self.meters = meters self.prefix = prefix def display(self, batch): entries = [self.prefix + self.batch_fmtstr.format(batch)] entries += [str(meter) for meter in self.meters] print('\t'.join(entries)) def _get_batch_fmtstr(self, num_batches): num_digits = len(str(num_batches // 1)) fmt = '{:' + str(num_digits) + 'd}' return '[' + fmt + '/' + fmt.format(num_batches) + ']' def accuracy(output, target, topk=(1,)): """Computes the accuracy over the k top predictions for the specified values of k""" with torch.no_grad(): maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, -1).expand_as(pred)) res = [] for k in topk: correct_k = correct[:k].view(-1).float().sum(0, keepdim=True) res.append(correct_k.mul_(100.0 / batch_size)) return res if __name__ == '__main__': main()
39.051975
113
0.615524
ace9f0a1b6502a969345bb438d7ca78db181d582
6,903
py
Python
src/prefect/contrib/tasks/mysql/mysql.py
LuisMuniz/prefect
bda761ff20273f5bb9013ee4a418fa595bf7fc39
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/prefect/contrib/tasks/mysql/mysql.py
LuisMuniz/prefect
bda761ff20273f5bb9013ee4a418fa595bf7fc39
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/prefect/contrib/tasks/mysql/mysql.py
LuisMuniz/prefect
bda761ff20273f5bb9013ee4a418fa595bf7fc39
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
from prefect import Task from prefect.utilities.tasks import defaults_from_attrs import pymysql.cursors import logging from typing import Any class MySQLExecute(Task): """ Task for executing a query against a MySQL database. Args: - db_name (str): name of MySQL database - user (str): user name used to authenticate - password (str): password used to authenticate - host (str): database host address - port (int, optional): port used to connect to MySQL database, defaults to 3307 if not provided - query (str, optional): query to execute against database - commit (bool, optional): set to True to commit transaction, defaults to false - charset (str, optional): charset you want to use (defaults to utf8mb4) - **kwargs (Any, optional): additional keyword arguments to pass to the Task constructor """ def __init__( self, db_name: str, user: str, password: str, host: str, port: int = 3307, query: str = None, commit: bool = False, charset: str = "utf8mb4", **kwargs: Any ): self.db_name = db_name self.user = user self.password = password self.host = host self.port = port self.query = query self.commit = commit self.charset = charset super().__init__(**kwargs) @defaults_from_attrs("query", "commit", "charset") def run( self, query: str = None, commit: bool = False, charset: str = "utf8mb4", ) -> int: """ Task run method. Executes a query against MySQL database. Args: - query (str, optional): query to execute against database - commit (bool, optional): set to True to commit transaction, defaults to False - charset (str, optional): charset of the query, defaults to "utf8mb4" Returns: - executed (int): number of affected rows Raises: - pymysql.MySQLError """ if not query: raise ValueError("A query string must be provided") conn = pymysql.connect( host=self.host, user=self.user, password=self.password, db=self.db_name, charset=self.charset, ) try: with conn: with conn.cursor() as cursor: executed = cursor.execute(query) if commit: conn.commit() conn.close() logging.debug("Execute Results: ", executed) return executed except (Exception, pymysql.MySQLError) as e: conn.close() logging.debug("Execute Error: ", e) raise e class MySQLFetch(Task): """ Task for fetching results of query from MySQL database. Args: - db_name (str): name of MySQL database - user (str): user name used to authenticate - password (str): password used to authenticate - host (str): database host address - port (int, optional): port used to connect to MySQL database, defaults to 3307 if not provided - fetch (str, optional): one of "one" "many" or "all", used to determine how many results to fetch from executed query - fetch_count (int, optional): if fetch = 'many', determines the number of results to fetch, defaults to 10 - query (str, optional): query to execute against database - commit (bool, optional): set to True to commit transaction, defaults to false - charset (str, optional): charset of the query, defaults to "utf8mb4" - **kwargs (Any, optional): additional keyword arguments to pass to the Task constructor """ def __init__( self, db_name: str, user: str, password: str, host: str, port: int = 3307, fetch: str = "one", fetch_count: int = 10, query: str = None, commit: bool = False, charset: str = "utf8mb4", **kwargs: Any ): self.db_name = db_name self.user = user self.password = password self.host = host self.port = port self.fetch = fetch self.fetch_count = fetch_count self.query = query self.commit = commit self.charset = charset super().__init__(**kwargs) @defaults_from_attrs("fetch", "fetch_count", "query", "commit", "charset") def run( self, fetch: str = "one", fetch_count: int = 10, query: str = None, commit: bool = False, charset: str = "utf8mb4", ) -> Any: """ Task run method. Executes a query against MySQL database and fetches results. Args: - fetch (str, optional): one of "one" "many" or "all", used to determine how many results to fetch from executed query - fetch_count (int, optional): if fetch = 'many', determines the number of results to fetch, defaults to 10 - query (str, optional): query to execute against database - commit (bool, optional): set to True to commit transaction, defaults to false - charset (str, optional): charset of the query, defaults to "utf8mb4" Returns: - results (tuple or list of tuples): records from provided query Raises: - pymysql.MySQLError """ if not query: raise ValueError("A query string must be provided") if fetch not in {"one", "many", "all"}: raise ValueError( "The 'fetch' parameter must be one of the following - ('one', 'many', 'all')" ) conn = pymysql.connect( host=self.host, user=self.user, password=self.password, db=self.db_name, charset=self.charset, ) try: with conn: with conn.cursor() as cursor: cursor.execute(query) # override mypy inferred type since we redefine with incompatible types results: Any if fetch == "all": results = cursor.fetchall() elif fetch == "many": results = cursor.fetchmany(fetch_count) else: results = cursor.fetchone() if commit: conn.commit() conn.close() logging.debug("Fetch Results: ", results) return results except (Exception, pymysql.MySQLError) as e: conn.close() logging.debug("Fetch Error: ", e) raise e
32.71564
95
0.547733
ace9f133278be18a77b8a904a8c8356c384ca2e5
1,219
py
Python
littlebrother/rank/weight.py
trunk/littlebrother
14cebcf8c91b4037db0c1915510cd689691ec9e2
[ "MIT" ]
null
null
null
littlebrother/rank/weight.py
trunk/littlebrother
14cebcf8c91b4037db0c1915510cd689691ec9e2
[ "MIT" ]
2
2020-11-21T14:41:06.000Z
2021-07-20T16:18:51.000Z
littlebrother/rank/weight.py
trunk/littlebrother
14cebcf8c91b4037db0c1915510cd689691ec9e2
[ "MIT" ]
null
null
null
#-*- coding: UTF-8 def next_weight(current_weight, samples_number, new_sample): """Add number to average, given current average and samples number""" if samples_number <= 0: return new_sample return (current_weight + new_sample / float(samples_number)) / ((samples_number + 1) / float(samples_number)) def prev_weight(current_weight, samples_number, old_sample): """Remove number from average, given current average and samples number""" if samples_number <= 1: return 0 return (current_weight - old_sample / float(samples_number)) / ((samples_number - 1) / float(samples_number)) if __name__ == '__main__': import unittest class WeightTest(unittest.TestCase): def testNext(self): assert(next_weight(0, 0, 9) == 9.0) assert(next_weight(9, 0, 9) == 9.0) assert(next_weight(9, 1, 9) == 9.0) assert((11 + 10 + 9 + 8) / 4.0 == next_weight( next_weight( next_weight( next_weight(0, 0, 8), 1, 9), 2, 10), 3, 11)) def testPrev(self): assert(prev_weight(0, 0, 9) == 0.0) assert(prev_weight(9, 0, 9) == 0.0) assert(prev_weight(9, 1, 9) == 0.0) assert(prev_weight((10 + 9 + 8 + 7) / 4.0, 4, 8) == (10 + 9 + 7) / 3.0) unittest.main()
25.395833
110
0.644791
ace9f15b2427271191fd71e92878f1563249d92b
224,146
py
Python
all_functions/configs/Links_site/web_a_ebscohost_com.py
Heroku-elasa/-heroku-buildpack-python-ieee-new
06ec2fda04d9e478ed2506400e460489b0ca91ab
[ "MIT" ]
null
null
null
all_functions/configs/Links_site/web_a_ebscohost_com.py
Heroku-elasa/-heroku-buildpack-python-ieee-new
06ec2fda04d9e478ed2506400e460489b0ca91ab
[ "MIT" ]
15
2021-03-18T20:23:25.000Z
2022-03-11T23:16:16.000Z
all_functions/configs/Links_site/web_a_ebscohost_com.py
Heroku-elasa/heroku-buildpack-python-ieee-new
06ec2fda04d9e478ed2506400e460489b0ca91ab
[ "MIT" ]
1
2017-03-04T16:48:55.000Z
2017-03-04T16:48:55.000Z
#!/usr/bin/python #---------------------------------------------------------------------- # # Author: Laszlo Nagy # # Copyright: (c) 2005 by Szoftver Messias Bt. # Licence: BSD style # # #---------------------------------------------------------------------- # from __future__ import with_statement # from google.appengine.api import files import os, re, errno, sys, time import urllib import urllib2, urlparse from urlparse import urlparse as urlparse2 from BeautifulSoup import BeautifulSoup import cookielib import mimetypes import random import mechanize import md5, hashlib print "Content-type: text/html\n" print "this is running" def import_mod(**kwargs): # import_mod(from_module='sss',from_module2='s') from_module_name1 = kwargs['from_module'] try: kwargs['from_module2'] from_module_name2 = kwargs['from_module2'] except: from_module_name2 = '' try: kwargs['dir_location'] CurrentDir = os.path.dirname(os.path.realpath(__file__)) s = CurrentDir.replace('\\', '/') + kwargs['dir_location'] sys.path.insert(0, s) except: pass if from_module_name1 in sys.modules: print "@@@@@@@@@@@@@@ module already exist for " + from_module_name1 + ' is \n: @@@@@@@@@@@@@@\n\n' if from_module_name2 == '': mod = sys.modules[from_module_name1] else: mod1 = sys.modules[from_module_name1] mod = getattr(mod1, from_module_name2) print "@@@@@@@@@@@@@@ module already exist for " + from_module_name1 + '.' + from_module_name2 + ' is \n: @@@@@@@@@@@@@@\n\n' else: print "@@@@@@@@@@@@@@ module inserting for " + from_module_name1 + " \n: @@@@@@@@@@@@@@\n\n" if from_module_name2 == '': mod = __import__(from_module_name1) else: mod1 = __import__(from_module_name1) mod = getattr(mod1, from_module_name2) # mod = getattr(mod1,from_module_name2) pass print's' # mod=mod1[from_module_name2] return mod # return urlparse.urljoin('file:', urllib.pathname2url(path)) class MozillaCacher(object): """A dictionary like object, that can cache results on a storage device.""" def __init__(self, cachedir='.cache'): self.cachedir = cachedir if not os.path.isdir(cachedir): os.mkdir(cachedir) def name2fname(self, name): return os.path.join(self.cachedir, name) def __getitem__(self, name): if not isinstance(name, str): raise TypeError() fname = self.name2fname(name) if os.path.isfile(fname): return file(fname, 'rb').read() else: raise IndexError() def __setitem__(self, name, value): if not isinstance(name, str): raise TypeError() fname = self.name2fname(name) if os.path.isfile(fname): os.unlink(fname) f = file(fname, 'wb+') try: f.write(value) finally: f.close() def __delitem__(self, name): if not isinstance(name, str): raise TypeError() fname = self.name2fname(name) if os.path.isfile(fname): os.unlink(fname) def __iter__(self): raise NotImplementedError() def has_key(self, name): return os.path.isfile(self.name2fname(name)) class HTTPNoRedirector(urllib2.HTTPRedirectHandler): """This is a custom http redirect handler that FORBIDS redirection.""" def http_error_302(self, req, fp, code, msg, headers): e = urllib2.HTTPError(req.get_full_url(), code, msg, headers, fp) if e.code in (301, 302): if 'location' in headers: newurl = headers.getheaders('location')[0] elif 'uri' in headers: newurl = headers.getheaders('uri')[0] e.newurl = newurl raise e def get_content_type(filename): return mimetypes.guess_type(filename)[0] or 'application/octet-stream' def encode_multipart_formdata(fields, files): """ fields is a sequence of (name, value) elements for regular form fields. files is a sequence of (name, filename, value) elements for data to be uploaded as files Return (content_type, body) ready for httplib.HTTP instance """ BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$' CRLF = '\r\n' L = [] for (key, value) in fields: L.append('--' + BOUNDARY) L.append('Content-Disposition: form-data; name="%s"' % key) L.append('') L.append(value) for (key, filename, value) in files: L.append('--' + BOUNDARY) L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename)) L.append('Content-Type: %s' % get_content_type(filename)) L.append('') L.append(value) L.append('--' + BOUNDARY + '--') L.append('') body = CRLF.join(L) content_type = 'multipart/form-data; boundary=%s' % BOUNDARY return content_type, body class MozillaEmulator(object): def __init__(self, cacher={}, trycount=0, debug=False, **kwargs): """Create a new MozillaEmulator object. @param cacher: A dictionary like object, that can cache search results on a storage device. You can use a simple dictionary here, but it is not recommended. You can also put None here to disable caching completely. @param trycount: The download() method will retry the operation if it fails. You can specify -1 for infinite retrying. A value of 0 means no retrying. A value of 1 means one retry. etc.""" if kwargs['cookies']: self.cookie3 = kwargs['cookies'] else: self.cookie3 = '' self.cacher = cacher if self.cookie3 != '': self.cookies = cookielib.MozillaCookieJar(self.cookie3) else: self.cookies = cookielib.MozillaCookieJar() # self.cookies = cookielib.CookieJar() self.debug = debug self.trycount = trycount def _hash(self, data): h = md5.new() h.update(data) return h.hexdigest() def build_opener(self, url, proxy=[], User_Pass=[], postdata=None, extraheaders={}, forbid_redirect=False): txheaders = { 'Accept': 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5', 'Accept-Language': 'en,hu;q=0.8,en-us;q=0.5,hu-hu;q=0.3', # 'Accept-Encoding': 'gzip, deflate', 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7', # 'Keep-Alive': '300', # 'Connection': 'keep-alive', # 'Cache-Control': 'max-age=0', } for key, value in extraheaders.iteritems(): txheaders[key] = value req = urllib2.Request(url, postdata, txheaders) self.cookies.add_cookie_header(req) if forbid_redirect: redirector = HTTPNoRedirector() else: redirector = urllib2.HTTPRedirectHandler() if proxy != [] and (not re.findall("None", proxy)) and proxy != '': if User_Pass != [] and User_Pass != '': proxies = {"http": "http://" + User_Pass + "@" + proxy} else: proxies = {"http": "http://%s" % proxy} proxy_support = urllib2.ProxyHandler(proxies) # opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler(debuglevel=1)) else: proxy_support = urllib2.ProxyHandler() # opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler(debuglevel=1)) # url=link.absolute_url # headers={'User-agent' : 'Mozilla/5.0'} http_handler = urllib2.HTTPHandler(debuglevel=self.debug) https_handler = urllib2.HTTPSHandler(debuglevel=self.debug) # default_classes = [ProxyHandler, UnknownHandler, HTTPHandler, # HTTPDefaultErrorHandler, HTTPRedirectHandler, # FTPHandler, FileHandler, HTTPErrorProcessor] u = urllib2.build_opener(proxy_support, http_handler, https_handler, urllib2.HTTPCookieProcessor(self.cookies), redirector) urllib2.install_opener(u) u.addheaders = [ ('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; hu-HU; rv:1.7.8) Gecko/20050511 Firefox/1.0.4')] if not postdata is None: req.add_data(postdata) if self.cookie3 == '': fo = os.getcwd().replace('\\', '/') # pathname = os.path.join("cookies", cookie3) site = urlparse2(url).hostname if not os.path.isdir(fo + "/cookies/" + site): os.mkdir(fo + "/cookies/" + site) chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" self.cookie3 = fo + "/cookies/" + site + '/' + ''.join([random.choice(chars) for x in range(5)]) + ".txt" self.cookies.save(self.cookie3) return (req, u, self.cookie3) def download(self, url, proxy=[], User_Pass=[], postdata=None, extraheaders={}, forbid_redirect=False, trycount=None, fd=None, onprogress=None, only_head=False): """Download an URL with GET or POST methods. @param proxy: set the proxy setting. @param User_Pass: user_pass for proxy. @param postdata: It can be a string that will be POST-ed to the URL. When None is given, the method will be GET instead. @param extraheaders: You can add/modify HTTP headers with a dict here. @param forbid_redirect: Set this flag if you do not want to handle HTTP 301 and 302 redirects. @param trycount: Specify the maximum number of retries here. 0 means no retry on error. Using -1 means infinite retring. None means the default value (that is self.trycount). @param fd: You can pass a file descriptor here. In this case, the data will be written into the file. Please note that when you save the raw data into a file then it won't be cached. @param onprogress: A function that has two parameters: the size of the resource and the downloaded size. This will be called for each 1KB chunk. (If the HTTP header does not contain the content-length field, then the size parameter will be zero!) @param only_head: Create the openerdirector and return it. In other words, this will not retrieve any content except HTTP headers. @return: The raw HTML page data, unless fd was specified. When fd was given, the return value is undefined. """ if trycount is None: trycount = self.trycount cnt = 0 while True: try: key = self._hash(url) if (self.cacher is None) or (not self.cacher.has_key(key)): req, u, cookie3 = self.build_opener(url, proxy, User_Pass, postdata, extraheaders, forbid_redirect) openerdirector = u.open(req) if self.debug: print req.get_method(), url print openerdirector.code, openerdirector.msg print openerdirector.headers self.cookies.extract_cookies(openerdirector, req) if only_head: return openerdirector if openerdirector.headers.has_key('content-length'): length = long(openerdirector.headers['content-length']) else: length = 0 dlength = 0 # piece_size = 4096 # 4 KiB piece_size = 1024 * 1024 # 1MB if fd: while True: data = openerdirector.read(piece_size) dlength += len(data) fd.write(data) if onprogress: onprogress(length, dlength) if not data: break else: data = '' while True: newdata = openerdirector.read(piece_size) dlength += len(newdata) data += newdata if onprogress: onprogress(length, dlength) if not newdata: break #data = openerdirector.read() if not (self.cacher is None): self.cacher[key] = data else: data = self.cacher[key] #try: # d2= GzipFile(fileobj=cStringIO.StringIO(data)).read() # data = d2 #except IOError: # pass self.cookies.save(self.cookie3) return data, cookie3 except urllib2.URLError: er = urllib2.URLError cnt += 1 if (trycount > -1) and (trycount < cnt): raise # Retry :-) if self.debug: print "MozillaEmulator: urllib2.URLError, retryting ", cnt def post_multipart(self, url, fields, files, pr=[], Up=[], forbid_redirect=True, ): """Post fields and files to an http host as multipart/form-data. fields is a sequence of (name, value) elements for regular form fields. files is a sequence of (name, filename, value) elements for data to be uploaded as files Return the server's response page. """ content_type, post_data = encode_multipart_formdata(fields, files) result = self.download(url, pr, Up, post_data, { 'Content-Type': content_type, 'Content-Length': str(len(post_data)) }, forbid_redirect=forbid_redirect ) return result class MECAHNIZM(object): def __init__(self, proxy='', User_Pass='', **kwargs): global PDF_Dir, Watermarked_PDF_Files_Dir if kwargs['cookies']: self.cookie3 = kwargs['cookies'] else: self.cookie3 = '' if kwargs['url']: self.url = kwargs['url'] else: self.url = '' self.proxy = proxy self.User_Pass = User_Pass self.br = self.BROWSER() def progressbar(self): pass # from clint.textui import progress # r = requests.get(url, stream=True) # with open(path, 'wb') as f: # total_length = int(r.headers.get('content-length')) # for chunk in progress.bar(r.iter_content(chunk_size=1024), expected_size=(total_length/1024) + 1): # if chunk: # f.write(chunk) # f.flush() def BROWSER(self, cookie3=''): """ :param url: """ # global br, cj, r, proxy, User_Pass br = mechanize.Browser() # print br # Cookie Jar # fo=os.getcwd()+"\\cookies\\" # try : # os.mkdir(fo) # except: # pass # os.chdir(fo) # folder=sys.path.insert(0,'/cookies') # os.chdir(..) # Browser options br.set_handle_equiv(True) br.set_handle_gzip(True) br.set_handle_referer(True) # no allow everything to be written to br.set_handle_robots(False) # no robots br.set_handle_refresh(True) # can sometimes hang without this br.set_handle_redirect(True) # Follows refresh 0 but not hangs on refresh > 0 br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=3) # Want debugging messages? #br.set_debug_http(True) br.set_debug_redirects(True) #br.set_debug_responses(True) # # User-Agent (this is cheating, ok?) # br.addheaders = [('User-Agent', 'Mozilla/5.0 (Linux; U; Android 2.3.4; en-us; T-Mobile myTouch 3G Slide Build/GRI40) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1'), # ('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'), # ('Accept-Language', 'en-gb,en;q=0.5'), # ('Accept-Encoding', 'gzip,deflate'), # ('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.7'), # ('Keep-Alive', '115'), # ('Connection', 'keep-alive'), # ('Cache-Control', 'max-age=0'), # ('Referer', 'http://yahoo.com')] # User-Agent (this is cheating, ok?) # br.addheaders = [('User-agent', # 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')] br.addheaders = [ ('User-agent', 'Mozilla/5.0 (Windows NT 6.1; rv:23.0) Gecko/20100101 Firefox/23.0'), ('Accept', 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5;application/json;text/javascript;*/*'), ('Accept-Language', 'en,hu;q=0.8,en-us;q=0.5,hu-hu;q=0.3'), ('Accept-Encoding', 'gzip, deflate'), ('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.7'), ('Keep-Alive', '300'), ('Connection', 'keep-alive'), ('Cache-Control', 'max-age=0'), ('Referer', self.url), ('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'), ('X-Requested-With', 'XMLHttpRequest') ] # # If the protected site didn't receive the authentication data you would # # end up with a 410 error in your face # br.add_password('http://safe-site.domain', 'username', 'password') # br.open('http://safe-site.domain') # Open some site, let's pick a random one, the first that pops in mind: # Proxy and user/password #proxy = "61.233.25.166:80" # proxy = "202.202.0.163:3128" # proxy=self.proxy # Proxy # dd=re.findall('None:None', proxy) if self.proxy != [] and self.proxy != '' and not (re.findall('None', self.proxy)): br.proxies = br.set_proxies({"http": self.proxy}) # br.proxies=br.set_proxies( proxy) if self.User_Pass != [] and self.User_Pass != '' and not (re.findall('None:None', self.User_Pass)): br.add_proxy_password(self.User_Pass.split(":")[0], self.User_Pass.split(":")[1]) # if r!={}: # rr = br.open(url) # c= cookielib.Cookie(version=0, name='PON', value="xxx.xxx.xxx.111", expires=365, port=None, port_specified=False, domain='xxxx', domain_specified=True, domain_initial_dot=False, path='/', path_specified=True, secure=True, discard=False, comment=None, comment_url=None, rest={'HttpOnly': False}, rfc2109=False) # cj.set_cookie(c0) if self.cookie3 == '': CurrentDir = os.path.dirname(os.path.realpath(__file__)).replace('\\', '/') fo = os.path.abspath(os.path.join(CurrentDir, '../..')).replace('\\', '/') # pathname = os.path.join("cookies", cookie3) site = urlparse2(self.url).hostname if not os.path.isdir(fo + "/cookies/" + site): os.mkdir(fo + "/cookies/" + site) chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" self.cookie3 = fo + "/cookies/" + site + '/' + ''.join([random.choice(chars) for x in range(5)]) + ".txt" self.cj = cookielib.LWPCookieJar() opener = mechanize.build_opener(mechanize.HTTPCookieProcessor(self.cj)) br.set_cookiejar(self.cj) self.cj.save(self.cookie3) else: self.cj = cookielib.LWPCookieJar() # self.cj.revert(self.cookie3) opener = mechanize.build_opener(mechanize.HTTPCookieProcessor(self.cj)) br.set_cookiejar(self.cj) # self.cj.load(self.cookie3) # self.cj.save( self.cookie3, ignore_discard=True, ignore_expires=True) # cookiefile=open(self.cookie3,'r') # s0=cookiefile.readlines() # # print s0 # for i in range(0,len(s0)): # if re.findall(':',s0[i]): # s2=s0[i].split(':')[1].replace('\n','') # print s2 # br.set_cookie(s2) # self.cj.save( self.cookie3) return br # Proxy password # br.add_proxy_password("joe", "password") # self.dl_acm = "http://dl.acm.org/citation.cfm?id=99977.100000&coll=DL&dl=ACM" def speed_download(self, pdf_url, piece_size=1024 * 1024,timeout=1111): # br2=self.br cookiefile = open(self.cookie3, 'r') s0 = cookiefile.readlines() # print s0 # for i in range(0,len(s0)): # if re.findall(':',s0[i]): # s2=s0[i].split(':')[1].replace('\n','') # print s2 # self.br.set_cookie(s2) # socket=import_mod(from_module='socket') # socket.setdefaulttimeout(300) # openerdirector = self.br.open(pdf_url,timeout=timeout) openerdirector = self.br.open(pdf_url) try: if (openerdirector._headers.dict['content-type']) == 'application/pdf': length = long(openerdirector._headers.dict['content-length']) ok = True else: length = 0 except: length = 0 dlength = 0 # piece_size = 4096 # 4 KiB # piece_size =1024*1024 # 1MB data = '' while True: newdata = openerdirector.read(piece_size) dlength += len(newdata) data += newdata if length != 0: status = r"%10d [%3.2f%%]" % (dlength, dlength * 100. / length) status = status + chr(8) * (len(status) + 1) print status # pdf_path=PDF_File().file_save(data, "PDF_Files\\", localName.filename) # if onprogress: # onprogress(length,dlength) if not newdata: self.cj.save(self.cookie3) break if data != []: [links, title] = link_tag_find(data, pdf_url) if links !=[] and links !='': data2=self.br_folow_link(self.br,self.cookie3) responce = { 'html': data2, 'links':links, 'title':title, 'file':data2 } return responce, self.cookie3 #,pdf_path else: return [], self.cookie3 def br_folow_link(self,br,cookies): for link1 in self.br.links(url_regex=".pdf"): # http://www.rfc-editor.org/rfc/rfc2606.txt # if re.findall(links11, link1.url): print(link1) # Link(base_url='http://www.example.com/', url='http://www.rfc-editor.org/rfc/rfc2606.txt', text='RFC 2606', tag='a', attrs=[('href', 'http://www.rfc-editor.org/rfc/rfc2606.txt')]) print(link1.url) print('match found') # match found break br2=self.br try: self.br.follow_link(link1) # link still holds the last value it had in the loop # print(br.geturl()) pdf_link=self.br.geturl() except: for link2 in br2.links(url_regex=".pdf"): # http://www.rfc-editor.org/rfc/rfc2606.txt # if re.findall(links11, link1.url): print(link2) # Link(base_url='http://www.example.com/', url='http://www.rfc-editor.org/rfc/rfc2606.txt', text='RFC 2606', tag='a', attrs=[('href', 'http://www.rfc-editor.org/rfc/rfc2606.txt')]) print(link2.url) print('match found') # match found break br2.follow_link(link2) # link still holds the last value it had in the loop # print(br.geturl()) pdf_link=br2.geturl() if pdf_link: self.br.set_cookiejar(self.cj) self.cj.save(cookies, ignore_discard=True, ignore_expires=True) # return html2, self.cookies, pdf_link, title, 0, self.log_out localName = LINK(PDF_Dir=PDF_Dir, Watermarked_PDF_Files_Dir=Watermarked_PDF_Files_Dir).filename2(pdf_link) try: f1 = self.br.retrieve(pdf_link, localName.pdf_Folder_filename) except: f1 =br2.retrieve(pdf_link, localName.pdf_Folder_filename) return f1[0] else: return [] def download_pdf_br0(self, pdf_url1): class pdf_url(): abs = 1 if not ("pdf_url1.absolute_url" is locals()): absolute_url = str(pdf_url1) else: pdf_url = str(pdf_url1) def __init__(self): self.absolute_url = 2 if not ("pdf_url1.absolute_url" is locals()): self.absolute_url = str(pdf_url1) else: pdf_url = str(pdf_url1) # pdf_url = pdf_url1 # pdf_url.='test'.split() # pdf_url2=str(pdf_url1) # if not ("pdf_url1.absolute_url" is locals()): # pdf_url.absolute_url = pdf_url2.split() # else: # pdf_url = pdf_url1 if pdf_url.absolute_url.endswith(".pdf") or pdf_url.absolute_url.endswith(".zip"): if pdf_url.absolute_url: # localName1 = basename(urlsplit(pdf_url.absolute_url)[2]) localName = LINK(PDF_Dir=PDF_Dir, Watermarked_PDF_Files_Dir=Watermarked_PDF_Files_Dir).filename( pdf_url.absolute_url) # pathname = os.path.join("PDF_Files", localName.filename) # s=get_full_url(pdf_url) # req = self.br.click_link(pdf_url.absolute_url) # html = self.br.open(req).read() f1 = self.br.retrieve(pdf_url.absolute_url, localName.pdf_Folder_filename) else: localName = LINK(PDF_Dir=PDF_Dir, Watermarked_PDF_Files_Dir=Watermarked_PDF_Files_Dir).filename( pdf_url.absolute_url) f1 = self.br.retrieve(pdf_url.absolute_url, localName.pdf_Folder_filename) # f1 = self.br.retrieve(pdf_url, localName.pdf_Folder_filename) if f1: self.cj.save(self.cookie3) return f1[0], self.cookie3 #,pdf_path # return os.getcwd()+PDF_File.pdf_Folder_filename,os.getcwd()+PDF_File.W_pdf_Folder_filename def download_pdf_br(self, pdf_url1): class pdf_url(): abs = 1 if not ("pdf_url1.absolute_url" is locals()): absolute_url = str(pdf_url1) else: pdf_url = str(pdf_url1) def __init__(self): self.absolute_url = 2 if not ("pdf_url1.absolute_url" is locals()): self.absolute_url = str(pdf_url1) else: pdf_url = str(pdf_url1) # pdf_url = pdf_url1 # pdf_url.='test'.split() # pdf_url2=str(pdf_url1) # if not ("pdf_url1.absolute_url" is locals()): # pdf_url.absolute_url = pdf_url2.split() # else: # pdf_url = pdf_url1 try: if pdf_url.absolute_url.endswith(".pdf") or pdf_url.absolute_url.endswith(".zip"): if pdf_url.absolute_url: # localName1 = basename(urlsplit(pdf_url.absolute_url)[2]) localName = LINK(PDF_Dir=PDF_Dir, Watermarked_PDF_Files_Dir=Watermarked_PDF_Files_Dir).filename( pdf_url.absolute_url) # pathname = os.path.join("PDF_Files", localName.filename) # s=get_full_url(pdf_url) # req = self.br.click_link(pdf_url.absolute_url) # html = self.br.open(req).read() f1 = self.br.retrieve(pdf_url.absolute_url, localName.pdf_Folder_filename) else: localName = LINK(PDF_Dir=PDF_Dir, Watermarked_PDF_Files_Dir=Watermarked_PDF_Files_Dir).filename( pdf_url.absolute_url) f1 = self.br.retrieve(pdf_url.absolute_url, localName.pdf_Folder_filename) # f1 = self.br.retrieve(pdf_url, localName.pdf_Folder_filename) except: if pdf_url1.endswith(".pdf") or pdf_url1.endswith(".zip"): if pdf_url: # localName1 = basename(urlsplit(pdf_url.absolute_url)[2]) localName = LINK(PDF_Dir=PDF_Dir, Watermarked_PDF_Files_Dir=Watermarked_PDF_Files_Dir).filename2( pdf_url1) # pathname = os.path.join("PDF_Files", localName.filename) # s=get_full_url(pdf_url) # req = self.br.click_link(pdf_url.absolute_url) # html = self.br.open(req).read() f1 = self.br.retrieve(pdf_url1, localName.pdf_Folder_filename) else: localName = LINK(PDF_Dir=PDF_Dir, Watermarked_PDF_Files_Dir=Watermarked_PDF_Files_Dir).filename2( pdf_url1) f1 = self.br.retrieve(pdf_url1, localName.pdf_Folder_filename) # f1 = self.br.retrieve(pdf_url, localName.pdf_Folder_filename) if f1: self.cj.save(self.cookie3) return f1[0], self.cookie3 #,pdf_path # return os.getcwd()+PDF_File.pdf_Folder_filename,os.getcwd()+PDF_File.W_pdf_Folder_filename class web(object): def __init__(self, url=''): self.url = url def download_mechanism(self, url='', proxy='', user_pass='', location='PDF_Files/', **kwargs): """ :param url: """ if kwargs['cookies']: cookies = kwargs['cookies'] else: cookies = '' if proxy == '' or proxy == []: import proxy_checker3_all_function fo = os.getcwd().replace('\\', '/') pr_h, proxy_h, user_pass_h = proxy_checker3_all_function.make_returning_proxy("configs//sites_proxy//", url) os.chdir(fo) else: pr_h = [] user_pass_h = [] pr_h.append(proxy) user_pass_h.append(user_pass) try: i = user_pass_h.index("") del user_pass_h[i] except: print 'there is no empty lsit in user_password list' try: i = pr_h.index("") del pr_h[i] except: print 'there is no empty lsit in proxy list' # pr_h=['222.66.115.233:80 ', '202.202.0.163:3128 ', '151.236.14.48:80'] pdf_dw_li = pdf_dw_Wr_li = [] frontpage = [] don_flg = -1 if pr_h != []: i = -1 for j in range(i + 1, len(pr_h)): if don_flg != 1: # debug = True # cash = None # dl = MozillaEmulator(cash,0,debug) # dl = MozillaEmulator(cash, 0) try: if 'user_pass_h[j]' is locals(): # frontpage,cookies=MECAHNIZM( proxy='', User_Pass='').speed_download(pdf_url,piece_size=1024*1024) frontpage, cookies = MECAHNIZM(pr_h[j], user_pass_h[j], cookies=cookies, url=url).speed_download(url) # frontpage,cookies = MECAHNIZM(pr_h[j],user_pass_h[j],cookies=cookies,url=url).download_pdf_br(url) pr = pr_h[j] upss = user_pass_h[j] else: # frontpage,cookies = MECAHNIZM(pr_h[j],cookies=cookies,url=url).download_pdf_br(url) frontpage, cookies = MECAHNIZM(pr_h[j], cookies=cookies, url=url).speed_download(url) pr = pr_h[j] upss = '' except: print "we cant dowload beacuse of invalid tag or invalid proxy line 620" + "\n" if frontpage != []: print "file downloaded " don_flg = 1 # pr = pr_h[j] # upss = user_pass_h[j] break else: print "we could not download file with proxy:" + pr_h[j] if don_flg != 1: print "we are unable to download your file Now!!" + '\n' frontpage = [] pr = '' upss = '' cookies = '' else: print "we are unable to download your file Now!! Becaouse proxy is empty" + '\n' return frontpage, pr, upss, cookies def download_mechanism_link(self, url='', proxy='', user_pass='', location='PDF_Files/', **kwargs): """ :param url: """ try:# kwargs['cookies']: cookies = kwargs['cookies'] except: cookies = '' try: if kwargs['piece_size']: piece_size = kwargs['piece_size'] else: piece_size = 1024 * 20 except: piece_size = 1024 * 20 try: url_ref=kwargs['url_reffrence'] except: url_ref=url if proxy == '' or proxy == []: import proxy_checker3_all_function site = urlparse2(url).hostname fo = os.getcwd().replace('\\', '/') pr_h, proxy_h, user_pass_h = proxy_checker3_all_function.make_returning_proxy( "configs//sites_proxy//" + site + '//', url) os.chdir(fo) else: pr_h = [] user_pass_h = [] pr_h.append(proxy) user_pass_h.append(user_pass) try: i = user_pass_h.index("") del user_pass_h[i] except: print 'there is no empty lsit in user_password list' try: i = pr_h.index("") del pr_h[i] except: print 'there is no empty lsit in proxy list' # pr_h=['222.66.115.233:80 ', '202.202.0.163:3128 ', '151.236.14.48:80'] pdf_dw_li = pdf_dw_Wr_li = [] frontpage = [] don_flg = -1 if pr_h != []: i = -1 for j in range(i + 1, len(pr_h)): if don_flg != 1: # debug = True # cash = None # dl = MozillaEmulator(cash,0,debug) # dl = MozillaEmulator(cash, 0) try: if 'user_pass_h[j]' is locals(): # frontpage,cookies=MECHANIZM( proxy='', User_Pass='').speed_download(pdf_url,piece_size=1024*1024) # frontpage, cookies = MECAHNIZM(pr_h[j], user_pass_h[j], cookies=cookies,url=url).speed_download(url, piece_size) frontpage,cookies = MECAHNIZM(pr_h[j],user_pass_h[j],cookies=cookies,url=url).download_pdf_br(url,piece_size) pr = pr_h[j] upss = user_pass_h[j] else: frontpage,cookies = MECAHNIZM(pr_h[j],cookies=cookies,url=url_ref).download_pdf_br(url) # frontpage, cookies = MECAHNIZM(pr_h[j], cookies=cookies, url=url_ref).speed_download(url,piece_size) pr = pr_h[j] upss = '' except: try: pass# frontpage=self.twill_download( url, cookies) except: print "we cant dowload beacuse of invalid tag or invalid proxy line 620 Proxy:" + pr_h[j]+"\n" if frontpage != []: print "file downloaded " don_flg = 1 # pr = pr_h[j] # upss = user_pass_h[j] break else: print "we could not download file with proxy:" + pr_h[j] if don_flg != 1: print "we are unable to download your file Now!!" + '\n' frontpage = [] pr = '' upss = '' cookies = '' else: print "we are unable to download your file Now!! Becaouse proxy is empty" + '\n' return frontpage, pr, upss, cookies def download_bash_curl(self, url='', proxy='', user_pass='', location='PDF_Files/', **kwargs): """ :param url: """ if kwargs['cookies']: cookies = kwargs['cookies'] else: cookies = '' if proxy == '' or proxy == []: import proxy_checker3_all_function fo = os.getcwd().replace('\\', '/') pr_h, proxy_h, user_pass_h = proxy_checker3_all_function.make_returning_proxy("configs//sites_proxy//", url) os.chdir(fo) else: pr_h = [] user_pass_h = [] pr_h.append(proxy) user_pass_h.append(user_pass) # try: # i = user_pass_h.index("") # del user_pass_h[i] # except: # print 'there is no empty lsit in user_password list' try: i = pr_h.index("") del pr_h[i] except: pass # print 'there is no empty list in proxy list' # pr_h=['222.66.115.233:80 ', '202.202.0.163:3128 ', '151.236.14.48:80'] pdf_dw_li = pdf_dw_Wr_li = [] frontpage = [] don_flg = -1 if pr_h != []: i = -1 for j in range(i + 1, len(pr_h)): if don_flg != 1: debug = True cash = None # dl = MozillaEmulator(cash,0,debug) dl = MozillaEmulator(cash, 0, cookies=cookies) try: if cookies != '': st = 'curl -v --cookie-jar' + cookies + ' -A "Mozilla/5.0 (Windows NT 6.0; rv:30.0) Gecko/20100101 Firefox/27.0"' if user_pass_h[j] != '': #http://stackoverflow.com/questions/14437864/save-result-from-system-command-to-a-variable-using-subprocess st = st + '--proxy http://' + user_pass_h[j] + '@' + pr_h[j] + ' -L ' + url # frontpage,cookies = dl.download(url, pr_h[j], user_pass_h[j]) pr = pr_h[j] upss = user_pass_h[j] else: # frontpage,cookies = dl.download(url, pr_h[j]) st = st + '--proxy http://' + pr_h[j] + ' -L ' + url pr = pr_h[j] upss = '' #http://stackoverflow.com/questions/14437864/save-result-from-system-command-to-a-variable-using-subprocess import subprocess awk_sort = subprocess.Popen([st], stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True) awk_sort.wait() output = awk_sort.communicate()[0] print output.rstrip() frontpage = output.rstrip() except: print "we cant download because of invalid tag or invalid proxy line 620" + "\n" if frontpage != []: if len(user_pass_h[j]) != 0: print "file downloaded with " + str(pr_h[j]) + '@' + str(user_pass_h[j]) else: print "file downloaded with " + str(pr_h[j]) don_flg = 1 # pr = pr_h[j] # upss = user_pass_h[j] break else: print "we could not download file with proxy:" + pr_h[j] if don_flg != 1: print "we are unable to download your file Now!!" + '\n' frontpage = [] pr = '' upss = '' # cookies='' else: print "we are unable to download your file Now!! Beacouse proxy is empty" + '\n' return frontpage, pr, upss, cookies def download(self, url='', proxy='', user_pass='', location='PDF_Files/', **kwargs): """ :param url: """ if kwargs['cookies']: cookies = kwargs['cookies'] else: cookies = '' if proxy == '' or proxy == []: import proxy_checker3_all_function fo = os.getcwd().replace('\\', '/') pr_h, proxy_h, user_pass_h = proxy_checker3_all_function.make_returning_proxy("configs//sites_proxy//", url) os.chdir(fo) else: pr_h = [] user_pass_h = [] pr_h.append(proxy) user_pass_h.append(user_pass) # try: # i = user_pass_h.index("") # del user_pass_h[i] # except: # print 'there is no empty lsit in user_password list' try: i = pr_h.index("") del pr_h[i] except: pass # print 'there is no empty list in proxy list' # pr_h=['222.66.115.233:80 ', '202.202.0.163:3128 ', '151.236.14.48:80'] pdf_dw_li = pdf_dw_Wr_li = [] frontpage = [] don_flg = -1 if pr_h != []: i = -1 for j in range(i + 1, len(pr_h)): if don_flg != 1: debug = True cash = None # dl = MozillaEmulator(cash,0,debug) dl = MozillaEmulator(cash, 0, cookies=cookies) try: if user_pass_h[j] != '': frontpage, cookies = dl.download(url, pr_h[j], user_pass_h[j]) pr = pr_h[j] upss = user_pass_h[j] else: frontpage, cookies = dl.download(url, pr_h[j]) pr = pr_h[j] upss = '' except: print "we cant download because of invalid tag or invalid proxy line 620" + "\n" if frontpage != []: if len(user_pass_h[j]) != 0: print "file downloaded with " + str(pr_h[j]) + '@' + str(user_pass_h[j]) else: print "file downloaded with " + str(pr_h[j]) don_flg = 1 # pr = pr_h[j] # upss = user_pass_h[j] break else: print "we could not download file with proxy:" + pr_h[j] if don_flg != 1: print "we are unable to download your file Now!!" + '\n' frontpage = [] pr = '' upss = '' # cookies='' else: print "we are unable to download your file Now!! Beacouse proxy is empty" + '\n' return frontpage, pr, upss, cookies def twill_download(self, url, cookies): # self.url="%(ezproxy_host)s"%form_data # self.database_link="%(database_link)s"%form_data # self.username="%(user)s"%form_data # self.password="%(pass)s"%form_data # self.user_tag="%(user_tag)s"%form_data # self.pass_tag="%(pass_tag)s"%form_data # self.Form_id="%(Form_id)s"%form_data # self.submit_tag_name="%(submit_tag_name)s"%form_data # self.submit_tag_value="%(submit_tag_value)s"%form_data # self.Form_Type="%(Form_Type)s"%form_data # self.log_done="%(Log_test)s"%form_data link = url; # lg = url['log_out']; # url_logout = lg['log_out']; # ez_link = lg['ez_link'] # twil__headers = lg['headers'] try: link = lg['pdf_link'] # site = urlparse2(link.absolute_url).hostname except: pass # site = urlparse2(link).hostname # self.a.config("readonly_controls_writeable", 1) # self.b = self.a.get_browser() # self.b.set_agent_string("Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14") # self.b.clear_cookies() twill = import_mod(from_module='twill') # t_com = twill.commands # t_com.reset_browser # t_com.reset_output t_com = twill.commands ## get the default browser t_brw = t_com.get_browser() try: t_brw.set_agent_string( "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14") t_com.add_extra_header('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1') t_com.add_extra_header('Accept', 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5;application/json;text/javascript;*/*') t_com.add_extra_header('Accept-Language', 'en,hu;q=0.8,en-us;q=0.5,hu-hu;q=0.3') t_com.add_extra_header('Accept-Encoding', 'gzip, deflate') t_com.add_extra_header('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.7') t_com.add_extra_header('Keep-Alive', '300') t_com.add_extra_header('Connection', 'keep-alive') t_com.add_extra_header('Cache-Control', 'max-age=0') # t_com.add_extra_header('Referer', ez_link) t_com.add_extra_header('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8') t_com.add_extra_header('X-Requested-With', 'XMLHttpRequest') except: t_com.add_extra_header('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1') t_com.add_extra_header('Accept', "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5;application/json;text/javascript;*/*") t_com.add_extra_header('Accept-Language', 'en,hu;q=0.8,en-us;q=0.5,hu-hu;q=0.3') t_com.add_extra_header('Accept-Encoding', 'gzip, deflate') t_com.add_extra_header('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.7') t_com.add_extra_header('Keep-Alive', '300') t_com.add_extra_header('Connection', 'keep-alive') t_com.add_extra_header('Cache-Control', 'max-age=0') # t_com.add_extra_header('Referer', ez_link) t_com.add_extra_header('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8') t_com.add_extra_header('X-Requested-With', 'XMLHttpRequest') # t_brw.set_agent_string(twil__headers) # cookies=cookies.replace('/','\\') try: t_brw.load_cookies(cookies) except:pass # socket=import_mod(from_module='socket') # socket.setdefaulttimeout(300) ## open the url # url = 'http://google.com' # t_brw.find_link(link) # t_brw.go(link) print '@@@@@@@@@@@@@ link download by twill is @@@@@@@@@@@@' print link print '@@@@@@@@@@@@@ link download by twill is @@@@@@@@@@@@' try: s = link.absolute_url t_brw.follow_link(link) except: t_brw.go(link) # class link_n(object): # def __init__(self): # self.absolute_url = link # self.base_url = ez_link # self.url=ez_link # def url(self): # return self # link=link_n.url # t_brw.follow_link(link) html0 = t_brw.result.page print '@@@@@@@@@@@@@ html0 download by twill is @@@@@@@@@@@@' print html0[:20] print '@@@@@@@@@@@@@ html0 download by twill is @@@@@@@@@@@@' # time.sleep(10) link2 = t_brw.result.url link2 = link.absolute_url if not (html0[:4] == '%PDF') or html0 == []: t_brw.go(link2) html, cookies = MECAHNIZM('', '', cookies=cookies, url=link2).speed_download(link2) # html3,pr,upss,cookies=web().download_mechanism_link(link,'',cookies=cookies) if not (html[:4] == '%PDF') or html == []: t_brw.save_cookies(cookies) t_brw = t_com.get_browser() t_brw.set_agent_string( "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14") t_brw.load_cookies(cookies) # socket=import_mod(from_module='socket') # socket.setdefaulttimeout(300) html3, pr, upss, cookies = web().download_mechanism_link(link, '', cookies=cookies) t_brw.go(link2) html = t_brw.result.page print '@@@@@@@@@@@@@ html download by twill is @@@@@@@@@@@@' print html print '@@@@@@@@@@@@@ html download by twill is @@@@@@@@@@@@' # time.sleep(10) else: html = html0 # t_brw.go(url_logout) os.remove(cookies) return html def twil_find_pdf_link(link): site = urlparse2(link).hostname # site2=site.replace('.','_') fo = os.getcwd().replace('\\', '/') CurrentDir = os.path.dirname(os.path.realpath(__file__)).replace('\\', '/') Parent_Dir = os.path.abspath(os.path.join(CurrentDir, '../')).replace('\\', '/') os.chdir(Parent_Dir) tw = twill(site_list_form='sites_proxy/' + site + '/site_list_form.txt') form = tw.find_form() for k in range(0, len(form)): # METHOD = "%(METODE)s" % form[k] # if True: try: if "%(METODE)s" % form[k] == '2': [html, cookies, links, title, times, log_out] = tw.login_to_site(link, form[k], [], []) elif "%(METODE)s" % form[k] == '1' or "%(METODE)s" % form[ k] == '1+d' or "%(METODE)s" % form[ k] == '1+d+d': #direct find link or direct find link and download [html, cookies, links, title, times, log_out] = tw.twill_find_link(link, form[k]) elif "%(METODE)s" % form[k] == '3': [html, cookies, links, title, times, log_out] = tw.twill_find_link(link, form[k]) elif "%(METODE)s" % form[k] == 'robobrowser': [html, cookies, links, title, times, log_out] = tw.twill_find_link_robobrowser(link, form[k]) # else: except: try: os.remove(cookies) except: pass html=[];cookies='';links=[]; title=''; times=0; log_out=[] if links != [] and (html !=[] and html !=''): break else: try: os.remove(cookies) except: pass os.chdir(fo) return html, cookies, links, title, form[k], times, log_out class twill: def __init__(self, **kwargs): # import socket # if kwargs['url']:self.url=kwargs['url'] if kwargs['site_list_form']: self.site_list_form = kwargs['site_list_form'] # if kwargs['url_to_ez_file']:self.url_to_ez_file=kwargs['url_to_ez_file'] # socket=import_mod(from_module='socket') # socket.setdefaulttimeout(100) def find_form(self): sa = open(self.site_list_form, 'r') listform = sa.readlines() # time.sleep(10) sa.close() k = -1 form_data = {} # for line in listform: # print '&&&&&&&&' # print line+'\n' # print '&&&&&&&&' for line in listform: if not re.findall('#', line) and line != '\n': k = k + 1 form_data[k] = self.usr_tag(line.replace('\n', '')) return form_data # self.url=url def find_ez_base_url(self, link): form = self.find_form() for k in range(0, len(form)): self.twill_download(self, link, form[k]) # sa=open(self.site_list_form,'r') # listform=sa.readlines() # sa.close() # host= urlparse2(self.url).hostname # k=-1 # for line in listform: # if line.find(host)!=-1: # k=k+1 # form_data[k]=self.usr_tag(line) # # break # return form_data def usr_tag(self, pip): z = '--' try: s = pip.split('USER:' + z)[1].split(":")[0] proxy_info = { 'ezproxy_host': pip.split('USER:' + z)[0].replace(' ', ''), 'METODE': pip.split('METODE:' + z)[1].split(z)[0], 'Link_part': pip.split('Link_part:' + z)[1].split(z)[0], 'user': pip.split('USER:' + z)[1].split(":")[0], 'pass': pip.split('USER:' + z)[1].split(z)[0].split(":")[1], 'user_tag': pip.split('Form_Tag:' + z)[1].split(":")[0], 'pass_tag': pip.split('Form_Tag:' + z)[1].split(z)[0].split(":")[1], 'submit_tag_name': pip.split('Submit_tag:' + z)[1].split(":")[0], 'submit_tag_value': pip.split('Submit_tag:' + z)[1].split(z)[0].split(":")[1], 'Form_id': pip.split('Form_id:' + z)[1].split(z)[0], 'Form_Type': pip.split('Form_Type:' + z)[1].split(z)[0], 'database_link': pip.split('database_link:' + z)[1].split(z)[0].replace('\n', ''), 'Log_test': pip.split('Log_test:' + z)[1].split(z)[0].replace('\n', ''), # or 8080 or whatever 'Log_out': pip.split('Log_out:' + z)[1].split(z)[0].replace('\n', '') # or 8080 or whatever } try: proxy_info['pre_Link_part'] = pip.split('Link_pre_part:' + z)[1].split(z)[0] except: proxy_info['pre_Link_part'] = '' try: proxy_info['submit_tag_name2'] = pip.split('Submit_tag2:' + z)[1].split(":")[0] proxy_info['Link_part'] = pip.split('Link_part:' + z)[1].split(z)[0] proxy_info['user_tag2'] = pip.split('Form_Tag2:' + z)[1].split(":")[0] proxy_info['pass_tag2'] = pip.split('Form_Tag2:' + z)[1].split(z)[0].split(":")[1], proxy_info['submit_tag_value2'] = pip.split('Submit_tag2:' + z)[1].split(z)[0].split(":")[1] proxy_info['Form_id2'] = pip.split('Form_id2:' + z)[1].split(z)[0] proxy_info['Form_Type2'] = pip.split('Form_Type2:' + z)[1].split(z)[0].replace('\n', '') # or 8080 or whatever proxy_info['Log_test2'] = pip.split('Log_test2:' + z)[1].split(z)[0].replace('\n', '') # or 8080 or whatever proxy_info['input_type2'] = pip.split('input_type2:' + z)[1].split(z)[0].replace('\n', '') # or 8080 or whatever except: proxy_info['submit_tag_name2'] = '' # proxy_="http://%(user)s:%(pass)s@%(host)s:%(port)s" % proxy_info # proxy_handler = urllib2.ProxyHandler({"http" : "http://%(user)s:%(pass)s@%(host)s:%(port)s" % proxy_info}) except: try: proxy_info = { 'Form_Tag': pip.split('Form_Tag:')[1].replace('\n', '') # or 8080 or whatever } except: proxy_info = {} return proxy_info def splinter0(self): from splinter import Browser with Browser('firefox') as browser: browser.visit(self.url) browser.find_by_name('element_name').click() def login_to_site(self, link, form_data, proxy=[], User_Pass=[]): self.url = "%(ezproxy_host)s" % form_data self.database_link = "%(database_link)s" % form_data self.submit_tag_name2 = '%(submit_tag_name2)s' % form_data self.log_out = { 'log_out': "%(Log_out)s" % form_data, 'METODE': form_data['METODE']} username = "%(user)s" % form_data password = "%(pass)s" % form_data user_tag = "%(user_tag)s" % form_data pass_tag = "%(pass_tag)s" % form_data Form_id = "%(Form_id)s" % form_data Form_id2 = "%(Form_id2)s" % form_data log_done = "%(Log_test)s" % form_data self.Log_test2 = "%(Log_test2)s" % form_data self.Log_test = "%(Log_test)s" % form_data site = urlparse2(link).hostname br = mechanize.Browser(factory=mechanize.RobustFactory()) # Browser options br.set_handle_robots(False) br.set_handle_referer(True) br.set_handle_refresh(True) br.set_handle_equiv(True) br.set_handle_gzip(True) br.set_handle_redirect(True) policy = mechanize.DefaultCookiePolicy(rfc2965=True) cj = mechanize.LWPCookieJar(policy=policy) # cj = cookielib.LWPCookieJar() # cj.revert(cookie3) opener = mechanize.build_opener(mechanize.HTTPCookieProcessor(cj)) br.set_cookiejar(cj) self.cookies_dir = os.getcwd().replace('\\', '/') + '/sites_proxy/' + site + '/cookies' if not os.path.isdir(self.cookies_dir): os.mkdir(self.cookies_dir) chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" self.cookies = self.cookies_dir + '/' + ''.join([random.choice(chars) for x in range(5)]) + ".txt" cj.save(self.cookies) # Follows refresh 0 but not hangs on refresh > 0 br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1) # Want debugging messages? # User-Agent (this is cheating, ok?) # br.addheaders = [('User-agent', # 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')] # br.addheaders =[('Content-type', 'application/x-www-form-urlencoded'), ('Content-length', '39'), ('Referer', 'http://lib.just.edu.jo/login?url='), ('Host', 'lib.just.edu.jo'), ('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')] br.addheaders = [ ('User-agent', 'Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:24.0) Gecko/20100101 Firefox/24.0'), #'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1'), ('Accept', 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5;application/json;text/javascript;*/*'), ('Accept-Language', 'en,hu;q=0.8,en-us;q=0.5,hu-hu;q=0.3'), ('Accept-Encoding', 'gzip, deflate'), ('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.7'), ('Keep-Alive', '300'), ('Connection', 'keep-alive'), ('Cache-Control', 'max-age=0'), ('Referer', self.url), ('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'), ('X-Requested-With', 'XMLHttpRequest') ] cj.add_cookie_header(br) # # req = urllib2.Request(url, txheaders) # req2 = urllib2.urlopen(req) # print req2 if proxy != [] and not (re.findall('None:None', proxy)): br.proxies = br.set_proxies({"http": proxy}) # br.proxies=br.set_proxies( proxy) if User_Pass != [] and not (re.findall('None:None', User_Pass)): br.add_proxy_password(User_Pass.split(":")[0], User_Pass.split(":")[1]) try: openerdirector = br.open(self.url) html = openerdirector.read() print html except urllib2.HTTPError, e: print "Got error code", e.code # try: # br.open(self.url) # except urllib2.HTTPError, e: # print "Got error code", e.code except urllib2.URLError, e: return [], self.cookies, [], [], 0, self.log_out # print "Got error code", e.code # os.environ['http_proxy']='' if br.forms(): print [form for form in br.forms()] # br.select_form(name="USER") # [f.id for f in br.forms()] formcount = done = 0 for form in br.forms(): try: form_id = form.attrs['id'] except: form_id = '' if form_id == Form_id: br.form = form done = 1 if done == 0: formcount = formcount + 1 formcount = 0 for frm in br.forms(): try: form_id = form.attrs['id'] except: form_id = '' if str(form_id) == Form_id2: done = 1 if done == 0: formcount = formcount + 1 br.select_form(nr=formcount) # br.select_form(nr = 0) # self.submit_tag_value2='%(submit_tag_value2)s'%form_data # self.Form_id2='%(Form_id2)s'%form_data # self.Form_Type2='%(Form_Type2)s'%form_data if '%(user_tag)s' % form_data != '': br[user_tag] = username br[pass_tag] = password br.submit() # br.form.click("submit") html = br.response().get_data() print br.response().get_data() # print current url print "We are now at:", br.geturl() # print error if br.geturl() == log_done: print "Login Failed" else: print "Successfully logged in" if self.submit_tag_name2 != '' and re.findall(self.Log_test2, html): if br.forms(): pass for form in br.forms(): print form # print [form for form in br.forms()] # br.select_form(name="USER") # [f.id for f in br.forms()] formcount = done = 0 for form in br.forms(): try: form_id = form.attrs['id'] except: form_id = '' if form_id == Form_id: br.form = form done = 1 if done == 0: formcount = formcount + 1 formcount = 0 for frm in br.forms(): try: form_id = form.attrs['id'] except: form_id = '' if str(form_id) == Form_id: done = 1 if done == 0: formcount = formcount + 1 br.select_form(nr=formcount) # br.select_form(nr = 0) if '%(user_tag2)s' % form_data != '': br[user_tag] = username br[pass_tag] = password br.submit() html = br.response().get_data() print br.response().get_data() if re.findall(log_done, html): # if log_done in br.response().get_data(): print ("You are logged on to the Public Access to Court Electronic " "Records (PACER) Case Search website as " + username + ". All costs " "will be billed to this account.") # print "<li><a>" # print (link) # print "</a></li>" # print "<li><a>" # print link.base_url # print "</a></li>" self.site = urlparse2(link).hostname site2 = form_data['database_link'] self.base_url = 'http://' + self.site + '.' + site2 ez_link = 'http://' + self.site + '.' + site2 + link.split(self.site)[1] cj.save(self.cookies) # for link1 in br.links(): # # http://www.rfc-editor.org/rfc/rfc2606.txt # if re.findall(self.site, link1.url): # print(link1) # # Link(base_url='http://www.example.com/', url='http://www.rfc-editor.org/rfc/rfc2606.txt', text='RFC 2606', tag='a', attrs=[('href', 'http://www.rfc-editor.org/rfc/rfc2606.txt')]) # print(link1.url) # print('match found') # # match found # break # # br.follow_link(link1) # link still holds the last value it had in the loop # print(br.geturl()) # req = br.click_link(link1) # html = br.open(req).read() html2 = br.open(ez_link).read() print html2 br.set_cookiejar(cj) cj.save(self.cookies, ignore_discard=True, ignore_expires=True) # cj.save(self.cookies, ignore_discard=False, ignore_expires=False) # br._ua_handlers['_cookies'].cookiejar.save(self.cookies, ignore_discard=True, ignore_expires=True) # br._ua_handlers['_cookies'].cookiejar.save(self.cookies)#, ignore_discard=True, ignore_expires=True) # cookiefile=open(self.cookies,'w') # cookiestr='' # for c in br._ua_handlers['_cookies'].cookiejar: # cookiestr+=c.name+'='+c.value+';' # cookiefile.write(cookiestr) self.br = br; self.cj = cj; # time_diff = str(round(time.time() - time0, 2)) links, title = self.link_tag_find(html2, self.base_url) # mechanize._sockettimeout._GLOBAL_DEFAULT_TIMEOUT = 300 # socket=import_mod(from_module='socket') # socket.setdefaulttimeout(300) if ( links!=[] ): # return html2, self.cookies, links, title, 0, self.log_out pass try: links11=links br.set_cookiejar(cj) openerdirector = br.open(links) except: links11=links[0] br.set_cookiejar(cj) openerdirector = br.open(links[0]) else: return html, self.cookies, [], [], 0, self.log_out try: if (openerdirector._headers.dict['content-type']) == 'application/pdf': length = long(openerdirector._headers.dict['content-length']) ok = True else: length = 0 except: length = 0 for link1 in br.links(url_regex=".pdf"): # http://www.rfc-editor.org/rfc/rfc2606.txt # if re.findall(links11, link1.url): print(link1) # Link(base_url='http://www.example.com/', url='http://www.rfc-editor.org/rfc/rfc2606.txt', text='RFC 2606', tag='a', attrs=[('href', 'http://www.rfc-editor.org/rfc/rfc2606.txt')]) print(link1.url) print('match found') # match found break time.sleep(2) br.follow_link(link1) # link still holds the last value it had in the loop # print(br.geturl()) pdf_link=br.geturl() if pdf_link: br.set_cookiejar(cj) cj.save(self.cookies, ignore_discard=True, ignore_expires=True) # return html2, self.cookies, pdf_link, title, 0, self.log_out localName = LINK(PDF_Dir=PDF_Dir, Watermarked_PDF_Files_Dir=Watermarked_PDF_Files_Dir).filename2( pdf_link) f1 = self.br.retrieve(pdf_link, localName.pdf_Folder_filename) if f1: cj.save(self.cookies, ignore_discard=True, ignore_expires=True) # return f1[0], self.cookie3 return f1[0], self.cookies, pdf_link, title, 0, self.log_out # f1 = br.retrieve(pdf_link) # if length==0: # return html2, self.cookies, [], [], 0, self.log_out # dlength = 0 piece_size = 4096 # 4 KiB # piece_size =1024*1024 # 1MB data = '' newdata = openerdirector.read(piece_size) print newdata f1 = br.retrieve(link1) if f1: self.cj.save(self.cookie3) return f1[0], self.cookie3 #,pdf_path import pickle # with open(self.cookies, 'wb') as f: # pickle.dump(cj, f) # html,pr,upss,cookies=web().download_mechanism_link(links,'None:None',cookies=self.cookies);mech=1 # print html # html, cookies2 = MECAHNIZM('None:None', '', cookies=self.cookies, url=links11).download_pdf_br(links11) print html # if link != []: # return html2, self.cookies, links, title, 0, self.log_out # return html2, self.cookies, [], [], 0, self.log_out # frontpage,cookies = MECAHNIZM([],[],cookies=self.cookies,url=ez_link).speed_download(ez_link) request = br.request header = request.header_items() # header=request.get_header() # Browser options br.set_handle_robots(False) # br.set_handle_referer(True) # br.set_handle_refresh(True) # br.set_handle_equiv(True) br.set_handle_gzip(True) # br.set_handle_redirect(True) cj = cookielib.LWPCookieJar() # cj.revert(cookie3) opener = mechanize.build_opener(mechanize.HTTPCookieProcessor(cj)) br.set_cookiejar(cj) cj.save(self.cookies) # Follows refresh 0 but not hangs on refresh > 0 br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1) time0 = time.time() # request = urllib2.Request(ez_link, None, header) # openerdirector = br.open(request) # br.addheaders(header) openerdirector = br.open(links11) try: if (openerdirector._headers.dict['content-type']) == 'application/pdf': length = long(openerdirector._headers.dict['content-length']) ok = True else: length = 0 except: length = 0 dlength = 0 # piece_size = 4096 # 4 KiB piece_size = 1024 * 1024 # 1MB data = '' while True: newdata = openerdirector.read(piece_size) dlength += len(newdata) data += newdata if length != 0: status = r"%10d [%3.2f%%]" % (dlength, dlength * 100. / length) status = status + chr(8) * (len(status) + 1) print status # pdf_path=PDF_File().file_save(data, "PDF_Files\\", localName.filename) # if onprogress: # onprogress(length,dlength) if not newdata: cj.save(self.cookies) break self.br = br; self.cj = cj; time_diff = str(round(time.time() - time0, 2)) links, title = self.link_tag_find(data, self.base_url) if links != []: return data, self.cookies, links, title, time_diff return data, self.cookies #,pdf_path else: # raise ValueError("Could not login to PACER Case Search. Check your " # "username and password") return html, self.cookies, [], [], 0, self.log_out return html, self.cookies, [], [], 0, self.log_out def link_tag_find(self, html, base_url): # try: # # title=LINK().find_my_tilte(data=html,start_dash='<h1 class="article-title"',end_dash='1>',make_url=False) # # title = LINK().find_my_tilte(data=html, start_dash='type="image/x-icon"><title>', end_dash='</title>',make_url=False) # title=LINK().find_my_tilte(data=html,start_dash='<title>',end_dash='</title>',make_url=False) # except: # title = '' # # links = LINK().find_my_tilte(data=html, start_dash='<a id="pdfLink" href="', end_dash='"', make_url=True) # # if links == [] or links == '': # links = LINK().soap_my(data=html, tag='pdfLink', attr='a', href='href', url=base_url) # if links == '' or links == []: # links = LINK().soap_my(data=html, tag='title="Download PDF" ', attr='a', href='href', url=base_url) # if title == '' or title == []: # title = LINK().soap_my(data=html, tag='class="article-title"', attr='h1', href='', url=base_url) # if title == '' or title == []: # title = LINK().soap_my(data=html, tag='<title>', attr='', href='', url=base_url) # if links != []: # pass [links, title] = link_tag_find(html, base_url) return links, title def twill_download(self, url, cookies): # self.url="%(ezproxy_host)s"%form_data # self.database_link="%(database_link)s"%form_data # self.username="%(user)s"%form_data # self.password="%(pass)s"%form_data # self.user_tag="%(user_tag)s"%form_data # self.pass_tag="%(pass_tag)s"%form_data # self.Form_id="%(Form_id)s"%form_data # self.submit_tag_name="%(submit_tag_name)s"%form_data # self.submit_tag_value="%(submit_tag_value)s"%form_data # self.Form_Type="%(Form_Type)s"%form_data # self.log_done="%(Log_test)s"%form_data link = url['link']; lg = url['log_out']; url_logout = lg['log_out']; ez_link = lg['ez_link'] twil__headers = lg['headers'] try: link = lg['pdf_link'] # site = urlparse2(link.absolute_url).hostname except: pass # site = urlparse2(link).hostname # self.a.config("readonly_controls_writeable", 1) # self.b = self.a.get_browser() # self.b.set_agent_string("Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14") # self.b.clear_cookies() twill = import_mod(from_module='twill') # t_com = twill.commands # t_com.reset_browser # t_com.reset_output t_com = twill.commands ## get the default browser t_brw = t_com.get_browser() # try: # t_brw.set_agent_string( # "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14") # # t_com.add_extra_header('User-agent', # 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1') # t_com.add_extra_header('Accept', # 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5;application/json;text/javascript;*/*') # t_com.add_extra_header('Accept-Language', 'en,hu;q=0.8,en-us;q=0.5,hu-hu;q=0.3') # t_com.add_extra_header('Accept-Encoding', 'gzip, deflate') # t_com.add_extra_header('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.7') # t_com.add_extra_header('Keep-Alive', '300') # t_com.add_extra_header('Connection', 'keep-alive') # t_com.add_extra_header('Cache-Control', 'max-age=0') # t_com.add_extra_header('Referer', ez_link) # t_com.add_extra_header('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8') # t_com.add_extra_header('X-Requested-With', 'XMLHttpRequest') # # t_com.add_extra_header('User-agent', # 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1') # t_com.add_extra_header('Accept', # "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5;application/json;text/javascript;*/*") # t_com.add_extra_header('Accept-Language', 'en,hu;q=0.8,en-us;q=0.5,hu-hu;q=0.3') # t_com.add_extra_header('Accept-Encoding', 'gzip, deflate') # t_com.add_extra_header('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.7') # t_com.add_extra_header('Keep-Alive', '300') # t_com.add_extra_header('Connection', 'keep-alive') # t_com.add_extra_header('Cache-Control', 'max-age=0') # t_com.add_extra_header('Referer', ez_link) # t_com.add_extra_header('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8') # t_com.add_extra_header('X-Requested-With', 'XMLHttpRequest') # except: # pass t_brw.set_agent_string(twil__headers) # t_brw._browser.addheaders = [] # del twil__headers[-1] # twil__headers += [('Referer', ez_link)] # t_brw._browser.addheaderst=twil__headers # t_com.add_extra_header('Referer', ez_link) #used foe some exproxies # cookies=cookies.replace('/','\\') t_brw.load_cookies(cookies) # socket=import_mod(from_module='socket') # socket.setdefaulttimeout(300) ## open the url # url = 'http://google.com' # t_brw.find_link(link) # t_brw.go(link) print '@@@@@@@@@@@@@ link download by twill is @@@@@@@@@@@@' print link print '@@@@@@@@@@@@@ link download by twill is @@@@@@@@@@@@' # import sys # sys.exit(1) # t2=t_brw.find_link('Download PDF') # t_brw.follow_link(t2) try: t_brw._browser.addheaders = [] del twil__headers[-1] twil__headers += [('Referer', ez_link)] t_brw._browser.addheaderst=twil__headers try: t2=t_brw.find_link('Download PDF') t_brw.follow_link(t2) except: t_brw = t_com.get_browser() t_brw.set_agent_string(twil__headers) t_brw.load_cookies(cookies) if len(link.absolute_url[0])!=1: s = link.absolute_url[0] s2 = type('test', (object,), {})() s2.absolute_url=link.absolute_url[0] s2.base_url=link.base_url print s2.absolute_url t_brw.follow_link(s2) else: t_brw.follow_link(link) except: # t_brw.set_agent_string(twil__headers) # t_com.add_extra_header('Referer', ez_link) try: if len(link.absolute_url[0])!=1: s = link.absolute_url[0] s2 = type('test', (object,), {})() s2.absolute_url=link.absolute_url[0] s2.base_url=link.base_url print s2.absolute_url t_brw.go(s2.absolute_url) else: t_brw.go(link.absolute_url) except: t_brw.set_agent_string(twil__headers) t_com.add_extra_header('Referer', ez_link) t_brw.go(link) # class link_n(object): # def __init__(self): # self.absolute_url = link # self.base_url = ez_link # self.url=ez_link # def url(self): # return self # link=link_n.url # t_brw.follow_link(link) html0 = t_brw.result.page print '@@@@@@@@@@@@@ html0 download by twill is @@@@@@@@@@@@' print html0[:20] print '@@@@@@@@@@@@@ html0 download by twill is @@@@@@@@@@@@' # time.sleep(10) link2 = t_brw.result.url link2 = link.absolute_url if not (html0[:4] == '%PDF') or html0 == []: t_brw.set_agent_string(twil__headers) t_com.add_extra_header('Referer', ez_link) t_brw.go(link2) html2 = t_brw.result.page html, cookies = MECAHNIZM('', '', cookies=cookies, url=link2).speed_download(link2) # html3,pr,upss,cookies=web().download_mechanism_link(link,'',cookies=cookies) if not (html[:4] == '%PDF') or html == []: t_brw.save_cookies(cookies) t_brw = t_com.get_browser() t_brw.set_agent_string( "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14") t_brw.load_cookies(cookies) # socket=import_mod(from_module='socket') # socket.setdefaulttimeout(300) html3, pr, upss, cookies = web().download_mechanism_link(link, '', cookies=cookies) t_brw.go(link2) html = t_brw.result.page print '@@@@@@@@@@@@@ html download by twill is @@@@@@@@@@@@' print html print '@@@@@@@@@@@@@ html download by twill is @@@@@@@@@@@@' # time.sleep(10) else: html = html0 t_brw.go(url_logout) os.remove(cookies) return html def twill_find_link_robobrowser(self, link, form_data): # from goto import goto, label self.url = "%(ezproxy_host)s" % form_data self.database_link = "%(database_link)s" % form_data self.Link_part = "%(Link_part)s" % form_data self.pre_Link_part = "%(pre_Link_part)s" % form_data self.username = "%(user)s" % form_data self.password = "%(pass)s" % form_data self.user_tag = "%(user_tag)s" % form_data self.pass_tag = "%(pass_tag)s" % form_data self.Form_id = "%(Form_id)s" % form_data self.submit_tag_name = "%(submit_tag_name)s" % form_data self.submit_tag_value = "%(submit_tag_value)s" % form_data self.Form_Type = "%(Form_Type)s" % form_data self.Log_test2 = "%(Log_test2)s" % form_data self.input_type2 = form_data['input_type2'] self.log_done = "%(Log_test)s" % form_data self.log_out = { 'log_out': "%(Log_out)s" % form_data, 'METODE': form_data['METODE']} self.submit_tag_name2 = '%(submit_tag_name2)s' % form_data site = urlparse2(link).hostname self.cookies_dir = os.getcwd().replace('\\', '/') + '/sites_proxy/' + site + '/cookies' if not os.path.isdir(self.cookies_dir): os.mkdir(self.cookies_dir) chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" self.cookies = self.cookies_dir + '/' + ''.join([random.choice(chars) for x in range(5)]) + ".txt" # self.a.config("readonly_controls_writeable", 1) # self.b = self.a.get_browser() # self.b.set_agent_string("Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14") # self.b.clear_cookies() time0 = time.time() try: i=o except: # from robobrowser import RoboBrowser RoboBrowser = import_mod(from_module='robobrowser',from_module2="RoboBrowser") # import requests requests = import_mod(from_module='requests') # browser = RoboBrowser(history=False) # user_agent2 = "Mozilla/5.0 (Windows NT 6.1; rv:18.0) Gecko/20100101 Firefox/18.0" s = requests.Session() s.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0' s.headers['Referer']= self.url s.headers['Accept']='text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' s.headers['Accept-Language']= 'en-US,en;q=0.5' s.headers['Accept-Encoding']= 'gzip, deflate' # s.headers['Accept-Charset']= 'ISO-8859-1,utf-8;q=0.7,*;q=0.7' # s.headers['Keep-Alive']= '300' s.headers['Connection']= 'keep-alive' # s.headers['Cache-Control']= 'max-age=0, no-cache, no-store' # s.headers['Content-Type']= 'application/x-www-form-urlencoded; charset=UTF-8' # s.headers['X-Requested-With']= 'XMLHttpRequest' # s.headers["Host"]= "consultaremota.upb.edu.co" browser = RoboBrowser(session=s,history=True,allow_redirects=True,cache=True,tries=10) browser.open(self.url) # request = browser.session.get(self.url, stream=True) # get form # fm=browser.get_forms() # your_form_variable = browser.get_form(your_form_id="create_event") # your_form_variable = browser.get_form(action='/login') your_form_variable = browser.get_forms()[int(self.Form_id)] # complete form your_form_variable [self.user_tag] = self.username # try: your_form_variable [self.pass_tag] = self.password #string or int? except: print "no password in forms" # submit form & log out browser.submit_form(your_form_variable) html = str(browser.parsed) if self.submit_tag_name2 != '' and re.findall(self.Log_test2, html): song_link = browser.get_link(self.log_done) browser.follow_link(song_link) site2 = self.Link_part if self.pre_Link_part != '': base_url = 'http://' + site + '.' + site2 ez_link = 'http://' + site + '.' + site2 + link.split(site)[1] if site2 == '': base_url = 'http://' + self.pre_Link_part ez_link = 'http://' + self.pre_Link_part + link.split(site)[1] else: if site2 == '': base_url = 'http://' ez_link = 'http://' + link.split(site)[1] else: base_url = 'http://' + site2 ez_link = 'http://' + site2 + link.split(site)[1] # s.headers["Host"]= "dl.acm.org.consultaremota.upb.edu.co" # browser.session.headers["Host"]= "dl.acm.org.consultaremota.upb.edu.co" browser.open(ez_link) song_link = browser.get_links() html0 = unicode(browser.parsed) html=str(html0.encode('utf-8')) [links, title] = link_tag_find(html, base_url) for link in song_link: if len(re.findall('pdfLink',str(link)))!=0: link_new=link; break url_new=str(link_new).split('href="')[1].split('"')[0] url_new=url_new.replace('amp;','') # ue='ft_gateway.cfm?id=100000&ftid=75414&dwn=1&CFID=793464469&CFTOKEN=31448951' url=browser._build_url(url_new) headers=browser.session.headers;print browser.session.headers # headers.replace(self.url,ez_link) # headers._store["referer"]=("Referer",ez_link) # re_link='http://consultaremota.upb.edu.co/login?url=http://dl.acm.org/'+url_new # browser.session.headers['Referer'] =re_link browser.session.headers['Referer'] =ez_link # browser.session.headers['Referer'] ='http://dl.acm.org.consultaremota.upb.edu.co' # browser.session.headers["Host"]= "dl.acm.org.consultaremota.upb.edu.co" # browser.session.headers=headers; print browser.session.headers cookies=browser.session.cookies;print browser.session.cookies # headers = { # "Accept-Encoding": "gzip, deflate", # "Accept-Language": "en-US,en;q=0.8,ru;q=0.6", # "User-Agent": "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.65 Safari/537.36", # "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", # 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', # "Referer": ez_link, # "X-Requested-With": "XMLHttpRequest", # "Connection": "keep-alive", # "Cache-Control": "max-age=0", # "Host": "dl.acm.org.consultaremota.upb.edu.co" # # } # headers._store["Host"]=("Host",'dl.acm.org.consultaremota.upb.edu.co') # browser.session.headers['Host'] ='dl.acm.org.consultaremota.upb.edu.co' headers=browser.session.headers;print browser.session.headers # browser.session.headers["Host"]= "delivery.acm.org" browser.follow_link(link_new, stream=True,timeout=300) html0 = unicode(browser.parsed._most_recent_element) html=str(html0.encode('utf-8')) # print song_link2 if False: request =browser.session.get(str(url), stream=True, allow_redirects=True, headers=headers,cookies=cookies) url2=str(request.url) cookies2=browser.session.cookies; print browser.session.cookies # headers._store["Host"]=("Host",'delivery.acm.org') # browser.session.headers=headers # url3='http://delivery.acm.org/10.1145/100000/100000/p170-neumann.pdf?ip=200.3.144.114&id=100000&acc=ACTIVE%20SERVICE&key=4D9619BEF5D5941F%2EA6DE646D1D737837%2E4D4702B0C3E38B35%2E4D4702B0C3E38B35&CFID=793190669&CFTOKEN=12845451&__acm__=1464765630_14e7a0892ee2d0e1edce5edc224ce9b0' request =browser.session.get(str(url2), allow_redirects=True,stream=True, headers=headers) # song_link = browser.get_link(self.log_done) # browser.session.headers["Host"]= "delivery.acm.org" # browser.follow_link(link_new, stream=True) # song_link2 = browser.parsed # print song_link2 # song_link = browser.get_links()request =browser.session.get(str(url), stream=True) # your_form_variable2 = browser.get_forms()[0] # your_form_variable2 ["Go"] = "Inside risks: the clock grows at midnight" # browser.submit_form(your_form_variable2) # song_link22 = browser.parsed # print song_link22 # # your_form_variable2 = browser.get_forms()[1] # your_form_variable2 ["Go"] = "Inside risks: the clock grows at midnight" # browser.submit_form(your_form_variable2) # song_link22 = browser.parsed # print song_link22 # [links, title] = link_tag_find(html, base_url) self.log_out = { 'log_out': "%(Log_out)s" % form_data, 'METODE': form_data['METODE'], 'ez_link': ez_link, 'headers': headers, 'pdf_link': links} time_diff = str(round(time.time() - time0, 2)) return html, self.cookies, links, title, time_diff, self.log_out def twill_find_link(self, link, form_data): # from goto import goto, label self.url = "%(ezproxy_host)s" % form_data self.database_link = "%(database_link)s" % form_data self.Link_part = "%(Link_part)s" % form_data self.pre_Link_part = "%(pre_Link_part)s" % form_data self.username = "%(user)s" % form_data self.password = "%(pass)s" % form_data self.user_tag = "%(user_tag)s" % form_data self.pass_tag = "%(pass_tag)s" % form_data self.Form_id = "%(Form_id)s" % form_data self.submit_tag_name = "%(submit_tag_name)s" % form_data self.submit_tag_value = "%(submit_tag_value)s" % form_data self.Form_Type = "%(Form_Type)s" % form_data self.Log_test2 = "%(Log_test2)s" % form_data self.input_type2 = form_data['input_type2'] self.log_done = "%(Log_test)s" % form_data self.log_out = { 'log_out': "%(Log_out)s" % form_data, 'METODE': form_data['METODE']} self.submit_tag_name2 = '%(submit_tag_name2)s' % form_data site = urlparse2(link).hostname self.cookies_dir = os.getcwd().replace('\\', '/') + '/sites_proxy/' + site + '/cookies' if not os.path.isdir(self.cookies_dir): os.mkdir(self.cookies_dir) chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" self.cookies = self.cookies_dir + '/' + ''.join([random.choice(chars) for x in range(5)]) + ".txt" # self.a.config("readonly_controls_writeable", 1) # self.b = self.a.get_browser() # self.b.set_agent_string("Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14") # self.b.clear_cookies() twill = import_mod(from_module='twill') # import twill t_com = twill.commands t_com.reset_browser t_com.reset_output t_com = twill.commands ## get the default browser t_brw = t_com.get_browser() # t_brw.set_agent_string("Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14") # t_com.add_extra_header('User-agent', # 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1') t_com.add_extra_header('User-agent', 'Mozilla/5.0 (Windows NT 6.1; rv:18.0) Gecko/20100101 Firefox/18.0') t_com.add_extra_header('Accept', 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5;application/json;application/atom+xml;text/javascript;*/*') t_com.add_extra_header('Accept-Language', 'en,hu;q=0.8,en-us;q=0.5,hu-hu;q=0.3') t_com.add_extra_header('Accept-Encoding', 'gzip, deflate') t_com.add_extra_header('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.7') t_com.add_extra_header('Keep-Alive', '300') t_com.add_extra_header('Connection', 'keep-alive') t_com.add_extra_header('Cache-Control', 'max-age=0, no-cache, no-store') t_com.add_extra_header('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8') # t_com.add_extra_header('Content-Type', 'application/x-www-form-urlencoded; charset=latin-1') t_com.add_extra_header('X-Requested-With', 'XMLHttpRequest') t_com.add_extra_header('X-ELS-ResourceVersion', 'XOCS') t_com.add_extra_header('Host', 'link.springer.com') t_com.add_extra_header('Referer', self.url) ## open the url # url = 'http://google.com' t_com.save_cookies(self.cookies) t_brw.load_cookies(self.cookies) # print t_com.show_extra_headers() # print t_com.show_cookies() # try:t_brw.go(self.log_out['log_out']) # except:pass try: t_brw.go(self.url) except: html=[];links=[];title=[];time_diff='0' return html, self.cookies, links, title, time_diff, self.log_out # t_brw.reload html = t_brw.result.page # print t_com.show_extra_headers() # print t_com.show_cookies() # print html # print fill_login_form(url, html, "john", "secret") if re.findall(self.log_done, html): # goto .find print ("You are logged on to the Public Access to Court Electronic " "Records (PACER) Case Search website as " + self.url + ". All costs " "will be billed to this account.") # t_brw.go(self.database_link) # site = urlparse2(link).hostname # site2 = urlparse2(self.url).hostname link2 = t_brw.result.url site2 = self.Link_part if self.pre_Link_part != '': base_url = 'http://' + site + '.' + site2 ez_link = 'http://' + site + '.' + site2 + link.split(site)[1] else: base_url = 'http://' + site2 ez_link = 'http://' + site2 + link.split(site)[1] time0 = time.time() t_brw.go(ez_link) time_diff = str(round(time.time() - time0, 2)) try: content1 = t_brw.result.page # print 'debug twill post content:', content # print 'debug twill post content:', content import StringIO content1 = StringIO.StringIO(content1) import gzip gzipper = gzip.GzipFile(fileobj=content1) html = gzipper.read() except: html = t_brw.result.page # html = t_brw.result.page # f=1 # links=LINK().find_my_tilte(data=html,start_dash='<a id="pdfLink" href="',end_dash='"',make_url=True) # # if links==''or links==[]: # links =LINK().soap_my(data=html, tag='title="Download PDF" ', attr='a', href='href',url=base_url) # # if links==[] or links=='': # links =LINK().soap_my(data=html, tag="Download PDF", attr='a', href='href',url=base_url) # if links==[] or links=='': # links=LINK().soap_my(data=html,tag='pdfLink',attr='a',href='href',url=base_url) # re.findall('if(SDM.pageType'.html) # if self.submit_tag_name2!='' and not re.findall ( "SDM.pageType",html ): # if self.submit_tag_name2!='' and re.findall ( self.log_done2,html ): if self.submit_tag_name2 != '' and re.findall(self.Log_test2, html): #"Choose Organization",html ): self.submit_tag_value2 = '%(submit_tag_value2)s' % form_data self.Form_id2 = '%(Form_id2)s' % form_data self.Form_Type2 = '%(Form_Type2)s' % form_data all_forms = t_brw.get_all_forms() ## this returns list of form objects print "Forms:" t_brw.showforms() ## now, you have to choose only that form, which is having POST method self.formnumber = 0 formnumber = 1 for each_frm in all_forms: self.formnumber = 1 + self.formnumber attr = each_frm.attrs ## all attributes of form try: form_id = each_frm.attrs['id'] except: form_id = '' if each_frm.method == 'POST' and (form_id == self.Form_id2 ): ctrl = each_frm.controls for ct in ctrl: if ct.type == self.input_type2: ## i did it as per my use, you can put your condition here # ct._value = "twill" # t_com.clicked(each_frm,'%(user_tag2)s'%form_data) ## clicked takes two parameter, form object and button name to be clicked. t_com.showforms() t_com.fv(self.formnumber, '%(user_tag2)s' % form_data, each_frm.controls[3]._value) t_com.showforms() t_com.submit() content = t_com.show() break # print 'debug twill post content:', content # t_com.formclear(formnumber) # va=each_frm.controls[3]._value # t_com.fv(self.formnumber, '%(user_tag2)s'%form_data, each_frm.controls[3]._value) # # t_com.fv(self.formnumber, self.pass_tag, self.password) # print "Forms:" # t_brw.showforms() # # t_com.submit(self.formnumber) # # t_brw.submit(self.submit_tag_name) # t_com.submit(self.submit_tag_name2) # # # content = t_com.show() # print 'debug twill post content:', content # t_com.save_cookies(self.cookies) t_brw.save_cookies(self.cookies) t_brw.load_cookies(self.cookies) # print t_brw.find_link('http://64.62.211.131:2082/frontend/x3/mail/fwds.html') t_brw.save_cookies(self.cookies) # print t_com.show_extra_headers() # print t_com.show_cookies() print t_com.showlinks() links2 = t_com.showlinks() # print t_brw.result.page try: content1 = t_brw.result.page # print 'debug twill post content:', content # print 'debug twill post content:', content import StringIO content1 = StringIO.StringIO(content1) import gzip gzipper = gzip.GzipFile(fileobj=content1) html = gzipper.read() except: html = t_brw.result.page # print t_com.show_extra_headers() headers = t_com.show_extra_headers() [links_0, title] = link_tag_find(html, base_url) # time0 = time.time() # t_brw.load_cookies(self.cookies) # t_brw.go(links_0[0]) # time_diff = str(round(time.time() - time0, 2)) # html = t_brw.result.page # if (not (html.endswith('.pdf'))) and html[:4]!='%PDF' : # return html, self.cookies, [], [], 0, self.log_out if len(links_0)>1: base_url_list=[];links_list=[] for links in links_0: if not (links == '' or links == []): if self.pre_Link_part != '': base_url = 'http://' + site + '.' + site2 links = 'http://' + site + '.' + site2 + links.split(site)[1] if site2 == '': base_url = 'http://' + self.pre_Link_part links = 'http://' + self.pre_Link_part + links.split(site)[1] else: if site2 == '': base_url = 'http://' links = 'http://' + links.split(site)[1] else: base_url = 'http://' + site2 try: links = 'http://' + site2 + links.split(site)[1] except: links=links_0[0] base_url_list.append(base_url);links_list.append(links) elif len(links_0)==1: links =links_0 if not (links == '' or links == []): if self.pre_Link_part != '': base_url = 'http://' + site + '.' + site2 links = 'http://' + site + '.' + site2 + links.split(site)[1] if site2 == '': base_url = 'http://' + self.pre_Link_part links = 'http://' + self.pre_Link_part + links.split(site)[1] else: if site2 == '': base_url = 'http://' links = 'http://' + links.split(site)[1] else: base_url = 'http://' + site2 links = 'http://' + site2 + links.split(site)[1] try: links=links_list base_url=base_url_list except:pass try: # title=LINK().find_my_tilte(data=html,start_dash='<h1 class="article-title"',end_dash='1>',make_url=False) if title=='' or title==[]: title = LINK().find_my_tilte(data=html, start_dash='type="image/x-icon"><title>', end_dash='</title>', make_url=False) except: title = '' links1 = t_brw.find_link('Download PDF') if links1 == '' or links1 == [] or links1 == 'None' or links1 == None: links = LINK().find_my_tilte(data=html, start_dash='<a id="pdfLink" href="', end_dash='"', make_url=True) if links == '' or links == []: links = LINK().soap_my(data=html, tag='title="Download PDF" ', attr='a', href='href', url=base_url) if links == [] or links == '': links = LINK().soap_my(data=html, tag="Download PDF", attr='a', href='href', url=base_url) if links == [] or links == '': links = LINK().soap_my(data=html, tag='pdfLink', attr='a', href='href', url=base_url) else: links = links1.absolute_url self.log_out = { 'log_out': "%(Log_out)s" % form_data, 'METODE': form_data['METODE'], 'ez_link': ez_link, 'headers': t_brw._browser.addheaders, 'pdf_link': links1} if title == '' or title == []: title = LINK().soap_my(data=html, tag='class="article-title"', attr='h1', href='', url=base_url) if title == '' or title == []: title = LINK().soap_my(data=html, tag='<title>', attr='', href='', url=base_url) if links != []: # t_brw.go(links) # html0=t_brw.result.page # print '@@@@@@@@@@@@@ html0 download by twill is @@@@@@@@@@@@' # print html0 # print '@@@@@@@@@@@@@ html0 download by twill is @@@@@@@@@@@@' # time.sleep(10) # link2=t_brw.result.url # print '@@@@@@@@@@@@@ time.sleep(10) download by twill is @@@@@@@@@@@@' # print link2 # print '@@@@@@@@@@@@@ time.sleep(10) download by twill is @@@@@@@@@@@@' # time.sleep(10) # if not (html0[:4]=='%PDF') or html0==[] : # html2,cookies = MECAHNIZM('','',cookies=self.cookies,url=link2).speed_download(link2) # print '@@@@@@@@@@@@@ MECAHNIZM download by twill is @@@@@@@@@@@@' # print html2 # print '@@@@@@@@@@@@@ MECAHNIZM download by twill is @@@@@@@@@@@@' # time.sleep(10) return html, self.cookies, links, title, time_diff, self.log_out else: return html, self.cookies, links, title, time_diff, self.log_out ## get all forms from that URL try: # s=uti all_forms = t_brw.get_all_forms() ## this returns list of form objects print "Forms:" t_brw.showforms() ## now, you have to choose only that form, which is having POST method self.formnumber = 0 formnumber = 1 for each_frm in all_forms: self.formnumber = 1 + self.formnumber attr = each_frm.attrs ## all attributes of form try: form_id = each_frm.attrs['id'] except: form_id = '' if each_frm.method == 'POST' and ((form_id == self.Form_id ) or ( str(self.formnumber )== self.Form_id )): t_com.formclear(formnumber) t_com.fv(self.formnumber, self.user_tag, self.username) t_com.fv(self.formnumber, self.pass_tag, self.password) all_forms = t_brw.get_all_forms() ## this returns list of form objects print "Forms:" t_brw.showforms() # t_com.submit(self.formnumber) # t_brw.submit(self.submit_tag_name) site2 = self.Link_part if True: if self.pre_Link_part != '': base_url = 'http://' + site + '.' + site2 ez_link = 'http://' + site + '.' + site2 + link.split(site)[1] if site2 == '': base_url = 'http://' + self.pre_Link_part ez_link = 'http://' + self.pre_Link_part + link.split(site)[1] else: if site2 == '': base_url = 'http://' ez_link = 'http://' + link.split(site)[1] else: base_url = 'http://' + site2 ez_link = 'http://' + site2 + link.split(site)[1] # time0 = time.time() # twil__headers=t_brw._browser.addheaders # del twil__headers[-1] # twil__headers += [('Referer', ez_link)] # t_com.add_extra_header = [] # # t_brw._browser.addheaderst=twil__headers # t_com.add_extra_header=twil__headers t_com.submit(self.submit_tag_name) # # html=t_brw.result.page # print html # content = t_com.show() try: content1 = t_brw.result.page # print 'debug twill post content:', content # print 'debug twill post content:', content import StringIO content1 = StringIO.StringIO(content1) import gzip gzipper = gzip.GzipFile(fileobj=content1) content = gzipper.read() except: content = t_brw.result.page t_com.save_cookies(self.cookies) # t_brw.load_cookies(self.cookies) except:content='' if re.findall(self.log_done, content): # label .find print ("You are logged on to the Public Access to Court Electronic " "Records (PACER) Case Search website as " + self.url + ". All costs " "will be billed to this account.") # t_brw.go(self.database_link) # site = urlparse2(link).hostname # site2 = self.database_link site2 = self.Link_part if self.pre_Link_part != '': base_url = 'http://' + site + '.' + site2 ez_link = 'http://' + site + '.' + site2 + link.split(site)[1] if site2 == '': base_url = 'http://' + self.pre_Link_part ez_link = 'http://' + self.pre_Link_part + link.split(site)[1] else: if site2 == '': base_url = 'http://' ez_link = 'http://' + link.split(site)[1] else: base_url = 'http://' + site2 ez_link = 'http://' + site2 + link.split(site)[1] time0 = time.time() twil__headers=t_brw._browser.addheaders del twil__headers[-1] twil__headers += [('Referer', ez_link)] t_brw._browser.addheaders = [] t_brw._browser.addheaderst=twil__headers t_brw.go(ez_link) time_diff = str(round(time.time() - time0, 2)) try: content1 = t_brw.result.page # print 'debug twill post content:', content # print 'debug twill post content:', content import StringIO content1 = StringIO.StringIO(content1) import gzip gzipper = gzip.GzipFile(fileobj=content1) html = gzipper.read() except: html = t_brw.result.page t_com.save_cookies(self.cookies) # t_brw.load_cookies(self.cookies) # if self.submit_tag_name2!=''and not re.findall ( "SDM.pageType",html ): if self.submit_tag_name2 != '' and re.findall(self.Log_test2, html): #"Choose Organization",html ): self.submit_tag_value2 = '%(submit_tag_value2)s' % form_data self.Form_id2 = '%(Form_id2)s' % form_data self.Form_Type2 = '%(Form_Type2)s' % form_data all_forms = t_brw.get_all_forms() ## this returns list of form objects print "Forms:" t_brw.showforms() ## now, you have to choose only that form, which is having POST method self.formnumber = 0 formnumber = 1 for each_frm in all_forms: self.formnumber = 1 + self.formnumber attr = each_frm.attrs ## all attributes of form try: form_id = each_frm.attrs['id'] except: form_id = '' if each_frm.method == 'POST' and (form_id == self.Form_id2 ): ctrl = each_frm.controls for ct in ctrl: if ct.type == self.input_type2: ## i did it as per my use, you can put your condition here # ct._value = "twill" # t_com.clicked(each_frm,'%(user_tag2)s'%form_data) ## clicked takes two parameter, form object and button name to be clicked. t_com.showforms() # t_com.fv(self.formnumber, form_data['user_tag2'], each_frm.controls[3]._value) t_com.fv(self.formnumber, form_data['user_tag2'], ct._value) t_com.showforms() t_com.submit() content = t_com.show() break # print 'debug twill post content:', content # t_com.formclear(formnumber) # va=each_frm.controls[3]._value # t_com.fv(self.formnumber, '%(user_tag2)s'%form_data, each_frm.controls[3]._value) # # t_com.fv(self.formnumber, self.pass_tag, self.password) # print "Forms:" # t_brw.showforms() # # t_com.submit(self.formnumber) # # t_brw.submit(self.submit_tag_name) # t_com.submit(self.submit_tag_name2) # # # content = t_com.show() # print 'debug twill post content:', content # t_com.save_cookies(self.cookies) t_brw.save_cookies(self.cookies) # cj.save(self.cookies, ignore_discard=True, ignore_expires=True) # t_brw.load_cookies(self.cookies) html = t_brw.result.page[:14100] else: pass # html=html; # print t_brw.find_link('http://64.62.211.131:2082/frontend/x3/mail/fwds.html') # print t_brw._browser.addheaders # print t_com.show_cookies() # print t_com.showlinks() # # print t_brw.result.page # import twill # t_com = twill.commands # ## get the default browser # t_brw = t_com.get_browser() # html=t_brw.result.page[:14100] t_com.save_cookies(self.cookies) # t2=t_brw.find_link('Download PDF') # t_brw.follow_link(t2) # print '@@@@@@@@@@@@@ html0 download by twill is @@@@@@@@@@@@\n' # if links == '' or links == []: if True: # links1 = t_brw.find_link('Download PDF') # else: try: t_brw.showlinks() links1 = t_brw.find_link('PDF Full Text') if links1==None: links1 = t_brw.find_link('PDF Full Text') # links1.absolute_url = links links=links1.absolute_url except:links1=[];links=[] if links==[]: [links, title] = link_tag_find(html, base_url) else: [links, title] = link_tag_find(html, base_url,links) # twil__headers=t_brw._browser.addheaders del twil__headers[-1] twil__headers += [('Referer', ez_link)] t_brw._browser.addheaders = [] t_brw._browser.addheaderst=twil__headers self.log_out = { 'log_out': "%(Log_out)s" % form_data, 'METODE': form_data['METODE'], 'ez_link': ez_link, # 'headers': t_brw._browser.addheaders, 'headers': twil__headers, 'pdf_link': links1} if self.log_out['METODE'] == '1+d': try: socket=import_mod(from_module='socket') socket.setdefaulttimeout(700) # twil__headers=t_brw._browser.addheaders # t_brw.set_agent_string(twil__headers) # t_brw._browser.addheaders = [] # del twil__headers[-1] # twil__headers += [('Referer', ez_link)] t_brw._browser.addheaders = [] t_brw._browser.addheaderst=twil__headers t_brw.load_cookies(self.cookies) t2 = t_brw.find_link('PDF Full Text') if t2==None: t2 = t_brw.find_link('PDF Full Text') t_brw.follow_link(t2) time_diff = str(round(time.time() - time0, 2)) html0=t_brw.result.page except: try: t_brw._browser.addheaders = [] t_brw._browser.addheaderst=twil__headers t_brw.load_cookies(self.cookies) t_brw.go(ez_link) t_brw.follow_link(links1) if len(links[0])!=1:pass else:t_brw.follow_link(links1) html0 = t_brw.result.page if len(links[0])!=1:t_brw.go(links[0]) else:t_brw.go(links) time_diff = str(round(time.time() - time0, 2)) html0 = t_brw.result.page except: print 'error in downloading MEHOD=1+d';html0='' else: html0='' # t_brw.load_cookies(self.cookies) if len(links[0])!=1:links3=[];links3=links[0];links=[];links.append(links3) # if not (links == '' or links == []): # if self.pre_Link_part != '': # base_url = 'http://' + site + '.' + site2 # links = 'http://' + site + '.' + site2 + links.split(site)[1] # if site2 == '': # base_url = 'http://' + self.pre_Link_part # links = 'http://' + self.pre_Link_part + links.split(site)[1] # else: # if site2 == '': # base_url = 'http://' # links = 'http://' + links.split(site)[1] # else: # base_url = 'http://' + site2 # links = 'http://' + site2 + links.split(site)[1] if title == '' or title == []: try: # title=LINK().find_my_tilte(data=html,start_dash='<h1 class="article-title"',end_dash='1>',make_url=False) # title=LINK().find_my_tilte(data=html,start_dash='type="image/x-icon"><title>',end_dash='</title>',make_url=False) title = LINK().find_my_tilte(data=html, start_dash='<title>', end_dash='</title>', make_url=False) except: title = '' if links == '' or links == []: links1 = t_brw.find_link('PDF Full Text') else: if links1 ==[] or links1=='': try: links1 = t_brw.find_link('PDF Full Text') links1.absolute_url = links except:links1=[] if (links1 == '' or links1 == [] or links1 == None )and (links==[] or links==""): # links = LINK().find_my_tilte(data=html, start_dash='<a id="pdfLink" href="', end_dash='"', # make_url=True) links = LINK().soap_my(data=html, tag='id="pdfLink"', attr='a', href='href', url=base_url) if links == '' or links == []: [links, title] = link_tag_find(html, base_url) # links =LINK().soap_my(data=html, tag='title="Download PDF" ', attr='a', href='href',url=base_url) if links == [] or links == '': pass # links =LINK().soap_my(data=html, tag="Download PDF", attr='a', href='href',url=base_url) # if links==[] or links=='': # links=LINK().soap_my(data=html,tag='pdfLink',attr='a',href='href',url=base_url) if self.log_out['METODE'] == '1+d' and (html0[:4]!='%PDF' or len (re.findall('%%EOF',html0))==0 ) : try: t_brw.load_cookies(self.cookies) t_brw.go(links) time_diff = str(round(time.time() - time0, 2)) html = t_brw.result.page except: print "error in METOD 1+d" html=[] else: if (links==[] or links==""): try: links = links1.absolute_url except: links = links1 if self.log_out['METODE'] == '1+d' and (html0[:4]!='%PDF' or len ( re.findall('%%EOF', html0 ))==0 ): # twil__headers=t_brw._browser.addheaders # t_brw._browser.addheaders = [] # del twil__headers[-1] # twil__headers += [('Referer', ez_link)] # t_brw._browser.addheaderst=twil__headers t_brw._browser.addheaders = [] t_brw._browser.addheaderst=twil__headers try: socket=import_mod(from_module='socket') # t_brw.reload() t2 = t_brw.find_link('PDF Full Text') if t2==None: t2 = t_brw.find_link('PDF Full Text') t_brw.follow_link(t2) time_diff = str(round(time.time() - time0, 2)) html=t_brw.result.page except: try: # twil__headers=t_brw._browser.addheaders # t_brw.set_agent_string(twil__headers) t_brw.load_cookies(self.cookies) t_brw.follow_link(links1) if len(links[0])!=1:pass else:t_brw.follow_link(links1) html0 = t_brw.result.page if len(links[0])!=1:t_brw.go(links[0]) else:t_brw.go(links) time_diff = str(round(time.time() - time0, 2)) html = t_brw.result.page except: print 'error in downloading' self.log_out = { 'log_out': "%(Log_out)s" % form_data, 'METODE': form_data['METODE'], 'ez_link': ez_link, # 'headers': t_brw._browser.addheaders, 'headers': twil__headers, 'pdf_link': links1} try:t_brw.go(self.log_out['log_out']) except: try: os.remove(self.cookies) except: pass return [], self.cookies, [], [], 0, self.log_out # twil__headers=t_brw._browser.addheaders # del twil__headers[-1] # twil__headers += [('Referer', ez_link)] self.log_out = { 'log_out': "%(Log_out)s" % form_data, 'METODE': form_data['METODE'], 'ez_link': ez_link, # 'headers': t_brw._browser.addheaders, 'headers': twil__headers, 'pdf_link': links1} # if (html0[:4]=='%PDF' or len ( re.findall('%%EOF', html ))!=0 ): if title == '' or title == []: # title = LINK().soap_my(data=html, tag='class="article-title"', attr='h1', href='', url=base_url) title = LINK().find_my_tilte(data=html, start_dash='<meta name="dc.Title" content="', end_dash='"', make_url=False) if title == '' or title == []: title = LINK().soap_my(data=html, tag='<title>', attr='', href='', url=base_url) if (html0[:4]=='%PDF' or len ( re.findall('%%EOF', html0 ))!=0):html=html0 if links != [] and self.log_out['METODE'] == '1+d+d' and( html0=='' or (html0[:4]!='%PDF' or html0[-7:]!='%%EOF' )): socket=import_mod(from_module='socket') # socket.setdefaulttimeout(3000) t_brw.load_cookies(self.cookies) # if len(links1.absolute_url[0])!=1: # s = links1.absolute_url[0] # s2 = type('test', (object,), {})() # s2.absolute_url=links1.absolute_url[0] # s2.base_url=links1.base_url # print s2.absolute_url # t_brw.follow_link(s2) # t_brw.go(s2.absolute_url) # t_brw.go(links) # content = t_com.show() headers = t_com.show_extra_headers() # twil__headers=t_brw._browser.addheaders # t_brw.set_agent_string(twil__headers) t_brw._browser.addheaders = [] del twil__headers[-1] twil__headers += [('Referer', ez_link)] t_brw._browser.addheaderst=twil__headers t = t_brw.find_link('PDF Full Text');t.url='http://library.uprm.edu:2404/ehost/detail/detail?sid=480bd76d-2997-488b-a0b0-0d8becbd7f9a%40sessionmgr4004&vid=0&hid=4201&bdata=JnNpdGU9ZWhvc3QtbGl2ZSZzY29wZT1zaXRl#db=f5h&AN=112925105' if t==None: t = t_brw.find_link('PDF Full Text') # t_com.add_extra_header('Referer', t.absolute_url[0]) # reffe='http://library.uprm.edu:2221/S0165176511002710/1-s2.0-S0165176511002710-main.pdf?_tid=ef4c2cd0-24fb-11e6-a3f1-00000aacb361&acdnat=1464457695_083096c5266459084e056213deaf4ba7' # t_com.add_extra_header('Referer', reffe) # t_brw.response() # t_brw.click_link(t) try:t_brw.follow_link(t) except: try:t_brw.go(self.log_out['log_out']) except:pass os.remove(self.cookies);return [], self.cookies, [], [], 0, self.log_out # content = t_com.show() html0=t_brw.result.page # import springerdl print '@@@@@@@@@@@@@ html0 download by twill is @@@@@@@@@@@@' # print html0 # print '@@@@@@@@@@@@@ html0 download by twill is @@@@@@@@@@@@' # time.sleep(10) # # link2=t_brw.result.url # print '@@@@@@@@@@@@@ time.sleep(10) download by twill is @@@@@@@@@@@@' # print link2 # print '@@@@@@@@@@@@@ time.sleep(10) download by twill is @@@@@@@@@@@@' # time.sleep(10) # if not (html0[:4]=='%PDF') or html0==[] : # html2,cookies = MECAHNIZM('','',cookies=self.cookies,url=link2).speed_download(link2) # print '@@@@@@@@@@@@@ MECAHNIZM download by twill is @@@@@@@@@@@@' # print html2 # print '@@@@@@@@@@@@@ MECAHNIZM download by twill is @@@@@@@@@@@@' # time.sleep(10) try:t_brw.go(self.log_out['log_out']) except:os.remove(self.cookies) if (html0[:4]=='%PDF' or len ( re.findall('%%EOF', html0 ))!=0):html=html0 else:html0='' return html0, self.cookies, links, title, time_diff, self.log_out else: pass # t_brw.go(self.log_out['log_out']) if links == '' or links == [] or links == None or html=='': return html, self.cookies, [], [], 0, self.log_out else: if (html[:4]=='%PDF' or len ( re.findall('%%EOF', html ))!=0): try: t_brw.go(self.log_out['log_out']);os.remove(self.cookies) except: try: os.remove(self.cookies) except: pass return html, self.cookies, links, title, time_diff, self.log_out def link_tag_find0( html, base_url): try: # title=LINK().find_my_tilte(data=html,start_dash='<h1 class="article-title"',end_dash='1>',make_url=False) # title = LINK().find_my_tilte(data=html, start_dash='type="image/x-icon"><title>', end_dash='</title>',make_url=False) title = LINK().find_my_tilte(data=html, start_dash='<title>', end_dash='</title>', make_url=False) except: title = '' links = LINK().find_my_tilte(data=html, start_dash='<a id="pdfLink" href="', end_dash='"', make_url=True) if links == [] or links == '': links = LINK().soap_my(data=html, tag='pdfLink', attr='a', href='href', url=base_url) if links == '' or links == []: links = LINK().soap_my(data=html, tag='title="Download PDF" ', attr='a', href='href', url=base_url) if title == '' or title == []: title = LINK().soap_my(data=html, tag='class="article-title"', attr='h1', href='', url=base_url) if title == '' or title == []: title = LINK().soap_my(data=html, tag='<title>', attr='', href='', url=base_url) if links != []: pass return links, title def link_tag_find01( html, base_url): try: # title=LINK().find_my_tilte(data=html,start_dash='<h1 class="article-title"',end_dash='1>',make_url=False) title = LINK().find_my_tilte(data=html, start_dash='type="<title>', end_dash='</title>', make_url=False) except: title = '' urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', html) print urls #http://stackoverflow.com/questions/6222911/how-can-i-grab-pdf-links-from-website-with-python-script import lxml.html, urllib2, urlparse # the url of the page you want to scrape # base_url = 'http://www.renderx.com/demos/examples.html' # fetch the page # res = urllib2.urlopen(base_url) # # # parse the response into an xml tree tree = lxml.html.fromstring(html) # construct a namespace dictionary to pass to the xpath() call # this lets us use regular expressions in the xpath ns = {'re': 'http://exslt.org/regular-expressions'} # iterate over all <a> tags whose href ends in ".pdf" (case-insensitive) for node in tree.xpath('//a[re:test(@href, "\.pdf$", "i")]', namespaces=ns): # print the href, joining it to the base_url print urlparse.urljoin(base_url, node.attrib['href']) #/////////////////////// links = LINK().find_my_tilte(data=html, start_dash='<a id="pdfLink" href="', end_dash='"', make_url=True) m = re.search(r'<a(?: id="[^"]+")? href="http://dx.doi.org/([^"]+)"', html) m = re.search(r'<a(?: id="[^pdfLink"]+")? href="([^"]+)"/([^"]+".pdf")', html) if links == [] or links == '': links = LINK().soap_my(data=html, tag='pdfLink', attr='a', href='href', url=base_url) if links == '' or links == []: links = LINK().soap_my(data=html, tag='title="Download PDF" ', attr='a', href='href', url=base_url) if title == '' or title == []: title = LINK().soap_my(data=html, tag='class="article-title"', attr='h1', href='', url=base_url) if title == '' or title == []: title = LINK().soap_my(data=html, tag='<title>', attr='', href='', url=base_url) if links != []: pass return links, title def link_tag_find( html, base_url,links=[]): try: # title=LINK().find_my_tilte(data=html,start_dash='<h1 class="article-title"',end_dash='1>',make_url=False) title = LINK().find_my_tilte(data=html, start_dash='"citation_title"><span>', end_dash='</span>', make_url=False) if links==[] : links = LINK().soap_my(data=html, tag='id="pdfLink"', attr='a', href='href', url=base_url) if title==[]: title = LINK().find_my_tilte(data=html, start_dash='<title>', end_dash='</title>', make_url=False) except: title = '' try:print links except:links=[] if links==[] or title=='' or title==[]: if title == '' or title == []: title = LINK().find_my_tilte(data=html, start_dash='<title>', end_dash='</title>', make_url=False) # if links == [] or links == '': # links = LINK().soap_my(data=html, tag='pdfLink', attr='a', href='href', url=base_url) if links == '' or links == []: links = LINK().soap_my(data=html, tag='title="Download PDF" ', attr='a', href='href', url=base_url) if title == '' or title == []: title = LINK().soap_my(data=html, tag='class="article-title"', attr='h1', href='', url=base_url) if title == '' or title == []: title = LINK().soap_my(data=html, tag='<title>', attr='', href='', url=base_url) if links != []: pass urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', html) links_1 = [] try: for url in urls: if url.endswith('.pdf') and url.split(base_url)[0]=='': links_1.append(url) print url except: pass if len(links_1)==1:links=links_1[0] elif len(links_1)>=1:links=links_1 else :links='' if links == '' or links == []: #http://stackoverflow.com/questions/6222911/how-can-i-grab-pdf-links-from-website-with-python-script import lxml.html, urllib2, urlparse # the url of the page you want to scrape # base_url = 'http://www.renderx.com/demos/examples.html' # fetch the page # res = urllib2.urlopen(base_url) # # # parse the response into an xml tree tree = lxml.html.fromstring(html) # construct a namespace dictionary to pass to the xpath() call # this lets us use regular expressions in the xpath ns = {'re': 'http://exslt.org/regular-expressions'} # iterate over all <a> tags whose href ends in ".pdf" (case-insensitive) for node in tree.xpath('//a[re:test(@href, "\.pdf$", "i")]', namespaces=ns): # print the href, joining it to the base_url print urlparse.urljoin(base_url, node.attrib['href']) #/////////////////////// return links, title class LINK: def __init__(self, url='', sites_list='configs/sites_list_pdf_tags.txt', sites_list_files="configs/sites_list_files.txt", site_proxy="configs//sites_proxy//", **kwargs): global PDF_Dir, Watermarked_PDF_Files_Dir fo = os.getcwd().replace('\\', '/') CurrentDir = os.path.dirname(os.path.realpath(__file__)).replace('\\', '/') Parent_Dir = os.path.abspath(os.path.join(CurrentDir, '../..')).replace('\\', '/') os.chdir(Parent_Dir) if Parent_Dir not in sys.path: sys.path.insert(0, Parent_Dir) # from download_mozilla import web import proxy_checker3_all_function self.proxy_checker3 = proxy_checker3_all_function self.Mozilla_Web = web self.url = url self.sites_list = Parent_Dir.replace('\\', '/') + '/' + sites_list self.sites_list_files = Parent_Dir.replace('\\', '/') + '/' + sites_list_files self.site_proxy = site_proxy os.chdir(fo) if kwargs: if kwargs['PDF_Dir']: PDF_Dir = kwargs['PDF_Dir'] else: PDF_Dir = Parent_Dir + '/PDF_Files' if kwargs['Watermarked_PDF_Files_Dir']: Watermarked_PDF_Files_Dir = kwargs['Watermarked_PDF_Files_Dir'] else: Watermarked_PDF_Files_Dir = Parent_Dir + '/Watermarked_PDF_Files' else: PDF_Dir = Parent_Dir + '/PDF_Files' Watermarked_PDF_Files_Dir = Parent_Dir + '/Watermarked_PDF_Files' self.Watermarked_PDF_Dir = Watermarked_PDF_Files_Dir self.PDF_Files_Dir = PDF_Dir self.url = url def filename(self, pdf_url0): pdf_url = str(pdf_url0) CurrentDir = os.path.dirname(os.path.realpath(__file__)).replace('\\', '/') try: if re.findall('/', pdf_url): self.suffix = os.path.splitext(pdf_url)[1] self.file_name_decode = urllib2.unquote(pdf_url).decode('utf8').split('/')[-1] # self.filename = urlparse.urlsplit(pdf_url).path.split('/')[-1] try: self.filename = str(self.file_name_decode).split(':')[0] except: self.filename = str(self.file_name_decode) if not (self.filename.endswith('.pdf')): self.filename =self.filename+'.pdf' # if self.filename.endswith('.jsp'): # self.filename=(self.suffix).split('arnumber=')[1]+'.pdf' # self.filename=(pdf_url).split('id=')[1].split('&')[0]+'.pdf' # self.pdf_Folder_filename = CurrentDir + "/"+self.PDF_Files_Dir+"/" + self.filename # self.W_pdf_Folder_filename = CurrentDir + "/"+self.Watermarked_PDF_Dir+"/" + self.filename self.pdf_Folder_filename = self.PDF_Files_Dir + "/" + self.filename self.W_pdf_Folder_filename = self.Watermarked_PDF_Dir + "/" + self.filename self.chdir = CurrentDir else: self.filename = urlparse.urlsplit(pdf_url).path.split('\\')[-1] self.chdir = CurrentDir # self.pdf_Folder_filename = CurrentDir+ "/"+self.PDF_Files_Dir+"/" + self.filename # self.W_pdf_Folder_filename = CurrentDir + "/"+self.Watermarked_PDF_Dir+"/" + self.filename self.pdf_Folder_filename = self.PDF_Files_Dir + "/" + self.filename self.W_pdf_Folder_filename = self.Watermarked_PDF_Dir + "/" + self.filename except: if re.findall('/', pdf_url): self.suffix = os.path.splitext(pdf_url)[1] self.file_name_decode = urllib2.unquote(pdf_url).decode('utf8').split('/')[-1] # self.filename = urlparse.urlsplit(pdf_url).path.split('/')[-1] self.filename = str(self.file_name_decode).split('?_tid=')[0] # if self.filename.endswith('.jsp'): # self.filename=(self.suffix).split('arnumber=')[1]+'.pdf' # self.filename=(pdf_url).split('id=')[1].split('&')[0]+'.pdf' # self.pdf_Folder_filename = CurrentDir + "/"+self.PDF_Files_Dir+"/" + self.filename # self.W_pdf_Folder_filename = CurrentDir + "/"+self.Watermarked_PDF_Dir+"/" + self.filename self.pdf_Folder_filename = self.PDF_Files_Dir + "/" + self.filename self.W_pdf_Folder_filename = self.Watermarked_PDF_Dir + "/" + self.filename self.chdir = CurrentDir else: self.filename = urlparse.urlsplit(pdf_url).path.split('\\')[-1] self.chdir = CurrentDir # self.pdf_Folder_filename = CurrentDir+ "/"+self.PDF_Files_Dir+"/" + self.filename # self.W_pdf_Folder_filename = CurrentDir + "/"+self.Watermarked_PDF_Dir+"/" + self.filename self.pdf_Folder_filename = self.PDF_Files_Dir + "/" + self.filename self.W_pdf_Folder_filename = self.Watermarked_PDF_Dir + "/" + self.filename return self def filename2(self, pdf_url0): pdf_url = str(pdf_url0) CurrentDir = os.path.dirname(os.path.realpath(__file__)).replace('\\', '/') if re.findall('/', pdf_url): self.suffix = os.path.splitext(pdf_url)[1] self.file_name_decode = urllib2.unquote(pdf_url).decode('utf8').split('/')[-1] # self.filename = urlparse.urlsplit(pdf_url).path.split('/')[-1] self.filename = str(self.file_name_decode).split('?_tid=')[0] # if self.filename.endswith('.jsp'): # self.filename=(self.suffix).split('arnumber=')[1]+'.pdf' # self.filename=(pdf_url).split('id=')[1].split('&')[0]+'.pdf' # self.pdf_Folder_filename = CurrentDir + "/"+self.PDF_Files_Dir+"/" + self.filename # self.W_pdf_Folder_filename = CurrentDir + "/"+self.Watermarked_PDF_Dir+"/" + self.filename self.pdf_Folder_filename = self.PDF_Files_Dir + "/" + self.filename self.W_pdf_Folder_filename = self.Watermarked_PDF_Dir + "/" + self.filename self.chdir = CurrentDir else: self.filename = urlparse.urlsplit(pdf_url).path.split('\\')[-1] self.chdir = CurrentDir # self.pdf_Folder_filename = CurrentDir+ "/"+self.PDF_Files_Dir+"/" + self.filename # self.W_pdf_Folder_filename = CurrentDir + "/"+self.Watermarked_PDF_Dir+"/" + self.filename self.pdf_Folder_filename = self.PDF_Files_Dir + "/" + self.filename self.W_pdf_Folder_filename = self.Watermarked_PDF_Dir + "/" + self.filename return self def file_rd(self, path, mode='r', main_data='0'): # proxylist = open(path).read().split('\n') # print os.getcwd() f = open(path, mode) if main_data == '0': data = f.read().split('\n') else: data = f.read() # data=f.readlines() # print data f.close return data # def soap_my(self, data, tag, attr='a', href='href'): def soap_my(self, **kwargs): data = kwargs['data'] tag = kwargs['tag'] try: attr = kwargs['attr'] except: attr = 'a' try: href = kwargs['href'] except: href = 'href' try: url = kwargs['url'] except: url = "http://" + urlparse2(self.url).hostname # from BeautifulSoup import BeautifulSoup # import re # site = urlparse2(self.url).hostname soup = BeautifulSoup(data) ################### links = soup.findAll(attr, href == True) # text=soup.findall('<h1>' ,text=True) # print links try: if links == []: links = soup.findAll(attr, href == True) except: pass done = 0 for everytext in links: if re.findall(tag, str(everytext)): print " link url finded for downloading...\n\t%s" % everytext # print everytext if len(href) != 0: if not (re.findall('www', everytext[href]) or re.findall('http://', everytext[href])): f_nmae = urlparse.urljoin(url, everytext[href]) else: f_nmae = everytext[href] print unicode(f_nmae) return f_nmae else: text = ''.join(everytext.findAll(text=True)) data = text.strip() done = 1 if len(text) == 0: f_nmae = urlparse.urljoin(url, everytext[href]) text = f_nmae return str(text) ############### if done == 0: link = [] return link def find_my_tilte(self, **kwargs): data = kwargs['data'] start_dash = kwargs['start_dash'] end_dash = kwargs['end_dash'] try: make_url = kwargs['make_url'] url = "http://" + urlparse2(self.url).hostname except: make_url = False try: revers = kwargs['reverce'] except: revers = False # data_lowered = data.lower(); if revers == False: begin = data.find(start_dash) end = data[begin + len(start_dash):].find(end_dash) + begin + len(start_dash) else: end = data.find(end_dash) begin = data[:end].rfind(start_dash) if begin == -1 or end == -1: return [] else: # Find in the original html f_nmae = data[begin + len(start_dash):end].strip() if not (re.findall('www', f_nmae) or re.findall('http://', f_nmae)) and make_url == True: f_nmae = urlparse.urljoin(url, f_nmae) print " link url finded for downloading...\n\t%s" % unicode(f_nmae) else: print " link target finded is ...\n\t%s" % f_nmae return f_nmae def dowload_basePr_userpass_link(self, url, pr_h, user_pass_h, **kwargs): try: if kwargs['cookies']: cookies = kwargs['cookies'] else: cookies = '' try: if kwargs['piece_size']: piece_size = kwargs['piece_size'] else: piece_size = 1024 * 20 except: piece_size = 1024 * 20 web = self.Mozilla_Web if len(user_pass_h) != 0: #user_pass_h !='' or # html,pr,upss,cookies=web().download(url,pr_h,user_pass_h,cookies=cookies);mech=0 # or by mechanizm method html,pr,upss,cookies=web().download_mechanism(url,pr_h,user_pass_h,cookies=cookies);mech=1 # html, pr, upss, cookies = web().download_mechanism_link(url, pr_h, user_pass_h, cookies=cookies, # piece_size=piece_size) # mech = 1 else: # html,pr,upss,cookies=web().download(url,pr_h,cookies=cookies);mech=0; # # or by mechanizm method html,pr,upss,cookies=web().download_mechanism(url,pr_h,cookies=cookies);mech=1 # html, pr, upss, cookies = web().download_mechanism_link(url, pr_h, cookies=cookies,piece_size=piece_size) # # mech = 1 if html==[] or html=='': pass #frontpage=self.twill_download( url, cookies,pr_h) except: html = [] link=[] pr = [] upss = [] cookies = '' mech = 0 print "we cant dowload beacuse of invalid tag or invalid proxy line 620" + "\n" responce = { 'html': html, 'proxy': pr, 'user_pass': upss, 'cookies': cookies, 'mechanizm': mech, } return responce def dowload_basePr_userpass(self, url, pr_h, user_pass_h, **kwargs): try: if kwargs['cookies']: cookies = kwargs['cookies'] else: cookies = '' web = self.Mozilla_Web try: site = urlparse2(url['link']).hostname except: site = urlparse2(url).hostname html = [] file = os.path.basename(os.path.realpath(__file__)).split('.pyc')[0].replace('_', '.') if file[-3:] == '.py': file = file[:-3] if str(site) != file: CurrentDir = os.path.dirname(os.path.realpath(__file__)).replace('\\', '/') Parent_Dir = os.path.abspath(os.path.join(CurrentDir, '../')).replace('\\', '/') # os.chdir(Parent_Dir) lg = url['log_out'] if lg['METODE'] == '1' or lg['METODE'] == '1+d': html = twill( site_list_form=Parent_Dir + '/sites_proxy/' + site + '/site_list_form.txt').twill_download(url, cookies) elif lg['METODE'] == '2': html, pr, upss, cookies = web().download_mechanism_link(url['link'], 'None:None', cookies=cookies); mech = 1 mech = 0 pr = pr_h upss = user_pass_h import cookielib else: if len(user_pass_h) != 0: #user_pass_h !='' or # html,pr,upss,cookies=web().download(url,pr_h,user_pass_h,cookies=cookies);mech=0 # # or by mechanizm method # # html,pr,upss,cookies=web().download_mechanism(url,pr_h,user_pass_h,cookies=cookies);mech=1 html, pr, upss, cookies = web().download_mechanism_link(url, pr_h, user_pass_h, cookies=cookies);mech = 1 else: # html,pr,upss,cookies=web().download(url,pr_h,cookies=cookies);mech=0 # or by mechanizm method # html,pr,upss,cookies=web().download_mechanism(url,pr_h,cookies=cookies);mech=1 html, pr, upss, cookies = web().download_mechanism_link(url, pr_h, cookies=cookies); mech = 1 try: os.path.isfile(html) file_is=1 except: file_is=0 if not (html != [] and html[:4] == '%PDF') and file_is!=1: if len(user_pass_h) != 0: #user_pass_h !='' or html,pr,upss,cookies=web().download(url,pr_h,user_pass_h,cookies=cookies);mech=0 # or by mechanizm method # html,pr,upss,cookies=web().download_mechanism(url,pr_h,user_pass_h,cookies=cookies);mech=1 # html, pr, upss, cookies = web().download_mechanism_link(url, pr_h, user_pass_h, cookies=cookies); # mech = 1 else: html,pr,upss,cookies=web().download(url,pr_h,cookies=cookies);mech=0 # or by mechanizm method # html,pr,upss,cookies=web().download_mechanism(url,pr_h,cookies=cookies);mech=1 # html, pr, upss, cookies = web().download_mechanism_link(url, pr_h, cookies=cookies); # mech = 1 except: html = [] pr = [] upss = [] cookies = '' mech = 0 print "we cant dowload beacuse of invalid tag or invalid proxy line 620" + "\n" responce = { 'html': html, 'proxy': pr, 'user_pass': upss, 'cookies': cookies, 'mechanizm': mech, } return responce def get_pdf_link(self, proxy='', user_pass=''): url = self.url site = urlparse2(url).hostname title='' CurrentDir = os.path.dirname(os.path.realpath(__file__)) Parent_Dir = os.path.abspath(os.path.join(CurrentDir, '../..')).replace('\\', '/') proxy_working_list = Parent_Dir + '/configs/sites_proxy/' + site + "/" + site + ".txt" proxy_bad_list = Parent_Dir + '/configs/sites_proxy/' + site + "/badproxylist.txt" if proxy == '': fo = os.getcwd() pr_h, proxy_h, user_pass_h = self.proxy_checker3.make_returning_proxy( "configs//sites_proxy//" + site + '//', url) # CurrentDir=os.path.dirname(os.path.realpath(__file__)) # Parent_Dir=os.path.abspath(os.path.join(CurrentDir, '../..')).replace('\\','/') # form_n,list=self.proxy_checker3.find_form(proxy_working_list) form_n, list, form_av = self.proxy_checker3.find_form_av(proxy_working_list) os.chdir(fo) if not os.path.isdir(Parent_Dir + '/configs/sites_proxy/' + site): os.mkdir(Parent_Dir + '/configs/sites_proxy/' + site) form_b, list_b = self.proxy_checker3.find_form(proxy_bad_list) else: pr_h = [] user_pass_h = [] pr_h.append(proxy) user_pass_h.append(user_pass) # i = user_pass_h.index("") # del user_pass_h[i] try: i = pr_h.index("") del pr_h[i] except: pass don_flg = -1 if pr_h != []: i = -1 listhandle = self.file_rd(self.sites_list, 'r') file_listhandle = self.file_rd(self.sites_list_files, 'r') link_done = 0 url_pdf = {} for j in range(0, len(pr_h)): form = form_n; form2 = form[j]; pr_h[j] = pr_h[j].replace(' ', '') if don_flg != 1 and not url.endswith('.pdf') \ and not url.endswith('.zip') and link_done == 0: time0 = time.time() # from articledownloader.articledownloader import ArticleDownloader if re.findall('None', pr_h[j]): [html, cookies, links, title, form, time_diff, log_out] = twil_find_pdf_link(url) # time_diff = str(round(time.time() - time0, 2)) if links != []: try: site_file = "configs//sites_proxy//" if user_pass_h[j] != []: pp = pr_h[j] + '@' + user_pass_h[j] else: pp = pr_h[j] self.proxy_checker3.make_txt_file(site_file + site + ".txt", pp, site, time_diff) self.proxy_checker3.sort_file(site_file + site + ".txt", " Rs_Time ") except: print 'we could not update proxy list for site:' + site + " that is worked with proxy " + pr_h[j] + '\n' responce = { 'html': html, 'url': url, 'links': links, 'title': title, 'proxy': pr_h[j], 'user_pass': user_pass_h[j], 'cookies': cookies, 'mechanizm': 0, 'form': form, 'log_out': log_out } return responce elif int(form2['Success_try']) >= int(form2['Failed_try']) + 10 or int(form2['Failed_try']) <= 10: res = self.dowload_basePr_userpass_link(url, pr_h[j], user_pass_h[j], cookies='', piece_size=1024 * 3) # res=self.dowload_basePr_userpass(url,pr_h[j],user_pass_h[j],cookies='') html = res['html']; proxy0 = res['proxy']; user_pass = res['user_pass']; cookies = res['cookies']; mech = res['mechanizm'] # print html[:4100] time_diff = str(round(time.time() - time0, 2)) try: try: html2=html['file'] except: html2=html os.path.isfile(html2) file_is=1 except: file_is=0 if (html2!=[] and html2[:4]=='%PDF')or file_is==1 : pass # responce = { # 'html': html, # 'url': url, # 'links': [], # 'title': title, # 'proxy': pr_h[j], # 'user_pass': user_pass_h[j], # 'cookies': cookies, # 'mechanizm': mech} # return responce if ( link_done == 0 and html2 != [] or html2[:4]=='%PDF') or file_is==1: if not ( html2[:4]=='%PDF' or file_is==1): [links, title] = link_tag_find(html2, url) try: links1 = links[1] except: links1=links if not ((links == [] or links == None or links == '') ) : res = self.dowload_basePr_userpass_link(links1, pr_h[j], user_pass_h[j], cookies='', piece_size=1024 * 3) html,cookies = MECAHNIZM(pr_h[j],cookies=cookies,url=url).download_pdf_br(url) # res=self.dowload_basePr_userpass(url,pr_h[j],user_pass_h[j],cookies='') html = res['html']; proxy0 = res['proxy']; user_pass = res['user_pass']; cookies = res['cookies']; mech = res['mechanizm'] print html else: links=html['links']; title=html['title']; html=html['html'] # [links, title] = link_tag_find(html, url) # links=self.url; links1=links # html2, pr, upss, cookies = web().download_mechanism_link(links1, proxy0, cookies=cookies,url_reffrence=url); # # download_bash_curl # # frontpage, pr, upss, cookies= web().download(links1, proxy0, cookies=cookies,url_reffrence=url); # try: # if os.path.isfile(html): # h=open(html) # ht=h.read() # h.close() # os.remove(html) # html=ht # except: # pass # links =self.soap_my(data=html, tag='FullTextPdf', attr='a', href='href',url=url) # try: # title=self.find_my_tilte(data=html,start_dash='<h1 class="article-title"',end_dash='1>',make_url=False) # title=self.find_my_tilte(data=title,start_dash='">',end_dash='</h',make_url=False) # except: # title='' # # # links=self.find_my_tilte(data=html,start_dash='<a id="pdfLink" href="',end_dash='"',make_url=True) # # # if links==''or links==[]: # links =self.soap_my(data=html, tag='title="Download PDF" ', attr='a', href='href',url=url) # # if links==[] or links=='': # # # links=self.soap_my(data=html,tag='pdfLink',attr='a',href='href',url=url) # if title=='' or title==[]: # title=self.soap_my(data=html, tag='class="article-title"', attr='h1', href='',url=url) # if title=='' or title==[]: # title=self.soap_my(data=html, tag='<title>', attr='h1', href='',url=url) # title=self.find_my_tilte(data=title,start_dash='">',end_dash='</h1>',make_url=False) # if links == [] or links==None: # links =self.soap_my(data=html, tag='Full Text', attr='a', href='href',url=url) # clear = lambda: os.system(['clear','cls'][os.name == 'nt']);clear() # print html # if links!=[] and mech!=1 : # res=self.dowload_basePr_userpass_link(url,pr_h[j],user_pass_h[j],cookies='') # html=res['html'];proxy0=res['proxy'];user_pass=res['user_pass'];cookies=res['cookies'];mech=res['mechanizm'] # # try: # # if os.path.isfile(html): # # h=open(html) # # ht=h.read() # # h.close() # # os.remove(html) # # html=ht # # except: # # pass # # links =self.soap_my(data=html, tag='<frame src="http://ieeexplore.ieee.org', attr='frame', href='src',url=str(links)) # # links2=self.soap_my(html,'<frame src="http://ieeexplore.ieee.org','frame','src') # links=links2 try: os.path.isfile(html) file_is=1 except: file_is=0 if ((links == [] or links == None or links == '') ) : pass else : if html[:4]=='%PDF' or file_is==1: link_done = 1 print '---------------we found Proper link which is :------------\n' + str(links) + \ '\n ----with proxy-------\n' + str(pr_h[j]) + ':' + str(user_pass_h[j]) print '----------------- Link Found -------------------------' try: site_file = "configs//sites_proxy//" if user_pass_h[j] != []: pp = pr_h[j] + '@' + user_pass_h[j] else: pp = pr_h[j] # form,list=self.proxy_checker3.find_form(site_file + site + ".txt") # for i in range(0,len(form)): # form2=form[i] if True: i = j if re.findall(pr_h[j], form2['ip']): if re.findall('Success_try:', list[i]): pattern = [list[i].split('Failed_try:')[0] + 'Failed_try:' + form2[ 'Failed_try'], list[i].split('Success_try:')[0] + 'Success_try:' + form2[ 'Success_try'], list[i].split('Rs_Time')[0] + 'Rs_Time ' + form2['time'] ]; new_pattenr = [list[i].split('Failed_try:')[0] + 'Failed_try:' + str( int(form2['Failed_try'])), list[i].split('Success_try:')[0] + 'Success_try:' + str( int((form2['Success_try'])) + 1), list[i].split('Rs_Time')[0] + 'Rs_Time ' + time_diff ] else: pattern = [list[i].replace('\r', '').replace('\n', ''), list[i].replace('\r', '').replace('\n', '') ]; new_pattenr = [list[i].replace('\r', '').replace('\n', ''), list[i].split('\n')[0].replace('\r', '').split( 'Rs_Time')[ 0] + ' Rs_Time ' + time_diff + ' Success_try:' + str( int(form2[ 'Success_try']) + 1) + ' Failed_try:' + str( int(form2['Failed_try'])) ] if int(form2['Success_try'])+ 30 >= int(form2['Failed_try']) : self.proxy_checker3.replace(proxy_working_list, pattern, new_pattenr) # self.proxy_checker3.make_txt_file(site_file + site + ".txt", pp, site, time_diff) # self.proxy_checker3.sort_file(proxy_working_list, " Rs_Time ") # self.proxy_checker3.sort_file(proxy_working_list, "Success_try:","Failed_try:", # sort_type='reversed') break except: print 'we could not update proxy list for site:' + site + " that is worked with proxy " +pr_h[j] + '\n' break # for line in listhandle: # if re.findall(site, line) and link_done == 0 and (not re.findall("#", line.split("TAG:")[0])) : # if re.findall("TAG1:", line): # try: # Tag = line.split("TAG1:")[1].split("---")[0] # Tag=Tag.replace("+++",'') # atrr = line.split("Attr1:")[1].split("---")[0] # atrr=atrr.replace("+++",'') # href=line.split('Href1:')[1].split("---")[0] # href=href.replace("+++",'') # links =self.soap_my(data=html, tag=Tag, attr=atrr, href=href,url=url) # # links = self.soap_my(html, Tag, atrr,href) # if links != [] and link_done!=None and mech!=1: # try: # Tag = line.split("TAG2:")[1].split("---")[0] # Tag=Tag.replace("---",'').replace("+++",'') # # atrr = line.split("Attr2:")[1].split("---")[0] # atrr=atrr.replace('---','').replace("+++",'') # href=line.split('Href2:')[1].split("---")[0] # href=href.replace("+++",'') # res=self.dowload_basePr_userpass_link(url,pr_h[j],user_pass_h[j],cookies='') # html=res['html'];proxy0=res['proxy'];user_pass=res['user_pass'];cookies=res['cookies'];mech=res['mechanizm'] # # links = self.soap_my(html, Tag, atrr,href) # except:pass # # [html,proxy0,user_pass]=self.dowload_basePr_userpass(links,pr_h[j],user_pass_h[j]) # # links =self.soap_my(data=html, tag=Tag, attr=atrr, href=href,url=url) # # links = self.soap_my(html, Tag, atrr,href) # if links != [] or links!=None: # link_done = 1 # print '---------------we found Proper link which is :------------\n'+str(links)+ \ # '\n ----with proxy-------\n'+str(pr_h[j])+':'+str(user_pass_h[j]) # print '----------------- Link Found -------------------------' # return links,pr_h[j],user_pass_h[j] # # except: # pass elif link_done == 1: print "<li><a>tag found</a></li>" print links break elif link_done == 0: # CurrentDir=os.path.dirname(os.path.realpath(__file__)) # Parent_Dir=os.path.abspath(os.path.join(CurrentDir, '../..')).replace('\\','/') # if not os.path.isdir(Parent_Dir+'/configs/sites_proxy/'+site): # os.mkdir(Parent_Dir+'/configs/sites_proxy/'+site) time_diff = str(round(time.time() - time0, 2)) # if len(user_pass)!=0: # self.proxy_checker3.make_txt_file(Parent_Dir+'/configs/sites_proxy/'+site+"/badproxylist.txt", str(pr_h[j])+'@'+str(user_pass_h[j]), site, time_diff) # else: # pass # # self.proxy_checker3.make_txt_file(Parent_Dir+'/configs/sites_proxy/'+site+"/badproxylist.txt", str(pr_h[j]), site, time_diff) if True: #badproxylist.txt done = 0 for i in range(0, len(form_b)): form3 = form_b[i] if re.findall(pr_h[j], form2['ip']): if re.findall('Success_try:', list_b[i]): pattern = [ list_b[i].split('Failed_try:')[0] + 'Failed_try:' + form3['Failed_try'], list_b[i].split('Success_try:')[0] + 'Success_try:' + form3[ 'Success_try'], list_b[i].split('Rs_Time ')[0] + 'Rs_Time ' + form3['time'] ]; new_pattenr = [list_b[i].split('Failed_try:')[0] + 'Failed_try:' + str( int(form3['Failed_try']) + 1), list_b[i].split('Success_try:')[0] + 'Success_try:' + form3[ 'Success_try'], list_b[i].split('Rs_Time ')[0] + 'Rs_Time ' + time_diff ] else: pattern = [list_b[i].replace('\r', '').replace('\n', ''), list_b[i].replace('\r', '').replace('\n', '') ]; new_pattenr = [list_b[i].replace('\r', '').replace('\n', ''), list_b[i].split('\n')[0].replace('\r', '').split( ' Rs_Time ')[ 0] + 'Rs_Time ' + time_diff + ' Success_try:' + form3[ 'Success_try'] + ' Failed_try:' + str( int(form3['Failed_try']) + 1) ] self.proxy_checker3.replace( Parent_Dir + '/configs/sites_proxy/' + site + "/badproxylist.txt", pattern, new_pattenr) don = 1 break if don == 0: if len(user_pass) != 0: self.proxy_checker3.make_txt_file( Parent_Dir + '/configs/sites_proxy/' + site + "/badproxylist.txt", str(pr_h[j]) + '@' + str(user_pass_h[j]), site, time_diff) else: self.proxy_checker3.make_txt_file( Parent_Dir + '/configs/sites_proxy/' + site + "/badproxylist.txt", str(pr_h[j]), site, time_diff) # form,list=self.proxy_checker3.find_form(Parent_Dir+'/configs/sites_proxy/'+site+"/"+site+".txt") # for i in range(0,len(form)): # form2=form[i] if True:#proxy_working_list if re.findall(form2['ip'], pr_h[j]): i = j if re.findall('Success_try:', list[i]): pattern = [ list[i].split('Failed_try:')[0] + 'Failed_try:' + form2['Failed_try'], list[i].split('Success_try:')[0] + 'Success_try:' + form2[ 'Success_try'], list[i].split('Rs_Time ')[0] + 'Rs_Time ' + form2['time'] ]; new_pattenr = [list[i].split('Failed_try:')[0] + 'Failed_try:' + str( int(form2['Failed_try']) + 1), list[i].split('Success_try:')[0] + 'Success_try:' + form2[ 'Success_try'], list[i].split('Rs_Time ')[0] + 'Rs_Time ' + time_diff ] else: pattern = [list[i].replace('\r', '').replace('\n', ''), list[i].replace('\r', '').replace('\n', '') ]; new_pattenr = [list[i].replace('\r', '').replace('\n', ''), list[i].split('\n')[0].replace('\r', '').split('Rs_Time ')[ 0] + 'Rs_Time ' + time_diff + ' Success_try:' + form2[ 'Success_try'] + ' Failed_try:' + str( int(form2['Failed_try']) + 1) ] self.proxy_checker3.replace( Parent_Dir + '/configs/sites_proxy/' + site + "/" + site + ".txt", pattern, new_pattenr) # break elif url != [] or (url.endswith('.pdf') or url.endswith('.zip')): cookies = '' responce = { 'html': html, 'url': url, 'links': url, 'title': '', 'proxy': '', 'user_pass': '', 'cookies': cookies, 'mechanizm': mech, } return responce # return url,'','',cookies if link_done == 0: links = [] pr_h[j] = [] user_pass_h[j] = [] title = '' cookies = '' mech = 0 print "we couldnt find link beacuase of no proxy is able to download .find good proxy over internet" responce = { 'html': html, 'url': url, 'links': links, 'title': title, 'proxy': pr_h[j], 'user_pass': user_pass_h[j], 'cookies': cookies, 'mechanizm': mech, } return responce # return links,pr_h[j],user_pass_h[j],cookies, else: # pr_h[j]=[] there is no trusted proxy for it res = self.dowload_basePr_userpass_link(url, "None:None", [], cookies='') html = res['html']; proxy0 = res['proxy']; user_pass = res['user_pass']; cookies = res['cookies']; mech = res['mechanizm'] # [html,proxy0,user_pass,cookies]=self.dowload_basePr_userpass_link(url,"None:None",[],cookies='') links = self.soap_my(data=html, tag='title="FullText PDF"', attr='a', href='href', url=url) title = self.soap_my(data=html, tag='class="mediumb-text" style="margin-top:0px; margin-bottom:0px;"', attr='h1', href='href', url=url) # if links==[]: # res=self.dowload_basePr_userpass_link(links,"None:None",[],cookies=cookies) # html=res['html'];proxy0=res['proxy'];user_pass=res['user_pass'];cookies=res['cookies'];mech=res['mechanizm'] # # [html,proxy0,user_pass,cookies]=self.dowload_basePr_userpass_link(links,"None:None",[],cookies=cookies) # links2=LINK(links).soap_my(html,'<frame src="http://ieeexplore.ieee.org','frame','src') # link=links2 if links == [] or links == None or links == '': print'there is no trusted proxy for downloading it' else: link_done = 1 responce = { 'html': html, 'url': url, 'links': links, 'title': title, 'proxy': [], 'user_pass': [], 'cookies': cookies, 'mechanizm': mech, } return responce # return links,[],[],cookies def get_pdf_link_two_state(self, proxy='', user_pass='',tag='', attr='', href=''): url = self.url site = urlparse2(url).hostname CurrentDir = os.path.dirname(os.path.realpath(__file__)) Parent_Dir = os.path.abspath(os.path.join(CurrentDir, '../..')).replace('\\', '/') proxy_working_list = Parent_Dir + '/configs/sites_proxy/' + site + "/" + site + ".txt" proxy_bad_list = Parent_Dir + '/configs/sites_proxy/' + site + "/badproxylist.txt" if proxy == '': fo = os.getcwd() pr_h, proxy_h, user_pass_h = self.proxy_checker3.make_returning_proxy( "configs//sites_proxy//" + site + '//', url) # CurrentDir=os.path.dirname(os.path.realpath(__file__)) # Parent_Dir=os.path.abspath(os.path.join(CurrentDir, '../..')).replace('\\','/') # form_n,list=self.proxy_checker3.find_form(proxy_working_list) form_n, list, form_av = self.proxy_checker3.find_form_av(proxy_working_list) os.chdir(fo) if not os.path.isdir(Parent_Dir + '/configs/sites_proxy/' + site): os.mkdir(Parent_Dir + '/configs/sites_proxy/' + site) form_b, list_b = self.proxy_checker3.find_form(proxy_bad_list) else: pr_h = [] user_pass_h = [] pr_h.append(proxy) user_pass_h.append(user_pass) # i = user_pass_h.index("") # del user_pass_h[i] try: i = pr_h.index("") del pr_h[i] except: pass don_flg = -1 if pr_h != []: i = -1 listhandle = self.file_rd(self.sites_list, 'r') file_listhandle = self.file_rd(self.sites_list_files, 'r') link_done = 0 url_pdf = {} for j in range(0, len(pr_h)): form = [];#form_n; form2 =[];# form[j]; pr_h[j] = pr_h[j].replace(' ', '') if don_flg != 1 and not url.endswith('.pdf') \ and not url.endswith('.zip') and link_done == 0: time0 = time.time() # from articledownloader.articledownloader import ArticleDownloader if re.findall('None', pr_h[j]): [html, cookies, links, title, form, time_diff, log_out] = twil_find_pdf_link(url) # time_diff = str(round(time.time() - time0, 2)) if links != []: try: site_file = "configs//sites_proxy//" if user_pass_h[j] != []: pp = pr_h[j] + '@' + user_pass_h[j] else: pp = pr_h[j] self.proxy_checker3.make_txt_file(site_file + site + ".txt", pp, site, time_diff) self.proxy_checker3.sort_file(site_file + site + ".txt", " Rs_Time ") except: print 'we could not update proxy list for site:' + site + " that is worked with proxy " + pr_h[j] + '\n' responce = { 'html': html, 'url': url, 'links': links, 'title': title, 'proxy': pr_h[j], 'user_pass': user_pass_h[j], 'cookies': cookies, 'mechanizm': 0, 'form': form, 'log_out': log_out } return responce elif True:# int(form2['Success_try']) >= int(form2['Failed_try']) + 10 or int(form2['Failed_try']) <= 10: res2 = self.dowload_basePr_userpass_link(url, pr_h[j], user_pass_h[j], cookies='', piece_size=1024 * 3) res = self.dowload_basePr_userpass_link(url, '', '', cookies='', piece_size=1024 * 3) # res=self.dowload_basePr_userpass(url,pr_h[j],user_pass_h[j],cookies='') html = res['html']; html2 = res2['html']; proxy0 = res['proxy']; user_pass = res['user_pass']; cookies = res['cookies']; mech = res['mechanizm'] # print html[:4100] time_diff = str(round(time.time() - time0, 2)) article_number=self.find_my_tilte(data=html,start_dash='<strong>Publications:',end_dash='</strong>',make_url=False) article_number2=self.find_my_tilte(data=html2,start_dash='<strong>Publications:',end_dash='</strong>',make_url=False) if link_done == 0 and html2 != [] and int(article_number2) > int(article_number): #[links, title] = link_tag_find(html, url) # try: # if os.path.isfile(html): # h=open(html) # ht=h.read() # h.close() # os.remove(html) # html=ht # except: # pass # links =self.soap_my(data=html, tag='FullTextPdf', attr='a', href='href',url=url) # try: # title=self.find_my_tilte(data=html,start_dash='<h1 class="article-title"',end_dash='1>',make_url=False) # title=self.find_my_tilte(data=title,start_dash='">',end_dash='</h',make_url=False) # except: # title='' # # # links=self.find_my_tilte(data=html,start_dash='<a id="pdfLink" href="',end_dash='"',make_url=True) # # # if links==''or links==[]: # links =self.soap_my(data=html, tag='title="Download PDF" ', attr='a', href='href',url=url) # # if links==[] or links=='': # # # links=self.soap_my(data=html,tag='pdfLink',attr='a',href='href',url=url) # if title=='' or title==[]: # title=self.soap_my(data=html, tag='class="article-title"', attr='h1', href='',url=url) # if title=='' or title==[]: # title=self.soap_my(data=html, tag='<title>', attr='h1', href='',url=url) # title=self.find_my_tilte(data=title,start_dash='">',end_dash='</h1>',make_url=False) # if links == [] or links==None: # links =self.soap_my(data=html, tag='Full Text', attr='a', href='href',url=url) # clear = lambda: os.system(['clear','cls'][os.name == 'nt']);clear() # print html # if links!=[] and mech!=1 : # res=self.dowload_basePr_userpass_link(url,pr_h[j],user_pass_h[j],cookies='') # html=res['html'];proxy0=res['proxy'];user_pass=res['user_pass'];cookies=res['cookies'];mech=res['mechanizm'] # # try: # # if os.path.isfile(html): # # h=open(html) # # ht=h.read() # # h.close() # # os.remove(html) # # html=ht # # except: # # pass # # links =self.soap_my(data=html, tag='<frame src="http://ieeexplore.ieee.org', attr='frame', href='src',url=str(links)) # # links2=self.soap_my(html,'<frame src="http://ieeexplore.ieee.org','frame','src') # links=links2 if links == [] or links == None or links == '': pass if int(article_number2) > int(article_number): link_done = 1 print '---------------we found Proper link which is :------------\n' + str(links) + \ '\n ----with proxy-------\n' + str(pr_h[j]) + ':' + str(user_pass_h[j]) print '----------------- Link Found -------------------------' try: site_file = "configs//sites_proxy//" if user_pass_h[j] != []: pp = pr_h[j] + '@' + user_pass_h[j] else: pp = pr_h[j] # form,list=self.proxy_checker3.find_form(site_file + site + ".txt") # for i in range(0,len(form)): # form2=form[i] if True: i = j if re.findall(pr_h[j], form2['ip']): if re.findall('Success_try:', list[i]): pattern = [list[i].split('Failed_try:')[0] + 'Failed_try:' + form2[ 'Failed_try'], list[i].split('Success_try:')[0] + 'Success_try:' + form2[ 'Success_try'], list[i].split('Rs_Time')[0] + 'Rs_Time ' + form2['time'] ]; new_pattenr = [list[i].split('Failed_try:')[0] + 'Failed_try:' + str( int(form2['Failed_try'])), list[i].split('Success_try:')[0] + 'Success_try:' + str( int((form2['Success_try'])) + 1), list[i].split('Rs_Time')[0] + 'Rs_Time ' + time_diff ] else: pattern = [list[i].replace('\r', '').replace('\n', ''), list[i].replace('\r', '').replace('\n', '') ]; new_pattenr = [list[i].replace('\r', '').replace('\n', ''), list[i].split('\n')[0].replace('\r', '').split( 'Rs_Time')[ 0] + ' Rs_Time ' + time_diff + ' Success_try:' + str( int(form2[ 'Success_try']) + 1) + ' Failed_try:' + str( int(form2['Failed_try'])) ] if int(form2['Success_try']) >= int(form2['Failed_try']) + 30: self.proxy_checker3.replace(proxy_working_list, pattern, new_pattenr) # self.proxy_checker3.make_txt_file(site_file + site + ".txt", pp, site, time_diff) # self.proxy_checker3.sort_file(proxy_working_list, " Rs_Time ") self.proxy_checker3.sort_file(proxy_working_list, " Success_try:", sort_type='reversed') break except: print 'we could not update proxy list for site:' + site + " that is worked with proxy " +pr_h[j] + '\n' break # for line in listhandle: # if re.findall(site, line) and link_done == 0 and (not re.findall("#", line.split("TAG:")[0])) : # if re.findall("TAG1:", line): # try: # Tag = line.split("TAG1:")[1].split("---")[0] # Tag=Tag.replace("+++",'') # atrr = line.split("Attr1:")[1].split("---")[0] # atrr=atrr.replace("+++",'') # href=line.split('Href1:')[1].split("---")[0] # href=href.replace("+++",'') # links =self.soap_my(data=html, tag=Tag, attr=atrr, href=href,url=url) # # links = self.soap_my(html, Tag, atrr,href) # if links != [] and link_done!=None and mech!=1: # try: # Tag = line.split("TAG2:")[1].split("---")[0] # Tag=Tag.replace("---",'').replace("+++",'') # # atrr = line.split("Attr2:")[1].split("---")[0] # atrr=atrr.replace('---','').replace("+++",'') # href=line.split('Href2:')[1].split("---")[0] # href=href.replace("+++",'') # res=self.dowload_basePr_userpass_link(url,pr_h[j],user_pass_h[j],cookies='') # html=res['html'];proxy0=res['proxy'];user_pass=res['user_pass'];cookies=res['cookies'];mech=res['mechanizm'] # # links = self.soap_my(html, Tag, atrr,href) # except:pass # # [html,proxy0,user_pass]=self.dowload_basePr_userpass(links,pr_h[j],user_pass_h[j]) # # links =self.soap_my(data=html, tag=Tag, attr=atrr, href=href,url=url) # # links = self.soap_my(html, Tag, atrr,href) # if links != [] or links!=None: # link_done = 1 # print '---------------we found Proper link which is :------------\n'+str(links)+ \ # '\n ----with proxy-------\n'+str(pr_h[j])+':'+str(user_pass_h[j]) # print '----------------- Link Found -------------------------' # return links,pr_h[j],user_pass_h[j] # # except: # pass elif link_done == 1: print "<li><a>tag found</a></li>" print links break elif link_done == 0: # CurrentDir=os.path.dirname(os.path.realpath(__file__)) # Parent_Dir=os.path.abspath(os.path.join(CurrentDir, '../..')).replace('\\','/') # if not os.path.isdir(Parent_Dir+'/configs/sites_proxy/'+site): # os.mkdir(Parent_Dir+'/configs/sites_proxy/'+site) time_diff = str(round(time.time() - time0, 2)) # if len(user_pass)!=0: # self.proxy_checker3.make_txt_file(Parent_Dir+'/configs/sites_proxy/'+site+"/badproxylist.txt", str(pr_h[j])+'@'+str(user_pass_h[j]), site, time_diff) # else: # pass # # self.proxy_checker3.make_txt_file(Parent_Dir+'/configs/sites_proxy/'+site+"/badproxylist.txt", str(pr_h[j]), site, time_diff) if True: done = 0 if done == 0: if len(user_pass) != 0: self.proxy_checker3.make_txt_file( Parent_Dir + '/configs/sites_proxy/' + site + "/badproxylist.txt", str(pr_h[j]) + '@' + str(user_pass_h[j]), site, time_diff) else: self.proxy_checker3.make_txt_file( Parent_Dir + '/configs/sites_proxy/' + site + "/badproxylist.txt", str(pr_h[j]), site, time_diff) # form,list=self.proxy_checker3.find_form(Parent_Dir+'/configs/sites_proxy/'+site+"/"+site+".txt") # for i in range(0,len(form)): # form2=form[i] if False: if re.findall(form2['ip'], pr_h[j]): i = j if re.findall('Success_try:', list[i]): pattern = [ list[i].split('Failed_try:')[0] + 'Failed_try:' + form2['Failed_try'], list[i].split('Success_try:')[0] + 'Success_try:' + form2[ 'Success_try'], list[i].split('Rs_Time ')[0] + 'Rs_Time ' + form2['time'] ]; new_pattenr = [list[i].split('Failed_try:')[0] + 'Failed_try:' + str( int(form2['Failed_try']) + 1), list[i].split('Success_try:')[0] + 'Success_try:' + form2[ 'Success_try'], list[i].split('Rs_Time ')[0] + 'Rs_Time ' + time_diff ] else: pattern = [list[i].replace('\r', '').replace('\n', ''), list[i].replace('\r', '').replace('\n', '') ]; new_pattenr = [list[i].replace('\r', '').replace('\n', ''), list[i].split('\n')[0].replace('\r', '').split('Rs_Time ')[ 0] + 'Rs_Time ' + time_diff + ' Success_try:' + form2[ 'Success_try'] + ' Failed_try:' + str( int(form2['Failed_try']) + 1) ] self.proxy_checker3.replace( Parent_Dir + '/configs/sites_proxy/' + site + "/" + site + ".txt", pattern, new_pattenr) # break elif url != [] or (url.endswith('.pdf') or url.endswith('.zip')): cookies = '' responce = { 'html': html, 'url': url, 'links': url, 'title': '', 'proxy': '', 'user_pass': '', 'cookies': cookies, 'mechanizm': mech, } return responce # return url,'','',cookies if link_done == 0: links = [] pr_h[j] = [] user_pass_h[j] = [] title = '' cookies = '' mech = 0 print "we couldnt find link beacuase of no proxy is able to download .find good proxy over internet" responce = { 'html': html, 'url': url, 'links': links, 'title': title, 'proxy': pr_h[j], 'user_pass': user_pass_h[j], 'cookies': cookies, 'mechanizm': mech, } return responce # return links,pr_h[j],user_pass_h[j],cookies, else: # pr_h[j]=[] there is no trusted proxy for it res = self.dowload_basePr_userpass_link(url, "None:None", [], cookies='') html = res['html']; proxy0 = res['proxy']; user_pass = res['user_pass']; cookies = res['cookies']; mech = res['mechanizm'] # [html,proxy0,user_pass,cookies]=self.dowload_basePr_userpass_link(url,"None:None",[],cookies='') links = self.soap_my(data=html, tag='title="FullText PDF"', attr='a', href='href', url=url) title = self.soap_my(data=html, tag='class="mediumb-text" style="margin-top:0px; margin-bottom:0px;"', attr='h1', href='href', url=url) # if links==[]: # res=self.dowload_basePr_userpass_link(links,"None:None",[],cookies=cookies) # html=res['html'];proxy0=res['proxy'];user_pass=res['user_pass'];cookies=res['cookies'];mech=res['mechanizm'] # # [html,proxy0,user_pass,cookies]=self.dowload_basePr_userpass_link(links,"None:None",[],cookies=cookies) # links2=LINK(links).soap_my(html,'<frame src="http://ieeexplore.ieee.org','frame','src') # link=links2 if links == [] or links == None or links == '': print'there is no trusted proxy for downloading it' else: link_done = 1 responce = { 'html': html, 'url': url, 'links': links, 'title': title, 'proxy': [], 'user_pass': [], 'cookies': cookies, 'mechanizm': mech, } return responce # return links,[],[],cookies def curl_download(self, url, cookies='',proxy=''): # self.url="%(ezproxy_host)s"%form_data # self.database_link="%(database_link)s"%form_data # self.username="%(user)s"%form_data # self.password="%(pass)s"%form_data # self.user_tag="%(user_tag)s"%form_data # self.pass_tag="%(pass_tag)s"%form_data # self.Form_id="%(Form_id)s"%form_data # self.submit_tag_name="%(submit_tag_name)s"%form_data # self.submit_tag_value="%(submit_tag_value)s"%form_data # self.Form_Type="%(Form_Type)s"%form_data # self.log_done="%(Log_test)s"%form_data link = url; # lg = url['log_out']; # url_logout = lg['log_out']; # ez_link = lg['ez_link'] # twil__headers = lg['headers'] if proxy!='': import subprocess #phantomjs --webdriver=8080 --webdriver-selenium-grid-hub=http://127.0.0.1:4444 #phantomjs --webdriver=8080 --webdriver-selenium-grid-hub=http://127.2.25.129:4444 #st='phantomjs --webdriver=8080 --webdriver-selenium-grid-hub=http://'+ip+':4444' # st='export http_proxy="http://'+proxy+'"' st='export HTTP_PROXY='+proxy awk_sort = subprocess.Popen( [st ], stdin= subprocess.PIPE, stdout= subprocess.PIPE,shell=True) awk_sort.wait() output = awk_sort.communicate()[0] print output.rstrip() #!/usr/bin/python #author: Bryan Bishop <kanzure@gmail.com> #date: 2010-03-03 #purpose: given a link on the command line to sciencedirect.com, download the associated PDF and put it in "sciencedirect.pdf" or something import os import re import pycurl #from BeautifulSoup import BeautifulSoup from lxml import etree import lxml.html from StringIO import StringIO from string import join, split user_agent = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.5) Gecko/20091123 Iceweasel/3.5.5 (like Firefox/3.5.5; Debian-3.5.5-1)" # def interscience(url): '''downloads the PDF from sciencedirect given a link to an article''' url = str(url) buffer = StringIO() curl = pycurl.Curl() curl.setopt(curl.URL, url) curl.setopt(curl.WRITEFUNCTION, buffer.write) curl.setopt(curl.VERBOSE, 0) curl.setopt(curl.USERAGENT, user_agent) curl.setopt(curl.TIMEOUT, 20) curl.perform() curl.close() buffer = buffer.getvalue().strip() html = lxml.html.parse(StringIO(buffer)) pdf_href = [] for item in html.getroot().iter('a'): if (('id' in item.attrib) and ('href' in item.attrib) and item.attrib['id']=='pdfLink'): pdf_href.append(item.attrib['href']) pdf_href = pdf_href[0] #now let's get the article title title_div = html.find("head/title") paper_title = title_div.text paper_title = paper_title.replace("\n", "") if paper_title[-1] == " ": paper_title = paper_title[:-1] re.sub('[^a-zA-Z0-9_\-.() ]+', '', paper_title) paper_title = paper_title.strip() paper_title = re.sub(' ','_',paper_title) #now fetch the document for the user command = "wget --user-agent=\"pyscholar/blah\" --output-document=\"%s.pdf\" \"%s\"" % (paper_title, pdf_href) os.system(command) print "\n\n" # interscience("http://www.sciencedirect.com/science/article/pii/S0163638307000628") # os.remove(cookies) return html def twill_download(self, url, cookies,proxy=''): # self.url="%(ezproxy_host)s"%form_data # self.database_link="%(database_link)s"%form_data # self.username="%(user)s"%form_data # self.password="%(pass)s"%form_data # self.user_tag="%(user_tag)s"%form_data # self.pass_tag="%(pass_tag)s"%form_data # self.Form_id="%(Form_id)s"%form_data # self.submit_tag_name="%(submit_tag_name)s"%form_data # self.submit_tag_value="%(submit_tag_value)s"%form_data # self.Form_Type="%(Form_Type)s"%form_data # self.log_done="%(Log_test)s"%form_data link = url; # lg = url['log_out']; # url_logout = lg['log_out']; # ez_link = lg['ez_link'] # twil__headers = lg['headers'] if proxy!='': import subprocess #phantomjs --webdriver=8080 --webdriver-selenium-grid-hub=http://127.0.0.1:4444 #phantomjs --webdriver=8080 --webdriver-selenium-grid-hub=http://127.2.25.129:4444 #st='phantomjs --webdriver=8080 --webdriver-selenium-grid-hub=http://'+ip+':4444' # st='export http_proxy="http://'+proxy+'"' st='export HTTP_PROXY='+proxy awk_sort = subprocess.Popen( [st ], stdin= subprocess.PIPE, stdout= subprocess.PIPE,shell=True) awk_sort.wait() output = awk_sort.communicate()[0] print output.rstrip() try: link = lg['pdf_link'] # site = urlparse2(link.absolute_url).hostname except: pass # site = urlparse2(link).hostname # self.a.config("readonly_controls_writeable", 1) # self.b = self.a.get_browser() # self.b.set_agent_string("Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14") # self.b.clear_cookies() twill = import_mod(from_module='twill') # t_com = twill.commands # t_com.reset_browser # t_com.reset_output t_com = twill.commands ## get the default browser t_brw = t_com.get_browser() try: t_brw.set_agent_string( "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14") t_com.add_extra_header('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1') t_com.add_extra_header('Accept', 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5;application/json;text/javascript;*/*') t_com.add_extra_header('Accept-Language', 'en,hu;q=0.8,en-us;q=0.5,hu-hu;q=0.3') t_com.add_extra_header('Accept-Encoding', 'gzip, deflate') t_com.add_extra_header('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.7') t_com.add_extra_header('Keep-Alive', '300') t_com.add_extra_header('Connection', 'keep-alive') t_com.add_extra_header('Cache-Control', 'max-age=0') # t_com.add_extra_header('Referer', ez_link) t_com.add_extra_header('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8') t_com.add_extra_header('X-Requested-With', 'XMLHttpRequest') except: t_com.add_extra_header('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1') t_com.add_extra_header('Accept', "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5;application/json;text/javascript;*/*") t_com.add_extra_header('Accept-Language', 'en,hu;q=0.8,en-us;q=0.5,hu-hu;q=0.3') t_com.add_extra_header('Accept-Encoding', 'gzip, deflate') t_com.add_extra_header('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.7') t_com.add_extra_header('Keep-Alive', '300') t_com.add_extra_header('Connection', 'keep-alive') t_com.add_extra_header('Cache-Control', 'max-age=0') # t_com.add_extra_header('Referer', ez_link) t_com.add_extra_header('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8') t_com.add_extra_header('X-Requested-With', 'XMLHttpRequest') # t_brw.set_agent_string(twil__headers) # cookies=cookies.replace('/','\\') try: t_brw.load_cookies(cookies) except:pass # socket=import_mod(from_module='socket') # socket.setdefaulttimeout(300) ## open the url # url = 'http://google.com' # t_brw.find_link(link) # t_brw.go(link) print '@@@@@@@@@@@@@ link download by twill is @@@@@@@@@@@@' print link print '@@@@@@@@@@@@@ link download by twill is @@@@@@@@@@@@' try: s = link.absolute_url t_brw.follow_link(link) except: t_brw.go(link) # class link_n(object): # def __init__(self): # self.absolute_url = link # self.base_url = ez_link # self.url=ez_link # def url(self): # return self # link=link_n.url # t_brw.follow_link(link) html0 = t_brw.result.page print '@@@@@@@@@@@@@ html0 download by twill is @@@@@@@@@@@@' print html0[:20] print '@@@@@@@@@@@@@ html0 download by twill is @@@@@@@@@@@@' # time.sleep(10) link2 = t_brw.result.url link2 = link.absolute_url if not (html0[:4] == '%PDF') or html0 == []: t_brw.go(link2) html, cookies = MECAHNIZM('', '', cookies=cookies, url=link2).speed_download(link2) # html3,pr,upss,cookies=web().download_mechanism_link(link,'',cookies=cookies) if not (html[:4] == '%PDF') or html == []: t_brw.save_cookies(cookies) t_brw = t_com.get_browser() t_brw.set_agent_string( "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14") t_brw.load_cookies(cookies) # socket=import_mod(from_module='socket') # socket.setdefaulttimeout(300) html3, pr, upss, cookies = web().download_mechanism_link(link, '', cookies=cookies) t_brw.go(link2) html = t_brw.result.page print '@@@@@@@@@@@@@ html download by twill is @@@@@@@@@@@@' print html print '@@@@@@@@@@@@@ html download by twill is @@@@@@@@@@@@' # time.sleep(10) else: html = html0 # t_brw.go(url_logout) os.remove(cookies) return html # ${OPENSHIFT_HOMEDIR}/app-root/runtime/srv/python/bin/python ${OPENSHIFT_HOMEDIR}/app-root/runtime/srv/tornado5/configs/Links_site/www_sciencedirect_com.py if __name__ == '__main__': #HOW TO USE: url = "http://127.0.0.1/1752-153X-2-5%20-%20Copy.pdf" url = "http://127.0.0.1/1752-153X-2-5.pdf" url = 'http://ieeexplore.ieee.org/xpl/articleDetails.jsp?tp=&arnumber=6180383&queryText%3Dpower' #91 KB # url = "http://127.0.0.1/" # url = "http://dl.acm.org/citation.cfm?id=99977.100000&coll=DL&dl=ACM" url='http://www.sciencedirect.com/science/article/pii/S0165176511002710' url='http://www.sciencedirect.com/science/article/pii/S2214629616300354' # url="http://www.sciencedirect.com.lib.just.edu.jo/science/article/pii/S009630031630282X/pdfft?md5=a22b846cbebf75dd7e816d7586a1a797&pid=1-s2.0-S009630031630282X-main.pdf" link=LINK(url).get_pdf_link() # link=LINK(url).curl_download(url) from optparse import OptionParser parser = OptionParser(description=__doc__) parser.add_option('-a', dest='url', help='adress url file name to be downloaded like:www.google.com') parser.add_option('-p', dest='url', help=' proxy setting for url file name to be download like:121.121.21.21:90') parser.add_option('-u', dest='user_name', help='user & password of proxy setting') parser.add_option('-i', dest='input_fname', help='file name to be watermarked (pdf)') parser.add_option('-w', dest='watermark_fname', help='watermark file name (pdf)') parser.add_option('-d', dest='pdfdir', help='make pdf files in this directory') parser.add_option('-o', dest='outdir', help='outputdir used with option -d', default='tmp') options, args = parser.parse_args()
48.193077
319
0.465946
ace9f32b54a98c71dd08a44b8013a38847dc87a2
3,698
py
Python
util/gen_ratio.py
Lukasa/hpack-test-case
c3e7c10eb1458cf0b42983d056939c2087fcc578
[ "MIT" ]
null
null
null
util/gen_ratio.py
Lukasa/hpack-test-case
c3e7c10eb1458cf0b42983d056939c2087fcc578
[ "MIT" ]
null
null
null
util/gen_ratio.py
Lukasa/hpack-test-case
c3e7c10eb1458cf0b42983d056939c2087fcc578
[ "MIT" ]
null
null
null
#!/usr/bin/env python # # This script takes directories which contain the hpack-test-case json # files, and calculates the compression ratio in each file and outputs # the result in table formatted in rst. # # The each directory contains the result of various HPACK compressor. # # The table is laid out so that we can see that how input header set # in one json file is compressed in each compressor. # import sys, json, os, re, argparse class Stat: def __init__(self, complen, srclen): self.complen = complen self.srclen = srclen def compute_stat(jsdata): complen = 0 srclen = 0 for item in jsdata['cases']: complen += len(item['wire']) // 2 srclen += \ sum([len(list(x.keys())[0]) + len(list(x.values())[0]) \ for x in item['headers']]) return Stat(complen, srclen) def format_result(r): return '{:.02f} ({}/{}) '.format(float(r.complen)/r.srclen, r.complen, r.srclen) if __name__ == '__main__': ignores = [ '.git', 'raw-data', 'util' ] basedir = os.path.dirname(os.path.abspath(__file__)) + '/../' entries = [(os.path.basename(re.sub(r'/+$', '', p)), p) for p in os.listdir(basedir)] entries.sort() maxnamelen = 0 maxstorynamelen = 0 res = {} stories = set() for name, ent in entries: entdir = basedir + ent if (not os.path.isdir(entdir)) or (ent in ignores): continue files = [p for p in os.listdir(entdir) if p.endswith('.json')] res[name] = {} maxnamelen = max(maxnamelen, len(name)) for fn in files: stories.add(fn) maxstorynamelen = max(maxstorynamelen, len(fn)) with open(os.path.join(entdir, fn)) as f: input = f.read() rv = compute_stat(json.loads(input)) res[name][fn] = rv maxnamelen = max(maxnamelen, len(format_result(rv))) stories = list(stories) stories.sort() overall = [] for name in res: r = Stat(0, 0) for _, stat in res[name].items(): r.srclen += stat.srclen r.complen += stat.complen overall.append(r) maxnamelen = max(maxnamelen, len(format_result(r))) storynameformat = '|{{:{}}} |'.format(maxstorynamelen) nameformat = '{{:{}}} |'.format(maxnamelen) sys.stdout.write('''\ The each cell has X (Y/Z) format: **X**: Y / Z **Y**: Number of bytes after compression **Z**: Number of bytes before compression ''') names = res.keys() names.sort() sys.stdout.write(storynameformat.format('story')) for name in names: sys.stdout.write(nameformat.format(name)) sys.stdout.write('\n') sys.stdout.write('|') sys.stdout.write('-'*(maxstorynamelen+1)) sys.stdout.write('|') for _ in names: sys.stdout.write('-'*(maxnamelen+1)) sys.stdout.write('|') sys.stdout.write('\n') for story in stories: sys.stdout.write(storynameformat.format(story)) srclen = -1 for name in names: stats = res[name] if story not in stats: sys.stdout.write(nameformat.format('N/A')) continue if srclen == -1: srclen = stats[story].srclen elif srclen != stats[story].srclen: raise Exception('Bad srclen') sys.stdout.write(nameformat.format(format_result(stats[story]))) sys.stdout.write('\n') sys.stdout.write(storynameformat.format('Overall')) for r in overall: sys.stdout.write(nameformat.format(format_result(r))) sys.stdout.write('\n')
30.561983
89
0.576528
ace9f3530c664ed5fda89ec1fb7f3fd2823357e0
3,749
py
Python
LuciferMoringstar_Robot/commands.py
coolboy007/updatedlucifer
e9420252641d2dd807741cf276d9dc2e5e615bb1
[ "MIT" ]
null
null
null
LuciferMoringstar_Robot/commands.py
coolboy007/updatedlucifer
e9420252641d2dd807741cf276d9dc2e5e615bb1
[ "MIT" ]
null
null
null
LuciferMoringstar_Robot/commands.py
coolboy007/updatedlucifer
e9420252641d2dd807741cf276d9dc2e5e615bb1
[ "MIT" ]
null
null
null
from random import choice from config import START_MSG, FORCES_SUB, BOT_PICS, ADMINS, bot_info, DEV_NAME from pyrogram import Client as LuciferMoringstar_Robot, filters as Worker from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton from translation import LuciferMoringstar from LuciferMoringstar_Robot.database.broadcast_db import Database db = Database() @LuciferMoringstar_Robot.on_message(Worker.private & Worker.command(["start"])) async def start_message(bot, message): if not await db.is_user_exist(message.from_user.id): await db.add_user(message.from_user.id) if len(message.command) != 2: if message.from_user.id not in ADMINS: buttons = [[ InlineKeyboardButton("➕️ Add me to Your Chat ➕️", url=f"http://t.me/{bot_info.BOT_USERNAME}?startgroup=true") ],[ InlineKeyboardButton("ℹ️ Help", callback_data="help"), InlineKeyboardButton("😎 About", callback_data="about") ],[ InlineKeyboardButton("🗳 Backup", url="https://t.me/sdmoviesflixback"), InlineKeyboardButton("🤖 Support", url="https://t.me/+F_s_7N05VRZlMzI1") ]] else: buttons = [[ InlineKeyboardButton("➕️ Add me to Your Chat ➕️", url=f"http://t.me/{bot_info.BOT_USERNAME}?startgroup=true") ],[ InlineKeyboardButton("ℹ️ Help", callback_data="bot_owner"), InlineKeyboardButton("😎 About", callback_data="about") ],[ InlineKeyboardButton("🗳 Backup", url="https://t.me/sdmoviesflixback"), InlineKeyboardButton("🤖 Support", url="https://t.me/+F_s_7N05VRZlMzI1") ]] await message.reply_photo(photo = choice(BOT_PICS), caption=START_MSG.format(mention = message.from_user.mention, bot_name = bot_info.BOT_NAME, bot_username = bot_info.BOT_USERNAME), reply_markup=InlineKeyboardMarkup(buttons)) elif len(message.command) ==2 and message.command[1] in ["subscribe"]: FORCES=["https://telegra.ph/file/b2acb2586995d0e107760.jpg"] invite_link = await bot.create_chat_invite_link(int(FORCES_SUB)) button=[[ InlineKeyboardButton("🔔 SUBSCRIBE 🔔", url=invite_link.invite_link) ]] reply_markup = InlineKeyboardMarkup(button) await message.reply_photo( photo=choice(FORCES), caption=f"""<i><b>Hello {message.from_user.mention}. \nYou Have <a href="{invite_link.invite_link}">Not Subscribed</a> To <a href="{invite_link.invite_link}">My Update Channel</a>.So you do not get the Files on Inline Mode, Bot Pm and Group</i></b>""", reply_markup=reply_markup ) return @LuciferMoringstar_Robot.on_message(Worker.private & Worker.command(["help"])) async def help(bot, message): button = [[ InlineKeyboardButton("🏠 Home", callback_data="start"), InlineKeyboardButton("About 😎", callback_data="about") ]] await message.reply_photo( photo = choice(BOT_PICS), caption=LuciferMoringstar.HELP_MSG.format(mention=message.from_user.mention), reply_markup=InlineKeyboardMarkup(button)) @LuciferMoringstar_Robot.on_message(Worker.private & Worker.command(["about"])) async def about(bot, message): button = [[ InlineKeyboardButton("🏠 Home", callback_data="start"), InlineKeyboardButton("Close 🗑️", callback_data="close") ]] await message.reply_photo( photo = choice(BOT_PICS), caption=LuciferMoringstar.ABOUT_MSG.format(mention=message.from_user.mention, bot_name=bot_info.BOT_NAME, bot_username=bot_info.BOT_USERNAME, dev_name=DEV_NAME), reply_markup=InlineKeyboardMarkup(button))
50.662162
264
0.67378
ace9f3bd5b01846cf4343fc54f95d6e06b5d86e6
3,324
py
Python
abstract/abstracttransfer.py
bhsingleton/eztransferweights
c26090ae5c9a28bac103f453d4e1216ec12bba82
[ "MIT" ]
null
null
null
abstract/abstracttransfer.py
bhsingleton/eztransferweights
c26090ae5c9a28bac103f453d4e1216ec12bba82
[ "MIT" ]
null
null
null
abstract/abstracttransfer.py
bhsingleton/eztransferweights
c26090ae5c9a28bac103f453d4e1216ec12bba82
[ "MIT" ]
null
null
null
from abc import ABCMeta, abstractmethod from six import with_metaclass from dcc import fnskin, fnmesh from dcc.decorators.classproperty import classproperty import logging logging.basicConfig() log = logging.getLogger(__name__) log.setLevel(logging.INFO) class AbstractTransfer(with_metaclass(ABCMeta, object)): """ Abstract base class that outlines weight transfer behavior. """ # region Dunderscores __slots__ = ('_skin', '_mesh', '_vertexIndices') def __init__(self, *args, **kwargs): """ Private method called after a new instance has been created. :rtype: None """ # Call parent method # super(AbstractTransfer, self).__init__() # Declare private variables # self._skin = fnskin.FnSkin() self._mesh = fnmesh.FnMesh() self._vertexIndices = [] # Inspect arguments # numArgs = len(args) if numArgs == 1: # Inspect skin type # skin = args[0] if not isinstance(skin, fnskin.FnSkin): raise TypeError('%s() expects a valid skin!' % self.className) # Store all vertex elements # self._skin = args[0] self._mesh.setObject(self._skin.intermediateObject()) self._vertexIndices = list(range(self._skin.numControlPoints())) elif numArgs == 2: # Inspect skin type # skin = args[0] if not isinstance(skin, fnskin.FnSkin): raise TypeError('%s() expects a valid skin!' % self.className) # Inspect vertex elements type # vertexIndices = args[1] if not isinstance(vertexIndices, (list, tuple, set)): raise TypeError('%s() expects a valid list (%s given)!' % (self.className, type(vertexIndices).__name__)) # Store vertex elements # self._skin = skin self._mesh.setObject(self._skin.intermediateObject()) self._vertexIndices = vertexIndices else: raise TypeError('TransferWeights() expects 1 or 2 arguments (%s given)!' % numArgs) # endregion # region Properties @classproperty def className(cls): """ Getter method that returns the name of this class. :rtype: str """ return cls.__name__ @property def mesh(self): """ Getter method that returns the mesh function set. :rtype: fnmesh.FnMesh """ return self._mesh @property def skin(self): """ Getter method that returns the skin function set. :rtype: fnskin.FnSkin """ return self._skin @property def vertexIndices(self): """ Getter method that returns the cached vertex indices. :rtype: List[int] """ return self._vertexIndices # endregion # region Methods @abstractmethod def transfer(self, otherSkin, vertexIndices): """ Transfers the weights from this object to the supplied skin. :type otherSkin: fnskin.FnSkin :type vertexIndices: List[int] :rtype: None """ pass # endregion
23.408451
121
0.573105
ace9f51559539d62d8ada34676e40b6d8797cf01
281
py
Python
tests/artificial/transf_RelativeDifference/trend_PolyTrend/cycle_30/ar_12/test_artificial_1024_RelativeDifference_PolyTrend_30_12_20.py
jmabry/pyaf
afbc15a851a2445a7824bf255af612dc429265af
[ "BSD-3-Clause" ]
null
null
null
tests/artificial/transf_RelativeDifference/trend_PolyTrend/cycle_30/ar_12/test_artificial_1024_RelativeDifference_PolyTrend_30_12_20.py
jmabry/pyaf
afbc15a851a2445a7824bf255af612dc429265af
[ "BSD-3-Clause" ]
1
2019-11-30T23:39:38.000Z
2019-12-01T04:34:35.000Z
tests/artificial/transf_RelativeDifference/trend_PolyTrend/cycle_30/ar_12/test_artificial_1024_RelativeDifference_PolyTrend_30_12_20.py
jmabry/pyaf
afbc15a851a2445a7824bf255af612dc429265af
[ "BSD-3-Clause" ]
null
null
null
import pyaf.Bench.TS_datasets as tsds import pyaf.tests.artificial.process_artificial_dataset as art art.process_dataset(N = 1024 , FREQ = 'D', seed = 0, trendtype = "PolyTrend", cycle_length = 30, transform = "RelativeDifference", sigma = 0.0, exog_count = 20, ar_order = 12);
40.142857
176
0.743772
ace9f52d6f288230c6a6b39827a14e24b34e42eb
3,715
py
Python
_07_WEB_BROWSER/gallery.py
khanhtranngoccva/100ProjectsOfCode
ca06ce324c35d150b48a7d8fe5aaba8c06264065
[ "MIT" ]
1
2021-12-25T13:10:58.000Z
2021-12-25T13:10:58.000Z
_07_WEB_BROWSER/gallery.py
khanhtranngoccva/100ProjectsOfCode
ca06ce324c35d150b48a7d8fe5aaba8c06264065
[ "MIT" ]
null
null
null
_07_WEB_BROWSER/gallery.py
khanhtranngoccva/100ProjectsOfCode
ca06ce324c35d150b48a7d8fe5aaba8c06264065
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'gallery.ui' # # Created by: PyQt5 UI code generator 5.15.4 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. import os from PyQt5 import QtCore, QtGui, QtWidgets def get_photos(): return [QtGui.QPixmap("gallery_photo/" + photo_name) for photo_name in os.listdir("gallery_photo")] class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(800, 600) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.horizontalLayoutWidget = QtWidgets.QWidget(self.centralwidget) self.horizontalLayoutWidget.setGeometry(QtCore.QRect(0, 500, 801, 80)) self.horizontalLayoutWidget.setObjectName("horizontalLayoutWidget") self.horizontalLayout = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget) self.horizontalLayout.setContentsMargins(0, 0, 0, 0) self.horizontalLayout.setObjectName("horizontalLayout") self.back = QtWidgets.QPushButton(self.horizontalLayoutWidget) self.back.setObjectName("back") self.horizontalLayout.addWidget(self.back) self.next = QtWidgets.QPushButton(self.horizontalLayoutWidget) self.next.setObjectName("next") self.horizontalLayout.addWidget(self.next) self.photo_label = QtWidgets.QLabel(self.centralwidget) self.photo_label.setGeometry(QtCore.QRect(0, 0, 801, 481)) self.photo_label.setObjectName("photo_label") MainWindow.setCentralWidget(self.centralwidget) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) self.photos = get_photos() self.photo_count = len(self.photos) self.position = 0 self.back.clicked.connect(lambda: self.update_photo(-1)) self.next.clicked.connect(lambda: self.update_photo(1)) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "Image Gallery")) self.back.setText(_translate("MainWindow", "Back")) self.next.setText(_translate("MainWindow", "Next")) self.photo_label.setText(_translate("MainWindow", "TextLabel")) def update_photo(self, offset): self.show_popup(f'You moved {offset} images.') self.position += offset if self.position >= self.photo_count: self.position %= self.photo_count elif self.position < 0: self.position %= self.photo_count # print(self.position) self.photo_label.setPixmap(self.photos[self.position]) def show_popup(self, text): msg = QtWidgets.QMessageBox() msg.setWindowTitle("Tutorial on PyQt5") msg.setText(text) msg.setIcon(QtWidgets.QMessageBox.Warning) msg.setStandardButtons(QtWidgets.QMessageBox.Close|QtWidgets.QMessageBox.Ignore) msg.setInformativeText("oof") msg.setDetailedText("ooooooffff") msg.buttonClicked.connect(self.popup_log) # msg.show() msg.exec_() def popup_log(self, i): print(i.text()) if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_())
39.946237
103
0.695289
ace9f5e7a231d29e9f3fcd2de2842147d51c5ecc
9,886
py
Python
scripts/couchdb_replication.py
ssjunnebo/scilifelab
79960f7042118f900bd1eaabe4902ee76abd8020
[ "MIT" ]
1
2016-03-21T14:04:09.000Z
2016-03-21T14:04:09.000Z
scripts/couchdb_replication.py
ssjunnebo/scilifelab
79960f7042118f900bd1eaabe4902ee76abd8020
[ "MIT" ]
35
2015-01-22T08:25:02.000Z
2020-02-17T12:09:12.000Z
scripts/couchdb_replication.py
ssjunnebo/scilifelab
79960f7042118f900bd1eaabe4902ee76abd8020
[ "MIT" ]
6
2015-01-16T15:32:08.000Z
2020-01-30T14:34:40.000Z
#!/usr/bin/env python import couchdb import json import argparse import logbook import sys import os import ConfigParser from couchdb import PreconditionFailed #Set up logging l = logbook.Logger('CouchDB-Replicator') class Config(object): """Singleton class that holds the confiuration for the CouchDB replicator. """ _instance = None def __new__(self, *args, **kwargs): if not self._instance: self._instance = super(Config, self).__new__(self, *args, **kwargs) return self._instance def __init__(self, config_file=None): config = ConfigParser.SafeConfigParser() try: if not config_file: config_file = os.path.join(os.environ['HOME'], '.couchrc') with open(config_file, 'r') as f: config.readfp(f) self.source = config.get('replication', 'SOURCE').rstrip() self.destination = config.get('replication', 'DESTINATION').rstrip() except: l.error("Please make sure you've created your own configuration file \ (i.e: ~/.couchrc), and that it contains a source and a destination servers") sys.exit(-1) self.exceptions = [] if not config.has_section('exceptions') else \ [exception for _, exception in config.items('exceptions')] self.roles = {"members": [], "admins": [] } if config.has_section('roles'): if config.has_option('roles', 'members'): self.roles['members'] = config.get('roles', 'members').split(',') if config.has_option('roles', 'admins'): self.roles['admins'] = config.get('roles', 'admins').split(',') def _get_databases_info(source, destination, skip): """Returns a tuple containing a python representation of source and destination couchDB instances. It also returns a list of the databases in both instances (excluding the _replicator database). """ s_couch = couchdb.Server(source) d_couch = couchdb.Server(destination) _, _, s_dbs = s_couch.resource.get_json('_all_dbs') _, _, d_dbs = d_couch.resource.get_json('_all_dbs') l.info("Databases in the source CouchDB instance: {}".format(', '.join(s_dbs))) l.info("Databases in the destination CouchDB instance: {}".format(', '.join(d_dbs))) #We don't want to replicate the replicator DB, and want to skip the databases in skip list skip.append('_replicator') for db in skip: try: s_dbs.remove(db) except ValueError: pass try: d_dbs.remove(db) except ValueError: pass return s_couch, d_couch, s_dbs, d_dbs def _setup_continuous(source, destination, copy_security): """Set up a continuous replication of all databases in source to destination. """ s_couch, d_couch, s_dbs, d_dbs = _get_databases_info(source, destination) #For each DB in the source CouchDB instance, create a replication document #and get its _security object to put it in the destination database for db in s_dbs: _, _, security = s_couch[db].resource.get_json('_security') doc = { 'name': '{}_rep'.format(db), 'source': '{}/{}/'.format(source, db), 'target': '{}/{}/'.format(destination, db), 'continuous': True } s_rep = s_couch['_replicator'] #Create the DB in the destination if not present try: d_couch.create(db) l.info("Created {} database in destination".format(db)) except PreconditionFailed: l.info("Database {} already existing in the destination, not creating it".format(db)) #Put the replicator document in source and set security object in destination l.info("Putting replicator document in _replicator database of source") s_rep.create(doc) if copy_security: l.info("Copying security object to {} database in destination".format(db)) d_couch[db].resource.put('_security', security) l.info("DONE!") def _clone(source, destination, copy_security, with_exceptions=False, skip=[]): """Creates a complete clone of source in destination. WARNING: This action will remove ALL content from destination. """ l.info("Performing a complete clone from source to destination") s_couch, d_couch, s_dbs, d_dbs = _get_databases_info(source, destination, skip) config = Config() #Delete all databases in destination l.info("Removing all databases from destination") for db in d_dbs: d_couch.delete(db) #Create all databases abailable in source to destination. Copy data and #permissions l.info("Re-creating databases from source into destination") for db in s_dbs: #The users database is never deleted if not db == '_users': d_couch.create(db) _, _, security = s_couch[db].resource.get_json('_security') source_db = '/'.join([source, db]) dest_db = '/'.join([destination, db]) l.info("Copying data from {} in source to destination".format(db)) d_couch.replicate(source_db, dest_db) if copy_security: l.info("Copying security object to {} database in destination".format(db)) d_couch[db].resource.put('_security', security) if with_exceptions: exceptions = config.exceptions if not exceptions: l.warn("--with-exceptions option was present, but didn't find " \ "any EXCEPTIONS list in your .couchrc file.") else: l.info("--with-exceptions option was present, removing following documents: {}".format(", ".join(exceptions))) for exception in exceptions: try: d_couch[db].delete(d_couch[db].get(exception)) except: l.warn("Document {} not found, not deleteing".format(exception)) l.info("DONE!") def _set_roles(server): """Apply the list of roles present in .couchrc to all databases in the server. """ security_obj = {"admins": { "names":[], "roles":[] }, "members": { "names":[], "roles":[] } } config = Config() security_obj['admins']['roles'] = config.roles['admins'] security_obj['members']['roles'] = config.roles['members'] s_couch, d_couch, s_dbs, d_dbs = _get_databases_info(source, destination) l.info("Setting roles to destination databases: {}".format(str(security_obj))) for db in d_dbs: d_couch[db].resource.put('_security', security_obj) if __name__ == "__main__": DESCRIPTION = """Set up complete one-way replication for CouchDB. Use this script if you want to configure a stage database that will have the exact same content of your production database. To do so, the script creates a replication document for each database in the source CouchDB instance that replicates such database (in continuous mode) to the destination database. Security object (permissions per database), are put to the destination databases. """ parser = argparse.ArgumentParser(description=DESCRIPTION) parser.add_argument('action', type=str, help = "Action to perform, either \ configure continuous replication (continuous) or punctual clone (clone)") parser.add_argument('--source', type=str, help = "Source CouchDB instance, \ with the credentials included in the URL. I.E: http://admin:passw@source_db:5984") parser.add_argument('--destination', type=str, help = "Destination CouchDB instance, \ with the credentials included in the URL. I.E: http://admin:passw@destination_db:5984") parser.add_argument('--no-security', action='store_const', const=True, \ help='Do not copy security objects') parser.add_argument('--with-exceptions', action='store_const', const=True, \ help='List of files to be deleted from the DataBases after being copied. ' \ 'To be specified in your .couchrc file') parser.add_argument('--set-roles', action='store_const', const=True, \ help='List of roles to apply to each database after copied. Only if' \ '--no-security is present.') parser.add_argument('--skip', nargs="+", type=str, help=('List of databases to skip during the replication. ' 'They will remain intact in the destination database')) args = parser.parse_args() source = args.source destination = args.destination copy_security = False if args.no_security else True action = args.action config = Config() if not all([source, destination]): source = config.source destination = config.destination actions = ['continuous', 'clone'] if action not in actions: raise ValueError("Action not recognised, please choose between %s" % \ ', '.join(actions)) l.info("Starting replication - source: {}, destination: {}".format( \ source.split('@')[-1], destination.split('@')[-1])) if action == "continuous": _setup_continuous(source, destination, copy_security) else: _clone(source, destination, copy_security, with_exceptions=args.with_exceptions, skip=args.skip) if args.set_roles: if not args.no_security: l.warn('--set-roles option only takes effect if applied together ' \ 'with --no-security. Ignoring it') else: _set_roles(destination)
39.544
126
0.620069
ace9f68d94b97bcc67254f9b237fbaa8ad90d984
6,146
py
Python
src/wx/analyse_movie.py
z80lives/affective-movie-evaluator
c22e0d75166c9c26cbca276c70b38c1f6419bfe0
[ "MIT" ]
null
null
null
src/wx/analyse_movie.py
z80lives/affective-movie-evaluator
c22e0d75166c9c26cbca276c70b38c1f6419bfe0
[ "MIT" ]
1
2019-11-16T23:43:28.000Z
2019-11-16T23:43:28.000Z
src/wx/analyse_movie.py
z80lives/affective-movie-evaluator
c22e0d75166c9c26cbca276c70b38c1f6419bfe0
[ "MIT" ]
null
null
null
import wx class FormObj: pass from src.wx.timeseries import SerialPlotter from src.wx.record import SearchBoxMovie from src.wx.player import VideoPlayerPanel import pandas as pd import numpy as np #class SamplePreviewPanel(wx.Panel): # pass class AnalyseMovieTabPanel(wx.Panel): selectedMovie=None recordMode=False last_sample_id=None mean_mag=[] mean_aud_score = 0 #timer = None testStatus=False def __init__(self, parent, event_handler, controllers): super().__init__(parent, wx.ID_ANY) self.top_parent = wx.GetApp().TopWindow self.form = FormObj() self.video_preview = FormObj() self.gsr_preview = FormObj() self.controllers = controllers #self.timer = wx.Timer(self) self.event_handler = event_handler self.parent = parent self.movie_player_ctrl = VideoPlayerPanel(self) #print(controllers.personController.getAll()) #self.create_preview_panel(self.video_preview) self.serial_plotter = SerialPlotter(self, ylim=(0,10)) self.serial_plotter.updateCallback = self.plotterUpdate self.serial_plotter.xvals = [] self.mean_mag = [(1,1),(2,3),(3,4),(4,5),(6,1)] self.serial_plotter.windowSize = 10 #self.serial_plotter.vals = self.top_parent.edaFrames self.create_form(self.form) self.do_layout() self.do_bind() def create_form(self, form): form.lblMovieID = wx.StaticText(self, wx.ID_ANY, "Movie") form.txtMovieID = wx.TextCtrl(self, wx.ID_ANY, "Not Selected", style=wx.TE_READONLY) form.btnFindMovie = wx.Button(self, wx.ID_ANY, "Find Movie") form.lblReport = wx.StaticText(self, wx.ID_ANY, "Report") form.btnSummary = wx.Button(self, wx.ID_ANY, "Summary") form.btnSamples = wx.Button(self, wx.ID_ANY, "Samples") form.btnCalculcate = wx.Button(self, wx.ID_ANY, "Calculate Scores") #form.btnRecord = wx.Button(self, wx.ID_ANY, "Record") #form.btnTest = wx.Button(self, wx.ID_ANY, "Test") def create_preview_panel(self, video_preview): video_preview.videoFrame = wx.Panel(self, -1, size=(320,200)) video_preview.timeslider = wx.Slider(self, -1, 0, 0, 1000) video_preview.timeslider.SetRange(0, 1000) #video_preview.Add(self.movie_player_ctrl, 1, wx.EXPAND) #self.top_parent.addCameraFrame(video_preview.videoFrame, "test", size=(320,200)) def do_layout(self): form = self.form main_sizer = wx.BoxSizer(wx.HORIZONTAL) form_grid = wx.GridSizer(8, 2, 0, 0) vid_container = wx.BoxSizer(wx.VERTICAL) ts_container = wx.BoxSizer(wx.VERTICAL) form_grid.Add(form.lblMovieID) form_grid.Add(form.txtMovieID) form_grid.Add((0,0)) form_grid.Add(form.btnFindMovie) #form_grid.Add(form.btnFindMovie) #form_grid.Add(form.btnRecord) form_grid.Add((0,0), 0,0,0) form_grid.Add((0,0), 0,0,0) #form_grid.Add(form.btnTest) form_grid.Add(form.lblReport) form_grid.Add(form.btnSummary) form_grid.Add(form.btnSamples) form_grid.Add((0,0), 0,0,0) form_grid.Add(form.btnCalculcate) ts_container.Add(self.serial_plotter) main_sizer.Add(form_grid, 0.3, wx.ALIGN_LEFT) #main_sizer.Add(vid_container) main_sizer.Add(self.movie_player_ctrl, 1, wx.EXPAND, 0) main_sizer.Add(ts_container, 1, wx.EXPAND) self.SetSizer(main_sizer) self.Layout() def loadTimeSeriesData(self, movie_id): samples = self.controllers.sampleController.getSamplesByMovie(movie_id) #samples = np.array(sample) total_aud_score = [] for sample in samples: total_aud_score.append(sample["score_5"]) #motion_history_df = pd.read_csv("./data/"+sample["id"]+"/motion_history.csv") #print(motion_history_df.describe()) #total_aud_score = np.array(total_aud_score) mean_aud_score = np.mean(total_aud_score) def searchMovie(self, event): movies = self.controllers.movieController.listMovies() movieDialog = SearchBoxMovie(self.parent, movies) result = movieDialog.ShowModal() if result == wx.ID_OK: item = movieDialog.getSelectedItem() self.form.txtMovieID.SetValue(item["name"]) self.selectedMovie = item self.movie_player_ctrl.setVideo("./movies/"+item["filename"]) #df = pd.read_csv() self.loadTimeSeriesData(item["id"]) movieDialog.Destroy() def do_bind(self): self.form.btnFindMovie.Bind(wx.EVT_BUTTON, self.searchMovie) #self.form.btnTest.Bind(wx.EVT_BUTTON, self.toggleTest) #self.Bind(wx.EVT_TIMER, self.onUpdate) def startRecord(self): self.top_parent.print("Starting record") def stopRecord(self): self.top_parent.print("Stopping record") def onRecordFrame(self, frame): pass def onRecordEnd(self, filename): pass def toggleTest(self,event): #gsrEnabled = self.form.cbGSR.GetValue() gsrEnabled = False if not self.testStatus: self.serial_plotter.clear() #if gsrEnabled: # self.top_parent.start_gsr() #self.top_parent.start_camera() self.startRecord() else: #if gsrEnabled: # self.top_parent.stop_gsr() #self.top_parent.stop_camera() self.stopRecord() self.testStatus = not self.testStatus def plotterUpdate(self, val, ts): if len(ts.xvals) != len(self.mean_mag): ts.xvals = [n[0] for n in self.mean_mag] ts.vals = [n[1] for n in self.mean_mag] #eda = self.top_parent.edaFrames #eda = self.mean_mag #print(eda) #if len(eda) > 0: # v = eda[len(eda)-1][1] # t = eda[len(eda)-1][0] # val.append(v) # ts.xvals.append(t)
35.12
93
0.623332
ace9f7f3b0395fce9412e5cd4ac42f6e61450686
2,032
py
Python
assignment8/assignment8.py
lancebrown42/pythonIntro
d151626a03c18f84b28b8567cdff0122358603bd
[ "MIT" ]
null
null
null
assignment8/assignment8.py
lancebrown42/pythonIntro
d151626a03c18f84b28b8567cdff0122358603bd
[ "MIT" ]
null
null
null
assignment8/assignment8.py
lancebrown42/pythonIntro
d151626a03c18f84b28b8567cdff0122358603bd
[ "MIT" ]
null
null
null
########################################################## # Lance Brown # Assignment 8 ########################################################## from StudentClass import Student as Student ########################################################## # Validate Gender- validates input is in a usable format ########################################################## def validateGender(strGender): if strGender != "MALE" and strGender != "FEMALE" and strGender != "M" and strGender != "F": validateGender((input("Please enter 'male' or 'female': ")).upper()) else: return strGender[0] ########################################################## # Validate GPA - validates input is numerical between 0 and 4 ########################################################## def validateGPA(dblGPA): try: dblGPA = float(dblGPA) except ValueError: dblGPA = validateGPA(input("Enter a numerical value: ")) if dblGPA < 0 or dblGPA > 4: dblGPA = validateGPA(input("Enter a valid GPA from 0-4: ")) return dblGPA ########################################################## # Validate age - validates input is integer and a reasonable range ########################################################## def validateAge(intAge): try: intAge = int(intAge) except ValueError: intAge = validateAge(input("Enter a numerical value: ")) if intAge <= 0 or intAge > 200: intAge = validateAge(input("Enter a valid age: ")) return intAge ########################################################## # Main ########################################################## arrStudents = [] while len(arrStudents) < 5: strFirstName = input("Enter a first name: ") strLastName = input("Enter last name: ") strGender = validateGender((input("Enter Gender: ")).upper()) dblGPA = validateGPA(input("Enter GPA: ")) intAge = validateAge(input("Enter age: ")) arrStudents.append(Student(strFirstName, strLastName, strGender, dblGPA, intAge)) Student.displayCount() Student.displayGenders() Student.displayAverageGPA() Student.displayAverageAge()
36.945455
92
0.515256
ace9f80e7b695e216ff9381a38131094538ff474
6,269
py
Python
1_code/stats/user_stats.py
jaimiles23/Multiplication_Medley
1072dea1a5be0b339211ff39db6a89a90aca64c1
[ "MIT" ]
null
null
null
1_code/stats/user_stats.py
jaimiles23/Multiplication_Medley
1072dea1a5be0b339211ff39db6a89a90aca64c1
[ "MIT" ]
null
null
null
1_code/stats/user_stats.py
jaimiles23/Multiplication_Medley
1072dea1a5be0b339211ff39db6a89a90aca64c1
[ "MIT" ]
null
null
null
"""/** * @author [Jai Miles] * @email [jaimiles23@gmail.com] * @create date 2020-05-14 11:56:25 * @modify date 2020-05-26 09:58:34 * @desc [ UserStats utility class to manage statistics. Methods for: - User stats - Mode stats - User table stats ] */ """ ########## # Imports ########## from statistics import mean, stdev from logs import log_func_name, logger, log_all from players.players_dict import PlayerDict from mult_questions.question_attr import QuestionAttr from aux_utils.z_score import calc_z_score import stats.data from stats.mode_stats import ModeStats ########## # AnswerPlayerAttr Utility Class ########## class UserStats(object): @staticmethod @log_func_name def update_player_stats(handler_input, correct: bool, player_obj: object = None) -> None: """Updates the user profile statistics. Increments the correct / incorrect counters. Updates the average tables and the info for each times table.""" attr = handler_input.attributes_manager.session_attributes tables = attr['question'] if not player_obj: player_obj = PlayerDict.load_player_obj(handler_input) player_obj.increment_answer_counter(correct) player_obj.update_average_table(tables) player_obj.update_times_tables_info_dict(tables, correct) PlayerDict.save_player_obj(handler_input, player_obj) return ########## # Mode stats ########## @staticmethod @log_func_name def update_player_fp_stats(handler_input, player_obj: object) -> None: """Updates player statistics for free play mode.""" attr = handler_input.attributes_manager.session_attributes mode = attr.get('mode', None) correct, _ = ModeStats.get_mode_stats(handler_input, mode = mode) return None @staticmethod @log_func_name def update_player_cp_stats( handler_input, player_obj: object = None) -> None: """Updates the player's Custom practice Statistics.""" correct, incorrect = ModeStats.get_mode_stats(handler_input, 'custom') if correct > 3: player_obj.cp_plays += 1 return None @staticmethod @log_func_name def update_player_sc_stats( handler_input, sc_score_time: int, player_obj: object = None) -> None: """Updates the player's Speed Challenge stats.""" attr = handler_input.attributes_manager.session_attributes sc_difficulty = attr['sc_difficulty'] if not player_obj: player_obj = PlayerDict.load_player_obj(handler_input) player_obj.set_sc_high_score(sc_difficulty, sc_score_time) player_obj.update_sc_average_record(sc_difficulty, sc_score_time) player_obj.sc_plays += 1 return None @staticmethod @log_func_name def update_player_sm_stats(handler_input, player_obj: object = None) -> None: """Updates the player's Survival Mode stats.""" attr = handler_input.attributes_manager.session_attributes mode = attr.get('mode', None) correct, _ = ModeStats.get_mode_stats(handler_input, mode= mode) if not player_obj: player_obj = PlayerDict.load_player_obj(handler_input) if correct > player_obj.get_sm_high_score(): player_obj.set_sm_high_score(correct) player_obj.update_sm_records(correct) player_obj.sm_plays += 1 PlayerDict.save_player_obj(handler_input, player_obj) return None ########## # User Table statistics ########## @staticmethod @log_func_name def get_higher_table_error_freq( handler_input, player_obj: object = None, tables: tuple = None ) -> float: """Returns z_score for the highest error tables.""" if not player_obj: player_obj = PlayerDict.load_player_obj(handler_input) if tables is None: tables = QuestionAttr.get_question_tables(handler_input, integers=False) times_tables_info = player_obj.get_times_table_info() times_tables_mean_err_list = [] for table in times_tables_info.keys(): table_mean = float(times_tables_info[table]['mean']) table_data = times_tables_info[table]['table_data'] if len(table_data) > stats.data.SUF_TABLE_DATA: times_tables_mean_err_list.append(1 - table_mean) # inversed, so errors are higher. ## Exit if not enough data. if len(times_tables_mean_err_list) <= stats.data.SUF_ERR_LIST: return 0 question_tables_err = [] for table in tables: table = str(table) table_info = float( times_tables_info[table]['mean']) table_info = (1 - table_info) # inverse mean. question_tables_err.append( table_info) max_table_err = max(question_tables_err) z_score = calc_z_score( data_point= max_table_err, data= times_tables_mean_err_list, ) return ( z_score) @staticmethod @log_func_name def get_higher_table_difficulty( handler_input, player_obj: object = None, tables: tuple = None, answered_tables: list = None ) -> float: """Returns z_score for the table with the highest difficulty. Difficulty is a constructed measure dependent on greatness of tables, e.g., 6 > 5.""" if not player_obj: player_obj = PlayerDict.load_player_obj(handler_input) if tables is None: tables = QuestionAttr.get_question_tables(handler_input, integers=True) if answered_tables is None: answered_tables = player_obj.get_answered_tables(integers = True) inflated_mean_table = mean(answered_tables) + 1 higher_table = max( [int(table) for table in tables]) z_score = calc_z_score( data_point= higher_table, data_mean = inflated_mean_table, data= answered_tables, required_data_length= stats.data.SUF_ANSWERED_TABLES ) return z_score
31.502513
101
0.645079
ace9f938d6f25e92a28570f5ff9483e8c9702a5f
1,825
py
Python
python/Autoencoder/DataGenerator.py
YushchenkoAndrew/template
35c6bcd2121647015308f0cc110da71aa148d5fb
[ "MIT" ]
5
2020-08-25T11:35:04.000Z
2021-12-25T18:57:58.000Z
python/Autoencoder/DataGenerator.py
YushchenkoAndrew/template
35c6bcd2121647015308f0cc110da71aa148d5fb
[ "MIT" ]
null
null
null
python/Autoencoder/DataGenerator.py
YushchenkoAndrew/template
35c6bcd2121647015308f0cc110da71aa148d5fb
[ "MIT" ]
3
2020-10-08T07:51:33.000Z
2021-12-29T10:19:24.000Z
import numpy as np import keras class DataGenerator(keras.utils.Sequence): 'Generates data for Keras' def __init__(self, list_IDs, labels, batch_size=32, dim=(32, 32, 32), n_channels=1, n_classes=10, shuffle=True): 'Initialization' self.dim = dim self.batch_size = batch_size self.labels = labels self.list_IDs = list_IDs self.n_channels = n_channels self.n_classes = n_classes self.shuffle = shuffle self.on_epoch_end() def __len__(self): 'Denotes the number of batches per epoch' return int(np.floor(len(self.list_IDs) / self.batch_size)) def __getitem__(self, index): 'Generate one batch of data' # Generate indexes of the batch indexes = self.indexes[index*self.batch_size:(index+1)*self.batch_size] # Find list of IDs list_IDs_temp = [self.list_IDs[k] for k in indexes] # Generate data X, y = self.__data_generation(list_IDs_temp) return X, y def on_epoch_end(self): 'Updates indexes after each epoch' self.indexes = np.arange(len(self.list_IDs)) if self.shuffle == True: np.random.shuffle(self.indexes) def __data_generation(self, list_IDs_temp): # X : (n_samples, *dim, n_channels) 'Generates data containing batch_size samples' # Initialization X = np.empty((self.batch_size, *self.dim, self.n_channels)) y = np.empty((self.batch_size), dtype=int) # Generate data for i, ID in enumerate(list_IDs_temp): # Store sample X[i, ] = np.load('data/' + ID + '.npy') # Store class y[i] = self.labels[ID] return X, keras.utils.to_categorical(y, num_classes=self.n_classes)
30.932203
87
0.612603
ace9f9a1df7b4a056cfc0e482b46bb22a4b47ac3
359
py
Python
loadbalancer_interface/schemas/__init__.py
juju-solutions/loadbalancer-interface
ee84fb93ea52e55506f267cde28935df7d60a16d
[ "Apache-2.0" ]
null
null
null
loadbalancer_interface/schemas/__init__.py
juju-solutions/loadbalancer-interface
ee84fb93ea52e55506f267cde28935df7d60a16d
[ "Apache-2.0" ]
2
2021-01-19T22:29:02.000Z
2021-03-12T16:55:06.000Z
loadbalancer_interface/schemas/__init__.py
juju-solutions/loadbalancer-interface
ee84fb93ea52e55506f267cde28935df7d60a16d
[ "Apache-2.0" ]
null
null
null
from importlib import import_module from pathlib import Path versions = {} for subpath in Path(__file__).parent.glob("*.py"): name = subpath.stem if name == __name__: continue submod = import_module(__package__ + "." + name) if hasattr(submod, "version"): versions[submod.version] = submod max_version = max(versions.keys())
25.642857
52
0.67688
ace9f9c3cdc8fd8fbd56bb667c992d38cc41f37a
264
py
Python
tests/artificial/transf_Logit/trend_ConstantTrend/cycle_30/ar_/test_artificial_128_Logit_ConstantTrend_30__0.py
shaido987/pyaf
b9afd089557bed6b90b246d3712c481ae26a1957
[ "BSD-3-Clause" ]
377
2016-10-13T20:52:44.000Z
2022-03-29T18:04:14.000Z
tests/artificial/transf_Logit/trend_ConstantTrend/cycle_30/ar_/test_artificial_128_Logit_ConstantTrend_30__0.py
ysdede/pyaf
b5541b8249d5a1cfdc01f27fdfd99b6580ed680b
[ "BSD-3-Clause" ]
160
2016-10-13T16:11:53.000Z
2022-03-28T04:21:34.000Z
tests/artificial/transf_Logit/trend_ConstantTrend/cycle_30/ar_/test_artificial_128_Logit_ConstantTrend_30__0.py
ysdede/pyaf
b5541b8249d5a1cfdc01f27fdfd99b6580ed680b
[ "BSD-3-Clause" ]
63
2017-03-09T14:51:18.000Z
2022-03-27T20:52:57.000Z
import pyaf.Bench.TS_datasets as tsds import tests.artificial.process_artificial_dataset as art art.process_dataset(N = 128 , FREQ = 'D', seed = 0, trendtype = "ConstantTrend", cycle_length = 30, transform = "Logit", sigma = 0.0, exog_count = 0, ar_order = 0);
37.714286
164
0.731061
ace9fa7c962038bba6aba062c2a5acf2a8aceb2a
912
py
Python
animal/arenas/create_reason.py
compsciencelab/ppo_D
1870c908f498ceb29295e5625ff5598bed82cbb3
[ "MIT" ]
4
2021-08-18T07:47:38.000Z
2022-01-06T17:27:21.000Z
animal/arenas/create_reason.py
compsciencelab/ppo_D
1870c908f498ceb29295e5625ff5598bed82cbb3
[ "MIT" ]
null
null
null
animal/arenas/create_reason.py
compsciencelab/ppo_D
1870c908f498ceb29295e5625ff5598bed82cbb3
[ "MIT" ]
1
2022-02-16T11:03:12.000Z
2022-02-16T11:03:12.000Z
""" Create a train set. """ import random import numpy as np from animal.arenas.utils import ( create_box_reasoning ) if __name__ == '__main__': import os import argparse parser = argparse.ArgumentParser() parser.add_argument( '-d', '--target-dir', help='path to arenas train directory') arguments = parser.parse_args() if not os.path.isdir(arguments.target_dir): os.mkdir(arguments.target_dir) skills = ["box_reasoning"] for skill in skills: if not os.path.isdir("{}/{}".format(arguments.target_dir, skill)): os.mkdir("{}/{}".format(arguments.target_dir, skill)) # box reasoning for i in range(1, 1000): reward_range_list = [[4, 5]] reward_range = random.choice(reward_range_list) create_box_reasoning( "{}/box_reasoning/".format(arguments.target_dir), 'c2_{}'.format(str(i).zfill(4)))
23.384615
79
0.640351
ace9fb1bba2fe2219d598b78d8cfa087f29117ae
9,439
py
Python
game/views/word_card_views.py
BlackwoodOne/Storytelling2.0
6a75045ced8711f52e568290b4b6b0d546434d7b
[ "MIT" ]
1
2018-07-20T20:17:47.000Z
2018-07-20T20:17:47.000Z
game/views/word_card_views.py
BlackwoodOne/Storytelling2.0
6a75045ced8711f52e568290b4b6b0d546434d7b
[ "MIT" ]
null
null
null
game/views/word_card_views.py
BlackwoodOne/Storytelling2.0
6a75045ced8711f52e568290b4b6b0d546434d7b
[ "MIT" ]
null
null
null
from django.views.generic.detail import DetailView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.views.generic.list import ListView from ..models import WordCard from ..forms import WordCardForm from django.urls import reverse_lazy from django.urls import reverse from django.http import Http404 class WordCardListView(ListView): model = WordCard template_name = "game/word_card_list.html" paginate_by = 20 context_object_name = "word_card_list" allow_empty = True page_kwarg = 'page' paginate_orphans = 0 def __init__(self, **kwargs): return super(WordCardListView, self).__init__(**kwargs) def dispatch(self, *args, **kwargs): return super(WordCardListView, self).dispatch(*args, **kwargs) def get(self, request, *args, **kwargs): return super(WordCardListView, self).get(request, *args, **kwargs) def get_queryset(self): return super(WordCardListView, self).get_queryset() def get_allow_empty(self): return super(WordCardListView, self).get_allow_empty() def get_context_data(self, *args, **kwargs): ret = super(WordCardListView, self).get_context_data(*args, **kwargs) return ret def get_paginate_by(self, queryset): return super(WordCardListView, self).get_paginate_by(queryset) def get_context_object_name(self, object_list): return super(WordCardListView, self).get_context_object_name(object_list) def paginate_queryset(self, queryset, page_size): return super(WordCardListView, self).paginate_queryset(queryset, page_size) def get_paginator(self, queryset, per_page, orphans=0, allow_empty_first_page=True): return super(WordCardListView, self).get_paginator(queryset, per_page, orphans=0, allow_empty_first_page=True) def render_to_response(self, context, **response_kwargs): return super(WordCardListView, self).render_to_response(context, **response_kwargs) def get_template_names(self): return super(WordCardListView, self).get_template_names() class WordCardDetailView(DetailView): model = WordCard template_name = "game/word_card_detail.html" context_object_name = "word_card" slug_field = 'slug' slug_url_kwarg = 'slug' pk_url_kwarg = 'pk' def __init__(self, **kwargs): return super(WordCardDetailView, self).__init__(**kwargs) def dispatch(self, *args, **kwargs): return super(WordCardDetailView, self).dispatch(*args, **kwargs) def get(self, request, *args, **kwargs): return super(WordCardDetailView, self).get(request, *args, **kwargs) def get_object(self, queryset=None): return super(WordCardDetailView, self).get_object(queryset) def get_queryset(self): return super(WordCardDetailView, self).get_queryset() def get_slug_field(self): return super(WordCardDetailView, self).get_slug_field() def get_context_data(self, **kwargs): ret = super(WordCardDetailView, self).get_context_data(**kwargs) return ret def get_context_object_name(self, obj): return super(WordCardDetailView, self).get_context_object_name(obj) def render_to_response(self, context, **response_kwargs): return super(WordCardDetailView, self).render_to_response(context, **response_kwargs) def get_template_names(self): return super(WordCardDetailView, self).get_template_names() class WordCardCreateView(CreateView): model = WordCard form_class = WordCardForm # fields = ['content', 'deckNumber', 'used', 'game', 'createdBy', 'onPlayerHand'] template_name = "game/word_card_create.html" success_url = reverse_lazy("word_card_list") def __init__(self, **kwargs): return super(WordCardCreateView, self).__init__(**kwargs) def dispatch(self, request, *args, **kwargs): return super(WordCardCreateView, self).dispatch(request, *args, **kwargs) def get(self, request, *args, **kwargs): return super(WordCardCreateView, self).get(request, *args, **kwargs) def post(self, request, *args, **kwargs): return super(WordCardCreateView, self).post(request, *args, **kwargs) def get_form_class(self): return super(WordCardCreateView, self).get_form_class() def get_form(self, form_class=None): return super(WordCardCreateView, self).get_form(form_class) def get_form_kwargs(self, **kwargs): return super(WordCardCreateView, self).get_form_kwargs(**kwargs) def get_initial(self): return super(WordCardCreateView, self).get_initial() def form_invalid(self, form): return super(WordCardCreateView, self).form_invalid(form) def form_valid(self, form): obj = form.save(commit=False) obj.save() return super(WordCardCreateView, self).form_valid(form) def get_context_data(self, **kwargs): ret = super(WordCardCreateView, self).get_context_data(**kwargs) return ret def render_to_response(self, context, **response_kwargs): return super(WordCardCreateView, self).render_to_response(context, **response_kwargs) def get_template_names(self): return super(WordCardCreateView, self).get_template_names() def get_success_url(self): return reverse("game:word_card_detail", args=(self.object.pk,)) class WordCardUpdateView(UpdateView): model = WordCard form_class = WordCardForm # fields = ['content', 'deckNumber', 'used', 'game', 'createdBy', 'onPlayerHand'] template_name = "game/word_card_update.html" initial = {} slug_field = 'slug' slug_url_kwarg = 'slug' pk_url_kwarg = 'pk' context_object_name = "word_card" def __init__(self, **kwargs): return super(WordCardUpdateView, self).__init__(**kwargs) def dispatch(self, *args, **kwargs): return super(WordCardUpdateView, self).dispatch(*args, **kwargs) def get(self, request, *args, **kwargs): return super(WordCardUpdateView, self).get(request, *args, **kwargs) def post(self, request, *args, **kwargs): return super(WordCardUpdateView, self).post(request, *args, **kwargs) def get_object(self, queryset=None): return super(WordCardUpdateView, self).get_object(queryset) def get_queryset(self): return super(WordCardUpdateView, self).get_queryset() def get_slug_field(self): return super(WordCardUpdateView, self).get_slug_field() def get_form_class(self): return super(WordCardUpdateView, self).get_form_class() def get_form(self, form_class=None): return super(WordCardUpdateView, self).get_form(form_class) def get_form_kwargs(self, **kwargs): return super(WordCardUpdateView, self).get_form_kwargs(**kwargs) def get_initial(self): return super(WordCardUpdateView, self).get_initial() def form_invalid(self, form): return super(WordCardUpdateView, self).form_invalid(form) def form_valid(self, form): obj = form.save(commit=False) obj.save() return super(WordCardUpdateView, self).form_valid(form) def get_context_data(self, **kwargs): ret = super(WordCardUpdateView, self).get_context_data(**kwargs) return ret def get_context_object_name(self, obj): return super(WordCardUpdateView, self).get_context_object_name(obj) def render_to_response(self, context, **response_kwargs): return super(WordCardUpdateView, self).render_to_response(context, **response_kwargs) def get_template_names(self): return super(WordCardUpdateView, self).get_template_names() def get_success_url(self): return reverse("game:word_card_detail", args=(self.object.pk,)) class WordCardDeleteView(DeleteView): model = WordCard template_name = "game/word_card_delete.html" slug_field = 'slug' slug_url_kwarg = 'slug' pk_url_kwarg = 'pk' context_object_name = "word_card" def __init__(self, **kwargs): return super(WordCardDeleteView, self).__init__(**kwargs) def dispatch(self, *args, **kwargs): return super(WordCardDeleteView, self).dispatch(*args, **kwargs) def get(self, request, *args, **kwargs): raise Http404 def post(self, request, *args, **kwargs): return super(WordCardDeleteView, self).post(request, *args, **kwargs) def delete(self, request, *args, **kwargs): return super(WordCardDeleteView, self).delete(request, *args, **kwargs) def get_object(self, queryset=None): return super(WordCardDeleteView, self).get_object(queryset) def get_queryset(self): return super(WordCardDeleteView, self).get_queryset() def get_slug_field(self): return super(WordCardDeleteView, self).get_slug_field() def get_context_data(self, **kwargs): ret = super(WordCardDeleteView, self).get_context_data(**kwargs) return ret def get_context_object_name(self, obj): return super(WordCardDeleteView, self).get_context_object_name(obj) def render_to_response(self, context, **response_kwargs): return super(WordCardDeleteView, self).render_to_response(context, **response_kwargs) def get_template_names(self): return super(WordCardDeleteView, self).get_template_names() def get_success_url(self): return reverse("game:word_card_list")
35.35206
118
0.706431
ace9fb26c2972984da30e93b2833fc426b9b107a
836
py
Python
insights/tests/parsers/test_bdi_read_ahead_kb.py
TZ3070/insights-core
13f4fc6bfcb89d76f0255c6259902360a298d619
[ "Apache-2.0" ]
null
null
null
insights/tests/parsers/test_bdi_read_ahead_kb.py
TZ3070/insights-core
13f4fc6bfcb89d76f0255c6259902360a298d619
[ "Apache-2.0" ]
null
null
null
insights/tests/parsers/test_bdi_read_ahead_kb.py
TZ3070/insights-core
13f4fc6bfcb89d76f0255c6259902360a298d619
[ "Apache-2.0" ]
null
null
null
import doctest import pytest from insights.parsers import bdi_read_ahead_kb, ParseException from insights.tests import context_wrap BDI_READ_AHEAD_KB = """ 128 """.strip() BDI_READ_AHEAD_KB_INVALID = """ invalid """.strip() def test_bdi_read_ahead_kb(): read_ahead_kb = bdi_read_ahead_kb.BDIReadAheadKB(context_wrap(BDI_READ_AHEAD_KB)) assert read_ahead_kb.read_ahead_kb == 128 def test_invalid_bdi_read_ahead_kb(): with pytest.raises(ParseException) as e: bdi_read_ahead_kb.BDIReadAheadKB(context_wrap(BDI_READ_AHEAD_KB_INVALID)) assert "Error: " in str(e) def test_bdi_read_ahead_kb_doc_examples(): env = { 'bdi_read_ahead_kb': bdi_read_ahead_kb.BDIReadAheadKB(context_wrap(BDI_READ_AHEAD_KB)), } failed, total = doctest.testmod(bdi_read_ahead_kb, globs=env) assert failed == 0
26.125
95
0.769139
ace9fb7caeec8c3509baf7b21559dcf1faac4415
808
py
Python
demo/test_demo.py
aldro61/devtools_tutorial
3a26c888c8cb9f7bd41d89130c6e33868586a3e5
[ "Unlicense" ]
1
2021-03-11T15:41:15.000Z
2021-03-11T15:41:15.000Z
demo/test_demo.py
aldro61/devtools_tutorial
3a26c888c8cb9f7bd41d89130c6e33868586a3e5
[ "Unlicense" ]
null
null
null
demo/test_demo.py
aldro61/devtools_tutorial
3a26c888c8cb9f7bd41d89130c6e33868586a3e5
[ "Unlicense" ]
1
2021-03-11T15:41:45.000Z
2021-03-11T15:41:45.000Z
import pytest import torch from demo import DummyNet def test_init() -> None: """ Test that the network can be initialized correctly """ # As long as this doesn't fail, the test will pass. # Note: This is a pedagogical example, we don't usually test this. DummyNet() def test_forward_input_validation() -> None: """ Test that input valiatin works in the forward pass """ m = DummyNet() with pytest.raises(ValueError): m(torch.ones(10,)) def test_forward_output() -> None: """ Test that the forward pass outputs values in [0, 1] """ m = DummyNet() for _ in range(100): inp = torch.rand(5, 10) * torch.randint(0, 1000, (1,)) out = m(inp) assert (out > 1).sum() == 0 assert (out < 0).sum() == 0
20.2
70
0.594059
ace9fb9f558d4ca1b65c625d4a52178b07c9bc10
3,598
py
Python
enaml/wx/wx_toolkit_object.py
pberkes/enaml
cbcbee929e3117dfe56c0b06dc2385acc832b0e8
[ "BSD-3-Clause-Clear" ]
11
2015-03-14T14:30:51.000Z
2022-03-15T13:01:44.000Z
enaml/wx/wx_toolkit_object.py
pberkes/enaml
cbcbee929e3117dfe56c0b06dc2385acc832b0e8
[ "BSD-3-Clause-Clear" ]
3
2015-01-31T11:12:56.000Z
2022-03-14T00:53:25.000Z
enaml/wx/wx_toolkit_object.py
pberkes/enaml
cbcbee929e3117dfe56c0b06dc2385acc832b0e8
[ "BSD-3-Clause-Clear" ]
4
2015-01-27T01:56:14.000Z
2021-02-23T07:21:20.000Z
#------------------------------------------------------------------------------ # Copyright (c) 2013, Nucleic Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #------------------------------------------------------------------------------ import wx from atom.api import Typed from enaml.widgets.toolkit_object import ProxyToolkitObject class WxToolkitObject(ProxyToolkitObject): """ A Wx implementation of an Enaml ProxyToolkitObject. """ #: A reference to the toolkit widget created by the proxy. widget = Typed(wx.Object) #-------------------------------------------------------------------------- # Initialization API #-------------------------------------------------------------------------- def create_widget(self): """ Create the toolkit widget for the proxy object. This method is called during the top-down pass, just before the 'init_widget()' method is called. This method should create the toolkit widget and assign it to the 'widget' attribute. """ self.widget = wx.Object() def init_widget(self): """ Initialize the state of the toolkit widget. This method is called during the top-down pass, just after the 'create_widget()' method is called. This method should init the state of the widget. The child widgets will not yet be created. """ pass def init_layout(self): """ Initialize the layout of the toolkit widget. This method is called during the bottom-up pass. This method should initialize the layout of the widget. The child widgets will be fully initialized and layed out when this is called. """ pass #-------------------------------------------------------------------------- # ProxyToolkitObject API #-------------------------------------------------------------------------- def activate_top_down(self): """ Activate the proxy tree for the top-down pass. """ self.create_widget() self.init_widget() def activate_bottom_up(self): """ Activate the proxy tree for the bottom-up pass. """ self.init_layout() def destroy(self): """ A reimplemented destructor. This destructor will drop the reference to the toolkit widget. """ if self.widget: try: self.widget.Destroy() except AttributeError: pass del self.widget super(WxToolkitObject, self).destroy() #-------------------------------------------------------------------------- # Public API #-------------------------------------------------------------------------- def parent_widget(self): """ Get the parent toolkit widget for this object. Returns ------- result : wxObject or None The toolkit widget declared on the declaration parent, or None if there is no such parent. """ parent = self.parent() if parent is not None: if parent.widget: return parent.widget def child_widgets(self): """ Get the child toolkit widgets for this object. Returns ------- result : iterable of wxObject The child widgets defined for this object. """ for child in self.children(): if child.widget: yield child.widget
31.286957
79
0.505559
ace9fbda72229450a5d2e77ba6a589233add04d6
106
py
Python
audit_history/settings.py
smileback-com/django-model-audit-history
0a127303d7bf4c998772c20f54611265f03f0d71
[ "MIT" ]
1
2019-01-23T11:47:33.000Z
2019-01-23T11:47:33.000Z
audit_history/settings.py
nexto/django-model-audit-history
0a127303d7bf4c998772c20f54611265f03f0d71
[ "MIT" ]
3
2019-01-25T11:11:17.000Z
2019-05-20T11:44:22.000Z
audit_history/settings.py
smileback-com/django-model-audit-history
0a127303d7bf4c998772c20f54611265f03f0d71
[ "MIT" ]
1
2019-01-24T14:17:26.000Z
2019-01-24T14:17:26.000Z
ADMIN_EVENT = 'CHANGE_VIA_ADMIN' DEFAULT_ACTOR = 'System' TIMESTAMP_FORMAT = '%Y-%m-%dT%H:%M:%S.%f+00:00'
26.5
47
0.698113
ace9fd459a90c0547773f1b369d08ac413ba9378
6,220
py
Python
glemmazon/train_analyzer.py
gustavoauma/glemmazon
2d67f78556f75141cadba99a65092c7d7b08cbdd
[ "MIT" ]
null
null
null
glemmazon/train_analyzer.py
gustavoauma/glemmazon
2d67f78556f75141cadba99a65092c7d7b08cbdd
[ "MIT" ]
2
2021-08-25T15:40:06.000Z
2022-02-10T00:13:49.000Z
glemmazon/train_analyzer.py
gustavoauma/glemmazon
2d67f78556f75141cadba99a65092c7d7b08cbdd
[ "MIT" ]
1
2020-10-28T16:06:02.000Z
2020-10-28T16:06:02.000Z
r"""Module for training a new model of the analyzer. Basic usage: python -m glemmazon.train_analyzer \ --conllu data/en_ewt-ud-train.conllu \ --model models/analyzer/en """ import tqdm from absl import app from absl import flags from sklearn.model_selection import train_test_split from tensorflow.keras.layers import ( Dense, Dropout, Input, LSTM, Bidirectional) from tensorflow.keras.models import Model from glemmazon import cleanup from glemmazon import constants as k from glemmazon import preprocess from glemmazon import utils from glemmazon.encoder import ( DenseTag, DictFeatureEncoder, DictLabelEncoder, LabelEncoder, SeqFeatureEncoder, SeqWordSuffix) from glemmazon.pipeline import Analyzer, LookupDictionary FLAGS = flags.FLAGS flags.DEFINE_string("conllu", None, "Path to a CoNLL-U file.") flags.DEFINE_string("model", None, "Path to store the Pickle file with the model.") flags.DEFINE_string("exceptions", None, "Path to a CSV with lemma exceptions [columns: " "'word', 'pos', 'lemma'].") flags.DEFINE_string("cleanup", "basic", "Name of the clean-up function to be used. Use " "'dummy' for no clean-up.") flags.DEFINE_integer("min_count", 3, "The minimum number of counts a lemma suffix need " "to have for it to be included for training.") flags.DEFINE_integer("max_features", 256, "The maximum number of characters to be " "considered in the vocabulary.") flags.DEFINE_boolean("no_losses", False, "If True, losses from training data will be added " "to the model's exception dictionary (not to the " ".csv file though).") flags.DEFINE_integer("embedding_size", 16, "Embedding size.") flags.DEFINE_integer("batch_size", 16, "Mini-batch size.") flags.DEFINE_integer("maxlen", 10, "The max length of the suffix to be extracted.") flags.DEFINE_integer("epochs", 25, "Epochs for training.") flags.mark_flag_as_required('model') flags.mark_flag_as_required('conllu') def _build_encoders(df): ch_list = {ch for word in df.word.apply(lambda x: list(x)) for ch in word} sfe = SeqFeatureEncoder( seq_name='word', seq_encoder=SeqWordSuffix(ch_list, suffix_length=6), dense_encoders=DictFeatureEncoder({'pos': DenseTag( df.pos.unique())})) label_encoders = { col: LabelEncoder(df[col].unique()) for col in df.columns if col not in (k.WORD_COL, k.LEMMA_COL) } dle = DictLabelEncoder(label_encoders) return sfe, dle def _build_model(input_shape, dle): inputs = Input(shape=input_shape) deep = Bidirectional(LSTM(32))(inputs) deep = Dropout(0.3)(deep) deep = Dense(64)(deep) outputs = [ Dense(dle.encoders[c].output_shape[0], activation='softmax', name=c)(deep) for c in dle.encoders ] return Model(inputs, outputs) def _add_losses_as_exceptions(l, df, logger): for i, row in tqdm.tqdm(df.iterrows(), initial=1): feats_dict = {'word': row[k.WORD_COL], 'pos': row[k.POS_COL]} y_pred_dict = l(word=row[k.WORD_COL], pos=row[k.POS_COL]).data all_attrs = {**feats_dict, **y_pred_dict} row_as_dict = row.to_dict() del row_as_dict[k.LEMMA_COL] if all_attrs != row_as_dict: diff = sorted(set(row_as_dict.items()) ^ set(all_attrs.items())) logger.info(f'{i}. Added exception: "{row[k.WORD_COL]}" -> ' f'"{row_as_dict}" [diff: "{diff}"]. ' f'Ratio: {len(l.exceptions) / i}.') l.exceptions.add_entry(**all_attrs) def main(_): logger = utils.get_logger(FLAGS.model) logger.info('Reading CoNLL-U sentences from "%s"...' % FLAGS.conllu) df = preprocess.conllu_to_df( FLAGS.conllu, getattr(cleanup, FLAGS.cleanup), min_count=FLAGS.min_count, lemmatizer_info=False) df.drop_duplicates(inplace=True) logger.info('Data sample:\n %s' % df.head()) logger.info('Splitting between training, test and val...') train, test = train_test_split(df, test_size=0.2) logger.info('# Training examples: %d' % len(train)) logger.info('# Test examples: %d' % len(test)) logger.info('Preparing training data and feature/label encoders...') sfe, dle = _build_encoders(df) logger.info('Preparing batch generators...') batch_generator = utils.BatchGenerator(df, sfe, dle) logger.info('Building the model...') model = _build_model(sfe.output_shape, dle) model.summary(print_fn=logger.info) logger.info('Running training...') model.compile('adam', 'categorical_crossentropy', metrics=['accuracy']) history = model.fit_generator(batch_generator, epochs=FLAGS.epochs, verbose=2) for i in range(FLAGS.epochs): epoch_metrics = {k: v[i] for k, v in history.history.items()} logger.debug('Epoch %d: %s' % (i + 1, sorted( epoch_metrics.items()))) if FLAGS.exceptions: logger.info('Loading exceptions...') exceptions = LookupDictionary.from_csv(FLAGS.exceptions) else: exceptions = LookupDictionary(columns=list(sfe.scope | dle.scope)) logger.info('Persisting the model and parameters...') analyzer = Analyzer(model=model, feature_enc=sfe, label_enc=dle, exceptions=exceptions) analyzer.save(FLAGS.model) if FLAGS.no_losses: logger.info( 'Adding losses to the dictionary with exceptions...') n_start = len(analyzer.exceptions) # noinspection PyUnboundLocalVariable _add_losses_as_exceptions(analyzer, df, logger) logger.info('# Exceptions added: %d' % ( len(analyzer.exceptions) - n_start)) analyzer.save(FLAGS.model) logger.info('Model successfully saved in folder: %s.' % FLAGS.model) if __name__ == '__main__': app.run(main)
35.953757
72
0.631029
ace9fd530ed1ba5d2dc00e5b09c8668c2062d9bb
216
py
Python
fcdjango/fc_community/fcuser/admin.py
djangojeng-e/djangoproejcts
1efc3bc04a4a1bef039c906584cfecf0231c177f
[ "MIT" ]
null
null
null
fcdjango/fc_community/fcuser/admin.py
djangojeng-e/djangoproejcts
1efc3bc04a4a1bef039c906584cfecf0231c177f
[ "MIT" ]
null
null
null
fcdjango/fc_community/fcuser/admin.py
djangojeng-e/djangoproejcts
1efc3bc04a4a1bef039c906584cfecf0231c177f
[ "MIT" ]
null
null
null
from django.contrib import admin from .models import Fcuser # Register your models here. class FcuserAdmin(admin.ModelAdmin): list_display = ("username", "password") admin.site.register(Fcuser,FcuserAdmin)
16.615385
43
0.763889
ace9fd9d0a1e777f1e3265b5010ac95a32848abe
567
py
Python
pyews/utils/exceptions.py
swimlane/pyews
61cc60226b347a881ce653acc7af276c26b37de9
[ "MIT" ]
26
2019-05-04T03:02:53.000Z
2022-02-04T14:56:30.000Z
pyews/utils/exceptions.py
swimlane/pyews
61cc60226b347a881ce653acc7af276c26b37de9
[ "MIT" ]
14
2019-07-30T15:32:27.000Z
2022-02-10T20:49:44.000Z
pyews/utils/exceptions.py
swimlane/pyews
61cc60226b347a881ce653acc7af276c26b37de9
[ "MIT" ]
12
2019-10-18T14:14:09.000Z
2021-11-15T09:29:30.000Z
class UknownValueError(ValueError): """Raised when the provided value is unkown or is not in a specified list or dictionary map """ def __init__(self, provided_value=None, known_values=None): if provided_value and known_values: if isinstance(known_values, list): super().__init__("The provided value {} is unknown. Please provide one of the following values: '{}'".format( provided_value, ','.join([x for x in known_values]) )) else: pass
43.615385
125
0.592593
ace9fdacd29a91a0fd0f9598c26de71c639b329b
5,725
py
Python
root/python/PythonAwesomeScript/EmailNotify/Notify.py
chyidl/chyidlTutorial
a033e0a57abf84fdbb61e57736822f9126db6ff7
[ "MIT" ]
5
2018-10-17T05:57:39.000Z
2021-07-05T15:38:24.000Z
root/python/PythonAwesomeScript/EmailNotify/Notify.py
chyidl/chyidlTutorial
a033e0a57abf84fdbb61e57736822f9126db6ff7
[ "MIT" ]
2
2021-04-14T00:48:43.000Z
2021-04-14T02:20:50.000Z
root/python/PythonAwesomeScript/EmailNotify/Notify.py
chyidl/chyidlTutorial
a033e0a57abf84fdbb61e57736822f9126db6ff7
[ "MIT" ]
3
2019-03-02T14:36:19.000Z
2022-03-18T10:12:09.000Z
#!/usr/bin/env python3 # -*- coding:utf-8 -*- import os import time import socket import datetime from chyiemail import sendMessage import mysql.connector # LPlus Test-Dev 01 MySQL lplus_test_dev_01_conf = { 'host': '', 'port': 3306, 'user': '', 'password': '', 'charset': 'utf8' } # Change to your own account information fromAddr = '@qq.com' fromPasswd = '' Names = [''] Emails = ['@gmail.com'] Subject = "" message_Template = """<!DOCTYPE html> <html> <body> Dear ${PERSON_NAME}, [CHYIDL.COM.HOOK] Yours Truly </body> </html> """ def get_device_ip_address(): try: if os.name == "nt": # On Windows result = "Running on Windows" hostname = socket.gethostname() result += "\nHostname: " + hostname host = socket.gethostbyname(hostname) result += "\nHost-IP-Address: " + host return result elif os.name == "posix": # gw = os.popen("ip -4 route show default").read().split() # s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # s.connect((gw[2], 0)) # ipaddr = s.getsockname()[0] # gateway = gw[2] # host = socket.gethostname() lsb_release = os.popen("lsb_release -a").read() # result = lsb_release + "\nIP:\t\t" + ipaddr + "\nGateway:\t\t" + # gateway + "\nHost:\t\t" + host ifconfig = os.popen("ifconfig").read() result = lsb_release + ifconfig return result else: result = os.name + " not supported yet." return result except Exception as e: return "Could not detect ip address, {}".format(e) def get_mysql_storage_info(conf, totalStorage): """ 获取数据库占用空间大小 :param conf: MySQL 连接信息 :param totalStorage: 数据库总存储空间 :return: status, rst: ture|false, string """ try: status = False rst_str = """Host: {}\n""".format(conf['host']) check_storage_sql = 'SELECT TABLE_SCHEMA AS "Database Name", ' \ 'ROUND(SUM(data_length + index_length)/1024/1024/1024, 2) AS "Size in (GB)" ' \ 'FROM information_schema.TABLES GROUP BY TABLE_SCHEMA ' \ 'UNION ' \ 'SELECT "Total Databases", SUM(`Size in (GB)`) AS "Size in (MB)" ' \ 'FROM (SELECT TABLE_SCHEMA AS "Database Name", ' \ 'ROUND(SUM(data_length + index_length)/1024/1024/1024, 2) AS "Size in (GB)" ' \ 'FROM information_schema.TABLES GROUP BY TABLE_SCHEMA) AS tmp_chyi GROUP BY "Size in (MB)";' cnx = mysql.connector.connect(**conf) cursor = cnx.cursor() cursor.execute(check_storage_sql) percentage = None; count = 0; print_str = """+--------------------+--------------+ | Database Name | Size in (GB) | +--------------------+--------------+""" print(print_str) rst_str += '<table style="width:50%"><tr><th>{}</th><th>{}</th></tr>\n'.format("database Name", "Size in (GB)") for (database, size) in cursor: if database == "Total Databases": percentage = size/totalStorage * 100 if percentage > 90: status = True count += 1 print_str = """|{0}|{1}|""".format(database+' '*(20-len(database)), ((14-len(str(size)))*' '+str(size))) print(print_str) rst_str += '<tr><td>{}</td><td>{}</td></tr>\n'.format(database, size) print_str = """+--------------------+--------------+""" print(print_str) rst_str += '</table>' if percentage: print_str = "{} rows in result, current percentage {} %".format(count+1, round(percentage, 2)) print(print_str) rst_str += print_str + "\n" return status, rst_str except mysql.connector.Error as err: print("mysql.connector.Error {}".format(err)) except Exception as e: print(e) finally: cursor.close() cnx.close() def timeit(func): def timed(*args, **kwargs): ts = time.time() result = func(*args, **kwargs) te = time.time() print('[ %r ] %r (%r, %r) %2.2f sec' % ( datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), func.__qualname__, args, kwargs, te-ts)) return result return timed @timeit def run(): status, rst_str = get_mysql_storage_info(lplus_test_dev_01_conf, 150) if status: template = message_Template.replace('[CHYIDL.COM.HOOK]', rst_str) sendMessage(fromAddr, fromPasswd, Names, Emails, Subject, template) print("[{}] Thanks my boss: -)".format(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))) if __name__ == '__main__': run() """ +--------------------+--------------+ | Database Name | Size in (GB) | +--------------------+--------------+ |chyi_test | 0.00| |demo | 0.06| |hq | 19.51| |information_schema | 0.00| |jyck | 0.61| |mysql | 0.01| |performance_schema | 0.00| |quant_new | 67.59| |recharge | 0.00| |sys | 0.00| |test1 | 0.23| |yongsheng_test | 0.00| |zonwer_test | 0.00| |Total Databases | 88.01| +--------------------+--------------+ 15 rows in result, current percentage 58.67 % [2019-06-12 16:39:23] Thanks my boss: -) [ '2019-06-12 16:39:23' ] 'run' ((), {}) 1.11 sec """
33.676471
120
0.50131
ace9fedea139c0e441657c02da55ee288ae94faa
220
py
Python
messages/__init__.py
notna24/discord-math-bot
22a43102a02864bd1e277493825baa444f99ef7c
[ "MIT" ]
1
2020-10-13T12:29:24.000Z
2020-10-13T12:29:24.000Z
messages/__init__.py
hello512/discord-math-bot
68bab917e7cdf150ff544dc514c8aa4c08bb7518
[ "MIT" ]
null
null
null
messages/__init__.py
hello512/discord-math-bot
68bab917e7cdf150ff544dc514c8aa4c08bb7518
[ "MIT" ]
null
null
null
from .embeds import MATHBOTINFOEMBED from .embeds import GENERALINFOEMBED from .embeds import make_result_embed from .text_messages import MATHBOT_ERROR_MESSAGE from .text_messages import COMMAND_NOT_AVAILABLE_MESSAGE
27.5
56
0.877273
ace9ff82062200258c076ad8cbc552d77ae1b97d
631
py
Python
examples/create_file_with_hashes.py
ben12385/client-python
e0636074046fa9921c8bb8535f28993c279e420c
[ "Apache-2.0" ]
null
null
null
examples/create_file_with_hashes.py
ben12385/client-python
e0636074046fa9921c8bb8535f28993c279e420c
[ "Apache-2.0" ]
null
null
null
examples/create_file_with_hashes.py
ben12385/client-python
e0636074046fa9921c8bb8535f28993c279e420c
[ "Apache-2.0" ]
null
null
null
# coding: utf-8 from pycti import OpenCTIApiClient # Variables api_url = "https://demo.opencti.io" api_token = "2b4f29e3-5ea8-4890-8cf5-a76f61f1e2b2" # OpenCTI initialization opencti_api_client = OpenCTIApiClient(api_url, api_token) # Create observable observable = opencti_api_client.stix_cyber_observable.create( observableData={ "type": "file", "hashes": { "md5": "16b3f663d0f0371a4706642c6ac04e42", "sha1": "3a1f908941311fc357051b5c35fd2a4e0c834e37", "sha256": "bcc70a49fab005b4cdbe0cbd87863ec622c6b2c656987d201adbb0e05ec03e56", }, } ) print(observable)
25.24
89
0.713154
acea00261c491e1190c9c1ce628eca8dada7de47
5,781
py
Python
earlier-2020/Zother algorithm/ant.py
transcendentsky/py_tutorials
fed8e6c8d79f854a1cebcfd5c37297a163846208
[ "Apache-2.0" ]
1
2018-06-18T12:09:33.000Z
2018-06-18T12:09:33.000Z
earlier-2020/Zother algorithm/ant.py
transcendentsky/py_tutorials
fed8e6c8d79f854a1cebcfd5c37297a163846208
[ "Apache-2.0" ]
null
null
null
earlier-2020/Zother algorithm/ant.py
transcendentsky/py_tutorials
fed8e6c8d79f854a1cebcfd5c37297a163846208
[ "Apache-2.0" ]
1
2018-06-18T12:13:21.000Z
2018-06-18T12:13:21.000Z
#coding=utf-8 import numpy as np import matplotlib.pyplot as plt # %pylab # coordinates = np.array([[565.0,575.0],[25.0,185.0],[345.0,750.0],[945.0,685.0],[845.0,655.0], # [880.0,660.0],[25.0,230.0],[525.0,1000.0],[580.0,1175.0],[650.0,1130.0], # [1605.0,620.0],[1220.0,580.0],[1465.0,200.0],[1530.0, 5.0],[845.0,680.0], # [725.0,370.0],[145.0,665.0],[415.0,635.0],[510.0,875.0],[560.0,365.0], # [300.0,465.0],[520.0,585.0],[480.0,415.0],[835.0,625.0],[975.0,580.0], # [1215.0,245.0],[1320.0,315.0],[1250.0,400.0],[660.0,180.0],[410.0,250.0], # [420.0,555.0],[575.0,665.0],[1150.0,1160.0],[700.0,580.0],[685.0,595.0], # [685.0,610.0],[770.0,610.0],[795.0,645.0],[720.0,635.0],[760.0,650.0], # [475.0,960.0],[95.0,260.0],[875.0,920.0],[700.0,500.0],[555.0,815.0], # [830.0,485.0],[1170.0, 65.0],[830.0,610.0],[605.0,625.0],[595.0,360.0], # [1340.0,725.0],[1740.0,245.0]]) cors = np.zeros((48,2)) with open('att48.tsp') as f: for _ in range(6): line = f.readline() for i in range(48): txt = f.readline().strip('\n').split(' ') cors[i] = np.array(txt)[1:] coordinates = cors def getdistmat(coordinates): num = coordinates.shape[0] distmat = np.zeros((len(coordinates),len(coordinates))) for i in range(num): for j in range(i,num): distmat[i][j] = distmat[j][i]=np.linalg.norm(coordinates[i]-coordinates[j]) return distmat distmat = getdistmat(coordinates) numant = 40 #蚂蚁个数 numcity = coordinates.shape[0] #城市个数 alpha = 1 #信息素重要程度因子 beta = 5 #启发函数重要程度因子 rho = 0.1 #信息素的挥发速度 Q = 1 iter = 0 itermax = 250 etatable = 1.0/(distmat+np.diag([1e10]*numcity)) #启发函数矩阵,表示蚂蚁从城市i转移到矩阵j的期望程度 pheromonetable = np.ones((numcity,numcity)) # 信息素矩阵 pathtable = np.zeros((numant,numcity)).astype(int) #路径记录表 distmat = getdistmat(coordinates) #城市的距离矩阵 lengthaver = np.zeros(itermax) #各代路径的平均长度 lengthbest = np.zeros(itermax) #各代及其之前遇到的最佳路径长度 pathbest = np.zeros((itermax,numcity)) # 各代及其之前遇到的最佳路径长度 while iter < itermax: # 随机产生各个蚂蚁的起点城市 if numant <= numcity:#城市数比蚂蚁数多 pathtable[:,0] = np.random.permutation(range(0,numcity))[:numant] else: #蚂蚁数比城市数多,需要补足 pathtable[:numcity,0] = np.random.permutation(range(0,numcity))[:] pathtable[numcity:,0] = np.random.permutation(range(0,numcity))[:numant-numcity] length = np.zeros(numant) #计算各个蚂蚁的路径距离 for i in range(numant): visiting = pathtable[i,0] # 当前所在的城市 #visited = set() #已访问过的城市,防止重复 #visited.add(visiting) #增加元素 unvisited = set(range(numcity))#未访问的城市 unvisited.remove(visiting) #删除元素 for j in range(1,numcity):#循环numcity-1次,访问剩余的numcity-1个城市 #每次用轮盘法选择下一个要访问的城市 listunvisited = list(unvisited) probtrans = np.zeros(len(listunvisited)) for k in range(len(listunvisited)): probtrans[k] = np.power(pheromonetable[visiting][listunvisited[k]],alpha)\ *np.power(etatable[visiting][listunvisited[k]],alpha) cumsumprobtrans = (probtrans/sum(probtrans)).cumsum() cumsumprobtrans -= np.random.rand() # k = listunvisited[find(cumsumprobtrans>0)[0]] #下一个要访问的城市 k = listunvisited[np.where(cumsumprobtrans>0)[0][0]] pathtable[i,j] = k unvisited.remove(k) #visited.add(k) length[i] += distmat[visiting][k] visiting = k length[i] += distmat[visiting][pathtable[i,0]] #蚂蚁的路径距离包括最后一个城市和第一个城市的距离 #print length # 包含所有蚂蚁的一个迭代结束后,统计本次迭代的若干统计参数 lengthaver[iter] = length.mean() if iter == 0: lengthbest[iter] = length.min() pathbest[iter] = pathtable[length.argmin()].copy() else: if length.min() > lengthbest[iter-1]: lengthbest[iter] = lengthbest[iter-1] pathbest[iter] = pathbest[iter-1].copy() else: lengthbest[iter] = length.min() pathbest[iter] = pathtable[length.argmin()].copy() # 更新信息素 changepheromonetable = np.zeros((numcity,numcity)) for i in range(numant): for j in range(numcity-1): changepheromonetable[pathtable[i,j]][pathtable[i,j+1]] += Q/distmat[pathtable[i,j]][pathtable[i,j+1]] changepheromonetable[pathtable[i,j+1]][pathtable[i,0]] += Q/distmat[pathtable[i,j+1]][pathtable[i,0]] pheromonetable = (1-rho)*pheromonetable + changepheromonetable iter += 1 #迭代次数指示器+1 #观察程序执行进度,该功能是非必须的 if (iter-1)%20==0: print iter-1 # 做出平均路径长度和最优路径长度 fig,axes = plt.subplots(nrows=2,ncols=1,figsize=(12,10)) axes[0].plot(lengthaver,'k',marker = u'') axes[0].set_title('Average Length') axes[0].set_xlabel(u'iteration') axes[1].plot(lengthbest,'k',marker = u'') axes[1].set_title('Best Length') axes[1].set_xlabel(u'iteration') fig.savefig('Average_Best.png',dpi=500,bbox_inches='tight') plt.close() #作出找到的最优路径图 bestpath = pathbest[-1] plt.plot(coordinates[:,0],coordinates[:,1],'r.',marker=u'$\cdot$') plt.xlim([0,10000]) plt.ylim([0,10000]) # bestpath = map(lambda x: int(x), bestpath) for i in range(numcity-1):# m,n = bestpath[i],bestpath[i+1] m,n = int(m), int(n) print m,n plt.plot([coordinates[m][0],coordinates[n][0]],[coordinates[m][1],coordinates[n][1]],'k') plt.plot([coordinates[bestpath[0]][0],coordinates[n][0]],[coordinates[bestpath[0]][1],coordinates[n][1]],'b') ax=plt.gca() ax.set_title("Best Path") ax.set_xlabel('X axis') ax.set_ylabel('Y_axis') plt.savefig('Best Path.png',dpi=500,bbox_inches='tight') plt.close()
31.590164
113
0.599377
acea003644e27fe6b1f193612c325e2d5a46a2d4
2,181
py
Python
backend/trr_31540/urls.py
crowdbotics-apps/trr-31540
38919ac10153bf370d2fc52130c6eb2c1941edd9
[ "FTL", "AML", "RSA-MD" ]
null
null
null
backend/trr_31540/urls.py
crowdbotics-apps/trr-31540
38919ac10153bf370d2fc52130c6eb2c1941edd9
[ "FTL", "AML", "RSA-MD" ]
null
null
null
backend/trr_31540/urls.py
crowdbotics-apps/trr-31540
38919ac10153bf370d2fc52130c6eb2c1941edd9
[ "FTL", "AML", "RSA-MD" ]
null
null
null
"""trr_31540 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include, re_path from django.views.generic.base import TemplateView from allauth.account.views import confirm_email from rest_framework import permissions from drf_yasg.views import get_schema_view from drf_yasg import openapi urlpatterns = [ path("", include("home.urls")), path("accounts/", include("allauth.urls")), path("modules/", include("modules.urls")), path("api/v1/", include("home.api.v1.urls")), path("admin/", admin.site.urls), path("users/", include("users.urls", namespace="users")), path("rest-auth/", include("rest_auth.urls")), # Override email confirm to use allauth's HTML view instead of rest_auth's API view path("rest-auth/registration/account-confirm-email/<str:key>/", confirm_email), path("rest-auth/registration/", include("rest_auth.registration.urls")), ] admin.site.site_header = "trr" admin.site.site_title = "trr Admin Portal" admin.site.index_title = "trr Admin" # swagger api_info = openapi.Info( title="trr API", default_version="v1", description="API documentation for trr App", ) schema_view = get_schema_view( api_info, public=True, permission_classes=(permissions.IsAuthenticated,), ) urlpatterns += [ path("api-docs/", schema_view.with_ui("swagger", cache_timeout=0), name="api_docs") ] urlpatterns += [path("", TemplateView.as_view(template_name='index.html'))] urlpatterns += [re_path(r"^(?:.*)/?$", TemplateView.as_view(template_name='index.html'))]
34.619048
87
0.708391
acea0220fd97f5333a3cb5443d417e98128fa5cd
3,141
py
Python
google/cloud/automl_v1/types/translation.py
genquan9/python-automl
7b9d62248c7d69bc9e6a00f2caf4d7a5fa6eabec
[ "Apache-2.0" ]
null
null
null
google/cloud/automl_v1/types/translation.py
genquan9/python-automl
7b9d62248c7d69bc9e6a00f2caf4d7a5fa6eabec
[ "Apache-2.0" ]
1
2021-02-23T12:40:11.000Z
2021-02-23T12:40:11.000Z
google/cloud/automl_v1/types/translation.py
isabella232/python-automl
dbf1bf1bcc7575cd5ab85921311e18ecfed27dc7
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import proto # type: ignore from google.cloud.automl_v1.types import data_items __protobuf__ = proto.module( package="google.cloud.automl.v1", manifest={ "TranslationDatasetMetadata", "TranslationEvaluationMetrics", "TranslationModelMetadata", "TranslationAnnotation", }, ) class TranslationDatasetMetadata(proto.Message): r"""Dataset metadata that is specific to translation. Attributes: source_language_code (str): Required. The BCP-47 language code of the source language. target_language_code (str): Required. The BCP-47 language code of the target language. """ source_language_code = proto.Field(proto.STRING, number=1) target_language_code = proto.Field(proto.STRING, number=2) class TranslationEvaluationMetrics(proto.Message): r"""Evaluation metrics for the dataset. Attributes: bleu_score (float): Output only. BLEU score. base_bleu_score (float): Output only. BLEU score for base model. """ bleu_score = proto.Field(proto.DOUBLE, number=1) base_bleu_score = proto.Field(proto.DOUBLE, number=2) class TranslationModelMetadata(proto.Message): r"""Model metadata that is specific to translation. Attributes: base_model (str): The resource name of the model to use as a baseline to train the custom model. If unset, we use the default base model provided by Google Translate. Format: ``projects/{project_id}/locations/{location_id}/models/{model_id}`` source_language_code (str): Output only. Inferred from the dataset. The source language (The BCP-47 language code) that is used for training. target_language_code (str): Output only. The target language (The BCP-47 language code) that is used for training. """ base_model = proto.Field(proto.STRING, number=1) source_language_code = proto.Field(proto.STRING, number=2) target_language_code = proto.Field(proto.STRING, number=3) class TranslationAnnotation(proto.Message): r"""Annotation details specific to translation. Attributes: translated_content (~.data_items.TextSnippet): Output only . The translated content. """ translated_content = proto.Field( proto.MESSAGE, number=1, message=data_items.TextSnippet, ) __all__ = tuple(sorted(__protobuf__.manifest))
29.632075
79
0.681948
acea023001bfcf800a6db6f8db513de192816da0
4,367
py
Python
offload/__init__.py
thejoltjoker/camera-offload
ec7e84eb6e22e2b420b8d01bcd0049831ed42af4
[ "MIT" ]
null
null
null
offload/__init__.py
thejoltjoker/camera-offload
ec7e84eb6e22e2b420b8d01bcd0049831ed42af4
[ "MIT" ]
null
null
null
offload/__init__.py
thejoltjoker/camera-offload
ec7e84eb6e22e2b420b8d01bcd0049831ed42af4
[ "MIT" ]
null
null
null
import sys import os import shutil from pathlib import Path print('') print(os.getcwd()) print('') if sys.platform == 'darwin': APP_DATA_PATH = Path().home() / 'Library/Application Support/Offload' elif sys.platform == 'win64': APP_DATA_PATH = Path().home() / 'AppData\Local\Offload' else: APP_DATA_PATH = Path(__file__).parent REPORTS_PATH = APP_DATA_PATH / 'reports' LOGS_PATH = APP_DATA_PATH / 'logs' VERSION = '0.1.2b0' EXCLUDE_FILES = ["MEDIAPRO.XML", "Icon", "STATUS.BIN", "SONYCARD.IND", "AVIN0001.INP", "AVIN0001.BNP", "MOVIEOBJ.BDM", "PRV00001.BIN", "INDEX.BDM", "fseventsd-uuid", ".dropbox.device", "AVIN0001.INT", "mdb.bk", "mdb.db", "Get_started_with_GoPro.url", ".Spotlight-V100", "VolumeConfiguration.plist", "psid.db", "indexState", "0.indexHead", "0.indexGroups", "live.0.indexPostings", "live.0.indexIds", "live.0.indexBigDates", "live.0.indexGroups", "live.0.indexPositions", "live.0.indexDirectory", "live.0.indexCompactDirectory", "live.0.indexArrays", "live.0.shadowIndexHead", "live.0.directoryStoreFile", "live.0.directoryStoreFile.shadow", "store.db", ".store.db", "reverseDirectoryStore", "tmp.spotlight.state", "shutdown_time", "reverseDirectoryStore.shadow", "0.shadowIndexHead", "store.updates", "permStore", "live.1.indexHead", "live.1.indexIds", "0.shadowIndexGroups", "live.1.indexUpdates", "live.2.indexHead", "live.2.indexIds", "live.2.indexBigDates", "live.2.indexGroups", "live.0.shadowIndexGroups", "reverseStore.updates", "live.1.indexBigDates", "tmp.spotlight.loc", "live.1.indexGroups", "live.1.indexPostings", "live.1.indexTermIds", "live.1.indexDirectory", "live.1.indexCompactDirectory", "live.1.indexArrays", "live.2.indexPostings", "live.1.directoryStoreFile", "live.1.shadowIndexHead", "live.1.shadowIndexTermIds", "live.1.shadowIndexArrays", "live.1.shadowIndexCompactDirectory", "live.1.shadowIndexDirectory", "live.1.directoryStoreFile.shadow", "live.1.shadowIndexGroups", "live.2.indexTermIds", "live.2.indexPositions", "live.2.indexPositionTable", "live.2.indexDirectory", "live.2.indexCompactDirectory", "live.2.indexArrays", "live.2.indexUpdates", "live.2.directoryStoreFile", "live.2.shadowIndexHead", "live.2.shadowIndexTermIds", "live.2.shadowIndexPositionTable", "live.2.shadowIndexArrays", "live.2.shadowIndexCompactDirectory", "live.2.shadowIndexDirectory", "live.2.directoryStoreFile.shadow", "live.2.shadowIndexGroups", "live.0.indexHead", "journal.412", "retire.411", ".DS_Store", "fseventsd-uuid.", ".dropbox.device", "Icon?", "Icon\r.", "Icon\r", "store_generation.", "store_generation.\r", ".Spotlight-V100"] _script_data = Path(os.getcwd()) / 'data' _script_data.mkdir(parents=True, exist_ok=True) shutil.copytree(_script_data, APP_DATA_PATH / 'data', dirs_exist_ok=True)
36.697479
73
0.467827