From 1643829b2507ea1f2d00c3c05b8428d2685fdd54 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=9D=80=EC=86=94?= Date: Thu, 22 May 2025 15:16:22 +0900 Subject: [PATCH 001/297] ADD: Github API Intergration --- requirements.txt | 3 +- src/autofic_core/cli.py | 21 +++++++++++++- src/github_handler.py | 64 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 86 insertions(+), 2 deletions(-) create mode 100644 src/github_handler.py diff --git a/requirements.txt b/requirements.txt index 529473d..0e8a89c 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,5 @@ click pytest requests -python-dotenv \ No newline at end of file +python-dotenv +PyGithub \ No newline at end of file diff --git a/src/autofic_core/cli.py b/src/autofic_core/cli.py index 0d2aab0..40ea526 100644 --- a/src/autofic_core/cli.py +++ b/src/autofic_core/cli.py @@ -1,9 +1,28 @@ import click +import argparse +from autofic_core.github_handler import get_repo_files @click.command() @click.option('--repo', help='GitHub repository URL') -def main(repo): +@click.option('--silent', is_flag=True, help="결과 출력 없이 조용히 실행") +def main(repo, silent): click.echo(f"Analyzing repo: {repo}") + parser = argparse.ArgumentParser(description="AutoFiC CLI") + parser.add_argument("--repo", type=str, required=True, help="GitHub 저장소 URL 입력") + parser.add_argument("--silent", action="store_true", help="결과 출력 없이 추출만 수행") # ✅ 이 줄 추가! + + args = parser.parse_args() + + files = get_repo_files(args.repo, silent=args.silent) + + # 파일 목록 출력 예시 + if not files: + print("JS 파일을 찾지 못했습니다. 저장소 구조 또는 필터 조건을 확인하세요.") + elif not args.silent: + print(f"JS 파일 {len(files)}개를 찾았습니다:") + for file in files: + print(f"{file['path']} -> {file['download_url']}") + if __name__ == '__main__': main() \ No newline at end of file diff --git a/src/github_handler.py b/src/github_handler.py new file mode 100644 index 0000000..58a1d35 --- /dev/null +++ b/src/github_handler.py @@ -0,0 +1,64 @@ +# autofic_core/github_handler.py + +import os +from github import Github +from dotenv import load_dotenv +from urllib.parse import urlparse + +load_dotenv() # .env 파일에서 환경 변수 로드 + +def parse_repo_url(repo_url): + """URL에서 사용자명/저장소명을 추출""" + path = urlparse(repo_url).path.strip("/") + owner, repo_name = path.split("/")[:2] + if repo_name.endswith(".git"): + repo_name = repo_name[:-4] + return owner, repo_name + +def get_repo_files(repo_url, file_extensions=(".js", ".mjs", ".jsx", ".ts"), silent=False): + token = os.getenv("GITHUB_TOKEN") + if not token: + raise ValueError("GITHUB_TOKEN이 .env에 없습니다.") + + print("GitHub API 인증 시도 중") + + try: + g = Github(token) + user = g.get_user() + print(f"인증 성공! 연결된 계정: {user.login}") + except Exception as e: + print("GitHub 인증 실패:", e) + return [] + + try: + owner, repo_name = parse_repo_url(repo_url) + repo = g.get_repo(f"{owner}/{repo_name}") + print(f"저장소: {repo.full_name} (기본 브랜치: {repo.default_branch})") + except Exception as e: + print("저장소 불러오기 실패:", e) + return [] + + target_exts = (".js", ".mjs", ".jsx", ".ts") + + js_files = [] + contents = repo.get_contents("") + + print("탐색 중입니다.") + + while contents: + file_content = contents.pop(0) + if not silent: + print(f"탐색 중: {file_content.path} ({file_content.type})") + if file_content.type == "dir": + contents.extend(repo.get_contents(file_content.path)) + elif file_content.name.endswith(file_extensions) and file_content.download_url: + js_files.append({ + "path": file_content.path, + "download_url": file_content.download_url + }) + if not silent: + print(f"발견: {file_content.path}") + + print(f"JS 파일 {len(js_files)}개를 찾았습니다:") + + return js_files From a9a6bc637f53c8938acdfe37177167b84ffb1eda Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=9D=80=EC=86=94?= Date: Thu, 22 May 2025 15:29:25 +0900 Subject: [PATCH 002/297] Fix: File location --- .DS_Store | Bin 0 -> 6148 bytes requirements.txt | 30 +++++++++++++++++++---- src/.DS_Store | Bin 0 -> 6148 bytes src/autofic_core/.DS_Store | Bin 0 -> 6148 bytes src/{ => autofic_core}/github_handler.py | 0 5 files changed, 25 insertions(+), 5 deletions(-) create mode 100644 .DS_Store create mode 100644 src/.DS_Store create mode 100644 src/autofic_core/.DS_Store rename src/{ => autofic_core}/github_handler.py (100%) diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..76be5a863c0076b67f812c14860f83e59d2e4526 GIT binary patch literal 6148 zcmeHKO>fgM7=GP$G-V9+0MafhN)qT4j4 zbNGZLeWZW}lu`{YX+)9!_Aj~LbKDA@qL(A;&@*5SjNv*%+{-bl=qI4hG^J4GMkvMT zEm3`*QJUj_&GCzfoX{W__3P>=f1Zr}NWJ|Je;kELTCe{Ug<@&vM%gJlyUtthgPeP5 zKbYZa5r~NPvCW;Ua1BASJ6~;q3Z_8;sOcdAC4Nk?W z^s4)dMdPq>;683Pmj~|Ruu(_;QFFPhICt+qcyikN6pdo}1#b=$*l(5X8N2`Sp}>D|4#wlA6z(N%iv0*+B%S^D*&*BYGugt zPXlvYgDrzAjc9=hO$BPIFjowr>8N*2T+84}qo$KEmk(ij7UqT`RPT7ctHMdNG}_cE zU=>(bps0&gKL5LazyGh3Y{@EM6}VOkh*HPvv@s-ewr&iL&srD$4$j7LD~*bR#2m*e g!$i2wiq literal 0 HcmV?d00001 diff --git a/requirements.txt b/requirements.txt index 0e8a89c..f3bb660 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,5 +1,25 @@ -click -pytest -requests -python-dotenv -PyGithub \ No newline at end of file +-e git+https://github.com/AutoFiC/autofic-core.git@1643829b2507ea1f2d00c3c05b8428d2685fdd54#egg=autofic_core +certifi==2025.4.26 +cffi==1.17.1 +charset-normalizer==3.4.2 +click==8.2.1 +cryptography==45.0.2 +Deprecated==1.2.18 +idna==3.10 +iniconfig==2.1.0 +markdown-it-py==3.0.0 +mdurl==0.1.2 +packaging==25.0 +pluggy==1.6.0 +pycparser==2.22 +PyGithub==2.6.1 +Pygments==2.19.1 +PyJWT==2.10.1 +PyNaCl==1.5.0 +pytest==8.3.5 +python-dotenv==1.1.0 +requests==2.32.3 +rich==14.0.0 +typing_extensions==4.13.2 +urllib3==2.4.0 +wrapt==1.17.2 diff --git a/src/.DS_Store b/src/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..ca58e505c3607afab9b7db06e6916e3e3b8fe022 GIT binary patch literal 6148 zcmeH~&u-H|5XNWQKpaY?9H`U_k|nOCgn%MdTufRHTrq+JpkUXgSQu~QI9OE_$!B<& zUi&0{o$}4@R%#N0)C)q@j5Yi1pBY>GlfCODA~l>QPl>ujv(BJc)4+ir+e|FICq5f{N+BQw771+HW|#N>SL@IJi%HTF0z%+c5m2q8 z@MwrBxxIB|a=h32@Xv5Ij%%!%6clbdHWl8Acj3k`=5qxaIBl$=2PQuP27?qr;GYus E4O|__E&u=k literal 0 HcmV?d00001 diff --git a/src/autofic_core/.DS_Store b/src/autofic_core/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..5eea9d665715d7a786b028b58a9fdbb7afc03b05 GIT binary patch literal 6148 zcmeHK!EVz)5S>j!>L^0;0i<4#EOD($2q;p;#e{O`wMK9N6zn>p7LGTH9il3VB;b4t+DbL1|qiP6)wHH2Y>}=h^XF+v_DFHCm)kiF_jR;Eb&yCUYTV=>#Po-epCqmm|F>(o(pQ8SuJZckJ)2R)fRAe(-!aT<-^~ z!$BYMv*CK(^&UQc^5SItC7%}hLav$=?sT#H7B_H-z$n?!*YS1aQXCVr@`f9cW|=0Bj>IhL}GVnG;wHE!GAx0#k+xG*o4`7|PI*4{Tj%u{LPv zr0nKH*)uDe96yk9QlUZDIt82pHx<}1U7y$g*T3HX-z2%7Q@|Mek8^Axo*|@GY_>+P_mSWWMQoIKjLq6aD7+S0iA_H?D0wRNJoC1GTfot~< BhMxcc literal 0 HcmV?d00001 diff --git a/src/github_handler.py b/src/autofic_core/github_handler.py similarity index 100% rename from src/github_handler.py rename to src/autofic_core/github_handler.py From 3048b4fa9e44eb355cd7a0ed7a59cb2b30efd818 Mon Sep 17 00:00:00 2001 From: inyeongjang <135231946+inyeongjang@users.noreply.github.com> Date: Thu, 22 May 2025 16:22:28 +0900 Subject: [PATCH 003/297] Docs: Update README.md --- README.md | 78 +++++++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 59 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index bcdca3e..b37d35e 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ **LLM을 활용한 취약한 소스코드 수정 솔루션** ---- +
## 🚀 개발 환경 세팅 @@ -65,7 +65,7 @@ cp .env.example .env > `.env` 파일에 본인의 GitHub 토큰, OpenAI API 키 등 필요한 값을 입력하세요. ---- +
## ⚡ 실행 방법 @@ -81,7 +81,7 @@ python -m autofic_core.cli --repo https://github.com/AutoFiC/autofic-core.git autofic-core --repo https://github.com/AutoFiC/autofic-core.git ``` ---- +
## 🧪 테스트 방법 @@ -91,7 +91,7 @@ pytest tests/ - 모든 테스트가 **passed** 되면 정상 ---- +
## 📁 주요 파일 설명 @@ -106,18 +106,41 @@ pytest tests/ | LICENSE | 오픈소스 라이선스(MIT) | | README.md | 이 문서 | ---- +
-## 👥 협업 규칙 +## 🤝 Git & GitHub 협업 가이드 + +### 👥 협업 규칙 - **가상환경(venv)과 .env 파일은 Git에 올리지 마세요!** - 기능 추가/수정은 반드시 브랜치 생성 후 Pull Request로 병합 - 코드 리뷰/테스트 통과 후 main 브랜치에 반영 ---- +### 1. 기능 개발 시작: 브랜치 생성하고 이동 + +``` +git switch -c feature/내기능이름 +``` + +**🌿 브랜치명 규칙** +- 브랜치명은 아래 형식을 권장합니다. + - `feature/기능명` (새 기능) + - `bugfix/이슈번호-설명` (버그 수정) + - `docs/문서명` (문서) + - `test/설명` (테스트) +- 예시: + - `feature/github-api-integration` + - `bugfix/34-filter-extension-error` + - `docs/update-readme` + +### 2. 코드 수정 → 변경사항 저장 (commit) -## 📝 커밋 메시지 규칙 +``` +git add . +git commit -m "Add: GitHub API 연동 기능 추가" +``` +**📝 커밋 메시지 규칙** - 커밋 메시지는 아래 형식을 지켜주세요. - `Add: ...` (새 기능) - `Fix: ...` (버그 수정) @@ -132,16 +155,33 @@ pytest tests/ - `Fix: 파일 필터링 버그 수정` - `Docs: README 업데이트` ---- +### 3. GitHub에 업로드 (push) -## 🌿 브랜치명 규칙 +``` +git push origin feature/github-api-integration +``` -- 브랜치명은 아래 형식을 권장합니다. - - `feature/기능명` (새 기능) - - `bugfix/이슈번호-설명` (버그 수정) - - `docs/문서명` (문서) - - `test/설명` (테스트) -- 예시: - - `feature/github-api-integration` - - `bugfix/34-filter-extension-error` - - `docs/update-readme` +### 4. 다른 사람 코드와 충돌 방지 (pull) + +``` +git pull origin dev +``` + +> 💡 최신 dev 브랜치 내용을 내 브랜치에 반영 + +### 5. GitHub에서 Pull Request 만들기 + +- GitHub에서 Compare & pull request 버튼 클릭 +- base는 dev, compare는 내 브랜치인지 확인 +- 제목/설명 작성 후 Create pull request + +### 6. 팀장이 Merge 완료 후 dev 최신화 + +``` +git switch dev +git pull origin dev +``` + +> 💡 Merge가 끝났다면 dev 브랜치에서도 최신 상태를 유지해야 해요! + +> 다음 기능 개발 시 1번부터터 반복합니다. From 757a1652a0cf47ae44c8d2e03cc62575d990bb7d Mon Sep 17 00:00:00 2001 From: inyeongjang <135231946+inyeongjang@users.noreply.github.com> Date: Thu, 22 May 2025 16:44:11 +0900 Subject: [PATCH 004/297] Docs: Update README.md --- README.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/README.md b/README.md index b37d35e..058abbd 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,7 @@ pip install --upgrade pip pip install -r requirements.txt pip install -e . ``` +> -e는 editable 모드입니다. 소스코드를 수정하면 바로 반영되어 개발에 편리합니다. ### 6. 환경변수 파일 준비 ``` @@ -185,3 +186,34 @@ git pull origin dev > 💡 Merge가 끝났다면 dev 브랜치에서도 최신 상태를 유지해야 해요! > 다음 기능 개발 시 1번부터터 반복합니다. + +
+ +## 📦 pip 의존성 관리 가이드 + +### ✅ 가상환경 사용하기 (venv) + +모든 작업은 가상환경 안에서 진행해주세요! +각자 다른 시스템 설정으로 인한 충돌을 방지할 수 있습니다. + +### 📥 의존성 설치 + +``` +pip install -r requirements.txt +``` +> 🔁 프로젝트 클론 후 또는 .env 등 환경 구성 후에 꼭 실행하세요. + +### 🆕 라이브러리 설치 시 주의 + +새 패키지를 설치했다면 requirements.txt에 반영해주세요. + +``` +pip install some-library +pip freeze > requirements.txt +``` + +> ⚠️ `pip freeze > requirements.txt`는 현재 가상환경의 모든 패키지를 덮어씁니다.
+> 새 패키지만 반영하려면 아래처럼 일부만 추출해서 추가하세요. +``` +pip freeze | grep some-library >> requirements.txt +``` From 6bddbcbb5ba41c1bff33f16e1ef1ed96cde0070d Mon Sep 17 00:00:00 2001 From: soonnae Date: Thu, 22 May 2025 17:04:44 +0900 Subject: [PATCH 005/297] =?UTF-8?q?feat:=20GitHub=20=EC=A0=80=EC=9E=A5?= =?UTF-8?q?=EC=86=8C=20=EB=8B=A4=EC=9A=B4=EB=A1=9C=EB=93=9C=20=EC=8A=A4?= =?UTF-8?q?=ED=81=AC=EB=A6=BD=ED=8A=B8=20=EC=83=88=EB=A1=9C=20=EC=9E=91?= =?UTF-8?q?=EC=84=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/downloader.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/downloader.py b/src/downloader.py index 0866f1a..b9926a0 100644 --- a/src/downloader.py +++ b/src/downloader.py @@ -1,4 +1,4 @@ -# 📄 src/downloader.py +#src/downloader.py import os import subprocess @@ -8,13 +8,13 @@ def clone_from_github(repo_url: str, dest_path: str): if os.path.exists(dest_path): - print(f"[i] 이미 폴더가 존재합니다: {dest_path} → 삭제 후 클론") + print(f"이미 폴더가 존재합니다: {dest_path} → 삭제 후 클론") shutil.rmtree(dest_path) try: subprocess.run(["git", "clone", repo_url, dest_path], check=True) - print(f"[✓] GitHub 클론 완료: {repo_url}") + print(f"GitHub 클론 완료: {repo_url}") except subprocess.CalledProcessError: - print("[!] git clone 실패. git이 설치되어 있는지 확인하세요.") + print("git clone 실패. git이 설치되어 있는지 확인하세요.") def download_and_extract_zip(repo_url: str, dest_path: str): zip_url = repo_url.rstrip("/").replace("github.com", "github.com") + "/archive/refs/heads/main.zip" @@ -23,17 +23,17 @@ def download_and_extract_zip(repo_url: str, dest_path: str): os.makedirs(dest_path, exist_ok=True) try: - print(f"[i] zip 다운로드 중... {zip_url}") + print(f"zip 다운로드 중... {zip_url}") with requests.get(zip_url, stream=True) as r: with open(zip_path, "wb") as f: shutil.copyfileobj(r.raw, f) with zipfile.ZipFile(zip_path, 'r') as zip_ref: zip_ref.extractall(dest_path) - print(f"[✓] zip 압축 해제 완료") + print(f"zip 압축 해제 완료") except Exception as e: - print(f"[!] zip 다운로드 실패: {e}") + print(f"zip 다운로드 실패: {e}") finally: if os.path.exists(zip_path): @@ -41,7 +41,7 @@ def download_and_extract_zip(repo_url: str, dest_path: str): def use_local_path(path: str) -> str: if not os.path.exists(path): - raise FileNotFoundError(f"[!] 경로가 존재하지 않습니다: {path}") - print(f"[✓] 로컬 경로 사용: {path}") + raise FileNotFoundError(f"경로가 존재하지 않습니다: {path}") + print(f"로컬 경로 사용: {path}") return os.path.abspath(path) From 33d97167b1da1092db0f99ea7e69dcb5ab4a6c8a Mon Sep 17 00:00:00 2001 From: soonnae Date: Thu, 22 May 2025 17:11:24 +0900 Subject: [PATCH 006/297] =?UTF-8?q?add:=20=EC=86=8C=EC=8A=A4=EC=BD=94?= =?UTF-8?q?=EB=93=9C=20=EB=8B=A4=EC=9A=B4=EB=A1=9C=EB=93=9C=20=EC=8A=A4?= =?UTF-8?q?=ED=81=AC=EB=A6=BD=ED=8A=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/downloader.py | 1 - 1 file changed, 1 deletion(-) diff --git a/src/downloader.py b/src/downloader.py index b9926a0..31120d0 100644 --- a/src/downloader.py +++ b/src/downloader.py @@ -1,5 +1,4 @@ #src/downloader.py - import os import subprocess import zipfile From a3ffbca912931d0080b452490fa5196e069d6c5f Mon Sep 17 00:00:00 2001 From: soonnae Date: Thu, 22 May 2025 17:39:07 +0900 Subject: [PATCH 007/297] =?UTF-8?q?Refactor:=20=EC=BD=94=EB=93=9C=20?= =?UTF-8?q?=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/downloader.py | 40 ++++++++-------------------------------- 1 file changed, 8 insertions(+), 32 deletions(-) diff --git a/src/downloader.py b/src/downloader.py index 31120d0..5e6c69f 100644 --- a/src/downloader.py +++ b/src/downloader.py @@ -1,11 +1,9 @@ -#src/downloader.py import os import subprocess -import zipfile -import requests import shutil +import argparse -def clone_from_github(repo_url: str, dest_path: str): +def clone_from_github(repo_url: str, dest_path: str = "downloaded_repo"): if os.path.exists(dest_path): print(f"이미 폴더가 존재합니다: {dest_path} → 삭제 후 클론") shutil.rmtree(dest_path) @@ -15,32 +13,10 @@ def clone_from_github(repo_url: str, dest_path: str): except subprocess.CalledProcessError: print("git clone 실패. git이 설치되어 있는지 확인하세요.") -def download_and_extract_zip(repo_url: str, dest_path: str): - zip_url = repo_url.rstrip("/").replace("github.com", "github.com") + "/archive/refs/heads/main.zip" - zip_path = os.path.join(dest_path, "temp.zip") - - os.makedirs(dest_path, exist_ok=True) - - try: - print(f"zip 다운로드 중... {zip_url}") - with requests.get(zip_url, stream=True) as r: - with open(zip_path, "wb") as f: - shutil.copyfileobj(r.raw, f) - - with zipfile.ZipFile(zip_path, 'r') as zip_ref: - zip_ref.extractall(dest_path) - print(f"zip 압축 해제 완료") - - except Exception as e: - print(f"zip 다운로드 실패: {e}") - - finally: - if os.path.exists(zip_path): - os.remove(zip_path) - -def use_local_path(path: str) -> str: - if not os.path.exists(path): - raise FileNotFoundError(f"경로가 존재하지 않습니다: {path}") - print(f"로컬 경로 사용: {path}") - return os.path.abspath(path) +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="GitHub 저장소 다운로드 자동화 스크립트") + parser.add_argument("--url", required=True, help="GitHub 저장소 URL") + parser.add_argument("--dest", default="downloaded_repo", help="다운로드 경로 (기본값: downloaded_repo)") + args = parser.parse_args() + clone_from_github(args.url, args.dest) From c1a730d59a8d361f787485c6ec113621748071d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=9D=80=EC=86=94?= Date: Sun, 25 May 2025 17:04:35 +0900 Subject: [PATCH 008/297] Fix: duplicate output, (cli.py)lib unification --- src/autofic_core/cli.py | 19 +++++++------------ src/autofic_core/github_handler.py | 4 +--- 2 files changed, 8 insertions(+), 15 deletions(-) diff --git a/src/autofic_core/cli.py b/src/autofic_core/cli.py index 40ea526..ba7f1b8 100644 --- a/src/autofic_core/cli.py +++ b/src/autofic_core/cli.py @@ -1,5 +1,4 @@ import click -import argparse from autofic_core.github_handler import get_repo_files @click.command() @@ -8,21 +7,17 @@ def main(repo, silent): click.echo(f"Analyzing repo: {repo}") - parser = argparse.ArgumentParser(description="AutoFiC CLI") - parser.add_argument("--repo", type=str, required=True, help="GitHub 저장소 URL 입력") - parser.add_argument("--silent", action="store_true", help="결과 출력 없이 추출만 수행") # ✅ 이 줄 추가! - - args = parser.parse_args() - - files = get_repo_files(args.repo, silent=args.silent) + files = get_repo_files(repo, silent=silent) # 파일 목록 출력 예시 if not files: - print("JS 파일을 찾지 못했습니다. 저장소 구조 또는 필터 조건을 확인하세요.") - elif not args.silent: - print(f"JS 파일 {len(files)}개를 찾았습니다:") + click.echo("JS 파일을 찾지 못했습니다. 저장소 구조 또는 필터 조건을 확인하세요.") + + click.echo(f"JS 파일 {len(files)}개를 찾았습니다:") + + if not silent: for file in files: - print(f"{file['path']} -> {file['download_url']}") + click.echo(f"{file['path']} -> {file['download_url']}") if __name__ == '__main__': main() \ No newline at end of file diff --git a/src/autofic_core/github_handler.py b/src/autofic_core/github_handler.py index 58a1d35..a736d84 100644 --- a/src/autofic_core/github_handler.py +++ b/src/autofic_core/github_handler.py @@ -43,7 +43,7 @@ def get_repo_files(repo_url, file_extensions=(".js", ".mjs", ".jsx", ".ts"), sil js_files = [] contents = repo.get_contents("") - print("탐색 중입니다.") + print("파일 탐색 시작...") while contents: file_content = contents.pop(0) @@ -58,7 +58,5 @@ def get_repo_files(repo_url, file_extensions=(".js", ".mjs", ".jsx", ".ts"), sil }) if not silent: print(f"발견: {file_content.path}") - - print(f"JS 파일 {len(js_files)}개를 찾았습니다:") return js_files From 4f06cb1caabee53729b1024b95dce2f903521092 Mon Sep 17 00:00:00 2001 From: soonnae Date: Sun, 25 May 2025 23:24:08 +0900 Subject: [PATCH 009/297] =?UTF-8?q?feat:=20downloader.py=20=EA=B5=AC?= =?UTF-8?q?=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- downloaded_repo | 1 + src/autofic_core/.DS_Store | Bin 6148 -> 0 bytes src/autofic_core/__init__.py | 2 -- src/autofic_core/cli.py | 28 ---------------------- src/autofic_core/downloader.py | 36 +++++++++++++++++++++++++++++ src/autofic_core/github_handler.py | 6 ++--- src/autofic_core/sample_module.py | 2 -- src/downloader.py | 22 ------------------ test_clone.py | 2 +- 9 files changed, 40 insertions(+), 59 deletions(-) create mode 160000 downloaded_repo delete mode 100644 src/autofic_core/.DS_Store delete mode 100644 src/autofic_core/__init__.py delete mode 100644 src/autofic_core/cli.py create mode 100644 src/autofic_core/downloader.py delete mode 100644 src/autofic_core/sample_module.py delete mode 100644 src/downloader.py diff --git a/downloaded_repo b/downloaded_repo new file mode 160000 index 0000000..757a165 --- /dev/null +++ b/downloaded_repo @@ -0,0 +1 @@ +Subproject commit 757a1652a0cf47ae44c8d2e03cc62575d990bb7d diff --git a/src/autofic_core/.DS_Store b/src/autofic_core/.DS_Store deleted file mode 100644 index 5eea9d665715d7a786b028b58a9fdbb7afc03b05..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeHK!EVz)5S>j!>L^0;0i<4#EOD($2q;p;#e{O`wMK9N6zn>p7LGTH9il3VB;b4t+DbL1|qiP6)wHH2Y>}=h^XF+v_DFHCm)kiF_jR;Eb&yCUYTV=>#Po-epCqmm|F>(o(pQ8SuJZckJ)2R)fRAe(-!aT<-^~ z!$BYMv*CK(^&UQc^5SItC7%}hLav$=?sT#H7B_H-z$n?!*YS1aQXCVr@`f9cW|=0Bj>IhL}GVnG;wHE!GAx0#k+xG*o4`7|PI*4{Tj%u{LPv zr0nKH*)uDe96yk9QlUZDIt82pHx<}1U7y$g*T3HX-z2%7Q@|Mek8^Axo*|@GY_>+P_mSWWMQoIKjLq6aD7+S0iA_H?D0wRNJoC1GTfot~< BhMxcc diff --git a/src/autofic_core/__init__.py b/src/autofic_core/__init__.py deleted file mode 100644 index c51ab4a..0000000 --- a/src/autofic_core/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -# 패키지 초기화 파일 -__version__ = "0.1.0" \ No newline at end of file diff --git a/src/autofic_core/cli.py b/src/autofic_core/cli.py deleted file mode 100644 index 40ea526..0000000 --- a/src/autofic_core/cli.py +++ /dev/null @@ -1,28 +0,0 @@ -import click -import argparse -from autofic_core.github_handler import get_repo_files - -@click.command() -@click.option('--repo', help='GitHub repository URL') -@click.option('--silent', is_flag=True, help="결과 출력 없이 조용히 실행") -def main(repo, silent): - click.echo(f"Analyzing repo: {repo}") - - parser = argparse.ArgumentParser(description="AutoFiC CLI") - parser.add_argument("--repo", type=str, required=True, help="GitHub 저장소 URL 입력") - parser.add_argument("--silent", action="store_true", help="결과 출력 없이 추출만 수행") # ✅ 이 줄 추가! - - args = parser.parse_args() - - files = get_repo_files(args.repo, silent=args.silent) - - # 파일 목록 출력 예시 - if not files: - print("JS 파일을 찾지 못했습니다. 저장소 구조 또는 필터 조건을 확인하세요.") - elif not args.silent: - print(f"JS 파일 {len(files)}개를 찾았습니다:") - for file in files: - print(f"{file['path']} -> {file['download_url']}") - -if __name__ == '__main__': - main() \ No newline at end of file diff --git a/src/autofic_core/downloader.py b/src/autofic_core/downloader.py new file mode 100644 index 0000000..8afa4d5 --- /dev/null +++ b/src/autofic_core/downloader.py @@ -0,0 +1,36 @@ +import os +import requests +import click +from autofic_core.github_handler import get_repo_files + +@click.command() +@click.option('--repo', required=True, help='GitHub 저장소 URL') +@click.option('--silent', is_flag=True, help='출력 생략 여부') +@click.option('--save-dir', default='downloaded_repo', help='다운로드할 로컬 디렉토리') +def download(repo, silent, save_dir): + click.echo(f"[START] 저장소 분석: {repo}") + + js_files = get_repo_files(repo, silent=silent) + if not js_files: + click.echo("JS 파일이 없습니다.") + return + + click.echo(f"총 {len(js_files)}개 JS 파일 다운로드 시작...") + + for file in js_files: + file_path = os.path.join(save_dir, file["path"]) + os.makedirs(os.path.dirname(file_path), exist_ok=True) + + response = requests.get(file["download_url"]) + if response.status_code == 200: + with open(file_path, 'wb') as f: + f.write(response.content) + if not silent: + click.echo(f"저장됨: {file_path}") + else: + click.echo(f"실패: {file['download_url']}") + + click.echo("다운로드 완료.") + +if __name__ == '__main__': + download() diff --git a/src/autofic_core/github_handler.py b/src/autofic_core/github_handler.py index 58a1d35..451b499 100644 --- a/src/autofic_core/github_handler.py +++ b/src/autofic_core/github_handler.py @@ -43,7 +43,7 @@ def get_repo_files(repo_url, file_extensions=(".js", ".mjs", ".jsx", ".ts"), sil js_files = [] contents = repo.get_contents("") - print("탐색 중입니다.") + print("파일 탐색 시작...") while contents: file_content = contents.pop(0) @@ -58,7 +58,5 @@ def get_repo_files(repo_url, file_extensions=(".js", ".mjs", ".jsx", ".ts"), sil }) if not silent: print(f"발견: {file_content.path}") - - print(f"JS 파일 {len(js_files)}개를 찾았습니다:") - return js_files + return js_files \ No newline at end of file diff --git a/src/autofic_core/sample_module.py b/src/autofic_core/sample_module.py deleted file mode 100644 index 8ec43c2..0000000 --- a/src/autofic_core/sample_module.py +++ /dev/null @@ -1,2 +0,0 @@ -def sample_function(): - return "Hello World" diff --git a/src/downloader.py b/src/downloader.py deleted file mode 100644 index 5e6c69f..0000000 --- a/src/downloader.py +++ /dev/null @@ -1,22 +0,0 @@ -import os -import subprocess -import shutil -import argparse - -def clone_from_github(repo_url: str, dest_path: str = "downloaded_repo"): - if os.path.exists(dest_path): - print(f"이미 폴더가 존재합니다: {dest_path} → 삭제 후 클론") - shutil.rmtree(dest_path) - try: - subprocess.run(["git", "clone", repo_url, dest_path], check=True) - print(f"GitHub 클론 완료: {repo_url}") - except subprocess.CalledProcessError: - print("git clone 실패. git이 설치되어 있는지 확인하세요.") - -if __name__ == "__main__": - parser = argparse.ArgumentParser(description="GitHub 저장소 다운로드 자동화 스크립트") - parser.add_argument("--url", required=True, help="GitHub 저장소 URL") - parser.add_argument("--dest", default="downloaded_repo", help="다운로드 경로 (기본값: downloaded_repo)") - args = parser.parse_args() - - clone_from_github(args.url, args.dest) diff --git a/test_clone.py b/test_clone.py index 55cc93d..4c8fa41 100644 --- a/test_clone.py +++ b/test_clone.py @@ -1,4 +1,4 @@ from src.downloader import clone_from_github -# ✅ 두 번째 인자 추가! clone_from_github("https://github.com/AutoFiC/autofic-core.git", "./downloaded_repo") +s \ No newline at end of file From 405033b560cf32ff11e8f47448dc79bb39d8dbb5 Mon Sep 17 00:00:00 2001 From: soonnae Date: Mon, 26 May 2025 00:02:53 +0900 Subject: [PATCH 010/297] =?UTF-8?q?resolve:=20dev=20=EA=B8=B0=EC=A4=80?= =?UTF-8?q?=EC=9C=BC=EB=A1=9C=20cli.py=20=EC=B6=A9=EB=8F=8C=20=ED=95=B4?= =?UTF-8?q?=EA=B2=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/autofic_core/cli.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 src/autofic_core/cli.py diff --git a/src/autofic_core/cli.py b/src/autofic_core/cli.py new file mode 100644 index 0000000..40ea526 --- /dev/null +++ b/src/autofic_core/cli.py @@ -0,0 +1,28 @@ +import click +import argparse +from autofic_core.github_handler import get_repo_files + +@click.command() +@click.option('--repo', help='GitHub repository URL') +@click.option('--silent', is_flag=True, help="결과 출력 없이 조용히 실행") +def main(repo, silent): + click.echo(f"Analyzing repo: {repo}") + + parser = argparse.ArgumentParser(description="AutoFiC CLI") + parser.add_argument("--repo", type=str, required=True, help="GitHub 저장소 URL 입력") + parser.add_argument("--silent", action="store_true", help="결과 출력 없이 추출만 수행") # ✅ 이 줄 추가! + + args = parser.parse_args() + + files = get_repo_files(args.repo, silent=args.silent) + + # 파일 목록 출력 예시 + if not files: + print("JS 파일을 찾지 못했습니다. 저장소 구조 또는 필터 조건을 확인하세요.") + elif not args.silent: + print(f"JS 파일 {len(files)}개를 찾았습니다:") + for file in files: + print(f"{file['path']} -> {file['download_url']}") + +if __name__ == '__main__': + main() \ No newline at end of file From f4c85b2e16a39f6a23bc4953dac87b16adb42004 Mon Sep 17 00:00:00 2001 From: soonnae Date: Mon, 26 May 2025 14:08:09 +0900 Subject: [PATCH 011/297] =?UTF-8?q?refactor:=20downloader.py=20=ED=95=A8?= =?UTF-8?q?=EC=88=98=20=EA=B5=AC=EC=A1=B0=20=EA=B0=9C=EC=84=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/autofic_core/downloader.py | 43 ++++++++++++++-------------------- 1 file changed, 18 insertions(+), 25 deletions(-) diff --git a/src/autofic_core/downloader.py b/src/autofic_core/downloader.py index 8afa4d5..f43dc27 100644 --- a/src/autofic_core/downloader.py +++ b/src/autofic_core/downloader.py @@ -1,36 +1,29 @@ import os import requests -import click -from autofic_core.github_handler import get_repo_files +from .github_handler import get_repo_files -@click.command() -@click.option('--repo', required=True, help='GitHub 저장소 URL') -@click.option('--silent', is_flag=True, help='출력 생략 여부') -@click.option('--save-dir', default='downloaded_repo', help='다운로드할 로컬 디렉토리') -def download(repo, silent, save_dir): - click.echo(f"[START] 저장소 분석: {repo}") +def download_files(repo_url, save_dir="downloaded_repo", silent=False): + """GitHub 저장소에서 JS 파일 목록을 가져와 다운로드합니다.""" + + js_files = get_repo_files(repo_url, silent=silent) - js_files = get_repo_files(repo, silent=silent) if not js_files: - click.echo("JS 파일이 없습니다.") + if not silent: + print("JS 파일을 찾지 못했습니다.") return - click.echo(f"총 {len(js_files)}개 JS 파일 다운로드 시작...") - for file in js_files: - file_path = os.path.join(save_dir, file["path"]) - os.makedirs(os.path.dirname(file_path), exist_ok=True) + path = file["path"] + url = file["download_url"] + local_path = os.path.join(save_dir, path) + + os.makedirs(os.path.dirname(local_path), exist_ok=True) - response = requests.get(file["download_url"]) - if response.status_code == 200: - with open(file_path, 'wb') as f: + try: + response = requests.get(url) + with open(local_path, "wb") as f: f.write(response.content) if not silent: - click.echo(f"저장됨: {file_path}") - else: - click.echo(f"실패: {file['download_url']}") - - click.echo("다운로드 완료.") - -if __name__ == '__main__': - download() + print(f"{path} 다운로드 완료") + except Exception as e: + print(f"{path} 다운로드 실패: {e}") From 09cd7fc5fb3c01b110e11921468274b5d38edf71 Mon Sep 17 00:00:00 2001 From: soonnae Date: Mon, 26 May 2025 14:19:08 +0900 Subject: [PATCH 012/297] =?UTF-8?q?feat:=20cli.py=EC=97=90=20download=5Ffi?= =?UTF-8?q?les=20=EA=B8=B0=EB=8A=A5=20=EC=97=B0=EB=8F=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/autofic_core/cli.py | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/src/autofic_core/cli.py b/src/autofic_core/cli.py index 40ea526..290498b 100644 --- a/src/autofic_core/cli.py +++ b/src/autofic_core/cli.py @@ -1,28 +1,26 @@ import click -import argparse from autofic_core.github_handler import get_repo_files +from autofic_core.downloader import download_files @click.command() @click.option('--repo', help='GitHub repository URL') @click.option('--silent', is_flag=True, help="결과 출력 없이 조용히 실행") -def main(repo, silent): +@click.option('--save-dir', default="downloaded_repo", help="저장할 디렉토리 경로") +def main(repo, silent, save_dir): click.echo(f"Analyzing repo: {repo}") - parser = argparse.ArgumentParser(description="AutoFiC CLI") - parser.add_argument("--repo", type=str, required=True, help="GitHub 저장소 URL 입력") - parser.add_argument("--silent", action="store_true", help="결과 출력 없이 추출만 수행") # ✅ 이 줄 추가! + files = get_repo_files(repo, silent=silent) - args = parser.parse_args() - - files = get_repo_files(args.repo, silent=args.silent) - - # 파일 목록 출력 예시 if not files: print("JS 파일을 찾지 못했습니다. 저장소 구조 또는 필터 조건을 확인하세요.") - elif not args.silent: + return + + if not silent: print(f"JS 파일 {len(files)}개를 찾았습니다:") for file in files: print(f"{file['path']} -> {file['download_url']}") + download_files(repo_url=repo, save_dir=save_dir, silent=silent) + if __name__ == '__main__': - main() \ No newline at end of file + main() From beaf24e0c0d4c9adadaee7820bb4a0c49b8f9327 Mon Sep 17 00:00:00 2001 From: inyeongjang <726jang@gmail.com> Date: Mon, 26 May 2025 17:28:02 +0900 Subject: [PATCH 013/297] =?UTF-8?q?Add:=20Semgrep=20=EA=B2=B0=EA=B3=BC=20?= =?UTF-8?q?=EC=A0=84=EC=B2=98=EB=A6=AC=20=EA=B8=B0=EB=8A=A5=20=EC=B6=94?= =?UTF-8?q?=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/autofic_core/cli.py | 10 +++++++- src/autofic_core/semgrep_preprocessor.py | 31 ++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 src/autofic_core/semgrep_preprocessor.py diff --git a/src/autofic_core/cli.py b/src/autofic_core/cli.py index 290498b..98665a1 100644 --- a/src/autofic_core/cli.py +++ b/src/autofic_core/cli.py @@ -1,12 +1,17 @@ import click from autofic_core.github_handler import get_repo_files from autofic_core.downloader import download_files +from autofic_core.semgrep_preprocessor import preprocess_semgrep_results @click.command() @click.option('--repo', help='GitHub repository URL') @click.option('--silent', is_flag=True, help="결과 출력 없이 조용히 실행") @click.option('--save-dir', default="downloaded_repo", help="저장할 디렉토리 경로") -def main(repo, silent, save_dir): +@click.option('--preprocess-semgrep', is_flag=True, help="Semgrep 결과 전처리 수행") +@click.option('--semgrep-input', default="semgrep_output.json", help="Semgrep 원본 결과 경로") +@click.option('--semgrep-output', default="llm_input.json", help="LLM 입력용 변환 결과 저장 경로") + +def main(repo, silent, save_dir, preprocess_semgrep, semgrep_input, semgrep_output): click.echo(f"Analyzing repo: {repo}") files = get_repo_files(repo, silent=silent) @@ -22,5 +27,8 @@ def main(repo, silent, save_dir): download_files(repo_url=repo, save_dir=save_dir, silent=silent) + if preprocess_semgrep: + preprocess_semgrep_results(semgrep_input, semgrep_output) + if __name__ == '__main__': main() diff --git a/src/autofic_core/semgrep_preprocessor.py b/src/autofic_core/semgrep_preprocessor.py new file mode 100644 index 0000000..7296bc8 --- /dev/null +++ b/src/autofic_core/semgrep_preprocessor.py @@ -0,0 +1,31 @@ +import json +from pathlib import Path + +def preprocess_semgrep_results(input_json_path: str, output_json_path: str, base_dir: str = "../.."): + with open(input_json_path, 'r', encoding='utf-8') as f: + results = json.load(f) + + processed = [] + + for idx, result in enumerate(results.get("results", [])): + file_path = Path(base_dir) / result.get("path", "") + start_line = result.get("start", {}).get("line", None) + end_line = result.get("end", {}).get("line", None) + + code_snippet = "" + if file_path.exists() and start_line and end_line: + with open(file_path, 'r', encoding='utf-8') as src_file: + lines = src_file.readlines() + code_snippet = "".join(lines[start_line-1:end_line]) + + processed.append({ + "instruction": "Refactor the code below to fix the security vulnerability and include a brief remediation guide.", + "input": code_snippet.strip(), + "output": "", + "idx": idx + }) + + with open(output_json_path, 'w', encoding='utf-8') as f: + json.dump(processed, f, indent=4, ensure_ascii=False) + + print(f"Preprocessing complete. Output saved to: {output_json_path}") \ No newline at end of file From 39c8404dc4523092bd64d0df28e78f434c7196bd Mon Sep 17 00:00:00 2001 From: soonnae Date: Mon, 26 May 2025 20:57:16 +0900 Subject: [PATCH 014/297] =?UTF-8?q?refactor:=20=EC=A4=91=EB=B3=B5=20API=20?= =?UTF-8?q?=ED=98=B8=EC=B6=9C=20=EC=A0=9C=EA=B1=B0=20=EB=B0=8F=20downloade?= =?UTF-8?q?r=20=ED=95=A8=EC=88=98=20=EA=B0=9C=EC=84=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/autofic_core/cli.py | 2 +- src/autofic_core/downloader.py | 11 +---------- 2 files changed, 2 insertions(+), 11 deletions(-) diff --git a/src/autofic_core/cli.py b/src/autofic_core/cli.py index 290498b..dd0570f 100644 --- a/src/autofic_core/cli.py +++ b/src/autofic_core/cli.py @@ -20,7 +20,7 @@ def main(repo, silent, save_dir): for file in files: print(f"{file['path']} -> {file['download_url']}") - download_files(repo_url=repo, save_dir=save_dir, silent=silent) + download_files(js_files=files, save_dir=save_dir, silent=silent) if __name__ == '__main__': main() diff --git a/src/autofic_core/downloader.py b/src/autofic_core/downloader.py index f43dc27..80fc3c0 100644 --- a/src/autofic_core/downloader.py +++ b/src/autofic_core/downloader.py @@ -1,16 +1,7 @@ import os import requests -from .github_handler import get_repo_files -def download_files(repo_url, save_dir="downloaded_repo", silent=False): - """GitHub 저장소에서 JS 파일 목록을 가져와 다운로드합니다.""" - - js_files = get_repo_files(repo_url, silent=silent) - - if not js_files: - if not silent: - print("JS 파일을 찾지 못했습니다.") - return +def download_files(js_files, save_dir="downloaded_repo", silent=False): for file in js_files: path = file["path"] From e228af7274d832237f338ddb8b9977653d81806e Mon Sep 17 00:00:00 2001 From: Minchae Kim Date: Tue, 27 May 2025 18:17:01 +0900 Subject: [PATCH 015/297] =?UTF-8?q?Add:=20Semgrep=20=EC=9E=90=EB=8F=99?= =?UTF-8?q?=ED=99=94=20=EC=8B=A4=ED=96=89=20=EC=8A=A4=ED=81=AC=EB=A6=BD=20?= =?UTF-8?q?=EC=9E=91=EC=84=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/autofic_core/sast.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 src/autofic_core/sast.py diff --git a/src/autofic_core/sast.py b/src/autofic_core/sast.py new file mode 100644 index 0000000..2bba104 --- /dev/null +++ b/src/autofic_core/sast.py @@ -0,0 +1,19 @@ +import subprocess + +def run_semgrep(repo_path: str, rule: str): + cmd = [ + "semgrep", + "--config", rule, + "--json", + "--include", "*.js", + "--include", "*.jsx", + "--include", "*.mjs", + repo_path + ] + + try: + completed = subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8', check=True) + return completed.stdout, completed.stderr, completed.returncode + + except subprocess.CalledProcessError as err: + return err.stdout, err.stderr, err.returncode \ No newline at end of file From 97f97dfd856ab46bfab3768979311b53971f4c24 Mon Sep 17 00:00:00 2001 From: inyeongjang <726jang@gmail.com> Date: Wed, 28 May 2025 01:48:16 +0900 Subject: [PATCH 016/297] =?UTF-8?q?Refactor:=20downloaded=5Frepo=20?= =?UTF-8?q?=EC=A0=9C=EA=B1=B0=20=EB=B0=8F=20=5F=5Finit=5F=5F.py=20?= =?UTF-8?q?=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- downloaded_repo | 1 - src/autofic_core/__init__.py | 0 2 files changed, 1 deletion(-) delete mode 160000 downloaded_repo create mode 100644 src/autofic_core/__init__.py diff --git a/downloaded_repo b/downloaded_repo deleted file mode 160000 index 757a165..0000000 --- a/downloaded_repo +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 757a1652a0cf47ae44c8d2e03cc62575d990bb7d diff --git a/src/autofic_core/__init__.py b/src/autofic_core/__init__.py new file mode 100644 index 0000000..e69de29 From bde30e6d378a02062525abc645718ece4a057b47 Mon Sep 17 00:00:00 2001 From: inyeongjang <726jang@gmail.com> Date: Wed, 28 May 2025 01:52:50 +0900 Subject: [PATCH 017/297] Chore: remove .DS_Store files and ignore them --- .DS_Store | Bin 6148 -> 0 bytes .gitignore | 3 +++ src/.DS_Store | Bin 6148 -> 0 bytes 3 files changed, 3 insertions(+) delete mode 100644 .DS_Store delete mode 100644 src/.DS_Store diff --git a/.DS_Store b/.DS_Store deleted file mode 100644 index 76be5a863c0076b67f812c14860f83e59d2e4526..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeHKO>fgM7=GP$G-V9+0MafhN)qT4j4 zbNGZLeWZW}lu`{YX+)9!_Aj~LbKDA@qL(A;&@*5SjNv*%+{-bl=qI4hG^J4GMkvMT zEm3`*QJUj_&GCzfoX{W__3P>=f1Zr}NWJ|Je;kELTCe{Ug<@&vM%gJlyUtthgPeP5 zKbYZa5r~NPvCW;Ua1BASJ6~;q3Z_8;sOcdAC4Nk?W z^s4)dMdPq>;683Pmj~|Ruu(_;QFFPhICt+qcyikN6pdo}1#b=$*l(5X8N2`Sp}>D|4#wlA6z(N%iv0*+B%S^D*&*BYGugt zPXlvYgDrzAjc9=hO$BPIFjowr>8N*2T+84}qo$KEmk(ij7UqT`RPT7ctHMdNG}_cE zU=>(bps0&gKL5LazyGh3Y{@EM6}VOkh*HPvv@s-ewr&iL&srD$4$j7LD~*bR#2m*e g!$i2wiq diff --git a/.gitignore b/.gitignore index 0a19790..7a553f8 100644 --- a/.gitignore +++ b/.gitignore @@ -172,3 +172,6 @@ cython_debug/ # PyPI configuration file .pypirc + +# macOS +.DS_Store \ No newline at end of file diff --git a/src/.DS_Store b/src/.DS_Store deleted file mode 100644 index ca58e505c3607afab9b7db06e6916e3e3b8fe022..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeH~&u-H|5XNWQKpaY?9H`U_k|nOCgn%MdTufRHTrq+JpkUXgSQu~QI9OE_$!B<& zUi&0{o$}4@R%#N0)C)q@j5Yi1pBY>GlfCODA~l>QPl>ujv(BJc)4+ir+e|FICq5f{N+BQw771+HW|#N>SL@IJi%HTF0z%+c5m2q8 z@MwrBxxIB|a=h32@Xv5Ij%%!%6clbdHWl8Acj3k`=5qxaIBl$=2PQuP27?qr;GYus E4O|__E&u=k From 770fd36f8a2043b0368b59ca01fc6ee61baea394 Mon Sep 17 00:00:00 2001 From: Minchae Kim Date: Wed, 28 May 2025 18:03:44 +0900 Subject: [PATCH 018/297] =?UTF-8?q?Add:=20Semgrep=20=EC=9E=90=EB=8F=99?= =?UTF-8?q?=ED=99=94=20=EC=9D=B8=ED=84=B0=ED=8E=98=EC=9D=B4=EC=8A=A4=20?= =?UTF-8?q?=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/autofic_core/cli.py | 42 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/src/autofic_core/cli.py b/src/autofic_core/cli.py index dd0570f..7092321 100644 --- a/src/autofic_core/cli.py +++ b/src/autofic_core/cli.py @@ -1,12 +1,17 @@ import click +import json from autofic_core.github_handler import get_repo_files from autofic_core.downloader import download_files +from autofic_core.sast import run_semgrep @click.command() @click.option('--repo', help='GitHub repository URL') @click.option('--silent', is_flag=True, help="결과 출력 없이 조용히 실행") @click.option('--save-dir', default="downloaded_repo", help="저장할 디렉토리 경로") -def main(repo, silent, save_dir): +@click.option('--sast', is_flag=True, help='SAST 분석 수행 여부') +@click.option('--rule', default='p/javascript', help='Semgrep 규칙') + +def main(repo, silent, save_dir, sast, rule): click.echo(f"Analyzing repo: {repo}") files = get_repo_files(repo, silent=silent) @@ -21,6 +26,41 @@ def main(repo, silent, save_dir): print(f"{file['path']} -> {file['download_url']}") download_files(js_files=files, save_dir=save_dir, silent=silent) + + if sast: + click.echo("\nSemgrep 분석 시작!") + click.echo("Semgrep 분석 진행 중...") + semgrep_output, semgrep_error, semgrep_status = run_semgrep(save_dir, rule) + + if semgrep_status != 0: + click.echo(f"\n[ ERROR ] Semgrep 실행 실패 (리턴 코드: {semgrep_status})\n") + + try: + err_json = json.loads(semgrep_output or semgrep_error) + click.echo("[ Semgrep 에러 내용 ]") + for err in err_json.get("errors", []): + click.echo(f"- {err.get('message')} (코드: {err.get('code')})") + + except json.JSONDecodeError: + click.echo("에러 메시지 JSON 파싱 실패 : ") + click.echo(semgrep_error or semgrep_output) + + return + + click.echo("Semgrep 분석 완료!\n\n") + click.echo("[ Semgrep 결과 ]\n") + + try: + results_json = json.loads(semgrep_output) + results = results_json.get("results", []) + + for result in results: + click.echo(json.dumps(result, indent=4)) + click.echo('\n' + '-'*80 + '\n') + + except json.JSONDecodeError: + click.echo("Semgrep 결과 JSON 파싱 실패") + click.echo(semgrep_output) if __name__ == '__main__': main() From ccd1561b497481dc70b9c47a105dfb9125d13ab2 Mon Sep 17 00:00:00 2001 From: inyeongjang <726jang@gmail.com> Date: Wed, 28 May 2025 18:06:08 +0900 Subject: [PATCH 019/297] Remove: test_clone.py --- test_clone.py | 4 ---- 1 file changed, 4 deletions(-) delete mode 100644 test_clone.py diff --git a/test_clone.py b/test_clone.py deleted file mode 100644 index 4c8fa41..0000000 --- a/test_clone.py +++ /dev/null @@ -1,4 +0,0 @@ -from src.downloader import clone_from_github - -clone_from_github("https://github.com/AutoFiC/autofic-core.git", "./downloaded_repo") -s \ No newline at end of file From ba70cb6cb7d446b5d18cc47d75e798aa33ed5fd8 Mon Sep 17 00:00:00 2001 From: inyeongjang <726jang@gmail.com> Date: Wed, 28 May 2025 18:31:23 +0900 Subject: [PATCH 020/297] =?UTF-8?q?Refactor:=20semgrep=20=EC=8B=A4?= =?UTF-8?q?=ED=96=89=20=EA=B2=B0=EA=B3=BC=EB=A5=BC=20=ED=8C=8C=EC=9D=BC?= =?UTF-8?q?=EB=A1=9C=20=EC=A0=80=EC=9E=A5=ED=95=98=EB=8F=84=EB=A1=9D=20?= =?UTF-8?q?=EB=B3=80=EA=B2=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/autofic_core/cli.py | 4 +++- src/autofic_core/sast.py | 8 ++++++-- src/autofic_core/semgrep_preprocessor.py | 3 ++- 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/src/autofic_core/cli.py b/src/autofic_core/cli.py index 8a77ebe..e2ae20b 100644 --- a/src/autofic_core/cli.py +++ b/src/autofic_core/cli.py @@ -7,6 +7,7 @@ @click.option('--repo', help='GitHub repository URL') @click.option('--silent', is_flag=True, help="결과 출력 없이 조용히 실행") @click.option('--save-dir', default="downloaded_repo", help="저장할 디렉토리 경로") + @click.option('--preprocess-semgrep', is_flag=True, help="Semgrep 결과 전처리 수행") @click.option('--semgrep-input', default="semgrep_output.json", help="Semgrep 원본 결과 경로") @click.option('--semgrep-output', default="llm_input.json", help="LLM 입력용 변환 결과 저장 경로") @@ -28,7 +29,8 @@ def main(repo, silent, save_dir, preprocess_semgrep, semgrep_input, semgrep_outp download_files(js_files=files, save_dir=save_dir, silent=silent) if preprocess_semgrep: - preprocess_semgrep_results(semgrep_input, semgrep_output) + output_json_path = preprocess_semgrep_results(semgrep_input, semgrep_output) + print(f"전처리 완료된 JSON 파일이 저장되었습니다 : {output_json_path}") if __name__ == '__main__': main() diff --git a/src/autofic_core/sast.py b/src/autofic_core/sast.py index 2bba104..9415753 100644 --- a/src/autofic_core/sast.py +++ b/src/autofic_core/sast.py @@ -1,6 +1,6 @@ import subprocess -def run_semgrep(repo_path: str, rule: str): +def run_semgrep(repo_path: str, rule: str, output_json: str = "semgrep_output.json"): cmd = [ "semgrep", "--config", rule, @@ -13,7 +13,11 @@ def run_semgrep(repo_path: str, rule: str): try: completed = subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8', check=True) - return completed.stdout, completed.stderr, completed.returncode + + with open(output_json, 'w', encoding='utf-8') as f: + f.write(completed.stdout) + + return output_json, completed.stderr, completed.returncode except subprocess.CalledProcessError as err: return err.stdout, err.stderr, err.returncode \ No newline at end of file diff --git a/src/autofic_core/semgrep_preprocessor.py b/src/autofic_core/semgrep_preprocessor.py index 7296bc8..0551cb8 100644 --- a/src/autofic_core/semgrep_preprocessor.py +++ b/src/autofic_core/semgrep_preprocessor.py @@ -28,4 +28,5 @@ def preprocess_semgrep_results(input_json_path: str, output_json_path: str, base with open(output_json_path, 'w', encoding='utf-8') as f: json.dump(processed, f, indent=4, ensure_ascii=False) - print(f"Preprocessing complete. Output saved to: {output_json_path}") \ No newline at end of file + return output_json_path + \ No newline at end of file From 22e89e2f6d3029270f15e6f81985dcdc57fe4be1 Mon Sep 17 00:00:00 2001 From: inyeongjang <726jang@gmail.com> Date: Wed, 28 May 2025 19:45:11 +0900 Subject: [PATCH 021/297] Remove: test_clone.py --- test_clone.py | 4 ---- 1 file changed, 4 deletions(-) delete mode 100644 test_clone.py diff --git a/test_clone.py b/test_clone.py deleted file mode 100644 index 4c8fa41..0000000 --- a/test_clone.py +++ /dev/null @@ -1,4 +0,0 @@ -from src.downloader import clone_from_github - -clone_from_github("https://github.com/AutoFiC/autofic-core.git", "./downloaded_repo") -s \ No newline at end of file From 39bc0065df8020e62213cdf534af9b27ab0fc187 Mon Sep 17 00:00:00 2001 From: inyeongjang <726jang@gmail.com> Date: Wed, 28 May 2025 19:57:17 +0900 Subject: [PATCH 022/297] =?UTF-8?q?Chore:=20requirements.txt=EC=97=90=20se?= =?UTF-8?q?mgrep=20=EC=B6=94=EA=B0=80=20=EB=B0=8F=20click/rich=20=EB=B2=84?= =?UTF-8?q?=EC=A0=84=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- requirements.txt | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/requirements.txt b/requirements.txt index f3bb660..626b19e 100644 --- a/requirements.txt +++ b/requirements.txt @@ -2,7 +2,7 @@ certifi==2025.4.26 cffi==1.17.1 charset-normalizer==3.4.2 -click==8.2.1 +click==8.1.8 cryptography==45.0.2 Deprecated==1.2.18 idna==3.10 @@ -19,7 +19,8 @@ PyNaCl==1.5.0 pytest==8.3.5 python-dotenv==1.1.0 requests==2.32.3 -rich==14.0.0 +rich==13.5.2 typing_extensions==4.13.2 urllib3==2.4.0 wrapt==1.17.2 +semgrep==1.122.0 \ No newline at end of file From 4bcab7bf8748e54cfd52cf8f051ce2e6be9fdd75 Mon Sep 17 00:00:00 2001 From: inyeongjang <726jang@gmail.com> Date: Thu, 29 May 2025 04:43:32 +0900 Subject: [PATCH 023/297] =?UTF-8?q?Feat:=20cli.py=EC=97=90=20SAST=20?= =?UTF-8?q?=EC=8B=A4=ED=96=89=20=EB=B0=8F=20Semgrep=20=EC=A0=84=EC=B2=98?= =?UTF-8?q?=EB=A6=AC=20=EC=98=B5=EC=85=98=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/autofic_core/cli.py | 52 +++++++++++++++++++++++++++++++++++------ 1 file changed, 45 insertions(+), 7 deletions(-) diff --git a/src/autofic_core/cli.py b/src/autofic_core/cli.py index e2ae20b..bd54ae4 100644 --- a/src/autofic_core/cli.py +++ b/src/autofic_core/cli.py @@ -1,18 +1,21 @@ import click +import json from autofic_core.github_handler import get_repo_files from autofic_core.downloader import download_files from autofic_core.semgrep_preprocessor import preprocess_semgrep_results +from autofic_core.sast import run_semgrep @click.command() @click.option('--repo', help='GitHub repository URL') @click.option('--silent', is_flag=True, help="결과 출력 없이 조용히 실행") @click.option('--save-dir', default="downloaded_repo", help="저장할 디렉토리 경로") - +@click.option('--sast', is_flag=True, help='SAST 분석 수행 여부') +@click.option('--rule', default='p/javascript', help='Semgrep 규칙') @click.option('--preprocess-semgrep', is_flag=True, help="Semgrep 결과 전처리 수행") -@click.option('--semgrep-input', default="semgrep_output.json", help="Semgrep 원본 결과 경로") -@click.option('--semgrep-output', default="llm_input.json", help="LLM 입력용 변환 결과 저장 경로") +@click.option('--semgrep-output', default="semgrep_output.json", help="Semgrep 원본 결과 경로") +@click.option('--llm-input', default="llm_input.json", help="LLM 입력용 변환 결과 저장 경로") -def main(repo, silent, save_dir, preprocess_semgrep, semgrep_input, semgrep_output): +def main(repo, silent, save_dir, sast, rule, preprocess_semgrep, semgrep_output, llm_input): click.echo(f"Analyzing repo: {repo}") files = get_repo_files(repo, silent=silent) @@ -27,10 +30,45 @@ def main(repo, silent, save_dir, preprocess_semgrep, semgrep_input, semgrep_outp print(f"{file['path']} -> {file['download_url']}") download_files(js_files=files, save_dir=save_dir, silent=silent) + + if sast: + click.echo("\nSemgrep 분석 시작!") + click.echo("Semgrep 분석 진행 중...") + semgrep_output, semgrep_error, semgrep_status = run_semgrep(save_dir, rule) + + if semgrep_status != 0: + click.echo(f"\n[ ERROR ] Semgrep 실행 실패 (리턴 코드: {semgrep_status})\n") + + try: + err_json = json.loads(semgrep_output or semgrep_error) + click.echo("[ Semgrep 에러 내용 ]") + for err in err_json.get("errors", []): + click.echo(f"- {err.get('message')} (코드: {err.get('code')})") + + except json.JSONDecodeError: + click.echo("에러 메시지 JSON 파싱 실패 : ") + click.echo(semgrep_error or semgrep_output) + + return + + click.echo("Semgrep 분석 완료!\n\n") + + try: + with open(semgrep_output, 'r', encoding='utf-8') as f: + results_json = json.load(f) + with open(semgrep_output, 'w', encoding='utf-8') as f: + json.dump(results_json, f, indent=4, ensure_ascii=False) + click.echo(f"Semgrep 결과가 '{semgrep_output}'에 저장되었습니다.") + + except (json.JSONDecodeError, OSError) as e: + click.echo(f"[ ERROR ] Semgrep 결과 파일 저장 중 문제 발생: {e}") if preprocess_semgrep: - output_json_path = preprocess_semgrep_results(semgrep_input, semgrep_output) - print(f"전처리 완료된 JSON 파일이 저장되었습니다 : {output_json_path}") + output_json_path = preprocess_semgrep_results(semgrep_output, llm_input) + if output_json_path: + click.echo(f"전처리 완료된 JSON 파일이 '{output_json_path}'에 저장되었습니다.") + else: + click.echo("[ ERROR ] 전처리 실패") if __name__ == '__main__': - main() + main() \ No newline at end of file From 850270e3308365e8a5746ae6100df0954fde9f5b Mon Sep 17 00:00:00 2001 From: inyeongjang <726jang@gmail.com> Date: Thu, 29 May 2025 04:47:02 +0900 Subject: [PATCH 024/297] =?UTF-8?q?Fix:=20Semgrep=20=EC=98=88=EC=99=B8=20?= =?UTF-8?q?=EB=B0=9C=EC=83=9D=20=EC=8B=9C=EC=97=90=EB=8F=84=20=EC=B6=9C?= =?UTF-8?q?=EB=A0=A5=20=EA=B2=B0=EA=B3=BC=20=ED=8C=8C=EC=9D=BC=20=EC=A0=80?= =?UTF-8?q?=EC=9E=A5=EB=90=98=EB=8F=84=EB=A1=9D=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/autofic_core/sast.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/autofic_core/sast.py b/src/autofic_core/sast.py index 9415753..775e5ac 100644 --- a/src/autofic_core/sast.py +++ b/src/autofic_core/sast.py @@ -13,11 +13,11 @@ def run_semgrep(repo_path: str, rule: str, output_json: str = "semgrep_output.js try: completed = subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8', check=True) - with open(output_json, 'w', encoding='utf-8') as f: f.write(completed.stdout) - return output_json, completed.stderr, completed.returncode except subprocess.CalledProcessError as err: - return err.stdout, err.stderr, err.returncode \ No newline at end of file + with open(output_json, 'w', encoding='utf-8') as f: + f.write(err.stdout or err.stderr or "") + return output_json, err.stderr, err.returncode \ No newline at end of file From 21377e184d0f24b1aa50eb1e1142e01b45457ec4 Mon Sep 17 00:00:00 2001 From: inyeongjang <726jang@gmail.com> Date: Thu, 29 May 2025 04:49:04 +0900 Subject: [PATCH 025/297] =?UTF-8?q?Update:=20Semgrep=20=EC=A0=84=EC=B2=98?= =?UTF-8?q?=EB=A6=AC=20=EB=A1=9C=EC=A7=81=20=EA=B0=9C=EC=84=A0=20=EB=B0=8F?= =?UTF-8?q?=20LLM=20=EC=9E=85=EB=A0=A5=20=EC=A0=95=EB=B3=B4=20=EC=B6=94?= =?UTF-8?q?=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/autofic_core/semgrep_preprocessor.py | 52 +++++++++++++++++------- 1 file changed, 38 insertions(+), 14 deletions(-) diff --git a/src/autofic_core/semgrep_preprocessor.py b/src/autofic_core/semgrep_preprocessor.py index 0551cb8..1cc70b5 100644 --- a/src/autofic_core/semgrep_preprocessor.py +++ b/src/autofic_core/semgrep_preprocessor.py @@ -1,32 +1,56 @@ import json from pathlib import Path -def preprocess_semgrep_results(input_json_path: str, output_json_path: str, base_dir: str = "../.."): - with open(input_json_path, 'r', encoding='utf-8') as f: - results = json.load(f) +def preprocess_semgrep_results(input_json_path: str, output_json_path: str, base_dir: str = "./"): + try: + with open(input_json_path, 'r', encoding='utf-8') as f: + results = json.load(f) + except (OSError, json.JSONDecodeError) as e: + print(f"[입력 파일 오류] {e}") + return None + base_dir = Path(base_dir).resolve() processed = [] for idx, result in enumerate(results.get("results", [])): - file_path = Path(base_dir) / result.get("path", "") + raw_path = result.get("path", "") + file_path = (base_dir / raw_path).resolve() + start_line = result.get("start", {}).get("line", None) end_line = result.get("end", {}).get("line", None) code_snippet = "" - if file_path.exists() and start_line and end_line: - with open(file_path, 'r', encoding='utf-8') as src_file: - lines = src_file.readlines() - code_snippet = "".join(lines[start_line-1:end_line]) + + if file_path.exists() and isinstance(start_line, int) and isinstance(end_line, int): + try: + with open(file_path, 'r', encoding='utf-8') as src_file: + lines = src_file.readlines() + code_snippet = "".join(lines[start_line-1:end_line]) + except Exception as e: + print(f"[파일 읽기 실패] {file_path} - {e}") + else: + print(f"[코드 추출 실패] {file_path}, lines {start_line}-{end_line}") + + extra = result.get("extra", {}) + metadata = extra.get("metadata", {}) processed.append({ - "instruction": "Refactor the code below to fix the security vulnerability and include a brief remediation guide.", + "Instruction": "Refactor the code below to fix the security vulnerability and include a brief remediation guide.", "input": code_snippet.strip(), "output": "", - "idx": idx + "idx": idx, + "message": extra.get("message", ""), + "vulnerability_class": metadata.get("vulnerability_class", []), + "cwe": metadata.get("cwe", []), + "severity": extra.get("severity", ""), + "references": metadata.get("references", []) }) - with open(output_json_path, 'w', encoding='utf-8') as f: - json.dump(processed, f, indent=4, ensure_ascii=False) + try: + with open(output_json_path, 'w', encoding='utf-8') as f: + json.dump(processed, f, indent=4, ensure_ascii=False) + except Exception as e: + print(f"[결과 저장 실패] {e}") + return None - return output_json_path - \ No newline at end of file + return output_json_path \ No newline at end of file From 9297f174de0260fa857a4a5d8252c47d5b52eee9 Mon Sep 17 00:00:00 2001 From: soonnae Date: Thu, 29 May 2025 10:19:57 +0900 Subject: [PATCH 026/297] =?UTF-8?q?refactor:=20downloader.py=20=EA=B8=B0?= =?UTF-8?q?=EB=8A=A5=EB=A7=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/autofic_core/downloader.py | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/src/autofic_core/downloader.py b/src/autofic_core/downloader.py index 80fc3c0..4fb4532 100644 --- a/src/autofic_core/downloader.py +++ b/src/autofic_core/downloader.py @@ -1,7 +1,8 @@ import os import requests -def download_files(js_files, save_dir="downloaded_repo", silent=False): +def download_files(js_files, save_dir="downloaded_repo"): + results = [] for file in js_files: path = file["path"] @@ -10,11 +11,18 @@ def download_files(js_files, save_dir="downloaded_repo", silent=False): os.makedirs(os.path.dirname(local_path), exist_ok=True) + if os.path.exists(local_path): + results.append({"path": path, "status": "skipped"}) + continue + try: response = requests.get(url) + response.raise_for_status() + with open(local_path, "wb") as f: f.write(response.content) - if not silent: - print(f"{path} 다운로드 완료") + results.append({"path": path, "status": "success"}) except Exception as e: - print(f"{path} 다운로드 실패: {e}") + results.append({"path": path, "status": "fail", "error": str(e)}) + + return results From f3ca34eef1a806e2df86b87c2c2d10d4e7256d96 Mon Sep 17 00:00:00 2001 From: soonnae Date: Thu, 29 May 2025 10:29:08 +0900 Subject: [PATCH 027/297] =?UTF-8?q?refactor:=20cli.py=20=EC=9D=B8=ED=84=B0?= =?UTF-8?q?=ED=8E=98=EC=9D=B4=EC=8A=A4=EB=A7=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/autofic_core/cli.py | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/src/autofic_core/cli.py b/src/autofic_core/cli.py index 7092321..c399db8 100644 --- a/src/autofic_core/cli.py +++ b/src/autofic_core/cli.py @@ -10,7 +10,6 @@ @click.option('--save-dir', default="downloaded_repo", help="저장할 디렉토리 경로") @click.option('--sast', is_flag=True, help='SAST 분석 수행 여부') @click.option('--rule', default='p/javascript', help='Semgrep 규칙') - def main(repo, silent, save_dir, sast, rule): click.echo(f"Analyzing repo: {repo}") @@ -25,8 +24,17 @@ def main(repo, silent, save_dir, sast, rule): for file in files: print(f"{file['path']} -> {file['download_url']}") - download_files(js_files=files, save_dir=save_dir, silent=silent) - + results = download_files(js_files=files, save_dir=save_dir, silent=silent) + + if not silent: + for r in results: + if r["status"] == "success": + print(f"{r['path']} 다운로드 완료") + elif r["status"] == "skipped": + print(f"{r['path']} 이미 존재함 - 건너뜀") + else: + print(f"{r['path']} 다운로드 실패: {r['error']}") + if sast: click.echo("\nSemgrep 분석 시작!") click.echo("Semgrep 분석 진행 중...") From f3034a919de9e1651c65bb3b321fbb88507a4fa0 Mon Sep 17 00:00:00 2001 From: soonnae Date: Thu, 29 May 2025 11:35:43 +0900 Subject: [PATCH 028/297] =?UTF-8?q?feat:=20download=5Ffiles=20=ED=95=A8?= =?UTF-8?q?=EC=88=98=EC=97=90=20silent=20=EC=98=B5=EC=85=98=20=EC=B6=94?= =?UTF-8?q?=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/autofic_core/downloader.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/autofic_core/downloader.py b/src/autofic_core/downloader.py index 4fb4532..2f4bd5d 100644 --- a/src/autofic_core/downloader.py +++ b/src/autofic_core/downloader.py @@ -1,7 +1,7 @@ import os import requests -def download_files(js_files, save_dir="downloaded_repo"): +def download_files(js_files, save_dir="downloaded_repo", silent=False): results = [] for file in js_files: From bee81b25391879954c0d221323b51d7efb302ae2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=9D=80=EC=86=94?= Date: Thu, 29 May 2025 13:51:44 +0900 Subject: [PATCH 029/297] Refactor: delete or move output and meaningless text --- src/autofic_core/cli.py | 14 +++++--------- src/autofic_core/github_handler.py | 17 +---------------- 2 files changed, 6 insertions(+), 25 deletions(-) diff --git a/src/autofic_core/cli.py b/src/autofic_core/cli.py index ba7f1b8..73cf18d 100644 --- a/src/autofic_core/cli.py +++ b/src/autofic_core/cli.py @@ -3,21 +3,17 @@ @click.command() @click.option('--repo', help='GitHub repository URL') -@click.option('--silent', is_flag=True, help="결과 출력 없이 조용히 실행") -def main(repo, silent): +def main(repo): click.echo(f"Analyzing repo: {repo}") - files = get_repo_files(repo, silent=silent) + click.echo("파일 탐색 시작 ...") + files = get_repo_files(repo) # 파일 목록 출력 예시 if not files: - click.echo("JS 파일을 찾지 못했습니다. 저장소 구조 또는 필터 조건을 확인하세요.") + click.echo("JS 파일을 찾지 못했습니다. Github 연결이나 저장소를 확인하세요.") - click.echo(f"JS 파일 {len(files)}개를 찾았습니다:") - - if not silent: - for file in files: - click.echo(f"{file['path']} -> {file['download_url']}") + click.echo(f"JS 파일 {len(files)}개를 찾았습니다!") if __name__ == '__main__': main() \ No newline at end of file diff --git a/src/autofic_core/github_handler.py b/src/autofic_core/github_handler.py index a736d84..4a7d189 100644 --- a/src/autofic_core/github_handler.py +++ b/src/autofic_core/github_handler.py @@ -15,40 +15,27 @@ def parse_repo_url(repo_url): repo_name = repo_name[:-4] return owner, repo_name -def get_repo_files(repo_url, file_extensions=(".js", ".mjs", ".jsx", ".ts"), silent=False): +def get_repo_files(repo_url, file_extensions=(".js", ".mjs", ".jsx", ".ts")): token = os.getenv("GITHUB_TOKEN") if not token: raise ValueError("GITHUB_TOKEN이 .env에 없습니다.") - print("GitHub API 인증 시도 중") - try: g = Github(token) - user = g.get_user() - print(f"인증 성공! 연결된 계정: {user.login}") except Exception as e: - print("GitHub 인증 실패:", e) return [] try: owner, repo_name = parse_repo_url(repo_url) repo = g.get_repo(f"{owner}/{repo_name}") - print(f"저장소: {repo.full_name} (기본 브랜치: {repo.default_branch})") except Exception as e: - print("저장소 불러오기 실패:", e) return [] - target_exts = (".js", ".mjs", ".jsx", ".ts") - js_files = [] contents = repo.get_contents("") - print("파일 탐색 시작...") - while contents: file_content = contents.pop(0) - if not silent: - print(f"탐색 중: {file_content.path} ({file_content.type})") if file_content.type == "dir": contents.extend(repo.get_contents(file_content.path)) elif file_content.name.endswith(file_extensions) and file_content.download_url: @@ -56,7 +43,5 @@ def get_repo_files(repo_url, file_extensions=(".js", ".mjs", ".jsx", ".ts"), sil "path": file_content.path, "download_url": file_content.download_url }) - if not silent: - print(f"발견: {file_content.path}") return js_files From c724f1e8ac81536f3f41b6917f94da5785903abf Mon Sep 17 00:00:00 2001 From: inyeongjang <726jang@gmail.com> Date: Thu, 29 May 2025 15:16:14 +0900 Subject: [PATCH 030/297] =?UTF-8?q?Remove:=20--silent=20=EC=98=B5=EC=85=98?= =?UTF-8?q?=20=EC=A0=9C=EA=B1=B0=20=EB=B0=8F=20=EA=B4=80=EB=A0=A8=20?= =?UTF-8?q?=EB=A1=9C=EC=A7=81=20=EC=A0=95=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/autofic_core/cli.py | 17 ++++++++--------- src/autofic_core/downloader.py | 2 +- 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/src/autofic_core/cli.py b/src/autofic_core/cli.py index 595e8ed..161df3c 100644 --- a/src/autofic_core/cli.py +++ b/src/autofic_core/cli.py @@ -21,16 +21,15 @@ def main(repo, save_dir, sast, rule): click.echo(f"JS 파일 {len(files)}개를 찾았습니다!") - results = download_files(js_files=files, save_dir=save_dir, silent=silent) + results = download_files(js_files=files, save_dir=save_dir) - if not silent: - for r in results: - if r["status"] == "success": - print(f"{r['path']} 다운로드 완료") - elif r["status"] == "skipped": - print(f"{r['path']} 이미 존재함 - 건너뜀") - else: - print(f"{r['path']} 다운로드 실패: {r['error']}") + for r in results: + if r["status"] == "success": + print(f"{r['path']} 다운로드 완료") + elif r["status"] == "skipped": + print(f"{r['path']} 이미 존재함 - 건너뜀") + else: + print(f"{r['path']} 다운로드 실패: {r['error']}") if sast: click.echo("\nSemgrep 분석 시작!") diff --git a/src/autofic_core/downloader.py b/src/autofic_core/downloader.py index 2f4bd5d..4fb4532 100644 --- a/src/autofic_core/downloader.py +++ b/src/autofic_core/downloader.py @@ -1,7 +1,7 @@ import os import requests -def download_files(js_files, save_dir="downloaded_repo", silent=False): +def download_files(js_files, save_dir="downloaded_repo"): results = [] for file in js_files: From f49dd851b34fa32f159a6354ae61162a48d3d50d Mon Sep 17 00:00:00 2001 From: inyeongjang <726jang@gmail.com> Date: Thu, 29 May 2025 20:10:19 +0900 Subject: [PATCH 031/297] =?UTF-8?q?Refactor:=20=ED=95=A8=EC=88=98=20?= =?UTF-8?q?=EB=B6=84=EB=A6=AC,=20=EC=A4=91=EB=B3=B5=20=EB=A1=9C=EC=A7=81?= =?UTF-8?q?=20=EA=B0=9C=EC=84=A0=20=EB=B0=8F=20=EC=98=88=EC=99=B8=20?= =?UTF-8?q?=EC=B2=98=EB=A6=AC=20=EA=B5=AC=EC=A1=B0=20=EA=B0=9C=EC=84=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/autofic_core/cli.py | 33 +++++------- src/autofic_core/sast.py | 10 ++-- src/autofic_core/semgrep_preprocessor.py | 67 +++++++++--------------- 3 files changed, 39 insertions(+), 71 deletions(-) diff --git a/src/autofic_core/cli.py b/src/autofic_core/cli.py index 8e66ea0..523d545 100644 --- a/src/autofic_core/cli.py +++ b/src/autofic_core/cli.py @@ -2,8 +2,8 @@ import json from autofic_core.github_handler import get_repo_files from autofic_core.downloader import download_files -from autofic_core.semgrep_preprocessor import preprocess_semgrep_results from autofic_core.sast import run_semgrep +from autofic_core.semgrep_preprocessor import preprocess_semgrep_results, save_json_file, read_json_file @click.command() @click.option('--repo', help='GitHub repository URL') @@ -11,10 +11,10 @@ @click.option('--sast', is_flag=True, help='SAST 분석 수행 여부') @click.option('--rule', default='p/javascript', help='Semgrep 규칙') @click.option('--preprocess-semgrep', is_flag=True, help="Semgrep 결과 전처리 수행") -@click.option('--semgrep-output', default="semgrep_output.json", help="Semgrep 원본 결과 경로") +@click.option('--semgrep-result', default="semgrep_result.json", help="Semgrep 원본 결과 경로") @click.option('--llm-input', default="llm_input.json", help="LLM 입력용 변환 결과 저장 경로") -def main(repo, silent, save_dir, sast, rule, preprocess_semgrep, semgrep_output, llm_input): +def main(repo, save_dir, sast, rule, preprocess_semgrep, semgrep_result, llm_input): click.echo(f"Analyzing repo: {repo}") click.echo("파일 탐색 시작 ...") @@ -54,25 +54,16 @@ def main(repo, silent, save_dir, sast, rule, preprocess_semgrep, semgrep_output, click.echo(semgrep_error or semgrep_output) return - - click.echo("Semgrep 분석 완료!\n\n") - - try: - with open(semgrep_output, 'r', encoding='utf-8') as f: - results_json = json.load(f) - with open(semgrep_output, 'w', encoding='utf-8') as f: - json.dump(results_json, f, indent=4, ensure_ascii=False) - click.echo(f"Semgrep 결과가 '{semgrep_output}'에 저장되었습니다.") - - except (json.JSONDecodeError, OSError) as e: - click.echo(f"[ ERROR ] Semgrep 결과 파일 저장 중 문제 발생: {e}") - + + save_json_file(json.loads(semgrep_output), semgrep_result) + click.echo(f"Semgrep 분석 완료! 결과가 '{semgrep_result}'에 저장되었습니다.") + if preprocess_semgrep: - output_json_path = preprocess_semgrep_results(semgrep_output, llm_input) - if output_json_path: - click.echo(f"전처리 완료된 JSON 파일이 '{output_json_path}'에 저장되었습니다.") - else: - click.echo("[ ERROR ] 전처리 실패") + try: + output_json_path = preprocess_semgrep_results(semgrep_result, llm_input) + click.echo(f"전처리 완료: '{output_json_path}'에 저장되었습니다.") + except Exception as e: + click.echo(f"[ERROR] 전처리 실패: {e}") if __name__ == '__main__': main() \ No newline at end of file diff --git a/src/autofic_core/sast.py b/src/autofic_core/sast.py index 775e5ac..2bba104 100644 --- a/src/autofic_core/sast.py +++ b/src/autofic_core/sast.py @@ -1,6 +1,6 @@ import subprocess -def run_semgrep(repo_path: str, rule: str, output_json: str = "semgrep_output.json"): +def run_semgrep(repo_path: str, rule: str): cmd = [ "semgrep", "--config", rule, @@ -13,11 +13,7 @@ def run_semgrep(repo_path: str, rule: str, output_json: str = "semgrep_output.js try: completed = subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8', check=True) - with open(output_json, 'w', encoding='utf-8') as f: - f.write(completed.stdout) - return output_json, completed.stderr, completed.returncode + return completed.stdout, completed.stderr, completed.returncode except subprocess.CalledProcessError as err: - with open(output_json, 'w', encoding='utf-8') as f: - f.write(err.stdout or err.stderr or "") - return output_json, err.stderr, err.returncode \ No newline at end of file + return err.stdout, err.stderr, err.returncode \ No newline at end of file diff --git a/src/autofic_core/semgrep_preprocessor.py b/src/autofic_core/semgrep_preprocessor.py index 1cc70b5..4f714b2 100644 --- a/src/autofic_core/semgrep_preprocessor.py +++ b/src/autofic_core/semgrep_preprocessor.py @@ -1,56 +1,37 @@ import json from pathlib import Path -def preprocess_semgrep_results(input_json_path: str, output_json_path: str, base_dir: str = "./"): - try: - with open(input_json_path, 'r', encoding='utf-8') as f: - results = json.load(f) - except (OSError, json.JSONDecodeError) as e: - print(f"[입력 파일 오류] {e}") - return None +def read_json_file(path: str) -> dict: + with open(path, 'r', encoding='utf-8') as f: + return json.load(f) - base_dir = Path(base_dir).resolve() - processed = [] - - for idx, result in enumerate(results.get("results", [])): - raw_path = result.get("path", "") - file_path = (base_dir / raw_path).resolve() - - start_line = result.get("start", {}).get("line", None) - end_line = result.get("end", {}).get("line", None) - - code_snippet = "" +def save_json_file(data: dict, path: str) -> None: + with open(path, 'w', encoding='utf-8') as f: + json.dump(data, f, indent=4, ensure_ascii=False) - if file_path.exists() and isinstance(start_line, int) and isinstance(end_line, int): - try: - with open(file_path, 'r', encoding='utf-8') as src_file: - lines = src_file.readlines() - code_snippet = "".join(lines[start_line-1:end_line]) - except Exception as e: - print(f"[파일 읽기 실패] {file_path} - {e}") - else: - print(f"[코드 추출 실패] {file_path}, lines {start_line}-{end_line}") +def extract_code_snippet(file_path: Path, start: int, end: int) -> str: + lines = file_path.read_text(encoding='utf-8').splitlines() + return "\n".join(lines[start-1:end]) +def preprocess_semgrep_results(input_json_path: str, output_json_path: str, base_dir: str = ".") -> str: + results = read_json_file(input_json_path) + base_dir = Path(base_dir).resolve() + processed = [] + for idx, result in enumerate(results.get("results", [])): + path = base_dir / result.get("path", "") + snippet = extract_code_snippet(path, result["start"]["line"], result["end"]["line"]) extra = result.get("extra", {}) - metadata = extra.get("metadata", {}) - + meta = extra.get("metadata", {}) processed.append({ - "Instruction": "Refactor the code below to fix the security vulnerability and include a brief remediation guide.", - "input": code_snippet.strip(), + "instruction": "Refactor the code below to fix the security vulnerability and include a brief remediation guide.", + "input": snippet.strip(), "output": "", - "idx": idx, + "idx": idx, "message": extra.get("message", ""), - "vulnerability_class": metadata.get("vulnerability_class", []), - "cwe": metadata.get("cwe", []), + "vulnerability_class": meta.get("vulnerability_class", []), + "cwe": meta.get("cwe", []), "severity": extra.get("severity", ""), - "references": metadata.get("references", []) + "references": meta.get("references", []) }) - - try: - with open(output_json_path, 'w', encoding='utf-8') as f: - json.dump(processed, f, indent=4, ensure_ascii=False) - except Exception as e: - print(f"[결과 저장 실패] {e}") - return None - + save_json_file(processed, output_json_path) return output_json_path \ No newline at end of file From 1a292f14295fa9daf09d52112885d5a84db50603 Mon Sep 17 00:00:00 2001 From: inyeongjang <726jang@gmail.com> Date: Thu, 29 May 2025 21:28:36 +0900 Subject: [PATCH 032/297] =?UTF-8?q?Refactor:=20=EB=B6=88=ED=95=84=EC=9A=94?= =?UTF-8?q?=ED=95=9C=20import=20=EC=A0=9C=EA=B1=B0=20=EB=B0=8F=20=EC=B6=9C?= =?UTF-8?q?=EB=A0=A5=20=EB=B0=A9=EC=8B=9D=20click.echo=EB=A1=9C=20?= =?UTF-8?q?=ED=86=B5=EC=9D=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/autofic_core/cli.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/autofic_core/cli.py b/src/autofic_core/cli.py index 523d545..c457b36 100644 --- a/src/autofic_core/cli.py +++ b/src/autofic_core/cli.py @@ -3,7 +3,7 @@ from autofic_core.github_handler import get_repo_files from autofic_core.downloader import download_files from autofic_core.sast import run_semgrep -from autofic_core.semgrep_preprocessor import preprocess_semgrep_results, save_json_file, read_json_file +from autofic_core.semgrep_preprocessor import preprocess_semgrep_results, save_json_file @click.command() @click.option('--repo', help='GitHub repository URL') @@ -29,11 +29,11 @@ def main(repo, save_dir, sast, rule, preprocess_semgrep, semgrep_result, llm_inp for r in results: if r["status"] == "success": - print(f"{r['path']} 다운로드 완료") + click.echo(f"{r['path']} 다운로드 완료") elif r["status"] == "skipped": - print(f"{r['path']} 이미 존재함 - 건너뜀") + click.echo(f"{r['path']} 이미 존재함 - 건너뜀") else: - print(f"{r['path']} 다운로드 실패: {r['error']}") + click.echo(f"{r['path']} 다운로드 실패: {r['error']}") if sast: click.echo("\nSemgrep 분석 시작!") From 323be72884f76b8d12c87ecb4faf7c0e9bbbcf71 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=9D=80=EC=86=94?= Date: Thu, 29 May 2025 23:43:21 +0900 Subject: [PATCH 033/297] Add: progress bar --- downloaded_folder/app.js | 96 + downloaded_folder/config.js | 48 + downloaded_folder/dummy.js | 68 + downloaded_folder/model/auth.js | 12 + downloaded_folder/model/init_db.js | 65 + downloaded_folder/model/products.js | 60 + downloaded_folder/public/js/bootstrap.js | 2363 ++++++++++++++++++ downloaded_folder/public/js/bootstrap.min.js | 7 + downloaded_folder/public/js/freewall.js | 1272 ++++++++++ downloaded_folder/public/js/jquery.js | 4 + downloaded_folder/routes/login.js | 53 + downloaded_folder/routes/login_check.js | 10 + downloaded_folder/routes/products.js | 149 ++ llm_input.json | 138 + semgrep_result.json | 503 ++++ src/autofic_core/cli.py | 16 +- src/autofic_core/downloader.py | 48 +- src/autofic_core/github_handler.py | 37 +- 18 files changed, 4921 insertions(+), 28 deletions(-) create mode 100644 downloaded_folder/app.js create mode 100644 downloaded_folder/config.js create mode 100644 downloaded_folder/dummy.js create mode 100644 downloaded_folder/model/auth.js create mode 100644 downloaded_folder/model/init_db.js create mode 100644 downloaded_folder/model/products.js create mode 100644 downloaded_folder/public/js/bootstrap.js create mode 100644 downloaded_folder/public/js/bootstrap.min.js create mode 100644 downloaded_folder/public/js/freewall.js create mode 100644 downloaded_folder/public/js/jquery.js create mode 100644 downloaded_folder/routes/login.js create mode 100644 downloaded_folder/routes/login_check.js create mode 100644 downloaded_folder/routes/products.js create mode 100644 llm_input.json create mode 100644 semgrep_result.json diff --git a/downloaded_folder/app.js b/downloaded_folder/app.js new file mode 100644 index 0000000..08cddf2 --- /dev/null +++ b/downloaded_folder/app.js @@ -0,0 +1,96 @@ +var express = require('express'); +var session = require('express-session') +var engine = require('ejs-locals'); +var path = require('path'); +var favicon = require('serve-favicon'); +var fs = require("fs"); +var logger = require('morgan'); +var cookieParser = require('cookie-parser'); +var bodyParser = require('body-parser'); +var log4js = require("log4js"); + +var init_db = require('./model/init_db'); +var login = require('./routes/login'); +var products = require('./routes/products'); + +var app = express(); + +// config second logger +log4js.loadAppender('file'); +//log4js.addAppender(log4js.appenders.console()); +log4js.addAppender(log4js.appenders.file('app-custom.log'), 'vnode'); + +var logger4js = log4js.getLogger('vnode'); +logger4js.setLevel('INFO'); + +var accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log')) + +/* + * Template engine + */ +app.engine('ejs', engine); + +app.set('views', path.join(__dirname, 'views')); +app.set('view engine', 'ejs'); + +// uncomment after placing your favicon in /public +app.use(logger('combined', {stream: accessLogStream})); +app.use(bodyParser()); +app.use(bodyParser.json()); +app.use(bodyParser.urlencoded({ extended: true })); +app.use(cookieParser()); +app.use(express.static(path.join(__dirname, 'public'))); +app.use(session({ + secret: 'ñasddfilhpaf78h78032h780g780fg780asg780dsbovncubuyvqy', + cookie: { + secure: false, + maxAge: 99999999999 + } +})); + +/* + * Routes config + */ +app.use('', products); +app.use('', login); + + +// catch 404 and forward to error handler +app.use(function(req, res, next) { + var err = new Error('Not Found'); + err.status = 404; + next(err); +}); + +/* + * Debug functions and error handlers + */ +if (app.get('env') === 'development') { + app.use(function(err, req, res, next) { + res.status(err.status || 500); + res.render('error', { + message: err.message, + error: err + }); + }); +} + +// production error handler +// no stacktraces leaked to user +app.use(function(err, req, res, next) { + res.status(err.status || 500); + res.render('error', { + message: err.message, + error: {} + }); +}); + +/* + * Create database + */ +logger4js.info("Building database") +// logger.info(("Building database"); + +init_db(); + +module.exports = app; diff --git a/downloaded_folder/config.js b/downloaded_folder/config.js new file mode 100644 index 0000000..849348b --- /dev/null +++ b/downloaded_folder/config.js @@ -0,0 +1,48 @@ +var config_local = { + // Customer module configs + "db": { + "server": "postgres://postgres:postgres@127.0.0.1", + "database": "vulnerablenode" + } +} + +var config_devel = { + // Customer module configs + "db": { + "server": "postgres://postgres:postgres@10.211.55.70", + "database": "vulnerablenode" + } +} + +var config_docker = { + // Customer module configs + "db": { + "server": "postgres://postgres:postgres@postgres_db", + "database": "vulnerablenode" + } +} + +// Select correct config +var config = null; + +switch (process.env.STAGE){ + case "DOCKER": + config = config_docker; + break; + + case "LOCAL": + config = config_local; + break; + + case "DEVEL": + config = config_devel; + break; + + default: + config = config_devel; +} + +// Build connection string +config.db.connectionString = config.db.server + "/" + config.db.database + +module.exports = config; \ No newline at end of file diff --git a/downloaded_folder/dummy.js b/downloaded_folder/dummy.js new file mode 100644 index 0000000..a55ab28 --- /dev/null +++ b/downloaded_folder/dummy.js @@ -0,0 +1,68 @@ +// This file contains dummy information data + +var dummy_info = { + // Customer module configs + "users": [ + { + "username": "admin", + "password": "admin" + }, + { + "username": "roberto", + "password": "asdfpiuw981" + } + ], + + "products": [ + { + "name": "My public privacy", + "description": "Grant privacy in public to watch your favorite programs", + "price": parseInt(Math.random() * 100), + "image": "product_1.jpg" + }, + { + "name": "The USB rocket", + "description": "Be happy with your USB rocket. Functionality: none. Usability: none. The best choice!", + "price": parseInt(Math.random() * 100), + "image": "product_2.jpg" + }, + { + "name": "Walker watermelons", + "description": "Take a walk your watermelons and make it feel comfortable.", + "price": parseInt(Math.random() * 100), + "image": "product_3.jpg" + }, + { + "name": "Potty Putter", + "description": "The game for the avid golfers!", + "price": 20, + "image": "product_4.jpg" + }, + { + "name": "Phone Fingers", + "description": "Phone fingers work perfectly well with iPhone's touch screen and prevent fingerprints and smudges", + "price": 3, + "image": "product_5.jpg" + }, + { + "name": "Daddle", + "description": "Be the best father with Daddle: dad's saddle for horsing around.", + "price": parseInt(Math.random() * 100), + "image": "product_6.jpg" + }, + { + "name": "HD Vision", + "description": "Reality is not enough for you? Improve your live with the HD vision glasses.", + "price": parseInt(Math.random() * 100), + "image": "product_7.jpg" + }, + { + "name": "Hangs free", + "description": "Say goodbye to the cumbersome cables with the authentic hands free.", + "price": parseInt(Math.random() * 100), + "image": "product_8.jpg" + } + ] +} + +module.exports = dummy_info; \ No newline at end of file diff --git a/downloaded_folder/model/auth.js b/downloaded_folder/model/auth.js new file mode 100644 index 0000000..1d4c221 --- /dev/null +++ b/downloaded_folder/model/auth.js @@ -0,0 +1,12 @@ +var config = require("../config"), + pgp = require('pg-promise')(); + +function do_auth(username, password) { + var db = pgp(config.db.connectionString); + + var q = "SELECT * FROM users WHERE name = '" + username + "' AND password ='" + password + "';"; + + return db.one(q); +} + +module.exports = do_auth; \ No newline at end of file diff --git a/downloaded_folder/model/init_db.js b/downloaded_folder/model/init_db.js new file mode 100644 index 0000000..5bab5b9 --- /dev/null +++ b/downloaded_folder/model/init_db.js @@ -0,0 +1,65 @@ +var config = require("../config"); +var dummy = require("../dummy"); +var pgp = require('pg-promise')(); + +/* + THIS FILE CREATES AND POPULATE THE DATABASE + */ + +function init_db() { + + // Create tables and dummy data + var db = pgp(config.db.connectionString); + + // Create init tables + db.one('CREATE TABLE users(name VARCHAR(100) PRIMARY KEY, password VARCHAR(50));') + .then(function () { + }) + .catch(function (err) { + + // Insert dummy users + var users = dummy.users; + for (var i = 0; i < users.length; i ++) { + var u = users[i]; + db.one('INSERT INTO users(name, password) values($1, $2)', [u.username, u.password]) + .then(function () { + // success; + }) + .catch(function (err) { + }); + } + + }); + + db.one('CREATE TABLE products(id INTEGER PRIMARY KEY, name VARCHAR(100) not null, description TEXT not null, price INTEGER, image VARCHAR(500))') + .then(function () { + + }) + .catch(function (err) { + + + // Insert dummy products + var products = dummy.products; + for (var i = 0; i < products.length; i ++) { + var p = products[i]; + db.one('INSERT INTO products(id, name, description, price, image) values($1, $2, $3, $4, $5)', [i, p.name, p.description, p.price, p.image]) + .then(function () { + // success; + }) + .catch(function (err) { + }); + } + + }); + + db.one('CREATE TABLE purchases(id SERIAL PRIMARY KEY, product_id INTEGER not null, product_name VARCHAR(100) not null, user_name VARCHAR(100), mail VARCHAR(100) not null, address VARCHAR(100) not null, phone VARCHAR(40) not null, ship_date VARCHAR(100) not null, price INTEGER not null)') + .then(function () { + + }) + .catch(function (err) { + }); + + +} + +module.exports = init_db; \ No newline at end of file diff --git a/downloaded_folder/model/products.js b/downloaded_folder/model/products.js new file mode 100644 index 0000000..6df3f92 --- /dev/null +++ b/downloaded_folder/model/products.js @@ -0,0 +1,60 @@ +var config = require("../config"), + pgp = require('pg-promise')(), + db = pgp(config.db.connectionString); + +function list_products() { + + var q = "SELECT * FROM products;"; + + return db.many(q); +} + +function getProduct(product_id) { + + var q = "SELECT * FROM products WHERE id = '" + product_id + "';"; + + return db.one(q); +} + +function search(query) { + + var q = "SELECT * FROM products WHERE name ILIKE '%" + query + "%' OR description ILIKE '%" + query + "%';"; + + return db.many(q); + +} + +function purchase(cart) { + + var q = "INSERT INTO purchases(mail, product_name, user_name, product_id, address, phone, ship_date, price) VALUES('" + + cart.mail + "', '" + + cart.product_name + "', '" + + cart.username + "', '" + + cart.product_id + "', '" + + cart.address + "', '" + + cart.ship_date + "', '" + + cart.phone + "', '" + + cart.price + + "');"; + + return db.one(q); + +} + +function get_purcharsed(username) { + + var q = "SELECT * FROM purchases WHERE user_name = '" + username + "';"; + + return db.many(q); + +} + +var actions = { + "list": list_products, + "getProduct": getProduct, + "search": search, + "purchase": purchase, + "getPurchased": get_purcharsed +} + +module.exports = actions; diff --git a/downloaded_folder/public/js/bootstrap.js b/downloaded_folder/public/js/bootstrap.js new file mode 100644 index 0000000..01fbbcb --- /dev/null +++ b/downloaded_folder/public/js/bootstrap.js @@ -0,0 +1,2363 @@ +/*! + * Bootstrap v3.3.6 (http://getbootstrap.com) + * Copyright 2011-2015 Twitter, Inc. + * Licensed under the MIT license + */ + +if (typeof jQuery === 'undefined') { + throw new Error('Bootstrap\'s JavaScript requires jQuery') +} + ++function ($) { + 'use strict'; + var version = $.fn.jquery.split(' ')[0].split('.') + if ((version[0] < 2 && version[1] < 9) || (version[0] == 1 && version[1] == 9 && version[2] < 1) || (version[0] > 2)) { + throw new Error('Bootstrap\'s JavaScript requires jQuery version 1.9.1 or higher, but lower than version 3') + } +}(jQuery); + +/* ======================================================================== + * Bootstrap: transition.js v3.3.6 + * http://getbootstrap.com/javascript/#transitions + * ======================================================================== + * Copyright 2011-2015 Twitter, Inc. + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) + * ======================================================================== */ + + ++function ($) { + 'use strict'; + + // CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/) + // ============================================================ + + function transitionEnd() { + var el = document.createElement('bootstrap') + + var transEndEventNames = { + WebkitTransition : 'webkitTransitionEnd', + MozTransition : 'transitionend', + OTransition : 'oTransitionEnd otransitionend', + transition : 'transitionend' + } + + for (var name in transEndEventNames) { + if (el.style[name] !== undefined) { + return { end: transEndEventNames[name] } + } + } + + return false // explicit for ie8 ( ._.) + } + + // http://blog.alexmaccaw.com/css-transitions + $.fn.emulateTransitionEnd = function (duration) { + var called = false + var $el = this + $(this).one('bsTransitionEnd', function () { called = true }) + var callback = function () { if (!called) $($el).trigger($.support.transition.end) } + setTimeout(callback, duration) + return this + } + + $(function () { + $.support.transition = transitionEnd() + + if (!$.support.transition) return + + $.event.special.bsTransitionEnd = { + bindType: $.support.transition.end, + delegateType: $.support.transition.end, + handle: function (e) { + if ($(e.target).is(this)) return e.handleObj.handler.apply(this, arguments) + } + } + }) + +}(jQuery); + +/* ======================================================================== + * Bootstrap: alert.js v3.3.6 + * http://getbootstrap.com/javascript/#alerts + * ======================================================================== + * Copyright 2011-2015 Twitter, Inc. + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) + * ======================================================================== */ + + ++function ($) { + 'use strict'; + + // ALERT CLASS DEFINITION + // ====================== + + var dismiss = '[data-dismiss="alert"]' + var Alert = function (el) { + $(el).on('click', dismiss, this.close) + } + + Alert.VERSION = '3.3.6' + + Alert.TRANSITION_DURATION = 150 + + Alert.prototype.close = function (e) { + var $this = $(this) + var selector = $this.attr('data-target') + + if (!selector) { + selector = $this.attr('href') + selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 + } + + var $parent = $(selector) + + if (e) e.preventDefault() + + if (!$parent.length) { + $parent = $this.closest('.alert') + } + + $parent.trigger(e = $.Event('close.bs.alert')) + + if (e.isDefaultPrevented()) return + + $parent.removeClass('in') + + function removeElement() { + // detach from parent, fire event then clean up data + $parent.detach().trigger('closed.bs.alert').remove() + } + + $.support.transition && $parent.hasClass('fade') ? + $parent + .one('bsTransitionEnd', removeElement) + .emulateTransitionEnd(Alert.TRANSITION_DURATION) : + removeElement() + } + + + // ALERT PLUGIN DEFINITION + // ======================= + + function Plugin(option) { + return this.each(function () { + var $this = $(this) + var data = $this.data('bs.alert') + + if (!data) $this.data('bs.alert', (data = new Alert(this))) + if (typeof option == 'string') data[option].call($this) + }) + } + + var old = $.fn.alert + + $.fn.alert = Plugin + $.fn.alert.Constructor = Alert + + + // ALERT NO CONFLICT + // ================= + + $.fn.alert.noConflict = function () { + $.fn.alert = old + return this + } + + + // ALERT DATA-API + // ============== + + $(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close) + +}(jQuery); + +/* ======================================================================== + * Bootstrap: button.js v3.3.6 + * http://getbootstrap.com/javascript/#buttons + * ======================================================================== + * Copyright 2011-2015 Twitter, Inc. + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) + * ======================================================================== */ + + ++function ($) { + 'use strict'; + + // BUTTON PUBLIC CLASS DEFINITION + // ============================== + + var Button = function (element, options) { + this.$element = $(element) + this.options = $.extend({}, Button.DEFAULTS, options) + this.isLoading = false + } + + Button.VERSION = '3.3.6' + + Button.DEFAULTS = { + loadingText: 'loading...' + } + + Button.prototype.setState = function (state) { + var d = 'disabled' + var $el = this.$element + var val = $el.is('input') ? 'val' : 'html' + var data = $el.data() + + state += 'Text' + + if (data.resetText == null) $el.data('resetText', $el[val]()) + + // push to event loop to allow forms to submit + setTimeout($.proxy(function () { + $el[val](data[state] == null ? this.options[state] : data[state]) + + if (state == 'loadingText') { + this.isLoading = true + $el.addClass(d).attr(d, d) + } else if (this.isLoading) { + this.isLoading = false + $el.removeClass(d).removeAttr(d) + } + }, this), 0) + } + + Button.prototype.toggle = function () { + var changed = true + var $parent = this.$element.closest('[data-toggle="buttons"]') + + if ($parent.length) { + var $input = this.$element.find('input') + if ($input.prop('type') == 'radio') { + if ($input.prop('checked')) changed = false + $parent.find('.active').removeClass('active') + this.$element.addClass('active') + } else if ($input.prop('type') == 'checkbox') { + if (($input.prop('checked')) !== this.$element.hasClass('active')) changed = false + this.$element.toggleClass('active') + } + $input.prop('checked', this.$element.hasClass('active')) + if (changed) $input.trigger('change') + } else { + this.$element.attr('aria-pressed', !this.$element.hasClass('active')) + this.$element.toggleClass('active') + } + } + + + // BUTTON PLUGIN DEFINITION + // ======================== + + function Plugin(option) { + return this.each(function () { + var $this = $(this) + var data = $this.data('bs.button') + var options = typeof option == 'object' && option + + if (!data) $this.data('bs.button', (data = new Button(this, options))) + + if (option == 'toggle') data.toggle() + else if (option) data.setState(option) + }) + } + + var old = $.fn.button + + $.fn.button = Plugin + $.fn.button.Constructor = Button + + + // BUTTON NO CONFLICT + // ================== + + $.fn.button.noConflict = function () { + $.fn.button = old + return this + } + + + // BUTTON DATA-API + // =============== + + $(document) + .on('click.bs.button.data-api', '[data-toggle^="button"]', function (e) { + var $btn = $(e.target) + if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn') + Plugin.call($btn, 'toggle') + if (!($(e.target).is('input[type="radio"]') || $(e.target).is('input[type="checkbox"]'))) e.preventDefault() + }) + .on('focus.bs.button.data-api blur.bs.button.data-api', '[data-toggle^="button"]', function (e) { + $(e.target).closest('.btn').toggleClass('focus', /^focus(in)?$/.test(e.type)) + }) + +}(jQuery); + +/* ======================================================================== + * Bootstrap: carousel.js v3.3.6 + * http://getbootstrap.com/javascript/#carousel + * ======================================================================== + * Copyright 2011-2015 Twitter, Inc. + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) + * ======================================================================== */ + + ++function ($) { + 'use strict'; + + // CAROUSEL CLASS DEFINITION + // ========================= + + var Carousel = function (element, options) { + this.$element = $(element) + this.$indicators = this.$element.find('.carousel-indicators') + this.options = options + this.paused = null + this.sliding = null + this.interval = null + this.$active = null + this.$items = null + + this.options.keyboard && this.$element.on('keydown.bs.carousel', $.proxy(this.keydown, this)) + + this.options.pause == 'hover' && !('ontouchstart' in document.documentElement) && this.$element + .on('mouseenter.bs.carousel', $.proxy(this.pause, this)) + .on('mouseleave.bs.carousel', $.proxy(this.cycle, this)) + } + + Carousel.VERSION = '3.3.6' + + Carousel.TRANSITION_DURATION = 600 + + Carousel.DEFAULTS = { + interval: 5000, + pause: 'hover', + wrap: true, + keyboard: true + } + + Carousel.prototype.keydown = function (e) { + if (/input|textarea/i.test(e.target.tagName)) return + switch (e.which) { + case 37: this.prev(); break + case 39: this.next(); break + default: return + } + + e.preventDefault() + } + + Carousel.prototype.cycle = function (e) { + e || (this.paused = false) + + this.interval && clearInterval(this.interval) + + this.options.interval + && !this.paused + && (this.interval = setInterval($.proxy(this.next, this), this.options.interval)) + + return this + } + + Carousel.prototype.getItemIndex = function (item) { + this.$items = item.parent().children('.item') + return this.$items.index(item || this.$active) + } + + Carousel.prototype.getItemForDirection = function (direction, active) { + var activeIndex = this.getItemIndex(active) + var willWrap = (direction == 'prev' && activeIndex === 0) + || (direction == 'next' && activeIndex == (this.$items.length - 1)) + if (willWrap && !this.options.wrap) return active + var delta = direction == 'prev' ? -1 : 1 + var itemIndex = (activeIndex + delta) % this.$items.length + return this.$items.eq(itemIndex) + } + + Carousel.prototype.to = function (pos) { + var that = this + var activeIndex = this.getItemIndex(this.$active = this.$element.find('.item.active')) + + if (pos > (this.$items.length - 1) || pos < 0) return + + if (this.sliding) return this.$element.one('slid.bs.carousel', function () { that.to(pos) }) // yes, "slid" + if (activeIndex == pos) return this.pause().cycle() + + return this.slide(pos > activeIndex ? 'next' : 'prev', this.$items.eq(pos)) + } + + Carousel.prototype.pause = function (e) { + e || (this.paused = true) + + if (this.$element.find('.next, .prev').length && $.support.transition) { + this.$element.trigger($.support.transition.end) + this.cycle(true) + } + + this.interval = clearInterval(this.interval) + + return this + } + + Carousel.prototype.next = function () { + if (this.sliding) return + return this.slide('next') + } + + Carousel.prototype.prev = function () { + if (this.sliding) return + return this.slide('prev') + } + + Carousel.prototype.slide = function (type, next) { + var $active = this.$element.find('.item.active') + var $next = next || this.getItemForDirection(type, $active) + var isCycling = this.interval + var direction = type == 'next' ? 'left' : 'right' + var that = this + + if ($next.hasClass('active')) return (this.sliding = false) + + var relatedTarget = $next[0] + var slideEvent = $.Event('slide.bs.carousel', { + relatedTarget: relatedTarget, + direction: direction + }) + this.$element.trigger(slideEvent) + if (slideEvent.isDefaultPrevented()) return + + this.sliding = true + + isCycling && this.pause() + + if (this.$indicators.length) { + this.$indicators.find('.active').removeClass('active') + var $nextIndicator = $(this.$indicators.children()[this.getItemIndex($next)]) + $nextIndicator && $nextIndicator.addClass('active') + } + + var slidEvent = $.Event('slid.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) // yes, "slid" + if ($.support.transition && this.$element.hasClass('slide')) { + $next.addClass(type) + $next[0].offsetWidth // force reflow + $active.addClass(direction) + $next.addClass(direction) + $active + .one('bsTransitionEnd', function () { + $next.removeClass([type, direction].join(' ')).addClass('active') + $active.removeClass(['active', direction].join(' ')) + that.sliding = false + setTimeout(function () { + that.$element.trigger(slidEvent) + }, 0) + }) + .emulateTransitionEnd(Carousel.TRANSITION_DURATION) + } else { + $active.removeClass('active') + $next.addClass('active') + this.sliding = false + this.$element.trigger(slidEvent) + } + + isCycling && this.cycle() + + return this + } + + + // CAROUSEL PLUGIN DEFINITION + // ========================== + + function Plugin(option) { + return this.each(function () { + var $this = $(this) + var data = $this.data('bs.carousel') + var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option) + var action = typeof option == 'string' ? option : options.slide + + if (!data) $this.data('bs.carousel', (data = new Carousel(this, options))) + if (typeof option == 'number') data.to(option) + else if (action) data[action]() + else if (options.interval) data.pause().cycle() + }) + } + + var old = $.fn.carousel + + $.fn.carousel = Plugin + $.fn.carousel.Constructor = Carousel + + + // CAROUSEL NO CONFLICT + // ==================== + + $.fn.carousel.noConflict = function () { + $.fn.carousel = old + return this + } + + + // CAROUSEL DATA-API + // ================= + + var clickHandler = function (e) { + var href + var $this = $(this) + var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) // strip for ie7 + if (!$target.hasClass('carousel')) return + var options = $.extend({}, $target.data(), $this.data()) + var slideIndex = $this.attr('data-slide-to') + if (slideIndex) options.interval = false + + Plugin.call($target, options) + + if (slideIndex) { + $target.data('bs.carousel').to(slideIndex) + } + + e.preventDefault() + } + + $(document) + .on('click.bs.carousel.data-api', '[data-slide]', clickHandler) + .on('click.bs.carousel.data-api', '[data-slide-to]', clickHandler) + + $(window).on('load', function () { + $('[data-ride="carousel"]').each(function () { + var $carousel = $(this) + Plugin.call($carousel, $carousel.data()) + }) + }) + +}(jQuery); + +/* ======================================================================== + * Bootstrap: collapse.js v3.3.6 + * http://getbootstrap.com/javascript/#collapse + * ======================================================================== + * Copyright 2011-2015 Twitter, Inc. + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) + * ======================================================================== */ + + ++function ($) { + 'use strict'; + + // COLLAPSE PUBLIC CLASS DEFINITION + // ================================ + + var Collapse = function (element, options) { + this.$element = $(element) + this.options = $.extend({}, Collapse.DEFAULTS, options) + this.$trigger = $('[data-toggle="collapse"][href="#' + element.id + '"],' + + '[data-toggle="collapse"][data-target="#' + element.id + '"]') + this.transitioning = null + + if (this.options.parent) { + this.$parent = this.getParent() + } else { + this.addAriaAndCollapsedClass(this.$element, this.$trigger) + } + + if (this.options.toggle) this.toggle() + } + + Collapse.VERSION = '3.3.6' + + Collapse.TRANSITION_DURATION = 350 + + Collapse.DEFAULTS = { + toggle: true + } + + Collapse.prototype.dimension = function () { + var hasWidth = this.$element.hasClass('width') + return hasWidth ? 'width' : 'height' + } + + Collapse.prototype.show = function () { + if (this.transitioning || this.$element.hasClass('in')) return + + var activesData + var actives = this.$parent && this.$parent.children('.panel').children('.in, .collapsing') + + if (actives && actives.length) { + activesData = actives.data('bs.collapse') + if (activesData && activesData.transitioning) return + } + + var startEvent = $.Event('show.bs.collapse') + this.$element.trigger(startEvent) + if (startEvent.isDefaultPrevented()) return + + if (actives && actives.length) { + Plugin.call(actives, 'hide') + activesData || actives.data('bs.collapse', null) + } + + var dimension = this.dimension() + + this.$element + .removeClass('collapse') + .addClass('collapsing')[dimension](0) + .attr('aria-expanded', true) + + this.$trigger + .removeClass('collapsed') + .attr('aria-expanded', true) + + this.transitioning = 1 + + var complete = function () { + this.$element + .removeClass('collapsing') + .addClass('collapse in')[dimension]('') + this.transitioning = 0 + this.$element + .trigger('shown.bs.collapse') + } + + if (!$.support.transition) return complete.call(this) + + var scrollSize = $.camelCase(['scroll', dimension].join('-')) + + this.$element + .one('bsTransitionEnd', $.proxy(complete, this)) + .emulateTransitionEnd(Collapse.TRANSITION_DURATION)[dimension](this.$element[0][scrollSize]) + } + + Collapse.prototype.hide = function () { + if (this.transitioning || !this.$element.hasClass('in')) return + + var startEvent = $.Event('hide.bs.collapse') + this.$element.trigger(startEvent) + if (startEvent.isDefaultPrevented()) return + + var dimension = this.dimension() + + this.$element[dimension](this.$element[dimension]())[0].offsetHeight + + this.$element + .addClass('collapsing') + .removeClass('collapse in') + .attr('aria-expanded', false) + + this.$trigger + .addClass('collapsed') + .attr('aria-expanded', false) + + this.transitioning = 1 + + var complete = function () { + this.transitioning = 0 + this.$element + .removeClass('collapsing') + .addClass('collapse') + .trigger('hidden.bs.collapse') + } + + if (!$.support.transition) return complete.call(this) + + this.$element + [dimension](0) + .one('bsTransitionEnd', $.proxy(complete, this)) + .emulateTransitionEnd(Collapse.TRANSITION_DURATION) + } + + Collapse.prototype.toggle = function () { + this[this.$element.hasClass('in') ? 'hide' : 'show']() + } + + Collapse.prototype.getParent = function () { + return $(this.options.parent) + .find('[data-toggle="collapse"][data-parent="' + this.options.parent + '"]') + .each($.proxy(function (i, element) { + var $element = $(element) + this.addAriaAndCollapsedClass(getTargetFromTrigger($element), $element) + }, this)) + .end() + } + + Collapse.prototype.addAriaAndCollapsedClass = function ($element, $trigger) { + var isOpen = $element.hasClass('in') + + $element.attr('aria-expanded', isOpen) + $trigger + .toggleClass('collapsed', !isOpen) + .attr('aria-expanded', isOpen) + } + + function getTargetFromTrigger($trigger) { + var href + var target = $trigger.attr('data-target') + || (href = $trigger.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') // strip for ie7 + + return $(target) + } + + + // COLLAPSE PLUGIN DEFINITION + // ========================== + + function Plugin(option) { + return this.each(function () { + var $this = $(this) + var data = $this.data('bs.collapse') + var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option) + + if (!data && options.toggle && /show|hide/.test(option)) options.toggle = false + if (!data) $this.data('bs.collapse', (data = new Collapse(this, options))) + if (typeof option == 'string') data[option]() + }) + } + + var old = $.fn.collapse + + $.fn.collapse = Plugin + $.fn.collapse.Constructor = Collapse + + + // COLLAPSE NO CONFLICT + // ==================== + + $.fn.collapse.noConflict = function () { + $.fn.collapse = old + return this + } + + + // COLLAPSE DATA-API + // ================= + + $(document).on('click.bs.collapse.data-api', '[data-toggle="collapse"]', function (e) { + var $this = $(this) + + if (!$this.attr('data-target')) e.preventDefault() + + var $target = getTargetFromTrigger($this) + var data = $target.data('bs.collapse') + var option = data ? 'toggle' : $this.data() + + Plugin.call($target, option) + }) + +}(jQuery); + +/* ======================================================================== + * Bootstrap: dropdown.js v3.3.6 + * http://getbootstrap.com/javascript/#dropdowns + * ======================================================================== + * Copyright 2011-2015 Twitter, Inc. + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) + * ======================================================================== */ + + ++function ($) { + 'use strict'; + + // DROPDOWN CLASS DEFINITION + // ========================= + + var backdrop = '.dropdown-backdrop' + var toggle = '[data-toggle="dropdown"]' + var Dropdown = function (element) { + $(element).on('click.bs.dropdown', this.toggle) + } + + Dropdown.VERSION = '3.3.6' + + function getParent($this) { + var selector = $this.attr('data-target') + + if (!selector) { + selector = $this.attr('href') + selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 + } + + var $parent = selector && $(selector) + + return $parent && $parent.length ? $parent : $this.parent() + } + + function clearMenus(e) { + if (e && e.which === 3) return + $(backdrop).remove() + $(toggle).each(function () { + var $this = $(this) + var $parent = getParent($this) + var relatedTarget = { relatedTarget: this } + + if (!$parent.hasClass('open')) return + + if (e && e.type == 'click' && /input|textarea/i.test(e.target.tagName) && $.contains($parent[0], e.target)) return + + $parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget)) + + if (e.isDefaultPrevented()) return + + $this.attr('aria-expanded', 'false') + $parent.removeClass('open').trigger($.Event('hidden.bs.dropdown', relatedTarget)) + }) + } + + Dropdown.prototype.toggle = function (e) { + var $this = $(this) + + if ($this.is('.disabled, :disabled')) return + + var $parent = getParent($this) + var isActive = $parent.hasClass('open') + + clearMenus() + + if (!isActive) { + if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) { + // if mobile we use a backdrop because click events don't delegate + $(document.createElement('div')) + .addClass('dropdown-backdrop') + .insertAfter($(this)) + .on('click', clearMenus) + } + + var relatedTarget = { relatedTarget: this } + $parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget)) + + if (e.isDefaultPrevented()) return + + $this + .trigger('focus') + .attr('aria-expanded', 'true') + + $parent + .toggleClass('open') + .trigger($.Event('shown.bs.dropdown', relatedTarget)) + } + + return false + } + + Dropdown.prototype.keydown = function (e) { + if (!/(38|40|27|32)/.test(e.which) || /input|textarea/i.test(e.target.tagName)) return + + var $this = $(this) + + e.preventDefault() + e.stopPropagation() + + if ($this.is('.disabled, :disabled')) return + + var $parent = getParent($this) + var isActive = $parent.hasClass('open') + + if (!isActive && e.which != 27 || isActive && e.which == 27) { + if (e.which == 27) $parent.find(toggle).trigger('focus') + return $this.trigger('click') + } + + var desc = ' li:not(.disabled):visible a' + var $items = $parent.find('.dropdown-menu' + desc) + + if (!$items.length) return + + var index = $items.index(e.target) + + if (e.which == 38 && index > 0) index-- // up + if (e.which == 40 && index < $items.length - 1) index++ // down + if (!~index) index = 0 + + $items.eq(index).trigger('focus') + } + + + // DROPDOWN PLUGIN DEFINITION + // ========================== + + function Plugin(option) { + return this.each(function () { + var $this = $(this) + var data = $this.data('bs.dropdown') + + if (!data) $this.data('bs.dropdown', (data = new Dropdown(this))) + if (typeof option == 'string') data[option].call($this) + }) + } + + var old = $.fn.dropdown + + $.fn.dropdown = Plugin + $.fn.dropdown.Constructor = Dropdown + + + // DROPDOWN NO CONFLICT + // ==================== + + $.fn.dropdown.noConflict = function () { + $.fn.dropdown = old + return this + } + + + // APPLY TO STANDARD DROPDOWN ELEMENTS + // =================================== + + $(document) + .on('click.bs.dropdown.data-api', clearMenus) + .on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() }) + .on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle) + .on('keydown.bs.dropdown.data-api', toggle, Dropdown.prototype.keydown) + .on('keydown.bs.dropdown.data-api', '.dropdown-menu', Dropdown.prototype.keydown) + +}(jQuery); + +/* ======================================================================== + * Bootstrap: modal.js v3.3.6 + * http://getbootstrap.com/javascript/#modals + * ======================================================================== + * Copyright 2011-2015 Twitter, Inc. + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) + * ======================================================================== */ + + ++function ($) { + 'use strict'; + + // MODAL CLASS DEFINITION + // ====================== + + var Modal = function (element, options) { + this.options = options + this.$body = $(document.body) + this.$element = $(element) + this.$dialog = this.$element.find('.modal-dialog') + this.$backdrop = null + this.isShown = null + this.originalBodyPad = null + this.scrollbarWidth = 0 + this.ignoreBackdropClick = false + + if (this.options.remote) { + this.$element + .find('.modal-content') + .load(this.options.remote, $.proxy(function () { + this.$element.trigger('loaded.bs.modal') + }, this)) + } + } + + Modal.VERSION = '3.3.6' + + Modal.TRANSITION_DURATION = 300 + Modal.BACKDROP_TRANSITION_DURATION = 150 + + Modal.DEFAULTS = { + backdrop: true, + keyboard: true, + show: true + } + + Modal.prototype.toggle = function (_relatedTarget) { + return this.isShown ? this.hide() : this.show(_relatedTarget) + } + + Modal.prototype.show = function (_relatedTarget) { + var that = this + var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget }) + + this.$element.trigger(e) + + if (this.isShown || e.isDefaultPrevented()) return + + this.isShown = true + + this.checkScrollbar() + this.setScrollbar() + this.$body.addClass('modal-open') + + this.escape() + this.resize() + + this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this)) + + this.$dialog.on('mousedown.dismiss.bs.modal', function () { + that.$element.one('mouseup.dismiss.bs.modal', function (e) { + if ($(e.target).is(that.$element)) that.ignoreBackdropClick = true + }) + }) + + this.backdrop(function () { + var transition = $.support.transition && that.$element.hasClass('fade') + + if (!that.$element.parent().length) { + that.$element.appendTo(that.$body) // don't move modals dom position + } + + that.$element + .show() + .scrollTop(0) + + that.adjustDialog() + + if (transition) { + that.$element[0].offsetWidth // force reflow + } + + that.$element.addClass('in') + + that.enforceFocus() + + var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget }) + + transition ? + that.$dialog // wait for modal to slide in + .one('bsTransitionEnd', function () { + that.$element.trigger('focus').trigger(e) + }) + .emulateTransitionEnd(Modal.TRANSITION_DURATION) : + that.$element.trigger('focus').trigger(e) + }) + } + + Modal.prototype.hide = function (e) { + if (e) e.preventDefault() + + e = $.Event('hide.bs.modal') + + this.$element.trigger(e) + + if (!this.isShown || e.isDefaultPrevented()) return + + this.isShown = false + + this.escape() + this.resize() + + $(document).off('focusin.bs.modal') + + this.$element + .removeClass('in') + .off('click.dismiss.bs.modal') + .off('mouseup.dismiss.bs.modal') + + this.$dialog.off('mousedown.dismiss.bs.modal') + + $.support.transition && this.$element.hasClass('fade') ? + this.$element + .one('bsTransitionEnd', $.proxy(this.hideModal, this)) + .emulateTransitionEnd(Modal.TRANSITION_DURATION) : + this.hideModal() + } + + Modal.prototype.enforceFocus = function () { + $(document) + .off('focusin.bs.modal') // guard against infinite focus loop + .on('focusin.bs.modal', $.proxy(function (e) { + if (this.$element[0] !== e.target && !this.$element.has(e.target).length) { + this.$element.trigger('focus') + } + }, this)) + } + + Modal.prototype.escape = function () { + if (this.isShown && this.options.keyboard) { + this.$element.on('keydown.dismiss.bs.modal', $.proxy(function (e) { + e.which == 27 && this.hide() + }, this)) + } else if (!this.isShown) { + this.$element.off('keydown.dismiss.bs.modal') + } + } + + Modal.prototype.resize = function () { + if (this.isShown) { + $(window).on('resize.bs.modal', $.proxy(this.handleUpdate, this)) + } else { + $(window).off('resize.bs.modal') + } + } + + Modal.prototype.hideModal = function () { + var that = this + this.$element.hide() + this.backdrop(function () { + that.$body.removeClass('modal-open') + that.resetAdjustments() + that.resetScrollbar() + that.$element.trigger('hidden.bs.modal') + }) + } + + Modal.prototype.removeBackdrop = function () { + this.$backdrop && this.$backdrop.remove() + this.$backdrop = null + } + + Modal.prototype.backdrop = function (callback) { + var that = this + var animate = this.$element.hasClass('fade') ? 'fade' : '' + + if (this.isShown && this.options.backdrop) { + var doAnimate = $.support.transition && animate + + this.$backdrop = $(document.createElement('div')) + .addClass('modal-backdrop ' + animate) + .appendTo(this.$body) + + this.$element.on('click.dismiss.bs.modal', $.proxy(function (e) { + if (this.ignoreBackdropClick) { + this.ignoreBackdropClick = false + return + } + if (e.target !== e.currentTarget) return + this.options.backdrop == 'static' + ? this.$element[0].focus() + : this.hide() + }, this)) + + if (doAnimate) this.$backdrop[0].offsetWidth // force reflow + + this.$backdrop.addClass('in') + + if (!callback) return + + doAnimate ? + this.$backdrop + .one('bsTransitionEnd', callback) + .emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) : + callback() + + } else if (!this.isShown && this.$backdrop) { + this.$backdrop.removeClass('in') + + var callbackRemove = function () { + that.removeBackdrop() + callback && callback() + } + $.support.transition && this.$element.hasClass('fade') ? + this.$backdrop + .one('bsTransitionEnd', callbackRemove) + .emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) : + callbackRemove() + + } else if (callback) { + callback() + } + } + + // these following methods are used to handle overflowing modals + + Modal.prototype.handleUpdate = function () { + this.adjustDialog() + } + + Modal.prototype.adjustDialog = function () { + var modalIsOverflowing = this.$element[0].scrollHeight > document.documentElement.clientHeight + + this.$element.css({ + paddingLeft: !this.bodyIsOverflowing && modalIsOverflowing ? this.scrollbarWidth : '', + paddingRight: this.bodyIsOverflowing && !modalIsOverflowing ? this.scrollbarWidth : '' + }) + } + + Modal.prototype.resetAdjustments = function () { + this.$element.css({ + paddingLeft: '', + paddingRight: '' + }) + } + + Modal.prototype.checkScrollbar = function () { + var fullWindowWidth = window.innerWidth + if (!fullWindowWidth) { // workaround for missing window.innerWidth in IE8 + var documentElementRect = document.documentElement.getBoundingClientRect() + fullWindowWidth = documentElementRect.right - Math.abs(documentElementRect.left) + } + this.bodyIsOverflowing = document.body.clientWidth < fullWindowWidth + this.scrollbarWidth = this.measureScrollbar() + } + + Modal.prototype.setScrollbar = function () { + var bodyPad = parseInt((this.$body.css('padding-right') || 0), 10) + this.originalBodyPad = document.body.style.paddingRight || '' + if (this.bodyIsOverflowing) this.$body.css('padding-right', bodyPad + this.scrollbarWidth) + } + + Modal.prototype.resetScrollbar = function () { + this.$body.css('padding-right', this.originalBodyPad) + } + + Modal.prototype.measureScrollbar = function () { // thx walsh + var scrollDiv = document.createElement('div') + scrollDiv.className = 'modal-scrollbar-measure' + this.$body.append(scrollDiv) + var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth + this.$body[0].removeChild(scrollDiv) + return scrollbarWidth + } + + + // MODAL PLUGIN DEFINITION + // ======================= + + function Plugin(option, _relatedTarget) { + return this.each(function () { + var $this = $(this) + var data = $this.data('bs.modal') + var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option) + + if (!data) $this.data('bs.modal', (data = new Modal(this, options))) + if (typeof option == 'string') data[option](_relatedTarget) + else if (options.show) data.show(_relatedTarget) + }) + } + + var old = $.fn.modal + + $.fn.modal = Plugin + $.fn.modal.Constructor = Modal + + + // MODAL NO CONFLICT + // ================= + + $.fn.modal.noConflict = function () { + $.fn.modal = old + return this + } + + + // MODAL DATA-API + // ============== + + $(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) { + var $this = $(this) + var href = $this.attr('href') + var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) // strip for ie7 + var option = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data()) + + if ($this.is('a')) e.preventDefault() + + $target.one('show.bs.modal', function (showEvent) { + if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown + $target.one('hidden.bs.modal', function () { + $this.is(':visible') && $this.trigger('focus') + }) + }) + Plugin.call($target, option, this) + }) + +}(jQuery); + +/* ======================================================================== + * Bootstrap: tooltip.js v3.3.6 + * http://getbootstrap.com/javascript/#tooltip + * Inspired by the original jQuery.tipsy by Jason Frame + * ======================================================================== + * Copyright 2011-2015 Twitter, Inc. + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) + * ======================================================================== */ + + ++function ($) { + 'use strict'; + + // TOOLTIP PUBLIC CLASS DEFINITION + // =============================== + + var Tooltip = function (element, options) { + this.type = null + this.options = null + this.enabled = null + this.timeout = null + this.hoverState = null + this.$element = null + this.inState = null + + this.init('tooltip', element, options) + } + + Tooltip.VERSION = '3.3.6' + + Tooltip.TRANSITION_DURATION = 150 + + Tooltip.DEFAULTS = { + animation: true, + placement: 'top', + selector: false, + template: '', + trigger: 'hover focus', + title: '', + delay: 0, + html: false, + container: false, + viewport: { + selector: 'body', + padding: 0 + } + } + + Tooltip.prototype.init = function (type, element, options) { + this.enabled = true + this.type = type + this.$element = $(element) + this.options = this.getOptions(options) + this.$viewport = this.options.viewport && $($.isFunction(this.options.viewport) ? this.options.viewport.call(this, this.$element) : (this.options.viewport.selector || this.options.viewport)) + this.inState = { click: false, hover: false, focus: false } + + if (this.$element[0] instanceof document.constructor && !this.options.selector) { + throw new Error('`selector` option must be specified when initializing ' + this.type + ' on the window.document object!') + } + + var triggers = this.options.trigger.split(' ') + + for (var i = triggers.length; i--;) { + var trigger = triggers[i] + + if (trigger == 'click') { + this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this)) + } else if (trigger != 'manual') { + var eventIn = trigger == 'hover' ? 'mouseenter' : 'focusin' + var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout' + + this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this)) + this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this)) + } + } + + this.options.selector ? + (this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) : + this.fixTitle() + } + + Tooltip.prototype.getDefaults = function () { + return Tooltip.DEFAULTS + } + + Tooltip.prototype.getOptions = function (options) { + options = $.extend({}, this.getDefaults(), this.$element.data(), options) + + if (options.delay && typeof options.delay == 'number') { + options.delay = { + show: options.delay, + hide: options.delay + } + } + + return options + } + + Tooltip.prototype.getDelegateOptions = function () { + var options = {} + var defaults = this.getDefaults() + + this._options && $.each(this._options, function (key, value) { + if (defaults[key] != value) options[key] = value + }) + + return options + } + + Tooltip.prototype.enter = function (obj) { + var self = obj instanceof this.constructor ? + obj : $(obj.currentTarget).data('bs.' + this.type) + + if (!self) { + self = new this.constructor(obj.currentTarget, this.getDelegateOptions()) + $(obj.currentTarget).data('bs.' + this.type, self) + } + + if (obj instanceof $.Event) { + self.inState[obj.type == 'focusin' ? 'focus' : 'hover'] = true + } + + if (self.tip().hasClass('in') || self.hoverState == 'in') { + self.hoverState = 'in' + return + } + + clearTimeout(self.timeout) + + self.hoverState = 'in' + + if (!self.options.delay || !self.options.delay.show) return self.show() + + self.timeout = setTimeout(function () { + if (self.hoverState == 'in') self.show() + }, self.options.delay.show) + } + + Tooltip.prototype.isInStateTrue = function () { + for (var key in this.inState) { + if (this.inState[key]) return true + } + + return false + } + + Tooltip.prototype.leave = function (obj) { + var self = obj instanceof this.constructor ? + obj : $(obj.currentTarget).data('bs.' + this.type) + + if (!self) { + self = new this.constructor(obj.currentTarget, this.getDelegateOptions()) + $(obj.currentTarget).data('bs.' + this.type, self) + } + + if (obj instanceof $.Event) { + self.inState[obj.type == 'focusout' ? 'focus' : 'hover'] = false + } + + if (self.isInStateTrue()) return + + clearTimeout(self.timeout) + + self.hoverState = 'out' + + if (!self.options.delay || !self.options.delay.hide) return self.hide() + + self.timeout = setTimeout(function () { + if (self.hoverState == 'out') self.hide() + }, self.options.delay.hide) + } + + Tooltip.prototype.show = function () { + var e = $.Event('show.bs.' + this.type) + + if (this.hasContent() && this.enabled) { + this.$element.trigger(e) + + var inDom = $.contains(this.$element[0].ownerDocument.documentElement, this.$element[0]) + if (e.isDefaultPrevented() || !inDom) return + var that = this + + var $tip = this.tip() + + var tipId = this.getUID(this.type) + + this.setContent() + $tip.attr('id', tipId) + this.$element.attr('aria-describedby', tipId) + + if (this.options.animation) $tip.addClass('fade') + + var placement = typeof this.options.placement == 'function' ? + this.options.placement.call(this, $tip[0], this.$element[0]) : + this.options.placement + + var autoToken = /\s?auto?\s?/i + var autoPlace = autoToken.test(placement) + if (autoPlace) placement = placement.replace(autoToken, '') || 'top' + + $tip + .detach() + .css({ top: 0, left: 0, display: 'block' }) + .addClass(placement) + .data('bs.' + this.type, this) + + this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element) + this.$element.trigger('inserted.bs.' + this.type) + + var pos = this.getPosition() + var actualWidth = $tip[0].offsetWidth + var actualHeight = $tip[0].offsetHeight + + if (autoPlace) { + var orgPlacement = placement + var viewportDim = this.getPosition(this.$viewport) + + placement = placement == 'bottom' && pos.bottom + actualHeight > viewportDim.bottom ? 'top' : + placement == 'top' && pos.top - actualHeight < viewportDim.top ? 'bottom' : + placement == 'right' && pos.right + actualWidth > viewportDim.width ? 'left' : + placement == 'left' && pos.left - actualWidth < viewportDim.left ? 'right' : + placement + + $tip + .removeClass(orgPlacement) + .addClass(placement) + } + + var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight) + + this.applyPlacement(calculatedOffset, placement) + + var complete = function () { + var prevHoverState = that.hoverState + that.$element.trigger('shown.bs.' + that.type) + that.hoverState = null + + if (prevHoverState == 'out') that.leave(that) + } + + $.support.transition && this.$tip.hasClass('fade') ? + $tip + .one('bsTransitionEnd', complete) + .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) : + complete() + } + } + + Tooltip.prototype.applyPlacement = function (offset, placement) { + var $tip = this.tip() + var width = $tip[0].offsetWidth + var height = $tip[0].offsetHeight + + // manually read margins because getBoundingClientRect includes difference + var marginTop = parseInt($tip.css('margin-top'), 10) + var marginLeft = parseInt($tip.css('margin-left'), 10) + + // we must check for NaN for ie 8/9 + if (isNaN(marginTop)) marginTop = 0 + if (isNaN(marginLeft)) marginLeft = 0 + + offset.top += marginTop + offset.left += marginLeft + + // $.fn.offset doesn't round pixel values + // so we use setOffset directly with our own function B-0 + $.offset.setOffset($tip[0], $.extend({ + using: function (props) { + $tip.css({ + top: Math.round(props.top), + left: Math.round(props.left) + }) + } + }, offset), 0) + + $tip.addClass('in') + + // check to see if placing tip in new offset caused the tip to resize itself + var actualWidth = $tip[0].offsetWidth + var actualHeight = $tip[0].offsetHeight + + if (placement == 'top' && actualHeight != height) { + offset.top = offset.top + height - actualHeight + } + + var delta = this.getViewportAdjustedDelta(placement, offset, actualWidth, actualHeight) + + if (delta.left) offset.left += delta.left + else offset.top += delta.top + + var isVertical = /top|bottom/.test(placement) + var arrowDelta = isVertical ? delta.left * 2 - width + actualWidth : delta.top * 2 - height + actualHeight + var arrowOffsetPosition = isVertical ? 'offsetWidth' : 'offsetHeight' + + $tip.offset(offset) + this.replaceArrow(arrowDelta, $tip[0][arrowOffsetPosition], isVertical) + } + + Tooltip.prototype.replaceArrow = function (delta, dimension, isVertical) { + this.arrow() + .css(isVertical ? 'left' : 'top', 50 * (1 - delta / dimension) + '%') + .css(isVertical ? 'top' : 'left', '') + } + + Tooltip.prototype.setContent = function () { + var $tip = this.tip() + var title = this.getTitle() + + $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title) + $tip.removeClass('fade in top bottom left right') + } + + Tooltip.prototype.hide = function (callback) { + var that = this + var $tip = $(this.$tip) + var e = $.Event('hide.bs.' + this.type) + + function complete() { + if (that.hoverState != 'in') $tip.detach() + that.$element + .removeAttr('aria-describedby') + .trigger('hidden.bs.' + that.type) + callback && callback() + } + + this.$element.trigger(e) + + if (e.isDefaultPrevented()) return + + $tip.removeClass('in') + + $.support.transition && $tip.hasClass('fade') ? + $tip + .one('bsTransitionEnd', complete) + .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) : + complete() + + this.hoverState = null + + return this + } + + Tooltip.prototype.fixTitle = function () { + var $e = this.$element + if ($e.attr('title') || typeof $e.attr('data-original-title') != 'string') { + $e.attr('data-original-title', $e.attr('title') || '').attr('title', '') + } + } + + Tooltip.prototype.hasContent = function () { + return this.getTitle() + } + + Tooltip.prototype.getPosition = function ($element) { + $element = $element || this.$element + + var el = $element[0] + var isBody = el.tagName == 'BODY' + + var elRect = el.getBoundingClientRect() + if (elRect.width == null) { + // width and height are missing in IE8, so compute them manually; see https://github.com/twbs/bootstrap/issues/14093 + elRect = $.extend({}, elRect, { width: elRect.right - elRect.left, height: elRect.bottom - elRect.top }) + } + var elOffset = isBody ? { top: 0, left: 0 } : $element.offset() + var scroll = { scroll: isBody ? document.documentElement.scrollTop || document.body.scrollTop : $element.scrollTop() } + var outerDims = isBody ? { width: $(window).width(), height: $(window).height() } : null + + return $.extend({}, elRect, scroll, outerDims, elOffset) + } + + Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) { + return placement == 'bottom' ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } : + placement == 'top' ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } : + placement == 'left' ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } : + /* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width } + + } + + Tooltip.prototype.getViewportAdjustedDelta = function (placement, pos, actualWidth, actualHeight) { + var delta = { top: 0, left: 0 } + if (!this.$viewport) return delta + + var viewportPadding = this.options.viewport && this.options.viewport.padding || 0 + var viewportDimensions = this.getPosition(this.$viewport) + + if (/right|left/.test(placement)) { + var topEdgeOffset = pos.top - viewportPadding - viewportDimensions.scroll + var bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight + if (topEdgeOffset < viewportDimensions.top) { // top overflow + delta.top = viewportDimensions.top - topEdgeOffset + } else if (bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height) { // bottom overflow + delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset + } + } else { + var leftEdgeOffset = pos.left - viewportPadding + var rightEdgeOffset = pos.left + viewportPadding + actualWidth + if (leftEdgeOffset < viewportDimensions.left) { // left overflow + delta.left = viewportDimensions.left - leftEdgeOffset + } else if (rightEdgeOffset > viewportDimensions.right) { // right overflow + delta.left = viewportDimensions.left + viewportDimensions.width - rightEdgeOffset + } + } + + return delta + } + + Tooltip.prototype.getTitle = function () { + var title + var $e = this.$element + var o = this.options + + title = $e.attr('data-original-title') + || (typeof o.title == 'function' ? o.title.call($e[0]) : o.title) + + return title + } + + Tooltip.prototype.getUID = function (prefix) { + do prefix += ~~(Math.random() * 1000000) + while (document.getElementById(prefix)) + return prefix + } + + Tooltip.prototype.tip = function () { + if (!this.$tip) { + this.$tip = $(this.options.template) + if (this.$tip.length != 1) { + throw new Error(this.type + ' `template` option must consist of exactly 1 top-level element!') + } + } + return this.$tip + } + + Tooltip.prototype.arrow = function () { + return (this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow')) + } + + Tooltip.prototype.enable = function () { + this.enabled = true + } + + Tooltip.prototype.disable = function () { + this.enabled = false + } + + Tooltip.prototype.toggleEnabled = function () { + this.enabled = !this.enabled + } + + Tooltip.prototype.toggle = function (e) { + var self = this + if (e) { + self = $(e.currentTarget).data('bs.' + this.type) + if (!self) { + self = new this.constructor(e.currentTarget, this.getDelegateOptions()) + $(e.currentTarget).data('bs.' + this.type, self) + } + } + + if (e) { + self.inState.click = !self.inState.click + if (self.isInStateTrue()) self.enter(self) + else self.leave(self) + } else { + self.tip().hasClass('in') ? self.leave(self) : self.enter(self) + } + } + + Tooltip.prototype.destroy = function () { + var that = this + clearTimeout(this.timeout) + this.hide(function () { + that.$element.off('.' + that.type).removeData('bs.' + that.type) + if (that.$tip) { + that.$tip.detach() + } + that.$tip = null + that.$arrow = null + that.$viewport = null + }) + } + + + // TOOLTIP PLUGIN DEFINITION + // ========================= + + function Plugin(option) { + return this.each(function () { + var $this = $(this) + var data = $this.data('bs.tooltip') + var options = typeof option == 'object' && option + + if (!data && /destroy|hide/.test(option)) return + if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options))) + if (typeof option == 'string') data[option]() + }) + } + + var old = $.fn.tooltip + + $.fn.tooltip = Plugin + $.fn.tooltip.Constructor = Tooltip + + + // TOOLTIP NO CONFLICT + // =================== + + $.fn.tooltip.noConflict = function () { + $.fn.tooltip = old + return this + } + +}(jQuery); + +/* ======================================================================== + * Bootstrap: popover.js v3.3.6 + * http://getbootstrap.com/javascript/#popovers + * ======================================================================== + * Copyright 2011-2015 Twitter, Inc. + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) + * ======================================================================== */ + + ++function ($) { + 'use strict'; + + // POPOVER PUBLIC CLASS DEFINITION + // =============================== + + var Popover = function (element, options) { + this.init('popover', element, options) + } + + if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js') + + Popover.VERSION = '3.3.6' + + Popover.DEFAULTS = $.extend({}, $.fn.tooltip.Constructor.DEFAULTS, { + placement: 'right', + trigger: 'click', + content: '', + template: '' + }) + + + // NOTE: POPOVER EXTENDS tooltip.js + // ================================ + + Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype) + + Popover.prototype.constructor = Popover + + Popover.prototype.getDefaults = function () { + return Popover.DEFAULTS + } + + Popover.prototype.setContent = function () { + var $tip = this.tip() + var title = this.getTitle() + var content = this.getContent() + + $tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title) + $tip.find('.popover-content').children().detach().end()[ // we use append for html objects to maintain js events + this.options.html ? (typeof content == 'string' ? 'html' : 'append') : 'text' + ](content) + + $tip.removeClass('fade top bottom left right in') + + // IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do + // this manually by checking the contents. + if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide() + } + + Popover.prototype.hasContent = function () { + return this.getTitle() || this.getContent() + } + + Popover.prototype.getContent = function () { + var $e = this.$element + var o = this.options + + return $e.attr('data-content') + || (typeof o.content == 'function' ? + o.content.call($e[0]) : + o.content) + } + + Popover.prototype.arrow = function () { + return (this.$arrow = this.$arrow || this.tip().find('.arrow')) + } + + + // POPOVER PLUGIN DEFINITION + // ========================= + + function Plugin(option) { + return this.each(function () { + var $this = $(this) + var data = $this.data('bs.popover') + var options = typeof option == 'object' && option + + if (!data && /destroy|hide/.test(option)) return + if (!data) $this.data('bs.popover', (data = new Popover(this, options))) + if (typeof option == 'string') data[option]() + }) + } + + var old = $.fn.popover + + $.fn.popover = Plugin + $.fn.popover.Constructor = Popover + + + // POPOVER NO CONFLICT + // =================== + + $.fn.popover.noConflict = function () { + $.fn.popover = old + return this + } + +}(jQuery); + +/* ======================================================================== + * Bootstrap: scrollspy.js v3.3.6 + * http://getbootstrap.com/javascript/#scrollspy + * ======================================================================== + * Copyright 2011-2015 Twitter, Inc. + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) + * ======================================================================== */ + + ++function ($) { + 'use strict'; + + // SCROLLSPY CLASS DEFINITION + // ========================== + + function ScrollSpy(element, options) { + this.$body = $(document.body) + this.$scrollElement = $(element).is(document.body) ? $(window) : $(element) + this.options = $.extend({}, ScrollSpy.DEFAULTS, options) + this.selector = (this.options.target || '') + ' .nav li > a' + this.offsets = [] + this.targets = [] + this.activeTarget = null + this.scrollHeight = 0 + + this.$scrollElement.on('scroll.bs.scrollspy', $.proxy(this.process, this)) + this.refresh() + this.process() + } + + ScrollSpy.VERSION = '3.3.6' + + ScrollSpy.DEFAULTS = { + offset: 10 + } + + ScrollSpy.prototype.getScrollHeight = function () { + return this.$scrollElement[0].scrollHeight || Math.max(this.$body[0].scrollHeight, document.documentElement.scrollHeight) + } + + ScrollSpy.prototype.refresh = function () { + var that = this + var offsetMethod = 'offset' + var offsetBase = 0 + + this.offsets = [] + this.targets = [] + this.scrollHeight = this.getScrollHeight() + + if (!$.isWindow(this.$scrollElement[0])) { + offsetMethod = 'position' + offsetBase = this.$scrollElement.scrollTop() + } + + this.$body + .find(this.selector) + .map(function () { + var $el = $(this) + var href = $el.data('target') || $el.attr('href') + var $href = /^#./.test(href) && $(href) + + return ($href + && $href.length + && $href.is(':visible') + && [[$href[offsetMethod]().top + offsetBase, href]]) || null + }) + .sort(function (a, b) { return a[0] - b[0] }) + .each(function () { + that.offsets.push(this[0]) + that.targets.push(this[1]) + }) + } + + ScrollSpy.prototype.process = function () { + var scrollTop = this.$scrollElement.scrollTop() + this.options.offset + var scrollHeight = this.getScrollHeight() + var maxScroll = this.options.offset + scrollHeight - this.$scrollElement.height() + var offsets = this.offsets + var targets = this.targets + var activeTarget = this.activeTarget + var i + + if (this.scrollHeight != scrollHeight) { + this.refresh() + } + + if (scrollTop >= maxScroll) { + return activeTarget != (i = targets[targets.length - 1]) && this.activate(i) + } + + if (activeTarget && scrollTop < offsets[0]) { + this.activeTarget = null + return this.clear() + } + + for (i = offsets.length; i--;) { + activeTarget != targets[i] + && scrollTop >= offsets[i] + && (offsets[i + 1] === undefined || scrollTop < offsets[i + 1]) + && this.activate(targets[i]) + } + } + + ScrollSpy.prototype.activate = function (target) { + this.activeTarget = target + + this.clear() + + var selector = this.selector + + '[data-target="' + target + '"],' + + this.selector + '[href="' + target + '"]' + + var active = $(selector) + .parents('li') + .addClass('active') + + if (active.parent('.dropdown-menu').length) { + active = active + .closest('li.dropdown') + .addClass('active') + } + + active.trigger('activate.bs.scrollspy') + } + + ScrollSpy.prototype.clear = function () { + $(this.selector) + .parentsUntil(this.options.target, '.active') + .removeClass('active') + } + + + // SCROLLSPY PLUGIN DEFINITION + // =========================== + + function Plugin(option) { + return this.each(function () { + var $this = $(this) + var data = $this.data('bs.scrollspy') + var options = typeof option == 'object' && option + + if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options))) + if (typeof option == 'string') data[option]() + }) + } + + var old = $.fn.scrollspy + + $.fn.scrollspy = Plugin + $.fn.scrollspy.Constructor = ScrollSpy + + + // SCROLLSPY NO CONFLICT + // ===================== + + $.fn.scrollspy.noConflict = function () { + $.fn.scrollspy = old + return this + } + + + // SCROLLSPY DATA-API + // ================== + + $(window).on('load.bs.scrollspy.data-api', function () { + $('[data-spy="scroll"]').each(function () { + var $spy = $(this) + Plugin.call($spy, $spy.data()) + }) + }) + +}(jQuery); + +/* ======================================================================== + * Bootstrap: tab.js v3.3.6 + * http://getbootstrap.com/javascript/#tabs + * ======================================================================== + * Copyright 2011-2015 Twitter, Inc. + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) + * ======================================================================== */ + + ++function ($) { + 'use strict'; + + // TAB CLASS DEFINITION + // ==================== + + var Tab = function (element) { + // jscs:disable requireDollarBeforejQueryAssignment + this.element = $(element) + // jscs:enable requireDollarBeforejQueryAssignment + } + + Tab.VERSION = '3.3.6' + + Tab.TRANSITION_DURATION = 150 + + Tab.prototype.show = function () { + var $this = this.element + var $ul = $this.closest('ul:not(.dropdown-menu)') + var selector = $this.data('target') + + if (!selector) { + selector = $this.attr('href') + selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 + } + + if ($this.parent('li').hasClass('active')) return + + var $previous = $ul.find('.active:last a') + var hideEvent = $.Event('hide.bs.tab', { + relatedTarget: $this[0] + }) + var showEvent = $.Event('show.bs.tab', { + relatedTarget: $previous[0] + }) + + $previous.trigger(hideEvent) + $this.trigger(showEvent) + + if (showEvent.isDefaultPrevented() || hideEvent.isDefaultPrevented()) return + + var $target = $(selector) + + this.activate($this.closest('li'), $ul) + this.activate($target, $target.parent(), function () { + $previous.trigger({ + type: 'hidden.bs.tab', + relatedTarget: $this[0] + }) + $this.trigger({ + type: 'shown.bs.tab', + relatedTarget: $previous[0] + }) + }) + } + + Tab.prototype.activate = function (element, container, callback) { + var $active = container.find('> .active') + var transition = callback + && $.support.transition + && ($active.length && $active.hasClass('fade') || !!container.find('> .fade').length) + + function next() { + $active + .removeClass('active') + .find('> .dropdown-menu > .active') + .removeClass('active') + .end() + .find('[data-toggle="tab"]') + .attr('aria-expanded', false) + + element + .addClass('active') + .find('[data-toggle="tab"]') + .attr('aria-expanded', true) + + if (transition) { + element[0].offsetWidth // reflow for transition + element.addClass('in') + } else { + element.removeClass('fade') + } + + if (element.parent('.dropdown-menu').length) { + element + .closest('li.dropdown') + .addClass('active') + .end() + .find('[data-toggle="tab"]') + .attr('aria-expanded', true) + } + + callback && callback() + } + + $active.length && transition ? + $active + .one('bsTransitionEnd', next) + .emulateTransitionEnd(Tab.TRANSITION_DURATION) : + next() + + $active.removeClass('in') + } + + + // TAB PLUGIN DEFINITION + // ===================== + + function Plugin(option) { + return this.each(function () { + var $this = $(this) + var data = $this.data('bs.tab') + + if (!data) $this.data('bs.tab', (data = new Tab(this))) + if (typeof option == 'string') data[option]() + }) + } + + var old = $.fn.tab + + $.fn.tab = Plugin + $.fn.tab.Constructor = Tab + + + // TAB NO CONFLICT + // =============== + + $.fn.tab.noConflict = function () { + $.fn.tab = old + return this + } + + + // TAB DATA-API + // ============ + + var clickHandler = function (e) { + e.preventDefault() + Plugin.call($(this), 'show') + } + + $(document) + .on('click.bs.tab.data-api', '[data-toggle="tab"]', clickHandler) + .on('click.bs.tab.data-api', '[data-toggle="pill"]', clickHandler) + +}(jQuery); + +/* ======================================================================== + * Bootstrap: affix.js v3.3.6 + * http://getbootstrap.com/javascript/#affix + * ======================================================================== + * Copyright 2011-2015 Twitter, Inc. + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) + * ======================================================================== */ + + ++function ($) { + 'use strict'; + + // AFFIX CLASS DEFINITION + // ====================== + + var Affix = function (element, options) { + this.options = $.extend({}, Affix.DEFAULTS, options) + + this.$target = $(this.options.target) + .on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this)) + .on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this)) + + this.$element = $(element) + this.affixed = null + this.unpin = null + this.pinnedOffset = null + + this.checkPosition() + } + + Affix.VERSION = '3.3.6' + + Affix.RESET = 'affix affix-top affix-bottom' + + Affix.DEFAULTS = { + offset: 0, + target: window + } + + Affix.prototype.getState = function (scrollHeight, height, offsetTop, offsetBottom) { + var scrollTop = this.$target.scrollTop() + var position = this.$element.offset() + var targetHeight = this.$target.height() + + if (offsetTop != null && this.affixed == 'top') return scrollTop < offsetTop ? 'top' : false + + if (this.affixed == 'bottom') { + if (offsetTop != null) return (scrollTop + this.unpin <= position.top) ? false : 'bottom' + return (scrollTop + targetHeight <= scrollHeight - offsetBottom) ? false : 'bottom' + } + + var initializing = this.affixed == null + var colliderTop = initializing ? scrollTop : position.top + var colliderHeight = initializing ? targetHeight : height + + if (offsetTop != null && scrollTop <= offsetTop) return 'top' + if (offsetBottom != null && (colliderTop + colliderHeight >= scrollHeight - offsetBottom)) return 'bottom' + + return false + } + + Affix.prototype.getPinnedOffset = function () { + if (this.pinnedOffset) return this.pinnedOffset + this.$element.removeClass(Affix.RESET).addClass('affix') + var scrollTop = this.$target.scrollTop() + var position = this.$element.offset() + return (this.pinnedOffset = position.top - scrollTop) + } + + Affix.prototype.checkPositionWithEventLoop = function () { + setTimeout($.proxy(this.checkPosition, this), 1) + } + + Affix.prototype.checkPosition = function () { + if (!this.$element.is(':visible')) return + + var height = this.$element.height() + var offset = this.options.offset + var offsetTop = offset.top + var offsetBottom = offset.bottom + var scrollHeight = Math.max($(document).height(), $(document.body).height()) + + if (typeof offset != 'object') offsetBottom = offsetTop = offset + if (typeof offsetTop == 'function') offsetTop = offset.top(this.$element) + if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element) + + var affix = this.getState(scrollHeight, height, offsetTop, offsetBottom) + + if (this.affixed != affix) { + if (this.unpin != null) this.$element.css('top', '') + + var affixType = 'affix' + (affix ? '-' + affix : '') + var e = $.Event(affixType + '.bs.affix') + + this.$element.trigger(e) + + if (e.isDefaultPrevented()) return + + this.affixed = affix + this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null + + this.$element + .removeClass(Affix.RESET) + .addClass(affixType) + .trigger(affixType.replace('affix', 'affixed') + '.bs.affix') + } + + if (affix == 'bottom') { + this.$element.offset({ + top: scrollHeight - height - offsetBottom + }) + } + } + + + // AFFIX PLUGIN DEFINITION + // ======================= + + function Plugin(option) { + return this.each(function () { + var $this = $(this) + var data = $this.data('bs.affix') + var options = typeof option == 'object' && option + + if (!data) $this.data('bs.affix', (data = new Affix(this, options))) + if (typeof option == 'string') data[option]() + }) + } + + var old = $.fn.affix + + $.fn.affix = Plugin + $.fn.affix.Constructor = Affix + + + // AFFIX NO CONFLICT + // ================= + + $.fn.affix.noConflict = function () { + $.fn.affix = old + return this + } + + + // AFFIX DATA-API + // ============== + + $(window).on('load', function () { + $('[data-spy="affix"]').each(function () { + var $spy = $(this) + var data = $spy.data() + + data.offset = data.offset || {} + + if (data.offsetBottom != null) data.offset.bottom = data.offsetBottom + if (data.offsetTop != null) data.offset.top = data.offsetTop + + Plugin.call($spy, data) + }) + }) + +}(jQuery); diff --git a/downloaded_folder/public/js/bootstrap.min.js b/downloaded_folder/public/js/bootstrap.min.js new file mode 100644 index 0000000..e79c065 --- /dev/null +++ b/downloaded_folder/public/js/bootstrap.min.js @@ -0,0 +1,7 @@ +/*! + * Bootstrap v3.3.6 (http://getbootstrap.com) + * Copyright 2011-2015 Twitter, Inc. + * Licensed under the MIT license + */ +if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript requires jQuery");+function(a){"use strict";var b=a.fn.jquery.split(" ")[0].split(".");if(b[0]<2&&b[1]<9||1==b[0]&&9==b[1]&&b[2]<1||b[0]>2)throw new Error("Bootstrap's JavaScript requires jQuery version 1.9.1 or higher, but lower than version 3")}(jQuery),+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]};return!1}a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one("bsTransitionEnd",function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b(),a.support.transition&&(a.event.special.bsTransitionEnd={bindType:a.support.transition.end,delegateType:a.support.transition.end,handle:function(b){return a(b.target).is(this)?b.handleObj.handler.apply(this,arguments):void 0}})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var c=a(this),e=c.data("bs.alert");e||c.data("bs.alert",e=new d(this)),"string"==typeof b&&e[b].call(c)})}var c='[data-dismiss="alert"]',d=function(b){a(b).on("click",c,this.close)};d.VERSION="3.3.6",d.TRANSITION_DURATION=150,d.prototype.close=function(b){function c(){g.detach().trigger("closed.bs.alert").remove()}var e=a(this),f=e.attr("data-target");f||(f=e.attr("href"),f=f&&f.replace(/.*(?=#[^\s]*$)/,""));var g=a(f);b&&b.preventDefault(),g.length||(g=e.closest(".alert")),g.trigger(b=a.Event("close.bs.alert")),b.isDefaultPrevented()||(g.removeClass("in"),a.support.transition&&g.hasClass("fade")?g.one("bsTransitionEnd",c).emulateTransitionEnd(d.TRANSITION_DURATION):c())};var e=a.fn.alert;a.fn.alert=b,a.fn.alert.Constructor=d,a.fn.alert.noConflict=function(){return a.fn.alert=e,this},a(document).on("click.bs.alert.data-api",c,d.prototype.close)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.button"),f="object"==typeof b&&b;e||d.data("bs.button",e=new c(this,f)),"toggle"==b?e.toggle():b&&e.setState(b)})}var c=function(b,d){this.$element=a(b),this.options=a.extend({},c.DEFAULTS,d),this.isLoading=!1};c.VERSION="3.3.6",c.DEFAULTS={loadingText:"loading..."},c.prototype.setState=function(b){var c="disabled",d=this.$element,e=d.is("input")?"val":"html",f=d.data();b+="Text",null==f.resetText&&d.data("resetText",d[e]()),setTimeout(a.proxy(function(){d[e](null==f[b]?this.options[b]:f[b]),"loadingText"==b?(this.isLoading=!0,d.addClass(c).attr(c,c)):this.isLoading&&(this.isLoading=!1,d.removeClass(c).removeAttr(c))},this),0)},c.prototype.toggle=function(){var a=!0,b=this.$element.closest('[data-toggle="buttons"]');if(b.length){var c=this.$element.find("input");"radio"==c.prop("type")?(c.prop("checked")&&(a=!1),b.find(".active").removeClass("active"),this.$element.addClass("active")):"checkbox"==c.prop("type")&&(c.prop("checked")!==this.$element.hasClass("active")&&(a=!1),this.$element.toggleClass("active")),c.prop("checked",this.$element.hasClass("active")),a&&c.trigger("change")}else this.$element.attr("aria-pressed",!this.$element.hasClass("active")),this.$element.toggleClass("active")};var d=a.fn.button;a.fn.button=b,a.fn.button.Constructor=c,a.fn.button.noConflict=function(){return a.fn.button=d,this},a(document).on("click.bs.button.data-api",'[data-toggle^="button"]',function(c){var d=a(c.target);d.hasClass("btn")||(d=d.closest(".btn")),b.call(d,"toggle"),a(c.target).is('input[type="radio"]')||a(c.target).is('input[type="checkbox"]')||c.preventDefault()}).on("focus.bs.button.data-api blur.bs.button.data-api",'[data-toggle^="button"]',function(b){a(b.target).closest(".btn").toggleClass("focus",/^focus(in)?$/.test(b.type))})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},c.DEFAULTS,d.data(),"object"==typeof b&&b),g="string"==typeof b?b:f.slide;e||d.data("bs.carousel",e=new c(this,f)),"number"==typeof b?e.to(b):g?e[g]():f.interval&&e.pause().cycle()})}var c=function(b,c){this.$element=a(b),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=null,this.sliding=null,this.interval=null,this.$active=null,this.$items=null,this.options.keyboard&&this.$element.on("keydown.bs.carousel",a.proxy(this.keydown,this)),"hover"==this.options.pause&&!("ontouchstart"in document.documentElement)&&this.$element.on("mouseenter.bs.carousel",a.proxy(this.pause,this)).on("mouseleave.bs.carousel",a.proxy(this.cycle,this))};c.VERSION="3.3.6",c.TRANSITION_DURATION=600,c.DEFAULTS={interval:5e3,pause:"hover",wrap:!0,keyboard:!0},c.prototype.keydown=function(a){if(!/input|textarea/i.test(a.target.tagName)){switch(a.which){case 37:this.prev();break;case 39:this.next();break;default:return}a.preventDefault()}},c.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},c.prototype.getItemIndex=function(a){return this.$items=a.parent().children(".item"),this.$items.index(a||this.$active)},c.prototype.getItemForDirection=function(a,b){var c=this.getItemIndex(b),d="prev"==a&&0===c||"next"==a&&c==this.$items.length-1;if(d&&!this.options.wrap)return b;var e="prev"==a?-1:1,f=(c+e)%this.$items.length;return this.$items.eq(f)},c.prototype.to=function(a){var b=this,c=this.getItemIndex(this.$active=this.$element.find(".item.active"));return a>this.$items.length-1||0>a?void 0:this.sliding?this.$element.one("slid.bs.carousel",function(){b.to(a)}):c==a?this.pause().cycle():this.slide(a>c?"next":"prev",this.$items.eq(a))},c.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},c.prototype.next=function(){return this.sliding?void 0:this.slide("next")},c.prototype.prev=function(){return this.sliding?void 0:this.slide("prev")},c.prototype.slide=function(b,d){var e=this.$element.find(".item.active"),f=d||this.getItemForDirection(b,e),g=this.interval,h="next"==b?"left":"right",i=this;if(f.hasClass("active"))return this.sliding=!1;var j=f[0],k=a.Event("slide.bs.carousel",{relatedTarget:j,direction:h});if(this.$element.trigger(k),!k.isDefaultPrevented()){if(this.sliding=!0,g&&this.pause(),this.$indicators.length){this.$indicators.find(".active").removeClass("active");var l=a(this.$indicators.children()[this.getItemIndex(f)]);l&&l.addClass("active")}var m=a.Event("slid.bs.carousel",{relatedTarget:j,direction:h});return a.support.transition&&this.$element.hasClass("slide")?(f.addClass(b),f[0].offsetWidth,e.addClass(h),f.addClass(h),e.one("bsTransitionEnd",function(){f.removeClass([b,h].join(" ")).addClass("active"),e.removeClass(["active",h].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger(m)},0)}).emulateTransitionEnd(c.TRANSITION_DURATION)):(e.removeClass("active"),f.addClass("active"),this.sliding=!1,this.$element.trigger(m)),g&&this.cycle(),this}};var d=a.fn.carousel;a.fn.carousel=b,a.fn.carousel.Constructor=c,a.fn.carousel.noConflict=function(){return a.fn.carousel=d,this};var e=function(c){var d,e=a(this),f=a(e.attr("data-target")||(d=e.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""));if(f.hasClass("carousel")){var g=a.extend({},f.data(),e.data()),h=e.attr("data-slide-to");h&&(g.interval=!1),b.call(f,g),h&&f.data("bs.carousel").to(h),c.preventDefault()}};a(document).on("click.bs.carousel.data-api","[data-slide]",e).on("click.bs.carousel.data-api","[data-slide-to]",e),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var c=a(this);b.call(c,c.data())})})}(jQuery),+function(a){"use strict";function b(b){var c,d=b.attr("data-target")||(c=b.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,"");return a(d)}function c(b){return this.each(function(){var c=a(this),e=c.data("bs.collapse"),f=a.extend({},d.DEFAULTS,c.data(),"object"==typeof b&&b);!e&&f.toggle&&/show|hide/.test(b)&&(f.toggle=!1),e||c.data("bs.collapse",e=new d(this,f)),"string"==typeof b&&e[b]()})}var d=function(b,c){this.$element=a(b),this.options=a.extend({},d.DEFAULTS,c),this.$trigger=a('[data-toggle="collapse"][href="#'+b.id+'"],[data-toggle="collapse"][data-target="#'+b.id+'"]'),this.transitioning=null,this.options.parent?this.$parent=this.getParent():this.addAriaAndCollapsedClass(this.$element,this.$trigger),this.options.toggle&&this.toggle()};d.VERSION="3.3.6",d.TRANSITION_DURATION=350,d.DEFAULTS={toggle:!0},d.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},d.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var b,e=this.$parent&&this.$parent.children(".panel").children(".in, .collapsing");if(!(e&&e.length&&(b=e.data("bs.collapse"),b&&b.transitioning))){var f=a.Event("show.bs.collapse");if(this.$element.trigger(f),!f.isDefaultPrevented()){e&&e.length&&(c.call(e,"hide"),b||e.data("bs.collapse",null));var g=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[g](0).attr("aria-expanded",!0),this.$trigger.removeClass("collapsed").attr("aria-expanded",!0),this.transitioning=1;var h=function(){this.$element.removeClass("collapsing").addClass("collapse in")[g](""),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return h.call(this);var i=a.camelCase(["scroll",g].join("-"));this.$element.one("bsTransitionEnd",a.proxy(h,this)).emulateTransitionEnd(d.TRANSITION_DURATION)[g](this.$element[0][i])}}}},d.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var b=a.Event("hide.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse in").attr("aria-expanded",!1),this.$trigger.addClass("collapsed").attr("aria-expanded",!1),this.transitioning=1;var e=function(){this.transitioning=0,this.$element.removeClass("collapsing").addClass("collapse").trigger("hidden.bs.collapse")};return a.support.transition?void this.$element[c](0).one("bsTransitionEnd",a.proxy(e,this)).emulateTransitionEnd(d.TRANSITION_DURATION):e.call(this)}}},d.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()},d.prototype.getParent=function(){return a(this.options.parent).find('[data-toggle="collapse"][data-parent="'+this.options.parent+'"]').each(a.proxy(function(c,d){var e=a(d);this.addAriaAndCollapsedClass(b(e),e)},this)).end()},d.prototype.addAriaAndCollapsedClass=function(a,b){var c=a.hasClass("in");a.attr("aria-expanded",c),b.toggleClass("collapsed",!c).attr("aria-expanded",c)};var e=a.fn.collapse;a.fn.collapse=c,a.fn.collapse.Constructor=d,a.fn.collapse.noConflict=function(){return a.fn.collapse=e,this},a(document).on("click.bs.collapse.data-api",'[data-toggle="collapse"]',function(d){var e=a(this);e.attr("data-target")||d.preventDefault();var f=b(e),g=f.data("bs.collapse"),h=g?"toggle":e.data();c.call(f,h)})}(jQuery),+function(a){"use strict";function b(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#[A-Za-z]/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}function c(c){c&&3===c.which||(a(e).remove(),a(f).each(function(){var d=a(this),e=b(d),f={relatedTarget:this};e.hasClass("open")&&(c&&"click"==c.type&&/input|textarea/i.test(c.target.tagName)&&a.contains(e[0],c.target)||(e.trigger(c=a.Event("hide.bs.dropdown",f)),c.isDefaultPrevented()||(d.attr("aria-expanded","false"),e.removeClass("open").trigger(a.Event("hidden.bs.dropdown",f)))))}))}function d(b){return this.each(function(){var c=a(this),d=c.data("bs.dropdown");d||c.data("bs.dropdown",d=new g(this)),"string"==typeof b&&d[b].call(c)})}var e=".dropdown-backdrop",f='[data-toggle="dropdown"]',g=function(b){a(b).on("click.bs.dropdown",this.toggle)};g.VERSION="3.3.6",g.prototype.toggle=function(d){var e=a(this);if(!e.is(".disabled, :disabled")){var f=b(e),g=f.hasClass("open");if(c(),!g){"ontouchstart"in document.documentElement&&!f.closest(".navbar-nav").length&&a(document.createElement("div")).addClass("dropdown-backdrop").insertAfter(a(this)).on("click",c);var h={relatedTarget:this};if(f.trigger(d=a.Event("show.bs.dropdown",h)),d.isDefaultPrevented())return;e.trigger("focus").attr("aria-expanded","true"),f.toggleClass("open").trigger(a.Event("shown.bs.dropdown",h))}return!1}},g.prototype.keydown=function(c){if(/(38|40|27|32)/.test(c.which)&&!/input|textarea/i.test(c.target.tagName)){var d=a(this);if(c.preventDefault(),c.stopPropagation(),!d.is(".disabled, :disabled")){var e=b(d),g=e.hasClass("open");if(!g&&27!=c.which||g&&27==c.which)return 27==c.which&&e.find(f).trigger("focus"),d.trigger("click");var h=" li:not(.disabled):visible a",i=e.find(".dropdown-menu"+h);if(i.length){var j=i.index(c.target);38==c.which&&j>0&&j--,40==c.which&&jdocument.documentElement.clientHeight;this.$element.css({paddingLeft:!this.bodyIsOverflowing&&a?this.scrollbarWidth:"",paddingRight:this.bodyIsOverflowing&&!a?this.scrollbarWidth:""})},c.prototype.resetAdjustments=function(){this.$element.css({paddingLeft:"",paddingRight:""})},c.prototype.checkScrollbar=function(){var a=window.innerWidth;if(!a){var b=document.documentElement.getBoundingClientRect();a=b.right-Math.abs(b.left)}this.bodyIsOverflowing=document.body.clientWidth
',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0}},c.prototype.init=function(b,c,d){if(this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d),this.$viewport=this.options.viewport&&a(a.isFunction(this.options.viewport)?this.options.viewport.call(this,this.$element):this.options.viewport.selector||this.options.viewport),this.inState={click:!1,hover:!1,focus:!1},this.$element[0]instanceof document.constructor&&!this.options.selector)throw new Error("`selector` option must be specified when initializing "+this.type+" on the window.document object!");for(var e=this.options.trigger.split(" "),f=e.length;f--;){var g=e[f];if("click"==g)this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this));else if("manual"!=g){var h="hover"==g?"mouseenter":"focusin",i="hover"==g?"mouseleave":"focusout";this.$element.on(h+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(i+"."+this.type,this.options.selector,a.proxy(this.leave,this))}}this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.getOptions=function(b){return b=a.extend({},this.getDefaults(),this.$element.data(),b),b.delay&&"number"==typeof b.delay&&(b.delay={show:b.delay,hide:b.delay}),b},c.prototype.getDelegateOptions=function(){var b={},c=this.getDefaults();return this._options&&a.each(this._options,function(a,d){c[a]!=d&&(b[a]=d)}),b},c.prototype.enter=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusin"==b.type?"focus":"hover"]=!0),c.tip().hasClass("in")||"in"==c.hoverState?void(c.hoverState="in"):(clearTimeout(c.timeout),c.hoverState="in",c.options.delay&&c.options.delay.show?void(c.timeout=setTimeout(function(){"in"==c.hoverState&&c.show()},c.options.delay.show)):c.show())},c.prototype.isInStateTrue=function(){for(var a in this.inState)if(this.inState[a])return!0;return!1},c.prototype.leave=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusout"==b.type?"focus":"hover"]=!1),c.isInStateTrue()?void 0:(clearTimeout(c.timeout),c.hoverState="out",c.options.delay&&c.options.delay.hide?void(c.timeout=setTimeout(function(){"out"==c.hoverState&&c.hide()},c.options.delay.hide)):c.hide())},c.prototype.show=function(){var b=a.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(b);var d=a.contains(this.$element[0].ownerDocument.documentElement,this.$element[0]);if(b.isDefaultPrevented()||!d)return;var e=this,f=this.tip(),g=this.getUID(this.type);this.setContent(),f.attr("id",g),this.$element.attr("aria-describedby",g),this.options.animation&&f.addClass("fade");var h="function"==typeof this.options.placement?this.options.placement.call(this,f[0],this.$element[0]):this.options.placement,i=/\s?auto?\s?/i,j=i.test(h);j&&(h=h.replace(i,"")||"top"),f.detach().css({top:0,left:0,display:"block"}).addClass(h).data("bs."+this.type,this),this.options.container?f.appendTo(this.options.container):f.insertAfter(this.$element),this.$element.trigger("inserted.bs."+this.type);var k=this.getPosition(),l=f[0].offsetWidth,m=f[0].offsetHeight;if(j){var n=h,o=this.getPosition(this.$viewport);h="bottom"==h&&k.bottom+m>o.bottom?"top":"top"==h&&k.top-mo.width?"left":"left"==h&&k.left-lg.top+g.height&&(e.top=g.top+g.height-i)}else{var j=b.left-f,k=b.left+f+c;jg.right&&(e.left=g.left+g.width-k)}return e},c.prototype.getTitle=function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||("function"==typeof c.title?c.title.call(b[0]):c.title)},c.prototype.getUID=function(a){do a+=~~(1e6*Math.random());while(document.getElementById(a));return a},c.prototype.tip=function(){if(!this.$tip&&(this.$tip=a(this.options.template),1!=this.$tip.length))throw new Error(this.type+" `template` option must consist of exactly 1 top-level element!");return this.$tip},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},c.prototype.enable=function(){this.enabled=!0},c.prototype.disable=function(){this.enabled=!1},c.prototype.toggleEnabled=function(){this.enabled=!this.enabled},c.prototype.toggle=function(b){var c=this;b&&(c=a(b.currentTarget).data("bs."+this.type),c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c))),b?(c.inState.click=!c.inState.click,c.isInStateTrue()?c.enter(c):c.leave(c)):c.tip().hasClass("in")?c.leave(c):c.enter(c)},c.prototype.destroy=function(){var a=this;clearTimeout(this.timeout),this.hide(function(){a.$element.off("."+a.type).removeData("bs."+a.type),a.$tip&&a.$tip.detach(),a.$tip=null,a.$arrow=null,a.$viewport=null})};var d=a.fn.tooltip;a.fn.tooltip=b,a.fn.tooltip.Constructor=c,a.fn.tooltip.noConflict=function(){return a.fn.tooltip=d,this}}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof b&&b;(e||!/destroy|hide/.test(b))&&(e||d.data("bs.popover",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.init("popover",a,b)};if(!a.fn.tooltip)throw new Error("Popover requires tooltip.js");c.VERSION="3.3.6",c.DEFAULTS=a.extend({},a.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:''}),c.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),c.prototype.constructor=c,c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content").children().detach().end()[this.options.html?"string"==typeof c?"html":"append":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},c.prototype.hasContent=function(){return this.getTitle()||this.getContent()},c.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")};var d=a.fn.popover;a.fn.popover=b,a.fn.popover.Constructor=c,a.fn.popover.noConflict=function(){return a.fn.popover=d,this}}(jQuery),+function(a){"use strict";function b(c,d){this.$body=a(document.body),this.$scrollElement=a(a(c).is(document.body)?window:c),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||"")+" .nav li > a",this.offsets=[],this.targets=[],this.activeTarget=null,this.scrollHeight=0,this.$scrollElement.on("scroll.bs.scrollspy",a.proxy(this.process,this)),this.refresh(),this.process()}function c(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})}b.VERSION="3.3.6",b.DEFAULTS={offset:10},b.prototype.getScrollHeight=function(){return this.$scrollElement[0].scrollHeight||Math.max(this.$body[0].scrollHeight,document.documentElement.scrollHeight)},b.prototype.refresh=function(){var b=this,c="offset",d=0;this.offsets=[],this.targets=[],this.scrollHeight=this.getScrollHeight(),a.isWindow(this.$scrollElement[0])||(c="position",d=this.$scrollElement.scrollTop()),this.$body.find(this.selector).map(function(){var b=a(this),e=b.data("target")||b.attr("href"),f=/^#./.test(e)&&a(e);return f&&f.length&&f.is(":visible")&&[[f[c]().top+d,e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){b.offsets.push(this[0]),b.targets.push(this[1])})},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.getScrollHeight(),d=this.options.offset+c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(this.scrollHeight!=c&&this.refresh(),b>=d)return g!=(a=f[f.length-1])&&this.activate(a);if(g&&b=e[a]&&(void 0===e[a+1]||b .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!1),b.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded",!0),h?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu").length&&b.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!0),e&&e()}var g=d.find("> .active"),h=e&&a.support.transition&&(g.length&&g.hasClass("fade")||!!d.find("> .fade").length);g.length&&h?g.one("bsTransitionEnd",f).emulateTransitionEnd(c.TRANSITION_DURATION):f(),g.removeClass("in")};var d=a.fn.tab;a.fn.tab=b,a.fn.tab.Constructor=c,a.fn.tab.noConflict=function(){return a.fn.tab=d,this};var e=function(c){c.preventDefault(),b.call(a(this),"show")};a(document).on("click.bs.tab.data-api",'[data-toggle="tab"]',e).on("click.bs.tab.data-api",'[data-toggle="pill"]',e)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof b&&b;e||d.data("bs.affix",e=new c(this,f)),"string"==typeof b&&e[b]()})}var c=function(b,d){this.options=a.extend({},c.DEFAULTS,d),this.$target=a(this.options.target).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(b),this.affixed=null,this.unpin=null,this.pinnedOffset=null,this.checkPosition()};c.VERSION="3.3.6",c.RESET="affix affix-top affix-bottom",c.DEFAULTS={offset:0,target:window},c.prototype.getState=function(a,b,c,d){var e=this.$target.scrollTop(),f=this.$element.offset(),g=this.$target.height();if(null!=c&&"top"==this.affixed)return c>e?"top":!1;if("bottom"==this.affixed)return null!=c?e+this.unpin<=f.top?!1:"bottom":a-d>=e+g?!1:"bottom";var h=null==this.affixed,i=h?e:f.top,j=h?g:b;return null!=c&&c>=e?"top":null!=d&&i+j>=a-d?"bottom":!1},c.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(c.RESET).addClass("affix");var a=this.$target.scrollTop(),b=this.$element.offset();return this.pinnedOffset=b.top-a},c.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},c.prototype.checkPosition=function(){if(this.$element.is(":visible")){var b=this.$element.height(),d=this.options.offset,e=d.top,f=d.bottom,g=Math.max(a(document).height(),a(document.body).height());"object"!=typeof d&&(f=e=d),"function"==typeof e&&(e=d.top(this.$element)),"function"==typeof f&&(f=d.bottom(this.$element));var h=this.getState(g,b,e,f);if(this.affixed!=h){null!=this.unpin&&this.$element.css("top","");var i="affix"+(h?"-"+h:""),j=a.Event(i+".bs.affix");if(this.$element.trigger(j),j.isDefaultPrevented())return;this.affixed=h,this.unpin="bottom"==h?this.getPinnedOffset():null,this.$element.removeClass(c.RESET).addClass(i).trigger(i.replace("affix","affixed")+".bs.affix")}"bottom"==h&&this.$element.offset({top:g-b-f})}};var d=a.fn.affix;a.fn.affix=b,a.fn.affix.Constructor=c,a.fn.affix.noConflict=function(){return a.fn.affix=d,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var c=a(this),d=c.data();d.offset=d.offset||{},null!=d.offsetBottom&&(d.offset.bottom=d.offsetBottom),null!=d.offsetTop&&(d.offset.top=d.offsetTop),b.call(c,d)})})}(jQuery); \ No newline at end of file diff --git a/downloaded_folder/public/js/freewall.js b/downloaded_folder/public/js/freewall.js new file mode 100644 index 0000000..01d217e --- /dev/null +++ b/downloaded_folder/public/js/freewall.js @@ -0,0 +1,1272 @@ +// created by Minh Nguyen; +// version 1.0.6; + +(function($) { + + // for zeptojs; + $.isNumeric == null && ($.isNumeric = function(src) { + return src != null && src.constructor === Number; + }); + + $.isFunction == null && ($.isFunction = function(src) { + return src != null && src instanceof Function; + }); + + var $W = $(window); + var $D = $(document); + + var layoutManager = { + // default setting; + defaultConfig: { + animate: false, + cellW: 100, // function(container) {return 100;} + cellH: 100, // function(container) {return 100;} + delay: 0, // slowdown active block; + engine: 'giot', + fixSize: null, // resize + adjust = fill gap; + //fixSize: 0, resize but keep ratio = no fill gap; + //fixSize: 1, no resize + no adjust = no fill gap; + gutterX: 15, // width spacing between blocks; + gutterY: 15, // height spacing between blocks; + keepOrder: false, + selector: '> div', + draggable: false, + cacheSize: true, // caches the original size of block; + rightToLeft: false, + bottomToTop: false, + onGapFound: function() {}, + onComplete: function() {}, + onResize: function() {}, + onBlockDrag: function() {}, + onBlockMove: function() {}, + onBlockDrop: function() {}, + onBlockReady: function() {}, + onBlockFinish: function() {}, + onBlockActive: function() {}, + onBlockResize: function() {} + }, + plugin: {}, + totalGrid: 1, + transition: false, + loadBlock: function(item, setting) { + var runtime = setting.runtime; + var gutterX = runtime.gutterX; + var gutterY = runtime.gutterY; + var cellH = runtime.cellH; + var cellW = runtime.cellW; + var block = null; + var $item = $(item); + var active = $item.data("active"); + var fixPos = $item.attr('data-position'); + var fixSize = parseInt($item.attr('data-fixSize')); + var blockId = runtime.lastId++ + '-' + runtime.totalGrid; + + //ignore dragging block; + if ($item.hasClass('fw-float')) return null; + $item.attr({id: blockId, 'data-delay': item.index}); + + //remove animation for speed render; + if (setting.animate && this.transition) { + this.setTransition(item, ""); + } + + isNaN(fixSize) && (fixSize = null); + (fixSize == null) && (fixSize = setting.fixSize); + var makeRound = (!fixSize) ? "round" : "ceil"; + // store original size; + + $item.attr('data-height') == null && $item.attr('data-height', $item.height()); + $item.attr('data-width') == null && $item.attr('data-width', $item.width()); + var height = 1 * $item.attr('data-height'); + var width = 1 * $item.attr('data-width'); + + if (!setting.cacheSize) { + item.style.width = ""; + width = $item.width(); + + item.style.height = ""; + height = $item.height(); + } + + var col = !width ? 0 : Math[makeRound]((width + gutterX) / cellW); + var row = !height ? 0 : Math[makeRound]((height + gutterY) / cellH); + + // estimate size; + if (!fixSize && setting.cellH == 'auto') { + $item.width(cellW * col - gutterX); + item.style.height = ""; + height = $item.height(); + row = !height ? 0 : Math.round((height + gutterY) / cellH); + } + + if (!fixSize && setting.cellW == 'auto') { + $item.height(cellH * row - gutterY); + item.style.width = ""; + width = $item.width(); + col = !width ? 0 : Math.round((width + gutterX) / cellW); + } + + // for none resize block; + if ((fixSize != null) && (col > runtime.limitCol || row > runtime.limitRow)) { + block = null; + } else { + // get smallest width and smallest height of block; + // using for image runtime; + row && row < runtime.minHoB && (runtime.minHoB = row); + col && col < runtime.minWoB && (runtime.minWoB = col); + + // get biggest width and biggest height of block; + row > runtime.maxHoB && (runtime.maxHoB = row); + col > runtime.maxWoB && (runtime.maxWoB = col); + + width == 0 && (col = 0); + height == 0 && (row = 0); + + block = { + resize: false, + id: blockId, + width: col, + height: row, + fixSize: fixSize + }; + + // for fix position; + if (fixPos) { + fixPos = fixPos.split("-"); + block.y = 1 * fixPos[0]; + block.x = 1 * fixPos[1]; + block.width = fixSize != null ? col : Math.min(col, runtime.limitCol - block.x); + block.height = fixSize != null ? row : Math.min(row, runtime.limitRow - block.y); + var holeId = block.y + "-" + block.x + "-" + block.width + "-" + block.height; + if (active) { + runtime.holes[holeId] = { + id: block.id, + top: block.y, + left: block.x, + width: block.width, + height: block.height + }; + this.setBlock(block, setting); + } else { + delete runtime.holes[holeId]; + } + + } + } + + // for css animation; + if ($item.attr("data-state") == null) { + $item.attr("data-state", "init"); + } else { + $item.attr("data-state", "move"); + } + + setting.onBlockReady.call(item, block, setting); + + return (fixPos && active) ? null : block; + }, + setBlock: function(block, setting) { + var runtime = setting.runtime; + var gutterX = runtime.gutterX; + var gutterY = runtime.gutterY; + var height = block.height; + var width = block.width; + var cellH = runtime.cellH; + var cellW = runtime.cellW; + var x = block.x; + var y = block.y; + + if (setting.rightToLeft) { + x = runtime.limitCol - x - width; + } + if (setting.bottomToTop) { + y = runtime.limitRow - y - height; + } + + var realBlock = { + fixSize: block.fixSize, + resize: block.resize, + top: y * cellH, + left: x * cellW, + width: cellW * width - gutterX, + height: cellH * height - gutterY + }; + + realBlock.top = 1 * realBlock.top.toFixed(2); + realBlock.left = 1 * realBlock.left.toFixed(2); + realBlock.width = 1 * realBlock.width.toFixed(2); + realBlock.height = 1 * realBlock.height.toFixed(2); + + //runtime.length += 1; + block.id && (runtime.blocks[block.id] = realBlock); + + // for append feature; + return realBlock; + }, + showBlock: function(item, setting) { + var runtime = setting.runtime; + var method = setting.animate && !this.transition ? 'animate' : 'css'; + var block = runtime.blocks[item.id]; + var $item = $(item); + var self = this; + var start = $item.attr("data-state") != "move"; + var trans = start ? "width 0.5s, height 0.5s" : "top 0.5s, left 0.5s, width 0.5s, height 0.5s, opacity 0.5s"; + + item.delay && clearTimeout(item.delay); + //ignore dragging block; + if ($item.hasClass('fw-float')) return; + + // kill the old transition; + self.setTransition(item, ""); + item.style.position = "absolute"; + setting.onBlockActive.call(item, block, setting); + + function action() { + // start to arrange; + start && $item.attr("data-state", "start"); + // add animation by using css3 transition; + if (setting.animate && self.transition) { + self.setTransition(item, trans); + } + + runtime.length -= 1; + + // for hidden block; + if (!block) { + //var position = $item.position(); <= make speed so slow; + var height = parseInt(item.style.height) || 0; + var width = parseInt(item.style.width) || 0; + var left = parseInt(item.style.left) || 0; + var top = parseInt(item.style.top) || 0; + $item[method]({ + left: left + width / 2, + top: top + height / 2, + width: 0, + height: 0, + opacity: 0 + }); + } else { + if (block.fixSize) { + block.height = 1 * $item.attr("data-height"); + block.width = 1 * $item.attr("data-width"); + } + + $item["css"]({ + opacity: 1, + width: block.width, + height: block.height + }); + + // for animating by javascript; + $item[method]({ + top: block.top, + left: block.left + }); + + if ($item.attr('data-nested') != null) { + self.nestedGrid(item, setting); + } + } + + setting.onBlockFinish.call(item, block, setting); + + if (runtime.length == 0) { + var duration = setting.animate ? 500 : 0; + item.delay = setTimeout(function() { + setting.onComplete.call(item, block, setting); + }, duration); + } + } + + block && block.resize && setting.onBlockResize.call(item, block, setting); + + setting.delay > 0 ? (item.delay = setTimeout(action, setting.delay * $item.attr("data-delay"))) : action(); + }, + nestedGrid: function(item, setting) { + var innerWall, $item = $(item), runtime = setting.runtime; + var gutterX = $item.attr("data-gutterX") || setting.gutterX; + var gutterY = $item.attr("data-gutterY") || setting.gutterY; + var method = $item.attr("data-method") || "fitZone"; + var nested = $item.attr('data-nested') || "> div"; + var cellH = $item.attr("data-cellH") || setting.cellH; + var cellW = $item.attr("data-cellW") || setting.cellW; + var block = runtime.blocks[item.id]; + + if (block) { + innerWall = new Freewall($item); + innerWall.reset({ + cellH: cellH, + cellW: cellW, + gutterX: 1 * gutterX, + gutterY: 1 * gutterY, + selector: nested, + cacheSize: false + }); + + switch (method) { + case "fitHeight": + innerWall[method](block.height); + break; + case "fitWidth": + innerWall[method](block.width); + break; + case "fitZone": + innerWall[method](block.width, block.height); + break; + } + } + }, + adjustBlock: function(block, setting) { + var runtime = setting.runtime; + var gutterX = runtime.gutterX; + var gutterY = runtime.gutterY; + var $item = $("#" + block.id); + var cellH = runtime.cellH; + var cellW = runtime.cellW; + + if (setting.cellH == 'auto') { + $item.width(block.width * cellW - gutterX); + $item[0].style.height = ""; + block.height = Math.round(($item.height() + gutterY) / cellH); + } + }, + adjustUnit: function(width, height, setting) { + var gutterX = setting.gutterX; + var gutterY = setting.gutterY; + var runtime = setting.runtime; + var cellW = setting.cellW; + var cellH = setting.cellH; + + $.isFunction(cellW) && (cellW = cellW(width)); + cellW = 1 * cellW; + !$.isNumeric(cellW) && (cellW = 1); + + $.isFunction(cellH) && (cellH = cellH(height)); + cellH = 1 * cellH; + !$.isNumeric(cellH) && (cellH = 1); + + if ($.isNumeric(width)) { + // adjust cell width via container; + cellW < 1 && (cellW = cellW * width); + + // estimate total columns; + var limitCol = Math.max(1, Math.floor(width / cellW)); + + // adjust unit size for fit width; + if (!$.isNumeric(gutterX)) { + gutterX = (width - limitCol * cellW) / Math.max(1, (limitCol - 1)); + gutterX = Math.max(0, gutterX); + } + + limitCol = Math.floor((width + gutterX) / cellW); + runtime.cellW = (width + gutterX) / Math.max(limitCol, 1); + runtime.cellS = runtime.cellW / cellW; + runtime.gutterX = gutterX; + runtime.limitCol = limitCol; + } + + if ($.isNumeric(height)) { + // adjust cell height via container; + cellH < 1 && (cellH = cellH * height); + + // estimate total rows; + var limitRow = Math.max(1, Math.floor(height / cellH)); + + // adjust size unit for fit height; + if (!$.isNumeric(gutterY)) { + gutterY = (height - limitRow * cellH) / Math.max(1, (limitRow - 1)); + gutterY = Math.max(0, gutterY); + } + + limitRow = Math.floor((height + gutterY) / cellH); + runtime.cellH = (height + gutterY) / Math.max(limitRow, 1); + runtime.cellS = runtime.cellH / cellH; + runtime.gutterY = gutterY; + runtime.limitRow = limitRow; + } + + if (!$.isNumeric(width)) { + // adjust cell width via cell height; + cellW < 1 && (cellW = runtime.cellH); + runtime.cellW = cellW != 1 ? cellW * runtime.cellS : 1; + runtime.gutterX = gutterX; + runtime.limitCol = 666666; + } + + if (!$.isNumeric(height)) { + // adjust cell height via cell width; + cellH < 1 && (cellH = runtime.cellW); + runtime.cellH = cellH != 1 ? cellH * runtime.cellS : 1; + runtime.gutterY = gutterY; + runtime.limitRow = 666666; + } + + runtime.keepOrder = setting.keepOrder; + }, + resetGrid: function(runtime) { + runtime.blocks = {}; + runtime.length = 0; + runtime.cellH = 0; + runtime.cellW = 0; + runtime.lastId = 1; + runtime.matrix = {}; + runtime.totalCol = 0; + runtime.totalRow = 0; + }, + setDraggable: function(item, option) { + var isTouch = false; + var config = { + startX: 0, //start clientX; + startY: 0, + top: 0, + left: 0, + handle: null, + onDrop: function() {}, + onDrag: function() {}, + onStart: function() {} + }; + + $(item).each(function() { + var setting = $.extend({}, config, option); + var handle = setting.handle || this; + var ele = this; + var $E = $(ele); + var $H = $(handle); + + var posStyle = $E.css("position"); + posStyle != "absolute" && $E.css("position", "relative"); + + + function mouseDown(evt) { + evt.stopPropagation(); + evt = evt.originalEvent; + + if (evt.touches) { + isTouch = true; + evt = evt.changedTouches[0]; + } + + if (evt.button != 2 && evt.which != 3) { + setting.onStart.call(ele, evt); + + setting.startX = evt.clientX; + setting.startY = evt.clientY; + setting.top = parseInt($E.css("top")) || 0; + setting.left = parseInt($E.css("left")) || 0; + + $D.bind("mouseup touchend", mouseUp); + $D.bind("mousemove touchmove", mouseMove); + } + + return false; + }; + + + function mouseMove(evt) { + evt = evt.originalEvent; + isTouch && (evt = evt.changedTouches[0]); + + $E.css({ + top: setting.top - (setting.startY - evt.clientY), + left: setting.left - (setting.startX - evt.clientX) + }); + + setting.onDrag.call(ele, evt); + }; + + function mouseUp(evt) { + evt = evt.originalEvent; + isTouch && (evt = evt.changedTouches[0]); + + setting.onDrop.call(ele, evt); + + $D.unbind("mouseup touchend", mouseUp); + $D.unbind("mousemove touchmove", mouseMove); + }; + + // ignore drag drop on text field; + $E.find("iframe, form, input, textarea, .ignore-drag") + .each(function() { + $(this).on("touchstart mousedown", function(evt) { + evt.stopPropagation(); + }); + }); + + $D.unbind("mouseup touchend", mouseUp); + $D.unbind("mousemove touchmove", mouseMove); + $H.unbind("mousedown touchstart").bind("mousedown touchstart", mouseDown); + + }); + }, + setTransition: function(item, trans) { + var style = item.style; + var $item = $(item); + + // remove animation; + if (!this.transition && $item.stop) { + $item.stop(); + } else if (style.webkitTransition != null) { + style.webkitTransition = trans; + } else if (style.MozTransition != null) { + style.MozTransition = trans; + } else if (style.msTransition != null) { + style.msTransition = trans; + } else if (style.OTransition != null) { + style.OTransition = trans; + } else { + style.transition = trans; + } + }, + getFreeArea: function(t, l, runtime) { + var maxY = Math.min(t + runtime.maxHoB, runtime.limitRow); + var maxX = Math.min(l + runtime.maxWoB, runtime.limitCol); + var minX = maxX; + var minY = maxY; + var matrix = runtime.matrix; + + // find limit zone by horizon; + for (var y = t; y < minY; ++y) { + for (var x = l; x < maxX; ++x) { + if (matrix[y + '-' + x]) { + (l < x && x < minX) && (minX = x); + } + } + } + + // find limit zone by vertical; + for (var y = t; y < maxY; ++y) { + for (var x = l; x < minX; ++x) { + if (matrix[y + '-' + x]) { + (t < y && y < minY) && (minY = y); + } + } + } + + return { + top: t, + left: l, + width: minX - l, + height: minY - t + }; + + }, + setWallSize: function(runtime, container) { + var totalRow = runtime.totalRow; + var totalCol = runtime.totalCol; + var gutterY = runtime.gutterY; + var gutterX = runtime.gutterX; + var cellH = runtime.cellH; + var cellW = runtime.cellW; + var totalWidth = Math.max(0, cellW * totalCol - gutterX); + var totalHeight = Math.max(0, cellH * totalRow - gutterY); + + container.attr({ + 'data-total-col': totalCol, + 'data-total-row': totalRow, + 'data-wall-width': Math.ceil(totalWidth), + 'data-wall-height': Math.ceil(totalHeight) + }); + + if (runtime.limitCol < runtime.limitRow) { + // do not set height with nesting grid; + !container.attr("data-height") && container.height(Math.ceil(totalHeight)); + } + } + }; + + + + var engine = { + // Giot just a person name; + giot: function(items, setting) { + var runtime = setting.runtime, + row = runtime.limitRow, + col = runtime.limitCol, + x = 0, + y = 0, + maxX = runtime.totalCol, + maxY = runtime.totalRow, + wall = {}, + holes = runtime.holes, + block = null, + matrix = runtime.matrix, + bigLoop = Math.max(col, row), + freeArea = null, + misBlock = null, + fitWidth = col < row ? 1 : 0, + lastBlock = null, + smallLoop = Math.min(col, row); + + // fill area with top, left, width, height; + function fillMatrix(id, t, l, w, h) { + for (var y = t; y < t + h;) { + for (var x = l; x < l + w;) { + matrix[y + '-' + x] = id; + ++x > maxX && (maxX = x); + } + ++y > maxY && (maxY = y); + } + } + + // set holes on the wall; + for (var i in holes) { + if (holes.hasOwnProperty(i)) { + fillMatrix(holes[i]["id"] || true, holes[i]['top'], holes[i]['left'], holes[i]['width'], holes[i]['height']); + } + } + + + for (var b = 0; b < bigLoop; ++b) { + if (!items.length) break; + fitWidth ? (y = b) : (x = b); + lastBlock = null; + + for (var s = 0; s < smallLoop; ++s) { + if (!items.length) break; + block = null; + fitWidth ? (x = s) : (y = s); + if (runtime.matrix[y + '-' + x]) continue; + freeArea = layoutManager.getFreeArea(y, x, runtime); + + // trying resize last block to fit free area; + if (setting.fixSize == null) { + // resize near block to fill gap; + if (lastBlock && !fitWidth && runtime.minHoB > freeArea.height) { + lastBlock.height += freeArea.height; + lastBlock.resize = true; + fillMatrix(lastBlock.id, lastBlock.y, lastBlock.x, lastBlock.width, lastBlock.height); + layoutManager.setBlock(lastBlock, setting); + continue; + } else if (lastBlock && fitWidth && runtime.minWoB > freeArea.width) { + lastBlock.width += freeArea.width; + lastBlock.resize = true; + fillMatrix(lastBlock.id, lastBlock.y, lastBlock.x, lastBlock.width, lastBlock.height); + layoutManager.setBlock(lastBlock, setting); + continue; + } + } + + // get the next block to keep order; + if (runtime.keepOrder) { + block = items.shift(); + block.resize = true; + } else { + // find a suitable block to fit gap; + for (var i = 0; i < items.length; ++i) { + if (items[i].height > freeArea.height) continue; + if (items[i].width > freeArea.width) continue; + block = items.splice(i, 1)[0]; + break; + } + + // trying resize the other block to fit gap; + if (block == null && setting.fixSize == null) { + // get other block fill to gap; + for (var i = 0; i < items.length; ++i) { + if (items[i]['fixSize'] != null) continue; + block = items.splice(i, 1)[0]; + block.resize = true; + break; + } + + } + } + + + if (block != null) { + // resize block with free area; + if (block.resize) { + if (fitWidth) { + block.width = freeArea.width; + if (setting.cellH == 'auto') { + layoutManager.adjustBlock(block, setting); + } + // for fitZone; + block.height = Math.min(block.height, freeArea.height); + } else { + block.height = freeArea.height; + // for fitZone; + block.width = Math.min(block.width, freeArea.width); + } + } + + wall[block.id] = { + id: block.id, + x: x, + y: y, + width: block.width, + height: block.height, + resize: block.resize, + fixSize: block.fixSize + }; + + // keep success block for next round; + lastBlock = wall[block.id]; + + fillMatrix(lastBlock.id, lastBlock.y, lastBlock.x, lastBlock.width, lastBlock.height); + layoutManager.setBlock(lastBlock, setting); + } else { + // get expect area; + var misBlock = { + x: x, + y: y, + fixSize: 0 + }; + if (fitWidth) { + misBlock.width = freeArea.width; + misBlock.height = 0; + var lastX = x - 1; + var lastY = y; + + while (matrix[lastY + '-' + lastX]) { + matrix[lastY + '-' + x] = true; + misBlock.height += 1; + lastY += 1; + } + } else { + misBlock.height = freeArea.height; + misBlock.width = 0; + var lastY = y - 1; + var lastX = x; + + while (matrix[lastY + '-' + lastX]) { + matrix[y + '-' + lastX] = true; + misBlock.width += 1; + lastX += 1; + } + } + setting.onGapFound(layoutManager.setBlock(misBlock, setting), setting); + } + } + + } + + runtime.matrix = matrix; + runtime.totalRow = maxY; + runtime.totalCol = maxX; + } + }; + + + + function Freewall(selector) { + + var container = $(selector); + if (container.css('position') == 'static') { + container.css('position', 'relative'); + } + var MAX = Number.MAX_VALUE; + var klass = this; + // increase the instance index; + layoutManager.totalGrid += 1; + + var setting = $.extend({}, layoutManager.defaultConfig); + var runtime = { + arguments: null, + blocks: {}, // store all items; + events: {}, // store custome events; + matrix: {}, + holes: {}, // forbidden zone; + + cellW: 0, + cellH: 0, // unit adjust; + cellS: 1, // unit scale; + + filter: '', // filter selector; + lastId: 0, + length: 0, + + maxWoB: 0, // max width of block; + maxHoB: 0, + minWoB: MAX, + minHoB: MAX, // min height of block; + + running: 0, // flag to check layout arranging; + + gutterX: 15, + gutterY: 15, + + totalCol: 0, + totalRow: 0, + + limitCol: 666666, // maximum column; + limitRow: 666666, + + sortFunc: null, + keepOrder: false + }; + setting.runtime = runtime; + runtime.totalGrid = layoutManager.totalGrid; + + // check browser support transition; + var bodyStyle = document.body.style; + if (!layoutManager.transition) { + (bodyStyle.webkitTransition != null || + bodyStyle.MozTransition != null || + bodyStyle.msTransition != null || + bodyStyle.OTransition != null || + bodyStyle.transition != null) && + (layoutManager.transition = true); + } + + + function setDraggable(item) { + + var gutterX = runtime.gutterX; + var gutterY = runtime.gutterY; + var cellH = runtime.cellH; + var cellW = runtime.cellW; + var $item = $(item); + var handle = $item.find($item.attr("data-handle")); + layoutManager.setDraggable(item, { + handle: handle[0], + onStart: function(event) { + if (setting.animate && layoutManager.transition) { + layoutManager.setTransition(this, ""); + } + $item.css('z-index', 9999).addClass('fw-float'); + + setting.onBlockDrag.call(item, event); + }, + onDrag: function(event, tracker) { + var position = $item.position(); + var top = Math.round(position.top / cellH); + var left = Math.round(position.left / cellW); + var width = Math.round($item.width() / cellW); + var height = Math.round($item.height() / cellH); + top = Math.min(Math.max(0, top), runtime.limitRow - height); + left = Math.min(Math.max(0, left), runtime.limitCol - width); + klass.setHoles({top: top, left: left, width: width, height: height}); + klass.refresh(); + + setting.onBlockMove.call(item, event); + }, + onDrop: function(event) { + var position = $item.position(); + var top = Math.round(position.top / cellH); + var left = Math.round(position.left / cellW); + var width = Math.round($item.width() / cellW); + var height = Math.round($item.height() / cellH); + top = Math.min(Math.max(0, top), runtime.limitRow - height); + left = Math.min(Math.max(0, left), runtime.limitCol - width); + + $item.removeClass('fw-float'); + $item.css({ + zIndex: "auto", + top: top * cellH, + left: left * cellW + }); + + //check old drag element; + var x, y, key, oldDropId; + for (y = 0; y < height; ++y) { + for (x = 0; x < width; ++x) { + key = (y + top) + "-" + (x + left); + oldDropId = runtime.matrix[key]; + if (oldDropId && oldDropId != true) { + $("#" + oldDropId).removeAttr("data-position"); + } + } + } + + runtime.holes = {}; + + $item.attr({ + "data-width": $item.width(), + "data-height": $item.height(), + "data-position": top + "-" + left + }); + + klass.refresh(); + + setting.onBlockDrop.call(item, event); + } + }); + } + + + $.extend(klass, { + + addCustomEvent: function(name, func) { + var events = runtime.events; + name = name.toLowerCase(); + !events[name] && (events[name] = []); + func.eid = events[name].length; + events[name].push(func); + return this; + }, + + appendBlock: function(items) { + var allBlock = $(items).appendTo(container); + var block = null; + var activeBlock = []; + + if (runtime.arguments) { + + if ($.isFunction(runtime.sortFunc)) { + allBlock.sort(runtime.sortFunc); + } + + allBlock.each(function(index, item) { + item.index = ++index; + block = layoutManager.loadBlock(item, setting); + block && activeBlock.push(block); + }); + + engine[setting.engine](activeBlock, setting); + + layoutManager.setWallSize(runtime, container); + + runtime.length = allBlock.length; + + allBlock.each(function(index, item) { + layoutManager.showBlock(item, setting); + if (setting.draggable || item.getAttribute('data-draggable')) { + setDraggable(item); + } + }); + } + }, + /* + add one or more blank area (hole) on layout; + example: + + wall.appendHoles({ + top: 10, + left: 36, + width: 2, + height: 6 + }); + + wall.appendHoles([ + { + top: 16, + left: 16, + width: 8, + height: 2 + }, + { + top: 10, + left: 36, + width: 2, + height: 6 + } + ]); + + */ + appendHoles: function(holes) { + var newHoles = [].concat(holes), h = {}, i; + for (i = 0; i < newHoles.length; ++i) { + h = newHoles[i]; + runtime.holes[h.top + "-" + h.left + "-" + h.width + "-" + h.height] = h; + } + return this; + }, + + container: container, + + destroy: function() { + var allBlock = container.find(setting.selector).removeAttr('id'), + block = null, + activeBlock = []; + + allBlock.each(function(index, item) { + $item = $(item); + var width = 1 * $item.attr('data-width') || ""; + var height = 1 * $item.attr('data-height') || ""; + $item.width(width).height(height).css({ + position: 'static' + }); + }); + }, + + fillHoles: function(holes) { + if (arguments.length == 0) { + runtime.holes = {}; + } else { + var newHoles = [].concat(holes), h = {}, i; + for (i = 0; i < newHoles.length; ++i) { + h = newHoles[i]; + delete runtime.holes[h.top + "-" + h.left + "-" + h.width + "-" + h.height]; + } + } + return this; + }, + + filter: function(filter) { + runtime.filter = filter; + if (runtime.arguments) { + this.refresh(); + } + return this; + }, + + fireEvent: function(name, object, setting) { + var events = runtime.events; + name = name.toLowerCase(); + if (events[name] && events[name].length) { + for (var i = 0; i < events[name].length; ++i) { + events[name][i].call(this, object, setting); + } + } + return this; + }, + + fitHeight: function(height) { + + var height = height ? height : container.height() || $W.height(); + + this.fitZone('auto', height); + + runtime.arguments = arguments; + }, + + fitWidth: function(width) { + + var width = width ? width : container.width() || $W.width(); + + this.fitZone(width, 'auto'); + + runtime.arguments = arguments; + }, + + fitZone: function(width, height) { + var allBlock = container.find(setting.selector).removeAttr('id'), + block = null, + activeBlock = []; + + height = height ? height : container.height() || $W.height(); + width = width ? width : container.width() || $W.width(); + + runtime.arguments = arguments; + + layoutManager.resetGrid(runtime); + + layoutManager.adjustUnit(width, height, setting); + + if (runtime.filter) { + allBlock.data('active', 0); + allBlock.filter(runtime.filter).data('active', 1); + } else { + allBlock.data('active', 1); + } + + if ($.isFunction(runtime.sortFunc)) { + allBlock.sort(runtime.sortFunc); + } + + allBlock.each(function(index, item) { + var $item = $(item); + item.index = ++index; + block = layoutManager.loadBlock(item, setting); + block && $item.data("active") && activeBlock.push(block); + }); + + klass.fireEvent('onGridReady', container, setting); + + engine[setting.engine](activeBlock, setting); + + layoutManager.setWallSize(runtime, container); + + klass.fireEvent('onGridArrange', container, setting); + + runtime.length = allBlock.length; + + allBlock.each(function(index, item) { + layoutManager.showBlock(item, setting); + if (setting.draggable || item.getAttribute('data-draggable')) { + setDraggable(item); + } + }); + }, + + /* + set block with special position, the top and left are multiple of unit width/height; + example: + + wall.fixPos({ + top: 0, + left: 0, + block: $('.free') + }); + */ + fixPos: function(option) { + $(option.block).attr({'data-position': option.top + "-" + option.left}); + return this; + }, + + /* + set block with special size, the width and height are multiple of unit width/height; + example: + + wall.fixSize({ + height: 5, + width: 2, + block: $('.free') + }); + */ + fixSize: function(option) { + option.height != null && $(option.block).attr({'data-height': option.height}); + option.width != null && $(option.block).attr({'data-width': option.width}); + return this; + }, + + prepend: function(items) { + container.prepend(items); + if (runtime.arguments) { + this.refresh(); + } + return this; + }, + + refresh: function() { + var params = arguments.length ? arguments : runtime.arguments; + var oldArg = runtime.arguments; + var method = oldArg ? oldArg.callee : this.fitWidth; + method.apply(this, Array.prototype.slice.call(params, 0)); + return this; + }, + + /* + custom layout setting; + example: + + wall.reset({ + selector: '.brick', + animate: true, + cellW: 160, + cellH: 160, + delay: 50, + onResize: function() { + wall.fitWidth(); + } + }); + */ + reset: function(option) { + $.extend(setting, option); + return this; + }, + + /* + create one or more blank area (hole) on layout; + example: + + wall.setHoles({ + top: 2, + left: 2, + width: 2, + height: 2 + }); + */ + + setHoles: function(holes) { + var newHoles = [].concat(holes), h = {}, i; + runtime.holes = {}; + for (i = 0; i < newHoles.length; ++i) { + h = newHoles[i]; + runtime.holes[h.top + "-" + h.left + "-" + h.width + "-" + h.height] = h; + } + return this; + }, + /* + sort items by using array sort function; + example: + + wall.sortBy(function(itemA, itemB) { + return $(itemA).width() - $(itemB).width(); + }); + */ + sortBy: function(func) { + runtime.sortFunc = func; + if (runtime.arguments) { + this.refresh(); + } + return this; + }, + + unFilter: function() { + delete runtime.filter; + this.refresh(); + return this; + } + }); + + container.attr('data-min-width', Math.floor($W.width() / 80) * 80); + // execute plugins; + for (var i in layoutManager.plugin) { + if (layoutManager.plugin.hasOwnProperty(i)) { + layoutManager.plugin[i].call(klass, setting, container); + } + } + + // setup resize event; + $W.resize(function() { + if (runtime.running) return; + runtime.running = 1; + setTimeout(function() { + runtime.running = 0; + setting.onResize.call(klass, container); + }, 122); + container.attr('data-min-width', Math.floor($W.width() / 80) * 80); + }); + }; + + /* + add default setting; + example: + + Freewall.addConfig({ + offsetLeft: 0 + }); + */ + Freewall.addConfig = function(newConfig) { + // add default setting; + $.extend(layoutManager.defaultConfig, newConfig); + }; + + + /* + support create new arrange algorithm; + example: + + Freewall.createEngine({ + slice: function(items, setting) { + // slice engine; + } + }); + */ + Freewall.createEngine = function(engineData) { + // create new engine; + $.extend(engine, engineData); + }; + + /* + support create new plugin; + example: + + Freewall.createPlugin({ + centering: function(setting, container) { + console.log(this); + console.log(setting); + } + })l + */ + Freewall.createPlugin = function(pluginData) { + // register new plugin; + $.extend(layoutManager.plugin, pluginData); + }; + + /* + support access helper function; + example: + + Freewall.getMethod('setBlock')(block, setting); + */ + Freewall.getMethod = function(method) { + // get helper method; + return layoutManager[method]; + }; + + window.Freewall = window.freewall = Freewall; + +})(window.Zepto || window.jQuery); diff --git a/downloaded_folder/public/js/jquery.js b/downloaded_folder/public/js/jquery.js new file mode 100644 index 0000000..d1608e3 --- /dev/null +++ b/downloaded_folder/public/js/jquery.js @@ -0,0 +1,4 @@ +/*! jQuery v1.11.1 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */ +!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l="1.11.1",m=function(a,b){return new m.fn.init(a,b)},n=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,o=/^-ms-/,p=/-([\da-z])/gi,q=function(a,b){return b.toUpperCase()};m.fn=m.prototype={jquery:l,constructor:m,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=m.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return m.each(this,a,b)},map:function(a){return this.pushStack(m.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},m.extend=m.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||m.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(m.isPlainObject(c)||(b=m.isArray(c)))?(b?(b=!1,f=a&&m.isArray(a)?a:[]):f=a&&m.isPlainObject(a)?a:{},g[d]=m.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},m.extend({expando:"jQuery"+(l+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===m.type(a)},isArray:Array.isArray||function(a){return"array"===m.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!m.isArray(a)&&a-parseFloat(a)>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==m.type(a)||a.nodeType||m.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(k.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&m.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(o,"ms-").replace(p,q)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=r(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(n,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(r(Object(a))?m.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=r(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),m.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||m.guid++,e):void 0},now:function(){return+new Date},support:k}),m.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function r(a){var b=a.length,c=m.type(a);return"function"===c||m.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var s=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+-new Date,v=a.document,w=0,x=0,y=gb(),z=gb(),A=gb(),B=function(a,b){return a===b&&(l=!0),0},C="undefined",D=1<<31,E={}.hasOwnProperty,F=[],G=F.pop,H=F.push,I=F.push,J=F.slice,K=F.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},L="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",N="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=N.replace("w","w#"),P="\\["+M+"*("+N+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+O+"))|)"+M+"*\\]",Q=":("+N+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+P+")*)|.*)\\)|)",R=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),S=new RegExp("^"+M+"*,"+M+"*"),T=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),U=new RegExp("="+M+"*([^\\]'\"]*?)"+M+"*\\]","g"),V=new RegExp(Q),W=new RegExp("^"+O+"$"),X={ID:new RegExp("^#("+N+")"),CLASS:new RegExp("^\\.("+N+")"),TAG:new RegExp("^("+N.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+Q),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+L+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ab=/[+~]/,bb=/'|\\/g,cb=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),db=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{I.apply(F=J.call(v.childNodes),v.childNodes),F[v.childNodes.length].nodeType}catch(eb){I={apply:F.length?function(a,b){H.apply(a,J.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function fb(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],!a||"string"!=typeof a)return d;if(1!==(k=b.nodeType)&&9!==k)return[];if(p&&!e){if(f=_.exec(a))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return I.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return I.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=9===k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(bb,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+qb(o[l]);w=ab.test(a)&&ob(b.parentNode)||b,x=o.join(",")}if(x)try{return I.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function gb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function hb(a){return a[u]=!0,a}function ib(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function jb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function kb(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||D)-(~a.sourceIndex||D);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function lb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function mb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function nb(a){return hb(function(b){return b=+b,hb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function ob(a){return a&&typeof a.getElementsByTagName!==C&&a}c=fb.support={},f=fb.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=fb.setDocument=function(a){var b,e=a?a.ownerDocument||a:v,g=e.defaultView;return e!==n&&9===e.nodeType&&e.documentElement?(n=e,o=e.documentElement,p=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){m()},!1):g.attachEvent&&g.attachEvent("onunload",function(){m()})),c.attributes=ib(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ib(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(e.getElementsByClassName)&&ib(function(a){return a.innerHTML="
",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=ib(function(a){return o.appendChild(a).id=u,!e.getElementsByName||!e.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==C&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){var c=typeof a.getAttributeNode!==C&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==C?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==C&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(e.querySelectorAll))&&(ib(function(a){a.innerHTML="",a.querySelectorAll("[msallowclip^='']").length&&q.push("[*^$]="+M+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+M+"*(?:value|"+L+")"),a.querySelectorAll(":checked").length||q.push(":checked")}),ib(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+M+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ib(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",Q)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===v&&t(v,a)?-1:b===e||b.ownerDocument===v&&t(v,b)?1:k?K.call(k,a)-K.call(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],i=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:k?K.call(k,a)-K.call(k,b):0;if(f===g)return kb(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?kb(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},e):n},fb.matches=function(a,b){return fb(a,null,null,b)},fb.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return fb(b,n,null,[a]).length>0},fb.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fb.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&E.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},fb.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},fb.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=fb.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=fb.selectors={cacheLength:50,createPseudo:hb,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(cb,db),a[3]=(a[3]||a[4]||a[5]||"").replace(cb,db),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||fb.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&fb.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(cb,db).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+M+")"+a+"("+M+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==C&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=fb.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||fb.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?hb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=K.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:hb(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?hb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:hb(function(a){return function(b){return fb(a,b).length>0}}),contains:hb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:hb(function(a){return W.test(a||"")||fb.error("unsupported lang: "+a),a=a.replace(cb,db).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:nb(function(){return[0]}),last:nb(function(a,b){return[b-1]}),eq:nb(function(a,b,c){return[0>c?c+b:c]}),even:nb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:nb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:nb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:nb(function(a,b,c){for(var d=0>c?c+b:c;++db;b++)d+=a[b].value;return d}function rb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function sb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function tb(a,b,c){for(var d=0,e=b.length;e>d;d++)fb(a,b[d],c);return c}function ub(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function vb(a,b,c,d,e,f){return d&&!d[u]&&(d=vb(d)),e&&!e[u]&&(e=vb(e,f)),hb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||tb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ub(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ub(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?K.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ub(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):I.apply(g,r)})}function wb(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=rb(function(a){return a===b},h,!0),l=rb(function(a){return K.call(b,a)>-1},h,!0),m=[function(a,c,d){return!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>i;i++)if(c=d.relative[a[i].type])m=[rb(sb(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return vb(i>1&&sb(m),i>1&&qb(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&wb(a.slice(i,e)),f>e&&wb(a=a.slice(e)),f>e&&qb(a))}m.push(c)}return sb(m)}function xb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=G.call(i));s=ub(s)}I.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&fb.uniqueSort(i)}return k&&(w=v,j=t),r};return c?hb(f):f}return h=fb.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=wb(b[c]),f[u]?d.push(f):e.push(f);f=A(a,xb(e,d)),f.selector=a}return f},i=fb.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(cb,db),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(cb,db),ab.test(j[0].type)&&ob(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&qb(j),!a)return I.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,ab.test(a)&&ob(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ib(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ib(function(a){return a.innerHTML="","#"===a.firstChild.getAttribute("href")})||jb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ib(function(a){return a.innerHTML="",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||jb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ib(function(a){return null==a.getAttribute("disabled")})||jb(L,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),fb}(a);m.find=s,m.expr=s.selectors,m.expr[":"]=m.expr.pseudos,m.unique=s.uniqueSort,m.text=s.getText,m.isXMLDoc=s.isXML,m.contains=s.contains;var t=m.expr.match.needsContext,u=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,v=/^.[^:#\[\.,]*$/;function w(a,b,c){if(m.isFunction(b))return m.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return m.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(v.test(b))return m.filter(b,a,c);b=m.filter(b,a)}return m.grep(a,function(a){return m.inArray(a,b)>=0!==c})}m.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?m.find.matchesSelector(d,a)?[d]:[]:m.find.matches(a,m.grep(b,function(a){return 1===a.nodeType}))},m.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(m(a).filter(function(){for(b=0;e>b;b++)if(m.contains(d[b],this))return!0}));for(b=0;e>b;b++)m.find(a,d[b],c);return c=this.pushStack(e>1?m.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(w(this,a||[],!1))},not:function(a){return this.pushStack(w(this,a||[],!0))},is:function(a){return!!w(this,"string"==typeof a&&t.test(a)?m(a):a||[],!1).length}});var x,y=a.document,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=m.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||x).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof m?b[0]:b,m.merge(this,m.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:y,!0)),u.test(c[1])&&m.isPlainObject(b))for(c in b)m.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=y.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return x.find(a);this.length=1,this[0]=d}return this.context=y,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):m.isFunction(a)?"undefined"!=typeof x.ready?x.ready(a):a(m):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),m.makeArray(a,this))};A.prototype=m.fn,x=m(y);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};m.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!m(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),m.fn.extend({has:function(a){var b,c=m(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(m.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=t.test(a)||"string"!=typeof a?m(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&m.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?m.unique(f):f)},index:function(a){return a?"string"==typeof a?m.inArray(this[0],m(a)):m.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(m.unique(m.merge(this.get(),m(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}m.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return m.dir(a,"parentNode")},parentsUntil:function(a,b,c){return m.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return m.dir(a,"nextSibling")},prevAll:function(a){return m.dir(a,"previousSibling")},nextUntil:function(a,b,c){return m.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return m.dir(a,"previousSibling",c)},siblings:function(a){return m.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return m.sibling(a.firstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:m.merge([],a.childNodes)}},function(a,b){m.fn[a]=function(c,d){var e=m.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=m.filter(d,e)),this.length>1&&(C[a]||(e=m.unique(e)),B.test(a)&&(e=e.reverse())),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return m.each(a.match(E)||[],function(a,c){b[c]=!0}),b}m.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):m.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){m.each(b,function(b,c){var d=m.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&m.each(arguments,function(a,c){var d;while((d=m.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?m.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},m.extend({Deferred:function(a){var b=[["resolve","done",m.Callbacks("once memory"),"resolved"],["reject","fail",m.Callbacks("once memory"),"rejected"],["notify","progress",m.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return m.Deferred(function(c){m.each(b,function(b,f){var g=m.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&m.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?m.extend(a,d):d}},e={};return d.pipe=d.then,m.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&m.isFunction(a.promise)?e:0,g=1===f?a:m.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&m.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;m.fn.ready=function(a){return m.ready.promise().done(a),this},m.extend({isReady:!1,readyWait:1,holdReady:function(a){a?m.readyWait++:m.ready(!0)},ready:function(a){if(a===!0?!--m.readyWait:!m.isReady){if(!y.body)return setTimeout(m.ready);m.isReady=!0,a!==!0&&--m.readyWait>0||(H.resolveWith(y,[m]),m.fn.triggerHandler&&(m(y).triggerHandler("ready"),m(y).off("ready")))}}});function I(){y.addEventListener?(y.removeEventListener("DOMContentLoaded",J,!1),a.removeEventListener("load",J,!1)):(y.detachEvent("onreadystatechange",J),a.detachEvent("onload",J))}function J(){(y.addEventListener||"load"===event.type||"complete"===y.readyState)&&(I(),m.ready())}m.ready.promise=function(b){if(!H)if(H=m.Deferred(),"complete"===y.readyState)setTimeout(m.ready);else if(y.addEventListener)y.addEventListener("DOMContentLoaded",J,!1),a.addEventListener("load",J,!1);else{y.attachEvent("onreadystatechange",J),a.attachEvent("onload",J);var c=!1;try{c=null==a.frameElement&&y.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!m.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}I(),m.ready()}}()}return H.promise(b)};var K="undefined",L;for(L in m(k))break;k.ownLast="0"!==L,k.inlineBlockNeedsLayout=!1,m(function(){var a,b,c,d;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",k.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(d))}),function(){var a=y.createElement("div");if(null==k.deleteExpando){k.deleteExpando=!0;try{delete a.test}catch(b){k.deleteExpando=!1}}a=null}(),m.acceptData=function(a){var b=m.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var M=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,N=/([A-Z])/g;function O(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(N,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:M.test(c)?m.parseJSON(c):c}catch(e){}m.data(a,b,c)}else c=void 0}return c}function P(a){var b;for(b in a)if(("data"!==b||!m.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function Q(a,b,d,e){if(m.acceptData(a)){var f,g,h=m.expando,i=a.nodeType,j=i?m.cache:a,k=i?a[h]:a[h]&&h; +if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||m.guid++:h),j[k]||(j[k]=i?{}:{toJSON:m.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=m.extend(j[k],b):j[k].data=m.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[m.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[m.camelCase(b)])):f=g,f}}function R(a,b,c){if(m.acceptData(a)){var d,e,f=a.nodeType,g=f?m.cache:a,h=f?a[m.expando]:m.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){m.isArray(b)?b=b.concat(m.map(b,m.camelCase)):b in d?b=[b]:(b=m.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!P(d):!m.isEmptyObject(d))return}(c||(delete g[h].data,P(g[h])))&&(f?m.cleanData([a],!0):k.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}m.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?m.cache[a[m.expando]]:a[m.expando],!!a&&!P(a)},data:function(a,b,c){return Q(a,b,c)},removeData:function(a,b){return R(a,b)},_data:function(a,b,c){return Q(a,b,c,!0)},_removeData:function(a,b){return R(a,b,!0)}}),m.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=m.data(f),1===f.nodeType&&!m._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=m.camelCase(d.slice(5)),O(f,d,e[d])));m._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){m.data(this,a)}):arguments.length>1?this.each(function(){m.data(this,a,b)}):f?O(f,a,m.data(f,a)):void 0},removeData:function(a){return this.each(function(){m.removeData(this,a)})}}),m.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=m._data(a,b),c&&(!d||m.isArray(c)?d=m._data(a,b,m.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=m.queue(a,b),d=c.length,e=c.shift(),f=m._queueHooks(a,b),g=function(){m.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return m._data(a,c)||m._data(a,c,{empty:m.Callbacks("once memory").add(function(){m._removeData(a,b+"queue"),m._removeData(a,c)})})}}),m.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.lengthh;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},W=/^(?:checkbox|radio)$/i;!function(){var a=y.createElement("input"),b=y.createElement("div"),c=y.createDocumentFragment();if(b.innerHTML="
a",k.leadingWhitespace=3===b.firstChild.nodeType,k.tbody=!b.getElementsByTagName("tbody").length,k.htmlSerialize=!!b.getElementsByTagName("link").length,k.html5Clone="<:nav>"!==y.createElement("nav").cloneNode(!0).outerHTML,a.type="checkbox",a.checked=!0,c.appendChild(a),k.appendChecked=a.checked,b.innerHTML="",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,c.appendChild(b),b.innerHTML="",k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,k.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){k.noCloneEvent=!1}),b.cloneNode(!0).click()),null==k.deleteExpando){k.deleteExpando=!0;try{delete b.test}catch(d){k.deleteExpando=!1}}}(),function(){var b,c,d=y.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(k[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),k[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var X=/^(?:input|select|textarea)$/i,Y=/^key/,Z=/^(?:mouse|pointer|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=/^([^.]*)(?:\.(.+)|)$/;function ab(){return!0}function bb(){return!1}function cb(){try{return y.activeElement}catch(a){}}m.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=m.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof m===K||a&&m.event.triggered===a.type?void 0:m.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(E)||[""],h=b.length;while(h--)f=_.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=m.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=m.event.special[o]||{},l=m.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&m.expr.match.needsContext.test(e),namespace:p.join(".")},i),(n=g[o])||(n=g[o]=[],n.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?n.splice(n.delegateCount++,0,l):n.push(l),m.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m.hasData(a)&&m._data(a);if(r&&(k=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=_.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=m.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,n=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=n.length;while(f--)g=n[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(n.splice(f,1),g.selector&&n.delegateCount--,l.remove&&l.remove.call(a,g));i&&!n.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||m.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)m.event.remove(a,o+b[j],c,d,!0);m.isEmptyObject(k)&&(delete r.handle,m._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,o=[d||y],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||y,3!==d.nodeType&&8!==d.nodeType&&!$.test(p+m.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[m.expando]?b:new m.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:m.makeArray(c,[b]),k=m.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!m.isWindow(d)){for(i=k.delegateType||p,$.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||y)&&o.push(l.defaultView||l.parentWindow||a)}n=0;while((h=o[n++])&&!b.isPropagationStopped())b.type=n>1?i:k.bindType||p,f=(m._data(h,"events")||{})[b.type]&&m._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&m.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&m.acceptData(d)&&g&&d[p]&&!m.isWindow(d)){l=d[g],l&&(d[g]=null),m.event.triggered=p;try{d[p]()}catch(r){}m.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=m.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(m._data(this,"events")||{})[a.type]||[],k=m.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=m.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((m.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?m(c,this).index(i)>=0:m.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h]","i"),hb=/^\s+/,ib=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,jb=/<([\w:]+)/,kb=/\s*$/g,rb={option:[1,""],legend:[1,"
","
"],area:[1,"",""],param:[1,"",""],thead:[1,"","
"],tr:[2,"","
"],col:[2,"","
"],td:[3,"","
"],_default:k.htmlSerialize?[0,"",""]:[1,"X
","
"]},sb=db(y),tb=sb.appendChild(y.createElement("div"));rb.optgroup=rb.option,rb.tbody=rb.tfoot=rb.colgroup=rb.caption=rb.thead,rb.th=rb.td;function ub(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==K?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==K?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||m.nodeName(d,b)?f.push(d):m.merge(f,ub(d,b));return void 0===b||b&&m.nodeName(a,b)?m.merge([a],f):f}function vb(a){W.test(a.type)&&(a.defaultChecked=a.checked)}function wb(a,b){return m.nodeName(a,"table")&&m.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function xb(a){return a.type=(null!==m.find.attr(a,"type"))+"/"+a.type,a}function yb(a){var b=pb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function zb(a,b){for(var c,d=0;null!=(c=a[d]);d++)m._data(c,"globalEval",!b||m._data(b[d],"globalEval"))}function Ab(a,b){if(1===b.nodeType&&m.hasData(a)){var c,d,e,f=m._data(a),g=m._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)m.event.add(b,c,h[c][d])}g.data&&(g.data=m.extend({},g.data))}}function Bb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!k.noCloneEvent&&b[m.expando]){e=m._data(b);for(d in e.events)m.removeEvent(b,d,e.handle);b.removeAttribute(m.expando)}"script"===c&&b.text!==a.text?(xb(b).text=a.text,yb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),k.html5Clone&&a.innerHTML&&!m.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&W.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}m.extend({clone:function(a,b,c){var d,e,f,g,h,i=m.contains(a.ownerDocument,a);if(k.html5Clone||m.isXMLDoc(a)||!gb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(tb.innerHTML=a.outerHTML,tb.removeChild(f=tb.firstChild)),!(k.noCloneEvent&&k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||m.isXMLDoc(a)))for(d=ub(f),h=ub(a),g=0;null!=(e=h[g]);++g)d[g]&&Bb(e,d[g]);if(b)if(c)for(h=h||ub(a),d=d||ub(f),g=0;null!=(e=h[g]);g++)Ab(e,d[g]);else Ab(a,f);return d=ub(f,"script"),d.length>0&&zb(d,!i&&ub(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,l,n=a.length,o=db(b),p=[],q=0;n>q;q++)if(f=a[q],f||0===f)if("object"===m.type(f))m.merge(p,f.nodeType?[f]:f);else if(lb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(jb.exec(f)||["",""])[1].toLowerCase(),l=rb[i]||rb._default,h.innerHTML=l[1]+f.replace(ib,"<$1>")+l[2],e=l[0];while(e--)h=h.lastChild;if(!k.leadingWhitespace&&hb.test(f)&&p.push(b.createTextNode(hb.exec(f)[0])),!k.tbody){f="table"!==i||kb.test(f)?""!==l[1]||kb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)m.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}m.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),k.appendChecked||m.grep(ub(p,"input"),vb),q=0;while(f=p[q++])if((!d||-1===m.inArray(f,d))&&(g=m.contains(f.ownerDocument,f),h=ub(o.appendChild(f),"script"),g&&zb(h),c)){e=0;while(f=h[e++])ob.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=m.expando,j=m.cache,l=k.deleteExpando,n=m.event.special;null!=(d=a[h]);h++)if((b||m.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)n[e]?m.event.remove(d,e):m.removeEvent(d,e,g.handle);j[f]&&(delete j[f],l?delete d[i]:typeof d.removeAttribute!==K?d.removeAttribute(i):d[i]=null,c.push(f))}}}),m.fn.extend({text:function(a){return V(this,function(a){return void 0===a?m.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?m.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||m.cleanData(ub(c)),c.parentNode&&(b&&m.contains(c.ownerDocument,c)&&zb(ub(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&m.cleanData(ub(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&m.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return m.clone(this,a,b)})},html:function(a){return V(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(fb,""):void 0;if(!("string"!=typeof a||mb.test(a)||!k.htmlSerialize&&gb.test(a)||!k.leadingWhitespace&&hb.test(a)||rb[(jb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ib,"<$1>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ub(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,m.cleanData(ub(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,n=this,o=l-1,p=a[0],q=m.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&nb.test(p))return this.each(function(c){var d=n.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(i=m.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=m.map(ub(i,"script"),xb),f=g.length;l>j;j++)d=i,j!==o&&(d=m.clone(d,!0,!0),f&&m.merge(g,ub(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,m.map(g,yb),j=0;f>j;j++)d=g[j],ob.test(d.type||"")&&!m._data(d,"globalEval")&&m.contains(h,d)&&(d.src?m._evalUrl&&m._evalUrl(d.src):m.globalEval((d.text||d.textContent||d.innerHTML||"").replace(qb,"")));i=c=null}return this}}),m.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){m.fn[a]=function(a){for(var c,d=0,e=[],g=m(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),m(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Cb,Db={};function Eb(b,c){var d,e=m(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:m.css(e[0],"display");return e.detach(),f}function Fb(a){var b=y,c=Db[a];return c||(c=Eb(a,b),"none"!==c&&c||(Cb=(Cb||m("