{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \n\"\"\"\n\n\ndef _update_label_on_show(label: QtWidgets.QLabel, text: str):\n def showEvent(_):\n if label._delayed_text is not None:\n label.setText(label._delayed_text)\n label._delayed_text = None\n\n label._delayed_text = text\n label.showEvent = showEvent\n\n\nclass MainWindow(WindowManager, Ui_MainWindow):\n newer_version_signal = Signal(str, str)\n options_changed_signal = Signal()\n _is_preview_mode: bool = False\n\n menu_new_version: Optional[QtWidgets.QAction] = None\n _current_version_url: Optional[str] = None\n _options: Options\n _data_visualizer: Optional[QtWidgets.QWidget] = None\n _map_tracker: QtWidgets.QWidget\n _preset_manager: PresetManager\n GameDetailsSignal = Signal(LayoutDescription)\n\n InitPostShowSignal = Signal()\n\n @property\n def _tab_widget(self):\n return self.main_tab_widget\n\n @property\n def preset_manager(self) -> PresetManager:\n return self._preset_manager\n\n @property\n def main_window(self) -> QtWidgets.QMainWindow:\n return self\n\n @property\n def is_preview_mode(self) -> bool:\n return self._is_preview_mode\n\n def __init__(self, options: Options, preset_manager: PresetManager,\n network_client, preview: bool):\n super().__init__()\n self.setupUi(self)\n self.setWindowTitle(\"Randovania {}\".format(VERSION))\n self._is_preview_mode = preview\n self.setAcceptDrops(True)\n common_qt_lib.set_default_window_icon(self)\n\n # Remove all hardcoded link color\n about_document: QtGui.QTextDocument = self.about_text_browser.document()\n about_document.setHtml(about_document.toHtml().replace(\"color:#0000ff;\", \"\"))\n self.browse_racetime_label.setText(self.browse_racetime_label.text().replace(\"color:#0000ff;\", \"\"))\n\n self.intro_label.setText(self.intro_label.text().format(version=VERSION))\n\n self._preset_manager = preset_manager\n self.network_client = network_client\n\n if preview:\n debug.set_level(2)\n\n # Signals\n self.newer_version_signal.connect(self.display_new_version)\n self.options_changed_signal.connect(self.on_options_changed)\n self.GameDetailsSignal.connect(self._open_game_details)\n self.InitPostShowSignal.connect(self.initialize_post_show)\n\n self.intro_play_now_button.clicked.connect(lambda: self.welcome_tab_widget.setCurrentWidget(self.tab_play))\n self.open_faq_button.clicked.connect(self._open_faq)\n self.open_database_viewer_button.clicked.connect(partial(self._open_data_visualizer_for_game,\n RandovaniaGame.PRIME2))\n\n for game in RandovaniaGame:\n self.hint_item_names_game_combo.addItem(game.long_name, game)\n self.hint_location_game_combo.addItem(game.long_name, game)\n\n self.hint_item_names_game_combo.currentIndexChanged.connect(self._update_hints_text)\n self.hint_location_game_combo.currentIndexChanged.connect(self._update_hint_locations)\n\n self.import_permalink_button.clicked.connect(self._import_permalink)\n self.import_game_file_button.clicked.connect(self._import_spoiler_log)\n self.browse_racetime_button.clicked.connect(self._browse_racetime)\n self.create_new_seed_button.clicked.connect(\n lambda: self.welcome_tab_widget.setCurrentWidget(self.tab_create_seed))\n\n # Menu Bar\n for action, game in ((self.menu_action_prime_1_data_visualizer, RandovaniaGame.PRIME1),\n (self.menu_action_prime_2_data_visualizer, RandovaniaGame.PRIME2),\n (self.menu_action_prime_3_data_visualizer, RandovaniaGame.PRIME3)):\n action.triggered.connect(partial(self._open_data_visualizer_for_game, game))\n\n for action, game in ((self.menu_action_edit_prime_1, RandovaniaGame.PRIME1),\n (self.menu_action_edit_prime_2, RandovaniaGame.PRIME2),\n (self.menu_action_edit_prime_3, RandovaniaGame.PRIME3)):\n action.triggered.connect(partial(self._open_data_editor_for_game, game))\n\n self.menu_action_item_tracker.triggered.connect(self._open_item_tracker)\n self.menu_action_map_tracker.triggered.connect(self._on_menu_action_map_tracker)\n self.menu_action_edit_existing_database.triggered.connect(self._open_data_editor_prompt)\n self.menu_action_validate_seed_after.triggered.connect(self._on_validate_seed_change)\n self.menu_action_timeout_generation_after_a_time_limit.triggered.connect(self._on_generate_time_limit_change)\n self.menu_action_dark_mode.triggered.connect(self._on_menu_action_dark_mode)\n self.menu_action_open_auto_tracker.triggered.connect(self._open_auto_tracker)\n self.menu_action_previously_generated_games.triggered.connect(self._on_menu_action_previously_generated_games)\n self.menu_action_layout_editor.triggered.connect(self._on_menu_action_layout_editor)\n\n self.menu_prime_1_trick_details.aboutToShow.connect(self._create_trick_details_prime_1)\n self.menu_prime_2_trick_details.aboutToShow.connect(self._create_trick_details_prime_2)\n self.menu_prime_3_trick_details.aboutToShow.connect(self._create_trick_details_prime_3)\n\n # Setting this event only now, so all options changed trigger only once\n options.on_options_changed = self.options_changed_signal.emit\n self._options = options\n\n self.main_tab_widget.setCurrentIndex(0)\n\n def closeEvent(self, event):\n self.generate_seed_tab.stop_background_process()\n super().closeEvent(event)\n\n def dragEnterEvent(self, event: QtGui.QDragEnterEvent):\n from randovania.layout.preset_migration import VersionedPreset\n\n valid_extensions = [\n LayoutDescription.file_extension(),\n VersionedPreset.file_extension(),\n ]\n valid_extensions_with_dot = {\n f\".{extension}\"\n for extension in valid_extensions\n }\n\n for url in event.mimeData().urls():\n ext = os.path.splitext(url.toLocalFile())[1]\n if ext in valid_extensions_with_dot:\n event.acceptProposedAction()\n return\n\n def dropEvent(self, event: QtGui.QDropEvent):\n from randovania.layout.preset_migration import VersionedPreset\n\n for url in event.mimeData().urls():\n path = Path(url.toLocalFile())\n if path.suffix == f\".{LayoutDescription.file_extension()}\":\n self.open_game_details(LayoutDescription.from_file(path))\n return\n\n elif path.suffix == f\".{VersionedPreset.file_extension()}\":\n self.main_tab_widget.setCurrentWidget(self.welcome_tab)\n self.welcome_tab_widget.setCurrentWidget(self.tab_create_seed)\n self.generate_seed_tab.import_preset_file(path)\n return\n\n def showEvent(self, event: QtGui.QShowEvent):\n self.InitPostShowSignal.emit()\n\n # Delayed Initialization\n @asyncSlot()\n async def initialize_post_show(self):\n self.InitPostShowSignal.disconnect(self.initialize_post_show)\n logging.info(\"Will initialize things in post show\")\n await self._initialize_post_show_body()\n logging.info(\"Finished initializing post show\")\n\n async def _initialize_post_show_body(self):\n logging.info(\"Will load OnlineInteractions\")\n from randovania.gui.main_online_interaction import OnlineInteractions\n logging.info(\"Creating OnlineInteractions...\")\n self.online_interactions = OnlineInteractions(self, self.preset_manager, self.network_client, self,\n self._options)\n\n logging.info(\"Will load GenerateSeedTab\")\n from randovania.gui.generate_seed_tab import GenerateSeedTab\n logging.info(\"Creating GenerateSeedTab...\")\n self.generate_seed_tab = GenerateSeedTab(self, self, self._options)\n logging.info(\"Running GenerateSeedTab.setup_ui\")\n self.generate_seed_tab.setup_ui()\n\n # Update hints text\n logging.info(\"Will _update_hints_text\")\n self._update_hints_text()\n logging.info(\"Will hide hint locations combo\")\n self.hint_location_game_combo.setVisible(False)\n self.hint_location_game_combo.setCurrentIndex(1)\n\n logging.info(\"Will update for modified options\")\n with self._options:\n self.on_options_changed()\n\n def _update_hints_text(self):\n from randovania.gui.lib import hints_text\n hints_text.update_hints_text(self.hint_item_names_game_combo.currentData(), self.hint_item_names_tree_widget)\n\n def _update_hint_locations(self):\n from randovania.gui.lib import hints_text\n hints_text.update_hint_locations(self.hint_location_game_combo.currentData(), self.hint_tree_widget)\n\n # Generate Seed\n def _open_faq(self):\n self.main_tab_widget.setCurrentWidget(self.help_tab)\n self.help_tab_widget.setCurrentWidget(self.tab_faq)\n\n async def generate_seed_from_permalink(self, permalink):\n from randovania.interface_common.status_update_lib import ProgressUpdateCallable\n from randovania.gui.dialog.background_process_dialog import BackgroundProcessDialog\n\n def work(progress_update: ProgressUpdateCallable):\n from randovania.interface_common import simplified_patcher\n layout = simplified_patcher.generate_layout(progress_update=progress_update,\n permalink=permalink,\n options=self._options)\n progress_update(f\"Success! (Seed hash: {layout.shareable_hash})\", 1)\n return layout\n\n new_layout = await BackgroundProcessDialog.open_for_background_task(work, \"Creating a game...\")\n self.open_game_details(new_layout)\n\n @asyncSlot()\n async def _import_permalink(self):\n from randovania.gui.dialog.permalink_dialog import PermalinkDialog\n dialog = PermalinkDialog()\n result = await async_dialog.execute_dialog(dialog)\n if result == QtWidgets.QDialog.Accepted:\n permalink = dialog.get_permalink_from_field()\n await self.generate_seed_from_permalink(permalink)\n\n def _import_spoiler_log(self):\n json_path = common_qt_lib.prompt_user_for_input_game_log(self)\n if json_path is not None:\n layout = LayoutDescription.from_file(json_path)\n self.open_game_details(layout)\n\n @asyncSlot()\n async def _browse_racetime(self):\n from randovania.gui.dialog.racetime_browser_dialog import RacetimeBrowserDialog\n dialog = RacetimeBrowserDialog()\n if not await dialog.refresh():\n return\n result = await async_dialog.execute_dialog(dialog)\n if result == QtWidgets.QDialog.Accepted:\n await self.generate_seed_from_permalink(dialog.permalink)\n\n def open_game_details(self, layout: LayoutDescription):\n self.GameDetailsSignal.emit(layout)\n\n def _open_game_details(self, layout: LayoutDescription):\n from randovania.gui.seed_details_window import SeedDetailsWindow\n details_window = SeedDetailsWindow(self, self._options)\n details_window.update_layout_description(layout)\n details_window.show()\n self.track_window(details_window)\n\n # Releases info\n async def request_new_data(self):\n from randovania.interface_common import github_releases_data\n await self._on_releases_data(await github_releases_data.get_releases())\n\n async def _on_releases_data(self, releases: Optional[List[dict]]):\n import markdown\n\n current_version = update_checker.strict_current_version()\n last_changelog = self._options.last_changelog_displayed\n\n all_change_logs, new_change_logs, version_to_display = update_checker.versions_to_display_for_releases(\n current_version, last_changelog, releases)\n\n if version_to_display is not None:\n self.display_new_version(version_to_display)\n\n if all_change_logs:\n changelog_tab = QtWidgets.QWidget()\n changelog_tab.setObjectName(\"changelog_tab\")\n changelog_tab_layout = QtWidgets.QVBoxLayout(changelog_tab)\n changelog_tab_layout.setContentsMargins(0, 0, 0, 0)\n changelog_tab_layout.setObjectName(\"changelog_tab_layout\")\n changelog_scroll_area = QtWidgets.QScrollArea(changelog_tab)\n changelog_scroll_area.setWidgetResizable(True)\n changelog_scroll_area.setObjectName(\"changelog_scroll_area\")\n changelog_scroll_contents = QtWidgets.QWidget()\n changelog_scroll_contents.setGeometry(QtCore.QRect(0, 0, 489, 337))\n changelog_scroll_contents.setObjectName(\"changelog_scroll_contents\")\n changelog_scroll_layout = QtWidgets.QVBoxLayout(changelog_scroll_contents)\n changelog_scroll_layout.setObjectName(\"changelog_scroll_layout\")\n\n for entry in all_change_logs:\n changelog_label = QtWidgets.QLabel(changelog_scroll_contents)\n _update_label_on_show(changelog_label, markdown.markdown(entry))\n changelog_label.setObjectName(\"changelog_label\")\n changelog_label.setWordWrap(True)\n changelog_scroll_layout.addWidget(changelog_label)\n\n changelog_scroll_area.setWidget(changelog_scroll_contents)\n changelog_tab_layout.addWidget(changelog_scroll_area)\n self.help_tab_widget.addTab(changelog_tab, \"Change Log\")\n\n if new_change_logs:\n await async_dialog.message_box(self, QtWidgets.QMessageBox.Information,\n \"What's new\", markdown.markdown(\"\\n\".join(new_change_logs)))\n with self._options as options:\n options.last_changelog_displayed = current_version\n\n def display_new_version(self, version: update_checker.VersionDescription):\n if self.menu_new_version is None:\n self.menu_new_version = QtWidgets.QAction(\"\", self)\n self.menu_new_version.triggered.connect(self.open_version_link)\n self.menu_bar.addAction(self.menu_new_version)\n\n self.menu_new_version.setText(\"New version available: {}\".format(version.tag_name))\n self._current_version_url = version.html_url\n\n def open_version_link(self):\n if self._current_version_url is None:\n raise RuntimeError(\"Called open_version_link, but _current_version_url is None\")\n\n QtGui.QDesktopServices.openUrl(QUrl(self._current_version_url))\n\n # Options\n def on_options_changed(self):\n self.menu_action_validate_seed_after.setChecked(self._options.advanced_validate_seed_after)\n self.menu_action_timeout_generation_after_a_time_limit.setChecked(\n self._options.advanced_timeout_during_generation)\n self.menu_action_dark_mode.setChecked(self._options.dark_mode)\n\n self.generate_seed_tab.on_options_changed(self._options)\n theme.set_dark_theme(self._options.dark_mode)\n\n # Menu Actions\n def _open_data_visualizer_for_game(self, game: RandovaniaGame):\n self.open_data_visualizer_at(None, None, game)\n\n def open_data_visualizer_at(self,\n world_name: Optional[str],\n area_name: Optional[str],\n game: RandovaniaGame = RandovaniaGame.PRIME2,\n ):\n from randovania.gui.data_editor import DataEditorWindow\n data_visualizer = DataEditorWindow.open_internal_data(game, False)\n self._data_visualizer = data_visualizer\n\n if world_name is not None:\n data_visualizer.focus_on_world(world_name)\n\n if area_name is not None:\n data_visualizer.focus_on_area(area_name)\n\n self._data_visualizer.show()\n\n def _open_data_editor_for_game(self, game: RandovaniaGame):\n from randovania.gui.data_editor import DataEditorWindow\n self._data_editor = DataEditorWindow.open_internal_data(game, True)\n self._data_editor.show()\n\n def _open_data_editor_prompt(self):\n from randovania.gui.data_editor import DataEditorWindow\n\n database_path = common_qt_lib.prompt_user_for_database_file(self)\n if database_path is None:\n return\n\n with database_path.open(\"r\") as database_file:\n self._data_editor = DataEditorWindow(json.load(database_file), database_path, False, True)\n self._data_editor.show()\n\n @asyncSlot()\n async def _on_menu_action_map_tracker(self):\n dialog = QtWidgets.QInputDialog(self)\n dialog.setWindowTitle(\"Map Tracker\")\n dialog.setLabelText(\"Select preset used for the tracker.\")\n dialog.setComboBoxItems([preset.name for preset in self._preset_manager.all_presets])\n dialog.setTextValue(self._options.selected_preset_name)\n result = await async_dialog.execute_dialog(dialog)\n if result == QtWidgets.QDialog.Accepted:\n preset = self._preset_manager.preset_for_name(dialog.textValue())\n self.open_map_tracker(preset.get_preset().configuration)\n\n def open_map_tracker(self, configuration: \"EchoesConfiguration\"):\n from randovania.gui.tracker_window import TrackerWindow, InvalidLayoutForTracker\n\n try:\n self._map_tracker = TrackerWindow(self._options.tracker_files_path, configuration)\n except InvalidLayoutForTracker as e:\n QtWidgets.QMessageBox.critical(\n self,\n \"Unsupported configuration for Tracker\",\n str(e)\n )\n return\n\n self._map_tracker.show()\n\n def _open_item_tracker(self):\n # Importing this at root level seems to crash linux tests :(\n from PySide2.QtWebEngineWidgets import QWebEngineView\n\n tracker_window = QtWidgets.QMainWindow()\n tracker_window.setWindowTitle(\"Item Tracker\")\n tracker_window.resize(370, 380)\n\n web_view = QWebEngineView(tracker_window)\n tracker_window.setCentralWidget(web_view)\n\n self.web_view = web_view\n\n def update_window_icon():\n tracker_window.setWindowIcon(web_view.icon())\n\n web_view.iconChanged.connect(update_window_icon)\n web_view.load(QUrl(\"https://spaghettitoastbook.github.io/echoes/tracker/\"))\n\n tracker_window.show()\n self._item_tracker_window = tracker_window\n\n # Difficulties stuff\n\n def _exec_trick_details(self, popup: \"TrickDetailsPopup\"):\n self._trick_details_popup = popup\n self._trick_details_popup.setWindowModality(Qt.WindowModal)\n self._trick_details_popup.open()\n\n def _open_trick_details_popup(self, game, trick: TrickResourceInfo, level: LayoutTrickLevel):\n from randovania.gui.dialog.trick_details_popup import TrickDetailsPopup\n self._exec_trick_details(TrickDetailsPopup(self, self, game, trick, level))\n\n def _create_trick_details_prime_1(self):\n self.menu_prime_1_trick_details.aboutToShow.disconnect(self._create_trick_details_prime_1)\n self._setup_difficulties_menu(RandovaniaGame.PRIME1, self.menu_prime_1_trick_details)\n\n def _create_trick_details_prime_2(self):\n self.menu_prime_2_trick_details.aboutToShow.disconnect(self._create_trick_details_prime_2)\n self._setup_difficulties_menu(RandovaniaGame.PRIME2, self.menu_prime_2_trick_details)\n\n def _create_trick_details_prime_3(self):\n self.menu_prime_3_trick_details.aboutToShow.disconnect(self._create_trick_details_prime_3)\n self._setup_difficulties_menu(RandovaniaGame.PRIME3, self.menu_prime_3_trick_details)\n\n def _setup_difficulties_menu(self, game: RandovaniaGame, menu: QtWidgets.QMenu):\n from randovania.game_description import default_database\n game = default_database.game_description_for(game)\n tricks_in_use = used_tricks(game)\n\n menu.clear()\n for trick in sorted(game.resource_database.trick, key=lambda _trick: _trick.long_name):\n if trick not in tricks_in_use:\n continue\n\n trick_menu = QtWidgets.QMenu(self)\n trick_menu.setTitle(trick.long_name)\n menu.addAction(trick_menu.menuAction())\n\n used_difficulties = difficulties_for_trick(game, trick)\n for i, trick_level in enumerate(iterate_enum(LayoutTrickLevel)):\n if trick_level in used_difficulties:\n difficulty_action = QtWidgets.QAction(self)\n difficulty_action.setText(trick_level.long_name)\n trick_menu.addAction(difficulty_action)\n difficulty_action.triggered.connect(\n functools.partial(self._open_trick_details_popup, game, trick, trick_level))\n\n # ==========\n\n @asyncSlot()\n async def _on_validate_seed_change(self):\n old_value = self._options.advanced_validate_seed_after\n new_value = self.menu_action_validate_seed_after.isChecked()\n\n if old_value and not new_value:\n box = QtWidgets.QMessageBox(self)\n box.setWindowTitle(\"Disable validation?\")\n box.setText(_DISABLE_VALIDATION_WARNING)\n box.setIcon(QtWidgets.QMessageBox.Warning)\n box.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)\n box.setDefaultButton(QtWidgets.QMessageBox.No)\n user_response = await async_dialog.execute_dialog(box)\n if user_response != QtWidgets.QMessageBox.Yes:\n self.menu_action_validate_seed_after.setChecked(True)\n return\n\n with self._options as options:\n options.advanced_validate_seed_after = new_value\n\n def _on_generate_time_limit_change(self):\n is_checked = self.menu_action_timeout_generation_after_a_time_limit.isChecked()\n with self._options as options:\n options.advanced_timeout_during_generation = is_checked\n\n def _on_menu_action_dark_mode(self):\n with self._options as options:\n options.dark_mode = self.menu_action_dark_mode.isChecked()\n\n def _open_auto_tracker(self):\n from randovania.gui.auto_tracker_window import AutoTrackerWindow\n self.auto_tracker_window = AutoTrackerWindow(common_qt_lib.get_game_connection(), self._options)\n self.auto_tracker_window.show()\n\n def _on_menu_action_previously_generated_games(self):\n path = self._options.data_dir.joinpath(\"game_history\")\n try:\n if platform.system() == \"Windows\":\n os.startfile(path)\n elif platform.system() == \"Darwin\":\n subprocess.run([\"open\", path])\n else:\n subprocess.run([\"xdg-open\", path])\n except OSError:\n print(\"Exception thrown :)\")\n box = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Information, \"Game History\",\n f\"Previously generated games can be found at:\\n{path}\",\n QtWidgets.QMessageBox.Ok, self)\n box.setTextInteractionFlags(Qt.TextSelectableByMouse)\n box.show()\n\n def _on_menu_action_layout_editor(self):\n from randovania.gui.corruption_layout_editor import CorruptionLayoutEditor\n self.corruption_editor = CorruptionLayoutEditor()\n self.corruption_editor.show()\n"},"license":{"kind":"string","value":"gpl-3.0"},"hash":{"kind":"number","value":-1612572667298678800,"string":"-1,612,572,667,298,678,800"},"line_mean":{"kind":"number","value":44.3303249097,"string":"44.330325"},"line_max":{"kind":"number","value":118,"string":"118"},"alpha_frac":{"kind":"number","value":0.6694540676,"string":"0.669454"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.873669597408607,"string":"3.87367"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45105,"cells":{"repo_name":{"kind":"string","value":"maltsev/LatexWebOffice"},"path":{"kind":"string","value":"app/views/document.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"15983"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\n\"\"\"\n\n* Purpose : Dokument- und Projektverwaltung Schnittstelle\n\n* Creation Date : 19-11-2014\n\n* Last Modified : Di 24 Feb 2015 15:46:51 CET\n\n* Author : mattis\n\n* Coauthors : christian, ingo, Kirill\n\n* Sprintnumber : 2, 5\n\n* Backlog entry : TEK1, 3ED9, DOK8, DO14, KOL1\n\n\"\"\"\nimport os\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.views.decorators.http import require_http_methods\nfrom django.shortcuts import render\nfrom django.views.static import serve\n\nimport settings\nfrom app.common import util\nfrom app.common.constants import ERROR_MESSAGES\nfrom app.views import file, folder, project, template\nfrom app.models.projecttemplate import ProjectTemplate\nfrom app.models.file.file import File\nfrom app.models.file.texfile import TexFile\nfrom app.models.file.plaintextfile import PlainTextFile\nfrom app.models.file.pdf import PDF\nfrom app.models.project import Project\nfrom app.models.folder import Folder\n\n\nglobalparas = {\n 'id': {'name': 'id', 'type': int},\n 'content': {'name': 'content', 'type': str},\n 'folderid': {'name': 'folderid', 'type': int},\n 'name': {'name': 'name', 'type': str},\n 'formatid': {'name': 'formatid', 'type': int},\n# 'compilerid': {'name': 'compilerid', 'type': int},\n 'forcecompile': {'name': 'forcecompile', 'type': int}\n}\n\n# dictionary mit verfügbaren Befehlen und den entsprechenden Aktionen\n# die entsprechenden Methoden befinden sich in:\n# '/app/views/project.py', '/app/views/file.py', '/app/views/folder.py' und '/app/views/collaboration.py'\navailable_commands = {\n 'projectcreate': {\n 'command': project.projectCreate,\n 'parameters': [{'para': globalparas['name'], 'stringcheck': True}]\n },\n 'projectclone': {\n 'command': project.projectClone,\n 'parameters': [{'para': globalparas['id'], 'type': Project, 'requirerights': ['owner', 'collaborator']},\n {'para': globalparas['name'], 'stringcheck': True}]\n },\n 'projectrm': {\n 'command': project.projectRm,\n 'parameters': [{'para': globalparas['id'], 'type': Project}]\n },\n 'projectrename': {\n 'command': project.projectRename,\n 'parameters': [{'para': globalparas['id'], 'type': Project},\n {'para': globalparas['name'], 'stringcheck': True}]\n },\n 'listprojects': {\n 'command': project.listProjects,\n 'parameters': []\n },\n 'importzip': {\n 'command': project.importZip,\n 'parameters': []\n },\n 'exportzip': {\n 'command': project.exportZip,\n 'parameters': [{'para': globalparas['id']}]\n },\n 'inviteuser': {\n 'command': project.inviteUser,\n 'parameters': [{'para': globalparas['id'], 'type': Project},\n {'para': globalparas['name'], 'stringcheck': True}]\n },\n 'hasinvitedusers': {\n 'command': project.hasInvitedUsers,\n 'parameters': [{'para': globalparas['id'], 'type': Project}]\n },\n 'listinvitedusers': {\n 'command': project.listInvitedUsers,\n 'parameters': [{'para': globalparas['id'], 'type': Project}]\n },\n 'listunconfirmedcollaborativeprojects': {\n 'command': project.listUnconfirmedCollaborativeProjects,\n 'parameters': []\n },\n 'activatecollaboration': {\n 'command': project.activateCollaboration,\n 'parameters': [{'para': globalparas['id'], 'type': Project, 'requirerights': ['owner', 'invitee']}]\n },\n 'quitcollaboration': {\n 'command': project.quitCollaboration,\n 'parameters': [\n {'para': globalparas['id'], 'type': Project, 'requirerights': ['owner', 'invitee', 'collaborator']}]\n },\n 'cancelcollaboration': {\n 'command': project.cancelCollaboration,\n 'parameters': [{'para': globalparas['id'], 'type': Project},\n {'para': globalparas['name'], 'stringcheck': True}]\n },\n 'createtex': {\n 'command': file.createTexFile,\n 'parameters': [{'para': globalparas['id'], 'type': Folder, 'requirerights': ['owner', 'collaborator']},\n {'para': globalparas['name'], 'filenamecheck': True}]\n },\n 'updatefile': {\n 'command': file.updateFile,\n 'parameters': [{'para': globalparas['id'], 'type': PlainTextFile,\n 'requirerights': ['owner', 'collaborator'], 'lockcheck': False},\n {'para': globalparas['content']}]\n },\n 'deletefile': {\n 'command': file.deleteFile,\n 'parameters': [{'para': globalparas['id'], 'type': File,\n 'requirerights': ['owner', 'collaborator'], 'lockcheck': True}]\n },\n 'renamefile': {\n 'command': file.renameFile,\n 'parameters': [{'para': globalparas['id'], 'type': File,\n 'requirerights': ['owner', 'collaborator'], 'lockcheck': True},\n {'para': globalparas['name'], 'filenamecheck': True}]\n },\n 'movefile': {\n 'command': file.moveFile,\n 'parameters': [{'para': globalparas['id'], 'type': File,\n 'requirerights': ['owner', 'collaborator'], 'lockcheck': True},\n {'para': globalparas['folderid'], 'type': Folder, 'requirerights': ['owner', 'collaborator']}]\n },\n 'uploadfiles': {\n 'command': file.uploadFiles,\n 'parameters': [{'para': globalparas['id'], 'type': Folder, 'requirerights': ['owner', 'collaborator']}]\n },\n 'downloadfile': {\n 'command': file.downloadFile,\n 'parameters': [{'para': globalparas['id']}]\n },\n 'gettext': {\n 'command': file.getText,\n 'parameters': [{'para': globalparas['id'], 'type': PlainTextFile, 'requirerights': ['owner', 'collaborator']}]\n },\n 'fileinfo': {\n 'command': file.fileInfo,\n 'parameters': [{'para': globalparas['id'], 'type': File, 'requirerights': ['owner', 'collaborator']}]\n },\n 'compile': {\n 'command': file.latexCompile,\n 'parameters': [{'para': globalparas['id'], 'type': TexFile,\n 'requirerights': ['owner', 'collaborator'], 'lockcheck': True},\n {'para': globalparas['formatid']},\n # {'para': globalparas['compilerid']},\n {'para': globalparas['forcecompile']}]\n },\n 'lockfile': {\n 'command': file.lockFile,\n 'parameters': [{'para': globalparas['id'], 'type': File, 'requirerights': ['owner', 'collaborator']}]\n },\n 'unlockfile': {\n 'command': file.unlockFile,\n 'parameters': [{'para': globalparas['id'], 'type': File, 'requirerights': ['owner', 'collaborator']}]\n },\n 'getlog': {\n 'command': file.getLog,\n 'parameters': [{'para': globalparas['id'], 'type': TexFile, 'requirerights': ['owner', 'collaborator']}]\n },\n 'createdir': {\n 'command': folder.createDir,\n 'parameters': [{'para': globalparas['id'], 'type': Folder, 'requirerights': ['owner', 'collaborator']},\n {'para': globalparas['name'], 'stringcheck': True}]\n },\n 'rmdir': {\n 'command': folder.rmDir,\n 'parameters': [{'para': globalparas['id'], 'type': Folder,\n 'requirerights': ['owner', 'collaborator'], 'lockcheck': True}]\n },\n 'renamedir': {\n 'command': folder.renameDir,\n 'parameters': [{'para': globalparas['id'], 'type': Folder,\n 'requirerights': ['owner', 'collaborator']},\n {'para': globalparas['name'], 'stringcheck': True}]\n },\n 'movedir': {\n 'command': folder.moveDir,\n 'parameters': [{'para': globalparas['id'], 'type': Folder,\n 'requirerights': ['owner', 'collaborator'], 'lockcheck': True},\n {'para': globalparas['folderid'], 'type': Folder, 'requirerights': ['owner', 'collaborator']}]\n },\n 'listfiles': {\n 'command': folder.listFiles,\n 'parameters': [{'para': globalparas['id'], 'type': Folder, 'requirerights': ['owner', 'collaborator']}]\n },\n 'template2project': {\n 'command': template.template2Project,\n 'parameters': [{'para': globalparas['id'], 'type': ProjectTemplate},\n {'para': globalparas['name'], 'stringcheck': True}]\n },\n 'project2template': {\n 'command': template.project2Template,\n 'parameters': [{'para': globalparas['id'], 'type': Project, 'requirerights': ['owner', 'collaborator']},\n {'para': globalparas['name'], 'stringcheck': True}]\n },\n 'templaterm': {\n 'command': template.templateRm,\n 'parameters': [{'para': globalparas['id'], 'type': ProjectTemplate}]\n },\n 'templaterename': {\n 'command': template.templateRename,\n 'parameters': [{'para': globalparas['id'], 'type': ProjectTemplate},\n {'para': globalparas['name'], 'stringcheck': True}]\n },\n 'listtemplates': {\n 'command': template.listTemplates,\n 'parameters': []\n }\n}\n\navailable_commands_output = {}\nfor key, value in available_commands.items():\n parameters = []\n for paras in value['parameters']:\n globalparainfo = (paras['para']).copy()\n value = {'para': globalparainfo}\n if globalparainfo.get('type'):\n del globalparainfo['type']\n parameters.append(value)\n if key == 'uploadfiles' or key == 'importzip':\n parameters.append({'para': {'name': 'files'}})\n available_commands_output.update({key: parameters})\n\n\n@login_required\ndef debug(request):\n return render(request, 'documentPoster.html')\n\n\n# Schnittstellenfunktion\n# bietet eine Schnittstelle zur Kommunikation zwischen Client und Server\n# liest den vom Client per POST Data übergebenen Befehl ein\n# und führt die entsprechende Methode aus\n@login_required\n@require_http_methods(['POST', 'GET'])\ndef execute(request):\n if request.method == 'POST' and 'command' in request.POST:\n\n # hole den aktuellen Benutzer\n user = request.user\n\n # wenn der Schlüssel nicht gefunden wurde\n # gib Fehlermeldung zurück\n if request.POST['command'] not in available_commands:\n return util.jsonErrorResponse(ERROR_MESSAGES['COMMANDNOTFOUND'], request)\n\n args = []\n\n # aktueller Befehl\n c = available_commands[request.POST['command']]\n # Parameter dieses Befehls\n paras = c['parameters']\n\n # durchlaufe alle Parameter des Befehls\n for para in paras:\n\n # wenn der Parameter nicht gefunden wurde oder ein Parameter, welcher eine id angeben sollte\n # Zeichen enthält, die keine Zahlen sind, gib Fehlermeldung zurück\n if request.POST.get(para['para']['name']) is None:\n return util.jsonErrorResponse(ERROR_MESSAGES['MISSINGPARAMETER'] % (para['para']), request)\n elif para['para']['type'] == int and (not request.POST.get(para['para']['name']).isdigit()):\n return util.jsonErrorResponse(ERROR_MESSAGES['MISSINGPARAMETER'] % (para['para']), request)\n # sonst füge den Parameter zu der Argumentliste hinzu\n else:\n args.append(request.POST[para['para']['name']])\n\n # Teste auf ungültige strings\n if para.get('stringcheck'):\n failstring, failurereturn = util.checkObjectForInvalidString(\n request.POST.get(para['para']['name']), request)\n if not failstring:\n return failurereturn\n elif para.get('filenamecheck'):\n failstring, failurereturn = util.checkFileForInvalidString(\n request.POST.get(para['para']['name']), request)\n if not failstring:\n return failurereturn\n\n # Teste, dass der User rechte auf das Objekt mit der angegebenen id\n # hat und diese existiert\n if para.get('type') and para['para']['type'] == int:\n objType = para.get('type')\n objId = request.POST.get(para['para']['name'])\n requireRights = para.get('requirerights', ['owner'])\n lockcheck = para.get('lockcheck', False)\n\n if objType == Project:\n rights, failurereturn = util.checkIfProjectExistsAndUserHasRights(objId, user, request,\n requireRights)\n if not rights:\n return failurereturn\n elif objType == Folder:\n rights, failurereturn = util.checkIfDirExistsAndUserHasRights(objId, user, request, requireRights, lockcheck)\n if not rights:\n return failurereturn\n elif objType == File:\n rights, failurereturn = util.checkIfFileExistsAndUserHasRights(objId, user, request, requireRights, lockcheck,\n objecttype=File)\n if not rights:\n return failurereturn\n\n elif objType == TexFile:\n rights, failurereturn = util.checkIfFileExistsAndUserHasRights(objId, user, request, requireRights, lockcheck,\n objecttype=TexFile)\n if not rights:\n return failurereturn\n elif objType == PlainTextFile:\n rights, failurereturn = util.checkIfFileExistsAndUserHasRights(objId, user, request, requireRights, lockcheck,\n objecttype=PlainTextFile)\n if not rights:\n return failurereturn\n elif objType == ProjectTemplate:\n # Überprüfe, ob Vorlage existiert und der User darauf Rechte hat\n emptystring, failurereturn = util.checkIfTemplateExistsAndUserHasRights(objId, user, request)\n if not emptystring:\n return failurereturn\n\n # führe den übergebenen Befehl aus\n return c['command'](request, user, *args)\n elif request.method == 'GET' and request.GET.get('command'):\n command = request.GET.get('command')\n pdfid = request.GET.get('id')\n texid = request.GET.get('texid')\n\n defaultpdfPath = filepath = os.path.join(settings.BASE_DIR, 'app', 'static', 'default.pdf')\n\n if (pdfid and not pdfid.isdigit()) or (texid and not texid.isdigit()):\n return serve(request, os.path.basename(defaultpdfPath), os.path.dirname(defaultpdfPath))\n\n if command == 'getpdf' and pdfid:\n requireRights = ['owner', 'collaborator']\n rights, failurereturn = util.checkIfFileExistsAndUserHasRights(pdfid, request.user, request, requireRights, lockcheck=False,\n objecttype=PDF)\n if not rights:\n return serve(request, os.path.basename(defaultpdfPath), os.path.dirname(defaultpdfPath))\n\n return file.getPDF(request, request.user, pdfid=pdfid, default=defaultpdfPath)\n\n elif command == 'getpdf' and texid:\n requireRights = ['owner', 'collaborator']\n rights, failurereturn = util.checkIfFileExistsAndUserHasRights(texid, request.user, request, requireRights, lockcheck=False,\n objecttype=TexFile)\n if not rights:\n return serve(request, os.path.basename(defaultpdfPath), os.path.dirname(defaultpdfPath))\n\n return file.getPDF(request, request.user, texid=texid, default=defaultpdfPath)\n\n return util.jsonErrorResponse(ERROR_MESSAGES['MISSINGPARAMETER'] % 'unknown', request)\n"},"license":{"kind":"string","value":"gpl-3.0"},"hash":{"kind":"number","value":953337725685583200,"string":"953,337,725,685,583,200"},"line_mean":{"kind":"number","value":42.6338797814,"string":"42.63388"},"line_max":{"kind":"number","value":136,"string":"136"},"alpha_frac":{"kind":"number","value":0.568503444,"string":"0.568503"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.9925,"string":"3.9925"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45106,"cells":{"repo_name":{"kind":"string","value":"psyonara/agonizomai"},"path":{"kind":"string","value":"sermons/models.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"5153"},"content":{"kind":"string","value":"from __future__ import unicode_literals\n\nfrom django.db import models\nfrom django.template.defaultfilters import slugify\n\nfrom bible.models import BibleBook\nfrom useraccounts.models import UserAccount\n\n\nclass Author(models.Model):\n name = models.CharField(null=False, blank=False, max_length=50)\n name_slug = models.SlugField(max_length=50, null=True, blank=True, db_index=True)\n\n def __str__(self):\n return self.name\n\n def save(self, *args, **kwargs):\n if self.name_slug is None or self.name_slug == \"\":\n self.name_slug = slugify(self.name)\n super(Author, self).save(*args, **kwargs)\n\n\nclass AuthorSetting(models.Model):\n \"\"\"\n Holds user settings specific to an author.\n \"\"\"\n\n author = models.ForeignKey(Author, on_delete=models.CASCADE)\n user = models.ForeignKey(\"useraccounts.UserAccount\", on_delete=models.CASCADE)\n name = models.CharField(max_length=30, db_index=True)\n value = models.CharField(max_length=50)\n\n\nclass Series(models.Model):\n name = models.CharField(null=False, blank=False, max_length=100)\n name_slug = models.SlugField(max_length=100, null=True, blank=True, db_index=True)\n author = models.ForeignKey(Author, null=False, blank=False, on_delete=models.CASCADE)\n complete = models.BooleanField(default=False)\n\n def __str__(self):\n return \"%s (%s)\" % (self.name, self.author.name)\n\n def save(self, *args, **kwargs):\n if self.name_slug is None or self.name_slug == \"\":\n self.name_slug = slugify(self.name)\n super(Series, self).save(*args, **kwargs)\n\n\nclass Sermon(models.Model):\n date_added = models.DateTimeField(auto_now_add=True)\n date_preached = models.DateField(null=True, blank=True)\n author = models.ForeignKey(Author, related_name=\"sermons\", on_delete=models.CASCADE)\n title = models.CharField(null=False, blank=False, max_length=100)\n title_slug = models.SlugField(max_length=100, null=True, blank=True, db_index=True)\n series = models.ForeignKey(\n Series, null=True, blank=True, related_name=\"sermons\", on_delete=models.CASCADE\n )\n ref = models.CharField(max_length=20, null=True, blank=True)\n\n def get_audio_file(self):\n files = self.media_files.filter(media_type=1)\n return files[0] if len(files) > 0 else None\n\n def __str__(self):\n return \"%s (by %s)\" % (self.title, self.author.name)\n\n def save(self, *args, **kwargs):\n if self.title_slug is None or self.title_slug == \"\":\n self.title_slug = slugify(self.title)\n super(Sermon, self).save(*args, **kwargs)\n\n class Meta:\n ordering = [\"-date_preached\"]\n\n\nclass ScriptureRef(models.Model):\n sermon = models.ForeignKey(Sermon, related_name=\"scripture_refs\", on_delete=models.CASCADE)\n bible_book = models.ForeignKey(BibleBook, on_delete=models.CASCADE)\n chapter_begin = models.PositiveSmallIntegerField()\n chapter_end = models.PositiveSmallIntegerField()\n verse_begin = models.PositiveSmallIntegerField(null=True, blank=True)\n verse_end = models.PositiveSmallIntegerField(null=True, blank=True)\n\n def __str__(self):\n end_string = \"\"\n if self.chapter_begin == self.chapter_end:\n end_string += \"%s %s\" % (self.bible_book.name, self.chapter_begin)\n if self.verse_begin is not None and self.verse_end is not None:\n if self.verse_begin == self.verse_end:\n end_string += \":%s\" % (self.verse_begin)\n else:\n end_string += \":%s-%s\" % (self.verse_begin, self.verse_end)\n else:\n end_string += \"%s %s\" % (self.bible_book.name, self.chapter_begin)\n if self.verse_begin is None and self.verse_end is None:\n end_string += \"-%s\" % (self.chapter_end)\n else:\n end_string += \":%s-%s:%s\" % (self.verse_begin, self.chapter_end, self.verse_end)\n return end_string\n\n\nclass MediaFile(models.Model):\n MEDIA_TYPE_CHOICES = ((1, \"audio\"), (2, \"video\"), (3, \"text\"), (4, \"pdf\"))\n\n LOCATION_TYPE_CHOICES = ((1, \"url\"),)\n\n sermon = models.ForeignKey(Sermon, related_name=\"media_files\", on_delete=models.CASCADE)\n media_type = models.PositiveSmallIntegerField(choices=MEDIA_TYPE_CHOICES, null=False, default=1)\n file_size = models.PositiveIntegerField(null=True, blank=True)\n location_type = models.PositiveSmallIntegerField(\n choices=LOCATION_TYPE_CHOICES, null=False, default=1\n )\n location = models.CharField(null=False, max_length=250)\n\n def __str__(self):\n return \"%s (%s)\" % (self.location, self.sermon.title)\n\n\nclass SermonSession(models.Model):\n sermon = models.ForeignKey(Sermon, related_name=\"sessions\", on_delete=models.CASCADE)\n session_started = models.DateTimeField(auto_now_add=True)\n session_updated = models.DateTimeField(auto_now=True)\n position = models.PositiveSmallIntegerField(default=0) # in seconds from start of file\n total_duration = models.PositiveSmallIntegerField(default=0) # in seconds\n user = models.ForeignKey(UserAccount, on_delete=models.CASCADE)\n completed = models.BooleanField(default=False)\n"},"license":{"kind":"string","value":"mit"},"hash":{"kind":"number","value":-3994879931140667400,"string":"-3,994,879,931,140,667,400"},"line_mean":{"kind":"number","value":39.8968253968,"string":"39.896825"},"line_max":{"kind":"number","value":100,"string":"100"},"alpha_frac":{"kind":"number","value":0.663496992,"string":"0.663497"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.5660899653979237,"string":"3.56609"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45107,"cells":{"repo_name":{"kind":"string","value":"funshine/rpidemo"},"path":{"kind":"string","value":"mqtt_oled/oled_test_luma.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"1273"},"content":{"kind":"string","value":"#!/usr/bin/python/\n# coding: utf-8\nimport time\nimport datetime\nfrom luma.core.interface.serial import i2c, spi\nfrom luma.core.render import canvas\nfrom luma.oled.device import ssd1306, ssd1325, ssd1331, sh1106\n\n\ndef do_nothing(obj):\n pass\n\n\n# rev.1 users set port=0\n# substitute spi(device=0, port=0) below if using that interface\n# serial = i2c(port=1, address=0x3C)\nserial = spi(device=0, port=0)\n\n# substitute ssd1331(...) or sh1106(...) below if using that device\n# device = ssd1306(serial, rotate=1)\ndevice = sh1106(serial)\n# device.cleanup = do_nothing\n\nprint(\"Testing display Hello World\")\n\nwith canvas(device) as draw:\n draw.rectangle(device.bounding_box, outline=\"white\", fill=\"black\")\n draw.text((30, 40), \"Hello World\", fill=\"white\")\n\ntime.sleep(3)\n\nprint(\"Testing display ON/OFF...\")\nfor _ in range(5):\n time.sleep(0.5)\n device.hide()\n\n time.sleep(0.5)\n device.show()\n\nprint(\"Testing clear display...\")\ntime.sleep(2)\ndevice.clear()\n\nprint(\"Testing screen updates...\")\ntime.sleep(2)\nfor x in range(40):\n with canvas(device) as draw:\n now = datetime.datetime.now()\n draw.text((x, 4), str(now.date()), fill=\"white\")\n draw.text((10, 16), str(now.time()), fill=\"white\")\n time.sleep(0.1)\n\nprint(\"Quit, cleanup...\")\n"},"license":{"kind":"string","value":"mit"},"hash":{"kind":"number","value":2993683248832655000,"string":"2,993,683,248,832,655,000"},"line_mean":{"kind":"number","value":23.0188679245,"string":"23.018868"},"line_max":{"kind":"number","value":70,"string":"70"},"alpha_frac":{"kind":"number","value":0.671641791,"string":"0.671642"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.0094562647754137,"string":"3.009456"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45108,"cells":{"repo_name":{"kind":"string","value":"jantman/nagios-scripts"},"path":{"kind":"string","value":"check_icinga_ido.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"6939"},"content":{"kind":"string","value":"#!/usr/bin/env python\n\"\"\"\nScript to check last update of core programstatus\nand service checks in Icinga ido2db Postgres database\n\"\"\"\n\n#\n# The latest version of this script lives at:\n# \n#\n# Please file bug/feature requests and submit patches through\n# the above GitHub repository. Feedback and patches are greatly\n# appreciated; patches are preferred as GitHub pull requests, but\n# emailed patches are also accepted.\n#\n# Copyright 2014 Jason Antman all rights reserved.\n# See the above git repository's LICENSE file for license terms (GPLv3).\n#\n\nimport sys\nfrom datetime import datetime\nimport pytz\nimport logging\nimport argparse\nfrom math import ceil\n\nimport nagiosplugin\nimport psycopg2\n\nimport pprint\n\n_log = logging.getLogger('nagiosplugin')\nutc = pytz.utc\n\nclass IdoStatus(nagiosplugin.Resource):\n \"\"\"Check age of ido2db programstatus and last service check in postgres database\"\"\"\n def __init__(self, db_host, db_name, db_user, db_pass, db_port=5432):\n self.db_host = db_host\n self.db_user = db_user\n self.db_pass = db_pass\n self.db_port = db_port\n self.db_name = db_name\n\n def probe(self):\n _log.info(\"connecting to Postgres DB %s on %s\" % (self.db_name, self.db_host))\n try:\n conn_str = \"dbname='%s' user='%s' host='%s' password='%s' port='%s' application_name='%s'\" % (\n self.db_name,\n self.db_user,\n self.db_host,\n self.db_pass,\n self.db_port,\n \"check_icinga_ido_core.py\",\n )\n _log.debug(\"psycopg2 connect string: %s\" % conn_str)\n conn = psycopg2.connect(conn_str)\n except psycopg2.OperationalError, e:\n _log.info(\"got psycopg2.OperationalError: %s\" % e.__str__())\n raise nagiosplugin.CheckError(e.__str__())\n _log.info(\"connected to database\")\n # these queries come from https://wiki.icinga.org/display/testing/Special+IDOUtils+Queries\n cur = conn.cursor()\n _log.debug(\"got cursor\")\n sql = \"SELECT EXTRACT(EPOCH FROM (NOW()-status_update_time)) AS age from icinga_programstatus where (UNIX_TIMESTAMP(status_update_time) > UNIX_TIMESTAMP(NOW())-60);\"\n _log.debug(\"executing query: %s\" % sql)\n cur.execute(sql)\n row = cur.fetchone()\n _log.debug(\"result: %s\" % row)\n programstatus_age = ceil(row[0])\n sql = \"select (UNIX_TIMESTAMP(NOW())-UNIX_TIMESTAMP(ss.status_update_time)) as age from icinga_servicestatus ss join icinga_objects os on os.object_id=ss.service_object_id order by status_update_time desc limit 1;\"\n _log.debug(\"executing query: %s\" % sql)\n cur.execute(sql)\n row = cur.fetchone()\n _log.debug(\"result: %s\" % row)\n last_check_age = ceil(row[0])\n return [\n nagiosplugin.Metric('programstatus_age', programstatus_age, uom='s', min=0),\n nagiosplugin.Metric('last_check_age', last_check_age, uom='s', min=0),\n ]\n\nclass LoadSummary(nagiosplugin.Summary):\n \"\"\"LoadSummary is used to provide custom outputs to the check\"\"\"\n def __init__(self, db_name):\n self.db_name = db_name\n\n def _human_time(self, seconds):\n \"\"\"convert an integer seconds into human-readable hms\"\"\"\n mins, secs = divmod(seconds, 60)\n hours, mins = divmod(mins, 60)\n return '%02d:%02d:%02d' % (hours, mins, secs)\n\n def _state_marker(self, state):\n \"\"\"return a textual marker for result states\"\"\"\n if type(state) == type(nagiosplugin.state.Critical):\n return \" (Crit)\"\n if type(state) == type(nagiosplugin.state.Warn):\n return \" (Warn)\"\n if type(state) == type(nagiosplugin.state.Unknown):\n return \" (Unk)\"\n return \"\"\n\n def status_line(self, results):\n if type(results.most_significant_state) == type(nagiosplugin.state.Unknown):\n # won't have perf values, so special handling\n return results.most_significant[0].hint.splitlines()[0]\n return \"Last Programstatus Update %s ago%s; Last Service Status Update %s ago%s (%s)\" % (\n self._human_time(results['programstatus_age'].metric.value),\n self._state_marker(results['programstatus_age'].state),\n self._human_time(results['last_check_age'].metric.value),\n self._state_marker(results['last_check_age'].state),\n self.db_name)\n\n def ok(self, results):\n return self.status_line(results)\n\n def problem(self, results):\n return self.status_line(results)\n\n@nagiosplugin.guarded\ndef main():\n parser = argparse.ArgumentParser(description=__doc__)\n parser.add_argument('-H', '--hostname', dest='hostname',\n help='Postgres server hostname')\n parser.add_argument('-p', '--port', dest='port',\n default='5432',\n help='Postgres port (Default: 5432)')\n parser.add_argument('-u', '--username', dest='username',\n default='icinga-ido',\n help='Postgres username (Default: icinga-ido)')\n parser.add_argument('-a', '--password', dest='password',\n default='icinga',\n help='Postgres password (Default: icinga)')\n parser.add_argument('-n', '--db-name', dest='db_name',\n default='icinga_ido',\n help='Postgres database name (Default: icinga_ido)')\n parser.add_argument('-w', '--warning', dest='warning',\n default='120',\n help='warning threshold for age of last programstatus or service status update, in seconds (Default: 120 / 2m)')\n parser.add_argument('-c', '--critical', dest='critical',\n default='600',\n help='critical threshold for age of last programstatus or service status update, in seconds (Default: 600 / 10m)')\n parser.add_argument('-v', '--verbose', action='count', default=0,\n help='increase output verbosity (use up to 3 times)')\n parser.add_argument('-t', '--timeout', dest='timeout',\n default=30,\n help='timeout (in seconds) for the command (Default: 30)')\n\n args = parser.parse_args()\n\n if not args.hostname:\n raise nagiosplugin.CheckError('hostname (-H|--hostname) must be provided')\n\n check = nagiosplugin.Check(\n IdoStatus(args.hostname, args.db_name, args.username, args.password, args.port),\n nagiosplugin.ScalarContext('programstatus_age', args.warning, args.critical),\n nagiosplugin.ScalarContext('last_check_age', args.warning, args.critical),\n LoadSummary(args.db_name))\n\n check.main(args.verbose, args.timeout)\n\nif __name__ == '__main__':\n main()\n"},"license":{"kind":"string","value":"gpl-3.0"},"hash":{"kind":"number","value":4422069438603399000,"string":"4,422,069,438,603,399,000"},"line_mean":{"kind":"number","value":41.8333333333,"string":"41.833333"},"line_max":{"kind":"number","value":222,"string":"222"},"alpha_frac":{"kind":"number","value":0.6081567949,"string":"0.608157"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.785597381342062,"string":"3.785597"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45109,"cells":{"repo_name":{"kind":"string","value":"3DLIRIOUS/BlendSCAD"},"path":{"kind":"string","value":"examples/example014.scad.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"1763"},"content":{"kind":"string","value":"# OpenSCAD example, ported by Michael Mlivoncic\n# a beautiful dice...\n# an interesting test case, to get the Boolean operations somehow fixed (TODO)\n\n\n#import sys\n#sys.path.append(\"O:/BlenderStuff\") \n\n\nimport blendscad \n\n\n#import imp\n#imp.reload(blendscad)\n#imp.reload(blendscad.core)\n#imp.reload(blendscad.primitives)\n\n\nblendscad.initns( globals() ) # try to add BlendSCAD names to current namespace .. as if they would be in this file...\n\n\n## Clear the open .blend file!!!\nclearAllObjects()\n\n###### End of Header ##############################################################################\n\n#OpenSCAD' intersection_for() is only a work around. As standard \"for\" implies a union of its content, this one is a combination of\n# for() and intersection() statements.\n# Not really needed as we currently do not support implicit union()'s, but to demonstrate, how it would be rewritten.\n# see: http://en.wikibooks.org/wiki/OpenSCAD_User_Manual/The_OpenSCAD_Language#Intersection_For_Loop\n\n\n# intersection_for(i = [\n# [0, 0, 0],\n# [10, 20, 300],\n# [200, 40, 57],\n# [20, 88, 57]\n# ])\n# rotate(i) cube([100, 20, 20], center = true)\n\n# example 2 - rotation:\n#intersection_for(i = [ ]\ntmp = None\nrnge = [ [ 0, 0, 0],\n\t\t[ 10, 20, 300],\n\t\t[200, 40, 57],\n\t\t[ 20, 88, 57] ]\nfor i in rnge:\n\ttmp = intersection(\n\t\trotate(i ,\n\t\tcube([100, 20, 20], center = true))\n\t\t, tmp);\n\n\n###### Begin of Footer ##############################################################################\ncolor(rands(0,1,3)) # random color last object. to see \"FINISH\" :-)\n\n# print timestamp and finish - sometimes it is easier to see differences in console then :-)\nimport time\nimport datetime\nst = datetime.datetime.fromtimestamp( time.time() ).strftime('%Y-%m-%d %H:%M:%S')\necho (\"FINISH\", st)\n\n\n"},"license":{"kind":"string","value":"gpl-3.0"},"hash":{"kind":"number","value":-6193139217817806000,"string":"-6,193,139,217,817,806,000"},"line_mean":{"kind":"number","value":26.546875,"string":"26.546875"},"line_max":{"kind":"number","value":131,"string":"131"},"alpha_frac":{"kind":"number","value":0.6148610323,"string":"0.614861"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.234862385321101,"string":"3.234862"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45110,"cells":{"repo_name":{"kind":"string","value":"stackunderflow-stackptr/stackptr_web"},"path":{"kind":"string","value":"crossbarconnect/client.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"8527"},"content":{"kind":"string","value":"###############################################################################\r\n##\r\n## Copyright (C) 2012-2014 Tavendo GmbH\r\n##\r\n## Licensed under the Apache License, Version 2.0 (the \"License\");\r\n## you may not use this file except in compliance with the License.\r\n## You may obtain a copy of the License at\r\n##\r\n## http://www.apache.org/licenses/LICENSE-2.0\r\n##\r\n## Unless required by applicable law or agreed to in writing, software\r\n## distributed under the License is distributed on an \"AS IS\" BASIS,\r\n## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n## See the License for the specific language governing permissions and\r\n## limitations under the License.\r\n##\r\n###############################################################################\r\n\r\n__all__ = ['Client']\r\n\r\ntry:\r\n import ssl\r\n _HAS_SSL = True\r\nexcept ImportError:\r\n _HAS_SSL = False\r\n\r\nimport sys\r\n\r\n_HAS_SSL_CLIENT_CONTEXT = sys.version_info >= (2,7,9)\r\n\r\nimport json\r\nimport hmac\r\nimport hashlib\r\nimport base64\r\nimport random\r\nfrom datetime import datetime\r\n\r\nimport six\r\nfrom six.moves.urllib import parse\r\nfrom six.moves.http_client import HTTPConnection, HTTPSConnection\r\n\r\n\r\n\r\ndef _utcnow():\r\n \"\"\"\r\n Get current time in UTC as ISO 8601 string.\r\n\r\n :returns str -- Current time as string in ISO 8601 format.\r\n \"\"\"\r\n now = datetime.utcnow()\r\n return now.strftime(\"%Y-%m-%dT%H:%M:%S.%f\")[:-3] + \"Z\"\r\n\r\n\r\n\r\ndef _parse_url(url):\r\n \"\"\"\r\n Parses a Crossbar.io HTTP bridge URL.\r\n \"\"\"\r\n parsed = parse.urlparse(url)\r\n if parsed.scheme not in [\"http\", \"https\"]:\r\n raise Exception(\"invalid Push URL scheme '%s'\" % parsed.scheme)\r\n if parsed.port is None or parsed.port == \"\":\r\n if parsed.scheme == \"http\":\r\n port = 80\r\n elif parsed.scheme == \"https\":\r\n port = 443\r\n else:\r\n raise Exception(\"logic error\")\r\n else:\r\n port = int(parsed.port)\r\n if parsed.fragment is not None and parsed.fragment != \"\":\r\n raise Exception(\"invalid Push URL: non-empty fragment '%s\" % parsed.fragment)\r\n if parsed.query is not None and parsed.query != \"\":\r\n raise Exception(\"invalid Push URL: non-empty query string '%s\" % parsed.query)\r\n if parsed.path is not None and parsed.path != \"\":\r\n ppath = parsed.path\r\n path = parse.unquote(ppath)\r\n else:\r\n ppath = \"/\"\r\n path = ppath\r\n return {'secure': parsed.scheme == \"https\",\r\n 'host': parsed.hostname,\r\n 'port': port,\r\n 'path': path}\r\n\r\n\r\n\r\nclass Client:\r\n \"\"\"\r\n Crossbar.io HTTP bridge client.\r\n \"\"\"\r\n\r\n def __init__(self, url, key = None, secret = None, timeout = 5, context = None):\r\n \"\"\"\r\n Create a new Crossbar.io push client.\r\n\r\n The only mandatory argument is the Push service endpoint of the Crossbar.io\r\n instance to push to.\r\n\r\n For signed pushes, provide authentication key and secret. If those are not\r\n given, unsigned pushes are performed.\r\n\r\n :param url: URL of the HTTP bridge of Crossbar.io (e.g. http://example.com:8080/push).\r\n :type url: str\r\n :param key: Optional key to use for signing requests.\r\n :type key: str\r\n :param secret: When using signed request, the secret corresponding to key.\r\n :type secret: str\r\n :param timeout: Timeout for requests.\r\n :type timeout: int\r\n :param context: If the HTTP bridge is running on HTTPS (that is securely over TLS),\r\n then the context provides the SSL settings the client should use (e.g. the\r\n certificate chain against which to verify the server certificate). This parameter\r\n is only available on Python 2.7.9+ and Python 3 (otherwise the parameter is silently\r\n ignored!). See: https://docs.python.org/2/library/ssl.html#ssl.SSLContext\r\n :type context: obj or None\r\n \"\"\"\r\n if six.PY2:\r\n if type(url) == str:\r\n url = six.u(url)\r\n if type(key) == str:\r\n key = six.u(key)\r\n if type(secret) == str:\r\n secret = six.u(secret)\r\n\r\n assert(type(url) == six.text_type)\r\n assert((key and secret) or (not key and not secret))\r\n assert(key is None or type(key) == six.text_type)\r\n assert(secret is None or type(secret) == six.text_type)\r\n assert(type(timeout) == int)\r\n if _HAS_SSL and _HAS_SSL_CLIENT_CONTEXT:\r\n assert(context is None or isinstance(context, ssl.SSLContext))\r\n\r\n self._seq = 1\r\n self._key = key\r\n self._secret = secret\r\n\r\n self._endpoint = _parse_url(url)\r\n self._endpoint['headers'] = {\r\n \"Content-type\": \"application/json\",\r\n \"User-agent\": \"crossbarconnect-python\"\r\n }\r\n\r\n if self._endpoint['secure']:\r\n if not _HAS_SSL:\r\n raise Exception(\"Bridge URL is using HTTPS, but Python SSL module is missing\")\r\n if _HAS_SSL_CLIENT_CONTEXT:\r\n self._connection = HTTPSConnection(self._endpoint['host'],\r\n self._endpoint['port'], timeout = timeout, context = context)\r\n else:\r\n self._connection = HTTPSConnection(self._endpoint['host'],\r\n self._endpoint['port'], timeout = timeout)\r\n else:\r\n self._connection = HTTPConnection(self._endpoint['host'],\r\n self._endpoint['port'], timeout = timeout)\r\n\r\n\r\n\r\n\r\n def publish(self, topic, *args, **kwargs):\r\n \"\"\"\r\n Publish an event to subscribers on specified topic via Crossbar.io HTTP bridge.\r\n\r\n The event payload (positional and keyword) can be of any type that can be\r\n serialized to JSON.\r\n\r\n If `kwargs` contains an `options` attribute, this is expected to\r\n be a dictionary with the following possible parameters:\r\n\r\n * `exclude`: A list of WAMP session IDs to exclude from receivers.\r\n * `eligible`: A list of WAMP session IDs eligible as receivers.\r\n\r\n :param topic: Topic to push to.\r\n :type topic: str\r\n :param args: Arbitrary application payload for the event (positional arguments).\r\n :type args: list\r\n :param kwargs: Arbitrary application payload for the event (keyword arguments).\r\n :type kwargs: dict\r\n\r\n :returns int -- The event publication ID assigned by the broker.\r\n \"\"\"\r\n if six.PY2 and type(topic) == str:\r\n topic = six.u(topic)\r\n assert(type(topic) == six.text_type)\r\n\r\n ## this will get filled and later serialized into HTTP/POST body\r\n ##\r\n event = {\r\n 'topic': topic\r\n }\r\n\r\n if 'options' in kwargs:\r\n event['options'] = kwargs.pop('options')\r\n assert(type(event['options']) == dict)\r\n\r\n if args:\r\n event['args'] = args\r\n\r\n if kwargs:\r\n event['kwargs'] = kwargs\r\n\r\n try:\r\n body = json.dumps(event, separators = (',',':'))\r\n if six.PY3:\r\n body = body.encode('utf8')\r\n\r\n except Exception as e:\r\n raise Exception(\"invalid event payload - not JSON serializable: {0}\".format(e))\r\n\r\n params = {\r\n 'timestamp': _utcnow(),\r\n 'seq': self._seq,\r\n }\r\n\r\n if self._key:\r\n ## if the request is to be signed, create extra fields and signature\r\n params['key'] = self._key\r\n params['nonce'] = random.randint(0, 9007199254740992)\r\n\r\n # HMAC[SHA256]_{secret} (key | timestamp | seq | nonce | body) => signature\r\n\r\n hm = hmac.new(self._secret.encode('utf8'), None, hashlib.sha256)\r\n hm.update(params['key'].encode('utf8'))\r\n hm.update(params['timestamp'].encode('utf8'))\r\n hm.update(u\"{0}\".format(params['seq']).encode('utf8'))\r\n hm.update(u\"{0}\".format(params['nonce']).encode('utf8'))\r\n hm.update(body)\r\n signature = base64.urlsafe_b64encode(hm.digest())\r\n\r\n params['signature'] = signature\r\n\r\n self._seq += 1\r\n\r\n path = \"{0}?{1}\".format(parse.quote(self._endpoint['path']), parse.urlencode(params))\r\n\r\n ## now issue the HTTP/POST\r\n ##\r\n self._connection.request('POST', path, body, self._endpoint['headers'])\r\n response = self._connection.getresponse()\r\n response_body = response.read()\r\n\r\n if response.status not in [200, 202]:\r\n raise Exception(\"publication request failed {0} [{1}] - {2}\".format(response.status, response.reason, response_body))\r\n\r\n try:\r\n res = json.loads(response_body)\r\n except Exception as e:\r\n raise Exception(\"publication request bogus result - {0}\".format(e))\r\n\r\n return res['id']\r\n"},"license":{"kind":"string","value":"agpl-3.0"},"hash":{"kind":"number","value":3583649226256367000,"string":"3,583,649,226,256,367,000"},"line_mean":{"kind":"number","value":32.108,"string":"32.108"},"line_max":{"kind":"number","value":126,"string":"126"},"alpha_frac":{"kind":"number","value":0.5871936203,"string":"0.587194"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":4.062410671748451,"string":"4.062411"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45111,"cells":{"repo_name":{"kind":"string","value":"VahidooX/DeepCCA"},"path":{"kind":"string","value":"objectives.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"2281"},"content":{"kind":"string","value":"import theano.tensor as T\n\n\ndef cca_loss(outdim_size, use_all_singular_values):\n \"\"\"\n The main loss function (inner_cca_objective) is wrapped in this function due to\n the constraints imposed by Keras on objective functions\n \"\"\"\n def inner_cca_objective(y_true, y_pred):\n \"\"\"\n It is the loss function of CCA as introduced in the original paper. There can be other formulations.\n It is implemented by Theano tensor operations, and does not work on Tensorflow backend\n y_true is just ignored\n \"\"\"\n\n r1 = 1e-4\n r2 = 1e-4\n eps = 1e-12\n o1 = o2 = y_pred.shape[1]//2\n\n # unpack (separate) the output of networks for view 1 and view 2\n H1 = y_pred[:, 0:o1].T\n H2 = y_pred[:, o1:o1+o2].T\n\n m = H1.shape[1]\n\n H1bar = H1 - (1.0 / m) * T.dot(H1, T.ones([m, m]))\n H2bar = H2 - (1.0 / m) * T.dot(H2, T.ones([m, m]))\n\n SigmaHat12 = (1.0 / (m - 1)) * T.dot(H1bar, H2bar.T)\n SigmaHat11 = (1.0 / (m - 1)) * T.dot(H1bar, H1bar.T) + r1 * T.eye(o1)\n SigmaHat22 = (1.0 / (m - 1)) * T.dot(H2bar, H2bar.T) + r2 * T.eye(o2)\n\n # Calculating the root inverse of covariance matrices by using eigen decomposition\n [D1, V1] = T.nlinalg.eigh(SigmaHat11)\n [D2, V2] = T.nlinalg.eigh(SigmaHat22)\n\n # Added to increase stability\n posInd1 = T.gt(D1, eps).nonzero()[0]\n D1 = D1[posInd1]\n V1 = V1[:, posInd1]\n posInd2 = T.gt(D2, eps).nonzero()[0]\n D2 = D2[posInd2]\n V2 = V2[:, posInd2]\n\n SigmaHat11RootInv = T.dot(T.dot(V1, T.nlinalg.diag(D1 ** -0.5)), V1.T)\n SigmaHat22RootInv = T.dot(T.dot(V2, T.nlinalg.diag(D2 ** -0.5)), V2.T)\n\n Tval = T.dot(T.dot(SigmaHat11RootInv, SigmaHat12), SigmaHat22RootInv)\n\n if use_all_singular_values:\n # all singular values are used to calculate the correlation\n corr = T.sqrt(T.nlinalg.trace(T.dot(Tval.T, Tval)))\n else:\n # just the top outdim_size singular values are used\n [U, V] = T.nlinalg.eigh(T.dot(Tval.T, Tval))\n U = U[T.gt(U, eps).nonzero()[0]]\n U = U.sort()\n corr = T.sum(T.sqrt(U[0:outdim_size]))\n\n return -corr\n\n return inner_cca_objective\n\n"},"license":{"kind":"string","value":"mit"},"hash":{"kind":"number","value":6360399072148163000,"string":"6,360,399,072,148,163,000"},"line_mean":{"kind":"number","value":34.640625,"string":"34.640625"},"line_max":{"kind":"number","value":108,"string":"108"},"alpha_frac":{"kind":"number","value":0.5620341955,"string":"0.562034"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":2.8091133004926108,"string":"2.809113"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45112,"cells":{"repo_name":{"kind":"string","value":"macioosch/dynamo-hard-spheres-sim"},"path":{"kind":"string","value":"convergence-plot.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"6346"},"content":{"kind":"string","value":"#!/usr/bin/env python2\n# encoding=utf-8\nfrom __future__ import division, print_function\n\nfrom glob import glob\nfrom itertools import izip\nfrom matplotlib import pyplot as plt\nimport numpy as np\n\ninput_files = glob(\"csv/convergence-256000-0.*.csv\")\n#input_files = glob(\"csv/convergence-500000-0.*.csv\")\n#input_files = glob(\"csv/convergence-1000188-0.*.csv\")\n\n#plotted_parameter = \"msds_diffusion\"\nplotted_parameter = \"pressures_collision\"\n#plotted_parameter = \"pressures_virial\"\n\n#plotted_parameter = \"msds_val\"\n#plotted_parameter = \"times\"\n\n\nlegend_names = []\ntight_layout = False\nshow_legend = False\n\nfor file_number, file_name in enumerate(sorted(input_files)):\n data = np.genfromtxt(file_name, delimiter='\\t', names=[\n \"packings\",\"densities\",\"collisions\",\"n_atoms\",\"pressures_virial\",\n \"pressures_collision\",\"msds_val\",\"msds_diffusion\",\"times\",\n \"std_pressures_virial\",\"std_pressures_collision\",\"std_msds_val\",\n \"std_msds_diffusion\",\"std_times\"])\n n_atoms = data[\"n_atoms\"][0]\n density = data[\"densities\"][0]\n equilibrated_collisions = data[\"collisions\"] - 2*data[\"collisions\"][0] \\\n + data[\"collisions\"][1]\n \"\"\"\n ### 5 graphs: D(CPS) ###\n tight_layout = True\n skip_points = 0\n ax = plt.subplot(3, 2, file_number+1)\n plt.fill_between((equilibrated_collisions / n_atoms)[skip_points:],\n data[plotted_parameter][skip_points:]\n - data[\"std_\" + plotted_parameter][skip_points:],\n data[plotted_parameter][skip_points:]\n + data[\"std_\" + plotted_parameter][skip_points:], alpha=0.3)\n plt.plot((equilibrated_collisions / n_atoms)[skip_points:],\n data[plotted_parameter][skip_points:], lw=2)\n if plotted_parameter == \"msds_diffusion\":\n plt.ylim(0.990*data[plotted_parameter][-1],\n 1.005*data[plotted_parameter][-1])\n plt.xlim([0, 1e5])\n plt.legend([\"Density {}\".format(data[\"densities\"][0])], loc=\"lower right\")\n ax.yaxis.set_major_formatter(plt.FormatStrFormatter('%.4f'))\n plt.xlabel(\"Collisions per sphere\")\n plt.ylabel(\"D\")\n \"\"\"\n\n ### 5 graphs: relative D(CPS) ###\n tight_layout = True\n skip_points = 0\n ax = plt.subplot(3, 2, file_number+1)\n plt.fill_between((equilibrated_collisions / n_atoms)[skip_points:],\n -1 + (data[plotted_parameter][skip_points:]\n - data[\"std_\" + plotted_parameter][skip_points:])/data[plotted_parameter][-1],\n -1 + (data[plotted_parameter][skip_points:]\n + data[\"std_\" + plotted_parameter][skip_points:])/data[plotted_parameter][-1], alpha=0.3)\n plt.plot((equilibrated_collisions / n_atoms)[skip_points:],\n -1 + data[plotted_parameter][skip_points:]/data[plotted_parameter][-1], lw=2)\n plt.ylim(data[\"std_\" + plotted_parameter][-1]*20*np.array([-1, 1])/data[plotted_parameter][-1])\n #plt.xscale(\"log\")\n plt.xlim([0, 1e5])\n plt.legend([\"$\\\\rho\\\\sigma^3=\\\\ {}$\".format(data[\"densities\"][0])], loc=\"lower right\")\n ax.yaxis.set_major_formatter(plt.FormatStrFormatter('%.2e'))\n plt.xlabel(\"$C/N$\")\n plt.ylabel(\"$[Z_{MD}(C) / Z_{MD}(C=10^5 N)] - 1$\")\n \"\"\"\n ### 1 graph: D(t) ###\n show_legend = True\n skip_points = 0\n plt.title(\"D(t) for 5 densities\")\n plt.loglog(data[\"times\"][skip_points:],\n data[plotted_parameter][skip_points:])\n legend_names.append(data[\"densities\"][0])\n plt.xlabel(\"Time\")\n plt.ylabel(\"D\")\n \"\"\"\n \"\"\"\n ### 1 graph: D(t) / Dinf ###\n show_legend = True\n skip_points = 0\n #plt.fill_between(data[\"times\"][skip_points:],\n # (data[plotted_parameter] - data[\"std_\" + plotted_parameter])\n # / data[plotted_parameter][-1] - 1,\n # (data[plotted_parameter] + data[\"std_\" + plotted_parameter])\n # / data[plotted_parameter][-1] - 1, color=\"grey\", alpha=0.4)\n plt.plot(data[\"times\"][skip_points:],\n data[plotted_parameter] / data[plotted_parameter][-1] - 1, lw=1)\n legend_names.append(data[\"densities\"][0])\n #plt.xscale(\"log\")\n plt.xlabel(\"Time\")\n plt.ylabel(\"D / D(t --> inf)\")\n \"\"\"\n \"\"\"\n ### 5 graphs: D(1/CPS) ###\n tight_layout = True\n skip_points = 40\n ax = plt.subplot(3, 2, file_number+1)\n plt.fill_between((n_atoms / equilibrated_collisions)[skip_points:],\n data[plotted_parameter][skip_points:]\n - data[\"std_\" + plotted_parameter][skip_points:],\n data[plotted_parameter][skip_points:]\n + data[\"std_\" + plotted_parameter][skip_points:], alpha=0.3)\n plt.plot((n_atoms / equilibrated_collisions)[skip_points:],\n data[plotted_parameter][skip_points:], lw=2)\n plt.title(\"Density {}:\".format(data[\"densities\"][0]))\n ax.yaxis.set_major_formatter(plt.FormatStrFormatter('%.7f'))\n plt.xlim(xmin=0)\n plt.xlabel(\"1 / Collisions per sphere\")\n plt.ylabel(\"D\")\n \"\"\"\n \"\"\"\n ### 1 graph: D(CPS) / Dinf ###\n show_legend = True\n plt.fill_between(equilibrated_collisions / n_atoms,\n (data[plotted_parameter] - data[\"std_\" + plotted_parameter])\n / data[plotted_parameter][-1] - 1,\n (data[plotted_parameter] + data[\"std_\" + plotted_parameter])\n / data[plotted_parameter][-1] - 1, color=\"grey\", alpha=0.4)\n plt.plot(equilibrated_collisions / n_atoms,\n data[plotted_parameter] / data[plotted_parameter][-1] - 1, lw=2)\n legend_names.append(data[\"densities\"][0])\n plt.xlabel(\"Collisions per sphere\")\n plt.ylabel(\"D / D(t --> inf)\")\n \"\"\"\n \"\"\"\n ### 1 graph: D(1/CPS) / Dinf ###\n show_legend = True\n plt.fill_between(n_atoms / equilibrated_collisions,\n (data[plotted_parameter] - data[\"std_\" + plotted_parameter])\n / data[plotted_parameter][-1] - 1,\n (data[plotted_parameter] + data[\"std_\" + plotted_parameter])\n / data[plotted_parameter][-1] - 1, color=\"grey\", alpha=0.4)\n plt.plot( n_atoms / equilibrated_collisions,\n data[plotted_parameter] / data[plotted_parameter][-1] - 1)\n legend_names.append(data[\"densities\"][0])\n plt.xlabel(\" 1 / Collisions per sphere\")\n plt.ylabel(plotted_parameter)\n \"\"\"\n\n#if tight_layout:\n# plt.tight_layout(pad=0.0, w_pad=0.0, h_pad=0.0)\nif show_legend:\n plt.legend(legend_names, title=\"Density:\", loc=\"lower right\")\n\nplt.show()\n"},"license":{"kind":"string","value":"gpl-3.0"},"hash":{"kind":"number","value":1205206185801680600,"string":"1,205,206,185,801,680,600"},"line_mean":{"kind":"number","value":39.9419354839,"string":"39.941935"},"line_max":{"kind":"number","value":101,"string":"101"},"alpha_frac":{"kind":"number","value":0.6019539868,"string":"0.601954"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.0835762876579205,"string":"3.083576"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45113,"cells":{"repo_name":{"kind":"string","value":"amdouglas/OpenPNM"},"path":{"kind":"string","value":"OpenPNM/Geometry/models/throat_misc.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"1124"},"content":{"kind":"string","value":"r\"\"\"\n===============================================================================\nthroat_misc -- Miscillaneous and generic functions to apply to throats\n===============================================================================\n\n\"\"\"\nimport scipy as _sp\n\n\ndef random(geometry, seed=None, num_range=[0, 1], **kwargs):\n r\"\"\"\n Assign random number to throats\n note: should this be called 'poisson'?\n \"\"\"\n range_size = num_range[1] - num_range[0]\n range_min = num_range[0]\n _sp.random.seed(seed=seed)\n value = _sp.random.rand(geometry.num_throats(),)\n value = value*range_size + range_min\n return value\n\n\ndef neighbor(geometry, network, pore_prop='pore.seed', mode='min', **kwargs):\n r\"\"\"\n Adopt a value based on the neighboring pores\n \"\"\"\n throats = network.throats(geometry.name)\n P12 = network.find_connected_pores(throats)\n pvalues = network[pore_prop][P12]\n if mode == 'min':\n value = _sp.amin(pvalues, axis=1)\n if mode == 'max':\n value = _sp.amax(pvalues, axis=1)\n if mode == 'mean':\n value = _sp.mean(pvalues, axis=1)\n return value\n"},"license":{"kind":"string","value":"mit"},"hash":{"kind":"number","value":7511632487340780000,"string":"7,511,632,487,340,780,000"},"line_mean":{"kind":"number","value":30.2222222222,"string":"30.222222"},"line_max":{"kind":"number","value":79,"string":"79"},"alpha_frac":{"kind":"number","value":0.5364768683,"string":"0.536477"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.523510971786834,"string":"3.523511"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45114,"cells":{"repo_name":{"kind":"string","value":"Digmaster/TicTacToe"},"path":{"kind":"string","value":"Agent.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"2030"},"content":{"kind":"string","value":"from random import randint\nfrom random import getrandbits\nfrom copy import deepcopy\n\n# Agent that will either be the human player or a secondary agent for the dual agent play\nclass DumbAgent:\n\t#initialize the board for the first player\n\tdef __init__(self, board):\n\t\tself.board = board\n\n\tdef __str__(self):\n\t\treturn \"Hi, Im dumb agent. I play randomly as player {0}\".format(self.player)\n\n\t# readin the next move for the human or secondary agent\n\tdef getNextMove(self, player):\n\t\tboard = deepcopy(self.board)\n\t\tif(player!='X' and player!='O'):\n\t\t\traise ValueError('The only valid players are X and O')\n\n\t\twhile(True):\n\t\t\ttry:\n\t\t\t\tsquare = randint(1, 9)\n\t\t\t\tboard.setSquare(square, player)\n\t\t\t\treturn square\n\t\t\texcept ValueError:\n\t\t\t\t\"\"\"Do nothing\"\"\"\n# Define the smart agent - uses the minimax algorithm\nclass SmartAgent:\n\tdef __init__(self, board):\n\t\tself.board = board\n\t\tself.signal = False\n\t\tself.bestVal = None\n\n\n\tdef __str__(self):\n\t\treturn \"Hi, Im smart agent. I whatever move will net me the most points, or avail my enemy of points. I'm {0}\".format(self.player)\n\n\t# to get the next move,call the decideMove function\n\tdef getNextMove(self, player):\n\t\tself.decideMove(deepcopy(self.board), player)\n\t\treturn self.bestVal\n\n\tdef decideMove(self, board, player):\n\t\tif(self.signal):\n\t\t\treturn 0\n\t\twinner = board.testWin() # test for a winning solution to the current state\n\t\tif(winner!='.'):\n\t\t\tif(winner=='X'):\n\t\t\t\treturn 1.0\n\t\t\telif(winner=='T'):\n\t\t\t\treturn 0.0\n\t\t\telse:\n\t\t\t\treturn -1.0\n\n\t\tvalues = []\n\t\tmoves = {}\n\t\tfor i in range(1,10):\n\t\t\tif(self.signal):\n\t\t\t\treturn 0\n\t\t\tif(board.getSquare(i)=='.'):\n\t\t\t\tnBoard = deepcopy(board)\n\t\t\t\tnBoard.setSquare(i, player)\n\t\t\t\tvalue = self.decideMove(nBoard, 'X' if player=='O' else 'O')\n\t\t\t\tvalues.append(value)\n\t\t\t\tmoves[value] = i\n\t\t\t\tif(player=='X'and value==1):\n\t\t\t\t\tbreak\n\t\t\t\telif(player=='O' and value==-1):\n\t\t\t\t\tbreak\n\t\t# calculate the highest probability / best move\n\t\tif(player=='X'):\n\t\t\tsum = max(values)\n\t\telse:\n\t\t\tsum = min(values)\n\t\tself.bestVal = moves[sum]\n\n\t\treturn sum\n"},"license":{"kind":"string","value":"apache-2.0"},"hash":{"kind":"number","value":287197937694822820,"string":"287,197,937,694,822,820"},"line_mean":{"kind":"number","value":25.3636363636,"string":"25.363636"},"line_max":{"kind":"number","value":132,"string":"132"},"alpha_frac":{"kind":"number","value":0.6669950739,"string":"0.666995"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.1424148606811144,"string":"3.142415"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45115,"cells":{"repo_name":{"kind":"string","value":"mfit/PdfTableAnnotator"},"path":{"kind":"string","value":"script/csv-compare.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"8051"},"content":{"kind":"string","value":"\"\"\"\n\n Copyright 2014 Matthias Frey\n \n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n \n http://www.apache.org/licenses/LICENSE-2.0\n \n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License. \n\"\"\"\n\n\"\"\" \n \n \n CSV-compare\n -----------\n \n Compare table data stored in CSV (comma seperated values) format.\n \n\"\"\"\n\n\nimport re\nimport csv\nimport sys\nimport os\n\n\ndef _pr_list(l1, l2, replace_chars = '[\\n ]'):\n \"\"\" Calculate precision and recall regarding elements of a list.\n \n When a 1:1 match cannot be achieved, the list pointers will be \n moved forward until a match occurs (first of list A, then of list B). \n The closest match will count, and matching will continue from those\n list positions onwards.\n \n The replace_chars parameter is used to remove characters from the \n strings before comparing. The default will remove newlines and spaces.\n \"\"\"\n def _fnext(l, item):\n item = re.sub(replace_chars, '', item).strip()\n \n for i, txt in enumerate(l):\n txt = re.sub(replace_chars, '', txt).strip()\n if txt == item:\n return i\n return -1\n \n if len(l2)==0 or len(l1)==0:\n return 0, 0\n \n i = 0\n j = 0\n match = 0\n while len(l1)>i and len(l2)>j:\n t1 = re.sub(replace_chars, '', l1[i]).strip()\n t2 = re.sub(replace_chars, '', l2[j]).strip()\n if t1 == t2:\n match += 1\n i += 1\n j += 1\n else:\n ii = _fnext(l1[i:], l2[j])\n jj = _fnext(l2[j:], l1[i])\n if ii>=0 and (ii=0: j+=jj\n else:\n i+=1\n j+=1\n \n return float(match)/len(l2), float(match)/len(l1) \n\n\ndef clean_table(tab):\n \"\"\" Remove trailing empty cells resulting from the way some\n spreadsheet application output csv for multi table documents.\n \"\"\"\n if len(tab) == 0: \n return []\n n_empty=[]\n for row in tab:\n for n, val in enumerate(reversed(row)):\n if val!='':\n break \n n_empty.append(n)\n strip_cols = min(n_empty)\n cleaned = []\n for row in tab:\n cleaned.append(row[0:len(row)-strip_cols])\n return cleaned\n\n\ndef compare_tables(tab1, tab2):\n \"\"\" Compare two tables (2dim lists).\n \"\"\"\n \n info = {'rows_a':len(tab1),\n 'rows_b':len(tab2),\n 'rows_match': 1 if len(tab1) == len(tab2) else 0,\n }\n \n sizesA = [len(l) for l in tab1]\n sizesB = [len(l) for l in tab2]\n \n info['dim_match'] = 1 if sizesA == sizesB else 0\n info['size_a'] = sum(sizesA)\n info['size_b'] = sum(sizesA)\n \n if len(sizesA)>0 and len(sizesB)>0:\n info['cols_match'] = 1 if min(sizesA) == max(sizesA) and \\\n min(sizesB) == max(sizesB) and min(sizesA) == min(sizesB) else 0\n \n # 'flatten' tables\n cellsA = []\n cellsB = []\n for r in tab1: cellsA += [c for c in r]\n for r in tab2: cellsB += [c for c in r]\n\n info['p'], info['r'] = _pr_list(cellsA, cellsB)\n info['F1'] = F1(info['p'], info['r'])\n \n return info\n \n\ndef compare_files_pr(file1, file2):\n \"\"\" Calculate simple P/R .\n Compare lists of cells, left to right , top to bottom.\n \"\"\"\n cells = [[], []]\n for i, fname in enumerate([file1, file2]):\n with file(fname) as csvfile:\n rd = csv.reader(csvfile, delimiter=',', quotechar='\"')\n for r in rd:\n cells[i] += [c for c in r]\n\n return _pr_list(*cells)\n\n\ndef compare_files(file1, file2):\n \"\"\" Compare two csv files.\n \"\"\"\n \n groundtruth = read_tables_from_file(file1)\n try:\n compare = read_tables_from_file(file2)\n except:\n compare = []\n \n tbs = [groundtruth, compare]\n \n finfo = {'tabcount_a': len(tbs[0]),\n 'tabcount_b': len(tbs[1]),\n 'tabcount_match': len(tbs[0]) == len(tbs[1]),\n }\n \n finfo['tables']=[]\n for n in range(0, len(tbs[0])):\n if finfo['tabcount_match']:\n comp_info = compare_tables(tbs[0][n], tbs[1][n])\n else:\n if n < len(tbs[1]):\n comp_info = compare_tables(tbs[0][n], tbs[1][n])\n else:\n comp_info = compare_tables(tbs[0][n], [[]])\n comp_info['n']=n\n finfo['tables'].append(comp_info)\n \n return finfo \n\n\ndef output_compareinfo_csv(file, info, fields=['p', 'r', 'F1']):\n \"\"\" Pre-format a row that holds measures about similarity of a table\n to the ground truth.\n \"\"\"\n lines = []\n tabmatch = 1 if info['tabcount_match'] else 0\n for tinfo in info['tables']:\n lines.append([file, str(tabmatch)] + [str(tinfo[k]) for k in fields])\n return lines\n\n\ndef F1(p, r):\n \"\"\" Calculate F1 score from precision and recall.\n Returns zero if one of p, r is zero.\n \"\"\"\n return (2*p*r/(p+r)) if p != 0 and r != 0 else 0\n\n\ndef read_tables_from_file(csvfile):\n \"\"\" Opens csvfile, returns all tables found.\n Guesses csv format (delimiter, etc.)\n Splits data into different tables at newline (or empty row).\n Returns list of tables.\n \"\"\" \n tables=[]\n table_id = 0\n with file(csvfile) as f:\n sniffer = csv.Sniffer()\n dialect = sniffer.sniff(f.next())\n rd = csv.reader(f, delimiter=dialect.delimiter, \n quotechar=dialect.quotechar)\n for r in rd:\n if len(tables) <= table_id:\n tables.append([])\n \n # Begin next table if there is an empty line\n if r == [] or sum([len(v) for v in r]) == 0:\n if len(tables[table_id])>0:\n table_id+=1\n else:\n tables[table_id].append(r)\n \n return [clean_table(t) for t in tables if t!=[]]\n\n\n\nif __name__ == '__main__':\n \"\"\" Script usage.\n \"\"\"\n \n fields = [\n #'rows_a', 'rows_b',\n #'size_a', 'size_b',\n 'n',\n 'rows_match', 'cols_match', 'dim_match',\n 'p', 'r', 'F1',]\n limitchar = ' & '\n \n if len(sys.argv) < 3:\n print \"Specify two (csv-)files or directories\"\n quit(-1)\n \n # Params 1 + 2 are files or directories\n file1 = sys.argv[1]\n file2 = sys.argv[2]\n srcinfo = [os.path.basename(file1), os.path.basename(file2)]\n \n # 3rd parameter becomes 'tooldef' (text cols to name rows), \n # and 4th parameter tells whether to print headers \n tooldef = sys.argv[3].split('-') if len(sys.argv) > 3 else ['na', 'na']\n print_headers = len(sys.argv) > 4 and sys.argv[4] in [\"1\", \"y\", \"yes\"]\n \n if print_headers:\n print ','.join(['name', 'tool', 'src1', 'src2', \n 'filename', 'tabsmatch',] + fields)\n \n if os.path.isfile(file1) and os.path.isfile(file2):\n inf = compare_files(file1, file2)\n lines = output_compareinfo_csv(file1, inf, fields)\n for l in lines:\n print ','.join(tooldef + srcinfo + l)\n \n \n elif os.path.isdir(file1) and os.path.isdir(file2):\n for f in [path for path in os.listdir(file1) if path[-4:]=='.csv']:\n if os.path.isfile(file2 + '/' + f):\n inf = compare_files(file1 + '/' + f, file2 + '/' + f)\n lines = output_compareinfo_csv(f, inf, fields)\n for l in lines:\n print ','.join(tooldef + srcinfo + l)\n else:\n print ','.join(['','',] + srcinfo + ['', \"Missing {} for {} {}\".format(f, *tooldef)])"},"license":{"kind":"string","value":"apache-2.0"},"hash":{"kind":"number","value":-7229538163487513000,"string":"-7,229,538,163,487,513,000"},"line_mean":{"kind":"number","value":29.0447761194,"string":"29.044776"},"line_max":{"kind":"number","value":101,"string":"101"},"alpha_frac":{"kind":"number","value":0.527263694,"string":"0.527264"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.5498236331569664,"string":"3.549824"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45116,"cells":{"repo_name":{"kind":"string","value":"locke105/mclib"},"path":{"kind":"string","value":"examples/wsgi.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"1781"},"content":{"kind":"string","value":"\nimport cgi\nimport json\nfrom wsgiref import simple_server\n\nimport falcon\n\nfrom mclib import mc_info\n\nclass MCInfo(object):\n\n def on_get(self, req, resp):\n\n host = req.get_param('host', required=True)\n port = req.get_param_as_int('port', min=1024,\n max=65565)\n\n try:\n if port is not None:\n info = mc_info.get_info(host=host,\n port=port)\n else:\n info = mc_info.get_info(host=host)\n except Exception:\n raise Exception('Couldn\\'t retrieve info.')\n\n if '.json' in req.uri:\n resp.body = self.get_json(info)\n return\n\n preferred = req.client_prefers(['application/json', 'text/html'])\n if 'html' in preferred:\n resp.content_type = 'text/html'\n resp.body = self.get_html(info)\n else:\n resp.body = self.get_json(info)\n\n def get_html(self, info):\n\n html = \"\"\"\n\n\n\n\"\"\"\n\n for k,v in info.iteritems():\n items = {'key': cgi.escape(k)}\n if isinstance(v, basestring):\n items['val'] = cgi.escape(v)\n else:\n items['val'] = v\n html = html + '' % items\n\n html = html + '
%(key)s%(val)s
'\n\n return html\n\n def get_json(self, info):\n return json.dumps(info)\n\napp = falcon.API()\n\nmcinfo = MCInfo()\n\napp.add_route('/mcinfo', mcinfo)\napp.add_route('/mcinfo.json', mcinfo)\n\nif __name__ == '__main__':\n httpd = simple_server.make_server('0.0.0.0', 3000, app)\n httpd.serve_forever()\n"},"license":{"kind":"string","value":"apache-2.0"},"hash":{"kind":"number","value":4936456139620774000,"string":"4,936,456,139,620,774,000"},"line_mean":{"kind":"number","value":21.2625,"string":"21.2625"},"line_max":{"kind":"number","value":77,"string":"77"},"alpha_frac":{"kind":"number","value":0.5216170691,"string":"0.521617"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.4853228962818004,"string":"3.485323"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45117,"cells":{"repo_name":{"kind":"string","value":"Meertecha/LearnPythonTheGame"},"path":{"kind":"string","value":"pyGameEngine.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"3565"},"content":{"kind":"string","value":"### Imports\nimport pickle, os, platform, random\n\n### Functions\ndef main():\n\tcurPlayer = loadPlayer( 'Tory' )\n\tcurGame = loadGame( 'Python_Tutorial' ) \n\tstartGame(curPlayer, curGame)\n\t\ndef banner():\n\t'''\n\tif platform.system() == \"Windows\":\n\t\tclearCmd = \"cls\"\n\telif platform.system() == \"Linux\":\n\t\tclearCmd = \"clear\"\n\telse:\n\t\tprint (\"Unknown operating system detected. Some operations may not perform correctly!\\n\")\n\tos.system(clearCmd)\n\t'''\n\tversion = 0.1\n\tbanner = (\" **Welcome to the Python Learning Environment\\n\\\n **Written by Tory Clasen - Version: \" + str(version) + \" \\n\\\n **For help at any time please type '?' or 'help' \\n\\\n **To exit the program type 'exit' or 'quit' \\n\\n\")\n\tprint banner\n\t\ndef startGame(curPlayer, curGame):\n\ttry:\n\t\tcurScore = curPlayer['score'][curGame['gameName']]\n\texcept:\n\t\tcurScore = 0\n\n\twhile True:\n\t\t#banner()\n\t\tprint '----------------------------------------\\n' + curGame['gameName'] + ' has been loaded'\n\t\tprint curGame['banner'] + '\\n----------------------------------------'\n\t\ttry:\n\t\t\tpickle.dump( curPlayer, open( ( str(curPlayer['Name']) + \".plep\"), \"wb\" ) )\n\t\texcept:\n\t\t\tprint \"Error! Unable to save player profile at current location!\"\n\t\tprint 'Your current score is: ' + str(curScore) + ' out of a total possible score of: ' + str(len(curGame['gameData']))\n\t\tprint \"Question \" + str(curScore) + \": \\n\" + str(curGame['gameData'][curScore][\"Q\"]) + \"\\n\"\n\t\ttemp = curGame['gameData'][curScore][\"D\"]\n\t\tdata = eval(str(curGame['gameData'][curScore][\"D\"]))\n\t\tprint \"Data \" + str(curScore) + \": \\n\" + data\n\t\tprint '----------------------------------------\\n'\n\t\ttry:\n\t\t\tmyAnswer = eval(str(getInput('What command do you want to submit? ')))\n\t\t\tif myAnswer == (eval(str(curGame['gameData'][curScore][\"A\"]))):\n\t\t\t\tprint \"Correct!\"\n\t\t\t\tcurScore = curScore + 1\n\t\t\telse:\n\t\t\t\tprint \"Incorrect!\"\n\t\texcept:\n\t\t\tprint 'The answer you submitted crashed the program, so it was probably wrong'\n\t\t#break\n\t\t\ndef getInput(prompt):\n\ttheInput = raw_input( str(prompt) + \"\\n\" )\n\tif theInput == '?' or theInput.lower() == 'help':\n\t\tprint \"HELP! HELP!\"\n\telif theInput.lower() == 'exit' or theInput.lower() == 'quit':\n\t\traise SystemExit\n\telse:\n\t\treturn theInput\n\ndef loadPlayer(playerName = ''):\n\t#banner()\n\tcurPlayer = {}\n\t\n\tif playerName == '':\n\t\tplayerName = getInput(\"I would like to load your profile. \\nWhat is your name? \")\n\t\n\ttry:\n\t\t# Attempt to load the player file.\n\t\tcurPlayer = pickle.load( open( ( str(playerName) + \".plep\"), \"rb\" ) )\n\t\tprint \"Player profile found... loading player data...\"\n\texcept:\n\t\t# Ask the player if they want to try to create a new profile file.\n\t\tcreateNew = getInput( \"Player profile not found for '\" + str(playerName) + \"'\\nWould you like to create a new one? [Y/N]\").lower()\n\t\tcurPlayer = {'Name':playerName}\n\t\tif createNew == \"y\":\n\t\t\ttry:\n\t\t\t\tpickle.dump( curPlayer, open( ( str(playerName) + \".plep\"), \"wb\" ) )\n\t\t\t\tprint \"Player profile successfully created!\"\n\t\t\texcept:\n\t\t\t\tprint \"Error! Unable to create player profile at current location!\"\n\t\telse:\n\t\t\tprint \"Progress will not be saved for you...\"\n\treturn curPlayer\t\t\n\t\ndef loadGame(gameName = ''):\n\tbanner()\n\tcurGame = {}\n\n\twhile True:\n\t\tif gameName == '':\n\t\t\tgameName = getInput(\"What game would you like to load? \")\n\t\ttry:\n\t\t\t# Attempt to load the player file.\n\t\t\tcurGame = pickle.load( open( ( str(gameName) + \".pleg\"), \"rb\" ) )\n\t\t\tprint \"Game module found... loading game data...\"\n\t\t\tgameName = ''\n\t\t\tbreak\n\t\texcept:\n\t\t\tgameName = ''\n\t\t\tprint \"Game module not found... please try again...\"\n\treturn curGame\t\t\n\t\nmain()\n"},"license":{"kind":"string","value":"mit"},"hash":{"kind":"number","value":4891151655040956000,"string":"4,891,151,655,040,956,000"},"line_mean":{"kind":"number","value":31.4090909091,"string":"31.409091"},"line_max":{"kind":"number","value":133,"string":"133"},"alpha_frac":{"kind":"number","value":0.6157082749,"string":"0.615708"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.2291666666666665,"string":"3.229167"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45118,"cells":{"repo_name":{"kind":"string","value":"openbig/odoo-contract"},"path":{"kind":"string","value":"partner_billing/wizard/sale_make_invoice_advance.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"1615"},"content":{"kind":"string","value":"# -*- encoding: utf-8 -*-\n##############################################################################\n#\n# partner_billing\n# (C) 2015 Mikołaj Dziurzyński, Grzegorz Grzelak, Thorsten Vocks (big-consulting GmbH)\n# All Rights reserved\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\nfrom openerp.osv import osv\nfrom openerp import fields, models \nimport logging\n\n_logger = logging.getLogger(__name__)\n\nclass sale_advance_payment_inv(osv.osv_memory):\n\t_inherit = \"sale.advance.payment.inv\"\n\n\tdef _prepare_advance_invoice_vals(self, cr, uid, ids, context=None):\n\t\tres = super(sale_advance_payment_inv,self)._prepare_advance_invoice_vals(cr, uid, ids, context=context)\n\t\tsale_order_obj = self.pool.get('sale.order')\n\t\tfor pair in res:\n\t\t\tfor sale in sale_order_obj.browse(cr, uid, [pair[0]]):\n\t\t\t\tpair[1]['associated_partner'] = sale.associated_partner and sale.associated_partner.id or False\n\n\t\treturn res\n\n"},"license":{"kind":"string","value":"agpl-3.0"},"hash":{"kind":"number","value":-6439668196751878000,"string":"-6,439,668,196,751,878,000"},"line_mean":{"kind":"number","value":39.325,"string":"39.325"},"line_max":{"kind":"number","value":105,"string":"105"},"alpha_frac":{"kind":"number","value":0.6515809051,"string":"0.651581"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.7511627906976743,"string":"3.751163"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45119,"cells":{"repo_name":{"kind":"string","value":"lipixun/pytest"},"path":{"kind":"string","value":"rabbitmq/deadchannel/going2dead.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"2112"},"content":{"kind":"string","value":"#!/usr/bin/env python\n# encoding=utf8\n# The dead channel applicationn\n\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf8')\n\nfrom uuid import uuid4\nfrom time import time, sleep\n\nfrom haigha.connections.rabbit_connection import RabbitConnection\nfrom haigha.message import Message\n\nclass Client(object):\n \"\"\"The RPC Client\n \"\"\"\n def __init__(self, host, port, vhost, user, password):\n \"\"\"Create a new Server\n \"\"\"\n self._conn = RabbitConnection(host = host, port = port, vhost = vhost, user = user, password = password)\n self._channel = self._conn.channel()\n result = self._channel.queue.declare(arguments = { 'x-dead-letter-exchange': 'amq.topic', 'x-dead-letter-routing-key': 'test.dead_channel' })\n self._deadQueue = result[0]\n # Send a message\n self._channel.basic.publish(Message('OMG! I\\'m dead!'), '', self._deadQueue)\n\n def dead(self):\n \"\"\"Normal dead\n \"\"\"\n self._channel.close()\n\nif __name__ == '__main__':\n\n from argparse import ArgumentParser\n\n def getArguments():\n \"\"\"Get arguments\n \"\"\"\n parser = ArgumentParser(description = 'RabbitMQ dead channel client')\n parser.add_argument('--host', dest = 'host', required = True, help = 'The host')\n parser.add_argument('--port', dest = 'port', default = 5672, type = int, help = 'The port')\n parser.add_argument('--vhost', dest = 'vhost', default = '/test', help = 'The virtual host')\n parser.add_argument('--user', dest = 'user', default = 'test', help = 'The user name')\n parser.add_argument('--password', dest = 'password', default = 'test', help = 'The password')\n # Done\n return parser.parse_args()\n\n def main():\n \"\"\"The main entry\n \"\"\"\n args = getArguments()\n # Create the server\n client = Client(args.host, args.port, args.vhost, args.user, args.password)\n # Go to dead\n print 'Will go to dead in 10s, or you can use ctrl + c to cause a unexpected death'\n sleep(10)\n client.dead()\n print 'Normal dead'\n\n main()\n\n"},"license":{"kind":"string","value":"gpl-2.0"},"hash":{"kind":"number","value":-8202055047594408000,"string":"-8,202,055,047,594,408,000"},"line_mean":{"kind":"number","value":33.064516129,"string":"33.064516"},"line_max":{"kind":"number","value":149,"string":"149"},"alpha_frac":{"kind":"number","value":0.6060606061,"string":"0.606061"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.84,"string":"3.84"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45120,"cells":{"repo_name":{"kind":"string","value":"gf712/AbPyTools"},"path":{"kind":"string","value":"abpytools/core/fab_collection.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"14123"},"content":{"kind":"string","value":"from .chain_collection import ChainCollection\nimport numpy as np\nimport pandas as pd\nfrom .chain import calculate_charge\nfrom abpytools.utils import DataLoader\nfrom operator import itemgetter\nfrom .fab import Fab\nfrom .helper_functions import germline_identity_pd, to_numbering_table\nfrom .base import CollectionBase\nimport os\nimport json\nfrom .utils import (json_FabCollection_formatter, pb2_FabCollection_formatter, pb2_FabCollection_parser,\n json_FabCollection_parser)\nfrom .flags import *\n\nif BACKEND_FLAGS.HAS_PROTO:\n from abpytools.core.formats import FabCollectionProto\n\n\nclass FabCollection(CollectionBase):\n\n def __init__(self, fab=None, heavy_chains=None, light_chains=None, names=None):\n \"\"\"\n Fab object container that handles combinations of light/heavy Chain pairs.\n\n Args:\n fab (list):\n heavy_chains (ChainCollection):\n light_chains (ChainCollection):\n names (list):\n \"\"\"\n # check if it's a Chain object\n if heavy_chains is None and light_chains is None and fab is None:\n raise ValueError('Provide a list of Chain objects or an ChainCollection object')\n\n # check if fab object is a list and if all object are abpytools.Fab objects\n if isinstance(fab, list) and all(isinstance(fab_i, Fab) for fab_i in fab):\n self._fab = fab\n self._light_chains = ChainCollection([x[0] for x in self._fab])\n self._heavy_chains = ChainCollection([x[1] for x in self._fab])\n\n if fab is None and (heavy_chains is not None and light_chains is not None):\n\n if isinstance(heavy_chains, list):\n self._heavy_chains = ChainCollection(antibody_objects=heavy_chains)\n\n elif isinstance(heavy_chains, ChainCollection):\n self._heavy_chains = heavy_chains\n\n else:\n raise ValueError('Provide a list of Chain objects or an ChainCollection object')\n\n if isinstance(light_chains, list):\n self._light_chains = ChainCollection(antibody_objects=light_chains)\n\n elif isinstance(light_chains, ChainCollection):\n self._light_chains = light_chains\n\n else:\n raise ValueError('Provide a list of Chain objects or an ChainCollection object')\n\n if len(self._light_chains.loading_status()) == 0:\n self._light_chains.load()\n\n if len(self._heavy_chains.loading_status()) == 0:\n self._heavy_chains.load()\n\n if self._light_chains.n_ab != self._heavy_chains.n_ab:\n raise ValueError('Number of heavy chains must be the same of light chains')\n\n if isinstance(names, list) and all(isinstance(name, str) for name in names):\n if len(names) == self._heavy_chains.n_ab:\n self._names = names\n else:\n raise ValueError(\n 'Length of name list must be the same as length of heavy_chains/light chains lists')\n\n elif names is None:\n self._names = ['{} - {}'.format(heavy, light) for heavy, light in zip(self._heavy_chains.names,\n self._light_chains.names)]\n\n else:\n raise ValueError(\"Names expected a list of strings, instead got {}\".format(type(names)))\n\n self._n_ab = self._light_chains.n_ab\n self._pair_sequences = [heavy + light for light, heavy in zip(self._heavy_chains.sequences,\n self._light_chains.sequences)]\n\n # keep the name of the heavy and light chains internally to keep everything in the right order\n self._internal_heavy_name = self._heavy_chains.names\n self._internal_light_name = self._light_chains.names\n\n # even though it makes more sense to draw all these values from the base Fab objects this is much slower\n # whenever self._n_ab > 1 it makes more sense to use the self._heavy_chain and self._light_chain containers\n # in all the methods\n # in essence the abpytools.Fab object is just a representative building block that could in future just\n # cache data and would then represent a speed up in the calculations\n def molecular_weights(self, monoisotopic=False):\n\n return [heavy + light for heavy, light in zip(self._heavy_chains.molecular_weights(monoisotopic=monoisotopic),\n self._light_chains.molecular_weights(monoisotopic=monoisotopic))]\n\n def extinction_coefficients(self, extinction_coefficient_database='Standard', reduced=False, normalise=False,\n **kwargs):\n\n heavy_ec = self._heavy_chains.extinction_coefficients(\n extinction_coefficient_database=extinction_coefficient_database,\n reduced=reduced)\n light_ec = self._light_chains.extinction_coefficients(\n extinction_coefficient_database=extinction_coefficient_database,\n reduced=reduced)\n\n if normalise:\n return [(heavy + light) / mw for heavy, light, mw in\n zip(heavy_ec, light_ec, self.molecular_weights(**kwargs))]\n else:\n return [heavy + light for heavy, light in zip(heavy_ec, light_ec)]\n\n def hydrophobicity_matrix(self):\n\n return np.column_stack((self._heavy_chains.hydrophobicity_matrix(), self._light_chains.hydrophobicity_matrix()))\n\n def charge(self):\n\n return np.column_stack((self._heavy_chains.charge, self._light_chains.charge))\n\n def total_charge(self, ph=7.4, pka_database='Wikipedia'):\n\n available_pi_databases = [\"EMBOSS\", \"DTASetect\", \"Solomon\", \"Sillero\", \"Rodwell\", \"Wikipedia\", \"Lehninger\",\n \"Grimsley\"]\n assert pka_database in available_pi_databases, \\\n \"Selected pI database {} not available. Available databases: {}\".format(pka_database,\n ' ,'.join(available_pi_databases))\n\n data_loader = DataLoader(data_type='AminoAcidProperties', data=['pI', pka_database])\n pka_data = data_loader.get_data()\n\n return [calculate_charge(sequence=seq, ph=ph, pka_values=pka_data) for seq in self.sequences]\n\n def igblast_local_query(self, file_path, chain):\n\n if chain.lower() == 'light':\n self._light_chains.igblast_local_query(file_path=file_path)\n elif chain.lower() == 'heavy':\n self._heavy_chains.igblast_local_query(file_path=file_path)\n else:\n raise ValueError('Specify if the data being loaded is for the heavy or light chain')\n\n def igblast_server_query(self, **kwargs):\n self._light_chains.igblast_server_query(**kwargs)\n self._heavy_chains.igblast_server_query(**kwargs)\n\n def numbering_table(self, as_array=False, region='all', chain='both', **kwargs):\n\n return to_numbering_table(as_array=as_array, region=region, chain=chain,\n heavy_chains_numbering_table=self._heavy_chains.numbering_table,\n light_chains_numbering_table=self._light_chains.numbering_table,\n names=self.names, **kwargs)\n\n def _germline_pd(self):\n\n # empty dictionaries return false, so this condition checks if any of the values are False\n if all([x for x in self._light_chains.germline_identity.values()]) is False:\n # this means there is no information about the germline,\n # by default it will run a web query\n self._light_chains.igblast_server_query()\n if all([x for x in self._heavy_chains.germline_identity.values()]) is False:\n self._heavy_chains.igblast_server_query()\n\n heavy_chain_germlines = self._heavy_chains.germline\n light_chain_germlines = self._light_chains.germline\n\n data = np.array([[heavy_chain_germlines[x][0] for x in self._internal_heavy_name],\n [heavy_chain_germlines[x][1] for x in self._internal_heavy_name],\n [light_chain_germlines[x][0] for x in self._internal_light_name],\n [light_chain_germlines[x][1] for x in self._internal_light_name]]).T\n\n df = pd.DataFrame(data=data,\n columns=pd.MultiIndex.from_tuples([('Heavy', 'Assignment'),\n ('Heavy', 'Score'),\n ('Light', 'Assignment'),\n ('Light', 'Score')]),\n index=self.names)\n\n df.loc[:, (slice(None), 'Score')] = df.loc[:, (slice(None), 'Score')].apply(pd.to_numeric)\n\n return df\n\n def save_to_json(self, path, update=True):\n with open(os.path.join(path + '.json'), 'w') as f:\n fab_data = json_FabCollection_formatter(self)\n json.dump(fab_data, f, indent=2)\n\n def save_to_pb2(self, path, update=True):\n proto_parser = FabCollectionProto()\n try:\n with open(os.path.join(path + '.pb2'), 'rb') as f:\n proto_parser.ParseFromString(f.read())\n except IOError:\n # Creating new file\n pass\n\n pb2_FabCollection_formatter(self, proto_parser)\n\n with open(os.path.join(path + '.pb2'), 'wb') as f:\n f.write(proto_parser.SerializeToString())\n\n def save_to_fasta(self, path, update=True):\n raise NotImplementedError\n\n @classmethod\n def load_from_json(cls, path, n_threads=20, verbose=True, show_progressbar=True):\n with open(path, 'r') as f:\n data = json.load(f)\n\n fab_objects = json_FabCollection_parser(data)\n\n fab_collection = cls(fab=fab_objects)\n\n return fab_collection\n\n @classmethod\n def load_from_pb2(cls, path, n_threads=20, verbose=True, show_progressbar=True):\n with open(path, 'rb') as f:\n proto_parser = FabCollectionProto()\n proto_parser.ParseFromString(f.read())\n\n fab_objects = pb2_FabCollection_parser(proto_parser)\n\n fab_collection = cls(fab=fab_objects)\n\n return fab_collection\n\n @classmethod\n def load_from_fasta(cls, path, numbering_scheme=NUMBERING_FLAGS.CHOTHIA, n_threads=20,\n verbose=True, show_progressbar=True):\n raise NotImplementedError\n\n def _get_names_iter(self, chain='both'):\n if chain == 'both':\n for light_chain, heavy_chain in zip(self._light_chains, self._heavy_chains):\n yield f\"{light_chain.name}-{heavy_chain.name}\"\n elif chain == 'light':\n for light_chain in self._light_chains:\n yield light_chain.name\n elif chain == 'heavy':\n for heavy_chain in self._heavy_chains:\n yield heavy_chain.name\n else:\n raise ValueError(f\"Unknown chain type ({chain}), available options are:\"\n f\"both, light or heavy.\")\n\n @property\n def regions(self):\n heavy_regions = self._heavy_chains.ab_region_index()\n light_regions = self._light_chains.ab_region_index()\n\n return {name: {CHAIN_FLAGS.HEAVY_CHAIN: heavy_regions[heavy],\n CHAIN_FLAGS.LIGHT_CHAIN: light_regions[light]} for name, heavy, light in\n zip(self.names, self._internal_heavy_name, self._internal_light_name)}\n\n @property\n def names(self):\n return self._names\n\n @property\n def sequences(self):\n return self._pair_sequences\n\n @property\n def aligned_sequences(self):\n return [heavy + light for light, heavy in\n zip(self._heavy_chains.aligned_sequences,\n self._light_chains.aligned_sequences)]\n\n @property\n def n_ab(self):\n return self._n_ab\n\n @property\n def germline_identity(self):\n return self._germline_identity()\n\n @property\n def germline(self):\n return self._germline_pd()\n\n def _string_summary_basic(self):\n return \"abpytools.FabCollection Number of sequences: {}\".format(self._n_ab)\n\n def __len__(self):\n return self._n_ab\n\n def __repr__(self):\n return \"<%s at 0x%02x>\" % (self._string_summary_basic(), id(self))\n\n def __getitem__(self, indices):\n if isinstance(indices, int):\n return Fab(heavy_chain=self._heavy_chains[indices],\n light_chain=self._light_chains[indices],\n name=self.names[indices], load=False)\n else:\n return FabCollection(heavy_chains=list(itemgetter(*indices)(self._heavy_chains)),\n light_chains=list(itemgetter(*indices)(self._light_chains)),\n names=list(itemgetter(*indices)(self._names)))\n\n def _germline_identity(self):\n\n # empty dictionaries return false, so this condition checks if any of the values are False\n if all([x for x in self._light_chains.germline_identity.values()]) is False:\n # this means there is no information about the germline,\n # by default it will run a web query\n self._light_chains.igblast_server_query()\n if all([x for x in self._heavy_chains.germline_identity.values()]) is False:\n self._heavy_chains.igblast_server_query()\n\n return germline_identity_pd(self._heavy_chains.germline_identity,\n self._light_chains.germline_identity,\n self._internal_heavy_name,\n self._internal_light_name,\n self._names)\n\n def get_object(self, name):\n\n \"\"\"\n\n :param name: str\n :return:\n \"\"\"\n\n if name in self.names:\n index = self.names.index(name)\n return self[index]\n else:\n raise ValueError('Could not find sequence with specified name')\n"},"license":{"kind":"string","value":"mit"},"hash":{"kind":"number","value":-4991626911150680000,"string":"-4,991,626,911,150,680,000"},"line_mean":{"kind":"number","value":41.1582089552,"string":"41.158209"},"line_max":{"kind":"number","value":120,"string":"120"},"alpha_frac":{"kind":"number","value":0.5930751257,"string":"0.593075"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":4.02594070695553,"string":"4.025941"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45121,"cells":{"repo_name":{"kind":"string","value":"jwill89/clifford-discord-bot"},"path":{"kind":"string","value":"source/retired/main.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"31345"},"content":{"kind":"string","value":"import discord\nfrom discord.ext import commands\nimport random\nimport MySQLdb\n\n# ********************************************** #\n# DEFINITIONS ********************************** #\n# ********************************************** #\n\n# Bot Description\ndescription = '''Official Zealot Gaming Discord bot!'''\n\n# Define Bot\nbot = commands.Bot(command_prefix='!', description='Official Zealot Gaming Discord Bot')\n\n# Define MySQL DB and Cursor Object\ndb = MySQLdb.connect(host=\"localhost\",\n user=\"discord_secure\",\n passwd=\"password-here\",\n db=\"discord\")\n\n\n# ********************************************** #\n# FUNCTIONS ************************************ #\n# ********************************************** #\n\n# Check for Game Abbreviations\ndef is_game_abv(game_abv: str):\n try:\n sql = \"SELECT 1 FROM games WHERE `abv` = %s LIMIT 1\"\n cur = db.cursor()\n result = cur.execute(sql, (game_abv,))\n cur.close()\n except Exception as e:\n print('Exception: ' + str(e))\n result = 0\n\n # If we got a result, true, else false\n return result == 1\n\n\n# Check for Game Names\ndef is_game_name(game_name: str):\n try:\n sql = \"SELECT 1 FROM games WHERE `name` = %s LIMIT 1\"\n cur = db.cursor()\n result = cur.execute(sql, (game_name,))\n cur.close()\n except Exception as e:\n print('Exception: ' + str(e))\n result = 0\n\n # If we got a result, true, else false\n return result == 1\n\n\n# Check for Staff Member Status\ndef is_staff(member: discord.Member):\n\n # Return True or False if User is a Staff Member\n return 'Staff' in [r.name for r in member.roles]\n\n\n# ********************************************** #\n# BOT EVENTS *********************************** #\n# ********************************************** #\n\n# Bot Start Event\t\n@bot.event\nasync def on_ready():\n print('Logged in as')\n print(bot.user.name)\n print(bot.user.id)\n print('------')\n await bot.change_presence(game=discord.Game(name='Zealot Gaming'))\n\n\n# Welcome Message\n@bot.event\nasync def on_member_join(member):\n channel = bot.get_channel('108369515502411776')\n fmt = \"Everyone welcome {0.mention} to Zealot Gaming! Have a great time here! :wink: \" \\\n \"http://puu.sh/nG6Qe.wav\".format(member)\n await bot.send_message(channel, fmt)\n\n\n# Goodbye Message\n@bot.event\nasync def on_member_remove(member):\n channel = bot.get_channel('108369515502411776')\n fmt = \":wave: Goodbye {0}, we're sad to see you go!\".format(member.name)\n await bot.send_message(channel, fmt)\n\n\n# ********************************************** #\n# UN-GROUPED BOT COMMANDS ********************** #\n# ********************************************** #\n\n# COMMAND: !hello\n@bot.command(pass_context=True)\nasync def hello(ctx):\n # we do not want the bot to reply to itself\n if ctx.message.author == bot.user:\n return\n else:\n msg = 'Hello {0.message.author.mention}'.format(ctx)\n await bot.send_message(ctx.message.channel, msg)\n\n\n# COMMAND: !carlito\n@bot.command()\nasync def carlito():\n \"\"\"The legendary message of Carlito, maz00's personal cabana boy.\"\"\"\n await bot.say(\"wew men :ok_hand::skin-tone-1: that's some good shit:100: some good shit :100: that's some good shit\"\n \" right there :100: :ok_hand::skin-tone-1: right there :ok_hand::skin-tone-1: :100: sign me the FUCK \"\n \"up:100: :100: :ok_hand::skin-tone-1: :eggplant:\")\n\n\n# COMMAND: !eightball\n@bot.command(pass_context=True)\nasync def eightball(ctx, question: str):\n \"\"\"Rolls a magic 8-ball to answer any question you have.\"\"\"\n\n if question is None:\n await bot.say('{0.message.author.mention}, you did not ask a question.'.format(ctx))\n return\n\n # Answers List (Classic 8-Ball, 20 Answers)\n answers = ['It is certain.',\n 'It is decidedly so',\n 'Without a doubt.',\n 'Yes, definitely.',\n 'You may rely on it.',\n 'As I see it, yes.',\n 'Most likely.',\n 'Outlook good.',\n 'Yes.',\n 'Signs point to yes.',\n 'Reply hazy; try again.',\n 'Ask again later.',\n 'Better not tell you now.',\n 'Cannot predict now.',\n 'Concentrate, then ask again.',\n 'Do not count on it.',\n 'My reply is no.',\n 'My sources say no.',\n 'Outlook not so good.',\n 'Very doubtful.']\n\n # Send the Answer\n await bot.say('{0.message.author.mention}, '.format(ctx) + random.choice(answers))\n\n\n# COMMAND: !roll\n@bot.command()\nasync def roll(dice: str):\n \"\"\"Rolls a dice in NdN format.\"\"\"\n try:\n rolls, limit = map(int, dice.split('d'))\n except Exception:\n await bot.say('Format has to be in NdN!')\n return\n\n result = ', '.join(str(random.randint(1, limit)) for r in range(rolls))\n await bot.say(result)\n\n\n# COMMAND: !choose\n@bot.command()\nasync def choose(*choices: str):\n \"\"\"Chooses between multiple choices.\"\"\"\n await bot.say(random.choice(choices))\n\n\n# COMMAND: !joined\n@bot.command()\nasync def joined(member: discord.Member):\n \"\"\"Says when a member joined.\"\"\"\n await bot.say('{0.name} joined in {0.joined_at}'.format(member))\n\n\n# COMMAND: !get_roles\n@bot.command()\nasync def get_roles(member: discord.Member):\n \"\"\"Lists a User's Roles\"\"\"\n\n total = 0\n role_list = ''\n\n for role in member.roles:\n if total > 0:\n role_list += ', '\n role_list += str(role)\n total += 1\n\n await bot.say('{0.name} is a member of these roles: '.format(member) + role_list)\n\n\n# COMMAND: !get_channel_id\n@bot.command(pass_context=True)\nasync def get_channel_id(ctx):\n \"\"\"Lists the ID of the channel the message is sent in.\"\"\"\n\n # Is the user allowed? (Must be staff)\n if not is_staff(ctx.message.author):\n await bot.say('{0.mention}, you must be a staff member to use this command.'.format(ctx.message.author))\n return\n\n await bot.say('Channel ID is {0.id}'.format(ctx.message.channel))\n\n\n# COMMAND: !join\n@bot.command(pass_context=True)\nasync def join(ctx, *, role_name: str):\n \"\"\"Allows a user to join a public group.\"\"\"\n\n # List of Allowed Public Roles\n allowed_roles = ['Europe',\n 'North America',\n 'Oceania',\n 'Overwatch',\n 'League of Legends',\n 'Co-op',\n 'Minna-chan']\n\n if role_name not in allowed_roles:\n await bot.say('{0.mention}, you may only join allowed public groups.'.format(ctx.message.author))\n return\n\n # Define role, then add role to member.\n try:\n role = discord.utils.get(ctx.message.server.roles, name=role_name)\n await bot.add_roles(ctx.message.author, role)\n except Exception as e:\n await bot.send_message(ctx.message.channel, \"{0.mention}, there was an error getting the roster for you. \"\n \"I'm sorry! : \".format(ctx.message.author) + str(e))\n return\n\n # Success Message\n await bot.say('{0.mention}, you have successfully been added to the group **{1}**.'\n .format(ctx.message.author, role_name))\n\n\n# ********************************************** #\n# GROUPED COMMANDS : EVENTS ******************** #\n# ********************************************** #\n\n# COMMAND: !events\n@bot.group(pass_context=True)\nasync def events(ctx):\n \"\"\"Manage events and attendance!\"\"\"\n\n if ctx.invoked_subcommand is None:\n await bot.say('Invalid command passed. Must be *add*, *description*, *edit*, *register*, or *remove*.')\n\n\n# COMMAND: !events add\n@events.command(name='add', pass_context=True)\nasync def events_add(ctx, date: str, time: str, *, title: str):\n \"\"\"Add an event to the Events List!\n Date **must** be in YYYY/MM/DD format. Time **must** be in UTC.\"\"\"\n\n # Set #events Channel\n event_channel = bot.get_channel('296694692135829504')\n\n # Is the user allowed? (Must be staff)\n if not is_staff(ctx.message.author):\n await bot.say('{0.mention}, you must be a staff member to use this command.'.format(ctx.message.author))\n return\n\n # Make sure we have a date.\n if date is None:\n await bot.say('Error: You must enter a date in YYYY/MM/DD format.')\n return\n\n # Make sure we have a time.\n if time is None:\n await bot.say('Error: You must enter a time in HH:MM format in UTC timezone.')\n return\n\n # Make sure we have a title.\n if date is None:\n await bot.say('Error: You must enter a title for the event.')\n return\n\n # Add Event to Database\n try:\n sql = \"INSERT INTO events (`date`,`time`,`title`) VALUES (%s, %s, %s)\"\n cur = db.cursor()\n cur.execute(sql, (date, time, title))\n event_id = cur.lastrowid\n\n msg_text = \"**Title**: {0} \\n**Event ID**: {1} \\n**Date & Time**: {2} at {3} (UTC)\"\n\n # Add Message to Events Channel and Save Message ID\n message = await bot.send_message(event_channel, msg_text.format(title, event_id, date, time))\n\n cur.execute('UPDATE events SET `message_id` = %s WHERE `event_id` = %s', (message.id, event_id))\n db.commit()\n cur.close()\n\n except Exception as e:\n await bot.say('{0.mention}, there was an error adding the event to the list. '.format(ctx.message.author)\n + str(e))\n return\n\n # Success Message\n await bot.say('{0.mention}, your event was successfully added. The event ID is: {1}.'\n .format(ctx.message.author, event_id))\n\n\n# COMMAND: !events description\n@events.command(name='description', pass_context=True)\nasync def events_description(ctx, event_id: int, *, desc: str):\n \"\"\"Adds a Description to an Event Given an Event ID.\"\"\"\n\n # EVENT CHANNEL ID: 296694692135829504\n event_channel = bot.get_channel('296694692135829504')\n\n # Is the user allowed? (Must be staff)\n if not is_staff(ctx.message.author):\n await bot.say('{0.mention}, you must be a staff member to use this command.'.format(ctx.message.author))\n return\n\n # Make sure we have a date.\n if event_id is None:\n await bot.say('Error: You must enter an event ID. Check the #events channel.')\n return\n\n # Make sure we have a date.\n if desc is None:\n await bot.say('Error: You must enter a description.')\n return\n\n try:\n sql = \"UPDATE events SET `description` = %s WHERE `event_id` = %s\"\n cur = db.cursor()\n cur.execute(sql, (desc, event_id))\n cur.execute(\"SELECT `message_id` FROM events WHERE `event_id` = %s\", (event_id,))\n msg_id = cur.fetchone()\n message = await bot.get_message(event_channel, msg_id[0])\n\n msg_text = message.content + \" \\n**Description**: {0}\".format(desc)\n\n # Update Message in Events Channel with Description\n await bot.edit_message(message, msg_text)\n\n db.commit()\n cur.close()\n except Exception as e:\n await bot.say('{0.mention}, there was an error adding a description to the event. '.format(ctx.message.author)\n + str(e))\n return\n\n # Success Message\n await bot.say('{0.mention}, the event was successfully updated with a description.'.format(ctx.message.author))\n\n\n# ********************************************** #\n# GROUPED COMMANDS : GAMES ********************* #\n# ********************************************** #\n\n# COMMAND: !games\n@bot.group(pass_context=True)\nasync def games(ctx):\n \"\"\"Manages games for the roster.\"\"\"\n\n if ctx.invoked_subcommand is None:\n await bot.say('Invalid command passed. Must be *add*, *edit*, *list*, or *remove*.')\n\n\n# COMMAND: !games add\n@games.command(name='add', pass_context=True)\nasync def games_add(ctx, game_abv: str, *, game_name: str):\n \"\"\"Adds a game to the list of games available in the roster.\"\"\"\n\n # Is the user allowed? (Must be staff)\n if not is_staff(ctx.message.author):\n await bot.say('{0.mention}, you must be a staff member to use this command.'.format(ctx.message.author))\n return\n\n # Does Game Abbreviation Exist?\n if is_game_abv(game_abv):\n await bot.say('{0.mention}, this abbreviation is already in use.'.format(ctx.message.author))\n return\n\n # Does Game Name Exist?\n if is_game_name(game_name):\n await bot.say('{0.mention}, this game is already in the list.'.format(ctx.message.author))\n return\n\n # Handle Database\n try:\n sql = \"INSERT INTO games (`abv`,`name`) VALUES (%s, %s)\"\n cur = db.cursor()\n cur.execute(sql, (game_abv, game_name))\n db.commit()\n cur.close()\n except Exception as e:\n await bot.say('{0.mention}, there was an error adding the game to the games list. '.format(ctx.message.author)\n + str(e))\n return\n\n # Display Success Message\n await bot.say('{0.mention}, the game was successfully added to the games list!'.format(ctx.message.author))\n\n\n# COMMAND: !games edit\n@games.command(name='edit', pass_context=True)\nasync def games_edit(ctx, game_abv: str, *, game_name: str):\n \"\"\"Updates a game in the list of games available in the roster.\"\"\"\n\n # Is the user allowed? (Must be staff)\n if not is_staff(ctx.message.author):\n await bot.say('{0.mention}, you must be a staff member to use this command.'.format(ctx.message.author))\n return\n\n # Is there anything to update?\n if not (is_game_abv(game_abv) or is_game_name(game_name)):\n await bot.say('{0.mention}, either the abbreviation of game must exist to update.'.format(ctx.message.author))\n return\n\n # Handle Database\n try:\n sql = \"UPDATE games SET `abv` = %s, `name = %s WHERE `abv` = %s OR `name` = %s\"\n cur = db.cursor()\n cur.execute(sql, (game_abv, game_name, game_abv, game_name))\n db.commit()\n cur.close()\n except Exception as e:\n await bot.say('{0.mention}, there was an error updating the game in the games list. '.format(ctx.message.author)\n + str(e))\n return\n\n # Display Success Message\n await bot.say('{0.mention}, the game was successfully updated in the games list!'.format(ctx.message.author))\n\n\n# COMMAND: !games remove\n@games.command(name='remove', pass_context=True)\nasync def games_remove(ctx, *, game_or_abv: str):\n \"\"\"Removes a game from the list of games available in the roster.\"\"\"\n\n # Is the user allowed? (Must be staff)\n if not is_staff(ctx.message.author):\n await bot.say('{0.mention}, you must be a staff member to use this command.'.format(ctx.message.author))\n return\n\n # Is there anything to update?\n if not (is_game_abv(game_or_abv) or is_game_name(game_or_abv)):\n await bot.say('{0.mention}, either the abbreviation of game must exist to update.'.format(ctx.message.author))\n return\n\n # Handle Database\n try:\n sql = \"DELETE FROM games WHERE `abv` = %s OR `name` = %s\"\n cur = db.cursor()\n cur.execute(sql, (game_or_abv, game_or_abv))\n db.commit()\n cur.close()\n except Exception as e:\n await bot.say(\"{0.mention}, there was an error deleting the game from the games list.\"\n \" \".format(ctx.message.author) + str(e))\n return\n\n # Display Success Message\n await bot.say('{0.mention}, the game was successfully deleted from the games list!'.format(ctx.message.author))\n\n\n# COMMAND: !games list\n@games.command(name='list', pass_context=True)\nasync def games_list(ctx):\n \"\"\"Sends a message to the user with the current games and abbreviations for use in the roster.\"\"\"\n\n # Handle Database\n try:\n sql = \"SELECT `abv`, `name` FROM games ORDER BY `name`\"\n cur = db.cursor()\n cur.execute(sql)\n result = cur.fetchall()\n cur.close()\n except Exception:\n await bot.send_message(ctx.message.channel, \"{0.mention}, there was an error getting the list of games for you.\"\n \" I'm sorry!\".format(ctx.message.author))\n return\n\n # Create Variables for Embed Table\n abvs = ''\n names = ''\n\n for row in result:\n abvs += (row[0] + '\\n')\n names += (row[1] + '\\n')\n\n # Create Embed Table\n embed = discord.Embed()\n embed.add_field(name=\"Abbreviation\", value=abvs, inline=True)\n embed.add_field(name=\"Game Name\", value=names, inline=True)\n\n # Send Table to User Privately\n await bot.send_message(ctx.message.channel, embed=embed)\n\n\n# ********************************************** #\n# GROUPED COMMANDS : ROSTER ******************** #\n# ********************************************** #\n\n# COMMAND: !roster\n@bot.group(pass_context=True)\nasync def roster(ctx):\n \"\"\"Handles Roster Management.\"\"\"\n\n if ctx.invoked_subcommand is None:\n await bot.say('Invalid roster command passed. Must be *add*, *edit*, *list*, or *remove*.')\n\n\n# COMMAND: !roster add\n@roster.command(name='add', pass_context=True)\nasync def roster_add(ctx, game_abv: str, *, ign: str):\n \"\"\"Adds username to roster.\n User a game abbreviation from the games list. Only one entry per game. Include all in-game names if necessary.\"\"\"\n\n username = str(ctx.message.author)\n\n # Does Game Abbreviation Exist?\n if not is_game_abv(game_abv):\n await bot.say('{0.mention}, this abbreviation does not exist. Use !games display for a list of acceptable game '\n 'abbreviations.'.format(ctx.message.author))\n return\n\n # Handle Database\n try:\n sql = \"INSERT INTO roster (`discord_account`,`game_abv`,`game_account`) VALUES (%s, %s, %s)\"\n cur = db.cursor()\n cur.execute(sql, (username, game_abv, ign))\n db.commit()\n cur.close()\n except Exception:\n await bot.say('{0.message.author.mention}, there was an error adding your information to the roster.'.format(ctx))\n return\n\n # Display Success Message\n await bot.say('{0.message.author.mention}, your information was successfully added to the roster!'.format(ctx))\n\n\n# COMMAND: !roster edit\n@roster.command(name='edit', pass_context=True)\nasync def roster_edit(ctx, game_abv: str, *, ign: str):\n \"\"\"Updates a roster entry for a specific game.\n If the either Game Name or your in-Game Name have spaces, put them in quotes.\"\"\"\n\n username = str(ctx.message.author)\n\n # Does Game Abbreviation Exist?\n if not is_game_abv(game_abv):\n await bot.say('{0.mention}, this abbreviation does not exist. Use !games display for a list of acceptable game'\n ' abbreviations.'.format(ctx.message.author))\n return\n\n # Handle Database\n try:\n sql = \"UPDATE roster SET `game_account` = %s WHERE `discord_account` = %s AND `game_abv` = %s\"\n cur = db.cursor()\n cur.execute(sql, (ign, username, game_abv))\n db.commit()\n cur.close()\n except Exception:\n await bot.say('{0.message.author.mention}, there was an error updating your roster information.'.format(ctx))\n return\n\n # Display Success Message\n await bot.say('{0.message.author.mention}, your roster information was successfully updated!'.format(ctx))\n\n\n# COMMAND: !roster remove\n@roster.command(name='remove', pass_context=True)\nasync def roster_remove(ctx, game_abv: str, *, ign: str):\n \"\"\"Removes a user's entries in the roster for the specified game.\"\"\"\n\n username = str(ctx.message.author)\n\n # Does Game Abbreviation Exist?\n if not is_game_abv(game_abv):\n await bot.say('{0.mention}, this abbreviation does not exist. Use !games display for a list of acceptable '\n 'game abbreviations.'.format(ctx.message.author))\n return\n\n # Handle Database\n try:\n sql = \"DELETE FROM roster WHERE `discord_account` = %s AND `game_abv` = %s AND `game_account` = %s\"\n cur = db.cursor()\n cur.execute(sql, (username, game_abv, ign))\n db.commit()\n cur.close()\n except Exception:\n await bot.say('{0.message.author.mention}, there was an error deleting your roster information.'.format(ctx))\n return\n\n # Display Success Message\n await bot.say('{0.message.author.mention}, your roster information was successfully deleted!'.format(ctx))\n\n\n# COMMAND: !roster list\n@roster.command(name='list', pass_context=True)\nasync def roster_list(ctx, game_abv: str):\n \"\"\"Sends a message to the user with the current roster for the specified game.\"\"\"\n\n # Does Game Abbreviation Exist?\n if not is_game_abv(game_abv):\n await bot.say('{0.mention}, this abbreviation does not exist. Use !games display for a list of acceptable game '\n 'abbreviations.'.format(ctx.message.author))\n return\n\n # Handle Database\n try:\n sql = \"SELECT `discord_account`, `game_account` FROM roster WHERE `game_abv` = %s ORDER BY `discord_account`\"\n cur = db.cursor()\n cur.execute(sql, (game_abv,))\n result = cur.fetchall()\n cur.close()\n except Exception:\n await bot.send_message(ctx.message.channel, \"{0.mention}, there was an error getting the roster for you. \"\n \"I'm sorry!\".format(ctx.message.author))\n return\n\n # Create Variables for Embed Table\n accounts = ''\n names = ''\n\n for row in result:\n accounts += (row[0] + '\\n')\n names += (row[1] + '\\n')\n\n # Create Embed Table\n embed = discord.Embed()\n embed.add_field(name=\"Discord Account\", value=accounts, inline=True)\n embed.add_field(name=\"In-Game Name\", value=names, inline=True)\n\n # Send Table to Channel\n await bot.send_message(ctx.message.channel, embed=embed)\n\n\n# ********************************************** #\n# GROUPED COMMANDS : RECRUIT ******************* #\n# ********************************************** #\n\n# COMMAND: !recruit\n@bot.group(pass_context=True)\nasync def recruit(ctx):\n \"\"\"Handles Recruitment Post and Invites Management.\"\"\"\n\n if ctx.invoked_subcommand is None:\n await bot.say('Invalid recruitment command passed. Must be *add*, *edit*, *invite*, *list*, or *remove*.')\n\n\n# COMMAND: !recruit add\n@recruit.command(name='add', pass_context=True)\nasync def recruit_add(ctx, game_abv: str, *, link: str):\n \"\"\"Adds recruitment post link to the recruitment list. Use a game abbreviation from the games list.\"\"\"\n\n # Is the user allowed? (Must be staff)\n if not is_staff(ctx.message.author):\n await bot.say('{0.mention}, you must be a staff member to use this command.'.format(ctx.message.author))\n return\n\n # Does Game Abbreviation Exist?\n if not is_game_abv(game_abv):\n await bot.say(\n '{0.mention}, this abbreviation does not exist. Use !games display for a list of acceptable game '\n 'abbreviations.'.format(ctx.message.author))\n return\n\n # Handle Database\n try:\n sql = \"INSERT INTO recruitment (`game`,`link`) VALUES (%s, %s)\"\n cur = db.cursor()\n cur.execute(sql, (game_abv, link))\n db.commit()\n cur.close()\n except Exception:\n await bot.say(\n '{0.message.author.mention}, there was an error adding your recruitment link to the list.'.format(ctx))\n return\n\n # Display Success Message\n await bot.say('{0.message.author.mention}, your information was successfully added to the recruitment '\n 'posts list!'.format(ctx))\n\n\n# COMMAND: !recruit edit\n@recruit.command(name='edit', pass_context=True)\nasync def roster_edit(ctx, entry_id: int, *, link: str):\n \"\"\"Updates a recruitment post entry with the specified entry ID.\"\"\"\n\n # Is the user allowed? (Must be staff)\n if not is_staff(ctx.message.author):\n await bot.say('{0.mention}, you must be a staff member to use this command.'.format(ctx.message.author))\n return\n\n # Handle Database\n try:\n sql = \"UPDATE recruitment SET `link` = %s WHERE `entry_id` = %s\"\n cur = db.cursor()\n cur.execute(sql, (link, entry_id))\n db.commit()\n cur.close()\n except Exception:\n await bot.say('{0.message.author.mention}, there was an error updating the specified '\n 'recruitment entry.'.format(ctx))\n return\n\n # Display Success Message\n await bot.say('{0.message.author.mention}, the recruitment entry was successfully updated!'.format(ctx))\n\n\n# COMMAND: !recruit remove\n@recruit.command(name='remove', pass_context=True)\nasync def recruit_remove(ctx, entry_id: int):\n \"\"\"Removes an entry for the recruitment posts list with the specified entry ID.\"\"\"\n\n # Is the user allowed? (Must be staff)\n if not is_staff(ctx.message.author):\n await bot.say('{0.mention}, you must be a staff member to use this command.'.format(ctx.message.author))\n return\n\n # Handle Database\n try:\n sql = \"DELETE FROM recruitment WHERE `entry_id` = %s\"\n cur = db.cursor()\n cur.execute(sql, (entry_id,))\n db.commit()\n cur.close()\n except Exception:\n await bot.say('{0.message.author.mention}, there was an error deleting the specified '\n 'recruitment entry.'.format(ctx))\n return\n\n # Display Success Message\n await bot.say('{0.message.author.mention}, the recruitment entry was successfully deleted!'.format(ctx))\n\n\n# COMMAND: !recruit list\n@recruit.command(name='list', pass_context=True)\nasync def recruit_list(ctx):\n \"\"\"Lists all recruitment post entries in the system.\"\"\"\n\n # Handle Database\n try:\n sql = \"SELECT * FROM recruitment ORDER BY `game`\"\n cur = db.cursor()\n cur.execute(sql)\n result = cur.fetchall()\n cur.close()\n except Exception:\n await bot.send_message(ctx.message.channel, \"{0.mention}, there was an error getting the recruitment list \"\n \"for you. I'm sorry!\".format(ctx.message.author))\n return\n\n # Create Variables for Embed Table\n entries = ''\n game_abvs = ''\n links = ''\n\n for row in result:\n entries += (row[0] + '\\n')\n game_abvs += (row[1] + '\\n')\n links += (row[2] + '\\n')\n\n # Create Embed Table\n embed = discord.Embed()\n embed.add_field(name=\"ID\", value=entries, inline=True)\n embed.add_field(name=\"Game\", value=game_abvs, inline=True)\n embed.add_field(name=\"Link\", value=links, inline=True)\n\n # Send Table to Channel\n await bot.send_message(ctx.message.channel, embed=embed)\n\n\n# COMMAND: !recruit invite\n@recruit.command(name='invite')\nasync def recruit_invite(duration: int):\n \"\"\"Provides an invite link to the Discord server. Set duration to 0 for permanent invite.\"\"\"\n\n # Default Duration 30 Minutes, Else Convert to Minutes\n if duration is None:\n duration = 1800\n else:\n duration *= 60\n\n # WELCOME CHANNEL ID: 141622052133142529\n welcome_channel = bot.get_channel('141622052133142529')\n\n # Create the Invite\n new_invite = await bot.create_invite(welcome_channel, max_age=duration)\n\n # Send Message with Invite Link\n await bot.say('Your newly generated invite link is: {0.url}'.format(new_invite))\n\n\n# ********************************************** #\n# MODERATOR COMMANDS *************************** #\n# ********************************************** #\n\n# COMMAND: !give_role\n@bot.command(pass_context=True)\nasync def give_role(ctx, username: str, *, role_name: str):\n \"\"\"Assigns a role to a user.\"\"\"\n\n # List of Roles Staff Can Add To.\n allowed_roles = ['Europe',\n 'North America',\n 'Oceania',\n 'Overwatch',\n 'League of Legends',\n 'Co-op',\n 'Minna-chan',\n 'Squire',\n 'Knight',\n 'Zealot']\n\n # Is the user allowed? (Must be Staff)\n if not is_staff(ctx.message.author):\n await bot.say('{0.mention}, you must be a staff member to use this command.'.format(ctx.message.author))\n return\n\n if role_name not in allowed_roles:\n await bot.say('{0.mention}, you may only assign users to public roles, Guest, or Registered Member'\n .format(ctx.message.author))\n return\n\n # Define role, then add role to member.\n try:\n role = discord.utils.get(ctx.message.server.roles, name=role_name)\n user = discord.utils.get(ctx.message.server.members, name=username)\n await bot.add_roles(user, role)\n except Exception as e:\n await bot.send_message(ctx.message.channel, \"{0.mention}, there was an granting the role to the user.\"\n \" \".format(ctx.message.author) + str(e))\n return\n\n # Success Message\n await bot.say('{0.mention}, you have successfully added **{1}** to the group **{2}**'\n '.'.format(ctx.message.author, username, role_name))\n\n\n# COMMAND: !kick\n@bot.command(name='kick', pass_context=True)\nasync def mod_kick(ctx, username: str, *, reason: str):\n \"\"\"Kicks a user from the server.\"\"\"\n\n # User must be a staff member\n if not is_staff(ctx.message.author):\n await bot.say('{0.mention}, you must be a staff member to use this command.'.format(ctx.message.author))\n return\n\n # Add to DB and Post Message\n try:\n # Variables Needed\n member = discord.utils.get(ctx.message.server.members, name=username)\n staffer = ctx.message.author\n\n # Handle Database\n sql = \"INSERT INTO mod_log (`action`,`user`, `user_id`, `staff`, `staff_id`, reason) \" \\\n \"VALUES ('kick', %s, %s, %s, %s, %s)\"\n cur = db.cursor()\n cur.execute(sql, (str(member), member.id, str(staffer), staffer.id, reason))\n\n # Save Last Row ID\n case_id = cur.lastrowid\n\n # Insert Message\n log_channel = bot.get_channel('303262467205890051')\n msg_text = \"**Case #{0}** | Kick :boot: \\n**User**: {1} ({2}) \" \\\n \"\\n**Moderator**: {3} ({4}) \\n**Reason**: {5}\"\n\n # Add Message to Events Channel and Save Message ID\n case_message = await bot.send_message(log_channel, msg_text.format(case_id, str(member), member.id, str(staffer), staffer.id, reason))\n cur.execute(\"UPDATE mod_log SET `message_id` = %s WHERE `case_id` = %s\", (case_message.id, case_id))\n\n # Finish Database Stuff and Commit\n db.commit()\n cur.close()\n\n # Kick the Member\n await bot.kick(member)\n except Exception as e:\n await bot.send_message(ctx.message.channel, \"{0.mention}, there was an error when kicking the user.\"\n \" \".format(ctx.message.author) + str(e))\n\n await bot.say(\"{0.mention}, the user was successfully kicked. A log entry has been added.\".format(ctx.message.author))\n\n\n# ********************************************** #\n# START THE BOT ******************************** #\n# ********************************************** #\n\n\n# Run the Bot\nbot.run('token-here')\n"},"license":{"kind":"string","value":"gpl-3.0"},"hash":{"kind":"number","value":2852675339850913300,"string":"2,852,675,339,850,913,300"},"line_mean":{"kind":"number","value":33.8665183537,"string":"33.866518"},"line_max":{"kind":"number","value":142,"string":"142"},"alpha_frac":{"kind":"number","value":0.5875897272,"string":"0.58759"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.7169453338076606,"string":"3.716945"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45122,"cells":{"repo_name":{"kind":"string","value":"nicain/dipde_dev"},"path":{"kind":"string","value":"dipde/interfaces/zmq/__init__.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"4371"},"content":{"kind":"string","value":"import time\nimport zmq\nimport threading\n\ncontext = zmq.Context()\n\nclass PublishCallback(object):\n \n def __init__(self, port, topic, message_callback):\n \n self.port = port\n self.topic = topic\n self.message_callback = message_callback \n self.socket = context.socket(zmq.PUB)\n \n def __call__(self, obj):\n message_to_send = list(self.message_callback(obj))\n message_to_send.insert(0,\"%s\" % self.topic)\n self.socket.send_multipart(map(str, message_to_send))\n \nclass PublishCallbackConnect(PublishCallback):\n \n def __init__(self, port, topic, message_callback):\n super(self.__class__, self).__init__(port, topic, message_callback)\n self.socket.connect(\"tcp://localhost:%s\" % self.port)\n\n \nclass CallbackSubscriber(object): \n \n def __init__(self, port=None, receive_callback=None):\n\n self.socket = context.socket(zmq.SUB)\n if port is None:\n self.port = self.socket.bind_to_random_port('tcp://*', min_port=6001, max_port=6004, max_tries=100)\n\n else:\n self.socket.bind(\"tcp://*:%s\" % port)\n self.port = port\n\n self.socket.setsockopt(zmq.SUBSCRIBE, 'test')\n \n if receive_callback is None:\n def receive_callback(received_message):\n print received_message\n self.receive_callback = receive_callback \n\n def run(self): \n while True: \n received_message_multipart = self.socket.recv_multipart() \n topic = received_message_multipart[0]\n received_message = received_message_multipart[1:]\n self.receive_callback(received_message)\n\nclass CallbackSubscriberThread(threading.Thread): \n def __init__(self, port=None):\n super(self.__class__, self).__init__()\n self.subscriber = CallbackSubscriber(port)\n self.daemon = True\n\n def run(self, port=None):\n\n self.subscriber.run()\n\n @property\n def port(self):\n return self.subscriber.port\n\n\nclass RequestConnection(object):\n \n def __init__(self, port):\n \n self.port = port \n self.socket = context.socket(zmq.REQ)\n self.socket.connect(\"tcp://localhost:%s\" % port)\n \n def __call__(self, *args):\n if len(args) == 0:\n self.socket.send(b'')\n else:\n self.socket.send_multipart(map(str,args))\n message = self.socket.recv_multipart()\n return float(message[0])\n\n def shutdown(self):\n self.socket.close()\n assert self.socket.closed\n \nclass ReplyServerBind(object):\n \n def __init__(self, reply_function, port=None):\n\n self.socket = context.socket(zmq.REP)\n if port is None:\n self.port = self.socket.bind_to_random_port('tcp://*', min_port=6001, max_port=6004, max_tries=100)\n\n else:\n self.socket.bind(\"tcp://*:%s\" % port)\n self.port = port\n\n self.reply_function = reply_function\n\n def run(self):\n \n while True:\n message = self.socket.recv()\n # print 'message:', message, type(message)\n if message == 'SHUTDOWN':\n break\n # print 'message'\n if message == '':\n requested_args = tuple()\n else:\n requested_args = tuple([float(message)])\n self.socket.send_multipart([b\"%s\" % self.reply_function(*requested_args)])\n self.socket.send('DOWN')\n self.socket.close()\n\nclass ReplyServerThread(threading.Thread):\n\n def __init__(self, reply_function, port=None):\n super(ReplyServerThread, self).__init__()\n self._stop = threading.Event()\n self.daemon = True\n self.reply_function = reply_function\n self.server = ReplyServerBind(self.reply_function, port=port)\n\n\n def run(self, port=None):\n self.server.run()\n\n def shutdown(self):\n shutdown_socket = context.socket(zmq.REQ)\n shutdown_socket.connect(\"tcp://localhost:%s\" % self.port)\n shutdown_socket.send('SHUTDOWN')\n message = shutdown_socket.recv()\n assert message == 'DOWN'\n self.stop()\n\n def stop(self):\n self._stop.set()\n\n def stopped(self):\n return self._stop.isSet()\n\n @property\n def port(self):\n return self.server.port\n\n\n\n"},"license":{"kind":"string","value":"gpl-3.0"},"hash":{"kind":"number","value":-8901712531665347000,"string":"-8,901,712,531,665,347,000"},"line_mean":{"kind":"number","value":27.9470198675,"string":"27.94702"},"line_max":{"kind":"number","value":111,"string":"111"},"alpha_frac":{"kind":"number","value":0.5774422329,"string":"0.577442"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":4.0285714285714285,"string":"4.028571"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45123,"cells":{"repo_name":{"kind":"string","value":"yantrabuddhi/nativeclient"},"path":{"kind":"string","value":"buildbot/buildbot_lib.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"21952"},"content":{"kind":"string","value":"#!/usr/bin/python\n# Copyright (c) 2012 The Native Client Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\nimport optparse\nimport os.path\nimport shutil\nimport subprocess\nimport stat\nimport sys\nimport time\nimport traceback\n\n\nARCH_MAP = {\n '32': {\n 'gyp_arch': 'ia32',\n 'scons_platform': 'x86-32',\n },\n '64': {\n 'gyp_arch': 'x64',\n 'scons_platform': 'x86-64',\n },\n 'arm': {\n 'gyp_arch': 'arm',\n 'scons_platform': 'arm',\n },\n 'mips32': {\n 'gyp_arch': 'mips32',\n 'scons_platform': 'mips32',\n },\n }\n\n\ndef RunningOnBuildbot():\n return os.environ.get('BUILDBOT_SLAVE_TYPE') is not None\n\n\ndef GetHostPlatform():\n sys_platform = sys.platform.lower()\n if sys_platform.startswith('linux'):\n return 'linux'\n elif sys_platform in ('win', 'win32', 'windows', 'cygwin'):\n return 'win'\n elif sys_platform in ('darwin', 'mac'):\n return 'mac'\n else:\n raise Exception('Can not determine the platform!')\n\n\ndef SetDefaultContextAttributes(context):\n \"\"\"\n Set default values for the attributes needed by the SCons function, so that\n SCons can be run without needing ParseStandardCommandLine\n \"\"\"\n platform = GetHostPlatform()\n context['platform'] = platform\n context['mode'] = 'opt'\n context['default_scons_mode'] = ['opt-host', 'nacl']\n context['default_scons_platform'] = ('x86-64' if platform == 'win'\n else 'x86-32')\n context['android'] = False\n context['clang'] = False\n context['asan'] = False\n context['pnacl'] = False\n context['use_glibc'] = False\n context['use_breakpad_tools'] = False\n context['max_jobs'] = 8\n context['scons_args'] = []\n\n\n# Windows-specific environment manipulation\ndef SetupWindowsEnvironment(context):\n # Poke around looking for MSVC. We should do something more principled in\n # the future.\n\n # The name of Program Files can differ, depending on the bittage of Windows.\n program_files = r'c:\\Program Files (x86)'\n if not os.path.exists(program_files):\n program_files = r'c:\\Program Files'\n if not os.path.exists(program_files):\n raise Exception('Cannot find the Program Files directory!')\n\n # The location of MSVC can differ depending on the version.\n msvc_locs = [\n ('Microsoft Visual Studio 12.0', 'VS120COMNTOOLS', '2013'),\n ('Microsoft Visual Studio 10.0', 'VS100COMNTOOLS', '2010'),\n ('Microsoft Visual Studio 9.0', 'VS90COMNTOOLS', '2008'),\n ('Microsoft Visual Studio 8.0', 'VS80COMNTOOLS', '2005'),\n ]\n\n for dirname, comntools_var, gyp_msvs_version in msvc_locs:\n msvc = os.path.join(program_files, dirname)\n context.SetEnv('GYP_MSVS_VERSION', gyp_msvs_version)\n if os.path.exists(msvc):\n break\n else:\n # The break statement did not execute.\n raise Exception('Cannot find MSVC!')\n\n # Put MSVC in the path.\n vc = os.path.join(msvc, 'VC')\n comntools = os.path.join(msvc, 'Common7', 'Tools')\n perf = os.path.join(msvc, 'Team Tools', 'Performance Tools')\n context.SetEnv('PATH', os.pathsep.join([\n context.GetEnv('PATH'),\n vc,\n comntools,\n perf]))\n\n # SCons needs this variable to find vsvars.bat.\n # The end slash is needed because the batch files expect it.\n context.SetEnv(comntools_var, comntools + '\\\\')\n\n # This environment variable will SCons to print debug info while it searches\n # for MSVC.\n context.SetEnv('SCONS_MSCOMMON_DEBUG', '-')\n\n # Needed for finding devenv.\n context['msvc'] = msvc\n\n SetupGyp(context, [])\n\n\ndef SetupGyp(context, extra_vars=[]):\n if RunningOnBuildbot():\n goma_opts = [\n 'use_goma=1',\n 'gomadir=/b/build/goma',\n ]\n else:\n goma_opts = []\n context.SetEnv('GYP_DEFINES', ' '.join(\n context['gyp_vars'] + goma_opts + extra_vars))\n\n\ndef SetupLinuxEnvironment(context):\n if context['arch'] == 'mips32':\n # Ensure the trusted mips toolchain is installed.\n cmd = ['build/package_version/package_version.py', '--packages',\n 'linux_x86/mips_trusted', 'sync', '-x']\n Command(context, cmd)\n\n SetupGyp(context, ['target_arch='+context['gyp_arch']])\n\n\ndef SetupMacEnvironment(context):\n SetupGyp(context, ['target_arch='+context['gyp_arch']])\n\n\ndef SetupAndroidEnvironment(context):\n SetupGyp(context, ['OS=android', 'target_arch='+context['gyp_arch']])\n context.SetEnv('GYP_CROSSCOMPILE', '1')\n\n\ndef ParseStandardCommandLine(context):\n \"\"\"\n The standard buildbot scripts require 3 arguments to run. The first\n argument (dbg/opt) controls if the build is a debug or a release build. The\n second argument (32/64) controls the machine architecture being targeted.\n The third argument (newlib/glibc) controls which c library we're using for\n the nexes. Different buildbots may have different sets of arguments.\n \"\"\"\n\n parser = optparse.OptionParser()\n parser.add_option('-n', '--dry-run', dest='dry_run', default=False,\n action='store_true', help='Do not execute any commands.')\n parser.add_option('--inside-toolchain', dest='inside_toolchain',\n default=bool(os.environ.get('INSIDE_TOOLCHAIN')),\n action='store_true', help='Inside toolchain build.')\n parser.add_option('--android', dest='android', default=False,\n action='store_true', help='Build for Android.')\n parser.add_option('--clang', dest='clang', default=False,\n action='store_true', help='Build trusted code with Clang.')\n parser.add_option('--coverage', dest='coverage', default=False,\n action='store_true',\n help='Build and test for code coverage.')\n parser.add_option('--validator', dest='validator', default=False,\n action='store_true',\n help='Only run validator regression test')\n parser.add_option('--asan', dest='asan', default=False,\n action='store_true', help='Build trusted code with ASan.')\n parser.add_option('--scons-args', dest='scons_args', default =[],\n action='append', help='Extra scons arguments.')\n parser.add_option('--step-suffix', metavar='SUFFIX', default='',\n help='Append SUFFIX to buildbot step names.')\n parser.add_option('--no-gyp', dest='no_gyp', default=False,\n action='store_true', help='Do not run the gyp build')\n parser.add_option('--no-goma', dest='no_goma', default=False,\n action='store_true', help='Do not run with goma')\n parser.add_option('--use-breakpad-tools', dest='use_breakpad_tools',\n default=False, action='store_true',\n help='Use breakpad tools for testing')\n parser.add_option('--skip-build', dest='skip_build', default=False,\n action='store_true',\n help='Skip building steps in buildbot_pnacl')\n parser.add_option('--skip-run', dest='skip_run', default=False,\n action='store_true',\n help='Skip test-running steps in buildbot_pnacl')\n\n options, args = parser.parse_args()\n\n if len(args) != 3:\n parser.error('Expected 3 arguments: mode arch toolchain')\n\n # script + 3 args == 4\n mode, arch, toolchain = args\n if mode not in ('dbg', 'opt', 'coverage'):\n parser.error('Invalid mode %r' % mode)\n\n if arch not in ARCH_MAP:\n parser.error('Invalid arch %r' % arch)\n\n if toolchain not in ('newlib', 'glibc', 'pnacl', 'nacl_clang'):\n parser.error('Invalid toolchain %r' % toolchain)\n\n # TODO(ncbray) allow a command-line override\n platform = GetHostPlatform()\n\n context['platform'] = platform\n context['mode'] = mode\n context['arch'] = arch\n context['android'] = options.android\n # ASan is Clang, so set the flag to simplify other checks.\n context['clang'] = options.clang or options.asan\n context['validator'] = options.validator\n context['asan'] = options.asan\n # TODO(ncbray) turn derived values into methods.\n context['gyp_mode'] = {\n 'opt': 'Release',\n 'dbg': 'Debug',\n 'coverage': 'Debug'}[mode]\n context['gn_is_debug'] = {\n 'opt': 'false',\n 'dbg': 'true',\n 'coverage': 'true'}[mode]\n context['gyp_arch'] = ARCH_MAP[arch]['gyp_arch']\n context['gyp_vars'] = []\n if context['clang']:\n context['gyp_vars'].append('clang=1')\n if context['asan']:\n context['gyp_vars'].append('asan=1')\n context['default_scons_platform'] = ARCH_MAP[arch]['scons_platform']\n context['default_scons_mode'] = ['nacl']\n # Only Linux can build trusted code on ARM.\n # TODO(mcgrathr): clean this up somehow\n if arch != 'arm' or platform == 'linux':\n context['default_scons_mode'] += [mode + '-host']\n context['use_glibc'] = toolchain == 'glibc'\n context['pnacl'] = toolchain == 'pnacl'\n context['nacl_clang'] = toolchain == 'nacl_clang'\n context['max_jobs'] = 8\n context['dry_run'] = options.dry_run\n context['inside_toolchain'] = options.inside_toolchain\n context['step_suffix'] = options.step_suffix\n context['no_gyp'] = options.no_gyp\n context['no_goma'] = options.no_goma\n context['coverage'] = options.coverage\n context['use_breakpad_tools'] = options.use_breakpad_tools\n context['scons_args'] = options.scons_args\n context['skip_build'] = options.skip_build\n context['skip_run'] = options.skip_run\n # Don't run gyp on coverage builds.\n if context['coverage']:\n context['no_gyp'] = True\n\n for key, value in sorted(context.config.items()):\n print '%s=%s' % (key, value)\n\n\ndef EnsureDirectoryExists(path):\n \"\"\"\n Create a directory if it does not already exist.\n Does not mask failures, but there really shouldn't be any.\n \"\"\"\n if not os.path.exists(path):\n os.makedirs(path)\n\n\ndef TryToCleanContents(path, file_name_filter=lambda fn: True):\n \"\"\"\n Remove the contents of a directory without touching the directory itself.\n Ignores all failures.\n \"\"\"\n if os.path.exists(path):\n for fn in os.listdir(path):\n TryToCleanPath(os.path.join(path, fn), file_name_filter)\n\n\ndef TryToCleanPath(path, file_name_filter=lambda fn: True):\n \"\"\"\n Removes a file or directory.\n Ignores all failures.\n \"\"\"\n if os.path.exists(path):\n if file_name_filter(path):\n print 'Trying to remove %s' % path\n try:\n RemovePath(path)\n except Exception:\n print 'Failed to remove %s' % path\n else:\n print 'Skipping %s' % path\n\n\ndef Retry(op, *args):\n # Windows seems to be prone to having commands that delete files or\n # directories fail. We currently do not have a complete understanding why,\n # and as a workaround we simply retry the command a few times.\n # It appears that file locks are hanging around longer than they should. This\n # may be a secondary effect of processes hanging around longer than they\n # should. This may be because when we kill a browser sel_ldr does not exit\n # immediately, etc.\n # Virus checkers can also accidently prevent files from being deleted, but\n # that shouldn't be a problem on the bots.\n if GetHostPlatform() == 'win':\n count = 0\n while True:\n try:\n op(*args)\n break\n except Exception:\n print \"FAILED: %s %s\" % (op.__name__, repr(args))\n count += 1\n if count < 5:\n print \"RETRY: %s %s\" % (op.__name__, repr(args))\n time.sleep(pow(2, count))\n else:\n # Don't mask the exception.\n raise\n else:\n op(*args)\n\n\ndef PermissionsFixOnError(func, path, exc_info):\n if not os.access(path, os.W_OK):\n os.chmod(path, stat.S_IWUSR)\n func(path)\n else:\n raise\n\n\ndef _RemoveDirectory(path):\n print 'Removing %s' % path\n if os.path.exists(path):\n shutil.rmtree(path, onerror=PermissionsFixOnError)\n print ' Succeeded.'\n else:\n print ' Path does not exist, nothing to do.'\n\n\ndef RemoveDirectory(path):\n \"\"\"\n Remove a directory if it exists.\n Does not mask failures, although it does retry a few times on Windows.\n \"\"\"\n Retry(_RemoveDirectory, path)\n\n\ndef RemovePath(path):\n \"\"\"Remove a path, file or directory.\"\"\"\n if os.path.isdir(path):\n RemoveDirectory(path)\n else:\n if os.path.isfile(path) and not os.access(path, os.W_OK):\n os.chmod(path, stat.S_IWUSR)\n os.remove(path)\n\n\n# This is a sanity check so Command can print out better error information.\ndef FileCanBeFound(name, paths):\n # CWD\n if os.path.exists(name):\n return True\n # Paths with directories are not resolved using the PATH variable.\n if os.path.dirname(name):\n return False\n # In path\n for path in paths.split(os.pathsep):\n full = os.path.join(path, name)\n if os.path.exists(full):\n return True\n return False\n\n\ndef RemoveGypBuildDirectories():\n # Remove all directories on all platforms. Overkill, but it allows for\n # straight-line code.\n # Windows\n RemoveDirectory('build/Debug')\n RemoveDirectory('build/Release')\n RemoveDirectory('build/Debug-Win32')\n RemoveDirectory('build/Release-Win32')\n RemoveDirectory('build/Debug-x64')\n RemoveDirectory('build/Release-x64')\n\n # Linux and Mac\n RemoveDirectory('../xcodebuild')\n RemoveDirectory('../out')\n RemoveDirectory('src/third_party/nacl_sdk/arm-newlib')\n\n\ndef RemoveSconsBuildDirectories():\n RemoveDirectory('scons-out')\n RemoveDirectory('breakpad-out')\n\n\n# Execute a command using Python's subprocess module.\ndef Command(context, cmd, cwd=None):\n print 'Running command: %s' % ' '.join(cmd)\n\n # Python's subprocess has a quirk. A subprocess can execute with an\n # arbitrary, user-defined environment. The first argument of the command,\n # however, is located using the PATH variable of the Python script that is\n # launching the subprocess. Modifying the PATH in the environment passed to\n # the subprocess does not affect Python's search for the first argument of\n # the command (the executable file.) This is a little counter intuitive,\n # so we're forcing the search to use the same PATH variable as is seen by\n # the subprocess.\n env = context.MakeCommandEnv()\n script_path = os.environ['PATH']\n os.environ['PATH'] = env['PATH']\n\n try:\n if FileCanBeFound(cmd[0], env['PATH']) or context['dry_run']:\n # Make sure that print statements before the subprocess call have been\n # flushed, otherwise the output of the subprocess call may appear before\n # the print statements.\n sys.stdout.flush()\n if context['dry_run']:\n retcode = 0\n else:\n retcode = subprocess.call(cmd, cwd=cwd, env=env)\n else:\n # Provide a nicer failure message.\n # If subprocess cannot find the executable, it will throw a cryptic\n # exception.\n print 'Executable %r cannot be found.' % cmd[0]\n retcode = 1\n finally:\n os.environ['PATH'] = script_path\n\n print 'Command return code: %d' % retcode\n if retcode != 0:\n raise StepFailed()\n return retcode\n\n\n# A specialized version of CommandStep.\ndef SCons(context, mode=None, platform=None, parallel=False, browser_test=False,\n args=(), cwd=None):\n python = sys.executable\n if mode is None: mode = context['default_scons_mode']\n if platform is None: platform = context['default_scons_platform']\n if parallel:\n jobs = context['max_jobs']\n else:\n jobs = 1\n cmd = []\n if browser_test and context.Linux():\n # Although we could use the \"browser_headless=1\" Scons option, it runs\n # xvfb-run once per Chromium invocation. This is good for isolating\n # the tests, but xvfb-run has a stupid fixed-period sleep, which would\n # slow down the tests unnecessarily.\n cmd.extend(['xvfb-run', '--auto-servernum'])\n cmd.extend([\n python, 'scons.py',\n '--verbose',\n '-k',\n '-j%d' % jobs,\n '--mode='+','.join(mode),\n 'platform='+platform,\n ])\n cmd.extend(context['scons_args'])\n if context['clang']: cmd.append('--clang')\n if context['asan']: cmd.append('--asan')\n if context['use_glibc']: cmd.append('--nacl_glibc')\n if context['pnacl']: cmd.append('bitcode=1')\n if context['nacl_clang']: cmd.append('nacl_clang=1')\n if context['use_breakpad_tools']:\n cmd.append('breakpad_tools_dir=breakpad-out')\n if context['android']:\n cmd.append('android=1')\n # Append used-specified arguments.\n cmd.extend(args)\n Command(context, cmd, cwd)\n\n\nclass StepFailed(Exception):\n \"\"\"\n Thrown when the step has failed.\n \"\"\"\n\n\nclass StopBuild(Exception):\n \"\"\"\n Thrown when the entire build should stop. This does not indicate a failure,\n in of itself.\n \"\"\"\n\n\nclass Step(object):\n \"\"\"\n This class is used in conjunction with a Python \"with\" statement to ensure\n that the preamble and postamble of each build step gets printed and failures\n get logged. This class also ensures that exceptions thrown inside a \"with\"\n statement don't take down the entire build.\n \"\"\"\n\n def __init__(self, name, status, halt_on_fail=True):\n self.status = status\n\n if 'step_suffix' in status.context:\n suffix = status.context['step_suffix']\n else:\n suffix = ''\n self.name = name + suffix\n self.halt_on_fail = halt_on_fail\n self.step_failed = False\n\n # Called on entry to a 'with' block.\n def __enter__(self):\n sys.stdout.flush()\n print\n print '@@@BUILD_STEP %s@@@' % self.name\n self.status.ReportBegin(self.name)\n\n # The method is called on exit from a 'with' block - even for non-local\n # control flow, i.e. exceptions, breaks, continues, returns, etc.\n # If an exception is thrown inside a block wrapped with a 'with' statement,\n # the __exit__ handler can suppress the exception by returning True. This is\n # used to isolate each step in the build - if an exception occurs in a given\n # step, the step is treated as a failure. This allows the postamble for each\n # step to be printed and also allows the build to continue of the failure of\n # a given step doesn't halt the build.\n def __exit__(self, type, exception, trace):\n sys.stdout.flush()\n if exception is None:\n # If exception is None, no exception occurred.\n step_failed = False\n elif isinstance(exception, StepFailed):\n step_failed = True\n print\n print 'Halting build step because of failure.'\n print\n else:\n step_failed = True\n print\n print 'The build step threw an exception...'\n print\n traceback.print_exception(type, exception, trace, file=sys.stdout)\n print\n\n if step_failed:\n self.status.ReportFail(self.name)\n print '@@@STEP_FAILURE@@@'\n if self.halt_on_fail:\n print\n print 'Entire build halted because %s failed.' % self.name\n sys.stdout.flush()\n raise StopBuild()\n else:\n self.status.ReportPass(self.name)\n\n sys.stdout.flush()\n # Suppress any exception that occurred.\n return True\n\n\n# Adds an arbitrary link inside the build stage on the waterfall.\ndef StepLink(text, link):\n print '@@@STEP_LINK@%s@%s@@@' % (text, link)\n\n\n# Adds arbitrary text inside the build stage on the waterfall.\ndef StepText(text):\n print '@@@STEP_TEXT@%s@@@' % (text)\n\n\nclass BuildStatus(object):\n \"\"\"\n Keeps track of the overall status of the build.\n \"\"\"\n\n def __init__(self, context):\n self.context = context\n self.ever_failed = False\n self.steps = []\n\n def ReportBegin(self, name):\n pass\n\n def ReportPass(self, name):\n self.steps.append((name, 'passed'))\n\n def ReportFail(self, name):\n self.steps.append((name, 'failed'))\n self.ever_failed = True\n\n # Handy info when this script is run outside of the buildbot.\n def DisplayBuildStatus(self):\n print\n for step, status in self.steps:\n print '%-40s[%s]' % (step, status)\n print\n\n if self.ever_failed:\n print 'Build failed.'\n else:\n print 'Build succeeded.'\n\n def ReturnValue(self):\n return int(self.ever_failed)\n\n\nclass BuildContext(object):\n \"\"\"\n Encapsulates the information needed for running a build command. This\n includes environment variables and default arguments for SCons invocations.\n \"\"\"\n\n # Only allow these attributes on objects of this type.\n __slots__ = ['status', 'global_env', 'config']\n\n def __init__(self):\n # The contents of global_env override os.environ for any commands run via\n # self.Command(...)\n self.global_env = {}\n # PATH is a special case. See: Command.\n self.global_env['PATH'] = os.environ.get('PATH', '')\n\n self.config = {}\n self['dry_run'] = False\n\n # Emulate dictionary subscripting.\n def __getitem__(self, key):\n return self.config[key]\n\n # Emulate dictionary subscripting.\n def __setitem__(self, key, value):\n self.config[key] = value\n\n # Emulate dictionary membership test\n def __contains__(self, key):\n return key in self.config\n\n def Windows(self):\n return self.config['platform'] == 'win'\n\n def Linux(self):\n return self.config['platform'] == 'linux'\n\n def Mac(self):\n return self.config['platform'] == 'mac'\n\n def GetEnv(self, name, default=None):\n return self.global_env.get(name, default)\n\n def SetEnv(self, name, value):\n self.global_env[name] = str(value)\n\n def MakeCommandEnv(self):\n # The external environment is not sanitized.\n e = dict(os.environ)\n # Arbitrary variables can be overridden.\n e.update(self.global_env)\n return e\n\n\ndef RunBuild(script, status):\n try:\n script(status, status.context)\n except StopBuild:\n pass\n\n # Emit a summary step for three reasons:\n # - The annotator will attribute non-zero exit status to the last build step.\n # This can misattribute failures to the last build step.\n # - runtest.py wraps the builds to scrape perf data. It emits an annotator\n # tag on exit which misattributes perf results to the last build step.\n # - Provide a label step in which to show summary result.\n # Otherwise these go back to the preamble.\n with Step('summary', status):\n if status.ever_failed:\n print 'There were failed stages.'\n else:\n print 'Success.'\n # Display a summary of the build.\n status.DisplayBuildStatus()\n\n sys.exit(status.ReturnValue())\n"},"license":{"kind":"string","value":"bsd-3-clause"},"hash":{"kind":"number","value":-6223911041280375000,"string":"-6,223,911,041,280,375,000"},"line_mean":{"kind":"number","value":30.7225433526,"string":"30.722543"},"line_max":{"kind":"number","value":80,"string":"80"},"alpha_frac":{"kind":"number","value":0.6542456268,"string":"0.654246"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.708108108108108,"string":"3.708108"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45124,"cells":{"repo_name":{"kind":"string","value":"tjcsl/director"},"path":{"kind":"string","value":"web3/apps/sites/migrations/0001_initial.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"1297"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\n# Generated by Django 1.10.3 on 2016-11-05 23:20\nfrom __future__ import unicode_literals\n\nimport django.core.validators\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ('users', '0002_auto_20161105_2046'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Website',\n fields=[\n ('id', models.PositiveIntegerField(primary_key=True, serialize=False, validators=[django.core.validators.MinValueValidator(1000)])),\n ('name', models.CharField(max_length=32, unique=True)),\n ('category', models.CharField(choices=[('legacy', 'legacy'), ('static', 'static'), ('php', 'php'), ('dynamic', 'dynamic')], max_length=16)),\n ('purpose', models.CharField(choices=[('user', 'user'), ('activity', 'activity')], max_length=16)),\n ('domain', models.TextField()),\n ('description', models.TextField()),\n ('group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='users.Group')),\n ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='users.User')),\n ],\n ),\n ]\n"},"license":{"kind":"string","value":"mit"},"hash":{"kind":"number","value":-8739404138227232000,"string":"-8,739,404,138,227,232,000"},"line_mean":{"kind":"number","value":39.53125,"string":"39.53125"},"line_max":{"kind":"number","value":156,"string":"156"},"alpha_frac":{"kind":"number","value":0.5967617579,"string":"0.596762"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":4.183870967741935,"string":"4.183871"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45125,"cells":{"repo_name":{"kind":"string","value":"TAMU-CPT/galaxy-tools"},"path":{"kind":"string","value":"tools/gff3/gff3_filter.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"1553"},"content":{"kind":"string","value":"#!/usr/bin/env python\nimport sys\nimport logging\nimport argparse\nfrom cpt_gffParser import gffParse, gffWrite\nfrom gff3 import feature_lambda, feature_test_qual_value\n\nlogging.basicConfig(level=logging.INFO)\nlog = logging.getLogger(__name__)\n\n\ndef gff_filter(gff3, id_list=None, id=\"\", attribute_field=\"ID\", subfeatures=True):\n attribute_field = attribute_field.split(\"__cn__\")\n if id_list:\n filter_strings = [line.strip() for line in id_list]\n else:\n filter_strings = [x.strip() for x in id.split(\"__cn__\")]\n for rec in gffParse(gff3):\n rec.features = feature_lambda(\n rec.features,\n feature_test_qual_value,\n {\"qualifier\": attribute_field, \"attribute_list\": filter_strings},\n subfeatures=subfeatures,\n )\n rec.annotations = {}\n gffWrite([rec], sys.stdout)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description=\"extract features from a GFF3 file based on ID/qualifiers\"\n )\n parser.add_argument(\"gff3\", type=argparse.FileType(\"r\"), help=\"GFF3 annotations\")\n parser.add_argument(\"--id_list\", type=argparse.FileType(\"r\"))\n parser.add_argument(\"--id\", type=str)\n parser.add_argument(\n \"--attribute_field\",\n type=str,\n help=\"Column 9 Field to search against\",\n default=\"ID\",\n )\n parser.add_argument(\n \"--subfeatures\",\n action=\"store_true\",\n help=\"Retain subfeature tree of matched features\",\n )\n args = parser.parse_args()\n gff_filter(**vars(args))\n"},"license":{"kind":"string","value":"gpl-3.0"},"hash":{"kind":"number","value":2550448760510067700,"string":"2,550,448,760,510,067,700"},"line_mean":{"kind":"number","value":31.3541666667,"string":"31.354167"},"line_max":{"kind":"number","value":85,"string":"85"},"alpha_frac":{"kind":"number","value":0.6278171281,"string":"0.627817"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.688836104513064,"string":"3.688836"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45126,"cells":{"repo_name":{"kind":"string","value":"greggian/TapdIn"},"path":{"kind":"string","value":"django/contrib/localflavor/us/models.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"1132"},"content":{"kind":"string","value":"from django.conf import settings\r\nfrom django.db.models.fields import Field\r\n\r\nclass USStateField(Field): \r\n def get_internal_type(self): \r\n return \"USStateField\" \r\n \r\n def db_type(self):\r\n if settings.DATABASE_ENGINE == 'oracle':\r\n return 'CHAR(2)'\r\n else:\r\n return 'varchar(2)'\r\n \r\n def formfield(self, **kwargs): \r\n from django.contrib.localflavor.us.forms import USStateSelect \r\n defaults = {'widget': USStateSelect} \r\n defaults.update(kwargs) \r\n return super(USStateField, self).formfield(**defaults)\r\n\r\nclass PhoneNumberField(Field):\r\n def get_internal_type(self):\r\n return \"PhoneNumberField\"\r\n\r\n def db_type(self):\r\n if settings.DATABASE_ENGINE == 'oracle':\r\n return 'VARCHAR2(20)'\r\n else:\r\n return 'varchar(20)'\r\n\r\n def formfield(self, **kwargs):\r\n from django.contrib.localflavor.us.forms import USPhoneNumberField\r\n defaults = {'form_class': USPhoneNumberField}\r\n defaults.update(kwargs)\r\n return super(PhoneNumberField, self).formfield(**defaults)\r\n\r\n"},"license":{"kind":"string","value":"apache-2.0"},"hash":{"kind":"number","value":2579539055631886000,"string":"2,579,539,055,631,886,000"},"line_mean":{"kind":"number","value":30.3428571429,"string":"30.342857"},"line_max":{"kind":"number","value":74,"string":"74"},"alpha_frac":{"kind":"number","value":0.6148409894,"string":"0.614841"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":4.337164750957855,"string":"4.337165"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45127,"cells":{"repo_name":{"kind":"string","value":"seraphlnWu/in_trip"},"path":{"kind":"string","value":"in_trip/scripts/change_data_from_hbase_to_pg.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"1620"},"content":{"kind":"string","value":"#coding=utf-8\nimport time\nimport cPickle\n\nfrom in_trip.store_data.views import pg_db,conn\n\nimport logging\nlogger = logging.getLogger('parser')\n\ndef creat_table():\n sql_str = '''\n create table \"tmp_hbase_to_pg\"( \n data text,\n timestamp float(24)\n )\n '''\n pg_db.execute(sql_str)\n conn.commit()\n\ndef insert_data(o_dict, default_value):\n data =cPickle.dumps({\n 'o_dict' : o_dict,\n 'default_value' : default_value\n })\n sql_str = '''\n insert into tmp_hbase_to_pg\n (data,timestamp) \n values\n (%s,%s);\n '''\n try:\n pg_db.execute(sql_str,(data,time.time()))\n conn.commit()\n except Exception as e:\n conn.rollback()\n logger.error('insert to pg error: %s', e)\n\n\ndef get_data_all():\n sql_str = '''\n select * from tmp_hbase_to_pg;\n '''\n pg_db.execute(sql_str)\n print pg_db.fetchall()\n\ndef get_data(offset,limit=1000):\n sql_str = '''\n select * from tmp_hbase_to_pg limit(%s) offset(%s);\n '''\n pg_db.execute(sql_str,(limit,offset))\n return pg_db.fetchall()\n\ndef insert_into_hbase():\n from in_trip.store_data.hbase.run import insert_data as hbase_insert\n offset = 0\n limit = 1000\n while True:\n res_list = get_data(offset,limit)\n if not res_list:\n break\n offset = offset + limit\n for item in res_list:\n tmp_data = cPickle.loads(item[0])\n hbase_insert(tmp_data['o_dict'],tmp_data['default_value'])\n return True\n\nif __name__ == \"__main__\":\n creat_table()\n print \"success!\"\n"},"license":{"kind":"string","value":"mit"},"hash":{"kind":"number","value":5948230377055756000,"string":"5,948,230,377,055,756,000"},"line_mean":{"kind":"number","value":22.4782608696,"string":"22.478261"},"line_max":{"kind":"number","value":72,"string":"72"},"alpha_frac":{"kind":"number","value":0.5574074074,"string":"0.557407"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.347107438016529,"string":"3.347107"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45128,"cells":{"repo_name":{"kind":"string","value":"fallen/artiq"},"path":{"kind":"string","value":"artiq/frontend/artiq_run.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"4103"},"content":{"kind":"string","value":"#!/usr/bin/env python3\n# Copyright (C) 2014, 2015 M-Labs Limited\n# Copyright (C) 2014, 2015 Robert Jordens \n\nimport argparse\nimport sys\nimport time\nfrom operator import itemgetter\nfrom itertools import chain\nimport logging\n\nimport h5py\n\nfrom artiq.language.environment import EnvExperiment\nfrom artiq.protocols.file_db import FlatFileDB\nfrom artiq.master.worker_db import DeviceManager, ResultDB\nfrom artiq.tools import *\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass ELFRunner(EnvExperiment):\n def build(self):\n self.attr_device(\"core\")\n self.attr_argument(\"file\")\n\n def run(self):\n with open(self.file, \"rb\") as f:\n self.core.comm.load(f.read())\n self.core.comm.run(\"run\")\n self.core.comm.serve(dict(), dict())\n\n\nclass SimpleParamLogger:\n def set(self, timestamp, name, value):\n logger.info(\"Parameter change: {} = {}\".format(name, value))\n\n\nclass DummyScheduler:\n def __init__(self):\n self.next_rid = 0\n self.pipeline_name = \"main\"\n self.priority = 0\n self.expid = None\n\n def submit(self, pipeline_name, expid, priority, due_date, flush):\n rid = self.next_rid\n self.next_rid += 1\n logger.info(\"Submitting: %s, RID=%s\", expid, rid)\n return rid\n\n def delete(self, rid):\n logger.info(\"Deleting RID %s\", rid)\n\n def pause(self):\n pass\n\n\ndef get_argparser(with_file=True):\n parser = argparse.ArgumentParser(\n description=\"Local experiment running tool\")\n\n verbosity_args(parser)\n parser.add_argument(\"-d\", \"--ddb\", default=\"ddb.pyon\",\n help=\"device database file\")\n parser.add_argument(\"-p\", \"--pdb\", default=\"pdb.pyon\",\n help=\"parameter database file\")\n\n parser.add_argument(\"-e\", \"--experiment\", default=None,\n help=\"experiment to run\")\n parser.add_argument(\"-o\", \"--hdf5\", default=None,\n help=\"write results to specified HDF5 file\"\n \" (default: print them)\")\n if with_file:\n parser.add_argument(\"file\",\n help=\"file containing the experiment to run\")\n parser.add_argument(\"arguments\", nargs=\"*\",\n help=\"run arguments\")\n\n return parser\n\n\ndef _build_experiment(dmgr, pdb, rdb, args):\n if hasattr(args, \"file\"):\n if args.file.endswith(\".elf\"):\n if args.arguments:\n raise ValueError(\"arguments not supported for ELF kernels\")\n if args.experiment:\n raise ValueError(\"experiment-by-name not supported \"\n \"for ELF kernels\")\n return ELFRunner(dmgr, pdb, rdb, file=args.file)\n else:\n module = file_import(args.file)\n file = args.file\n else:\n module = sys.modules[\"__main__\"]\n file = getattr(module, \"__file__\")\n exp = get_experiment(module, args.experiment)\n arguments = parse_arguments(args.arguments)\n expid = {\n \"file\": file,\n \"experiment\": args.experiment,\n \"arguments\": arguments\n }\n dmgr.virtual_devices[\"scheduler\"].expid = expid\n return exp(dmgr, pdb, rdb, **arguments)\n\n\ndef run(with_file=False):\n args = get_argparser(with_file).parse_args()\n init_logger(args)\n\n dmgr = DeviceManager(FlatFileDB(args.ddb),\n virtual_devices={\"scheduler\": DummyScheduler()})\n pdb = FlatFileDB(args.pdb)\n pdb.hooks.append(SimpleParamLogger())\n rdb = ResultDB()\n\n try:\n exp_inst = _build_experiment(dmgr, pdb, rdb, args)\n exp_inst.prepare()\n exp_inst.run()\n exp_inst.analyze()\n finally:\n dmgr.close_devices()\n\n if args.hdf5 is not None:\n with h5py.File(args.hdf5, \"w\") as f:\n rdb.write_hdf5(f)\n elif rdb.rt.read or rdb.nrt:\n r = chain(rdb.rt.read.items(), rdb.nrt.items())\n for k, v in sorted(r, key=itemgetter(0)):\n print(\"{}: {}\".format(k, v))\n\n\ndef main():\n return run(with_file=True)\n\n\nif __name__ == \"__main__\":\n main()\n"},"license":{"kind":"string","value":"gpl-3.0"},"hash":{"kind":"number","value":-3275687307934452700,"string":"-3,275,687,307,934,452,700"},"line_mean":{"kind":"number","value":27.8943661972,"string":"27.894366"},"line_max":{"kind":"number","value":75,"string":"75"},"alpha_frac":{"kind":"number","value":0.5883499878,"string":"0.58835"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.76076993583868,"string":"3.76077"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45129,"cells":{"repo_name":{"kind":"string","value":"vntarasov/openpilot"},"path":{"kind":"string","value":"selfdrive/debug/get_fingerprint.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"1030"},"content":{"kind":"string","value":"#!/usr/bin/env python3\n\n# simple script to get a vehicle fingerprint.\n\n# Instructions:\n# - connect to a Panda\n# - run selfdrive/boardd/boardd\n# - launching this script\n# - turn on the car in STOCK MODE (set giraffe switches properly).\n# Note: it's very important that the car is in stock mode, in order to collect a complete fingerprint\n# - since some messages are published at low frequency, keep this script running for at least 30s,\n# until all messages are received at least once\n\nimport cereal.messaging as messaging\n\nlogcan = messaging.sub_sock('can')\nmsgs = {}\nwhile True:\n lc = messaging.recv_sock(logcan, True)\n if lc is None:\n continue\n\n for c in lc.can:\n # read also msgs sent by EON on CAN bus 0x80 and filter out the\n # addr with more than 11 bits\n if c.src in [0, 2] and c.address < 0x800:\n msgs[c.address] = len(c.dat)\n\n fingerprint = ', '.join(\"%d: %d\" % v for v in sorted(msgs.items()))\n\n print(\"number of messages {0}:\".format(len(msgs)))\n print(\"fingerprint {0}\".format(fingerprint))\n"},"license":{"kind":"string","value":"mit"},"hash":{"kind":"number","value":-3785566846449061400,"string":"-3,785,566,846,449,061,400"},"line_mean":{"kind":"number","value":31.1875,"string":"31.1875"},"line_max":{"kind":"number","value":103,"string":"103"},"alpha_frac":{"kind":"number","value":0.6951456311,"string":"0.695146"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.3993399339933994,"string":"3.39934"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45130,"cells":{"repo_name":{"kind":"string","value":"vcoin-project/v"},"path":{"kind":"string","value":"qa/rpc-tests/test_framework/bignum.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"1991"},"content":{"kind":"string","value":"#\n#\n# bignum.py\n#\n# This file is copied from python-vcoinlib.\n#\n# Distributed under the MIT/X11 software license, see the accompanying\n# file COPYING or http://www.opensource.org/licenses/mit-license.php.\n#\n\n\"\"\"Bignum routines\"\"\"\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport struct\n\n\n# generic big endian MPI format\n\ndef bn_bytes(v, have_ext=False):\n ext = 0\n if have_ext:\n ext = 1\n return ((v.bit_length()+7)//8) + ext\n\ndef bn2bin(v):\n s = bytearray()\n i = bn_bytes(v)\n while i > 0:\n s.append((v >> ((i-1) * 8)) & 0xff)\n i -= 1\n return s\n\ndef bin2bn(s):\n l = 0\n for ch in s:\n l = (l << 8) | ch\n return l\n\ndef bn2mpi(v):\n have_ext = False\n if v.bit_length() > 0:\n have_ext = (v.bit_length() & 0x07) == 0\n\n neg = False\n if v < 0:\n neg = True\n v = -v\n\n s = struct.pack(b\">I\", bn_bytes(v, have_ext))\n ext = bytearray()\n if have_ext:\n ext.append(0)\n v_bin = bn2bin(v)\n if neg:\n if have_ext:\n ext[0] |= 0x80\n else:\n v_bin[0] |= 0x80\n return s + ext + v_bin\n\ndef mpi2bn(s):\n if len(s) < 4:\n return None\n s_size = bytes(s[:4])\n v_len = struct.unpack(b\">I\", s_size)[0]\n if len(s) != (v_len + 4):\n return None\n if v_len == 0:\n return 0\n\n v_str = bytearray(s[4:])\n neg = False\n i = v_str[0]\n if i & 0x80:\n neg = True\n i &= ~0x80\n v_str[0] = i\n\n v = bin2bn(v_str)\n\n if neg:\n return -v\n return v\n\n# vcoin-specific little endian format, with implicit size\ndef mpi2vch(s):\n r = s[4:] # strip size\n r = r[::-1] # reverse string, converting BE->LE\n return r\n\ndef bn2vch(v):\n return bytes(mpi2vch(bn2mpi(v)))\n\ndef vch2mpi(s):\n r = struct.pack(b\">I\", len(s)) # size\n r += s[::-1] # reverse string, converting LE->BE\n return r\n\ndef vch2bn(s):\n return mpi2bn(vch2mpi(s))\n\n"},"license":{"kind":"string","value":"mit"},"hash":{"kind":"number","value":-4014981737356212000,"string":"-4,014,981,737,356,212,000"},"line_mean":{"kind":"number","value":18.5196078431,"string":"18.519608"},"line_max":{"kind":"number","value":82,"string":"82"},"alpha_frac":{"kind":"number","value":0.5243596183,"string":"0.52436"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":2.8688760806916425,"string":"2.868876"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45131,"cells":{"repo_name":{"kind":"string","value":"ultimanet/nifty"},"path":{"kind":"string","value":"rg/powerspectrum.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"26583"},"content":{"kind":"string","value":"## NIFTY (Numerical Information Field Theory) has been developed at the\n## Max-Planck-Institute for Astrophysics.\n##\n## Copyright (C) 2013 Max-Planck-Society\n##\n## Author: Marco Selig\n## Project homepage: \n##\n## This program is free software: you can redistribute it and/or modify\n## it under the terms of the GNU General Public License as published by\n## the Free Software Foundation, either version 3 of the License, or\n## (at your option) any later version.\n##\n## This program is distributed in the hope that it will be useful,\n## but WITHOUT ANY WARRANTY; without even the implied warranty of\n## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n## See the GNU General Public License for more details.\n##\n## You should have received a copy of the GNU General Public License\n## along with this program. If not, see .\n\n## TODO: cythonize\n\nfrom __future__ import division\nimport numpy as np\n\n\ndef draw_vector_nd(axes,dgrid,ps,symtype=0,fourier=False,zerocentered=False,kpack=None):\n\n \"\"\"\n Draws a n-dimensional field on a regular grid from a given power\n spectrum. The grid parameters need to be specified, together with a\n couple of global options explained below. The dimensionality of the\n field is determined automatically.\n\n Parameters\n ----------\n axes : ndarray\n An array with the length of each axis.\n\n dgrid : ndarray\n An array with the pixel length of each axis.\n\n ps : ndarray\n The power spectrum as a function of Fourier modes.\n\n symtype : int {0,1,2} : *optional*\n Whether the output should be real valued (0), complex-hermitian (1)\n or complex without symmetry (2). (default=0)\n\n fourier : bool : *optional*\n Whether the output should be in Fourier space or not\n (default=False).\n\n zerocentered : bool : *optional*\n Whether the output array should be zerocentered, i.e. starting with\n negative Fourier modes going over the zero mode to positive modes,\n or not zerocentered, where zero, positive and negative modes are\n simpy ordered consecutively.\n\n Returns\n -------\n field : ndarray\n The drawn random field.\n\n \"\"\"\n if(kpack is None):\n kdict = np.fft.fftshift(nkdict_fast(axes,dgrid,fourier))\n klength = nklength(kdict)\n else:\n kdict = kpack[1][np.fft.ifftshift(kpack[0],axes=shiftaxes(zerocentered,st_to_zero_mode=False))]\n klength = kpack[1]\n\n #output is in position space\n if(not fourier):\n\n #output is real-valued\n if(symtype==0):\n vector = drawherm(klength,kdict,ps)\n if(np.any(zerocentered==True)):\n return np.real(np.fft.fftshift(np.fft.ifftn(vector),axes=shiftaxes(zerocentered)))\n else:\n return np.real(np.fft.ifftn(vector))\n\n #output is complex with hermitian symmetry\n elif(symtype==1):\n vector = drawwild(klength,kdict,ps,real_corr=2)\n if(np.any(zerocentered==True)):\n return np.fft.fftshift(np.fft.ifftn(np.real(vector)),axes=shiftaxes(zerocentered))\n else:\n return np.fft.ifftn(np.real(vector))\n\n #output is complex without symmetry\n else:\n vector = drawwild(klength,kdict,ps)\n if(np.any(zerocentered==True)):\n return np.fft.fftshift(np.fft.ifftn(vector),axes=shiftaxes(zerocentered))\n else:\n return np.fft.ifftn(vector)\n\n #output is in fourier space\n else:\n\n #output is real-valued\n if(symtype==0):\n vector = drawwild(klength,kdict,ps,real_corr=2)\n if np.any(zerocentered == True):\n return np.real(np.fft.fftshift(vector,axes=shiftaxes(zerocentered)))\n else:\n return np.real(vector)\n\n #output is complex with hermitian symmetry\n elif(symtype==1):\n vector = drawherm(klength,kdict,ps)\n if(np.any(zerocentered==True)):\n return np.fft.fftshift(vector,axes=shiftaxes(zerocentered))\n else:\n return vector\n\n #output is complex without symmetry\n else:\n vector = drawwild(klength,kdict,ps)\n if(np.any(zerocentered==True)):\n return np.fft.fftshift(vector,axes=shiftaxes(zerocentered))\n else:\n return vector\n\n\n#def calc_ps(field,axes,dgrid,zerocentered=False,fourier=False):\n#\n# \"\"\"\n# Calculates the power spectrum of a given field assuming that the field\n# is statistically homogenous and isotropic.\n#\n# Parameters\n# ----------\n# field : ndarray\n# The input field from which the power spectrum should be determined.\n#\n# axes : ndarray\n# An array with the length of each axis.\n#\n# dgrid : ndarray\n# An array with the pixel length of each axis.\n#\n# zerocentered : bool : *optional*\n# Whether the output array should be zerocentered, i.e. starting with\n# negative Fourier modes going over the zero mode to positive modes,\n# or not zerocentered, where zero, positive and negative modes are\n# simpy ordered consecutively.\n#\n# fourier : bool : *optional*\n# Whether the output should be in Fourier space or not\n# (default=False).\n#\n# \"\"\"\n#\n# ## field absolutes\n# if(not fourier):\n# foufield = np.fft.fftshift(np.fft.fftn(field))\n# elif(np.any(zerocentered==False)):\n# foufield = np.fft.fftshift(field, axes=shiftaxes(zerocentered,st_to_zero_mode=True))\n# else:\n# foufield = field\n# fieldabs = np.abs(foufield)**2\n#\n# kdict = nkdict_fast(axes,dgrid,fourier)\n# klength = nklength(kdict)\n#\n# ## power spectrum\n# ps = np.zeros(klength.size)\n# rho = np.zeros(klength.size)\n# for ii in np.ndindex(kdict.shape):\n# position = np.searchsorted(klength,kdict[ii])\n# rho[position] += 1\n# ps[position] += fieldabs[ii]\n# ps = np.divide(ps,rho)\n# return ps\n\ndef calc_ps_fast(field,axes,dgrid,zerocentered=False,fourier=False,pindex=None,kindex=None,rho=None):\n\n \"\"\"\n Calculates the power spectrum of a given field faster assuming that the\n field is statistically homogenous and isotropic.\n\n Parameters\n ----------\n field : ndarray\n The input field from which the power spectrum should be determined.\n\n axes : ndarray\n An array with the length of each axis.\n\n dgrid : ndarray\n An array with the pixel length of each axis.\n\n zerocentered : bool : *optional*\n Whether the output array should be zerocentered, i.e. starting with\n negative Fourier modes going over the zero mode to positive modes,\n or not zerocentered, where zero, positive and negative modes are\n simpy ordered consecutively.\n\n fourier : bool : *optional*\n Whether the output should be in Fourier space or not\n (default=False).\n\n pindex : ndarray\n Index of the Fourier grid points in a numpy.ndarray ordered\n following the zerocentered flag (default=None).\n\n kindex : ndarray\n Array of all k-vector lengths (default=None).\n\n rho : ndarray\n Degeneracy of the Fourier grid, indicating how many k-vectors in\n Fourier space have the same length (default=None).\n\n \"\"\"\n ## field absolutes\n if(not fourier):\n foufield = np.fft.fftshift(np.fft.fftn(field))\n elif(np.any(zerocentered==False)):\n foufield = np.fft.fftshift(field, axes=shiftaxes(zerocentered,st_to_zero_mode=True))\n else:\n foufield = field\n fieldabs = np.abs(foufield)**2\n\n if(rho is None):\n if(pindex is None):\n ## kdict\n kdict = nkdict_fast(axes,dgrid,fourier)\n ## klength\n if(kindex is None):\n klength = nklength(kdict)\n else:\n klength = kindex\n ## power spectrum\n ps = np.zeros(klength.size)\n rho = np.zeros(klength.size)\n for ii in np.ndindex(kdict.shape):\n position = np.searchsorted(klength,kdict[ii])\n ps[position] += fieldabs[ii]\n rho[position] += 1\n else:\n ## zerocenter pindex\n if(np.any(zerocentered==False)):\n pindex = np.fft.fftshift(pindex, axes=shiftaxes(zerocentered,st_to_zero_mode=True))\n ## power spectrum\n ps = np.zeros(np.max(pindex)+1)\n rho = np.zeros(ps.size)\n for ii in np.ndindex(pindex.shape):\n ps[pindex[ii]] += fieldabs[ii]\n rho[pindex[ii]] += 1\n elif(pindex is None):\n ## kdict\n kdict = nkdict_fast(axes,dgrid,fourier)\n ## klength\n if(kindex is None):\n klength = nklength(kdict)\n else:\n klength = kindex\n ## power spectrum\n ps = np.zeros(klength.size)\n for ii in np.ndindex(kdict.shape):\n position = np.searchsorted(klength,kdict[ii])\n ps[position] += fieldabs[ii]\n else:\n ## zerocenter pindex\n if(np.any(zerocentered==False)):\n pindex = np.fft.fftshift(pindex, axes=shiftaxes(zerocentered,st_to_zero_mode=True))\n ## power spectrum\n ps = np.zeros(rho.size)\n for ii in np.ndindex(pindex.shape):\n ps[pindex[ii]] += fieldabs[ii]\n\n ps = np.divide(ps,rho)\n return ps\n\n\ndef get_power_index(axes,dgrid,zerocentered,irred=False,fourier=True):\n\n \"\"\"\n Returns the index of the Fourier grid points in a numpy\n array, ordered following the zerocentered flag.\n\n Parameters\n ----------\n axes : ndarray\n An array with the length of each axis.\n\n dgrid : ndarray\n An array with the pixel length of each axis.\n\n zerocentered : bool\n Whether the output array should be zerocentered, i.e. starting with\n negative Fourier modes going over the zero mode to positive modes,\n or not zerocentered, where zero, positive and negative modes are\n simpy ordered consecutively.\n\n irred : bool : *optional*\n If True, the function returns an array of all k-vector lengths and\n their degeneracy factors. If False, just the power index array is\n returned.\n\n fourier : bool : *optional*\n Whether the output should be in Fourier space or not\n (default=False).\n\n Returns\n -------\n index or {klength, rho} : scalar or list\n Returns either an array of all k-vector lengths and\n their degeneracy factors or just the power index array\n depending on the flag irred.\n\n \"\"\"\n\n ## kdict, klength\n if(np.any(zerocentered==False)):\n kdict = np.fft.fftshift(nkdict_fast(axes,dgrid,fourier),axes=shiftaxes(zerocentered,st_to_zero_mode=True))\n else:\n kdict = nkdict_fast(axes,dgrid,fourier)\n klength = nklength(kdict)\n ## output\n if(irred):\n rho = np.zeros(klength.shape,dtype=np.int)\n for ii in np.ndindex(kdict.shape):\n rho[np.searchsorted(klength,kdict[ii])] += 1\n return klength,rho\n else:\n ind = np.empty(axes,dtype=np.int)\n for ii in np.ndindex(kdict.shape):\n ind[ii] = np.searchsorted(klength,kdict[ii])\n return ind\n\n\ndef get_power_indices(axes,dgrid,zerocentered,fourier=True):\n \"\"\"\n Returns the index of the Fourier grid points in a numpy\n array, ordered following the zerocentered flag.\n\n Parameters\n ----------\n axes : ndarray\n An array with the length of each axis.\n\n dgrid : ndarray\n An array with the pixel length of each axis.\n\n zerocentered : bool\n Whether the output array should be zerocentered, i.e. starting with\n negative Fourier modes going over the zero mode to positive modes,\n or not zerocentered, where zero, positive and negative modes are\n simpy ordered consecutively.\n\n irred : bool : *optional*\n If True, the function returns an array of all k-vector lengths and\n their degeneracy factors. If False, just the power index array is\n returned.\n\n fourier : bool : *optional*\n Whether the output should be in Fourier space or not\n (default=False).\n\n Returns\n -------\n index, klength, rho : ndarrays\n Returns the power index array, an array of all k-vector lengths and\n their degeneracy factors.\n\n \"\"\"\n\n ## kdict, klength\n if(np.any(zerocentered==False)):\n kdict = np.fft.fftshift(nkdict_fast(axes,dgrid,fourier),axes=shiftaxes(zerocentered,st_to_zero_mode=True))\n else:\n kdict = nkdict_fast(axes,dgrid,fourier)\n klength = nklength(kdict)\n ## output\n ind = np.empty(axes,dtype=np.int)\n rho = np.zeros(klength.shape,dtype=np.int)\n for ii in np.ndindex(kdict.shape):\n ind[ii] = np.searchsorted(klength,kdict[ii])\n rho[ind[ii]] += 1\n return ind,klength,rho\n\n\ndef get_power_indices2(axes,dgrid,zerocentered,fourier=True):\n \"\"\"\n Returns the index of the Fourier grid points in a numpy\n array, ordered following the zerocentered flag.\n\n Parameters\n ----------\n axes : ndarray\n An array with the length of each axis.\n\n dgrid : ndarray\n An array with the pixel length of each axis.\n\n zerocentered : bool\n Whether the output array should be zerocentered, i.e. starting with\n negative Fourier modes going over the zero mode to positive modes,\n or not zerocentered, where zero, positive and negative modes are\n simpy ordered consecutively.\n\n irred : bool : *optional*\n If True, the function returns an array of all k-vector lengths and\n their degeneracy factors. If False, just the power index array is\n returned.\n\n fourier : bool : *optional*\n Whether the output should be in Fourier space or not\n (default=False).\n\n Returns\n -------\n index, klength, rho : ndarrays\n Returns the power index array, an array of all k-vector lengths and\n their degeneracy factors.\n\n \"\"\"\n\n ## kdict, klength\n if(np.any(zerocentered==False)):\n kdict = np.fft.fftshift(nkdict_fast2(axes,dgrid,fourier),axes=shiftaxes(zerocentered,st_to_zero_mode=True))\n else:\n kdict = nkdict_fast2(axes,dgrid,fourier)\n\n klength,rho,ind = nkdict_to_indices(kdict)\n\n return ind,klength,rho\n\n\ndef nkdict_to_indices(kdict):\n\n kindex,pindex = np.unique(kdict,return_inverse=True)\n pindex = pindex.reshape(kdict.shape)\n\n rho = pindex.flatten()\n rho.sort()\n rho = np.unique(rho,return_index=True,return_inverse=False)[1]\n rho = np.append(rho[1:]-rho[:-1],[np.prod(pindex.shape)-rho[-1]])\n\n return kindex,rho,pindex\n\n\ndef bin_power_indices(pindex,kindex,rho,log=False,nbin=None,binbounds=None):\n \"\"\"\n Returns the (re)binned power indices associated with the Fourier grid.\n\n Parameters\n ----------\n pindex : ndarray\n Index of the Fourier grid points in a numpy.ndarray ordered\n following the zerocentered flag (default=None).\n kindex : ndarray\n Array of all k-vector lengths (default=None).\n rho : ndarray\n Degeneracy of the Fourier grid, indicating how many k-vectors in\n Fourier space have the same length (default=None).\n log : bool\n Flag specifying if the binning is performed on logarithmic scale\n (default: False).\n nbin : integer\n Number of used bins (default: None).\n binbounds : {list, array}\n Array-like inner boundaries of the used bins (default: None).\n\n Returns\n -------\n pindex, kindex, rho : ndarrays\n The (re)binned power indices.\n\n \"\"\"\n ## boundaries\n if(binbounds is not None):\n binbounds = np.sort(binbounds)\n ## equal binning\n else:\n if(log is None):\n log = False\n if(log):\n k = np.r_[0,np.log(kindex[1:])]\n else:\n k = kindex\n dk = np.max(k[2:]-k[1:-1]) ## minimal dk\n if(nbin is None):\n nbin = int((k[-1]-0.5*(k[2]+k[1]))/dk-0.5) ## maximal nbin\n else:\n nbin = min(int(nbin),int((k[-1]-0.5*(k[2]+k[1]))/dk+2.5))\n dk = (k[-1]-0.5*(k[2]+k[1]))/(nbin-2.5)\n binbounds = np.r_[0.5*(3*k[1]-k[2]),0.5*(k[1]+k[2])+dk*np.arange(nbin-2)]\n if(log):\n binbounds = np.exp(binbounds)\n ## reordering\n reorder = np.searchsorted(binbounds,kindex)\n rho_ = np.zeros(len(binbounds)+1,dtype=rho.dtype)\n kindex_ = np.empty(len(binbounds)+1,dtype=kindex.dtype)\n for ii in range(len(reorder)):\n if(rho_[reorder[ii]]==0):\n kindex_[reorder[ii]] = kindex[ii]\n rho_[reorder[ii]] += rho[ii]\n else:\n kindex_[reorder[ii]] = (kindex_[reorder[ii]]*rho_[reorder[ii]]+kindex[ii]*rho[ii])/(rho_[reorder[ii]]+rho[ii])\n rho_[reorder[ii]] += rho[ii]\n\n return reorder[pindex],kindex_,rho_\n\n\ndef nhermitianize(field,zerocentered):\n\n \"\"\"\n Hermitianizes an arbitrary n-dimensional field. Becomes relatively slow\n for large n.\n\n Parameters\n ----------\n field : ndarray\n The input field that should be hermitianized.\n\n zerocentered : bool\n Whether the output array should be zerocentered, i.e. starting with\n negative Fourier modes going over the zero mode to positive modes,\n or not zerocentered, where zero, positive and negative modes are\n simpy ordered consecutively.\n\n Returns\n -------\n hermfield : ndarray\n The hermitianized field.\n\n \"\"\"\n ## shift zerocentered axes\n if(np.any(zerocentered==True)):\n field = np.fft.fftshift(field, axes=shiftaxes(zerocentered))\n# for index in np.ndenumerate(field):\n# negind = tuple(-np.array(index[0]))\n# field[negind] = np.conjugate(index[1])\n# if(field[negind]==field[index[0]]):\n# field[index[0]] = np.abs(index[1])*(np.sign(index[1].real)+(np.sign(index[1].real)==0)*np.sign(index[1].imag)).astype(np.int)\n subshape = np.array(field.shape,dtype=np.int) ## == axes\n maxindex = subshape//2\n subshape[np.argmax(subshape)] = subshape[np.argmax(subshape)]//2+1 ## ~half larges axis\n for ii in np.ndindex(tuple(subshape)):\n negii = tuple(-np.array(ii))\n field[negii] = np.conjugate(field[ii])\n for ii in np.ndindex((2,)*maxindex.size):\n index = tuple(ii*maxindex)\n field[index] = np.abs(field[index])*(np.sign(field[index].real)+(np.sign(field[index].real)==0)*-np.sign(field[index].imag)).astype(np.int) ## minus since overwritten before\n ## reshift zerocentered axes\n if(np.any(zerocentered==True)):\n field = np.fft.fftshift(field,axes=shiftaxes(zerocentered))\n return field\n\ndef nhermitianize_fast(field,zerocentered,special=False):\n\n \"\"\"\n Hermitianizes an arbitrary n-dimensional field faster.\n Still becomes comparably slow for large n.\n\n Parameters\n ----------\n field : ndarray\n The input field that should be hermitianized.\n\n zerocentered : bool\n Whether the output array should be zerocentered, i.e. starting with\n negative Fourier modes going over the zero mode to positive modes,\n or not zerocentered, where zero, positive and negative modes are\n simpy ordered consecutively.\n\n special : bool, *optional*\n Must be True for random fields drawn from Gaussian or pm1\n distributions.\n\n Returns\n -------\n hermfield : ndarray\n The hermitianized field.\n\n \"\"\"\n ## shift zerocentered axes\n if(np.any(zerocentered==True)):\n field = np.fft.fftshift(field, axes=shiftaxes(zerocentered))\n dummy = np.conjugate(field)\n ## mirror conjugate field\n for ii in range(field.ndim):\n dummy = np.swapaxes(dummy,0,ii)\n dummy = np.flipud(dummy)\n dummy = np.roll(dummy,1,axis=0)\n dummy = np.swapaxes(dummy,0,ii)\n if(special): ## special normalisation for certain random fields\n field = np.sqrt(0.5)*(field+dummy)\n maxindex = np.array(field.shape,dtype=np.int)//2\n for ii in np.ndindex((2,)*maxindex.size):\n index = tuple(ii*maxindex)\n field[index] *= np.sqrt(0.5)\n else: ## regular case\n field = 0.5*(field+dummy)\n ## reshift zerocentered axes\n if(np.any(zerocentered==True)):\n field = np.fft.fftshift(field,axes=shiftaxes(zerocentered))\n return field\n\n\ndef random_hermitian_pm1(datatype,zerocentered,shape):\n\n \"\"\"\n Draws a set of hermitianized random, complex pm1 numbers.\n\n \"\"\"\n\n field = np.random.randint(4,high=None,size=np.prod(shape,axis=0,dtype=np.int,out=None)).reshape(shape,order='C')\n dummy = np.copy(field)\n ## mirror field\n for ii in range(field.ndim):\n dummy = np.swapaxes(dummy,0,ii)\n dummy = np.flipud(dummy)\n dummy = np.roll(dummy,1,axis=0)\n dummy = np.swapaxes(dummy,0,ii)\n field = (field+dummy+2*(field>dummy)*((field+dummy)%2))%4 ## wicked magic\n x = np.array([1+0j,0+1j,-1+0j,0-1j],dtype=datatype)[field]\n ## (re)shift zerocentered axes\n if(np.any(zerocentered==True)):\n field = np.fft.fftshift(field,axes=shiftaxes(zerocentered))\n return x\n\n\n#-----------------------------------------------------------------------------\n# Auxiliary functions\n#-----------------------------------------------------------------------------\n\ndef shiftaxes(zerocentered,st_to_zero_mode=False):\n\n \"\"\"\n Shifts the axes in a special way needed for some functions\n \"\"\"\n\n axes = []\n for ii in range(len(zerocentered)):\n if(st_to_zero_mode==False)and(zerocentered[ii]):\n axes += [ii]\n if(st_to_zero_mode==True)and(not zerocentered[ii]):\n axes += [ii]\n return axes\n\n\ndef nkdict(axes,dgrid,fourier=True):\n \"\"\"\n Calculates an n-dimensional array with its entries being the lengths of\n the k-vectors from the zero point of the Fourier grid.\n\n \"\"\"\n if(fourier):\n dk = dgrid\n else:\n dk = np.array([1/axes[i]/dgrid[i] for i in range(len(axes))])\n\n kdict = np.empty(axes)\n for ii in np.ndindex(kdict.shape):\n kdict[ii] = np.sqrt(np.sum(((ii-axes//2)*dk)**2))\n return kdict\n\n\ndef nkdict_fast(axes,dgrid,fourier=True):\n \"\"\"\n Calculates an n-dimensional array with its entries being the lengths of\n the k-vectors from the zero point of the Fourier grid.\n\n \"\"\"\n if(fourier):\n dk = dgrid\n else:\n dk = np.array([1/dgrid[i]/axes[i] for i in range(len(axes))])\n\n temp_vecs = np.array(np.where(np.ones(axes)),dtype='float').reshape(np.append(len(axes),axes))\n temp_vecs = np.rollaxis(temp_vecs,0,len(temp_vecs.shape))\n temp_vecs -= axes//2\n temp_vecs *= dk\n temp_vecs *= temp_vecs\n return np.sqrt(np.sum((temp_vecs),axis=-1))\n\n\ndef nkdict_fast2(axes,dgrid,fourier=True):\n \"\"\"\n Calculates an n-dimensional array with its entries being the lengths of\n the k-vectors from the zero point of the grid.\n\n \"\"\"\n if(fourier):\n dk = dgrid\n else:\n dk = np.array([1/dgrid[i]/axes[i] for i in range(len(axes))])\n\n inds = []\n for a in axes:\n inds += [slice(0,a)]\n\n cords = np.ogrid[inds]\n\n dists = ((cords[0]-axes[0]//2)*dk[0])**2\n for ii in range(1,len(axes)):\n dists = dists + ((cords[ii]-axes[ii]//2)*dk[ii])**2\n dists = np.sqrt(dists)\n\n return dists\n\n\ndef nklength(kdict):\n return np.sort(list(set(kdict.flatten())))\n\n\n#def drawherm(vector,klength,kdict,ps): ## vector = np.zeros(kdict.shape,dtype=np.complex)\n# for ii in np.ndindex(vector.shape):\n# if(vector[ii]==np.complex(0.,0.)):\n# vector[ii] = np.sqrt(0.5*ps[np.searchsorted(klength,kdict[ii])])*np.complex(np.random.normal(0.,1.),np.random.normal(0.,1.))\n# negii = tuple(-np.array(ii))\n# vector[negii] = np.conjugate(vector[ii])\n# if(vector[negii]==vector[ii]):\n# vector[ii] = np.float(np.sqrt(ps[klength==kdict[ii]]))*np.random.normal(0.,1.)\n# return vector\n\ndef drawherm(klength,kdict,ps):\n\n \"\"\"\n Draws a hermitian random field from a Gaussian distribution.\n\n \"\"\"\n\n# vector = np.zeros(kdict.shape,dtype='complex')\n# for ii in np.ndindex(vector.shape):\n# if(vector[ii]==np.complex(0.,0.)):\n# vector[ii] = np.sqrt(0.5*ps[np.searchsorted(klength,kdict[ii])])*np.complex(np.random.normal(0.,1.),np.random.normal(0.,1.))\n# negii = tuple(-np.array(ii))\n# vector[negii] = np.conjugate(vector[ii])\n# if(vector[negii]==vector[ii]):\n# vector[ii] = np.float(np.sqrt(ps[np.searchsorted(klength,kdict[ii])]))*np.random.normal(0.,1.)\n# return vector\n vec = np.random.normal(loc=0,scale=1,size=kdict.size).reshape(kdict.shape)\n vec = np.fft.fftn(vec)/np.sqrt(np.prod(kdict.shape))\n for ii in np.ndindex(kdict.shape):\n vec[ii] *= np.sqrt(ps[np.searchsorted(klength,kdict[ii])])\n return vec\n\n\n#def drawwild(vector,klength,kdict,ps,real_corr=1): ## vector = np.zeros(kdict.shape,dtype=np.complex)\n# for ii in np.ndindex(vector.shape):\n# vector[ii] = np.sqrt(real_corr*0.5*ps[klength==kdict[ii]])*np.complex(np.random.normal(0.,1.),np.random.normal(0.,1.))\n# return vector\n\ndef drawwild(klength,kdict,ps,real_corr=1):\n\n \"\"\"\n Draws a field of arbitrary symmetry from a Gaussian distribution.\n\n \"\"\"\n\n vec = np.empty(kdict.size,dtype=np.complex)\n vec.real = np.random.normal(loc=0,scale=np.sqrt(real_corr*0.5),size=kdict.size)\n vec.imag = np.random.normal(loc=0,scale=np.sqrt(real_corr*0.5),size=kdict.size)\n vec = vec.reshape(kdict.shape)\n for ii in np.ndindex(kdict.shape):\n vec[ii] *= np.sqrt(ps[np.searchsorted(klength,kdict[ii])])\n return vec\n\n"},"license":{"kind":"string","value":"gpl-3.0"},"hash":{"kind":"number","value":8155718674426123000,"string":"8,155,718,674,426,123,000"},"line_mean":{"kind":"number","value":33.7036553525,"string":"33.703655"},"line_max":{"kind":"number","value":181,"string":"181"},"alpha_frac":{"kind":"number","value":0.6002708498,"string":"0.600271"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.521860095389507,"string":"3.52186"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45132,"cells":{"repo_name":{"kind":"string","value":"fnordahl/nova"},"path":{"kind":"string","value":"nova/exception.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"56858"},"content":{"kind":"string","value":"# Copyright 2010 United States Government as represented by the\n# Administrator of the National Aeronautics and Space Administration.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Nova base exception handling.\n\nIncludes decorator for re-raising Nova-type exceptions.\n\nSHOULD include dedicated exception logging.\n\n\"\"\"\n\nimport functools\nimport sys\n\nfrom oslo_config import cfg\nfrom oslo_log import log as logging\nfrom oslo_utils import excutils\nimport six\nimport webob.exc\nfrom webob import util as woutil\n\nfrom nova.i18n import _, _LE\nfrom nova import safe_utils\n\nLOG = logging.getLogger(__name__)\n\nexc_log_opts = [\n cfg.BoolOpt('fatal_exception_format_errors',\n default=False,\n help='Make exception message format errors fatal'),\n]\n\nCONF = cfg.CONF\nCONF.register_opts(exc_log_opts)\n\n\nclass ConvertedException(webob.exc.WSGIHTTPException):\n def __init__(self, code, title=\"\", explanation=\"\"):\n self.code = code\n # There is a strict rule about constructing status line for HTTP:\n # '...Status-Line, consisting of the protocol version followed by a\n # numeric status code and its associated textual phrase, with each\n # element separated by SP characters'\n # (http://www.faqs.org/rfcs/rfc2616.html)\n # 'code' and 'title' can not be empty because they correspond\n # to numeric status code and its associated text\n if title:\n self.title = title\n else:\n try:\n self.title = woutil.status_reasons[self.code]\n except KeyError:\n msg = _LE(\"Improper or unknown HTTP status code used: %d\")\n LOG.error(msg, code)\n self.title = woutil.status_generic_reasons[self.code // 100]\n self.explanation = explanation\n super(ConvertedException, self).__init__()\n\n\ndef _cleanse_dict(original):\n \"\"\"Strip all admin_password, new_pass, rescue_pass keys from a dict.\"\"\"\n return {k: v for k, v in six.iteritems(original) if \"_pass\" not in k}\n\n\ndef wrap_exception(notifier=None, get_notifier=None):\n \"\"\"This decorator wraps a method to catch any exceptions that may\n get thrown. It also optionally sends the exception to the notification\n system.\n \"\"\"\n def inner(f):\n def wrapped(self, context, *args, **kw):\n # Don't store self or context in the payload, it now seems to\n # contain confidential information.\n try:\n return f(self, context, *args, **kw)\n except Exception as e:\n with excutils.save_and_reraise_exception():\n if notifier or get_notifier:\n payload = dict(exception=e)\n call_dict = safe_utils.getcallargs(f, context,\n *args, **kw)\n cleansed = _cleanse_dict(call_dict)\n payload.update({'args': cleansed})\n\n # If f has multiple decorators, they must use\n # functools.wraps to ensure the name is\n # propagated.\n event_type = f.__name__\n\n (notifier or get_notifier()).error(context,\n event_type,\n payload)\n\n return functools.wraps(f)(wrapped)\n return inner\n\n\nclass NovaException(Exception):\n \"\"\"Base Nova Exception\n\n To correctly use this class, inherit from it and define\n a 'msg_fmt' property. That msg_fmt will get printf'd\n with the keyword arguments provided to the constructor.\n\n \"\"\"\n msg_fmt = _(\"An unknown exception occurred.\")\n code = 500\n headers = {}\n safe = False\n\n def __init__(self, message=None, **kwargs):\n self.kwargs = kwargs\n\n if 'code' not in self.kwargs:\n try:\n self.kwargs['code'] = self.code\n except AttributeError:\n pass\n\n if not message:\n try:\n message = self.msg_fmt % kwargs\n\n except Exception:\n exc_info = sys.exc_info()\n # kwargs doesn't match a variable in the message\n # log the issue and the kwargs\n LOG.exception(_LE('Exception in string format operation'))\n for name, value in six.iteritems(kwargs):\n LOG.error(\"%s: %s\" % (name, value)) # noqa\n\n if CONF.fatal_exception_format_errors:\n six.reraise(*exc_info)\n else:\n # at least get the core message out if something happened\n message = self.msg_fmt\n\n self.message = message\n super(NovaException, self).__init__(message)\n\n def format_message(self):\n # NOTE(mrodden): use the first argument to the python Exception object\n # which should be our full NovaException message, (see __init__)\n return self.args[0]\n\n\nclass EncryptionFailure(NovaException):\n msg_fmt = _(\"Failed to encrypt text: %(reason)s\")\n\n\nclass DecryptionFailure(NovaException):\n msg_fmt = _(\"Failed to decrypt text: %(reason)s\")\n\n\nclass RevokeCertFailure(NovaException):\n msg_fmt = _(\"Failed to revoke certificate for %(project_id)s\")\n\n\nclass VirtualInterfaceCreateException(NovaException):\n msg_fmt = _(\"Virtual Interface creation failed\")\n\n\nclass VirtualInterfaceMacAddressException(NovaException):\n msg_fmt = _(\"Creation of virtual interface with \"\n \"unique mac address failed\")\n\n\nclass VirtualInterfacePlugException(NovaException):\n msg_fmt = _(\"Virtual interface plugin failed\")\n\n\nclass GlanceConnectionFailed(NovaException):\n msg_fmt = _(\"Connection to glance host %(host)s:%(port)s failed: \"\n \"%(reason)s\")\n\n\nclass CinderConnectionFailed(NovaException):\n msg_fmt = _(\"Connection to cinder host failed: %(reason)s\")\n\n\nclass Forbidden(NovaException):\n ec2_code = 'AuthFailure'\n msg_fmt = _(\"Not authorized.\")\n code = 403\n\n\nclass AdminRequired(Forbidden):\n msg_fmt = _(\"User does not have admin privileges\")\n\n\nclass PolicyNotAuthorized(Forbidden):\n msg_fmt = _(\"Policy doesn't allow %(action)s to be performed.\")\n\n\nclass VolumeLimitExceeded(Forbidden):\n msg_fmt = _(\"Volume resource quota exceeded\")\n\n\nclass ImageNotActive(NovaException):\n # NOTE(jruzicka): IncorrectState is used for volumes only in EC2,\n # but it still seems like the most appropriate option.\n ec2_code = 'IncorrectState'\n msg_fmt = _(\"Image %(image_id)s is not active.\")\n\n\nclass ImageNotAuthorized(NovaException):\n msg_fmt = _(\"Not authorized for image %(image_id)s.\")\n\n\nclass Invalid(NovaException):\n msg_fmt = _(\"Unacceptable parameters.\")\n code = 400\n\n\nclass InvalidBDM(Invalid):\n msg_fmt = _(\"Block Device Mapping is Invalid.\")\n\n\nclass InvalidBDMSnapshot(InvalidBDM):\n msg_fmt = _(\"Block Device Mapping is Invalid: \"\n \"failed to get snapshot %(id)s.\")\n\n\nclass InvalidBDMVolume(InvalidBDM):\n msg_fmt = _(\"Block Device Mapping is Invalid: \"\n \"failed to get volume %(id)s.\")\n\n\nclass InvalidBDMImage(InvalidBDM):\n msg_fmt = _(\"Block Device Mapping is Invalid: \"\n \"failed to get image %(id)s.\")\n\n\nclass InvalidBDMBootSequence(InvalidBDM):\n msg_fmt = _(\"Block Device Mapping is Invalid: \"\n \"Boot sequence for the instance \"\n \"and image/block device mapping \"\n \"combination is not valid.\")\n\n\nclass InvalidBDMLocalsLimit(InvalidBDM):\n msg_fmt = _(\"Block Device Mapping is Invalid: \"\n \"You specified more local devices than the \"\n \"limit allows\")\n\n\nclass InvalidBDMEphemeralSize(InvalidBDM):\n msg_fmt = _(\"Ephemeral disks requested are larger than \"\n \"the instance type allows.\")\n\n\nclass InvalidBDMSwapSize(InvalidBDM):\n msg_fmt = _(\"Swap drive requested is larger than instance type allows.\")\n\n\nclass InvalidBDMFormat(InvalidBDM):\n msg_fmt = _(\"Block Device Mapping is Invalid: \"\n \"%(details)s\")\n\n\nclass InvalidBDMForLegacy(InvalidBDM):\n msg_fmt = _(\"Block Device Mapping cannot \"\n \"be converted to legacy format. \")\n\n\nclass InvalidBDMVolumeNotBootable(InvalidBDM):\n msg_fmt = _(\"Block Device %(id)s is not bootable.\")\n\n\nclass InvalidAttribute(Invalid):\n msg_fmt = _(\"Attribute not supported: %(attr)s\")\n\n\nclass ValidationError(Invalid):\n msg_fmt = \"%(detail)s\"\n\n\nclass VolumeUnattached(Invalid):\n ec2_code = 'IncorrectState'\n msg_fmt = _(\"Volume %(volume_id)s is not attached to anything\")\n\n\nclass VolumeNotCreated(NovaException):\n msg_fmt = _(\"Volume %(volume_id)s did not finish being created\"\n \" even after we waited %(seconds)s seconds or %(attempts)s\"\n \" attempts. And its status is %(volume_status)s.\")\n\n\nclass VolumeEncryptionNotSupported(Invalid):\n msg_fmt = _(\"Volume encryption is not supported for %(volume_type)s \"\n \"volume %(volume_id)s\")\n\n\nclass InvalidKeypair(Invalid):\n ec2_code = 'InvalidKeyPair.Format'\n msg_fmt = _(\"Keypair data is invalid: %(reason)s\")\n\n\nclass InvalidRequest(Invalid):\n msg_fmt = _(\"The request is invalid.\")\n\n\nclass InvalidInput(Invalid):\n msg_fmt = _(\"Invalid input received: %(reason)s\")\n\n\nclass InvalidVolume(Invalid):\n ec2_code = 'UnsupportedOperation'\n msg_fmt = _(\"Invalid volume: %(reason)s\")\n\n\nclass InvalidVolumeAccessMode(Invalid):\n msg_fmt = _(\"Invalid volume access mode: %(access_mode)s\")\n\n\nclass InvalidMetadata(Invalid):\n msg_fmt = _(\"Invalid metadata: %(reason)s\")\n\n\nclass InvalidMetadataSize(Invalid):\n msg_fmt = _(\"Invalid metadata size: %(reason)s\")\n\n\nclass InvalidPortRange(Invalid):\n ec2_code = 'InvalidParameterValue'\n msg_fmt = _(\"Invalid port range %(from_port)s:%(to_port)s. %(msg)s\")\n\n\nclass InvalidIpProtocol(Invalid):\n msg_fmt = _(\"Invalid IP protocol %(protocol)s.\")\n\n\nclass InvalidContentType(Invalid):\n msg_fmt = _(\"Invalid content type %(content_type)s.\")\n\n\nclass InvalidAPIVersionString(Invalid):\n msg_fmt = _(\"API Version String %(version)s is of invalid format. Must \"\n \"be of format MajorNum.MinorNum.\")\n\n\nclass VersionNotFoundForAPIMethod(Invalid):\n msg_fmt = _(\"API version %(version)s is not supported on this method.\")\n\n\nclass InvalidGlobalAPIVersion(Invalid):\n msg_fmt = _(\"Version %(req_ver)s is not supported by the API. Minimum \"\n \"is %(min_ver)s and maximum is %(max_ver)s.\")\n\n\n# Cannot be templated as the error syntax varies.\n# msg needs to be constructed when raised.\nclass InvalidParameterValue(Invalid):\n ec2_code = 'InvalidParameterValue'\n msg_fmt = _(\"%(err)s\")\n\n\nclass InvalidAggregateAction(Invalid):\n msg_fmt = _(\"Unacceptable parameters.\")\n code = 400\n\n\nclass InvalidAggregateActionAdd(InvalidAggregateAction):\n msg_fmt = _(\"Cannot add host to aggregate \"\n \"%(aggregate_id)s. Reason: %(reason)s.\")\n\n\nclass InvalidAggregateActionDelete(InvalidAggregateAction):\n msg_fmt = _(\"Cannot remove host from aggregate \"\n \"%(aggregate_id)s. Reason: %(reason)s.\")\n\n\nclass InvalidAggregateActionUpdate(InvalidAggregateAction):\n msg_fmt = _(\"Cannot update aggregate \"\n \"%(aggregate_id)s. Reason: %(reason)s.\")\n\n\nclass InvalidAggregateActionUpdateMeta(InvalidAggregateAction):\n msg_fmt = _(\"Cannot update metadata of aggregate \"\n \"%(aggregate_id)s. Reason: %(reason)s.\")\n\n\nclass InvalidGroup(Invalid):\n msg_fmt = _(\"Group not valid. Reason: %(reason)s\")\n\n\nclass InvalidSortKey(Invalid):\n msg_fmt = _(\"Sort key supplied was not valid.\")\n\n\nclass InvalidStrTime(Invalid):\n msg_fmt = _(\"Invalid datetime string: %(reason)s\")\n\n\nclass InstanceInvalidState(Invalid):\n msg_fmt = _(\"Instance %(instance_uuid)s in %(attr)s %(state)s. Cannot \"\n \"%(method)s while the instance is in this state.\")\n\n\nclass InstanceNotRunning(Invalid):\n msg_fmt = _(\"Instance %(instance_id)s is not running.\")\n\n\nclass InstanceNotInRescueMode(Invalid):\n msg_fmt = _(\"Instance %(instance_id)s is not in rescue mode\")\n\n\nclass InstanceNotRescuable(Invalid):\n msg_fmt = _(\"Instance %(instance_id)s cannot be rescued: %(reason)s\")\n\n\nclass InstanceNotReady(Invalid):\n msg_fmt = _(\"Instance %(instance_id)s is not ready\")\n\n\nclass InstanceSuspendFailure(Invalid):\n msg_fmt = _(\"Failed to suspend instance: %(reason)s\")\n\n\nclass InstanceResumeFailure(Invalid):\n msg_fmt = _(\"Failed to resume instance: %(reason)s\")\n\n\nclass InstancePowerOnFailure(Invalid):\n msg_fmt = _(\"Failed to power on instance: %(reason)s\")\n\n\nclass InstancePowerOffFailure(Invalid):\n msg_fmt = _(\"Failed to power off instance: %(reason)s\")\n\n\nclass InstanceRebootFailure(Invalid):\n msg_fmt = _(\"Failed to reboot instance: %(reason)s\")\n\n\nclass InstanceTerminationFailure(Invalid):\n msg_fmt = _(\"Failed to terminate instance: %(reason)s\")\n\n\nclass InstanceDeployFailure(Invalid):\n msg_fmt = _(\"Failed to deploy instance: %(reason)s\")\n\n\nclass MultiplePortsNotApplicable(Invalid):\n msg_fmt = _(\"Failed to launch instances: %(reason)s\")\n\n\nclass InvalidFixedIpAndMaxCountRequest(Invalid):\n msg_fmt = _(\"Failed to launch instances: %(reason)s\")\n\n\nclass ServiceUnavailable(Invalid):\n msg_fmt = _(\"Service is unavailable at this time.\")\n\n\nclass ComputeResourcesUnavailable(ServiceUnavailable):\n msg_fmt = _(\"Insufficient compute resources: %(reason)s.\")\n\n\nclass HypervisorUnavailable(NovaException):\n msg_fmt = _(\"Connection to the hypervisor is broken on host: %(host)s\")\n\n\nclass ComputeServiceUnavailable(ServiceUnavailable):\n msg_fmt = _(\"Compute service of %(host)s is unavailable at this time.\")\n\n\nclass ComputeServiceInUse(NovaException):\n msg_fmt = _(\"Compute service of %(host)s is still in use.\")\n\n\nclass UnableToMigrateToSelf(Invalid):\n msg_fmt = _(\"Unable to migrate instance (%(instance_id)s) \"\n \"to current host (%(host)s).\")\n\n\nclass InvalidHypervisorType(Invalid):\n msg_fmt = _(\"The supplied hypervisor type of is invalid.\")\n\n\nclass DestinationHypervisorTooOld(Invalid):\n msg_fmt = _(\"The instance requires a newer hypervisor version than \"\n \"has been provided.\")\n\n\nclass ServiceTooOld(Invalid):\n msg_fmt = _(\"This service is older (v%(thisver)i) than the minimum \"\n \"(v%(minver)i) version of the rest of the deployment. \"\n \"Unable to continue.\")\n\n\nclass DestinationDiskExists(Invalid):\n msg_fmt = _(\"The supplied disk path (%(path)s) already exists, \"\n \"it is expected not to exist.\")\n\n\nclass InvalidDevicePath(Invalid):\n msg_fmt = _(\"The supplied device path (%(path)s) is invalid.\")\n\n\nclass DevicePathInUse(Invalid):\n msg_fmt = _(\"The supplied device path (%(path)s) is in use.\")\n code = 409\n\n\nclass DeviceIsBusy(Invalid):\n msg_fmt = _(\"The supplied device (%(device)s) is busy.\")\n\n\nclass InvalidCPUInfo(Invalid):\n msg_fmt = _(\"Unacceptable CPU info: %(reason)s\")\n\n\nclass InvalidIpAddressError(Invalid):\n msg_fmt = _(\"%(address)s is not a valid IP v4/6 address.\")\n\n\nclass InvalidVLANTag(Invalid):\n msg_fmt = _(\"VLAN tag is not appropriate for the port group \"\n \"%(bridge)s. Expected VLAN tag is %(tag)s, \"\n \"but the one associated with the port group is %(pgroup)s.\")\n\n\nclass InvalidVLANPortGroup(Invalid):\n msg_fmt = _(\"vSwitch which contains the port group %(bridge)s is \"\n \"not associated with the desired physical adapter. \"\n \"Expected vSwitch is %(expected)s, but the one associated \"\n \"is %(actual)s.\")\n\n\nclass InvalidDiskFormat(Invalid):\n msg_fmt = _(\"Disk format %(disk_format)s is not acceptable\")\n\n\nclass InvalidDiskInfo(Invalid):\n msg_fmt = _(\"Disk info file is invalid: %(reason)s\")\n\n\nclass DiskInfoReadWriteFail(Invalid):\n msg_fmt = _(\"Failed to read or write disk info file: %(reason)s\")\n\n\nclass ImageUnacceptable(Invalid):\n msg_fmt = _(\"Image %(image_id)s is unacceptable: %(reason)s\")\n\n\nclass InstanceUnacceptable(Invalid):\n msg_fmt = _(\"Instance %(instance_id)s is unacceptable: %(reason)s\")\n\n\nclass InvalidEc2Id(Invalid):\n msg_fmt = _(\"Ec2 id %(ec2_id)s is unacceptable.\")\n\n\nclass InvalidUUID(Invalid):\n msg_fmt = _(\"Expected a uuid but received %(uuid)s.\")\n\n\nclass InvalidID(Invalid):\n msg_fmt = _(\"Invalid ID received %(id)s.\")\n\n\nclass ConstraintNotMet(NovaException):\n msg_fmt = _(\"Constraint not met.\")\n code = 412\n\n\nclass NotFound(NovaException):\n msg_fmt = _(\"Resource could not be found.\")\n code = 404\n\n\nclass AgentBuildNotFound(NotFound):\n msg_fmt = _(\"No agent-build associated with id %(id)s.\")\n\n\nclass AgentBuildExists(NovaException):\n msg_fmt = _(\"Agent-build with hypervisor %(hypervisor)s os %(os)s \"\n \"architecture %(architecture)s exists.\")\n\n\nclass VolumeNotFound(NotFound):\n ec2_code = 'InvalidVolume.NotFound'\n msg_fmt = _(\"Volume %(volume_id)s could not be found.\")\n\n\nclass BDMNotFound(NotFound):\n msg_fmt = _(\"No Block Device Mapping with id %(id)s.\")\n\n\nclass VolumeBDMNotFound(NotFound):\n msg_fmt = _(\"No volume Block Device Mapping with id %(volume_id)s.\")\n\n\nclass VolumeBDMPathNotFound(VolumeBDMNotFound):\n msg_fmt = _(\"No volume Block Device Mapping at path: %(path)s\")\n\n\nclass SnapshotNotFound(NotFound):\n ec2_code = 'InvalidSnapshot.NotFound'\n msg_fmt = _(\"Snapshot %(snapshot_id)s could not be found.\")\n\n\nclass DiskNotFound(NotFound):\n msg_fmt = _(\"No disk at %(location)s\")\n\n\nclass VolumeDriverNotFound(NotFound):\n msg_fmt = _(\"Could not find a handler for %(driver_type)s volume.\")\n\n\nclass InvalidImageRef(Invalid):\n msg_fmt = _(\"Invalid image href %(image_href)s.\")\n\n\nclass AutoDiskConfigDisabledByImage(Invalid):\n msg_fmt = _(\"Requested image %(image)s \"\n \"has automatic disk resize disabled.\")\n\n\nclass ImageNotFound(NotFound):\n msg_fmt = _(\"Image %(image_id)s could not be found.\")\n\n\nclass PreserveEphemeralNotSupported(Invalid):\n msg_fmt = _(\"The current driver does not support \"\n \"preserving ephemeral partitions.\")\n\n\n# NOTE(jruzicka): ImageNotFound is not a valid EC2 error code.\nclass ImageNotFoundEC2(ImageNotFound):\n msg_fmt = _(\"Image %(image_id)s could not be found. The nova EC2 API \"\n \"assigns image ids dynamically when they are listed for the \"\n \"first time. Have you listed image ids since adding this \"\n \"image?\")\n\n\nclass ProjectNotFound(NotFound):\n msg_fmt = _(\"Project %(project_id)s could not be found.\")\n\n\nclass StorageRepositoryNotFound(NotFound):\n msg_fmt = _(\"Cannot find SR to read/write VDI.\")\n\n\nclass InstanceMappingNotFound(NotFound):\n msg_fmt = _(\"Instance %(uuid)s has no mapping to a cell.\")\n\n\nclass NetworkDuplicated(Invalid):\n msg_fmt = _(\"Network %(network_id)s is duplicated.\")\n\n\nclass NetworkDhcpReleaseFailed(NovaException):\n msg_fmt = _(\"Failed to release IP %(address)s with MAC %(mac_address)s\")\n\n\nclass NetworkInUse(NovaException):\n msg_fmt = _(\"Network %(network_id)s is still in use.\")\n\n\nclass NetworkSetHostFailed(NovaException):\n msg_fmt = _(\"Network set host failed for network %(network_id)s.\")\n\n\nclass NetworkNotCreated(Invalid):\n msg_fmt = _(\"%(req)s is required to create a network.\")\n\n\nclass LabelTooLong(Invalid):\n msg_fmt = _(\"Maximum allowed length for 'label' is 255.\")\n\n\nclass InvalidIntValue(Invalid):\n msg_fmt = _(\"%(key)s must be an integer.\")\n\n\nclass InvalidCidr(Invalid):\n msg_fmt = _(\"%(cidr)s is not a valid ip network.\")\n\n\nclass InvalidAddress(Invalid):\n msg_fmt = _(\"%(address)s is not a valid ip address.\")\n\n\nclass AddressOutOfRange(Invalid):\n msg_fmt = _(\"%(address)s is not within %(cidr)s.\")\n\n\nclass DuplicateVlan(NovaException):\n msg_fmt = _(\"Detected existing vlan with id %(vlan)d\")\n code = 409\n\n\nclass CidrConflict(NovaException):\n msg_fmt = _('Requested cidr (%(cidr)s) conflicts '\n 'with existing cidr (%(other)s)')\n code = 409\n\n\nclass NetworkHasProject(NetworkInUse):\n msg_fmt = _('Network must be disassociated from project '\n '%(project_id)s before it can be deleted.')\n\n\nclass NetworkNotFound(NotFound):\n msg_fmt = _(\"Network %(network_id)s could not be found.\")\n\n\nclass PortNotFound(NotFound):\n msg_fmt = _(\"Port id %(port_id)s could not be found.\")\n\n\nclass NetworkNotFoundForBridge(NetworkNotFound):\n msg_fmt = _(\"Network could not be found for bridge %(bridge)s\")\n\n\nclass NetworkNotFoundForUUID(NetworkNotFound):\n msg_fmt = _(\"Network could not be found for uuid %(uuid)s\")\n\n\nclass NetworkNotFoundForCidr(NetworkNotFound):\n msg_fmt = _(\"Network could not be found with cidr %(cidr)s.\")\n\n\nclass NetworkNotFoundForInstance(NetworkNotFound):\n msg_fmt = _(\"Network could not be found for instance %(instance_id)s.\")\n\n\nclass NoNetworksFound(NotFound):\n msg_fmt = _(\"No networks defined.\")\n\n\nclass NoMoreNetworks(NovaException):\n msg_fmt = _(\"No more available networks.\")\n\n\nclass NetworkNotFoundForProject(NetworkNotFound):\n msg_fmt = _(\"Either network uuid %(network_uuid)s is not present or \"\n \"is not assigned to the project %(project_id)s.\")\n\n\nclass NetworkAmbiguous(Invalid):\n msg_fmt = _(\"More than one possible network found. Specify \"\n \"network ID(s) to select which one(s) to connect to.\")\n\n\nclass NetworkRequiresSubnet(Invalid):\n msg_fmt = _(\"Network %(network_uuid)s requires a subnet in order to boot\"\n \" instances on.\")\n\n\nclass ExternalNetworkAttachForbidden(Forbidden):\n msg_fmt = _(\"It is not allowed to create an interface on \"\n \"external network %(network_uuid)s\")\n\n\nclass NetworkMissingPhysicalNetwork(NovaException):\n msg_fmt = _(\"Physical network is missing for network %(network_uuid)s\")\n\n\nclass VifDetailsMissingVhostuserSockPath(Invalid):\n msg_fmt = _(\"vhostuser_sock_path not present in vif_details\"\n \" for vif %(vif_id)s\")\n\n\nclass VifDetailsMissingMacvtapParameters(Invalid):\n msg_fmt = _(\"Parameters %(missing_params)s not present in\"\n \" vif_details for vif %(vif_id)s. Check your Neutron\"\n \" configuration to validate that the macvtap parameters are\"\n \" correct.\")\n\n\nclass DatastoreNotFound(NotFound):\n msg_fmt = _(\"Could not find the datastore reference(s) which the VM uses.\")\n\n\nclass PortInUse(Invalid):\n msg_fmt = _(\"Port %(port_id)s is still in use.\")\n\n\nclass PortRequiresFixedIP(Invalid):\n msg_fmt = _(\"Port %(port_id)s requires a FixedIP in order to be used.\")\n\n\nclass PortNotUsable(Invalid):\n msg_fmt = _(\"Port %(port_id)s not usable for instance %(instance)s.\")\n\n\nclass PortNotFree(Invalid):\n msg_fmt = _(\"No free port available for instance %(instance)s.\")\n\n\nclass PortBindingFailed(Invalid):\n msg_fmt = _(\"Binding failed for port %(port_id)s, please check neutron \"\n \"logs for more information.\")\n\n\nclass FixedIpExists(NovaException):\n msg_fmt = _(\"Fixed ip %(address)s already exists.\")\n\n\nclass FixedIpNotFound(NotFound):\n msg_fmt = _(\"No fixed IP associated with id %(id)s.\")\n\n\nclass FixedIpNotFoundForAddress(FixedIpNotFound):\n msg_fmt = _(\"Fixed ip not found for address %(address)s.\")\n\n\nclass FixedIpNotFoundForInstance(FixedIpNotFound):\n msg_fmt = _(\"Instance %(instance_uuid)s has zero fixed ips.\")\n\n\nclass FixedIpNotFoundForNetworkHost(FixedIpNotFound):\n msg_fmt = _(\"Network host %(host)s has zero fixed ips \"\n \"in network %(network_id)s.\")\n\n\nclass FixedIpNotFoundForSpecificInstance(FixedIpNotFound):\n msg_fmt = _(\"Instance %(instance_uuid)s doesn't have fixed ip '%(ip)s'.\")\n\n\nclass FixedIpNotFoundForNetwork(FixedIpNotFound):\n msg_fmt = _(\"Fixed IP address (%(address)s) does not exist in \"\n \"network (%(network_uuid)s).\")\n\n\nclass FixedIpAssociateFailed(NovaException):\n msg_fmt = _(\"Fixed IP associate failed for network: %(net)s.\")\n\n\nclass FixedIpAlreadyInUse(NovaException):\n msg_fmt = _(\"Fixed IP address %(address)s is already in use on instance \"\n \"%(instance_uuid)s.\")\n\n\nclass FixedIpAssociatedWithMultipleInstances(NovaException):\n msg_fmt = _(\"More than one instance is associated with fixed ip address \"\n \"'%(address)s'.\")\n\n\nclass FixedIpInvalid(Invalid):\n msg_fmt = _(\"Fixed IP address %(address)s is invalid.\")\n\n\nclass NoMoreFixedIps(NovaException):\n ec2_code = 'UnsupportedOperation'\n msg_fmt = _(\"No fixed IP addresses available for network: %(net)s\")\n\n\nclass NoFixedIpsDefined(NotFound):\n msg_fmt = _(\"Zero fixed ips could be found.\")\n\n\nclass FloatingIpExists(NovaException):\n msg_fmt = _(\"Floating ip %(address)s already exists.\")\n\n\nclass FloatingIpNotFound(NotFound):\n ec2_code = \"UnsupportedOperation\"\n msg_fmt = _(\"Floating ip not found for id %(id)s.\")\n\n\nclass FloatingIpDNSExists(Invalid):\n msg_fmt = _(\"The DNS entry %(name)s already exists in domain %(domain)s.\")\n\n\nclass FloatingIpNotFoundForAddress(FloatingIpNotFound):\n msg_fmt = _(\"Floating ip not found for address %(address)s.\")\n\n\nclass FloatingIpNotFoundForHost(FloatingIpNotFound):\n msg_fmt = _(\"Floating ip not found for host %(host)s.\")\n\n\nclass FloatingIpMultipleFoundForAddress(NovaException):\n msg_fmt = _(\"Multiple floating ips are found for address %(address)s.\")\n\n\nclass FloatingIpPoolNotFound(NotFound):\n msg_fmt = _(\"Floating ip pool not found.\")\n safe = True\n\n\nclass NoMoreFloatingIps(FloatingIpNotFound):\n msg_fmt = _(\"Zero floating ips available.\")\n safe = True\n\n\nclass FloatingIpAssociated(NovaException):\n ec2_code = \"UnsupportedOperation\"\n msg_fmt = _(\"Floating ip %(address)s is associated.\")\n\n\nclass FloatingIpNotAssociated(NovaException):\n msg_fmt = _(\"Floating ip %(address)s is not associated.\")\n\n\nclass NoFloatingIpsDefined(NotFound):\n msg_fmt = _(\"Zero floating ips exist.\")\n\n\nclass NoFloatingIpInterface(NotFound):\n ec2_code = \"UnsupportedOperation\"\n msg_fmt = _(\"Interface %(interface)s not found.\")\n\n\nclass FloatingIpAllocateFailed(NovaException):\n msg_fmt = _(\"Floating IP allocate failed.\")\n\n\nclass FloatingIpAssociateFailed(NovaException):\n msg_fmt = _(\"Floating IP %(address)s association has failed.\")\n\n\nclass FloatingIpBadRequest(Invalid):\n ec2_code = \"UnsupportedOperation\"\n msg_fmt = _(\"The floating IP request failed with a BadRequest\")\n\n\nclass CannotDisassociateAutoAssignedFloatingIP(NovaException):\n ec2_code = \"UnsupportedOperation\"\n msg_fmt = _(\"Cannot disassociate auto assigned floating ip\")\n\n\nclass KeypairNotFound(NotFound):\n ec2_code = 'InvalidKeyPair.NotFound'\n msg_fmt = _(\"Keypair %(name)s not found for user %(user_id)s\")\n\n\nclass ServiceNotFound(NotFound):\n msg_fmt = _(\"Service %(service_id)s could not be found.\")\n\n\nclass ServiceBinaryExists(NovaException):\n msg_fmt = _(\"Service with host %(host)s binary %(binary)s exists.\")\n\n\nclass ServiceTopicExists(NovaException):\n msg_fmt = _(\"Service with host %(host)s topic %(topic)s exists.\")\n\n\nclass HostNotFound(NotFound):\n msg_fmt = _(\"Host %(host)s could not be found.\")\n\n\nclass ComputeHostNotFound(HostNotFound):\n msg_fmt = _(\"Compute host %(host)s could not be found.\")\n\n\nclass ComputeHostNotCreated(HostNotFound):\n msg_fmt = _(\"Compute host %(name)s needs to be created first\"\n \" before updating.\")\n\n\nclass HostBinaryNotFound(NotFound):\n msg_fmt = _(\"Could not find binary %(binary)s on host %(host)s.\")\n\n\nclass InvalidReservationExpiration(Invalid):\n msg_fmt = _(\"Invalid reservation expiration %(expire)s.\")\n\n\nclass InvalidQuotaValue(Invalid):\n msg_fmt = _(\"Change would make usage less than 0 for the following \"\n \"resources: %(unders)s\")\n\n\nclass InvalidQuotaMethodUsage(Invalid):\n msg_fmt = _(\"Wrong quota method %(method)s used on resource %(res)s\")\n\n\nclass QuotaNotFound(NotFound):\n msg_fmt = _(\"Quota could not be found\")\n\n\nclass QuotaExists(NovaException):\n msg_fmt = _(\"Quota exists for project %(project_id)s, \"\n \"resource %(resource)s\")\n\n\nclass QuotaResourceUnknown(QuotaNotFound):\n msg_fmt = _(\"Unknown quota resources %(unknown)s.\")\n\n\nclass ProjectUserQuotaNotFound(QuotaNotFound):\n msg_fmt = _(\"Quota for user %(user_id)s in project %(project_id)s \"\n \"could not be found.\")\n\n\nclass ProjectQuotaNotFound(QuotaNotFound):\n msg_fmt = _(\"Quota for project %(project_id)s could not be found.\")\n\n\nclass QuotaClassNotFound(QuotaNotFound):\n msg_fmt = _(\"Quota class %(class_name)s could not be found.\")\n\n\nclass QuotaUsageNotFound(QuotaNotFound):\n msg_fmt = _(\"Quota usage for project %(project_id)s could not be found.\")\n\n\nclass ReservationNotFound(QuotaNotFound):\n msg_fmt = _(\"Quota reservation %(uuid)s could not be found.\")\n\n\nclass OverQuota(NovaException):\n msg_fmt = _(\"Quota exceeded for resources: %(overs)s\")\n\n\nclass SecurityGroupNotFound(NotFound):\n msg_fmt = _(\"Security group %(security_group_id)s not found.\")\n\n\nclass SecurityGroupNotFoundForProject(SecurityGroupNotFound):\n msg_fmt = _(\"Security group %(security_group_id)s not found \"\n \"for project %(project_id)s.\")\n\n\nclass SecurityGroupNotFoundForRule(SecurityGroupNotFound):\n msg_fmt = _(\"Security group with rule %(rule_id)s not found.\")\n\n\nclass SecurityGroupExists(Invalid):\n ec2_code = 'InvalidGroup.Duplicate'\n msg_fmt = _(\"Security group %(security_group_name)s already exists \"\n \"for project %(project_id)s.\")\n\n\nclass SecurityGroupExistsForInstance(Invalid):\n msg_fmt = _(\"Security group %(security_group_id)s is already associated\"\n \" with the instance %(instance_id)s\")\n\n\nclass SecurityGroupNotExistsForInstance(Invalid):\n msg_fmt = _(\"Security group %(security_group_id)s is not associated with\"\n \" the instance %(instance_id)s\")\n\n\nclass SecurityGroupDefaultRuleNotFound(Invalid):\n msg_fmt = _(\"Security group default rule (%rule_id)s not found.\")\n\n\nclass SecurityGroupCannotBeApplied(Invalid):\n msg_fmt = _(\"Network requires port_security_enabled and subnet associated\"\n \" in order to apply security groups.\")\n\n\nclass SecurityGroupRuleExists(Invalid):\n ec2_code = 'InvalidPermission.Duplicate'\n msg_fmt = _(\"Rule already exists in group: %(rule)s\")\n\n\nclass NoUniqueMatch(NovaException):\n msg_fmt = _(\"No Unique Match Found.\")\n code = 409\n\n\nclass MigrationNotFound(NotFound):\n msg_fmt = _(\"Migration %(migration_id)s could not be found.\")\n\n\nclass MigrationNotFoundByStatus(MigrationNotFound):\n msg_fmt = _(\"Migration not found for instance %(instance_id)s \"\n \"with status %(status)s.\")\n\n\nclass ConsolePoolNotFound(NotFound):\n msg_fmt = _(\"Console pool %(pool_id)s could not be found.\")\n\n\nclass ConsolePoolExists(NovaException):\n msg_fmt = _(\"Console pool with host %(host)s, console_type \"\n \"%(console_type)s and compute_host %(compute_host)s \"\n \"already exists.\")\n\n\nclass ConsolePoolNotFoundForHostType(NotFound):\n msg_fmt = _(\"Console pool of type %(console_type)s \"\n \"for compute host %(compute_host)s \"\n \"on proxy host %(host)s not found.\")\n\n\nclass ConsoleNotFound(NotFound):\n msg_fmt = _(\"Console %(console_id)s could not be found.\")\n\n\nclass ConsoleNotFoundForInstance(ConsoleNotFound):\n msg_fmt = _(\"Console for instance %(instance_uuid)s could not be found.\")\n\n\nclass ConsoleNotFoundInPoolForInstance(ConsoleNotFound):\n msg_fmt = _(\"Console for instance %(instance_uuid)s \"\n \"in pool %(pool_id)s could not be found.\")\n\n\nclass ConsoleTypeInvalid(Invalid):\n msg_fmt = _(\"Invalid console type %(console_type)s\")\n\n\nclass ConsoleTypeUnavailable(Invalid):\n msg_fmt = _(\"Unavailable console type %(console_type)s.\")\n\n\nclass ConsolePortRangeExhausted(NovaException):\n msg_fmt = _(\"The console port range %(min_port)d-%(max_port)d is \"\n \"exhausted.\")\n\n\nclass FlavorNotFound(NotFound):\n msg_fmt = _(\"Flavor %(flavor_id)s could not be found.\")\n\n\nclass FlavorNotFoundByName(FlavorNotFound):\n msg_fmt = _(\"Flavor with name %(flavor_name)s could not be found.\")\n\n\nclass FlavorAccessNotFound(NotFound):\n msg_fmt = _(\"Flavor access not found for %(flavor_id)s / \"\n \"%(project_id)s combination.\")\n\n\nclass FlavorExtraSpecUpdateCreateFailed(NovaException):\n msg_fmt = _(\"Flavor %(id)d extra spec cannot be updated or created \"\n \"after %(retries)d retries.\")\n\n\nclass CellNotFound(NotFound):\n msg_fmt = _(\"Cell %(cell_name)s doesn't exist.\")\n\n\nclass CellExists(NovaException):\n msg_fmt = _(\"Cell with name %(name)s already exists.\")\n\n\nclass CellRoutingInconsistency(NovaException):\n msg_fmt = _(\"Inconsistency in cell routing: %(reason)s\")\n\n\nclass CellServiceAPIMethodNotFound(NotFound):\n msg_fmt = _(\"Service API method not found: %(detail)s\")\n\n\nclass CellTimeout(NotFound):\n msg_fmt = _(\"Timeout waiting for response from cell\")\n\n\nclass CellMaxHopCountReached(NovaException):\n msg_fmt = _(\"Cell message has reached maximum hop count: %(hop_count)s\")\n\n\nclass NoCellsAvailable(NovaException):\n msg_fmt = _(\"No cells available matching scheduling criteria.\")\n\n\nclass CellsUpdateUnsupported(NovaException):\n msg_fmt = _(\"Cannot update cells configuration file.\")\n\n\nclass InstanceUnknownCell(NotFound):\n msg_fmt = _(\"Cell is not known for instance %(instance_uuid)s\")\n\n\nclass SchedulerHostFilterNotFound(NotFound):\n msg_fmt = _(\"Scheduler Host Filter %(filter_name)s could not be found.\")\n\n\nclass FlavorExtraSpecsNotFound(NotFound):\n msg_fmt = _(\"Flavor %(flavor_id)s has no extra specs with \"\n \"key %(extra_specs_key)s.\")\n\n\nclass ComputeHostMetricNotFound(NotFound):\n msg_fmt = _(\"Metric %(name)s could not be found on the compute \"\n \"host node %(host)s.%(node)s.\")\n\n\nclass FileNotFound(NotFound):\n msg_fmt = _(\"File %(file_path)s could not be found.\")\n\n\nclass SwitchNotFoundForNetworkAdapter(NotFound):\n msg_fmt = _(\"Virtual switch associated with the \"\n \"network adapter %(adapter)s not found.\")\n\n\nclass NetworkAdapterNotFound(NotFound):\n msg_fmt = _(\"Network adapter %(adapter)s could not be found.\")\n\n\nclass ClassNotFound(NotFound):\n msg_fmt = _(\"Class %(class_name)s could not be found: %(exception)s\")\n\n\nclass InstanceTagNotFound(NotFound):\n msg_fmt = _(\"Instance %(instance_id)s has no tag '%(tag)s'\")\n\n\nclass RotationRequiredForBackup(NovaException):\n msg_fmt = _(\"Rotation param is required for backup image_type\")\n\n\nclass KeyPairExists(NovaException):\n ec2_code = 'InvalidKeyPair.Duplicate'\n msg_fmt = _(\"Key pair '%(key_name)s' already exists.\")\n\n\nclass InstanceExists(NovaException):\n msg_fmt = _(\"Instance %(name)s already exists.\")\n\n\nclass FlavorExists(NovaException):\n msg_fmt = _(\"Flavor with name %(name)s already exists.\")\n\n\nclass FlavorIdExists(NovaException):\n msg_fmt = _(\"Flavor with ID %(flavor_id)s already exists.\")\n\n\nclass FlavorAccessExists(NovaException):\n msg_fmt = _(\"Flavor access already exists for flavor %(flavor_id)s \"\n \"and project %(project_id)s combination.\")\n\n\nclass InvalidSharedStorage(NovaException):\n msg_fmt = _(\"%(path)s is not on shared storage: %(reason)s\")\n\n\nclass InvalidLocalStorage(NovaException):\n msg_fmt = _(\"%(path)s is not on local storage: %(reason)s\")\n\n\nclass StorageError(NovaException):\n msg_fmt = _(\"Storage error: %(reason)s\")\n\n\nclass MigrationError(NovaException):\n msg_fmt = _(\"Migration error: %(reason)s\")\n\n\nclass MigrationPreCheckError(MigrationError):\n msg_fmt = _(\"Migration pre-check error: %(reason)s\")\n\n\nclass MalformedRequestBody(NovaException):\n msg_fmt = _(\"Malformed message body: %(reason)s\")\n\n\n# NOTE(johannes): NotFound should only be used when a 404 error is\n# appropriate to be returned\nclass ConfigNotFound(NovaException):\n msg_fmt = _(\"Could not find config at %(path)s\")\n\n\nclass PasteAppNotFound(NovaException):\n msg_fmt = _(\"Could not load paste app '%(name)s' from %(path)s\")\n\n\nclass CannotResizeToSameFlavor(NovaException):\n msg_fmt = _(\"When resizing, instances must change flavor!\")\n\n\nclass ResizeError(NovaException):\n msg_fmt = _(\"Resize error: %(reason)s\")\n\n\nclass CannotResizeDisk(NovaException):\n msg_fmt = _(\"Server disk was unable to be resized because: %(reason)s\")\n\n\nclass FlavorMemoryTooSmall(NovaException):\n msg_fmt = _(\"Flavor's memory is too small for requested image.\")\n\n\nclass FlavorDiskTooSmall(NovaException):\n msg_fmt = _(\"The created instance's disk would be too small.\")\n\n\nclass FlavorDiskSmallerThanImage(FlavorDiskTooSmall):\n msg_fmt = _(\"Flavor's disk is too small for requested image. Flavor disk \"\n \"is %(flavor_size)i bytes, image is %(image_size)i bytes.\")\n\n\nclass FlavorDiskSmallerThanMinDisk(FlavorDiskTooSmall):\n msg_fmt = _(\"Flavor's disk is smaller than the minimum size specified in \"\n \"image metadata. Flavor disk is %(flavor_size)i bytes, \"\n \"minimum size is %(image_min_disk)i bytes.\")\n\n\nclass VolumeSmallerThanMinDisk(FlavorDiskTooSmall):\n msg_fmt = _(\"Volume is smaller than the minimum size specified in image \"\n \"metadata. Volume size is %(volume_size)i bytes, minimum \"\n \"size is %(image_min_disk)i bytes.\")\n\n\nclass InsufficientFreeMemory(NovaException):\n msg_fmt = _(\"Insufficient free memory on compute node to start %(uuid)s.\")\n\n\nclass NoValidHost(NovaException):\n msg_fmt = _(\"No valid host was found. %(reason)s\")\n\n\nclass MaxRetriesExceeded(NoValidHost):\n msg_fmt = _(\"Exceeded maximum number of retries. %(reason)s\")\n\n\nclass QuotaError(NovaException):\n ec2_code = 'ResourceLimitExceeded'\n msg_fmt = _(\"Quota exceeded: code=%(code)s\")\n # NOTE(cyeoh): 413 should only be used for the ec2 API\n # The error status code for out of quota for the nova api should be\n # 403 Forbidden.\n code = 413\n headers = {'Retry-After': 0}\n safe = True\n\n\nclass TooManyInstances(QuotaError):\n msg_fmt = _(\"Quota exceeded for %(overs)s: Requested %(req)s,\"\n \" but already used %(used)s of %(allowed)s %(overs)s\")\n\n\nclass FloatingIpLimitExceeded(QuotaError):\n msg_fmt = _(\"Maximum number of floating ips exceeded\")\n\n\nclass FixedIpLimitExceeded(QuotaError):\n msg_fmt = _(\"Maximum number of fixed ips exceeded\")\n\n\nclass MetadataLimitExceeded(QuotaError):\n msg_fmt = _(\"Maximum number of metadata items exceeds %(allowed)d\")\n\n\nclass OnsetFileLimitExceeded(QuotaError):\n msg_fmt = _(\"Personality file limit exceeded\")\n\n\nclass OnsetFilePathLimitExceeded(OnsetFileLimitExceeded):\n msg_fmt = _(\"Personality file path too long\")\n\n\nclass OnsetFileContentLimitExceeded(OnsetFileLimitExceeded):\n msg_fmt = _(\"Personality file content too long\")\n\n\nclass KeypairLimitExceeded(QuotaError):\n msg_fmt = _(\"Maximum number of key pairs exceeded\")\n\n\nclass SecurityGroupLimitExceeded(QuotaError):\n ec2_code = 'SecurityGroupLimitExceeded'\n msg_fmt = _(\"Maximum number of security groups or rules exceeded\")\n\n\nclass PortLimitExceeded(QuotaError):\n msg_fmt = _(\"Maximum number of ports exceeded\")\n\n\nclass AggregateError(NovaException):\n msg_fmt = _(\"Aggregate %(aggregate_id)s: action '%(action)s' \"\n \"caused an error: %(reason)s.\")\n\n\nclass AggregateNotFound(NotFound):\n msg_fmt = _(\"Aggregate %(aggregate_id)s could not be found.\")\n\n\nclass AggregateNameExists(NovaException):\n msg_fmt = _(\"Aggregate %(aggregate_name)s already exists.\")\n\n\nclass AggregateHostNotFound(NotFound):\n msg_fmt = _(\"Aggregate %(aggregate_id)s has no host %(host)s.\")\n\n\nclass AggregateMetadataNotFound(NotFound):\n msg_fmt = _(\"Aggregate %(aggregate_id)s has no metadata with \"\n \"key %(metadata_key)s.\")\n\n\nclass AggregateHostExists(NovaException):\n msg_fmt = _(\"Aggregate %(aggregate_id)s already has host %(host)s.\")\n\n\nclass FlavorCreateFailed(NovaException):\n msg_fmt = _(\"Unable to create flavor\")\n\n\nclass InstancePasswordSetFailed(NovaException):\n msg_fmt = _(\"Failed to set admin password on %(instance)s \"\n \"because %(reason)s\")\n safe = True\n\n\nclass InstanceNotFound(NotFound):\n ec2_code = 'InvalidInstanceID.NotFound'\n msg_fmt = _(\"Instance %(instance_id)s could not be found.\")\n\n\nclass InstanceInfoCacheNotFound(NotFound):\n msg_fmt = _(\"Info cache for instance %(instance_uuid)s could not be \"\n \"found.\")\n\n\nclass InvalidAssociation(NotFound):\n ec2_code = 'InvalidAssociationID.NotFound'\n msg_fmt = _(\"Invalid association.\")\n\n\nclass MarkerNotFound(NotFound):\n msg_fmt = _(\"Marker %(marker)s could not be found.\")\n\n\nclass InvalidInstanceIDMalformed(Invalid):\n msg_fmt = _(\"Invalid id: %(instance_id)s (expecting \\\"i-...\\\")\")\n ec2_code = 'InvalidInstanceID.Malformed'\n\n\nclass InvalidVolumeIDMalformed(Invalid):\n msg_fmt = _(\"Invalid id: %(volume_id)s (expecting \\\"i-...\\\")\")\n ec2_code = 'InvalidVolumeID.Malformed'\n\n\nclass CouldNotFetchImage(NovaException):\n msg_fmt = _(\"Could not fetch image %(image_id)s\")\n\n\nclass CouldNotUploadImage(NovaException):\n msg_fmt = _(\"Could not upload image %(image_id)s\")\n\n\nclass TaskAlreadyRunning(NovaException):\n msg_fmt = _(\"Task %(task_name)s is already running on host %(host)s\")\n\n\nclass TaskNotRunning(NovaException):\n msg_fmt = _(\"Task %(task_name)s is not running on host %(host)s\")\n\n\nclass InstanceIsLocked(InstanceInvalidState):\n msg_fmt = _(\"Instance %(instance_uuid)s is locked\")\n\n\nclass ConfigDriveInvalidValue(Invalid):\n msg_fmt = _(\"Invalid value for Config Drive option: %(option)s\")\n\n\nclass ConfigDriveMountFailed(NovaException):\n msg_fmt = _(\"Could not mount vfat config drive. %(operation)s failed. \"\n \"Error: %(error)s\")\n\n\nclass ConfigDriveUnknownFormat(NovaException):\n msg_fmt = _(\"Unknown config drive format %(format)s. Select one of \"\n \"iso9660 or vfat.\")\n\n\nclass InterfaceAttachFailed(Invalid):\n msg_fmt = _(\"Failed to attach network adapter device to \"\n \"%(instance_uuid)s\")\n\n\nclass InterfaceDetachFailed(Invalid):\n msg_fmt = _(\"Failed to detach network adapter device from \"\n \"%(instance_uuid)s\")\n\n\nclass InstanceUserDataTooLarge(NovaException):\n msg_fmt = _(\"User data too large. User data must be no larger than \"\n \"%(maxsize)s bytes once base64 encoded. Your data is \"\n \"%(length)d bytes\")\n\n\nclass InstanceUserDataMalformed(NovaException):\n msg_fmt = _(\"User data needs to be valid base 64.\")\n\n\nclass InstanceUpdateConflict(NovaException):\n msg_fmt = _(\"Conflict updating instance %(instance_uuid)s. \"\n \"Expected: %(expected)s. Actual: %(actual)s\")\n\n\nclass UnknownInstanceUpdateConflict(InstanceUpdateConflict):\n msg_fmt = _(\"Conflict updating instance %(instance_uuid)s, but we were \"\n \"unable to determine the cause\")\n\n\nclass UnexpectedTaskStateError(InstanceUpdateConflict):\n pass\n\n\nclass UnexpectedDeletingTaskStateError(UnexpectedTaskStateError):\n pass\n\n\nclass InstanceActionNotFound(NovaException):\n msg_fmt = _(\"Action for request_id %(request_id)s on instance\"\n \" %(instance_uuid)s not found\")\n\n\nclass InstanceActionEventNotFound(NovaException):\n msg_fmt = _(\"Event %(event)s not found for action id %(action_id)s\")\n\n\nclass CryptoCAFileNotFound(FileNotFound):\n msg_fmt = _(\"The CA file for %(project)s could not be found\")\n\n\nclass CryptoCRLFileNotFound(FileNotFound):\n msg_fmt = _(\"The CRL file for %(project)s could not be found\")\n\n\nclass InstanceRecreateNotSupported(Invalid):\n msg_fmt = _('Instance recreate is not supported.')\n\n\nclass ServiceGroupUnavailable(NovaException):\n msg_fmt = _(\"The service from servicegroup driver %(driver)s is \"\n \"temporarily unavailable.\")\n\n\nclass DBNotAllowed(NovaException):\n msg_fmt = _('%(binary)s attempted direct database access which is '\n 'not allowed by policy')\n\n\nclass UnsupportedVirtType(Invalid):\n msg_fmt = _(\"Virtualization type '%(virt)s' is not supported by \"\n \"this compute driver\")\n\n\nclass UnsupportedHardware(Invalid):\n msg_fmt = _(\"Requested hardware '%(model)s' is not supported by \"\n \"the '%(virt)s' virt driver\")\n\n\nclass Base64Exception(NovaException):\n msg_fmt = _(\"Invalid Base 64 data for file %(path)s\")\n\n\nclass BuildAbortException(NovaException):\n msg_fmt = _(\"Build of instance %(instance_uuid)s aborted: %(reason)s\")\n\n\nclass RescheduledException(NovaException):\n msg_fmt = _(\"Build of instance %(instance_uuid)s was re-scheduled: \"\n \"%(reason)s\")\n\n\nclass ShadowTableExists(NovaException):\n msg_fmt = _(\"Shadow table with name %(name)s already exists.\")\n\n\nclass InstanceFaultRollback(NovaException):\n def __init__(self, inner_exception=None):\n message = _(\"Instance rollback performed due to: %s\")\n self.inner_exception = inner_exception\n super(InstanceFaultRollback, self).__init__(message % inner_exception)\n\n\nclass OrphanedObjectError(NovaException):\n msg_fmt = _('Cannot call %(method)s on orphaned %(objtype)s object')\n\n\nclass ObjectActionError(NovaException):\n msg_fmt = _('Object action %(action)s failed because: %(reason)s')\n\n\nclass CoreAPIMissing(NovaException):\n msg_fmt = _(\"Core API extensions are missing: %(missing_apis)s\")\n\n\nclass AgentError(NovaException):\n msg_fmt = _('Error during following call to agent: %(method)s')\n\n\nclass AgentTimeout(AgentError):\n msg_fmt = _('Unable to contact guest agent. '\n 'The following call timed out: %(method)s')\n\n\nclass AgentNotImplemented(AgentError):\n msg_fmt = _('Agent does not support the call: %(method)s')\n\n\nclass InstanceGroupNotFound(NotFound):\n msg_fmt = _(\"Instance group %(group_uuid)s could not be found.\")\n\n\nclass InstanceGroupIdExists(NovaException):\n msg_fmt = _(\"Instance group %(group_uuid)s already exists.\")\n\n\nclass InstanceGroupMemberNotFound(NotFound):\n msg_fmt = _(\"Instance group %(group_uuid)s has no member with \"\n \"id %(instance_id)s.\")\n\n\nclass InstanceGroupPolicyNotFound(NotFound):\n msg_fmt = _(\"Instance group %(group_uuid)s has no policy %(policy)s.\")\n\n\nclass InstanceGroupSaveException(NovaException):\n msg_fmt = _(\"%(field)s should not be part of the updates.\")\n\n\nclass PluginRetriesExceeded(NovaException):\n msg_fmt = _(\"Number of retries to plugin (%(num_retries)d) exceeded.\")\n\n\nclass ImageDownloadModuleError(NovaException):\n msg_fmt = _(\"There was an error with the download module %(module)s. \"\n \"%(reason)s\")\n\n\nclass ImageDownloadModuleMetaDataError(ImageDownloadModuleError):\n msg_fmt = _(\"The metadata for this location will not work with this \"\n \"module %(module)s. %(reason)s.\")\n\n\nclass ImageDownloadModuleNotImplementedError(ImageDownloadModuleError):\n msg_fmt = _(\"The method %(method_name)s is not implemented.\")\n\n\nclass ImageDownloadModuleConfigurationError(ImageDownloadModuleError):\n msg_fmt = _(\"The module %(module)s is misconfigured: %(reason)s.\")\n\n\nclass ResourceMonitorError(NovaException):\n msg_fmt = _(\"Error when creating resource monitor: %(monitor)s\")\n\n\nclass PciDeviceWrongAddressFormat(NovaException):\n msg_fmt = _(\"The PCI address %(address)s has an incorrect format.\")\n\n\nclass PciDeviceInvalidAddressField(NovaException):\n msg_fmt = _(\"Invalid PCI Whitelist: \"\n \"The PCI address %(address)s has an invalid %(field)s.\")\n\n\nclass PciDeviceInvalidDeviceName(NovaException):\n msg_fmt = _(\"Invalid PCI Whitelist: \"\n \"The PCI whitelist can specify devname or address,\"\n \" but not both\")\n\n\nclass PciDeviceNotFoundById(NotFound):\n msg_fmt = _(\"PCI device %(id)s not found\")\n\n\nclass PciDeviceNotFound(NotFound):\n msg_fmt = _(\"PCI Device %(node_id)s:%(address)s not found.\")\n\n\nclass PciDeviceInvalidStatus(Invalid):\n msg_fmt = _(\n \"PCI device %(compute_node_id)s:%(address)s is %(status)s \"\n \"instead of %(hopestatus)s\")\n\n\nclass PciDeviceInvalidOwner(Invalid):\n msg_fmt = _(\n \"PCI device %(compute_node_id)s:%(address)s is owned by %(owner)s \"\n \"instead of %(hopeowner)s\")\n\n\nclass PciDeviceRequestFailed(NovaException):\n msg_fmt = _(\n \"PCI device request (%requests)s failed\")\n\n\nclass PciDevicePoolEmpty(NovaException):\n msg_fmt = _(\n \"Attempt to consume PCI device %(compute_node_id)s:%(address)s \"\n \"from empty pool\")\n\n\nclass PciInvalidAlias(Invalid):\n msg_fmt = _(\"Invalid PCI alias definition: %(reason)s\")\n\n\nclass PciRequestAliasNotDefined(NovaException):\n msg_fmt = _(\"PCI alias %(alias)s is not defined\")\n\n\nclass MissingParameter(NovaException):\n ec2_code = 'MissingParameter'\n msg_fmt = _(\"Not enough parameters: %(reason)s\")\n code = 400\n\n\nclass PciConfigInvalidWhitelist(Invalid):\n msg_fmt = _(\"Invalid PCI devices Whitelist config %(reason)s\")\n\n\n# Cannot be templated, msg needs to be constructed when raised.\nclass InternalError(NovaException):\n ec2_code = 'InternalError'\n msg_fmt = \"%(err)s\"\n\n\nclass PciDevicePrepareFailed(NovaException):\n msg_fmt = _(\"Failed to prepare PCI device %(id)s for instance \"\n \"%(instance_uuid)s: %(reason)s\")\n\n\nclass PciDeviceDetachFailed(NovaException):\n msg_fmt = _(\"Failed to detach PCI device %(dev)s: %(reason)s\")\n\n\nclass PciDeviceUnsupportedHypervisor(NovaException):\n msg_fmt = _(\"%(type)s hypervisor does not support PCI devices\")\n\n\nclass KeyManagerError(NovaException):\n msg_fmt = _(\"Key manager error: %(reason)s\")\n\n\nclass VolumesNotRemoved(Invalid):\n msg_fmt = _(\"Failed to remove volume(s): (%(reason)s)\")\n\n\nclass InvalidVideoMode(Invalid):\n msg_fmt = _(\"Provided video model (%(model)s) is not supported.\")\n\n\nclass RngDeviceNotExist(Invalid):\n msg_fmt = _(\"The provided RNG device path: (%(path)s) is not \"\n \"present on the host.\")\n\n\nclass RequestedVRamTooHigh(NovaException):\n msg_fmt = _(\"The requested amount of video memory %(req_vram)d is higher \"\n \"than the maximum allowed by flavor %(max_vram)d.\")\n\n\nclass InvalidWatchdogAction(Invalid):\n msg_fmt = _(\"Provided watchdog action (%(action)s) is not supported.\")\n\n\nclass NoLiveMigrationForConfigDriveInLibVirt(NovaException):\n msg_fmt = _(\"Live migration of instances with config drives is not \"\n \"supported in libvirt unless libvirt instance path and \"\n \"drive data is shared across compute nodes.\")\n\n\nclass LiveMigrationWithOldNovaNotSafe(NovaException):\n msg_fmt = _(\"Host %(server)s is running an old version of Nova, \"\n \"live migrations involving that version may cause data loss. \"\n \"Upgrade Nova on %(server)s and try again.\")\n\n\nclass UnshelveException(NovaException):\n msg_fmt = _(\"Error during unshelve instance %(instance_id)s: %(reason)s\")\n\n\nclass ImageVCPULimitsRangeExceeded(Invalid):\n msg_fmt = _(\"Image vCPU limits %(sockets)d:%(cores)d:%(threads)d \"\n \"exceeds permitted %(maxsockets)d:%(maxcores)d:%(maxthreads)d\")\n\n\nclass ImageVCPUTopologyRangeExceeded(Invalid):\n msg_fmt = _(\"Image vCPU topology %(sockets)d:%(cores)d:%(threads)d \"\n \"exceeds permitted %(maxsockets)d:%(maxcores)d:%(maxthreads)d\")\n\n\nclass ImageVCPULimitsRangeImpossible(Invalid):\n msg_fmt = _(\"Requested vCPU limits %(sockets)d:%(cores)d:%(threads)d \"\n \"are impossible to satisfy for vcpus count %(vcpus)d\")\n\n\nclass InvalidArchitectureName(Invalid):\n msg_fmt = _(\"Architecture name '%(arch)s' is not recognised\")\n\n\nclass ImageNUMATopologyIncomplete(Invalid):\n msg_fmt = _(\"CPU and memory allocation must be provided for all \"\n \"NUMA nodes\")\n\n\nclass ImageNUMATopologyForbidden(Forbidden):\n msg_fmt = _(\"Image property '%(name)s' is not permitted to override \"\n \"NUMA configuration set against the flavor\")\n\n\nclass ImageNUMATopologyAsymmetric(Invalid):\n msg_fmt = _(\"Asymmetric NUMA topologies require explicit assignment \"\n \"of CPUs and memory to nodes in image or flavor\")\n\n\nclass ImageNUMATopologyCPUOutOfRange(Invalid):\n msg_fmt = _(\"CPU number %(cpunum)d is larger than max %(cpumax)d\")\n\n\nclass ImageNUMATopologyCPUDuplicates(Invalid):\n msg_fmt = _(\"CPU number %(cpunum)d is assigned to two nodes\")\n\n\nclass ImageNUMATopologyCPUsUnassigned(Invalid):\n msg_fmt = _(\"CPU number %(cpuset)s is not assigned to any node\")\n\n\nclass ImageNUMATopologyMemoryOutOfRange(Invalid):\n msg_fmt = _(\"%(memsize)d MB of memory assigned, but expected \"\n \"%(memtotal)d MB\")\n\n\nclass InvalidHostname(Invalid):\n msg_fmt = _(\"Invalid characters in hostname '%(hostname)s'\")\n\n\nclass NumaTopologyNotFound(NotFound):\n msg_fmt = _(\"Instance %(instance_uuid)s does not specify a NUMA topology\")\n\n\nclass MigrationContextNotFound(NotFound):\n msg_fmt = _(\"Instance %(instance_uuid)s does not specify a migration \"\n \"context.\")\n\n\nclass SocketPortRangeExhaustedException(NovaException):\n msg_fmt = _(\"Not able to acquire a free port for %(host)s\")\n\n\nclass SocketPortInUseException(NovaException):\n msg_fmt = _(\"Not able to bind %(host)s:%(port)d, %(error)s\")\n\n\nclass ImageSerialPortNumberInvalid(Invalid):\n msg_fmt = _(\"Number of serial ports '%(num_ports)s' specified in \"\n \"'%(property)s' isn't valid.\")\n\n\nclass ImageSerialPortNumberExceedFlavorValue(Invalid):\n msg_fmt = _(\"Forbidden to exceed flavor value of number of serial \"\n \"ports passed in image meta.\")\n\n\nclass InvalidImageConfigDrive(Invalid):\n msg_fmt = _(\"Image's config drive option '%(config_drive)s' is invalid\")\n\n\nclass InvalidHypervisorVirtType(Invalid):\n msg_fmt = _(\"Hypervisor virtualization type '%(hv_type)s' is not \"\n \"recognised\")\n\n\nclass InvalidVirtualMachineMode(Invalid):\n msg_fmt = _(\"Virtual machine mode '%(vmmode)s' is not recognised\")\n\n\nclass InvalidToken(Invalid):\n msg_fmt = _(\"The token '%(token)s' is invalid or has expired\")\n\n\nclass InvalidConnectionInfo(Invalid):\n msg_fmt = _(\"Invalid Connection Info\")\n\n\nclass InstanceQuiesceNotSupported(Invalid):\n msg_fmt = _('Quiescing is not supported in instance %(instance_id)s')\n\n\nclass QemuGuestAgentNotEnabled(Invalid):\n msg_fmt = _('QEMU guest agent is not enabled')\n\n\nclass SetAdminPasswdNotSupported(Invalid):\n msg_fmt = _('Set admin password is not supported')\n\n\nclass MemoryPageSizeInvalid(Invalid):\n msg_fmt = _(\"Invalid memory page size '%(pagesize)s'\")\n\n\nclass MemoryPageSizeForbidden(Invalid):\n msg_fmt = _(\"Page size %(pagesize)s forbidden against '%(against)s'\")\n\n\nclass MemoryPageSizeNotSupported(Invalid):\n msg_fmt = _(\"Page size %(pagesize)s is not supported by the host.\")\n\n\nclass CPUPinningNotSupported(Invalid):\n msg_fmt = _(\"CPU pinning is not supported by the host: \"\n \"%(reason)s\")\n\n\nclass CPUPinningInvalid(Invalid):\n msg_fmt = _(\"Cannot pin/unpin cpus %(requested)s from the following \"\n \"pinned set %(pinned)s\")\n\n\nclass CPUPinningUnknown(Invalid):\n msg_fmt = _(\"CPU set to pin/unpin %(requested)s must be a subset of \"\n \"known CPU set %(cpuset)s\")\n\n\nclass ImageCPUPinningForbidden(Forbidden):\n msg_fmt = _(\"Image property 'hw_cpu_policy' is not permitted to override \"\n \"CPU pinning policy set against the flavor\")\n\n\nclass UnsupportedPolicyException(Invalid):\n msg_fmt = _(\"ServerGroup policy is not supported: %(reason)s\")\n\n\nclass CellMappingNotFound(NotFound):\n msg_fmt = _(\"Cell %(uuid)s has no mapping.\")\n\n\nclass NUMATopologyUnsupported(Invalid):\n msg_fmt = _(\"Host does not support guests with NUMA topology set\")\n\n\nclass MemoryPagesUnsupported(Invalid):\n msg_fmt = _(\"Host does not support guests with custom memory page sizes\")\n\n\nclass EnumFieldInvalid(Invalid):\n msg_fmt = _('%(typename)s in %(fieldname)s is not an instance of Enum')\n\n\nclass EnumFieldUnset(Invalid):\n msg_fmt = _('%(fieldname)s missing field type')\n\n\nclass InvalidImageFormat(Invalid):\n msg_fmt = _(\"Invalid image format '%(format)s'\")\n\n\nclass UnsupportedImageModel(Invalid):\n msg_fmt = _(\"Image model '%(image)s' is not supported\")\n\n\nclass HostMappingNotFound(Invalid):\n msg_fmt = _(\"Host '%(name)s' is not mapped to any cell\")\n"},"license":{"kind":"string","value":"apache-2.0"},"hash":{"kind":"number","value":-6969698482296145000,"string":"-6,969,698,482,296,145,000"},"line_mean":{"kind":"number","value":28.0982599795,"string":"28.09826"},"line_max":{"kind":"number","value":79,"string":"79"},"alpha_frac":{"kind":"number","value":0.6728516656,"string":"0.672852"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.944363510232397,"string":"3.944364"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45133,"cells":{"repo_name":{"kind":"string","value":"google/ion"},"path":{"kind":"string","value":"ion/dev/doxygen_filter.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"8299"},"content":{"kind":"string","value":"#!/usr/bin/python\n#\n# Copyright 2017 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS-IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\"\"\"Doxygen pre-filter script for ion.\n\nThis filter processes code and adds Doxygen-compatible markup in various places\nto enable Doxygen to read the docs more fully. Unlike some other Doxygen\nfilters, it is designed to work with Doxygen's newer markdown syntax.\n\nIn order to ensure proper syntax coloring of indented code blocks, make sure\nthere is a blank (commented) line both above and below the block. For example:\n\n// Comment comment comment.\n//\n// int CodeBlock() {\n// Goes here;\n// }\n//\n// More comment.\n\"\"\"\n\n\nimport re\nimport sys\n\n\nclass DoxygenFormatter(object):\n \"\"\"Transforms lines of a source file to make them doxygen-friendly.\"\"\"\n\n ANYWHERE = 'anywhere'\n COMMENT = 'comment'\n\n def __init__(self, outfile):\n # The file-like object to which we will write lines.\n self.out = outfile\n\n # A buffer for storing empty lines which we can use later if we need to\n # retroactively insert markup without causing line number offset problems.\n self.empty_line_buffer = []\n\n # Whether we are currently inside an indented code block.\n self.in_code_block = False\n\n self.CompileExpressions()\n\n def CompileExpressions(self):\n \"\"\"Pre-compiles frequently used regexps for improved performance.\n\n The regexps are arranged as a list of 3-tuples, where the second value is\n the replacement string (which may include backreferences) and the third\n value is one of the context constants ANYWHERE or COMMENT. This is a list\n of tuples instead of a dictionary because order matters: earlier regexps\n will be applied first, and the resulting text (not the original) will be\n what is seen by subsequent regexps.\n \"\"\"\n self.comment_regex = re.compile(r'^\\s*//')\n\n self.substitutions = [\n # Remove copyright lines.\n (re.compile(r'^\\s*//\\s*[Cc]opyright.*Google.*'), r'', self.ANYWHERE),\n\n # Remove any comment lines that consist of only punctuation (banners).\n # We only allow a maximum of two spaces before the punctuation so we\n # don't accidentally get rid of code examples with bare braces and\n # whatnot.\n (re.compile(r'(^\\s*)//\\s{0,2}[-=#/]+$'), r'\\1//\\n', self.ANYWHERE),\n\n # If we find something that looks like a list item that is indented four\n # or more spaces, pull it back to the left so doxygen's Markdown engine\n # doesn't treat it like a code block.\n (re.compile(r'(^\\s*)//\\s{4,}([-\\d*].*)'), r'\\1 \\2', self.COMMENT),\n\n\n (re.compile(r'TODO'), r'@todo ', self.COMMENT),\n\n # Replace leading 'Note:' or 'Note that' in a comment with @note\n (re.compile(r'(\\/\\/\\s+)Note(?:\\:| that)', re.I), r'\\1@note',\n self.COMMENT),\n\n # Replace leading 'Warning:' in a comment with @warning\n (re.compile(r'(\\/\\/\\s+)Warning:', re.I), r'\\1@warning', self.COMMENT),\n\n # Replace leading 'Deprecated' in a comment with @deprecated\n (re.compile(r'(\\/\\/\\s+)Deprecated[^\\w\\s]*', re.I), r'\\1@deprecated',\n self.COMMENT),\n\n # Replace pipe-delimited parameter names with backtick-delimiters\n (re.compile(r'\\|(\\w+)\\|'), r'`\\1`', self.COMMENT),\n\n # Convert standalone comment lines to Doxygen style.\n (re.compile(r'(^\\s*)//(?=[^/])'), r'\\1///', self.ANYWHERE),\n\n # Strip trailing comments from preprocessor directives.\n (re.compile(r'(^#.*)//.*'), r'\\1', self.ANYWHERE),\n\n # Convert remaining trailing comments to doxygen style, unless they are\n # documenting the end of a block.\n (re.compile(r'([^} ]\\s+)//(?=[^/])'), r'\\1///<', self.ANYWHERE),\n ]\n\n def Transform(self, line):\n \"\"\"Performs the regexp transformations defined by self.substitutions.\n\n Args:\n line: The line to transform.\n\n Returns:\n The resulting line.\n \"\"\"\n for (regex, repl, where) in self.substitutions:\n if where is self.COMMENT and not self.comment_regex.match(line):\n return line\n line = regex.sub(repl, line)\n return line\n\n def AppendToBufferedLine(self, text):\n \"\"\"Appends text to the last buffered empty line.\n\n Empty lines are buffered rather than being written out directly. This lets\n us retroactively rewrite buffered lines to include markup that affects the\n following line, while avoiding the line number offset that would result from\n inserting a line that wasn't in the original source.\n\n Args:\n text: The text to append to the line.\n\n Returns:\n True if there was an available empty line to which text could be\n appended, and False otherwise.\n \"\"\"\n if self.empty_line_buffer:\n last_line = self.empty_line_buffer.pop().rstrip()\n last_line += text + '\\n'\n self.empty_line_buffer.append(last_line)\n return True\n else:\n return False\n\n def ConvertCodeBlock(self, line):\n \"\"\"Converts any code block that may begin or end on this line.\n\n Doxygen has (at least) two kinds of code blocks. Any block indented at\n least four spaces gets formatted as code, but (for some reason) no syntax\n highlighting is applied. Any block surrounded by \"~~~\" on both sides is\n also treated as code, but these are syntax highlighted intelligently\n depending on the file type. We typically write code blocks in the former\n style, but we'd like them to be highlighted, so this function converts them\n to the latter style by adding in the ~~~ lines.\n\n To make this a bit more complicated, we would really prefer not to insert\n new lines into the file, since that will make the line numbers shown in\n doxygen not match the line numbers in the actual source code. For this\n reason, we only perform the conversion if at least one \"blank\" line (empty\n comment line) appears before the start of the code block. If we get down to\n the bottom of the block and there's no blank line after it, we will be\n forced to add a line, since we can't go back and undo what we already did.\n\n Args:\n line: The line to process.\n\n Returns:\n The converted line.\n \"\"\"\n if not self.in_code_block and re.match(r'\\s*///\\s{4,}', line):\n if self.AppendToBufferedLine(' ~~~'):\n # If this fails, we'll just leave it un-highlighted.\n self.in_code_block = True\n elif self.in_code_block and not re.match(r'\\s*///\\s{4,}', line):\n if not self.AppendToBufferedLine(' ~~~'):\n # This is bad. We don't have a buffered line to use to end the code\n # block, so we'll have to insert one. This will cause the line\n # numbers to stop matching the original source, unfortunately.\n line = '/// ~~~\\n' + line\n self.in_code_block = False\n return line\n\n def ProcessLine(self, line):\n \"\"\"Processes a line.\n\n If the line is an empty line inside a comment, we buffer it for possible\n rewriting later on. Otherwise, we transform it using our regexps and\n write it (as well as any buffered blank lines) out to the output.\n\n Args:\n line: The line to process.\n \"\"\"\n line = self.Transform(line)\n\n if line.strip() == '///':\n # We may repurpose this empty line later, so don't write it out yet.\n self.empty_line_buffer.append(line)\n else:\n line = self.ConvertCodeBlock(line)\n # Flush the line buffer and write this line as well.\n for buffered_line in self.empty_line_buffer:\n self.out.write(buffered_line)\n self.empty_line_buffer = []\n self.out.write(line)\n\n\ndef main(argv):\n sourcefile = argv[1]\n with open(sourcefile, 'r') as infile:\n formatter = DoxygenFormatter(sys.stdout)\n for line in infile:\n formatter.ProcessLine(line)\n\n\nif __name__ == '__main__':\n main(sys.argv)\n\n"},"license":{"kind":"string","value":"apache-2.0"},"hash":{"kind":"number","value":6935754025838835000,"string":"6,935,754,025,838,835,000"},"line_mean":{"kind":"number","value":35.8844444444,"string":"35.884444"},"line_max":{"kind":"number","value":80,"string":"80"},"alpha_frac":{"kind":"number","value":0.6623689601,"string":"0.662369"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.920170051960321,"string":"3.92017"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45134,"cells":{"repo_name":{"kind":"string","value":"FlannelFox/FlannelFox"},"path":{"kind":"string","value":"tests/flannelfox/torrenttools/test_torrentQueue.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"1999"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\n\nimport unittest\nfrom unittest.mock import patch\nimport os\n\nfrom flannelfox.torrenttools.TorrentQueue import Queue\nfrom flannelfox.torrenttools import Torrents\n\nclass TestTorrentQueue(unittest.TestCase):\n\n\ttestDatabaseFile = 'ff.db'\n\n\tdef removeDatabase(self):\n\t\ttry:\n\t\t\tos.remove(self.testDatabaseFile)\n\t\texcept Exception:\n\t\t\tpass\n\n\t@patch.object(Queue, 'databaseTorrentBlacklisted')\n\t@patch.object(Queue, 'databaseTorrentExists')\n\tdef test_Queue(self, mockDatabaseTorrentExists, mockDatabaseTorrentBlacklisted):\n\n\t\tself.removeDatabase()\n\n\t\ttorrentQueue = Queue()\n\n\t\tmockDatabaseTorrentBlacklisted.return_value = False\n\t\tmockDatabaseTorrentExists.return_value = False\n\n\t\t# Ensure len returns a valid answer\n\t\tself.assertEqual(len(torrentQueue), 0)\n\n\t\t# Make sure appending an item works\n\t\ttorrentQueue.append(Torrents.TV(torrentTitle='some.show.s01e01.720p.junk.here'))\n\t\tself.assertEqual(len(torrentQueue), 1)\n\n\t\t# Make sure appending a duplicate item does not work\n\t\ttorrentQueue.append(Torrents.TV(torrentTitle='some.show.s01e01.720p.junk.here'))\n\t\tself.assertEqual(len(torrentQueue), 1)\n\n\t\t# Add a different item and make sure it works\n\t\ttorrentQueue.append(Torrents.TV(torrentTitle='some.show.s01e02.720p.junk.here2'))\n\t\tself.assertEqual(len(torrentQueue), 2)\n\n\t\tmockDatabaseTorrentBlacklisted.return_value = True\n\t\tmockDatabaseTorrentExists.return_value = False\n\n\t\t# Check if Blacklisted torrent gets blocked\n\t\ttorrentQueue.append(Torrents.TV(torrentTitle='some.show.s01e02.720p.junk.here3'))\n\t\tself.assertEqual(len(torrentQueue), 2)\n\n\n\t\tmockDatabaseTorrentBlacklisted.return_value = False\n\t\tmockDatabaseTorrentExists.return_value = True\n\n\t\t# Check if Existing Torrent in Database gets blocked\n\t\ttorrentQueue.append(Torrents.TV(torrentTitle='some.show.s01e02.720p.junk.here3'))\n\t\tself.assertEqual(len(torrentQueue), 2)\n\n\t\tmockDatabaseTorrentBlacklisted.return_value = False\n\t\tmockDatabaseTorrentExists.return_value = False\n\nif __name__ == '__main__':\n\tunittest.main()\n"},"license":{"kind":"string","value":"mit"},"hash":{"kind":"number","value":-7580618446876378000,"string":"-7,580,618,446,876,378,000"},"line_mean":{"kind":"number","value":29.7538461538,"string":"29.753846"},"line_max":{"kind":"number","value":83,"string":"83"},"alpha_frac":{"kind":"number","value":0.7803901951,"string":"0.78039"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.3996598639455784,"string":"3.39966"},"config_test":{"kind":"bool","value":true,"string":"true"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45135,"cells":{"repo_name":{"kind":"string","value":"vhosouza/invesalius3"},"path":{"kind":"string","value":"invesalius/gui/task_exporter.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"15556"},"content":{"kind":"string","value":"#--------------------------------------------------------------------------\n# Software: InVesalius - Software de Reconstrucao 3D de Imagens Medicas\n# Copyright: (C) 2001 Centro de Pesquisas Renato Archer\n# Homepage: http://www.softwarepublico.gov.br\n# Contact: invesalius@cti.gov.br\n# License: GNU - GPL 2 (LICENSE.txt/LICENCA.txt)\n#--------------------------------------------------------------------------\n# Este programa e software livre; voce pode redistribui-lo e/ou\n# modifica-lo sob os termos da Licenca Publica Geral GNU, conforme\n# publicada pela Free Software Foundation; de acordo com a versao 2\n# da Licenca.\n#\n# Este programa eh distribuido na expectativa de ser util, mas SEM\n# QUALQUER GARANTIA; sem mesmo a garantia implicita de\n# COMERCIALIZACAO ou de ADEQUACAO A QUALQUER PROPOSITO EM\n# PARTICULAR. Consulte a Licenca Publica Geral GNU para obter mais\n# detalhes.\n#--------------------------------------------------------------------------\n\nimport os\nimport pathlib\nimport sys\n\nimport wx\n\ntry:\n import wx.lib.agw.hyperlink as hl\nexcept ImportError:\n import wx.lib.hyperlink as hl\n\nimport wx.lib.platebtn as pbtn\nfrom pubsub import pub as Publisher\n\nimport invesalius.constants as const\nimport invesalius.gui.dialogs as dlg\nimport invesalius.project as proj\nimport invesalius.session as ses\n\nfrom invesalius import inv_paths\n\nBTN_MASK = wx.NewId()\nBTN_PICTURE = wx.NewId()\nBTN_SURFACE = wx.NewId()\nBTN_REPORT = wx.NewId()\nBTN_REQUEST_RP = wx.NewId()\n\nWILDCARD_SAVE_3D = \"Inventor (*.iv)|*.iv|\"\\\n \"PLY (*.ply)|*.ply|\"\\\n \"Renderman (*.rib)|*.rib|\"\\\n \"STL (*.stl)|*.stl|\"\\\n \"STL ASCII (*.stl)|*.stl|\"\\\n \"VRML (*.vrml)|*.vrml|\"\\\n \"VTK PolyData (*.vtp)|*.vtp|\"\\\n \"Wavefront (*.obj)|*.obj|\"\\\n \"X3D (*.x3d)|*.x3d\"\n\nINDEX_TO_TYPE_3D = {0: const.FILETYPE_IV,\n 1: const.FILETYPE_PLY,\n 2: const.FILETYPE_RIB,\n 3: const.FILETYPE_STL,\n 4: const.FILETYPE_STL_ASCII,\n 5: const.FILETYPE_VRML,\n 6: const.FILETYPE_VTP,\n 7: const.FILETYPE_OBJ,\n 8: const.FILETYPE_X3D}\nINDEX_TO_EXTENSION = {0: \"iv\",\n 1: \"ply\",\n 2: \"rib\",\n 3: \"stl\",\n 4: \"stl\",\n 5: \"vrml\",\n 6: \"vtp\",\n 7: \"obj\",\n 8: \"x3d\"}\n\nWILDCARD_SAVE_2D = \"BMP (*.bmp)|*.bmp|\"\\\n \"JPEG (*.jpg)|*.jpg|\"\\\n \"PNG (*.png)|*.png|\"\\\n \"PostScript (*.ps)|*.ps|\"\\\n \"Povray (*.pov)|*.pov|\"\\\n \"TIFF (*.tiff)|*.tiff\"\nINDEX_TO_TYPE_2D = {0: const.FILETYPE_BMP,\n 1: const.FILETYPE_JPG,\n 2: const.FILETYPE_PNG,\n 3: const.FILETYPE_PS,\n 4: const.FILETYPE_POV,\n 5: const.FILETYPE_OBJ}\n\nWILDCARD_SAVE_MASK = \"VTK ImageData (*.vti)|*.vti\"\n\n\nclass TaskPanel(wx.Panel):\n def __init__(self, parent):\n wx.Panel.__init__(self, parent)\n\n inner_panel = InnerTaskPanel(self)\n\n sizer = wx.BoxSizer(wx.VERTICAL)\n sizer.Add(inner_panel, 1, wx.EXPAND | wx.GROW | wx.BOTTOM | wx.RIGHT |\n wx.LEFT, 7)\n sizer.Fit(self)\n\n self.SetSizer(sizer)\n self.Update()\n self.SetAutoLayout(1)\n\nclass InnerTaskPanel(wx.Panel):\n\n def __init__(self, parent):\n wx.Panel.__init__(self, parent)\n backgroud_colour = wx.Colour(255,255,255)\n self.SetBackgroundColour(backgroud_colour)\n self.SetAutoLayout(1)\n\n # Counter for projects loaded in current GUI\n\n # Fixed hyperlink items\n tooltip = wx.ToolTip(_(\"Export InVesalius screen to an image file\"))\n link_export_picture = hl.HyperLinkCtrl(self, -1,\n _(\"Export picture...\"))\n link_export_picture.SetUnderlines(False, False, False)\n link_export_picture.SetBold(True)\n link_export_picture.SetColours(\"BLACK\", \"BLACK\", \"BLACK\")\n link_export_picture.SetBackgroundColour(self.GetBackgroundColour())\n link_export_picture.SetToolTip(tooltip)\n link_export_picture.AutoBrowse(False)\n link_export_picture.UpdateLink()\n link_export_picture.Bind(hl.EVT_HYPERLINK_LEFT,\n self.OnLinkExportPicture)\n\n tooltip = wx.ToolTip(_(\"Export 3D surface\"))\n link_export_surface = hl.HyperLinkCtrl(self, -1,_(\"Export 3D surface...\"))\n link_export_surface.SetUnderlines(False, False, False)\n link_export_surface.SetBold(True)\n link_export_surface.SetColours(\"BLACK\", \"BLACK\", \"BLACK\")\n link_export_surface.SetBackgroundColour(self.GetBackgroundColour())\n link_export_surface.SetToolTip(tooltip)\n link_export_surface.AutoBrowse(False)\n link_export_surface.UpdateLink()\n link_export_surface.Bind(hl.EVT_HYPERLINK_LEFT,\n self.OnLinkExportSurface)\n\n #tooltip = wx.ToolTip(_(\"Export 3D mask (voxels)\"))\n #link_export_mask = hl.HyperLinkCtrl(self, -1,_(\"Export mask...\"))\n #link_export_mask.SetUnderlines(False, False, False)\n #link_export_mask.SetColours(\"BLACK\", \"BLACK\", \"BLACK\")\n #link_export_mask.SetToolTip(tooltip)\n #link_export_mask.AutoBrowse(False)\n #link_export_mask.UpdateLink()\n #link_export_mask.Bind(hl.EVT_HYPERLINK_LEFT,\n # self.OnLinkExportMask)\n\n\n #tooltip = wx.ToolTip(\"Request rapid prototyping services\")\n #link_request_rp = hl.HyperLinkCtrl(self,-1,\"Request rapid prototyping...\")\n #link_request_rp.SetUnderlines(False, False, False)\n #link_request_rp.SetColours(\"BLACK\", \"BLACK\", \"BLACK\")\n #link_request_rp.SetToolTip(tooltip)\n #link_request_rp.AutoBrowse(False)\n #link_request_rp.UpdateLink()\n #link_request_rp.Bind(hl.EVT_HYPERLINK_LEFT, self.OnLinkRequestRP)\n\n #tooltip = wx.ToolTip(\"Open report tool...\")\n #link_report = hl.HyperLinkCtrl(self,-1,\"Open report tool...\")\n #link_report.SetUnderlines(False, False, False)\n #link_report.SetColours(\"BLACK\", \"BLACK\", \"BLACK\")\n #link_report.SetToolTip(tooltip)\n #link_report.AutoBrowse(False)\n #link_report.UpdateLink()\n #link_report.Bind(hl.EVT_HYPERLINK_LEFT, self.OnLinkReport)\n\n\n # Image(s) for buttons\n if sys.platform == 'darwin':\n BMP_EXPORT_SURFACE = wx.Bitmap(\\\n os.path.join(inv_paths.ICON_DIR, \"surface_export_original.png\"),\n wx.BITMAP_TYPE_PNG).ConvertToImage()\\\n .Rescale(25, 25).ConvertToBitmap()\n BMP_TAKE_PICTURE = wx.Bitmap(\\\n os.path.join(inv_paths.ICON_DIR, \"tool_photo_original.png\"),\n wx.BITMAP_TYPE_PNG).ConvertToImage()\\\n .Rescale(25, 25).ConvertToBitmap()\n\n #BMP_EXPORT_MASK = wx.Bitmap(\"../icons/mask.png\",\n # wx.BITMAP_TYPE_PNG)\n else:\n BMP_EXPORT_SURFACE = wx.Bitmap(os.path.join(inv_paths.ICON_DIR, \"surface_export.png\"),\n wx.BITMAP_TYPE_PNG).ConvertToImage()\\\n .Rescale(25, 25).ConvertToBitmap()\n\n BMP_TAKE_PICTURE = wx.Bitmap(os.path.join(inv_paths.ICON_DIR, \"tool_photo.png\"),\n wx.BITMAP_TYPE_PNG).ConvertToImage()\\\n .Rescale(25, 25).ConvertToBitmap()\n\n #BMP_EXPORT_MASK = wx.Bitmap(\"../icons/mask_small.png\",\n # wx.BITMAP_TYPE_PNG)\n\n\n\n # Buttons related to hyperlinks\n button_style = pbtn.PB_STYLE_SQUARE | pbtn.PB_STYLE_DEFAULT\n\n button_picture = pbtn.PlateButton(self, BTN_PICTURE, \"\",\n BMP_TAKE_PICTURE,\n style=button_style)\n button_picture.SetBackgroundColour(self.GetBackgroundColour())\n self.button_picture = button_picture\n\n button_surface = pbtn.PlateButton(self, BTN_SURFACE, \"\",\n BMP_EXPORT_SURFACE,\n style=button_style)\n button_surface.SetBackgroundColour(self.GetBackgroundColour())\n #button_mask = pbtn.PlateButton(self, BTN_MASK, \"\",\n # BMP_EXPORT_MASK,\n # style=button_style)\n #button_request_rp = pbtn.PlateButton(self, BTN_REQUEST_RP, \"\",\n # BMP_IMPORT, style=button_style)\n #button_report = pbtn.PlateButton(self, BTN_REPORT, \"\",\n # BMP_IMPORT,\n # style=button_style)\n\n # When using PlaneButton, it is necessary to bind events from parent win\n self.Bind(wx.EVT_BUTTON, self.OnButton)\n\n # Tags and grid sizer for fixed items\n flag_link = wx.EXPAND|wx.GROW|wx.LEFT|wx.TOP\n flag_button = wx.EXPAND | wx.GROW\n\n fixed_sizer = wx.FlexGridSizer(rows=2, cols=2, hgap=2, vgap=0)\n fixed_sizer.AddGrowableCol(0, 1)\n fixed_sizer.AddMany([ (link_export_picture, 1, flag_link, 3),\n (button_picture, 0, flag_button),\n (link_export_surface, 1, flag_link, 3),\n (button_surface, 0, flag_button),])\n #(link_export_mask, 1, flag_link, 3),\n #(button_mask, 0, flag_button)])\n #(link_report, 0, flag_link, 3),\n #(button_report, 0, flag_button),\n #(link_request_rp, 1, flag_link, 3),\n #(button_request_rp, 0, flag_button)])\n\n # Add line sizers into main sizer\n main_sizer = wx.BoxSizer(wx.VERTICAL)\n main_sizer.Add(fixed_sizer, 0, wx.GROW|wx.EXPAND)\n\n # Update main sizer and panel layout\n self.SetSizer(main_sizer)\n self.Fit()\n self.sizer = main_sizer\n self.__init_menu()\n\n def __init_menu(self):\n\n\n menu = wx.Menu()\n self.id_to_name = {const.AXIAL:_(\"Axial slice\"),\n const.CORONAL:_(\"Coronal slice\"),\n const.SAGITAL:_(\"Sagittal slice\"),\n const.VOLUME:_(\"Volume\")}\n\n for id in self.id_to_name:\n item = wx.MenuItem(menu, id, self.id_to_name[id])\n menu.Append(item)\n\n self.menu_picture = menu\n menu.Bind(wx.EVT_MENU, self.OnMenuPicture)\n\n def OnMenuPicture(self, evt):\n id = evt.GetId()\n value = dlg.ExportPicture(self.id_to_name[id])\n if value:\n filename, filetype = value\n Publisher.sendMessage('Export picture to file',\n orientation=id, filename=filename, filetype=filetype)\n\n\n\n def OnLinkExportPicture(self, evt=None):\n self.button_picture.PopupMenu(self.menu_picture)\n\n\n def OnLinkExportMask(self, evt=None):\n project = proj.Project()\n if sys.platform == 'win32':\n project_name = project.name\n else:\n project_name = project.name+\".vti\"\n\n\n dlg = wx.FileDialog(None,\n \"Save mask as...\", # title\n \"\", # last used directory\n project_name, # filename\n WILDCARD_SAVE_MASK,\n wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT)\n dlg.SetFilterIndex(0) # default is VTI\n\n if dlg.ShowModal() == wx.ID_OK:\n filename = dlg.GetPath()\n extension = \"vti\"\n if sys.platform != 'win32':\n if filename.split(\".\")[-1] != extension:\n filename = filename + \".\"+ extension\n filetype = const.FILETYPE_IMAGEDATA\n Publisher.sendMessage('Export mask to file',\n filename=filename,\n filetype=filetype)\n\n\n def OnLinkExportSurface(self, evt=None):\n \"OnLinkExportSurface\"\n project = proj.Project()\n n_surface = 0\n\n for index in project.surface_dict:\n if project.surface_dict[index].is_shown:\n n_surface += 1\n\n if n_surface:\n if sys.platform == 'win32':\n project_name = pathlib.Path(project.name).stem\n else:\n project_name = pathlib.Path(project.name).stem + \".stl\"\n\n session = ses.Session()\n last_directory = session.get('paths', 'last_directory_3d_surface', '')\n\n dlg = wx.FileDialog(None,\n _(\"Save 3D surface as...\"), # title\n last_directory, # last used directory\n project_name, # filename\n WILDCARD_SAVE_3D,\n wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT)\n dlg.SetFilterIndex(3) # default is STL\n\n if dlg.ShowModal() == wx.ID_OK:\n filetype_index = dlg.GetFilterIndex()\n filetype = INDEX_TO_TYPE_3D[filetype_index]\n filename = dlg.GetPath()\n extension = INDEX_TO_EXTENSION[filetype_index]\n if sys.platform != 'win32':\n if filename.split(\".\")[-1] != extension:\n filename = filename + \".\"+ extension\n\n if filename:\n session['paths']['last_directory_3d_surface'] = os.path.split(filename)[0]\n session.WriteSessionFile()\n\n Publisher.sendMessage('Export surface to file',\n filename=filename, filetype=filetype)\n if not os.path.exists(filename):\n dlg = wx.MessageDialog(None,\n _(\"It was not possible to save the surface.\"),\n _(\"Error saving surface\"),\n wx.OK | wx.ICON_ERROR)\n dlg.ShowModal()\n dlg.Destroy()\n else:\n dlg = wx.MessageDialog(None,\n _(\"You need to create a surface and make it \") +\n _(\"visible before exporting it.\"),\n 'InVesalius 3',\n wx.OK | wx.ICON_INFORMATION)\n try:\n dlg.ShowModal()\n finally:\n dlg.Destroy()\n\n def OnLinkRequestRP(self, evt=None):\n pass\n\n def OnLinkReport(self, evt=None):\n pass\n\n def OnButton(self, evt):\n id = evt.GetId()\n if id == BTN_PICTURE:\n self.OnLinkExportPicture()\n elif id == BTN_SURFACE:\n self.OnLinkExportSurface()\n elif id == BTN_REPORT:\n self.OnLinkReport()\n elif id == BTN_REQUEST_RP:\n self.OnLinkRequestRP()\n else:# id == BTN_MASK:\n self.OnLinkExportMask()\n"},"license":{"kind":"string","value":"gpl-2.0"},"hash":{"kind":"number","value":-955293151013029400,"string":"-955,293,151,013,029,400"},"line_mean":{"kind":"number","value":39.3005181347,"string":"39.300518"},"line_max":{"kind":"number","value":98,"string":"98"},"alpha_frac":{"kind":"number","value":0.5097711494,"string":"0.509771"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.917401158398388,"string":"3.917401"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45136,"cells":{"repo_name":{"kind":"string","value":"bmya/tkobr-addons"},"path":{"kind":"string","value":"tko_web_sessions_management/main.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"11671"},"content":{"kind":"string","value":"# -*- encoding: utf-8 -*-\n##############################################################################\n#\n# OpenERP, Open Source Management Solution\n# Copyright (C) 2004-2010 Tiny SPRL ().\n#\n# ThinkOpen Solutions Brasil\n# Copyright (C) Thinkopen Solutions .\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\nimport logging\nimport openerp\nfrom openerp.osv import fields, osv, orm\nimport pytz\nfrom datetime import date, datetime, time, timedelta\nfrom dateutil.relativedelta import *\nfrom openerp.addons.base.ir.ir_cron import _intervalTypes\nfrom openerp import SUPERUSER_ID\nfrom openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT\nfrom openerp.http import request\nfrom openerp.tools.translate import _\nfrom openerp import http\nimport werkzeug.contrib.sessions\nfrom openerp.http import Response\n# from openerp import pooler\n\n_logger = logging.getLogger(__name__)\n\n\nclass Home_tkobr(openerp.addons.web.controllers.main.Home):\n\n @http.route('/web/login', type='http', auth=\"none\")\n def web_login(self, redirect=None, **kw):\n openerp.addons.web.controllers.main.ensure_db()\n multi_ok = True\n calendar_set = 0\n calendar_ok = False\n calendar_group = ''\n unsuccessful_message = ''\n now = datetime.now()\n\n if request.httprequest.method == 'GET' and redirect and request.session.uid:\n return http.redirect_with_hash(redirect)\n\n if not request.uid:\n request.uid = openerp.SUPERUSER_ID\n\n values = request.params.copy()\n if not redirect:\n redirect = '/web?' + request.httprequest.query_string\n values['redirect'] = redirect\n\n try:\n values['databases'] = http.db_list()\n except openerp.exceptions.AccessDenied:\n values['databases'] = None\n\n if request.httprequest.method == 'POST':\n old_uid = request.uid\n uid = False\n if 'login' in request.params and 'password' in request.params:\n uid = request.session.authenticate(request.session.db, request.params[\n 'login'], request.params['password'])\n if uid is not False:\n user = request.registry.get('res.users').browse(\n request.cr, request.uid, uid, request.context)\n if not uid is SUPERUSER_ID:\n # check for multiple sessions block\n sessions = request.registry.get('ir.sessions').search(\n request.cr, request.uid, [\n ('user_id', '=', uid), ('logged_in', '=', True)], context=request.context)\n\n if sessions and user.multiple_sessions_block:\n multi_ok = False\n\n if multi_ok:\n # check calendars\n calendar_obj = request.registry.get(\n 'resource.calendar')\n attendance_obj = request.registry.get(\n 'resource.calendar.attendance')\n\n # GET USER LOCAL TIME\n if user.tz:\n tz = pytz.timezone(user.tz)\n else:\n tz = pytz.timezone('GMT')\n tzoffset = tz.utcoffset(now)\n now = now + tzoffset\n\n if user.login_calendar_id:\n calendar_set += 1\n # check user calendar\n attendances = attendance_obj.search(request.cr,\n request.uid, [('calendar_id', '=', user.login_calendar_id.id),\n ('dayofweek', '=', str(now.weekday())),\n ('hour_from', '<=', now.hour + now.minute / 60.0),\n ('hour_to', '>=', now.hour + now.minute / 60.0)],\n context=request.context)\n if attendances:\n calendar_ok = True\n else:\n unsuccessful_message = \"unsuccessful login from '%s', user time out of allowed calendar defined in user\" % request.params[\n 'login']\n else:\n # check user groups calendar\n for group in user.groups_id:\n if group.login_calendar_id:\n calendar_set += 1\n attendances = attendance_obj.search(request.cr,\n request.uid, [('calendar_id', '=', group.login_calendar_id.id),\n ('dayofweek', '=', str(now.weekday())),\n ('hour_from', '<=', now.hour + now.minute / 60.0),\n ('hour_to', '>=', now.hour + now.minute / 60.0)],\n context=request.context)\n if attendances:\n calendar_ok = True\n else:\n calendar_group = group.name\n if sessions and group.multiple_sessions_block and multi_ok:\n multi_ok = False\n unsuccessful_message = \"unsuccessful login from '%s', multisessions block defined in group '%s'\" % (\n request.params['login'], group.name)\n break\n if calendar_set > 0 and calendar_ok == False:\n unsuccessful_message = \"unsuccessful login from '%s', user time out of allowed calendar defined in group '%s'\" % (\n request.params['login'], calendar_group)\n else:\n unsuccessful_message = \"unsuccessful login from '%s', multisessions block defined in user\" % request.params[\n 'login']\n else:\n unsuccessful_message = \"unsuccessful login from '%s', wrong username or password\" % request.params[\n 'login']\n if not unsuccessful_message or uid is SUPERUSER_ID:\n self.save_session(\n request.cr,\n uid,\n user.tz,\n request.httprequest.session.sid,\n context=request.context)\n return http.redirect_with_hash(redirect)\n user = request.registry.get('res.users').browse(\n request.cr, SUPERUSER_ID, SUPERUSER_ID, request.context)\n self.save_session(\n request.cr,\n uid,\n user.tz,\n request.httprequest.session.sid,\n unsuccessful_message,\n request.context)\n _logger.error(unsuccessful_message)\n request.uid = old_uid\n values['error'] = 'Login failed due to one of the following reasons:'\n values['reason1'] = '- Wrong login/password'\n values['reason2'] = '- User not allowed to have multiple logins'\n values[\n 'reason3'] = '- User not allowed to login at this specific time or day'\n return request.render('web.login', values)\n\n def save_session(\n self,\n cr,\n uid,\n tz,\n sid,\n unsuccessful_message='',\n context=None):\n now = fields.datetime.now()\n session_obj = request.registry.get('ir.sessions')\n cr = request.registry.cursor()\n\n # for GeoIP\n geo_ip_resolver = None\n ip_location = \"\"\n\n try:\n import GeoIP\n geo_ip_resolver = GeoIP.open(\n '/usr/share/GeoIP/GeoIP.dat',\n GeoIP.GEOIP_STANDARD)\n except ImportError:\n geo_ip_resolver = False\n if geo_ip_resolver:\n ip_location = (str(geo_ip_resolver.country_name_by_addr(\n request.httprequest.remote_addr)) or \"\")\n\n # autocommit: our single update request will be performed atomically.\n # (In this way, there is no opportunity to have two transactions\n # interleaving their cr.execute()..cr.commit() calls and have one\n # of them rolled back due to a concurrent access.)\n cr.autocommit(True)\n user = request.registry.get('res.users').browse(\n cr, request.uid, uid, request.context)\n ip = request.httprequest.headers.environ['REMOTE_ADDR']\n logged_in = True\n if unsuccessful_message:\n uid = SUPERUSER_ID\n logged_in = False\n sessions = False\n else:\n sessions = session_obj.search(cr, uid, [('session_id', '=', sid),\n ('ip', '=', ip),\n ('user_id', '=', uid),\n ('logged_in', '=', True)],\n context=context)\n if not sessions:\n values = {\n 'user_id': uid,\n 'logged_in': logged_in,\n 'session_id': sid,\n 'session_seconds': user.session_default_seconds,\n 'multiple_sessions_block': user.multiple_sessions_block,\n 'date_login': now,\n 'expiration_date': datetime.strftime(\n (datetime.strptime(\n now,\n DEFAULT_SERVER_DATETIME_FORMAT) +\n relativedelta(\n seconds=user.session_default_seconds)),\n DEFAULT_SERVER_DATETIME_FORMAT),\n 'ip': ip,\n 'ip_location': ip_location,\n 'remote_tz': tz or 'GMT',\n 'unsuccessful_message': unsuccessful_message,\n }\n session_obj.create(cr, uid, values, context=context)\n cr.commit()\n cr.close()\n return True\n\n @http.route('/web/session/logout', type='http', auth=\"none\")\n def logout(self, redirect='/web'):\n request.session.logout(keep_db=True, logout_type='ul')\n return werkzeug.utils.redirect(redirect, 303)\n"},"license":{"kind":"string","value":"agpl-3.0"},"hash":{"kind":"number","value":-2443623195217171000,"string":"-2,443,623,195,217,171,000"},"line_mean":{"kind":"number","value":46.060483871,"string":"46.060484"},"line_max":{"kind":"number","value":154,"string":"154"},"alpha_frac":{"kind":"number","value":0.4762231171,"string":"0.476223"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":5.164159292035398,"string":"5.164159"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45137,"cells":{"repo_name":{"kind":"string","value":"limemadness/selenium_training"},"path":{"kind":"string","value":"test_countries_sort.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"2050"},"content":{"kind":"string","value":"import pytest\nfrom selenium import webdriver\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\n\n@pytest.fixture\n#def driver(request):\n# wd = webdriver.Firefox(firefox_binary=\"c:\\\\Program Files (x86)\\\\Mozilla Firefox\\\\firefox.exe\")\n# print(wd.capabilities)\n# request.addfinalizer(wd.quit)\n# return wd\ndef driver(request):\n wd = webdriver.Chrome()\n wd.implicitly_wait(10)\n request.addfinalizer(wd.quit)\n return wd\n\n\ndef test_countries_sort(driver):\n driver.get(\"http://localhost/litecart/admin/\")\n driver.find_element_by_name(\"username\").click()\n driver.find_element_by_name(\"username\").send_keys(\"admin\")\n driver.find_element_by_name(\"password\").click()\n driver.find_element_by_name(\"password\").send_keys(\"admin\")\n driver.find_element_by_xpath(\"//div[2]/button\").click()\n driver.get(\"http://localhost/litecart/admin/?app=countries&doc=countries\")\n #get country data\n countries = driver.find_elements_by_css_selector(\"#content tr.row\")\n countries_timezone_url = []\n country_name = []\n #verify alphabetical order of country names\n for country in countries:\n country_name.append(country.find_element_by_css_selector(\"td:nth-child(5)\").text)\n assert sorted(country_name) == country_name\n #get countries with multiple timezones\n for country in countries:\n if int(country.find_element_by_css_selector(\"td:nth-child(6)\").text) > 0:\n countries_timezone_url.append(country.find_element_by_css_selector(\"td:nth-child(5) a\").get_attribute(\"href\"))\n #verify alphabetical order of timezones\n for country_timezone_url in countries_timezone_url:\n driver.get(country_timezone_url)\n timezone_list = driver.find_elements_by_css_selector(\"#table-zones td:nth-child(2)\")\n del timezone_list[-1:]\n timezones = []\n for timezone in timezone_list:\n timezones.append(timezone.text)\n print(timezones)\n assert sorted(timezones) == timezones\n\n"},"license":{"kind":"string","value":"apache-2.0"},"hash":{"kind":"number","value":-2674985192745299500,"string":"-2,674,985,192,745,299,500"},"line_mean":{"kind":"number","value":40,"string":"40"},"line_max":{"kind":"number","value":122,"string":"122"},"alpha_frac":{"kind":"number","value":0.6990243902,"string":"0.699024"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.6936936936936937,"string":"3.693694"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45138,"cells":{"repo_name":{"kind":"string","value":"Beyond-Imagination/BlubBlub"},"path":{"kind":"string","value":"ChatbotServer/ChatbotEnv/Lib/site-packages/konlpy/corpus.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"1849"},"content":{"kind":"string","value":"#! /usr/bin/python2.7\n# -*- coding: utf-8 -*-\n\nimport os\n\nfrom . import utils\n\n\nclass CorpusLoader():\n \"\"\"Loader for corpora.\n For a complete list of corpora available in KoNLPy,\n refer to :ref:`corpora`.\n\n .. code-block:: python\n\n >>> from konlpy.corpus import kolaw\n >>> fids = kolaw.fileids()\n >>> fobj = kolaw.open(fids[0])\n >>> print fobj.read(140)\n 대한민국헌법\n\n 유구한 역사와 전통에 빛나는 우리 대한국민은 3·1운동으로 건립된 대한민국임시정부의 법통과 불의에 항거한 4·19민주이념을 계승하고, 조국의 민주개혁과 평화적 통일의 사명에 입각하여 정의·인도와 동포애로써 민족의 단결을 공고히 하고, 모든 사회적 폐습과 불의를 타파하며, 자율과 조화를 바 바\n \"\"\"\n\n def abspath(self, filename=None):\n \"\"\"Absolute path of corpus file.\n If ``filename`` is *None*, returns absolute path of corpus.\n\n :param filename: Name of a particular file in the corpus.\n \"\"\"\n basedir = '%s/data/corpus/%s' % (utils.installpath, self.name)\n if filename:\n return '%s/%s' % (basedir, filename)\n else:\n return '%s/' % basedir\n\n def fileids(self):\n \"\"\"List of file IDs in the corpus.\"\"\"\n return os.listdir(self.abspath())\n\n def open(self, filename):\n \"\"\"Method to open a file in the corpus.\n Returns a file object.\n\n :param filename: Name of a particular file in the corpus.\n \"\"\"\n return utils.load_txt(self.abspath(filename))\n\n def __init__(self, name=None):\n if not name:\n raise Exception(\"You need to input the name of the corpus\")\n else:\n self.name = name\n\n\nkolaw = CorpusLoader('kolaw')\nkobill = CorpusLoader('kobill')\n"},"license":{"kind":"string","value":"gpl-3.0"},"hash":{"kind":"number","value":3655224125584470500,"string":"3,655,224,125,584,470,500"},"line_mean":{"kind":"number","value":27.0350877193,"string":"27.035088"},"line_max":{"kind":"number","value":171,"string":"171"},"alpha_frac":{"kind":"number","value":0.5876095119,"string":"0.58761"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":2.201101928374656,"string":"2.201102"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45139,"cells":{"repo_name":{"kind":"string","value":"ErickMurillo/aprocacaho"},"path":{"kind":"string","value":"organizacion/admin.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"3456"},"content":{"kind":"string","value":"from django.contrib import admin\nfrom .models import *\n\n# Register your models here.\n#organizacion\nclass InlineEscuelaCampo(admin.TabularInline):\n model = EscuelaCampo\n extra = 1\n\nclass OrganizacionAdmin(admin.ModelAdmin):\n inlines = [InlineEscuelaCampo]\n list_display = ('id','nombre','siglas')\n list_display_links = ('id','nombre','siglas')\n\n#encuesta organizacion\nclass InlineAspectosJuridicos(admin.TabularInline):\n model = AspectosJuridicos\n max_num = 1\n can_delete = False\n\nclass InlineListaMiembros(admin.TabularInline):\n model = ListaMiembros\n extra = 1\n\nclass InlineDocumentacion(admin.TabularInline):\n model = Documentacion\n extra = 1\n max_num = 7\n\nclass InlineProduccionComercializacion(admin.TabularInline):\n model = ProduccionComercializacion\n extra = 1\n\nclass InlineNivelCumplimiento(admin.TabularInline):\n model = NivelCumplimiento\n extra = 1\n max_num = 7\n\n# class InlineDatosProductivos(admin.TabularInline):\n# model = DatosProductivos\n# extra = 1\n# max_num = 4\n#\n# class InlineDatosProductivosTabla(admin.TabularInline):\n# model = DatosProductivosTabla\n# extra = 1\n# max_num = 2\n\nclass InlineInfraestructura(admin.TabularInline):\n model = Infraestructura\n extra = 1\n\nclass InlineTransporte(admin.TabularInline):\n model = Transporte\n max_num = 1\n can_delete = False\n\n# class InlineComercializacion(admin.TabularInline):\n# model = Comercializacion\n# extra = 1\n# max_num = 3\n#\n# class InlineCacaoComercializado(admin.TabularInline):\n# model = CacaoComercializado\n# max_num = 1\n# can_delete = False\n\nclass InlineCertificacionOrg(admin.TabularInline):\n model = CertificacionOrg\n max_num = 1\n can_delete = False\n\nclass InlineDestinoProdCorriente(admin.TabularInline):\n model = DestinoProdCorriente\n extra = 1\n max_num = 4\n\nclass InlineDestinoProdFermentado(admin.TabularInline):\n model = DestinoProdFermentado\n extra = 1\n max_num = 4\n\nclass InlineFinanciamiento(admin.TabularInline):\n model = Financiamiento\n max_num = 1\n can_delete = False\n\nclass InlineFinanciamientoProductores(admin.TabularInline):\n model = FinanciamientoProductores\n extra = 1\n max_num = 5\n\nclass InlineInfoFinanciamiento(admin.TabularInline):\n model = InfoFinanciamiento\n extra = 1\n max_num = 4\n\nclass EncuestaOrganicacionAdmin(admin.ModelAdmin):\n # def get_queryset(self, request):\n # if request.user.is_superuser:\n # return EncuestaOrganicacion.objects.all()\n # return EncuestaOrganicacion.objects.filter(usuario=request.user)\n\n def save_model(self, request, obj, form, change):\n obj.usuario = request.user\n obj.save()\n\n inlines = [InlineAspectosJuridicos,InlineListaMiembros,InlineDocumentacion,\n InlineNivelCumplimiento,InlineProduccionComercializacion,\n InlineInfraestructura,InlineTransporte,\n InlineCertificacionOrg,InlineDestinoProdCorriente,InlineDestinoProdFermentado,\n InlineFinanciamiento,InlineFinanciamientoProductores,InlineInfoFinanciamiento]\n\n list_display = ('id','organizacion','fecha')\n list_display_links = ('id','organizacion')\n\n class Media:\n css = {\n 'all': ('css/admin.css',)\n }\n js = ('js/admin_org.js',)\n\n\nadmin.site.register(Organizacion,OrganizacionAdmin)\nadmin.site.register(EncuestaOrganicacion,EncuestaOrganicacionAdmin)\n"},"license":{"kind":"string","value":"mit"},"hash":{"kind":"number","value":-7994590496220483000,"string":"-7,994,590,496,220,483,000"},"line_mean":{"kind":"number","value":26.648,"string":"26.648"},"line_max":{"kind":"number","value":94,"string":"94"},"alpha_frac":{"kind":"number","value":0.7120949074,"string":"0.712095"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.167736021998167,"string":"3.167736"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45140,"cells":{"repo_name":{"kind":"string","value":"srio/shadow3-scripts"},"path":{"kind":"string","value":"transfocator_id30b.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"25823"},"content":{"kind":"string","value":"import numpy\nimport xraylib\n\n\"\"\"\ntransfocator_id30b : transfocator for id13b:\n It can:\n\n 1) guess the lens configuration (number of lenses for each type) for a given photon energy\n and target image size. Use transfocator_compute_configuration() for this task\n\n 2) for a given transfocator configuration, compute the main optical parameters\n (image size, focal distance, focal position and divergence).\n Use transfocator_compute_parameters() for this task\n\n 3) Performs full ray tracing. Use id30b_ray_tracing() for this task\n\n Note that for the optimization and parameters calculations the transfocator configuration is\n given in keywords. For ray tracing calculations many parameters of the transfocator are hard coded\n with the values of id30b\n\n See main program for examples.\n\n Dependencies:\n Numpy\n xraylib (to compute refracion indices)\n Shadow (for ray tracing only)\n matplotlib (for some plots of ray=tracing)\n\n Side effects:\n When running ray tracing some files are created.\n\n MODIFICATION HISTORY:\n 2015-03-25 srio@esrf.eu, written\n\n\"\"\"\n\n__author__ = \"Manuel Sanchez del Rio\"\n__contact__ = \"srio@esrf.eu\"\n__copyright__ = \"ESRF, 2015\"\n\n\ndef transfocator_compute_configuration(photon_energy_ev,s_target,\\\n symbol=[\"Be\",\"Be\",\"Be\"], density=[1.845,1.845,1.845],\\\n nlenses_max = [15,3,1], nlenses_radii = [500e-4,1000e-4,1500e-4], lens_diameter=0.05, \\\n sigmaz=6.46e-4, alpha = 0.55, \\\n tf_p=5960, tf_q=3800, verbose=1 ):\n \"\"\"\n Computes the optimum transfocator configuration for a given photon energy and target image size.\n\n All length units are cm\n\n :param photon_energy_ev: the photon energy in eV\n :param s_target: the target image size in cm.\n :param symbol: the chemical symbol of the lens material of each type. Default symbol=[\"Be\",\"Be\",\"Be\"]\n :param density: the density of each type of lens. Default: density=[1.845,1.845,1.845]\n :param nlenses_max: the maximum allowed number of lenases for each type of lens. nlenses_max = [15,3,1]\n :param nlenses_radii: the radii in cm of each type of lens. Default: nlenses_radii = [500e-4,1000e-4,1500e-4]\n :param lens_diameter: the physical diameter (acceptance) in cm of the lenses. If different for each type of lens,\n consider the smaller one. Default: lens_diameter=0.05\n :param sigmaz: the sigma (standard deviation) of the source in cm\n :param alpha: an adjustable parameter in [0,1](see doc). Default: 0.55 (it is 0.76 for pure Gaussian beams)\n :param tf_p: the distance source-transfocator in cm\n :param tf_q: the distance transfocator-image in cm\n :param:verbose: set to 1 for verbose text output\n :return: a list with the number of lenses of each type.\n\n \"\"\"\n if s_target < 2.35*sigmaz*tf_q/tf_p:\n print(\"Source size FWHM is: %f um\"%(1e4*2.35*sigmaz))\n print(\"Maximum Demagnifications is: %f um\"%(tf_p/tf_q))\n print(\"Minimum possible size is: %f um\"%(1e4*2.35*sigmaz*tf_q/tf_p))\n print(\"Error: redefine size\")\n return None\n\n deltas = [(1.0 - xraylib.Refractive_Index_Re(symbol[i],photon_energy_ev*1e-3,density[i])) \\\n for i in range(len(symbol))]\n\n focal_q_target = _tansfocator_guess_focal_position( s_target, p=tf_p, q=tf_q, sigmaz=sigmaz, alpha=alpha, \\\n lens_diameter=lens_diameter,method=2)\n\n focal_f_target = 1.0 / (1.0/focal_q_target + 1.0/tf_p)\n div_q_target = alpha * lens_diameter / focal_q_target\n\n #corrections for extreme cases\n source_demagnified = 2.35*sigmaz*focal_q_target/tf_p\n if source_demagnified > lens_diameter: source_demagnified = lens_diameter\n\n s_target_calc = numpy.sqrt( (div_q_target*(tf_q-focal_q_target))**2 + source_demagnified**2)\n\n nlenses_target = _transfocator_guess_configuration(focal_f_target,deltas=deltas,\\\n nlenses_max=nlenses_max,radii=nlenses_radii, )\n if verbose:\n print(\"transfocator_compute_configuration: focal_f_target: %f\"%(focal_f_target))\n print(\"transfocator_compute_configuration: focal_q_target: %f cm\"%(focal_q_target))\n print(\"transfocator_compute_configuration: s_target: %f um\"%(s_target_calc*1e4))\n print(\"transfocator_compute_configuration: nlenses_target: \",nlenses_target)\n\n return nlenses_target\n\ndef transfocator_compute_parameters(photon_energy_ev, nlenses_target,\\\n symbol=[\"Be\",\"Be\",\"Be\"], density=[1.845,1.845,1.845],\\\n nlenses_max = [15,3,1], nlenses_radii = [500e-4,1000e-4,1500e-4], lens_diameter=0.05, \\\n sigmaz=6.46e-4, alpha = 0.55, \\\n tf_p=5960, tf_q=3800 ):\n \"\"\"\n Computes the parameters of the optical performances of a given transgocator configuration.\n\n returns a l\n\n All length units are cm\n\n :param photon_energy_ev:\n :param nlenses_target: a list with the lens configuration, i.e. the number of lenses of each type.\n :param symbol: the chemical symbol of the lens material of each type. Default symbol=[\"Be\",\"Be\",\"Be\"]\n :param density: the density of each type of lens. Default: density=[1.845,1.845,1.845]\n :param nlenses_max: the maximum allowed number of lenases for each type of lens. nlenses_max = [15,3,1]\n TODO: remove (not used)\n :param nlenses_radii: the radii in cm of each type of lens. Default: nlenses_radii = [500e-4,1000e-4,1500e-4]\n :param lens_diameter: the physical diameter (acceptance) in cm of the lenses. If different for each type of lens,\n consider the smaller one. Default: lens_diameter=0.05\n :param sigmaz: the sigma (standard deviation) of the source in cm\n :param alpha: an adjustable parameter in [0,1](see doc). Default: 0.55 (it is 0.76 for pure Gaussian beams)\n :param tf_p: the distance source-transfocator in cm\n :param tf_q: the distance transfocator-image in cm\n :return: a list with parameters (image_siza, lens_focal_distance,\n focal_position from transfocator center, divergence of beam after the transfocator)\n \"\"\"\n\n deltas = [(1.0 - xraylib.Refractive_Index_Re(symbol[i],photon_energy_ev*1e-3,density[i])) \\\n for i in range(len(symbol))]\n focal_f = _transfocator_calculate_focal_distance( deltas=deltas,\\\n nlenses=nlenses_target,radii=nlenses_radii)\n focal_q = 1.0 / (1.0/focal_f - 1.0/tf_p)\n div_q = alpha * lens_diameter / focal_q\n #corrections\n source_demagnified = 2.35*sigmaz*focal_q/tf_p\n if source_demagnified > lens_diameter: source_demagnified = lens_diameter\n s_target = numpy.sqrt( (div_q*(tf_q-focal_q))**2 + (source_demagnified)**2 )\n return (s_target,focal_f,focal_q,div_q)\n\n\ndef transfocator_nlenses_to_slots(nlenses,nlenses_max=None):\n \"\"\"\n converts the transfocator configuration from a list of the number of lenses of each type,\n into a list of active (1) or inactive (0) actuators for the slots.\n\n :param nlenses: the list with number of lenses (e.g., [5,2,0]\n :param nlenses_max: the maximum number of lenses of each type, usually powers of two minus one.\n E.g. [15,3,1]\n :return: a list of on (1) and off (0) slots, e.g., [1, 0, 1, 0, 0, 1, 0]\n (first type: 1*1+0*2+1*4+0*8=5, second type: 0*1+1*2=2, third type: 0*1=0)\n \"\"\"\n if nlenses_max == None:\n nlenses_max = nlenses\n\n ss = []\n for i,iopt in enumerate(nlenses):\n if iopt > nlenses_max[i]:\n print(\"Error: i:%d, nlenses: %d, nlenses_max: %d\"%(i,iopt,nlenses_max[i]))\n ncharacters = len(\"{0:b}\".format(nlenses_max[i]))\n\n si = list( (\"{0:0%db}\"%(ncharacters)).format(int(iopt)) )\n si.reverse()\n ss += si\n\n on_off = [int(i) for i in ss]\n #print(\"transfocator_nlenses_to_slots: nlenses_max: \",nlenses_max,\" nlenses: \",nlenses,\" slots: \",on_off)\n return on_off\n\n\ndef _transfocator_calculate_focal_distance(deltas=[0.999998],nlenses=[1],radii=[500e-4]):\n\n inverse_focal_distance = 0.0\n for i,nlensesi in enumerate(nlenses):\n if nlensesi > 0:\n focal_distance_i = radii[i] / (2.*nlensesi*deltas[i])\n inverse_focal_distance += 1.0/focal_distance_i\n if inverse_focal_distance == 0:\n return 99999999999999999999999999.\n else:\n return 1.0/inverse_focal_distance\n\n\ndef _tansfocator_guess_focal_position( s_target, p=5960., q=3800.0, sigmaz=6.46e-4, \\\n alpha=0.66, lens_diameter=0.05, method=2):\n x = 1e15\n if method == 1: # simple sum\n AA = 2.35*sigmaz/p\n BB = -(s_target + alpha * lens_diameter)\n CC = alpha*lens_diameter*q\n\n cc = numpy.roots([AA,BB,CC])\n x = cc[1]\n return x\n\n if method == 2: # sum in quadrature\n AA = ( (2.35*sigmaz)**2)/(p**2)\n BB = 0.0\n CC = alpha**2 * lens_diameter**2 - s_target**2\n DD = - 2.0 * alpha**2 * lens_diameter**2 * q\n EE = alpha**2 * lens_diameter**2 * q**2\n cc = numpy.roots([AA,BB,CC,DD,EE])\n for i,cci in enumerate(cc):\n if numpy.imag(cci) == 0:\n return numpy.real(cci)\n\n return x\n\ndef _transfocator_guess_configuration(focal_f_target,deltas=[0.999998],nlenses_max=[15],radii=[500e-4]):\n\n nn = len(nlenses_max)\n\n ncombinations = (1+nlenses_max[0]) * (1+nlenses_max[1]) * (1+nlenses_max[2])\n\n icombinations = 0\n aa = numpy.zeros((3,ncombinations),dtype=int)\n bb = numpy.zeros(ncombinations)\n for i0 in range(1+nlenses_max[0]):\n for i1 in range(1+nlenses_max[1]):\n for i2 in range(1+nlenses_max[2]):\n aa[0,icombinations] = i0\n aa[1,icombinations] = i1\n aa[2,icombinations] = i2\n bb[icombinations] = focal_f_target - _transfocator_calculate_focal_distance(deltas=deltas,nlenses=[i0,i1,i2],radii=radii)\n icombinations += 1\n bb1 = numpy.abs(bb)\n ibest = bb1.argmin()\n\n return (aa[:,ibest]).tolist()\n\n\n#\n#\n#\n\ndef id30b_ray_tracing(emittH=4e-9,emittV=1e-11,betaH=35.6,betaV=3.0,number_of_rays=50000,\\\n density=1.845,symbol=\"Be\",tf_p=1000.0,tf_q=1000.0,lens_diameter=0.05,\\\n slots_max=None,slots_on_off=None,photon_energy_ev=14000.0,\\\n slots_lens_thickness=None,slots_steps=None,slots_radii=None,\\\n s_target=10e-4,focal_f=10.0,focal_q=10.0,div_q=1e-6):\n\n #=======================================================================================================================\n # Gaussian undulator source\n #=======================================================================================================================\n\n\n import Shadow\n #import Shadow.ShadowPreprocessorsXraylib as sx\n\n sigmaXp = numpy.sqrt(emittH/betaH)\n sigmaZp = numpy.sqrt(emittV/betaV)\n sigmaX = emittH/sigmaXp\n sigmaZ = emittV/sigmaZp\n\n print(\"\\n\\nElectron sizes H:%f um, V:%fu m;\\nelectron divergences: H:%f urad, V:%f urad\"%\\\n (sigmaX*1e6, sigmaZ*1e6, sigmaXp*1e6, sigmaZp*1e6))\n\n # set Gaussian source\n src = Shadow.Source()\n src.set_energy_monochromatic(photon_energy_ev)\n src.set_gauss(sigmaX*1e2,sigmaZ*1e2,sigmaXp,sigmaZp)\n\n print(\"\\n\\nElectron sizes stored H:%f um, V:%f um;\\nelectron divergences: H:%f urad, V:%f urad\"%\\\n (src.SIGMAX*1e4,src.SIGMAZ*1e4,src.SIGDIX*1e6,src.SIGDIZ*1e6))\n\n src.apply_gaussian_undulator(undulator_length_in_m=2.8, user_unit_to_m=1e-2, verbose=1)\n\n print(\"\\n\\nElectron sizes stored (undulator) H:%f um, V:%f um;\\nelectron divergences: H:%f urad, V:%f urad\"%\\\n (src.SIGMAX*1e4,src.SIGMAZ*1e4,src.SIGDIX*1e6,src.SIGDIZ*1e6))\n\n print(\"\\n\\nSource size in vertical FWHM: %f um\\n\"%\\\n (2.35*src.SIGMAZ*1e4))\n\n src.NPOINT = number_of_rays\n src.ISTAR1 = 0 # 677543155\n\n\n src.write(\"start.00\")\n\n # create source\n beam = Shadow.Beam()\n beam.genSource(src)\n beam.write(\"begin.dat\")\n src.write(\"end.00\")\n\n\n #=======================================================================================================================\n # complete the (detailed) transfocator description\n #=======================================================================================================================\n\n\n print(\"\\nSetting detailed Transfocator for ID30B\")\n\n\n\n slots_nlenses = numpy.array(slots_max)*numpy.array(slots_on_off)\n slots_empty = (numpy.array(slots_max)-slots_nlenses)\n\n #\n ####interactive=True, SYMBOL=\"SiC\",DENSITY=3.217,FILE=\"prerefl.dat\",E_MIN=100.0,E_MAX=20000.0,E_STEP=100.0\n\n\n Shadow.ShadowPreprocessorsXraylib.prerefl(interactive=False,E_MIN=2000.0,E_MAX=55000.0,E_STEP=100.0,\\\n DENSITY=density,SYMBOL=symbol,FILE=\"Be2_55.dat\" )\n\n nslots = len(slots_max)\n prerefl_file = [\"Be2_55.dat\" for i in range(nslots)]\n\n\n print(\"slots_max: \",slots_max)\n #print(\"slots_target: \",slots_target)\n print(\"slots_on_off: \",slots_on_off)\n print(\"slots_steps: \",slots_steps)\n print(\"slots_radii: \",slots_radii)\n print(\"slots_nlenses: \",slots_nlenses)\n print(\"slots_empty: \",slots_empty)\n\n\n #calculate distances, nlenses and slots_empty\n\n # these are distances p and q with TF length removed\n tf_length = numpy.array(slots_steps).sum() #tf length in cm\n tf_fs_before = tf_p - 0.5*tf_length #distance from source to center of transfocator\n tf_fs_after = tf_q - 0.5*tf_length # distance from center of transfocator to image\n\n # for each slot, these are the empty distances before and after the lenses\n tf_p0 = numpy.zeros(nslots)\n tf_q0 = numpy.array(slots_steps) - (numpy.array(slots_max) * slots_lens_thickness)\n # add now the p q distances\n tf_p0[0] += tf_fs_before\n tf_q0[-1] += tf_fs_after\n\n print(\"tf_p0: \",tf_p0)\n print(\"tf_q0: \",tf_q0)\n print(\"tf_length: %f cm\"%(tf_length))\n\n\n # build transfocator\n tf = Shadow.CompoundOE(name='TF ID30B')\n\n\n tf.append_transfocator(tf_p0.tolist(), tf_q0.tolist(), \\\n nlenses=slots_nlenses.tolist(), radius=slots_radii, slots_empty=slots_empty.tolist(),\\\n thickness=slots_lens_thickness, prerefl_file=prerefl_file,\\\n surface_shape=4, convex_to_the_beam=0, diameter=lens_diameter,\\\n cylinder_angle=0.0,interthickness=50e-4,use_ccc=0)\n\n\n itmp = input(\"SHADOW Source complete. Do you want to run SHADOR trace? [1=Yes,0=No]: \")\n if str(itmp) != \"1\":\n return\n\n #trace system\n tf.dump_systemfile()\n beam.traceCompoundOE(tf,write_start_files=0,write_end_files=0,write_star_files=0, write_mirr_files=0)\n\n #write only last result file\n beam.write(\"star_tf.dat\")\n print(\"\\nFile written to disk: star_tf.dat\")\n\n\n\n #\n # #ideal calculations\n #\n\n\n\n print(\"\\n\\n\\n\")\n print(\"=============================================== TRANSFOCATOR OUTPUTS ==========================================\")\n\n print(\"\\nTHEORETICAL results: \")\n\n print(\"REMIND-----With these lenses we obtained (analytically): \")\n print(\"REMIND----- focal_f: %f cm\"%(focal_f))\n print(\"REMIND----- focal_q: %f cm\"%(focal_q))\n print(\"REMIND----- s_target: %f um\"%(s_target*1e4))\n\n\n demagnification_factor = tf_p/focal_q\n theoretical_focal_size = src.SIGMAZ*2.35/demagnification_factor\n\n\n\n # analyze shadow results\n print(\"\\nSHADOW results: \")\n st1 = beam.get_standard_deviation(3,ref=0)\n st2 = beam.get_standard_deviation(3,ref=1)\n\n print(\" stDev*2.35: unweighted: %f um, weighted: %f um \"%(st1*2.35*1e4,st2*2.35*1e4))\n\n tk = beam.histo1(3, nbins=75, ref=1, nolost=1, write=\"HISTO1\")\n\n print(\" Histogram FWHM: %f um \"%(1e4*tk[\"fwhm\"]))\n\n\n print(\" Transmitted intensity: %f (source was: %d) (transmission is %f %%) \"%(beam.intensity(nolost=1), src.NPOINT, beam.intensity(nolost=1)/src.NPOINT*100))\n\n\n\n #scan around image\n xx1 = numpy.linspace(0.0,1.1*tf_fs_after,11) # position from TF exit plane\n\n #xx0 = focal_q - tf_length*0.5\n xx0 = focal_q - tf_length*0.5 # position of focus from TF exit plane\n\n xx2 = numpy.linspace(xx0-100.0,xx0+100,21) # position from TF exit plane\n xx3 = numpy.array([tf_fs_after])\n\n xx = numpy.concatenate(([-0.5*tf_length],xx1,xx2,[tf_fs_after]))\n\n xx.sort()\n\n\n f = open(\"id30b.spec\",\"w\")\n f.write(\"#F id30b.spec\\n\")\n f.write(\"\\n#S 1 calculations for id30b transfocator\\n\")\n f.write(\"#N 8\\n\")\n labels = \" %18s %18s %18s %18s %18s %18s %18s %18s\"%\\\n (\"pos from source\",\"pos from image\",\"[pos from TF]\", \"pos from TF center\", \"pos from focus\",\\\n \"fwhm shadow(stdev)\",\"fwhm shadow(histo)\",\"fwhm theoretical\")\n\n f.write(\"#L \"+labels+\"\\n\")\n\n out = numpy.zeros((8,xx.size))\n for i,pos in enumerate(xx):\n beam2 = beam.duplicate()\n beam2.retrace(-tf_fs_after+pos)\n fwhm1 = 2.35*1e4*beam2.get_standard_deviation(3,ref=1,nolost=1)\n tk = beam2.histo1(3, nbins=75, ref=1, nolost=1)\n fwhm2 = 1e4*tk[\"fwhm\"]\n #fwhm_th = 1e4*transfocator_calculate_estimated_size(pos,diameter=diameter,focal_distance=focal_q)\n fwhm_th2 = 1e4*numpy.sqrt( (div_q*(pos+0.5*tf_length-focal_q))**2 + theoretical_focal_size**2 )\n #fwhm_th2 = 1e4*( numpy.abs(div_q*(pos-focal_q+0.5*tf_length)) + theoretical_focal_size )\n\n\n out[0,i] = tf_fs_before+tf_length+pos\n out[1,i] = -tf_fs_after+pos\n out[2,i] = pos\n out[3,i] = pos+0.5*tf_length\n out[4,i] = pos+0.5*tf_length-focal_q\n\n\n out[5,i] = fwhm1\n out[6,i] = fwhm2\n out[7,i] = fwhm_th2\n\n\n f.write(\" %18.3f %18.3f %18.3f %18.3f %18.3f %18.3f %18.3f %18.3f \\n\"%\\\n (tf_fs_before+tf_length+pos,\\\n -tf_fs_after+pos,\\\n pos,\\\n pos+0.5*tf_length,\\\n pos+0.5*tf_length-focal_q,\\\n fwhm1,fwhm2,fwhm_th2))\n\n f.close()\n print(\"File with beam evolution written to disk: id30b.spec\")\n\n\n #\n # plots\n #\n itmp = input(\"Do you want to plot the intensity distribution and beam evolution? [1=yes,0=No]\")\n if str(itmp) != \"1\":\n return\n\n import matplotlib.pylab as plt\n\n plt.figure(1)\n plt.plot(out[1,:],out[5,:],'blue',label=\"fwhm shadow(stdev)\")\n plt.plot(out[1,:],out[6,:],'green',label=\"fwhm shadow(histo1)\")\n plt.plot(out[1,:],out[7,:],'red',label=\"fwhm theoretical\")\n\n plt.xlabel(\"Distance from image plane [cm]\")\n plt.ylabel(\"spot size [um] \")\n ax = plt.subplot(111)\n ax.legend(bbox_to_anchor=(1.1, 1.05))\n\n print(\"Kill graphic to continue.\")\n plt.show()\n\n Shadow.ShadowTools.histo1(beam,3,nbins=75,ref=1,nolost=1,calfwhm=1)\n\n input(\" to finish.\")\n return None\n\ndef id30b_full_simulation(photon_energy_ev=14000.0,s_target=20.0e-4,nlenses_target=None):\n\n\n if nlenses_target == None:\n force_nlenses = 0\n else:\n force_nlenses = 1\n\n #\n # define lens setup (general)\n #\n xrl_symbol = [\"Be\",\"Be\",\"Be\"]\n xrl_density = [1.845,1.845,1.845]\n lens_diameter = 0.05\n nlenses_max = [15,3,1]\n nlenses_radii = [500e-4,1000e-4,1500e-4]\n\n sigmaz=6.46e-4\n alpha = 0.55\n\n tf_p = 5960 # position of the TF measured from the center of the transfocator\n tf_q = 9760 - tf_p # position of the image plane measured from the center of the transfocator\n\n\n if s_target < 2.35*sigmaz*tf_q/tf_p:\n print(\"Source size FWHM is: %f um\"%(1e4*2.35*sigmaz))\n print(\"Maximum Demagnifications is: %f um\"%(tf_p/tf_q))\n print(\"Minimum possible size is: %f um\"%(1e4*2.35*sigmaz*tf_q/tf_p))\n print(\"Error: redefine size\")\n return\n\n\n print(\"================================== TRANSFOCATOR INPUTS \")\n print(\"Photon energy: %f eV\"%(photon_energy_ev))\n if force_nlenses:\n print(\"Forced_nlenses: \",nlenses_target)\n else:\n print(\"target size: %f cm\"%(s_target))\n\n print(\"materials: \",xrl_symbol)\n print(\"densities: \",xrl_density)\n print(\"Lens diameter: %f cm\"%(lens_diameter))\n print(\"nlenses_max:\",nlenses_max,\"nlenses_radii: \",nlenses_radii)\n\n print(\"Source size (sigma): %f um, FWHM: %f um\"%(1e4*sigmaz,2.35*1e4*sigmaz))\n print(\"Distances: tf_p: %f cm, tf_q: %f cm\"%(tf_p,tf_q))\n print(\"alpha: %f\"%(alpha))\n\n print(\"========================================================\")\n\n\n if force_nlenses != 1:\n nlenses_target = transfocator_compute_configuration(photon_energy_ev,s_target,\\\n symbol=xrl_symbol,density=xrl_density,\\\n nlenses_max=nlenses_max, nlenses_radii=nlenses_radii, lens_diameter=lens_diameter, \\\n sigmaz=sigmaz, alpha=alpha, \\\n tf_p=tf_p,tf_q=tf_q, verbose=1)\n\n\n (s_target,focal_f,focal_q,div_q) = \\\n transfocator_compute_parameters(photon_energy_ev, nlenses_target,\\\n symbol=xrl_symbol,density=xrl_density,\\\n nlenses_max=nlenses_max, nlenses_radii=nlenses_radii, \\\n lens_diameter=lens_diameter,\\\n sigmaz=sigmaz, alpha=alpha,\\\n tf_p=tf_p,tf_q=tf_q)\n\n slots_max = [ 1, 2, 4, 8, 1, 2, 1] # slots\n slots_on_off = transfocator_nlenses_to_slots(nlenses_target,nlenses_max=nlenses_max)\n\n\n print(\"=============================== TRANSFOCATOR SET\")\n #print(\"deltas: \",deltas)\n\n if force_nlenses != 1:\n print(\"nlenses_target (optimized): \",nlenses_target)\n else:\n print(\"nlenses_target (forced): \",nlenses_target)\n\n print(\"With these lenses we obtain: \")\n print(\" focal_f: %f cm\"%(focal_f))\n print(\" focal_q: %f cm\"%(focal_q))\n print(\" s_target: %f um\"%(s_target*1e4))\n print(\" slots_max: \",slots_max)\n print(\" slots_on_off: \",slots_on_off)\n print(\"==================================================\")\n\n # for theoretical calculations use the focal position and distances given by the target nlenses\n\n itmp = input(\"Start SHADOW simulation? [1=yes,0=No]: \")\n if str(itmp) != \"1\":\n return\n\n #=======================================================================================================================\n # Inputs\n #=======================================================================================================================\n\n\n emittH = 3.9e-9\n emittV = 10e-12\n betaH = 35.6\n betaV = 3.0\n number_of_rays = 50000\n\n nslots = len(slots_max)\n slots_lens_thickness = [0.3 for i in range(nslots)] #total thickness of a single lens in cm\n # for each slot, positional gap of the first lens in cm\n slots_steps = [ 4, 4, 1.9, 6.1, 4, 4, slots_lens_thickness[-1]]\n slots_radii = [.05, .05, .05, .05, 0.1, 0.1, 0.15] # radii of the lenses in cm\n AAA= 333\n id30b_ray_tracing(emittH=emittH,emittV=emittV,betaH=betaH,betaV=betaV,number_of_rays=number_of_rays,\\\n density=xrl_density[0],symbol=xrl_symbol[0],tf_p=tf_p,tf_q=tf_q,lens_diameter=lens_diameter,\\\n slots_max=slots_max,slots_on_off=slots_on_off,photon_energy_ev=photon_energy_ev,\\\n slots_lens_thickness=slots_lens_thickness,slots_steps=slots_steps,slots_radii=slots_radii,\\\n s_target=s_target,focal_f=focal_f,focal_q=focal_q,div_q=div_q)\n\n\ndef main():\n\n # this performs the full simulation: calculates the optimum configuration and do the ray-tracing\n\n itmp = input(\"Enter: \\n 0 = optimization calculation only \\n 1 = full simulation (ray tracing) \\n?> \")\n photon_energy_kev = float(input(\"Enter photon energy in keV: \"))\n s_target_um = float(input(\"Enter target focal dimension in microns: \"))\n if str(itmp) == \"1\":\n\n id30b_full_simulation(photon_energy_ev=photon_energy_kev*1e3,s_target=s_target_um*1e-4,nlenses_target=None)\n #id30b_full_simulation(photon_energy_ev=14000.0,s_target=20.0e-4,nlenses_target=[3,1,1])\n else:\n #this performs the calculation of the optimizad configuration\n\n nlenses_optimum = transfocator_compute_configuration(photon_energy_kev*1e3,s_target_um*1e-4,\\\n symbol=[\"Be\",\"Be\",\"Be\"], density=[1.845,1.845,1.845],\\\n nlenses_max = [15,3,1], nlenses_radii = [500e-4,1000e-4,1500e-4], lens_diameter=0.05, \\\n sigmaz=6.46e-4, alpha = 0.55, \\\n tf_p=5960, tf_q=3800, verbose=0 )\n print(\"Optimum lens configuration is: \",nlenses_optimum)\n\n if nlenses_optimum == None:\n return\n\n print(\"Activate slots: \",transfocator_nlenses_to_slots(nlenses_optimum,nlenses_max=[15,3,1]))\n\n # this calculates the parameters (image size, etc) for a given lens configuration\n\n (size, f, q_f, div) = transfocator_compute_parameters(photon_energy_kev*1e3, nlenses_optimum,\\\n symbol=[\"Be\",\"Be\",\"Be\"], density=[1.845,1.845,1.845],\\\n nlenses_max = [15,3,1], nlenses_radii = [500e-4,1000e-4,1500e-4], lens_diameter=0.05, \\\n sigmaz=6.46e-4, alpha = 0.55, \\\n tf_p=5960, tf_q=3800 )\n print(\"For given configuration \",nlenses_optimum,\" we get: \")\n print(\" size: %f cm, focal length: %f cm, focal distance: %f cm, divergence: %f rad: \"%(size, f, q_f, div))\n\nif __name__ == \"__main__\":\n main()"},"license":{"kind":"string","value":"mit"},"hash":{"kind":"number","value":5677322547994774000,"string":"5,677,322,547,994,774,000"},"line_mean":{"kind":"number","value":39.2242990654,"string":"39.224299"},"line_max":{"kind":"number","value":162,"string":"162"},"alpha_frac":{"kind":"number","value":0.5849049297,"string":"0.584905"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.0160009343611307,"string":"3.016001"},"config_test":{"kind":"bool","value":true,"string":"true"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45141,"cells":{"repo_name":{"kind":"string","value":"jose187/gh_word_count"},"path":{"kind":"string","value":"gh_word_count/__init__.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"2681"},"content":{"kind":"string","value":"\nfrom ommit_words import list_ommited_words\nfrom re import sub\nimport operator\n\nclass _input_list:\n\n\n def __init__(self,list_TITLES):\n\n self.list_TITLES = list_TITLES\n self.list_remove = list_ommited_words()\n\n def _word_count(self):\n # these are all the words that are in the text\n dict_words = {}\n \n # now we go through each of the lines\n for str_line in self.list_TITLES:\n str_raw_line1 = sub('[^a-z0-9 ]','',str_line.lower())\n list_line_words = str_raw_line1.split()\n for str_word in list_line_words:\n # check to see if its in the ommited word list\n if str_word not in self.list_remove:\n # create new key if it is not there yet\n if str_word not in dict_words:\n dict_words[str_word] = [1]\n # add if is already there\n elif str_word in dict_words:\n dict_words[str_word].append(1)\n\n sorted_x = sorted(dict_words.iteritems(),\n key=operator.itemgetter(1),\n reverse=True)\n \n list_OUTPUT = []\n for each_item in sorted_x:\n int_COUNT = sum(each_item[1])\n if int_COUNT > 1:\n tup_ONE_COUNT = ('%s' % each_item[0],\n '%d' % int_COUNT)\n\n list_OUTPUT.append(tup_ONE_COUNT)\n\n return list_OUTPUT\n\n\n # gets the top x according to frequency\n # returns list\n def _get_top(self,int_TOP):\n list_TOP_N = []\n for str_WORD in self._word_count()[:int_TOP]:\n list_TOP_N.append(str_WORD)\n return list_TOP_N\n\n\n# displays the count on the terminal\ndef _show_count(list_TUPS,entries=0):\n if entries == 0:\n int_TOP = len(list_TUPS)\n else:\n int_TOP = entries\n\n print 'Count\\tWord\\n'\n for tup_ITEM in list_TUPS[:int_TOP]:\n print '%d\\t%s' % (int(tup_ITEM[1]),str(tup_ITEM[0]))\n\n# saves the count to csv file\ndef _save_counts(list_COUNTS,str_FILE_PATH,entries=0):\n if entries == 0:\n int_TOP = len(list_COUNTS)\n else:\n int_TOP = entries\n\n list_OUTPUT = ['\"Count\",\"Word\"']\n for tup_ITEM in list_COUNTS[:int_TOP]:\n str_OUTPUT = '%d,\"%s\"' % (int(tup_ITEM[1]),str(tup_ITEM[0]))\n list_OUTPUT.append(str_OUTPUT)\n\n fw_OUTPUT = open(str_FILE_PATH,'w')\n fw_OUTPUT.write('\\n'.join(list_OUTPUT))\n fw_OUTPUT.close()\n \n\n"},"license":{"kind":"string","value":"bsd-2-clause"},"hash":{"kind":"number","value":-7451965439748880000,"string":"-7,451,965,439,748,880,000"},"line_mean":{"kind":"number","value":30.9166666667,"string":"30.916667"},"line_max":{"kind":"number","value":69,"string":"69"},"alpha_frac":{"kind":"number","value":0.4975755315,"string":"0.497576"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.723611111111111,"string":"3.723611"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45142,"cells":{"repo_name":{"kind":"string","value":"CSD-Public/stonix"},"path":{"kind":"string","value":"src/tests/rules/unit_tests/zzzTestRuleDisableOpenSafeSafari.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"4752"},"content":{"kind":"string","value":"###############################################################################\n# #\n# Copyright 2019. Triad National Security, LLC. All rights reserved. #\n# This program was produced under U.S. Government contract 89233218CNA000001 #\n# for Los Alamos National Laboratory (LANL), which is operated by Triad #\n# National Security, LLC for the U.S. Department of Energy/National Nuclear #\n# Security Administration. #\n# #\n# All rights in the program are reserved by Triad National Security, LLC, and #\n# the U.S. Department of Energy/National Nuclear Security Administration. The #\n# Government is granted for itself and others acting on its behalf a #\n# nonexclusive, paid-up, irrevocable worldwide license in this material to #\n# reproduce, prepare derivative works, distribute copies to the public, #\n# perform publicly and display publicly, and to permit others to do so. #\n# #\n###############################################################################\n\n'''\nThis is a Unit Test for Rule DisableOpenSafeSafari\nCreated on Jan 22, 2015\n\n@author: dwalker\n@change: 2015-02-25 - ekkehard - Updated to make unit test work\n@change: 2016/02/10 roy Added sys.path.append for being able to unit test this\n file as well as with the test harness.\n'''\n\nimport unittest\nimport sys\n\nsys.path.append(\"../../../..\")\nfrom src.tests.lib.RuleTestTemplate import RuleTest\nfrom src.stonix_resources.CommandHelper import CommandHelper\nfrom src.tests.lib.logdispatcher_mock import LogPriority\nfrom src.stonix_resources.rules.DisableOpenSafeSafari import DisableOpenSafeSafari\n\nclass zzzTestRuleDisableOpenSafeSafari(RuleTest):\n \n def setUp(self):\n RuleTest.setUp(self)\n self.rule = DisableOpenSafeSafari(self.config,\n self.environ,\n self.logdispatch,\n self.statechglogger)\n self.rulename = self.rule.rulename\n self.rulenumber = self.rule.rulenumber\n self.ch = CommandHelper(self.logdispatch)\n self.dc = \"/usr/bin/defaults\"\n self.path = \"com.apple.Safari\"\n self.key = \"AutoOpenSafeDownloads\"\n def tearDown(self):\n pass\n\n def runTest(self):\n self.simpleRuleTest()\n\n def setConditionsForRule(self):\n '''This makes sure the intial report fails by executing the following\n commands:\n defaults write com.apple.Safari AutoOpenSafeDownloads -bool yes\n\n :param self: essential if you override this definition\n :returns: boolean - If successful True; If failure False\n @author: dwalker\n\n '''\n success = False\n cmd = [self.dc, \"write\", self.path, self.key, \"-bool\", \"yes\"]\n self.logdispatch.log(LogPriority.DEBUG, str(cmd))\n if self.ch.executeCommand(cmd):\n success = self.checkReportForRule(False, True)\n return success\n \n def checkReportForRule(self, pCompliance, pRuleSuccess):\n '''To see what happended run these commands:\n defaults read com.apple.Safari AutoOpenSafeDownloads\n\n :param self: essential if you override this definition\n :param pCompliance: \n :param pRuleSuccess: \n :returns: boolean - If successful True; If failure False\n @author: ekkehard j. koch\n\n '''\n success = True\n self.logdispatch.log(LogPriority.DEBUG, \"pCompliance = \" + \\\n str(pCompliance) + \".\")\n self.logdispatch.log(LogPriority.DEBUG, \"pRuleSuccess = \" + \\\n str(pRuleSuccess) + \".\")\n cmd = [self.dc, \"read\", self.path, self.key]\n self.logdispatch.log(LogPriority.DEBUG, str(cmd))\n if self.ch.executeCommand(cmd):\n output = self.ch.getOutputString()\n return success\n\n def checkFixForRule(self, pRuleSuccess):\n self.logdispatch.log(LogPriority.DEBUG, \"pRuleSuccess = \" + \\\n str(pRuleSuccess) + \".\")\n success = self.checkReportForRule(True, pRuleSuccess)\n return success\n\n def checkUndoForRule(self, pRuleSuccess):\n self.logdispatch.log(LogPriority.DEBUG, \"pRuleSuccess = \" + \\\n str(pRuleSuccess) + \".\")\n success = self.checkReportForRule(False, pRuleSuccess)\n return success\n\nif __name__ == \"__main__\":\n #import sys;sys.argv = ['', 'Test.testName']\n unittest.main()\n"},"license":{"kind":"string","value":"gpl-2.0"},"hash":{"kind":"number","value":6575902741037396000,"string":"6,575,902,741,037,396,000"},"line_mean":{"kind":"number","value":42.2,"string":"42.2"},"line_max":{"kind":"number","value":82,"string":"82"},"alpha_frac":{"kind":"number","value":0.5801767677,"string":"0.580177"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":4.2772277227722775,"string":"4.277228"},"config_test":{"kind":"bool","value":true,"string":"true"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45143,"cells":{"repo_name":{"kind":"string","value":"HomeRad/TorCleaner"},"path":{"kind":"string","value":"wc/filter/rules/FolderRule.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"3945"},"content":{"kind":"string","value":"# -*- coding: iso-8859-1 -*-\n# Copyright (C) 2000-2009 Bastian Kleineidam\n\"\"\"\nGroup filter rules into folders.\n\"\"\"\nfrom ... import fileutil, configuration\nfrom . import Rule\n\n\ndef recalc_up_down(rules):\n \"\"\"\n Add .up and .down attributes to rules, used for display up/down\n arrows in GUIs\n \"\"\"\n upper = len(rules)-1\n for i, rule in enumerate(rules):\n rule.up = (i>0)\n rule.down = (i> log, _(\"inserting new rule %s\") % \\\n child.tiptext()\n if not dryrun:\n self.rules.append(child)\n chg = True\n if chg:\n recalc_up_down(self.rules)\n return chg\n\n def get_rule(self, sid):\n \"\"\"\n Return rule with given sid or None if not found.\n \"\"\"\n for rule in self.rules:\n if rule.sid == sid:\n return rule\n return None\n\n def toxml(self):\n \"\"\"\n Rule data as XML for storing.\n \"\"\"\n s = u\"\"\"\n\n%s oid=\"%d\" configversion=\"%s\">\"\"\" % \\\n (configuration.ConfigCharset, super(FolderRule, self).toxml(),\n self.oid, self.configversion)\n s += u\"\\n\"+self.title_desc_toxml()+u\"\\n\"\n for r in self.rules:\n s += u\"\\n%s\\n\" % r.toxml()\n return s+u\"\\n\"\n\n def write(self, fd=None):\n \"\"\"\n Write xml data into filename.\n @raise: OSError if file could not be written.\n \"\"\"\n s = self.toxml().encode(\"iso-8859-1\", \"replace\")\n if fd is None:\n fileutil.write_file(self.filename, s)\n else:\n fd.write(s)\n\n def tiptext(self):\n \"\"\"\n Return short info for gui display.\n \"\"\"\n l = len(self.rules)\n if l == 1:\n text = _(\"with 1 rule\")\n else:\n text = _(\"with %d rules\") % l\n return \"%s %s\" % (super(FolderRule, self).tiptext(), text)\n"},"license":{"kind":"string","value":"gpl-2.0"},"hash":{"kind":"number","value":716819241840942200,"string":"716,819,241,840,942,200"},"line_mean":{"kind":"number","value":27.795620438,"string":"27.79562"},"line_max":{"kind":"number","value":78,"string":"78"},"alpha_frac":{"kind":"number","value":0.5097591888,"string":"0.509759"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.937125748502994,"string":"3.937126"},"config_test":{"kind":"bool","value":true,"string":"true"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45144,"cells":{"repo_name":{"kind":"string","value":"RAJSD2610/SDNopenflowSwitchAnalysis"},"path":{"kind":"string","value":"TotalFlowPlot.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"2742"},"content":{"kind":"string","value":"import os\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport seaborn\nseaborn.set()\n\npath= os.path.expanduser(\"~/Desktop/ece671/udpt8\")\nnum_files = len([f for f in os.listdir(path)if os.path.isfile(os.path.join(path, f))])\nprint(num_files)\nu8=[]\ni=0\ndef file_len(fname):\n with open(fname) as f:\n for i, l in enumerate(f):\n pass\n return i + 1\nwhile i<(num_files/2) :\n # df+=[]\n j=i+1\n\n path =\"/home/vetri/Desktop/ece671/udpt8/ftotal.\"+str(j)+\".csv\"\n y = file_len(path)\n # except: pass\n #df.append(pd.read_csv(path,header=None)) \n# a+=[]\n #y=len(df[i].index)-1 #1 row added by default so that table has a entry\n if y<0:\n y=0 \n \n u8.append(y)\n \n i+=1\nprint(u8)\npath= os.path.expanduser(\"~/Desktop/ece671/udpnone\")\nnum_files = len([f for f in os.listdir(path)if os.path.isfile(os.path.join(path, f))])\nprint(num_files)\ni=0 \nj=0\nu=[]\nwhile i<(num_files/2):\n j=i+1\n\n path =\"/home/vetri/Desktop/ece671/udpnone/ftotal.\"+str(j)+\".csv\"\n y = file_len(path)\n # except: pass\n #df.append(pd.read_csv(path,header=None)) \n# a+=[]\n #y=len(df[i].index)-1 #1 row added by default so that table has a entry\n if y<0:\n y=0 \n u.append(y)\n i+=1\n\nprint(u)\npath= os.path.expanduser(\"~/Desktop/ece671/tcpnone\")\nnum_files = len([f for f in os.listdir(path)if os.path.isfile(os.path.join(path, f))])\nprint(num_files)\ni=0 \nj=0\nt=[]\nwhile i<(num_files/2):\n j=i+1\n\n path =\"/home/vetri/Desktop/ece671/tcpnone/ftotal.\"+str(j)+\".csv\"\n y = file_len(path)\n # except: pass\n #df.append(pd.read_csv(path,header=None)) \n# a+=[]\n #y=len(df[i].index)-1 #1 row added by default so that table has a entry\n if y<0:\n y=0 \n t.append(y)\n i+=1\n\nprint(t)\npath= os.path.expanduser(\"~/Desktop/ece671/tcpt8\")\nnum_files = len([f for f in os.listdir(path)if os.path.isfile(os.path.join(path, f))])\nprint(num_files)\ni=0 \nj=0\nt8=[]\nwhile i<(num_files/2):\n j=i+1\n\n path =\"/home/vetri/Desktop/ece671/tcpt8/ftotal.\"+str(j)+\".csv\"\n y = file_len(path)\n # except: pass\n #df.append(pd.read_csv(path,header=None)) \n# a+=[]\n #y=len(df[i].index)-1 #1 row added by default so that table has a entry\n if y<0:\n y=0 \n t8.append(y)\n i+=1\n\nprint(t8)\n#plt.figure(figsize=(4, 5))\nplt.plot(list(range(1,len(u8)+1)),u8, '.-',label=\"udpt8\")\nplt.plot(list(range(1,len(u)+1)),u, '.-',label=\"udpnone\")\nplt.plot(list(range(1,len(t)+1)),t, '.-',label=\"tcpnone\")\nplt.plot(list(range(1,len(t8)+1)),t8, '.-',label=\"tcpt8\")\nplt.title(\"Total Flows Present after 1st flow\")\nplt.xlabel(\"time(s)\")\nplt.ylabel(\"flows\")\n#plt.frameon=True\nplt.legend()\nplt.show()\n"},"license":{"kind":"string","value":"gpl-3.0"},"hash":{"kind":"number","value":3297434910053564400,"string":"3,297,434,910,053,564,400"},"line_mean":{"kind":"number","value":24.3888888889,"string":"24.388889"},"line_max":{"kind":"number","value":86,"string":"86"},"alpha_frac":{"kind":"number","value":0.5911743253,"string":"0.591174"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":2.5155963302752293,"string":"2.515596"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45145,"cells":{"repo_name":{"kind":"string","value":"cschenck/blender_sim"},"path":{"kind":"string","value":"fluid_sim_deps/blender-2.69/2.69/scripts/addons/io_scene_3ds/__init__.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"6950"},"content":{"kind":"string","value":"# ##### BEGIN GPL LICENSE BLOCK #####\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software Foundation,\n# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n#\n# ##### END GPL LICENSE BLOCK #####\n\n# \n\nbl_info = {\n \"name\": \"Autodesk 3DS format\",\n \"author\": \"Bob Holcomb, Campbell Barton\",\n \"blender\": (2, 57, 0),\n \"location\": \"File > Import-Export\",\n \"description\": \"Import-Export 3DS, meshes, uvs, materials, textures, \"\n \"cameras & lamps\",\n \"warning\": \"\",\n \"wiki_url\": \"http://wiki.blender.org/index.php/Extensions:2.6/Py/\"\n \"Scripts/Import-Export/Autodesk_3DS\",\n \"tracker_url\": \"\",\n \"support\": 'OFFICIAL',\n \"category\": \"Import-Export\"}\n\nif \"bpy\" in locals():\n import imp\n if \"import_3ds\" in locals():\n imp.reload(import_3ds)\n if \"export_3ds\" in locals():\n imp.reload(export_3ds)\n\n\nimport bpy\nfrom bpy.props import StringProperty, FloatProperty, BoolProperty, EnumProperty\n\nfrom bpy_extras.io_utils import (ImportHelper,\n ExportHelper,\n axis_conversion,\n )\n\n\nclass Import3DS(bpy.types.Operator, ImportHelper):\n \"\"\"Import from 3DS file format (.3ds)\"\"\"\n bl_idname = \"import_scene.autodesk_3ds\"\n bl_label = 'Import 3DS'\n bl_options = {'UNDO'}\n\n filename_ext = \".3ds\"\n filter_glob = StringProperty(default=\"*.3ds\", options={'HIDDEN'})\n\n constrain_size = FloatProperty(\n name=\"Size Constraint\",\n description=\"Scale the model by 10 until it reaches the \"\n \"size constraint (0 to disable)\",\n min=0.0, max=1000.0,\n soft_min=0.0, soft_max=1000.0,\n default=10.0,\n )\n use_image_search = BoolProperty(\n name=\"Image Search\",\n description=\"Search subdirectories for any associated images \"\n \"(Warning, may be slow)\",\n default=True,\n )\n use_apply_transform = BoolProperty(\n name=\"Apply Transform\",\n description=\"Workaround for object transformations \"\n \"importing incorrectly\",\n default=True,\n )\n\n axis_forward = EnumProperty(\n name=\"Forward\",\n items=(('X', \"X Forward\", \"\"),\n ('Y', \"Y Forward\", \"\"),\n ('Z', \"Z Forward\", \"\"),\n ('-X', \"-X Forward\", \"\"),\n ('-Y', \"-Y Forward\", \"\"),\n ('-Z', \"-Z Forward\", \"\"),\n ),\n default='Y',\n )\n\n axis_up = EnumProperty(\n name=\"Up\",\n items=(('X', \"X Up\", \"\"),\n ('Y', \"Y Up\", \"\"),\n ('Z', \"Z Up\", \"\"),\n ('-X', \"-X Up\", \"\"),\n ('-Y', \"-Y Up\", \"\"),\n ('-Z', \"-Z Up\", \"\"),\n ),\n default='Z',\n )\n\n def execute(self, context):\n from . import import_3ds\n\n keywords = self.as_keywords(ignore=(\"axis_forward\",\n \"axis_up\",\n \"filter_glob\",\n ))\n\n global_matrix = axis_conversion(from_forward=self.axis_forward,\n from_up=self.axis_up,\n ).to_4x4()\n keywords[\"global_matrix\"] = global_matrix\n\n return import_3ds.load(self, context, **keywords)\n\n\nclass Export3DS(bpy.types.Operator, ExportHelper):\n \"\"\"Export to 3DS file format (.3ds)\"\"\"\n bl_idname = \"export_scene.autodesk_3ds\"\n bl_label = 'Export 3DS'\n\n filename_ext = \".3ds\"\n filter_glob = StringProperty(\n default=\"*.3ds\",\n options={'HIDDEN'},\n )\n\n use_selection = BoolProperty(\n name=\"Selection Only\",\n description=\"Export selected objects only\",\n default=False,\n )\n\n axis_forward = EnumProperty(\n name=\"Forward\",\n items=(('X', \"X Forward\", \"\"),\n ('Y', \"Y Forward\", \"\"),\n ('Z', \"Z Forward\", \"\"),\n ('-X', \"-X Forward\", \"\"),\n ('-Y', \"-Y Forward\", \"\"),\n ('-Z', \"-Z Forward\", \"\"),\n ),\n default='Y',\n )\n\n axis_up = EnumProperty(\n name=\"Up\",\n items=(('X', \"X Up\", \"\"),\n ('Y', \"Y Up\", \"\"),\n ('Z', \"Z Up\", \"\"),\n ('-X', \"-X Up\", \"\"),\n ('-Y', \"-Y Up\", \"\"),\n ('-Z', \"-Z Up\", \"\"),\n ),\n default='Z',\n )\n\n def execute(self, context):\n from . import export_3ds\n\n keywords = self.as_keywords(ignore=(\"axis_forward\",\n \"axis_up\",\n \"filter_glob\",\n \"check_existing\",\n ))\n global_matrix = axis_conversion(to_forward=self.axis_forward,\n to_up=self.axis_up,\n ).to_4x4()\n keywords[\"global_matrix\"] = global_matrix\n\n return export_3ds.save(self, context, **keywords)\n\n\n# Add to a menu\ndef menu_func_export(self, context):\n self.layout.operator(Export3DS.bl_idname, text=\"3D Studio (.3ds)\")\n\n\ndef menu_func_import(self, context):\n self.layout.operator(Import3DS.bl_idname, text=\"3D Studio (.3ds)\")\n\n\ndef register():\n bpy.utils.register_module(__name__)\n\n bpy.types.INFO_MT_file_import.append(menu_func_import)\n bpy.types.INFO_MT_file_export.append(menu_func_export)\n\n\ndef unregister():\n bpy.utils.unregister_module(__name__)\n\n bpy.types.INFO_MT_file_import.remove(menu_func_import)\n bpy.types.INFO_MT_file_export.remove(menu_func_export)\n\n# NOTES:\n# why add 1 extra vertex? and remove it when done? -\n# \"Answer - eekadoodle - would need to re-order UV's without this since face\n# order isnt always what we give blender, BMesh will solve :D\"\n#\n# disabled scaling to size, this requires exposing bb (easy) and understanding\n# how it works (needs some time)\n\nif __name__ == \"__main__\":\n register()\n"},"license":{"kind":"string","value":"gpl-3.0"},"hash":{"kind":"number","value":-6396439276597938000,"string":"-6,396,439,276,597,938,000"},"line_mean":{"kind":"number","value":32.0952380952,"string":"32.095238"},"line_max":{"kind":"number","value":79,"string":"79"},"alpha_frac":{"kind":"number","value":0.4962589928,"string":"0.496259"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":4.1319857312722945,"string":"4.131986"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45146,"cells":{"repo_name":{"kind":"string","value":"HyperloopTeam/FullOpenMDAO"},"path":{"kind":"string","value":"cantera-2.0.2/interfaces/python/MixMaster/Units/unit.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"2833"},"content":{"kind":"string","value":"import operator\n\nclass unit:\n\n _zero = (0,) * 7\n _negativeOne = (-1, ) * 7\n\n _labels = ('m', 'kg', 's', 'A', 'K', 'mol', 'cd')\n\n\n def __init__(self, value, derivation):\n self.value = value\n self.derivation = derivation\n return\n\n\n def __add__(self, other):\n if not self.derivation == other.derivation:\n raise ImcompatibleUnits(self, other)\n\n return unit(self.value + other.value, self.derivation)\n\n\n def __sub__(self, other):\n if not self.derivation == other.derivation:\n raise ImcompatibleUnits(self, other)\n\n return unit(self.value - other.value, self.derivation)\n\n\n def __mul__(self, other):\n if type(other) == type(0) or type(other) == type(0.0):\n return unit(other*self.value, self.derivation)\n\n value = self.value * other.value\n derivation = tuple(map(operator.add, self.derivation, other.derivation))\n\n return unit(value, derivation)\n\n\n def __div__(self, other):\n if type(other) == type(0) or type(other) == type(0.0):\n return unit(self.value/other, self.derivation)\n\n value = self.value / other.value\n derivation = tuple(map(operator.sub, self.derivation, other.derivation))\n\n return unit(value, derivation)\n\n\n def __pow__(self, other):\n if type(other) != type(0) and type(other) != type(0.0):\n raise BadOperation\n\n value = self.value ** other\n derivation = tuple(map(operator.mul, [other]*7, self.derivation))\n\n return unit(value, derivation)\n\n\n def __pos__(self): return self\n\n\n def __neg__(self): return unit(-self.value, self.derivation)\n\n\n def __abs__(self): return unit(abs(self.value), self.derivation)\n\n\n def __invert__(self):\n value = 1./self.value\n derivation = tuple(map(operator.mul, self._negativeOne, self.derivation))\n return unit(value, derivation)\n\n\n def __rmul__(self, other):\n return unit.__mul__(self, other)\n\n def __rdiv__(self, other):\n if type(other) != type(0) and type(other) != type(0.0):\n raise BadOperation(self, other)\n\n value = other/self.value\n derivation = tuple(map(operator.mul, self._negativeOne, self.derivation))\n\n return unit(value, derivation)\n\n\n def __float__(self):\n return self.value\n #if self.derivation == self._zero: return self.value\n #raise BadConversion(self)\n\n\n def __str__(self):\n str = \"%g\" % self.value\n for i in range(0, 7):\n exponent = self.derivation[i]\n if exponent == 0: continue\n if exponent == 1:\n str = str + \" %s\" % (self._labels[i])\n else:\n str = str + \" %s^%d\" % (self._labels[i], exponent)\n\n return str\n\ndimensionless = unit(1, unit._zero)\n"},"license":{"kind":"string","value":"gpl-2.0"},"hash":{"kind":"number","value":3539097702608451000,"string":"3,539,097,702,608,451,000"},"line_mean":{"kind":"number","value":25.476635514,"string":"25.476636"},"line_max":{"kind":"number","value":81,"string":"81"},"alpha_frac":{"kind":"number","value":0.5707730321,"string":"0.570773"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.6744487678339817,"string":"3.674449"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45147,"cells":{"repo_name":{"kind":"string","value":"lmazuel/azure-sdk-for-python"},"path":{"kind":"string","value":"azure-mgmt-compute/azure/mgmt/compute/v2016_03_30/models/windows_configuration_py3.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"2719"},"content":{"kind":"string","value":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is\n# regenerated.\n# --------------------------------------------------------------------------\n\nfrom msrest.serialization import Model\n\n\nclass WindowsConfiguration(Model):\n \"\"\"Specifies Windows operating system settings on the virtual machine.\n\n :param provision_vm_agent: Indicates whether virtual machine agent should\n be provisioned on the virtual machine.

When this property is not\n specified in the request body, default behavior is to set it to true.\n This will ensure that VM Agent is installed on the VM so that extensions\n can be added to the VM later.\n :type provision_vm_agent: bool\n :param enable_automatic_updates: Indicates whether virtual machine is\n enabled for automatic updates.\n :type enable_automatic_updates: bool\n :param time_zone: Specifies the time zone of the virtual machine. e.g.\n \"Pacific Standard Time\"\n :type time_zone: str\n :param additional_unattend_content: Specifies additional base-64 encoded\n XML formatted information that can be included in the Unattend.xml file,\n which is used by Windows Setup.\n :type additional_unattend_content:\n list[~azure.mgmt.compute.v2016_03_30.models.AdditionalUnattendContent]\n :param win_rm: Specifies the Windows Remote Management listeners. This\n enables remote Windows PowerShell.\n :type win_rm: ~azure.mgmt.compute.v2016_03_30.models.WinRMConfiguration\n \"\"\"\n\n _attribute_map = {\n 'provision_vm_agent': {'key': 'provisionVMAgent', 'type': 'bool'},\n 'enable_automatic_updates': {'key': 'enableAutomaticUpdates', 'type': 'bool'},\n 'time_zone': {'key': 'timeZone', 'type': 'str'},\n 'additional_unattend_content': {'key': 'additionalUnattendContent', 'type': '[AdditionalUnattendContent]'},\n 'win_rm': {'key': 'winRM', 'type': 'WinRMConfiguration'},\n }\n\n def __init__(self, *, provision_vm_agent: bool=None, enable_automatic_updates: bool=None, time_zone: str=None, additional_unattend_content=None, win_rm=None, **kwargs) -> None:\n super(WindowsConfiguration, self).__init__(**kwargs)\n self.provision_vm_agent = provision_vm_agent\n self.enable_automatic_updates = enable_automatic_updates\n self.time_zone = time_zone\n self.additional_unattend_content = additional_unattend_content\n self.win_rm = win_rm\n"},"license":{"kind":"string","value":"mit"},"hash":{"kind":"number","value":7741615214177697000,"string":"7,741,615,214,177,697,000"},"line_mean":{"kind":"number","value":49.3518518519,"string":"49.351852"},"line_max":{"kind":"number","value":180,"string":"180"},"alpha_frac":{"kind":"number","value":0.6708348658,"string":"0.670835"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":4.1895223420647145,"string":"4.189522"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45148,"cells":{"repo_name":{"kind":"string","value":"matiboy/django_safari_notifications"},"path":{"kind":"string","value":"django_safari_notifications/apps.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"1111"},"content":{"kind":"string","value":"# -*- coding: utf-8\nfrom django.apps import AppConfig\nimport logging\n\n\nclass DjangoSafariNotificationsConfig(AppConfig):\n name = 'django_safari_notifications'\n verbose_name = 'Safari Push Notifications'\n version = 'v1'\n service_base = 'push'\n userinfo_key = 'userinfo'\n logger = logging.getLogger('django_safari_notifications')\n # Provide path to a pem file containing the certificate, the key as well as Apple's WWDRCA\n cert = 'path/to/your/cert'\n passphrase = 'pass:xxxx' # this will be used with -passin in the openssl command so could be with pass, env etc\n # If single site, just set these values. Otherwise create Domain entries\n website_conf = None\n # sample single site: do not include the authenticationToken\n \"\"\"\n website_conf = {\n \"websiteName\": \"Bay Airlines\",\n \"websitePushID\": \"web.com.example.domain\",\n \"allowedDomains\": [\"http://domain.example.com\"],\n \"urlFormatString\": \"http://domain.example.com/%@/?flight=%@\",\n \"webServiceURL\": \"https://example.com/push\"\n }\n \"\"\"\n iconset_folder = '/path/to/your/iconset'\n"},"license":{"kind":"string","value":"mit"},"hash":{"kind":"number","value":-6515032378796969000,"string":"-6,515,032,378,796,969,000"},"line_mean":{"kind":"number","value":38.6785714286,"string":"38.678571"},"line_max":{"kind":"number","value":115,"string":"115"},"alpha_frac":{"kind":"number","value":0.6732673267,"string":"0.673267"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.7157190635451505,"string":"3.715719"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45149,"cells":{"repo_name":{"kind":"string","value":"TomSkelly/MatchAnnot"},"path":{"kind":"string","value":"showAnnot.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"2299"},"content":{"kind":"string","value":"#!/usr/bin/env python\n\n# Read annotation file, print selected stuff in human-readable format.\n\n# AUTHOR: Tom Skelly (thomas.skelly@fnlcr.nih.gov)\n\nimport os\nimport sys\nimport optparse\nimport re # regular expressions\nimport cPickle as pickle\n\nfrom tt_log import logger\nimport Annotations as anno\n\nVERSION = '20150417.01'\n\ndef main ():\n\n logger.debug('version %s starting' % VERSION)\n\n opt, args = getParms()\n\n if opt.gtfpickle is not None:\n handle = open (opt.gtfpickle, 'r')\n pk = pickle.Unpickler (handle)\n annotList = pk.load()\n handle.close()\n else:\n annotList = anno.AnnotationList (opt.gtf)\n\n geneList = annotList.getGene (opt.gene)\n if geneList is None:\n print 'gene %s not found in annotations' % opt.gene\n elif len(geneList) != 1:\n print 'there are %d occurrences of gene %s in annotations' % (len(geneList), opt.gene)\n else:\n geneEnt = geneList[0]\n\n print 'gene: ',\n printEnt (geneEnt)\n\n for transEnt in geneEnt.getChildren():\n print '\\ntr: ',\n printTran (transEnt)\n\n for exonEnt in transEnt.getChildren():\n print 'exon: ',\n printEnt (exonEnt)\n\n logger.debug('finished')\n\n return\n\ndef printEnt (ent):\n\n print '%-15s %9d %9d %6d' % (ent.name, ent.start, ent.end, ent.end-ent.start+1)\n\n return\n\ndef printTran (ent):\n\n print '%-15s %9d %9d %6d' % (ent.name, ent.start, ent.end, ent.end-ent.start+1),\n if hasattr (ent, 'startcodon'):\n print ' start: %9d' % ent.startcodon,\n if hasattr (ent, 'stopcodon'):\n print ' stop: %9d' % ent.stopcodon,\n print\n\n return\n\ndef getParms (): # use default input sys.argv[1:]\n\n parser = optparse.OptionParser(usage='%prog [options] ... ')\n\n parser.add_option ('--gtf', help='annotations in gtf format')\n parser.add_option ('--gtfpickle', help='annotations in pickled gtf format')\n parser.add_option ('--gene', help='gene to print')\n\n parser.set_defaults (gtf=None,\n gtfpickle=None,\n gene=None,\n )\n\n opt, args = parser.parse_args()\n\n return opt, args\n\n\nif __name__ == \"__main__\":\n main()\n"},"license":{"kind":"string","value":"gpl-3.0"},"hash":{"kind":"number","value":-1754153406302757400,"string":"-1,754,153,406,302,757,400"},"line_mean":{"kind":"number","value":24.2637362637,"string":"24.263736"},"line_max":{"kind":"number","value":94,"string":"94"},"alpha_frac":{"kind":"number","value":0.5793823401,"string":"0.579382"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.4675716440422324,"string":"3.467572"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45150,"cells":{"repo_name":{"kind":"string","value":"Midrya/chromium"},"path":{"kind":"string","value":"rietveld.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"26054"},"content":{"kind":"string","value":"# coding: utf-8\n# Copyright (c) 2012 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\"\"\"Defines class Rietveld to easily access a rietveld instance.\n\nSecurity implications:\n\nThe following hypothesis are made:\n- Rietveld enforces:\n - Nobody else than issue owner can upload a patch set\n - Verifies the issue owner credentials when creating new issues\n - A issue owner can't change once the issue is created\n - A patch set cannot be modified\n\"\"\"\n\nimport copy\nimport errno\nimport json\nimport logging\nimport re\nimport socket\nimport ssl\nimport sys\nimport time\nimport urllib\nimport urllib2\nimport urlparse\n\nimport patch\n\nfrom third_party import upload\nimport third_party.oauth2client.client as oa2client\nfrom third_party import httplib2\n\n# Appengine replies with 302 when authentication fails (sigh.)\noa2client.REFRESH_STATUS_CODES.append(302)\nupload.LOGGER.setLevel(logging.WARNING) # pylint: disable=E1103\n\n\nclass Rietveld(object):\n \"\"\"Accesses rietveld.\"\"\"\n def __init__(\n self, url, auth_config, email=None, extra_headers=None, maxtries=None):\n self.url = url.rstrip('/')\n self.rpc_server = upload.GetRpcServer(self.url, auth_config, email)\n\n self._xsrf_token = None\n self._xsrf_token_time = None\n\n self._maxtries = maxtries or 40\n\n def xsrf_token(self):\n if (not self._xsrf_token_time or\n (time.time() - self._xsrf_token_time) > 30*60):\n self._xsrf_token_time = time.time()\n self._xsrf_token = self.get(\n '/xsrf_token',\n extra_headers={'X-Requesting-XSRF-Token': '1'})\n return self._xsrf_token\n\n def get_pending_issues(self):\n \"\"\"Returns an array of dict of all the pending issues on the server.\"\"\"\n # TODO: Convert this to use Rietveld::search(), defined below.\n return json.loads(\n self.get('/search?format=json&commit=2&closed=3&'\n 'keys_only=True&limit=1000&order=__key__'))['results']\n\n def close_issue(self, issue):\n \"\"\"Closes the Rietveld issue for this changelist.\"\"\"\n logging.info('closing issue %d' % issue)\n self.post(\"/%d/close\" % issue, [('xsrf_token', self.xsrf_token())])\n\n def get_description(self, issue):\n \"\"\"Returns the issue's description.\n\n Converts any CRLF into LF and strip extraneous whitespace.\n \"\"\"\n return '\\n'.join(self.get('/%d/description' % issue).strip().splitlines())\n\n def get_issue_properties(self, issue, messages):\n \"\"\"Returns all the issue's metadata as a dictionary.\"\"\"\n url = '/api/%d' % issue\n if messages:\n url += '?messages=true'\n data = json.loads(self.get(url, retry_on_404=True))\n data['description'] = '\\n'.join(data['description'].strip().splitlines())\n return data\n\n def get_depends_on_patchset(self, issue, patchset):\n \"\"\"Returns the patchset this patchset depends on if it exists.\"\"\"\n url = '/%d/patchset/%d/get_depends_on_patchset' % (issue, patchset)\n resp = None\n try:\n resp = json.loads(self.post(url, []))\n except (urllib2.HTTPError, ValueError):\n # The get_depends_on_patchset endpoint does not exist on this Rietveld\n # instance yet. Ignore the error and proceed.\n # TODO(rmistry): Make this an error when all Rietveld instances have\n # this endpoint.\n pass\n return resp\n\n def get_patchset_properties(self, issue, patchset):\n \"\"\"Returns the patchset properties.\"\"\"\n url = '/api/%d/%d' % (issue, patchset)\n return json.loads(self.get(url))\n\n def get_file_content(self, issue, patchset, item):\n \"\"\"Returns the content of a new file.\n\n Throws HTTP 302 exception if the file doesn't exist or is not a binary file.\n \"\"\"\n # content = 0 is the old file, 1 is the new file.\n content = 1\n url = '/%d/binary/%d/%d/%d' % (issue, patchset, item, content)\n return self.get(url)\n\n def get_file_diff(self, issue, patchset, item):\n \"\"\"Returns the diff of the file.\n\n Returns a useless diff for binary files.\n \"\"\"\n url = '/download/issue%d_%d_%d.diff' % (issue, patchset, item)\n return self.get(url)\n\n def get_patch(self, issue, patchset):\n \"\"\"Returns a PatchSet object containing the details to apply this patch.\"\"\"\n props = self.get_patchset_properties(issue, patchset) or {}\n out = []\n for filename, state in props.get('files', {}).iteritems():\n logging.debug('%s' % filename)\n # If not status, just assume it's a 'M'. Rietveld often gets it wrong and\n # just has status: null. Oh well.\n status = state.get('status') or 'M'\n if status[0] not in ('A', 'D', 'M', 'R'):\n raise patch.UnsupportedPatchFormat(\n filename, 'Change with status \\'%s\\' is not supported.' % status)\n\n svn_props = self.parse_svn_properties(\n state.get('property_changes', ''), filename)\n\n if state.get('is_binary'):\n if status[0] == 'D':\n if status[0] != status.strip():\n raise patch.UnsupportedPatchFormat(\n filename, 'Deleted file shouldn\\'t have property change.')\n out.append(patch.FilePatchDelete(filename, state['is_binary']))\n else:\n content = self.get_file_content(issue, patchset, state['id'])\n if not content:\n # As a precaution due to a bug in upload.py for git checkout, refuse\n # empty files. If it's empty, it's not a binary file.\n raise patch.UnsupportedPatchFormat(\n filename,\n 'Binary file is empty. Maybe the file wasn\\'t uploaded in the '\n 'first place?')\n out.append(patch.FilePatchBinary(\n filename,\n content,\n svn_props,\n is_new=(status[0] == 'A')))\n continue\n\n try:\n diff = self.get_file_diff(issue, patchset, state['id'])\n except urllib2.HTTPError, e:\n if e.code == 404:\n raise patch.UnsupportedPatchFormat(\n filename, 'File doesn\\'t have a diff.')\n raise\n\n # FilePatchDiff() will detect file deletion automatically.\n p = patch.FilePatchDiff(filename, diff, svn_props)\n out.append(p)\n if status[0] == 'A':\n # It won't be set for empty file.\n p.is_new = True\n if (len(status) > 1 and\n status[1] == '+' and\n not (p.source_filename or p.svn_properties)):\n raise patch.UnsupportedPatchFormat(\n filename, 'Failed to process the svn properties')\n\n return patch.PatchSet(out)\n\n @staticmethod\n def parse_svn_properties(rietveld_svn_props, filename):\n \"\"\"Returns a list of tuple [('property', 'newvalue')].\n\n rietveld_svn_props is the exact format from 'svn diff'.\n \"\"\"\n rietveld_svn_props = rietveld_svn_props.splitlines()\n svn_props = []\n if not rietveld_svn_props:\n return svn_props\n # 1. Ignore svn:mergeinfo.\n # 2. Accept svn:eol-style and svn:executable.\n # 3. Refuse any other.\n # \\n\n # Added: svn:ignore\\n\n # + LF\\n\n\n spacer = rietveld_svn_props.pop(0)\n if spacer or not rietveld_svn_props:\n # svn diff always put a spacer between the unified diff and property\n # diff\n raise patch.UnsupportedPatchFormat(\n filename, 'Failed to parse svn properties.')\n\n while rietveld_svn_props:\n # Something like 'Added: svn:eol-style'. Note the action is localized.\n # *sigh*.\n action = rietveld_svn_props.pop(0)\n match = re.match(r'^(\\w+): (.+)$', action)\n if not match or not rietveld_svn_props:\n raise patch.UnsupportedPatchFormat(\n filename,\n 'Failed to parse svn properties: %s, %s' % (action, svn_props))\n\n if match.group(2) == 'svn:mergeinfo':\n # Silently ignore the content.\n rietveld_svn_props.pop(0)\n continue\n\n if match.group(1) not in ('Added', 'Modified'):\n # Will fail for our French friends.\n raise patch.UnsupportedPatchFormat(\n filename, 'Unsupported svn property operation.')\n\n if match.group(2) in ('svn:eol-style', 'svn:executable', 'svn:mime-type'):\n # ' + foo' where foo is the new value. That's fragile.\n content = rietveld_svn_props.pop(0)\n match2 = re.match(r'^ \\+ (.*)$', content)\n if not match2:\n raise patch.UnsupportedPatchFormat(\n filename, 'Unsupported svn property format.')\n svn_props.append((match.group(2), match2.group(1)))\n return svn_props\n\n def update_description(self, issue, description):\n \"\"\"Sets the description for an issue on Rietveld.\"\"\"\n logging.info('new description for issue %d' % issue)\n self.post('/%d/description' % issue, [\n ('description', description),\n ('xsrf_token', self.xsrf_token())])\n\n def add_comment(self, issue, message, add_as_reviewer=False):\n max_message = 10000\n tail = '…\\n(message too large)'\n if len(message) > max_message:\n message = message[:max_message-len(tail)] + tail\n logging.info('issue %d; comment: %s' % (issue, message.strip()[:300]))\n return self.post('/%d/publish' % issue, [\n ('xsrf_token', self.xsrf_token()),\n ('message', message),\n ('message_only', 'True'),\n ('add_as_reviewer', str(bool(add_as_reviewer))),\n ('send_mail', 'True'),\n ('no_redirect', 'True')])\n\n def add_inline_comment(\n self, issue, text, side, snapshot, patchset, patchid, lineno):\n logging.info('add inline comment for issue %d' % issue)\n return self.post('/inline_draft', [\n ('issue', str(issue)),\n ('text', text),\n ('side', side),\n ('snapshot', snapshot),\n ('patchset', str(patchset)),\n ('patch', str(patchid)),\n ('lineno', str(lineno))])\n\n def set_flag(self, issue, patchset, flag, value):\n return self.post('/%d/edit_flags' % issue, [\n ('last_patchset', str(patchset)),\n ('xsrf_token', self.xsrf_token()),\n (flag, str(value))])\n\n def search(\n self,\n owner=None, reviewer=None,\n base=None,\n closed=None, private=None, commit=None,\n created_before=None, created_after=None,\n modified_before=None, modified_after=None,\n per_request=None, keys_only=False,\n with_messages=False):\n \"\"\"Yields search results.\"\"\"\n # These are expected to be strings.\n string_keys = {\n 'owner': owner,\n 'reviewer': reviewer,\n 'base': base,\n 'created_before': created_before,\n 'created_after': created_after,\n 'modified_before': modified_before,\n 'modified_after': modified_after,\n }\n # These are either None, False or True.\n three_state_keys = {\n 'closed': closed,\n 'private': private,\n 'commit': commit,\n }\n\n url = '/search?format=json'\n # Sort the keys mainly to ease testing.\n for key in sorted(string_keys):\n value = string_keys[key]\n if value:\n url += '&%s=%s' % (key, urllib2.quote(value))\n for key in sorted(three_state_keys):\n value = three_state_keys[key]\n if value is not None:\n url += '&%s=%d' % (key, int(value) + 1)\n\n if keys_only:\n url += '&keys_only=True'\n if with_messages:\n url += '&with_messages=True'\n if per_request:\n url += '&limit=%d' % per_request\n\n cursor = ''\n while True:\n output = self.get(url + cursor)\n if output.startswith('<'):\n # It's an error message. Return as no result.\n break\n data = json.loads(output) or {}\n if not data.get('results'):\n break\n for i in data['results']:\n yield i\n cursor = '&cursor=%s' % data['cursor']\n\n def trigger_try_jobs(\n self, issue, patchset, reason, clobber, revision, builders_and_tests,\n master=None, category='cq'):\n \"\"\"Requests new try jobs.\n\n |builders_and_tests| is a map of builders: [tests] to run.\n |master| is the name of the try master the builders belong to.\n |category| is used to distinguish regular jobs and experimental jobs.\n\n Returns the keys of the new TryJobResult entites.\n \"\"\"\n params = [\n ('reason', reason),\n ('clobber', 'True' if clobber else 'False'),\n ('builders', json.dumps(builders_and_tests)),\n ('xsrf_token', self.xsrf_token()),\n ('category', category),\n ]\n if revision:\n params.append(('revision', revision))\n if master:\n # Temporarily allow empty master names for old configurations. The try\n # job will not be associated with a master name on rietveld. This is\n # going to be deprecated.\n params.append(('master', master))\n return self.post('/%d/try/%d' % (issue, patchset), params)\n\n def trigger_distributed_try_jobs(\n self, issue, patchset, reason, clobber, revision, masters,\n category='cq'):\n \"\"\"Requests new try jobs.\n\n |masters| is a map of masters: map of builders: [tests] to run.\n |category| is used to distinguish regular jobs and experimental jobs.\n \"\"\"\n for (master, builders_and_tests) in masters.iteritems():\n self.trigger_try_jobs(\n issue, patchset, reason, clobber, revision, builders_and_tests,\n master, category)\n\n def get_pending_try_jobs(self, cursor=None, limit=100):\n \"\"\"Retrieves the try job requests in pending state.\n\n Returns a tuple of the list of try jobs and the cursor for the next request.\n \"\"\"\n url = '/get_pending_try_patchsets?limit=%d' % limit\n extra = ('&cursor=' + cursor) if cursor else ''\n data = json.loads(self.get(url + extra))\n return data['jobs'], data['cursor']\n\n def get(self, request_path, **kwargs):\n kwargs.setdefault('payload', None)\n return self._send(request_path, **kwargs)\n\n def post(self, request_path, data, **kwargs):\n ctype, body = upload.EncodeMultipartFormData(data, [])\n return self._send(request_path, payload=body, content_type=ctype, **kwargs)\n\n def _send(self, request_path, retry_on_404=False, **kwargs):\n \"\"\"Sends a POST/GET to Rietveld. Returns the response body.\"\"\"\n # rpc_server.Send() assumes timeout=None by default; make sure it's set\n # to something reasonable.\n kwargs.setdefault('timeout', 15)\n logging.debug('POSTing to %s, args %s.', request_path, kwargs)\n try:\n # Sadly, upload.py calls ErrorExit() which does a sys.exit(1) on HTTP\n # 500 in AbstractRpcServer.Send().\n old_error_exit = upload.ErrorExit\n def trap_http_500(msg):\n \"\"\"Converts an incorrect ErrorExit() call into a HTTPError exception.\"\"\"\n m = re.search(r'(50\\d) Server Error', msg)\n if m:\n # Fake an HTTPError exception. Cheezy. :(\n raise urllib2.HTTPError(\n request_path, int(m.group(1)), msg, None, None)\n old_error_exit(msg)\n upload.ErrorExit = trap_http_500\n\n for retry in xrange(self._maxtries):\n try:\n logging.debug('%s' % request_path)\n result = self.rpc_server.Send(request_path, **kwargs)\n # Sometimes GAE returns a HTTP 200 but with HTTP 500 as the content.\n # How nice.\n return result\n except urllib2.HTTPError, e:\n if retry >= (self._maxtries - 1):\n raise\n flake_codes = [500, 502, 503]\n if retry_on_404:\n flake_codes.append(404)\n if e.code not in flake_codes:\n raise\n except urllib2.URLError, e:\n if retry >= (self._maxtries - 1):\n raise\n if (not 'Name or service not known' in e.reason and\n not 'EOF occurred in violation of protocol' in e.reason and\n # On windows we hit weird bug http://crbug.com/537417\n # with message '[Errno 10060] A connection attempt failed...'\n not (sys.platform.startswith('win') and\n isinstance(e.reason, socket.error) and\n e.reason.errno == errno.ETIMEDOUT\n )\n ):\n # Usually internal GAE flakiness.\n raise\n except ssl.SSLError, e:\n if retry >= (self._maxtries - 1):\n raise\n if not 'timed out' in str(e):\n raise\n # If reaching this line, loop again. Uses a small backoff.\n time.sleep(min(10, 1+retry*2))\n except urllib2.HTTPError as e:\n print 'Request to %s failed: %s' % (e.geturl(), e.read())\n raise\n finally:\n upload.ErrorExit = old_error_exit\n\n # DEPRECATED.\n Send = get\n\n\nclass OAuthRpcServer(object):\n def __init__(self,\n host,\n client_email,\n client_private_key,\n private_key_password='notasecret',\n user_agent=None,\n timeout=None,\n extra_headers=None):\n \"\"\"Wrapper around httplib2.Http() that handles authentication.\n\n client_email: email associated with the service account\n client_private_key: encrypted private key, as a string\n private_key_password: password used to decrypt the private key\n \"\"\"\n\n # Enforce https\n host_parts = urlparse.urlparse(host)\n\n if host_parts.scheme == 'https': # fine\n self.host = host\n elif host_parts.scheme == 'http':\n upload.logging.warning('Changing protocol to https')\n self.host = 'https' + host[4:]\n else:\n msg = 'Invalid url provided: %s' % host\n upload.logging.error(msg)\n raise ValueError(msg)\n\n self.host = self.host.rstrip('/')\n\n self.extra_headers = extra_headers or {}\n\n if not oa2client.HAS_OPENSSL:\n logging.error(\"No support for OpenSSL has been found, \"\n \"OAuth2 support requires it.\")\n logging.error(\"Installing pyopenssl will probably solve this issue.\")\n raise RuntimeError('No OpenSSL support')\n self.creds = oa2client.SignedJwtAssertionCredentials(\n client_email,\n client_private_key,\n 'https://www.googleapis.com/auth/userinfo.email',\n private_key_password=private_key_password,\n user_agent=user_agent)\n\n self._http = self.creds.authorize(httplib2.Http(timeout=timeout))\n\n def Send(self,\n request_path,\n payload=None,\n content_type='application/octet-stream',\n timeout=None,\n extra_headers=None,\n **kwargs):\n \"\"\"Send a POST or GET request to the server.\n\n Args:\n request_path: path on the server to hit. This is concatenated with the\n value of 'host' provided to the constructor.\n payload: request is a POST if not None, GET otherwise\n timeout: in seconds\n extra_headers: (dict)\n \"\"\"\n # This method signature should match upload.py:AbstractRpcServer.Send()\n method = 'GET'\n\n headers = self.extra_headers.copy()\n headers.update(extra_headers or {})\n\n if payload is not None:\n method = 'POST'\n headers['Content-Type'] = content_type\n\n prev_timeout = self._http.timeout\n try:\n if timeout:\n self._http.timeout = timeout\n # TODO(pgervais) implement some kind of retry mechanism (see upload.py).\n url = self.host + request_path\n if kwargs:\n url += \"?\" + urllib.urlencode(kwargs)\n\n # This weird loop is there to detect when the OAuth2 token has expired.\n # This is specific to appengine *and* rietveld. It relies on the\n # assumption that a 302 is triggered only by an expired OAuth2 token. This\n # prevents any usage of redirections in pages accessed this way.\n\n # This variable is used to make sure the following loop runs only twice.\n redirect_caught = False\n while True:\n try:\n ret = self._http.request(url,\n method=method,\n body=payload,\n headers=headers,\n redirections=0)\n except httplib2.RedirectLimit:\n if redirect_caught or method != 'GET':\n logging.error('Redirection detected after logging in. Giving up.')\n raise\n redirect_caught = True\n logging.debug('Redirection detected. Trying to log in again...')\n self.creds.access_token = None\n continue\n break\n\n return ret[1]\n\n finally:\n self._http.timeout = prev_timeout\n\n\nclass JwtOAuth2Rietveld(Rietveld):\n \"\"\"Access to Rietveld using OAuth authentication.\n\n This class is supposed to be used only by bots, since this kind of\n access is restricted to service accounts.\n \"\"\"\n # The parent__init__ is not called on purpose.\n # pylint: disable=W0231\n def __init__(self,\n url,\n client_email,\n client_private_key_file,\n private_key_password=None,\n extra_headers=None,\n maxtries=None):\n\n if private_key_password is None: # '' means 'empty password'\n private_key_password = 'notasecret'\n\n self.url = url.rstrip('/')\n bot_url = self.url\n if self.url.endswith('googleplex.com'):\n bot_url = self.url + '/bots'\n\n with open(client_private_key_file, 'rb') as f:\n client_private_key = f.read()\n logging.info('Using OAuth login: %s' % client_email)\n self.rpc_server = OAuthRpcServer(bot_url,\n client_email,\n client_private_key,\n private_key_password=private_key_password,\n extra_headers=extra_headers or {})\n self._xsrf_token = None\n self._xsrf_token_time = None\n\n self._maxtries = maxtries or 40\n\n\nclass CachingRietveld(Rietveld):\n \"\"\"Caches the common queries.\n\n Not to be used in long-standing processes, like the commit queue.\n \"\"\"\n def __init__(self, *args, **kwargs):\n super(CachingRietveld, self).__init__(*args, **kwargs)\n self._cache = {}\n\n def _lookup(self, function_name, args, update):\n \"\"\"Caches the return values corresponding to the arguments.\n\n It is important that the arguments are standardized, like None vs False.\n \"\"\"\n function_cache = self._cache.setdefault(function_name, {})\n if args not in function_cache:\n function_cache[args] = update(*args)\n return copy.deepcopy(function_cache[args])\n\n def get_description(self, issue):\n return self._lookup(\n 'get_description',\n (issue,),\n super(CachingRietveld, self).get_description)\n\n def get_issue_properties(self, issue, messages):\n \"\"\"Returns the issue properties.\n\n Because in practice the presubmit checks often ask without messages first\n and then with messages, always ask with messages and strip off if not asked\n for the messages.\n \"\"\"\n # It's a tad slower to request with the message but it's better than\n # requesting the properties twice.\n data = self._lookup(\n 'get_issue_properties',\n (issue, True),\n super(CachingRietveld, self).get_issue_properties)\n if not messages:\n # Assumes self._lookup uses deepcopy.\n del data['messages']\n return data\n\n def get_patchset_properties(self, issue, patchset):\n return self._lookup(\n 'get_patchset_properties',\n (issue, patchset),\n super(CachingRietveld, self).get_patchset_properties)\n\n\nclass ReadOnlyRietveld(object):\n \"\"\"\n Only provides read operations, and simulates writes locally.\n\n Intentionally do not inherit from Rietveld to avoid any write-issuing\n logic to be invoked accidentally.\n \"\"\"\n\n # Dictionary of local changes, indexed by issue number as int.\n _local_changes = {}\n\n def __init__(self, *args, **kwargs):\n # We still need an actual Rietveld instance to issue reads, just keep\n # it hidden.\n self._rietveld = Rietveld(*args, **kwargs)\n\n @classmethod\n def _get_local_changes(cls, issue):\n \"\"\"Returns dictionary of local changes for |issue|, if any.\"\"\"\n return cls._local_changes.get(issue, {})\n\n @property\n def url(self):\n return self._rietveld.url\n\n def get_pending_issues(self):\n pending_issues = self._rietveld.get_pending_issues()\n\n # Filter out issues we've closed or unchecked the commit checkbox.\n return [issue for issue in pending_issues\n if not self._get_local_changes(issue).get('closed', False) and\n self._get_local_changes(issue).get('commit', True)]\n\n def close_issue(self, issue): # pylint:disable=R0201\n logging.info('ReadOnlyRietveld: closing issue %d' % issue)\n ReadOnlyRietveld._local_changes.setdefault(issue, {})['closed'] = True\n\n def get_issue_properties(self, issue, messages):\n data = self._rietveld.get_issue_properties(issue, messages)\n data.update(self._get_local_changes(issue))\n return data\n\n def get_patchset_properties(self, issue, patchset):\n return self._rietveld.get_patchset_properties(issue, patchset)\n\n def get_depends_on_patchset(self, issue, patchset):\n return self._rietveld.get_depends_on_patchset(issue, patchset)\n\n def get_patch(self, issue, patchset):\n return self._rietveld.get_patch(issue, patchset)\n\n def update_description(self, issue, description): # pylint:disable=R0201\n logging.info('ReadOnlyRietveld: new description for issue %d: %s' %\n (issue, description))\n\n def add_comment(self, # pylint:disable=R0201\n issue,\n message,\n add_as_reviewer=False):\n logging.info('ReadOnlyRietveld: posting comment \"%s\" to issue %d' %\n (message, issue))\n\n def set_flag(self, issue, patchset, flag, value): # pylint:disable=R0201\n logging.info('ReadOnlyRietveld: setting flag \"%s\" to \"%s\" for issue %d' %\n (flag, value, issue))\n ReadOnlyRietveld._local_changes.setdefault(issue, {})[flag] = value\n\n def trigger_try_jobs( # pylint:disable=R0201\n self, issue, patchset, reason, clobber, revision, builders_and_tests,\n master=None, category='cq'):\n logging.info('ReadOnlyRietveld: triggering try jobs %r for issue %d' %\n (builders_and_tests, issue))\n\n def trigger_distributed_try_jobs( # pylint:disable=R0201\n self, issue, patchset, reason, clobber, revision, masters,\n category='cq'):\n logging.info('ReadOnlyRietveld: triggering try jobs %r for issue %d' %\n (masters, issue))\n"},"license":{"kind":"string","value":"bsd-3-clause"},"hash":{"kind":"number","value":759426349750002600,"string":"759,426,349,750,002,600"},"line_mean":{"kind":"number","value":34.2530446549,"string":"34.253045"},"line_max":{"kind":"number","value":80,"string":"80"},"alpha_frac":{"kind":"number","value":0.6201827115,"string":"0.620183"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.8015467678389028,"string":"3.801547"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45151,"cells":{"repo_name":{"kind":"string","value":"gonicus/gosa"},"path":{"kind":"string","value":"backend/src/gosa/backend/plugins/samba/logonhours.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"2755"},"content":{"kind":"string","value":"# This file is part of the GOsa framework.\n#\n# http://gosa-project.org\n#\n# Copyright:\n# (C) 2016 GONICUS GmbH, Germany, http://www.gonicus.de\n#\n# See the LICENSE file in the project's top-level directory for details.\n\nimport time\nfrom gosa.backend.objects.types import AttributeType\n\n\nclass SambaLogonHoursAttribute(AttributeType):\n \"\"\"\n This is a special object-attribute-type for sambaLogonHours.\n\n This call can convert sambaLogonHours to a UnicodeString and vice versa.\n It is used in the samba-object definition file.\n \"\"\"\n\n __alias__ = \"SambaLogonHours\"\n\n def values_match(self, value1, value2):\n return str(value1) == str(value2)\n\n def is_valid_value(self, value):\n if len(value):\n try:\n\n # Check if each week day contains 24 values.\n if type(value[0]) is not str or len(value[0]) != 168 or len(set(value[0]) - set('01')):\n return False\n return True\n\n except:\n return False\n\n def _convert_to_unicodestring(self, value):\n \"\"\"\n This method is a converter used when values gets read from or written to the backend.\n\n Converts the 'SambaLogonHours' object-type into a 'UnicodeString'-object.\n \"\"\"\n if len(value):\n\n # Combine the binary strings\n lstr = value[0]\n\n # New reverse every 8 bit part, and toggle high- and low-tuple (4Bits)\n new = \"\"\n for i in range(0, 21):\n n = lstr[i * 8:((i + 1) * 8)]\n n = n[0:4] + n[4:]\n n = n[::-1]\n n = str(hex(int(n, 2)))[2::].rjust(2, '0')\n new += n\n value = [new.upper()]\n\n return value\n\n def _convert_from_string(self, value):\n return self._convert_from_unicodestring(value)\n\n def _convert_from_unicodestring(self, value):\n \"\"\"\n This method is a converter used when values gets read from or written to the backend.\n\n Converts a 'UnicodeString' attribute into the 'SambaLogonHours' object-type.\n \"\"\"\n\n if len(value):\n\n # Convert each hex-pair into binary values.\n # Then reverse the binary result and switch high and low pairs.\n value = value[0]\n lstr = \"\"\n for i in range(0, 42, 2):\n n = (bin(int(value[i:i + 2], 16))[2::]).rjust(8, '0')\n n = n[::-1]\n lstr += n[0:4] + n[4:]\n\n # Shift lster by timezone offset\n shift_by = int((168 + (time.timezone/3600)) % 168)\n lstr = lstr[shift_by:] + lstr[:shift_by]\n\n # Parse result into more readable value\n value = [lstr]\n\n return value\n"},"license":{"kind":"string","value":"lgpl-2.1"},"hash":{"kind":"number","value":5620265410477604000,"string":"5,620,265,410,477,604,000"},"line_mean":{"kind":"number","value":29.6111111111,"string":"29.611111"},"line_max":{"kind":"number","value":103,"string":"103"},"alpha_frac":{"kind":"number","value":0.5495462795,"string":"0.549546"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.8370473537604455,"string":"3.837047"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45152,"cells":{"repo_name":{"kind":"string","value":"mice-software/maus"},"path":{"kind":"string","value":"tests/integration/test_simulation/test_beam_maker/binomial_beam_config.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"4151"},"content":{"kind":"string","value":"# This file is part of MAUS: http://micewww.pp.rl.ac.uk:8080/projects/maus\n#\n# MAUS is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# MAUS is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with MAUS. If not, see .\n\n\"\"\"\nConfiguration to generate a beam distribution with binomial distribution in\nthe spill and various distributions for difference particle types\n\"\"\"\n\n#pylint: disable = C0103, R0801\n\nimport os\nmrd = os.environ[\"MAUS_ROOT_DIR\"]\n\nsimulation_geometry_filename = os.path.join(\n mrd, \"tests\", \"integration\", \"test_simulation\", \"test_beam_maker\", \n \"BeamTest.dat\"\n)\noutput_root_file_name = os.path.join(mrd, \"tmp\", \"test_beammaker_output.root\")\ninput_root_file_name = output_root_file_name # for conversion\n\nspill_generator_number_of_spills = 1000\nverbose_level = 1\nbeam = {\n \"particle_generator\":\"binomial\", # routine for generating empty primaries\n \"binomial_n\":20, # number of coin tosses\n \"binomial_p\":0.1, # probability of making a particle on each toss\n \"random_seed\":5, # random seed for beam generation; controls also how the MC\n # seeds are generated\n \"definitions\":[\n ##### MUONS #######\n {\n \"reference\":{\n \"position\":{\"x\":0.0, \"y\":0.0, \"z\":3.0},\n \"momentum\":{\"x\":0.0, \"y\":0.0, \"z\":1.0},\n \"spin\":{\"x\":0.0, \"y\":0.0, \"z\":1.0},\n \"particle_id\":-13,\n \"energy\":226.0,\n \"time\":2.e6,\n \"random_seed\":0\n }, # reference particle\n \"random_seed_algorithm\":\"incrementing_random\", # algorithm for seeding MC\n \"weight\":90., # probability of generating a particle\n \"transverse\":{\n \"transverse_mode\":\"penn\", \n \"emittance_4d\":6., \n \"beta_4d\":333.,\n \"alpha_4d\":1., \n \"normalised_angular_momentum\":2.,\n \"bz\":4.e-3\n },\n \"longitudinal\":{\n \"longitudinal_mode\":\"sawtooth_time\",\n \"momentum_variable\":\"p\",\n \"sigma_p\":25.,\n \"t_start\":-1.e6,\n \"t_end\":+1.e6},\n \"coupling\":{\"coupling_mode\":\"none\"}\n },\n ##### PIONS #####\n { # as above...\n \"reference\":{\n \"position\":{\"x\":0.0, \"y\":-0.0, \"z\":0.0},\n \"momentum\":{\"x\":0.0, \"y\":0.0, \"z\":1.0},\n \"spin\":{\"x\":0.0, \"y\":0.0, \"z\":1.0},\n \"particle_id\":211, \"energy\":285.0, \"time\":0.0, \"random_seed\":10\n },\n \"random_seed_algorithm\":\"incrementing_random\",\n \"weight\":2.,\n \"transverse\":{\"transverse_mode\":\"constant_solenoid\", \"emittance_4d\":6.,\n \"normalised_angular_momentum\":0.1, \"bz\":4.e-3},\n \"longitudinal\":{\"longitudinal_mode\":\"uniform_time\",\n \"momentum_variable\":\"p\",\n \"sigma_p\":25.,\n \"t_start\":-1.e6,\n \"t_end\":+1.e6},\n \"coupling\":{\"coupling_mode\":\"none\"}\n },\n ##### ELECTRONS #####\n { # as above...\n \"reference\":{\n \"position\":{\"x\":0.0, \"y\":-0.0, \"z\":0.0},\n \"momentum\":{\"x\":0.0, \"y\":0.0, \"z\":1.0},\n \"spin\":{\"x\":0.0, \"y\":0.0, \"z\":1.0},\n \"particle_id\":-11, \"energy\":200.0, \"time\":0.0, \"random_seed\":10\n },\n \"random_seed_algorithm\":\"incrementing_random\",\n \"weight\":8.,\n \"transverse\":{\"transverse_mode\":\"constant_solenoid\", \"emittance_4d\":6.,\n \"normalised_angular_momentum\":0.1, \"bz\":4.e-3},\n \"longitudinal\":{\"longitudinal_mode\":\"uniform_time\",\n \"momentum_variable\":\"p\",\n \"sigma_p\":25.,\n \"t_start\":-2.e6,\n \"t_end\":+1.e6},\n \"coupling\":{\"coupling_mode\":\"none\"}\n }]\n}\n"},"license":{"kind":"string","value":"gpl-3.0"},"hash":{"kind":"number","value":8497676633273780000,"string":"8,497,676,633,273,780,000"},"line_mean":{"kind":"number","value":37.0825688073,"string":"37.082569"},"line_max":{"kind":"number","value":80,"string":"80"},"alpha_frac":{"kind":"number","value":0.544688027,"string":"0.544688"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.245504300234558,"string":"3.245504"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45153,"cells":{"repo_name":{"kind":"string","value":"amagnus/pulsegig"},"path":{"kind":"string","value":"app/models.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"1894"},"content":{"kind":"string","value":"from django.db import models\nfrom django.contrib.auth.models import User\n\n\nclass Guy(models.Model):\n user = models.OneToOneField(User, primary_key=True)\n cell = models.CharField(max_length=15)\n metroarea_name = models.CharField(max_length=30, default=None, null=True)\n metroareaID = models.IntegerField(default=None, null=True)\n created = models.DateTimeField(auto_now_add=True)\n\n def __unicode__(self):\n return self.user\n\n\nclass Band(models.Model):\n name = models.CharField(max_length=100)\n genre = models.CharField(max_length=100)\n skID = models.IntegerField()\n created = models.DateTimeField(auto_now_add=True)\n\n def __unicode__(self):\n return self.name\n\n\nclass SimilarBand(models.Model):\n band_input = models.ForeignKey(Band, related_name='band_input')\n band_suggest = models.ForeignKey(Band, related_name='band_suggest')\n disabled = models.BooleanField(default=False)\n created = models.DateTimeField(auto_now_add=True)\n modified = models.DateTimeField(auto_now=True)\n\n def __unicode__(self):\n return self.band_input.name\n\n\nclass Alert(models.Model):\n user = models.ForeignKey(User)\n band = models.ForeignKey(Band)\n disabled = models.BooleanField(default=False)\n created = models.DateTimeField(auto_now_add=True)\n\n def __unicode__(self):\n return self.band.name\n\n\nclass AlertLog(models.Model):\n user = models.ForeignKey(User)\n band = models.ForeignKey(Band)\n eventskID = models.IntegerField(default=None)\n showDate = models.DateField()\n showURL = models.CharField(max_length=255)\n is_similar = models.BooleanField(default=False)\n send_on = models.DateTimeField()\n has_sent = models.BooleanField(default=False)\n created = models.DateTimeField(auto_now_add=True)\n modified = models.DateTimeField(auto_now=True)\n\n def __unicode__(self):\n return self.band.name\n"},"license":{"kind":"string","value":"mit"},"hash":{"kind":"number","value":-6112383756835243000,"string":"-6,112,383,756,835,243,000"},"line_mean":{"kind":"number","value":30.5666666667,"string":"30.566667"},"line_max":{"kind":"number","value":77,"string":"77"},"alpha_frac":{"kind":"number","value":0.7059134108,"string":"0.705913"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.7430830039525693,"string":"3.743083"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45154,"cells":{"repo_name":{"kind":"string","value":"PyBossa/pybossa"},"path":{"kind":"string","value":"pybossa/auth/token.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"1271"},"content":{"kind":"string","value":"# -*- coding: utf8 -*-\n# This file is part of PYBOSSA.\n#\n# Copyright (C) 2015 Scifabric LTD.\n#\n# PYBOSSA is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# PYBOSSA is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with PYBOSSA. If not, see .\n\n\nclass TokenAuth(object):\n _specific_actions = []\n\n @property\n def specific_actions(self):\n return self._specific_actions\n\n def can(self, user, action, _, token=None):\n action = ''.join(['_', action])\n return getattr(self, action)(user, token)\n\n def _create(self, user, token=None):\n return False\n\n def _read(self, user, token=None):\n return not user.is_anonymous()\n\n def _update(self, user, token):\n return False\n\n def _delete(self, user, token):\n return False\n"},"license":{"kind":"string","value":"agpl-3.0"},"hash":{"kind":"number","value":7030215194736983000,"string":"7,030,215,194,736,983,000"},"line_mean":{"kind":"number","value":30,"string":"30"},"line_max":{"kind":"number","value":77,"string":"77"},"alpha_frac":{"kind":"number","value":0.6837136113,"string":"0.683714"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.875,"string":"3.875"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45155,"cells":{"repo_name":{"kind":"string","value":"ekumenlabs/terminus"},"path":{"kind":"string","value":"terminus/generators/rndf_id_mapper.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"2695"},"content":{"kind":"string","value":"\"\"\"\nCopyright (C) 2017 Open Source Robotics Foundation\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nfrom city_visitor import CityVisitor\nfrom models.polyline_geometry import PolylineGeometry\n\n\nclass RNDFIdMapper(CityVisitor):\n \"\"\"Simple city visitor that generates the RNDF ids for segments,\n lanes and waypoints. Ids and objects are stored in two dictionaries,\n so we can later perform lookups in either way\"\"\"\n\n # Note: For the time being we treat streets and trunks in the same way,\n # hence generating a single lane for any of them. This will change in the\n # future, when we properly support multi-lanes trunks.\n\n def run(self):\n self.segment_id = 0\n self.waypoint_id = 0\n self.lane_id = 0\n self.object_to_id_level_1 = {}\n self.object_to_id_level_2 = {}\n self.id_to_object = {}\n super(RNDFIdMapper, self).run()\n\n def id_for(self, object):\n try:\n return self.object_to_id_level_1[id(object)]\n except KeyError:\n return self.object_to_id_level_2[object]\n\n def object_for(self, id):\n return self.id_to_object[id]\n\n def map_road(self, road):\n self.segment_id = self.segment_id + 1\n self.lane_id = 0\n self._register(str(self.segment_id), road)\n\n def start_street(self, street):\n self.map_road(street)\n\n def start_trunk(self, trunk):\n self.map_road(trunk)\n\n def start_lane(self, lane):\n self.lane_id = self.lane_id + 1\n rndf_lane_id = str(self.segment_id) + '.' + str(self.lane_id)\n self._register(rndf_lane_id, lane)\n self.waypoint_id = 0\n for waypoint in lane.waypoints_for(PolylineGeometry):\n self.waypoint_id = self.waypoint_id + 1\n rndf_waypoint_id = rndf_lane_id + '.' + str(self.waypoint_id)\n self._register(rndf_waypoint_id, waypoint)\n\n def _register(self, rndf_id, object):\n \"\"\"We do some caching by id, to avoid computing hashes if they are\n expensive, but keep the hash-based dict as a fallback\"\"\"\n self.object_to_id_level_1[id(object)] = rndf_id\n self.object_to_id_level_2[object] = rndf_id\n self.id_to_object[rndf_id] = object\n"},"license":{"kind":"string","value":"apache-2.0"},"hash":{"kind":"number","value":-5815910434938483000,"string":"-5,815,910,434,938,483,000"},"line_mean":{"kind":"number","value":35.4189189189,"string":"35.418919"},"line_max":{"kind":"number","value":77,"string":"77"},"alpha_frac":{"kind":"number","value":0.6612244898,"string":"0.661224"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.550724637681159,"string":"3.550725"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45156,"cells":{"repo_name":{"kind":"string","value":"wkia/kodi-addon-repo"},"path":{"kind":"string","value":"plugin.audio.openlast/default.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"6672"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\n\nimport os\nimport sys\nimport urllib\nimport urlparse\nimport xbmcaddon\nimport xbmcgui\nimport xbmcplugin\n\nif sys.version_info < (2, 7):\n import simplejson as json\nelse:\n import json\n\nfrom logging import log\nfrom util import build_url\n\n__addon__ = xbmcaddon.Addon()\n#__addonid__ = __addon__.getAddonInfo('id')\n#__settings__ = xbmcaddon.Addon(id='xbmc-vk.svoka.com')\n#__language__ = __settings__.getLocalizedString\n#LANGUAGE = __addon__.getLocalizedString\nADDONVERSION = __addon__.getAddonInfo('version')\nCWD = __addon__.getAddonInfo('path').decode(\"utf-8\")\n\nlog('start -----------------------------------------------------')\nlog('script version %s started' % ADDONVERSION)\n\n#xbmc.log(str(sys.argv))\naddonUrl = sys.argv[0]\naddon_handle = int(sys.argv[1])\nargs = urlparse.parse_qs(sys.argv[2][1:])\n\n#my_addon = xbmcaddon.Addon()\n# lastfmUser = my_addon.getSetting('lastfm_username')\n\nxbmcplugin.setContent(addon_handle, 'audio')\n\nlastfmApi = 'http://ws.audioscrobbler.com/2.0/'\nlastfmApiKey = '47608ece2138b2edae9538f83f703457' # TODO use Openlast key\n\nlastfmAddon = None\nlastfmUser = ''\ntry:\n lastfmAddon = xbmcaddon.Addon('service.scrobbler.lastfm')\n lastfmUser = lastfmAddon.getSetting('lastfmuser')\nexcept RuntimeError:\n pass\n\n#xbmc.log(str(args))\naction = args.get('action', None)\nfolder = args.get('folder', None)\n\n#xbmc.log('openlast: folder=' + str(folder)) #, xbmc.LOGDEBUG)\n#xbmc.log('openlast: action=' + str(action)) #, xbmc.LOGDEBUG)\n\nif folder is None:\n\n url = build_url(addonUrl, {'folder': 'similarArtist'})\n li = xbmcgui.ListItem('Similar artist radio', iconImage='DefaultFolder.png')\n xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li, isFolder=True)\n\n if '' != lastfmUser:\n url = build_url(addonUrl, {'folder': 'lastfm', 'username': lastfmUser})\n # xbmc.log(url)\n li = xbmcgui.ListItem('Personal radio for Last.fm user: ' + lastfmUser, iconImage='DefaultFolder.png')\n xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li, isFolder=True)\n\n url = build_url(addonUrl, {'folder': 'lastfm'})\n li = xbmcgui.ListItem('Personal radio for Last.fm user...', iconImage='DefaultFolder.png')\n xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li, isFolder=True)\n\n xbmcplugin.endOfDirectory(addon_handle)\n\nelif folder[0] == 'lastfm':\n\n username = ''\n if None != args.get('username'):\n username = args.get('username')[0]\n\n playcount = 0\n if None != args.get('playcount'):\n playcount = int(args.get('playcount')[0])\n\n if username == '':\n user_keyboard = xbmc.Keyboard()\n user_keyboard.setHeading('Last.FM user name') # __language__(30001))\n user_keyboard.setHiddenInput(False)\n user_keyboard.setDefault(lastfmUser)\n user_keyboard.doModal()\n if user_keyboard.isConfirmed():\n username = user_keyboard.getText()\n else:\n raise Exception(\"Login input was cancelled.\")\n\n if action is None:\n url = build_url(lastfmApi, {'method': 'user.getInfo', 'user': username,\n 'format': 'json', 'api_key': lastfmApiKey})\n reply = urllib.urlopen(url)\n resp = json.load(reply)\n if \"error\" in resp:\n raise Exception(\"Error! DATA: \" + str(resp))\n else:\n # xbmc.log(str(resp))\n pass\n\n playcount = int(resp['user']['playcount'])\n img = resp['user']['image'][2]['#text']\n if '' == img:\n img = 'DefaultAudio.png'\n\n url = build_url(addonUrl, {'folder': folder[0], 'action': 'lovedTracks', 'username': username})\n li = xbmcgui.ListItem('Listen to loved tracks', iconImage=img)\n xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li, isFolder=False)\n\n url = build_url(addonUrl, {'folder': folder[0], 'action': 'topTracks', 'username': username, 'playcount': playcount})\n li = xbmcgui.ListItem('Listen to track library', iconImage=img)\n xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li, isFolder=False)\n\n url = build_url(addonUrl, {'folder': folder[0], 'action': 'topArtists', 'username': username, 'playcount': playcount})\n li = xbmcgui.ListItem('Listen to artist library', iconImage=img)\n xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li, isFolder=False)\n\n url = build_url(addonUrl, {'folder': folder[0], 'action': 'syncLibrary', 'username': username, 'playcount': playcount})\n li = xbmcgui.ListItem('[EXPERIMENTAL] Syncronize library to folder', iconImage=img)\n xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li, isFolder=False)\n\n xbmcplugin.endOfDirectory(addon_handle)\n\n elif action[0] == 'lovedTracks':\n script = os.path.join(CWD, \"run_app.py\")\n log('running script %s...' % script)\n xbmc.executebuiltin('XBMC.RunScript(%s, %s, %s)' % (script, action[0], username))\n\n elif action[0] == 'topTracks':\n script = os.path.join(CWD, \"run_app.py\")\n log('running script %s...' % script)\n xbmc.executebuiltin('XBMC.RunScript(%s, %s, %s, %s)' % (script, action[0], username, playcount))\n\n elif action[0] == 'topArtists':\n script = os.path.join(CWD, \"run_app.py\")\n log('running script %s...' % script)\n xbmc.executebuiltin('XBMC.RunScript(%s, %s, %s, %s)' % (script, action[0], username, playcount))\n\n elif action[0] == 'syncLibrary':\n script = os.path.join(CWD, \"run_app.py\")\n log('running script %s...' % script)\n xbmc.executebuiltin('XBMC.RunScript(%s, %s, %s)' % (script, action[0], username))\n\nelif folder[0] == 'similarArtist':\n if action is None:\n url = build_url(lastfmApi, {'method': 'chart.getTopArtists',\n 'format': 'json', 'api_key': lastfmApiKey})\n reply = urllib.urlopen(url)\n resp = json.load(reply)\n if \"error\" in resp:\n raise Exception(\"Error! DATA: \" + str(resp))\n else:\n #log(str(resp))\n pass\n\n for a in resp['artists']['artist']:\n url = build_url(addonUrl, {'folder': folder[0], 'action': a['name'].encode('utf-8')})\n li = xbmcgui.ListItem(a['name'])\n li.setArt({'icon': a['image'][2]['#text'], 'thumb': a['image'][2]['#text'], 'fanart': a['image'][4]['#text']})\n xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li, isFolder=False)\n\n pass\n\n xbmcplugin.endOfDirectory(addon_handle)\n\nlog('end -----------------------------------------------------')\n"},"license":{"kind":"string","value":"gpl-2.0"},"hash":{"kind":"number","value":4180069975239429000,"string":"4,180,069,975,239,429,000"},"line_mean":{"kind":"number","value":37.5664739884,"string":"37.566474"},"line_max":{"kind":"number","value":127,"string":"127"},"alpha_frac":{"kind":"number","value":0.6188549161,"string":"0.618855"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.439175257731959,"string":"3.439175"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45157,"cells":{"repo_name":{"kind":"string","value":"mozman/ezdxf"},"path":{"kind":"string","value":"tests/test_06_math/test_630b_bezier4p_functions.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"4662"},"content":{"kind":"string","value":"# Copyright (c) 2010-2020 Manfred Moitzi\n# License: MIT License\nimport pytest\nimport random\n\nfrom ezdxf.math import (\n cubic_bezier_interpolation, Vec3, Bezier3P, quadratic_to_cubic_bezier,\n Bezier4P, have_bezier_curves_g1_continuity, bezier_to_bspline,\n)\n\n\ndef test_vertex_interpolation():\n points = [(0, 0), (3, 1), (5, 3), (0, 8)]\n result = list(cubic_bezier_interpolation(points))\n assert len(result) == 3\n c1, c2, c3 = result\n p = c1.control_points\n assert p[0].isclose((0, 0))\n assert p[1].isclose((0.9333333333333331, 0.3111111111111111))\n assert p[2].isclose((1.8666666666666663, 0.6222222222222222))\n assert p[3].isclose((3, 1))\n\n p = c2.control_points\n assert p[0].isclose((3, 1))\n assert p[1].isclose((4.133333333333334, 1.3777777777777778))\n assert p[2].isclose((5.466666666666667, 1.822222222222222))\n assert p[3].isclose((5, 3))\n\n p = c3.control_points\n assert p[0].isclose((5, 3))\n assert p[1].isclose((4.533333333333333, 4.177777777777778))\n assert p[2].isclose((2.2666666666666666, 6.088888888888889))\n assert p[3].isclose((0, 8))\n\n\ndef test_quadratic_to_cubic_bezier():\n r = random.Random(0)\n\n def random_vec() -> Vec3:\n return Vec3(r.uniform(-10, 10), r.uniform(-10, 10), r.uniform(-10, 10))\n\n for i in range(1000):\n quadratic = Bezier3P((random_vec(), random_vec(), random_vec()))\n quadratic_approx = list(quadratic.approximate(10))\n cubic = quadratic_to_cubic_bezier(quadratic)\n cubic_approx = list(cubic.approximate(10))\n\n assert len(quadratic_approx) == len(cubic_approx)\n for p1, p2 in zip(quadratic_approx, cubic_approx):\n assert p1.isclose(p2)\n\n\n# G1 continuity: normalized end-tangent == normalized start-tangent of next curve\nB1 = Bezier4P([(0, 0), (1, 1), (2, 1), (3, 0)])\n\n# B1/B2 has G1 continuity:\nB2 = Bezier4P([(3, 0), (4, -1), (5, -1), (6, 0)])\n\n# B1/B3 has no G1 continuity:\nB3 = Bezier4P([(3, 0), (4, 1), (5, 1), (6, 0)])\n\n# B1/B4 G1 continuity off tolerance:\nB4 = Bezier4P([(3, 0), (4, -1.03), (5, -1.0), (6, 0)])\n\n# B1/B5 has a gap between B1 end and B5 start:\nB5 = Bezier4P([(4, 0), (5, -1), (6, -1), (7, 0)])\n\n\ndef test_g1_continuity_for_bezier_curves():\n assert have_bezier_curves_g1_continuity(B1, B2) is True\n assert have_bezier_curves_g1_continuity(B1, B3) is False\n assert have_bezier_curves_g1_continuity(B1, B4, g1_tol=1e-4) is False, \\\n \"should be outside of tolerance \"\n assert have_bezier_curves_g1_continuity(B1, B5) is False, \\\n \"end- and start point should match\"\n\n\nD1 = Bezier4P([(0, 0), (1, 1), (3, 0), (3, 0)])\nD2 = Bezier4P([(3, 0), (3, 0), (5, -1), (6, 0)])\n\n\ndef test_g1_continuity_for_degenerated_bezier_curves():\n assert have_bezier_curves_g1_continuity(D1, B2) is False\n assert have_bezier_curves_g1_continuity(B1, D2) is False\n assert have_bezier_curves_g1_continuity(D1, D2) is False\n\n\n@pytest.mark.parametrize('curve', [D1, D2])\ndef test_flatten_degenerated_bezier_curves(curve):\n # Degenerated Bezier curves behave like regular curves!\n assert len(list(curve.flattening(0.1))) > 4\n\n\n@pytest.mark.parametrize(\"b1,b2\", [\n (B1, B2), # G1 continuity, the common case\n (B1, B3), # without G1 continuity is also a regular B-spline\n (B1, B5), # regular B-spline, but first control point of B5 is lost\n], ids=[\"G1\", \"without G1\", \"gap\"])\ndef test_bezier_curves_to_bspline(b1, b2):\n bspline = bezier_to_bspline([b1, b2])\n # Remove duplicate control point between two adjacent curves:\n expected = list(b1.control_points) + list(b2.control_points)[1:]\n assert bspline.degree == 3, \"should be a cubic B-spline\"\n assert bspline.control_points == tuple(expected)\n\n\ndef test_quality_of_bezier_to_bspline_conversion_1():\n # This test shows the close relationship between cubic Bézier- and\n # cubic B-spline curves.\n points0 = B1.approximate(10)\n points1 = bezier_to_bspline([B1]).approximate(10)\n for p0, p1 in zip(points0, points1):\n assert p0.isclose(p1) is True, \"conversion should be perfect\"\n\n\ndef test_quality_of_bezier_to_bspline_conversion_2():\n # This test shows the close relationship between cubic Bézier- and\n # cubic B-spline curves.\n # Remove duplicate point between the two curves:\n points0 = list(B1.approximate(10)) + list(B2.approximate(10))[1:]\n points1 = bezier_to_bspline([B1, B2]).approximate(20)\n for p0, p1 in zip(points0, points1):\n assert p0.isclose(p1) is True, \"conversion should be perfect\"\n\n\ndef test_bezier_curves_to_bspline_error():\n with pytest.raises(ValueError):\n bezier_to_bspline([]) # one or more curves expected\n"},"license":{"kind":"string","value":"mit"},"hash":{"kind":"number","value":2218089063526213400,"string":"2,218,089,063,526,213,400"},"line_mean":{"kind":"number","value":35.40625,"string":"35.40625"},"line_max":{"kind":"number","value":81,"string":"81"},"alpha_frac":{"kind":"number","value":0.6579399142,"string":"0.65794"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":2.7299355594610426,"string":"2.729936"},"config_test":{"kind":"bool","value":true,"string":"true"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45158,"cells":{"repo_name":{"kind":"string","value":"fdouetteau/PyBabe"},"path":{"kind":"string","value":"pybabe/format_csv.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"3107"},"content":{"kind":"string","value":"\nfrom base import BabeBase, StreamHeader, StreamFooter\nimport csv\nfrom charset import UTF8Recoder, UTF8RecoderWithCleanup, PrefixReader, UnicodeCSVWriter\nimport codecs\nimport logging\n\nlog = logging.getLogger(\"csv\")\n\n\ndef linepull(stream, dialect, kwargs):\n it = iter(stream)\n fields = kwargs.get('fields', None)\n if not fields:\n fields = [it.next().rstrip('\\r\\n')]\n metainfo = StreamHeader(**dict(kwargs, fields=fields))\n yield metainfo\n for row in it:\n yield metainfo.t._make([row.rstrip('\\r\\n')])\n yield StreamFooter()\n\n\ndef build_value(x, null_value):\n if x == null_value:\n return None\n else:\n return unicode(x, \"utf-8\")\n\n\ndef csvpull(stream, dialect, kwargs):\n reader = csv.reader(stream, dialect)\n fields = kwargs.get('fields', None)\n null_value = kwargs.get('null_value', \"\")\n ignore_malformed = kwargs.get('ignore_bad_lines', False)\n if not fields:\n fields = reader.next()\n metainfo = StreamHeader(**dict(kwargs, fields=fields))\n yield metainfo\n for row in reader:\n try:\n yield metainfo.t._make([build_value(x, null_value) for x in row])\n except Exception, e:\n if ignore_malformed:\n log.warn(\"Malformed line: %s, %s\" % (row, e))\n else:\n raise e\n yield StreamFooter()\n\n\ndef pull(format, stream, kwargs):\n if kwargs.get('utf8_cleanup', False):\n stream = UTF8RecoderWithCleanup(stream, kwargs.get('encoding', 'utf-8'))\n elif codecs.getreader(kwargs.get('encoding', 'utf-8')) != codecs.getreader('utf-8'):\n stream = UTF8Recoder(stream, kwargs.get('encoding', None))\n else:\n pass\n delimiter = kwargs.get('delimiter', None)\n sniff_read = stream.next()\n stream = PrefixReader(sniff_read, stream, linefilter=kwargs.get(\"linefilter\", None))\n dialect = csv.Sniffer().sniff(sniff_read)\n if sniff_read.endswith('\\r\\n'):\n dialect.lineterminator = '\\r\\n'\n else:\n dialect.lineterminator = '\\n'\n if dialect.delimiter.isalpha() and not delimiter:\n # http://bugs.python.org/issue2078\n for row in linepull(stream, dialect, kwargs):\n yield row\n return\n if delimiter:\n dialect.delimiter = delimiter\n for row in csvpull(stream, dialect, kwargs):\n yield row\n\n\nclass default_dialect(csv.Dialect):\n lineterminator = '\\n'\n delimiter = ','\n doublequote = False\n escapechar = '\\\\'\n quoting = csv.QUOTE_MINIMAL\n quotechar = '\"'\n\n\ndef push(format, metainfo, instream, outfile, encoding, delimiter=None, **kwargs):\n if not encoding:\n encoding = \"utf8\"\n dialect = kwargs.get('dialect', default_dialect)\n if delimiter:\n dialect.delimiter = delimiter\n writer = UnicodeCSVWriter(outfile, dialect=dialect, encoding=encoding)\n writer.writerow(metainfo.fields)\n for k in instream:\n if isinstance(k, StreamFooter):\n break\n else:\n writer.writerow(k)\n\nBabeBase.addPullPlugin('csv', ['csv', 'tsv', 'txt'], pull)\nBabeBase.addPushPlugin('csv', ['csv', 'tsv', 'txt'], push)\n"},"license":{"kind":"string","value":"bsd-3-clause"},"hash":{"kind":"number","value":-8952105549496500000,"string":"-8,952,105,549,496,500,000"},"line_mean":{"kind":"number","value":30.07,"string":"30.07"},"line_max":{"kind":"number","value":88,"string":"88"},"alpha_frac":{"kind":"number","value":0.6317991632,"string":"0.631799"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.703218116805721,"string":"3.703218"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45159,"cells":{"repo_name":{"kind":"string","value":"filippog/pysnmp"},"path":{"kind":"string","value":"examples/hlapi/asyncore/sync/agent/ntforg/v3-trap.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"1601"},"content":{"kind":"string","value":"\"\"\"\nSNMPv3 TRAP: auth SHA, privacy: AES128\n++++++++++++++++++++++++++++++++++++++\n\nSend SNMP notification using the following options:\n\n* SNMPv3\n* with authoritative snmpEngineId = 0x8000000001020304 \n (USM must be configured at the Receiver accordingly)\n* with user 'usr-sha-aes128', auth: SHA, priv: AES128\n* over IPv4/UDP\n* send TRAP notification\n* with TRAP ID 'authenticationFailure' specified as a MIB symbol\n* do not include any additional managed object information\n\nSNMPv3 TRAPs requires pre-sharing the Notification Originator's\nvalue of SnmpEngineId with Notification Receiver. To facilitate that\nwe will use static (e.g. not autogenerated) version of snmpEngineId.\n\nFunctionally similar to:\n\n| $ snmptrap -v3 -e 8000000001020304 -l authPriv -u usr-sha-aes -A authkey1 -X privkey1 -a SHA -x AES demo.snmplabs.com 12345 1.3.6.1.4.1.20408.4.1.1.2 1.3.6.1.2.1.1.1.0 s \"my system\"\n\n\"\"\"#\nfrom pysnmp.hlapi import *\n\nerrorIndication, errorStatus, errorIndex, varBinds = next(\n sendNotification(SnmpEngine(OctetString(hexValue='8000000001020304')),\n UsmUserData('usr-sha-aes128', 'authkey1', 'privkey1',\n authProtocol=usmHMACSHAAuthProtocol,\n privProtocol=usmAesCfb128Protocol),\n UdpTransportTarget(('demo.snmplabs.com', 162)),\n ContextData(),\n 'trap',\n NotificationType(\n ObjectIdentity('SNMPv2-MIB', 'authenticationFailure')\n )\n )\n)\nif errorIndication:\n print(errorIndication)\n"},"license":{"kind":"string","value":"bsd-3-clause"},"hash":{"kind":"number","value":7296825608207418000,"string":"7,296,825,608,207,418,000"},"line_mean":{"kind":"number","value":38.0487804878,"string":"38.04878"},"line_max":{"kind":"number","value":183,"string":"183"},"alpha_frac":{"kind":"number","value":0.6470955653,"string":"0.647096"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.5736607142857144,"string":"3.573661"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":true,"string":"true"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45160,"cells":{"repo_name":{"kind":"string","value":"SU-ECE-17-7/hotspotter"},"path":{"kind":"string","value":"hsviz/draw_func2.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"54605"},"content":{"kind":"string","value":"''' Lots of functions for drawing and plotting visiony things '''\n# TODO: New naming scheme\n# viz_ will clear everything. The current axes and fig: clf, cla. # Will add annotations\n# interact_ will clear everything and start user interactions.\n# show_ will always clear the current axes, but not fig: cla # Might # add annotates?\n# plot_ will not clear the axes or figure. More useful for graphs\n# draw_ same as plot for now. More useful for images\nfrom __future__ import division, print_function\nfrom hscom import __common__\n(print, print_, print_on, print_off, rrr, profile,\n printDBG) = __common__.init(__name__, '[df2]', DEBUG=False, initmpl=True)\n# Python\nfrom itertools import izip\nfrom os.path import splitext, split, join, normpath, exists\nimport colorsys\nimport itertools\nimport pylab\nimport sys\nimport textwrap\nimport time\nimport warnings\n# Matplotlib / Qt\nimport matplotlib\nimport matplotlib as mpl # NOQA\nfrom matplotlib.collections import PatchCollection, LineCollection\nfrom matplotlib.font_manager import FontProperties\nfrom matplotlib.patches import Rectangle, Circle, FancyArrow\nfrom matplotlib.transforms import Affine2D\nfrom matplotlib.backends import backend_qt4\nimport matplotlib.pyplot as plt\n# Qt\nfrom PyQt4 import QtCore, QtGui\nfrom PyQt4.QtCore import Qt\n# Scientific\nimport numpy as np\nimport scipy.stats\nimport cv2\n# HotSpotter\nfrom hscom import helpers\nfrom hscom import tools\nfrom hscom.Printable import DynStruct\n\n#================\n# GLOBALS\n#================\n\nTMP_mevent = None\nQT4_WINS = []\nplotWidget = None\n\n# GENERAL FONTS\n\nSMALLER = 8\nSMALL = 10\nMED = 12\nLARGE = 14\n#fpargs = dict(family=None, style=None, variant=None, stretch=None, fname=None)\nFONTS = DynStruct()\nFONTS.small = FontProperties(weight='light', size=SMALL)\nFONTS.smaller = FontProperties(weight='light', size=SMALLER)\nFONTS.med = FontProperties(weight='light', size=MED)\nFONTS.large = FontProperties(weight='light', size=LARGE)\nFONTS.medbold = FontProperties(weight='bold', size=MED)\nFONTS.largebold = FontProperties(weight='bold', size=LARGE)\n\n# SPECIFIC FONTS\n\nFONTS.legend = FONTS.small\nFONTS.figtitle = FONTS.med\nFONTS.axtitle = FONTS.med\nFONTS.subtitle = FONTS.med\nFONTS.xlabel = FONTS.smaller\nFONTS.ylabel = FONTS.small\nFONTS.relative = FONTS.smaller\n\n# COLORS\n\nORANGE = np.array((255, 127, 0, 255)) / 255.0\nRED = np.array((255, 0, 0, 255)) / 255.0\nGREEN = np.array(( 0, 255, 0, 255)) / 255.0\nBLUE = np.array(( 0, 0, 255, 255)) / 255.0\nYELLOW = np.array((255, 255, 0, 255)) / 255.0\nBLACK = np.array(( 0, 0, 0, 255)) / 255.0\nWHITE = np.array((255, 255, 255, 255)) / 255.0\nGRAY = np.array((127, 127, 127, 255)) / 255.0\nDEEP_PINK = np.array((255, 20, 147, 255)) / 255.0\nPINK = np.array((255, 100, 100, 255)) / 255.0\nFALSE_RED = np.array((255, 51, 0, 255)) / 255.0\nTRUE_GREEN = np.array(( 0, 255, 0, 255)) / 255.0\nDARK_ORANGE = np.array((127, 63, 0, 255)) / 255.0\nDARK_YELLOW = np.array((127, 127, 0, 255)) / 255.0\nPURPLE = np.array((102, 0, 153, 255)) / 255.0\nUNKNOWN_PURP = PURPLE\n\n# FIGURE GEOMETRY\n\nDPI = 80\n#DPI = 160\n#FIGSIZE = (24) # default windows fullscreen\nFIGSIZE_MED = (12, 6)\nFIGSIZE_SQUARE = (12, 12)\nFIGSIZE_BIGGER = (24, 12)\nFIGSIZE_HUGE = (32, 16)\n\nFIGSIZE = FIGSIZE_MED\n# Quality drawings\n#FIGSIZE = FIGSIZE_SQUARE\n#DPI = 120\n\ntile_within = (-1, 30, 969, 1041)\nif helpers.get_computer_name() == 'Ooo':\n TILE_WITHIN = (-1912, 30, -969, 1071)\n\n# DEFAULTS. (TODO: Can these be cleaned up?)\n\nDISTINCT_COLORS = True # and False\nDARKEN = None\nELL_LINEWIDTH = 1.5\nif DISTINCT_COLORS:\n ELL_ALPHA = .6\n LINE_ALPHA = .35\nelse:\n ELL_ALPHA = .4\n LINE_ALPHA = .4\n\nLINE_ALPHA_OVERRIDE = helpers.get_arg('--line-alpha-override', type_=float, default=None)\nELL_ALPHA_OVERRIDE = helpers.get_arg('--ell-alpha-override', type_=float, default=None)\n#LINE_ALPHA_OVERRIDE = None\n#ELL_ALPHA_OVERRIDE = None\nELL_COLOR = BLUE\n\nLINE_COLOR = RED\nLINE_WIDTH = 1.4\n\nSHOW_LINES = True # True\nSHOW_ELLS = True\n\nPOINT_SIZE = 2\n\n\nbase_fnum = 9001\n\n\ndef next_fnum():\n global base_fnum\n base_fnum += 1\n return base_fnum\n\n\ndef my_prefs():\n global LINE_COLOR\n global ELL_COLOR\n global ELL_LINEWIDTH\n global ELL_ALPHA\n LINE_COLOR = (1, 0, 0)\n ELL_COLOR = (0, 0, 1)\n ELL_LINEWIDTH = 2\n ELL_ALPHA = .5\n\n\ndef execstr_global():\n execstr = ['global' + key for key in globals().keys()]\n return execstr\n\n\ndef register_matplotlib_widget(plotWidget_):\n 'talks to PyQt4 guis'\n global plotWidget\n plotWidget = plotWidget_\n #fig = plotWidget.figure\n #axes_list = fig.get_axes()\n #ax = axes_list[0]\n #plt.sca(ax)\n\n\ndef unregister_qt4_win(win):\n global QT4_WINS\n if win == 'all':\n QT4_WINS = []\n\n\ndef register_qt4_win(win):\n global QT4_WINS\n QT4_WINS.append(win)\n\n\ndef OooScreen2():\n nRows = 1\n nCols = 1\n x_off = 30 * 4\n y_off = 30 * 4\n x_0 = -1920\n y_0 = 30\n w = (1912 - x_off) / nRows\n h = (1080 - y_off) / nCols\n return dict(num_rc=(1, 1), wh=(w, h), xy_off=(x_0, y_0), wh_off=(0, 10),\n row_first=True, no_tile=False)\n\n\ndef deterministic_shuffle(list_):\n randS = int(np.random.rand() * np.uint(0 - 2) / 2)\n np.random.seed(len(list_))\n np.random.shuffle(list_)\n np.random.seed(randS)\n\n\ndef distinct_colors(N, brightness=.878):\n # http://blog.jianhuashao.com/2011/09/generate-n-distinct-colors.html\n sat = brightness\n val = brightness\n HSV_tuples = [(x * 1.0 / N, sat, val) for x in xrange(N)]\n RGB_tuples = map(lambda x: colorsys.hsv_to_rgb(*x), HSV_tuples)\n deterministic_shuffle(RGB_tuples)\n return RGB_tuples\n\n\ndef add_alpha(colors):\n return [list(color) + [1] for color in colors]\n\n\ndef _axis_xy_width_height(ax, xaug=0, yaug=0, waug=0, haug=0):\n 'gets geometry of a subplot'\n autoAxis = ax.axis()\n xy = (autoAxis[0] + xaug, autoAxis[2] + yaug)\n width = (autoAxis[1] - autoAxis[0]) + waug\n height = (autoAxis[3] - autoAxis[2]) + haug\n return xy, width, height\n\n\ndef draw_border(ax, color=GREEN, lw=2, offset=None):\n 'draws rectangle border around a subplot'\n xy, width, height = _axis_xy_width_height(ax, -.7, -.2, 1, .4)\n if offset is not None:\n xoff, yoff = offset\n xy = [xoff, yoff]\n height = - height - yoff\n width = width - xoff\n rect = matplotlib.patches.Rectangle(xy, width, height, lw=lw)\n rect = ax.add_patch(rect)\n rect.set_clip_on(False)\n rect.set_fill(False)\n rect.set_edgecolor(color)\n\n\ndef draw_roi(roi, label=None, bbox_color=(1, 0, 0),\n lbl_bgcolor=(0, 0, 0), lbl_txtcolor=(1, 1, 1), theta=0, ax=None):\n if ax is None:\n ax = gca()\n (rx, ry, rw, rh) = roi\n #cos_ = np.cos(theta)\n #sin_ = np.sin(theta)\n #rot_t = Affine2D([( cos_, -sin_, 0),\n #( sin_, cos_, 0),\n #( 0, 0, 1)])\n #scale_t = Affine2D([( rw, 0, 0),\n #( 0, rh, 0),\n #( 0, 0, 1)])\n #trans_t = Affine2D([( 1, 0, rx + rw / 2),\n #( 0, 1, ry + rh / 2),\n #( 0, 0, 1)])\n #t_end = scale_t + rot_t + trans_t + t_start\n # Transformations are specified in backwards order.\n trans_roi = Affine2D()\n trans_roi.scale(rw, rh)\n trans_roi.rotate(theta)\n trans_roi.translate(rx + rw / 2, ry + rh / 2)\n t_end = trans_roi + ax.transData\n bbox = matplotlib.patches.Rectangle((-.5, -.5), 1, 1, lw=2, transform=t_end)\n arw_x, arw_y, arw_dx, arw_dy = (-0.5, -0.5, 1.0, 0.0)\n arrowargs = dict(head_width=.1, transform=t_end, length_includes_head=True)\n arrow = FancyArrow(arw_x, arw_y, arw_dx, arw_dy, **arrowargs)\n\n bbox.set_fill(False)\n #bbox.set_transform(trans)\n bbox.set_edgecolor(bbox_color)\n arrow.set_edgecolor(bbox_color)\n arrow.set_facecolor(bbox_color)\n\n ax.add_patch(bbox)\n ax.add_patch(arrow)\n #ax.add_patch(arrow2)\n if label is not None:\n ax_absolute_text(rx, ry, label, ax=ax,\n horizontalalignment='center',\n verticalalignment='center',\n color=lbl_txtcolor,\n backgroundcolor=lbl_bgcolor)\n\n\n# ---- GENERAL FIGURE COMMANDS ----\ndef sanatize_img_fname(fname):\n fname_clean = fname\n search_replace_list = [(' ', '_'), ('\\n', '--'), ('\\\\', ''), ('/', '')]\n for old, new in search_replace_list:\n fname_clean = fname_clean.replace(old, new)\n fname_noext, ext = splitext(fname_clean)\n fname_clean = fname_noext + ext.lower()\n # Check for correct extensions\n if not ext.lower() in helpers.IMG_EXTENSIONS:\n fname_clean += '.png'\n return fname_clean\n\n\ndef sanatize_img_fpath(fpath):\n [dpath, fname] = split(fpath)\n fname_clean = sanatize_img_fname(fname)\n fpath_clean = join(dpath, fname_clean)\n fpath_clean = normpath(fpath_clean)\n return fpath_clean\n\n\ndef set_geometry(fnum, x, y, w, h):\n fig = get_fig(fnum)\n qtwin = fig.canvas.manager.window\n qtwin.setGeometry(x, y, w, h)\n\n\ndef get_geometry(fnum):\n fig = get_fig(fnum)\n qtwin = fig.canvas.manager.window\n (x1, y1, x2, y2) = qtwin.geometry().getCoords()\n (x, y, w, h) = (x1, y1, x2 - x1, y2 - y1)\n return (x, y, w, h)\n\n\ndef get_screen_info():\n from PyQt4 import Qt, QtGui # NOQA\n desktop = QtGui.QDesktopWidget()\n mask = desktop.mask() # NOQA\n layout_direction = desktop.layoutDirection() # NOQA\n screen_number = desktop.screenNumber() # NOQA\n normal_geometry = desktop.normalGeometry() # NOQA\n num_screens = desktop.screenCount() # NOQA\n avail_rect = desktop.availableGeometry() # NOQA\n screen_rect = desktop.screenGeometry() # NOQA\n QtGui.QDesktopWidget().availableGeometry().center() # NOQA\n normal_geometry = desktop.normalGeometry() # NOQA\n\n\ndef get_all_figures():\n all_figures_ = [manager.canvas.figure for manager in\n matplotlib._pylab_helpers.Gcf.get_all_fig_managers()]\n all_figures = []\n # Make sure you dont show figures that this module closed\n for fig in iter(all_figures_):\n if not 'df2_closed' in fig.__dict__.keys() or not fig.df2_closed:\n all_figures.append(fig)\n # Return all the figures sorted by their number\n all_figures = sorted(all_figures, key=lambda fig: fig.number)\n return all_figures\n\n\ndef get_all_qt4_wins():\n return QT4_WINS\n\n\ndef all_figures_show():\n if plotWidget is not None:\n plotWidget.figure.show()\n plotWidget.figure.canvas.draw()\n for fig in iter(get_all_figures()):\n time.sleep(.1)\n fig.show()\n fig.canvas.draw()\n\n\ndef all_figures_tight_layout():\n for fig in iter(get_all_figures()):\n fig.tight_layout()\n #adjust_subplots()\n time.sleep(.1)\n\n\ndef get_monitor_geom(monitor_num=0):\n from PyQt4 import QtGui # NOQA\n desktop = QtGui.QDesktopWidget()\n rect = desktop.availableGeometry()\n geom = (rect.x(), rect.y(), rect.width(), rect.height())\n return geom\n\n\ndef golden_wh(x):\n 'returns a width / height with a golden aspect ratio'\n return map(int, map(round, (x * .618, x * .312)))\n\n\ndef all_figures_tile(num_rc=(3, 4), wh=1000, xy_off=(0, 0), wh_off=(0, 10),\n row_first=True, no_tile=False, override1=False):\n 'Lays out all figures in a grid. if wh is a scalar, a golden ratio is used'\n # RCOS TODO:\n # I want this function to layout all the figures and qt windows within the\n # bounds of a rectangle. (taken from the get_monitor_geom, or specified by\n # the user i.e. left half of monitor 0). It should lay them out\n # rectangularly and choose figure sizes such that all of them will fit.\n if no_tile:\n return\n\n if not np.iterable(wh):\n wh = golden_wh(wh)\n\n all_figures = get_all_figures()\n all_qt4wins = get_all_qt4_wins()\n\n if override1:\n if len(all_figures) == 1:\n fig = all_figures[0]\n win = fig.canvas.manager.window\n win.setGeometry(0, 0, 900, 900)\n update()\n return\n\n #nFigs = len(all_figures) + len(all_qt4_wins)\n\n num_rows, num_cols = num_rc\n\n w, h = wh\n x_off, y_off = xy_off\n w_off, h_off = wh_off\n x_pad, y_pad = (0, 0)\n printDBG('[df2] Tile all figures: ')\n printDBG('[df2] wh = %r' % ((w, h),))\n printDBG('[df2] xy_offsets = %r' % ((x_off, y_off),))\n printDBG('[df2] wh_offsets = %r' % ((w_off, h_off),))\n printDBG('[df2] xy_pads = %r' % ((x_pad, y_pad),))\n if sys.platform == 'win32':\n h_off += 0\n w_off += 40\n x_off += 40\n y_off += 40\n x_pad += 0\n y_pad += 100\n\n def position_window(i, win):\n isqt4_mpl = isinstance(win, backend_qt4.MainWindow)\n isqt4_back = isinstance(win, QtGui.QMainWindow)\n if not isqt4_mpl and not isqt4_back:\n raise NotImplementedError('%r-th Backend %r is not a Qt Window' % (i, win))\n if row_first:\n y = (i % num_rows) * (h + h_off) + 40\n x = (int(i / num_rows)) * (w + w_off) + x_pad\n else:\n x = (i % num_cols) * (w + w_off) + 40\n y = (int(i / num_cols)) * (h + h_off) + y_pad\n x += x_off\n y += y_off\n win.setGeometry(x, y, w, h)\n ioff = 0\n for i, win in enumerate(all_qt4wins):\n position_window(i, win)\n ioff += 1\n for i, fig in enumerate(all_figures):\n win = fig.canvas.manager.window\n position_window(i + ioff, win)\n\n\ndef all_figures_bring_to_front():\n all_figures = get_all_figures()\n for fig in iter(all_figures):\n bring_to_front(fig)\n\n\ndef close_all_figures():\n all_figures = get_all_figures()\n for fig in iter(all_figures):\n close_figure(fig)\n\n\ndef close_figure(fig):\n fig.clf()\n fig.df2_closed = True\n qtwin = fig.canvas.manager.window\n qtwin.close()\n\n\ndef bring_to_front(fig):\n #what is difference between show and show normal?\n qtwin = fig.canvas.manager.window\n qtwin.raise_()\n qtwin.activateWindow()\n qtwin.setWindowFlags(Qt.WindowStaysOnTopHint)\n qtwin.setWindowFlags(Qt.WindowFlags(0))\n qtwin.show()\n\n\ndef show():\n all_figures_show()\n all_figures_bring_to_front()\n plt.show()\n\n\ndef reset():\n close_all_figures()\n\n\ndef draw():\n all_figures_show()\n\n\ndef update():\n draw()\n all_figures_bring_to_front()\n\n\ndef present(*args, **kwargs):\n 'execing present should cause IPython magic'\n print('[df2] Presenting figures...')\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n all_figures_tile(*args, **kwargs)\n all_figures_show()\n all_figures_bring_to_front()\n # Return an exec string\n execstr = helpers.ipython_execstr()\n execstr += textwrap.dedent('''\n if not embedded:\n print('[df2] Presenting in normal shell.')\n print('[df2] ... plt.show()')\n plt.show()\n ''')\n return execstr\n\n\ndef save_figure(fnum=None, fpath=None, usetitle=False, overwrite=True):\n #import warnings\n #warnings.simplefilter(\"error\")\n # Find the figure\n if fnum is None:\n fig = gcf()\n else:\n fig = plt.figure(fnum, figsize=FIGSIZE, dpi=DPI)\n # Enforce inches and DPI\n fig.set_size_inches(FIGSIZE[0], FIGSIZE[1])\n fnum = fig.number\n if fpath is None:\n # Find the title\n fpath = sanatize_img_fname(fig.canvas.get_window_title())\n if usetitle:\n title = sanatize_img_fname(fig.canvas.get_window_title())\n fpath = join(fpath, title)\n # Add in DPI information\n fpath_noext, ext = splitext(fpath)\n size_suffix = '_DPI=%r_FIGSIZE=%d,%d' % (DPI, FIGSIZE[0], FIGSIZE[1])\n fpath = fpath_noext + size_suffix + ext\n # Sanatize the filename\n fpath_clean = sanatize_img_fpath(fpath)\n #fname_clean = split(fpath_clean)[1]\n print('[df2] save_figure() %r' % (fpath_clean,))\n #adjust_subplots()\n with warnings.catch_warnings():\n warnings.filterwarnings('ignore', category=DeprecationWarning)\n if not exists(fpath_clean) or overwrite:\n fig.savefig(fpath_clean, dpi=DPI)\n\n\ndef set_ticks(xticks, yticks):\n ax = gca()\n ax.set_xticks(xticks)\n ax.set_yticks(yticks)\n\n\ndef set_xticks(tick_set):\n ax = gca()\n ax.set_xticks(tick_set)\n\n\ndef set_yticks(tick_set):\n ax = gca()\n ax.set_yticks(tick_set)\n\n\ndef set_xlabel(lbl, ax=None):\n if ax is None:\n ax = gca()\n ax.set_xlabel(lbl, fontproperties=FONTS.xlabel)\n\n\ndef set_title(title, ax=None):\n if ax is None:\n ax = gca()\n ax.set_title(title, fontproperties=FONTS.axtitle)\n\n\ndef set_ylabel(lbl):\n ax = gca()\n ax.set_ylabel(lbl, fontproperties=FONTS.xlabel)\n\n\ndef plot(*args, **kwargs):\n return plt.plot(*args, **kwargs)\n\n\ndef plot2(x_data, y_data, marker='o', title_pref='', x_label='x', y_label='y', *args,\n **kwargs):\n do_plot = True\n ax = gca()\n if len(x_data) != len(y_data):\n warnstr = '[df2] ! Warning: len(x_data) != len(y_data). Cannot plot2'\n warnings.warn(warnstr)\n draw_text(warnstr)\n do_plot = False\n if len(x_data) == 0:\n warnstr = '[df2] ! Warning: len(x_data) == 0. Cannot plot2'\n warnings.warn(warnstr)\n draw_text(warnstr)\n do_plot = False\n if do_plot:\n ax.plot(x_data, y_data, marker, *args, **kwargs)\n\n min_ = min(x_data.min(), y_data.min())\n max_ = max(x_data.max(), y_data.max())\n # Equal aspect ratio\n ax.set_xlim(min_, max_)\n ax.set_ylim(min_, max_)\n ax.set_aspect('equal')\n ax.set_xlabel(x_label, fontproperties=FONTS.xlabel)\n ax.set_ylabel(y_label, fontproperties=FONTS.xlabel)\n ax.set_title(title_pref + ' ' + x_label + ' vs ' + y_label,\n fontproperties=FONTS.axtitle)\n\n\ndef adjust_subplots_xlabels():\n adjust_subplots(left=.03, right=.97, bottom=.2, top=.9, hspace=.15)\n\n\ndef adjust_subplots_xylabels():\n adjust_subplots(left=.03, right=1, bottom=.1, top=.9, hspace=.15)\n\n\ndef adjust_subplots_safe(left=.1, right=.9, bottom=.1, top=.9, wspace=.3, hspace=.5):\n adjust_subplots(left, bottom, right, top, wspace, hspace)\n\n\ndef adjust_subplots(left=0.02, bottom=0.02,\n right=0.98, top=0.90,\n wspace=0.1, hspace=0.15):\n '''\n left = 0.125 # the left side of the subplots of the figure\n right = 0.9 # the right side of the subplots of the figure\n bottom = 0.1 # the bottom of the subplots of the figure\n top = 0.9 # the top of the subplots of the figure\n wspace = 0.2 # the amount of width reserved for blank space between subplots\n hspace = 0.2\n '''\n #print('[df2] adjust_subplots(%r)' % locals())\n plt.subplots_adjust(left, bottom, right, top, wspace, hspace)\n\n\n#=======================\n# TEXT FUNCTIONS\n# TODO: I have too many of these. Need to consolidate\n#=======================\n\n\ndef upperleft_text(txt):\n txtargs = dict(horizontalalignment='left',\n verticalalignment='top',\n #fontsize='smaller',\n #fontweight='ultralight',\n backgroundcolor=(0, 0, 0, .5),\n color=ORANGE)\n ax_relative_text(.02, .02, txt, **txtargs)\n\n\ndef upperright_text(txt, offset=None):\n txtargs = dict(horizontalalignment='right',\n verticalalignment='top',\n #fontsize='smaller',\n #fontweight='ultralight',\n backgroundcolor=(0, 0, 0, .5),\n color=ORANGE,\n offset=offset)\n ax_relative_text(.98, .02, txt, **txtargs)\n\n\ndef lowerright_text(txt):\n txtargs = dict(horizontalalignment='right',\n verticalalignment='top',\n #fontsize='smaller',\n #fontweight='ultralight',\n backgroundcolor=(0, 0, 0, .5),\n color=ORANGE)\n ax_relative_text(.98, .92, txt, **txtargs)\n\n\ndef absolute_lbl(x_, y_, txt, roffset=(-.02, -.02), **kwargs):\n txtargs = dict(horizontalalignment='right',\n verticalalignment='top',\n backgroundcolor=(0, 0, 0, .5),\n color=ORANGE,\n **kwargs)\n ax_absolute_text(x_, y_, txt, roffset=roffset, **txtargs)\n\n\ndef ax_relative_text(x, y, txt, ax=None, offset=None, **kwargs):\n if ax is None:\n ax = gca()\n xy, width, height = _axis_xy_width_height(ax)\n x_, y_ = ((xy[0]) + x * width, (xy[1] + height) - y * height)\n if offset is not None:\n xoff, yoff = offset\n x_ += xoff\n y_ += yoff\n ax_absolute_text(x_, y_, txt, ax=ax, **kwargs)\n\n\ndef ax_absolute_text(x_, y_, txt, ax=None, roffset=None, **kwargs):\n if ax is None:\n ax = gca()\n if 'fontproperties' in kwargs:\n kwargs['fontproperties'] = FONTS.relative\n if roffset is not None:\n xroff, yroff = roffset\n xy, width, height = _axis_xy_width_height(ax)\n x_ += xroff * width\n y_ += yroff * height\n\n ax.text(x_, y_, txt, **kwargs)\n\n\ndef fig_relative_text(x, y, txt, **kwargs):\n kwargs['horizontalalignment'] = 'center'\n kwargs['verticalalignment'] = 'center'\n fig = gcf()\n #xy, width, height = _axis_xy_width_height(ax)\n #x_, y_ = ((xy[0]+width)+x*width, (xy[1]+height)-y*height)\n fig.text(x, y, txt, **kwargs)\n\n\ndef draw_text(text_str, rgb_textFG=(0, 0, 0), rgb_textBG=(1, 1, 1)):\n ax = gca()\n xy, width, height = _axis_xy_width_height(ax)\n text_x = xy[0] + (width / 2)\n text_y = xy[1] + (height / 2)\n ax.text(text_x, text_y, text_str,\n horizontalalignment='center',\n verticalalignment='center',\n color=rgb_textFG,\n backgroundcolor=rgb_textBG)\n\n\ndef set_figtitle(figtitle, subtitle='', forcefignum=True, incanvas=True):\n if figtitle is None:\n figtitle = ''\n fig = gcf()\n if incanvas:\n if subtitle != '':\n subtitle = '\\n' + subtitle\n fig.suptitle(figtitle + subtitle, fontsize=14, fontweight='bold')\n #fig.suptitle(figtitle, x=.5, y=.98, fontproperties=FONTS.figtitle)\n #fig_relative_text(.5, .96, subtitle, fontproperties=FONTS.subtitle)\n else:\n fig.suptitle('')\n window_figtitle = ('fig(%d) ' % fig.number) + figtitle\n fig.canvas.set_window_title(window_figtitle)\n\n\ndef convert_keypress_event_mpl_to_qt4(mevent):\n global TMP_mevent\n TMP_mevent = mevent\n # Grab the key from the mpl.KeyPressEvent\n key = mevent.key\n print('[df2] convert event mpl -> qt4')\n print('[df2] key=%r' % key)\n # dicts modified from backend_qt4.py\n mpl2qtkey = {'control': Qt.Key_Control, 'shift': Qt.Key_Shift,\n 'alt': Qt.Key_Alt, 'super': Qt.Key_Meta,\n 'enter': Qt.Key_Return, 'left': Qt.Key_Left, 'up': Qt.Key_Up,\n 'right': Qt.Key_Right, 'down': Qt.Key_Down,\n 'escape': Qt.Key_Escape, 'f1': Qt.Key_F1, 'f2': Qt.Key_F2,\n 'f3': Qt.Key_F3, 'f4': Qt.Key_F4, 'f5': Qt.Key_F5,\n 'f6': Qt.Key_F6, 'f7': Qt.Key_F7, 'f8': Qt.Key_F8,\n 'f9': Qt.Key_F9, 'f10': Qt.Key_F10, 'f11': Qt.Key_F11,\n 'f12': Qt.Key_F12, 'home': Qt.Key_Home, 'end': Qt.Key_End,\n 'pageup': Qt.Key_PageUp, 'pagedown': Qt.Key_PageDown}\n # Reverse the control and super (aka cmd/apple) keys on OSX\n if sys.platform == 'darwin':\n mpl2qtkey.update({'super': Qt.Key_Control, 'control': Qt.Key_Meta, })\n\n # Try to reconstruct QtGui.KeyEvent\n type_ = QtCore.QEvent.Type(QtCore.QEvent.KeyPress) # The type should always be KeyPress\n text = ''\n # Try to extract the original modifiers\n modifiers = QtCore.Qt.NoModifier # initialize to no modifiers\n if key.find(u'ctrl+') >= 0:\n modifiers = modifiers | QtCore.Qt.ControlModifier\n key = key.replace(u'ctrl+', u'')\n print('[df2] has ctrl modifier')\n text += 'Ctrl+'\n if key.find(u'alt+') >= 0:\n modifiers = modifiers | QtCore.Qt.AltModifier\n key = key.replace(u'alt+', u'')\n print('[df2] has alt modifier')\n text += 'Alt+'\n if key.find(u'super+') >= 0:\n modifiers = modifiers | QtCore.Qt.MetaModifier\n key = key.replace(u'super+', u'')\n print('[df2] has super modifier')\n text += 'Super+'\n if key.isupper():\n modifiers = modifiers | QtCore.Qt.ShiftModifier\n print('[df2] has shift modifier')\n text += 'Shift+'\n # Try to extract the original key\n try:\n if key in mpl2qtkey:\n key_ = mpl2qtkey[key]\n else:\n key_ = ord(key.upper()) # Qt works with uppercase keys\n text += key.upper()\n except Exception as ex:\n print('[df2] ERROR key=%r' % key)\n print('[df2] ERROR %r' % ex)\n raise\n autorep = False # default false\n count = 1 # default 1\n text = QtCore.QString(text) # The text is somewhat arbitrary\n # Create the QEvent\n print('----------------')\n print('[df2] Create event')\n print('[df2] type_ = %r' % type_)\n print('[df2] text = %r' % text)\n print('[df2] modifiers = %r' % modifiers)\n print('[df2] autorep = %r' % autorep)\n print('[df2] count = %r ' % count)\n print('----------------')\n qevent = QtGui.QKeyEvent(type_, key_, modifiers, text, autorep, count)\n return qevent\n\n\ndef test_build_qkeyevent():\n import draw_func2 as df2\n qtwin = df2.QT4_WINS[0]\n # This reconstructs an test mplevent\n canvas = df2.figure(1).canvas\n mevent = matplotlib.backend_bases.KeyEvent('key_press_event', canvas, u'ctrl+p', x=672, y=230.0)\n qevent = df2.convert_keypress_event_mpl_to_qt4(mevent)\n app = qtwin.backend.app\n app.sendEvent(qtwin.ui, mevent)\n #type_ = QtCore.QEvent.Type(QtCore.QEvent.KeyPress) # The type should always be KeyPress\n #text = QtCore.QString('A') # The text is somewhat arbitrary\n #modifiers = QtCore.Qt.NoModifier # initialize to no modifiers\n #modifiers = modifiers | QtCore.Qt.ControlModifier\n #modifiers = modifiers | QtCore.Qt.AltModifier\n #key_ = ord('A') # Qt works with uppercase keys\n #autorep = False # default false\n #count = 1 # default 1\n #qevent = QtGui.QKeyEvent(type_, key_, modifiers, text, autorep, count)\n return qevent\n\n\n# This actually doesn't matter\ndef on_key_press_event(event):\n 'redirects keypress events to main window'\n global QT4_WINS\n print('[df2] %r' % event)\n print('[df2] %r' % str(event.__dict__))\n for qtwin in QT4_WINS:\n qevent = convert_keypress_event_mpl_to_qt4(event)\n app = qtwin.backend.app\n print('[df2] attempting to send qevent to qtwin')\n app.sendEvent(qtwin, qevent)\n # TODO: FINISH ME\n #PyQt4.QtGui.QKeyEvent\n #qtwin.keyPressEvent(event)\n #fig.canvas.manager.window.keyPressEvent()\n\n\ndef customize_figure(fig, docla):\n if not 'user_stat_list' in fig.__dict__.keys() or docla:\n fig.user_stat_list = []\n fig.user_notes = []\n # We dont need to catch keypress events because you just need to set it as\n # an application level shortcut\n # Catch key press events\n #key_event_cbid = fig.__dict__.get('key_event_cbid', None)\n #if key_event_cbid is not None:\n #fig.canvas.mpl_disconnect(key_event_cbid)\n #fig.key_event_cbid = fig.canvas.mpl_connect('key_press_event', on_key_press_event)\n fig.df2_closed = False\n\n\ndef gcf():\n if plotWidget is not None:\n #print('is plotwidget visible = %r' % plotWidget.isVisible())\n fig = plotWidget.figure\n return fig\n return plt.gcf()\n\n\ndef gca():\n if plotWidget is not None:\n #print('is plotwidget visible = %r' % plotWidget.isVisible())\n axes_list = plotWidget.figure.get_axes()\n current = 0\n ax = axes_list[current]\n return ax\n return plt.gca()\n\n\ndef cla():\n return plt.cla()\n\n\ndef clf():\n return plt.clf()\n\n\ndef get_fig(fnum=None):\n printDBG('[df2] get_fig(fnum=%r)' % fnum)\n fig_kwargs = dict(figsize=FIGSIZE, dpi=DPI)\n if plotWidget is not None:\n return gcf()\n if fnum is None:\n try:\n fig = gcf()\n except Exception as ex:\n printDBG('[df2] get_fig(): ex=%r' % ex)\n fig = plt.figure(**fig_kwargs)\n fnum = fig.number\n else:\n try:\n fig = plt.figure(fnum, **fig_kwargs)\n except Exception as ex:\n print(repr(ex))\n warnings.warn(repr(ex))\n fig = gcf()\n return fig\n\n\ndef get_ax(fnum=None, pnum=None):\n figure(fnum=fnum, pnum=pnum)\n ax = gca()\n return ax\n\n\ndef figure(fnum=None, docla=False, title=None, pnum=(1, 1, 1), figtitle=None,\n doclf=False, **kwargs):\n '''\n fnum = fignum = figure number\n pnum = plotnum = plot tuple\n '''\n #matplotlib.pyplot.xkcd()\n fig = get_fig(fnum)\n axes_list = fig.get_axes()\n # Ensure my customized settings\n customize_figure(fig, docla)\n # Convert pnum to tuple format\n if tools.is_int(pnum):\n nr = pnum // 100\n nc = pnum // 10 - (nr * 10)\n px = pnum - (nr * 100) - (nc * 10)\n pnum = (nr, nc, px)\n if doclf: # a bit hacky. Need to rectify docla and doclf\n fig.clf()\n # Get the subplot\n if docla or len(axes_list) == 0:\n printDBG('[df2] *** NEW FIGURE %r.%r ***' % (fnum, pnum))\n if not pnum is None:\n #ax = plt.subplot(*pnum)\n ax = fig.add_subplot(*pnum)\n ax.cla()\n else:\n ax = gca()\n else:\n printDBG('[df2] *** OLD FIGURE %r.%r ***' % (fnum, pnum))\n if not pnum is None:\n ax = plt.subplot(*pnum) # fig.add_subplot fails here\n #ax = fig.add_subplot(*pnum)\n else:\n ax = gca()\n #ax = axes_list[0]\n # Set the title\n if not title is None:\n ax = gca()\n ax.set_title(title, fontproperties=FONTS.axtitle)\n # Add title to figure\n if figtitle is None and pnum == (1, 1, 1):\n figtitle = title\n if not figtitle is None:\n set_figtitle(figtitle, incanvas=False)\n return fig\n\n\ndef plot_pdf(data, draw_support=True, scale_to=None, label=None, color=0,\n nYTicks=3):\n fig = gcf()\n ax = gca()\n data = np.array(data)\n if len(data) == 0:\n warnstr = '[df2] ! Warning: len(data) = 0. Cannot visualize pdf'\n warnings.warn(warnstr)\n draw_text(warnstr)\n return\n bw_factor = .05\n if isinstance(color, (int, float)):\n colorx = color\n line_color = plt.get_cmap('gist_rainbow')(colorx)\n else:\n line_color = color\n\n # Estimate a pdf\n data_pdf = estimate_pdf(data, bw_factor)\n # Get probability of seen data\n prob_x = data_pdf(data)\n # Get probability of unseen data data\n x_data = np.linspace(0, data.max(), 500)\n y_data = data_pdf(x_data)\n # Scale if requested\n if not scale_to is None:\n scale_factor = scale_to / y_data.max()\n y_data *= scale_factor\n prob_x *= scale_factor\n #Plot the actual datas on near the bottom perterbed in Y\n if draw_support:\n pdfrange = prob_x.max() - prob_x.min()\n perb = (np.random.randn(len(data))) * pdfrange / 30.\n preb_y_data = np.abs([pdfrange / 50. for _ in data] + perb)\n ax.plot(data, preb_y_data, 'o', color=line_color, figure=fig, alpha=.1)\n # Plot the pdf (unseen data)\n ax.plot(x_data, y_data, color=line_color, label=label)\n if nYTicks is not None:\n yticks = np.linspace(min(y_data), max(y_data), nYTicks)\n ax.set_yticks(yticks)\n\n\ndef estimate_pdf(data, bw_factor):\n try:\n data_pdf = scipy.stats.gaussian_kde(data, bw_factor)\n data_pdf.covariance_factor = bw_factor\n except Exception as ex:\n print('[df2] ! Exception while estimating kernel density')\n print('[df2] data=%r' % (data,))\n print('[df2] ex=%r' % (ex,))\n raise\n return data_pdf\n\n\ndef show_histogram(data, bins=None, **kwargs):\n print('[df2] show_histogram()')\n dmin = int(np.floor(data.min()))\n dmax = int(np.ceil(data.max()))\n if bins is None:\n bins = dmax - dmin\n fig = figure(**kwargs)\n ax = gca()\n ax.hist(data, bins=bins, range=(dmin, dmax))\n #help(np.bincount)\n fig.show()\n\n\ndef show_signature(sig, **kwargs):\n fig = figure(**kwargs)\n plt.plot(sig)\n fig.show()\n\n\ndef plot_stems(x_data=None, y_data=None):\n if y_data is not None and x_data is None:\n x_data = np.arange(len(y_data))\n pass\n if len(x_data) != len(y_data):\n print('[df2] WARNING plot_stems(): len(x_data)!=len(y_data)')\n if len(x_data) == 0:\n print('[df2] WARNING plot_stems(): len(x_data)=len(y_data)=0')\n x_data_ = np.array(x_data)\n y_data_ = np.array(y_data)\n x_data_sort = x_data_[y_data_.argsort()[::-1]]\n y_data_sort = y_data_[y_data_.argsort()[::-1]]\n\n markerline, stemlines, baseline = pylab.stem(x_data_sort, y_data_sort, linefmt='-')\n pylab.setp(markerline, 'markerfacecolor', 'b')\n pylab.setp(baseline, 'linewidth', 0)\n ax = gca()\n ax.set_xlim(min(x_data) - 1, max(x_data) + 1)\n ax.set_ylim(min(y_data) - 1, max(max(y_data), max(x_data)) + 1)\n\n\ndef plot_sift_signature(sift, title='', fnum=None, pnum=None):\n figure(fnum=fnum, pnum=pnum)\n ax = gca()\n plot_bars(sift, 16)\n ax.set_xlim(0, 128)\n ax.set_ylim(0, 256)\n space_xticks(9, 16)\n space_yticks(5, 64)\n ax.set_title(title)\n dark_background(ax)\n return ax\n\n\ndef dark_background(ax=None, doubleit=False):\n if ax is None:\n ax = gca()\n xy, width, height = _axis_xy_width_height(ax)\n if doubleit:\n halfw = (doubleit) * (width / 2)\n halfh = (doubleit) * (height / 2)\n xy = (xy[0] - halfw, xy[1] - halfh)\n width *= (doubleit + 1)\n height *= (doubleit + 1)\n rect = matplotlib.patches.Rectangle(xy, width, height, lw=0, zorder=0)\n rect.set_clip_on(True)\n rect.set_fill(True)\n rect.set_color(BLACK * .9)\n rect = ax.add_patch(rect)\n\n\ndef space_xticks(nTicks=9, spacing=16, ax=None):\n if ax is None:\n ax = gca()\n ax.set_xticks(np.arange(nTicks) * spacing)\n small_xticks(ax)\n\n\ndef space_yticks(nTicks=9, spacing=32, ax=None):\n if ax is None:\n ax = gca()\n ax.set_yticks(np.arange(nTicks) * spacing)\n small_yticks(ax)\n\n\ndef small_xticks(ax=None):\n for tick in ax.xaxis.get_major_ticks():\n tick.label.set_fontsize(8)\n\n\ndef small_yticks(ax=None):\n for tick in ax.yaxis.get_major_ticks():\n tick.label.set_fontsize(8)\n\n\ndef plot_bars(y_data, nColorSplits=1):\n width = 1\n nDims = len(y_data)\n nGroup = nDims // nColorSplits\n ori_colors = distinct_colors(nColorSplits)\n x_data = np.arange(nDims)\n ax = gca()\n for ix in xrange(nColorSplits):\n xs = np.arange(nGroup) + (nGroup * ix)\n color = ori_colors[ix]\n x_dat = x_data[xs]\n y_dat = y_data[xs]\n ax.bar(x_dat, y_dat, width, color=color, edgecolor=np.array(color) * .8)\n\n\ndef phantom_legend_label(label, color, loc='upper right'):\n 'adds a legend label without displaying an actor'\n pass\n #phantom_actor = plt.Circle((0, 0), 1, fc=color, prop=FONTS.legend, loc=loc)\n #plt.legend(phant_actor, label, framealpha=.2)\n #plt.legend(*zip(*legend_tups), framealpha=.2)\n #legend_tups = []\n #legend_tups.append((phantom_actor, label))\n\n\ndef legend(loc='upper right'):\n ax = gca()\n ax.legend(prop=FONTS.legend, loc=loc)\n\n\ndef plot_histpdf(data, label=None, draw_support=False, nbins=10):\n freq, _ = plot_hist(data, nbins=nbins)\n plot_pdf(data, draw_support=draw_support, scale_to=freq.max(), label=label)\n\n\ndef plot_hist(data, bins=None, nbins=10, weights=None):\n if isinstance(data, list):\n data = np.array(data)\n if bins is None:\n dmin = data.min()\n dmax = data.max()\n bins = dmax - dmin\n ax = gca()\n freq, bins_, patches = ax.hist(data, bins=nbins, weights=weights, range=(dmin, dmax))\n return freq, bins_\n\n\ndef variation_trunctate(data):\n ax = gca()\n data = np.array(data)\n if len(data) == 0:\n warnstr = '[df2] ! Warning: len(data) = 0. Cannot variation_truncate'\n warnings.warn(warnstr)\n return\n trunc_max = data.mean() + data.std() * 2\n trunc_min = np.floor(data.min())\n ax.set_xlim(trunc_min, trunc_max)\n #trunc_xticks = np.linspace(0, int(trunc_max),11)\n #trunc_xticks = trunc_xticks[trunc_xticks >= trunc_min]\n #trunc_xticks = np.append([int(trunc_min)], trunc_xticks)\n #no_zero_yticks = ax.get_yticks()[ax.get_yticks() > 0]\n #ax.set_xticks(trunc_xticks)\n #ax.set_yticks(no_zero_yticks)\n#_----------------- HELPERS ^^^ ---------\n\n\n# ---- IMAGE CREATION FUNCTIONS ----\n@tools.debug_exception\ndef draw_sift(desc, kp=None):\n # TODO: There might be a divide by zero warning in here.\n ''' desc = np.random.rand(128)\n desc = desc / np.sqrt((desc**2).sum())\n desc = np.round(desc * 255) '''\n # This is draw, because it is an overlay\n ax = gca()\n tau = 2 * np.pi\n DSCALE = .25\n XYSCALE = .5\n XYSHIFT = -.75\n ORI_SHIFT = 0 # -tau #1/8 * tau\n # SIFT CONSTANTS\n NORIENTS = 8\n NX = 4\n NY = 4\n NBINS = NX * NY\n\n def cirlce_rad2xy(radians, mag):\n return np.cos(radians) * mag, np.sin(radians) * mag\n discrete_ori = (np.arange(0, NORIENTS) * (tau / NORIENTS) + ORI_SHIFT)\n # Build list of plot positions\n # Build an \"arm\" for each sift measurement\n arm_mag = desc / 255.0\n arm_ori = np.tile(discrete_ori, (NBINS, 1)).flatten()\n # The offset x,y's for each sift measurment\n arm_dxy = np.array(zip(*cirlce_rad2xy(arm_ori, arm_mag)))\n yxt_gen = itertools.product(xrange(NY), xrange(NX), xrange(NORIENTS))\n yx_gen = itertools.product(xrange(NY), xrange(NX))\n # Transform the drawing of the SIFT descriptor to the its elliptical patch\n axTrans = ax.transData\n kpTrans = None\n if kp is None:\n kp = [0, 0, 1, 0, 1]\n kp = np.array(kp)\n kpT = kp.T\n x, y, a, c, d = kpT[:, 0]\n kpTrans = Affine2D([( a, 0, x),\n ( c, d, y),\n ( 0, 0, 1)])\n axTrans = ax.transData\n # Draw 8 directional arms in each of the 4x4 grid cells\n arrow_patches = []\n arrow_patches2 = []\n for y, x, t in yxt_gen:\n index = y * NX * NORIENTS + x * NORIENTS + t\n (dx, dy) = arm_dxy[index]\n arw_x = x * XYSCALE + XYSHIFT\n arw_y = y * XYSCALE + XYSHIFT\n arw_dy = dy * DSCALE * 1.5 # scale for viz Hack\n arw_dx = dx * DSCALE * 1.5\n #posA = (arw_x, arw_y)\n #posB = (arw_x+arw_dx, arw_y+arw_dy)\n _args = [arw_x, arw_y, arw_dx, arw_dy]\n _kwargs = dict(head_width=.0001, transform=kpTrans, length_includes_head=False)\n arrow_patches += [FancyArrow(*_args, **_kwargs)]\n arrow_patches2 += [FancyArrow(*_args, **_kwargs)]\n # Draw circles around each of the 4x4 grid cells\n circle_patches = []\n for y, x in yx_gen:\n circ_xy = (x * XYSCALE + XYSHIFT, y * XYSCALE + XYSHIFT)\n circ_radius = DSCALE\n circle_patches += [Circle(circ_xy, circ_radius, transform=kpTrans)]\n # Efficiently draw many patches with PatchCollections\n circ_collection = PatchCollection(circle_patches)\n circ_collection.set_facecolor('none')\n circ_collection.set_transform(axTrans)\n circ_collection.set_edgecolor(BLACK)\n circ_collection.set_alpha(.5)\n # Body of arrows\n arw_collection = PatchCollection(arrow_patches)\n arw_collection.set_transform(axTrans)\n arw_collection.set_linewidth(.5)\n arw_collection.set_color(RED)\n arw_collection.set_alpha(1)\n # Border of arrows\n arw_collection2 = matplotlib.collections.PatchCollection(arrow_patches2)\n arw_collection2.set_transform(axTrans)\n arw_collection2.set_linewidth(1)\n arw_collection2.set_color(BLACK)\n arw_collection2.set_alpha(1)\n # Add artists to axes\n ax.add_collection(circ_collection)\n ax.add_collection(arw_collection2)\n ax.add_collection(arw_collection)\n\n\ndef feat_scores_to_color(fs, cmap_='hot'):\n assert len(fs.shape) == 1, 'score must be 1d'\n cmap = plt.get_cmap(cmap_)\n mins = fs.min()\n rnge = fs.max() - mins\n if rnge == 0:\n return [cmap(.5) for fx in xrange(len(fs))]\n score2_01 = lambda score: .1 + .9 * (float(score) - mins) / (rnge)\n colors = [cmap(score2_01(score)) for score in fs]\n return colors\n\n\ndef colorbar(scalars, colors):\n 'adds a color bar next to the axes'\n orientation = ['vertical', 'horizontal'][0]\n TICK_FONTSIZE = 8\n # Put colors and scalars in correct order\n sorted_scalars = sorted(scalars)\n sorted_colors = [x for (y, x) in sorted(zip(scalars, colors))]\n # Make a listed colormap and mappable object\n listed_cmap = mpl.colors.ListedColormap(sorted_colors)\n sm = plt.cm.ScalarMappable(cmap=listed_cmap)\n sm.set_array(sorted_scalars)\n # Use mapable object to create the colorbar\n cb = plt.colorbar(sm, orientation=orientation)\n # Add the colorbar to the correct label\n axis = cb.ax.xaxis if orientation == 'horizontal' else cb.ax.yaxis\n position = 'bottom' if orientation == 'horizontal' else 'right'\n axis.set_ticks_position(position)\n axis.set_ticks([0, .5, 1])\n cb.ax.tick_params(labelsize=TICK_FONTSIZE)\n\n\ndef draw_lines2(kpts1, kpts2, fm=None, fs=None, kpts2_offset=(0, 0),\n color_list=None, **kwargs):\n if not DISTINCT_COLORS:\n color_list = None\n # input data\n if not SHOW_LINES:\n return\n if fm is None: # assume kpts are in director correspondence\n assert kpts1.shape == kpts2.shape\n if len(fm) == 0:\n return\n ax = gca()\n woff, hoff = kpts2_offset\n # Draw line collection\n kpts1_m = kpts1[fm[:, 0]].T\n kpts2_m = kpts2[fm[:, 1]].T\n xxyy_iter = iter(zip(kpts1_m[0],\n kpts2_m[0] + woff,\n kpts1_m[1],\n kpts2_m[1] + hoff))\n if color_list is None:\n if fs is None: # Draw with solid color\n color_list = [ LINE_COLOR for fx in xrange(len(fm))]\n else: # Draw with colors proportional to score difference\n color_list = feat_scores_to_color(fs)\n segments = [((x1, y1), (x2, y2)) for (x1, x2, y1, y2) in xxyy_iter]\n linewidth = [LINE_WIDTH for fx in xrange(len(fm))]\n line_alpha = LINE_ALPHA\n if LINE_ALPHA_OVERRIDE is not None:\n line_alpha = LINE_ALPHA_OVERRIDE\n line_group = LineCollection(segments, linewidth, color_list, alpha=line_alpha)\n #plt.colorbar(line_group, ax=ax)\n ax.add_collection(line_group)\n #figure(100)\n #plt.hexbin(x,y, cmap=plt.cm.YlOrRd_r)\n\n\ndef draw_kpts(kpts, *args, **kwargs):\n draw_kpts2(kpts, *args, **kwargs)\n\n\ndef draw_kpts2(kpts, offset=(0, 0), ell=SHOW_ELLS, pts=False, pts_color=ORANGE,\n pts_size=POINT_SIZE, ell_alpha=ELL_ALPHA,\n ell_linewidth=ELL_LINEWIDTH, ell_color=ELL_COLOR,\n color_list=None, rect=None, arrow=False, **kwargs):\n if not DISTINCT_COLORS:\n color_list = None\n printDBG('drawkpts2: Drawing Keypoints! ell=%r pts=%r' % (ell, pts))\n # get matplotlib info\n ax = gca()\n pltTrans = ax.transData\n ell_actors = []\n # data\n kpts = np.array(kpts)\n kptsT = kpts.T\n x = kptsT[0, :] + offset[0]\n y = kptsT[1, :] + offset[1]\n printDBG('[df2] draw_kpts()----------')\n printDBG('[df2] draw_kpts() ell=%r pts=%r' % (ell, pts))\n printDBG('[df2] draw_kpts() drawing kpts.shape=%r' % (kpts.shape,))\n if rect is None:\n rect = ell\n rect = False\n if pts is True:\n rect = False\n if ell or rect:\n printDBG('[df2] draw_kpts() drawing ell kptsT.shape=%r' % (kptsT.shape,))\n # We have the transformation from unit circle to ellipse here. (inv(A))\n a = kptsT[2]\n b = np.zeros(len(a))\n c = kptsT[3]\n d = kptsT[4]\n\n kpts_iter = izip(x, y, a, b, c, d)\n aff_list = [Affine2D([( a_, b_, x_),\n ( c_, d_, y_),\n ( 0, 0, 1)])\n for (x_, y_, a_, b_, c_, d_) in kpts_iter]\n patch_list = []\n ell_actors = [Circle( (0, 0), 1, transform=aff) for aff in aff_list]\n if ell:\n patch_list += ell_actors\n if rect:\n rect_actors = [Rectangle( (-1, -1), 2, 2, transform=aff) for aff in aff_list]\n patch_list += rect_actors\n if arrow:\n _kwargs = dict(head_width=.01, length_includes_head=False)\n arrow_actors1 = [FancyArrow(0, 0, 0, 1, transform=aff, **_kwargs) for aff in aff_list]\n arrow_actors2 = [FancyArrow(0, 0, 1, 0, transform=aff, **_kwargs) for aff in aff_list]\n patch_list += arrow_actors1\n patch_list += arrow_actors2\n ellipse_collection = matplotlib.collections.PatchCollection(patch_list)\n ellipse_collection.set_facecolor('none')\n ellipse_collection.set_transform(pltTrans)\n if ELL_ALPHA_OVERRIDE is not None:\n ell_alpha = ELL_ALPHA_OVERRIDE\n ellipse_collection.set_alpha(ell_alpha)\n ellipse_collection.set_linewidth(ell_linewidth)\n if not color_list is None:\n ell_color = color_list\n if ell_color == 'distinct':\n ell_color = distinct_colors(len(kpts))\n ellipse_collection.set_edgecolor(ell_color)\n ax.add_collection(ellipse_collection)\n if pts:\n printDBG('[df2] draw_kpts() drawing pts x.shape=%r y.shape=%r' % (x.shape, y.shape))\n if color_list is None:\n color_list = [pts_color for _ in xrange(len(x))]\n ax.autoscale(enable=False)\n ax.scatter(x, y, c=color_list, s=2 * pts_size, marker='o', edgecolor='none')\n #ax.autoscale(enable=False)\n #ax.plot(x, y, linestyle='None', marker='o', markerfacecolor=pts_color, markersize=pts_size, markeredgewidth=0)\n\n\n# ---- CHIP DISPLAY COMMANDS ----\ndef imshow(img, fnum=None, title=None, figtitle=None, pnum=None,\n interpolation='nearest', **kwargs):\n 'other interpolations = nearest, bicubic, bilinear'\n #printDBG('[df2] ----- IMSHOW ------ ')\n #printDBG('[***df2.imshow] fnum=%r pnum=%r title=%r *** ' % (fnum, pnum, title))\n #printDBG('[***df2.imshow] img.shape = %r ' % (img.shape,))\n #printDBG('[***df2.imshow] img.stats = %r ' % (helpers.printable_mystats(img),))\n fig = figure(fnum=fnum, pnum=pnum, title=title, figtitle=figtitle, **kwargs)\n ax = gca()\n if not DARKEN is None:\n imgdtype = img.dtype\n img = np.array(img, dtype=float) * DARKEN\n img = np.array(img, dtype=imgdtype)\n\n plt_imshow_kwargs = {\n 'interpolation': interpolation,\n #'cmap': plt.get_cmap('gray'),\n 'vmin': 0,\n 'vmax': 255,\n }\n try:\n if len(img.shape) == 3 and img.shape[2] == 3:\n # img is in a color format\n imgBGR = img\n if imgBGR.dtype == np.float64:\n if imgBGR.max() <= 1:\n imgBGR = np.array(imgBGR, dtype=np.float32)\n else:\n imgBGR = np.array(imgBGR, dtype=np.uint8)\n imgRGB = cv2.cvtColor(imgBGR, cv2.COLOR_BGR2RGB)\n ax.imshow(imgRGB, **plt_imshow_kwargs)\n elif len(img.shape) == 2:\n # img is in grayscale\n imgGRAY = img\n ax.imshow(imgGRAY, cmap=plt.get_cmap('gray'), **plt_imshow_kwargs)\n else:\n raise Exception('unknown image format')\n except TypeError as te:\n print('[df2] imshow ERROR %r' % te)\n raise\n except Exception as ex:\n print('[df2] img.dtype = %r' % (img.dtype,))\n print('[df2] type(img) = %r' % (type(img),))\n print('[df2] img.shape = %r' % (img.shape,))\n print('[df2] imshow ERROR %r' % ex)\n raise\n #plt.set_cmap('gray')\n ax.set_xticks([])\n ax.set_yticks([])\n #ax.set_autoscale(False)\n #try:\n #if pnum == 111:\n #fig.tight_layout()\n #except Exception as ex:\n #print('[df2] !! Exception durring fig.tight_layout: '+repr(ex))\n #raise\n return fig, ax\n\n\ndef get_num_channels(img):\n ndims = len(img.shape)\n if ndims == 2:\n nChannels = 1\n elif ndims == 3 and img.shape[2] == 3:\n nChannels = 3\n elif ndims == 3 and img.shape[2] == 1:\n nChannels = 1\n else:\n raise Exception('Cannot determine number of channels')\n return nChannels\n\n\ndef stack_images(img1, img2, vert=None):\n nChannels = get_num_channels(img1)\n nChannels2 = get_num_channels(img2)\n assert nChannels == nChannels2\n (h1, w1) = img1.shape[0: 2] # get chip dimensions\n (h2, w2) = img2.shape[0: 2]\n woff, hoff = 0, 0\n vert_wh = max(w1, w2), h1 + h2\n horiz_wh = w1 + w2, max(h1, h2)\n if vert is None:\n # Display the orientation with the better (closer to 1) aspect ratio\n vert_ar = max(vert_wh) / min(vert_wh)\n horiz_ar = max(horiz_wh) / min(horiz_wh)\n vert = vert_ar < horiz_ar\n if vert:\n wB, hB = vert_wh\n hoff = h1\n else:\n wB, hB = horiz_wh\n woff = w1\n # concatentate images\n if nChannels == 3:\n imgB = np.zeros((hB, wB, 3), np.uint8)\n imgB[0:h1, 0:w1, :] = img1\n imgB[hoff:(hoff + h2), woff:(woff + w2), :] = img2\n elif nChannels == 1:\n imgB = np.zeros((hB, wB), np.uint8)\n imgB[0:h1, 0:w1] = img1\n imgB[hoff:(hoff + h2), woff:(woff + w2)] = img2\n return imgB, woff, hoff\n\n\ndef show_chipmatch2(rchip1, rchip2, kpts1, kpts2, fm=None, fs=None, title=None,\n vert=None, fnum=None, pnum=None, **kwargs):\n '''Draws two chips and the feature matches between them. feature matches\n kpts1 and kpts2 use the (x,y,a,c,d)\n '''\n printDBG('[df2] draw_matches2() fnum=%r, pnum=%r' % (fnum, pnum))\n # get matching keypoints + offset\n (h1, w1) = rchip1.shape[0:2] # get chip (h, w) dimensions\n (h2, w2) = rchip2.shape[0:2]\n # Stack the compared chips\n match_img, woff, hoff = stack_images(rchip1, rchip2, vert)\n xywh1 = (0, 0, w1, h1)\n xywh2 = (woff, hoff, w2, h2)\n # Show the stacked chips\n fig, ax = imshow(match_img, title=title, fnum=fnum, pnum=pnum)\n # Overlay feature match nnotations\n draw_fmatch(xywh1, xywh2, kpts1, kpts2, fm, fs, **kwargs)\n return ax, xywh1, xywh2\n\n\n# draw feature match\ndef draw_fmatch(xywh1, xywh2, kpts1, kpts2, fm, fs=None, lbl1=None, lbl2=None,\n fnum=None, pnum=None, rect=False, colorbar_=True, **kwargs):\n '''Draws the matching features. This is draw because it is an overlay\n xywh1 - location of rchip1 in the axes\n xywh2 - location or rchip2 in the axes\n '''\n if fm is None:\n assert kpts1.shape == kpts2.shape, 'shapes different or fm not none'\n fm = np.tile(np.arange(0, len(kpts1)), (2, 1)).T\n pts = kwargs.get('draw_pts', False)\n ell = kwargs.get('draw_ell', True)\n lines = kwargs.get('draw_lines', True)\n ell_alpha = kwargs.get('ell_alpha', .4)\n nMatch = len(fm)\n #printDBG('[df2.draw_fnmatch] nMatch=%r' % nMatch)\n x1, y1, w1, h1 = xywh1\n x2, y2, w2, h2 = xywh2\n offset2 = (x2, y2)\n # Custom user label for chips 1 and 2\n if lbl1 is not None:\n absolute_lbl(x1 + w1, y1, lbl1)\n if lbl2 is not None:\n absolute_lbl(x2 + w2, y2, lbl2)\n # Plot the number of matches\n if kwargs.get('show_nMatches', False):\n upperleft_text('#match=%d' % nMatch)\n # Draw all keypoints in both chips as points\n if kwargs.get('all_kpts', False):\n all_args = dict(ell=False, pts=pts, pts_color=GREEN, pts_size=2,\n ell_alpha=ell_alpha, rect=rect)\n all_args.update(kwargs)\n draw_kpts2(kpts1, **all_args)\n draw_kpts2(kpts2, offset=offset2, **all_args)\n # Draw Lines and Ellipses and Points oh my\n if nMatch > 0:\n colors = [kwargs['colors']] * nMatch if 'colors' in kwargs else distinct_colors(nMatch)\n if fs is not None:\n colors = feat_scores_to_color(fs, 'hot')\n\n acols = add_alpha(colors)\n\n # Helper functions\n def _drawkpts(**_kwargs):\n _kwargs.update(kwargs)\n fxs1 = fm[:, 0]\n fxs2 = fm[:, 1]\n draw_kpts2(kpts1[fxs1], rect=rect, **_kwargs)\n draw_kpts2(kpts2[fxs2], offset=offset2, rect=rect, **_kwargs)\n\n def _drawlines(**_kwargs):\n _kwargs.update(kwargs)\n draw_lines2(kpts1, kpts2, fm, fs, kpts2_offset=offset2, **_kwargs)\n\n # User helpers\n if ell:\n _drawkpts(pts=False, ell=True, color_list=colors)\n if pts:\n _drawkpts(pts_size=8, pts=True, ell=False, pts_color=BLACK)\n _drawkpts(pts_size=6, pts=True, ell=False, color_list=acols)\n if lines:\n _drawlines(color_list=colors)\n else:\n draw_boxedX(xywh2)\n if fs is not None and colorbar_ and 'colors' in vars() and colors is not None:\n colorbar(fs, colors)\n #legend()\n return None\n\n\ndef draw_boxedX(xywh, color=RED, lw=2, alpha=.5, theta=0):\n 'draws a big red x. redx'\n ax = gca()\n x1, y1, w, h = xywh\n x2, y2 = x1 + w, y1 + h\n segments = [((x1, y1), (x2, y2)),\n ((x1, y2), (x2, y1))]\n trans = Affine2D()\n trans.rotate(theta)\n trans = trans + ax.transData\n width_list = [lw] * len(segments)\n color_list = [color] * len(segments)\n line_group = LineCollection(segments, width_list, color_list, alpha=alpha,\n transOffset=trans)\n ax.add_collection(line_group)\n\n\ndef disconnect_callback(fig, callback_type, **kwargs):\n #print('[df2] disconnect %r callback' % callback_type)\n axes = kwargs.get('axes', [])\n for ax in axes:\n ax._hs_viewtype = ''\n cbid_type = callback_type + '_cbid'\n cbfn_type = callback_type + '_func'\n cbid = fig.__dict__.get(cbid_type, None)\n cbfn = fig.__dict__.get(cbfn_type, None)\n if cbid is not None:\n fig.canvas.mpl_disconnect(cbid)\n else:\n cbfn = None\n fig.__dict__[cbid_type] = None\n return cbid, cbfn\n\n\ndef connect_callback(fig, callback_type, callback_fn):\n #print('[df2] register %r callback' % callback_type)\n if callback_fn is None:\n return\n cbid_type = callback_type + '_cbid'\n cbfn_type = callback_type + '_func'\n fig.__dict__[cbid_type] = fig.canvas.mpl_connect(callback_type, callback_fn)\n fig.__dict__[cbfn_type] = callback_fn\n"},"license":{"kind":"string","value":"apache-2.0"},"hash":{"kind":"number","value":-1678968028501710800,"string":"-1,678,968,028,501,710,800"},"line_mean":{"kind":"number","value":31.6976047904,"string":"31.697605"},"line_max":{"kind":"number","value":119,"string":"119"},"alpha_frac":{"kind":"number","value":0.588352715,"string":"0.588353"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.0527757589310673,"string":"3.052776"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45161,"cells":{"repo_name":{"kind":"string","value":"silas/rock"},"path":{"kind":"string","value":"rock/text.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"1235"},"content":{"kind":"string","value":"from __future__ import unicode_literals\n\n\ndef _(text):\n return text.strip('\\n')\n\nUSAGE = _(\"\"\"\nUsage: rock [--help] [--env=ENV] [--path=PATH] [--runtime=RUNTIME] command\n\"\"\")\n\nHELP = _(\"\"\"\n --help show help message\n --verbose show script while running\n --dry-run show script without running\n --version show version\n\nproject:\n --env=ENV set env\n --path=PATH set path\n --runtime=RUNTIME set runtime\n\ncommands:\n build run build\n test run tests\n run run in environment\n clean clean project files\n\nother commands:\n config show project configuration\n env show evaluable environment variables\n init generates project skeleton\n runtime show installed runtimes\n\"\"\")\n\nCONFIG_USAGE = _(\"\"\"\nUsage: rock config [--format=FORMAT]\n\"\"\")\n\nCONFIG_HELP = _(\"\"\"\n --help show help message\n --format set output format (json, yaml)\n\"\"\")\n\nENV_USAGE = _(\"\"\"\nUsage: rock env\n\"\"\")\n\nENV_HELP = _(\"\"\"\n --help show help message\n\"\"\")\n\nRUNTIME_USAGE = _(\"\"\"\nUsage: rock runtime\n\"\"\")\n\nRUNTIME_HELP = _(\"\"\"\n --help show help message\n\"\"\")\n"},"license":{"kind":"string","value":"mit"},"hash":{"kind":"number","value":5519456527590050000,"string":"5,519,456,527,590,050,000"},"line_mean":{"kind":"number","value":20.2931034483,"string":"20.293103"},"line_max":{"kind":"number","value":74,"string":"74"},"alpha_frac":{"kind":"number","value":0.5457489879,"string":"0.545749"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":4.116666666666666,"string":"4.116667"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45162,"cells":{"repo_name":{"kind":"string","value":"setsid/yacron"},"path":{"kind":"string","value":"yacron/time.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"5052"},"content":{"kind":"string","value":"\"\"\"\n This file is part of yacron.\n\n Copyright (C) 2016 Vadim Kuznetsov \n\n yacron is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n yacron is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with yacron. If not, see .\n\"\"\"\n\n\nclass CronTime(object):\n \"\"\"\n Parse and store scheduled time.\n \"\"\"\n def __init__(self, minutes, hours, weekdays):\n \"\"\"\n Parse and store the minutes, hours and weekdays values.\n :param minutes: Minutes (str)\n :param hours: Hours (str)\n :param weekdays: Weekdays (str)\n :raise ValueError if any of the values is invalid\n \"\"\"\n self._minutes = self._parse_value(0, minutes, 59)\n self._hours = self._parse_value(0, hours, 23)\n # slashes are unacceptable in weekdays value\n self._weekdays = self._parse_value(1, weekdays, 7, slash_acceptable=False)\n\n @property\n def minutes(self):\n return self._minutes\n\n @property\n def hours(self):\n return self._hours\n\n @property\n def weekdays(self):\n return self._weekdays\n\n def _check_value_range(self, min_value, value, max_value):\n \"\"\"\n Check is value in range.\n :param min_value: Minimal valid value\n :param value: Value\n :param max_value: Maximum valid value\n :return True if the value is in range\n :raise ValueError if the value is out of range\n \"\"\"\n if not (min_value <= value <= max_value):\n raise ValueError(\"invalid value '{0:d}', must be in [{1:d}..{2:d}]\".format(value, min_value, max_value))\n return True\n\n def _check_special_chars(self, value):\n \"\"\"\n Check special characters in the value:\n 1) value can not contains more than one '*' or '/' or '-' characters;\n 2) special characters can not be mixed (there can be the only one except ',');\n :param value: Value.\n :raise ValueError if any invalid sequence of special characters found in the value.\n \"\"\"\n all_count = value.count('*')\n slash_count = value.count('/')\n comma_count = value.count(',')\n hyphen_count = value.count('-')\n\n is_invalid = any((\n all_count > 1,\n slash_count > 1,\n hyphen_count > 1,\n all_count and (slash_count or comma_count or hyphen_count),\n slash_count and (all_count or comma_count or hyphen_count),\n comma_count and (all_count or slash_count or hyphen_count),\n hyphen_count and (all_count or slash_count or comma_count),\n ))\n\n if is_invalid:\n raise ValueError(\"invalid format in value '{0:s}'\".format(value))\n\n def _parse_value(self, min_value, value, max_value, slash_acceptable=True):\n \"\"\"\n Parse and check a value.\n :param min_value: Minimal valid value\n :param value: Value\n :param max_value: Maximum valid value\n :param slash_acceptable: Slash is valid in the value\n :return: List of values.\n :raise ValueError if parsing failed\n \"\"\"\n self._check_special_chars(value)\n\n if value == '*':\n return list(range(min_value, max_value + 1))\n\n if value.startswith('/'):\n if not slash_acceptable:\n raise ValueError(\"value '{0:s}' can not contains slash\".format(value))\n\n divisor = int(value[1:])\n self._check_value_range(min_value, divisor, max_value)\n\n return [n for n in range(min_value, max_value + 1) if n % divisor == 0]\n\n if '-' in value:\n start_value, stop_value = map(int, value.split('-'))\n\n self._check_value_range(min_value, start_value, max_value)\n self._check_value_range(min_value, stop_value, max_value)\n\n if start_value >= stop_value:\n raise ValueError(\"start value can not be greater or equal to stop value\")\n\n return list(range(start_value, stop_value + 1))\n\n if ',' in value:\n return [n for n in map(int, value.split(',')) if self._check_value_range(min_value, n, max_value)]\n\n return [int(value)]\n\n def check_time(self, cur_time):\n \"\"\"\n Compare parsed time and current time.\n :param cur_time: Current time (datetime).\n :return: True if current time matches with parser time and False otherwise\n \"\"\"\n return all((\n cur_time.minute in self._minutes,\n cur_time.hour in self._hours,\n cur_time.isoweekday() in self._weekdays,\n ))\n"},"license":{"kind":"string","value":"gpl-3.0"},"hash":{"kind":"number","value":7801523714869108000,"string":"7,801,523,714,869,108,000"},"line_mean":{"kind":"number","value":35.345323741,"string":"35.345324"},"line_max":{"kind":"number","value":116,"string":"116"},"alpha_frac":{"kind":"number","value":0.5987727633,"string":"0.598773"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":4.103980503655564,"string":"4.103981"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45163,"cells":{"repo_name":{"kind":"string","value":"UCSC-iGEM-2016/taris_controller"},"path":{"kind":"string","value":"taris_controller/taris_sensor.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"9944"},"content":{"kind":"string","value":"#!/usr/bin/python\n\nfrom __future__ import print_function\nimport io # used to create file streams\nimport fcntl # used to access I2C parameters like addresses\nimport sys\nimport time # used for sleep delay and timestamps\n\n\nclass Taris_Sensor(): \n \n ''' This object holds all required interface data for the Atlas Scientific \\\n EZO pH and RTD sensors. Built off of the base library, with new functions \\\n added for calibration and additional testing. '''\n def __init__(self, address, bus):\n # open two file streams, one for reading and one for writing\n # the specific I2C channel is selected with bus\n # it is usually 1, except for older revisions where it's 0\n # wb and rb indicate binary read and write\n self.file_read = io.open(\"/dev/i2c-\"+str(bus), \"rb\", buffering=0)\n self.file_write = io.open(\"/dev/i2c-\"+str(bus), \"wb\", buffering=0)\n\n # initializes I2C to either a user specified or default address\n self.set_i2c_address(address)\n self.cal_timeout = 1.6 # timeout for calibrations\n self.read_timeout = 1.0 # timeout for reads\n self.short_timeout = 0.3 # timeout for regular commands\n \n # Set if testing board\n self.DEBUG = True\n \n def set_i2c_address(self, addr):\n '''Set the I2C communications to the slave specified by the address. \\\n The commands for I2C dev using the ioctl functions are specified in \\\n the i2c-dev.h file from i2c-tools'''\n I2C_SLAVE = 0x703\n fcntl.ioctl(self.file_read, I2C_SLAVE, addr)\n fcntl.ioctl(self.file_write, I2C_SLAVE, addr)\n\n def write(self, cmd):\n '''Writes a command to the sensor.'''\n # appends the null character and sends the string over I2C\n cmd += \"\\00\"\n self.file_write.write(cmd)\n\n def read(self, num_of_bytes=31,startbit=1):\n '''Reads data from the sensor and parses the incoming response.'''\n # reads a specified number of bytes from I2C, then parses and displays the result\n res = self.file_read.read(num_of_bytes) # read from the board\n response = filter(lambda x: x != '\\x00', res) # remove the null characters to get the response\n if ord(response[0]) == 1: # if the response isn't an error\n # change MSB to 0 for all received characters except the first and get a list of characters\n char_list = map(lambda x: chr(ord(x) & ~0x80), list(response[startbit:]))\n # NOTE: having to change the MSB to 0 is a glitch in the raspberry pi, and you shouldn't have to do this!\n return ''.join(char_list) # convert the char list to a string and returns it\n else:\n return \"Error \" + str(ord(response[0]))\n\n def query(self, string, start=1):\n '''For commands that require a write, a wait, and a response. For instance, \\\n calibration requires writing an initial CAL command, waiting 300ms, \\\n then checking for a pass/fail indicator message.'''\n # write a command to the board, wait the correct timeout, and read the response\n self.write(string)\n\n # the read and calibration commands require a longer timeout\n if string.upper().startswith(\"R\"):\n time.sleep(self.read_timeout)\n elif string.upper().startswith(\"CAL\"):\n time.sleep(self.cal_timeout)\n else:\n time.sleep(self.short_timeout)\n return self.read(startbit=start)\n\n def verify(self):\n '''Verifies that the sensor is connected, also returns firmware version.'''\n device_ID = self.query(\"I\")\n if device_ID.startswith(\"?I\"):\n print(\"Connected sensor: \" + str(device_ID)[3:])\n else:\n raw_input(\"EZO not connected: \" + device_ID)\n\n def close(self):\n '''Closes the sensor's filestream, not usually required.'''\n self.file_read.close()\n self.file_write.close()\n\n def getData(self):\n '''Gets data from sensor reading as a float.'''\n data = self.query(\"R\")\n return float(data)\n \n def cal_wait(self, cal_time):\n '''UI for waiting for pH sensor to stabilize during calibration'''\n x=1\n if self.DEBUG == True:\n cal_time = 4\n while x>\")\n self.cal_wait(5)\n q = str(ord(self.query(\"Cal,\"+str(cal_temp) + \"\\0x0d\", 0)))\n \n if q == \"1\":\n \n q = str(self.query(\"Cal,?\"))\n if q == \"?CAL,1\":\n print(\"One point temperature calibration complete!\")\n return True\n \n elif q == \"?CAL,0\":\n print(\"One point temperature calibration incomplete!\")\n cal_response = raw_input(\"Enter R to retry or Enter to exit.\")\n if cal_response == \"R\" or cal_response == \"r\":\n self.temp_calibrateSensor()\n else:\n return False\n else:\n print(\"Error setting new calibration temperature: \" + str(q))\n time.sleep(1)\n return False\n else:\n print(\"Could not set new calibration temperature: \" + str(q))\n time.sleep(1)\n return False\n else:\n print(\"Could not clear RTD sensor: \" + str(q))\n time.sleep(1)\n return False\n return False\n\n def pH_compensateTemp(self,temp):\n '''Compensates the pH sensor for temperature, is used in conjunction with \\\n a reading from the RTD sensor.'''\n comp_status = self.query(\"T,\" + str(temp),0)\n \n if str(ord(comp_status)) != '1':\n print(\"Temperature compensation failed!: \")\n time.sleep(2)\n return False\n\n else:\n comp_status = str(self.query(\"T,?\"))\n print(\"Temperature compensation set for: \" + comp_status[3:] + u'\\xb0' + \"C\")\n time.sleep(2)\n return False\n\n def lockProtocol(self,command):\n '''Not currently working. Normally used for locking some of the \\\n internal parameters (e.g. baud rate for UART mode).'''\n \n read_bytes = 9\n\n print(\"1.\\tDisconnect power to device and any signal wires.\\n\\\n 2.\\tShort PRB to TX.\\n\\\n 3.\\tTurn device on and wait for LED to change to blue.\\n\\\n 4.\\tRemove short from PRB to TX, then restart device.\\n\\\n 5.\\tConnect data lines to Raspberry Pi I2C pins.\")\n\n raw_input(\"Press Enter when this is complete.\")\n\n raw_input(\"Press Enter to prevent further changes to device configuration.\")\n command_message = \"PLOCK,\" + str(command)\n\n self.sensorQ(command_message)\n time.sleep(0.3)\n \n lock_status = self.sensorRead(read_bytes)\n if lock_status == \"?PLOCK,1\":\n print(\"Sensor settings locked.\")\n return_code = 1\n elif lock_status == \"?PLOCK,0\":\n print(\"Sensor settings unlocked.\")\n return_code = 0\n else:\n print(\"False locking sensor settings.\")\n return False\n\n return return_code\n"},"license":{"kind":"string","value":"gpl-3.0"},"hash":{"kind":"number","value":2327405068719227000,"string":"2,327,405,068,719,227,000"},"line_mean":{"kind":"number","value":38.776,"string":"38.776"},"line_max":{"kind":"number","value":117,"string":"117"},"alpha_frac":{"kind":"number","value":0.5594328238,"string":"0.559433"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":4.107393638992152,"string":"4.107394"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45164,"cells":{"repo_name":{"kind":"string","value":"lezizi/A-Framework"},"path":{"kind":"string","value":"python/local-source/source.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"2324"},"content":{"kind":"string","value":"#!/usr/bin/env python\r\n#\r\n# Copyright (C) 2012 LeZiZi Studio\r\n# \r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n\r\nclass SourceHandler():\r\n '''\r\n Provides basic source handling.\r\n\r\n Property:\r\n source: source object\r\n '''\r\n from base import Source\r\n\r\n def __init__(self, source=None):\r\n if source is None:\r\n self.source = self.Source()\r\n else:\r\n self.source = source\r\n\r\n def append(self,action):\r\n '''\r\n Append an Action to current source.\r\n \r\n Argument:\r\n action: An Action.\r\n Return:\r\n Boolean. True for success and False when action exsisits.\r\n '''\r\n \r\n self.source.list.append(action)\r\n \r\n def delete(self,act):\r\n '''\r\n Argument:\r\n act: An Action OR a string of action key.\r\n Return:\r\n Boolean. True for success.\r\n '''\r\n if self.source.list.count(act) == 0:\r\n del(self.list[self.list.index(act)])\r\n return(True)\r\n else:\r\n return(False)\r\n \r\n def join(self, source):\r\n '''\r\n Copy source form another souce to current source.\r\n '''\r\n for each in source:\r\n if self.list.count(each) == 0 :\r\n self.list.append(each)\r\n\r\n def match(self,ingroups=[],outgroups=[],implementation=None,key=None):\r\n ### NOT YET IMP ##\r\n pass\r\n\r\ndef test():\r\n from base import Action\r\n b = Action()\r\n b.key = \"1\"\r\n c = Action()\r\n c.key = \"1\"\r\n print(cmp(b,c))\r\n \r\n a = SourceHandler()\r\n \r\n print(a.append(b))\r\n print(a.append(c))\r\n print(a.source.list)\r\n print(a.delete(b))\r\n #for each in dir(a):\r\n # print(getattr(a,each))\r\n \r\n# test()\r\n"},"license":{"kind":"string","value":"apache-2.0"},"hash":{"kind":"number","value":-1190390218465255400,"string":"-1,190,390,218,465,255,400"},"line_mean":{"kind":"number","value":25.023255814,"string":"25.023256"},"line_max":{"kind":"number","value":76,"string":"76"},"alpha_frac":{"kind":"number","value":0.5477624785,"string":"0.547762"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":4.0700525394045535,"string":"4.070053"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45165,"cells":{"repo_name":{"kind":"string","value":"lyndsysimon/hgrid-git-example"},"path":{"kind":"string","value":"app.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"1874"},"content":{"kind":"string","value":"from flask import Flask, jsonify, render_template, request\nimport json\nimport os\nimport tempfile\n\napp = Flask(__name__)\n\nfrom git_subprocess import Repository\n\nrepo_path = '/tmp/test/'\n\n# Set up a git repository for a storage backend\nrepo = Repository(repo_path or tempfile.mkdtemp())\nrepo.init()\n\n# Homepage - just render the template\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n# DELETE verb\n@app.route('/api/files/', methods=['DELETE', ])\ndef delete_files():\n # since multiple items could be deleted at once, iterate the list.\n for id in json.loads(request.form.get('ids', '[]')):\n repo._rm_file(id)\n repo.commit(\n author='Internet User ',\n message='Deleted file(s)',\n )\n\n return jsonify({'deleted': request.form.get('ids')})\n\n# GET verb\n@app.route('/api/files/', methods=['GET', ])\ndef get_files():\n return jsonify({\n 'files': [\n _file_dict(f)\n for f in os.listdir(repo.path)\n if os.path.isfile(os.path.join(repo.path, f))\n ]\n })\n\n# POST verb\n@app.route('/api/files/', methods=['POST', ])\ndef add_file():\n f = request.files.get('file')\n\n # write the file out to its new location\n new_path = os.path.join(repo.path, f.filename)\n with open(new_path, 'w') as outfile:\n outfile.write(f.read())\n\n # add it to git and commit\n repo.add_file(\n file_path=f.filename,\n commit_author='Internet User ',\n commit_message='Commited file {}'.format(f.filename)\n )\n\n return json.dumps([_file_dict(new_path), ])\n\ndef _file_dict(f):\n return {\n 'uid': f,\n 'name': f,\n 'size': os.path.getsize(os.path.join(repo.path, f)),\n 'type': 'file',\n 'parent_uid': 'null'\n }\n\n\nif __name__ == '__main__':\n app.run(debug=True, port=5000)\n\n\n"},"license":{"kind":"string","value":"bsd-2-clause"},"hash":{"kind":"number","value":4562782882468337000,"string":"4,562,782,882,468,337,000"},"line_mean":{"kind":"number","value":23.3376623377,"string":"23.337662"},"line_max":{"kind":"number","value":70,"string":"70"},"alpha_frac":{"kind":"number","value":0.5939167556,"string":"0.593917"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.432234432234432,"string":"3.432234"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45166,"cells":{"repo_name":{"kind":"string","value":"lliss/tr-55"},"path":{"kind":"string","value":"tr55/model.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"14151"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\nfrom __future__ import division\n\n\"\"\"\nTR-55 Model Implementation\n\nA mapping between variable/parameter names found in the TR-55 document\nand variables used in this program are as follows:\n * `precip` is referred to as P in the report\n * `runoff` is Q\n * `evaptrans` maps to ET, the evapotranspiration\n * `inf` is the amount of water that infiltrates into the soil (in inches)\n * `init_abs` is Ia, the initial abstraction, another form of infiltration\n\"\"\"\n\nimport copy\n\nfrom tr55.tablelookup import lookup_cn, lookup_bmp_infiltration, \\\n lookup_ki, is_bmp, is_built_type, make_precolumbian, get_pollutants\nfrom tr55.water_quality import get_volume_of_runoff, get_pollutant_load\nfrom tr55.operations import dict_plus\n\n\ndef runoff_pitt(precip, land_use):\n \"\"\"\n The Pitt Small Storm Hydrology method. The output is a runoff\n value in inches.\n \"\"\"\n c1 = +3.638858398e-2\n c2 = -1.243464039e-1\n c3 = +1.295682223e-1\n c4 = +9.375868043e-1\n c5 = -2.235170859e-2\n c6 = +0.170228067e+0\n c7 = -3.971810782e-1\n c8 = +3.887275538e-1\n c9 = -2.289321859e-2\n p4 = pow(precip, 4)\n p3 = pow(precip, 3)\n p2 = pow(precip, 2)\n\n impervious = (c1 * p3) + (c2 * p2) + (c3 * precip) + c4\n urb_grass = (c5 * p4) + (c6 * p3) + (c7 * p2) + (c8 * precip) + c9\n\n runoff_vals = {\n 'open_water': impervious,\n 'developed_low': 0.20 * impervious + 0.80 * urb_grass,\n 'cluster_housing': 0.20 * impervious + 0.80 * urb_grass,\n 'developed_med': 0.65 * impervious + 0.35 * urb_grass,\n 'developed_high': impervious,\n 'developed_open': urb_grass\n }\n\n if land_use not in runoff_vals:\n raise Exception('Land use %s not a built-type.' % land_use)\n else:\n return min(runoff_vals[land_use], precip)\n\n\ndef nrcs_cutoff(precip, curve_number):\n \"\"\"\n A function to find the cutoff between precipitation/curve number\n pairs that have zero runoff by definition, and those that do not.\n \"\"\"\n if precip <= -1 * (2 * (curve_number - 100.0) / curve_number):\n return True\n else:\n return False\n\n\ndef runoff_nrcs(precip, evaptrans, soil_type, land_use):\n \"\"\"\n The runoff equation from the TR-55 document. The output is a\n runoff value in inches.\n \"\"\"\n if land_use == 'cluster_housing':\n land_use = 'developed_low'\n curve_number = lookup_cn(soil_type, land_use)\n if nrcs_cutoff(precip, curve_number):\n return 0.0\n potential_retention = (1000.0 / curve_number) - 10\n initial_abs = 0.2 * potential_retention\n precip_minus_initial_abs = precip - initial_abs\n numerator = pow(precip_minus_initial_abs, 2)\n denominator = (precip_minus_initial_abs + potential_retention)\n runoff = numerator / denominator\n return min(runoff, precip - evaptrans)\n\n\ndef simulate_cell_day(precip, evaptrans, cell, cell_count):\n \"\"\"\n Simulate a bunch of cells of the same type during a one-day event.\n\n `precip` is the amount of precipitation in inches.\n\n `evaptrans` is evapotranspiration.\n\n `cell` is a string which contains a soil type and land use\n separated by a colon.\n\n `cell_count` is the number of cells to simulate.\n\n The return value is a dictionary of runoff, evapotranspiration, and\n infiltration as volumes of water.\n \"\"\"\n def clamp(runoff, et, inf, precip):\n \"\"\"\n This function clamps ensures that runoff + et + inf <= precip.\n\n NOTE: infiltration is normally independent of the\n precipitation level, but this function introduces a slight\n dependency (that is, at very low levels of precipitation, this\n function can cause infiltration to be smaller than it\n ordinarily would be.\n \"\"\"\n total = runoff + et + inf\n if (total > precip):\n scale = precip / total\n runoff *= scale\n et *= scale\n inf *= scale\n return (runoff, et, inf)\n\n precip = max(0.0, precip)\n soil_type, land_use, bmp = cell.lower().split(':')\n\n # If there is no precipitation, then there is no runoff or\n # infiltration. There is evapotranspiration, however (it is\n # understood that over a period of time, this can lead to the sum\n # of the three values exceeding the total precipitation).\n if precip == 0.0:\n return {\n 'runoff-vol': 0.0,\n # 'et-vol': cell_count * evaptrans,\n 'et-vol': 0.0,\n 'inf-vol': 0.0,\n }\n\n # Deal with the Best Management Practices (BMPs). For most BMPs,\n # the infiltration is read from the table and the runoff is what\n # is left over after infiltration and evapotranspiration. Rain\n # gardens are treated differently.\n if bmp and is_bmp(bmp) and bmp != 'rain_garden':\n inf = lookup_bmp_infiltration(soil_type, bmp) # infiltration\n runoff = max(0.0, precip - (evaptrans + inf)) # runoff\n (runoff, evaptrans, inf) = clamp(runoff, evaptrans, inf, precip)\n return {\n 'runoff-vol': cell_count * runoff,\n 'et-vol': cell_count * evaptrans,\n 'inf-vol': cell_count * inf\n }\n elif bmp and bmp == 'rain_garden':\n # Here, return a mixture of 20% ideal rain garden and 80%\n # high-intensity residential.\n inf = lookup_bmp_infiltration(soil_type, bmp)\n runoff = max(0.0, precip - (evaptrans + inf))\n hi_res_cell = soil_type + ':developed_med:'\n hi_res = simulate_cell_day(precip, evaptrans, hi_res_cell, 1)\n hir_run = hi_res['runoff-vol']\n hir_et = hi_res['et-vol']\n hir_inf = hi_res['inf-vol']\n final_runoff = (0.2 * runoff + 0.8 * hir_run)\n final_et = (0.2 * evaptrans + 0.8 * hir_et)\n final_inf = (0.2 * inf + 0.8 * hir_inf)\n final = clamp(final_runoff, final_et, final_inf, precip)\n (final_runoff, final_et, final_inf) = final\n return {\n 'runoff-vol': cell_count * final_runoff,\n 'et-vol': cell_count * final_et,\n 'inf-vol': cell_count * final_inf\n }\n\n # At this point, if the `bmp` string has non-zero length, it is\n # equal to either 'no_till' or 'cluster_housing'.\n if bmp and bmp != 'no_till' and bmp != 'cluster_housing':\n raise KeyError('Unexpected BMP: %s' % bmp)\n land_use = bmp or land_use\n\n # When the land use is a built-type and the level of precipitation\n # is two inches or less, use the Pitt Small Storm Hydrology Model.\n # When the land use is a built-type but the level of precipitation\n # is higher, the runoff is the larger of that predicted by the\n # Pitt model and NRCS model. Otherwise, return the NRCS amount.\n if is_built_type(land_use) and precip <= 2.0:\n runoff = runoff_pitt(precip, land_use)\n elif is_built_type(land_use):\n pitt_runoff = runoff_pitt(2.0, land_use)\n nrcs_runoff = runoff_nrcs(precip, evaptrans, soil_type, land_use)\n runoff = max(pitt_runoff, nrcs_runoff)\n else:\n runoff = runoff_nrcs(precip, evaptrans, soil_type, land_use)\n inf = max(0.0, precip - (evaptrans + runoff))\n\n (runoff, evaptrans, inf) = clamp(runoff, evaptrans, inf, precip)\n return {\n 'runoff-vol': cell_count * runoff,\n 'et-vol': cell_count * evaptrans,\n 'inf-vol': cell_count * inf,\n }\n\n\ndef create_unmodified_census(census):\n \"\"\"\n This creates a cell census, ignoring any modifications. The\n output is suitable for use with `simulate_water_quality`.\n \"\"\"\n unmod = copy.deepcopy(census)\n unmod.pop('modifications', None)\n return unmod\n\n\ndef create_modified_census(census):\n \"\"\"\n This creates a cell census, with modifications, that is suitable\n for use with `simulate_water_quality`.\n\n For every type of cell that undergoes modification, the\n modifications are indicated with a sub-distribution under that\n cell type.\n \"\"\"\n mod = copy.deepcopy(census)\n mod.pop('modifications', None)\n\n for (cell, subcensus) in mod['distribution'].items():\n n = subcensus['cell_count']\n\n changes = {\n 'distribution': {\n cell: {\n 'distribution': {\n cell: {'cell_count': n}\n }\n }\n }\n }\n\n mod = dict_plus(mod, changes)\n\n for modification in (census.get('modifications') or []):\n for (orig_cell, subcensus) in modification['distribution'].items():\n n = subcensus['cell_count']\n soil1, land1 = orig_cell.split(':')\n soil2, land2, bmp = modification['change'].split(':')\n changed_cell = '%s:%s:%s' % (soil2 or soil1, land2 or land1, bmp)\n\n changes = {\n 'distribution': {\n orig_cell: {\n 'distribution': {\n orig_cell: {'cell_count': -n},\n changed_cell: {'cell_count': n}\n }\n }\n }\n }\n\n mod = dict_plus(mod, changes)\n\n return mod\n\n\ndef simulate_water_quality(tree, cell_res, fn,\n current_cell=None, precolumbian=False):\n \"\"\"\n Perform a water quality simulation by doing simulations on each of\n the cell types (leaves), then adding them together by summing the\n values of a node's subtrees and storing them at that node.\n\n `tree` is the (sub)tree of cell distributions that is currently\n under consideration.\n\n `cell_res` is the size of each cell (used for turning inches of\n water into volumes of water).\n\n `fn` is a function that takes a cell type and a number of cells\n and returns a dictionary containing runoff, et, and inf as\n volumes.\n\n `current_cell` is the cell type for the present node.\n \"\"\"\n # Internal node.\n if 'cell_count' in tree and 'distribution' in tree:\n n = tree['cell_count']\n\n # simulate subtrees\n if n != 0:\n tally = {}\n for cell, subtree in tree['distribution'].items():\n simulate_water_quality(subtree, cell_res, fn,\n cell, precolumbian)\n subtree_ex_dist = subtree.copy()\n subtree_ex_dist.pop('distribution', None)\n tally = dict_plus(tally, subtree_ex_dist)\n tree.update(tally) # update this node\n\n # effectively a leaf\n elif n == 0:\n for pol in get_pollutants():\n tree[pol] = 0.0\n\n # Leaf node.\n elif 'cell_count' in tree and 'distribution' not in tree:\n # the number of cells covered by this leaf\n n = tree['cell_count']\n\n # canonicalize the current_cell string\n split = current_cell.split(':')\n if (len(split) == 2):\n split.append('')\n if precolumbian:\n split[1] = make_precolumbian(split[1])\n current_cell = '%s:%s:%s' % tuple(split)\n\n # run the runoff model on this leaf\n result = fn(current_cell, n) # runoff, et, inf\n tree.update(result)\n\n # perform water quality calculation\n if n != 0:\n soil_type, land_use, bmp = split\n runoff_per_cell = result['runoff-vol'] / n\n liters = get_volume_of_runoff(runoff_per_cell, n, cell_res)\n for pol in get_pollutants():\n tree[pol] = get_pollutant_load(land_use, pol, liters)\n\n\ndef postpass(tree):\n \"\"\"\n Remove volume units and replace them with inches.\n \"\"\"\n if 'cell_count' in tree:\n if tree['cell_count'] > 0:\n n = tree['cell_count']\n tree['runoff'] = tree['runoff-vol'] / n\n tree['et'] = tree['et-vol'] / n\n tree['inf'] = tree['inf-vol'] / n\n else:\n tree['runoff'] = 0\n tree['et'] = 0\n tree['inf'] = 0\n tree.pop('runoff-vol', None)\n tree.pop('et-vol', None)\n tree.pop('inf-vol', None)\n\n if 'distribution' in tree:\n for subtree in tree['distribution'].values():\n postpass(subtree)\n\n\ndef simulate_modifications(census, fn, cell_res, precolumbian=False):\n \"\"\"\n Simulate effects of modifications.\n\n `census` contains a distribution of cell-types in the area of interest.\n\n `fn` is as described in `simulate_water_quality`.\n\n `cell_res` is as described in `simulate_water_quality`.\n \"\"\"\n mod = create_modified_census(census)\n simulate_water_quality(mod, cell_res, fn, precolumbian=precolumbian)\n postpass(mod)\n\n unmod = create_unmodified_census(census)\n simulate_water_quality(unmod, cell_res, fn, precolumbian=precolumbian)\n postpass(unmod)\n\n return {\n 'unmodified': unmod,\n 'modified': mod\n }\n\n\ndef simulate_day(census, precip, cell_res=10, precolumbian=False):\n \"\"\"\n Simulate a day, including water quality effects of modifications.\n\n `census` contains a distribution of cell-types in the area of interest.\n\n `cell_res` is as described in `simulate_water_quality`.\n\n `precolumbian` indicates that artificial types should be turned\n into forest.\n \"\"\"\n et_max = 0.207\n\n if 'modifications' in census:\n verify_census(census)\n\n def fn(cell, cell_count):\n # Compute et for cell type\n split = cell.split(':')\n if (len(split) == 2):\n (land_use, bmp) = split\n else:\n (_, land_use, bmp) = split\n et = et_max * lookup_ki(bmp or land_use)\n\n # Simulate the cell for one day\n return simulate_cell_day(precip, et, cell, cell_count)\n\n return simulate_modifications(census, fn, cell_res, precolumbian)\n\n\ndef verify_census(census):\n \"\"\"\n Assures that there is no soil type/land cover pair\n in a modification census that isn't in the AoI census.\n \"\"\"\n for modification in census['modifications']:\n for land_cover in modification['distribution']:\n if land_cover not in census['distribution']:\n raise ValueError(\"Invalid modification census\")\n"},"license":{"kind":"string","value":"apache-2.0"},"hash":{"kind":"number","value":-1927152914711812900,"string":"-1,927,152,914,711,812,900"},"line_mean":{"kind":"number","value":33.0987951807,"string":"33.098795"},"line_max":{"kind":"number","value":77,"string":"77"},"alpha_frac":{"kind":"number","value":0.5966362801,"string":"0.596636"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.4297140087251576,"string":"3.429714"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45167,"cells":{"repo_name":{"kind":"string","value":"luwei0917/awsemmd_script"},"path":{"kind":"string","value":"small_script/computeRg.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"2040"},"content":{"kind":"string","value":"from Bio.PDB.PDBParser import PDBParser\nimport argparse\nparser = argparse.ArgumentParser(description=\"Compute Rg of pdb\")\nparser.add_argument(\"pdb\", help=\"pdb file\")\nargs = parser.parse_args()\n\ndef computeRg(pdb_file, chain=\"A\"):\n # compute Radius of gyration\n # pdb_file = f\"/Users/weilu/Research/server/feb_2019/iterative_optimization_new_temp_range/all_simulations/{p}/{p}/crystal_structure.pdb\"\n chain_name = chain\n parser = PDBParser()\n structure = parser.get_structure('X', pdb_file)\n chain = list(structure[0][chain_name])\n all_res = list(structure.get_residues())\n # n = len(all_res)\n # n = len(chain)\n regular_res_list = [res for res in all_res if res.get_id()[0] == ' ']\n n = len(regular_res_list)\n print(\"all chains\")\n cutoff = 15\n for residue in regular_res_list:\n if residue.get_id()[0] == ' ' and abs(residue[\"CA\"].get_vector()[-1]) < cutoff:\n print(residue.get_id()[1])\n rg = 0.0\n for i, residue_i in enumerate(regular_res_list):\n for j, residue_j in enumerate(regular_res_list[i+1:]):\n try:\n r = residue_i[\"CA\"] - residue_j[\"CA\"]\n except:\n print(residue_i, residue_j)\n rg += r**2\n return (rg/(n**2))**0.5\n\nrg = computeRg(args.pdb)\nprint(rg)\n\n\ndef cylindrical_rg_bias_term(oa, k_rg=4.184, rg0=0, atomGroup=-1, forceGroup=27):\n nres, ca = oa.nres, oa.ca\n if atomGroup == -1:\n group = list(range(nres))\n else:\n group = atomGroup # atomGroup = [0, 1, 10, 12] means include residue 1, 2, 11, 13.\n n = len(group)\n rg_square = CustomBondForce(\"1/normalization*(x^2+y^2)\")\n # rg = CustomBondForce(\"1\")\n rg_square.addGlobalParameter(\"normalization\", n*n)\n for i in group:\n for j in group:\n if j <= i:\n continue\n rg_square.addBond(ca[i], ca[j], [])\n rg = CustomCVForce(f\"{k_rg}*(rg_square^0.5-{rg0})^2\")\n rg.addCollectiveVariable(\"rg_square\", rg_square)\n rg.setForceGroup(forceGroup)\n return rg\n"},"license":{"kind":"string","value":"mit"},"hash":{"kind":"number","value":9124268330187088000,"string":"9,124,268,330,187,088,000"},"line_mean":{"kind":"number","value":35.4285714286,"string":"35.428571"},"line_max":{"kind":"number","value":141,"string":"141"},"alpha_frac":{"kind":"number","value":0.5995098039,"string":"0.59951"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.022222222222222,"string":"3.022222"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45168,"cells":{"repo_name":{"kind":"string","value":"Airbitz/airbitz-ofx"},"path":{"kind":"string","value":"qbo.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"7851"},"content":{"kind":"string","value":"#####################################################################\r\n#\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#\r\n#\tFile: qbo.py\t\t\t\t\t\t\t\t\t\t\t\t\t#\r\n#\tDeveloper: Justin Leto\t\t\t\t\t\t\t\t\t\t\t#\r\n#\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#\r\n#\tqbo class provides an interface from main csv iterator method\t#\r\n#\tto handle qbo formatting, validations, and writing to file.\t\t#\r\n#\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#\r\n#\tUsage: python csvtoqbo.py \t\t\t\t\t#\r\n#\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#\r\n#####################################################################\r\n\r\nimport sys, traceback\r\nimport os\r\nfrom datetime import datetime\r\nimport logging\r\nimport qboconst\r\n\r\nclass qbo:\r\n\r\n\t#\tHolds a list of valid transactions via the addTransaction() method\r\n\t__transactions = list()\r\n\r\n\t#\tThe full QBO document build from constants and transactions\r\n\t__document = None\r\n\r\n\t#\tFlag indicating whether the QBO document is valid\r\n\t__isValid = None\r\n\r\n\t#\tconstructor\r\n\tdef __init__(self):\r\n\t\t#\tReads in constant values from file, set to private (const) variables\r\n\t\tself.__HEADER = qboconst.HEADER\r\n\t\tself.__FOOTER = qboconst.FOOTER\r\n\t\tself.__DATE_START = qboconst.DATE_START\r\n\t\tself.__DATE_END = qboconst.DATE_END\r\n\t\tself.__BANKTRANLIST_START = qboconst.BANKTRANLIST_START\r\n\t\tself.__BANKTRANLIST_END = qboconst.BANKTRANLIST_END\r\n\t\tself.__TRANSACTION_START = qboconst.TRANSACTION_START\r\n\t\tself.__TRANSACTION_END = qboconst.TRANSACTION_END\r\n\r\n\t\t#\tSet document to valid\r\n\t\tself.__isValid = True\r\n\t\r\n\r\n\t# PUBLIC GET METHODS for constant values - used in unit testing.\r\n\t#\r\n\t#\r\n\tdef getHEADER(self):\r\n\t\treturn self.__HEADER\r\n\r\n\tdef getFOOTER(self):\r\n\t\treturn self.__FOOTER\r\n\r\n\tdef getDATE_START(self):\r\n\t\treturn self.__DATE_START\r\n\r\n\tdef getDATE_END(self):\r\n\t\treturn self.__DATE_END\r\n\t\r\n\tdef getBANKTRANLIST_START(self):\r\n\t\treturn self.__BANKTRANLIST_START\r\n\r\n\tdef getBANKTRANLIST_END(self):\r\n\t\treturn self.__BANKTRANLIST_END\r\n\r\n\tdef getTRANSACTION_START(self):\r\n\t\treturn self.__TRANSACTION_START\r\n\r\n\tdef getTRANSACTION_END(self):\r\n\t\treturn self.__TRANSACTION_END\r\n\t\r\n\t#\tmethod to validate paramters used to submit transactions\r\n\tdef validateTransaction(self, status, date_posted, txn_type, to_from_flag, txn_amount, txn_exrate, name):\r\n\r\n\t\t# if str.lower(status) != 'completed':\r\n\t\t# \t#log status failure\r\n\t\t# \tlogging.info(\"Transaction status [\" + status + \"] invalid.\")\r\n\t\t# \traise Exception(\"Transaction status [\" + status + \"] invalid.\")\r\n #\r\n\t\t#if type(datetime.strptime(str(date_posted), '%m/%d/%Y')) is not datetime:\r\n\t\t#\tlogging.info(\"Transaction posted date [\" + date_posted + \"] invalid.\")\r\n\t\t#\traise Exception(\"Transaction posted date [\" + date_posted + \"] invalid.\")\r\n\r\n\t\t# if str.lower(txn_type) not in ('payment','refund','withdrawal', 'withdraw funds', 'send', 'receive'):\r\n\t\t# \tlogging.info(\"Transaction type [\" + str(txn_type) + \"] not 'Payment', 'Refund', 'Withdraw Funds', or 'Withdrawal'.\")\r\n\t\t# \traise Exception(\"Transaction type [\" + str(txn_type) + \"] not 'Payment', 'Refund', 'Withdraw Funds', or 'Withdrawal'.\")\r\n #\r\n\t\t# if str.lower(to_from_flag) not in ('to', 'from'):\r\n\t\t# \tlogging.info(\"Transaction 'To/From' field [\" + to_from_flag + \"] invalid.\")\r\n\t\t# \traise Exception(\"Transaction 'To/From' field [\" + to_from_flag + \"] invalid.\")\r\n #\r\n\t\t# #logical test of txn_type and to_from_flag\r\n\t\t# if ((str.lower(txn_type) == 'refund' and str.lower(to_from_flag) != 'to') or (str.lower(txn_type) == 'payment' and str.lower(to_from_flag) != 'from')):\r\n\t\t# \tlogging.info(\"Transaction type inconsistent with 'To/From' field.\")\r\n\t\t# \traise Exception(\"Transaction type inconsistent with 'To/From' field.\")\r\n #\r\n\t\tif len(name) == 0 or not name:\r\n\t\t\tlogging.info(\"Transaction name empty or null.\")\r\n\t\t\traise Exception(\"Transaction name empty or null.\")\r\n\r\n\t\treturn True\r\n\r\n\t#\tAdd transaction takes in param values uses the required formatting QBO transactions\r\n\t#\tand pushes to list\r\n\tdef addTransaction(self, denom, date_posted, txn_memo, txn_id, txn_amount, txn_curamt, txn_category, name):\r\n\t\t\r\n\t\t# try:\r\n\t\t# \t#\tValidating param values prior to committing transaction\r\n\t\t# \tself.validateTransaction(status, date_posted, txn_type, txn_id, txn_amount, name)\r\n\t\t# except:\r\n\t\t# \traise Exception\r\n\r\n\t\t#\tConstruct QBO formatted transaction\r\n\t\ttransaction = \"\"\r\n\r\n\t\tday = \"\"\r\n\t\tmonth = \"\"\r\n\t\tdate_array = date_posted.split('-')\r\n\t\tday = date_array[2]\r\n\t\tmonth = date_array[1]\r\n\t\tyear = date_array[0]\r\n\t\tif len(day) == 1:\r\n\t\t\tday = \"0\"+day\r\n\t\tif len(month) ==1:\r\n\t\t\tmonth = \"0\"+month\r\n\t\t\t\r\n\t\trec_date = datetime.strptime(year+\"/\"+month+\"/\"+day, '%Y/%m/%d')\r\n\t\trec_date = rec_date.strftime('%Y%m%d%H%M%S') + '.000'\r\n\r\n\t\tdtposted = ' ' + rec_date\r\n\r\n\t\tif float(txn_amount) > 0:\r\n\t\t\ttrtype = ' CREDIT'\r\n\t\telse:\r\n\t\t\ttrtype = ' DEBIT'\r\n\t\t#\r\n\t\t# if str.lower(txn_type) == 'receive':\r\n\t\t# \ttrtype = 'CREDIT'\r\n\t\t# elif str.lower(txn_type) == 'send':\r\n\t\t# \ttrtype = 'DEBIT'\r\n\r\n\t\t# if str.lower(txn_type) in ('refund', 'withdrawal', 'withdraw funds'):\r\n\t\t# \ttramt = '-' + str(txn_amount).replace('$','')\r\n\t\t# else:\r\n\t\t# \ttramt = '' + str(txn_amount).replace('$','')\r\n\r\n\t\ttramtbits = float(txn_amount) * denom\r\n\t\ttramt = ' ' + str(tramtbits)\r\n\r\n\t\tif name:\r\n\t\t\ttrname = ' ' + str(name) + \"\\n\"\r\n\t\telse:\r\n\t\t\ttrname = ''\r\n\r\n\t\texrate = float(txn_curamt) / (tramtbits)\r\n\t\tcuramt = \"{0:0.2f}\".format(abs(float(txn_curamt)))\r\n\t\tfmtexrate = \"{0:0.6f}\".format(float(exrate))\r\n\r\n\t\trawmemo = 'Rate=' + fmtexrate + \" USD=\" + curamt + \" category=\\\"\" + str(txn_category) + \"\\\" memo=\\\"\" + str(txn_memo)\r\n\t\tmemo = ' ' + rawmemo[:253] + \"\\\"\\n\"\r\n\r\n\t\tfitid = ' ' + str(txn_id)\r\n\t\texrate = ' ' + fmtexrate\r\n\r\n\t\ttransaction = (\"\" + self.__TRANSACTION_START + \"\\n\"\r\n\t\t\t\t\t\t\"\" + trtype + \"\\n\"\r\n\t\t\t\t\t\t\"\" + dtposted + \"\\n\"\r\n\t\t\t\t\t\t\"\" + tramt + \"\\n\"\r\n\t\t\t\t\t\t\"\" + fitid + \"\\n\"\r\n\t\t\t\t\t\t\"\" + trname +\r\n\t\t\t\t\t\t\"\" + memo +\r\n\t\t\t\t\t\t\"\" + \" \" + \"\\n\"\r\n\t\t\t\t\t\t\"\" + exrate + \"\\n\"\r\n\t\t\t\t\t\t\"\" + \" USD\" + \"\\n\"\r\n\t\t\t\t\t\t\"\" + \" \" + \"\\n\"\r\n\t\t\t\t\t\t\"\" + self.__TRANSACTION_END + \"\\n\")\r\n\r\n\t\t#\tCommit transaction to the document by adding to private member list object\r\n\t\tself.__transactions.append(transaction)\r\n\r\n\t\tlogging.info(\"Transaction [\" + str(self.getCount()) + \"] Accepted.\")\r\n\t\treturn True\r\n\r\n\t#\tget the current number of valid committed transactions\r\n\tdef getCount(self):\r\n\t\treturn len(self.__transactions)\r\n\r\n\t#\tget the valid status of the document\r\n\tdef isValid(self):\r\n\t\t#\tIf number of valid transactions are 0 document is invalid\r\n\t\tif self.getCount() == 0:\r\n\t\t\tself.__isValid = False\r\n\t\treturn self.__isValid\r\n\r\n\t#\tget the text of the document\r\n\tdef getDocument(self):\r\n\t\tself.Build()\r\n\t\treturn self.__document\r\n\r\n\t#\tConstruct the document, add the transactions\r\n\t#\tsave str into private member variable __document\r\n\tdef Build(self):\r\n\t\tif not self.isValid():\r\n\t\t\tlogging.info(\"Error: QBO document is not valid.\")\r\n\t\t\traise Exception(\"Error: QBO document is not valid.\")\r\n\r\n\t\tself.__document = (\"\" + self.__HEADER + \"\\n\"\r\n\t\t\t\t\t\"\" + self.__BANKTRANLIST_START + \"\\n\"\r\n\t\t\t\t\t\"\" + self.__DATE_START + \"\\n\"\r\n\t\t\t\t\t\"\" + self.__DATE_END + \"\\n\")\r\n\r\n\t\tfor txn in self.__transactions:\r\n\t\t\tself.__document = self.__document + str(txn)\r\n\t\t\r\n\t\tself.__document = self.__document + (\"\" + self.__BANKTRANLIST_END + \"\\n\"\r\n\t\t\t\t\t\t\t \"\" + self.__FOOTER + \"\")\r\n\r\n\t#\tWrite QBO document to file\r\n\tdef Write(self, filename):\r\n\r\n\t\ttry:\r\n\r\n\t\t\twith open(filename, 'w') as f:\r\n\t\t\t\t#\tgetDocument method will build document\r\n\t\t\t\t#\ttest for validity and return string for write\r\n\t\t\t\tf.write(self.getDocument())\r\n\r\n\t\t\treturn True\r\n\r\n\t\texcept:\r\n\t\t\t#log io error return False\r\n\t\t\texc_type, exc_value, exc_traceback = sys.exc_info()\r\n\t\t\tlines = traceback.format_exception(exc_type, exc_value, exc_traceback)\r\n\t\t\tprint(''.join('!! ' + line for line in lines))\r\n\t\t\tlogging.info('qbo.Write() method: '.join('!! ' + line for line in lines))\r\n\t\t\treturn False\r\n"},"license":{"kind":"string","value":"mit"},"hash":{"kind":"number","value":1675282766867628800,"string":"1,675,282,766,867,628,800"},"line_mean":{"kind":"number","value":31.1265822785,"string":"31.126582"},"line_max":{"kind":"number","value":155,"string":"155"},"alpha_frac":{"kind":"number","value":0.6032352567,"string":"0.603235"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.155546623794212,"string":"3.155547"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45169,"cells":{"repo_name":{"kind":"string","value":"berkerpeksag/pythondotorg"},"path":{"kind":"string","value":"pydotorg/settings/base.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"5943"},"content":{"kind":"string","value":"import os\nimport dj_database_url\n\n### Basic config\n\nBASE = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))\nDEBUG = TEMPLATE_DEBUG = True\nSITE_ID = 1\nSECRET_KEY = 'its-a-secret-to-everybody'\n\n# Until Sentry works on Py3, do errors the old-fashioned way.\nADMINS = []\n\n# General project information\n# These are available in the template as SITE_INFO.\nSITE_VARIABLES = {\n 'site_name': 'Python.org',\n 'site_descript': 'The official home of the Python Programming Language',\n}\n\n### Databases\n\nDATABASES = {\n 'default': dj_database_url.config(default='postgres:///python.org')\n}\n\n### Locale settings\n\nTIME_ZONE = 'UTC'\nLANGUAGE_CODE = 'en-us'\nUSE_I18N = True\nUSE_L10N = True\nUSE_TZ = True\n\nDATE_FORMAT = 'Y-m-d'\n\n### Files (media and static)\n\nMEDIA_ROOT = os.path.join(BASE, 'media')\nMEDIA_URL = '/m/'\n\n# Absolute path to the directory static files should be collected to.\n# Don't put anything in this directory yourself; store your static files\n# in apps' \"static/\" subdirectories and in STATICFILES_DIRS.\n# Example: \"/var/www/example.com/static/\"\nSTATIC_ROOT = os.path.join(BASE, 'static-root')\nSTATIC_URL = '/static/'\n\nSTATICFILES_DIRS = [\n os.path.join(BASE, 'static'),\n]\nSTATICFILES_STORAGE = 'pipeline.storage.PipelineStorage'\n\n\n### Authentication\n\nAUTHENTICATION_BACKENDS = (\n # Needed to login by username in Django admin, regardless of `allauth`\n \"django.contrib.auth.backends.ModelBackend\",\n\n # `allauth` specific authentication methods, such as login by e-mail\n \"allauth.account.auth_backends.AuthenticationBackend\",\n)\n\nLOGIN_REDIRECT_URL = 'home'\nACCOUNT_LOGOUT_REDIRECT_URL = 'home'\nACCOUNT_EMAIL_REQUIRED = True\nACCOUNT_UNIQUE_EMAIL = True\nACCOUNT_EMAIL_VERIFICATION = 'mandatory'\nSOCIALACCOUNT_EMAIL_REQUIRED = True\nSOCIALACCOUNT_EMAIL_VERIFICATION = True\nSOCIALACCOUNT_QUERY_EMAIL = True\n\n### Templates\n\nTEMPLATE_DIRS = [\n os.path.join(BASE, 'templates')\n]\n\nTEMPLATE_CONTEXT_PROCESSORS = [\n \"django.contrib.auth.context_processors.auth\",\n \"django.core.context_processors.debug\",\n \"django.core.context_processors.i18n\",\n \"django.core.context_processors.media\",\n \"django.core.context_processors.static\",\n \"django.core.context_processors.tz\",\n \"django.core.context_processors.request\",\n \"allauth.account.context_processors.account\",\n \"allauth.socialaccount.context_processors.socialaccount\",\n \"django.contrib.messages.context_processors.messages\",\n \"pydotorg.context_processors.site_info\",\n \"pydotorg.context_processors.url_name\",\n]\n\n### URLs, WSGI, middleware, etc.\n\nROOT_URLCONF = 'pydotorg.urls'\n\nMIDDLEWARE_CLASSES = (\n 'pydotorg.middleware.AdminNoCaching',\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n 'pages.middleware.PageFallbackMiddleware',\n 'django.contrib.redirects.middleware.RedirectFallbackMiddleware',\n)\n\nAUTH_USER_MODEL = 'users.User'\n\nWSGI_APPLICATION = 'pydotorg.wsgi.application'\n\n### Apps\n\nINSTALLED_APPS = [\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.redirects',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'django.contrib.comments',\n 'django.contrib.admin',\n 'django.contrib.admindocs',\n\n 'django_comments_xtd',\n 'jsonfield',\n 'pipeline',\n 'sitetree',\n 'timedelta',\n 'imagekit',\n 'haystack',\n 'honeypot',\n\n 'users',\n 'boxes',\n 'cms',\n 'companies',\n 'feedbacks',\n 'community',\n 'jobs',\n 'pages',\n 'sponsors',\n 'successstories',\n 'events',\n 'minutes',\n 'peps',\n 'blogs',\n 'downloads',\n 'codesamples',\n\n 'allauth',\n 'allauth.account',\n 'allauth.socialaccount',\n #'allauth.socialaccount.providers.facebook',\n #'allauth.socialaccount.providers.github',\n #'allauth.socialaccount.providers.openid',\n #'allauth.socialaccount.providers.twitter',\n\n # Tastypie needs the `users` app to be already loaded.\n 'tastypie',\n\n]\n\n# Fixtures\n\nFIXTURE_DIRS = (\n os.path.join(BASE, 'fixtures'),\n)\n\n### Testing\n\nSKIP_NETWORK_TESTS = True\n\n### Logging\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'filters': {\n 'require_debug_false': {\n '()': 'django.utils.log.RequireDebugFalse'\n }\n },\n 'handlers': {\n 'mail_admins': {\n 'level': 'ERROR',\n 'filters': ['require_debug_false'],\n 'class': 'django.utils.log.AdminEmailHandler'\n }\n },\n 'loggers': {\n 'django.request': {\n 'handlers': ['mail_admins'],\n 'level': 'ERROR',\n 'propagate': True,\n },\n }\n}\n\n### Development\nDEV_FIXTURE_URL = 'https://www.python.org/m/fixtures/dev-fixtures.json.gz'\n\n### Comments\n\nCOMMENTS_APP = 'django_comments_xtd'\nCOMMENTS_XTD_MAX_THREAD_LEVEL = 0\nCOMMENTS_XTD_FORM_CLASS = \"jobs.forms.JobCommentForm\"\n\n### Honeypot\nHONEYPOT_FIELD_NAME = 'email_body_text'\nHONEYPOT_VALUE = 'write your message'\n\n### Blog Feed URL\nPYTHON_BLOG_FEED_URL = \"http://feeds.feedburner.com/PythonInsider\"\nPYTHON_BLOG_URL = \"http://blog.python.org\"\n\n### Registration mailing lists\nMAILING_LIST_PSF_MEMBERS = \"psf-members-announce-request@python.org\"\n\n### PEP Repo Location\nPEP_REPO_PATH = ''\n\n### Fastly ###\nFASTLY_API_KEY = False # Set to Fastly API key in production to allow pages to\n # be purged on save\n\n# Jobs\nJOB_THRESHOLD_DAYS = 90\nJOB_FROM_EMAIL = 'jobs@python.org'\n\n### Pipeline\n\nfrom .pipeline import (\n PIPELINE_CSS, PIPELINE_JS,\n PIPELINE_COMPILERS,\n PIPELINE_SASS_BINARY, PIPELINE_SASS_ARGUMENTS,\n PIPELINE_CSS_COMPRESSOR, PIPELINE_JS_COMPRESSOR,\n)\n"},"license":{"kind":"string","value":"apache-2.0"},"hash":{"kind":"number","value":-7469629725360730000,"string":"-7,469,629,725,360,730,000"},"line_mean":{"kind":"number","value":23.5578512397,"string":"23.557851"},"line_max":{"kind":"number","value":79,"string":"79"},"alpha_frac":{"kind":"number","value":0.676930843,"string":"0.676931"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.3462837837837838,"string":"3.346284"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45170,"cells":{"repo_name":{"kind":"string","value":"stevegt/UltimakerUtils"},"path":{"kind":"string","value":"leveling-rings-UM1.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"2681"},"content":{"kind":"string","value":"#!/usr/bin/python\n\n# Derived from the UM2 version by an anonymous contributor...\n#\n# http://umforum.ultimaker.com/index.php?/topic/5951-um2-calibration-utility-leveling-ringsgcode/?p=54694\n#\n# ...who wisely says: \"I accept NO liability for any damage done by\n# using either version or any derivatives. USE AT YOUR OWN RISK.\" \n\nfilament_diameter = 2.89\nbuild_area_width = 205.0\nbuild_area_depth = 205.0\nrings = 10\nwide = 0.4\nthick = 0.2925 / 2\n\ntemperature = 230\nbed_temperature = 60\n\nbase_dia = 180\n\npi=3.1415927\n\ncenter_x = build_area_width/2.0\ncenter_y = build_area_depth/2.0\n\nfilament_area = (filament_diameter / 2) ** 2 * pi\n\nhead = '''\nM107 ;start with the fan off\nG21 ;metric values\nG90 ;absolute positioning\nM82 ;set extruder to absolute mode\nM107 ;start with the fan off\nG28 X0 Y0 ;move X/Y to min endstops\nG28 Z0 ;move Z to min endstops\nG1 Z15.0 F9000 ;move the platform down 15mm\nM140 S{bed_temperature:.2f} ;set bed temp (no wait)\nM109 T0 S{temperature:.2f} ;set extruder temp (wait)\nM190 S{bed_temperature:.2f} ;set bed temp (wait)\nG92 E0 ;zero the extruded length\nG1 F200 E3 ;extrude 3mm of feed stock\nG92 E0 ;zero the extruded length again\nG1 F9000 ;set speed to 9000\n;Put printing message on LCD screen\nM117 Printing...\n\n;Layer count: 1\n;LAYER:0\n'''\n\nloop = '''\nG0 F9000 X{x:.2f} Y{y:.2f} Z{z:.2f}\nG2 F1000 X{x:.2f} Y{y:.2f} I{r:.2f} E{total_mm3:.2f}'''\n\ntail = '''\n;End GCode\nM104 S0 ;extruder heater off\nM140 S0 ;heated bed heater off (if you have it)\nG91 ;relative positioning\nG1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure\nG1 Z+0.5 E-5 X-20 Y-20 F9000 ;move Z up a bit and retract filament even more\nG28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way\nM84 ;steppers off\nG90 ;absolute positioning'''\n\ntotal_mm3 = 0\n\nbody = ''\n\ncross_section = thick * wide\nz = thick\n\nfor i in range(rings):\n\tdia = base_dia - ((wide * 2) * i)\n\tcircumference = pi * dia \n\tr = dia/2.0;\n\tx = center_x - r\n\ty = center_y \n\tmm3 = (circumference * cross_section) / filament_area\n\ttotal_mm3 += mm3\n\tbody += loop.format(**vars())\n\nprint head.format(**vars())\nprint body\nprint tail.format(**vars())\n"},"license":{"kind":"string","value":"gpl-2.0"},"hash":{"kind":"number","value":5621385078935052000,"string":"5,621,385,078,935,052,000"},"line_mean":{"kind":"number","value":30.1744186047,"string":"30.174419"},"line_max":{"kind":"number","value":118,"string":"118"},"alpha_frac":{"kind":"number","value":0.5647146587,"string":"0.564715"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.099421965317919,"string":"3.099422"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45171,"cells":{"repo_name":{"kind":"string","value":"udapi/udapi-python"},"path":{"kind":"string","value":"udapi/block/ud/complywithtext.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"11648"},"content":{"kind":"string","value":"r\"\"\"Block ComplyWithText for adapting the nodes to comply with the text.\n\nImplementation design details:\nUsually, most of the inconsistencies between tree tokens and the raw text are simple to solve.\nHowever, there may be also rare cases when it is not clear how to align the tokens\n(nodes in the tree) with the raw text (stored in ``root.text``).\nThis block tries to solve the general case using several heuristics.\n\nIt starts with running a LCS-like algorithm (LCS = longest common subsequence)\n``difflib.SequenceMatcher`` on the raw text and concatenation of tokens' forms,\ni.e. on sequences of characters (as opposed to running LCS on sequences of tokens).\n\nTo prevent mis-alignment problems, we keep the spaces present in the raw text\nand we insert spaces into the concatenated forms (``tree_chars``) according to ``SpaceAfter=No``.\nAn example of a mis-alignment problem:\ntext \"énfase na necesidade\" with 4 nodes \"énfase en a necesidade\"\nshould be solved by adding multiword token \"na\" over the nodes \"en\" and \"a\".\nHowever, running LCS (or difflib) over the character sequences\n\"énfaseenanecesidade\"\n\"énfasenanecesidade\"\nmay result in énfase -> énfas.\n\nAuthor: Martin Popel\n\"\"\"\nimport difflib\nimport logging\nimport re\n\nfrom udapi.core.block import Block\nfrom udapi.core.mwt import MWT\n\n\nclass ComplyWithText(Block):\n \"\"\"Adapt the nodes to comply with the text.\"\"\"\n\n def __init__(self, fix_text=True, prefer_mwt=True, allow_goeswith=True, max_mwt_length=4,\n **kwargs):\n \"\"\"Args:\n fix_text: After all heuristics are applied, the token forms may still not match the text.\n Should we edit the text to match the token forms (as a last resort)? Default=True.\n prefer_mwt - What to do if multiple subsequent nodes correspond to a text written\n without spaces and non-word characters (punctuation)?\n E.g. if \"3pm doesn't\" is annotated with four nodes \"3 pm does n't\".\n We can use either SpaceAfter=No, or create a multi-word token (MWT).\n Note that if there is space or punctuation, SpaceAfter=No will be used always\n (e.g. \"3 p.m.\" annotated with three nodes \"3 p. m.\").\n If the character sequence does not match exactly, MWT will be used always\n (e.g. \"3pm doesn't\" annotated with four nodes \"3 p.m. does not\").\n Thus this parameter influences only the \"unclear\" cases.\n Default=True (i.e. prefer multi-word tokens over SpaceAfter=No).\n allow_goeswith - If a node corresponds to multiple space-separated strings in text,\n which are not allowed as tokens with space, we can either leave this diff\n unresolved or create new nodes and join them with the `goeswith` deprel.\n Default=True (i.e. add the goeswith nodes if applicable).\n max_mwt_length - Maximum length of newly created multi-word tokens (in syntactic words).\n Default=4.\n \"\"\"\n super().__init__(**kwargs)\n self.fix_text = fix_text\n self.prefer_mwt = prefer_mwt\n self.allow_goeswith = allow_goeswith\n self.max_mwt_length = max_mwt_length\n\n @staticmethod\n def allow_space(form):\n \"\"\"Is space allowed within this token form?\"\"\"\n return re.fullmatch('[0-9 ]+([,.][0-9]+)?', form)\n\n @staticmethod\n def store_orig_form(node, new_form):\n \"\"\"Store the original form of this node into MISC, unless the change is common&expected.\"\"\"\n _ = new_form\n if node.form not in (\"''\", \"``\"):\n node.misc['OrigForm'] = node.form\n\n def process_tree(self, root):\n text = root.text\n if text is None:\n raise ValueError('Tree %s has no text, cannot use ud.ComplyWithText' % root)\n\n # Normalize the stored text (double space -> single space)\n # and skip sentences which are already ok.\n text = ' '.join(text.split())\n if text == root.compute_text():\n return\n\n tree_chars, char_nodes = _nodes_to_chars(root.token_descendants)\n\n # Align. difflib may not give LCS, but usually it is good enough.\n matcher = difflib.SequenceMatcher(None, tree_chars, text, autojunk=False)\n diffs = list(matcher.get_opcodes())\n _log_diffs(diffs, tree_chars, text, 'matcher')\n\n diffs = self.unspace_diffs(diffs, tree_chars, text)\n _log_diffs(diffs, tree_chars, text, 'unspace')\n\n diffs = self.merge_diffs(diffs, char_nodes)\n _log_diffs(diffs, tree_chars, text, 'merge')\n\n # Solve diffs.\n self.solve_diffs(diffs, tree_chars, char_nodes, text)\n\n # Fill SpaceAfter=No.\n tmp_text = text\n for node in root.token_descendants:\n if tmp_text.startswith(node.form):\n tmp_text = tmp_text[len(node.form):]\n if not tmp_text or tmp_text[0].isspace():\n del node.misc['SpaceAfter']\n tmp_text = tmp_text.lstrip()\n else:\n node.misc['SpaceAfter'] = 'No'\n else:\n logging.warning('Node %s does not match text \"%s\"', node, tmp_text[:20])\n return\n\n # Edit root.text if needed.\n if self.fix_text:\n computed_text = root.compute_text()\n if text != computed_text:\n root.add_comment('ToDoOrigText = ' + root.text)\n root.text = computed_text\n\n def unspace_diffs(self, orig_diffs, tree_chars, text):\n diffs = []\n for diff in orig_diffs:\n edit, tree_lo, tree_hi, text_lo, text_hi = diff\n if edit != 'insert':\n if tree_chars[tree_lo] == ' ':\n tree_lo += 1\n if tree_chars[tree_hi - 1] == ' ':\n tree_hi -= 1\n old = tree_chars[tree_lo:tree_hi]\n new = text[text_lo:text_hi]\n if old == '' and new == '':\n continue\n elif old == new:\n edit = 'equal'\n elif old == '':\n edit = 'insert'\n diffs.append((edit, tree_lo, tree_hi, text_lo, text_hi))\n return diffs\n\n def merge_diffs(self, orig_diffs, char_nodes):\n \"\"\"Make sure each diff starts on original token boundary.\n\n If not, merge the diff with the previous diff.\n E.g. (equal, \"5\", \"5\"), (replace, \"-6\", \"–7\")\n is changed into (replace, \"5-6\", \"5–7\")\n \"\"\"\n diffs = []\n for diff in orig_diffs:\n edit, tree_lo, tree_hi, text_lo, text_hi = diff\n if edit != 'insert' and char_nodes[tree_lo] is not None:\n diffs.append(diff)\n elif edit == 'equal':\n while tree_lo < tree_hi and char_nodes[tree_lo] is None:\n tree_lo += 1\n text_lo += 1\n diffs[-1] = ('replace', diffs[-1][1], tree_lo, diffs[-1][3], text_lo)\n if tree_lo < tree_hi:\n diffs.append(('equal', tree_lo, tree_hi, text_lo, text_hi))\n else:\n if not diffs:\n diffs = [diff]\n elif diffs[-1][0] != 'equal':\n diffs[-1] = ('replace', diffs[-1][1], tree_hi, diffs[-1][3], text_hi)\n else:\n p_tree_hi = diffs[-1][2] - 1\n p_text_hi = diffs[-1][4] - 1\n while char_nodes[p_tree_hi] is None:\n p_tree_hi -= 1\n p_text_hi -= 1\n assert p_tree_hi >= diffs[-1][1]\n assert p_text_hi >= diffs[-1][3]\n diffs[-1] = ('equal', diffs[-1][1], p_tree_hi, diffs[-1][3], p_text_hi)\n diffs.append(('replace', p_tree_hi, tree_hi, p_text_hi, text_hi))\n return diffs\n\n def solve_diffs(self, diffs, tree_chars, char_nodes, text):\n for diff in diffs:\n edit, tree_lo, tree_hi, text_lo, text_hi = diff\n\n # Focus only on edits of type 'replace', log insertions and deletions as failures.\n if edit == 'equal':\n continue\n if edit in ('insert', 'delete'):\n logging.warning('Unable to solve token-vs-text mismatch\\n%s',\n _diff2str(diff, tree_chars, text))\n continue\n\n # Revert the splittng and solve the diff.\n nodes = [n for n in char_nodes[tree_lo:tree_hi] if n is not None]\n form = text[text_lo:text_hi]\n self.solve_diff(nodes, form.strip())\n\n def solve_diff(self, nodes, form):\n \"\"\"Fix a given (minimal) tokens-vs-text inconsistency.\"\"\"\n nodes_str = ' '.join([n.form for n in nodes]) # just for debugging\n node = nodes[0]\n\n # First, solve the cases when the text contains a space.\n if ' ' in form:\n if len(nodes) == 1 and node.form == form.replace(' ', ''):\n if self.allow_space(form):\n self.store_orig_form(node, form)\n node.form = form\n elif self.allow_goeswith:\n forms = form.split()\n node.form = forms[0]\n for split_form in reversed(forms[1:]):\n new = node.create_child(form=split_form, deprel='goeswith', upos=node.upos)\n new.shift_after_node(node)\n else:\n logging.warning('Unable to solve 1:m diff:\\n%s -> %s', nodes_str, form)\n else:\n logging.warning('Unable to solve n:m diff:\\n%s -> %s', nodes_str, form)\n\n # Second, solve the cases when multiple nodes match one form (without any spaces).\n elif len(nodes) > 1:\n # If the match is exact, we can choose between MWT ans SpaceAfter solutions.\n if not self.prefer_mwt and ''.join([n.form for n in nodes]) == form:\n pass # SpaceAfter=No will be added later on.\n # If one of the nodes is already a MWT, we cannot have nested MWTs.\n # TODO: enlarge the MWT instead of failing.\n elif any(isinstance(n, MWT) for n in nodes):\n logging.warning('Unable to solve partial-MWT diff:\\n%s -> %s', nodes_str, form)\n # MWT with too many words are suspicious.\n elif len(nodes) > self.max_mwt_length:\n logging.warning('Not creating too long (%d>%d) MWT:\\n%s -> %s',\n len(nodes), self.max_mwt_length, nodes_str, form)\n # Otherwise, create a new MWT.\n else:\n node.root.create_multiword_token(nodes, form)\n\n # Third, solve the 1-1 cases.\n else:\n self.store_orig_form(node, form)\n node.form = form\n\n\ndef _nodes_to_chars(nodes):\n chars, char_nodes = [], []\n for node in nodes:\n form = node.form\n if node.misc['SpaceAfter'] != 'No' and node != nodes[-1]:\n form += ' '\n chars.extend(form)\n char_nodes.append(node)\n char_nodes.extend([None] * (len(form) - 1))\n return ''.join(chars), char_nodes\n\n\ndef _log_diffs(diffs, tree_chars, text, msg):\n if logging.getLogger().isEnabledFor(logging.DEBUG):\n logging.warning('=== After %s:', msg)\n for diff in diffs:\n logging.warning(_diff2str(diff, tree_chars, text))\n\n\ndef _diff2str(diff, tree, text):\n old = '|' + ''.join(tree[diff[1]:diff[2]]) + '|'\n new = '|' + ''.join(text[diff[3]:diff[4]]) + '|'\n if diff[0] == 'equal':\n return '{:7} {!s:>50}'.format(diff[0], old)\n return '{:7} {!s:>50} --> {!s}'.format(diff[0], old, new)\n"},"license":{"kind":"string","value":"gpl-3.0"},"hash":{"kind":"number","value":6423815890427901000,"string":"6,423,815,890,427,901,000"},"line_mean":{"kind":"number","value":42.7518796992,"string":"42.75188"},"line_max":{"kind":"number","value":99,"string":"99"},"alpha_frac":{"kind":"number","value":0.5591166867,"string":"0.559117"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.7896450667535007,"string":"3.789645"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45172,"cells":{"repo_name":{"kind":"string","value":"storiesofsolidarity/story-database"},"path":{"kind":"string","value":"stories/admin.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"1393"},"content":{"kind":"string","value":"from django.contrib import admin\nfrom models import Location, Story\nfrom people.models import Author\n\n\nclass LocationAdmin(admin.ModelAdmin):\n list_display = ('zipcode', 'city_fmt', 'county_fmt', 'state_fmt', 'story_count')\n list_filter = ('state',)\n search_fields = ('zipcode', 'city', 'county')\n\nadmin.site.register(Location, LocationAdmin)\n\n\nclass EmployerFilter(admin.SimpleListFilter):\n title = 'author employer'\n parameter_name = 'employer'\n\n def lookups(self, request, model_admin):\n employer_set = set()\n for a in Author.objects.all():\n if a.employer:\n employer_set.add(a.employer.split(' ', 1)[0])\n return [(str(c), str(c)) for c in employer_set if c]\n\n def queryset(self, request, queryset):\n if self.value() or self.value() == 'None':\n return queryset.filter(author__employer__startswith=self.value())\n else:\n return queryset\n\n\nclass StoryAdmin(admin.ModelAdmin):\n list_display = ('excerpt', 'author_display', 'employer', 'anonymous', 'created_at')\n list_filter = (EmployerFilter, 'location__state', 'truncated')\n date_hierarchy = 'created_at'\n readonly_fields = ('truncated',)\n raw_id_fields = ('author', 'location')\n search_fields = ('location__city', 'author__user__first_name', 'author__user__last_name', 'content')\n\nadmin.site.register(Story, StoryAdmin)\n"},"license":{"kind":"string","value":"agpl-3.0"},"hash":{"kind":"number","value":-544278433607546560,"string":"-544,278,433,607,546,560"},"line_mean":{"kind":"number","value":33.825,"string":"33.825"},"line_max":{"kind":"number","value":104,"string":"104"},"alpha_frac":{"kind":"number","value":0.6489590811,"string":"0.648959"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.491228070175439,"string":"3.491228"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45173,"cells":{"repo_name":{"kind":"string","value":"peppelinux/inventario_verdebinario"},"path":{"kind":"string","value":"museo/models.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"4183"},"content":{"kind":"string","value":"from django.db import models\nfrom photologue.models import ImageModel\nfrom django.core.urlresolvers import reverse\nfrom django.utils.translation import ugettext_lazy as _\n\n\nclass Produttore(ImageModel):\n id_tabella = models.AutoField(primary_key=True)\n nome = models.CharField(max_length=135, blank=True)\n nome_abbreviato = models.CharField(max_length=135, blank=True)\n #slug = models.SlugField(unique=True, help_text=('\"slug\": un identificatore automatico e univoco'))\n descrizione = models.TextField(max_length=1024, blank=True)\n data_nascita = models.DateField(null=True, blank=True)\n data_chiusura = models.DateField(null=True, blank=True)\n #immagine_logo = models.ImageField(upload_to=\"LoghiProduttori\", blank=True)\n url = models.CharField(max_length=256, blank=True)\n\n def save(self, *args, **kwargs):\n if self.nome_abbreviato == None or self.nome_abbreviato.split() == []:\n self.nome_abbreviato = self.nome.upper()\n super(self.__class__, self).save(*args, **kwargs) # Call the \"real\" save() method.\n\n class Meta:\n ordering = ['nome']\n db_table = 'produttore'\n verbose_name_plural = \"Produttore\"\n\n# def get_absolute_url(self):\n# return '%s' % (self.url)\n\n def __str__(self):\n return '%s' % (self.nome_abbreviato)\n\n\nclass SchedaTecnica(models.Model):\n id_tabella = models.AutoField(primary_key=True)\n modello = models.CharField(max_length=135, blank=True)\n produttore = models.ForeignKey(Produttore, null=True, blank=True, on_delete=models.SET_NULL)\n paese_di_origine = models.CharField(max_length=135, blank=True)\n anno = models.CharField(max_length=135, blank=True)\n tastiera = models.CharField(max_length=135, blank=True)\n cpu = models.CharField(max_length=135, blank=True)\n velocita = models.CharField(max_length=135, blank=True)\n memoria_volatile = models.CharField(max_length=135, blank=True)\n memoria_di_massa = models.CharField(max_length=135, blank=True)\n modalita_grafica = models.CharField(max_length=135, blank=True)\n audio = models.CharField(max_length=135, blank=True)\n dispositivi_media = models.CharField(max_length=135, blank=True)\n alimentazione = models.CharField(max_length=135, blank=True)\n prezzo = models.CharField(max_length=135, blank=True)\n descrizione = models.TextField(max_length=1024, blank=True)\n data_inserimento = models.DateField(null=True, blank=False, auto_now_add=True)\n\n class Meta:\n db_table = 'scheda_tecnica'\n verbose_name_plural = \"Scheda Tecnica\"\n\n\nclass FotoHardwareMuseo(ImageModel):\n id_tabella = models.AutoField(primary_key=True)\n #immagine = models.ImageField(upload_to=\"FotoHardwareMuseo/%d.%m.%Y\", blank=True)\n etichetta_verde = models.CharField(max_length=135, blank=True)\n data_inserimento = models.DateField(null=True, blank=False, auto_now_add=True)\n seriale = models.CharField(max_length=384, blank=True)\n didascalia = models.TextField(max_length=328, blank=True)\n scheda_tecnica = models.ForeignKey(SchedaTecnica, null=True, blank=True, on_delete=models.SET_NULL)\n\n class Meta:\n db_table = 'foto_hardware_museo'\n verbose_name_plural = \"Foto Hardware Museo\"\n\n def __str__(self):\n return '%s %s' % (self.seriale, self.scheda_tecnica)\n\n def get_absolute_url(self):\n #return '/media/foto/FotoHardwareMuseo/' + self.data_inserimento.strftime('%d.%m.%Y') + '/' + self.image.name\n return '/media/%s' % self.image.name\n\n def admin_thumbnail(self):\n func = getattr(self, 'get_admin_thumbnail_url', None)\n if func is None:\n return _('An \"admin_thumbnail\" photo size has not been defined.')\n else:\n if hasattr(self, 'get_absolute_url'):\n return '<a class=\"foto_admin_thumbs\" target=\"_blank\" href=\"%s\"><img src=\"%s\"></a>' % \\\n (self.get_absolute_url(), func())\n else:\n return '<a class=\"foto_admin_thumbs\" target=\"_blank\" href=\"%s\"><img src=\"%s\"></a>' % \\\n (self.image.url, func())\n admin_thumbnail.short_description = _('Thumbnail')\n admin_thumbnail.allow_tags = True\n"},"license":{"kind":"string","value":"gpl-3.0"},"hash":{"kind":"number","value":3234902780985170000,"string":"3,234,902,780,985,170,000"},"line_mean":{"kind":"number","value":44.967032967,"string":"44.967033"},"line_max":{"kind":"number","value":117,"string":"117"},"alpha_frac":{"kind":"number","value":0.6715276118,"string":"0.671528"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.2201693610469593,"string":"3.220169"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45174,"cells":{"repo_name":{"kind":"string","value":"XtheOne/Inverter-Data-Logger"},"path":{"kind":"string","value":"InverterLib.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"3301"},"content":{"kind":"string","value":"import socket\nimport struct\nimport os\nimport binascii\nimport sys\n\nif sys.version[0] == '2':\n reload(sys)\n sys.setdefaultencoding('cp437')\n\ndef getNetworkIp():\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)\n s.connect(('<broadcast>', 0))\n return s.getsockname()[0]\n\ndef createV4RequestFrame(logger_sn):\n \"\"\"Create request frame for inverter logger.\n\n The request string is build from several parts. The first part is a\n fixed 4 char string; the second part is the reversed hex notation of\n the s/n twice; then again a fixed string of two chars; a checksum of\n the double s/n with an offset; and finally a fixed ending char.\n\n Args:\n logger_sn (int): Serial number of the inverter\n\n Returns:\n str: Information request string for inverter\n \"\"\"\n #frame = (headCode) + (dataFieldLength) + (contrlCode) + (sn) + (sn) + (command) + (checksum) + (endCode)\n frame_hdr = binascii.unhexlify('680241b1') #from SolarMan / new Omnik app\n command = binascii.unhexlify('0100')\n defchk = binascii.unhexlify('87')\n endCode = binascii.unhexlify('16')\n\n tar = bytearray.fromhex(hex(logger_sn)[8:10] + hex(logger_sn)[6:8] + hex(logger_sn)[4:6] + hex(logger_sn)[2:4])\n frame = bytearray(frame_hdr + tar + tar + command + defchk + endCode)\n\n checksum = 0\n frame_bytes = bytearray(frame)\n for i in range(1, len(frame_bytes) - 2, 1):\n checksum += frame_bytes[i] & 255\n frame_bytes[len(frame_bytes) - 2] = int((checksum & 255))\n return bytearray(frame_bytes)\n\ndef expand_path(path):\n \"\"\"\n Expand relative path to absolute path.\n\n Args:\n path: file path\n\n Returns: absolute path to file\n\n \"\"\"\n if os.path.isabs(path):\n return path\n else:\n return os.path.dirname(os.path.abspath(__file__)) + \"/\" + path\n\ndef getLoggers():\n # Create the datagram socket\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n sock.bind((getNetworkIp(), 48899))\n # Set a timeout so the socket does not block indefinitely when trying to receive data.\n sock.settimeout(3)\n # Set the time-to-live for messages to 1 so they do not go past the local network segment.\n ttl = struct.pack('b', 1)\n sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl)\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)\n SendData = \"WIFIKIT-214028-READ\" # Lotto/TM = \"AT+YZAPP=214028,READ\"\n\n gateways = ''\n try:\n # Send data to the broadcast address\n sent = sock.sendto(SendData, ('<broadcast>', 48899))\n # Look for responses from all recipients\n while True:\n try:\n data, server = sock.recvfrom(1024)\n except socket.timeout:\n break\n else:\n if (data == SendData): continue #skip sent data\n a = data.split(',')\n wifi_ip, wifi_mac, wifi_sn = a[0],a[1],a[2]\n if (len(gateways)>1):\n gateways = gateways+','\n gateways = gateways+wifi_ip+','+wifi_sn\n\n finally:\n sock.close()\n return gateways\n"},"license":{"kind":"string","value":"gpl-3.0"},"hash":{"kind":"number","value":8714258900020281000,"string":"8,714,258,900,020,281,000"},"line_mean":{"kind":"number","value":33.3854166667,"string":"33.385417"},"line_max":{"kind":"number","value":115,"string":"115"},"alpha_frac":{"kind":"number","value":0.6267797637,"string":"0.62678"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.5456498388829214,"string":"3.54565"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45175,"cells":{"repo_name":{"kind":"string","value":"jiaojianbupt/tools"},"path":{"kind":"string","value":"project_manager/alias.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"1746"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated by jiaojian at 2018/6/29 16:30\n\"\"\"\nimport os\nimport sys\nimport termios\nfrom tools.utils.basic_printer import print_with_style, ConsoleColor\nHOME = os.environ['HOME']\n\n\ndef get_input():\n fd = sys.stdin.fileno()\n old_tty_info = termios.tcgetattr(fd)\n new_tty_info = old_tty_info[:]\n new_tty_info[3] &= ~termios.ICANON\n new_tty_info[3] &= ~termios.ECHO\n termios.tcsetattr(fd, termios.TCSANOW, new_tty_info)\n answer = os.read(fd, 1)\n termios.tcsetattr(fd, termios.TCSANOW, old_tty_info)\n return answer\n\n\ndef add_alias():\n if sys.platform == 'darwin':\n bash_profile_name = '.bash_profile'\n else:\n bash_profile_name = '.bashrc'\n linux_bash_profile_path = os.path.join(HOME, bash_profile_name)\n exec_file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'main.py')\n alias = 'alias updateall=\"python %s\"' % exec_file_path\n if os.path.exists(linux_bash_profile_path):\n with open(linux_bash_profile_path, 'rw') as bashrc_file:\n bash_profile = bashrc_file.read()\n if bash_profile.find(alias) >= 0:\n return\n answer = ''\n while not answer or answer not in {'y', 'n'}:\n print_with_style('Add \\'%s\\' to your %s?(y/n)' % (alias, bash_profile_name), color=ConsoleColor.YELLOW)\n answer = get_input()\n if answer == 'n':\n return\n elif answer == 'y':\n break\n bash_profile = bash_profile + '\\n' + alias\n with open(linux_bash_profile_path, 'w') as bashrc_file:\n bashrc_file.write(bash_profile)\n print_with_style('Alias added.', color=ConsoleColor.YELLOW)\n"},"license":{"kind":"string","value":"gpl-3.0"},"hash":{"kind":"number","value":-6002306353356231,"string":"-6,002,306,353,356,231"},"line_mean":{"kind":"number","value":35.375,"string":"35.375"},"line_max":{"kind":"number","value":119,"string":"119"},"alpha_frac":{"kind":"number","value":0.5870561283,"string":"0.587056"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.33206106870229,"string":"3.332061"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45176,"cells":{"repo_name":{"kind":"string","value":"dapengchen123/code_v1"},"path":{"kind":"string","value":"reid/datasets/market1501.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"3563"},"content":{"kind":"string","value":"from __future__ import print_function, absolute_import\nimport os.path as osp\n\nfrom ..utils.data import Dataset\nfrom ..utils.osutils import mkdir_if_missing\nfrom ..utils.serialization import write_json\n\n\nclass Market1501(Dataset):\n url = 'https://drive.google.com/file/d/0B8-rUzbwVRk0c054eEozWG9COHM/view'\n md5 = '65005ab7d12ec1c44de4eeafe813e68a'\n\n def __init__(self, root, split_id=0, num_val=0.3, download=False):\n super(Market1501, self).__init__(root, split_id=split_id)\n\n if download:\n self.download()\n\n if not self._check_integrity():\n raise RuntimeError(\"Dataset not found or corrupted. \" +\n \"You can use download=True to download it.\")\n\n self.load(num_val)\n\n def download(self):\n if self._check_integrity():\n print(\"Files already downloaded and verified\")\n return\n\n import re\n import hashlib\n import shutil\n from glob import glob\n from zipfile import ZipFile\n\n raw_dir = osp.join(self.root, 'raw')\n mkdir_if_missing(raw_dir)\n\n # Download the raw zip file\n fpath = osp.join(raw_dir, 'Market-1501-v15.09.15.zip')\n if osp.isfile(fpath) and \\\n hashlib.md5(open(fpath, 'rb').read()).hexdigest() == self.md5:\n print(\"Using downloaded file: \" + fpath)\n else:\n raise RuntimeError(\"Please download the dataset manually from {} \"\n \"to {}\".format(self.url, fpath))\n\n # Extract the file\n exdir = osp.join(raw_dir, 'Market-1501-v15.09.15')\n if not osp.isdir(exdir):\n print(\"Extracting zip file\")\n with ZipFile(fpath) as z:\n z.extractall(path=raw_dir)\n\n # Format\n images_dir = osp.join(self.root, 'images')\n mkdir_if_missing(images_dir)\n\n # 1501 identities (+1 for background) with 6 camera views each\n identities = [[[] for _ in range(6)] for _ in range(1502)]\n\n def register(subdir, pattern=re.compile(r'([-\\d]+)_c(\\d)')):\n fpaths = sorted(glob(osp.join(exdir, subdir, '*.jpg')))\n pids = set()\n for fpath in fpaths:\n fname = osp.basename(fpath)\n pid, cam = map(int, pattern.search(fname).groups())\n if pid == -1: continue # junk images are just ignored\n assert 0 <= pid <= 1501 # pid == 0 means background\n assert 1 <= cam <= 6\n cam -= 1\n pids.add(pid)\n fname = ('{:08d}_{:02d}_{:04d}.jpg'\n .format(pid, cam, len(identities[pid][cam])))\n identities[pid][cam].append(fname)\n shutil.copy(fpath, osp.join(images_dir, fname))\n return pids\n\n trainval_pids = register('bounding_box_train')\n gallery_pids = register('bounding_box_test')\n query_pids = register('query')\n assert query_pids <= gallery_pids\n assert trainval_pids.isdisjoint(gallery_pids)\n\n # Save meta information into a json file\n meta = {'name': 'Market1501', 'shot': 'multiple', 'num_cameras': 6,\n 'identities': identities}\n write_json(meta, osp.join(self.root, 'meta.json'))\n\n # Save the only training / test split\n splits = [{\n 'trainval': sorted(list(trainval_pids)),\n 'query': sorted(list(query_pids)),\n 'gallery': sorted(list(gallery_pids))}]\n write_json(splits, osp.join(self.root, 'splits.json'))\n"},"license":{"kind":"string","value":"mit"},"hash":{"kind":"number","value":-2535048846858501600,"string":"-2,535,048,846,858,501,600"},"line_mean":{"kind":"number","value":36.5052631579,"string":"36.505263"},"line_max":{"kind":"number","value":78,"string":"78"},"alpha_frac":{"kind":"number","value":0.5616053887,"string":"0.561605"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.7823779193205946,"string":"3.782378"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45177,"cells":{"repo_name":{"kind":"string","value":"glenflet/ZtoRGBpy"},"path":{"kind":"string","value":"ZtoRGBpy/_info.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"2082"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\n# =================================================================================\n# Copyright 2019 Glen Fletcher <mail@glenfletcher.com>\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# All documentation this file as docstrings or comments are licensed under the\n# Creative Commons Attribution-ShareAlike 4.0 International License; you may\n# not use this documentation except in compliance with this License.\n# You may obtain a copy of this License at\n#\n# https://creativecommons.org/licenses/by-sa/4.0\n#\n# =================================================================================\n\"\"\"\nZtoRGB information definition module\n\nSpecial private module used for automatic processing, and inclusion\n\n.. moduleauthor:: Glen Fletcher <mail@glenfletcher.com>\n\"\"\"\n\n__authors__ = [\n (\"Glen Fletcher\", \"mail@glenfletcher.com\")]\n__copyright__ = \"2019 Glen Fletcher\"\n__license__ = \"\"\"\\\nThe source code for this package is licensed under the [Apache 2.0 License](http://www.apache.org/licenses/LICENSE-2.0),\nwhile the documentation including docstrings and comments embedded in the source code are licensed under the\n[Creative Commons Attribution-ShareAlike 4.0 International License](https://creativecommons.org/licenses/by-sa/4.0)\n\"\"\"\n__contact__ = \"Glen Fletcher <mail@glenfletcher.com>\"\n__version__ = \"2.0\"\n__title__ = \"ZtoRGBpy\"\n__desc__ = \"\"\"\\\nComplex number to perceptually uniform RGB subset mapping library\"\"\"\n\n__all__ = [\n '__authors__', '__copyright__', '__license__',\n '__contact__', '__version__', '__title__',\n '__desc__']\n"},"license":{"kind":"string","value":"mit"},"hash":{"kind":"number","value":-2552345746239531500,"string":"-2,552,345,746,239,531,500"},"line_mean":{"kind":"number","value":40.64,"string":"40.64"},"line_max":{"kind":"number","value":120,"string":"120"},"alpha_frac":{"kind":"number","value":0.6623439001,"string":"0.662344"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.869888475836431,"string":"3.869888"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45178,"cells":{"repo_name":{"kind":"string","value":"ElecProg/decmath"},"path":{"kind":"string","value":"decmath/trig.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"4598"},"content":{"kind":"string","value":"from decimal import getcontext, Decimal\nfrom decmath import _pi, _to_Decimal, sign\n\n# Trigonometric functions\n\n\ndef acos(x):\n \"\"\"Return the arc cosine (measured in radians) of x.\"\"\"\n x = _to_Decimal(x)\n\n if x.is_nan():\n return Decimal(\"NaN\")\n elif abs(x) > 1:\n raise ValueError(\"Domain error: acos accepts -1 <= x <= 1.\")\n elif x == -1:\n return _pi()\n elif x == 0:\n return _pi() / 2\n elif x == 1:\n return Decimal(0)\n\n getcontext().prec += 2\n one_half = Decimal('0.5')\n i, lasts, s, gamma, fact, num = Decimal(0), 0, _pi() / 2 - x, 1, 1, x\n while s != lasts:\n lasts = s\n i += 1\n fact *= i\n num *= x * x\n gamma *= i - one_half\n coeff = gamma / ((2 * i + 1) * fact)\n s -= coeff * num\n getcontext().prec -= 2\n return +s\n\n\ndef asin(x):\n \"\"\"Return the arc sine (measured in radians) of x.\"\"\"\n x = _to_Decimal(x)\n\n if x.is_nan():\n return Decimal(\"NaN\")\n elif abs(x) > 1:\n raise ValueError(\"Domain error: asin accepts -1 <= x <= 1.\")\n elif x == -1:\n return -_pi() / 2\n elif x == 0:\n return Decimal(0)\n elif x == 1:\n return _pi() / 2\n\n getcontext().prec += 2\n one_half = Decimal('0.5')\n i, lasts, s, gamma, fact, num = Decimal(0), 0, x, 1, 1, x\n while s != lasts:\n lasts = s\n i += 1\n fact *= i\n num *= x * x\n gamma *= i - one_half\n coeff = gamma / ((2 * i + 1) * fact)\n s += coeff * num\n getcontext().prec -= 2\n return +s\n\n\ndef atan(x):\n \"\"\"Return the arc tangent (measured in radians) of x.\"\"\"\n x = _to_Decimal(x)\n\n if x.is_nan():\n return Decimal(\"NaN\")\n elif x == Decimal('-Inf'):\n return -_pi() / 2\n elif x == 0:\n return Decimal(0)\n elif x == Decimal('Inf'):\n return _pi() / 2\n\n if x < -1:\n c = _pi() / -2\n x = 1 / x\n elif x > 1:\n c = _pi() / 2\n x = 1 / x\n else:\n c = 0\n\n getcontext().prec += 2\n x_squared = x**2\n y = x_squared / (1 + x_squared)\n y_over_x = y / x\n i, lasts, s, coeff, num = Decimal(0), 0, y_over_x, 1, y_over_x\n while s != lasts:\n lasts = s\n i += 2\n coeff *= i / (i + 1)\n num *= y\n s += coeff * num\n if c:\n s = c - s\n getcontext().prec -= 2\n return +s\n\n\ndef atan2(y, x):\n \"\"\"Return the arc tangent (measured in radians) of y/x.\n Unlike atan(y/x), the signs of both x and y are considered.\"\"\"\n y = _to_Decimal(y)\n x = _to_Decimal(x)\n abs_y = abs(y)\n abs_x = abs(x)\n y_is_real = abs_y != Decimal('Inf')\n\n if y.is_nan() or x.is_nan():\n return Decimal(\"NaN\")\n\n if x:\n if y_is_real:\n a = y and atan(y / x) or Decimal(0)\n if x < 0:\n a += sign(y) * _pi()\n return a\n elif abs_y == abs_x:\n x = sign(x)\n y = sign(y)\n return _pi() * (Decimal(2) * abs(x) - x) / (Decimal(4) * y)\n if y:\n return atan(sign(y) * Decimal('Inf'))\n elif sign(x) < 0:\n return sign(y) * _pi()\n else:\n return sign(y) * Decimal(0)\n\n\ndef cos(x):\n \"\"\"Return the cosine of x as measured in radians.\"\"\"\n x = _to_Decimal(x) % (2 * _pi())\n\n if x.is_nan():\n return Decimal('NaN')\n elif x == _pi() / 2 or x == 3 * _pi() / 2:\n return Decimal(0)\n\n getcontext().prec += 2\n i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1\n while s != lasts:\n lasts = s\n i += 2\n fact *= i * (i - 1)\n num *= x * x\n sign *= -1\n s += num / fact * sign\n getcontext().prec -= 2\n return +s\n\n\ndef hypot(x, y):\n \"\"\"Return the Euclidean distance, sqrt(x*x + y*y).\"\"\"\n return (_to_Decimal(x).__pow__(2) + _to_Decimal(y).__pow__(2)).sqrt()\n\n\ndef sin(x):\n \"\"\"Return the sine of x as measured in radians.\"\"\"\n x = _to_Decimal(x) % (2 * _pi())\n\n if x.is_nan():\n return Decimal('NaN')\n elif x == 0 or x == _pi():\n return Decimal(0)\n\n getcontext().prec += 2\n i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1\n while s != lasts:\n lasts = s\n i += 2\n fact *= i * (i - 1)\n num *= x * x\n sign *= -1\n s += num / fact * sign\n getcontext().prec -= 2\n return +s\n\n\ndef tan(x):\n \"\"\"Return the tangent of x (measured in radians).\"\"\"\n x = _to_Decimal(x)\n\n if x.is_nan():\n return Decimal('NaN')\n elif x == _pi() / 2:\n return Decimal('Inf')\n elif x == 3 * _pi() / 2:\n return Decimal('-Inf')\n return sin(x) / cos(x)\n"},"license":{"kind":"string","value":"mit"},"hash":{"kind":"number","value":-8599662519578526000,"string":"-8,599,662,519,578,526,000"},"line_mean":{"kind":"number","value":22.5794871795,"string":"22.579487"},"line_max":{"kind":"number","value":73,"string":"73"},"alpha_frac":{"kind":"number","value":0.4593301435,"string":"0.45933"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.1025641025641026,"string":"3.102564"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45179,"cells":{"repo_name":{"kind":"string","value":"martindurant/astrobits"},"path":{"kind":"string","value":"time_series.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"12543"},"content":{"kind":"string","value":"\"\"\"Take a list of files and known star coordinates, and\nperform photometry on them all, either with apertures (phot)\nor by PSF fitting (daophot, which required additional\nparameters and is apropriate to poor S/N or crowded fields).\nMakes extensive use of iraf tasks; set all photometry parameters\nbefore running:\ndatapars - for data characteristics\ncenterpars - finding the reference star on each image.\ncenterpars, photpars, fitskypars - for controling aperture photometry\ndaopars - for controling daophot\n\nfilelist: set of image files, in IRAF syntax (image.fits[1][*,*,2] etc);\ncan be more than one per cube.\ncoords: name a file containing all star coords for photometry, based on\nan image unshifted relative to (0,0) in the shifts list. Be pure numbers\nfor phot method, .mag or .als for daophot method.\nshifts: name a file containing shifts, a tuple of shifts arrays, image\nheader keywords (tuple of two= or None for no shifts\nrefstar: coords of star for deriving (x,y) offset, as in coords\ntimestamp: source of the timing information: a header keyword, delta-t\nfor uniform sampling or a file with times (in whatever formate you'll be\nusing later.\n\npsf: whether to use daophot or aperture phot for analysis. If this is a\nfilename, that is the PSF profile to use for every image; if it is \"True\",\nmake a new PSF for every image. Pars below only for full PSF fitting\npststars: a .pst file from daophot, listing the IDs of stars for making\nthe PSF for each image. NB: DAOphot refuses to measure any star with SNR<2.\n\nids: which stars are interesting, by ID (in input coord list order)\ncoords: starting well-measured coords (pdump-ed from a .als, perhaps).\n\"\"\"\nimport os\nimport numpy\nfrom glob import glob\nimport pyfits\nfrom pylab import find\nfrom numpy import load,vstack,save,median\n\nthisdir = os.getcwd()\nos.chdir(\"/home/durant\")\nfrom pyraf import iraf\niraf.cd(thisdir)\niraf.digiphot()\niraf.daophot()\nimport pyraf\nimport pyfits\nimport numpy as n\n\ndef shift_file_coords(filename,xshift,yshift,output,sort=None):\n \"\"\"Understands filetypes: 2-column ascii numbers, .mag, .als, .pst.\nNB: shift means where each image is, relative to the original (not where\nit should be moved to).\n\"\"\"\n if not(sort):\n sort = 'num'\n if filename.find('.mag')>0: sort = 'mag'\n if filename.find('.als')>0: sort = 'als'\n if filename.find('.pst')>0: sort = 'pst'\n if not(sort=='num' or sort=='mag' or sort=='als' or sort=='pst'):\n raise ValueError('Unknown input filetype: %s'%filename)\n if sort=='num': # shift 2-column numeric ASCII table\n x,y = load(filename,usecols=[0,1],unpack=True)\n x += xshift\n y += yshift\n X = vstack((x,y))\n save(output,X.transpose())\n return\n if sort=='mag': #shift a .mag photometry file\n fred = open(filename)\n freda= open(output,'w')\n for line in fred:\n if line.split()[-1]=='\\\\' and len(line.split())==9 and line[0]!='#':\n x = float(line.split()[0]) + xshift\n y = float(line.split()[1]) + yshift\n line = \"%-14.3f %-11.3f\"%(x,y)+line[21:]\n freda.write(line) \n if sort=='als': #shift a .als DAOphot photometry file\n fred = open(filename)\n freda= open(output,'w')\n for line in fred:\n if line.split()[-1]=='\\\\' and len(line.split())==8 and line[0]!='#':\n x = float(line.split()[1]) + xshift\n y = float(line.split()[2]) + yshift\n line = line[:9] + \"%-10.3f %-10.3f\"%(x,y) + line[29:]\n freda.write(line)\n if sort=='pst': #shift a PSF star list for DAOphot\n fred = open(filename)\n freda= open(output,'w')\n for line in fred:\n if line[0]!=\"#\":\n x = float(line.split()[1]) + xshift\n y = float(line.split()[2]) + yshift\n line = line[:9] + \"%-10.3f %-10.3f\"%(x,y) + line[29:]\n freda.write(line) \n fred.close()\n freda.close()\n\ndef recentre(image,refcoordfile):\n \"\"\"Returns improved shift by centroiding\non the reference star using phot. This can be VERY\nsensitive to the parameters in centerpars.\"\"\"\n xin,yin = load(refcoordfile,unpack=True)\n try:\n iraf.phot(image,refcoordfile,'temp.mag',inter=\"no\",calgorithm='centroid',\n mode='h',verify='no',update='no',verbose='no')\n xout,yout=iraf.pdump('temp.mag','xcen,ycen','yes',Stdout=1)[0].split()\n except:\n print \"Recentring failed on\", image\n return 0.,0.\n xout,yout = float(xout),float(yout)\n return xout-xin,yout-yin\n\nvary_par = 1.\nvary_max = 10\nvary_min = 6\nvary_fwhm= 0\n \ndef setaperture(image,refstar):\n \"\"\"Measure the FWHM of the reference star unsing simple DAOphot editor\n and then set the photometry aperture to this number\"\"\"\n x,y = load(refstar,unpack=True)\n fred = open('tempaperfile','w')\n fred.write(\"%f %f 100 a\\nq\"%(x,y))\n fred.close()\n try:\n output=iraf.daoedit(image,icomm='tempaperfile',Stdout=1,Stderr=1)\n except:\n print \"Aperture setting failed on\",image\n return\n FWHM = float(output[3].split()[4])\n iraf.photpars.apertures = min(max(FWHM*vary_par,vary_min),vary_max)\n iraf.daopars.fitrad = min(max(FWHM*vary_par,vary_min),vary_max)\n global vary_fwhm\n vary_fwhm = FWHM\n print \"FWHM: \", FWHM, \" aperture: \",iraf.photpars.apertures\n\ndef apphot(image,coords,refstar=None,centre=False,vary=False):\n \"\"\"Apperture photometry with centering based on a reference star.\nNB: centre refers to shifting the coordinates by centroiding on the\nreference star; recentering on the final phot depends on\ncenterpars.calgorithm .\"\"\"\n iraf.dele('temp.mag*')\n if centre:\n xsh,ysh = recentre(image,refstar)\n print \"Fine centring: \", xsh,ysh\n else: #no recentreing by reference star (but could still have calgorithm!=none)\n xsh,ysh = 0,0\n if vary:\n setaperture(image,refstar)\n shift_file_coords(coords,xsh,ysh,'tempcoords')\n iraf.phot(image,'tempcoords','temp.mag2',inter=\"no\",\n mode='h',verify='no',update='no',verbose='no')\n out = iraf.pdump('temp.mag2','id,flux,msky,stdev','yes',Stdout=1)\n return out\n\ndef psfphot(image,coords,pststars,refstar,centre=True,vary=False):\n \"\"\"PSF photometry. Centering is through phot on refstar.\nAssume coords is a .als file for now. Recentering is always done\nfor the reference star, never for the targets.\"\"\"\n iraf.dele('temp.mag*')\n iraf.dele('temp.psf.fits')\n iraf.dele('temp.als')\n if centre:\n xsh,ysh = recentre(image,refstar) \n print \"Fine Centring: \", xsh,ysh\n else: xsh,ysh = 0,0\n if vary:\n setaperture(image,refstar)\n shift_file_coords(coords,xsh,ysh,'tempcoords2',sort='als')\n shift_file_coords(pststars,xsh,ysh,'temppst2',sort='pst')\n iraf.phot(image,'tempcoords2','temp.mag2',inter=\"no\",calgorithm='none',\n mode='h',verify='no',update='no',verbose='no')\n iraf.psf(image,'temp.mag2','temppst2','temp.psf','temp.mag.pst','temp.mag.psg',\n inter='no',mode='h',verify='no',update='no',verbose='no')\n iraf.allstar(image,'temp.mag2','temp.psf','temp.als','temp.mag.arj',\"default\",\n mode='h',verify='no',update='no',verbose='no')\n out = iraf.pdump('temp.als','id,mag,merr,msky','yes',Stdout=1)\n return out \n\ndef simplepsfphot(image,coords,psf,refstar,centre=True,vary=False):\n \"\"\"PSF photometry, with a given PSF file in psf used for every image\"\"\"\n iraf.dele('temp.mag*')\n iraf.dele('temp.als')\n iraf.dele('temp.sub.fits')\n if centre:\n xsh,ysh = recentre(image,refstar) \n print \"Fine Centring: \", xsh,ysh\n else: xsh,ysh = 0,0\n if vary:\n setaperture(image,refstar)\n shift_file_coords(coords,xsh,ysh,'tempcoords2',sort='als')\n iraf.phot(image,'tempcoords2','temp.mag2',inter=\"no\",calgorithm='none',\n mode='h',verify='no',update='no',verbose='no')\n iraf.allstar(image,'temp.mag2',psf,'temp.als','temp.mag.arj','temp.sub.fits',\n mode='h',verify='no',update='no',verbose='no')\n out = iraf.pdump('temp.als','id,mag,merr,msky','yes',Stdout=1)\n return out \n\ndef custom1(filename): # for NACO timing mode cubes - removes horizontal banding\n #iraf.imarith(filename,'-','dark','temp')\n iraf.imarith(filename,'/','flatK','temp')\n im = pyfits.getdata('temp.fits')\n med = median(im.transpose())\n out = ((im).transpose()-med).transpose()\n (pyfits.ImageHDU(out)).writeto(\"temp2.fits\",clobber=True)\n iraf.imdel('temp')\n iraf.imcopy('temp2[1]','temp')\n\ndef get_id(starid,output='output'):\n \"\"\"from the output of the photometry, grab the magnitudes and magerrs of starid\"\"\"\n mag = load(output,usecols=[4+starid*4])\n merr= load(output,usecols=[5+starid*4])\n return mag,merr\n\ndef run(filelist,coords,refstar,shifts=None,centre=False,psf=False,pststars=None,\n ids=None,dark=0,flat=1,timestamp=\"TIME\",output='output',custom_process=None,\n vary=False):\n \"\"\"If psf==True, must include all extra par files.\nIf PSF is a filename (.psf.fits), this profileis used to fit every image.\nTimestamp can be either a file of times (same length as filelist), a header\nkeyword, or an array of times.\nThe input list can include [] notation for multiple extensions or sections\nof each file (incompatible with header-based time-stamps).\ncustom_process(file) is a function taking a filename (possible including [x]\nsyntax) and places a processed image in temp.fits.\"\"\"\n output = open(output,'w')\n x = load(coords,usecols=[1])\n numstars = len(x)\n myfiles = open(filelist).readlines()\n myfiles = [myfiles[i][:-1] for i in range(len(myfiles))]\n if timestamp.__class__ == numpy.ndarray: #--sort out times--\n times = 1 #times=1 means we know the times beforehand\n elif len(glob(timestamp))>0:\n timestamp = load(timestamp,usecols=[0])\n times=1\n else:\n times=0 #times=0 mean find the time from each image\n if type(shifts)==type(\" \"): #--sort out shifts--\n xshifts,yshifts = load(shifts,unpack=True)#filename give, assuming 2 columns\n xshifts,yshifts = -xshifts,-yshifts #these are in the opposite sense to coords from stack\n elif n.iterable(shifts): \n xshifts=n.array(shifts[0]) #for shifts given as arrays/lists\n yshifts=n.array(shifts[1])\n else:\n print \"No shifts\" #assume all shifts are zero\n xshifts = n.zeros(len(myfiles))\n yshifts = n.zeros(len(myfiles))\n for i,thisfile in enumerate(myfiles): #run!\n print i,thisfile\n if times: \n time = timestamp[i] #known time\n else:\n time = pyfits.getval(thisfile,timestamp) #FITS keyword\n try:\n iraf.dele('temp.fits')\n if custom_process: #arbitrary subroutine to process a file -> temp.fits\n custom_process(thisfile)\n else: #typical dark/bias subtract and flatfield\n iraf.imarith(thisfile,'-',dark,'temp')\n iraf.imarith('temp','/',flat,'temp')\n shift_file_coords(coords,xshifts[i],yshifts[i],'tempcoords') #apply coarse shifts\n shift_file_coords(refstar,xshifts[i],yshifts[i],'tempref',sort='num')\n if psf:\n if psf is True: #full PSF fit\n shift_file_coords(pststars,xshifts[i],yshifts[i],'temppst')\n out=psfphot('temp.fits','tempcoords','temppst','tempref',centre,vary)\n else: #DAOphot with known PSF\n out=simplepsfphot('temp.fits','tempcoords',psf,'tempref',centre,vary)\n else: #aperture photometry\n out=apphot('temp.fits','tempcoords','tempref',centre,vary=vary)\n output.write(\"%s %s %s \"%(thisfile,time,vary_fwhm))\n myids = n.array([int(out[i].split()[0]) for i in range(len(out))])\n for i in ids or range(numstars):\n try: #search for each requested ID\n foundid = find(myids==i)[0]\n output.write(out[foundid]+\" \")\n except: #ID not found\n output.write(\" 0 0 0 0 \")\n output.write(\"\\n\")\n except KeyboardInterrupt: #exit on Ctrl-C\n break\n except pyraf.irafglobals.IrafError, err:\n print \"IRAF error \",err,thisfile\n break\n except ValueError, err:\n print \"Value error \",err,thisfile\n raise\n output.close()\n #iraf.dele('temp*') \n"},"license":{"kind":"string","value":"mit"},"hash":{"kind":"number","value":-5665480579238870000,"string":"-5,665,480,579,238,870,000"},"line_mean":{"kind":"number","value":42.2517241379,"string":"42.251724"},"line_max":{"kind":"number","value":97,"string":"97"},"alpha_frac":{"kind":"number","value":0.6335804831,"string":"0.63358"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.2095701125895597,"string":"3.20957"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45180,"cells":{"repo_name":{"kind":"string","value":"freelawproject/recap-server"},"path":{"kind":"string","value":"settings.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"1377"},"content":{"kind":"string","value":"\"\"\"Settings are derived by compiling any files ending in .py in the settings\ndirectory, in alphabetical order.\n\nThis results in the following concept:\n - default settings are in 10-public.py (this should contain most settings)\n - custom settings are in 05-private.py (an example of this file is here for\n you)\n - any overrides to public settings can go in 20-private.py (you'll need to\n create this)\n\"\"\"\n\nfrom __future__ import with_statement\nimport os\nimport glob\nimport sys\n\n\ndef _generate_secret_key(file_path):\n import random\n chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'\n\n def random_char():\n return chars[int(len(chars)*random.random())]\n rand_str = ''.join(random_char() for i in range(64))\n with open(file_path, 'w') as f:\n f.write('SECRET_KEY=%s\\n' % repr(rand_str))\n\nROOT_PATH = os.path.dirname(__file__)\n\n# Try importing the SECRET_KEY from the file secret_key.py. If it doesn't exist,\n# there is an import error, and the key is generated and written to the file.\ntry:\n from secret_key import SECRET_KEY\nexcept ImportError:\n _generate_secret_key(os.path.join(ROOT_PATH, 'secret_key.py'))\n from secret_key import SECRET_KEY\n\n# Load the conf files.\nconf_files = glob.glob(os.path.join(\n os.path.dirname(__file__), 'settings', '*.py'))\nconf_files.sort()\nfor f in conf_files:\n execfile(os.path.abspath(f))\n"},"license":{"kind":"string","value":"gpl-3.0"},"hash":{"kind":"number","value":8784527857870266000,"string":"8,784,527,857,870,266,000"},"line_mean":{"kind":"number","value":31.023255814,"string":"31.023256"},"line_max":{"kind":"number","value":80,"string":"80"},"alpha_frac":{"kind":"number","value":0.697167756,"string":"0.697168"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.4511278195488724,"string":"3.451128"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45181,"cells":{"repo_name":{"kind":"string","value":"mxamin/youtube-dl"},"path":{"kind":"string","value":"youtube_dl/extractor/criterion.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"1284"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nimport re\n\nfrom .common import InfoExtractor\n\n\nclass CriterionIE(InfoExtractor):\n _VALID_URL = r'https?://(?:www\\.)?criterion\\.com/films/(?P<id>[0-9]+)-.+'\n _TEST = {\n 'url': 'http://www.criterion.com/films/184-le-samourai',\n 'md5': 'bc51beba55685509883a9a7830919ec3',\n 'info_dict': {\n 'id': '184',\n 'ext': 'mp4',\n 'title': 'Le Samouraï',\n 'description': 'md5:a2b4b116326558149bef81f76dcbb93f',\n }\n }\n\n def _real_extract(self, url):\n mobj = re.match(self._VALID_URL, url)\n video_id = mobj.group('id')\n webpage = self._download_webpage(url, video_id)\n\n final_url = self._search_regex(\n r'so.addVariable\\(\"videoURL\", \"(.+?)\"\\)\\;', webpage, 'video url')\n title = self._og_search_title(webpage)\n description = self._html_search_meta('description', webpage)\n thumbnail = self._search_regex(\n r'so.addVariable\\(\"thumbnailURL\", \"(.+?)\"\\)\\;',\n webpage, 'thumbnail url')\n\n return {\n 'id': video_id,\n 'url': final_url,\n 'title': title,\n 'description': description,\n 'thumbnail': thumbnail,\n }\n"},"license":{"kind":"string","value":"unlicense"},"hash":{"kind":"number","value":-7290849255959012000,"string":"-7,290,849,255,959,012,000"},"line_mean":{"kind":"number","value":30.2926829268,"string":"30.292683"},"line_max":{"kind":"number","value":77,"string":"77"},"alpha_frac":{"kind":"number","value":0.5354637568,"string":"0.535464"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.4396782841823055,"string":"3.439678"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45182,"cells":{"repo_name":{"kind":"string","value":"qedsoftware/commcare-hq"},"path":{"kind":"string","value":"custom/opm/constants.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"1732"},"content":{"kind":"string","value":"from corehq.apps.fixtures.models import FixtureDataItem\nfrom corehq.util.quickcache import quickcache\n\nDOMAIN = 'opm'\n\nPREG_REG_XMLNS = \"http://openrosa.org/formdesigner/D127C457-3E15-4F5E-88C3-98CD1722C625\"\nVHND_XMLNS = \"http://openrosa.org/formdesigner/ff5de10d75afda15cddb3b00a0b1e21d33a50d59\"\nBIRTH_PREP_XMLNS = \"http://openrosa.org/formdesigner/50378991-FEC3-408D-B4A5-A264F3B52184\"\nDELIVERY_XMLNS = \"http://openrosa.org/formdesigner/492F8F0E-EE7D-4B28-B890-7CDA5F137194\"\nCHILD_FOLLOWUP_XMLNS = \"http://openrosa.org/formdesigner/C90C2C1F-3B34-47F3-B3A3-061EAAC1A601\"\nCFU1_XMLNS = \"http://openrosa.org/formdesigner/d642dd328514f2af92c093d414d63e5b2670b9c\"\nCFU2_XMLNS = \"http://openrosa.org/formdesigner/9ef423bba8595a99976f0bc9532617841253a7fa\"\nCFU3_XMLNS = \"http://openrosa.org/formdesigner/f15b9f8fb92e2552b1885897ece257609ed16649\"\nGROWTH_MONITORING_XMLNS= \"http://openrosa.org/formdesigner/F1356F3F-C695-491F-9277-7F9B5522200C\"\n\nCLOSE_FORM = \"http://openrosa.org/formdesigner/41A1B3E0-C1A4-41EA-AE90-71A328F0D8FD\"\nCHILDREN_FORMS = [CFU1_XMLNS, CFU2_XMLNS, CFU3_XMLNS, CHILD_FOLLOWUP_XMLNS]\n\nOPM_XMLNSs = [PREG_REG_XMLNS, VHND_XMLNS, BIRTH_PREP_XMLNS, DELIVERY_XMLNS,\n CHILD_FOLLOWUP_XMLNS, CFU1_XMLNS, CFU2_XMLNS, CFU3_XMLNS,\n GROWTH_MONITORING_XMLNS, CLOSE_FORM]\n\n# TODO Move these to a cached fixtures lookup\nMONTH_AMT = 250\nTWO_YEAR_AMT = 2000\nTHREE_YEAR_AMT = 3000\n\n\n@quickcache([], timeout=30 * 60)\ndef get_fixture_data():\n fixtures = FixtureDataItem.get_indexed_items(DOMAIN, 'condition_amounts', 'condition')\n return dict((k, int(fixture['rs_amount'])) for k, fixture in fixtures.items())\n\n\nclass InvalidRow(Exception):\n \"\"\"\n Raise this in the row constructor to skip row\n \"\"\"\n"},"license":{"kind":"string","value":"bsd-3-clause"},"hash":{"kind":"number","value":7714274633423886000,"string":"7,714,274,633,423,886,000"},"line_mean":{"kind":"number","value":44.5789473684,"string":"44.578947"},"line_max":{"kind":"number","value":96,"string":"96"},"alpha_frac":{"kind":"number","value":0.7690531178,"string":"0.769053"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":2.2552083333333335,"string":"2.255208"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45183,"cells":{"repo_name":{"kind":"string","value":"tonioo/modoboa"},"path":{"kind":"string","value":"modoboa/lib/u2u_decode.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"2282"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\n\n\"\"\"\nUnstructured rfc2047 header to unicode.\n\nA stupid (and not accurate) answer to https://bugs.python.org/issue1079.\n\n\"\"\"\n\nfrom __future__ import unicode_literals\n\nimport re\nfrom email.header import decode_header, make_header\nfrom email.utils import parseaddr\n\nfrom django.utils.encoding import smart_text\n\n# check spaces between encoded_words (and strip them)\nsre = re.compile(r\"\\?=[ \\t]+=\\?\")\n# re pat for MIME encoded_word (without trailing spaces)\nmre = re.compile(r\"=\\?[^?]*?\\?[bq]\\?[^?\\t]*?\\?=\", re.I)\n# re do detect encoded ASCII characters\nascii_re = re.compile(r\"=[\\dA-F]{2,3}\", re.I)\n\n\ndef clean_spaces(m):\n \"\"\"Replace unencoded spaces in string.\n\n :param str m: a match object\n :return: the cleaned string\n \"\"\"\n return m.group(0).replace(\" \", \"=20\")\n\n\ndef clean_non_printable_char(m):\n \"\"\"Strip non printable characters.\"\"\"\n code = int(m.group(0)[1:], 16)\n if code < 20:\n return \"\"\n return m.group(0)\n\n\ndef decode_mime(m):\n \"\"\"Substitute matching encoded_word with unicode equiv.\"\"\"\n h = decode_header(clean_spaces(m))\n try:\n u = smart_text(make_header(h))\n except (LookupError, UnicodeDecodeError):\n return m.group(0)\n return u\n\n\ndef clean_header(header):\n \"\"\"Clean header function.\"\"\"\n header = \"\".join(header.splitlines())\n header = sre.sub(\"?==?\", header)\n return ascii_re.sub(clean_non_printable_char, header)\n\n\ndef u2u_decode(s):\n \"\"\"utility function for (final) decoding of mime header\n\n note: resulting string is in one line (no \\n within)\n note2: spaces between enc_words are stripped (see RFC2047)\n \"\"\"\n return mre.sub(decode_mime, clean_header(s)).strip(\" \\r\\t\\n\")\n\n\ndef decode_address(value):\n \"\"\"Special function for address decoding.\n\n We need a dedicated processing because RFC1342 explicitely says\n address MUST NOT contain encoded-word:\n\n These are the ONLY locations where an encoded-word may appear. In\n particular, an encoded-word MUST NOT appear in any portion of an\n \"address\". In addition, an encoded-word MUST NOT be used in a\n Received header field.\n \"\"\"\n phrase, address = parseaddr(clean_header(value))\n if phrase:\n phrase = mre.sub(decode_mime, phrase)\n return phrase, address\n"},"license":{"kind":"string","value":"isc"},"hash":{"kind":"number","value":-962520203660710000,"string":"-962,520,203,660,710,000"},"line_mean":{"kind":"number","value":26.4939759036,"string":"26.493976"},"line_max":{"kind":"number","value":72,"string":"72"},"alpha_frac":{"kind":"number","value":0.6608238387,"string":"0.660824"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.5107692307692306,"string":"3.510769"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45184,"cells":{"repo_name":{"kind":"string","value":"tudarmstadt-lt/topicrawler"},"path":{"kind":"string","value":"lt.lm/src/main/py/mr_ngram_count.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"1297"},"content":{"kind":"string","value":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n\ntest:\n cat data | map | sort | reduce\n cat data | ./x.py -m | sort | ./x.py -r\n\nhadoop jar /opt/cloudera/parcels/CDH/lib/hadoop-mapreduce/hadoop-streaming.jar \\\n-files x.py \\\n-mapper 'x.py -m' \\\n-reducer 'x.py -r' \\\n-input in \\\n-output out\n\n@author: stevo\n\"\"\"\n\nfrom __future__ import print_function\nfrom __future__ import division\nimport itertools as it\nimport sys\n\ndef readlines():\n with sys.stdin as f:\n for line in f:\n if line.strip():\n yield line\n\ndef mapper(lines):\n for line in lines:\n print('{}'.format(line.rstrip()))\n\ndef line2tuple(lines):\n for line in lines:\n splits = line.rstrip().split('\\t')\n yield splits\n\ndef reducer(lines, mincount=1):\n for key, values in it.groupby(lines, lambda line : line.rstrip()):\n num = reduce(lambda x, y: x + 1, values, 0)\n if num >= mincount:\n print('{}\\t{}'.format(key, num))\n\nif len(sys.argv) < 2:\n raise Exception('specify mapper (-m) or reducer (-r) function')\n\nt = sys.argv[1]\nmincount = int(sys.argv[2]) if len(sys.argv) > 2 else 1\nif '-m' == t:\n mapper(readlines());\nelif '-r' == t:\n reducer(readlines(), mincount);\nelse:\n raise Exception('specify mapper (-m) or reducer (-r) function')"},"license":{"kind":"string","value":"apache-2.0"},"hash":{"kind":"number","value":-1830261497265860000,"string":"-1,830,261,497,265,860,000"},"line_mean":{"kind":"number","value":22.6,"string":"22.6"},"line_max":{"kind":"number","value":80,"string":"80"},"alpha_frac":{"kind":"number","value":0.5975327679,"string":"0.597533"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.1177884615384617,"string":"3.117788"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45185,"cells":{"repo_name":{"kind":"string","value":"Ziqi-Li/bknqgis"},"path":{"kind":"string","value":"bokeh/bokeh/sphinxext/example_handler.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"2905"},"content":{"kind":"string","value":"import sys\n\nfrom ..application.handlers.code_runner import CodeRunner\nfrom ..application.handlers.handler import Handler\nfrom ..io import set_curdoc, curdoc\n\nclass ExampleHandler(Handler):\n \"\"\" A stripped-down handler similar to CodeHandler but that does\n some appropriate monkeypatching to\n\n \"\"\"\n\n _output_funcs = ['output_notebook', 'output_file', 'reset_output']\n _io_funcs = ['show', 'save']\n\n def __init__(self, source, filename):\n super(ExampleHandler, self).__init__(self)\n self._runner = CodeRunner(source, filename, [])\n\n def modify_document(self, doc):\n if self.failed:\n return\n\n module = self._runner.new_module()\n\n sys.modules[module.__name__] = module\n doc._modules.append(module)\n\n old_doc = curdoc()\n set_curdoc(doc)\n\n old_io, old_doc = self._monkeypatch()\n\n try:\n self._runner.run(module, lambda: None)\n finally:\n self._unmonkeypatch(old_io, old_doc)\n set_curdoc(old_doc)\n\n def _monkeypatch(self):\n\n def _pass(*args, **kw): pass\n def _add_root(obj, *args, **kw):\n from bokeh.io import curdoc\n curdoc().add_root(obj)\n def _curdoc(*args, **kw):\n return curdoc()\n\n # these functions are transitively imported from io into plotting,\n # so we have to patch them all. Assumption is that no other patching\n # has occurred, i.e. we can just save the funcs being patched once,\n # from io, and use those as the originals to replace everywhere\n import bokeh.io as io\n import bokeh.plotting as p\n mods = [io, p]\n\n # TODO (bev) restore when bkcharts package is ready (but remove at 1.0 release)\n # import bkcharts as c\n # mods.append(c)\n\n old_io = {}\n for f in self._output_funcs + self._io_funcs:\n old_io[f] = getattr(io, f)\n\n for mod in mods:\n for f in self._output_funcs:\n setattr(mod, f, _pass)\n for f in self._io_funcs:\n setattr(mod, f, _add_root)\n\n import bokeh.document as d\n old_doc = d.Document\n d.Document = _curdoc\n\n return old_io, old_doc\n\n def _unmonkeypatch(self, old_io, old_doc):\n import bokeh.io as io\n import bokeh.plotting as p\n mods = [io, p]\n\n # TODO (bev) restore when bkcharts package is ready (but remove at 1.0 release)\n # import bkcharts as c\n # mods.append(c)\n\n for mod in mods:\n for f in old_io:\n setattr(mod, f, old_io[f])\n\n import bokeh.document as d\n d.Document = old_doc\n\n @property\n def failed(self):\n return self._runner.failed\n\n @property\n def error(self):\n return self._runner.error\n\n @property\n def error_detail(self):\n return self._runner.error_detail\n"},"license":{"kind":"string","value":"gpl-2.0"},"hash":{"kind":"number","value":-5235527630608026000,"string":"-5,235,527,630,608,026,000"},"line_mean":{"kind":"number","value":27.2038834951,"string":"27.203883"},"line_max":{"kind":"number","value":87,"string":"87"},"alpha_frac":{"kind":"number","value":0.578313253,"string":"0.578313"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.878504672897196,"string":"3.878505"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45186,"cells":{"repo_name":{"kind":"string","value":"BurningNetel/ctf-manager"},"path":{"kind":"string","value":"CTFmanager/tests/views/event/test_event.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"6138"},"content":{"kind":"string","value":"import json\n\nfrom django.core.urlresolvers import reverse\n\nfrom CTFmanager.tests.views.base import ViewTestCase\n\n\nclass EventPageAJAXJoinEventTest(ViewTestCase):\n \"\"\" Tests that a user can join an event\n A user should be able to join upcoming events.\n And get a response without the page reloading\n \"\"\"\n\n def get_valid_event_join_post(self):\n event = self.create_event()\n response = self.client.post(reverse('event_join', args=[event.name]))\n _json = json.loads(response.content.decode())\n return _json, event\n\n def test_POST_returns_expected_json_on_valid_post(self):\n _json, event = self.get_valid_event_join_post()\n self.assertEqual(200, _json['status_code'])\n\n def test_POST_gives_correct_user_count(self):\n _json, event = self.get_valid_event_join_post()\n\n self.assertEqual(1, _json['members'])\n\n def test_logout_POST_gives_401_and_negative(self):\n self.client.logout()\n _json, event = self.get_valid_event_join_post()\n\n self.assertEqual(-1, _json['members'])\n self.assertEqual(401, _json['status_code'])\n\n def test_duplicate_POST_gives_304_and_negative(self):\n _json, event = self.get_valid_event_join_post()\n response = self.client.post(reverse('event_join', args=[event.name]))\n _json = json.loads(response.content.decode())\n\n self.assertEqual(-1, _json['members'])\n self.assertEqual(304, _json['status_code'])\n\n def test_valid_DELETE_gives_valid_json(self):\n event = self.create_event_join_user()\n response = self.client.delete(reverse('event_join', args=[event.name]))\n _json = json.loads(response.content.decode())\n\n self.assertEqual(200, _json['status_code'])\n self.assertEqual(0, _json['members'])\n\n def test_duplicate_DELETE_gives_304_and_negative(self):\n event = self.create_event_join_user()\n self.client.delete(reverse('event_join', args=[event.name]))\n response = self.client.delete(reverse('event_join', args=[event.name]))\n _json = json.loads(response.content.decode())\n\n self.assertEqual(304, _json['status_code'])\n self.assertEqual(-1, _json['members'])\n\n def test_logout_then_DELTE_gives_401_and_negative(self):\n event = self.create_event_join_user()\n self.client.logout()\n response = self.client.delete(reverse('event_join', args=[event.name]))\n _json = json.loads(response.content.decode())\n\n self.assertEqual(401, _json['status_code'])\n self.assertEqual(-1, _json['members'])\n\n def create_event_join_user(self):\n event = self.create_event()\n event.join(self.user)\n return event\n\n\nclass EventPageTest(ViewTestCase):\n def test_events_page_requires_authentication(self):\n self.client.logout()\n response = self.client.get(reverse('events'))\n self.assertRedirects(response, reverse('login') + '?next=' + reverse('events'))\n\n def test_events_page_renders_events_template(self):\n response = self.client.get(reverse('events'))\n self.assertTemplateUsed(response, 'event/events.html')\n\n def test_events_page_contains_new_event_button(self):\n response = self.client.get(reverse('events'))\n expected = 'id=\"btn_add_event\" href=\"/events/new/\">Add Event</a>'\n self.assertContains(response, expected)\n\n def test_events_page_displays_only_upcoming_events(self):\n event_future = self.create_event(\"hatCTF\", True)\n event_past = self.create_event(\"RuCTF_2015\", False)\n response = self.client.get(reverse('events'))\n _event = response.context['events']\n self.assertEqual(_event[0], event_future)\n self.assertEqual(len(_event), 1)\n self.assertNotEqual(_event[0], event_past)\n\n def test_events_page_has_correct_headers(self):\n response = self.client.get(reverse('events'))\n expected = 'Upcoming Events'\n expected2 = 'Archive'\n self.assertContains(response, expected)\n self.assertContains(response, expected2)\n\n def test_empty_events_set_shows_correct_message(self):\n response = self.client.get(reverse('events'))\n expected = 'No upcoming events!'\n self.assertContains(response, expected)\n\n def test_events_page_display_archive(self):\n event_past = self.create_event('past_event', False)\n response = self.client.get(reverse('events'))\n archive = response.context['archive']\n self.assertContains(response, '<table id=\"table_archive\"')\n self.assertContains(response, event_past.name)\n self.assertEqual(archive[0], event_past)\n\n def test_events_page_displays_error_message_when_nothing_in_archive(self):\n response = self.client.get(reverse('events'))\n archive = response.context['archive']\n self.assertEqual(len(archive), 0)\n self.assertContains(response, 'No past events!')\n\n def test_event_page_displays_event_members_count(self):\n event = self.create_event()\n response = self.client.get(reverse('events'))\n self.assertContains(response, '0 Participating')\n\n event.members.add(self.user)\n event.save()\n response = self.client.get(reverse('events'))\n\n self.assertContains(response, '1 Participating')\n\n def test_event_page_displays_correct_button_text(self):\n event = self.create_event()\n response = self.client.get(reverse('events'))\n self.assertContains(response, 'Join</button>')\n\n event.join(self.user)\n response = self.client.get(reverse('events'))\n self.assertContains(response, 'Leave</button>')\n\n def test_event_page_shows_username_in_popup(self):\n event = self.create_event()\n response = self.client.get(reverse('events'))\n self.assertContains(response, self.user.username, 1)\n self.assertContains(response, 'Nobody has joined yet!')\n\n event.join(self.user)\n\n response = self.client.get(reverse('events'))\n self.assertContains(response, self.user.username, 2)\n self.assertNotContains(response, 'Nobody has joined yet!')"},"license":{"kind":"string","value":"gpl-3.0"},"hash":{"kind":"number","value":-6477876122721076000,"string":"-6,477,876,122,721,076,000"},"line_mean":{"kind":"number","value":38.3525641026,"string":"38.352564"},"line_max":{"kind":"number","value":87,"string":"87"},"alpha_frac":{"kind":"number","value":0.6547735419,"string":"0.654774"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.8076923076923075,"string":"3.807692"},"config_test":{"kind":"bool","value":true,"string":"true"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45187,"cells":{"repo_name":{"kind":"string","value":"jeffmurphy/cif-router"},"path":{"kind":"string","value":"poc/cif-router.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"21349"},"content":{"kind":"string","value":"#!/usr/bin/python\n#\n\n# \n# cif-router proof of concept\n#\n# cif-router [-p pubport] [-r routerport] [-m myname] [-h] \n# -p default: 5556\n# -r default: 5555\n# -m default: cif-router\n#\n# cif-router is a zmq device with the following sockets:\n# XPUB \n# for republishing messages \n# XSUB\n# for subscribing to message feeds\n# ROUTER\n# for routing REQ/REP messages between clients\n# also for accepting REQs from clients\n# locally accepted types:\n# REGISTER, UNREGISTER, LIST-CLIENTS\n# locally generated replies:\n# UNAUTHORIZED, OK, FAILED\n#\n# communication between router and clients is via CIF.msg passing\n# the 'ControlStruct' portion of CIF.msg is used for communication\n#\n# a typical use case:\n# \n# cif-smrt's REQ connects to ROUTER and sends a REGISTER message with dst=cif-router\n# cif-router's ROUTER responds with SUCCESS (if valid) or UNAUTHORIZED (if not valid)\n# the apikey will be validated during this step\n# cif-router's XSUB connects to cif-smrt's XPUB\n# cif-smrt begins publishing CIF messages \n# cif-router re-publishes the CIF messages to clients connected to cif-router's XPUB \n# clients may be: cif-correlator, cif-db\n\nimport sys\nimport zmq\nimport time\nimport datetime\nimport threading\nimport getopt\nimport json\nimport pprint\nimport struct\n\nsys.path.append('/usr/local/lib/cif-protocol/pb-python/gen-py')\nimport msg_pb2\nimport feed_pb2\nimport RFC5070_IODEF_v1_pb2\nimport MAEC_v2_pb2\nimport control_pb2\nimport cifsupport\n\nsys.path.append('../../libcif/lib')\n\nfrom CIF.RouterStats import *\nfrom CIF.CtrlCommands.Clients import *\nfrom CIF.CtrlCommands.Ping import *\nfrom CIFRouter.MiniClient import *\nfrom CIF.CtrlCommands.ThreadTracker import ThreadTracker\n\nmyname = \"cif-router\"\n\ndef dosubscribe(client, m):\n client = m.src\n if client in publishers :\n print \"dosubscribe: we've seen this client before. re-using old connection.\"\n return control_pb2.ControlType.SUCCESS\n elif clients.isregistered(client) == True:\n if clients.apikey(client) == m.apikey:\n print \"dosubscribe: New publisher to connect to \" + client\n publishers[client] = time.time()\n addr = m.iPublishRequest.ipaddress\n port = m.iPublishRequest.port\n print \"dosubscribe: connect our xsub -> xpub on \" + addr + \":\" + str(port)\n xsub.connect(\"tcp://\" + addr + \":\" + str(port))\n return control_pb2.ControlType.SUCCESS\n print \"dosubscribe: iPublish from a registered client with a bad apikey: \" + client + \" \" + m.apikey\n print \"dosubscribe: iPublish from a client who isnt registered: \\\"\" + client + \"\\\"\"\n return control_pb2.ControlType.FAILED\n\ndef list_clients(client, apikey):\n if clients.isregistered(client) == True and clients.apikey(client) == apikey:\n return clients.asmessage()\n return None\n\ndef make_register_reply(msgfrom, _apikey):\n msg = control_pb2.ControlType()\n msg.version = msg.version # required\n msg.type = control_pb2.ControlType.REPLY\n msg.command = control_pb2.ControlType.REGISTER\n msg.dst = msgfrom\n msg.src = \"cif-router\"\n print \"mrr \" + _apikey\n msg.apikey = _apikey\n\n return msg\n\ndef make_unregister_reply(msgfrom, _apikey):\n msg = control_pb2.ControlType()\n msg.version = msg.version # required\n msg.type = control_pb2.ControlType.REPLY\n msg.command = control_pb2.ControlType.UNREGISTER\n msg.dst = msgfrom\n msg.src = \"cif-router\"\n msg.apikey = _apikey\n\n return msg\n\ndef make_msg_seq(msg):\n _md5 = hashlib.md5()\n _md5.update(msg.SerializeToString())\n return _md5.digest()\n\ndef handle_miniclient_reply(socket, routerport, publisherport):\n pending_registers = miniclient.pending_apikey_lookups()\n print \"pending_apikey_lookups: \", pending_registers\n \n for apikey in pending_registers:\n if apikey in register_wait_map:\n reply_to = register_wait_map[apikey]\n apikey_results = miniclient.get_pending_apikey(apikey)\n \n print \" send reply to: \", reply_to\n msg = make_register_reply(reply_to['msgfrom'], apikey)\n msg.status = control_pb2.ControlType.FAILED\n \n if apikey_results != None:\n if apikey_results.revoked == False:\n if apikey_results.expires == 0 or apikey_results.expires >= time.time():\n msg.registerResponse.REQport = routerport\n msg.registerResponse.PUBport = publisherport\n msg.status = control_pb2.ControlType.SUCCESS\n clients.register(reply_to['msgfrom'], reply_to['from_zmqid'], apikey)\n print \" Register succeeded.\"\n else:\n print \" Register failed: key expired\"\n else:\n print \" Register failed: key revoked\"\n else:\n print \" Register failed: unknown key\"\n \n msg.seq = reply_to['msgseq']\n socket.send_multipart([reply_to['from_zmqid'], '', msg.SerializeToString()])\n del register_wait_map[apikey]\n elif apikey in unregister_wait_map:\n reply_to = unregister_wait_map[apikey]\n apikey_results = miniclient.get_pending_apikey(apikey)\n \n print \" send reply to: \", reply_to\n msg = make_unregister_reply(reply_to['msgfrom'], apikey)\n msg.status = control_pb2.ControlType.FAILED\n \n if apikey_results != None:\n if apikey_results.revoked == False:\n if apikey_results.expires == 0 or apikey_results.expires >= time.time():\n msg.status = control_pb2.ControlType.SUCCESS\n clients.unregister(reply_to['msgfrom'])\n print \" Unregister succeeded.\"\n else:\n print \" Unregister failed: key expired\"\n else:\n print \" Unregister failed: key revoked\"\n else:\n print \" Unregister failed: unknown key\"\n \n msg.seq = reply_to['msgseq'] \n socket.send_multipart([reply_to['from_zmqid'], '', msg.SerializeToString()])\n del unregister_wait_map[apikey]\n \n \n miniclient.remove_pending_apikey(apikey)\n\ndef myrelay(pubport):\n relaycount = 0\n print \"[myrelay] Create XPUB socket on \" + str(pubport)\n xpub = context.socket(zmq.PUB)\n xpub.bind(\"tcp://*:\" + str(pubport))\n \n while True:\n try:\n relaycount = relaycount + 1\n m = xsub.recv()\n \n _m = msg_pb2.MessageType()\n _m.ParseFromString(m)\n \n if _m.type == msg_pb2.MessageType.QUERY:\n mystats.setrelayed(1, 'QUERY')\n elif _m.type == msg_pb2.MessageType.REPLY:\n mystats.setrelayed(1, 'REPLY')\n elif _m.type == msg_pb2.MessageType.SUBMISSION:\n mystats.setrelayed(1, 'SUBMISSION')\n \n for bmt in _m.submissionRequest:\n mystats.setrelayed(1, bmt.baseObjectType)\n \n \n print \"[myrelay] total:%d got:%d bytes\" % (relaycount, len(m)) \n #print \"[myrelay] got msg on our xsub socket: \" , m\n xpub.send(m)\n\n except Exception as e:\n print \"[myrelay] invalid message received: \", e\n \ndef usage():\n print \"cif-router [-r routerport] [-p pubport] [-m myid] [-a myapikey] [-dn dbname] [-dk dbkey] [-h]\"\n print \" routerport = 5555, pubport = 5556, myid = cif-router\"\n print \" dbkey = a8fd97c3-9f8b-477b-b45b-ba06719a0088\"\n print \" dbname = cif-db\"\n \ntry:\n opts, args = getopt.getopt(sys.argv[1:], 'p:r:m:h')\nexcept getopt.GetoptError, err:\n print str(err)\n usage()\n sys.exit(2)\n\nglobal mystats\nglobal clients\nglobal thread_tracker\n\ncontext = zmq.Context()\nclients = Clients()\nmystats = RouterStats()\npublishers = {}\nrouterport = 5555\npublisherport = 5556\nmyid = \"cif-router\"\ndbkey = 'a8fd97c3-9f8b-477b-b45b-ba06719a0088'\ndbname = 'cif-db'\nglobal apikey\napikey = 'a1fd11c1-1f1b-477b-b45b-ba06719a0088'\nminiclient = None\nminiclient_id = myid + \"-miniclient\"\nregister_wait_map = {}\nunregister_wait_map = {}\n\n\nfor o, a in opts:\n if o == \"-r\":\n routerport = a\n elif o == \"-p\":\n publisherport = a\n elif o == \"-m\":\n myid = a\n elif o == \"-dk\":\n dbkey = a\n elif o == \"-dn\":\n dbname = a\n elif o == \"-a\":\n apikey = a\n elif o == \"-h\":\n usage()\n sys.exit(2)\n \nprint \"Create ROUTER socket on \" + str(routerport)\nglobal socket\nsocket = context.socket(zmq.ROUTER)\nsocket.bind(\"tcp://*:\" + str(routerport))\nsocket.setsockopt(zmq.IDENTITY, myname)\n\npoller = zmq.Poller()\npoller.register(socket, zmq.POLLIN)\n\nprint \"Create XSUB socket\"\nxsub = context.socket(zmq.SUB)\nxsub.setsockopt(zmq.SUBSCRIBE, '')\n\nprint \"Connect XSUB<->XPUB\"\nthread = threading.Thread(target=myrelay, args=(publisherport,))\nthread.start()\nwhile not thread.isAlive():\n print \"waiting for pubsub relay thread to become alive\"\n time.sleep(1)\nthread_tracker = ThreadTracker(False)\nthread_tracker.add(id=thread.ident, user='Router', host='localhost', state='Running', info=\"PUBSUB Relay\")\n\n\nprint \"Entering event loop\"\n\ntry:\n open_for_business = False\n \n while True:\n sockets_with_data_ready = dict(poller.poll(1000))\n #print \"[up \" + str(int(mystats.getuptime())) + \"s]: Wakeup: \"\n\n if miniclient != None:\n if miniclient.pending() == True:\n print \"\\tMiniclient has replies we need to handle.\"\n handle_miniclient_reply(socket, routerport, publisherport)\n \n if sockets_with_data_ready and sockets_with_data_ready.get(socket) == zmq.POLLIN:\n print \"[up \" + str(int(mystats.getuptime())) + \"s]: Got an inbound message\"\n rawmsg = socket.recv_multipart()\n #print \" Got \", rawmsg\n \n msg = control_pb2.ControlType()\n \n try:\n msg.ParseFromString(rawmsg[2])\n except Exception as e:\n print \"Received message isn't a protobuf: \", e\n mystats.setbad()\n else:\n from_zmqid = rawmsg[0] # save the ZMQ identity of who sent us this message\n \n #print \"Got msg: \"#, msg.seq\n \n try:\n cifsupport.versionCheck(msg)\n except Exception as e:\n print \"\\tReceived message has incompatible version: \", e\n mystats.setbadversion(1, msg.version)\n else:\n \n if cifsupport.isControl(msg):\n msgfrom = msg.src\n msgto = msg.dst\n msgcommand = msg.command\n msgcommandtext = control_pb2._CONTROLTYPE_COMMANDTYPE.values_by_number[msg.command].name\n msgid = msg.seq\n \n if msgfrom != '' and msg.apikey != '':\n if msgto == myname and msg.type == control_pb2.ControlType.REPLY:\n print \"\\tREPLY for me: \", msgcommand\n if msgcommand == control_pb2.ControlType.APIKEY_GET:\n print \"\\tReceived a REPLY for an APIKEY_GET\"\n \n elif msgto == myname and msg.type == control_pb2.ControlType.COMMAND:\n print \"\\tCOMMAND for me: \", msgcommandtext\n \n mystats.setcontrols(1, msgcommandtext)\n \n \"\"\"\n For REGISTER:\n We allow only the db to register with us while we are not\n open_for_business. Once the DB registers, we are open_for_business\n since we can then start validating apikeys. Until that time, we can\n only validate the dbkey that is specified on the command line when\n you launch this program.\n \"\"\"\n if msgcommand == control_pb2.ControlType.REGISTER:\n print \"\\tREGISTER from: \" + msgfrom\n \n msg.status = control_pb2.ControlType.FAILED\n msg.type = control_pb2.ControlType.REPLY\n msg.seq = msgid\n \n if msgfrom == miniclient_id and msg.apikey == apikey:\n clients.register(msgfrom, from_zmqid, msg.apikey)\n msg.status = control_pb2.ControlType.SUCCESS\n msg.registerResponse.REQport = routerport\n msg.registerResponse.PUBport = publisherport\n print \"\\tMiniClient has registered.\"\n socket.send_multipart([from_zmqid, '', msg.SerializeToString()])\n\n elif msgfrom == dbname and msg.apikey == dbkey:\n clients.register(msgfrom, from_zmqid, msg.apikey)\n msg.status = control_pb2.ControlType.SUCCESS\n msg.registerResponse.REQport = routerport\n msg.registerResponse.PUBport = publisherport\n open_for_business = True\n print \"\\tDB has connected successfully. Sending reply to DB.\"\n print \"\\tStarting embedded client\"\n miniclient = MiniClient(apikey, \"127.0.0.1\", \"127.0.0.1:\" + str(routerport), 5557, miniclient_id, thread_tracker, True)\n socket.send_multipart([from_zmqid, '', msg.SerializeToString()])\n\n elif open_for_business == True:\n \"\"\"\n Since we need to wait for the DB to response, we note this pending request, ask the miniclient\n to handle the lookup. We will poll the MC to see if the lookup has finished. Reply to client \n will be sent from handle_miniclient_reply()\n \"\"\"\n miniclient.lookup_apikey(msg.apikey)\n register_wait_map[msg.apikey] = {'msgfrom': msgfrom, 'from_zmqid': from_zmqid, 'msgseq': msg.seq}\n\n else:\n print \"\\tNot open_for_business yet. Go away.\"\n \n \n elif msgcommand == control_pb2.ControlType.UNREGISTER:\n \"\"\"\n If the database unregisters, then we are not open_for_business any more.\n \"\"\"\n print \"\\tUNREGISTER from: \" + msgfrom\n if open_for_business == True:\n if msgfrom == dbname and msg.apikey == dbkey:\n print \"\\t\\tDB unregistered. Closing for business.\"\n open_for_business = False\n clients.unregister(msgfrom)\n msg.status = control_pb2.ControlType.SUCCESS\n msg.seq = msgid\n socket.send_multipart([ from_zmqid, '', msg.SerializeToString()])\n else:\n \"\"\"\n Since we need to wait for the DB to response, we note this pending request, ask the miniclient\n to handle the lookup. We will poll the MC to see if the lookup has finished. Reply to the client\n will be sent from handle_miniclient_reply() \n \"\"\"\n miniclient.lookup_apikey(msg.apikey)\n unregister_wait_map[msg.apikey] = {'msgfrom': msgfrom, 'from_zmqid': from_zmqid, 'msgseq': msg.seq}\n \n elif msgcommand == control_pb2.ControlType.LISTCLIENTS:\n print \"\\tLIST-CLIENTS for: \" + msgfrom\n if open_for_business == True:\n rv = list_clients(msg.src, msg.apikey)\n msg.seq = msgid\n msg.status = msg.status | control_pb2.ControlType.FAILED\n \n if rv != None:\n msg.status = msg.status | control_pb2.ControlType.SUCCESS\n msg.listClientsResponse.client.extend(rv.client)\n msg.listClientsResponse.connectTimestamp.extend(rv.connectTimestamp)\n \n socket.send_multipart( [ from_zmqid, '', msg.SerializeToString() ] )\n \n elif msg.command == control_pb2.ControlType.STATS:\n print \"\\tSTATS for: \" + msgfrom\n \n if open_for_business == True:\n tmp = msg.dst\n msg.dst = msg.src\n msg.src = tmp\n msg.status = control_pb2.ControlType.SUCCESS\n msg.statsResponse.statsType = control_pb2.StatsResponse.ROUTER\n msg.statsResponse.stats = mystats.asjson()\n \n socket.send_multipart( [ from_zmqid, '', msg.SerializeToString() ] )\n \n elif msg.command == control_pb2.ControlType.THREADS_LIST:\n tmp = msg.dst\n msg.dst = msg.src\n msg.src = tmp\n msg.status = control_pb2.ControlType.SUCCESS\n thread_tracker.asmessage(msg.listThreadsResponse)\n socket.send_multipart( [ from_zmqid, '', msg.SerializeToString() ] )\n \n if msg.command == control_pb2.ControlType.PING:\n c = Ping.makereply(msg)\n socket.send_multipart( [ from_zmqid, '', c.SerializeToString() ] )\n \n elif msgcommand == control_pb2.ControlType.IPUBLISH:\n print \"\\tIPUBLISH from: \" + msgfrom\n if open_for_business == True:\n rv = dosubscribe(from_zmqid, msg)\n msg.status = rv\n socket.send_multipart( [from_zmqid, '', msg.SerializeToString()] )\n else:\n print \"\\tCOMMAND for someone else: cmd=\", msgcommandtext, \"src=\", msgfrom, \" dst=\", msgto\n msgto_zmqid = clients.getzmqidentity(msgto)\n if msgto_zmqid != None:\n socket.send_multipart([msgto_zmqid, '', msg.SerializeToString()])\n else:\n print \"\\tUnknown message destination: \", msgto\n else:\n print \"\\tmsgfrom and/or msg.apikey is empty\"\n \nexcept KeyboardInterrupt:\n print \"Shut down.\"\n if thread.isAlive():\n try:\n thread._Thread__stop()\n except:\n print(str(thread.getName()) + ' could not be terminated')\n sys.exit(0)\n\n \n \n"},"license":{"kind":"string","value":"bsd-3-clause"},"hash":{"kind":"number","value":-4783758994462898000,"string":"-4,783,758,994,462,898,000"},"line_mean":{"kind":"number","value":44.2309322034,"string":"44.230932"},"line_max":{"kind":"number","value":161,"string":"161"},"alpha_frac":{"kind":"number","value":0.4921541993,"string":"0.492154"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":4.620995670995671,"string":"4.620996"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45188,"cells":{"repo_name":{"kind":"string","value":"fdouetteau/PyBabe"},"path":{"kind":"string","value":"pybabe/pivot.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"2935"},"content":{"kind":"string","value":"\ntry:\n from collections import OrderedDict\nexcept:\n ## 2.6 Fallback\n from ordereddict import OrderedDict\n\nfrom base import StreamHeader, StreamFooter, BabeBase\n\n\nclass OrderedDefaultdict(OrderedDict):\n def __init__(self, *args, **kwargs):\n newdefault = None\n newargs = ()\n if args:\n newdefault = args[0]\n if not (newdefault is None or callable(newdefault)):\n raise TypeError('first argument must be callable or None')\n newargs = args[1:]\n self.default_factory = newdefault\n super(self.__class__, self).__init__(*newargs, **kwargs)\n\n def __missing__(self, key):\n if self.default_factory is None:\n raise KeyError(key)\n self[key] = value = self.default_factory()\n return value\n\n def __reduce__(self): # optional, for pickle support\n args = self.default_factory if self.default_factory else tuple()\n return type(self), args, None, None, self.items()\n\n\nclass OrderedSet(set):\n def __init__(self):\n self.list = []\n\n def add(self, elt):\n if elt in self:\n return\n else:\n super(OrderedSet, self).add(elt)\n self.list.append(elt)\n\n def __iter__(self):\n return self.list.__iter__()\n\n\ndef pivot(stream, pivot, group):\n \"Create a pivot around field, grouping on identical value for 'group'\"\n groups = OrderedDefaultdict(dict)\n pivot_values = OrderedSet()\n header = None\n group_n = map(StreamHeader.keynormalize, group)\n for row in stream:\n if isinstance(row, StreamHeader):\n header = row\n elif isinstance(row, StreamFooter):\n # HEADER IS : GROUP + (OTHER FIELDS * EACH VALUE\n other_fields = [f for f in header.fields if not f in group and not f == pivot]\n other_fields_k = map(StreamHeader.keynormalize, other_fields)\n fields = group + [f + \"-\" + str(v)\n for v in pivot_values.list for f in other_fields]\n newheader = header.replace(fields=fields)\n yield newheader\n for _, row_dict in groups.iteritems():\n ## Create a line per group\n mrow = row_dict.itervalues().next()\n group_cols = [getattr(mrow, col) for col in group_n]\n for v in pivot_values:\n if v in row_dict:\n mrow = row_dict[v]\n group_cols.extend([getattr(mrow, col) for col in other_fields_k])\n else:\n group_cols.extend([None for col in other_fields])\n yield group_cols\n yield row\n else:\n kgroup = \"\"\n for f in group_n:\n kgroup = kgroup + str(getattr(row, f))\n groups[kgroup][getattr(row, pivot)] = row\n pivot_values.add(getattr(row, pivot))\n\nBabeBase.register(\"pivot\", pivot)\n"},"license":{"kind":"string","value":"bsd-3-clause"},"hash":{"kind":"number","value":-1801747529367375600,"string":"-1,801,747,529,367,375,600"},"line_mean":{"kind":"number","value":33.5294117647,"string":"33.529412"},"line_max":{"kind":"number","value":90,"string":"90"},"alpha_frac":{"kind":"number","value":0.5601362862,"string":"0.560136"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":4.186875891583452,"string":"4.186876"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45189,"cells":{"repo_name":{"kind":"string","value":"rbn42/stiler"},"path":{"kind":"string","value":"config.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"1027"},"content":{"kind":"string","value":"WinBorder = 2\nLeftPadding = 15\nBottomPadding = 15\nTopPadding = BottomPadding\nRightPadding = BottomPadding\nNavigateAcrossWorkspaces = True # availabe in Unity7\nTempFile = \"/dev/shm/.stiler_db\"\nLockFile = \"/dev/shm/.stiler.lock\"\n\n\n# This is the congiguration that works for unity7. If you are using a\n# different Desktop Environment, close all windows and execute \"wmctrl\n# -lG\" to find out all the applications need to exclude.\n\nEXCLUDE_APPLICATIONS = ['<unknown>', 'x-nautilus-desktop', 'unity-launcher',\n 'unity-panel', 'Hud', 'unity-dash', 'Desktop',\n 'Docky',\n 'screenkey', 'XdndCollectionWindowImp']\n# An alternative method to exclude applications.\nEXCLUDE_WM_CLASS = ['wesnoth-1.12']\n\nUNRESIZABLE_APPLICATIONS = ['Screenkey']\nRESIZE_STEP = 50\nMOVE_STEP = 50\nMIN_WINDOW_WIDTH = 50\nMIN_WINDOW_HEIGHT = 50\n\n#NOFRAME_WMCLASS = ['Wine']\n\n# In i3-wm's window tree, only one child of a node is allowed to split.\n#MAX_KD_TREE_BRANCH = 1\nMAX_KD_TREE_BRANCH = 2\n"},"license":{"kind":"string","value":"mit"},"hash":{"kind":"number","value":8967949853643365000,"string":"8,967,949,853,643,365,000"},"line_mean":{"kind":"number","value":31.09375,"string":"31.09375"},"line_max":{"kind":"number","value":76,"string":"76"},"alpha_frac":{"kind":"number","value":0.6854917235,"string":"0.685492"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.229559748427673,"string":"3.22956"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45190,"cells":{"repo_name":{"kind":"string","value":"ojii/sandlib"},"path":{"kind":"string","value":"lib/lib_pypy/_ctypes/primitive.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"11496"},"content":{"kind":"string","value":"import _ffi\nimport _rawffi\nimport weakref\nimport sys\n\nSIMPLE_TYPE_CHARS = \"cbBhHiIlLdfguzZqQPXOv?\"\n\nfrom _ctypes.basics import _CData, _CDataMeta, cdata_from_address,\\\n CArgObject\nfrom _ctypes.builtin import ConvMode\nfrom _ctypes.array import Array\nfrom _ctypes.pointer import _Pointer, as_ffi_pointer\n#from _ctypes.function import CFuncPtr # this import is moved at the bottom\n # because else it's circular\n\nclass NULL(object):\n pass\nNULL = NULL()\n\nTP_TO_DEFAULT = {\n 'c': 0,\n 'u': 0,\n 'b': 0,\n 'B': 0,\n 'h': 0,\n 'H': 0,\n 'i': 0,\n 'I': 0,\n 'l': 0,\n 'L': 0,\n 'q': 0,\n 'Q': 0,\n 'f': 0.0,\n 'd': 0.0,\n 'g': 0.0,\n 'P': None,\n # not part of struct\n 'O': NULL,\n 'z': None,\n 'Z': None,\n '?': False,\n}\n\nif sys.platform == 'win32':\n TP_TO_DEFAULT['X'] = NULL\n TP_TO_DEFAULT['v'] = 0\n\nDEFAULT_VALUE = object()\n\nclass GlobalPyobjContainer(object):\n def __init__(self):\n self.objs = []\n\n def add(self, obj):\n num = len(self.objs)\n self.objs.append(weakref.ref(obj))\n return num\n\n def get(self, num):\n return self.objs[num]()\n\npyobj_container = GlobalPyobjContainer()\n\ndef generic_xxx_p_from_param(cls, value):\n if value is None:\n return cls(None)\n if isinstance(value, basestring):\n return cls(value)\n if isinstance(value, _SimpleCData) and \\\n type(value)._type_ in 'zZP':\n return value\n return None # eventually raise\n\ndef from_param_char_p(cls, value):\n \"used by c_char_p and c_wchar_p subclasses\"\n res = generic_xxx_p_from_param(cls, value)\n if res is not None:\n return res\n if isinstance(value, (Array, _Pointer)):\n from ctypes import c_char, c_byte, c_wchar\n if type(value)._type_ in [c_char, c_byte, c_wchar]:\n return value\n\ndef from_param_void_p(cls, value):\n \"used by c_void_p subclasses\"\n res = generic_xxx_p_from_param(cls, value)\n if res is not None:\n return res\n if isinstance(value, Array):\n return value\n if isinstance(value, (_Pointer, CFuncPtr)):\n return cls.from_address(value._buffer.buffer)\n if isinstance(value, (int, long)):\n return cls(value)\n\nFROM_PARAM_BY_TYPE = {\n 'z': from_param_char_p,\n 'Z': from_param_char_p,\n 'P': from_param_void_p,\n }\n\nclass SimpleType(_CDataMeta):\n def __new__(self, name, bases, dct):\n try:\n tp = dct['_type_']\n except KeyError:\n for base in bases:\n if hasattr(base, '_type_'):\n tp = base._type_\n break\n else:\n raise AttributeError(\"cannot find _type_ attribute\")\n if (not isinstance(tp, str) or\n not len(tp) == 1 or\n tp not in SIMPLE_TYPE_CHARS):\n raise ValueError('%s is not a type character' % (tp))\n default = TP_TO_DEFAULT[tp]\n ffiarray = _rawffi.Array(tp)\n result = type.__new__(self, name, bases, dct)\n result._ffiargshape = tp\n result._ffishape = tp\n result._fficompositesize = None\n result._ffiarray = ffiarray\n if tp == 'z':\n # c_char_p\n def _getvalue(self):\n addr = self._buffer[0]\n if addr == 0:\n return None\n else:\n return _rawffi.charp2string(addr)\n\n def _setvalue(self, value):\n if isinstance(value, basestring):\n if isinstance(value, unicode):\n value = value.encode(ConvMode.encoding,\n ConvMode.errors)\n #self._objects = value\n array = _rawffi.Array('c')(len(value)+1, value)\n self._objects = CArgObject(value, array)\n value = array.buffer\n elif value is None:\n value = 0\n self._buffer[0] = value\n result.value = property(_getvalue, _setvalue)\n result._ffiargtype = _ffi.types.Pointer(_ffi.types.char)\n\n elif tp == 'Z':\n # c_wchar_p\n def _getvalue(self):\n addr = self._buffer[0]\n if addr == 0:\n return None\n else:\n return _rawffi.wcharp2unicode(addr)\n\n def _setvalue(self, value):\n if isinstance(value, basestring):\n if isinstance(value, str):\n value = value.decode(ConvMode.encoding,\n ConvMode.errors)\n #self._objects = value\n array = _rawffi.Array('u')(len(value)+1, value)\n self._objects = CArgObject(value, array)\n value = array.buffer\n elif value is None:\n value = 0\n self._buffer[0] = value\n result.value = property(_getvalue, _setvalue)\n result._ffiargtype = _ffi.types.Pointer(_ffi.types.unichar)\n\n elif tp == 'P':\n # c_void_p\n\n def _getvalue(self):\n addr = self._buffer[0]\n if addr == 0:\n return None\n return addr\n\n def _setvalue(self, value):\n if isinstance(value, str):\n array = _rawffi.Array('c')(len(value)+1, value)\n self._objects = CArgObject(value, array)\n value = array.buffer\n elif value is None:\n value = 0\n self._buffer[0] = value\n result.value = property(_getvalue, _setvalue) \n \n elif tp == 'u':\n def _setvalue(self, val):\n if isinstance(val, str):\n val = val.decode(ConvMode.encoding, ConvMode.errors)\n # possible if we use 'ignore'\n if val:\n self._buffer[0] = val\n def _getvalue(self):\n return self._buffer[0]\n result.value = property(_getvalue, _setvalue)\n\n elif tp == 'c':\n def _setvalue(self, val):\n if isinstance(val, unicode):\n val = val.encode(ConvMode.encoding, ConvMode.errors)\n if val:\n self._buffer[0] = val\n def _getvalue(self):\n return self._buffer[0]\n result.value = property(_getvalue, _setvalue)\n\n elif tp == 'O':\n def _setvalue(self, val):\n num = pyobj_container.add(val)\n self._buffer[0] = num\n def _getvalue(self):\n return pyobj_container.get(self._buffer[0])\n result.value = property(_getvalue, _setvalue)\n\n elif tp == 'X':\n from ctypes import WinDLL\n # Use WinDLL(\"oleaut32\") instead of windll.oleaut32\n # because the latter is a shared (cached) object; and\n # other code may set their own restypes. We need out own\n # restype here.\n oleaut32 = WinDLL(\"oleaut32\")\n SysAllocStringLen = oleaut32.SysAllocStringLen\n SysStringLen = oleaut32.SysStringLen\n SysFreeString = oleaut32.SysFreeString\n def _getvalue(self):\n addr = self._buffer[0]\n if addr == 0:\n return None\n else:\n size = SysStringLen(addr)\n return _rawffi.wcharp2rawunicode(addr, size)\n\n def _setvalue(self, value):\n if isinstance(value, basestring):\n if isinstance(value, str):\n value = value.decode(ConvMode.encoding,\n ConvMode.errors)\n array = _rawffi.Array('u')(len(value)+1, value)\n value = SysAllocStringLen(array.buffer, len(value))\n elif value is None:\n value = 0\n if self._buffer[0]:\n SysFreeString(self._buffer[0])\n self._buffer[0] = value\n result.value = property(_getvalue, _setvalue)\n\n elif tp == '?': # regular bool\n def _getvalue(self):\n return bool(self._buffer[0])\n def _setvalue(self, value):\n self._buffer[0] = bool(value)\n result.value = property(_getvalue, _setvalue)\n\n elif tp == 'v': # VARIANT_BOOL type\n def _getvalue(self):\n return bool(self._buffer[0])\n def _setvalue(self, value):\n if value:\n self._buffer[0] = -1 # VARIANT_TRUE\n else:\n self._buffer[0] = 0 # VARIANT_FALSE\n result.value = property(_getvalue, _setvalue)\n\n # make pointer-types compatible with the _ffi fast path\n if result._is_pointer_like():\n def _as_ffi_pointer_(self, ffitype):\n return as_ffi_pointer(self, ffitype)\n result._as_ffi_pointer_ = _as_ffi_pointer_\n \n return result\n\n from_address = cdata_from_address\n\n def from_param(self, value):\n if isinstance(value, self):\n return value\n \n from_param_f = FROM_PARAM_BY_TYPE.get(self._type_)\n if from_param_f:\n res = from_param_f(self, value)\n if res is not None:\n return res\n else:\n try:\n return self(value)\n except (TypeError, ValueError):\n pass\n\n return super(SimpleType, self).from_param(value)\n\n def _CData_output(self, resbuffer, base=None, index=-1):\n output = super(SimpleType, self)._CData_output(resbuffer, base, index)\n if self.__bases__[0] is _SimpleCData:\n return output.value\n return output\n \n def _sizeofinstances(self):\n return _rawffi.sizeof(self._type_)\n\n def _alignmentofinstances(self):\n return _rawffi.alignment(self._type_)\n\n def _is_pointer_like(self):\n return self._type_ in \"sPzUZXO\"\n\nclass _SimpleCData(_CData):\n __metaclass__ = SimpleType\n _type_ = 'i'\n\n def __init__(self, value=DEFAULT_VALUE):\n if not hasattr(self, '_buffer'):\n self._buffer = self._ffiarray(1, autofree=True)\n if value is not DEFAULT_VALUE:\n self.value = value\n\n def _ensure_objects(self):\n if self._type_ not in 'zZP':\n assert self._objects is None\n return self._objects\n\n def _getvalue(self):\n return self._buffer[0]\n\n def _setvalue(self, value):\n self._buffer[0] = value\n value = property(_getvalue, _setvalue)\n del _getvalue, _setvalue\n\n def __ctypes_from_outparam__(self):\n meta = type(type(self))\n if issubclass(meta, SimpleType) and meta != SimpleType:\n return self\n\n return self.value\n\n def __repr__(self):\n if type(self).__bases__[0] is _SimpleCData:\n return \"%s(%r)\" % (type(self).__name__, self.value)\n else:\n return \"<%s object at 0x%x>\" % (type(self).__name__,\n id(self))\n\n def __nonzero__(self):\n return self._buffer[0] not in (0, '\\x00')\n\nfrom _ctypes.function import CFuncPtr\n"},"license":{"kind":"string","value":"bsd-3-clause"},"hash":{"kind":"number","value":4007503311104080000,"string":"4,007,503,311,104,080,000"},"line_mean":{"kind":"number","value":31.7521367521,"string":"31.752137"},"line_max":{"kind":"number","value":78,"string":"78"},"alpha_frac":{"kind":"number","value":0.5010438413,"string":"0.501044"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":4.086740135087096,"string":"4.08674"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45191,"cells":{"repo_name":{"kind":"string","value":"mongolab/mongoctl"},"path":{"kind":"string","value":"mongoctl/tests/sharded_test.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"2582"},"content":{"kind":"string","value":"# The MIT License\n\n# Copyright (c) 2012 ObjectLabs Corporation\n\n# Permission is hereby granted, free of charge, to any person obtaining\n# a copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to\n# permit persons to whom the Software is furnished to do so, subject to\n# the following conditions:\n\n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Software.\n\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nimport unittest\nimport time\n\nfrom mongoctl.tests.test_base import MongoctlTestBase, append_user_arg\n\n########################################################################################################################\n# Servers\nSHARD_TEST_SERVERS = [\n \"ConfigServer1\",\n \"ConfigServer2\",\n \"ConfigServer3\",\n \"Mongos1\",\n \"Mongos2\",\n \"ShardServer1\",\n \"ShardServer2\",\n \"ShardServer3\",\n \"ShardServer4\",\n \"ShardServer5\",\n \"ShardServer6\",\n \"ShardArbiter\"\n\n\n]\n########################################################################################################################\n### Sharded Servers\nclass ShardedTest(MongoctlTestBase):\n\n\n ########################################################################################################################\n def test_sharded(self):\n # Start all sharded servers\n\n for s_id in SHARD_TEST_SERVERS:\n self.assert_start_server(s_id, start_options=[\"--rs-add\"])\n\n print \"Sleeping for 10 seconds...\"\n # sleep for 10 of seconds\n time.sleep(10)\n conf_cmd = [\"configure-shard-cluster\", \"ShardedCluster\"]\n append_user_arg(conf_cmd)\n # Configure the sharded cluster\n self.mongoctl_assert_cmd(conf_cmd)\n\n ###########################################################################\n def get_my_test_servers(self):\n return SHARD_TEST_SERVERS\n\n# booty\nif __name__ == '__main__':\n unittest.main()\n\n"},"license":{"kind":"string","value":"mit"},"hash":{"kind":"number","value":1538437245596689700,"string":"1,538,437,245,596,689,700"},"line_mean":{"kind":"number","value":33.8918918919,"string":"33.891892"},"line_max":{"kind":"number","value":124,"string":"124"},"alpha_frac":{"kind":"number","value":0.5855925639,"string":"0.585593"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":4.635547576301616,"string":"4.635548"},"config_test":{"kind":"bool","value":true,"string":"true"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45192,"cells":{"repo_name":{"kind":"string","value":"jamasi/Xtal-xplore-R"},"path":{"kind":"string","value":"gui/doublespinslider.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"3682"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\n\"\"\"DoubleSpinSlider - a custom widget combining a slider with a spinbox\n\n Copyright (C) 2014 Jan M. Simons <marten@xtal.rwth-aachen.de>\n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU Affero General Public License as\n published by the Free Software Foundation, either version 3 of the\n License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with this program. If not, see <http://www.gnu.org/licenses/>.\n\"\"\"\nfrom __future__ import division, print_function, absolute_import\n\nfrom decimal import Decimal\nfrom PyQt4 import QtGui, QtCore\nfrom PyQt4.QtCore import pyqtSlot\n\n\nclass DoubleSpinSlider(QtGui.QWidget):\n \"\"\"This is a QWidget containing a QSlider and a QDoubleSpinBox\"\"\"\n def __init__(self, parent=None, width=50, height=100, dpi=100):\n #super(DoubleSpinSlider, self).__init__(parent)\n QtGui.QWidget.__init__(self, parent)\n self._vLayout = QtGui.QVBoxLayout()\n\n self._label = QtGui.QLabel(parent)\n self._label.setAlignment(QtCore.Qt.AlignCenter)\n self._vLayout.addWidget(self._label)\n\n self._dSBox = QtGui.QDoubleSpinBox(parent)\n self._dSBox.setWrapping(True)\n self._dSBox.setDecimals(4)\n self._dSBox.setMaximum(1.00000000)\n self._dSBox.setSingleStep(0.1000000000)\n self._vLayout.addWidget(self._dSBox)\n\n self._hLayout = QtGui.QHBoxLayout()\n self._vSlider = QtGui.QSlider(parent)\n self._vSlider.setMinimum(0)\n self._vSlider.setMaximum(10000)\n self._vSlider.setPageStep(1000)\n self._vSlider.setOrientation(QtCore.Qt.Vertical)\n self._vSlider.setTickPosition(QtGui.QSlider.TicksBothSides)\n self._vSlider.setTickInterval(0)\n self._hLayout.addWidget(self._vSlider)\n self._vLayout.addLayout(self._hLayout)\n self.setLayout(self._vLayout)\n self.setParent(parent)\n\n # map functions\n self.setText = self._label.setText\n self.text = self._label.text\n self.setValue = self._dSBox.setValue\n self.value = self._dSBox.value\n self._vSlider.valueChanged.connect(self.ChangeSpinBox)\n self._dSBox.valueChanged.connect(self.ChangeSlider)\n\n def _multiplier(self):\n return 10.000000 ** self._dSBox.decimals()\n\n @pyqtSlot(int)\n def ChangeSpinBox(self, slidervalue):\n #print(\"sv: {}\".format(slidervalue))\n newvalue = round(slidervalue / (self._multiplier()),4)\n #print(\"nv: {}\".format(newvalue))\n if newvalue != self._dSBox.value():\n self._dSBox.setValue(newvalue)\n\n @pyqtSlot('double')\n def ChangeSlider(self, spinboxvalue):\n newvalue = spinboxvalue * self._multiplier()\n #print(\"sb: {sb} mult: {mult} prod: {prod}\".format(\n # sb=spinboxvalue,\n # mult=int(10.00000000 ** self._dSBox.decimals()),\n # prod=newvalue))\n self._vSlider.setValue(newvalue)\n\n @pyqtSlot('double')\n def setMaximum(self, maximum):\n self._dSBox.setMaximum(maximum)\n self._vSlider.setMaximum(maximum * self._multiplier())\n\n @pyqtSlot('double')\n def setMinimum(self, minimum):\n self._dSBox.setMinimum(minimum)\n self._vSlider.setMinimum(minimum * self._multiplier())\n"},"license":{"kind":"string","value":"agpl-3.0"},"hash":{"kind":"number","value":7329879116559789000,"string":"7,329,879,116,559,789,000"},"line_mean":{"kind":"number","value":38.5913978495,"string":"38.591398"},"line_max":{"kind":"number","value":77,"string":"77"},"alpha_frac":{"kind":"number","value":0.6558935361,"string":"0.655894"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.8354166666666667,"string":"3.835417"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45193,"cells":{"repo_name":{"kind":"string","value":"adw0rd/lettuce-py3"},"path":{"kind":"string","value":"lettuce/__init__.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"6767"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\n# <Lettuce - Behaviour Driven Development for python>\n# Copyright (C) <2010-2012> Gabriel Falcão <gabriel@nacaolivre.org>\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see <http://www.gnu.org/licenses/>.\n\n__version__ = version = '0.2.22'\n\nrelease = 'kryptonite'\n\nimport os\nimport sys\nimport traceback\nimport warnings\ntry:\n from imp import reload\nexcept ImportError:\n # python 2.5 fallback\n pass\n\nimport random\n\nfrom lettuce.core import Feature, TotalResult\n\nfrom lettuce.terrain import after\nfrom lettuce.terrain import before\nfrom lettuce.terrain import world\n\nfrom lettuce.decorators import step, steps\nfrom lettuce.registry import call_hook\nfrom lettuce.registry import STEP_REGISTRY\nfrom lettuce.registry import CALLBACK_REGISTRY\nfrom lettuce.exceptions import StepLoadingError\nfrom lettuce.plugins import (\n xunit_output,\n subunit_output,\n autopdb,\n smtp_mail_queue,\n)\nfrom lettuce import fs\nfrom lettuce import exceptions\n\ntry:\n from colorama import init as ms_windows_workaround\n ms_windows_workaround()\nexcept ImportError:\n pass\n\n\n__all__ = [\n 'after',\n 'before',\n 'step',\n 'steps',\n 'world',\n 'STEP_REGISTRY',\n 'CALLBACK_REGISTRY',\n 'call_hook',\n]\n\ntry:\n terrain = fs.FileSystem._import(\"terrain\")\n reload(terrain)\nexcept Exception as e:\n if not \"No module named 'terrain'\" in str(e):\n string = 'Lettuce has tried to load the conventional environment ' \\\n 'module \"terrain\"\\nbut it has errors, check its contents and ' \\\n 'try to run lettuce again.\\n\\nOriginal traceback below:\\n\\n'\n\n sys.stderr.write(string)\n sys.stderr.write(exceptions.traceback.format_exc())\n raise SystemExit(1)\n\n\nclass Runner(object):\n \"\"\" Main lettuce's test runner\n\n Takes a base path as parameter (string), so that it can look for\n features and step definitions on there.\n \"\"\"\n def __init__(self, base_path, scenarios=None,\n verbosity=0, no_color=False, random=False,\n enable_xunit=False, xunit_filename=None,\n enable_subunit=False, subunit_filename=None,\n tags=None, failfast=False, auto_pdb=False,\n smtp_queue=None, root_dir=None, **kwargs):\n\n \"\"\" lettuce.Runner will try to find a terrain.py file and\n import it from within `base_path`\n \"\"\"\n\n self.tags = tags\n self.single_feature = None\n\n if os.path.isfile(base_path) and os.path.exists(base_path):\n self.single_feature = base_path\n base_path = os.path.dirname(base_path)\n\n sys.path.insert(0, base_path)\n self.loader = fs.FeatureLoader(base_path, root_dir)\n self.verbosity = verbosity\n self.scenarios = scenarios and list(map(int, scenarios.split(\",\"))) or None\n self.failfast = failfast\n if auto_pdb:\n autopdb.enable(self)\n\n sys.path.remove(base_path)\n\n if verbosity == 0:\n from lettuce.plugins import non_verbose as output\n elif verbosity == 1:\n from lettuce.plugins import dots as output\n elif verbosity == 2:\n from lettuce.plugins import scenario_names as output\n else:\n if verbosity == 4:\n from lettuce.plugins import colored_shell_output as output\n msg = ('Deprecated in lettuce 2.2.21. Use verbosity 3 without '\n '--no-color flag instead of verbosity 4')\n warnings.warn(msg, DeprecationWarning)\n elif verbosity == 3:\n if no_color:\n from lettuce.plugins import shell_output as output\n else:\n from lettuce.plugins import colored_shell_output as output\n\n self.random = random\n\n if enable_xunit:\n xunit_output.enable(filename=xunit_filename)\n if smtp_queue:\n smtp_mail_queue.enable()\n\n if enable_subunit:\n subunit_output.enable(filename=subunit_filename)\n\n reload(output)\n\n self.output = output\n\n def run(self):\n \"\"\" Find and load step definitions, and them find and load\n features under `base_path` specified on constructor\n \"\"\"\n results = []\n if self.single_feature:\n features_files = [self.single_feature]\n else:\n features_files = self.loader.find_feature_files()\n if self.random:\n random.shuffle(features_files)\n\n if not features_files:\n self.output.print_no_features_found(self.loader.base_dir)\n return\n\n # only load steps if we've located some features.\n # this prevents stupid bugs when loading django modules\n # that we don't even want to test.\n try:\n self.loader.find_and_load_step_definitions()\n except StepLoadingError as e:\n print(\"Error loading step definitions:\\n\", e)\n return\n\n call_hook('before', 'all')\n\n failed = False\n try:\n for filename in features_files:\n feature = Feature.from_file(filename)\n results.append(\n feature.run(self.scenarios,\n tags=self.tags,\n random=self.random,\n failfast=self.failfast))\n\n except exceptions.LettuceSyntaxError as e:\n sys.stderr.write(e.msg)\n failed = True\n except exceptions.NoDefinitionFound as e:\n sys.stderr.write(e.msg)\n failed = True\n except:\n if not self.failfast:\n e = sys.exc_info()[1]\n print(\"Died with %s\" % str(e))\n traceback.print_exc()\n else:\n print()\n print (\"Lettuce aborted running any more tests \"\n \"because was called with the `--failfast` option\")\n\n failed = True\n\n finally:\n total = TotalResult(results)\n total.output_format()\n call_hook('after', 'all', total)\n\n if failed:\n raise SystemExit(2)\n\n return total\n"},"license":{"kind":"string","value":"gpl-3.0"},"hash":{"kind":"number","value":-6675595172369562000,"string":"-6,675,595,172,369,562,000"},"line_mean":{"kind":"number","value":30.4697674419,"string":"30.469767"},"line_max":{"kind":"number","value":83,"string":"83"},"alpha_frac":{"kind":"number","value":0.6049364469,"string":"0.604936"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":4.143294549908145,"string":"4.143295"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45194,"cells":{"repo_name":{"kind":"string","value":"sam-roth/Keypad"},"path":{"kind":"string","value":"keypad/plugins/shell/bourne_model.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"4068"},"content":{"kind":"string","value":"import subprocess\nimport shlex\n\nfrom keypad.api import (Plugin,\n register_plugin,\n Filetype,\n Cursor)\n\nfrom keypad.abstract.code import IndentRetainingCodeModel, AbstractCompletionResults\nfrom keypad.core.syntaxlib import SyntaxHighlighter, lazy\nfrom keypad.core.processmgr.client import AsyncServerProxy\nfrom keypad.core.fuzzy import FuzzyMatcher\nfrom keypad.core.executors import future_wrap\nfrom keypad.core.attributed_string import AttributedString\n\n@lazy\ndef lexer():\n from . import bourne_lexer\n return bourne_lexer.Shell\n \nclass GetManPage:\n def __init__(self, cmd):\n self.cmd = cmd\n\n def __call__(self, ns):\n with subprocess.Popen(['man', self.cmd], stdout=subprocess.PIPE) as proc:\n out, _ = proc.communicate()\n\n\n\n import re\n\n return [re.subn('.\\x08', '', out.decode())[0]]\n\nclass ShellCompletionResults(AbstractCompletionResults):\n\n def __init__(self, token_start, results, prox):\n '''\n token_start - the (line, col) position at which the token being completed starts\n '''\n\n super().__init__(token_start)\n self.results = [(AttributedString(x.decode()),) for x in results]\n self._prox = prox\n\n def doc_async(self, index):\n '''\n Return a Future for the documentation for a given completion result as a list of \n AttributedString. \n '''\n \n return self._prox.submit(GetManPage(self.text(index)))\n\n @property\n def rows(self):\n '''\n Return a list of tuples of AttributedString containing the contents of \n each column for each row in the completion results.\n '''\n\n return self._filtered.rows\n\n\n def text(self, index):\n '''\n Return the text that should be inserted for the given completion.\n '''\n\n return self._filtered.rows[index][0].text\n\n def filter(self, text=''):\n '''\n Filter the completion results using the given text.\n '''\n self._filtered = FuzzyMatcher(text).filter(self.results, key=lambda x: x[0].text)\n self._filtered.sort(lambda item: len(item[0].text))\n\n def dispose(self):\n pass\n\n\nclass GetPathItems:\n def __init__(self, prefix):\n self.prefix = prefix\n def __call__(self, ns):\n\n with subprocess.Popen(['bash',\n '-c',\n 'compgen -c ' + shlex.quote(self.prefix)],\n stdout=subprocess.PIPE) as proc:\n out, _ = proc.communicate()\n\n return [l.strip() for l in out.splitlines()]\n\nclass BourneCodeModel(IndentRetainingCodeModel):\n completion_triggers = []\n\n def __init__(self, *args, **kw):\n super().__init__(*args, **kw)\n self._prox = AsyncServerProxy()\n self._prox.start()\n\n def dispose(self):\n self._prox.shutdown()\n super().dispose()\n \n def highlight(self):\n '''\n Rehighlight the buffer. \n '''\n \n \n highlighter = SyntaxHighlighter(\n 'keypad.plugins.shell.syntax',\n lexer(),\n dict(lexcat=None)\n )\n \n highlighter.highlight_buffer(self.buffer)\n \n \n def completions_async(self, pos):\n '''\n Return a future to the completions available at the given position in the document.\n \n Raise NotImplementedError if not implemented.\n '''\n\n\n c = Cursor(self.buffer).move(pos)\n text_to_pos = c.line.text[:c.x]\n \n for x, ch in reversed(list(enumerate(text_to_pos))):\n if ch.isspace():\n x += 1\n break\n else:\n x = 0\n \n\n print('text_to_pos', text_to_pos[x:], pos)\n\n return self._prox.submit(GetPathItems(text_to_pos[x:]),\n transform=lambda r: ShellCompletionResults((pos[0], x), r,\n self._prox))\n \n"},"license":{"kind":"string","value":"gpl-3.0"},"hash":{"kind":"number","value":-4100649501340423000,"string":"-4,100,649,501,340,423,000"},"line_mean":{"kind":"number","value":26.8630136986,"string":"26.863014"},"line_max":{"kind":"number","value":91,"string":"91"},"alpha_frac":{"kind":"number","value":0.5555555556,"string":"0.555556"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":4.360128617363344,"string":"4.360129"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45195,"cells":{"repo_name":{"kind":"string","value":"dmvieira/P.O.D."},"path":{"kind":"string","value":"func.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"5799"},"content":{"kind":"string","value":"from mergesort import *\r\ndef comeca(sequencia,entrada,entrada2,entrada3):\r\n div=open(entrada3,'w')\r\n t=open(entrada,'r')\r\n saida=open(entrada2,'w')\r\n x=t.readlines()\r\n if (x[-1][-1])<>'\\n':\r\n comp=x[-1][-1]\r\n comp=comp+'\\n'\r\n x.insert(-1,comp)\r\n comp=x[-1]\r\n comp=comp+'\\n'\r\n del(x[-1])\r\n x.insert(-1,comp)\r\n del(x[-1])\r\n l=[]\r\n b=0\r\n t.close()\r\n if sequencia=='r':\r\n for j in range(0,len(x)):\r\n k=len(x[j])\r\n if x[j][0]=='>':\r\n if b==1:\r\n l.append(c)\r\n l.append(x[j][:k-1])\r\n c=\"\"\r\n b=1\r\n else:\r\n y=\"\"\r\n for i in range(0,k-1):\r\n if x[j][i] == 'a' or x[j][i] == 'A' or x[j][i] == 'c' or x[j][i] == 'C' or x[j][i] == 'g' or x[j][i] == 'G' or x[j][i] == 'u' or x[j][i] == 'U' or x[j][i] == 'r' or x[j][i] == 'R' or x[j][i] == 'y' or x[j][i] == 'Y' or x[j][i] == 'k' or x[j][i] == 'K' or x[j][i] == 'm' or x[j][i] == 'M' or x[j][i] == 's' or x[j][i] == 'S' or x[j][i] == 'w' or x[j][i] == 'W' or x[j][i] == 'b' or x[j][i] == 'B' or x[j][i] == 'd' or x[j][i] == 'D' or x[j][i] == 'h' or x[j][i] == 'H' or x[j][i] == 'v' or x[j][i] == 'V' or x[j][i] == 'n' or x[j][i] == 'N':\r\n y=y+x[j][i]\r\n c=c+y\r\n l.append(c)\r\n \r\n elif sequencia=='p':\r\n for j in range(0,len(x)):\r\n k=len(x[j])\r\n if x[j][0]=='>':\r\n if b==1:\r\n l.append(c)\r\n l.append(x[j][:k-1])\r\n c=\"\"\r\n b=1\r\n else:\r\n y=\"\"\r\n for i in range(0,k-1):\r\n if x[j][i] == 'a' or x[j][i] == 'A' or x[j][i] == 'c' or x[j][i] == 'C' or x[j][i] == 'g' or x[j][i] == 'G' or x[j][i] == 'v' or x[j][i] == 'V' or x[j][i] == 'L' or x[j][i] == 'l' or x[j][i] == 'I' or x[j][i] == 'i' or x[j][i] == 'S' or x[j][i] == 's' or x[j][i] == 'T' or x[j][i] == 't' or x[j][i] == 'Y' or x[j][i] == 'y' or x[j][i] == 'M' or x[j][i] == 'm' or x[j][i] == 'd' or x[j][i] == 'D' or x[j][i] == 'n' or x[j][i] == 'N' or x[j][i] == 'E' or x[j][i] == 'e' or x[j][i] == 'Q' or x[j][i] == 'q' or x[j][i] == 'R' or x[j][i] == 'r' or x[j][i] == 'K' or x[j][i] == 'k' or x[j][i] == 'H' or x[j][i] == 'h' or x[j][i] == 'F' or x[j][i] == 'f' or x[j][i] == 'W' or x[j][i] == 'w' or x[j][i] == 'P' or x[j][i] == 'p' or x[j][i] == 'b' or x[j][i] == 'B' or x[j][i] == 'z' or x[j][i] == 'Z' or x[j][i] == 'x' or x[j][i] == 'X' or x[j][i] == 'u' or x[j][i] == 'U':\r\n y=y+x[j][i]\r\n c=c+y\r\n l.append(c)\r\n\r\n else:\r\n for j in range(0,len(x)):\r\n k=len(x[j])\r\n if x[j][0]=='>':\r\n if b==1:\r\n l.append(c)\r\n l.append(x[j][:k-1])\r\n c=\"\"\r\n b=1\r\n else:\r\n y=\"\"\r\n for i in range(0,k-1):\r\n if x[j][i] == 'a' or x[j][i] == 'A' or x[j][i] == 'c' or x[j][i] == 'C' or x[j][i] == 'g' or x[j][i] == 'G' or x[j][i] == 't' or x[j][i] == 'T' or x[j][i] == 'r' or x[j][i] == 'R' or x[j][i] == 'y' or x[j][i] == 'Y' or x[j][i] == 'k' or x[j][i] == 'K' or x[j][i] == 'm' or x[j][i] == 'M' or x[j][i] == 's' or x[j][i] == 'S' or x[j][i] == 'w' or x[j][i] == 'W' or x[j][i] == 'b' or x[j][i] == 'B' or x[j][i] == 'd' or x[j][i] == 'D' or x[j][i] == 'h' or x[j][i] == 'H' or x[j][i] == 'v' or x[j][i] == 'V' or x[j][i] == 'n' or x[j][i] == 'N':\r\n y=y+x[j][i]\r\n c=c+y\r\n l.append(c)\r\n \r\n dec,dic={},{}\r\n for j in range(0,len(l),2):\r\n alta=(l[j+1]).upper()\r\n del(l[j+1])\r\n l.insert(j+1,alta)\r\n if (dic.has_key((l[j+1][::-1])))==True:\r\n del(l[j+1])\r\n l.insert((j+1),alta[::-1])\r\n d={l[j]:l[j+1]}\r\n dec.update(d)\r\n d={l[j+1]:l[j]}\r\n dic.update(d)\r\n vou=dic.keys()\r\n v=dec.values()\r\n diversidade=[] \r\n dic={}\r\n for j in range(0,len(l),2):\r\n alta=(l[j+1]) \r\n divo=(len(alta))/65\r\n if divo > 0:\r\n alta2=''\r\n for h in range(1,divo+1):\r\n alta2=alta2+alta[(65*(h-1)):(65*h)]+'\\n'\r\n alta=alta2+alta[65*divo:]\r\n del(l[j+1])\r\n l.insert(j+1,alta)\r\n d= {alta:l[j]}\r\n dic.update(d)\r\n\r\n key=dic.keys()\r\n value=dic.values()\r\n\r\n for j in range(len(key)):\r\n saida.write(value[j]+'\\n'+key[j]+'\\n')\r\n diversidade.append((v.count(vou[j])))\r\n saida.close()\r\n ordena(diversidade, value, key, div)\r\n div.close()\r\n"},"license":{"kind":"string","value":"gpl-3.0"},"hash":{"kind":"number","value":-1694803398801581800,"string":"-1,694,803,398,801,581,800"},"line_mean":{"kind":"number","value":52.1962616822,"string":"52.196262"},"line_max":{"kind":"number","value":904,"string":"904"},"alpha_frac":{"kind":"number","value":0.272115882,"string":"0.272116"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":2.7772988505747125,"string":"2.777299"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45196,"cells":{"repo_name":{"kind":"string","value":"cdriehuys/chmvh-website"},"path":{"kind":"string","value":"chmvh_website/contact/forms.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"2333"},"content":{"kind":"string","value":"import logging\n\nfrom smtplib import SMTPException\n\nfrom captcha.fields import ReCaptchaField\nfrom django import forms\nfrom django.conf import settings\nfrom django.core import mail\nfrom django.template import loader\n\n\nlogger = logging.getLogger(\"chmvh_website.{0}\".format(__name__))\n\n\nclass ContactForm(forms.Form):\n captcha = ReCaptchaField()\n name = forms.CharField()\n email = forms.EmailField()\n message = forms.CharField(widget=forms.Textarea(attrs={\"rows\": 5}))\n street_address = forms.CharField(required=False)\n city = forms.CharField(required=False)\n zipcode = forms.CharField(required=False)\n\n template = loader.get_template(\"contact/email/message.txt\")\n\n def clean_city(self):\n \"\"\"\n If no city was provided, use a default string.\n \"\"\"\n if not self.cleaned_data[\"city\"]:\n return \"<No City Given>\"\n\n return self.cleaned_data[\"city\"]\n\n def send_email(self):\n assert self.is_valid(), self.errors\n\n subject = \"[CHMVH Website] Message from {}\".format(\n self.cleaned_data[\"name\"]\n )\n\n address_line_2_parts = [self.cleaned_data[\"city\"], \"North Carolina\"]\n if self.cleaned_data[\"zipcode\"]:\n address_line_2_parts.append(self.cleaned_data[\"zipcode\"])\n\n address_line_1 = self.cleaned_data[\"street_address\"]\n address_line_2 = \", \".join(address_line_2_parts)\n\n address = \"\"\n if address_line_1:\n address = \"\\n\".join([address_line_1, address_line_2])\n\n context = {\n \"name\": self.cleaned_data[\"name\"],\n \"email\": self.cleaned_data[\"email\"],\n \"message\": self.cleaned_data[\"message\"],\n \"address\": address,\n }\n\n logger.debug(\"Preparing to send email\")\n\n try:\n emails_sent = mail.send_mail(\n subject,\n self.template.render(context),\n settings.DEFAULT_FROM_EMAIL,\n [\"info@chapelhillvet.com\"],\n )\n\n logger.info(\n \"Succesfully sent email from {0}\".format(\n self.cleaned_data[\"email\"]\n )\n )\n except SMTPException as e:\n emails_sent = 0\n\n logger.exception(\"Failed to send email.\", exc_info=e)\n\n return emails_sent == 1\n"},"license":{"kind":"string","value":"mit"},"hash":{"kind":"number","value":3360558135283314700,"string":"3,360,558,135,283,314,700"},"line_mean":{"kind":"number","value":28.1625,"string":"28.1625"},"line_max":{"kind":"number","value":76,"string":"76"},"alpha_frac":{"kind":"number","value":0.5825117874,"string":"0.582512"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":4.078671328671328,"string":"4.078671"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45197,"cells":{"repo_name":{"kind":"string","value":"gdsfactory/gdsfactory"},"path":{"kind":"string","value":"pp/components/coupler.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"2755"},"content":{"kind":"string","value":"import pp\nfrom pp.component import Component\nfrom pp.components.coupler_straight import coupler_straight\nfrom pp.components.coupler_symmetric import coupler_symmetric\nfrom pp.cross_section import get_waveguide_settings\nfrom pp.snap import assert_on_1nm_grid\nfrom pp.types import ComponentFactory\n\n\n@pp.cell_with_validator\ndef coupler(\n gap: float = 0.236,\n length: float = 20.0,\n coupler_symmetric_factory: ComponentFactory = coupler_symmetric,\n coupler_straight_factory: ComponentFactory = coupler_straight,\n dy: float = 5.0,\n dx: float = 10.0,\n waveguide: str = \"strip\",\n **kwargs\n) -> Component:\n r\"\"\"Symmetric coupler.\n\n Args:\n gap: between straights\n length: of coupling region\n coupler_symmetric_factory\n coupler_straight_factory\n dy: port to port vertical spacing\n dx: length of bend in x direction\n waveguide: from tech.waveguide\n kwargs: overwrites waveguide_settings\n\n .. code::\n\n dx dx\n |------| |------|\n W1 ________ _______E1\n \\ / |\n \\ length / |\n ======================= gap | dy\n / \\ |\n ________/ \\_______ |\n W0 E0\n\n coupler_straight_factory coupler_symmetric_factory\n\n\n \"\"\"\n assert_on_1nm_grid(length)\n assert_on_1nm_grid(gap)\n c = Component()\n\n waveguide_settings = get_waveguide_settings(waveguide, **kwargs)\n\n sbend = coupler_symmetric_factory(gap=gap, dy=dy, dx=dx, **waveguide_settings)\n\n sr = c << sbend\n sl = c << sbend\n cs = c << coupler_straight_factory(length=length, gap=gap, **waveguide_settings)\n sl.connect(\"W1\", destination=cs.ports[\"W0\"])\n sr.connect(\"W0\", destination=cs.ports[\"E0\"])\n\n c.add_port(\"W1\", port=sl.ports[\"E0\"])\n c.add_port(\"W0\", port=sl.ports[\"E1\"])\n c.add_port(\"E0\", port=sr.ports[\"E0\"])\n c.add_port(\"E1\", port=sr.ports[\"E1\"])\n\n c.absorb(sl)\n c.absorb(sr)\n c.absorb(cs)\n c.length = sbend.length\n c.min_bend_radius = sbend.min_bend_radius\n return c\n\n\nif __name__ == \"__main__\":\n\n # c = pp.Component()\n # cp1 = c << coupler(gap=0.2)\n # cp2 = c << coupler(gap=0.5)\n # cp1.ymin = 0\n # cp2.ymin = 0\n\n # c = coupler(gap=0.2, waveguide=\"nitride\")\n # c = coupler(width=0.9, length=1, dy=2, gap=0.2)\n # print(c.settings_changed)\n c = coupler(gap=0.2, waveguide=\"nitride\")\n # c = coupler(gap=0.2, waveguide=\"strip_heater\")\n c.show()\n"},"license":{"kind":"string","value":"mit"},"hash":{"kind":"number","value":505920847848893060,"string":"505,920,847,848,893,060"},"line_mean":{"kind":"number","value":29.9550561798,"string":"29.955056"},"line_max":{"kind":"number","value":84,"string":"84"},"alpha_frac":{"kind":"number","value":0.5255898367,"string":"0.52559"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.4480600750938675,"string":"3.44806"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45198,"cells":{"repo_name":{"kind":"string","value":"Murali-group/GraphSpace"},"path":{"kind":"string","value":"applications/uniprot/models.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"1246"},"content":{"kind":"string","value":"from __future__ import unicode_literals\n\nfrom sqlalchemy import ForeignKeyConstraint, text\n\nfrom applications.users.models import *\nfrom django.conf import settings\nfrom graphspace.mixins import *\n\nBase = settings.BASE\n\n# ================== Table Definitions =================== #\n\n\nclass UniprotAlias(IDMixin, TimeStampMixin, Base):\n\t__tablename__ = 'uniprot_alias'\n\n\taccession_number = Column(String, nullable=False)\n\talias_source = Column(String, nullable=False)\n\talias_name = Column(String, nullable=False)\n\n\tconstraints = (\n\t\tUniqueConstraint('accession_number', 'alias_source', 'alias_name', name='_uniprot_alias_uc_accession_number_alias_source_alias_name'),\n\t)\n\n\tindices = (\n\t\tIndex('uniprot_alias_idx_accession_number', text(\"accession_number gin_trgm_ops\"), postgresql_using=\"gin\"),\n\t\tIndex('uniprot_alias_idx_alias_name', text(\"alias_name gin_trgm_ops\"), postgresql_using=\"gin\"),\n\t)\n\n\t@declared_attr\n\tdef __table_args__(cls):\n\t\targs = cls.constraints + cls.indices\n\t\treturn args\n\n\tdef serialize(cls, **kwargs):\n\t\treturn {\n\t\t\t# 'id': cls.id,\n\t\t\t'id': cls.accession_number,\n\t\t\t'alias_source': cls.alias_source,\n\t\t\t'alias_name': cls.alias_name,\n\t\t\t'created_at': cls.created_at.isoformat(),\n\t\t\t'updated_at': cls.updated_at.isoformat()\n\t\t}\n"},"license":{"kind":"string","value":"gpl-2.0"},"hash":{"kind":"number","value":1488446659459923500,"string":"1,488,446,659,459,923,500"},"line_mean":{"kind":"number","value":27.976744186,"string":"27.976744"},"line_max":{"kind":"number","value":136,"string":"136"},"alpha_frac":{"kind":"number","value":0.695024077,"string":"0.695024"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.1785714285714284,"string":"3.178571"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":45199,"cells":{"repo_name":{"kind":"string","value":"rohithredd94/Computer-Vision-using-OpenCV"},"path":{"kind":"string","value":"Particle-Filter-Tracking/PF_Tracker.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"4110"},"content":{"kind":"string","value":"import cv2\r\nimport numpy as mp\r\nfrom similarity import *\r\nfrom hist import *\r\n\r\nclass PF_Tracker:\r\n def __init__(self, model, search_space, num_particles=100, state_dims=2,\r\n control_std=10, sim_std=20, alpha=0.0):\r\n self.model = model\r\n self.search_space = search_space[::-1]\r\n self.num_particles = num_particles\r\n self.state_dims = state_dims\r\n self.control_std = control_std\r\n self.sim_std = sim_std\r\n self.alpha = alpha\r\n\r\n #Initialize particles using a uniform distribution\r\n self.particles = np.array([np.random.uniform(0, self.search_space[i],self.num_particles) for i in range(self.state_dims)]).T\r\n self.weights = np.ones(len(self.particles)) / len(self.particles)\r\n self.idxs = np.arange(num_particles)\r\n self.estimate_state()\r\n\r\n def update(self, frame):\r\n self.displace()\r\n self.observe(frame)\r\n self.resample()\r\n self.estimate_state()\r\n\r\n if self.alpha > 0:\r\n self.update_model(frame)\r\n\r\n def displace(self):\r\n #Displace particles using a normal distribution centered around 0\r\n self.particles += np.random.normal(0, self.control_std,\r\n self.particles.shape)\r\n\r\n def observe(self, img):\r\n #Get patches corresponding to each particle\r\n mh, mw = self.model.shape[:2]\r\n minx = (self.particles[:,0] - mw/2).astype(np.int)\r\n miny = (self.particles[:,1] - mh/2).astype(np.int)\r\n\r\n candidates = [img[miny[i]:miny[i]+mh, minx[i]:minx[i]+mw]\r\n for i in range(self.num_particles)]\r\n\r\n #Compute importance weight - similarity of each patch to the model\r\n self.weights = np.array([similarity(cand, self.model, self.sim_std) for cand in candidates])\r\n self.weights /= np.sum(self.weights)\r\n\r\n def resample(self):\r\n sw, sh = self.search_space[:2]\r\n mh, mw = self.model.shape[:2]\r\n\r\n j = np.random.choice(self.idxs, self.num_particles, True,\r\n p=self.weights.T) #Sample new particle indices using the distribution of the weights\r\n \r\n control = np.random.normal(0, self.control_std, self.particles.shape) #Get a random control input from a normal distribution\r\n\r\n self.particles = np.array(self.particles[j])\r\n\r\n self.particles[:,0] = np.clip(self.particles[:,0], 0, sw - 1)\r\n self.particles[:,1] = np.clip(self.particles[:,1], 0, sh - 1)\r\n\r\n def estimate_state(self):\r\n state_idx = np.random.choice(self.idxs, 1, p=self.weights)\r\n self.state = self.particles[state_idx][0]\r\n\r\n def update_model(self, frame):\r\n #Get current model based on belief\r\n mh, mw = self.model.shape[:2]\r\n minx = int(self.state[0] - mw/2)\r\n miny = int(self.state[1] - mh/2)\r\n best_model = frame[miny:miny+mh, minx:minx+mw]\r\n\r\n #Apply appearance model update if new model shape is unchanged\r\n if best_model.shape == self.model.shape:\r\n self.model = self.alpha * best_model + (1-self.alpha) * self.model\r\n self.model = self.model.astype(np.uint8)\r\n\r\n def visualize_filter(self, img):\r\n self.draw_particles(img)\r\n self.draw_window(img)\r\n self.draw_std(img)\r\n\r\n def draw_particles(self, img):\r\n for p in self.particles:\r\n cv2.circle(img, tuple(p.astype(int)), 2, (180,255,0), -1)\r\n\r\n def draw_window(self, img):\r\n best_idx = cv2.minMaxLoc(self.weights)[3][1]\r\n best_state = self.particles[best_idx]\r\n pt1 = (best_state - np.array(self.model.shape[::-1])/2).astype(np.int)\r\n\r\n pt2 = pt1 + np.array(self.model.shape[::-1])\r\n cv2.rectangle(img, tuple(pt1), tuple(pt2), (0,255,0), 2)\r\n\r\n def draw_std(self, img):\r\n weighted_sum = 0\r\n dist = np.linalg.norm(self.particles - self.state)\r\n weighted_sum = np.sum(dist * self.weights.reshape((-1,1)))\r\n \r\n cv2.circle(img, tuple(self.state.astype(np.int)),\r\n int(weighted_sum), (255,255,255), 1)"},"license":{"kind":"string","value":"mit"},"hash":{"kind":"number","value":-8084760379983337000,"string":"-8,084,760,379,983,337,000"},"line_mean":{"kind":"number","value":37.9223300971,"string":"37.92233"},"line_max":{"kind":"number","value":132,"string":"132"},"alpha_frac":{"kind":"number","value":0.5846715328,"string":"0.584672"},"autogenerated":{"kind":"bool","value":false,"string":"false"},"ratio":{"kind":"number","value":3.506825938566553,"string":"3.506826"},"config_test":{"kind":"bool","value":false,"string":"false"},"has_no_keywords":{"kind":"bool","value":false,"string":"false"},"few_assignments":{"kind":"bool","value":false,"string":"false"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":451,"numItemsPerPage":100,"numTotalItems":45404,"offset":45100,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1NjMxMjM5Nywic3ViIjoiL2RhdGFzZXRzL2NvZGVwYXJyb3QvY29kZXBhcnJvdC12YWxpZC12Mi1uZWFyLWRlZHVwIiwiZXhwIjoxNzU2MzE1OTk3LCJpc3MiOiJodHRwczovL2h1Z2dpbmdmYWNlLmNvIn0.qCdD5ULrtHSomZJzXcCCh-WXlxC8_QAflWDS2TuuGiSTxK7sCYywaW4HQAaSXOdtf6QetDwjSLrlDyC-vGpCDg","displayUrls":true},"discussionsStats":{"closed":1,"open":0,"total":1},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}"><div><header class="bg-linear-to-t border-b border-gray-100 pt-4 xl:pt-0 from-purple-500/8 dark:from-purple-500/20 to-white to-70% dark:to-gray-950"><div class="mx-4 relative flex flex-col xl:flex-row"><h1 class="flex flex-wrap items-center max-md:leading-tight gap-y-1 text-lg xl:flex-none"><a href="/datasets" class="group flex items-center"><svg class="sm:mr-1 -mr-1 text-gray-400" style="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 25 25"><ellipse cx="12.5" cy="5" fill="currentColor" fill-opacity="0.25" rx="7.5" ry="2"></ellipse><path d="M12.5 15C16.6421 15 20 14.1046 20 13V20C20 21.1046 16.6421 22 12.5 22C8.35786 22 5 21.1046 5 20V13C5 14.1046 8.35786 15 12.5 15Z" fill="currentColor" opacity="0.5"></path><path d="M12.5 7C16.6421 7 20 6.10457 20 5V11.5C20 12.6046 16.6421 13.5 12.5 13.5C8.35786 13.5 5 12.6046 5 11.5V5C5 6.10457 8.35786 7 12.5 7Z" fill="currentColor" opacity="0.5"></path><path d="M5.23628 12C5.08204 12.1598 5 12.8273 5 13C5 14.1046 8.35786 15 12.5 15C16.6421 15 20 14.1046 20 13C20 12.8273 19.918 12.1598 19.7637 12C18.9311 12.8626 15.9947 13.5 12.5 13.5C9.0053 13.5 6.06886 12.8626 5.23628 12Z" fill="currentColor"></path></svg> <span class="mr-2.5 font-semibold text-gray-400 group-hover:text-gray-500 max-sm:hidden">Datasets:</span></a> <hr class="mx-1.5 h-2 translate-y-px rounded-sm border-r dark:border-gray-600 sm:hidden"> <div class="group flex flex-none items-center"><div class="relative mr-1 flex items-center"> <span class="inline-block "><span class="contents"><a href="/codeparrot" class="text-gray-400 hover:text-blue-600"><img alt="" class="size-3.5 rounded-sm flex-none" src="https://aifasthub.com/avatars/v1/production/uploads/1655756383598-61c141342aac764ce1654e43.png" crossorigin="anonymous"></a></span> </span></div> <span class="inline-block "><span class="contents"><a href="/codeparrot" class="text-gray-400 hover:text-blue-600">codeparrot</a></span> </span> <div class="mx-0.5 text-gray-300">/</div></div> <div class="max-w-full xl:flex xl:min-w-0 xl:flex-nowrap xl:items-center xl:gap-x-1"><a class="break-words font-mono font-semibold hover:text-blue-600 text-[1.07rem] xl:truncate" href="/datasets/codeparrot/codeparrot-valid-v2-near-dedup">codeparrot-valid-v2-near-dedup</a> <button class="text-xs mr-3 focus:outline-hidden inline-flex cursor-pointer items-center text-sm mx-0.5 text-gray-600 " title="Copy dataset name to clipboard" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> </button></div> <div class="inline-flex items-center overflow-hidden whitespace-nowrap rounded-md border bg-white text-sm leading-none text-gray-500 mr-2"><button class="relative flex items-center overflow-hidden from-red-50 to-transparent dark:from-red-900 px-1.5 py-1 hover:bg-linear-to-t focus:outline-hidden" title="Like"><svg class="left-1.5 absolute" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32" fill="currentColor"><path d="M22.45,6a5.47,5.47,0,0,1,3.91,1.64,5.7,5.7,0,0,1,0,8L16,26.13,5.64,15.64a5.7,5.7,0,0,1,0-8,5.48,5.48,0,0,1,7.82,0L16,10.24l2.53-2.58A5.44,5.44,0,0,1,22.45,6m0-2a7.47,7.47,0,0,0-5.34,2.24L16,7.36,14.89,6.24a7.49,7.49,0,0,0-10.68,0,7.72,7.72,0,0,0,0,10.82L16,29,27.79,17.06a7.72,7.72,0,0,0,0-10.82A7.49,7.49,0,0,0,22.45,4Z"></path></svg> <span class="ml-4 pl-0.5 ">like</span></button> <button class="focus:outline-hidden flex items-center border-l px-1.5 py-1 text-gray-400 hover:bg-gray-50 focus:bg-gray-100 dark:hover:bg-gray-900 dark:focus:bg-gray-800" title="See users who liked this repository">2</button></div> <div class="relative flex items-center gap-1.5 "><div class="mr-2 inline-flex h-6 items-center overflow-hidden whitespace-nowrap rounded-md border text-sm text-gray-500"><button class="focus:outline-hidden relative flex h-full max-w-56 items-center gap-1.5 overflow-hidden px-1.5 hover:bg-gray-50 focus:bg-gray-100 dark:hover:bg-gray-900 dark:focus:bg-gray-800" type="button" ><div class="flex h-full flex-1 items-center justify-center ">Follow</div> <img alt="" class="rounded-xs size-3 flex-none" src="https://aifasthub.com/avatars/v1/production/uploads/1655756383598-61c141342aac764ce1654e43.png"> <span class="truncate">CodeParrot</span></button> <button class="focus:outline-hidden flex h-full items-center border-l pl-1.5 pr-1.5 text-gray-400 hover:bg-gray-50 focus:bg-gray-100 dark:hover:bg-gray-900 dark:focus:bg-gray-800" title="Show CodeParrot's followers" type="button">173</button></div> </div> </h1> <div class="flex flex-col-reverse gap-x-2 sm:flex-row sm:items-center sm:justify-between xl:ml-auto"><div class="-mb-px flex h-12 items-center overflow-x-auto overflow-y-hidden "> <a class="tab-alternate" href="/datasets/codeparrot/codeparrot-valid-v2-near-dedup"><svg class="mr-1.5 text-gray-400 flex-none" style="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24"><path class="uim-quaternary" d="M20.23 7.24L12 12L3.77 7.24a1.98 1.98 0 0 1 .7-.71L11 2.76c.62-.35 1.38-.35 2 0l6.53 3.77c.29.173.531.418.7.71z" opacity=".25" fill="currentColor"></path><path class="uim-tertiary" d="M12 12v9.5a2.09 2.09 0 0 1-.91-.21L4.5 17.48a2.003 2.003 0 0 1-1-1.73v-7.5a2.06 2.06 0 0 1 .27-1.01L12 12z" opacity=".5" fill="currentColor"></path><path class="uim-primary" d="M20.5 8.25v7.5a2.003 2.003 0 0 1-1 1.73l-6.62 3.82c-.275.13-.576.198-.88.2V12l8.23-4.76c.175.308.268.656.27 1.01z" fill="currentColor"></path></svg> Dataset card </a><a class="tab-alternate active" href="/datasets/codeparrot/codeparrot-valid-v2-near-dedup/viewer/"><svg class="mr-1.5 text-gray-400 flex-none" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 12 12"><path fill="currentColor" d="M2.5 2h7a1 1 0 0 1 1 1v6a1 1 0 0 1-1 1h-7a1 1 0 0 1-1-1V3a1 1 0 0 1 1-1Zm0 2v2h3V4h-3Zm4 0v2h3V4h-3Zm-4 3v2h3V7h-3Zm4 0v2h3V7h-3Z"></path></svg> Data Studio </a><a class="tab-alternate" href="/datasets/codeparrot/codeparrot-valid-v2-near-dedup/tree/main"><svg class="mr-1.5 text-gray-400 flex-none" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24"><path class="uim-tertiary" d="M21 19h-8a1 1 0 0 1 0-2h8a1 1 0 0 1 0 2zm0-4h-8a1 1 0 0 1 0-2h8a1 1 0 0 1 0 2zm0-8h-8a1 1 0 0 1 0-2h8a1 1 0 0 1 0 2zm0 4h-8a1 1 0 0 1 0-2h8a1 1 0 0 1 0 2z" opacity=".5" fill="currentColor"></path><path class="uim-primary" d="M9 19a1 1 0 0 1-1-1V6a1 1 0 0 1 2 0v12a1 1 0 0 1-1 1zm-6-4.333a1 1 0 0 1-.64-1.769L3.438 12l-1.078-.898a1 1 0 0 1 1.28-1.538l2 1.667a1 1 0 0 1 0 1.538l-2 1.667a.999.999 0 0 1-.64.231z" fill="currentColor"></path></svg> <span class="xl:hidden">Files</span> <span class="hidden xl:inline">Files and versions</span> <span class="inline-block "><span class="contents"><div slot="anchor" class="shadow-purple-500/10 ml-2 inline-flex -translate-y-px items-center gap-0.5 rounded-md border bg-white px-1 py-0.5 align-middle text-xs font-semibold leading-none text-gray-800 shadow-sm dark:border-gray-700 dark:bg-gradient-to-b dark:from-gray-925 dark:to-gray-925 dark:text-gray-300"><svg class="size-3 " xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 12 12"><path fill-rule="evenodd" clip-rule="evenodd" d="M6.14 3.64 5.1 4.92 2.98 2.28h2.06l1.1 1.36Zm0 4.72-1.1 1.36H2.98l2.13-2.64 1.03 1.28Zm4.9 1.36L8.03 6l3-3.72H8.96L5.97 6l3 3.72h2.06Z" fill="#7875FF"></path><path d="M4.24 6 2.6 8.03.97 6 2.6 3.97 4.24 6Z" fill="#FF7F41" opacity="1"></path></svg> <span>xet</span> </div></span> </span> </a><a class="tab-alternate" href="/datasets/codeparrot/codeparrot-valid-v2-near-dedup/discussions"><svg class="mr-1.5 text-gray-400 flex-none" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M20.6081 3C21.7684 3 22.8053 3.49196 23.5284 4.38415C23.9756 4.93678 24.4428 5.82749 24.4808 7.16133C24.9674 7.01707 25.4353 6.93643 25.8725 6.93643C26.9833 6.93643 27.9865 7.37587 28.696 8.17411C29.6075 9.19872 30.0124 10.4579 29.8361 11.7177C29.7523 12.3177 29.5581 12.8555 29.2678 13.3534C29.8798 13.8646 30.3306 14.5763 30.5485 15.4322C30.719 16.1032 30.8939 17.5006 29.9808 18.9403C30.0389 19.0342 30.0934 19.1319 30.1442 19.2318C30.6932 20.3074 30.7283 21.5229 30.2439 22.6548C29.5093 24.3704 27.6841 25.7219 24.1397 27.1727C21.9347 28.0753 19.9174 28.6523 19.8994 28.6575C16.9842 29.4379 14.3477 29.8345 12.0653 29.8345C7.87017 29.8345 4.8668 28.508 3.13831 25.8921C0.356375 21.6797 0.754104 17.8269 4.35369 14.1131C6.34591 12.058 7.67023 9.02782 7.94613 8.36275C8.50224 6.39343 9.97271 4.20438 12.4172 4.20438H12.4179C12.6236 4.20438 12.8314 4.2214 13.0364 4.25468C14.107 4.42854 15.0428 5.06476 15.7115 6.02205C16.4331 5.09583 17.134 4.359 17.7682 3.94323C18.7242 3.31737 19.6794 3 20.6081 3ZM20.6081 5.95917C20.2427 5.95917 19.7963 6.1197 19.3039 6.44225C17.7754 7.44319 14.8258 12.6772 13.7458 14.7131C13.3839 15.3952 12.7655 15.6837 12.2086 15.6837C11.1036 15.6837 10.2408 14.5497 12.1076 13.1085C14.9146 10.9402 13.9299 7.39584 12.5898 7.1776C12.5311 7.16799 12.4731 7.16355 12.4172 7.16355C11.1989 7.16355 10.6615 9.33114 10.6615 9.33114C10.6615 9.33114 9.0863 13.4148 6.38031 16.206C3.67434 18.998 3.5346 21.2388 5.50675 24.2246C6.85185 26.2606 9.42666 26.8753 12.0653 26.8753C14.8021 26.8753 17.6077 26.2139 19.1799 25.793C19.2574 25.7723 28.8193 22.984 27.6081 20.6107C27.4046 20.212 27.0693 20.0522 26.6471 20.0522C24.9416 20.0522 21.8393 22.6726 20.5057 22.6726C20.2076 22.6726 19.9976 22.5416 19.9116 22.222C19.3433 20.1173 28.552 19.2325 27.7758 16.1839C27.639 15.6445 27.2677 15.4256 26.746 15.4263C24.4923 15.4263 19.4358 19.5181 18.3759 19.5181C18.2949 19.5181 18.2368 19.4937 18.2053 19.4419C17.6743 18.557 17.9653 17.9394 21.7082 15.6009C25.4511 13.2617 28.0783 11.8545 26.5841 10.1752C26.4121 9.98141 26.1684 9.8956 25.8725 9.8956C23.6001 9.89634 18.2311 14.9403 18.2311 14.9403C18.2311 14.9403 16.7821 16.496 15.9057 16.496C15.7043 16.496 15.533 16.4139 15.4169 16.2112C14.7956 15.1296 21.1879 10.1286 21.5484 8.06535C21.7928 6.66715 21.3771 5.95917 20.6081 5.95917Z" fill="#FF9D00"></path><path d="M5.50686 24.2246C3.53472 21.2387 3.67446 18.9979 6.38043 16.206C9.08641 13.4147 10.6615 9.33111 10.6615 9.33111C10.6615 9.33111 11.2499 6.95933 12.59 7.17757C13.93 7.39581 14.9139 10.9401 12.1069 13.1084C9.29997 15.276 12.6659 16.7489 13.7459 14.713C14.8258 12.6772 17.7747 7.44316 19.304 6.44221C20.8326 5.44128 21.9089 6.00204 21.5484 8.06532C21.188 10.1286 14.795 15.1295 15.4171 16.2118C16.0391 17.2934 18.2312 14.9402 18.2312 14.9402C18.2312 14.9402 25.0907 8.49588 26.5842 10.1752C28.0776 11.8545 25.4512 13.2616 21.7082 15.6008C17.9646 17.9393 17.6744 18.557 18.2054 19.4418C18.7372 20.3266 26.9998 13.1351 27.7759 16.1838C28.5513 19.2324 19.3434 20.1173 19.9117 22.2219C20.48 24.3274 26.3979 18.2382 27.6082 20.6107C28.8193 22.9839 19.2574 25.7722 19.18 25.7929C16.0914 26.62 8.24723 28.3726 5.50686 24.2246Z" fill="#FFD21E"></path></svg> Community <div class="ml-1.5 flex h-4 min-w-[1rem] items-center justify-center rounded px-1 text-xs leading-none shadow-sm bg-gray-200 text-gray-600 dark:bg-gray-900 dark:text-gray-500">1</div> </a></div> </div></div></header> </div> <div class="flex flex-col w-full"> <div class="flex h-full flex-1"> <div class="flex flex-1 flex-col overflow-hidden " style="height: calc(100vh - 48px)"><div class="flex flex-col overflow-hidden h-full "> <div class="flex flex-1 flex-col overflow-hidden "><div class="flex flex-1 flex-col overflow-hidden"><div class="flex min-h-0 flex-1"><div class="flex flex-1 flex-col overflow-hidden"><div class="md:shadow-xs dark:border-gray-800 md:my-4 md:ml-4 md:rounded-lg md:border flex min-w-0 flex-wrap "><div class="flex min-w-0 flex-1 flex-wrap"><div class="grid flex-1 grid-cols-1 overflow-hidden text-sm md:grid-cols-2 md:place-content-center md:rounded-lg"><label class="relative block flex-1 px-3 py-2 hover:bg-gray-50 dark:border-gray-850 dark:hover:bg-gray-950 md:border-r md:border-r-0 hidden" title="default"><span class="text-gray-500">Subset (1)</span> <div class="flex items-center whitespace-nowrap"><span class="truncate">default</span> <span class="mx-2 text-gray-500">·</span> <span class="text-gray-500">45.4k rows</span> <svg class="ml-auto min-w-6 pl-2" width="1em" height="1em" viewBox="0 0 12 7" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M1 1L6 6L11 1" stroke="currentColor"></path></svg></div> <select class="absolute inset-0 z-10 w-full cursor-pointer border-0 bg-white text-base opacity-0"><optgroup label="Subset (1)"><option value="default" selected>default (45.4k rows)</option></optgroup></select></label> <label class="relative block flex-1 px-3 py-2 hover:bg-gray-50 dark:border-gray-850 dark:hover:bg-gray-900 md:border-r md:border-r" title="train"><div class="text-gray-500">Split (1)</div> <div class="flex items-center overflow-hidden whitespace-nowrap"><span class="truncate">train</span> <span class="mx-2 text-gray-500">·</span> <span class="text-gray-500">45.4k rows</span> <svg class="ml-auto min-w-6 pl-2" width="1em" height="1em" viewBox="0 0 12 7" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M1 1L6 6L11 1" stroke="currentColor"></path></svg></div> <select class="absolute inset-0 z-10 w-full cursor-pointer border-0 bg-white text-base opacity-0"><optgroup label="Split (1)"><option value="train" selected>train (45.4k rows)</option></optgroup></select></label></div></div> <div class="hidden flex-none flex-col items-center gap-0.5 border-l px-1 md:flex justify-end"> <span class="inline-block "><span class="contents"><div slot="anchor"><button class="group text-gray-500 hover:text-gray-700" aria-label="Hide sidepanel"><div class="rounded-xs flex size-4 items-center justify-center border border-gray-400 bg-gray-100 hover:border-gray-600 hover:bg-blue-50 dark:border-gray-600 dark:bg-gray-800 dark:hover:bg-gray-700 dark:group-hover:border-gray-400"><div class="float-left h-full w-[65%]"></div> <div class="float-right h-full w-[35%] bg-gray-400 group-hover:bg-gray-600 dark:bg-gray-600 dark:group-hover:bg-gray-400"></div></div></button></div></span> </span> <div class="relative "> <button class="btn px-0.5 py-0.5 " type="button"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="p-0.5" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><circle cx="16" cy="7" r="3" fill="currentColor"></circle><circle cx="16" cy="16" r="3" fill="currentColor"></circle><circle cx="16" cy="25" r="3" fill="currentColor"></circle></svg> </button> </div></div></div> <div class="flex min-h-0 flex-1 flex-col border dark:border-gray-800 md:mb-4 md:ml-4 md:rounded-lg"> <div class="bg-linear-to-r text-smd relative flex items-center dark:border-gray-900 dark:bg-gray-950 false rounded-t-lg [&:has(:focus)]:from-gray-50 [&:has(:focus)]:to-transparent [&:has(:focus)]:to-20% dark:[&:has(:focus)]:from-gray-900"><form class="flex-1"><svg class="absolute left-3 top-1/2 transform -translate-y-1/2 pointer-events-none text-gray-400" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M30 28.59L22.45 21A11 11 0 1 0 21 22.45L28.59 30zM5 14a9 9 0 1 1 9 9a9 9 0 0 1-9-9z" fill="currentColor"></path></svg> <input disabled class="outline-hidden h-9 w-full border-none bg-transparent px-1 pl-9 pr-3 placeholder:text-gray-400 " placeholder="Search this dataset" dir="auto"></form> <div class="flex items-center gap-2 px-2 py-1"><button type="button" class="hover:bg-yellow-200/70 flex items-center gap-1 rounded-md border border-yellow-200 bg-yellow-100 pl-0.5 pr-1 text-[.8rem] leading-normal text-gray-700 dark:border-orange-500/25 dark:bg-orange-500/20 dark:text-gray-300 dark:hover:brightness-110 md:hidden"><div class="rounded-sm bg-yellow-300 px-1 font-mono text-[.7rem] font-bold text-black dark:bg-yellow-700 dark:text-gray-200">SQL </div> Console </button></div></div> <div class="flex flex-1 flex-col overflow-hidden min-h-64 flex w-full flex-col border-t md:rounded-b-lg md:shadow-lg"> <div class="flex-1 relative overflow-auto"><table class="w-full table-auto rounded-lg font-mono text-xs text-gray-900"><thead class="shadow-xs sticky left-0 right-0 top-0 z-1 bg-white align-top"><tr class="space-y-54 h-full min-w-fit divide-x border-b text-left"><th class="h-full max-w-sm p-2 text-left relative w-auto"><div class="flex h-full flex-col flex-nowrap justify-between"><div><div class="flex items-center justify-between">repo_name <form class="flex flex-col"><button id="asc" class="-mr-1 ml-2 h-[0.4rem] w-[0.8rem] transition ease-in-out"><svg class="-rotate-180 transform text-gray-300 hover:text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 64 256 128" fill="currentColor" aria-hidden="true"><path d="M213.65674,101.657l-80,79.99976a7.99945,7.99945,0,0,1-11.31348,0l-80-79.99976A8,8,0,0,1,48,88H208a8,8,0,0,1,5.65674,13.657Z"></path></svg></button> <button id="desc" class="-mr-1 ml-2 h-[0.4rem] w-[0.8rem] transition ease-in-out"><svg class="text-gray-300 hover:text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 64 256 128" fill="currentColor" aria-hidden="true"><path d="M213.65674,101.657l-80,79.99976a7.99945,7.99945,0,0,1-11.31348,0l-80-79.99976A8,8,0,0,1,48,88H208a8,8,0,0,1,5.65674,13.657Z"></path></svg></button></form></div> <div class="mb-2 whitespace-nowrap text-xs font-normal text-gray-500"><span>string</span><span class="italic text-gray-400 before:mx-1 before:content-['·']">lengths</span></div></div> <div><div class="" style="height: 40px; padding-top: 2px"><svg width="130" height="28"><g><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="0" y="19.857073407875546" width="11.2" height="10.142926592124454" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="13.2" y="0" width="11.2" height="30" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="26.4" y="13.674120888024632" width="11.2" height="16.325879111975368" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="39.599999999999994" y="23.26454383406255" width="11.2" height="6.73545616593745" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="52.8" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="66" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="79.19999999999999" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="92.39999999999999" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="105.6" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="118.8" y="25" width="11.2" height="5" fill-opacity="1"></rect></g><rect class="fill-white dark:fill-gray-900" x="0" y="26" width="130" height="2" stroke-opacity="1"></rect><line class="stroke-gray-100 dark:stroke-gray-500/20" x1="0" y1="27.5" x2="130" y2="27.5" stroke-opacity="1"></line><g><rect class="fill-indigo-500 cursor-pointer" x="-1" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="12.2" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="25.4" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="38.599999999999994" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="51.8" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="65" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="78.19999999999999" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="91.39999999999999" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="104.6" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="117.8" y="0" width="13.2" height="30" fill-opacity="0"></rect></g></svg> <div class="relative font-light text-gray-400" style="height: 10px; width: 130px;"><div class="absolute left-0 overflow-hidden text-ellipsis whitespace-nowrap" style="max-width: 60px">5</div> <div class="absolute overflow-hidden text-ellipsis whitespace-nowrap" style="right: 0px; max-width: 60px">92</div> </div></div></div></div> <div class="absolute right-0 top-0 z-10 h-full w-1 cursor-col-resize hover:bg-indigo-100 active:bg-indigo-500 dark:hover:bg-indigo-800 dark:active:bg-indigo-600/80"><div class="absolute right-0 top-0 h-full w-1"></div> </div> </th><th class="h-full max-w-sm p-2 text-left relative w-auto"><div class="flex h-full flex-col flex-nowrap justify-between"><div><div class="flex items-center justify-between">path <form class="flex flex-col"><button id="asc" class="-mr-1 ml-2 h-[0.4rem] w-[0.8rem] transition ease-in-out"><svg class="-rotate-180 transform text-gray-300 hover:text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 64 256 128" fill="currentColor" aria-hidden="true"><path d="M213.65674,101.657l-80,79.99976a7.99945,7.99945,0,0,1-11.31348,0l-80-79.99976A8,8,0,0,1,48,88H208a8,8,0,0,1,5.65674,13.657Z"></path></svg></button> <button id="desc" class="-mr-1 ml-2 h-[0.4rem] w-[0.8rem] transition ease-in-out"><svg class="text-gray-300 hover:text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 64 256 128" fill="currentColor" aria-hidden="true"><path d="M213.65674,101.657l-80,79.99976a7.99945,7.99945,0,0,1-11.31348,0l-80-79.99976A8,8,0,0,1,48,88H208a8,8,0,0,1,5.65674,13.657Z"></path></svg></button></form></div> <div class="mb-2 whitespace-nowrap text-xs font-normal text-gray-500"><span>string</span><span class="italic text-gray-400 before:mx-1 before:content-['·']">lengths</span></div></div> <div><div class="" style="height: 40px; padding-top: 2px"><svg width="130" height="28"><g><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="0" y="0" width="11.2" height="30" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="13.2" y="2.5146055280082464" width="11.2" height="27.485394471991754" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="26.4" y="19.61264666895773" width="11.2" height="10.38735333104227" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="39.599999999999994" y="24.542294663459177" width="11.2" height="5.457705336540822" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="52.8" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="66" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="79.19999999999999" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="92.39999999999999" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="105.6" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="118.8" y="25" width="11.2" height="5" fill-opacity="1"></rect></g><rect class="fill-white dark:fill-gray-900" x="0" y="26" width="130" height="2" stroke-opacity="1"></rect><line class="stroke-gray-100 dark:stroke-gray-500/20" x1="0" y1="27.5" x2="130" y2="27.5" stroke-opacity="1"></line><g><rect class="fill-indigo-500 cursor-pointer" x="-1" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="12.2" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="25.4" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="38.599999999999994" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="51.8" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="65" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="78.19999999999999" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="91.39999999999999" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="104.6" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="117.8" y="0" width="13.2" height="30" fill-opacity="0"></rect></g></svg> <div class="relative font-light text-gray-400" style="height: 10px; width: 130px;"><div class="absolute left-0 overflow-hidden text-ellipsis whitespace-nowrap" style="max-width: 60px">4</div> <div class="absolute overflow-hidden text-ellipsis whitespace-nowrap" style="right: 0px; max-width: 60px">221</div> </div></div></div></div> <div class="absolute right-0 top-0 z-10 h-full w-1 cursor-col-resize hover:bg-indigo-100 active:bg-indigo-500 dark:hover:bg-indigo-800 dark:active:bg-indigo-600/80"><div class="absolute right-0 top-0 h-full w-1"></div> </div> </th><th class="h-full max-w-sm p-2 text-left relative w-auto"><div class="flex h-full flex-col flex-nowrap justify-between"><div><div class="flex items-center justify-between">copies <form class="flex flex-col"><button id="asc" class="-mr-1 ml-2 h-[0.4rem] w-[0.8rem] transition ease-in-out"><svg class="-rotate-180 transform text-gray-300 hover:text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 64 256 128" fill="currentColor" aria-hidden="true"><path d="M213.65674,101.657l-80,79.99976a7.99945,7.99945,0,0,1-11.31348,0l-80-79.99976A8,8,0,0,1,48,88H208a8,8,0,0,1,5.65674,13.657Z"></path></svg></button> <button id="desc" class="-mr-1 ml-2 h-[0.4rem] w-[0.8rem] transition ease-in-out"><svg class="text-gray-300 hover:text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 64 256 128" fill="currentColor" aria-hidden="true"><path d="M213.65674,101.657l-80,79.99976a7.99945,7.99945,0,0,1-11.31348,0l-80-79.99976A8,8,0,0,1,48,88H208a8,8,0,0,1,5.65674,13.657Z"></path></svg></button></form></div> <div class="mb-2 whitespace-nowrap text-xs font-normal text-gray-500"><span>string</span><span class="italic text-gray-400 before:mx-1 before:content-['·']">classes</span></div></div> <div><div class="" style="height: 40px; padding-top: 2px"><svg width="130" height="28"><defs><clipPath id="rounded-bar"><rect x="0" y="0" width="130" height="8" rx="4"></rect></clipPath><pattern id="hatching" patternUnits="userSpaceOnUse" patternTransform="rotate(-45)" height="1" width="5"><line y1="0" class="stroke-gray-400 dark:stroke-gray-500/80" stroke-width="3" y2="1" x1="2" x2="2"></line></pattern><pattern id="hatching-faded" patternUnits="userSpaceOnUse" patternTransform="rotate(-45)" height="1" width="5"><line y1="0" class="stroke-gray-100 dark:stroke-gray-500/20" stroke-width="3" y2="1" x1="2" x2="2"></line></pattern></defs><g height="8" style="transform: translateY(20px)" clip-path="url(#rounded-bar)"><g style="transform: scaleX(1.0153846153846153) translateX(-1px)"><g><rect class="fill-indigo-500 dark:fill-indigo-600/80" x="1" y="0" width="124.95070918861775" height="8" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" x="127.95070918861775" y="0" width="0.17315655008369335" height="8" fill-opacity="1"></rect></g></g></g><g style="transform: scaleX(1.0153846153846153) translateX(-1px)"><g><rect class="fill-white cursor-pointer" x="0" y="0" width="126.95070918861775" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="126.95070918861775" y="0" width="2.1731565500836934" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="129.12386573870145" y="0" width="0.3321293278125275" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="129.455995066514" y="0" width="0.19469650251079199" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="129.6506915690248" y="0" width="0.13170645758082988" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="129.78239802660562" y="0" width="0.06299004492996212" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="129.84538807153558" y="0" width="0.048674125627697996" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="129.89406219716327" y="0" width="0.02290547088362259" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="129.91696766804688" y="0" width="0.020042287023169764" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="129.93700995507004" y="0" width="0.020042287023169764" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="129.9570522420932" y="0" width="0.011452735441811294" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="129.96850497753502" y="0" width="0.005726367720905647" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="129.97423134525593" y="0" width="0.005726367720905647" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="129.97995771297684" y="0" width="0.005726367720905647" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="129.98568408069775" y="0" width="0.0028631838604528236" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="129.9885472645582" y="0" width="0.0028631838604528236" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="129.99141044841866" y="0" width="0.0028631838604528236" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="129.99427363227912" y="0" width="0.0028631838604528236" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="129.99713681613957" y="0" width="0.0028631838604528236" height="28" fill-opacity="0"></rect></g></g></svg> <div class="relative font-light text-gray-400" style="height: 10px; width: 130px;"><div class="absolute left-0 max-w-full overflow-hidden text-ellipsis whitespace-nowrap">19 values</div></div></div></div></div> <div class="absolute right-0 top-0 z-10 h-full w-1 cursor-col-resize hover:bg-indigo-100 active:bg-indigo-500 dark:hover:bg-indigo-800 dark:active:bg-indigo-600/80"><div class="absolute right-0 top-0 h-full w-1"></div> </div> </th><th class="h-full max-w-sm p-2 text-left relative w-auto"><div class="flex h-full flex-col flex-nowrap justify-between"><div><div class="flex items-center justify-between">size <form class="flex flex-col"><button id="asc" class="-mr-1 ml-2 h-[0.4rem] w-[0.8rem] transition ease-in-out"><svg class="-rotate-180 transform text-gray-300 hover:text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 64 256 128" fill="currentColor" aria-hidden="true"><path d="M213.65674,101.657l-80,79.99976a7.99945,7.99945,0,0,1-11.31348,0l-80-79.99976A8,8,0,0,1,48,88H208a8,8,0,0,1,5.65674,13.657Z"></path></svg></button> <button id="desc" class="-mr-1 ml-2 h-[0.4rem] w-[0.8rem] transition ease-in-out"><svg class="text-gray-300 hover:text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 64 256 128" fill="currentColor" aria-hidden="true"><path d="M213.65674,101.657l-80,79.99976a7.99945,7.99945,0,0,1-11.31348,0l-80-79.99976A8,8,0,0,1,48,88H208a8,8,0,0,1,5.65674,13.657Z"></path></svg></button></form></div> <div class="mb-2 whitespace-nowrap text-xs font-normal text-gray-500"><span>string</span><span class="italic text-gray-400 before:mx-1 before:content-['·']">lengths</span></div></div> <div><div class="" style="height: 40px; padding-top: 2px"><svg width="130" height="28"><g><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="0" y="0" width="42" height="30" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="44" y="19.05936226998174" width="42" height="10.94063773001826" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="88" y="25" width="42" height="5" fill-opacity="1"></rect></g><rect class="fill-white dark:fill-gray-900" x="0" y="26" width="130" height="2" stroke-opacity="1"></rect><line class="stroke-gray-100 dark:stroke-gray-500/20" x1="0" y1="27.5" x2="130" y2="27.5" stroke-opacity="1"></line><g><rect class="fill-indigo-500 cursor-pointer" x="-1" y="0" width="44" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="43" y="0" width="44" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="87" y="0" width="44" height="30" fill-opacity="0"></rect></g></svg> <div class="relative font-light text-gray-400" style="height: 10px; width: 130px;"><div class="absolute left-0 overflow-hidden text-ellipsis whitespace-nowrap" style="max-width: 60px">4</div> <div class="absolute overflow-hidden text-ellipsis whitespace-nowrap" style="right: 0px; max-width: 60px">6</div> </div></div></div></div> <div class="absolute right-0 top-0 z-10 h-full w-1 cursor-col-resize hover:bg-indigo-100 active:bg-indigo-500 dark:hover:bg-indigo-800 dark:active:bg-indigo-600/80"><div class="absolute right-0 top-0 h-full w-1"></div> </div> </th><th class="h-full max-w-sm p-2 text-left relative w-auto"><div class="flex h-full flex-col flex-nowrap justify-between"><div><div class="flex items-center justify-between">content <form class="flex flex-col"><button id="asc" class="-mr-1 ml-2 h-[0.4rem] w-[0.8rem] transition ease-in-out"><svg class="-rotate-180 transform text-gray-300 hover:text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 64 256 128" fill="currentColor" aria-hidden="true"><path d="M213.65674,101.657l-80,79.99976a7.99945,7.99945,0,0,1-11.31348,0l-80-79.99976A8,8,0,0,1,48,88H208a8,8,0,0,1,5.65674,13.657Z"></path></svg></button> <button id="desc" class="-mr-1 ml-2 h-[0.4rem] w-[0.8rem] transition ease-in-out"><svg class="text-gray-300 hover:text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 64 256 128" fill="currentColor" aria-hidden="true"><path d="M213.65674,101.657l-80,79.99976a7.99945,7.99945,0,0,1-11.31348,0l-80-79.99976A8,8,0,0,1,48,88H208a8,8,0,0,1,5.65674,13.657Z"></path></svg></button></form></div> <div class="mb-2 whitespace-nowrap text-xs font-normal text-gray-500"><span>string</span><span class="italic text-gray-400 before:mx-1 before:content-['·']">lengths</span></div></div> <div><div class="" style="height: 40px; padding-top: 2px"><svg width="130" height="28"><g><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="0" y="0" width="11.2" height="30" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="13.2" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="26.4" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="39.599999999999994" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="52.8" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="66" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="79.19999999999999" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="92.39999999999999" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="105.6" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="118.8" y="25" width="11.2" height="5" fill-opacity="1"></rect></g><rect class="fill-white dark:fill-gray-900" x="0" y="26" width="130" height="2" stroke-opacity="1"></rect><line class="stroke-gray-100 dark:stroke-gray-500/20" x1="0" y1="27.5" x2="130" y2="27.5" stroke-opacity="1"></line><g><rect class="fill-indigo-500 cursor-pointer" x="-1" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="12.2" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="25.4" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="38.599999999999994" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="51.8" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="65" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="78.19999999999999" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="91.39999999999999" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="104.6" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="117.8" y="0" width="13.2" height="30" fill-opacity="0"></rect></g></svg> <div class="relative font-light text-gray-400" style="height: 10px; width: 130px;"><div class="absolute left-0 overflow-hidden text-ellipsis whitespace-nowrap" style="max-width: 60px">766</div> <div class="absolute overflow-hidden text-ellipsis whitespace-nowrap" style="right: 0px; max-width: 60px">896k</div> </div></div></div></div> <div class="absolute right-0 top-0 z-10 h-full w-1 cursor-col-resize hover:bg-indigo-100 active:bg-indigo-500 dark:hover:bg-indigo-800 dark:active:bg-indigo-600/80"><div class="absolute right-0 top-0 h-full w-1"></div> </div> </th><th class="h-full max-w-sm p-2 text-left relative w-auto"><div class="flex h-full flex-col flex-nowrap justify-between"><div><div class="flex items-center justify-between">license <form class="flex flex-col"><button id="asc" class="-mr-1 ml-2 h-[0.4rem] w-[0.8rem] transition ease-in-out"><svg class="-rotate-180 transform text-gray-300 hover:text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 64 256 128" fill="currentColor" aria-hidden="true"><path d="M213.65674,101.657l-80,79.99976a7.99945,7.99945,0,0,1-11.31348,0l-80-79.99976A8,8,0,0,1,48,88H208a8,8,0,0,1,5.65674,13.657Z"></path></svg></button> <button id="desc" class="-mr-1 ml-2 h-[0.4rem] w-[0.8rem] transition ease-in-out"><svg class="text-gray-300 hover:text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 64 256 128" fill="currentColor" aria-hidden="true"><path d="M213.65674,101.657l-80,79.99976a7.99945,7.99945,0,0,1-11.31348,0l-80-79.99976A8,8,0,0,1,48,88H208a8,8,0,0,1,5.65674,13.657Z"></path></svg></button></form></div> <div class="mb-2 whitespace-nowrap text-xs font-normal text-gray-500"><span>string</span><span class="italic text-gray-400 before:mx-1 before:content-['·']">classes</span></div></div> <div><div class="" style="height: 40px; padding-top: 2px"><svg width="130" height="28"><defs><clipPath id="rounded-bar"><rect x="0" y="0" width="130" height="8" rx="4"></rect></clipPath><pattern id="hatching" patternUnits="userSpaceOnUse" patternTransform="rotate(-45)" height="1" width="5"><line y1="0" class="stroke-gray-400 dark:stroke-gray-500/80" stroke-width="3" y2="1" x1="2" x2="2"></line></pattern><pattern id="hatching-faded" patternUnits="userSpaceOnUse" patternTransform="rotate(-45)" height="1" width="5"><line y1="0" class="stroke-gray-100 dark:stroke-gray-500/20" stroke-width="3" y2="1" x1="2" x2="2"></line></pattern></defs><g height="8" style="transform: translateY(20px)" clip-path="url(#rounded-bar)"><g style="transform: scaleX(1.0153846153846153) translateX(-1px)"><g><rect class="fill-indigo-500 dark:fill-indigo-600/80" x="1" y="0" width="38.402387454849794" height="8" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" x="41.402387454849794" y="0" width="21.194652453528324" height="8" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" x="64.59703990837812" y="0" width="21.134525592458814" height="8" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" x="87.73156550083694" y="0" width="11.376794996035592" height="8" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" x="101.10836049687254" y="0" width="11.127698000176196" height="8" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" x="114.23605849704873" y="0" width="4.548101488855607" height="8" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" x="120.78415998590434" y="0" width="1.4787683904501807" height="8" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" x="124.26292837635452" y="0" width="0.26764161747863646" height="8" fill-opacity="1"></rect></g></g></g><g style="transform: scaleX(1.0153846153846153) translateX(-1px)"><g><rect class="fill-white cursor-pointer" x="0" y="0" width="40.402387454849794" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="40.402387454849794" y="0" width="23.194652453528324" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="63.59703990837812" y="0" width="23.134525592458814" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="86.73156550083694" y="0" width="13.376794996035592" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="100.10836049687254" y="0" width="13.127698000176196" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="113.23605849704873" y="0" width="6.548101488855607" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="119.78415998590434" y="0" width="3.4787683904501807" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="123.26292837635452" y="0" width="2.2676416174786365" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="125.53056999383315" y="0" width="1.6320148004581094" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="127.16258479429126" y="0" width="0.9362611223680732" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="128.09884591665934" y="0" width="0.7730596423222624" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="128.8719055589816" y="0" width="0.4638357853933574" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="129.33574134437498" y="0" width="0.38366663730067835" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="129.71940798167566" y="0" width="0.2204651572548674" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="129.93987313893052" y="0" width="0.06012686106950929" height="28" fill-opacity="0"></rect></g></g></svg> <div class="relative font-light text-gray-400" style="height: 10px; width: 130px;"><div class="absolute left-0 max-w-full overflow-hidden text-ellipsis whitespace-nowrap">15 values</div></div></div></div></div> <div class="absolute right-0 top-0 z-10 h-full w-1 cursor-col-resize hover:bg-indigo-100 active:bg-indigo-500 dark:hover:bg-indigo-800 dark:active:bg-indigo-600/80"><div class="absolute right-0 top-0 h-full w-1"></div> </div> </th><th class="h-full max-w-sm p-2 text-left relative w-auto"><div class="flex h-full flex-col flex-nowrap justify-between"><div><div class="flex items-center justify-between">hash <form class="flex flex-col"><button id="asc" class="-mr-1 ml-2 h-[0.4rem] w-[0.8rem] transition ease-in-out"><svg class="-rotate-180 transform text-gray-300 hover:text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 64 256 128" fill="currentColor" aria-hidden="true"><path d="M213.65674,101.657l-80,79.99976a7.99945,7.99945,0,0,1-11.31348,0l-80-79.99976A8,8,0,0,1,48,88H208a8,8,0,0,1,5.65674,13.657Z"></path></svg></button> <button id="desc" class="-mr-1 ml-2 h-[0.4rem] w-[0.8rem] transition ease-in-out"><svg class="text-gray-300 hover:text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 64 256 128" fill="currentColor" aria-hidden="true"><path d="M213.65674,101.657l-80,79.99976a7.99945,7.99945,0,0,1-11.31348,0l-80-79.99976A8,8,0,0,1,48,88H208a8,8,0,0,1,5.65674,13.657Z"></path></svg></button></form></div> <div class="mb-2 whitespace-nowrap text-xs font-normal text-gray-500"><span>int64</span></div></div> <div><div class="" style="height: 40px; padding-top: 2px"><svg width="130" height="28"><g><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="0" y="0.5343609505459206" width="11.2" height="29.46563904945408" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="13.2" y="0" width="11.2" height="30" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="26.4" y="1.063155641190324" width="11.2" height="28.936844358809676" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="39.599999999999994" y="1.3080710768572033" width="11.2" height="28.691928923142797" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="52.8" y="1.2524084778420033" width="11.2" height="28.747591522157997" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="66" y="0.1836865767501621" width="11.2" height="29.816313423249838" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="79.19999999999999" y="0.33954185399272063" width="11.2" height="29.66045814600728" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="92.39999999999999" y="1.202312138728324" width="11.2" height="28.797687861271676" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="105.6" y="0.4230357525155206" width="11.2" height="29.57696424748448" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="118.8" y="0.9629629629629619" width="11.2" height="29.037037037037038" fill-opacity="1"></rect></g><rect class="fill-white dark:fill-gray-900" x="0" y="26" width="130" height="2" stroke-opacity="1"></rect><line class="stroke-gray-100 dark:stroke-gray-500/20" x1="0" y1="27.5" x2="130" y2="27.5" stroke-opacity="1"></line><g><rect class="fill-indigo-500 cursor-pointer" x="-1" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="12.2" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="25.4" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="38.599999999999994" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="51.8" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="65" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="78.19999999999999" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="91.39999999999999" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="104.6" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="117.8" y="0" width="13.2" height="30" fill-opacity="0"></rect></g></svg> <div class="relative font-light text-gray-400" style="height: 10px; width: 130px;"><div class="absolute left-0 overflow-hidden text-ellipsis whitespace-nowrap" style="max-width: 60px">-9,223,277,421,539,062,000</div> <div class="absolute overflow-hidden text-ellipsis whitespace-nowrap" style="right: 0px; max-width: 60px">9,223,102,107B</div> </div></div></div></div> <div class="absolute right-0 top-0 z-10 h-full w-1 cursor-col-resize hover:bg-indigo-100 active:bg-indigo-500 dark:hover:bg-indigo-800 dark:active:bg-indigo-600/80"><div class="absolute right-0 top-0 h-full w-1"></div> </div> </th><th class="h-full max-w-sm p-2 text-left relative w-auto"><div class="flex h-full flex-col flex-nowrap justify-between"><div><div class="flex items-center justify-between">line_mean <form class="flex flex-col"><button id="asc" class="-mr-1 ml-2 h-[0.4rem] w-[0.8rem] transition ease-in-out"><svg class="-rotate-180 transform text-gray-300 hover:text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 64 256 128" fill="currentColor" aria-hidden="true"><path d="M213.65674,101.657l-80,79.99976a7.99945,7.99945,0,0,1-11.31348,0l-80-79.99976A8,8,0,0,1,48,88H208a8,8,0,0,1,5.65674,13.657Z"></path></svg></button> <button id="desc" class="-mr-1 ml-2 h-[0.4rem] w-[0.8rem] transition ease-in-out"><svg class="text-gray-300 hover:text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 64 256 128" fill="currentColor" aria-hidden="true"><path d="M213.65674,101.657l-80,79.99976a7.99945,7.99945,0,0,1-11.31348,0l-80-79.99976A8,8,0,0,1,48,88H208a8,8,0,0,1,5.65674,13.657Z"></path></svg></button></form></div> <div class="mb-2 whitespace-nowrap text-xs font-normal text-gray-500"><span>float64</span></div></div> <div><div class="" style="height: 40px; padding-top: 2px"><svg width="130" height="28"><g><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="0" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="13.2" y="21.15271627132021" width="11.2" height="8.847283728679791" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="26.4" y="0" width="11.2" height="30" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="39.599999999999994" y="9.156487043451573" width="11.2" height="20.843512956548427" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="52.8" y="23.039417722629018" width="11.2" height="6.960582277370983" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="66" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="79.19999999999999" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="92.39999999999999" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="105.6" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="118.8" y="25" width="11.2" height="5" fill-opacity="1"></rect></g><rect class="fill-white dark:fill-gray-900" x="0" y="26" width="130" height="2" stroke-opacity="1"></rect><line class="stroke-gray-100 dark:stroke-gray-500/20" x1="0" y1="27.5" x2="130" y2="27.5" stroke-opacity="1"></line><g><rect class="fill-indigo-500 cursor-pointer" x="-1" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="12.2" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="25.4" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="38.599999999999994" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="51.8" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="65" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="78.19999999999999" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="91.39999999999999" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="104.6" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="117.8" y="0" width="13.2" height="30" fill-opacity="0"></rect></g></svg> <div class="relative font-light text-gray-400" style="height: 10px; width: 130px;"><div class="absolute left-0 overflow-hidden text-ellipsis whitespace-nowrap" style="max-width: 60px">6.51</div> <div class="absolute overflow-hidden text-ellipsis whitespace-nowrap" style="right: 0px; max-width: 60px">99.9</div> </div></div></div></div> <div class="absolute right-0 top-0 z-10 h-full w-1 cursor-col-resize hover:bg-indigo-100 active:bg-indigo-500 dark:hover:bg-indigo-800 dark:active:bg-indigo-600/80"><div class="absolute right-0 top-0 h-full w-1"></div> </div> </th><th class="h-full max-w-sm p-2 text-left relative w-auto"><div class="flex h-full flex-col flex-nowrap justify-between"><div><div class="flex items-center justify-between">line_max <form class="flex flex-col"><button id="asc" class="-mr-1 ml-2 h-[0.4rem] w-[0.8rem] transition ease-in-out"><svg class="-rotate-180 transform text-gray-300 hover:text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 64 256 128" fill="currentColor" aria-hidden="true"><path d="M213.65674,101.657l-80,79.99976a7.99945,7.99945,0,0,1-11.31348,0l-80-79.99976A8,8,0,0,1,48,88H208a8,8,0,0,1,5.65674,13.657Z"></path></svg></button> <button id="desc" class="-mr-1 ml-2 h-[0.4rem] w-[0.8rem] transition ease-in-out"><svg class="text-gray-300 hover:text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 64 256 128" fill="currentColor" aria-hidden="true"><path d="M213.65674,101.657l-80,79.99976a7.99945,7.99945,0,0,1-11.31348,0l-80-79.99976A8,8,0,0,1,48,88H208a8,8,0,0,1,5.65674,13.657Z"></path></svg></button></form></div> <div class="mb-2 whitespace-nowrap text-xs font-normal text-gray-500"><span>int64</span></div></div> <div><div class="" style="height: 40px; padding-top: 2px"><svg width="130" height="28"><g><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="0" y="0" width="11.2" height="30" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="13.2" y="20.35524881946967" width="11.2" height="9.644751180530331" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="26.4" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="39.599999999999994" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="52.8" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="66" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="79.19999999999999" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="92.39999999999999" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="105.6" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="118.8" y="25" width="11.2" height="5" fill-opacity="1"></rect></g><rect class="fill-white dark:fill-gray-900" x="0" y="26" width="130" height="2" stroke-opacity="1"></rect><line class="stroke-gray-100 dark:stroke-gray-500/20" x1="0" y1="27.5" x2="130" y2="27.5" stroke-opacity="1"></line><g><rect class="fill-indigo-500 cursor-pointer" x="-1" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="12.2" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="25.4" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="38.599999999999994" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="51.8" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="65" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="78.19999999999999" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="91.39999999999999" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="104.6" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="117.8" y="0" width="13.2" height="30" fill-opacity="0"></rect></g></svg> <div class="relative font-light text-gray-400" style="height: 10px; width: 130px;"><div class="absolute left-0 overflow-hidden text-ellipsis whitespace-nowrap" style="max-width: 60px">32</div> <div class="absolute overflow-hidden text-ellipsis whitespace-nowrap" style="right: 0px; max-width: 60px">997</div> </div></div></div></div> <div class="absolute right-0 top-0 z-10 h-full w-1 cursor-col-resize hover:bg-indigo-100 active:bg-indigo-500 dark:hover:bg-indigo-800 dark:active:bg-indigo-600/80"><div class="absolute right-0 top-0 h-full w-1"></div> </div> </th><th class="h-full max-w-sm p-2 text-left relative w-auto"><div class="flex h-full flex-col flex-nowrap justify-between"><div><div class="flex items-center justify-between">alpha_frac <form class="flex flex-col"><button id="asc" class="-mr-1 ml-2 h-[0.4rem] w-[0.8rem] transition ease-in-out"><svg class="-rotate-180 transform text-gray-300 hover:text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 64 256 128" fill="currentColor" aria-hidden="true"><path d="M213.65674,101.657l-80,79.99976a7.99945,7.99945,0,0,1-11.31348,0l-80-79.99976A8,8,0,0,1,48,88H208a8,8,0,0,1,5.65674,13.657Z"></path></svg></button> <button id="desc" class="-mr-1 ml-2 h-[0.4rem] w-[0.8rem] transition ease-in-out"><svg class="text-gray-300 hover:text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 64 256 128" fill="currentColor" aria-hidden="true"><path d="M213.65674,101.657l-80,79.99976a7.99945,7.99945,0,0,1-11.31348,0l-80-79.99976A8,8,0,0,1,48,88H208a8,8,0,0,1,5.65674,13.657Z"></path></svg></button></form></div> <div class="mb-2 whitespace-nowrap text-xs font-normal text-gray-500"><span>float64</span></div></div> <div><div class="" style="height: 40px; padding-top: 2px"><svg width="130" height="28"><g><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="0" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="13.2" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="26.4" y="24.412676220435745" width="11.2" height="5.5873237795642545" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="39.599999999999994" y="17.718047302807875" width="11.2" height="12.281952697192123" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="52.8" y="0" width="11.2" height="30" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="66" y="2.39461726668997" width="11.2" height="27.60538273331003" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="79.19999999999999" y="17.65746242572527" width="11.2" height="12.34253757427473" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="92.39999999999999" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="105.6" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="118.8" y="25" width="11.2" height="5" fill-opacity="1"></rect></g><rect class="fill-white dark:fill-gray-900" x="0" y="26" width="130" height="2" stroke-opacity="1"></rect><line class="stroke-gray-100 dark:stroke-gray-500/20" x1="0" y1="27.5" x2="130" y2="27.5" stroke-opacity="1"></line><g><rect class="fill-indigo-500 cursor-pointer" x="-1" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="12.2" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="25.4" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="38.599999999999994" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="51.8" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="65" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="78.19999999999999" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="91.39999999999999" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="104.6" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="117.8" y="0" width="13.2" height="30" fill-opacity="0"></rect></g></svg> <div class="relative font-light text-gray-400" style="height: 10px; width: 130px;"><div class="absolute left-0 overflow-hidden text-ellipsis whitespace-nowrap" style="max-width: 60px">0.25</div> <div class="absolute overflow-hidden text-ellipsis whitespace-nowrap" style="right: 0px; max-width: 60px">0.96</div> </div></div></div></div> <div class="absolute right-0 top-0 z-10 h-full w-1 cursor-col-resize hover:bg-indigo-100 active:bg-indigo-500 dark:hover:bg-indigo-800 dark:active:bg-indigo-600/80"><div class="absolute right-0 top-0 h-full w-1"></div> </div> </th><th class="h-full max-w-sm p-2 text-left relative w-auto"><div class="flex h-full flex-col flex-nowrap justify-between"><div><div class="flex items-center justify-between">autogenerated <form class="flex flex-col"><button id="asc" class="-mr-1 ml-2 h-[0.4rem] w-[0.8rem] transition ease-in-out"><svg class="-rotate-180 transform text-gray-300 hover:text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 64 256 128" fill="currentColor" aria-hidden="true"><path d="M213.65674,101.657l-80,79.99976a7.99945,7.99945,0,0,1-11.31348,0l-80-79.99976A8,8,0,0,1,48,88H208a8,8,0,0,1,5.65674,13.657Z"></path></svg></button> <button id="desc" class="-mr-1 ml-2 h-[0.4rem] w-[0.8rem] transition ease-in-out"><svg class="text-gray-300 hover:text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 64 256 128" fill="currentColor" aria-hidden="true"><path d="M213.65674,101.657l-80,79.99976a7.99945,7.99945,0,0,1-11.31348,0l-80-79.99976A8,8,0,0,1,48,88H208a8,8,0,0,1,5.65674,13.657Z"></path></svg></button></form></div> <div class="mb-2 whitespace-nowrap text-xs font-normal text-gray-500"><span>bool</span></div></div> <div><div class="" style="height: 40px; padding-top: 2px"><svg width="130" height="28"><defs><clipPath id="rounded-bar"><rect x="0" y="0" width="130" height="8" rx="4"></rect></clipPath><pattern id="hatching" patternUnits="userSpaceOnUse" patternTransform="rotate(-45)" height="1" width="5"><line y1="0" class="stroke-gray-400 dark:stroke-gray-500/80" stroke-width="3" y2="1" x1="2" x2="2"></line></pattern><pattern id="hatching-faded" patternUnits="userSpaceOnUse" patternTransform="rotate(-45)" height="1" width="5"><line y1="0" class="stroke-gray-100 dark:stroke-gray-500/20" stroke-width="3" y2="1" x1="2" x2="2"></line></pattern></defs><g height="8" style="transform: translateY(20px)" clip-path="url(#rounded-bar)"><g style="transform: scaleX(1.0153846153846153) translateX(-1px)"><g><rect class="fill-indigo-500 dark:fill-indigo-600/80" x="1" y="0" width="128" height="8" fill-opacity="1"></rect></g></g></g><g style="transform: scaleX(1.0153846153846153) translateX(-1px)"><g><rect class="fill-white cursor-pointer" x="0" y="0" width="130" height="28" fill-opacity="0"></rect></g></g></svg> <div class="relative font-light text-gray-400" style="height: 10px; width: 130px;"><div class="absolute left-0 max-w-full overflow-hidden text-ellipsis whitespace-nowrap">1 class</div></div></div></div></div> <div class="absolute right-0 top-0 z-10 h-full w-1 cursor-col-resize hover:bg-indigo-100 active:bg-indigo-500 dark:hover:bg-indigo-800 dark:active:bg-indigo-600/80"><div class="absolute right-0 top-0 h-full w-1"></div> </div> </th><th class="h-full max-w-sm p-2 text-left relative w-auto"><div class="flex h-full flex-col flex-nowrap justify-between"><div><div class="flex items-center justify-between">ratio <form class="flex flex-col"><button id="asc" class="-mr-1 ml-2 h-[0.4rem] w-[0.8rem] transition ease-in-out"><svg class="-rotate-180 transform text-gray-300 hover:text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 64 256 128" fill="currentColor" aria-hidden="true"><path d="M213.65674,101.657l-80,79.99976a7.99945,7.99945,0,0,1-11.31348,0l-80-79.99976A8,8,0,0,1,48,88H208a8,8,0,0,1,5.65674,13.657Z"></path></svg></button> <button id="desc" class="-mr-1 ml-2 h-[0.4rem] w-[0.8rem] transition ease-in-out"><svg class="text-gray-300 hover:text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 64 256 128" fill="currentColor" aria-hidden="true"><path d="M213.65674,101.657l-80,79.99976a7.99945,7.99945,0,0,1-11.31348,0l-80-79.99976A8,8,0,0,1,48,88H208a8,8,0,0,1,5.65674,13.657Z"></path></svg></button></form></div> <div class="mb-2 whitespace-nowrap text-xs font-normal text-gray-500"><span>float64</span></div></div> <div><div class="" style="height: 40px; padding-top: 2px"><svg width="130" height="28"><g><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="0" y="24.015794523581075" width="11.2" height="5.984205476418924" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="13.2" y="0" width="11.2" height="30" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="26.4" y="10.58019041995719" width="11.2" height="19.41980958004281" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="39.599999999999994" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="52.8" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="66" y="26" width="11.2" height="4" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="79.19999999999999" y="26" width="11.2" height="4" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="92.39999999999999" y="26" width="11.2" height="4" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="105.6" y="26" width="11.2" height="4" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="118.8" y="25" width="11.2" height="5" fill-opacity="1"></rect></g><rect class="fill-white dark:fill-gray-900" x="0" y="26" width="130" height="2" stroke-opacity="1"></rect><line class="stroke-gray-100 dark:stroke-gray-500/20" x1="0" y1="27.5" x2="130" y2="27.5" stroke-opacity="1"></line><g><rect class="fill-indigo-500 cursor-pointer" x="-1" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="12.2" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="25.4" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="38.599999999999994" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="51.8" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="65" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="78.19999999999999" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="91.39999999999999" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="104.6" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="117.8" y="0" width="13.2" height="30" fill-opacity="0"></rect></g></svg> <div class="relative font-light text-gray-400" style="height: 10px; width: 130px;"><div class="absolute left-0 overflow-hidden text-ellipsis whitespace-nowrap" style="max-width: 60px">1.5</div> <div class="absolute overflow-hidden text-ellipsis whitespace-nowrap" style="right: 0px; max-width: 60px">13.6</div> </div></div></div></div> <div class="absolute right-0 top-0 z-10 h-full w-1 cursor-col-resize hover:bg-indigo-100 active:bg-indigo-500 dark:hover:bg-indigo-800 dark:active:bg-indigo-600/80"><div class="absolute right-0 top-0 h-full w-1"></div> </div> </th><th class="h-full max-w-sm p-2 text-left relative w-auto"><div class="flex h-full flex-col flex-nowrap justify-between"><div><div class="flex items-center justify-between">config_test <form class="flex flex-col"><button id="asc" class="-mr-1 ml-2 h-[0.4rem] w-[0.8rem] transition ease-in-out"><svg class="-rotate-180 transform text-gray-300 hover:text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 64 256 128" fill="currentColor" aria-hidden="true"><path d="M213.65674,101.657l-80,79.99976a7.99945,7.99945,0,0,1-11.31348,0l-80-79.99976A8,8,0,0,1,48,88H208a8,8,0,0,1,5.65674,13.657Z"></path></svg></button> <button id="desc" class="-mr-1 ml-2 h-[0.4rem] w-[0.8rem] transition ease-in-out"><svg class="text-gray-300 hover:text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 64 256 128" fill="currentColor" aria-hidden="true"><path d="M213.65674,101.657l-80,79.99976a7.99945,7.99945,0,0,1-11.31348,0l-80-79.99976A8,8,0,0,1,48,88H208a8,8,0,0,1,5.65674,13.657Z"></path></svg></button></form></div> <div class="mb-2 whitespace-nowrap text-xs font-normal text-gray-500"><span>bool</span></div></div> <div><div class="" style="height: 40px; padding-top: 2px"><svg width="130" height="28"><defs><clipPath id="rounded-bar"><rect x="0" y="0" width="130" height="8" rx="4"></rect></clipPath><pattern id="hatching" patternUnits="userSpaceOnUse" patternTransform="rotate(-45)" height="1" width="5"><line y1="0" class="stroke-gray-400 dark:stroke-gray-500/80" stroke-width="3" y2="1" x1="2" x2="2"></line></pattern><pattern id="hatching-faded" patternUnits="userSpaceOnUse" patternTransform="rotate(-45)" height="1" width="5"><line y1="0" class="stroke-gray-100 dark:stroke-gray-500/20" stroke-width="3" y2="1" x1="2" x2="2"></line></pattern></defs><g height="8" style="transform: translateY(20px)" clip-path="url(#rounded-bar)"><g style="transform: scaleX(1.0153846153846153) translateX(-1px)"><g><rect class="fill-indigo-500 dark:fill-indigo-600/80" x="1" y="0" width="113.68694388159633" height="8" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" x="116.68694388159633" y="0" width="12.313056118403663" height="8" fill-opacity="1"></rect></g></g></g><g style="transform: scaleX(1.0153846153846153) translateX(-1px)"><g><rect class="fill-white cursor-pointer" x="0" y="0" width="115.68694388159633" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="115.68694388159633" y="0" width="14.313056118403663" height="28" fill-opacity="0"></rect></g></g></svg> <div class="relative font-light text-gray-400" style="height: 10px; width: 130px;"><div class="absolute left-0 max-w-full overflow-hidden text-ellipsis whitespace-nowrap">2 classes</div></div></div></div></div> <div class="absolute right-0 top-0 z-10 h-full w-1 cursor-col-resize hover:bg-indigo-100 active:bg-indigo-500 dark:hover:bg-indigo-800 dark:active:bg-indigo-600/80"><div class="absolute right-0 top-0 h-full w-1"></div> </div> </th><th class="h-full max-w-sm p-2 text-left relative w-auto"><div class="flex h-full flex-col flex-nowrap justify-between"><div><div class="flex items-center justify-between">has_no_keywords <form class="flex flex-col"><button id="asc" class="-mr-1 ml-2 h-[0.4rem] w-[0.8rem] transition ease-in-out"><svg class="-rotate-180 transform text-gray-300 hover:text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 64 256 128" fill="currentColor" aria-hidden="true"><path d="M213.65674,101.657l-80,79.99976a7.99945,7.99945,0,0,1-11.31348,0l-80-79.99976A8,8,0,0,1,48,88H208a8,8,0,0,1,5.65674,13.657Z"></path></svg></button> <button id="desc" class="-mr-1 ml-2 h-[0.4rem] w-[0.8rem] transition ease-in-out"><svg class="text-gray-300 hover:text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 64 256 128" fill="currentColor" aria-hidden="true"><path d="M213.65674,101.657l-80,79.99976a7.99945,7.99945,0,0,1-11.31348,0l-80-79.99976A8,8,0,0,1,48,88H208a8,8,0,0,1,5.65674,13.657Z"></path></svg></button></form></div> <div class="mb-2 whitespace-nowrap text-xs font-normal text-gray-500"><span>bool</span></div></div> <div><div class="" style="height: 40px; padding-top: 2px"><svg width="130" height="28"><defs><clipPath id="rounded-bar"><rect x="0" y="0" width="130" height="8" rx="4"></rect></clipPath><pattern id="hatching" patternUnits="userSpaceOnUse" patternTransform="rotate(-45)" height="1" width="5"><line y1="0" class="stroke-gray-400 dark:stroke-gray-500/80" stroke-width="3" y2="1" x1="2" x2="2"></line></pattern><pattern id="hatching-faded" patternUnits="userSpaceOnUse" patternTransform="rotate(-45)" height="1" width="5"><line y1="0" class="stroke-gray-100 dark:stroke-gray-500/20" stroke-width="3" y2="1" x1="2" x2="2"></line></pattern></defs><g height="8" style="transform: translateY(20px)" clip-path="url(#rounded-bar)"><g style="transform: scaleX(1.0153846153846153) translateX(-1px)"><g><rect class="fill-indigo-500 dark:fill-indigo-600/80" x="1" y="0" width="127.14390802572461" height="8" fill-opacity="1"></rect></g></g></g><g style="transform: scaleX(1.0153846153846153) translateX(-1px)"><g><rect class="fill-white cursor-pointer" x="0" y="0" width="129.1439080257246" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="129.1439080257246" y="0" width="0.8560919742753943" height="28" fill-opacity="0"></rect></g></g></svg> <div class="relative font-light text-gray-400" style="height: 10px; width: 130px;"><div class="absolute left-0 max-w-full overflow-hidden text-ellipsis whitespace-nowrap">2 classes</div></div></div></div></div> <div class="absolute right-0 top-0 z-10 h-full w-1 cursor-col-resize hover:bg-indigo-100 active:bg-indigo-500 dark:hover:bg-indigo-800 dark:active:bg-indigo-600/80"><div class="absolute right-0 top-0 h-full w-1"></div> </div> </th><th class="h-full max-w-sm p-2 text-left relative w-auto"><div class="flex h-full flex-col flex-nowrap justify-between"><div><div class="flex items-center justify-between">few_assignments <form class="flex flex-col"><button id="asc" class="-mr-1 ml-2 h-[0.4rem] w-[0.8rem] transition ease-in-out"><svg class="-rotate-180 transform text-gray-300 hover:text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 64 256 128" fill="currentColor" aria-hidden="true"><path d="M213.65674,101.657l-80,79.99976a7.99945,7.99945,0,0,1-11.31348,0l-80-79.99976A8,8,0,0,1,48,88H208a8,8,0,0,1,5.65674,13.657Z"></path></svg></button> <button id="desc" class="-mr-1 ml-2 h-[0.4rem] w-[0.8rem] transition ease-in-out"><svg class="text-gray-300 hover:text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 64 256 128" fill="currentColor" aria-hidden="true"><path d="M213.65674,101.657l-80,79.99976a7.99945,7.99945,0,0,1-11.31348,0l-80-79.99976A8,8,0,0,1,48,88H208a8,8,0,0,1,5.65674,13.657Z"></path></svg></button></form></div> <div class="mb-2 whitespace-nowrap text-xs font-normal text-gray-500"><span>bool</span></div></div> <div><div class="" style="height: 40px; padding-top: 2px"><svg width="130" height="28"><defs><clipPath id="rounded-bar"><rect x="0" y="0" width="130" height="8" rx="4"></rect></clipPath><pattern id="hatching" patternUnits="userSpaceOnUse" patternTransform="rotate(-45)" height="1" width="5"><line y1="0" class="stroke-gray-400 dark:stroke-gray-500/80" stroke-width="3" y2="1" x1="2" x2="2"></line></pattern><pattern id="hatching-faded" patternUnits="userSpaceOnUse" patternTransform="rotate(-45)" height="1" width="5"><line y1="0" class="stroke-gray-100 dark:stroke-gray-500/20" stroke-width="3" y2="1" x1="2" x2="2"></line></pattern></defs><g height="8" style="transform: translateY(20px)" clip-path="url(#rounded-bar)"><g style="transform: scaleX(1.0153846153846153) translateX(-1px)"><g><rect class="fill-indigo-500 dark:fill-indigo-600/80" x="1" y="0" width="128" height="8" fill-opacity="1"></rect></g></g></g><g style="transform: scaleX(1.0153846153846153) translateX(-1px)"><g><rect class="fill-white cursor-pointer" x="0" y="0" width="130" height="28" fill-opacity="0"></rect></g></g></svg> <div class="relative font-light text-gray-400" style="height: 10px; width: 130px;"><div class="absolute left-0 max-w-full overflow-hidden text-ellipsis whitespace-nowrap">1 class</div></div></div></div></div> <div class="absolute right-0 top-0 z-10 h-full w-1 cursor-col-resize hover:bg-indigo-100 active:bg-indigo-500 dark:hover:bg-indigo-800 dark:active:bg-indigo-600/80"><div class="absolute right-0 top-0 h-full w-1"></div> </div> </th></tr></thead> <tbody class="h-16 overflow-scroll"><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45100"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Tilo15/PhotoFiddle2</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">PF2/Tools/HueEqualiser.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">5526</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">import cv2 import numpy import Tool class HueEqualiser(Tool.Tool): def on_init(self): self.id = "hueequaliser" self.name = "Hue Equaliser" self.icon_path = "ui/PF2_Icons/HueEqualiser.png" self.properties = [ Tool.Property("header", "Hue Equaliser", "Header", None, has_toggle=False, has_button=False), Tool.Property("bleed", "Hue Bleed", "Slider", 0.5, max=2.0, min=0.01), Tool.Property("neighbour_bleed", "Neighbour Bleed", "Slider", 0.25, max=2.0, min=0.0), # Red Tool.Property("header_red", "Red", "Header", None, has_toggle=False, has_button=False), Tool.Property("red_value", "Value", "Slider", 0, max=50, min=-50), Tool.Property("red_saturation", "Saturation", "Slider", 0, max=50, min=-50), # Yellow Tool.Property("header_yellow", "Yellow", "Header", None, has_toggle=False, has_button=False), Tool.Property("yellow_value", "Value", "Slider", 0, max=50, min=-50), Tool.Property("yellow_saturation", "Saturation", "Slider", 0, max=50, min=-50), # Green Tool.Property("header_green", "Green", "Header", None, has_toggle=False, has_button=False), Tool.Property("green_value", "Value", "Slider", 0, max=50, min=-50), Tool.Property("green_saturation", "Saturation", "Slider", 0, max=50, min=-50), # Cyan Tool.Property("header_cyan", "Cyan", "Header", None, has_toggle=False, has_button=False), Tool.Property("cyan_value", "Value", "Slider", 0, max=50, min=-50), Tool.Property("cyan_saturation", "Saturation", "Slider", 0, max=50, min=-50), # Blue Tool.Property("header_blue", "Blue", "Header", None, has_toggle=False, has_button=False), Tool.Property("blue_value", "Value", "Slider", 0, max=50, min=-50), Tool.Property("blue_saturation", "Saturation", "Slider", 0, max=50, min=-50), # Violet Tool.Property("header_violet", "Violet", "Header", None, has_toggle=False, has_button=False), Tool.Property("violet_value", "Value", "Slider", 0, max=50, min=-50), Tool.Property("violet_saturation", "Saturation", "Slider", 0, max=50, min=-50), ] def on_update(self, image): hues = { "red": 0, "yellow": 60, "green": 120, "cyan": 180, "blue": 240, "violet": 300, "_red": 360, } out = image if(not self.is_default()): bleed = self.props["bleed"].get_value() neighbour_bleed = self.props["neighbour_bleed"].get_value() out = out.astype(numpy.float32) # Convert to HSV colorspace out = cv2.cvtColor(out, cv2.COLOR_BGR2HSV) # Bits per pixel bpp = float(str(image.dtype).replace("uint", "").replace("float", "")) # Pixel value range np = float(2 ** bpp - 1) imhue = out[0:, 0:, 0] imsat = out[0:, 0:, 1] imval = out[0:, 0:, 2] for hue in hues: hsat = self.props["%s_saturation" % hue.replace('_', '')].get_value() hval = self.props["%s_value" % hue.replace('_', '')].get_value() isHue = self._is_hue(imhue, hues[hue], (3.5/bleed)) isHue = self._neighbour_bleed(isHue, neighbour_bleed) imsat = imsat + ((hsat / 10000) * 255) * isHue imval = imval + ((hval / 1000) * np) * isHue # Clip any values out of bounds imval[imval < 0.0] = 0.0 imval[imval > np] = np imsat[imsat < 0.0] = 0.0 imsat[imsat > 1.0] = 1.0 out[0:, 0:, 1] = imsat out[0:, 0:, 2] = imval # Convert back to BGR colorspace out = cv2.cvtColor(out, cv2.COLOR_HSV2BGR) out = out.astype(image.dtype) return out def _is_hue(self, image, hue_value, bleed_value = 3.5): mif = hue_value - 30 mir = hue_value + 30 if (mir > 360): mir = 360 if (mif < 0): mif = 0 bleed = float(360 / bleed_value) icopy = image.copy() print(bleed, mif, mir) if(mif != 0): icopy[icopy < mif - bleed] = 0.0 icopy[icopy > mir + bleed] = 0.0 icopy[(icopy < mif) * (icopy != 0.0)] = (((mif - (icopy[(icopy < mif) * (icopy != 0.0)]))/360.0) / (bleed/360.0)) * -1 + 1 icopy[(icopy > mir) * (icopy != 0.0)] = ((((icopy[(icopy > mir) * (icopy != 0.0)]) - mir)/360.0) / (bleed/360.0)) * -1 + 1 icopy[(icopy >= mif) * (icopy <= mir)] = 1.0 if(mif == 0): icopy[icopy > mir + bleed] = 0.0 icopy[(icopy > mir) * (icopy != 0.0)] = ((((icopy[(icopy > mir) * (icopy != 0.0)]) - mir) / 360.0) / (bleed/360.0)) * -1 + 1 return icopy def _neighbour_bleed(self, map, bleed): strength = bleed*30 if (strength > 0): height, width = map.shape[:2] size = (height * width) mul = numpy.math.sqrt(size) / 1064.416 # numpy.math.sqrt(1132982.0) map = map*255 blur_size = abs(2 * round((round(strength * mul) + 1) / 2) - 1) im = cv2.blur(map, (int(blur_size), int(blur_size))) return im/255.0 return map</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-3.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">7,938,162,124,587,179,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">35.361842</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">136</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.500181</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.139773</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45101"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">OCA/sale-workflow</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">sale_product_set/wizard/product_set_add.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">3428</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "># Copyright 2015 Anybox S.A.S # Copyright 2016-2018 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import models, fields, api, exceptions, _ import odoo.addons.decimal_precision as dp class ProductSetAdd(models.TransientModel): _name = 'product.set.add' _rec_name = 'product_set_id' _description = "Wizard model to add product set into a quotation" order_id = fields.Many2one( 'sale.order', 'Sale Order', required=True, default=lambda self: self.env.context.get('active_id'), ondelete='cascade' ) partner_id = fields.Many2one( related='order_id.partner_id', ondelete='cascade' ) product_set_id = fields.Many2one( 'product.set', 'Product set', required=True, ondelete='cascade' ) quantity = fields.Float( digits=dp.get_precision('Product Unit of Measure'), required=True, default=1) skip_existing_products = fields.Boolean( default=False, help='Enable this to not add new lines ' 'for products already included in SO lines.' ) def _check_partner(self): if self.product_set_id.partner_id: if self.product_set_id.partner_id != self.order_id.partner_id: raise exceptions.ValidationError(_( "Select a product set assigned to " "the same partner of the order." )) @api.multi def add_set(self): """ Add product set, multiplied by quantity in sale order line """ self._check_partner() order_lines = self._prepare_order_lines() if order_lines: self.order_id.write({ "order_line": order_lines }) return order_lines def _prepare_order_lines(self): max_sequence = self._get_max_sequence() order_lines = [] for set_line in self._get_lines(): order_lines.append( (0, 0, self.prepare_sale_order_line_data( set_line, max_sequence=max_sequence)) ) return order_lines def _get_max_sequence(self): max_sequence = 0 if self.order_id.order_line: max_sequence = max([ line.sequence for line in self.order_id.order_line ]) return max_sequence def _get_lines(self): # hook here to take control on used lines so_product_ids = self.order_id.order_line.mapped('product_id').ids for set_line in self.product_set_id.set_line_ids: if (self.skip_existing_products and set_line.product_id.id in so_product_ids): continue yield set_line @api.multi def prepare_sale_order_line_data(self, set_line, max_sequence=0): self.ensure_one() sale_line = self.env['sale.order.line'].new({ 'order_id': self.order_id.id, 'product_id': set_line.product_id.id, 'product_uom_qty': set_line.quantity * self.quantity, 'product_uom': set_line.product_id.uom_id.id, 'sequence': max_sequence + set_line.sequence, 'discount': set_line.discount, }) sale_line.product_id_change() line_values = sale_line._convert_to_write(sale_line._cache) return line_values </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">agpl-3.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">4,705,311,278,881,153,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">34.340206</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">74</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.574096</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.86036</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45102"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">wolfelee/luokr.com</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">www.luokr.com/app/ctrls/admin/posts.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">10035</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">#coding=utf-8 from admin import admin, AdminCtrl class Admin_PostsCtrl(AdminCtrl): @admin def get(self): pager = {} pager['qnty'] = min(int(self.input('qnty', 10)), 50) pager['page'] = max(int(self.input('page', 1)), 1) pager['list'] = 0; cur_posts = self.dbase('posts').cursor() cur_users = self.dbase('users').cursor() cur_posts.execute('select * from posts order by post_id desc limit ? offset ?', (pager['qnty'], (pager['page']-1)*pager['qnty'], )) posts = cur_posts.fetchall() psers = {} if posts: pager['list'] = len(posts) cur_users.execute('select * from users where user_id in (' + ','.join(str(i['user_id']) for i in posts) + ')') psers = self.utils().array_keyto(cur_users.fetchall(), 'user_id') cur_posts.close() cur_users.close() self.render('admin/posts.html', pager = pager, posts = posts, psers = psers) class Admin_PostHiddenCtrl(AdminCtrl): @admin def post(self): try: post_id = self.input('post_id') con = self.dbase('posts') cur = con.cursor() cur.execute('update posts set post_stat = 0 where post_id = ?', (post_id, )) con.commit() cur.close() self.flash(1) except: self.flash(0) class Admin_PostCreateCtrl(AdminCtrl): @admin def get(self): cur = self.dbase('terms').cursor() cur.execute('select * from terms order by term_id desc, term_refc desc limit 9') terms = cur.fetchall() cur.close() mode = self.input('mode', None) self.render('admin/post-create.html', mode = mode, terms = terms) @admin def post(self): try: user = self.current_user post_type = self.input('post_type', 'blog') post_title = self.input('post_title') post_descp = self.input('post_descp') post_author = self.input('post_author') post_source = self.input('post_source') post_summary = self.input('post_summary') post_content = self.input('post_content') post_rank = self.input('post_rank') post_stat = self.input('post_stat', 0) post_ptms = int(self.timer().mktime(self.timer().strptime(self.input('post_ptms'), '%Y-%m-%d %H:%M:%S'))) post_ctms = self.stime() post_utms = post_ctms term_list = [] for term_name in self.input('term_list').split(' '): if term_name == '': continue term_list.append(term_name) if len(term_list) > 10: self.flash(0, {'msg': '标签数量限制不能超过 10 个'}) return con_posts = self.dbase('posts') cur_posts = con_posts.cursor() con_terms = self.dbase('terms') cur_terms = con_terms.cursor() term_imap = {} term_ctms = self.stime() for term_name in term_list: cur_terms.execute('select term_id from terms where term_name = ?', (term_name ,)) term_id = cur_terms.fetchone() if term_id: term_id = term_id['term_id'] else: cur_terms.execute('insert or ignore into terms (term_name, term_ctms) values (?, ?)', (term_name , term_ctms, )) if cur_terms.lastrowid: term_id = cur_terms.lastrowid if term_id: term_imap[term_id] = term_name cur_posts.execute('insert into posts (user_id, post_type, post_title, post_descp, post_author, post_source, post_summary, post_content,post_stat, post_rank, post_ptms, post_ctms, post_utms) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', \ (user['user_id'], post_type, post_title, post_descp, post_author, post_source, post_summary, post_content, post_stat, post_rank, post_ptms, post_ctms, post_utms ,)) post_id = cur_posts.lastrowid if term_imap: for term_id in term_imap: cur_posts.execute('insert or ignore into post_terms (post_id, term_id) values (' + str(post_id) + ',' + str(term_id) + ')') if term_imap: cur_terms.execute('update terms set term_refc = term_refc + 1 where term_id in (' + ','.join([str(i) for i in term_imap.keys()]) + ')') con_posts.commit() cur_posts.close() con_terms.commit() con_terms.close() self.model('alogs').add(self.dbase('alogs'), '新增文章:' + str(post_id), user_ip = self.request.remote_ip, user_id = user['user_id'], user_name = user['user_name']) self.flash(1, {'url': '/admin/post?post_id=' + str(post_id)}) except: self.flash(0) class Admin_PostCtrl(AdminCtrl): @admin def get(self): post_id = self.input('post_id') con_posts = self.dbase('posts') cur_posts = con_posts.cursor() cur_posts.execute('select * from posts where post_id = ?', (post_id, )) post = cur_posts.fetchone() if not post: cur_posts.close() return self.send_error(404) mode = self.input('mode', None) con_terms = self.dbase('terms') cur_terms = con_terms.cursor() cur_terms.execute('select * from terms order by term_id desc, term_refc desc limit 9') terms = cur_terms.fetchall() ptids = {} ptags = {} cur_posts.execute('select post_id,term_id from post_terms where post_id = ?', (post_id, )) ptids = cur_posts.fetchall() if ptids: cur_terms.execute('select * from terms where term_id in (' + ','.join(str(i['term_id']) for i in ptids) + ')') ptags = cur_terms.fetchall() if ptags: ptids = self.utils().array_group(ptids, 'post_id') ptags = self.utils().array_keyto(ptags, 'term_id') cur_posts.close() cur_terms.close() self.render('admin/post.html', mode = mode, post = post, terms = terms, ptids = ptids, ptags = ptags) @admin def post(self): try: user = self.current_user post_id = self.input('post_id') post_title = self.input('post_title') post_descp = self.input('post_descp') post_author = self.input('post_author') post_source = self.input('post_source') post_summary = self.input('post_summary') post_content = self.input('post_content') post_rank = self.input('post_rank') post_stat = self.input('post_stat', 0) post_ptms = int(self.timer().mktime(self.timer().strptime(self.input('post_ptms'), '%Y-%m-%d %H:%M:%S'))) post_utms = self.stime() term_list = [] for term_name in self.input('term_list').split(' '): if term_name == '': continue term_list.append(term_name) if len(term_list) > 10: self.flash(0, {'msg': '标签数量限制不能超过 10 个'}) return con_posts = self.dbase('posts') cur_posts = con_posts.cursor() con_terms = self.dbase('terms') cur_terms = con_terms.cursor() cur_posts.execute('select * from posts where post_id = ?', (post_id, )) post = cur_posts.fetchone() if not post: cur_posts.close() cur_terms.close() self.flash(0, '没有指定文章ID') return term_imap = {} term_ctms = self.stime() for term_name in term_list: cur_terms.execute('select term_id from terms where term_name = ?', (term_name ,)) term_id = cur_terms.fetchone() if term_id: term_id = term_id['term_id'] else: cur_terms.execute('insert or ignore into terms (term_name, term_ctms) values (?, ?)', (term_name , term_ctms, )) if cur_terms.lastrowid: term_id = cur_terms.lastrowid if term_id: term_imap[term_id] = term_name cur_posts.execute('select term_id from post_terms where post_id = ?', (post_id, )) post_tids = cur_posts.fetchall() cur_posts.execute('update posts set user_id=?,post_title=?,post_descp=?,post_author=?,post_source=?,post_summary=?,post_content=?,post_stat=?,post_rank=?,post_ptms=?,post_utms=? where post_id=?', \ (user['user_id'], post_title, post_descp, post_author, post_source, post_summary, post_content, post_stat, post_rank, post_ptms, post_utms, post_id,)) cur_posts.execute('delete from post_terms where post_id = ?', (post_id,)) if term_imap: for term_id in term_imap: cur_posts.execute('insert or ignore into post_terms (post_id, term_id) values (' + str(post_id) + ',' + str(term_id) + ')') if post_tids: cur_terms.execute('update terms set term_refc = term_refc - 1 where term_id in (' + ','.join([str(i['term_id']) for i in post_tids]) + ')') if term_imap: cur_terms.execute('update terms set term_refc = term_refc + 1 where term_id in (' + ','.join([str(i) for i in term_imap.keys()]) + ')') con_posts.commit() cur_posts.close() con_terms.commit() cur_terms.close() self.model('alogs').add(self.dbase('alogs'), '更新文章:' + str(post_id), user_ip = self.request.remote_ip, user_id = user['user_id'], user_name = user['user_name']) self.flash(1) except: self.flash(0) </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">bsd-3-clause</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-2,849,066,017,734,671,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">38.519841</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">252</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.520835</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.517838</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45103"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">advancedplotting/aplot</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">python/plotserv/api_annotations.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">8009</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "># Copyright (c) 2014-2015, Heliosphere Research LLC # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from this # software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """ Handles VIs in "api_annotations". """ import numpy as np from matplotlib import pyplot as plt from .core import resource from .terminals import remove_none from . import filters from . import errors @resource('text') def text(ctx, a): """ Display text on the plot """ plotid = a.plotid() x = a.float('x') y = a.float('y') s = a.string('s') relative = a.bool('coordinates') textprops = a.text() display = a.display() ctx.set(plotid) ax = plt.gca() # None-finite values here mean we skip the plot if x is None or y is None: return k = textprops._k() k.update(display._k()) k['clip_on'] = True if relative: k['transform'] = ax.transAxes remove_none(k) plt.text(x, y, s, **k) @resource('hline') def hline(ctx, a): """ Plot a horizontal line """ plotid = a.plotid() y = a.float('y') xmin = a.float('xmin') xmax = a.float('xmax') line = a.line() display = a.display() ctx.set(plotid) ctx.fail_if_polar() # Non-finite value provided if y is None: return k = { 'xmin': xmin, 'xmax': xmax, 'linewidth': line.width, 'linestyle': line.style, 'color': line.color if line.color is not None else 'k', } k.update(display._k()) remove_none(k) plt.axhline(y, **k) @resource('vline') def vline(ctx, a): """ Plot a vertical line """ plotid = a.plotid() x = a.float('x') ymin = a.float('ymin') ymax = a.float('ymax') line = a.line() display = a.display() ctx.set(plotid) ctx.fail_if_polar() # Non-finite value provided if x is None: return k = { 'ymin': ymin, 'ymax': ymax, 'linewidth': line.width, 'linestyle': line.style, 'color': line.color if line.color is not None else 'k', } k.update(display._k()) remove_none(k) plt.axvline(x, **k) @resource('colorbar') def colorbar(ctx, a): """ Display a colorbar """ plotid = a.plotid() label = a.string('label') ticks = a.dbl_1d('ticks') ticklabels = a.string_1d('ticklabels') ctx.set(plotid) # If no colormapped object has been plotted, MPL complains. # We permit this, and simply don't add the colorbar. if ctx.mappable is None: return c = plt.colorbar(ctx.mappable) # Don't bother setting an empty label if len(label) > 0: c.set_label(label) # Both specified if len(ticks) > 0 and len(ticklabels) > 0: ticks, ticklabels = filters.filter_1d(ticks, ticklabels) c.set_ticks(ticks) c.set_ticklabels(ticklabels) # Just ticks specified elif len(ticks) > 0: ticks = ticks[np.isfinite(ticks)] c.set_ticks(ticks) # Just ticklabels specified else: # Providing zero-length "ticks" array invokes auto-ticking, in which # case any ticklabels are ignored. pass @resource('legend') def legend(ctx, a): """ Represents Legend.vi. Note that there is no Positions enum on the Python side; the MPL values are hard-coded into the LabView control. """ POSITIONS = { 0: 0, 1: 1, 2: 9, 3: 2, 4: 6, 5: 3, 6: 8, 7: 4, 8: 7, 9: 10 } plotid = a.plotid() position = a.enum('position', POSITIONS) ctx.set(plotid) k = {'loc': position, 'fontsize': 'medium'} remove_none(k) if len(ctx.legend_entries) > 0: objects, labels = zip(*ctx.legend_entries) plt.legend(objects, labels, **k) @resource('label') def label(ctx, a): """ Title, X axis and Y axis labels. """ LOCATIONS = {0: 'title', 1: 'xlabel', 2: 'ylabel'} plotid = a.plotid() location = a.enum('kind', LOCATIONS) label = a.string('label') text = a.text() ctx.set(plotid) k = text._k() if location == 'title': plt.title(label, **k) elif location == 'xlabel': plt.xlabel(label, **k) elif location == 'ylabel': ctx.fail_if_polar() plt.ylabel(label, **k) else: pass @resource('circle') def circle(ctx, a): """ Draw a circle on a rectangular plot """ plotid = a.plotid() x = a.float('x') y = a.float('y') radius = a.float('radius') color = a.color('color') line = a.line() display = a.display() f = ctx.set(plotid) ctx.fail_if_polar() ctx.fail_if_log_symlog() # Like Text.vi, if any critical input is Nan we do nothing if x is None or y is None or radius is None: return # Catch this before MPL complains if radius <= 0: return k = { 'edgecolor': line.color, 'linestyle': line.style, 'linewidth': line.width, 'facecolor': color if color is not None else '#bbbbbb', } k.update(display._k()) remove_none(k) c = plt.Circle((x,y), radius, **k) f.gca().add_artist(c) @resource('rectangle') def rectangle(ctx, a): """ Draw a rectangle """ plotid = a.plotid() x = a.float('x') y = a.float('y') width = a.float('width') height = a.float('height') color = a.color('color') line = a.line() display = a.display() f = ctx.set(plotid) ctx.fail_if_symlog() # Like Text.vi, if any critical input is Nan we do nothing if x is None or y is None or width is None or height is None: return if width == 0 or height == 0: return k = { 'edgecolor': line.color, 'linestyle': line.style, 'linewidth': line.width, 'facecolor': color if color is not None else '#bbbbbb', } k.update(display._k()) remove_none(k) r = plt.Rectangle((x,y), width, height, **k) f.gca().add_artist(r)</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">bsd-3-clause</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3,550,723,003,300,049,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">25.611296</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">77</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.558122</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.680607</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45104"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">henriquegemignani/randovania</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">randovania/gui/main_window.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">25113</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">import functools import json import logging import os import platform import subprocess from functools import partial from pathlib import Path from typing import Optional, List from PySide2 import QtCore, QtWidgets, QtGui from PySide2.QtCore import QUrl, Signal, Qt from qasync import asyncSlot from randovania import VERSION from randovania.game_description.resources.trick_resource_info import TrickResourceInfo from randovania.games.game import RandovaniaGame from randovania.gui.generated.main_window_ui import Ui_MainWindow from randovania.gui.lib import common_qt_lib, async_dialog, theme from randovania.gui.lib.trick_lib import used_tricks, difficulties_for_trick from randovania.gui.lib.window_manager import WindowManager from randovania.interface_common import update_checker from randovania.interface_common.enum_lib import iterate_enum from randovania.interface_common.options import Options from randovania.interface_common.preset_manager import PresetManager from randovania.layout.layout_description import LayoutDescription from randovania.layout.trick_level import LayoutTrickLevel from randovania.resolver import debug _DISABLE_VALIDATION_WARNING = """ <html><head/><body> <p>While it sometimes throws errors, the validation is what guarantees that your seed is completable.<br/> Do <span style=" font-weight:600;">not</span> disable if you're uncomfortable with possibly unbeatable seeds. </p><p align="center">Are you sure you want to disable validation?</p></body></html> """ def _update_label_on_show(label: QtWidgets.QLabel, text: str): def showEvent(_): if label._delayed_text is not None: label.setText(label._delayed_text) label._delayed_text = None label._delayed_text = text label.showEvent = showEvent class MainWindow(WindowManager, Ui_MainWindow): newer_version_signal = Signal(str, str) options_changed_signal = Signal() _is_preview_mode: bool = False menu_new_version: Optional[QtWidgets.QAction] = None _current_version_url: Optional[str] = None _options: Options _data_visualizer: Optional[QtWidgets.QWidget] = None _map_tracker: QtWidgets.QWidget _preset_manager: PresetManager GameDetailsSignal = Signal(LayoutDescription) InitPostShowSignal = Signal() @property def _tab_widget(self): return self.main_tab_widget @property def preset_manager(self) -> PresetManager: return self._preset_manager @property def main_window(self) -> QtWidgets.QMainWindow: return self @property def is_preview_mode(self) -> bool: return self._is_preview_mode def __init__(self, options: Options, preset_manager: PresetManager, network_client, preview: bool): super().__init__() self.setupUi(self) self.setWindowTitle("Randovania {}".format(VERSION)) self._is_preview_mode = preview self.setAcceptDrops(True) common_qt_lib.set_default_window_icon(self) # Remove all hardcoded link color about_document: QtGui.QTextDocument = self.about_text_browser.document() about_document.setHtml(about_document.toHtml().replace("color:#0000ff;", "")) self.browse_racetime_label.setText(self.browse_racetime_label.text().replace("color:#0000ff;", "")) self.intro_label.setText(self.intro_label.text().format(version=VERSION)) self._preset_manager = preset_manager self.network_client = network_client if preview: debug.set_level(2) # Signals self.newer_version_signal.connect(self.display_new_version) self.options_changed_signal.connect(self.on_options_changed) self.GameDetailsSignal.connect(self._open_game_details) self.InitPostShowSignal.connect(self.initialize_post_show) self.intro_play_now_button.clicked.connect(lambda: self.welcome_tab_widget.setCurrentWidget(self.tab_play)) self.open_faq_button.clicked.connect(self._open_faq) self.open_database_viewer_button.clicked.connect(partial(self._open_data_visualizer_for_game, RandovaniaGame.PRIME2)) for game in RandovaniaGame: self.hint_item_names_game_combo.addItem(game.long_name, game) self.hint_location_game_combo.addItem(game.long_name, game) self.hint_item_names_game_combo.currentIndexChanged.connect(self._update_hints_text) self.hint_location_game_combo.currentIndexChanged.connect(self._update_hint_locations) self.import_permalink_button.clicked.connect(self._import_permalink) self.import_game_file_button.clicked.connect(self._import_spoiler_log) self.browse_racetime_button.clicked.connect(self._browse_racetime) self.create_new_seed_button.clicked.connect( lambda: self.welcome_tab_widget.setCurrentWidget(self.tab_create_seed)) # Menu Bar for action, game in ((self.menu_action_prime_1_data_visualizer, RandovaniaGame.PRIME1), (self.menu_action_prime_2_data_visualizer, RandovaniaGame.PRIME2), (self.menu_action_prime_3_data_visualizer, RandovaniaGame.PRIME3)): action.triggered.connect(partial(self._open_data_visualizer_for_game, game)) for action, game in ((self.menu_action_edit_prime_1, RandovaniaGame.PRIME1), (self.menu_action_edit_prime_2, RandovaniaGame.PRIME2), (self.menu_action_edit_prime_3, RandovaniaGame.PRIME3)): action.triggered.connect(partial(self._open_data_editor_for_game, game)) self.menu_action_item_tracker.triggered.connect(self._open_item_tracker) self.menu_action_map_tracker.triggered.connect(self._on_menu_action_map_tracker) self.menu_action_edit_existing_database.triggered.connect(self._open_data_editor_prompt) self.menu_action_validate_seed_after.triggered.connect(self._on_validate_seed_change) self.menu_action_timeout_generation_after_a_time_limit.triggered.connect(self._on_generate_time_limit_change) self.menu_action_dark_mode.triggered.connect(self._on_menu_action_dark_mode) self.menu_action_open_auto_tracker.triggered.connect(self._open_auto_tracker) self.menu_action_previously_generated_games.triggered.connect(self._on_menu_action_previously_generated_games) self.menu_action_layout_editor.triggered.connect(self._on_menu_action_layout_editor) self.menu_prime_1_trick_details.aboutToShow.connect(self._create_trick_details_prime_1) self.menu_prime_2_trick_details.aboutToShow.connect(self._create_trick_details_prime_2) self.menu_prime_3_trick_details.aboutToShow.connect(self._create_trick_details_prime_3) # Setting this event only now, so all options changed trigger only once options.on_options_changed = self.options_changed_signal.emit self._options = options self.main_tab_widget.setCurrentIndex(0) def closeEvent(self, event): self.generate_seed_tab.stop_background_process() super().closeEvent(event) def dragEnterEvent(self, event: QtGui.QDragEnterEvent): from randovania.layout.preset_migration import VersionedPreset valid_extensions = [ LayoutDescription.file_extension(), VersionedPreset.file_extension(), ] valid_extensions_with_dot = { f".{extension}" for extension in valid_extensions } for url in event.mimeData().urls(): ext = os.path.splitext(url.toLocalFile())[1] if ext in valid_extensions_with_dot: event.acceptProposedAction() return def dropEvent(self, event: QtGui.QDropEvent): from randovania.layout.preset_migration import VersionedPreset for url in event.mimeData().urls(): path = Path(url.toLocalFile()) if path.suffix == f".{LayoutDescription.file_extension()}": self.open_game_details(LayoutDescription.from_file(path)) return elif path.suffix == f".{VersionedPreset.file_extension()}": self.main_tab_widget.setCurrentWidget(self.welcome_tab) self.welcome_tab_widget.setCurrentWidget(self.tab_create_seed) self.generate_seed_tab.import_preset_file(path) return def showEvent(self, event: QtGui.QShowEvent): self.InitPostShowSignal.emit() # Delayed Initialization @asyncSlot() async def initialize_post_show(self): self.InitPostShowSignal.disconnect(self.initialize_post_show) logging.info("Will initialize things in post show") await self._initialize_post_show_body() logging.info("Finished initializing post show") async def _initialize_post_show_body(self): logging.info("Will load OnlineInteractions") from randovania.gui.main_online_interaction import OnlineInteractions logging.info("Creating OnlineInteractions...") self.online_interactions = OnlineInteractions(self, self.preset_manager, self.network_client, self, self._options) logging.info("Will load GenerateSeedTab") from randovania.gui.generate_seed_tab import GenerateSeedTab logging.info("Creating GenerateSeedTab...") self.generate_seed_tab = GenerateSeedTab(self, self, self._options) logging.info("Running GenerateSeedTab.setup_ui") self.generate_seed_tab.setup_ui() # Update hints text logging.info("Will _update_hints_text") self._update_hints_text() logging.info("Will hide hint locations combo") self.hint_location_game_combo.setVisible(False) self.hint_location_game_combo.setCurrentIndex(1) logging.info("Will update for modified options") with self._options: self.on_options_changed() def _update_hints_text(self): from randovania.gui.lib import hints_text hints_text.update_hints_text(self.hint_item_names_game_combo.currentData(), self.hint_item_names_tree_widget) def _update_hint_locations(self): from randovania.gui.lib import hints_text hints_text.update_hint_locations(self.hint_location_game_combo.currentData(), self.hint_tree_widget) # Generate Seed def _open_faq(self): self.main_tab_widget.setCurrentWidget(self.help_tab) self.help_tab_widget.setCurrentWidget(self.tab_faq) async def generate_seed_from_permalink(self, permalink): from randovania.interface_common.status_update_lib import ProgressUpdateCallable from randovania.gui.dialog.background_process_dialog import BackgroundProcessDialog def work(progress_update: ProgressUpdateCallable): from randovania.interface_common import simplified_patcher layout = simplified_patcher.generate_layout(progress_update=progress_update, permalink=permalink, options=self._options) progress_update(f"Success! (Seed hash: {layout.shareable_hash})", 1) return layout new_layout = await BackgroundProcessDialog.open_for_background_task(work, "Creating a game...") self.open_game_details(new_layout) @asyncSlot() async def _import_permalink(self): from randovania.gui.dialog.permalink_dialog import PermalinkDialog dialog = PermalinkDialog() result = await async_dialog.execute_dialog(dialog) if result == QtWidgets.QDialog.Accepted: permalink = dialog.get_permalink_from_field() await self.generate_seed_from_permalink(permalink) def _import_spoiler_log(self): json_path = common_qt_lib.prompt_user_for_input_game_log(self) if json_path is not None: layout = LayoutDescription.from_file(json_path) self.open_game_details(layout) @asyncSlot() async def _browse_racetime(self): from randovania.gui.dialog.racetime_browser_dialog import RacetimeBrowserDialog dialog = RacetimeBrowserDialog() if not await dialog.refresh(): return result = await async_dialog.execute_dialog(dialog) if result == QtWidgets.QDialog.Accepted: await self.generate_seed_from_permalink(dialog.permalink) def open_game_details(self, layout: LayoutDescription): self.GameDetailsSignal.emit(layout) def _open_game_details(self, layout: LayoutDescription): from randovania.gui.seed_details_window import SeedDetailsWindow details_window = SeedDetailsWindow(self, self._options) details_window.update_layout_description(layout) details_window.show() self.track_window(details_window) # Releases info async def request_new_data(self): from randovania.interface_common import github_releases_data await self._on_releases_data(await github_releases_data.get_releases()) async def _on_releases_data(self, releases: Optional[List[dict]]): import markdown current_version = update_checker.strict_current_version() last_changelog = self._options.last_changelog_displayed all_change_logs, new_change_logs, version_to_display = update_checker.versions_to_display_for_releases( current_version, last_changelog, releases) if version_to_display is not None: self.display_new_version(version_to_display) if all_change_logs: changelog_tab = QtWidgets.QWidget() changelog_tab.setObjectName("changelog_tab") changelog_tab_layout = QtWidgets.QVBoxLayout(changelog_tab) changelog_tab_layout.setContentsMargins(0, 0, 0, 0) changelog_tab_layout.setObjectName("changelog_tab_layout") changelog_scroll_area = QtWidgets.QScrollArea(changelog_tab) changelog_scroll_area.setWidgetResizable(True) changelog_scroll_area.setObjectName("changelog_scroll_area") changelog_scroll_contents = QtWidgets.QWidget() changelog_scroll_contents.setGeometry(QtCore.QRect(0, 0, 489, 337)) changelog_scroll_contents.setObjectName("changelog_scroll_contents") changelog_scroll_layout = QtWidgets.QVBoxLayout(changelog_scroll_contents) changelog_scroll_layout.setObjectName("changelog_scroll_layout") for entry in all_change_logs: changelog_label = QtWidgets.QLabel(changelog_scroll_contents) _update_label_on_show(changelog_label, markdown.markdown(entry)) changelog_label.setObjectName("changelog_label") changelog_label.setWordWrap(True) changelog_scroll_layout.addWidget(changelog_label) changelog_scroll_area.setWidget(changelog_scroll_contents) changelog_tab_layout.addWidget(changelog_scroll_area) self.help_tab_widget.addTab(changelog_tab, "Change Log") if new_change_logs: await async_dialog.message_box(self, QtWidgets.QMessageBox.Information, "What's new", markdown.markdown("\n".join(new_change_logs))) with self._options as options: options.last_changelog_displayed = current_version def display_new_version(self, version: update_checker.VersionDescription): if self.menu_new_version is None: self.menu_new_version = QtWidgets.QAction("", self) self.menu_new_version.triggered.connect(self.open_version_link) self.menu_bar.addAction(self.menu_new_version) self.menu_new_version.setText("New version available: {}".format(version.tag_name)) self._current_version_url = version.html_url def open_version_link(self): if self._current_version_url is None: raise RuntimeError("Called open_version_link, but _current_version_url is None") QtGui.QDesktopServices.openUrl(QUrl(self._current_version_url)) # Options def on_options_changed(self): self.menu_action_validate_seed_after.setChecked(self._options.advanced_validate_seed_after) self.menu_action_timeout_generation_after_a_time_limit.setChecked( self._options.advanced_timeout_during_generation) self.menu_action_dark_mode.setChecked(self._options.dark_mode) self.generate_seed_tab.on_options_changed(self._options) theme.set_dark_theme(self._options.dark_mode) # Menu Actions def _open_data_visualizer_for_game(self, game: RandovaniaGame): self.open_data_visualizer_at(None, None, game) def open_data_visualizer_at(self, world_name: Optional[str], area_name: Optional[str], game: RandovaniaGame = RandovaniaGame.PRIME2, ): from randovania.gui.data_editor import DataEditorWindow data_visualizer = DataEditorWindow.open_internal_data(game, False) self._data_visualizer = data_visualizer if world_name is not None: data_visualizer.focus_on_world(world_name) if area_name is not None: data_visualizer.focus_on_area(area_name) self._data_visualizer.show() def _open_data_editor_for_game(self, game: RandovaniaGame): from randovania.gui.data_editor import DataEditorWindow self._data_editor = DataEditorWindow.open_internal_data(game, True) self._data_editor.show() def _open_data_editor_prompt(self): from randovania.gui.data_editor import DataEditorWindow database_path = common_qt_lib.prompt_user_for_database_file(self) if database_path is None: return with database_path.open("r") as database_file: self._data_editor = DataEditorWindow(json.load(database_file), database_path, False, True) self._data_editor.show() @asyncSlot() async def _on_menu_action_map_tracker(self): dialog = QtWidgets.QInputDialog(self) dialog.setWindowTitle("Map Tracker") dialog.setLabelText("Select preset used for the tracker.") dialog.setComboBoxItems([preset.name for preset in self._preset_manager.all_presets]) dialog.setTextValue(self._options.selected_preset_name) result = await async_dialog.execute_dialog(dialog) if result == QtWidgets.QDialog.Accepted: preset = self._preset_manager.preset_for_name(dialog.textValue()) self.open_map_tracker(preset.get_preset().configuration) def open_map_tracker(self, configuration: "EchoesConfiguration"): from randovania.gui.tracker_window import TrackerWindow, InvalidLayoutForTracker try: self._map_tracker = TrackerWindow(self._options.tracker_files_path, configuration) except InvalidLayoutForTracker as e: QtWidgets.QMessageBox.critical( self, "Unsupported configuration for Tracker", str(e) ) return self._map_tracker.show() def _open_item_tracker(self): # Importing this at root level seems to crash linux tests :( from PySide2.QtWebEngineWidgets import QWebEngineView tracker_window = QtWidgets.QMainWindow() tracker_window.setWindowTitle("Item Tracker") tracker_window.resize(370, 380) web_view = QWebEngineView(tracker_window) tracker_window.setCentralWidget(web_view) self.web_view = web_view def update_window_icon(): tracker_window.setWindowIcon(web_view.icon()) web_view.iconChanged.connect(update_window_icon) web_view.load(QUrl("https://spaghettitoastbook.github.io/echoes/tracker/")) tracker_window.show() self._item_tracker_window = tracker_window # Difficulties stuff def _exec_trick_details(self, popup: "TrickDetailsPopup"): self._trick_details_popup = popup self._trick_details_popup.setWindowModality(Qt.WindowModal) self._trick_details_popup.open() def _open_trick_details_popup(self, game, trick: TrickResourceInfo, level: LayoutTrickLevel): from randovania.gui.dialog.trick_details_popup import TrickDetailsPopup self._exec_trick_details(TrickDetailsPopup(self, self, game, trick, level)) def _create_trick_details_prime_1(self): self.menu_prime_1_trick_details.aboutToShow.disconnect(self._create_trick_details_prime_1) self._setup_difficulties_menu(RandovaniaGame.PRIME1, self.menu_prime_1_trick_details) def _create_trick_details_prime_2(self): self.menu_prime_2_trick_details.aboutToShow.disconnect(self._create_trick_details_prime_2) self._setup_difficulties_menu(RandovaniaGame.PRIME2, self.menu_prime_2_trick_details) def _create_trick_details_prime_3(self): self.menu_prime_3_trick_details.aboutToShow.disconnect(self._create_trick_details_prime_3) self._setup_difficulties_menu(RandovaniaGame.PRIME3, self.menu_prime_3_trick_details) def _setup_difficulties_menu(self, game: RandovaniaGame, menu: QtWidgets.QMenu): from randovania.game_description import default_database game = default_database.game_description_for(game) tricks_in_use = used_tricks(game) menu.clear() for trick in sorted(game.resource_database.trick, key=lambda _trick: _trick.long_name): if trick not in tricks_in_use: continue trick_menu = QtWidgets.QMenu(self) trick_menu.setTitle(trick.long_name) menu.addAction(trick_menu.menuAction()) used_difficulties = difficulties_for_trick(game, trick) for i, trick_level in enumerate(iterate_enum(LayoutTrickLevel)): if trick_level in used_difficulties: difficulty_action = QtWidgets.QAction(self) difficulty_action.setText(trick_level.long_name) trick_menu.addAction(difficulty_action) difficulty_action.triggered.connect( functools.partial(self._open_trick_details_popup, game, trick, trick_level)) # ========== @asyncSlot() async def _on_validate_seed_change(self): old_value = self._options.advanced_validate_seed_after new_value = self.menu_action_validate_seed_after.isChecked() if old_value and not new_value: box = QtWidgets.QMessageBox(self) box.setWindowTitle("Disable validation?") box.setText(_DISABLE_VALIDATION_WARNING) box.setIcon(QtWidgets.QMessageBox.Warning) box.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No) box.setDefaultButton(QtWidgets.QMessageBox.No) user_response = await async_dialog.execute_dialog(box) if user_response != QtWidgets.QMessageBox.Yes: self.menu_action_validate_seed_after.setChecked(True) return with self._options as options: options.advanced_validate_seed_after = new_value def _on_generate_time_limit_change(self): is_checked = self.menu_action_timeout_generation_after_a_time_limit.isChecked() with self._options as options: options.advanced_timeout_during_generation = is_checked def _on_menu_action_dark_mode(self): with self._options as options: options.dark_mode = self.menu_action_dark_mode.isChecked() def _open_auto_tracker(self): from randovania.gui.auto_tracker_window import AutoTrackerWindow self.auto_tracker_window = AutoTrackerWindow(common_qt_lib.get_game_connection(), self._options) self.auto_tracker_window.show() def _on_menu_action_previously_generated_games(self): path = self._options.data_dir.joinpath("game_history") try: if platform.system() == "Windows": os.startfile(path) elif platform.system() == "Darwin": subprocess.run(["open", path]) else: subprocess.run(["xdg-open", path]) except OSError: print("Exception thrown :)") box = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Information, "Game History", f"Previously generated games can be found at:\n{path}", QtWidgets.QMessageBox.Ok, self) box.setTextInteractionFlags(Qt.TextSelectableByMouse) box.show() def _on_menu_action_layout_editor(self): from randovania.gui.corruption_layout_editor import CorruptionLayoutEditor self.corruption_editor = CorruptionLayoutEditor() self.corruption_editor.show() </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-3.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-1,612,572,667,298,678,800</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">44.330325</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">118</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.669454</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.87367</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45105"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">maltsev/LatexWebOffice</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">app/views/document.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">15983</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "># -*- coding: utf-8 -*- """ * Purpose : Dokument- und Projektverwaltung Schnittstelle * Creation Date : 19-11-2014 * Last Modified : Di 24 Feb 2015 15:46:51 CET * Author : mattis * Coauthors : christian, ingo, Kirill * Sprintnumber : 2, 5 * Backlog entry : TEK1, 3ED9, DOK8, DO14, KOL1 """ import os from django.contrib.auth.decorators import login_required from django.views.decorators.http import require_http_methods from django.shortcuts import render from django.views.static import serve import settings from app.common import util from app.common.constants import ERROR_MESSAGES from app.views import file, folder, project, template from app.models.projecttemplate import ProjectTemplate from app.models.file.file import File from app.models.file.texfile import TexFile from app.models.file.plaintextfile import PlainTextFile from app.models.file.pdf import PDF from app.models.project import Project from app.models.folder import Folder globalparas = { 'id': {'name': 'id', 'type': int}, 'content': {'name': 'content', 'type': str}, 'folderid': {'name': 'folderid', 'type': int}, 'name': {'name': 'name', 'type': str}, 'formatid': {'name': 'formatid', 'type': int}, # 'compilerid': {'name': 'compilerid', 'type': int}, 'forcecompile': {'name': 'forcecompile', 'type': int} } # dictionary mit verfügbaren Befehlen und den entsprechenden Aktionen # die entsprechenden Methoden befinden sich in: # '/app/views/project.py', '/app/views/file.py', '/app/views/folder.py' und '/app/views/collaboration.py' available_commands = { 'projectcreate': { 'command': project.projectCreate, 'parameters': [{'para': globalparas['name'], 'stringcheck': True}] }, 'projectclone': { 'command': project.projectClone, 'parameters': [{'para': globalparas['id'], 'type': Project, 'requirerights': ['owner', 'collaborator']}, {'para': globalparas['name'], 'stringcheck': True}] }, 'projectrm': { 'command': project.projectRm, 'parameters': [{'para': globalparas['id'], 'type': Project}] }, 'projectrename': { 'command': project.projectRename, 'parameters': [{'para': globalparas['id'], 'type': Project}, {'para': globalparas['name'], 'stringcheck': True}] }, 'listprojects': { 'command': project.listProjects, 'parameters': [] }, 'importzip': { 'command': project.importZip, 'parameters': [] }, 'exportzip': { 'command': project.exportZip, 'parameters': [{'para': globalparas['id']}] }, 'inviteuser': { 'command': project.inviteUser, 'parameters': [{'para': globalparas['id'], 'type': Project}, {'para': globalparas['name'], 'stringcheck': True}] }, 'hasinvitedusers': { 'command': project.hasInvitedUsers, 'parameters': [{'para': globalparas['id'], 'type': Project}] }, 'listinvitedusers': { 'command': project.listInvitedUsers, 'parameters': [{'para': globalparas['id'], 'type': Project}] }, 'listunconfirmedcollaborativeprojects': { 'command': project.listUnconfirmedCollaborativeProjects, 'parameters': [] }, 'activatecollaboration': { 'command': project.activateCollaboration, 'parameters': [{'para': globalparas['id'], 'type': Project, 'requirerights': ['owner', 'invitee']}] }, 'quitcollaboration': { 'command': project.quitCollaboration, 'parameters': [ {'para': globalparas['id'], 'type': Project, 'requirerights': ['owner', 'invitee', 'collaborator']}] }, 'cancelcollaboration': { 'command': project.cancelCollaboration, 'parameters': [{'para': globalparas['id'], 'type': Project}, {'para': globalparas['name'], 'stringcheck': True}] }, 'createtex': { 'command': file.createTexFile, 'parameters': [{'para': globalparas['id'], 'type': Folder, 'requirerights': ['owner', 'collaborator']}, {'para': globalparas['name'], 'filenamecheck': True}] }, 'updatefile': { 'command': file.updateFile, 'parameters': [{'para': globalparas['id'], 'type': PlainTextFile, 'requirerights': ['owner', 'collaborator'], 'lockcheck': False}, {'para': globalparas['content']}] }, 'deletefile': { 'command': file.deleteFile, 'parameters': [{'para': globalparas['id'], 'type': File, 'requirerights': ['owner', 'collaborator'], 'lockcheck': True}] }, 'renamefile': { 'command': file.renameFile, 'parameters': [{'para': globalparas['id'], 'type': File, 'requirerights': ['owner', 'collaborator'], 'lockcheck': True}, {'para': globalparas['name'], 'filenamecheck': True}] }, 'movefile': { 'command': file.moveFile, 'parameters': [{'para': globalparas['id'], 'type': File, 'requirerights': ['owner', 'collaborator'], 'lockcheck': True}, {'para': globalparas['folderid'], 'type': Folder, 'requirerights': ['owner', 'collaborator']}] }, 'uploadfiles': { 'command': file.uploadFiles, 'parameters': [{'para': globalparas['id'], 'type': Folder, 'requirerights': ['owner', 'collaborator']}] }, 'downloadfile': { 'command': file.downloadFile, 'parameters': [{'para': globalparas['id']}] }, 'gettext': { 'command': file.getText, 'parameters': [{'para': globalparas['id'], 'type': PlainTextFile, 'requirerights': ['owner', 'collaborator']}] }, 'fileinfo': { 'command': file.fileInfo, 'parameters': [{'para': globalparas['id'], 'type': File, 'requirerights': ['owner', 'collaborator']}] }, 'compile': { 'command': file.latexCompile, 'parameters': [{'para': globalparas['id'], 'type': TexFile, 'requirerights': ['owner', 'collaborator'], 'lockcheck': True}, {'para': globalparas['formatid']}, # {'para': globalparas['compilerid']}, {'para': globalparas['forcecompile']}] }, 'lockfile': { 'command': file.lockFile, 'parameters': [{'para': globalparas['id'], 'type': File, 'requirerights': ['owner', 'collaborator']}] }, 'unlockfile': { 'command': file.unlockFile, 'parameters': [{'para': globalparas['id'], 'type': File, 'requirerights': ['owner', 'collaborator']}] }, 'getlog': { 'command': file.getLog, 'parameters': [{'para': globalparas['id'], 'type': TexFile, 'requirerights': ['owner', 'collaborator']}] }, 'createdir': { 'command': folder.createDir, 'parameters': [{'para': globalparas['id'], 'type': Folder, 'requirerights': ['owner', 'collaborator']}, {'para': globalparas['name'], 'stringcheck': True}] }, 'rmdir': { 'command': folder.rmDir, 'parameters': [{'para': globalparas['id'], 'type': Folder, 'requirerights': ['owner', 'collaborator'], 'lockcheck': True}] }, 'renamedir': { 'command': folder.renameDir, 'parameters': [{'para': globalparas['id'], 'type': Folder, 'requirerights': ['owner', 'collaborator']}, {'para': globalparas['name'], 'stringcheck': True}] }, 'movedir': { 'command': folder.moveDir, 'parameters': [{'para': globalparas['id'], 'type': Folder, 'requirerights': ['owner', 'collaborator'], 'lockcheck': True}, {'para': globalparas['folderid'], 'type': Folder, 'requirerights': ['owner', 'collaborator']}] }, 'listfiles': { 'command': folder.listFiles, 'parameters': [{'para': globalparas['id'], 'type': Folder, 'requirerights': ['owner', 'collaborator']}] }, 'template2project': { 'command': template.template2Project, 'parameters': [{'para': globalparas['id'], 'type': ProjectTemplate}, {'para': globalparas['name'], 'stringcheck': True}] }, 'project2template': { 'command': template.project2Template, 'parameters': [{'para': globalparas['id'], 'type': Project, 'requirerights': ['owner', 'collaborator']}, {'para': globalparas['name'], 'stringcheck': True}] }, 'templaterm': { 'command': template.templateRm, 'parameters': [{'para': globalparas['id'], 'type': ProjectTemplate}] }, 'templaterename': { 'command': template.templateRename, 'parameters': [{'para': globalparas['id'], 'type': ProjectTemplate}, {'para': globalparas['name'], 'stringcheck': True}] }, 'listtemplates': { 'command': template.listTemplates, 'parameters': [] } } available_commands_output = {} for key, value in available_commands.items(): parameters = [] for paras in value['parameters']: globalparainfo = (paras['para']).copy() value = {'para': globalparainfo} if globalparainfo.get('type'): del globalparainfo['type'] parameters.append(value) if key == 'uploadfiles' or key == 'importzip': parameters.append({'para': {'name': 'files'}}) available_commands_output.update({key: parameters}) @login_required def debug(request): return render(request, 'documentPoster.html') # Schnittstellenfunktion # bietet eine Schnittstelle zur Kommunikation zwischen Client und Server # liest den vom Client per POST Data übergebenen Befehl ein # und führt die entsprechende Methode aus @login_required @require_http_methods(['POST', 'GET']) def execute(request): if request.method == 'POST' and 'command' in request.POST: # hole den aktuellen Benutzer user = request.user # wenn der Schlüssel nicht gefunden wurde # gib Fehlermeldung zurück if request.POST['command'] not in available_commands: return util.jsonErrorResponse(ERROR_MESSAGES['COMMANDNOTFOUND'], request) args = [] # aktueller Befehl c = available_commands[request.POST['command']] # Parameter dieses Befehls paras = c['parameters'] # durchlaufe alle Parameter des Befehls for para in paras: # wenn der Parameter nicht gefunden wurde oder ein Parameter, welcher eine id angeben sollte # Zeichen enthält, die keine Zahlen sind, gib Fehlermeldung zurück if request.POST.get(para['para']['name']) is None: return util.jsonErrorResponse(ERROR_MESSAGES['MISSINGPARAMETER'] % (para['para']), request) elif para['para']['type'] == int and (not request.POST.get(para['para']['name']).isdigit()): return util.jsonErrorResponse(ERROR_MESSAGES['MISSINGPARAMETER'] % (para['para']), request) # sonst füge den Parameter zu der Argumentliste hinzu else: args.append(request.POST[para['para']['name']]) # Teste auf ungültige strings if para.get('stringcheck'): failstring, failurereturn = util.checkObjectForInvalidString( request.POST.get(para['para']['name']), request) if not failstring: return failurereturn elif para.get('filenamecheck'): failstring, failurereturn = util.checkFileForInvalidString( request.POST.get(para['para']['name']), request) if not failstring: return failurereturn # Teste, dass der User rechte auf das Objekt mit der angegebenen id # hat und diese existiert if para.get('type') and para['para']['type'] == int: objType = para.get('type') objId = request.POST.get(para['para']['name']) requireRights = para.get('requirerights', ['owner']) lockcheck = para.get('lockcheck', False) if objType == Project: rights, failurereturn = util.checkIfProjectExistsAndUserHasRights(objId, user, request, requireRights) if not rights: return failurereturn elif objType == Folder: rights, failurereturn = util.checkIfDirExistsAndUserHasRights(objId, user, request, requireRights, lockcheck) if not rights: return failurereturn elif objType == File: rights, failurereturn = util.checkIfFileExistsAndUserHasRights(objId, user, request, requireRights, lockcheck, objecttype=File) if not rights: return failurereturn elif objType == TexFile: rights, failurereturn = util.checkIfFileExistsAndUserHasRights(objId, user, request, requireRights, lockcheck, objecttype=TexFile) if not rights: return failurereturn elif objType == PlainTextFile: rights, failurereturn = util.checkIfFileExistsAndUserHasRights(objId, user, request, requireRights, lockcheck, objecttype=PlainTextFile) if not rights: return failurereturn elif objType == ProjectTemplate: # Überprüfe, ob Vorlage existiert und der User darauf Rechte hat emptystring, failurereturn = util.checkIfTemplateExistsAndUserHasRights(objId, user, request) if not emptystring: return failurereturn # führe den übergebenen Befehl aus return c['command'](request, user, *args) elif request.method == 'GET' and request.GET.get('command'): command = request.GET.get('command') pdfid = request.GET.get('id') texid = request.GET.get('texid') defaultpdfPath = filepath = os.path.join(settings.BASE_DIR, 'app', 'static', 'default.pdf') if (pdfid and not pdfid.isdigit()) or (texid and not texid.isdigit()): return serve(request, os.path.basename(defaultpdfPath), os.path.dirname(defaultpdfPath)) if command == 'getpdf' and pdfid: requireRights = ['owner', 'collaborator'] rights, failurereturn = util.checkIfFileExistsAndUserHasRights(pdfid, request.user, request, requireRights, lockcheck=False, objecttype=PDF) if not rights: return serve(request, os.path.basename(defaultpdfPath), os.path.dirname(defaultpdfPath)) return file.getPDF(request, request.user, pdfid=pdfid, default=defaultpdfPath) elif command == 'getpdf' and texid: requireRights = ['owner', 'collaborator'] rights, failurereturn = util.checkIfFileExistsAndUserHasRights(texid, request.user, request, requireRights, lockcheck=False, objecttype=TexFile) if not rights: return serve(request, os.path.basename(defaultpdfPath), os.path.dirname(defaultpdfPath)) return file.getPDF(request, request.user, texid=texid, default=defaultpdfPath) return util.jsonErrorResponse(ERROR_MESSAGES['MISSINGPARAMETER'] % 'unknown', request) </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-3.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">953,337,725,685,583,200</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">42.63388</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">136</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.568503</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.9925</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45106"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">psyonara/agonizomai</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">sermons/models.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">5153</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">from __future__ import unicode_literals from django.db import models from django.template.defaultfilters import slugify from bible.models import BibleBook from useraccounts.models import UserAccount class Author(models.Model): name = models.CharField(null=False, blank=False, max_length=50) name_slug = models.SlugField(max_length=50, null=True, blank=True, db_index=True) def __str__(self): return self.name def save(self, *args, **kwargs): if self.name_slug is None or self.name_slug == "": self.name_slug = slugify(self.name) super(Author, self).save(*args, **kwargs) class AuthorSetting(models.Model): """ Holds user settings specific to an author. """ author = models.ForeignKey(Author, on_delete=models.CASCADE) user = models.ForeignKey("useraccounts.UserAccount", on_delete=models.CASCADE) name = models.CharField(max_length=30, db_index=True) value = models.CharField(max_length=50) class Series(models.Model): name = models.CharField(null=False, blank=False, max_length=100) name_slug = models.SlugField(max_length=100, null=True, blank=True, db_index=True) author = models.ForeignKey(Author, null=False, blank=False, on_delete=models.CASCADE) complete = models.BooleanField(default=False) def __str__(self): return "%s (%s)" % (self.name, self.author.name) def save(self, *args, **kwargs): if self.name_slug is None or self.name_slug == "": self.name_slug = slugify(self.name) super(Series, self).save(*args, **kwargs) class Sermon(models.Model): date_added = models.DateTimeField(auto_now_add=True) date_preached = models.DateField(null=True, blank=True) author = models.ForeignKey(Author, related_name="sermons", on_delete=models.CASCADE) title = models.CharField(null=False, blank=False, max_length=100) title_slug = models.SlugField(max_length=100, null=True, blank=True, db_index=True) series = models.ForeignKey( Series, null=True, blank=True, related_name="sermons", on_delete=models.CASCADE ) ref = models.CharField(max_length=20, null=True, blank=True) def get_audio_file(self): files = self.media_files.filter(media_type=1) return files[0] if len(files) > 0 else None def __str__(self): return "%s (by %s)" % (self.title, self.author.name) def save(self, *args, **kwargs): if self.title_slug is None or self.title_slug == "": self.title_slug = slugify(self.title) super(Sermon, self).save(*args, **kwargs) class Meta: ordering = ["-date_preached"] class ScriptureRef(models.Model): sermon = models.ForeignKey(Sermon, related_name="scripture_refs", on_delete=models.CASCADE) bible_book = models.ForeignKey(BibleBook, on_delete=models.CASCADE) chapter_begin = models.PositiveSmallIntegerField() chapter_end = models.PositiveSmallIntegerField() verse_begin = models.PositiveSmallIntegerField(null=True, blank=True) verse_end = models.PositiveSmallIntegerField(null=True, blank=True) def __str__(self): end_string = "" if self.chapter_begin == self.chapter_end: end_string += "%s %s" % (self.bible_book.name, self.chapter_begin) if self.verse_begin is not None and self.verse_end is not None: if self.verse_begin == self.verse_end: end_string += ":%s" % (self.verse_begin) else: end_string += ":%s-%s" % (self.verse_begin, self.verse_end) else: end_string += "%s %s" % (self.bible_book.name, self.chapter_begin) if self.verse_begin is None and self.verse_end is None: end_string += "-%s" % (self.chapter_end) else: end_string += ":%s-%s:%s" % (self.verse_begin, self.chapter_end, self.verse_end) return end_string class MediaFile(models.Model): MEDIA_TYPE_CHOICES = ((1, "audio"), (2, "video"), (3, "text"), (4, "pdf")) LOCATION_TYPE_CHOICES = ((1, "url"),) sermon = models.ForeignKey(Sermon, related_name="media_files", on_delete=models.CASCADE) media_type = models.PositiveSmallIntegerField(choices=MEDIA_TYPE_CHOICES, null=False, default=1) file_size = models.PositiveIntegerField(null=True, blank=True) location_type = models.PositiveSmallIntegerField( choices=LOCATION_TYPE_CHOICES, null=False, default=1 ) location = models.CharField(null=False, max_length=250) def __str__(self): return "%s (%s)" % (self.location, self.sermon.title) class SermonSession(models.Model): sermon = models.ForeignKey(Sermon, related_name="sessions", on_delete=models.CASCADE) session_started = models.DateTimeField(auto_now_add=True) session_updated = models.DateTimeField(auto_now=True) position = models.PositiveSmallIntegerField(default=0) # in seconds from start of file total_duration = models.PositiveSmallIntegerField(default=0) # in seconds user = models.ForeignKey(UserAccount, on_delete=models.CASCADE) completed = models.BooleanField(default=False) </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-3,994,879,931,140,667,400</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">39.896825</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">100</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.663497</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.56609</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45107"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">funshine/rpidemo</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mqtt_oled/oled_test_luma.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1273</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">#!/usr/bin/python/ # coding: utf-8 import time import datetime from luma.core.interface.serial import i2c, spi from luma.core.render import canvas from luma.oled.device import ssd1306, ssd1325, ssd1331, sh1106 def do_nothing(obj): pass # rev.1 users set port=0 # substitute spi(device=0, port=0) below if using that interface # serial = i2c(port=1, address=0x3C) serial = spi(device=0, port=0) # substitute ssd1331(...) or sh1106(...) below if using that device # device = ssd1306(serial, rotate=1) device = sh1106(serial) # device.cleanup = do_nothing print("Testing display Hello World") with canvas(device) as draw: draw.rectangle(device.bounding_box, outline="white", fill="black") draw.text((30, 40), "Hello World", fill="white") time.sleep(3) print("Testing display ON/OFF...") for _ in range(5): time.sleep(0.5) device.hide() time.sleep(0.5) device.show() print("Testing clear display...") time.sleep(2) device.clear() print("Testing screen updates...") time.sleep(2) for x in range(40): with canvas(device) as draw: now = datetime.datetime.now() draw.text((x, 4), str(now.date()), fill="white") draw.text((10, 16), str(now.time()), fill="white") time.sleep(0.1) print("Quit, cleanup...") </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">2,993,683,248,832,655,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">23.018868</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">70</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.671642</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.009456</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45108"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">jantman/nagios-scripts</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">check_icinga_ido.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">6939</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">#!/usr/bin/env python """ Script to check last update of core programstatus and service checks in Icinga ido2db Postgres database """ # # The latest version of this script lives at: # <https://github.com/jantman/nagios-scripts/blob/master/check_puppetdb_agent_run.py> # # Please file bug/feature requests and submit patches through # the above GitHub repository. Feedback and patches are greatly # appreciated; patches are preferred as GitHub pull requests, but # emailed patches are also accepted. # # Copyright 2014 Jason Antman <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="167c77657978567c776579787778627b77783875797b">[email protected]</a>> all rights reserved. # See the above git repository's LICENSE file for license terms (GPLv3). # import sys from datetime import datetime import pytz import logging import argparse from math import ceil import nagiosplugin import psycopg2 import pprint _log = logging.getLogger('nagiosplugin') utc = pytz.utc class IdoStatus(nagiosplugin.Resource): """Check age of ido2db programstatus and last service check in postgres database""" def __init__(self, db_host, db_name, db_user, db_pass, db_port=5432): self.db_host = db_host self.db_user = db_user self.db_pass = db_pass self.db_port = db_port self.db_name = db_name def probe(self): _log.info("connecting to Postgres DB %s on %s" % (self.db_name, self.db_host)) try: conn_str = "dbname='%s' user='%s' host='%s' password='%s' port='%s' application_name='%s'" % ( self.db_name, self.db_user, self.db_host, self.db_pass, self.db_port, "check_icinga_ido_core.py", ) _log.debug("psycopg2 connect string: %s" % conn_str) conn = psycopg2.connect(conn_str) except psycopg2.OperationalError, e: _log.info("got psycopg2.OperationalError: %s" % e.__str__()) raise nagiosplugin.CheckError(e.__str__()) _log.info("connected to database") # these queries come from https://wiki.icinga.org/display/testing/Special+IDOUtils+Queries cur = conn.cursor() _log.debug("got cursor") sql = "SELECT EXTRACT(EPOCH FROM (NOW()-status_update_time)) AS age from icinga_programstatus where (UNIX_TIMESTAMP(status_update_time) > UNIX_TIMESTAMP(NOW())-60);" _log.debug("executing query: %s" % sql) cur.execute(sql) row = cur.fetchone() _log.debug("result: %s" % row) programstatus_age = ceil(row[0]) sql = "select (UNIX_TIMESTAMP(NOW())-UNIX_TIMESTAMP(ss.status_update_time)) as age from icinga_servicestatus ss join icinga_objects os on os.object_id=ss.service_object_id order by status_update_time desc limit 1;" _log.debug("executing query: %s" % sql) cur.execute(sql) row = cur.fetchone() _log.debug("result: %s" % row) last_check_age = ceil(row[0]) return [ nagiosplugin.Metric('programstatus_age', programstatus_age, uom='s', min=0), nagiosplugin.Metric('last_check_age', last_check_age, uom='s', min=0), ] class LoadSummary(nagiosplugin.Summary): """LoadSummary is used to provide custom outputs to the check""" def __init__(self, db_name): self.db_name = db_name def _human_time(self, seconds): """convert an integer seconds into human-readable hms""" mins, secs = divmod(seconds, 60) hours, mins = divmod(mins, 60) return '%02d:%02d:%02d' % (hours, mins, secs) def _state_marker(self, state): """return a textual marker for result states""" if type(state) == type(nagiosplugin.state.Critical): return " (Crit)" if type(state) == type(nagiosplugin.state.Warn): return " (Warn)" if type(state) == type(nagiosplugin.state.Unknown): return " (Unk)" return "" def status_line(self, results): if type(results.most_significant_state) == type(nagiosplugin.state.Unknown): # won't have perf values, so special handling return results.most_significant[0].hint.splitlines()[0] return "Last Programstatus Update %s ago%s; Last Service Status Update %s ago%s (%s)" % ( self._human_time(results['programstatus_age'].metric.value), self._state_marker(results['programstatus_age'].state), self._human_time(results['last_check_age'].metric.value), self._state_marker(results['last_check_age'].state), self.db_name) def ok(self, results): return self.status_line(results) def problem(self, results): return self.status_line(results) @nagiosplugin.guarded def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-H', '--hostname', dest='hostname', help='Postgres server hostname') parser.add_argument('-p', '--port', dest='port', default='5432', help='Postgres port (Default: 5432)') parser.add_argument('-u', '--username', dest='username', default='icinga-ido', help='Postgres username (Default: icinga-ido)') parser.add_argument('-a', '--password', dest='password', default='icinga', help='Postgres password (Default: icinga)') parser.add_argument('-n', '--db-name', dest='db_name', default='icinga_ido', help='Postgres database name (Default: icinga_ido)') parser.add_argument('-w', '--warning', dest='warning', default='120', help='warning threshold for age of last programstatus or service status update, in seconds (Default: 120 / 2m)') parser.add_argument('-c', '--critical', dest='critical', default='600', help='critical threshold for age of last programstatus or service status update, in seconds (Default: 600 / 10m)') parser.add_argument('-v', '--verbose', action='count', default=0, help='increase output verbosity (use up to 3 times)') parser.add_argument('-t', '--timeout', dest='timeout', default=30, help='timeout (in seconds) for the command (Default: 30)') args = parser.parse_args() if not args.hostname: raise nagiosplugin.CheckError('hostname (-H|--hostname) must be provided') check = nagiosplugin.Check( IdoStatus(args.hostname, args.db_name, args.username, args.password, args.port), nagiosplugin.ScalarContext('programstatus_age', args.warning, args.critical), nagiosplugin.ScalarContext('last_check_age', args.warning, args.critical), LoadSummary(args.db_name)) check.main(args.verbose, args.timeout) if __name__ == '__main__': main() </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-3.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">4,422,069,438,603,399,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">41.833333</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">222</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.608157</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.785597</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45109"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">3DLIRIOUS/BlendSCAD</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">examples/example014.scad.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1763</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "># OpenSCAD example, ported by Michael Mlivoncic # a beautiful dice... # an interesting test case, to get the Boolean operations somehow fixed (TODO) #import sys #sys.path.append("O:/BlenderStuff") import blendscad #import imp #imp.reload(blendscad) #imp.reload(blendscad.core) #imp.reload(blendscad.primitives) blendscad.initns( globals() ) # try to add BlendSCAD names to current namespace .. as if they would be in this file... ## Clear the open .blend file!!! clearAllObjects() ###### End of Header ############################################################################## #OpenSCAD' intersection_for() is only a work around. As standard "for" implies a union of its content, this one is a combination of # for() and intersection() statements. # Not really needed as we currently do not support implicit union()'s, but to demonstrate, how it would be rewritten. # see: http://en.wikibooks.org/wiki/OpenSCAD_User_Manual/The_OpenSCAD_Language#Intersection_For_Loop # intersection_for(i = [ # [0, 0, 0], # [10, 20, 300], # [200, 40, 57], # [20, 88, 57] # ]) # rotate(i) cube([100, 20, 20], center = true) # example 2 - rotation: #intersection_for(i = [ ] tmp = None rnge = [ [ 0, 0, 0], [ 10, 20, 300], [200, 40, 57], [ 20, 88, 57] ] for i in rnge: tmp = intersection( rotate(i , cube([100, 20, 20], center = true)) , tmp); ###### Begin of Footer ############################################################################## color(rands(0,1,3)) # random color last object. to see "FINISH" :-) # print timestamp and finish - sometimes it is easier to see differences in console then :-) import time import datetime st = datetime.datetime.fromtimestamp( time.time() ).strftime('%Y-%m-%d %H:%M:%S') echo ("FINISH", st) </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-3.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-6,193,139,217,817,806,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">26.546875</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">131</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.614861</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.234862</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45110"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">stackunderflow-stackptr/stackptr_web</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">crossbarconnect/client.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">8527</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">############################################################################### ## ## Copyright (C) 2012-2014 Tavendo GmbH ## ## Licensed under the Apache License, Version 2.0 (the "License"); ## you may not use this file except in compliance with the License. ## You may obtain a copy of the License at ## ## http://www.apache.org/licenses/LICENSE-2.0 ## ## Unless required by applicable law or agreed to in writing, software ## distributed under the License is distributed on an "AS IS" BASIS, ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ## See the License for the specific language governing permissions and ## limitations under the License. ## ############################################################################### __all__ = ['Client'] try: import ssl _HAS_SSL = True except ImportError: _HAS_SSL = False import sys _HAS_SSL_CLIENT_CONTEXT = sys.version_info >= (2,7,9) import json import hmac import hashlib import base64 import random from datetime import datetime import six from six.moves.urllib import parse from six.moves.http_client import HTTPConnection, HTTPSConnection def _utcnow(): """ Get current time in UTC as ISO 8601 string. :returns str -- Current time as string in ISO 8601 format. """ now = datetime.utcnow() return now.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z" def _parse_url(url): """ Parses a Crossbar.io HTTP bridge URL. """ parsed = parse.urlparse(url) if parsed.scheme not in ["http", "https"]: raise Exception("invalid Push URL scheme '%s'" % parsed.scheme) if parsed.port is None or parsed.port == "": if parsed.scheme == "http": port = 80 elif parsed.scheme == "https": port = 443 else: raise Exception("logic error") else: port = int(parsed.port) if parsed.fragment is not None and parsed.fragment != "": raise Exception("invalid Push URL: non-empty fragment '%s" % parsed.fragment) if parsed.query is not None and parsed.query != "": raise Exception("invalid Push URL: non-empty query string '%s" % parsed.query) if parsed.path is not None and parsed.path != "": ppath = parsed.path path = parse.unquote(ppath) else: ppath = "/" path = ppath return {'secure': parsed.scheme == "https", 'host': parsed.hostname, 'port': port, 'path': path} class Client: """ Crossbar.io HTTP bridge client. """ def __init__(self, url, key = None, secret = None, timeout = 5, context = None): """ Create a new Crossbar.io push client. The only mandatory argument is the Push service endpoint of the Crossbar.io instance to push to. For signed pushes, provide authentication key and secret. If those are not given, unsigned pushes are performed. :param url: URL of the HTTP bridge of Crossbar.io (e.g. http://example.com:8080/push). :type url: str :param key: Optional key to use for signing requests. :type key: str :param secret: When using signed request, the secret corresponding to key. :type secret: str :param timeout: Timeout for requests. :type timeout: int :param context: If the HTTP bridge is running on HTTPS (that is securely over TLS), then the context provides the SSL settings the client should use (e.g. the certificate chain against which to verify the server certificate). This parameter is only available on Python 2.7.9+ and Python 3 (otherwise the parameter is silently ignored!). See: https://docs.python.org/2/library/ssl.html#ssl.SSLContext :type context: obj or None """ if six.PY2: if type(url) == str: url = six.u(url) if type(key) == str: key = six.u(key) if type(secret) == str: secret = six.u(secret) assert(type(url) == six.text_type) assert((key and secret) or (not key and not secret)) assert(key is None or type(key) == six.text_type) assert(secret is None or type(secret) == six.text_type) assert(type(timeout) == int) if _HAS_SSL and _HAS_SSL_CLIENT_CONTEXT: assert(context is None or isinstance(context, ssl.SSLContext)) self._seq = 1 self._key = key self._secret = secret self._endpoint = _parse_url(url) self._endpoint['headers'] = { "Content-type": "application/json", "User-agent": "crossbarconnect-python" } if self._endpoint['secure']: if not _HAS_SSL: raise Exception("Bridge URL is using HTTPS, but Python SSL module is missing") if _HAS_SSL_CLIENT_CONTEXT: self._connection = HTTPSConnection(self._endpoint['host'], self._endpoint['port'], timeout = timeout, context = context) else: self._connection = HTTPSConnection(self._endpoint['host'], self._endpoint['port'], timeout = timeout) else: self._connection = HTTPConnection(self._endpoint['host'], self._endpoint['port'], timeout = timeout) def publish(self, topic, *args, **kwargs): """ Publish an event to subscribers on specified topic via Crossbar.io HTTP bridge. The event payload (positional and keyword) can be of any type that can be serialized to JSON. If `kwargs` contains an `options` attribute, this is expected to be a dictionary with the following possible parameters: * `exclude`: A list of WAMP session IDs to exclude from receivers. * `eligible`: A list of WAMP session IDs eligible as receivers. :param topic: Topic to push to. :type topic: str :param args: Arbitrary application payload for the event (positional arguments). :type args: list :param kwargs: Arbitrary application payload for the event (keyword arguments). :type kwargs: dict :returns int -- The event publication ID assigned by the broker. """ if six.PY2 and type(topic) == str: topic = six.u(topic) assert(type(topic) == six.text_type) ## this will get filled and later serialized into HTTP/POST body ## event = { 'topic': topic } if 'options' in kwargs: event['options'] = kwargs.pop('options') assert(type(event['options']) == dict) if args: event['args'] = args if kwargs: event['kwargs'] = kwargs try: body = json.dumps(event, separators = (',',':')) if six.PY3: body = body.encode('utf8') except Exception as e: raise Exception("invalid event payload - not JSON serializable: {0}".format(e)) params = { 'timestamp': _utcnow(), 'seq': self._seq, } if self._key: ## if the request is to be signed, create extra fields and signature params['key'] = self._key params['nonce'] = random.randint(0, 9007199254740992) # HMAC[SHA256]_{secret} (key | timestamp | seq | nonce | body) => signature hm = hmac.new(self._secret.encode('utf8'), None, hashlib.sha256) hm.update(params['key'].encode('utf8')) hm.update(params['timestamp'].encode('utf8')) hm.update(u"{0}".format(params['seq']).encode('utf8')) hm.update(u"{0}".format(params['nonce']).encode('utf8')) hm.update(body) signature = base64.urlsafe_b64encode(hm.digest()) params['signature'] = signature self._seq += 1 path = "{0}?{1}".format(parse.quote(self._endpoint['path']), parse.urlencode(params)) ## now issue the HTTP/POST ## self._connection.request('POST', path, body, self._endpoint['headers']) response = self._connection.getresponse() response_body = response.read() if response.status not in [200, 202]: raise Exception("publication request failed {0} [{1}] - {2}".format(response.status, response.reason, response_body)) try: res = json.loads(response_body) except Exception as e: raise Exception("publication request bogus result - {0}".format(e)) return res['id'] </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">agpl-3.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3,583,649,226,256,367,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">32.108</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">126</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.587194</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">4.062411</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45111"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">VahidooX/DeepCCA</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">objectives.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">2281</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">import theano.tensor as T def cca_loss(outdim_size, use_all_singular_values): """ The main loss function (inner_cca_objective) is wrapped in this function due to the constraints imposed by Keras on objective functions """ def inner_cca_objective(y_true, y_pred): """ It is the loss function of CCA as introduced in the original paper. There can be other formulations. It is implemented by Theano tensor operations, and does not work on Tensorflow backend y_true is just ignored """ r1 = 1e-4 r2 = 1e-4 eps = 1e-12 o1 = o2 = y_pred.shape[1]//2 # unpack (separate) the output of networks for view 1 and view 2 H1 = y_pred[:, 0:o1].T H2 = y_pred[:, o1:o1+o2].T m = H1.shape[1] H1bar = H1 - (1.0 / m) * T.dot(H1, T.ones([m, m])) H2bar = H2 - (1.0 / m) * T.dot(H2, T.ones([m, m])) SigmaHat12 = (1.0 / (m - 1)) * T.dot(H1bar, H2bar.T) SigmaHat11 = (1.0 / (m - 1)) * T.dot(H1bar, H1bar.T) + r1 * T.eye(o1) SigmaHat22 = (1.0 / (m - 1)) * T.dot(H2bar, H2bar.T) + r2 * T.eye(o2) # Calculating the root inverse of covariance matrices by using eigen decomposition [D1, V1] = T.nlinalg.eigh(SigmaHat11) [D2, V2] = T.nlinalg.eigh(SigmaHat22) # Added to increase stability posInd1 = T.gt(D1, eps).nonzero()[0] D1 = D1[posInd1] V1 = V1[:, posInd1] posInd2 = T.gt(D2, eps).nonzero()[0] D2 = D2[posInd2] V2 = V2[:, posInd2] SigmaHat11RootInv = T.dot(T.dot(V1, T.nlinalg.diag(D1 ** -0.5)), V1.T) SigmaHat22RootInv = T.dot(T.dot(V2, T.nlinalg.diag(D2 ** -0.5)), V2.T) Tval = T.dot(T.dot(SigmaHat11RootInv, SigmaHat12), SigmaHat22RootInv) if use_all_singular_values: # all singular values are used to calculate the correlation corr = T.sqrt(T.nlinalg.trace(T.dot(Tval.T, Tval))) else: # just the top outdim_size singular values are used [U, V] = T.nlinalg.eigh(T.dot(Tval.T, Tval)) U = U[T.gt(U, eps).nonzero()[0]] U = U.sort() corr = T.sum(T.sqrt(U[0:outdim_size])) return -corr return inner_cca_objective </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">6,360,399,072,148,163,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">34.640625</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">108</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.562034</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">2.809113</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45112"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">macioosch/dynamo-hard-spheres-sim</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">convergence-plot.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">6346</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">#!/usr/bin/env python2 # encoding=utf-8 from __future__ import division, print_function from glob import glob from itertools import izip from matplotlib import pyplot as plt import numpy as np input_files = glob("csv/convergence-256000-0.*.csv") #input_files = glob("csv/convergence-500000-0.*.csv") #input_files = glob("csv/convergence-1000188-0.*.csv") #plotted_parameter = "msds_diffusion" plotted_parameter = "pressures_collision" #plotted_parameter = "pressures_virial" #plotted_parameter = "msds_val" #plotted_parameter = "times" legend_names = [] tight_layout = False show_legend = False for file_number, file_name in enumerate(sorted(input_files)): data = np.genfromtxt(file_name, delimiter='\t', names=[ "packings","densities","collisions","n_atoms","pressures_virial", "pressures_collision","msds_val","msds_diffusion","times", "std_pressures_virial","std_pressures_collision","std_msds_val", "std_msds_diffusion","std_times"]) n_atoms = data["n_atoms"][0] density = data["densities"][0] equilibrated_collisions = data["collisions"] - 2*data["collisions"][0] \ + data["collisions"][1] """ ### 5 graphs: D(CPS) ### tight_layout = True skip_points = 0 ax = plt.subplot(3, 2, file_number+1) plt.fill_between((equilibrated_collisions / n_atoms)[skip_points:], data[plotted_parameter][skip_points:] - data["std_" + plotted_parameter][skip_points:], data[plotted_parameter][skip_points:] + data["std_" + plotted_parameter][skip_points:], alpha=0.3) plt.plot((equilibrated_collisions / n_atoms)[skip_points:], data[plotted_parameter][skip_points:], lw=2) if plotted_parameter == "msds_diffusion": plt.ylim(0.990*data[plotted_parameter][-1], 1.005*data[plotted_parameter][-1]) plt.xlim([0, 1e5]) plt.legend(["Density {}".format(data["densities"][0])], loc="lower right") ax.yaxis.set_major_formatter(plt.FormatStrFormatter('%.4f')) plt.xlabel("Collisions per sphere") plt.ylabel("D") """ ### 5 graphs: relative D(CPS) ### tight_layout = True skip_points = 0 ax = plt.subplot(3, 2, file_number+1) plt.fill_between((equilibrated_collisions / n_atoms)[skip_points:], -1 + (data[plotted_parameter][skip_points:] - data["std_" + plotted_parameter][skip_points:])/data[plotted_parameter][-1], -1 + (data[plotted_parameter][skip_points:] + data["std_" + plotted_parameter][skip_points:])/data[plotted_parameter][-1], alpha=0.3) plt.plot((equilibrated_collisions / n_atoms)[skip_points:], -1 + data[plotted_parameter][skip_points:]/data[plotted_parameter][-1], lw=2) plt.ylim(data["std_" + plotted_parameter][-1]*20*np.array([-1, 1])/data[plotted_parameter][-1]) #plt.xscale("log") plt.xlim([0, 1e5]) plt.legend(["$\\rho\\sigma^3=\\ {}$".format(data["densities"][0])], loc="lower right") ax.yaxis.set_major_formatter(plt.FormatStrFormatter('%.2e')) plt.xlabel("$C/N$") plt.ylabel("$[Z_{MD}(C) / Z_{MD}(C=10^5 N)] - 1$") """ ### 1 graph: D(t) ### show_legend = True skip_points = 0 plt.title("D(t) for 5 densities") plt.loglog(data["times"][skip_points:], data[plotted_parameter][skip_points:]) legend_names.append(data["densities"][0]) plt.xlabel("Time") plt.ylabel("D") """ """ ### 1 graph: D(t) / Dinf ### show_legend = True skip_points = 0 #plt.fill_between(data["times"][skip_points:], # (data[plotted_parameter] - data["std_" + plotted_parameter]) # / data[plotted_parameter][-1] - 1, # (data[plotted_parameter] + data["std_" + plotted_parameter]) # / data[plotted_parameter][-1] - 1, color="grey", alpha=0.4) plt.plot(data["times"][skip_points:], data[plotted_parameter] / data[plotted_parameter][-1] - 1, lw=1) legend_names.append(data["densities"][0]) #plt.xscale("log") plt.xlabel("Time") plt.ylabel("D / D(t --> inf)") """ """ ### 5 graphs: D(1/CPS) ### tight_layout = True skip_points = 40 ax = plt.subplot(3, 2, file_number+1) plt.fill_between((n_atoms / equilibrated_collisions)[skip_points:], data[plotted_parameter][skip_points:] - data["std_" + plotted_parameter][skip_points:], data[plotted_parameter][skip_points:] + data["std_" + plotted_parameter][skip_points:], alpha=0.3) plt.plot((n_atoms / equilibrated_collisions)[skip_points:], data[plotted_parameter][skip_points:], lw=2) plt.title("Density {}:".format(data["densities"][0])) ax.yaxis.set_major_formatter(plt.FormatStrFormatter('%.7f')) plt.xlim(xmin=0) plt.xlabel("1 / Collisions per sphere") plt.ylabel("D") """ """ ### 1 graph: D(CPS) / Dinf ### show_legend = True plt.fill_between(equilibrated_collisions / n_atoms, (data[plotted_parameter] - data["std_" + plotted_parameter]) / data[plotted_parameter][-1] - 1, (data[plotted_parameter] + data["std_" + plotted_parameter]) / data[plotted_parameter][-1] - 1, color="grey", alpha=0.4) plt.plot(equilibrated_collisions / n_atoms, data[plotted_parameter] / data[plotted_parameter][-1] - 1, lw=2) legend_names.append(data["densities"][0]) plt.xlabel("Collisions per sphere") plt.ylabel("D / D(t --> inf)") """ """ ### 1 graph: D(1/CPS) / Dinf ### show_legend = True plt.fill_between(n_atoms / equilibrated_collisions, (data[plotted_parameter] - data["std_" + plotted_parameter]) / data[plotted_parameter][-1] - 1, (data[plotted_parameter] + data["std_" + plotted_parameter]) / data[plotted_parameter][-1] - 1, color="grey", alpha=0.4) plt.plot( n_atoms / equilibrated_collisions, data[plotted_parameter] / data[plotted_parameter][-1] - 1) legend_names.append(data["densities"][0]) plt.xlabel(" 1 / Collisions per sphere") plt.ylabel(plotted_parameter) """ #if tight_layout: # plt.tight_layout(pad=0.0, w_pad=0.0, h_pad=0.0) if show_legend: plt.legend(legend_names, title="Density:", loc="lower right") plt.show() </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-3.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">1,205,206,185,801,680,600</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">39.941935</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">101</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.601954</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.083576</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45113"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">amdouglas/OpenPNM</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">OpenPNM/Geometry/models/throat_misc.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1124</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">r""" =============================================================================== throat_misc -- Miscillaneous and generic functions to apply to throats =============================================================================== """ import scipy as _sp def random(geometry, seed=None, num_range=[0, 1], **kwargs): r""" Assign random number to throats note: should this be called 'poisson'? """ range_size = num_range[1] - num_range[0] range_min = num_range[0] _sp.random.seed(seed=seed) value = _sp.random.rand(geometry.num_throats(),) value = value*range_size + range_min return value def neighbor(geometry, network, pore_prop='pore.seed', mode='min', **kwargs): r""" Adopt a value based on the neighboring pores """ throats = network.throats(geometry.name) P12 = network.find_connected_pores(throats) pvalues = network[pore_prop][P12] if mode == 'min': value = _sp.amin(pvalues, axis=1) if mode == 'max': value = _sp.amax(pvalues, axis=1) if mode == 'mean': value = _sp.mean(pvalues, axis=1) return value </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">7,511,632,487,340,780,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">30.222222</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">79</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.536477</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.523511</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45114"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Digmaster/TicTacToe</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Agent.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">2030</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">from random import randint from random import getrandbits from copy import deepcopy # Agent that will either be the human player or a secondary agent for the dual agent play class DumbAgent: #initialize the board for the first player def __init__(self, board): self.board = board def __str__(self): return "Hi, Im dumb agent. I play randomly as player {0}".format(self.player) # readin the next move for the human or secondary agent def getNextMove(self, player): board = deepcopy(self.board) if(player!='X' and player!='O'): raise ValueError('The only valid players are X and O') while(True): try: square = randint(1, 9) board.setSquare(square, player) return square except ValueError: """Do nothing""" # Define the smart agent - uses the minimax algorithm class SmartAgent: def __init__(self, board): self.board = board self.signal = False self.bestVal = None def __str__(self): return "Hi, Im smart agent. I whatever move will net me the most points, or avail my enemy of points. I'm {0}".format(self.player) # to get the next move,call the decideMove function def getNextMove(self, player): self.decideMove(deepcopy(self.board), player) return self.bestVal def decideMove(self, board, player): if(self.signal): return 0 winner = board.testWin() # test for a winning solution to the current state if(winner!='.'): if(winner=='X'): return 1.0 elif(winner=='T'): return 0.0 else: return -1.0 values = [] moves = {} for i in range(1,10): if(self.signal): return 0 if(board.getSquare(i)=='.'): nBoard = deepcopy(board) nBoard.setSquare(i, player) value = self.decideMove(nBoard, 'X' if player=='O' else 'O') values.append(value) moves[value] = i if(player=='X'and value==1): break elif(player=='O' and value==-1): break # calculate the highest probability / best move if(player=='X'): sum = max(values) else: sum = min(values) self.bestVal = moves[sum] return sum </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">apache-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">287,197,937,694,822,820</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">25.363636</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">132</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.666995</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.142415</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45115"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mfit/PdfTableAnnotator</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">script/csv-compare.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">8051</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">""" Copyright 2014 Matthias Frey Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ """ CSV-compare ----------- Compare table data stored in CSV (comma seperated values) format. """ import re import csv import sys import os def _pr_list(l1, l2, replace_chars = '[\n ]'): """ Calculate precision and recall regarding elements of a list. When a 1:1 match cannot be achieved, the list pointers will be moved forward until a match occurs (first of list A, then of list B). The closest match will count, and matching will continue from those list positions onwards. The replace_chars parameter is used to remove characters from the strings before comparing. The default will remove newlines and spaces. """ def _fnext(l, item): item = re.sub(replace_chars, '', item).strip() for i, txt in enumerate(l): txt = re.sub(replace_chars, '', txt).strip() if txt == item: return i return -1 if len(l2)==0 or len(l1)==0: return 0, 0 i = 0 j = 0 match = 0 while len(l1)>i and len(l2)>j: t1 = re.sub(replace_chars, '', l1[i]).strip() t2 = re.sub(replace_chars, '', l2[j]).strip() if t1 == t2: match += 1 i += 1 j += 1 else: ii = _fnext(l1[i:], l2[j]) jj = _fnext(l2[j:], l1[i]) if ii>=0 and (ii<jj or jj<0): i+=ii elif jj>=0: j+=jj else: i+=1 j+=1 return float(match)/len(l2), float(match)/len(l1) def clean_table(tab): """ Remove trailing empty cells resulting from the way some spreadsheet application output csv for multi table documents. """ if len(tab) == 0: return [] n_empty=[] for row in tab: for n, val in enumerate(reversed(row)): if val!='': break n_empty.append(n) strip_cols = min(n_empty) cleaned = [] for row in tab: cleaned.append(row[0:len(row)-strip_cols]) return cleaned def compare_tables(tab1, tab2): """ Compare two tables (2dim lists). """ info = {'rows_a':len(tab1), 'rows_b':len(tab2), 'rows_match': 1 if len(tab1) == len(tab2) else 0, } sizesA = [len(l) for l in tab1] sizesB = [len(l) for l in tab2] info['dim_match'] = 1 if sizesA == sizesB else 0 info['size_a'] = sum(sizesA) info['size_b'] = sum(sizesA) if len(sizesA)>0 and len(sizesB)>0: info['cols_match'] = 1 if min(sizesA) == max(sizesA) and \ min(sizesB) == max(sizesB) and min(sizesA) == min(sizesB) else 0 # 'flatten' tables cellsA = [] cellsB = [] for r in tab1: cellsA += [c for c in r] for r in tab2: cellsB += [c for c in r] info['p'], info['r'] = _pr_list(cellsA, cellsB) info['F1'] = F1(info['p'], info['r']) return info def compare_files_pr(file1, file2): """ Calculate simple P/R . Compare lists of cells, left to right , top to bottom. """ cells = [[], []] for i, fname in enumerate([file1, file2]): with file(fname) as csvfile: rd = csv.reader(csvfile, delimiter=',', quotechar='"') for r in rd: cells[i] += [c for c in r] return _pr_list(*cells) def compare_files(file1, file2): """ Compare two csv files. """ groundtruth = read_tables_from_file(file1) try: compare = read_tables_from_file(file2) except: compare = [] tbs = [groundtruth, compare] finfo = {'tabcount_a': len(tbs[0]), 'tabcount_b': len(tbs[1]), 'tabcount_match': len(tbs[0]) == len(tbs[1]), } finfo['tables']=[] for n in range(0, len(tbs[0])): if finfo['tabcount_match']: comp_info = compare_tables(tbs[0][n], tbs[1][n]) else: if n < len(tbs[1]): comp_info = compare_tables(tbs[0][n], tbs[1][n]) else: comp_info = compare_tables(tbs[0][n], [[]]) comp_info['n']=n finfo['tables'].append(comp_info) return finfo def output_compareinfo_csv(file, info, fields=['p', 'r', 'F1']): """ Pre-format a row that holds measures about similarity of a table to the ground truth. """ lines = [] tabmatch = 1 if info['tabcount_match'] else 0 for tinfo in info['tables']: lines.append([file, str(tabmatch)] + [str(tinfo[k]) for k in fields]) return lines def F1(p, r): """ Calculate F1 score from precision and recall. Returns zero if one of p, r is zero. """ return (2*p*r/(p+r)) if p != 0 and r != 0 else 0 def read_tables_from_file(csvfile): """ Opens csvfile, returns all tables found. Guesses csv format (delimiter, etc.) Splits data into different tables at newline (or empty row). Returns list of tables. """ tables=[] table_id = 0 with file(csvfile) as f: sniffer = csv.Sniffer() dialect = sniffer.sniff(f.next()) rd = csv.reader(f, delimiter=dialect.delimiter, quotechar=dialect.quotechar) for r in rd: if len(tables) <= table_id: tables.append([]) # Begin next table if there is an empty line if r == [] or sum([len(v) for v in r]) == 0: if len(tables[table_id])>0: table_id+=1 else: tables[table_id].append(r) return [clean_table(t) for t in tables if t!=[]] if __name__ == '__main__': """ Script usage. """ fields = [ #'rows_a', 'rows_b', #'size_a', 'size_b', 'n', 'rows_match', 'cols_match', 'dim_match', 'p', 'r', 'F1',] limitchar = ' & ' if len(sys.argv) < 3: print "Specify two (csv-)files or directories" quit(-1) # Params 1 + 2 are files or directories file1 = sys.argv[1] file2 = sys.argv[2] srcinfo = [os.path.basename(file1), os.path.basename(file2)] # 3rd parameter becomes 'tooldef' (text cols to name rows), # and 4th parameter tells whether to print headers tooldef = sys.argv[3].split('-') if len(sys.argv) > 3 else ['na', 'na'] print_headers = len(sys.argv) > 4 and sys.argv[4] in ["1", "y", "yes"] if print_headers: print ','.join(['name', 'tool', 'src1', 'src2', 'filename', 'tabsmatch',] + fields) if os.path.isfile(file1) and os.path.isfile(file2): inf = compare_files(file1, file2) lines = output_compareinfo_csv(file1, inf, fields) for l in lines: print ','.join(tooldef + srcinfo + l) elif os.path.isdir(file1) and os.path.isdir(file2): for f in [path for path in os.listdir(file1) if path[-4:]=='.csv']: if os.path.isfile(file2 + '/' + f): inf = compare_files(file1 + '/' + f, file2 + '/' + f) lines = output_compareinfo_csv(f, inf, fields) for l in lines: print ','.join(tooldef + srcinfo + l) else: print ','.join(['','',] + srcinfo + ['', "Missing {} for {} {}".format(f, *tooldef)])</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">apache-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-7,229,538,163,487,513,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">29.044776</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">101</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.527264</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.549824</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45116"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">locke105/mclib</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">examples/wsgi.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1781</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "> import cgi import json from wsgiref import simple_server import falcon from mclib import mc_info class MCInfo(object): def on_get(self, req, resp): host = req.get_param('host', required=True) port = req.get_param_as_int('port', min=1024, max=65565) try: if port is not None: info = mc_info.get_info(host=host, port=port) else: info = mc_info.get_info(host=host) except Exception: raise Exception('Couldn\'t retrieve info.') if '.json' in req.uri: resp.body = self.get_json(info) return preferred = req.client_prefers(['application/json', 'text/html']) if 'html' in preferred: resp.content_type = 'text/html' resp.body = self.get_html(info) else: resp.body = self.get_json(info) def get_html(self, info): html = """<body> <style> table,th,td { border:1px solid black; border-collapse:collapse } th,td { padding: 5px } </style> <table> """ for k,v in info.iteritems(): items = {'key': cgi.escape(k)} if isinstance(v, basestring): items['val'] = cgi.escape(v) else: items['val'] = v html = html + '<tr><td>%(key)s</td><td>%(val)s</td></tr>' % items html = html + '</table></body>' return html def get_json(self, info): return json.dumps(info) app = falcon.API() mcinfo = MCInfo() app.add_route('/mcinfo', mcinfo) app.add_route('/mcinfo.json', mcinfo) if __name__ == '__main__': httpd = simple_server.make_server('0.0.0.0', 3000, app) httpd.serve_forever() </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">apache-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">4,936,456,139,620,774,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">21.2625</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">77</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.521617</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.485323</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45117"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Meertecha/LearnPythonTheGame</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">pyGameEngine.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">3565</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">### Imports import pickle, os, platform, random ### Functions def main(): curPlayer = loadPlayer( 'Tory' ) curGame = loadGame( 'Python_Tutorial' ) startGame(curPlayer, curGame) def banner(): ''' if platform.system() == "Windows": clearCmd = "cls" elif platform.system() == "Linux": clearCmd = "clear" else: print ("Unknown operating system detected. Some operations may not perform correctly!\n") os.system(clearCmd) ''' version = 0.1 banner = (" **Welcome to the Python Learning Environment\n\ **Written by Tory Clasen - Version: " + str(version) + " \n\ **For help at any time please type '?' or 'help' \n\ **To exit the program type 'exit' or 'quit' \n\n") print banner def startGame(curPlayer, curGame): try: curScore = curPlayer['score'][curGame['gameName']] except: curScore = 0 while True: #banner() print '----------------------------------------\n' + curGame['gameName'] + ' has been loaded' print curGame['banner'] + '\n----------------------------------------' try: pickle.dump( curPlayer, open( ( str(curPlayer['Name']) + ".plep"), "wb" ) ) except: print "Error! Unable to save player profile at current location!" print 'Your current score is: ' + str(curScore) + ' out of a total possible score of: ' + str(len(curGame['gameData'])) print "Question " + str(curScore) + ": \n" + str(curGame['gameData'][curScore]["Q"]) + "\n" temp = curGame['gameData'][curScore]["D"] data = eval(str(curGame['gameData'][curScore]["D"])) print "Data " + str(curScore) + ": \n" + data print '----------------------------------------\n' try: myAnswer = eval(str(getInput('What command do you want to submit? '))) if myAnswer == (eval(str(curGame['gameData'][curScore]["A"]))): print "Correct!" curScore = curScore + 1 else: print "Incorrect!" except: print 'The answer you submitted crashed the program, so it was probably wrong' #break def getInput(prompt): theInput = raw_input( str(prompt) + "\n" ) if theInput == '?' or theInput.lower() == 'help': print "HELP! HELP!" elif theInput.lower() == 'exit' or theInput.lower() == 'quit': raise SystemExit else: return theInput def loadPlayer(playerName = ''): #banner() curPlayer = {} if playerName == '': playerName = getInput("I would like to load your profile. \nWhat is your name? ") try: # Attempt to load the player file. curPlayer = pickle.load( open( ( str(playerName) + ".plep"), "rb" ) ) print "Player profile found... loading player data..." except: # Ask the player if they want to try to create a new profile file. createNew = getInput( "Player profile not found for '" + str(playerName) + "'\nWould you like to create a new one? [Y/N]").lower() curPlayer = {'Name':playerName} if createNew == "y": try: pickle.dump( curPlayer, open( ( str(playerName) + ".plep"), "wb" ) ) print "Player profile successfully created!" except: print "Error! Unable to create player profile at current location!" else: print "Progress will not be saved for you..." return curPlayer def loadGame(gameName = ''): banner() curGame = {} while True: if gameName == '': gameName = getInput("What game would you like to load? ") try: # Attempt to load the player file. curGame = pickle.load( open( ( str(gameName) + ".pleg"), "rb" ) ) print "Game module found... loading game data..." gameName = '' break except: gameName = '' print "Game module not found... please try again..." return curGame main() </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">4,891,151,655,040,956,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">31.409091</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">133</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.615708</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.229167</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45118"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">openbig/odoo-contract</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">partner_billing/wizard/sale_make_invoice_advance.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1615</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "># -*- encoding: utf-8 -*- ############################################################################## # # partner_billing # (C) 2015 Mikołaj Dziurzyński, Grzegorz Grzelak, Thorsten Vocks (big-consulting GmbH) # All Rights reserved # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.osv import osv from openerp import fields, models import logging _logger = logging.getLogger(__name__) class sale_advance_payment_inv(osv.osv_memory): _inherit = "sale.advance.payment.inv" def _prepare_advance_invoice_vals(self, cr, uid, ids, context=None): res = super(sale_advance_payment_inv,self)._prepare_advance_invoice_vals(cr, uid, ids, context=context) sale_order_obj = self.pool.get('sale.order') for pair in res: for sale in sale_order_obj.browse(cr, uid, [pair[0]]): pair[1]['associated_partner'] = sale.associated_partner and sale.associated_partner.id or False return res </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">agpl-3.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-6,439,668,196,751,878,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">39.325</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">105</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.651581</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.751163</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45119"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">lipixun/pytest</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">rabbitmq/deadchannel/going2dead.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">2112</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">#!/usr/bin/env python # encoding=utf8 # The dead channel applicationn import sys reload(sys) sys.setdefaultencoding('utf8') from uuid import uuid4 from time import time, sleep from haigha.connections.rabbit_connection import RabbitConnection from haigha.message import Message class Client(object): """The RPC Client """ def __init__(self, host, port, vhost, user, password): """Create a new Server """ self._conn = RabbitConnection(host = host, port = port, vhost = vhost, user = user, password = password) self._channel = self._conn.channel() result = self._channel.queue.declare(arguments = { 'x-dead-letter-exchange': 'amq.topic', 'x-dead-letter-routing-key': 'test.dead_channel' }) self._deadQueue = result[0] # Send a message self._channel.basic.publish(Message('OMG! I\'m dead!'), '', self._deadQueue) def dead(self): """Normal dead """ self._channel.close() if __name__ == '__main__': from argparse import ArgumentParser def getArguments(): """Get arguments """ parser = ArgumentParser(description = 'RabbitMQ dead channel client') parser.add_argument('--host', dest = 'host', required = True, help = 'The host') parser.add_argument('--port', dest = 'port', default = 5672, type = int, help = 'The port') parser.add_argument('--vhost', dest = 'vhost', default = '/test', help = 'The virtual host') parser.add_argument('--user', dest = 'user', default = 'test', help = 'The user name') parser.add_argument('--password', dest = 'password', default = 'test', help = 'The password') # Done return parser.parse_args() def main(): """The main entry """ args = getArguments() # Create the server client = Client(args.host, args.port, args.vhost, args.user, args.password) # Go to dead print 'Will go to dead in 10s, or you can use ctrl + c to cause a unexpected death' sleep(10) client.dead() print 'Normal dead' main() </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-8,202,055,047,594,408,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">33.064516</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">149</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.606061</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.84</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45120"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gf712/AbPyTools</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">abpytools/core/fab_collection.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">14123</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">from .chain_collection import ChainCollection import numpy as np import pandas as pd from .chain import calculate_charge from abpytools.utils import DataLoader from operator import itemgetter from .fab import Fab from .helper_functions import germline_identity_pd, to_numbering_table from .base import CollectionBase import os import json from .utils import (json_FabCollection_formatter, pb2_FabCollection_formatter, pb2_FabCollection_parser, json_FabCollection_parser) from .flags import * if BACKEND_FLAGS.HAS_PROTO: from abpytools.core.formats import FabCollectionProto class FabCollection(CollectionBase): def __init__(self, fab=None, heavy_chains=None, light_chains=None, names=None): """ Fab object container that handles combinations of light/heavy Chain pairs. Args: fab (list): heavy_chains (ChainCollection): light_chains (ChainCollection): names (list): """ # check if it's a Chain object if heavy_chains is None and light_chains is None and fab is None: raise ValueError('Provide a list of Chain objects or an ChainCollection object') # check if fab object is a list and if all object are abpytools.Fab objects if isinstance(fab, list) and all(isinstance(fab_i, Fab) for fab_i in fab): self._fab = fab self._light_chains = ChainCollection([x[0] for x in self._fab]) self._heavy_chains = ChainCollection([x[1] for x in self._fab]) if fab is None and (heavy_chains is not None and light_chains is not None): if isinstance(heavy_chains, list): self._heavy_chains = ChainCollection(antibody_objects=heavy_chains) elif isinstance(heavy_chains, ChainCollection): self._heavy_chains = heavy_chains else: raise ValueError('Provide a list of Chain objects or an ChainCollection object') if isinstance(light_chains, list): self._light_chains = ChainCollection(antibody_objects=light_chains) elif isinstance(light_chains, ChainCollection): self._light_chains = light_chains else: raise ValueError('Provide a list of Chain objects or an ChainCollection object') if len(self._light_chains.loading_status()) == 0: self._light_chains.load() if len(self._heavy_chains.loading_status()) == 0: self._heavy_chains.load() if self._light_chains.n_ab != self._heavy_chains.n_ab: raise ValueError('Number of heavy chains must be the same of light chains') if isinstance(names, list) and all(isinstance(name, str) for name in names): if len(names) == self._heavy_chains.n_ab: self._names = names else: raise ValueError( 'Length of name list must be the same as length of heavy_chains/light chains lists') elif names is None: self._names = ['{} - {}'.format(heavy, light) for heavy, light in zip(self._heavy_chains.names, self._light_chains.names)] else: raise ValueError("Names expected a list of strings, instead got {}".format(type(names))) self._n_ab = self._light_chains.n_ab self._pair_sequences = [heavy + light for light, heavy in zip(self._heavy_chains.sequences, self._light_chains.sequences)] # keep the name of the heavy and light chains internally to keep everything in the right order self._internal_heavy_name = self._heavy_chains.names self._internal_light_name = self._light_chains.names # even though it makes more sense to draw all these values from the base Fab objects this is much slower # whenever self._n_ab > 1 it makes more sense to use the self._heavy_chain and self._light_chain containers # in all the methods # in essence the abpytools.Fab object is just a representative building block that could in future just # cache data and would then represent a speed up in the calculations def molecular_weights(self, monoisotopic=False): return [heavy + light for heavy, light in zip(self._heavy_chains.molecular_weights(monoisotopic=monoisotopic), self._light_chains.molecular_weights(monoisotopic=monoisotopic))] def extinction_coefficients(self, extinction_coefficient_database='Standard', reduced=False, normalise=False, **kwargs): heavy_ec = self._heavy_chains.extinction_coefficients( extinction_coefficient_database=extinction_coefficient_database, reduced=reduced) light_ec = self._light_chains.extinction_coefficients( extinction_coefficient_database=extinction_coefficient_database, reduced=reduced) if normalise: return [(heavy + light) / mw for heavy, light, mw in zip(heavy_ec, light_ec, self.molecular_weights(**kwargs))] else: return [heavy + light for heavy, light in zip(heavy_ec, light_ec)] def hydrophobicity_matrix(self): return np.column_stack((self._heavy_chains.hydrophobicity_matrix(), self._light_chains.hydrophobicity_matrix())) def charge(self): return np.column_stack((self._heavy_chains.charge, self._light_chains.charge)) def total_charge(self, ph=7.4, pka_database='Wikipedia'): available_pi_databases = ["EMBOSS", "DTASetect", "Solomon", "Sillero", "Rodwell", "Wikipedia", "Lehninger", "Grimsley"] assert pka_database in available_pi_databases, \ "Selected pI database {} not available. Available databases: {}".format(pka_database, ' ,'.join(available_pi_databases)) data_loader = DataLoader(data_type='AminoAcidProperties', data=['pI', pka_database]) pka_data = data_loader.get_data() return [calculate_charge(sequence=seq, ph=ph, pka_values=pka_data) for seq in self.sequences] def igblast_local_query(self, file_path, chain): if chain.lower() == 'light': self._light_chains.igblast_local_query(file_path=file_path) elif chain.lower() == 'heavy': self._heavy_chains.igblast_local_query(file_path=file_path) else: raise ValueError('Specify if the data being loaded is for the heavy or light chain') def igblast_server_query(self, **kwargs): self._light_chains.igblast_server_query(**kwargs) self._heavy_chains.igblast_server_query(**kwargs) def numbering_table(self, as_array=False, region='all', chain='both', **kwargs): return to_numbering_table(as_array=as_array, region=region, chain=chain, heavy_chains_numbering_table=self._heavy_chains.numbering_table, light_chains_numbering_table=self._light_chains.numbering_table, names=self.names, **kwargs) def _germline_pd(self): # empty dictionaries return false, so this condition checks if any of the values are False if all([x for x in self._light_chains.germline_identity.values()]) is False: # this means there is no information about the germline, # by default it will run a web query self._light_chains.igblast_server_query() if all([x for x in self._heavy_chains.germline_identity.values()]) is False: self._heavy_chains.igblast_server_query() heavy_chain_germlines = self._heavy_chains.germline light_chain_germlines = self._light_chains.germline data = np.array([[heavy_chain_germlines[x][0] for x in self._internal_heavy_name], [heavy_chain_germlines[x][1] for x in self._internal_heavy_name], [light_chain_germlines[x][0] for x in self._internal_light_name], [light_chain_germlines[x][1] for x in self._internal_light_name]]).T df = pd.DataFrame(data=data, columns=pd.MultiIndex.from_tuples([('Heavy', 'Assignment'), ('Heavy', 'Score'), ('Light', 'Assignment'), ('Light', 'Score')]), index=self.names) df.loc[:, (slice(None), 'Score')] = df.loc[:, (slice(None), 'Score')].apply(pd.to_numeric) return df def save_to_json(self, path, update=True): with open(os.path.join(path + '.json'), 'w') as f: fab_data = json_FabCollection_formatter(self) json.dump(fab_data, f, indent=2) def save_to_pb2(self, path, update=True): proto_parser = FabCollectionProto() try: with open(os.path.join(path + '.pb2'), 'rb') as f: proto_parser.ParseFromString(f.read()) except IOError: # Creating new file pass pb2_FabCollection_formatter(self, proto_parser) with open(os.path.join(path + '.pb2'), 'wb') as f: f.write(proto_parser.SerializeToString()) def save_to_fasta(self, path, update=True): raise NotImplementedError @classmethod def load_from_json(cls, path, n_threads=20, verbose=True, show_progressbar=True): with open(path, 'r') as f: data = json.load(f) fab_objects = json_FabCollection_parser(data) fab_collection = cls(fab=fab_objects) return fab_collection @classmethod def load_from_pb2(cls, path, n_threads=20, verbose=True, show_progressbar=True): with open(path, 'rb') as f: proto_parser = FabCollectionProto() proto_parser.ParseFromString(f.read()) fab_objects = pb2_FabCollection_parser(proto_parser) fab_collection = cls(fab=fab_objects) return fab_collection @classmethod def load_from_fasta(cls, path, numbering_scheme=NUMBERING_FLAGS.CHOTHIA, n_threads=20, verbose=True, show_progressbar=True): raise NotImplementedError def _get_names_iter(self, chain='both'): if chain == 'both': for light_chain, heavy_chain in zip(self._light_chains, self._heavy_chains): yield f"{light_chain.name}-{heavy_chain.name}" elif chain == 'light': for light_chain in self._light_chains: yield light_chain.name elif chain == 'heavy': for heavy_chain in self._heavy_chains: yield heavy_chain.name else: raise ValueError(f"Unknown chain type ({chain}), available options are:" f"both, light or heavy.") @property def regions(self): heavy_regions = self._heavy_chains.ab_region_index() light_regions = self._light_chains.ab_region_index() return {name: {CHAIN_FLAGS.HEAVY_CHAIN: heavy_regions[heavy], CHAIN_FLAGS.LIGHT_CHAIN: light_regions[light]} for name, heavy, light in zip(self.names, self._internal_heavy_name, self._internal_light_name)} @property def names(self): return self._names @property def sequences(self): return self._pair_sequences @property def aligned_sequences(self): return [heavy + light for light, heavy in zip(self._heavy_chains.aligned_sequences, self._light_chains.aligned_sequences)] @property def n_ab(self): return self._n_ab @property def germline_identity(self): return self._germline_identity() @property def germline(self): return self._germline_pd() def _string_summary_basic(self): return "abpytools.FabCollection Number of sequences: {}".format(self._n_ab) def __len__(self): return self._n_ab def __repr__(self): return "<%s at 0x%02x>" % (self._string_summary_basic(), id(self)) def __getitem__(self, indices): if isinstance(indices, int): return Fab(heavy_chain=self._heavy_chains[indices], light_chain=self._light_chains[indices], name=self.names[indices], load=False) else: return FabCollection(heavy_chains=list(itemgetter(*indices)(self._heavy_chains)), light_chains=list(itemgetter(*indices)(self._light_chains)), names=list(itemgetter(*indices)(self._names))) def _germline_identity(self): # empty dictionaries return false, so this condition checks if any of the values are False if all([x for x in self._light_chains.germline_identity.values()]) is False: # this means there is no information about the germline, # by default it will run a web query self._light_chains.igblast_server_query() if all([x for x in self._heavy_chains.germline_identity.values()]) is False: self._heavy_chains.igblast_server_query() return germline_identity_pd(self._heavy_chains.germline_identity, self._light_chains.germline_identity, self._internal_heavy_name, self._internal_light_name, self._names) def get_object(self, name): """ :param name: str :return: """ if name in self.names: index = self.names.index(name) return self[index] else: raise ValueError('Could not find sequence with specified name') </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-4,991,626,911,150,680,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">41.158209</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">120</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.593075</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">4.025941</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45121"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">jwill89/clifford-discord-bot</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">source/retired/main.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">31345</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">import discord from discord.ext import commands import random import MySQLdb # ********************************************** # # DEFINITIONS ********************************** # # ********************************************** # # Bot Description description = '''Official Zealot Gaming Discord bot!''' # Define Bot bot = commands.Bot(command_prefix='!', description='Official Zealot Gaming Discord Bot') # Define MySQL DB and Cursor Object db = MySQLdb.connect(host="localhost", user="discord_secure", passwd="password-here", db="discord") # ********************************************** # # FUNCTIONS ************************************ # # ********************************************** # # Check for Game Abbreviations def is_game_abv(game_abv: str): try: sql = "SELECT 1 FROM games WHERE `abv` = %s LIMIT 1" cur = db.cursor() result = cur.execute(sql, (game_abv,)) cur.close() except Exception as e: print('Exception: ' + str(e)) result = 0 # If we got a result, true, else false return result == 1 # Check for Game Names def is_game_name(game_name: str): try: sql = "SELECT 1 FROM games WHERE `name` = %s LIMIT 1" cur = db.cursor() result = cur.execute(sql, (game_name,)) cur.close() except Exception as e: print('Exception: ' + str(e)) result = 0 # If we got a result, true, else false return result == 1 # Check for Staff Member Status def is_staff(member: discord.Member): # Return True or False if User is a Staff Member return 'Staff' in [r.name for r in member.roles] # ********************************************** # # BOT EVENTS *********************************** # # ********************************************** # # Bot Start Event @bot.event async def on_ready(): print('Logged in as') print(bot.user.name) print(bot.user.id) print('------') await bot.change_presence(game=discord.Game(name='Zealot Gaming')) # Welcome Message @bot.event async def on_member_join(member): channel = bot.get_channel('108369515502411776') fmt = "Everyone welcome {0.mention} to Zealot Gaming! Have a great time here! :wink: " \ "http://puu.sh/nG6Qe.wav".format(member) await bot.send_message(channel, fmt) # Goodbye Message @bot.event async def on_member_remove(member): channel = bot.get_channel('108369515502411776') fmt = ":wave: Goodbye {0}, we're sad to see you go!".format(member.name) await bot.send_message(channel, fmt) # ********************************************** # # UN-GROUPED BOT COMMANDS ********************** # # ********************************************** # # COMMAND: !hello @bot.command(pass_context=True) async def hello(ctx): # we do not want the bot to reply to itself if ctx.message.author == bot.user: return else: msg = 'Hello {0.message.author.mention}'.format(ctx) await bot.send_message(ctx.message.channel, msg) # COMMAND: !carlito @bot.command() async def carlito(): """The legendary message of Carlito, maz00's personal cabana boy.""" await bot.say("wew men :ok_hand::skin-tone-1: that's some good shit:100: some good shit :100: that's some good shit" " right there :100: :ok_hand::skin-tone-1: right there :ok_hand::skin-tone-1: :100: sign me the FUCK " "up:100: :100: :ok_hand::skin-tone-1: :eggplant:") # COMMAND: !eightball @bot.command(pass_context=True) async def eightball(ctx, question: str): """Rolls a magic 8-ball to answer any question you have.""" if question is None: await bot.say('{0.message.author.mention}, you did not ask a question.'.format(ctx)) return # Answers List (Classic 8-Ball, 20 Answers) answers = ['It is certain.', 'It is decidedly so', 'Without a doubt.', 'Yes, definitely.', 'You may rely on it.', 'As I see it, yes.', 'Most likely.', 'Outlook good.', 'Yes.', 'Signs point to yes.', 'Reply hazy; try again.', 'Ask again later.', 'Better not tell you now.', 'Cannot predict now.', 'Concentrate, then ask again.', 'Do not count on it.', 'My reply is no.', 'My sources say no.', 'Outlook not so good.', 'Very doubtful.'] # Send the Answer await bot.say('{0.message.author.mention}, '.format(ctx) + random.choice(answers)) # COMMAND: !roll @bot.command() async def roll(dice: str): """Rolls a dice in NdN format.""" try: rolls, limit = map(int, dice.split('d')) except Exception: await bot.say('Format has to be in NdN!') return result = ', '.join(str(random.randint(1, limit)) for r in range(rolls)) await bot.say(result) # COMMAND: !choose @bot.command() async def choose(*choices: str): """Chooses between multiple choices.""" await bot.say(random.choice(choices)) # COMMAND: !joined @bot.command() async def joined(member: discord.Member): """Says when a member joined.""" await bot.say('{0.name} joined in {0.joined_at}'.format(member)) # COMMAND: !get_roles @bot.command() async def get_roles(member: discord.Member): """Lists a User's Roles""" total = 0 role_list = '' for role in member.roles: if total > 0: role_list += ', ' role_list += str(role) total += 1 await bot.say('{0.name} is a member of these roles: '.format(member) + role_list) # COMMAND: !get_channel_id @bot.command(pass_context=True) async def get_channel_id(ctx): """Lists the ID of the channel the message is sent in.""" # Is the user allowed? (Must be staff) if not is_staff(ctx.message.author): await bot.say('{0.mention}, you must be a staff member to use this command.'.format(ctx.message.author)) return await bot.say('Channel ID is {0.id}'.format(ctx.message.channel)) # COMMAND: !join @bot.command(pass_context=True) async def join(ctx, *, role_name: str): """Allows a user to join a public group.""" # List of Allowed Public Roles allowed_roles = ['Europe', 'North America', 'Oceania', 'Overwatch', 'League of Legends', 'Co-op', 'Minna-chan'] if role_name not in allowed_roles: await bot.say('{0.mention}, you may only join allowed public groups.'.format(ctx.message.author)) return # Define role, then add role to member. try: role = discord.utils.get(ctx.message.server.roles, name=role_name) await bot.add_roles(ctx.message.author, role) except Exception as e: await bot.send_message(ctx.message.channel, "{0.mention}, there was an error getting the roster for you. " "I'm sorry! : ".format(ctx.message.author) + str(e)) return # Success Message await bot.say('{0.mention}, you have successfully been added to the group **{1}**.' .format(ctx.message.author, role_name)) # ********************************************** # # GROUPED COMMANDS : EVENTS ******************** # # ********************************************** # # COMMAND: !events @bot.group(pass_context=True) async def events(ctx): """Manage events and attendance!""" if ctx.invoked_subcommand is None: await bot.say('Invalid command passed. Must be *add*, *description*, *edit*, *register*, or *remove*.') # COMMAND: !events add @events.command(name='add', pass_context=True) async def events_add(ctx, date: str, time: str, *, title: str): """Add an event to the Events List! Date **must** be in YYYY/MM/DD format. Time **must** be in UTC.""" # Set #events Channel event_channel = bot.get_channel('296694692135829504') # Is the user allowed? (Must be staff) if not is_staff(ctx.message.author): await bot.say('{0.mention}, you must be a staff member to use this command.'.format(ctx.message.author)) return # Make sure we have a date. if date is None: await bot.say('Error: You must enter a date in YYYY/MM/DD format.') return # Make sure we have a time. if time is None: await bot.say('Error: You must enter a time in HH:MM format in UTC timezone.') return # Make sure we have a title. if date is None: await bot.say('Error: You must enter a title for the event.') return # Add Event to Database try: sql = "INSERT INTO events (`date`,`time`,`title`) VALUES (%s, %s, %s)" cur = db.cursor() cur.execute(sql, (date, time, title)) event_id = cur.lastrowid msg_text = "**Title**: {0} \n**Event ID**: {1} \n**Date & Time**: {2} at {3} (UTC)" # Add Message to Events Channel and Save Message ID message = await bot.send_message(event_channel, msg_text.format(title, event_id, date, time)) cur.execute('UPDATE events SET `message_id` = %s WHERE `event_id` = %s', (message.id, event_id)) db.commit() cur.close() except Exception as e: await bot.say('{0.mention}, there was an error adding the event to the list. '.format(ctx.message.author) + str(e)) return # Success Message await bot.say('{0.mention}, your event was successfully added. The event ID is: {1}.' .format(ctx.message.author, event_id)) # COMMAND: !events description @events.command(name='description', pass_context=True) async def events_description(ctx, event_id: int, *, desc: str): """Adds a Description to an Event Given an Event ID.""" # EVENT CHANNEL ID: 296694692135829504 event_channel = bot.get_channel('296694692135829504') # Is the user allowed? (Must be staff) if not is_staff(ctx.message.author): await bot.say('{0.mention}, you must be a staff member to use this command.'.format(ctx.message.author)) return # Make sure we have a date. if event_id is None: await bot.say('Error: You must enter an event ID. Check the #events channel.') return # Make sure we have a date. if desc is None: await bot.say('Error: You must enter a description.') return try: sql = "UPDATE events SET `description` = %s WHERE `event_id` = %s" cur = db.cursor() cur.execute(sql, (desc, event_id)) cur.execute("SELECT `message_id` FROM events WHERE `event_id` = %s", (event_id,)) msg_id = cur.fetchone() message = await bot.get_message(event_channel, msg_id[0]) msg_text = message.content + " \n**Description**: {0}".format(desc) # Update Message in Events Channel with Description await bot.edit_message(message, msg_text) db.commit() cur.close() except Exception as e: await bot.say('{0.mention}, there was an error adding a description to the event. '.format(ctx.message.author) + str(e)) return # Success Message await bot.say('{0.mention}, the event was successfully updated with a description.'.format(ctx.message.author)) # ********************************************** # # GROUPED COMMANDS : GAMES ********************* # # ********************************************** # # COMMAND: !games @bot.group(pass_context=True) async def games(ctx): """Manages games for the roster.""" if ctx.invoked_subcommand is None: await bot.say('Invalid command passed. Must be *add*, *edit*, *list*, or *remove*.') # COMMAND: !games add @games.command(name='add', pass_context=True) async def games_add(ctx, game_abv: str, *, game_name: str): """Adds a game to the list of games available in the roster.""" # Is the user allowed? (Must be staff) if not is_staff(ctx.message.author): await bot.say('{0.mention}, you must be a staff member to use this command.'.format(ctx.message.author)) return # Does Game Abbreviation Exist? if is_game_abv(game_abv): await bot.say('{0.mention}, this abbreviation is already in use.'.format(ctx.message.author)) return # Does Game Name Exist? if is_game_name(game_name): await bot.say('{0.mention}, this game is already in the list.'.format(ctx.message.author)) return # Handle Database try: sql = "INSERT INTO games (`abv`,`name`) VALUES (%s, %s)" cur = db.cursor() cur.execute(sql, (game_abv, game_name)) db.commit() cur.close() except Exception as e: await bot.say('{0.mention}, there was an error adding the game to the games list. '.format(ctx.message.author) + str(e)) return # Display Success Message await bot.say('{0.mention}, the game was successfully added to the games list!'.format(ctx.message.author)) # COMMAND: !games edit @games.command(name='edit', pass_context=True) async def games_edit(ctx, game_abv: str, *, game_name: str): """Updates a game in the list of games available in the roster.""" # Is the user allowed? (Must be staff) if not is_staff(ctx.message.author): await bot.say('{0.mention}, you must be a staff member to use this command.'.format(ctx.message.author)) return # Is there anything to update? if not (is_game_abv(game_abv) or is_game_name(game_name)): await bot.say('{0.mention}, either the abbreviation of game must exist to update.'.format(ctx.message.author)) return # Handle Database try: sql = "UPDATE games SET `abv` = %s, `name = %s WHERE `abv` = %s OR `name` = %s" cur = db.cursor() cur.execute(sql, (game_abv, game_name, game_abv, game_name)) db.commit() cur.close() except Exception as e: await bot.say('{0.mention}, there was an error updating the game in the games list. '.format(ctx.message.author) + str(e)) return # Display Success Message await bot.say('{0.mention}, the game was successfully updated in the games list!'.format(ctx.message.author)) # COMMAND: !games remove @games.command(name='remove', pass_context=True) async def games_remove(ctx, *, game_or_abv: str): """Removes a game from the list of games available in the roster.""" # Is the user allowed? (Must be staff) if not is_staff(ctx.message.author): await bot.say('{0.mention}, you must be a staff member to use this command.'.format(ctx.message.author)) return # Is there anything to update? if not (is_game_abv(game_or_abv) or is_game_name(game_or_abv)): await bot.say('{0.mention}, either the abbreviation of game must exist to update.'.format(ctx.message.author)) return # Handle Database try: sql = "DELETE FROM games WHERE `abv` = %s OR `name` = %s" cur = db.cursor() cur.execute(sql, (game_or_abv, game_or_abv)) db.commit() cur.close() except Exception as e: await bot.say("{0.mention}, there was an error deleting the game from the games list." " ".format(ctx.message.author) + str(e)) return # Display Success Message await bot.say('{0.mention}, the game was successfully deleted from the games list!'.format(ctx.message.author)) # COMMAND: !games list @games.command(name='list', pass_context=True) async def games_list(ctx): """Sends a message to the user with the current games and abbreviations for use in the roster.""" # Handle Database try: sql = "SELECT `abv`, `name` FROM games ORDER BY `name`" cur = db.cursor() cur.execute(sql) result = cur.fetchall() cur.close() except Exception: await bot.send_message(ctx.message.channel, "{0.mention}, there was an error getting the list of games for you." " I'm sorry!".format(ctx.message.author)) return # Create Variables for Embed Table abvs = '' names = '' for row in result: abvs += (row[0] + '\n') names += (row[1] + '\n') # Create Embed Table embed = discord.Embed() embed.add_field(name="Abbreviation", value=abvs, inline=True) embed.add_field(name="Game Name", value=names, inline=True) # Send Table to User Privately await bot.send_message(ctx.message.channel, embed=embed) # ********************************************** # # GROUPED COMMANDS : ROSTER ******************** # # ********************************************** # # COMMAND: !roster @bot.group(pass_context=True) async def roster(ctx): """Handles Roster Management.""" if ctx.invoked_subcommand is None: await bot.say('Invalid roster command passed. Must be *add*, *edit*, *list*, or *remove*.') # COMMAND: !roster add @roster.command(name='add', pass_context=True) async def roster_add(ctx, game_abv: str, *, ign: str): """Adds username to roster. User a game abbreviation from the games list. Only one entry per game. Include all in-game names if necessary.""" username = str(ctx.message.author) # Does Game Abbreviation Exist? if not is_game_abv(game_abv): await bot.say('{0.mention}, this abbreviation does not exist. Use !games display for a list of acceptable game ' 'abbreviations.'.format(ctx.message.author)) return # Handle Database try: sql = "INSERT INTO roster (`discord_account`,`game_abv`,`game_account`) VALUES (%s, %s, %s)" cur = db.cursor() cur.execute(sql, (username, game_abv, ign)) db.commit() cur.close() except Exception: await bot.say('{0.message.author.mention}, there was an error adding your information to the roster.'.format(ctx)) return # Display Success Message await bot.say('{0.message.author.mention}, your information was successfully added to the roster!'.format(ctx)) # COMMAND: !roster edit @roster.command(name='edit', pass_context=True) async def roster_edit(ctx, game_abv: str, *, ign: str): """Updates a roster entry for a specific game. If the either Game Name or your in-Game Name have spaces, put them in quotes.""" username = str(ctx.message.author) # Does Game Abbreviation Exist? if not is_game_abv(game_abv): await bot.say('{0.mention}, this abbreviation does not exist. Use !games display for a list of acceptable game' ' abbreviations.'.format(ctx.message.author)) return # Handle Database try: sql = "UPDATE roster SET `game_account` = %s WHERE `discord_account` = %s AND `game_abv` = %s" cur = db.cursor() cur.execute(sql, (ign, username, game_abv)) db.commit() cur.close() except Exception: await bot.say('{0.message.author.mention}, there was an error updating your roster information.'.format(ctx)) return # Display Success Message await bot.say('{0.message.author.mention}, your roster information was successfully updated!'.format(ctx)) # COMMAND: !roster remove @roster.command(name='remove', pass_context=True) async def roster_remove(ctx, game_abv: str, *, ign: str): """Removes a user's entries in the roster for the specified game.""" username = str(ctx.message.author) # Does Game Abbreviation Exist? if not is_game_abv(game_abv): await bot.say('{0.mention}, this abbreviation does not exist. Use !games display for a list of acceptable ' 'game abbreviations.'.format(ctx.message.author)) return # Handle Database try: sql = "DELETE FROM roster WHERE `discord_account` = %s AND `game_abv` = %s AND `game_account` = %s" cur = db.cursor() cur.execute(sql, (username, game_abv, ign)) db.commit() cur.close() except Exception: await bot.say('{0.message.author.mention}, there was an error deleting your roster information.'.format(ctx)) return # Display Success Message await bot.say('{0.message.author.mention}, your roster information was successfully deleted!'.format(ctx)) # COMMAND: !roster list @roster.command(name='list', pass_context=True) async def roster_list(ctx, game_abv: str): """Sends a message to the user with the current roster for the specified game.""" # Does Game Abbreviation Exist? if not is_game_abv(game_abv): await bot.say('{0.mention}, this abbreviation does not exist. Use !games display for a list of acceptable game ' 'abbreviations.'.format(ctx.message.author)) return # Handle Database try: sql = "SELECT `discord_account`, `game_account` FROM roster WHERE `game_abv` = %s ORDER BY `discord_account`" cur = db.cursor() cur.execute(sql, (game_abv,)) result = cur.fetchall() cur.close() except Exception: await bot.send_message(ctx.message.channel, "{0.mention}, there was an error getting the roster for you. " "I'm sorry!".format(ctx.message.author)) return # Create Variables for Embed Table accounts = '' names = '' for row in result: accounts += (row[0] + '\n') names += (row[1] + '\n') # Create Embed Table embed = discord.Embed() embed.add_field(name="Discord Account", value=accounts, inline=True) embed.add_field(name="In-Game Name", value=names, inline=True) # Send Table to Channel await bot.send_message(ctx.message.channel, embed=embed) # ********************************************** # # GROUPED COMMANDS : RECRUIT ******************* # # ********************************************** # # COMMAND: !recruit @bot.group(pass_context=True) async def recruit(ctx): """Handles Recruitment Post and Invites Management.""" if ctx.invoked_subcommand is None: await bot.say('Invalid recruitment command passed. Must be *add*, *edit*, *invite*, *list*, or *remove*.') # COMMAND: !recruit add @recruit.command(name='add', pass_context=True) async def recruit_add(ctx, game_abv: str, *, link: str): """Adds recruitment post link to the recruitment list. Use a game abbreviation from the games list.""" # Is the user allowed? (Must be staff) if not is_staff(ctx.message.author): await bot.say('{0.mention}, you must be a staff member to use this command.'.format(ctx.message.author)) return # Does Game Abbreviation Exist? if not is_game_abv(game_abv): await bot.say( '{0.mention}, this abbreviation does not exist. Use !games display for a list of acceptable game ' 'abbreviations.'.format(ctx.message.author)) return # Handle Database try: sql = "INSERT INTO recruitment (`game`,`link`) VALUES (%s, %s)" cur = db.cursor() cur.execute(sql, (game_abv, link)) db.commit() cur.close() except Exception: await bot.say( '{0.message.author.mention}, there was an error adding your recruitment link to the list.'.format(ctx)) return # Display Success Message await bot.say('{0.message.author.mention}, your information was successfully added to the recruitment ' 'posts list!'.format(ctx)) # COMMAND: !recruit edit @recruit.command(name='edit', pass_context=True) async def roster_edit(ctx, entry_id: int, *, link: str): """Updates a recruitment post entry with the specified entry ID.""" # Is the user allowed? (Must be staff) if not is_staff(ctx.message.author): await bot.say('{0.mention}, you must be a staff member to use this command.'.format(ctx.message.author)) return # Handle Database try: sql = "UPDATE recruitment SET `link` = %s WHERE `entry_id` = %s" cur = db.cursor() cur.execute(sql, (link, entry_id)) db.commit() cur.close() except Exception: await bot.say('{0.message.author.mention}, there was an error updating the specified ' 'recruitment entry.'.format(ctx)) return # Display Success Message await bot.say('{0.message.author.mention}, the recruitment entry was successfully updated!'.format(ctx)) # COMMAND: !recruit remove @recruit.command(name='remove', pass_context=True) async def recruit_remove(ctx, entry_id: int): """Removes an entry for the recruitment posts list with the specified entry ID.""" # Is the user allowed? (Must be staff) if not is_staff(ctx.message.author): await bot.say('{0.mention}, you must be a staff member to use this command.'.format(ctx.message.author)) return # Handle Database try: sql = "DELETE FROM recruitment WHERE `entry_id` = %s" cur = db.cursor() cur.execute(sql, (entry_id,)) db.commit() cur.close() except Exception: await bot.say('{0.message.author.mention}, there was an error deleting the specified ' 'recruitment entry.'.format(ctx)) return # Display Success Message await bot.say('{0.message.author.mention}, the recruitment entry was successfully deleted!'.format(ctx)) # COMMAND: !recruit list @recruit.command(name='list', pass_context=True) async def recruit_list(ctx): """Lists all recruitment post entries in the system.""" # Handle Database try: sql = "SELECT * FROM recruitment ORDER BY `game`" cur = db.cursor() cur.execute(sql) result = cur.fetchall() cur.close() except Exception: await bot.send_message(ctx.message.channel, "{0.mention}, there was an error getting the recruitment list " "for you. I'm sorry!".format(ctx.message.author)) return # Create Variables for Embed Table entries = '' game_abvs = '' links = '' for row in result: entries += (row[0] + '\n') game_abvs += (row[1] + '\n') links += (row[2] + '\n') # Create Embed Table embed = discord.Embed() embed.add_field(name="ID", value=entries, inline=True) embed.add_field(name="Game", value=game_abvs, inline=True) embed.add_field(name="Link", value=links, inline=True) # Send Table to Channel await bot.send_message(ctx.message.channel, embed=embed) # COMMAND: !recruit invite @recruit.command(name='invite') async def recruit_invite(duration: int): """Provides an invite link to the Discord server. Set duration to 0 for permanent invite.""" # Default Duration 30 Minutes, Else Convert to Minutes if duration is None: duration = 1800 else: duration *= 60 # WELCOME CHANNEL ID: 141622052133142529 welcome_channel = bot.get_channel('141622052133142529') # Create the Invite new_invite = await bot.create_invite(welcome_channel, max_age=duration) # Send Message with Invite Link await bot.say('Your newly generated invite link is: {0.url}'.format(new_invite)) # ********************************************** # # MODERATOR COMMANDS *************************** # # ********************************************** # # COMMAND: !give_role @bot.command(pass_context=True) async def give_role(ctx, username: str, *, role_name: str): """Assigns a role to a user.""" # List of Roles Staff Can Add To. allowed_roles = ['Europe', 'North America', 'Oceania', 'Overwatch', 'League of Legends', 'Co-op', 'Minna-chan', 'Squire', 'Knight', 'Zealot'] # Is the user allowed? (Must be Staff) if not is_staff(ctx.message.author): await bot.say('{0.mention}, you must be a staff member to use this command.'.format(ctx.message.author)) return if role_name not in allowed_roles: await bot.say('{0.mention}, you may only assign users to public roles, Guest, or Registered Member' .format(ctx.message.author)) return # Define role, then add role to member. try: role = discord.utils.get(ctx.message.server.roles, name=role_name) user = discord.utils.get(ctx.message.server.members, name=username) await bot.add_roles(user, role) except Exception as e: await bot.send_message(ctx.message.channel, "{0.mention}, there was an granting the role to the user." " ".format(ctx.message.author) + str(e)) return # Success Message await bot.say('{0.mention}, you have successfully added **{1}** to the group **{2}**' '.'.format(ctx.message.author, username, role_name)) # COMMAND: !kick @bot.command(name='kick', pass_context=True) async def mod_kick(ctx, username: str, *, reason: str): """Kicks a user from the server.""" # User must be a staff member if not is_staff(ctx.message.author): await bot.say('{0.mention}, you must be a staff member to use this command.'.format(ctx.message.author)) return # Add to DB and Post Message try: # Variables Needed member = discord.utils.get(ctx.message.server.members, name=username) staffer = ctx.message.author # Handle Database sql = "INSERT INTO mod_log (`action`,`user`, `user_id`, `staff`, `staff_id`, reason) " \ "VALUES ('kick', %s, %s, %s, %s, %s)" cur = db.cursor() cur.execute(sql, (str(member), member.id, str(staffer), staffer.id, reason)) # Save Last Row ID case_id = cur.lastrowid # Insert Message log_channel = bot.get_channel('303262467205890051') msg_text = "**Case #{0}** | Kick :boot: \n**User**: {1} ({2}) " \ "\n**Moderator**: {3} ({4}) \n**Reason**: {5}" # Add Message to Events Channel and Save Message ID case_message = await bot.send_message(log_channel, msg_text.format(case_id, str(member), member.id, str(staffer), staffer.id, reason)) cur.execute("UPDATE mod_log SET `message_id` = %s WHERE `case_id` = %s", (case_message.id, case_id)) # Finish Database Stuff and Commit db.commit() cur.close() # Kick the Member await bot.kick(member) except Exception as e: await bot.send_message(ctx.message.channel, "{0.mention}, there was an error when kicking the user." " ".format(ctx.message.author) + str(e)) await bot.say("{0.mention}, the user was successfully kicked. A log entry has been added.".format(ctx.message.author)) # ********************************************** # # START THE BOT ******************************** # # ********************************************** # # Run the Bot bot.run('token-here') </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-3.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">2,852,675,339,850,913,300</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">33.866518</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">142</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.58759</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.716945</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45122"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">nicain/dipde_dev</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">dipde/interfaces/zmq/__init__.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">4371</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">import time import zmq import threading context = zmq.Context() class PublishCallback(object): def __init__(self, port, topic, message_callback): self.port = port self.topic = topic self.message_callback = message_callback self.socket = context.socket(zmq.PUB) def __call__(self, obj): message_to_send = list(self.message_callback(obj)) message_to_send.insert(0,"%s" % self.topic) self.socket.send_multipart(map(str, message_to_send)) class PublishCallbackConnect(PublishCallback): def __init__(self, port, topic, message_callback): super(self.__class__, self).__init__(port, topic, message_callback) self.socket.connect("tcp://localhost:%s" % self.port) class CallbackSubscriber(object): def __init__(self, port=None, receive_callback=None): self.socket = context.socket(zmq.SUB) if port is None: self.port = self.socket.bind_to_random_port('tcp://*', min_port=6001, max_port=6004, max_tries=100) else: self.socket.bind("tcp://*:%s" % port) self.port = port self.socket.setsockopt(zmq.SUBSCRIBE, 'test') if receive_callback is None: def receive_callback(received_message): print received_message self.receive_callback = receive_callback def run(self): while True: received_message_multipart = self.socket.recv_multipart() topic = received_message_multipart[0] received_message = received_message_multipart[1:] self.receive_callback(received_message) class CallbackSubscriberThread(threading.Thread): def __init__(self, port=None): super(self.__class__, self).__init__() self.subscriber = CallbackSubscriber(port) self.daemon = True def run(self, port=None): self.subscriber.run() @property def port(self): return self.subscriber.port class RequestConnection(object): def __init__(self, port): self.port = port self.socket = context.socket(zmq.REQ) self.socket.connect("tcp://localhost:%s" % port) def __call__(self, *args): if len(args) == 0: self.socket.send(b'') else: self.socket.send_multipart(map(str,args)) message = self.socket.recv_multipart() return float(message[0]) def shutdown(self): self.socket.close() assert self.socket.closed class ReplyServerBind(object): def __init__(self, reply_function, port=None): self.socket = context.socket(zmq.REP) if port is None: self.port = self.socket.bind_to_random_port('tcp://*', min_port=6001, max_port=6004, max_tries=100) else: self.socket.bind("tcp://*:%s" % port) self.port = port self.reply_function = reply_function def run(self): while True: message = self.socket.recv() # print 'message:', message, type(message) if message == 'SHUTDOWN': break # print 'message' if message == '': requested_args = tuple() else: requested_args = tuple([float(message)]) self.socket.send_multipart([b"%s" % self.reply_function(*requested_args)]) self.socket.send('DOWN') self.socket.close() class ReplyServerThread(threading.Thread): def __init__(self, reply_function, port=None): super(ReplyServerThread, self).__init__() self._stop = threading.Event() self.daemon = True self.reply_function = reply_function self.server = ReplyServerBind(self.reply_function, port=port) def run(self, port=None): self.server.run() def shutdown(self): shutdown_socket = context.socket(zmq.REQ) shutdown_socket.connect("tcp://localhost:%s" % self.port) shutdown_socket.send('SHUTDOWN') message = shutdown_socket.recv() assert message == 'DOWN' self.stop() def stop(self): self._stop.set() def stopped(self): return self._stop.isSet() @property def port(self): return self.server.port </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-3.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-8,901,712,531,665,347,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">27.94702</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">111</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.577442</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">4.028571</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45123"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">yantrabuddhi/nativeclient</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">buildbot/buildbot_lib.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">21952</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">#!/usr/bin/python # Copyright (c) 2012 The Native Client Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import optparse import os.path import shutil import subprocess import stat import sys import time import traceback ARCH_MAP = { '32': { 'gyp_arch': 'ia32', 'scons_platform': 'x86-32', }, '64': { 'gyp_arch': 'x64', 'scons_platform': 'x86-64', }, 'arm': { 'gyp_arch': 'arm', 'scons_platform': 'arm', }, 'mips32': { 'gyp_arch': 'mips32', 'scons_platform': 'mips32', }, } def RunningOnBuildbot(): return os.environ.get('BUILDBOT_SLAVE_TYPE') is not None def GetHostPlatform(): sys_platform = sys.platform.lower() if sys_platform.startswith('linux'): return 'linux' elif sys_platform in ('win', 'win32', 'windows', 'cygwin'): return 'win' elif sys_platform in ('darwin', 'mac'): return 'mac' else: raise Exception('Can not determine the platform!') def SetDefaultContextAttributes(context): """ Set default values for the attributes needed by the SCons function, so that SCons can be run without needing ParseStandardCommandLine """ platform = GetHostPlatform() context['platform'] = platform context['mode'] = 'opt' context['default_scons_mode'] = ['opt-host', 'nacl'] context['default_scons_platform'] = ('x86-64' if platform == 'win' else 'x86-32') context['android'] = False context['clang'] = False context['asan'] = False context['pnacl'] = False context['use_glibc'] = False context['use_breakpad_tools'] = False context['max_jobs'] = 8 context['scons_args'] = [] # Windows-specific environment manipulation def SetupWindowsEnvironment(context): # Poke around looking for MSVC. We should do something more principled in # the future. # The name of Program Files can differ, depending on the bittage of Windows. program_files = r'c:\Program Files (x86)' if not os.path.exists(program_files): program_files = r'c:\Program Files' if not os.path.exists(program_files): raise Exception('Cannot find the Program Files directory!') # The location of MSVC can differ depending on the version. msvc_locs = [ ('Microsoft Visual Studio 12.0', 'VS120COMNTOOLS', '2013'), ('Microsoft Visual Studio 10.0', 'VS100COMNTOOLS', '2010'), ('Microsoft Visual Studio 9.0', 'VS90COMNTOOLS', '2008'), ('Microsoft Visual Studio 8.0', 'VS80COMNTOOLS', '2005'), ] for dirname, comntools_var, gyp_msvs_version in msvc_locs: msvc = os.path.join(program_files, dirname) context.SetEnv('GYP_MSVS_VERSION', gyp_msvs_version) if os.path.exists(msvc): break else: # The break statement did not execute. raise Exception('Cannot find MSVC!') # Put MSVC in the path. vc = os.path.join(msvc, 'VC') comntools = os.path.join(msvc, 'Common7', 'Tools') perf = os.path.join(msvc, 'Team Tools', 'Performance Tools') context.SetEnv('PATH', os.pathsep.join([ context.GetEnv('PATH'), vc, comntools, perf])) # SCons needs this variable to find vsvars.bat. # The end slash is needed because the batch files expect it. context.SetEnv(comntools_var, comntools + '\\') # This environment variable will SCons to print debug info while it searches # for MSVC. context.SetEnv('SCONS_MSCOMMON_DEBUG', '-') # Needed for finding devenv. context['msvc'] = msvc SetupGyp(context, []) def SetupGyp(context, extra_vars=[]): if RunningOnBuildbot(): goma_opts = [ 'use_goma=1', 'gomadir=/b/build/goma', ] else: goma_opts = [] context.SetEnv('GYP_DEFINES', ' '.join( context['gyp_vars'] + goma_opts + extra_vars)) def SetupLinuxEnvironment(context): if context['arch'] == 'mips32': # Ensure the trusted mips toolchain is installed. cmd = ['build/package_version/package_version.py', '--packages', 'linux_x86/mips_trusted', 'sync', '-x'] Command(context, cmd) SetupGyp(context, ['target_arch='+context['gyp_arch']]) def SetupMacEnvironment(context): SetupGyp(context, ['target_arch='+context['gyp_arch']]) def SetupAndroidEnvironment(context): SetupGyp(context, ['OS=android', 'target_arch='+context['gyp_arch']]) context.SetEnv('GYP_CROSSCOMPILE', '1') def ParseStandardCommandLine(context): """ The standard buildbot scripts require 3 arguments to run. The first argument (dbg/opt) controls if the build is a debug or a release build. The second argument (32/64) controls the machine architecture being targeted. The third argument (newlib/glibc) controls which c library we're using for the nexes. Different buildbots may have different sets of arguments. """ parser = optparse.OptionParser() parser.add_option('-n', '--dry-run', dest='dry_run', default=False, action='store_true', help='Do not execute any commands.') parser.add_option('--inside-toolchain', dest='inside_toolchain', default=bool(os.environ.get('INSIDE_TOOLCHAIN')), action='store_true', help='Inside toolchain build.') parser.add_option('--android', dest='android', default=False, action='store_true', help='Build for Android.') parser.add_option('--clang', dest='clang', default=False, action='store_true', help='Build trusted code with Clang.') parser.add_option('--coverage', dest='coverage', default=False, action='store_true', help='Build and test for code coverage.') parser.add_option('--validator', dest='validator', default=False, action='store_true', help='Only run validator regression test') parser.add_option('--asan', dest='asan', default=False, action='store_true', help='Build trusted code with ASan.') parser.add_option('--scons-args', dest='scons_args', default =[], action='append', help='Extra scons arguments.') parser.add_option('--step-suffix', metavar='SUFFIX', default='', help='Append SUFFIX to buildbot step names.') parser.add_option('--no-gyp', dest='no_gyp', default=False, action='store_true', help='Do not run the gyp build') parser.add_option('--no-goma', dest='no_goma', default=False, action='store_true', help='Do not run with goma') parser.add_option('--use-breakpad-tools', dest='use_breakpad_tools', default=False, action='store_true', help='Use breakpad tools for testing') parser.add_option('--skip-build', dest='skip_build', default=False, action='store_true', help='Skip building steps in buildbot_pnacl') parser.add_option('--skip-run', dest='skip_run', default=False, action='store_true', help='Skip test-running steps in buildbot_pnacl') options, args = parser.parse_args() if len(args) != 3: parser.error('Expected 3 arguments: mode arch toolchain') # script + 3 args == 4 mode, arch, toolchain = args if mode not in ('dbg', 'opt', 'coverage'): parser.error('Invalid mode %r' % mode) if arch not in ARCH_MAP: parser.error('Invalid arch %r' % arch) if toolchain not in ('newlib', 'glibc', 'pnacl', 'nacl_clang'): parser.error('Invalid toolchain %r' % toolchain) # TODO(ncbray) allow a command-line override platform = GetHostPlatform() context['platform'] = platform context['mode'] = mode context['arch'] = arch context['android'] = options.android # ASan is Clang, so set the flag to simplify other checks. context['clang'] = options.clang or options.asan context['validator'] = options.validator context['asan'] = options.asan # TODO(ncbray) turn derived values into methods. context['gyp_mode'] = { 'opt': 'Release', 'dbg': 'Debug', 'coverage': 'Debug'}[mode] context['gn_is_debug'] = { 'opt': 'false', 'dbg': 'true', 'coverage': 'true'}[mode] context['gyp_arch'] = ARCH_MAP[arch]['gyp_arch'] context['gyp_vars'] = [] if context['clang']: context['gyp_vars'].append('clang=1') if context['asan']: context['gyp_vars'].append('asan=1') context['default_scons_platform'] = ARCH_MAP[arch]['scons_platform'] context['default_scons_mode'] = ['nacl'] # Only Linux can build trusted code on ARM. # TODO(mcgrathr): clean this up somehow if arch != 'arm' or platform == 'linux': context['default_scons_mode'] += [mode + '-host'] context['use_glibc'] = toolchain == 'glibc' context['pnacl'] = toolchain == 'pnacl' context['nacl_clang'] = toolchain == 'nacl_clang' context['max_jobs'] = 8 context['dry_run'] = options.dry_run context['inside_toolchain'] = options.inside_toolchain context['step_suffix'] = options.step_suffix context['no_gyp'] = options.no_gyp context['no_goma'] = options.no_goma context['coverage'] = options.coverage context['use_breakpad_tools'] = options.use_breakpad_tools context['scons_args'] = options.scons_args context['skip_build'] = options.skip_build context['skip_run'] = options.skip_run # Don't run gyp on coverage builds. if context['coverage']: context['no_gyp'] = True for key, value in sorted(context.config.items()): print '%s=%s' % (key, value) def EnsureDirectoryExists(path): """ Create a directory if it does not already exist. Does not mask failures, but there really shouldn't be any. """ if not os.path.exists(path): os.makedirs(path) def TryToCleanContents(path, file_name_filter=lambda fn: True): """ Remove the contents of a directory without touching the directory itself. Ignores all failures. """ if os.path.exists(path): for fn in os.listdir(path): TryToCleanPath(os.path.join(path, fn), file_name_filter) def TryToCleanPath(path, file_name_filter=lambda fn: True): """ Removes a file or directory. Ignores all failures. """ if os.path.exists(path): if file_name_filter(path): print 'Trying to remove %s' % path try: RemovePath(path) except Exception: print 'Failed to remove %s' % path else: print 'Skipping %s' % path def Retry(op, *args): # Windows seems to be prone to having commands that delete files or # directories fail. We currently do not have a complete understanding why, # and as a workaround we simply retry the command a few times. # It appears that file locks are hanging around longer than they should. This # may be a secondary effect of processes hanging around longer than they # should. This may be because when we kill a browser sel_ldr does not exit # immediately, etc. # Virus checkers can also accidently prevent files from being deleted, but # that shouldn't be a problem on the bots. if GetHostPlatform() == 'win': count = 0 while True: try: op(*args) break except Exception: print "FAILED: %s %s" % (op.__name__, repr(args)) count += 1 if count < 5: print "RETRY: %s %s" % (op.__name__, repr(args)) time.sleep(pow(2, count)) else: # Don't mask the exception. raise else: op(*args) def PermissionsFixOnError(func, path, exc_info): if not os.access(path, os.W_OK): os.chmod(path, stat.S_IWUSR) func(path) else: raise def _RemoveDirectory(path): print 'Removing %s' % path if os.path.exists(path): shutil.rmtree(path, onerror=PermissionsFixOnError) print ' Succeeded.' else: print ' Path does not exist, nothing to do.' def RemoveDirectory(path): """ Remove a directory if it exists. Does not mask failures, although it does retry a few times on Windows. """ Retry(_RemoveDirectory, path) def RemovePath(path): """Remove a path, file or directory.""" if os.path.isdir(path): RemoveDirectory(path) else: if os.path.isfile(path) and not os.access(path, os.W_OK): os.chmod(path, stat.S_IWUSR) os.remove(path) # This is a sanity check so Command can print out better error information. def FileCanBeFound(name, paths): # CWD if os.path.exists(name): return True # Paths with directories are not resolved using the PATH variable. if os.path.dirname(name): return False # In path for path in paths.split(os.pathsep): full = os.path.join(path, name) if os.path.exists(full): return True return False def RemoveGypBuildDirectories(): # Remove all directories on all platforms. Overkill, but it allows for # straight-line code. # Windows RemoveDirectory('build/Debug') RemoveDirectory('build/Release') RemoveDirectory('build/Debug-Win32') RemoveDirectory('build/Release-Win32') RemoveDirectory('build/Debug-x64') RemoveDirectory('build/Release-x64') # Linux and Mac RemoveDirectory('../xcodebuild') RemoveDirectory('../out') RemoveDirectory('src/third_party/nacl_sdk/arm-newlib') def RemoveSconsBuildDirectories(): RemoveDirectory('scons-out') RemoveDirectory('breakpad-out') # Execute a command using Python's subprocess module. def Command(context, cmd, cwd=None): print 'Running command: %s' % ' '.join(cmd) # Python's subprocess has a quirk. A subprocess can execute with an # arbitrary, user-defined environment. The first argument of the command, # however, is located using the PATH variable of the Python script that is # launching the subprocess. Modifying the PATH in the environment passed to # the subprocess does not affect Python's search for the first argument of # the command (the executable file.) This is a little counter intuitive, # so we're forcing the search to use the same PATH variable as is seen by # the subprocess. env = context.MakeCommandEnv() script_path = os.environ['PATH'] os.environ['PATH'] = env['PATH'] try: if FileCanBeFound(cmd[0], env['PATH']) or context['dry_run']: # Make sure that print statements before the subprocess call have been # flushed, otherwise the output of the subprocess call may appear before # the print statements. sys.stdout.flush() if context['dry_run']: retcode = 0 else: retcode = subprocess.call(cmd, cwd=cwd, env=env) else: # Provide a nicer failure message. # If subprocess cannot find the executable, it will throw a cryptic # exception. print 'Executable %r cannot be found.' % cmd[0] retcode = 1 finally: os.environ['PATH'] = script_path print 'Command return code: %d' % retcode if retcode != 0: raise StepFailed() return retcode # A specialized version of CommandStep. def SCons(context, mode=None, platform=None, parallel=False, browser_test=False, args=(), cwd=None): python = sys.executable if mode is None: mode = context['default_scons_mode'] if platform is None: platform = context['default_scons_platform'] if parallel: jobs = context['max_jobs'] else: jobs = 1 cmd = [] if browser_test and context.Linux(): # Although we could use the "browser_headless=1" Scons option, it runs # xvfb-run once per Chromium invocation. This is good for isolating # the tests, but xvfb-run has a stupid fixed-period sleep, which would # slow down the tests unnecessarily. cmd.extend(['xvfb-run', '--auto-servernum']) cmd.extend([ python, 'scons.py', '--verbose', '-k', '-j%d' % jobs, '--mode='+','.join(mode), 'platform='+platform, ]) cmd.extend(context['scons_args']) if context['clang']: cmd.append('--clang') if context['asan']: cmd.append('--asan') if context['use_glibc']: cmd.append('--nacl_glibc') if context['pnacl']: cmd.append('bitcode=1') if context['nacl_clang']: cmd.append('nacl_clang=1') if context['use_breakpad_tools']: cmd.append('breakpad_tools_dir=breakpad-out') if context['android']: cmd.append('android=1') # Append used-specified arguments. cmd.extend(args) Command(context, cmd, cwd) class StepFailed(Exception): """ Thrown when the step has failed. """ class StopBuild(Exception): """ Thrown when the entire build should stop. This does not indicate a failure, in of itself. """ class Step(object): """ This class is used in conjunction with a Python "with" statement to ensure that the preamble and postamble of each build step gets printed and failures get logged. This class also ensures that exceptions thrown inside a "with" statement don't take down the entire build. """ def __init__(self, name, status, halt_on_fail=True): self.status = status if 'step_suffix' in status.context: suffix = status.context['step_suffix'] else: suffix = '' self.name = name + suffix self.halt_on_fail = halt_on_fail self.step_failed = False # Called on entry to a 'with' block. def __enter__(self): sys.stdout.flush() print print '@@@BUILD_STEP %s@@@' % self.name self.status.ReportBegin(self.name) # The method is called on exit from a 'with' block - even for non-local # control flow, i.e. exceptions, breaks, continues, returns, etc. # If an exception is thrown inside a block wrapped with a 'with' statement, # the __exit__ handler can suppress the exception by returning True. This is # used to isolate each step in the build - if an exception occurs in a given # step, the step is treated as a failure. This allows the postamble for each # step to be printed and also allows the build to continue of the failure of # a given step doesn't halt the build. def __exit__(self, type, exception, trace): sys.stdout.flush() if exception is None: # If exception is None, no exception occurred. step_failed = False elif isinstance(exception, StepFailed): step_failed = True print print 'Halting build step because of failure.' print else: step_failed = True print print 'The build step threw an exception...' print traceback.print_exception(type, exception, trace, file=sys.stdout) print if step_failed: self.status.ReportFail(self.name) print '@@@STEP_FAILURE@@@' if self.halt_on_fail: print print 'Entire build halted because %s failed.' % self.name sys.stdout.flush() raise StopBuild() else: self.status.ReportPass(self.name) sys.stdout.flush() # Suppress any exception that occurred. return True # Adds an arbitrary link inside the build stage on the waterfall. def StepLink(text, link): print '@@@STEP_LINK@%s@%s@@@' % (text, link) # Adds arbitrary text inside the build stage on the waterfall. def StepText(text): print '@@@STEP_TEXT@%s@@@' % (text) class BuildStatus(object): """ Keeps track of the overall status of the build. """ def __init__(self, context): self.context = context self.ever_failed = False self.steps = [] def ReportBegin(self, name): pass def ReportPass(self, name): self.steps.append((name, 'passed')) def ReportFail(self, name): self.steps.append((name, 'failed')) self.ever_failed = True # Handy info when this script is run outside of the buildbot. def DisplayBuildStatus(self): print for step, status in self.steps: print '%-40s[%s]' % (step, status) print if self.ever_failed: print 'Build failed.' else: print 'Build succeeded.' def ReturnValue(self): return int(self.ever_failed) class BuildContext(object): """ Encapsulates the information needed for running a build command. This includes environment variables and default arguments for SCons invocations. """ # Only allow these attributes on objects of this type. __slots__ = ['status', 'global_env', 'config'] def __init__(self): # The contents of global_env override os.environ for any commands run via # self.Command(...) self.global_env = {} # PATH is a special case. See: Command. self.global_env['PATH'] = os.environ.get('PATH', '') self.config = {} self['dry_run'] = False # Emulate dictionary subscripting. def __getitem__(self, key): return self.config[key] # Emulate dictionary subscripting. def __setitem__(self, key, value): self.config[key] = value # Emulate dictionary membership test def __contains__(self, key): return key in self.config def Windows(self): return self.config['platform'] == 'win' def Linux(self): return self.config['platform'] == 'linux' def Mac(self): return self.config['platform'] == 'mac' def GetEnv(self, name, default=None): return self.global_env.get(name, default) def SetEnv(self, name, value): self.global_env[name] = str(value) def MakeCommandEnv(self): # The external environment is not sanitized. e = dict(os.environ) # Arbitrary variables can be overridden. e.update(self.global_env) return e def RunBuild(script, status): try: script(status, status.context) except StopBuild: pass # Emit a summary step for three reasons: # - The annotator will attribute non-zero exit status to the last build step. # This can misattribute failures to the last build step. # - runtest.py wraps the builds to scrape perf data. It emits an annotator # tag on exit which misattributes perf results to the last build step. # - Provide a label step in which to show summary result. # Otherwise these go back to the preamble. with Step('summary', status): if status.ever_failed: print 'There were failed stages.' else: print 'Success.' # Display a summary of the build. status.DisplayBuildStatus() sys.exit(status.ReturnValue()) </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">bsd-3-clause</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-6,223,911,041,280,375,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">30.722543</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">80</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.654246</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.708108</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45124"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">tjcsl/director</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">web3/apps/sites/migrations/0001_initial.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1297</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "># -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2016-11-05 23:20 from __future__ import unicode_literals import django.core.validators from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('users', '0002_auto_20161105_2046'), ] operations = [ migrations.CreateModel( name='Website', fields=[ ('id', models.PositiveIntegerField(primary_key=True, serialize=False, validators=[django.core.validators.MinValueValidator(1000)])), ('name', models.CharField(max_length=32, unique=True)), ('category', models.CharField(choices=[('legacy', 'legacy'), ('static', 'static'), ('php', 'php'), ('dynamic', 'dynamic')], max_length=16)), ('purpose', models.CharField(choices=[('user', 'user'), ('activity', 'activity')], max_length=16)), ('domain', models.TextField()), ('description', models.TextField()), ('group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='users.Group')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='users.User')), ], ), ] </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-8,739,404,138,227,232,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">39.53125</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">156</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.596762</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">4.183871</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45125"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">TAMU-CPT/galaxy-tools</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">tools/gff3/gff3_filter.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1553</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">#!/usr/bin/env python import sys import logging import argparse from cpt_gffParser import gffParse, gffWrite from gff3 import feature_lambda, feature_test_qual_value logging.basicConfig(level=logging.INFO) log = logging.getLogger(__name__) def gff_filter(gff3, id_list=None, id="", attribute_field="ID", subfeatures=True): attribute_field = attribute_field.split("__cn__") if id_list: filter_strings = [line.strip() for line in id_list] else: filter_strings = [x.strip() for x in id.split("__cn__")] for rec in gffParse(gff3): rec.features = feature_lambda( rec.features, feature_test_qual_value, {"qualifier": attribute_field, "attribute_list": filter_strings}, subfeatures=subfeatures, ) rec.annotations = {} gffWrite([rec], sys.stdout) if __name__ == "__main__": parser = argparse.ArgumentParser( description="extract features from a GFF3 file based on ID/qualifiers" ) parser.add_argument("gff3", type=argparse.FileType("r"), help="GFF3 annotations") parser.add_argument("--id_list", type=argparse.FileType("r")) parser.add_argument("--id", type=str) parser.add_argument( "--attribute_field", type=str, help="Column 9 Field to search against", default="ID", ) parser.add_argument( "--subfeatures", action="store_true", help="Retain subfeature tree of matched features", ) args = parser.parse_args() gff_filter(**vars(args)) </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-3.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">2,550,448,760,510,067,700</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">31.354167</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">85</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.627817</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.688836</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45126"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">greggian/TapdIn</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">django/contrib/localflavor/us/models.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1132</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">from django.conf import settings from django.db.models.fields import Field class USStateField(Field): def get_internal_type(self): return "USStateField" def db_type(self): if settings.DATABASE_ENGINE == 'oracle': return 'CHAR(2)' else: return 'varchar(2)' def formfield(self, **kwargs): from django.contrib.localflavor.us.forms import USStateSelect defaults = {'widget': USStateSelect} defaults.update(kwargs) return super(USStateField, self).formfield(**defaults) class PhoneNumberField(Field): def get_internal_type(self): return "PhoneNumberField" def db_type(self): if settings.DATABASE_ENGINE == 'oracle': return 'VARCHAR2(20)' else: return 'varchar(20)' def formfield(self, **kwargs): from django.contrib.localflavor.us.forms import USPhoneNumberField defaults = {'form_class': USPhoneNumberField} defaults.update(kwargs) return super(PhoneNumberField, self).formfield(**defaults) </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">apache-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">2,579,539,055,631,886,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">30.342857</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">74</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.614841</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">4.337165</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45127"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">seraphlnWu/in_trip</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">in_trip/scripts/change_data_from_hbase_to_pg.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1620</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">#coding=utf-8 import time import cPickle from in_trip.store_data.views import pg_db,conn import logging logger = logging.getLogger('parser') def creat_table(): sql_str = ''' create table "tmp_hbase_to_pg"( data text, timestamp float(24) ) ''' pg_db.execute(sql_str) conn.commit() def insert_data(o_dict, default_value): data =cPickle.dumps({ 'o_dict' : o_dict, 'default_value' : default_value }) sql_str = ''' insert into tmp_hbase_to_pg (data,timestamp) values (%s,%s); ''' try: pg_db.execute(sql_str,(data,time.time())) conn.commit() except Exception as e: conn.rollback() logger.error('insert to pg error: %s', e) def get_data_all(): sql_str = ''' select * from tmp_hbase_to_pg; ''' pg_db.execute(sql_str) print pg_db.fetchall() def get_data(offset,limit=1000): sql_str = ''' select * from tmp_hbase_to_pg limit(%s) offset(%s); ''' pg_db.execute(sql_str,(limit,offset)) return pg_db.fetchall() def insert_into_hbase(): from in_trip.store_data.hbase.run import insert_data as hbase_insert offset = 0 limit = 1000 while True: res_list = get_data(offset,limit) if not res_list: break offset = offset + limit for item in res_list: tmp_data = cPickle.loads(item[0]) hbase_insert(tmp_data['o_dict'],tmp_data['default_value']) return True if __name__ == "__main__": creat_table() print "success!" </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">5,948,230,377,055,756,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">22.478261</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">72</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.557407</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.347107</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45128"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">fallen/artiq</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">artiq/frontend/artiq_run.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">4103</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">#!/usr/bin/env python3 # Copyright (C) 2014, 2015 M-Labs Limited # Copyright (C) 2014, 2015 Robert Jordens <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="94fefbe6f0f1fae7d4f3f9f5fdf8baf7fbf9">[email protected]</a>> import argparse import sys import time from operator import itemgetter from itertools import chain import logging import h5py from artiq.language.environment import EnvExperiment from artiq.protocols.file_db import FlatFileDB from artiq.master.worker_db import DeviceManager, ResultDB from artiq.tools import * logger = logging.getLogger(__name__) class ELFRunner(EnvExperiment): def build(self): self.attr_device("core") self.attr_argument("file") def run(self): with open(self.file, "rb") as f: self.core.comm.load(f.read()) self.core.comm.run("run") self.core.comm.serve(dict(), dict()) class SimpleParamLogger: def set(self, timestamp, name, value): logger.info("Parameter change: {} = {}".format(name, value)) class DummyScheduler: def __init__(self): self.next_rid = 0 self.pipeline_name = "main" self.priority = 0 self.expid = None def submit(self, pipeline_name, expid, priority, due_date, flush): rid = self.next_rid self.next_rid += 1 logger.info("Submitting: %s, RID=%s", expid, rid) return rid def delete(self, rid): logger.info("Deleting RID %s", rid) def pause(self): pass def get_argparser(with_file=True): parser = argparse.ArgumentParser( description="Local experiment running tool") verbosity_args(parser) parser.add_argument("-d", "--ddb", default="ddb.pyon", help="device database file") parser.add_argument("-p", "--pdb", default="pdb.pyon", help="parameter database file") parser.add_argument("-e", "--experiment", default=None, help="experiment to run") parser.add_argument("-o", "--hdf5", default=None, help="write results to specified HDF5 file" " (default: print them)") if with_file: parser.add_argument("file", help="file containing the experiment to run") parser.add_argument("arguments", nargs="*", help="run arguments") return parser def _build_experiment(dmgr, pdb, rdb, args): if hasattr(args, "file"): if args.file.endswith(".elf"): if args.arguments: raise ValueError("arguments not supported for ELF kernels") if args.experiment: raise ValueError("experiment-by-name not supported " "for ELF kernels") return ELFRunner(dmgr, pdb, rdb, file=args.file) else: module = file_import(args.file) file = args.file else: module = sys.modules["__main__"] file = getattr(module, "__file__") exp = get_experiment(module, args.experiment) arguments = parse_arguments(args.arguments) expid = { "file": file, "experiment": args.experiment, "arguments": arguments } dmgr.virtual_devices["scheduler"].expid = expid return exp(dmgr, pdb, rdb, **arguments) def run(with_file=False): args = get_argparser(with_file).parse_args() init_logger(args) dmgr = DeviceManager(FlatFileDB(args.ddb), virtual_devices={"scheduler": DummyScheduler()}) pdb = FlatFileDB(args.pdb) pdb.hooks.append(SimpleParamLogger()) rdb = ResultDB() try: exp_inst = _build_experiment(dmgr, pdb, rdb, args) exp_inst.prepare() exp_inst.run() exp_inst.analyze() finally: dmgr.close_devices() if args.hdf5 is not None: with h5py.File(args.hdf5, "w") as f: rdb.write_hdf5(f) elif rdb.rt.read or rdb.nrt: r = chain(rdb.rt.read.items(), rdb.nrt.items()) for k, v in sorted(r, key=itemgetter(0)): print("{}: {}".format(k, v)) def main(): return run(with_file=True) if __name__ == "__main__": main() </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-3.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-3,275,687,307,934,452,700</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">27.894366</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">75</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.58835</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.76077</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45129"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">vntarasov/openpilot</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">selfdrive/debug/get_fingerprint.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1030</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">#!/usr/bin/env python3 # simple script to get a vehicle fingerprint. # Instructions: # - connect to a Panda # - run selfdrive/boardd/boardd # - launching this script # - turn on the car in STOCK MODE (set giraffe switches properly). # Note: it's very important that the car is in stock mode, in order to collect a complete fingerprint # - since some messages are published at low frequency, keep this script running for at least 30s, # until all messages are received at least once import cereal.messaging as messaging logcan = messaging.sub_sock('can') msgs = {} while True: lc = messaging.recv_sock(logcan, True) if lc is None: continue for c in lc.can: # read also msgs sent by EON on CAN bus 0x80 and filter out the # addr with more than 11 bits if c.src in [0, 2] and c.address < 0x800: msgs[c.address] = len(c.dat) fingerprint = ', '.join("%d: %d" % v for v in sorted(msgs.items())) print("number of messages {0}:".format(len(msgs))) print("fingerprint {0}".format(fingerprint)) </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-3,785,566,846,449,061,400</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">31.1875</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">103</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.695146</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.39934</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45130"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">vcoin-project/v</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">qa/rpc-tests/test_framework/bignum.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1991</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "># # # bignum.py # # This file is copied from python-vcoinlib. # # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # """Bignum routines""" from __future__ import absolute_import, division, print_function, unicode_literals import struct # generic big endian MPI format def bn_bytes(v, have_ext=False): ext = 0 if have_ext: ext = 1 return ((v.bit_length()+7)//8) + ext def bn2bin(v): s = bytearray() i = bn_bytes(v) while i > 0: s.append((v >> ((i-1) * 8)) & 0xff) i -= 1 return s def bin2bn(s): l = 0 for ch in s: l = (l << 8) | ch return l def bn2mpi(v): have_ext = False if v.bit_length() > 0: have_ext = (v.bit_length() & 0x07) == 0 neg = False if v < 0: neg = True v = -v s = struct.pack(b">I", bn_bytes(v, have_ext)) ext = bytearray() if have_ext: ext.append(0) v_bin = bn2bin(v) if neg: if have_ext: ext[0] |= 0x80 else: v_bin[0] |= 0x80 return s + ext + v_bin def mpi2bn(s): if len(s) < 4: return None s_size = bytes(s[:4]) v_len = struct.unpack(b">I", s_size)[0] if len(s) != (v_len + 4): return None if v_len == 0: return 0 v_str = bytearray(s[4:]) neg = False i = v_str[0] if i & 0x80: neg = True i &= ~0x80 v_str[0] = i v = bin2bn(v_str) if neg: return -v return v # vcoin-specific little endian format, with implicit size def mpi2vch(s): r = s[4:] # strip size r = r[::-1] # reverse string, converting BE->LE return r def bn2vch(v): return bytes(mpi2vch(bn2mpi(v))) def vch2mpi(s): r = struct.pack(b">I", len(s)) # size r += s[::-1] # reverse string, converting LE->BE return r def vch2bn(s): return mpi2bn(vch2mpi(s)) </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-4,014,981,737,356,212,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">18.519608</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">82</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.52436</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">2.868876</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45131"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">ultimanet/nifty</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">rg/powerspectrum.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">26583</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">## NIFTY (Numerical Information Field Theory) has been developed at the ## Max-Planck-Institute for Astrophysics. ## ## Copyright (C) 2013 Max-Planck-Society ## ## Author: Marco Selig ## Project homepage: <http://www.mpa-garching.mpg.de/ift/nifty/> ## ## This program is free software: you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation, either version 3 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ## See the GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program. If not, see <http://www.gnu.org/licenses/>. ## TODO: cythonize from __future__ import division import numpy as np def draw_vector_nd(axes,dgrid,ps,symtype=0,fourier=False,zerocentered=False,kpack=None): """ Draws a n-dimensional field on a regular grid from a given power spectrum. The grid parameters need to be specified, together with a couple of global options explained below. The dimensionality of the field is determined automatically. Parameters ---------- axes : ndarray An array with the length of each axis. dgrid : ndarray An array with the pixel length of each axis. ps : ndarray The power spectrum as a function of Fourier modes. symtype : int {0,1,2} : *optional* Whether the output should be real valued (0), complex-hermitian (1) or complex without symmetry (2). (default=0) fourier : bool : *optional* Whether the output should be in Fourier space or not (default=False). zerocentered : bool : *optional* Whether the output array should be zerocentered, i.e. starting with negative Fourier modes going over the zero mode to positive modes, or not zerocentered, where zero, positive and negative modes are simpy ordered consecutively. Returns ------- field : ndarray The drawn random field. """ if(kpack is None): kdict = np.fft.fftshift(nkdict_fast(axes,dgrid,fourier)) klength = nklength(kdict) else: kdict = kpack[1][np.fft.ifftshift(kpack[0],axes=shiftaxes(zerocentered,st_to_zero_mode=False))] klength = kpack[1] #output is in position space if(not fourier): #output is real-valued if(symtype==0): vector = drawherm(klength,kdict,ps) if(np.any(zerocentered==True)): return np.real(np.fft.fftshift(np.fft.ifftn(vector),axes=shiftaxes(zerocentered))) else: return np.real(np.fft.ifftn(vector)) #output is complex with hermitian symmetry elif(symtype==1): vector = drawwild(klength,kdict,ps,real_corr=2) if(np.any(zerocentered==True)): return np.fft.fftshift(np.fft.ifftn(np.real(vector)),axes=shiftaxes(zerocentered)) else: return np.fft.ifftn(np.real(vector)) #output is complex without symmetry else: vector = drawwild(klength,kdict,ps) if(np.any(zerocentered==True)): return np.fft.fftshift(np.fft.ifftn(vector),axes=shiftaxes(zerocentered)) else: return np.fft.ifftn(vector) #output is in fourier space else: #output is real-valued if(symtype==0): vector = drawwild(klength,kdict,ps,real_corr=2) if np.any(zerocentered == True): return np.real(np.fft.fftshift(vector,axes=shiftaxes(zerocentered))) else: return np.real(vector) #output is complex with hermitian symmetry elif(symtype==1): vector = drawherm(klength,kdict,ps) if(np.any(zerocentered==True)): return np.fft.fftshift(vector,axes=shiftaxes(zerocentered)) else: return vector #output is complex without symmetry else: vector = drawwild(klength,kdict,ps) if(np.any(zerocentered==True)): return np.fft.fftshift(vector,axes=shiftaxes(zerocentered)) else: return vector #def calc_ps(field,axes,dgrid,zerocentered=False,fourier=False): # # """ # Calculates the power spectrum of a given field assuming that the field # is statistically homogenous and isotropic. # # Parameters # ---------- # field : ndarray # The input field from which the power spectrum should be determined. # # axes : ndarray # An array with the length of each axis. # # dgrid : ndarray # An array with the pixel length of each axis. # # zerocentered : bool : *optional* # Whether the output array should be zerocentered, i.e. starting with # negative Fourier modes going over the zero mode to positive modes, # or not zerocentered, where zero, positive and negative modes are # simpy ordered consecutively. # # fourier : bool : *optional* # Whether the output should be in Fourier space or not # (default=False). # # """ # # ## field absolutes # if(not fourier): # foufield = np.fft.fftshift(np.fft.fftn(field)) # elif(np.any(zerocentered==False)): # foufield = np.fft.fftshift(field, axes=shiftaxes(zerocentered,st_to_zero_mode=True)) # else: # foufield = field # fieldabs = np.abs(foufield)**2 # # kdict = nkdict_fast(axes,dgrid,fourier) # klength = nklength(kdict) # # ## power spectrum # ps = np.zeros(klength.size) # rho = np.zeros(klength.size) # for ii in np.ndindex(kdict.shape): # position = np.searchsorted(klength,kdict[ii]) # rho[position] += 1 # ps[position] += fieldabs[ii] # ps = np.divide(ps,rho) # return ps def calc_ps_fast(field,axes,dgrid,zerocentered=False,fourier=False,pindex=None,kindex=None,rho=None): """ Calculates the power spectrum of a given field faster assuming that the field is statistically homogenous and isotropic. Parameters ---------- field : ndarray The input field from which the power spectrum should be determined. axes : ndarray An array with the length of each axis. dgrid : ndarray An array with the pixel length of each axis. zerocentered : bool : *optional* Whether the output array should be zerocentered, i.e. starting with negative Fourier modes going over the zero mode to positive modes, or not zerocentered, where zero, positive and negative modes are simpy ordered consecutively. fourier : bool : *optional* Whether the output should be in Fourier space or not (default=False). pindex : ndarray Index of the Fourier grid points in a numpy.ndarray ordered following the zerocentered flag (default=None). kindex : ndarray Array of all k-vector lengths (default=None). rho : ndarray Degeneracy of the Fourier grid, indicating how many k-vectors in Fourier space have the same length (default=None). """ ## field absolutes if(not fourier): foufield = np.fft.fftshift(np.fft.fftn(field)) elif(np.any(zerocentered==False)): foufield = np.fft.fftshift(field, axes=shiftaxes(zerocentered,st_to_zero_mode=True)) else: foufield = field fieldabs = np.abs(foufield)**2 if(rho is None): if(pindex is None): ## kdict kdict = nkdict_fast(axes,dgrid,fourier) ## klength if(kindex is None): klength = nklength(kdict) else: klength = kindex ## power spectrum ps = np.zeros(klength.size) rho = np.zeros(klength.size) for ii in np.ndindex(kdict.shape): position = np.searchsorted(klength,kdict[ii]) ps[position] += fieldabs[ii] rho[position] += 1 else: ## zerocenter pindex if(np.any(zerocentered==False)): pindex = np.fft.fftshift(pindex, axes=shiftaxes(zerocentered,st_to_zero_mode=True)) ## power spectrum ps = np.zeros(np.max(pindex)+1) rho = np.zeros(ps.size) for ii in np.ndindex(pindex.shape): ps[pindex[ii]] += fieldabs[ii] rho[pindex[ii]] += 1 elif(pindex is None): ## kdict kdict = nkdict_fast(axes,dgrid,fourier) ## klength if(kindex is None): klength = nklength(kdict) else: klength = kindex ## power spectrum ps = np.zeros(klength.size) for ii in np.ndindex(kdict.shape): position = np.searchsorted(klength,kdict[ii]) ps[position] += fieldabs[ii] else: ## zerocenter pindex if(np.any(zerocentered==False)): pindex = np.fft.fftshift(pindex, axes=shiftaxes(zerocentered,st_to_zero_mode=True)) ## power spectrum ps = np.zeros(rho.size) for ii in np.ndindex(pindex.shape): ps[pindex[ii]] += fieldabs[ii] ps = np.divide(ps,rho) return ps def get_power_index(axes,dgrid,zerocentered,irred=False,fourier=True): """ Returns the index of the Fourier grid points in a numpy array, ordered following the zerocentered flag. Parameters ---------- axes : ndarray An array with the length of each axis. dgrid : ndarray An array with the pixel length of each axis. zerocentered : bool Whether the output array should be zerocentered, i.e. starting with negative Fourier modes going over the zero mode to positive modes, or not zerocentered, where zero, positive and negative modes are simpy ordered consecutively. irred : bool : *optional* If True, the function returns an array of all k-vector lengths and their degeneracy factors. If False, just the power index array is returned. fourier : bool : *optional* Whether the output should be in Fourier space or not (default=False). Returns ------- index or {klength, rho} : scalar or list Returns either an array of all k-vector lengths and their degeneracy factors or just the power index array depending on the flag irred. """ ## kdict, klength if(np.any(zerocentered==False)): kdict = np.fft.fftshift(nkdict_fast(axes,dgrid,fourier),axes=shiftaxes(zerocentered,st_to_zero_mode=True)) else: kdict = nkdict_fast(axes,dgrid,fourier) klength = nklength(kdict) ## output if(irred): rho = np.zeros(klength.shape,dtype=np.int) for ii in np.ndindex(kdict.shape): rho[np.searchsorted(klength,kdict[ii])] += 1 return klength,rho else: ind = np.empty(axes,dtype=np.int) for ii in np.ndindex(kdict.shape): ind[ii] = np.searchsorted(klength,kdict[ii]) return ind def get_power_indices(axes,dgrid,zerocentered,fourier=True): """ Returns the index of the Fourier grid points in a numpy array, ordered following the zerocentered flag. Parameters ---------- axes : ndarray An array with the length of each axis. dgrid : ndarray An array with the pixel length of each axis. zerocentered : bool Whether the output array should be zerocentered, i.e. starting with negative Fourier modes going over the zero mode to positive modes, or not zerocentered, where zero, positive and negative modes are simpy ordered consecutively. irred : bool : *optional* If True, the function returns an array of all k-vector lengths and their degeneracy factors. If False, just the power index array is returned. fourier : bool : *optional* Whether the output should be in Fourier space or not (default=False). Returns ------- index, klength, rho : ndarrays Returns the power index array, an array of all k-vector lengths and their degeneracy factors. """ ## kdict, klength if(np.any(zerocentered==False)): kdict = np.fft.fftshift(nkdict_fast(axes,dgrid,fourier),axes=shiftaxes(zerocentered,st_to_zero_mode=True)) else: kdict = nkdict_fast(axes,dgrid,fourier) klength = nklength(kdict) ## output ind = np.empty(axes,dtype=np.int) rho = np.zeros(klength.shape,dtype=np.int) for ii in np.ndindex(kdict.shape): ind[ii] = np.searchsorted(klength,kdict[ii]) rho[ind[ii]] += 1 return ind,klength,rho def get_power_indices2(axes,dgrid,zerocentered,fourier=True): """ Returns the index of the Fourier grid points in a numpy array, ordered following the zerocentered flag. Parameters ---------- axes : ndarray An array with the length of each axis. dgrid : ndarray An array with the pixel length of each axis. zerocentered : bool Whether the output array should be zerocentered, i.e. starting with negative Fourier modes going over the zero mode to positive modes, or not zerocentered, where zero, positive and negative modes are simpy ordered consecutively. irred : bool : *optional* If True, the function returns an array of all k-vector lengths and their degeneracy factors. If False, just the power index array is returned. fourier : bool : *optional* Whether the output should be in Fourier space or not (default=False). Returns ------- index, klength, rho : ndarrays Returns the power index array, an array of all k-vector lengths and their degeneracy factors. """ ## kdict, klength if(np.any(zerocentered==False)): kdict = np.fft.fftshift(nkdict_fast2(axes,dgrid,fourier),axes=shiftaxes(zerocentered,st_to_zero_mode=True)) else: kdict = nkdict_fast2(axes,dgrid,fourier) klength,rho,ind = nkdict_to_indices(kdict) return ind,klength,rho def nkdict_to_indices(kdict): kindex,pindex = np.unique(kdict,return_inverse=True) pindex = pindex.reshape(kdict.shape) rho = pindex.flatten() rho.sort() rho = np.unique(rho,return_index=True,return_inverse=False)[1] rho = np.append(rho[1:]-rho[:-1],[np.prod(pindex.shape)-rho[-1]]) return kindex,rho,pindex def bin_power_indices(pindex,kindex,rho,log=False,nbin=None,binbounds=None): """ Returns the (re)binned power indices associated with the Fourier grid. Parameters ---------- pindex : ndarray Index of the Fourier grid points in a numpy.ndarray ordered following the zerocentered flag (default=None). kindex : ndarray Array of all k-vector lengths (default=None). rho : ndarray Degeneracy of the Fourier grid, indicating how many k-vectors in Fourier space have the same length (default=None). log : bool Flag specifying if the binning is performed on logarithmic scale (default: False). nbin : integer Number of used bins (default: None). binbounds : {list, array} Array-like inner boundaries of the used bins (default: None). Returns ------- pindex, kindex, rho : ndarrays The (re)binned power indices. """ ## boundaries if(binbounds is not None): binbounds = np.sort(binbounds) ## equal binning else: if(log is None): log = False if(log): k = np.r_[0,np.log(kindex[1:])] else: k = kindex dk = np.max(k[2:]-k[1:-1]) ## minimal dk if(nbin is None): nbin = int((k[-1]-0.5*(k[2]+k[1]))/dk-0.5) ## maximal nbin else: nbin = min(int(nbin),int((k[-1]-0.5*(k[2]+k[1]))/dk+2.5)) dk = (k[-1]-0.5*(k[2]+k[1]))/(nbin-2.5) binbounds = np.r_[0.5*(3*k[1]-k[2]),0.5*(k[1]+k[2])+dk*np.arange(nbin-2)] if(log): binbounds = np.exp(binbounds) ## reordering reorder = np.searchsorted(binbounds,kindex) rho_ = np.zeros(len(binbounds)+1,dtype=rho.dtype) kindex_ = np.empty(len(binbounds)+1,dtype=kindex.dtype) for ii in range(len(reorder)): if(rho_[reorder[ii]]==0): kindex_[reorder[ii]] = kindex[ii] rho_[reorder[ii]] += rho[ii] else: kindex_[reorder[ii]] = (kindex_[reorder[ii]]*rho_[reorder[ii]]+kindex[ii]*rho[ii])/(rho_[reorder[ii]]+rho[ii]) rho_[reorder[ii]] += rho[ii] return reorder[pindex],kindex_,rho_ def nhermitianize(field,zerocentered): """ Hermitianizes an arbitrary n-dimensional field. Becomes relatively slow for large n. Parameters ---------- field : ndarray The input field that should be hermitianized. zerocentered : bool Whether the output array should be zerocentered, i.e. starting with negative Fourier modes going over the zero mode to positive modes, or not zerocentered, where zero, positive and negative modes are simpy ordered consecutively. Returns ------- hermfield : ndarray The hermitianized field. """ ## shift zerocentered axes if(np.any(zerocentered==True)): field = np.fft.fftshift(field, axes=shiftaxes(zerocentered)) # for index in np.ndenumerate(field): # negind = tuple(-np.array(index[0])) # field[negind] = np.conjugate(index[1]) # if(field[negind]==field[index[0]]): # field[index[0]] = np.abs(index[1])*(np.sign(index[1].real)+(np.sign(index[1].real)==0)*np.sign(index[1].imag)).astype(np.int) subshape = np.array(field.shape,dtype=np.int) ## == axes maxindex = subshape//2 subshape[np.argmax(subshape)] = subshape[np.argmax(subshape)]//2+1 ## ~half larges axis for ii in np.ndindex(tuple(subshape)): negii = tuple(-np.array(ii)) field[negii] = np.conjugate(field[ii]) for ii in np.ndindex((2,)*maxindex.size): index = tuple(ii*maxindex) field[index] = np.abs(field[index])*(np.sign(field[index].real)+(np.sign(field[index].real)==0)*-np.sign(field[index].imag)).astype(np.int) ## minus since overwritten before ## reshift zerocentered axes if(np.any(zerocentered==True)): field = np.fft.fftshift(field,axes=shiftaxes(zerocentered)) return field def nhermitianize_fast(field,zerocentered,special=False): """ Hermitianizes an arbitrary n-dimensional field faster. Still becomes comparably slow for large n. Parameters ---------- field : ndarray The input field that should be hermitianized. zerocentered : bool Whether the output array should be zerocentered, i.e. starting with negative Fourier modes going over the zero mode to positive modes, or not zerocentered, where zero, positive and negative modes are simpy ordered consecutively. special : bool, *optional* Must be True for random fields drawn from Gaussian or pm1 distributions. Returns ------- hermfield : ndarray The hermitianized field. """ ## shift zerocentered axes if(np.any(zerocentered==True)): field = np.fft.fftshift(field, axes=shiftaxes(zerocentered)) dummy = np.conjugate(field) ## mirror conjugate field for ii in range(field.ndim): dummy = np.swapaxes(dummy,0,ii) dummy = np.flipud(dummy) dummy = np.roll(dummy,1,axis=0) dummy = np.swapaxes(dummy,0,ii) if(special): ## special normalisation for certain random fields field = np.sqrt(0.5)*(field+dummy) maxindex = np.array(field.shape,dtype=np.int)//2 for ii in np.ndindex((2,)*maxindex.size): index = tuple(ii*maxindex) field[index] *= np.sqrt(0.5) else: ## regular case field = 0.5*(field+dummy) ## reshift zerocentered axes if(np.any(zerocentered==True)): field = np.fft.fftshift(field,axes=shiftaxes(zerocentered)) return field def random_hermitian_pm1(datatype,zerocentered,shape): """ Draws a set of hermitianized random, complex pm1 numbers. """ field = np.random.randint(4,high=None,size=np.prod(shape,axis=0,dtype=np.int,out=None)).reshape(shape,order='C') dummy = np.copy(field) ## mirror field for ii in range(field.ndim): dummy = np.swapaxes(dummy,0,ii) dummy = np.flipud(dummy) dummy = np.roll(dummy,1,axis=0) dummy = np.swapaxes(dummy,0,ii) field = (field+dummy+2*(field>dummy)*((field+dummy)%2))%4 ## wicked magic x = np.array([1+0j,0+1j,-1+0j,0-1j],dtype=datatype)[field] ## (re)shift zerocentered axes if(np.any(zerocentered==True)): field = np.fft.fftshift(field,axes=shiftaxes(zerocentered)) return x #----------------------------------------------------------------------------- # Auxiliary functions #----------------------------------------------------------------------------- def shiftaxes(zerocentered,st_to_zero_mode=False): """ Shifts the axes in a special way needed for some functions """ axes = [] for ii in range(len(zerocentered)): if(st_to_zero_mode==False)and(zerocentered[ii]): axes += [ii] if(st_to_zero_mode==True)and(not zerocentered[ii]): axes += [ii] return axes def nkdict(axes,dgrid,fourier=True): """ Calculates an n-dimensional array with its entries being the lengths of the k-vectors from the zero point of the Fourier grid. """ if(fourier): dk = dgrid else: dk = np.array([1/axes[i]/dgrid[i] for i in range(len(axes))]) kdict = np.empty(axes) for ii in np.ndindex(kdict.shape): kdict[ii] = np.sqrt(np.sum(((ii-axes//2)*dk)**2)) return kdict def nkdict_fast(axes,dgrid,fourier=True): """ Calculates an n-dimensional array with its entries being the lengths of the k-vectors from the zero point of the Fourier grid. """ if(fourier): dk = dgrid else: dk = np.array([1/dgrid[i]/axes[i] for i in range(len(axes))]) temp_vecs = np.array(np.where(np.ones(axes)),dtype='float').reshape(np.append(len(axes),axes)) temp_vecs = np.rollaxis(temp_vecs,0,len(temp_vecs.shape)) temp_vecs -= axes//2 temp_vecs *= dk temp_vecs *= temp_vecs return np.sqrt(np.sum((temp_vecs),axis=-1)) def nkdict_fast2(axes,dgrid,fourier=True): """ Calculates an n-dimensional array with its entries being the lengths of the k-vectors from the zero point of the grid. """ if(fourier): dk = dgrid else: dk = np.array([1/dgrid[i]/axes[i] for i in range(len(axes))]) inds = [] for a in axes: inds += [slice(0,a)] cords = np.ogrid[inds] dists = ((cords[0]-axes[0]//2)*dk[0])**2 for ii in range(1,len(axes)): dists = dists + ((cords[ii]-axes[ii]//2)*dk[ii])**2 dists = np.sqrt(dists) return dists def nklength(kdict): return np.sort(list(set(kdict.flatten()))) #def drawherm(vector,klength,kdict,ps): ## vector = np.zeros(kdict.shape,dtype=np.complex) # for ii in np.ndindex(vector.shape): # if(vector[ii]==np.complex(0.,0.)): # vector[ii] = np.sqrt(0.5*ps[np.searchsorted(klength,kdict[ii])])*np.complex(np.random.normal(0.,1.),np.random.normal(0.,1.)) # negii = tuple(-np.array(ii)) # vector[negii] = np.conjugate(vector[ii]) # if(vector[negii]==vector[ii]): # vector[ii] = np.float(np.sqrt(ps[klength==kdict[ii]]))*np.random.normal(0.,1.) # return vector def drawherm(klength,kdict,ps): """ Draws a hermitian random field from a Gaussian distribution. """ # vector = np.zeros(kdict.shape,dtype='complex') # for ii in np.ndindex(vector.shape): # if(vector[ii]==np.complex(0.,0.)): # vector[ii] = np.sqrt(0.5*ps[np.searchsorted(klength,kdict[ii])])*np.complex(np.random.normal(0.,1.),np.random.normal(0.,1.)) # negii = tuple(-np.array(ii)) # vector[negii] = np.conjugate(vector[ii]) # if(vector[negii]==vector[ii]): # vector[ii] = np.float(np.sqrt(ps[np.searchsorted(klength,kdict[ii])]))*np.random.normal(0.,1.) # return vector vec = np.random.normal(loc=0,scale=1,size=kdict.size).reshape(kdict.shape) vec = np.fft.fftn(vec)/np.sqrt(np.prod(kdict.shape)) for ii in np.ndindex(kdict.shape): vec[ii] *= np.sqrt(ps[np.searchsorted(klength,kdict[ii])]) return vec #def drawwild(vector,klength,kdict,ps,real_corr=1): ## vector = np.zeros(kdict.shape,dtype=np.complex) # for ii in np.ndindex(vector.shape): # vector[ii] = np.sqrt(real_corr*0.5*ps[klength==kdict[ii]])*np.complex(np.random.normal(0.,1.),np.random.normal(0.,1.)) # return vector def drawwild(klength,kdict,ps,real_corr=1): """ Draws a field of arbitrary symmetry from a Gaussian distribution. """ vec = np.empty(kdict.size,dtype=np.complex) vec.real = np.random.normal(loc=0,scale=np.sqrt(real_corr*0.5),size=kdict.size) vec.imag = np.random.normal(loc=0,scale=np.sqrt(real_corr*0.5),size=kdict.size) vec = vec.reshape(kdict.shape) for ii in np.ndindex(kdict.shape): vec[ii] *= np.sqrt(ps[np.searchsorted(klength,kdict[ii])]) return vec </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-3.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">8,155,718,674,426,123,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">33.703655</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">181</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.600271</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.52186</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45132"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">fnordahl/nova</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">nova/exception.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">56858</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "># Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Nova base exception handling. Includes decorator for re-raising Nova-type exceptions. SHOULD include dedicated exception logging. """ import functools import sys from oslo_config import cfg from oslo_log import log as logging from oslo_utils import excutils import six import webob.exc from webob import util as woutil from nova.i18n import _, _LE from nova import safe_utils LOG = logging.getLogger(__name__) exc_log_opts = [ cfg.BoolOpt('fatal_exception_format_errors', default=False, help='Make exception message format errors fatal'), ] CONF = cfg.CONF CONF.register_opts(exc_log_opts) class ConvertedException(webob.exc.WSGIHTTPException): def __init__(self, code, title="", explanation=""): self.code = code # There is a strict rule about constructing status line for HTTP: # '...Status-Line, consisting of the protocol version followed by a # numeric status code and its associated textual phrase, with each # element separated by SP characters' # (http://www.faqs.org/rfcs/rfc2616.html) # 'code' and 'title' can not be empty because they correspond # to numeric status code and its associated text if title: self.title = title else: try: self.title = woutil.status_reasons[self.code] except KeyError: msg = _LE("Improper or unknown HTTP status code used: %d") LOG.error(msg, code) self.title = woutil.status_generic_reasons[self.code // 100] self.explanation = explanation super(ConvertedException, self).__init__() def _cleanse_dict(original): """Strip all admin_password, new_pass, rescue_pass keys from a dict.""" return {k: v for k, v in six.iteritems(original) if "_pass" not in k} def wrap_exception(notifier=None, get_notifier=None): """This decorator wraps a method to catch any exceptions that may get thrown. It also optionally sends the exception to the notification system. """ def inner(f): def wrapped(self, context, *args, **kw): # Don't store self or context in the payload, it now seems to # contain confidential information. try: return f(self, context, *args, **kw) except Exception as e: with excutils.save_and_reraise_exception(): if notifier or get_notifier: payload = dict(exception=e) call_dict = safe_utils.getcallargs(f, context, *args, **kw) cleansed = _cleanse_dict(call_dict) payload.update({'args': cleansed}) # If f has multiple decorators, they must use # functools.wraps to ensure the name is # propagated. event_type = f.__name__ (notifier or get_notifier()).error(context, event_type, payload) return functools.wraps(f)(wrapped) return inner class NovaException(Exception): """Base Nova Exception To correctly use this class, inherit from it and define a 'msg_fmt' property. That msg_fmt will get printf'd with the keyword arguments provided to the constructor. """ msg_fmt = _("An unknown exception occurred.") code = 500 headers = {} safe = False def __init__(self, message=None, **kwargs): self.kwargs = kwargs if 'code' not in self.kwargs: try: self.kwargs['code'] = self.code except AttributeError: pass if not message: try: message = self.msg_fmt % kwargs except Exception: exc_info = sys.exc_info() # kwargs doesn't match a variable in the message # log the issue and the kwargs LOG.exception(_LE('Exception in string format operation')) for name, value in six.iteritems(kwargs): LOG.error("%s: %s" % (name, value)) # noqa if CONF.fatal_exception_format_errors: six.reraise(*exc_info) else: # at least get the core message out if something happened message = self.msg_fmt self.message = message super(NovaException, self).__init__(message) def format_message(self): # NOTE(mrodden): use the first argument to the python Exception object # which should be our full NovaException message, (see __init__) return self.args[0] class EncryptionFailure(NovaException): msg_fmt = _("Failed to encrypt text: %(reason)s") class DecryptionFailure(NovaException): msg_fmt = _("Failed to decrypt text: %(reason)s") class RevokeCertFailure(NovaException): msg_fmt = _("Failed to revoke certificate for %(project_id)s") class VirtualInterfaceCreateException(NovaException): msg_fmt = _("Virtual Interface creation failed") class VirtualInterfaceMacAddressException(NovaException): msg_fmt = _("Creation of virtual interface with " "unique mac address failed") class VirtualInterfacePlugException(NovaException): msg_fmt = _("Virtual interface plugin failed") class GlanceConnectionFailed(NovaException): msg_fmt = _("Connection to glance host %(host)s:%(port)s failed: " "%(reason)s") class CinderConnectionFailed(NovaException): msg_fmt = _("Connection to cinder host failed: %(reason)s") class Forbidden(NovaException): ec2_code = 'AuthFailure' msg_fmt = _("Not authorized.") code = 403 class AdminRequired(Forbidden): msg_fmt = _("User does not have admin privileges") class PolicyNotAuthorized(Forbidden): msg_fmt = _("Policy doesn't allow %(action)s to be performed.") class VolumeLimitExceeded(Forbidden): msg_fmt = _("Volume resource quota exceeded") class ImageNotActive(NovaException): # NOTE(jruzicka): IncorrectState is used for volumes only in EC2, # but it still seems like the most appropriate option. ec2_code = 'IncorrectState' msg_fmt = _("Image %(image_id)s is not active.") class ImageNotAuthorized(NovaException): msg_fmt = _("Not authorized for image %(image_id)s.") class Invalid(NovaException): msg_fmt = _("Unacceptable parameters.") code = 400 class InvalidBDM(Invalid): msg_fmt = _("Block Device Mapping is Invalid.") class InvalidBDMSnapshot(InvalidBDM): msg_fmt = _("Block Device Mapping is Invalid: " "failed to get snapshot %(id)s.") class InvalidBDMVolume(InvalidBDM): msg_fmt = _("Block Device Mapping is Invalid: " "failed to get volume %(id)s.") class InvalidBDMImage(InvalidBDM): msg_fmt = _("Block Device Mapping is Invalid: " "failed to get image %(id)s.") class InvalidBDMBootSequence(InvalidBDM): msg_fmt = _("Block Device Mapping is Invalid: " "Boot sequence for the instance " "and image/block device mapping " "combination is not valid.") class InvalidBDMLocalsLimit(InvalidBDM): msg_fmt = _("Block Device Mapping is Invalid: " "You specified more local devices than the " "limit allows") class InvalidBDMEphemeralSize(InvalidBDM): msg_fmt = _("Ephemeral disks requested are larger than " "the instance type allows.") class InvalidBDMSwapSize(InvalidBDM): msg_fmt = _("Swap drive requested is larger than instance type allows.") class InvalidBDMFormat(InvalidBDM): msg_fmt = _("Block Device Mapping is Invalid: " "%(details)s") class InvalidBDMForLegacy(InvalidBDM): msg_fmt = _("Block Device Mapping cannot " "be converted to legacy format. ") class InvalidBDMVolumeNotBootable(InvalidBDM): msg_fmt = _("Block Device %(id)s is not bootable.") class InvalidAttribute(Invalid): msg_fmt = _("Attribute not supported: %(attr)s") class ValidationError(Invalid): msg_fmt = "%(detail)s" class VolumeUnattached(Invalid): ec2_code = 'IncorrectState' msg_fmt = _("Volume %(volume_id)s is not attached to anything") class VolumeNotCreated(NovaException): msg_fmt = _("Volume %(volume_id)s did not finish being created" " even after we waited %(seconds)s seconds or %(attempts)s" " attempts. And its status is %(volume_status)s.") class VolumeEncryptionNotSupported(Invalid): msg_fmt = _("Volume encryption is not supported for %(volume_type)s " "volume %(volume_id)s") class InvalidKeypair(Invalid): ec2_code = 'InvalidKeyPair.Format' msg_fmt = _("Keypair data is invalid: %(reason)s") class InvalidRequest(Invalid): msg_fmt = _("The request is invalid.") class InvalidInput(Invalid): msg_fmt = _("Invalid input received: %(reason)s") class InvalidVolume(Invalid): ec2_code = 'UnsupportedOperation' msg_fmt = _("Invalid volume: %(reason)s") class InvalidVolumeAccessMode(Invalid): msg_fmt = _("Invalid volume access mode: %(access_mode)s") class InvalidMetadata(Invalid): msg_fmt = _("Invalid metadata: %(reason)s") class InvalidMetadataSize(Invalid): msg_fmt = _("Invalid metadata size: %(reason)s") class InvalidPortRange(Invalid): ec2_code = 'InvalidParameterValue' msg_fmt = _("Invalid port range %(from_port)s:%(to_port)s. %(msg)s") class InvalidIpProtocol(Invalid): msg_fmt = _("Invalid IP protocol %(protocol)s.") class InvalidContentType(Invalid): msg_fmt = _("Invalid content type %(content_type)s.") class InvalidAPIVersionString(Invalid): msg_fmt = _("API Version String %(version)s is of invalid format. Must " "be of format MajorNum.MinorNum.") class VersionNotFoundForAPIMethod(Invalid): msg_fmt = _("API version %(version)s is not supported on this method.") class InvalidGlobalAPIVersion(Invalid): msg_fmt = _("Version %(req_ver)s is not supported by the API. Minimum " "is %(min_ver)s and maximum is %(max_ver)s.") # Cannot be templated as the error syntax varies. # msg needs to be constructed when raised. class InvalidParameterValue(Invalid): ec2_code = 'InvalidParameterValue' msg_fmt = _("%(err)s") class InvalidAggregateAction(Invalid): msg_fmt = _("Unacceptable parameters.") code = 400 class InvalidAggregateActionAdd(InvalidAggregateAction): msg_fmt = _("Cannot add host to aggregate " "%(aggregate_id)s. Reason: %(reason)s.") class InvalidAggregateActionDelete(InvalidAggregateAction): msg_fmt = _("Cannot remove host from aggregate " "%(aggregate_id)s. Reason: %(reason)s.") class InvalidAggregateActionUpdate(InvalidAggregateAction): msg_fmt = _("Cannot update aggregate " "%(aggregate_id)s. Reason: %(reason)s.") class InvalidAggregateActionUpdateMeta(InvalidAggregateAction): msg_fmt = _("Cannot update metadata of aggregate " "%(aggregate_id)s. Reason: %(reason)s.") class InvalidGroup(Invalid): msg_fmt = _("Group not valid. Reason: %(reason)s") class InvalidSortKey(Invalid): msg_fmt = _("Sort key supplied was not valid.") class InvalidStrTime(Invalid): msg_fmt = _("Invalid datetime string: %(reason)s") class InstanceInvalidState(Invalid): msg_fmt = _("Instance %(instance_uuid)s in %(attr)s %(state)s. Cannot " "%(method)s while the instance is in this state.") class InstanceNotRunning(Invalid): msg_fmt = _("Instance %(instance_id)s is not running.") class InstanceNotInRescueMode(Invalid): msg_fmt = _("Instance %(instance_id)s is not in rescue mode") class InstanceNotRescuable(Invalid): msg_fmt = _("Instance %(instance_id)s cannot be rescued: %(reason)s") class InstanceNotReady(Invalid): msg_fmt = _("Instance %(instance_id)s is not ready") class InstanceSuspendFailure(Invalid): msg_fmt = _("Failed to suspend instance: %(reason)s") class InstanceResumeFailure(Invalid): msg_fmt = _("Failed to resume instance: %(reason)s") class InstancePowerOnFailure(Invalid): msg_fmt = _("Failed to power on instance: %(reason)s") class InstancePowerOffFailure(Invalid): msg_fmt = _("Failed to power off instance: %(reason)s") class InstanceRebootFailure(Invalid): msg_fmt = _("Failed to reboot instance: %(reason)s") class InstanceTerminationFailure(Invalid): msg_fmt = _("Failed to terminate instance: %(reason)s") class InstanceDeployFailure(Invalid): msg_fmt = _("Failed to deploy instance: %(reason)s") class MultiplePortsNotApplicable(Invalid): msg_fmt = _("Failed to launch instances: %(reason)s") class InvalidFixedIpAndMaxCountRequest(Invalid): msg_fmt = _("Failed to launch instances: %(reason)s") class ServiceUnavailable(Invalid): msg_fmt = _("Service is unavailable at this time.") class ComputeResourcesUnavailable(ServiceUnavailable): msg_fmt = _("Insufficient compute resources: %(reason)s.") class HypervisorUnavailable(NovaException): msg_fmt = _("Connection to the hypervisor is broken on host: %(host)s") class ComputeServiceUnavailable(ServiceUnavailable): msg_fmt = _("Compute service of %(host)s is unavailable at this time.") class ComputeServiceInUse(NovaException): msg_fmt = _("Compute service of %(host)s is still in use.") class UnableToMigrateToSelf(Invalid): msg_fmt = _("Unable to migrate instance (%(instance_id)s) " "to current host (%(host)s).") class InvalidHypervisorType(Invalid): msg_fmt = _("The supplied hypervisor type of is invalid.") class DestinationHypervisorTooOld(Invalid): msg_fmt = _("The instance requires a newer hypervisor version than " "has been provided.") class ServiceTooOld(Invalid): msg_fmt = _("This service is older (v%(thisver)i) than the minimum " "(v%(minver)i) version of the rest of the deployment. " "Unable to continue.") class DestinationDiskExists(Invalid): msg_fmt = _("The supplied disk path (%(path)s) already exists, " "it is expected not to exist.") class InvalidDevicePath(Invalid): msg_fmt = _("The supplied device path (%(path)s) is invalid.") class DevicePathInUse(Invalid): msg_fmt = _("The supplied device path (%(path)s) is in use.") code = 409 class DeviceIsBusy(Invalid): msg_fmt = _("The supplied device (%(device)s) is busy.") class InvalidCPUInfo(Invalid): msg_fmt = _("Unacceptable CPU info: %(reason)s") class InvalidIpAddressError(Invalid): msg_fmt = _("%(address)s is not a valid IP v4/6 address.") class InvalidVLANTag(Invalid): msg_fmt = _("VLAN tag is not appropriate for the port group " "%(bridge)s. Expected VLAN tag is %(tag)s, " "but the one associated with the port group is %(pgroup)s.") class InvalidVLANPortGroup(Invalid): msg_fmt = _("vSwitch which contains the port group %(bridge)s is " "not associated with the desired physical adapter. " "Expected vSwitch is %(expected)s, but the one associated " "is %(actual)s.") class InvalidDiskFormat(Invalid): msg_fmt = _("Disk format %(disk_format)s is not acceptable") class InvalidDiskInfo(Invalid): msg_fmt = _("Disk info file is invalid: %(reason)s") class DiskInfoReadWriteFail(Invalid): msg_fmt = _("Failed to read or write disk info file: %(reason)s") class ImageUnacceptable(Invalid): msg_fmt = _("Image %(image_id)s is unacceptable: %(reason)s") class InstanceUnacceptable(Invalid): msg_fmt = _("Instance %(instance_id)s is unacceptable: %(reason)s") class InvalidEc2Id(Invalid): msg_fmt = _("Ec2 id %(ec2_id)s is unacceptable.") class InvalidUUID(Invalid): msg_fmt = _("Expected a uuid but received %(uuid)s.") class InvalidID(Invalid): msg_fmt = _("Invalid ID received %(id)s.") class ConstraintNotMet(NovaException): msg_fmt = _("Constraint not met.") code = 412 class NotFound(NovaException): msg_fmt = _("Resource could not be found.") code = 404 class AgentBuildNotFound(NotFound): msg_fmt = _("No agent-build associated with id %(id)s.") class AgentBuildExists(NovaException): msg_fmt = _("Agent-build with hypervisor %(hypervisor)s os %(os)s " "architecture %(architecture)s exists.") class VolumeNotFound(NotFound): ec2_code = 'InvalidVolume.NotFound' msg_fmt = _("Volume %(volume_id)s could not be found.") class BDMNotFound(NotFound): msg_fmt = _("No Block Device Mapping with id %(id)s.") class VolumeBDMNotFound(NotFound): msg_fmt = _("No volume Block Device Mapping with id %(volume_id)s.") class VolumeBDMPathNotFound(VolumeBDMNotFound): msg_fmt = _("No volume Block Device Mapping at path: %(path)s") class SnapshotNotFound(NotFound): ec2_code = 'InvalidSnapshot.NotFound' msg_fmt = _("Snapshot %(snapshot_id)s could not be found.") class DiskNotFound(NotFound): msg_fmt = _("No disk at %(location)s") class VolumeDriverNotFound(NotFound): msg_fmt = _("Could not find a handler for %(driver_type)s volume.") class InvalidImageRef(Invalid): msg_fmt = _("Invalid image href %(image_href)s.") class AutoDiskConfigDisabledByImage(Invalid): msg_fmt = _("Requested image %(image)s " "has automatic disk resize disabled.") class ImageNotFound(NotFound): msg_fmt = _("Image %(image_id)s could not be found.") class PreserveEphemeralNotSupported(Invalid): msg_fmt = _("The current driver does not support " "preserving ephemeral partitions.") # NOTE(jruzicka): ImageNotFound is not a valid EC2 error code. class ImageNotFoundEC2(ImageNotFound): msg_fmt = _("Image %(image_id)s could not be found. The nova EC2 API " "assigns image ids dynamically when they are listed for the " "first time. Have you listed image ids since adding this " "image?") class ProjectNotFound(NotFound): msg_fmt = _("Project %(project_id)s could not be found.") class StorageRepositoryNotFound(NotFound): msg_fmt = _("Cannot find SR to read/write VDI.") class InstanceMappingNotFound(NotFound): msg_fmt = _("Instance %(uuid)s has no mapping to a cell.") class NetworkDuplicated(Invalid): msg_fmt = _("Network %(network_id)s is duplicated.") class NetworkDhcpReleaseFailed(NovaException): msg_fmt = _("Failed to release IP %(address)s with MAC %(mac_address)s") class NetworkInUse(NovaException): msg_fmt = _("Network %(network_id)s is still in use.") class NetworkSetHostFailed(NovaException): msg_fmt = _("Network set host failed for network %(network_id)s.") class NetworkNotCreated(Invalid): msg_fmt = _("%(req)s is required to create a network.") class LabelTooLong(Invalid): msg_fmt = _("Maximum allowed length for 'label' is 255.") class InvalidIntValue(Invalid): msg_fmt = _("%(key)s must be an integer.") class InvalidCidr(Invalid): msg_fmt = _("%(cidr)s is not a valid ip network.") class InvalidAddress(Invalid): msg_fmt = _("%(address)s is not a valid ip address.") class AddressOutOfRange(Invalid): msg_fmt = _("%(address)s is not within %(cidr)s.") class DuplicateVlan(NovaException): msg_fmt = _("Detected existing vlan with id %(vlan)d") code = 409 class CidrConflict(NovaException): msg_fmt = _('Requested cidr (%(cidr)s) conflicts ' 'with existing cidr (%(other)s)') code = 409 class NetworkHasProject(NetworkInUse): msg_fmt = _('Network must be disassociated from project ' '%(project_id)s before it can be deleted.') class NetworkNotFound(NotFound): msg_fmt = _("Network %(network_id)s could not be found.") class PortNotFound(NotFound): msg_fmt = _("Port id %(port_id)s could not be found.") class NetworkNotFoundForBridge(NetworkNotFound): msg_fmt = _("Network could not be found for bridge %(bridge)s") class NetworkNotFoundForUUID(NetworkNotFound): msg_fmt = _("Network could not be found for uuid %(uuid)s") class NetworkNotFoundForCidr(NetworkNotFound): msg_fmt = _("Network could not be found with cidr %(cidr)s.") class NetworkNotFoundForInstance(NetworkNotFound): msg_fmt = _("Network could not be found for instance %(instance_id)s.") class NoNetworksFound(NotFound): msg_fmt = _("No networks defined.") class NoMoreNetworks(NovaException): msg_fmt = _("No more available networks.") class NetworkNotFoundForProject(NetworkNotFound): msg_fmt = _("Either network uuid %(network_uuid)s is not present or " "is not assigned to the project %(project_id)s.") class NetworkAmbiguous(Invalid): msg_fmt = _("More than one possible network found. Specify " "network ID(s) to select which one(s) to connect to.") class NetworkRequiresSubnet(Invalid): msg_fmt = _("Network %(network_uuid)s requires a subnet in order to boot" " instances on.") class ExternalNetworkAttachForbidden(Forbidden): msg_fmt = _("It is not allowed to create an interface on " "external network %(network_uuid)s") class NetworkMissingPhysicalNetwork(NovaException): msg_fmt = _("Physical network is missing for network %(network_uuid)s") class VifDetailsMissingVhostuserSockPath(Invalid): msg_fmt = _("vhostuser_sock_path not present in vif_details" " for vif %(vif_id)s") class VifDetailsMissingMacvtapParameters(Invalid): msg_fmt = _("Parameters %(missing_params)s not present in" " vif_details for vif %(vif_id)s. Check your Neutron" " configuration to validate that the macvtap parameters are" " correct.") class DatastoreNotFound(NotFound): msg_fmt = _("Could not find the datastore reference(s) which the VM uses.") class PortInUse(Invalid): msg_fmt = _("Port %(port_id)s is still in use.") class PortRequiresFixedIP(Invalid): msg_fmt = _("Port %(port_id)s requires a FixedIP in order to be used.") class PortNotUsable(Invalid): msg_fmt = _("Port %(port_id)s not usable for instance %(instance)s.") class PortNotFree(Invalid): msg_fmt = _("No free port available for instance %(instance)s.") class PortBindingFailed(Invalid): msg_fmt = _("Binding failed for port %(port_id)s, please check neutron " "logs for more information.") class FixedIpExists(NovaException): msg_fmt = _("Fixed ip %(address)s already exists.") class FixedIpNotFound(NotFound): msg_fmt = _("No fixed IP associated with id %(id)s.") class FixedIpNotFoundForAddress(FixedIpNotFound): msg_fmt = _("Fixed ip not found for address %(address)s.") class FixedIpNotFoundForInstance(FixedIpNotFound): msg_fmt = _("Instance %(instance_uuid)s has zero fixed ips.") class FixedIpNotFoundForNetworkHost(FixedIpNotFound): msg_fmt = _("Network host %(host)s has zero fixed ips " "in network %(network_id)s.") class FixedIpNotFoundForSpecificInstance(FixedIpNotFound): msg_fmt = _("Instance %(instance_uuid)s doesn't have fixed ip '%(ip)s'.") class FixedIpNotFoundForNetwork(FixedIpNotFound): msg_fmt = _("Fixed IP address (%(address)s) does not exist in " "network (%(network_uuid)s).") class FixedIpAssociateFailed(NovaException): msg_fmt = _("Fixed IP associate failed for network: %(net)s.") class FixedIpAlreadyInUse(NovaException): msg_fmt = _("Fixed IP address %(address)s is already in use on instance " "%(instance_uuid)s.") class FixedIpAssociatedWithMultipleInstances(NovaException): msg_fmt = _("More than one instance is associated with fixed ip address " "'%(address)s'.") class FixedIpInvalid(Invalid): msg_fmt = _("Fixed IP address %(address)s is invalid.") class NoMoreFixedIps(NovaException): ec2_code = 'UnsupportedOperation' msg_fmt = _("No fixed IP addresses available for network: %(net)s") class NoFixedIpsDefined(NotFound): msg_fmt = _("Zero fixed ips could be found.") class FloatingIpExists(NovaException): msg_fmt = _("Floating ip %(address)s already exists.") class FloatingIpNotFound(NotFound): ec2_code = "UnsupportedOperation" msg_fmt = _("Floating ip not found for id %(id)s.") class FloatingIpDNSExists(Invalid): msg_fmt = _("The DNS entry %(name)s already exists in domain %(domain)s.") class FloatingIpNotFoundForAddress(FloatingIpNotFound): msg_fmt = _("Floating ip not found for address %(address)s.") class FloatingIpNotFoundForHost(FloatingIpNotFound): msg_fmt = _("Floating ip not found for host %(host)s.") class FloatingIpMultipleFoundForAddress(NovaException): msg_fmt = _("Multiple floating ips are found for address %(address)s.") class FloatingIpPoolNotFound(NotFound): msg_fmt = _("Floating ip pool not found.") safe = True class NoMoreFloatingIps(FloatingIpNotFound): msg_fmt = _("Zero floating ips available.") safe = True class FloatingIpAssociated(NovaException): ec2_code = "UnsupportedOperation" msg_fmt = _("Floating ip %(address)s is associated.") class FloatingIpNotAssociated(NovaException): msg_fmt = _("Floating ip %(address)s is not associated.") class NoFloatingIpsDefined(NotFound): msg_fmt = _("Zero floating ips exist.") class NoFloatingIpInterface(NotFound): ec2_code = "UnsupportedOperation" msg_fmt = _("Interface %(interface)s not found.") class FloatingIpAllocateFailed(NovaException): msg_fmt = _("Floating IP allocate failed.") class FloatingIpAssociateFailed(NovaException): msg_fmt = _("Floating IP %(address)s association has failed.") class FloatingIpBadRequest(Invalid): ec2_code = "UnsupportedOperation" msg_fmt = _("The floating IP request failed with a BadRequest") class CannotDisassociateAutoAssignedFloatingIP(NovaException): ec2_code = "UnsupportedOperation" msg_fmt = _("Cannot disassociate auto assigned floating ip") class KeypairNotFound(NotFound): ec2_code = 'InvalidKeyPair.NotFound' msg_fmt = _("Keypair %(name)s not found for user %(user_id)s") class ServiceNotFound(NotFound): msg_fmt = _("Service %(service_id)s could not be found.") class ServiceBinaryExists(NovaException): msg_fmt = _("Service with host %(host)s binary %(binary)s exists.") class ServiceTopicExists(NovaException): msg_fmt = _("Service with host %(host)s topic %(topic)s exists.") class HostNotFound(NotFound): msg_fmt = _("Host %(host)s could not be found.") class ComputeHostNotFound(HostNotFound): msg_fmt = _("Compute host %(host)s could not be found.") class ComputeHostNotCreated(HostNotFound): msg_fmt = _("Compute host %(name)s needs to be created first" " before updating.") class HostBinaryNotFound(NotFound): msg_fmt = _("Could not find binary %(binary)s on host %(host)s.") class InvalidReservationExpiration(Invalid): msg_fmt = _("Invalid reservation expiration %(expire)s.") class InvalidQuotaValue(Invalid): msg_fmt = _("Change would make usage less than 0 for the following " "resources: %(unders)s") class InvalidQuotaMethodUsage(Invalid): msg_fmt = _("Wrong quota method %(method)s used on resource %(res)s") class QuotaNotFound(NotFound): msg_fmt = _("Quota could not be found") class QuotaExists(NovaException): msg_fmt = _("Quota exists for project %(project_id)s, " "resource %(resource)s") class QuotaResourceUnknown(QuotaNotFound): msg_fmt = _("Unknown quota resources %(unknown)s.") class ProjectUserQuotaNotFound(QuotaNotFound): msg_fmt = _("Quota for user %(user_id)s in project %(project_id)s " "could not be found.") class ProjectQuotaNotFound(QuotaNotFound): msg_fmt = _("Quota for project %(project_id)s could not be found.") class QuotaClassNotFound(QuotaNotFound): msg_fmt = _("Quota class %(class_name)s could not be found.") class QuotaUsageNotFound(QuotaNotFound): msg_fmt = _("Quota usage for project %(project_id)s could not be found.") class ReservationNotFound(QuotaNotFound): msg_fmt = _("Quota reservation %(uuid)s could not be found.") class OverQuota(NovaException): msg_fmt = _("Quota exceeded for resources: %(overs)s") class SecurityGroupNotFound(NotFound): msg_fmt = _("Security group %(security_group_id)s not found.") class SecurityGroupNotFoundForProject(SecurityGroupNotFound): msg_fmt = _("Security group %(security_group_id)s not found " "for project %(project_id)s.") class SecurityGroupNotFoundForRule(SecurityGroupNotFound): msg_fmt = _("Security group with rule %(rule_id)s not found.") class SecurityGroupExists(Invalid): ec2_code = 'InvalidGroup.Duplicate' msg_fmt = _("Security group %(security_group_name)s already exists " "for project %(project_id)s.") class SecurityGroupExistsForInstance(Invalid): msg_fmt = _("Security group %(security_group_id)s is already associated" " with the instance %(instance_id)s") class SecurityGroupNotExistsForInstance(Invalid): msg_fmt = _("Security group %(security_group_id)s is not associated with" " the instance %(instance_id)s") class SecurityGroupDefaultRuleNotFound(Invalid): msg_fmt = _("Security group default rule (%rule_id)s not found.") class SecurityGroupCannotBeApplied(Invalid): msg_fmt = _("Network requires port_security_enabled and subnet associated" " in order to apply security groups.") class SecurityGroupRuleExists(Invalid): ec2_code = 'InvalidPermission.Duplicate' msg_fmt = _("Rule already exists in group: %(rule)s") class NoUniqueMatch(NovaException): msg_fmt = _("No Unique Match Found.") code = 409 class MigrationNotFound(NotFound): msg_fmt = _("Migration %(migration_id)s could not be found.") class MigrationNotFoundByStatus(MigrationNotFound): msg_fmt = _("Migration not found for instance %(instance_id)s " "with status %(status)s.") class ConsolePoolNotFound(NotFound): msg_fmt = _("Console pool %(pool_id)s could not be found.") class ConsolePoolExists(NovaException): msg_fmt = _("Console pool with host %(host)s, console_type " "%(console_type)s and compute_host %(compute_host)s " "already exists.") class ConsolePoolNotFoundForHostType(NotFound): msg_fmt = _("Console pool of type %(console_type)s " "for compute host %(compute_host)s " "on proxy host %(host)s not found.") class ConsoleNotFound(NotFound): msg_fmt = _("Console %(console_id)s could not be found.") class ConsoleNotFoundForInstance(ConsoleNotFound): msg_fmt = _("Console for instance %(instance_uuid)s could not be found.") class ConsoleNotFoundInPoolForInstance(ConsoleNotFound): msg_fmt = _("Console for instance %(instance_uuid)s " "in pool %(pool_id)s could not be found.") class ConsoleTypeInvalid(Invalid): msg_fmt = _("Invalid console type %(console_type)s") class ConsoleTypeUnavailable(Invalid): msg_fmt = _("Unavailable console type %(console_type)s.") class ConsolePortRangeExhausted(NovaException): msg_fmt = _("The console port range %(min_port)d-%(max_port)d is " "exhausted.") class FlavorNotFound(NotFound): msg_fmt = _("Flavor %(flavor_id)s could not be found.") class FlavorNotFoundByName(FlavorNotFound): msg_fmt = _("Flavor with name %(flavor_name)s could not be found.") class FlavorAccessNotFound(NotFound): msg_fmt = _("Flavor access not found for %(flavor_id)s / " "%(project_id)s combination.") class FlavorExtraSpecUpdateCreateFailed(NovaException): msg_fmt = _("Flavor %(id)d extra spec cannot be updated or created " "after %(retries)d retries.") class CellNotFound(NotFound): msg_fmt = _("Cell %(cell_name)s doesn't exist.") class CellExists(NovaException): msg_fmt = _("Cell with name %(name)s already exists.") class CellRoutingInconsistency(NovaException): msg_fmt = _("Inconsistency in cell routing: %(reason)s") class CellServiceAPIMethodNotFound(NotFound): msg_fmt = _("Service API method not found: %(detail)s") class CellTimeout(NotFound): msg_fmt = _("Timeout waiting for response from cell") class CellMaxHopCountReached(NovaException): msg_fmt = _("Cell message has reached maximum hop count: %(hop_count)s") class NoCellsAvailable(NovaException): msg_fmt = _("No cells available matching scheduling criteria.") class CellsUpdateUnsupported(NovaException): msg_fmt = _("Cannot update cells configuration file.") class InstanceUnknownCell(NotFound): msg_fmt = _("Cell is not known for instance %(instance_uuid)s") class SchedulerHostFilterNotFound(NotFound): msg_fmt = _("Scheduler Host Filter %(filter_name)s could not be found.") class FlavorExtraSpecsNotFound(NotFound): msg_fmt = _("Flavor %(flavor_id)s has no extra specs with " "key %(extra_specs_key)s.") class ComputeHostMetricNotFound(NotFound): msg_fmt = _("Metric %(name)s could not be found on the compute " "host node %(host)s.%(node)s.") class FileNotFound(NotFound): msg_fmt = _("File %(file_path)s could not be found.") class SwitchNotFoundForNetworkAdapter(NotFound): msg_fmt = _("Virtual switch associated with the " "network adapter %(adapter)s not found.") class NetworkAdapterNotFound(NotFound): msg_fmt = _("Network adapter %(adapter)s could not be found.") class ClassNotFound(NotFound): msg_fmt = _("Class %(class_name)s could not be found: %(exception)s") class InstanceTagNotFound(NotFound): msg_fmt = _("Instance %(instance_id)s has no tag '%(tag)s'") class RotationRequiredForBackup(NovaException): msg_fmt = _("Rotation param is required for backup image_type") class KeyPairExists(NovaException): ec2_code = 'InvalidKeyPair.Duplicate' msg_fmt = _("Key pair '%(key_name)s' already exists.") class InstanceExists(NovaException): msg_fmt = _("Instance %(name)s already exists.") class FlavorExists(NovaException): msg_fmt = _("Flavor with name %(name)s already exists.") class FlavorIdExists(NovaException): msg_fmt = _("Flavor with ID %(flavor_id)s already exists.") class FlavorAccessExists(NovaException): msg_fmt = _("Flavor access already exists for flavor %(flavor_id)s " "and project %(project_id)s combination.") class InvalidSharedStorage(NovaException): msg_fmt = _("%(path)s is not on shared storage: %(reason)s") class InvalidLocalStorage(NovaException): msg_fmt = _("%(path)s is not on local storage: %(reason)s") class StorageError(NovaException): msg_fmt = _("Storage error: %(reason)s") class MigrationError(NovaException): msg_fmt = _("Migration error: %(reason)s") class MigrationPreCheckError(MigrationError): msg_fmt = _("Migration pre-check error: %(reason)s") class MalformedRequestBody(NovaException): msg_fmt = _("Malformed message body: %(reason)s") # NOTE(johannes): NotFound should only be used when a 404 error is # appropriate to be returned class ConfigNotFound(NovaException): msg_fmt = _("Could not find config at %(path)s") class PasteAppNotFound(NovaException): msg_fmt = _("Could not load paste app '%(name)s' from %(path)s") class CannotResizeToSameFlavor(NovaException): msg_fmt = _("When resizing, instances must change flavor!") class ResizeError(NovaException): msg_fmt = _("Resize error: %(reason)s") class CannotResizeDisk(NovaException): msg_fmt = _("Server disk was unable to be resized because: %(reason)s") class FlavorMemoryTooSmall(NovaException): msg_fmt = _("Flavor's memory is too small for requested image.") class FlavorDiskTooSmall(NovaException): msg_fmt = _("The created instance's disk would be too small.") class FlavorDiskSmallerThanImage(FlavorDiskTooSmall): msg_fmt = _("Flavor's disk is too small for requested image. Flavor disk " "is %(flavor_size)i bytes, image is %(image_size)i bytes.") class FlavorDiskSmallerThanMinDisk(FlavorDiskTooSmall): msg_fmt = _("Flavor's disk is smaller than the minimum size specified in " "image metadata. Flavor disk is %(flavor_size)i bytes, " "minimum size is %(image_min_disk)i bytes.") class VolumeSmallerThanMinDisk(FlavorDiskTooSmall): msg_fmt = _("Volume is smaller than the minimum size specified in image " "metadata. Volume size is %(volume_size)i bytes, minimum " "size is %(image_min_disk)i bytes.") class InsufficientFreeMemory(NovaException): msg_fmt = _("Insufficient free memory on compute node to start %(uuid)s.") class NoValidHost(NovaException): msg_fmt = _("No valid host was found. %(reason)s") class MaxRetriesExceeded(NoValidHost): msg_fmt = _("Exceeded maximum number of retries. %(reason)s") class QuotaError(NovaException): ec2_code = 'ResourceLimitExceeded' msg_fmt = _("Quota exceeded: code=%(code)s") # NOTE(cyeoh): 413 should only be used for the ec2 API # The error status code for out of quota for the nova api should be # 403 Forbidden. code = 413 headers = {'Retry-After': 0} safe = True class TooManyInstances(QuotaError): msg_fmt = _("Quota exceeded for %(overs)s: Requested %(req)s," " but already used %(used)s of %(allowed)s %(overs)s") class FloatingIpLimitExceeded(QuotaError): msg_fmt = _("Maximum number of floating ips exceeded") class FixedIpLimitExceeded(QuotaError): msg_fmt = _("Maximum number of fixed ips exceeded") class MetadataLimitExceeded(QuotaError): msg_fmt = _("Maximum number of metadata items exceeds %(allowed)d") class OnsetFileLimitExceeded(QuotaError): msg_fmt = _("Personality file limit exceeded") class OnsetFilePathLimitExceeded(OnsetFileLimitExceeded): msg_fmt = _("Personality file path too long") class OnsetFileContentLimitExceeded(OnsetFileLimitExceeded): msg_fmt = _("Personality file content too long") class KeypairLimitExceeded(QuotaError): msg_fmt = _("Maximum number of key pairs exceeded") class SecurityGroupLimitExceeded(QuotaError): ec2_code = 'SecurityGroupLimitExceeded' msg_fmt = _("Maximum number of security groups or rules exceeded") class PortLimitExceeded(QuotaError): msg_fmt = _("Maximum number of ports exceeded") class AggregateError(NovaException): msg_fmt = _("Aggregate %(aggregate_id)s: action '%(action)s' " "caused an error: %(reason)s.") class AggregateNotFound(NotFound): msg_fmt = _("Aggregate %(aggregate_id)s could not be found.") class AggregateNameExists(NovaException): msg_fmt = _("Aggregate %(aggregate_name)s already exists.") class AggregateHostNotFound(NotFound): msg_fmt = _("Aggregate %(aggregate_id)s has no host %(host)s.") class AggregateMetadataNotFound(NotFound): msg_fmt = _("Aggregate %(aggregate_id)s has no metadata with " "key %(metadata_key)s.") class AggregateHostExists(NovaException): msg_fmt = _("Aggregate %(aggregate_id)s already has host %(host)s.") class FlavorCreateFailed(NovaException): msg_fmt = _("Unable to create flavor") class InstancePasswordSetFailed(NovaException): msg_fmt = _("Failed to set admin password on %(instance)s " "because %(reason)s") safe = True class InstanceNotFound(NotFound): ec2_code = 'InvalidInstanceID.NotFound' msg_fmt = _("Instance %(instance_id)s could not be found.") class InstanceInfoCacheNotFound(NotFound): msg_fmt = _("Info cache for instance %(instance_uuid)s could not be " "found.") class InvalidAssociation(NotFound): ec2_code = 'InvalidAssociationID.NotFound' msg_fmt = _("Invalid association.") class MarkerNotFound(NotFound): msg_fmt = _("Marker %(marker)s could not be found.") class InvalidInstanceIDMalformed(Invalid): msg_fmt = _("Invalid id: %(instance_id)s (expecting \"i-...\")") ec2_code = 'InvalidInstanceID.Malformed' class InvalidVolumeIDMalformed(Invalid): msg_fmt = _("Invalid id: %(volume_id)s (expecting \"i-...\")") ec2_code = 'InvalidVolumeID.Malformed' class CouldNotFetchImage(NovaException): msg_fmt = _("Could not fetch image %(image_id)s") class CouldNotUploadImage(NovaException): msg_fmt = _("Could not upload image %(image_id)s") class TaskAlreadyRunning(NovaException): msg_fmt = _("Task %(task_name)s is already running on host %(host)s") class TaskNotRunning(NovaException): msg_fmt = _("Task %(task_name)s is not running on host %(host)s") class InstanceIsLocked(InstanceInvalidState): msg_fmt = _("Instance %(instance_uuid)s is locked") class ConfigDriveInvalidValue(Invalid): msg_fmt = _("Invalid value for Config Drive option: %(option)s") class ConfigDriveMountFailed(NovaException): msg_fmt = _("Could not mount vfat config drive. %(operation)s failed. " "Error: %(error)s") class ConfigDriveUnknownFormat(NovaException): msg_fmt = _("Unknown config drive format %(format)s. Select one of " "iso9660 or vfat.") class InterfaceAttachFailed(Invalid): msg_fmt = _("Failed to attach network adapter device to " "%(instance_uuid)s") class InterfaceDetachFailed(Invalid): msg_fmt = _("Failed to detach network adapter device from " "%(instance_uuid)s") class InstanceUserDataTooLarge(NovaException): msg_fmt = _("User data too large. User data must be no larger than " "%(maxsize)s bytes once base64 encoded. Your data is " "%(length)d bytes") class InstanceUserDataMalformed(NovaException): msg_fmt = _("User data needs to be valid base 64.") class InstanceUpdateConflict(NovaException): msg_fmt = _("Conflict updating instance %(instance_uuid)s. " "Expected: %(expected)s. Actual: %(actual)s") class UnknownInstanceUpdateConflict(InstanceUpdateConflict): msg_fmt = _("Conflict updating instance %(instance_uuid)s, but we were " "unable to determine the cause") class UnexpectedTaskStateError(InstanceUpdateConflict): pass class UnexpectedDeletingTaskStateError(UnexpectedTaskStateError): pass class InstanceActionNotFound(NovaException): msg_fmt = _("Action for request_id %(request_id)s on instance" " %(instance_uuid)s not found") class InstanceActionEventNotFound(NovaException): msg_fmt = _("Event %(event)s not found for action id %(action_id)s") class CryptoCAFileNotFound(FileNotFound): msg_fmt = _("The CA file for %(project)s could not be found") class CryptoCRLFileNotFound(FileNotFound): msg_fmt = _("The CRL file for %(project)s could not be found") class InstanceRecreateNotSupported(Invalid): msg_fmt = _('Instance recreate is not supported.') class ServiceGroupUnavailable(NovaException): msg_fmt = _("The service from servicegroup driver %(driver)s is " "temporarily unavailable.") class DBNotAllowed(NovaException): msg_fmt = _('%(binary)s attempted direct database access which is ' 'not allowed by policy') class UnsupportedVirtType(Invalid): msg_fmt = _("Virtualization type '%(virt)s' is not supported by " "this compute driver") class UnsupportedHardware(Invalid): msg_fmt = _("Requested hardware '%(model)s' is not supported by " "the '%(virt)s' virt driver") class Base64Exception(NovaException): msg_fmt = _("Invalid Base 64 data for file %(path)s") class BuildAbortException(NovaException): msg_fmt = _("Build of instance %(instance_uuid)s aborted: %(reason)s") class RescheduledException(NovaException): msg_fmt = _("Build of instance %(instance_uuid)s was re-scheduled: " "%(reason)s") class ShadowTableExists(NovaException): msg_fmt = _("Shadow table with name %(name)s already exists.") class InstanceFaultRollback(NovaException): def __init__(self, inner_exception=None): message = _("Instance rollback performed due to: %s") self.inner_exception = inner_exception super(InstanceFaultRollback, self).__init__(message % inner_exception) class OrphanedObjectError(NovaException): msg_fmt = _('Cannot call %(method)s on orphaned %(objtype)s object') class ObjectActionError(NovaException): msg_fmt = _('Object action %(action)s failed because: %(reason)s') class CoreAPIMissing(NovaException): msg_fmt = _("Core API extensions are missing: %(missing_apis)s") class AgentError(NovaException): msg_fmt = _('Error during following call to agent: %(method)s') class AgentTimeout(AgentError): msg_fmt = _('Unable to contact guest agent. ' 'The following call timed out: %(method)s') class AgentNotImplemented(AgentError): msg_fmt = _('Agent does not support the call: %(method)s') class InstanceGroupNotFound(NotFound): msg_fmt = _("Instance group %(group_uuid)s could not be found.") class InstanceGroupIdExists(NovaException): msg_fmt = _("Instance group %(group_uuid)s already exists.") class InstanceGroupMemberNotFound(NotFound): msg_fmt = _("Instance group %(group_uuid)s has no member with " "id %(instance_id)s.") class InstanceGroupPolicyNotFound(NotFound): msg_fmt = _("Instance group %(group_uuid)s has no policy %(policy)s.") class InstanceGroupSaveException(NovaException): msg_fmt = _("%(field)s should not be part of the updates.") class PluginRetriesExceeded(NovaException): msg_fmt = _("Number of retries to plugin (%(num_retries)d) exceeded.") class ImageDownloadModuleError(NovaException): msg_fmt = _("There was an error with the download module %(module)s. " "%(reason)s") class ImageDownloadModuleMetaDataError(ImageDownloadModuleError): msg_fmt = _("The metadata for this location will not work with this " "module %(module)s. %(reason)s.") class ImageDownloadModuleNotImplementedError(ImageDownloadModuleError): msg_fmt = _("The method %(method_name)s is not implemented.") class ImageDownloadModuleConfigurationError(ImageDownloadModuleError): msg_fmt = _("The module %(module)s is misconfigured: %(reason)s.") class ResourceMonitorError(NovaException): msg_fmt = _("Error when creating resource monitor: %(monitor)s") class PciDeviceWrongAddressFormat(NovaException): msg_fmt = _("The PCI address %(address)s has an incorrect format.") class PciDeviceInvalidAddressField(NovaException): msg_fmt = _("Invalid PCI Whitelist: " "The PCI address %(address)s has an invalid %(field)s.") class PciDeviceInvalidDeviceName(NovaException): msg_fmt = _("Invalid PCI Whitelist: " "The PCI whitelist can specify devname or address," " but not both") class PciDeviceNotFoundById(NotFound): msg_fmt = _("PCI device %(id)s not found") class PciDeviceNotFound(NotFound): msg_fmt = _("PCI Device %(node_id)s:%(address)s not found.") class PciDeviceInvalidStatus(Invalid): msg_fmt = _( "PCI device %(compute_node_id)s:%(address)s is %(status)s " "instead of %(hopestatus)s") class PciDeviceInvalidOwner(Invalid): msg_fmt = _( "PCI device %(compute_node_id)s:%(address)s is owned by %(owner)s " "instead of %(hopeowner)s") class PciDeviceRequestFailed(NovaException): msg_fmt = _( "PCI device request (%requests)s failed") class PciDevicePoolEmpty(NovaException): msg_fmt = _( "Attempt to consume PCI device %(compute_node_id)s:%(address)s " "from empty pool") class PciInvalidAlias(Invalid): msg_fmt = _("Invalid PCI alias definition: %(reason)s") class PciRequestAliasNotDefined(NovaException): msg_fmt = _("PCI alias %(alias)s is not defined") class MissingParameter(NovaException): ec2_code = 'MissingParameter' msg_fmt = _("Not enough parameters: %(reason)s") code = 400 class PciConfigInvalidWhitelist(Invalid): msg_fmt = _("Invalid PCI devices Whitelist config %(reason)s") # Cannot be templated, msg needs to be constructed when raised. class InternalError(NovaException): ec2_code = 'InternalError' msg_fmt = "%(err)s" class PciDevicePrepareFailed(NovaException): msg_fmt = _("Failed to prepare PCI device %(id)s for instance " "%(instance_uuid)s: %(reason)s") class PciDeviceDetachFailed(NovaException): msg_fmt = _("Failed to detach PCI device %(dev)s: %(reason)s") class PciDeviceUnsupportedHypervisor(NovaException): msg_fmt = _("%(type)s hypervisor does not support PCI devices") class KeyManagerError(NovaException): msg_fmt = _("Key manager error: %(reason)s") class VolumesNotRemoved(Invalid): msg_fmt = _("Failed to remove volume(s): (%(reason)s)") class InvalidVideoMode(Invalid): msg_fmt = _("Provided video model (%(model)s) is not supported.") class RngDeviceNotExist(Invalid): msg_fmt = _("The provided RNG device path: (%(path)s) is not " "present on the host.") class RequestedVRamTooHigh(NovaException): msg_fmt = _("The requested amount of video memory %(req_vram)d is higher " "than the maximum allowed by flavor %(max_vram)d.") class InvalidWatchdogAction(Invalid): msg_fmt = _("Provided watchdog action (%(action)s) is not supported.") class NoLiveMigrationForConfigDriveInLibVirt(NovaException): msg_fmt = _("Live migration of instances with config drives is not " "supported in libvirt unless libvirt instance path and " "drive data is shared across compute nodes.") class LiveMigrationWithOldNovaNotSafe(NovaException): msg_fmt = _("Host %(server)s is running an old version of Nova, " "live migrations involving that version may cause data loss. " "Upgrade Nova on %(server)s and try again.") class UnshelveException(NovaException): msg_fmt = _("Error during unshelve instance %(instance_id)s: %(reason)s") class ImageVCPULimitsRangeExceeded(Invalid): msg_fmt = _("Image vCPU limits %(sockets)d:%(cores)d:%(threads)d " "exceeds permitted %(maxsockets)d:%(maxcores)d:%(maxthreads)d") class ImageVCPUTopologyRangeExceeded(Invalid): msg_fmt = _("Image vCPU topology %(sockets)d:%(cores)d:%(threads)d " "exceeds permitted %(maxsockets)d:%(maxcores)d:%(maxthreads)d") class ImageVCPULimitsRangeImpossible(Invalid): msg_fmt = _("Requested vCPU limits %(sockets)d:%(cores)d:%(threads)d " "are impossible to satisfy for vcpus count %(vcpus)d") class InvalidArchitectureName(Invalid): msg_fmt = _("Architecture name '%(arch)s' is not recognised") class ImageNUMATopologyIncomplete(Invalid): msg_fmt = _("CPU and memory allocation must be provided for all " "NUMA nodes") class ImageNUMATopologyForbidden(Forbidden): msg_fmt = _("Image property '%(name)s' is not permitted to override " "NUMA configuration set against the flavor") class ImageNUMATopologyAsymmetric(Invalid): msg_fmt = _("Asymmetric NUMA topologies require explicit assignment " "of CPUs and memory to nodes in image or flavor") class ImageNUMATopologyCPUOutOfRange(Invalid): msg_fmt = _("CPU number %(cpunum)d is larger than max %(cpumax)d") class ImageNUMATopologyCPUDuplicates(Invalid): msg_fmt = _("CPU number %(cpunum)d is assigned to two nodes") class ImageNUMATopologyCPUsUnassigned(Invalid): msg_fmt = _("CPU number %(cpuset)s is not assigned to any node") class ImageNUMATopologyMemoryOutOfRange(Invalid): msg_fmt = _("%(memsize)d MB of memory assigned, but expected " "%(memtotal)d MB") class InvalidHostname(Invalid): msg_fmt = _("Invalid characters in hostname '%(hostname)s'") class NumaTopologyNotFound(NotFound): msg_fmt = _("Instance %(instance_uuid)s does not specify a NUMA topology") class MigrationContextNotFound(NotFound): msg_fmt = _("Instance %(instance_uuid)s does not specify a migration " "context.") class SocketPortRangeExhaustedException(NovaException): msg_fmt = _("Not able to acquire a free port for %(host)s") class SocketPortInUseException(NovaException): msg_fmt = _("Not able to bind %(host)s:%(port)d, %(error)s") class ImageSerialPortNumberInvalid(Invalid): msg_fmt = _("Number of serial ports '%(num_ports)s' specified in " "'%(property)s' isn't valid.") class ImageSerialPortNumberExceedFlavorValue(Invalid): msg_fmt = _("Forbidden to exceed flavor value of number of serial " "ports passed in image meta.") class InvalidImageConfigDrive(Invalid): msg_fmt = _("Image's config drive option '%(config_drive)s' is invalid") class InvalidHypervisorVirtType(Invalid): msg_fmt = _("Hypervisor virtualization type '%(hv_type)s' is not " "recognised") class InvalidVirtualMachineMode(Invalid): msg_fmt = _("Virtual machine mode '%(vmmode)s' is not recognised") class InvalidToken(Invalid): msg_fmt = _("The token '%(token)s' is invalid or has expired") class InvalidConnectionInfo(Invalid): msg_fmt = _("Invalid Connection Info") class InstanceQuiesceNotSupported(Invalid): msg_fmt = _('Quiescing is not supported in instance %(instance_id)s') class QemuGuestAgentNotEnabled(Invalid): msg_fmt = _('QEMU guest agent is not enabled') class SetAdminPasswdNotSupported(Invalid): msg_fmt = _('Set admin password is not supported') class MemoryPageSizeInvalid(Invalid): msg_fmt = _("Invalid memory page size '%(pagesize)s'") class MemoryPageSizeForbidden(Invalid): msg_fmt = _("Page size %(pagesize)s forbidden against '%(against)s'") class MemoryPageSizeNotSupported(Invalid): msg_fmt = _("Page size %(pagesize)s is not supported by the host.") class CPUPinningNotSupported(Invalid): msg_fmt = _("CPU pinning is not supported by the host: " "%(reason)s") class CPUPinningInvalid(Invalid): msg_fmt = _("Cannot pin/unpin cpus %(requested)s from the following " "pinned set %(pinned)s") class CPUPinningUnknown(Invalid): msg_fmt = _("CPU set to pin/unpin %(requested)s must be a subset of " "known CPU set %(cpuset)s") class ImageCPUPinningForbidden(Forbidden): msg_fmt = _("Image property 'hw_cpu_policy' is not permitted to override " "CPU pinning policy set against the flavor") class UnsupportedPolicyException(Invalid): msg_fmt = _("ServerGroup policy is not supported: %(reason)s") class CellMappingNotFound(NotFound): msg_fmt = _("Cell %(uuid)s has no mapping.") class NUMATopologyUnsupported(Invalid): msg_fmt = _("Host does not support guests with NUMA topology set") class MemoryPagesUnsupported(Invalid): msg_fmt = _("Host does not support guests with custom memory page sizes") class EnumFieldInvalid(Invalid): msg_fmt = _('%(typename)s in %(fieldname)s is not an instance of Enum') class EnumFieldUnset(Invalid): msg_fmt = _('%(fieldname)s missing field type') class InvalidImageFormat(Invalid): msg_fmt = _("Invalid image format '%(format)s'") class UnsupportedImageModel(Invalid): msg_fmt = _("Image model '%(image)s' is not supported") class HostMappingNotFound(Invalid): msg_fmt = _("Host '%(name)s' is not mapped to any cell") </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">apache-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-6,969,698,482,296,145,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">28.09826</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">79</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.672852</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.944364</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45133"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">google/ion</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">ion/dev/doxygen_filter.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">8299</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">#!/usr/bin/python # # Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """Doxygen pre-filter script for ion. This filter processes code and adds Doxygen-compatible markup in various places to enable Doxygen to read the docs more fully. Unlike some other Doxygen filters, it is designed to work with Doxygen's newer markdown syntax. In order to ensure proper syntax coloring of indented code blocks, make sure there is a blank (commented) line both above and below the block. For example: // Comment comment comment. // // int CodeBlock() { // Goes here; // } // // More comment. """ import re import sys class DoxygenFormatter(object): """Transforms lines of a source file to make them doxygen-friendly.""" ANYWHERE = 'anywhere' COMMENT = 'comment' def __init__(self, outfile): # The file-like object to which we will write lines. self.out = outfile # A buffer for storing empty lines which we can use later if we need to # retroactively insert markup without causing line number offset problems. self.empty_line_buffer = [] # Whether we are currently inside an indented code block. self.in_code_block = False self.CompileExpressions() def CompileExpressions(self): """Pre-compiles frequently used regexps for improved performance. The regexps are arranged as a list of 3-tuples, where the second value is the replacement string (which may include backreferences) and the third value is one of the context constants ANYWHERE or COMMENT. This is a list of tuples instead of a dictionary because order matters: earlier regexps will be applied first, and the resulting text (not the original) will be what is seen by subsequent regexps. """ self.comment_regex = re.compile(r'^\s*//') self.substitutions = [ # Remove copyright lines. (re.compile(r'^\s*//\s*[Cc]opyright.*Google.*'), r'', self.ANYWHERE), # Remove any comment lines that consist of only punctuation (banners). # We only allow a maximum of two spaces before the punctuation so we # don't accidentally get rid of code examples with bare braces and # whatnot. (re.compile(r'(^\s*)//\s{0,2}[-=#/]+$'), r'\1//\n', self.ANYWHERE), # If we find something that looks like a list item that is indented four # or more spaces, pull it back to the left so doxygen's Markdown engine # doesn't treat it like a code block. (re.compile(r'(^\s*)//\s{4,}([-\d*].*)'), r'\1 \2', self.COMMENT), (re.compile(r'TODO'), r'@todo ', self.COMMENT), # Replace leading 'Note:' or 'Note that' in a comment with @note (re.compile(r'(\/\/\s+)Note(?:\:| that)', re.I), r'\1@note', self.COMMENT), # Replace leading 'Warning:' in a comment with @warning (re.compile(r'(\/\/\s+)Warning:', re.I), r'\1@warning', self.COMMENT), # Replace leading 'Deprecated' in a comment with @deprecated (re.compile(r'(\/\/\s+)Deprecated[^\w\s]*', re.I), r'\1@deprecated', self.COMMENT), # Replace pipe-delimited parameter names with backtick-delimiters (re.compile(r'\|(\w+)\|'), r'`\1`', self.COMMENT), # Convert standalone comment lines to Doxygen style. (re.compile(r'(^\s*)//(?=[^/])'), r'\1///', self.ANYWHERE), # Strip trailing comments from preprocessor directives. (re.compile(r'(^#.*)//.*'), r'\1', self.ANYWHERE), # Convert remaining trailing comments to doxygen style, unless they are # documenting the end of a block. (re.compile(r'([^} ]\s+)//(?=[^/])'), r'\1///<', self.ANYWHERE), ] def Transform(self, line): """Performs the regexp transformations defined by self.substitutions. Args: line: The line to transform. Returns: The resulting line. """ for (regex, repl, where) in self.substitutions: if where is self.COMMENT and not self.comment_regex.match(line): return line line = regex.sub(repl, line) return line def AppendToBufferedLine(self, text): """Appends text to the last buffered empty line. Empty lines are buffered rather than being written out directly. This lets us retroactively rewrite buffered lines to include markup that affects the following line, while avoiding the line number offset that would result from inserting a line that wasn't in the original source. Args: text: The text to append to the line. Returns: True if there was an available empty line to which text could be appended, and False otherwise. """ if self.empty_line_buffer: last_line = self.empty_line_buffer.pop().rstrip() last_line += text + '\n' self.empty_line_buffer.append(last_line) return True else: return False def ConvertCodeBlock(self, line): """Converts any code block that may begin or end on this line. Doxygen has (at least) two kinds of code blocks. Any block indented at least four spaces gets formatted as code, but (for some reason) no syntax highlighting is applied. Any block surrounded by "~~~" on both sides is also treated as code, but these are syntax highlighted intelligently depending on the file type. We typically write code blocks in the former style, but we'd like them to be highlighted, so this function converts them to the latter style by adding in the ~~~ lines. To make this a bit more complicated, we would really prefer not to insert new lines into the file, since that will make the line numbers shown in doxygen not match the line numbers in the actual source code. For this reason, we only perform the conversion if at least one "blank" line (empty comment line) appears before the start of the code block. If we get down to the bottom of the block and there's no blank line after it, we will be forced to add a line, since we can't go back and undo what we already did. Args: line: The line to process. Returns: The converted line. """ if not self.in_code_block and re.match(r'\s*///\s{4,}', line): if self.AppendToBufferedLine(' ~~~'): # If this fails, we'll just leave it un-highlighted. self.in_code_block = True elif self.in_code_block and not re.match(r'\s*///\s{4,}', line): if not self.AppendToBufferedLine(' ~~~'): # This is bad. We don't have a buffered line to use to end the code # block, so we'll have to insert one. This will cause the line # numbers to stop matching the original source, unfortunately. line = '/// ~~~\n' + line self.in_code_block = False return line def ProcessLine(self, line): """Processes a line. If the line is an empty line inside a comment, we buffer it for possible rewriting later on. Otherwise, we transform it using our regexps and write it (as well as any buffered blank lines) out to the output. Args: line: The line to process. """ line = self.Transform(line) if line.strip() == '///': # We may repurpose this empty line later, so don't write it out yet. self.empty_line_buffer.append(line) else: line = self.ConvertCodeBlock(line) # Flush the line buffer and write this line as well. for buffered_line in self.empty_line_buffer: self.out.write(buffered_line) self.empty_line_buffer = [] self.out.write(line) def main(argv): sourcefile = argv[1] with open(sourcefile, 'r') as infile: formatter = DoxygenFormatter(sys.stdout) for line in infile: formatter.ProcessLine(line) if __name__ == '__main__': main(sys.argv) </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">apache-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">6,935,754,025,838,835,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">35.884444</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">80</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.662369</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.92017</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45134"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">FlannelFox/FlannelFox</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">tests/flannelfox/torrenttools/test_torrentQueue.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1999</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "># -*- coding: utf-8 -*- import unittest from unittest.mock import patch import os from flannelfox.torrenttools.TorrentQueue import Queue from flannelfox.torrenttools import Torrents class TestTorrentQueue(unittest.TestCase): testDatabaseFile = 'ff.db' def removeDatabase(self): try: os.remove(self.testDatabaseFile) except Exception: pass @patch.object(Queue, 'databaseTorrentBlacklisted') @patch.object(Queue, 'databaseTorrentExists') def test_Queue(self, mockDatabaseTorrentExists, mockDatabaseTorrentBlacklisted): self.removeDatabase() torrentQueue = Queue() mockDatabaseTorrentBlacklisted.return_value = False mockDatabaseTorrentExists.return_value = False # Ensure len returns a valid answer self.assertEqual(len(torrentQueue), 0) # Make sure appending an item works torrentQueue.append(Torrents.TV(torrentTitle='some.show.s01e01.720p.junk.here')) self.assertEqual(len(torrentQueue), 1) # Make sure appending a duplicate item does not work torrentQueue.append(Torrents.TV(torrentTitle='some.show.s01e01.720p.junk.here')) self.assertEqual(len(torrentQueue), 1) # Add a different item and make sure it works torrentQueue.append(Torrents.TV(torrentTitle='some.show.s01e02.720p.junk.here2')) self.assertEqual(len(torrentQueue), 2) mockDatabaseTorrentBlacklisted.return_value = True mockDatabaseTorrentExists.return_value = False # Check if Blacklisted torrent gets blocked torrentQueue.append(Torrents.TV(torrentTitle='some.show.s01e02.720p.junk.here3')) self.assertEqual(len(torrentQueue), 2) mockDatabaseTorrentBlacklisted.return_value = False mockDatabaseTorrentExists.return_value = True # Check if Existing Torrent in Database gets blocked torrentQueue.append(Torrents.TV(torrentTitle='some.show.s01e02.720p.junk.here3')) self.assertEqual(len(torrentQueue), 2) mockDatabaseTorrentBlacklisted.return_value = False mockDatabaseTorrentExists.return_value = False if __name__ == '__main__': unittest.main() </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-7,580,618,446,876,378,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">29.753846</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">83</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.78039</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.39966</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">true</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45135"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">vhosouza/invesalius3</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">invesalius/gui/task_exporter.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">15556</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">#-------------------------------------------------------------------------- # Software: InVesalius - Software de Reconstrucao 3D de Imagens Medicas # Copyright: (C) 2001 Centro de Pesquisas Renato Archer # Homepage: http://www.softwarepublico.gov.br # Contact: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a9c0c7dfccdac8c5c0dcdae9caddc087cec6df87cbdb">[email protected]</a> # License: GNU - GPL 2 (LICENSE.txt/LICENCA.txt) #-------------------------------------------------------------------------- # Este programa e software livre; voce pode redistribui-lo e/ou # modifica-lo sob os termos da Licenca Publica Geral GNU, conforme # publicada pela Free Software Foundation; de acordo com a versao 2 # da Licenca. # # Este programa eh distribuido na expectativa de ser util, mas SEM # QUALQUER GARANTIA; sem mesmo a garantia implicita de # COMERCIALIZACAO ou de ADEQUACAO A QUALQUER PROPOSITO EM # PARTICULAR. Consulte a Licenca Publica Geral GNU para obter mais # detalhes. #-------------------------------------------------------------------------- import os import pathlib import sys import wx try: import wx.lib.agw.hyperlink as hl except ImportError: import wx.lib.hyperlink as hl import wx.lib.platebtn as pbtn from pubsub import pub as Publisher import invesalius.constants as const import invesalius.gui.dialogs as dlg import invesalius.project as proj import invesalius.session as ses from invesalius import inv_paths BTN_MASK = wx.NewId() BTN_PICTURE = wx.NewId() BTN_SURFACE = wx.NewId() BTN_REPORT = wx.NewId() BTN_REQUEST_RP = wx.NewId() WILDCARD_SAVE_3D = "Inventor (*.iv)|*.iv|"\ "PLY (*.ply)|*.ply|"\ "Renderman (*.rib)|*.rib|"\ "STL (*.stl)|*.stl|"\ "STL ASCII (*.stl)|*.stl|"\ "VRML (*.vrml)|*.vrml|"\ "VTK PolyData (*.vtp)|*.vtp|"\ "Wavefront (*.obj)|*.obj|"\ "X3D (*.x3d)|*.x3d" INDEX_TO_TYPE_3D = {0: const.FILETYPE_IV, 1: const.FILETYPE_PLY, 2: const.FILETYPE_RIB, 3: const.FILETYPE_STL, 4: const.FILETYPE_STL_ASCII, 5: const.FILETYPE_VRML, 6: const.FILETYPE_VTP, 7: const.FILETYPE_OBJ, 8: const.FILETYPE_X3D} INDEX_TO_EXTENSION = {0: "iv", 1: "ply", 2: "rib", 3: "stl", 4: "stl", 5: "vrml", 6: "vtp", 7: "obj", 8: "x3d"} WILDCARD_SAVE_2D = "BMP (*.bmp)|*.bmp|"\ "JPEG (*.jpg)|*.jpg|"\ "PNG (*.png)|*.png|"\ "PostScript (*.ps)|*.ps|"\ "Povray (*.pov)|*.pov|"\ "TIFF (*.tiff)|*.tiff" INDEX_TO_TYPE_2D = {0: const.FILETYPE_BMP, 1: const.FILETYPE_JPG, 2: const.FILETYPE_PNG, 3: const.FILETYPE_PS, 4: const.FILETYPE_POV, 5: const.FILETYPE_OBJ} WILDCARD_SAVE_MASK = "VTK ImageData (*.vti)|*.vti" class TaskPanel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent) inner_panel = InnerTaskPanel(self) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(inner_panel, 1, wx.EXPAND | wx.GROW | wx.BOTTOM | wx.RIGHT | wx.LEFT, 7) sizer.Fit(self) self.SetSizer(sizer) self.Update() self.SetAutoLayout(1) class InnerTaskPanel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent) backgroud_colour = wx.Colour(255,255,255) self.SetBackgroundColour(backgroud_colour) self.SetAutoLayout(1) # Counter for projects loaded in current GUI # Fixed hyperlink items tooltip = wx.ToolTip(_("Export InVesalius screen to an image file")) link_export_picture = hl.HyperLinkCtrl(self, -1, _("Export picture...")) link_export_picture.SetUnderlines(False, False, False) link_export_picture.SetBold(True) link_export_picture.SetColours("BLACK", "BLACK", "BLACK") link_export_picture.SetBackgroundColour(self.GetBackgroundColour()) link_export_picture.SetToolTip(tooltip) link_export_picture.AutoBrowse(False) link_export_picture.UpdateLink() link_export_picture.Bind(hl.EVT_HYPERLINK_LEFT, self.OnLinkExportPicture) tooltip = wx.ToolTip(_("Export 3D surface")) link_export_surface = hl.HyperLinkCtrl(self, -1,_("Export 3D surface...")) link_export_surface.SetUnderlines(False, False, False) link_export_surface.SetBold(True) link_export_surface.SetColours("BLACK", "BLACK", "BLACK") link_export_surface.SetBackgroundColour(self.GetBackgroundColour()) link_export_surface.SetToolTip(tooltip) link_export_surface.AutoBrowse(False) link_export_surface.UpdateLink() link_export_surface.Bind(hl.EVT_HYPERLINK_LEFT, self.OnLinkExportSurface) #tooltip = wx.ToolTip(_("Export 3D mask (voxels)")) #link_export_mask = hl.HyperLinkCtrl(self, -1,_("Export mask...")) #link_export_mask.SetUnderlines(False, False, False) #link_export_mask.SetColours("BLACK", "BLACK", "BLACK") #link_export_mask.SetToolTip(tooltip) #link_export_mask.AutoBrowse(False) #link_export_mask.UpdateLink() #link_export_mask.Bind(hl.EVT_HYPERLINK_LEFT, # self.OnLinkExportMask) #tooltip = wx.ToolTip("Request rapid prototyping services") #link_request_rp = hl.HyperLinkCtrl(self,-1,"Request rapid prototyping...") #link_request_rp.SetUnderlines(False, False, False) #link_request_rp.SetColours("BLACK", "BLACK", "BLACK") #link_request_rp.SetToolTip(tooltip) #link_request_rp.AutoBrowse(False) #link_request_rp.UpdateLink() #link_request_rp.Bind(hl.EVT_HYPERLINK_LEFT, self.OnLinkRequestRP) #tooltip = wx.ToolTip("Open report tool...") #link_report = hl.HyperLinkCtrl(self,-1,"Open report tool...") #link_report.SetUnderlines(False, False, False) #link_report.SetColours("BLACK", "BLACK", "BLACK") #link_report.SetToolTip(tooltip) #link_report.AutoBrowse(False) #link_report.UpdateLink() #link_report.Bind(hl.EVT_HYPERLINK_LEFT, self.OnLinkReport) # Image(s) for buttons if sys.platform == 'darwin': BMP_EXPORT_SURFACE = wx.Bitmap(\ os.path.join(inv_paths.ICON_DIR, "surface_export_original.png"), wx.BITMAP_TYPE_PNG).ConvertToImage()\ .Rescale(25, 25).ConvertToBitmap() BMP_TAKE_PICTURE = wx.Bitmap(\ os.path.join(inv_paths.ICON_DIR, "tool_photo_original.png"), wx.BITMAP_TYPE_PNG).ConvertToImage()\ .Rescale(25, 25).ConvertToBitmap() #BMP_EXPORT_MASK = wx.Bitmap("../icons/mask.png", # wx.BITMAP_TYPE_PNG) else: BMP_EXPORT_SURFACE = wx.Bitmap(os.path.join(inv_paths.ICON_DIR, "surface_export.png"), wx.BITMAP_TYPE_PNG).ConvertToImage()\ .Rescale(25, 25).ConvertToBitmap() BMP_TAKE_PICTURE = wx.Bitmap(os.path.join(inv_paths.ICON_DIR, "tool_photo.png"), wx.BITMAP_TYPE_PNG).ConvertToImage()\ .Rescale(25, 25).ConvertToBitmap() #BMP_EXPORT_MASK = wx.Bitmap("../icons/mask_small.png", # wx.BITMAP_TYPE_PNG) # Buttons related to hyperlinks button_style = pbtn.PB_STYLE_SQUARE | pbtn.PB_STYLE_DEFAULT button_picture = pbtn.PlateButton(self, BTN_PICTURE, "", BMP_TAKE_PICTURE, style=button_style) button_picture.SetBackgroundColour(self.GetBackgroundColour()) self.button_picture = button_picture button_surface = pbtn.PlateButton(self, BTN_SURFACE, "", BMP_EXPORT_SURFACE, style=button_style) button_surface.SetBackgroundColour(self.GetBackgroundColour()) #button_mask = pbtn.PlateButton(self, BTN_MASK, "", # BMP_EXPORT_MASK, # style=button_style) #button_request_rp = pbtn.PlateButton(self, BTN_REQUEST_RP, "", # BMP_IMPORT, style=button_style) #button_report = pbtn.PlateButton(self, BTN_REPORT, "", # BMP_IMPORT, # style=button_style) # When using PlaneButton, it is necessary to bind events from parent win self.Bind(wx.EVT_BUTTON, self.OnButton) # Tags and grid sizer for fixed items flag_link = wx.EXPAND|wx.GROW|wx.LEFT|wx.TOP flag_button = wx.EXPAND | wx.GROW fixed_sizer = wx.FlexGridSizer(rows=2, cols=2, hgap=2, vgap=0) fixed_sizer.AddGrowableCol(0, 1) fixed_sizer.AddMany([ (link_export_picture, 1, flag_link, 3), (button_picture, 0, flag_button), (link_export_surface, 1, flag_link, 3), (button_surface, 0, flag_button),]) #(link_export_mask, 1, flag_link, 3), #(button_mask, 0, flag_button)]) #(link_report, 0, flag_link, 3), #(button_report, 0, flag_button), #(link_request_rp, 1, flag_link, 3), #(button_request_rp, 0, flag_button)]) # Add line sizers into main sizer main_sizer = wx.BoxSizer(wx.VERTICAL) main_sizer.Add(fixed_sizer, 0, wx.GROW|wx.EXPAND) # Update main sizer and panel layout self.SetSizer(main_sizer) self.Fit() self.sizer = main_sizer self.__init_menu() def __init_menu(self): menu = wx.Menu() self.id_to_name = {const.AXIAL:_("Axial slice"), const.CORONAL:_("Coronal slice"), const.SAGITAL:_("Sagittal slice"), const.VOLUME:_("Volume")} for id in self.id_to_name: item = wx.MenuItem(menu, id, self.id_to_name[id]) menu.Append(item) self.menu_picture = menu menu.Bind(wx.EVT_MENU, self.OnMenuPicture) def OnMenuPicture(self, evt): id = evt.GetId() value = dlg.ExportPicture(self.id_to_name[id]) if value: filename, filetype = value Publisher.sendMessage('Export picture to file', orientation=id, filename=filename, filetype=filetype) def OnLinkExportPicture(self, evt=None): self.button_picture.PopupMenu(self.menu_picture) def OnLinkExportMask(self, evt=None): project = proj.Project() if sys.platform == 'win32': project_name = project.name else: project_name = project.name+".vti" dlg = wx.FileDialog(None, "Save mask as...", # title "", # last used directory project_name, # filename WILDCARD_SAVE_MASK, wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT) dlg.SetFilterIndex(0) # default is VTI if dlg.ShowModal() == wx.ID_OK: filename = dlg.GetPath() extension = "vti" if sys.platform != 'win32': if filename.split(".")[-1] != extension: filename = filename + "."+ extension filetype = const.FILETYPE_IMAGEDATA Publisher.sendMessage('Export mask to file', filename=filename, filetype=filetype) def OnLinkExportSurface(self, evt=None): "OnLinkExportSurface" project = proj.Project() n_surface = 0 for index in project.surface_dict: if project.surface_dict[index].is_shown: n_surface += 1 if n_surface: if sys.platform == 'win32': project_name = pathlib.Path(project.name).stem else: project_name = pathlib.Path(project.name).stem + ".stl" session = ses.Session() last_directory = session.get('paths', 'last_directory_3d_surface', '') dlg = wx.FileDialog(None, _("Save 3D surface as..."), # title last_directory, # last used directory project_name, # filename WILDCARD_SAVE_3D, wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT) dlg.SetFilterIndex(3) # default is STL if dlg.ShowModal() == wx.ID_OK: filetype_index = dlg.GetFilterIndex() filetype = INDEX_TO_TYPE_3D[filetype_index] filename = dlg.GetPath() extension = INDEX_TO_EXTENSION[filetype_index] if sys.platform != 'win32': if filename.split(".")[-1] != extension: filename = filename + "."+ extension if filename: session['paths']['last_directory_3d_surface'] = os.path.split(filename)[0] session.WriteSessionFile() Publisher.sendMessage('Export surface to file', filename=filename, filetype=filetype) if not os.path.exists(filename): dlg = wx.MessageDialog(None, _("It was not possible to save the surface."), _("Error saving surface"), wx.OK | wx.ICON_ERROR) dlg.ShowModal() dlg.Destroy() else: dlg = wx.MessageDialog(None, _("You need to create a surface and make it ") + _("visible before exporting it."), 'InVesalius 3', wx.OK | wx.ICON_INFORMATION) try: dlg.ShowModal() finally: dlg.Destroy() def OnLinkRequestRP(self, evt=None): pass def OnLinkReport(self, evt=None): pass def OnButton(self, evt): id = evt.GetId() if id == BTN_PICTURE: self.OnLinkExportPicture() elif id == BTN_SURFACE: self.OnLinkExportSurface() elif id == BTN_REPORT: self.OnLinkReport() elif id == BTN_REQUEST_RP: self.OnLinkRequestRP() else:# id == BTN_MASK: self.OnLinkExportMask() </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-955,293,151,013,029,400</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">39.300518</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">98</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.509771</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.917401</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45136"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">bmya/tkobr-addons</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">tko_web_sessions_management/main.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">11671</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "># -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # ThinkOpen Solutions Brasil # Copyright (C) Thinkopen Solutions <http://www.tkobr.com>. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import logging import openerp from openerp.osv import fields, osv, orm import pytz from datetime import date, datetime, time, timedelta from dateutil.relativedelta import * from openerp.addons.base.ir.ir_cron import _intervalTypes from openerp import SUPERUSER_ID from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT from openerp.http import request from openerp.tools.translate import _ from openerp import http import werkzeug.contrib.sessions from openerp.http import Response # from openerp import pooler _logger = logging.getLogger(__name__) class Home_tkobr(openerp.addons.web.controllers.main.Home): @http.route('/web/login', type='http', auth="none") def web_login(self, redirect=None, **kw): openerp.addons.web.controllers.main.ensure_db() multi_ok = True calendar_set = 0 calendar_ok = False calendar_group = '' unsuccessful_message = '' now = datetime.now() if request.httprequest.method == 'GET' and redirect and request.session.uid: return http.redirect_with_hash(redirect) if not request.uid: request.uid = openerp.SUPERUSER_ID values = request.params.copy() if not redirect: redirect = '/web?' + request.httprequest.query_string values['redirect'] = redirect try: values['databases'] = http.db_list() except openerp.exceptions.AccessDenied: values['databases'] = None if request.httprequest.method == 'POST': old_uid = request.uid uid = False if 'login' in request.params and 'password' in request.params: uid = request.session.authenticate(request.session.db, request.params[ 'login'], request.params['password']) if uid is not False: user = request.registry.get('res.users').browse( request.cr, request.uid, uid, request.context) if not uid is SUPERUSER_ID: # check for multiple sessions block sessions = request.registry.get('ir.sessions').search( request.cr, request.uid, [ ('user_id', '=', uid), ('logged_in', '=', True)], context=request.context) if sessions and user.multiple_sessions_block: multi_ok = False if multi_ok: # check calendars calendar_obj = request.registry.get( 'resource.calendar') attendance_obj = request.registry.get( 'resource.calendar.attendance') # GET USER LOCAL TIME if user.tz: tz = pytz.timezone(user.tz) else: tz = pytz.timezone('GMT') tzoffset = tz.utcoffset(now) now = now + tzoffset if user.login_calendar_id: calendar_set += 1 # check user calendar attendances = attendance_obj.search(request.cr, request.uid, [('calendar_id', '=', user.login_calendar_id.id), ('dayofweek', '=', str(now.weekday())), ('hour_from', '<=', now.hour + now.minute / 60.0), ('hour_to', '>=', now.hour + now.minute / 60.0)], context=request.context) if attendances: calendar_ok = True else: unsuccessful_message = "unsuccessful login from '%s', user time out of allowed calendar defined in user" % request.params[ 'login'] else: # check user groups calendar for group in user.groups_id: if group.login_calendar_id: calendar_set += 1 attendances = attendance_obj.search(request.cr, request.uid, [('calendar_id', '=', group.login_calendar_id.id), ('dayofweek', '=', str(now.weekday())), ('hour_from', '<=', now.hour + now.minute / 60.0), ('hour_to', '>=', now.hour + now.minute / 60.0)], context=request.context) if attendances: calendar_ok = True else: calendar_group = group.name if sessions and group.multiple_sessions_block and multi_ok: multi_ok = False unsuccessful_message = "unsuccessful login from '%s', multisessions block defined in group '%s'" % ( request.params['login'], group.name) break if calendar_set > 0 and calendar_ok == False: unsuccessful_message = "unsuccessful login from '%s', user time out of allowed calendar defined in group '%s'" % ( request.params['login'], calendar_group) else: unsuccessful_message = "unsuccessful login from '%s', multisessions block defined in user" % request.params[ 'login'] else: unsuccessful_message = "unsuccessful login from '%s', wrong username or password" % request.params[ 'login'] if not unsuccessful_message or uid is SUPERUSER_ID: self.save_session( request.cr, uid, user.tz, request.httprequest.session.sid, context=request.context) return http.redirect_with_hash(redirect) user = request.registry.get('res.users').browse( request.cr, SUPERUSER_ID, SUPERUSER_ID, request.context) self.save_session( request.cr, uid, user.tz, request.httprequest.session.sid, unsuccessful_message, request.context) _logger.error(unsuccessful_message) request.uid = old_uid values['error'] = 'Login failed due to one of the following reasons:' values['reason1'] = '- Wrong login/password' values['reason2'] = '- User not allowed to have multiple logins' values[ 'reason3'] = '- User not allowed to login at this specific time or day' return request.render('web.login', values) def save_session( self, cr, uid, tz, sid, unsuccessful_message='', context=None): now = fields.datetime.now() session_obj = request.registry.get('ir.sessions') cr = request.registry.cursor() # for GeoIP geo_ip_resolver = None ip_location = "" try: import GeoIP geo_ip_resolver = GeoIP.open( '/usr/share/GeoIP/GeoIP.dat', GeoIP.GEOIP_STANDARD) except ImportError: geo_ip_resolver = False if geo_ip_resolver: ip_location = (str(geo_ip_resolver.country_name_by_addr( request.httprequest.remote_addr)) or "") # autocommit: our single update request will be performed atomically. # (In this way, there is no opportunity to have two transactions # interleaving their cr.execute()..cr.commit() calls and have one # of them rolled back due to a concurrent access.) cr.autocommit(True) user = request.registry.get('res.users').browse( cr, request.uid, uid, request.context) ip = request.httprequest.headers.environ['REMOTE_ADDR'] logged_in = True if unsuccessful_message: uid = SUPERUSER_ID logged_in = False sessions = False else: sessions = session_obj.search(cr, uid, [('session_id', '=', sid), ('ip', '=', ip), ('user_id', '=', uid), ('logged_in', '=', True)], context=context) if not sessions: values = { 'user_id': uid, 'logged_in': logged_in, 'session_id': sid, 'session_seconds': user.session_default_seconds, 'multiple_sessions_block': user.multiple_sessions_block, 'date_login': now, 'expiration_date': datetime.strftime( (datetime.strptime( now, DEFAULT_SERVER_DATETIME_FORMAT) + relativedelta( seconds=user.session_default_seconds)), DEFAULT_SERVER_DATETIME_FORMAT), 'ip': ip, 'ip_location': ip_location, 'remote_tz': tz or 'GMT', 'unsuccessful_message': unsuccessful_message, } session_obj.create(cr, uid, values, context=context) cr.commit() cr.close() return True @http.route('/web/session/logout', type='http', auth="none") def logout(self, redirect='/web'): request.session.logout(keep_db=True, logout_type='ul') return werkzeug.utils.redirect(redirect, 303) </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">agpl-3.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-2,443,623,195,217,171,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">46.060484</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">154</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.476223</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">5.164159</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45137"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">limemadness/selenium_training</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">test_countries_sort.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">2050</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">import pytest from selenium import webdriver from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC @pytest.fixture #def driver(request): # wd = webdriver.Firefox(firefox_binary="c:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe") # print(wd.capabilities) # request.addfinalizer(wd.quit) # return wd def driver(request): wd = webdriver.Chrome() wd.implicitly_wait(10) request.addfinalizer(wd.quit) return wd def test_countries_sort(driver): driver.get("http://localhost/litecart/admin/") driver.find_element_by_name("username").click() driver.find_element_by_name("username").send_keys("admin") driver.find_element_by_name("password").click() driver.find_element_by_name("password").send_keys("admin") driver.find_element_by_xpath("//div[2]/button").click() driver.get("http://localhost/litecart/admin/?app=countries&doc=countries") #get country data countries = driver.find_elements_by_css_selector("#content tr.row") countries_timezone_url = [] country_name = [] #verify alphabetical order of country names for country in countries: country_name.append(country.find_element_by_css_selector("td:nth-child(5)").text) assert sorted(country_name) == country_name #get countries with multiple timezones for country in countries: if int(country.find_element_by_css_selector("td:nth-child(6)").text) > 0: countries_timezone_url.append(country.find_element_by_css_selector("td:nth-child(5) a").get_attribute("href")) #verify alphabetical order of timezones for country_timezone_url in countries_timezone_url: driver.get(country_timezone_url) timezone_list = driver.find_elements_by_css_selector("#table-zones td:nth-child(2)") del timezone_list[-1:] timezones = [] for timezone in timezone_list: timezones.append(timezone.text) print(timezones) assert sorted(timezones) == timezones </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">apache-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-2,674,985,192,745,299,500</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">40</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">122</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.699024</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.693694</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45138"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Beyond-Imagination/BlubBlub</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">ChatbotServer/ChatbotEnv/Lib/site-packages/konlpy/corpus.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1849</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">#! /usr/bin/python2.7 # -*- coding: utf-8 -*- import os from . import utils class CorpusLoader(): """Loader for corpora. For a complete list of corpora available in KoNLPy, refer to :ref:`corpora`. .. code-block:: python >>> from konlpy.corpus import kolaw >>> fids = kolaw.fileids() >>> fobj = kolaw.open(fids[0]) >>> print fobj.read(140) 대한민국헌법 유구한 역사와 전통에 빛나는 우리 대한국민은 3·1운동으로 건립된 대한민국임시정부의 법통과 불의에 항거한 4·19민주이념을 계승하고, 조국의 민주개혁과 평화적 통일의 사명에 입각하여 정의·인도와 동포애로써 민족의 단결을 공고히 하고, 모든 사회적 폐습과 불의를 타파하며, 자율과 조화를 바 바 """ def abspath(self, filename=None): """Absolute path of corpus file. If ``filename`` is *None*, returns absolute path of corpus. :param filename: Name of a particular file in the corpus. """ basedir = '%s/data/corpus/%s' % (utils.installpath, self.name) if filename: return '%s/%s' % (basedir, filename) else: return '%s/' % basedir def fileids(self): """List of file IDs in the corpus.""" return os.listdir(self.abspath()) def open(self, filename): """Method to open a file in the corpus. Returns a file object. :param filename: Name of a particular file in the corpus. """ return utils.load_txt(self.abspath(filename)) def __init__(self, name=None): if not name: raise Exception("You need to input the name of the corpus") else: self.name = name kolaw = CorpusLoader('kolaw') kobill = CorpusLoader('kobill') </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-3.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3,655,224,125,584,470,500</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">27.035088</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">171</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.58761</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">2.201102</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45139"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">ErickMurillo/aprocacaho</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">organizacion/admin.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">3456</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">from django.contrib import admin from .models import * # Register your models here. #organizacion class InlineEscuelaCampo(admin.TabularInline): model = EscuelaCampo extra = 1 class OrganizacionAdmin(admin.ModelAdmin): inlines = [InlineEscuelaCampo] list_display = ('id','nombre','siglas') list_display_links = ('id','nombre','siglas') #encuesta organizacion class InlineAspectosJuridicos(admin.TabularInline): model = AspectosJuridicos max_num = 1 can_delete = False class InlineListaMiembros(admin.TabularInline): model = ListaMiembros extra = 1 class InlineDocumentacion(admin.TabularInline): model = Documentacion extra = 1 max_num = 7 class InlineProduccionComercializacion(admin.TabularInline): model = ProduccionComercializacion extra = 1 class InlineNivelCumplimiento(admin.TabularInline): model = NivelCumplimiento extra = 1 max_num = 7 # class InlineDatosProductivos(admin.TabularInline): # model = DatosProductivos # extra = 1 # max_num = 4 # # class InlineDatosProductivosTabla(admin.TabularInline): # model = DatosProductivosTabla # extra = 1 # max_num = 2 class InlineInfraestructura(admin.TabularInline): model = Infraestructura extra = 1 class InlineTransporte(admin.TabularInline): model = Transporte max_num = 1 can_delete = False # class InlineComercializacion(admin.TabularInline): # model = Comercializacion # extra = 1 # max_num = 3 # # class InlineCacaoComercializado(admin.TabularInline): # model = CacaoComercializado # max_num = 1 # can_delete = False class InlineCertificacionOrg(admin.TabularInline): model = CertificacionOrg max_num = 1 can_delete = False class InlineDestinoProdCorriente(admin.TabularInline): model = DestinoProdCorriente extra = 1 max_num = 4 class InlineDestinoProdFermentado(admin.TabularInline): model = DestinoProdFermentado extra = 1 max_num = 4 class InlineFinanciamiento(admin.TabularInline): model = Financiamiento max_num = 1 can_delete = False class InlineFinanciamientoProductores(admin.TabularInline): model = FinanciamientoProductores extra = 1 max_num = 5 class InlineInfoFinanciamiento(admin.TabularInline): model = InfoFinanciamiento extra = 1 max_num = 4 class EncuestaOrganicacionAdmin(admin.ModelAdmin): # def get_queryset(self, request): # if request.user.is_superuser: # return EncuestaOrganicacion.objects.all() # return EncuestaOrganicacion.objects.filter(usuario=request.user) def save_model(self, request, obj, form, change): obj.usuario = request.user obj.save() inlines = [InlineAspectosJuridicos,InlineListaMiembros,InlineDocumentacion, InlineNivelCumplimiento,InlineProduccionComercializacion, InlineInfraestructura,InlineTransporte, InlineCertificacionOrg,InlineDestinoProdCorriente,InlineDestinoProdFermentado, InlineFinanciamiento,InlineFinanciamientoProductores,InlineInfoFinanciamiento] list_display = ('id','organizacion','fecha') list_display_links = ('id','organizacion') class Media: css = { 'all': ('css/admin.css',) } js = ('js/admin_org.js',) admin.site.register(Organizacion,OrganizacionAdmin) admin.site.register(EncuestaOrganicacion,EncuestaOrganicacionAdmin) </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-7,994,590,496,220,483,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">26.648</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">94</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.712095</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.167736</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45140"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">srio/shadow3-scripts</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">transfocator_id30b.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">25823</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">import numpy import xraylib """ transfocator_id30b : transfocator for id13b: It can: 1) guess the lens configuration (number of lenses for each type) for a given photon energy and target image size. Use transfocator_compute_configuration() for this task 2) for a given transfocator configuration, compute the main optical parameters (image size, focal distance, focal position and divergence). Use transfocator_compute_parameters() for this task 3) Performs full ray tracing. Use id30b_ray_tracing() for this task Note that for the optimization and parameters calculations the transfocator configuration is given in keywords. For ray tracing calculations many parameters of the transfocator are hard coded with the values of id30b See main program for examples. Dependencies: Numpy xraylib (to compute refracion indices) Shadow (for ray tracing only) matplotlib (for some plots of ray=tracing) Side effects: When running ray tracing some files are created. MODIFICATION HISTORY: 2015-03-25 <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2b585942446b4e58594d054e5e">[email protected]</a>, written """ __author__ = "Manuel Sanchez del Rio" __contact__ = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7f0c0d16103f1a0c0d19511a0a">[email protected]</a>" __copyright__ = "ESRF, 2015" def transfocator_compute_configuration(photon_energy_ev,s_target,\ symbol=["Be","Be","Be"], density=[1.845,1.845,1.845],\ nlenses_max = [15,3,1], nlenses_radii = [500e-4,1000e-4,1500e-4], lens_diameter=0.05, \ sigmaz=6.46e-4, alpha = 0.55, \ tf_p=5960, tf_q=3800, verbose=1 ): """ Computes the optimum transfocator configuration for a given photon energy and target image size. All length units are cm :param photon_energy_ev: the photon energy in eV :param s_target: the target image size in cm. :param symbol: the chemical symbol of the lens material of each type. Default symbol=["Be","Be","Be"] :param density: the density of each type of lens. Default: density=[1.845,1.845,1.845] :param nlenses_max: the maximum allowed number of lenases for each type of lens. nlenses_max = [15,3,1] :param nlenses_radii: the radii in cm of each type of lens. Default: nlenses_radii = [500e-4,1000e-4,1500e-4] :param lens_diameter: the physical diameter (acceptance) in cm of the lenses. If different for each type of lens, consider the smaller one. Default: lens_diameter=0.05 :param sigmaz: the sigma (standard deviation) of the source in cm :param alpha: an adjustable parameter in [0,1](see doc). Default: 0.55 (it is 0.76 for pure Gaussian beams) :param tf_p: the distance source-transfocator in cm :param tf_q: the distance transfocator-image in cm :param:verbose: set to 1 for verbose text output :return: a list with the number of lenses of each type. """ if s_target < 2.35*sigmaz*tf_q/tf_p: print("Source size FWHM is: %f um"%(1e4*2.35*sigmaz)) print("Maximum Demagnifications is: %f um"%(tf_p/tf_q)) print("Minimum possible size is: %f um"%(1e4*2.35*sigmaz*tf_q/tf_p)) print("Error: redefine size") return None deltas = [(1.0 - xraylib.Refractive_Index_Re(symbol[i],photon_energy_ev*1e-3,density[i])) \ for i in range(len(symbol))] focal_q_target = _tansfocator_guess_focal_position( s_target, p=tf_p, q=tf_q, sigmaz=sigmaz, alpha=alpha, \ lens_diameter=lens_diameter,method=2) focal_f_target = 1.0 / (1.0/focal_q_target + 1.0/tf_p) div_q_target = alpha * lens_diameter / focal_q_target #corrections for extreme cases source_demagnified = 2.35*sigmaz*focal_q_target/tf_p if source_demagnified > lens_diameter: source_demagnified = lens_diameter s_target_calc = numpy.sqrt( (div_q_target*(tf_q-focal_q_target))**2 + source_demagnified**2) nlenses_target = _transfocator_guess_configuration(focal_f_target,deltas=deltas,\ nlenses_max=nlenses_max,radii=nlenses_radii, ) if verbose: print("transfocator_compute_configuration: focal_f_target: %f"%(focal_f_target)) print("transfocator_compute_configuration: focal_q_target: %f cm"%(focal_q_target)) print("transfocator_compute_configuration: s_target: %f um"%(s_target_calc*1e4)) print("transfocator_compute_configuration: nlenses_target: ",nlenses_target) return nlenses_target def transfocator_compute_parameters(photon_energy_ev, nlenses_target,\ symbol=["Be","Be","Be"], density=[1.845,1.845,1.845],\ nlenses_max = [15,3,1], nlenses_radii = [500e-4,1000e-4,1500e-4], lens_diameter=0.05, \ sigmaz=6.46e-4, alpha = 0.55, \ tf_p=5960, tf_q=3800 ): """ Computes the parameters of the optical performances of a given transgocator configuration. returns a l All length units are cm :param photon_energy_ev: :param nlenses_target: a list with the lens configuration, i.e. the number of lenses of each type. :param symbol: the chemical symbol of the lens material of each type. Default symbol=["Be","Be","Be"] :param density: the density of each type of lens. Default: density=[1.845,1.845,1.845] :param nlenses_max: the maximum allowed number of lenases for each type of lens. nlenses_max = [15,3,1] TODO: remove (not used) :param nlenses_radii: the radii in cm of each type of lens. Default: nlenses_radii = [500e-4,1000e-4,1500e-4] :param lens_diameter: the physical diameter (acceptance) in cm of the lenses. If different for each type of lens, consider the smaller one. Default: lens_diameter=0.05 :param sigmaz: the sigma (standard deviation) of the source in cm :param alpha: an adjustable parameter in [0,1](see doc). Default: 0.55 (it is 0.76 for pure Gaussian beams) :param tf_p: the distance source-transfocator in cm :param tf_q: the distance transfocator-image in cm :return: a list with parameters (image_siza, lens_focal_distance, focal_position from transfocator center, divergence of beam after the transfocator) """ deltas = [(1.0 - xraylib.Refractive_Index_Re(symbol[i],photon_energy_ev*1e-3,density[i])) \ for i in range(len(symbol))] focal_f = _transfocator_calculate_focal_distance( deltas=deltas,\ nlenses=nlenses_target,radii=nlenses_radii) focal_q = 1.0 / (1.0/focal_f - 1.0/tf_p) div_q = alpha * lens_diameter / focal_q #corrections source_demagnified = 2.35*sigmaz*focal_q/tf_p if source_demagnified > lens_diameter: source_demagnified = lens_diameter s_target = numpy.sqrt( (div_q*(tf_q-focal_q))**2 + (source_demagnified)**2 ) return (s_target,focal_f,focal_q,div_q) def transfocator_nlenses_to_slots(nlenses,nlenses_max=None): """ converts the transfocator configuration from a list of the number of lenses of each type, into a list of active (1) or inactive (0) actuators for the slots. :param nlenses: the list with number of lenses (e.g., [5,2,0] :param nlenses_max: the maximum number of lenses of each type, usually powers of two minus one. E.g. [15,3,1] :return: a list of on (1) and off (0) slots, e.g., [1, 0, 1, 0, 0, 1, 0] (first type: 1*1+0*2+1*4+0*8=5, second type: 0*1+1*2=2, third type: 0*1=0) """ if nlenses_max == None: nlenses_max = nlenses ss = [] for i,iopt in enumerate(nlenses): if iopt > nlenses_max[i]: print("Error: i:%d, nlenses: %d, nlenses_max: %d"%(i,iopt,nlenses_max[i])) ncharacters = len("{0:b}".format(nlenses_max[i])) si = list( ("{0:0%db}"%(ncharacters)).format(int(iopt)) ) si.reverse() ss += si on_off = [int(i) for i in ss] #print("transfocator_nlenses_to_slots: nlenses_max: ",nlenses_max," nlenses: ",nlenses," slots: ",on_off) return on_off def _transfocator_calculate_focal_distance(deltas=[0.999998],nlenses=[1],radii=[500e-4]): inverse_focal_distance = 0.0 for i,nlensesi in enumerate(nlenses): if nlensesi > 0: focal_distance_i = radii[i] / (2.*nlensesi*deltas[i]) inverse_focal_distance += 1.0/focal_distance_i if inverse_focal_distance == 0: return 99999999999999999999999999. else: return 1.0/inverse_focal_distance def _tansfocator_guess_focal_position( s_target, p=5960., q=3800.0, sigmaz=6.46e-4, \ alpha=0.66, lens_diameter=0.05, method=2): x = 1e15 if method == 1: # simple sum AA = 2.35*sigmaz/p BB = -(s_target + alpha * lens_diameter) CC = alpha*lens_diameter*q cc = numpy.roots([AA,BB,CC]) x = cc[1] return x if method == 2: # sum in quadrature AA = ( (2.35*sigmaz)**2)/(p**2) BB = 0.0 CC = alpha**2 * lens_diameter**2 - s_target**2 DD = - 2.0 * alpha**2 * lens_diameter**2 * q EE = alpha**2 * lens_diameter**2 * q**2 cc = numpy.roots([AA,BB,CC,DD,EE]) for i,cci in enumerate(cc): if numpy.imag(cci) == 0: return numpy.real(cci) return x def _transfocator_guess_configuration(focal_f_target,deltas=[0.999998],nlenses_max=[15],radii=[500e-4]): nn = len(nlenses_max) ncombinations = (1+nlenses_max[0]) * (1+nlenses_max[1]) * (1+nlenses_max[2]) icombinations = 0 aa = numpy.zeros((3,ncombinations),dtype=int) bb = numpy.zeros(ncombinations) for i0 in range(1+nlenses_max[0]): for i1 in range(1+nlenses_max[1]): for i2 in range(1+nlenses_max[2]): aa[0,icombinations] = i0 aa[1,icombinations] = i1 aa[2,icombinations] = i2 bb[icombinations] = focal_f_target - _transfocator_calculate_focal_distance(deltas=deltas,nlenses=[i0,i1,i2],radii=radii) icombinations += 1 bb1 = numpy.abs(bb) ibest = bb1.argmin() return (aa[:,ibest]).tolist() # # # def id30b_ray_tracing(emittH=4e-9,emittV=1e-11,betaH=35.6,betaV=3.0,number_of_rays=50000,\ density=1.845,symbol="Be",tf_p=1000.0,tf_q=1000.0,lens_diameter=0.05,\ slots_max=None,slots_on_off=None,photon_energy_ev=14000.0,\ slots_lens_thickness=None,slots_steps=None,slots_radii=None,\ s_target=10e-4,focal_f=10.0,focal_q=10.0,div_q=1e-6): #======================================================================================================================= # Gaussian undulator source #======================================================================================================================= import Shadow #import Shadow.ShadowPreprocessorsXraylib as sx sigmaXp = numpy.sqrt(emittH/betaH) sigmaZp = numpy.sqrt(emittV/betaV) sigmaX = emittH/sigmaXp sigmaZ = emittV/sigmaZp print("\n\nElectron sizes H:%f um, V:%fu m;\nelectron divergences: H:%f urad, V:%f urad"%\ (sigmaX*1e6, sigmaZ*1e6, sigmaXp*1e6, sigmaZp*1e6)) # set Gaussian source src = Shadow.Source() src.set_energy_monochromatic(photon_energy_ev) src.set_gauss(sigmaX*1e2,sigmaZ*1e2,sigmaXp,sigmaZp) print("\n\nElectron sizes stored H:%f um, V:%f um;\nelectron divergences: H:%f urad, V:%f urad"%\ (src.SIGMAX*1e4,src.SIGMAZ*1e4,src.SIGDIX*1e6,src.SIGDIZ*1e6)) src.apply_gaussian_undulator(undulator_length_in_m=2.8, user_unit_to_m=1e-2, verbose=1) print("\n\nElectron sizes stored (undulator) H:%f um, V:%f um;\nelectron divergences: H:%f urad, V:%f urad"%\ (src.SIGMAX*1e4,src.SIGMAZ*1e4,src.SIGDIX*1e6,src.SIGDIZ*1e6)) print("\n\nSource size in vertical FWHM: %f um\n"%\ (2.35*src.SIGMAZ*1e4)) src.NPOINT = number_of_rays src.ISTAR1 = 0 # 677543155 src.write("start.00") # create source beam = Shadow.Beam() beam.genSource(src) beam.write("begin.dat") src.write("end.00") #======================================================================================================================= # complete the (detailed) transfocator description #======================================================================================================================= print("\nSetting detailed Transfocator for ID30B") slots_nlenses = numpy.array(slots_max)*numpy.array(slots_on_off) slots_empty = (numpy.array(slots_max)-slots_nlenses) # ####interactive=True, SYMBOL="SiC",DENSITY=3.217,FILE="prerefl.dat",E_MIN=100.0,E_MAX=20000.0,E_STEP=100.0 Shadow.ShadowPreprocessorsXraylib.prerefl(interactive=False,E_MIN=2000.0,E_MAX=55000.0,E_STEP=100.0,\ DENSITY=density,SYMBOL=symbol,FILE="Be2_55.dat" ) nslots = len(slots_max) prerefl_file = ["Be2_55.dat" for i in range(nslots)] print("slots_max: ",slots_max) #print("slots_target: ",slots_target) print("slots_on_off: ",slots_on_off) print("slots_steps: ",slots_steps) print("slots_radii: ",slots_radii) print("slots_nlenses: ",slots_nlenses) print("slots_empty: ",slots_empty) #calculate distances, nlenses and slots_empty # these are distances p and q with TF length removed tf_length = numpy.array(slots_steps).sum() #tf length in cm tf_fs_before = tf_p - 0.5*tf_length #distance from source to center of transfocator tf_fs_after = tf_q - 0.5*tf_length # distance from center of transfocator to image # for each slot, these are the empty distances before and after the lenses tf_p0 = numpy.zeros(nslots) tf_q0 = numpy.array(slots_steps) - (numpy.array(slots_max) * slots_lens_thickness) # add now the p q distances tf_p0[0] += tf_fs_before tf_q0[-1] += tf_fs_after print("tf_p0: ",tf_p0) print("tf_q0: ",tf_q0) print("tf_length: %f cm"%(tf_length)) # build transfocator tf = Shadow.CompoundOE(name='TF ID30B') tf.append_transfocator(tf_p0.tolist(), tf_q0.tolist(), \ nlenses=slots_nlenses.tolist(), radius=slots_radii, slots_empty=slots_empty.tolist(),\ thickness=slots_lens_thickness, prerefl_file=prerefl_file,\ surface_shape=4, convex_to_the_beam=0, diameter=lens_diameter,\ cylinder_angle=0.0,interthickness=50e-4,use_ccc=0) itmp = input("SHADOW Source complete. Do you want to run SHADOR trace? [1=Yes,0=No]: ") if str(itmp) != "1": return #trace system tf.dump_systemfile() beam.traceCompoundOE(tf,write_start_files=0,write_end_files=0,write_star_files=0, write_mirr_files=0) #write only last result file beam.write("star_tf.dat") print("\nFile written to disk: star_tf.dat") # # #ideal calculations # print("\n\n\n") print("=============================================== TRANSFOCATOR OUTPUTS ==========================================") print("\nTHEORETICAL results: ") print("REMIND-----With these lenses we obtained (analytically): ") print("REMIND----- focal_f: %f cm"%(focal_f)) print("REMIND----- focal_q: %f cm"%(focal_q)) print("REMIND----- s_target: %f um"%(s_target*1e4)) demagnification_factor = tf_p/focal_q theoretical_focal_size = src.SIGMAZ*2.35/demagnification_factor # analyze shadow results print("\nSHADOW results: ") st1 = beam.get_standard_deviation(3,ref=0) st2 = beam.get_standard_deviation(3,ref=1) print(" stDev*2.35: unweighted: %f um, weighted: %f um "%(st1*2.35*1e4,st2*2.35*1e4)) tk = beam.histo1(3, nbins=75, ref=1, nolost=1, write="HISTO1") print(" Histogram FWHM: %f um "%(1e4*tk["fwhm"])) print(" Transmitted intensity: %f (source was: %d) (transmission is %f %%) "%(beam.intensity(nolost=1), src.NPOINT, beam.intensity(nolost=1)/src.NPOINT*100)) #scan around image xx1 = numpy.linspace(0.0,1.1*tf_fs_after,11) # position from TF exit plane #xx0 = focal_q - tf_length*0.5 xx0 = focal_q - tf_length*0.5 # position of focus from TF exit plane xx2 = numpy.linspace(xx0-100.0,xx0+100,21) # position from TF exit plane xx3 = numpy.array([tf_fs_after]) xx = numpy.concatenate(([-0.5*tf_length],xx1,xx2,[tf_fs_after])) xx.sort() f = open("id30b.spec","w") f.write("#F id30b.spec\n") f.write("\n#S 1 calculations for id30b transfocator\n") f.write("#N 8\n") labels = " %18s %18s %18s %18s %18s %18s %18s %18s"%\ ("pos from source","pos from image","[pos from TF]", "pos from TF center", "pos from focus",\ "fwhm shadow(stdev)","fwhm shadow(histo)","fwhm theoretical") f.write("#L "+labels+"\n") out = numpy.zeros((8,xx.size)) for i,pos in enumerate(xx): beam2 = beam.duplicate() beam2.retrace(-tf_fs_after+pos) fwhm1 = 2.35*1e4*beam2.get_standard_deviation(3,ref=1,nolost=1) tk = beam2.histo1(3, nbins=75, ref=1, nolost=1) fwhm2 = 1e4*tk["fwhm"] #fwhm_th = 1e4*transfocator_calculate_estimated_size(pos,diameter=diameter,focal_distance=focal_q) fwhm_th2 = 1e4*numpy.sqrt( (div_q*(pos+0.5*tf_length-focal_q))**2 + theoretical_focal_size**2 ) #fwhm_th2 = 1e4*( numpy.abs(div_q*(pos-focal_q+0.5*tf_length)) + theoretical_focal_size ) out[0,i] = tf_fs_before+tf_length+pos out[1,i] = -tf_fs_after+pos out[2,i] = pos out[3,i] = pos+0.5*tf_length out[4,i] = pos+0.5*tf_length-focal_q out[5,i] = fwhm1 out[6,i] = fwhm2 out[7,i] = fwhm_th2 f.write(" %18.3f %18.3f %18.3f %18.3f %18.3f %18.3f %18.3f %18.3f \n"%\ (tf_fs_before+tf_length+pos,\ -tf_fs_after+pos,\ pos,\ pos+0.5*tf_length,\ pos+0.5*tf_length-focal_q,\ fwhm1,fwhm2,fwhm_th2)) f.close() print("File with beam evolution written to disk: id30b.spec") # # plots # itmp = input("Do you want to plot the intensity distribution and beam evolution? [1=yes,0=No]") if str(itmp) != "1": return import matplotlib.pylab as plt plt.figure(1) plt.plot(out[1,:],out[5,:],'blue',label="fwhm shadow(stdev)") plt.plot(out[1,:],out[6,:],'green',label="fwhm shadow(histo1)") plt.plot(out[1,:],out[7,:],'red',label="fwhm theoretical") plt.xlabel("Distance from image plane [cm]") plt.ylabel("spot size [um] ") ax = plt.subplot(111) ax.legend(bbox_to_anchor=(1.1, 1.05)) print("Kill graphic to continue.") plt.show() Shadow.ShadowTools.histo1(beam,3,nbins=75,ref=1,nolost=1,calfwhm=1) input("<Enter> to finish.") return None def id30b_full_simulation(photon_energy_ev=14000.0,s_target=20.0e-4,nlenses_target=None): if nlenses_target == None: force_nlenses = 0 else: force_nlenses = 1 # # define lens setup (general) # xrl_symbol = ["Be","Be","Be"] xrl_density = [1.845,1.845,1.845] lens_diameter = 0.05 nlenses_max = [15,3,1] nlenses_radii = [500e-4,1000e-4,1500e-4] sigmaz=6.46e-4 alpha = 0.55 tf_p = 5960 # position of the TF measured from the center of the transfocator tf_q = 9760 - tf_p # position of the image plane measured from the center of the transfocator if s_target < 2.35*sigmaz*tf_q/tf_p: print("Source size FWHM is: %f um"%(1e4*2.35*sigmaz)) print("Maximum Demagnifications is: %f um"%(tf_p/tf_q)) print("Minimum possible size is: %f um"%(1e4*2.35*sigmaz*tf_q/tf_p)) print("Error: redefine size") return print("================================== TRANSFOCATOR INPUTS ") print("Photon energy: %f eV"%(photon_energy_ev)) if force_nlenses: print("Forced_nlenses: ",nlenses_target) else: print("target size: %f cm"%(s_target)) print("materials: ",xrl_symbol) print("densities: ",xrl_density) print("Lens diameter: %f cm"%(lens_diameter)) print("nlenses_max:",nlenses_max,"nlenses_radii: ",nlenses_radii) print("Source size (sigma): %f um, FWHM: %f um"%(1e4*sigmaz,2.35*1e4*sigmaz)) print("Distances: tf_p: %f cm, tf_q: %f cm"%(tf_p,tf_q)) print("alpha: %f"%(alpha)) print("========================================================") if force_nlenses != 1: nlenses_target = transfocator_compute_configuration(photon_energy_ev,s_target,\ symbol=xrl_symbol,density=xrl_density,\ nlenses_max=nlenses_max, nlenses_radii=nlenses_radii, lens_diameter=lens_diameter, \ sigmaz=sigmaz, alpha=alpha, \ tf_p=tf_p,tf_q=tf_q, verbose=1) (s_target,focal_f,focal_q,div_q) = \ transfocator_compute_parameters(photon_energy_ev, nlenses_target,\ symbol=xrl_symbol,density=xrl_density,\ nlenses_max=nlenses_max, nlenses_radii=nlenses_radii, \ lens_diameter=lens_diameter,\ sigmaz=sigmaz, alpha=alpha,\ tf_p=tf_p,tf_q=tf_q) slots_max = [ 1, 2, 4, 8, 1, 2, 1] # slots slots_on_off = transfocator_nlenses_to_slots(nlenses_target,nlenses_max=nlenses_max) print("=============================== TRANSFOCATOR SET") #print("deltas: ",deltas) if force_nlenses != 1: print("nlenses_target (optimized): ",nlenses_target) else: print("nlenses_target (forced): ",nlenses_target) print("With these lenses we obtain: ") print(" focal_f: %f cm"%(focal_f)) print(" focal_q: %f cm"%(focal_q)) print(" s_target: %f um"%(s_target*1e4)) print(" slots_max: ",slots_max) print(" slots_on_off: ",slots_on_off) print("==================================================") # for theoretical calculations use the focal position and distances given by the target nlenses itmp = input("Start SHADOW simulation? [1=yes,0=No]: ") if str(itmp) != "1": return #======================================================================================================================= # Inputs #======================================================================================================================= emittH = 3.9e-9 emittV = 10e-12 betaH = 35.6 betaV = 3.0 number_of_rays = 50000 nslots = len(slots_max) slots_lens_thickness = [0.3 for i in range(nslots)] #total thickness of a single lens in cm # for each slot, positional gap of the first lens in cm slots_steps = [ 4, 4, 1.9, 6.1, 4, 4, slots_lens_thickness[-1]] slots_radii = [.05, .05, .05, .05, 0.1, 0.1, 0.15] # radii of the lenses in cm AAA= 333 id30b_ray_tracing(emittH=emittH,emittV=emittV,betaH=betaH,betaV=betaV,number_of_rays=number_of_rays,\ density=xrl_density[0],symbol=xrl_symbol[0],tf_p=tf_p,tf_q=tf_q,lens_diameter=lens_diameter,\ slots_max=slots_max,slots_on_off=slots_on_off,photon_energy_ev=photon_energy_ev,\ slots_lens_thickness=slots_lens_thickness,slots_steps=slots_steps,slots_radii=slots_radii,\ s_target=s_target,focal_f=focal_f,focal_q=focal_q,div_q=div_q) def main(): # this performs the full simulation: calculates the optimum configuration and do the ray-tracing itmp = input("Enter: \n 0 = optimization calculation only \n 1 = full simulation (ray tracing) \n?> ") photon_energy_kev = float(input("Enter photon energy in keV: ")) s_target_um = float(input("Enter target focal dimension in microns: ")) if str(itmp) == "1": id30b_full_simulation(photon_energy_ev=photon_energy_kev*1e3,s_target=s_target_um*1e-4,nlenses_target=None) #id30b_full_simulation(photon_energy_ev=14000.0,s_target=20.0e-4,nlenses_target=[3,1,1]) else: #this performs the calculation of the optimizad configuration nlenses_optimum = transfocator_compute_configuration(photon_energy_kev*1e3,s_target_um*1e-4,\ symbol=["Be","Be","Be"], density=[1.845,1.845,1.845],\ nlenses_max = [15,3,1], nlenses_radii = [500e-4,1000e-4,1500e-4], lens_diameter=0.05, \ sigmaz=6.46e-4, alpha = 0.55, \ tf_p=5960, tf_q=3800, verbose=0 ) print("Optimum lens configuration is: ",nlenses_optimum) if nlenses_optimum == None: return print("Activate slots: ",transfocator_nlenses_to_slots(nlenses_optimum,nlenses_max=[15,3,1])) # this calculates the parameters (image size, etc) for a given lens configuration (size, f, q_f, div) = transfocator_compute_parameters(photon_energy_kev*1e3, nlenses_optimum,\ symbol=["Be","Be","Be"], density=[1.845,1.845,1.845],\ nlenses_max = [15,3,1], nlenses_radii = [500e-4,1000e-4,1500e-4], lens_diameter=0.05, \ sigmaz=6.46e-4, alpha = 0.55, \ tf_p=5960, tf_q=3800 ) print("For given configuration ",nlenses_optimum," we get: ") print(" size: %f cm, focal length: %f cm, focal distance: %f cm, divergence: %f rad: "%(size, f, q_f, div)) if __name__ == "__main__": main()</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">5,677,322,547,994,774,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">39.224299</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">162</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.584905</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.016001</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">true</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45141"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">jose187/gh_word_count</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gh_word_count/__init__.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">2681</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "> from ommit_words import list_ommited_words from re import sub import operator class _input_list: def __init__(self,list_TITLES): self.list_TITLES = list_TITLES self.list_remove = list_ommited_words() def _word_count(self): # these are all the words that are in the text dict_words = {} # now we go through each of the lines for str_line in self.list_TITLES: str_raw_line1 = sub('[^a-z0-9 ]','',str_line.lower()) list_line_words = str_raw_line1.split() for str_word in list_line_words: # check to see if its in the ommited word list if str_word not in self.list_remove: # create new key if it is not there yet if str_word not in dict_words: dict_words[str_word] = [1] # add if is already there elif str_word in dict_words: dict_words[str_word].append(1) sorted_x = sorted(dict_words.iteritems(), key=operator.itemgetter(1), reverse=True) list_OUTPUT = [] for each_item in sorted_x: int_COUNT = sum(each_item[1]) if int_COUNT > 1: tup_ONE_COUNT = ('%s' % each_item[0], '%d' % int_COUNT) list_OUTPUT.append(tup_ONE_COUNT) return list_OUTPUT # gets the top x according to frequency # returns list def _get_top(self,int_TOP): list_TOP_N = [] for str_WORD in self._word_count()[:int_TOP]: list_TOP_N.append(str_WORD) return list_TOP_N # displays the count on the terminal def _show_count(list_TUPS,entries=0): if entries == 0: int_TOP = len(list_TUPS) else: int_TOP = entries print 'Count\tWord\n' for tup_ITEM in list_TUPS[:int_TOP]: print '%d\t%s' % (int(tup_ITEM[1]),str(tup_ITEM[0])) # saves the count to csv file def _save_counts(list_COUNTS,str_FILE_PATH,entries=0): if entries == 0: int_TOP = len(list_COUNTS) else: int_TOP = entries list_OUTPUT = ['"Count","Word"'] for tup_ITEM in list_COUNTS[:int_TOP]: str_OUTPUT = '%d,"%s"' % (int(tup_ITEM[1]),str(tup_ITEM[0])) list_OUTPUT.append(str_OUTPUT) fw_OUTPUT = open(str_FILE_PATH,'w') fw_OUTPUT.write('\n'.join(list_OUTPUT)) fw_OUTPUT.close() </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">bsd-2-clause</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-7,451,965,439,748,880,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">30.916667</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">69</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.497576</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.723611</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45142"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">CSD-Public/stonix</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">src/tests/rules/unit_tests/zzzTestRuleDisableOpenSafeSafari.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">4752</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">############################################################################### # # # Copyright 2019. Triad National Security, LLC. All rights reserved. # # This program was produced under U.S. Government contract 89233218CNA000001 # # for Los Alamos National Laboratory (LANL), which is operated by Triad # # National Security, LLC for the U.S. Department of Energy/National Nuclear # # Security Administration. # # # # All rights in the program are reserved by Triad National Security, LLC, and # # the U.S. Department of Energy/National Nuclear Security Administration. The # # Government is granted for itself and others acting on its behalf a # # nonexclusive, paid-up, irrevocable worldwide license in this material to # # reproduce, prepare derivative works, distribute copies to the public, # # perform publicly and display publicly, and to permit others to do so. # # # ############################################################################### ''' This is a Unit Test for Rule DisableOpenSafeSafari Created on Jan 22, 2015 @author: dwalker @change: 2015-02-25 - ekkehard - Updated to make unit test work @change: 2016/02/10 roy Added sys.path.append for being able to unit test this file as well as with the test harness. ''' import unittest import sys sys.path.append("../../../..") from src.tests.lib.RuleTestTemplate import RuleTest from src.stonix_resources.CommandHelper import CommandHelper from src.tests.lib.logdispatcher_mock import LogPriority from src.stonix_resources.rules.DisableOpenSafeSafari import DisableOpenSafeSafari class zzzTestRuleDisableOpenSafeSafari(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = DisableOpenSafeSafari(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(self.logdispatch) self.dc = "/usr/bin/defaults" self.path = "com.apple.Safari" self.key = "AutoOpenSafeDownloads" def tearDown(self): pass def runTest(self): self.simpleRuleTest() def setConditionsForRule(self): '''This makes sure the intial report fails by executing the following commands: defaults write com.apple.Safari AutoOpenSafeDownloads -bool yes :param self: essential if you override this definition :returns: boolean - If successful True; If failure False @author: dwalker ''' success = False cmd = [self.dc, "write", self.path, self.key, "-bool", "yes"] self.logdispatch.log(LogPriority.DEBUG, str(cmd)) if self.ch.executeCommand(cmd): success = self.checkReportForRule(False, True) return success def checkReportForRule(self, pCompliance, pRuleSuccess): '''To see what happended run these commands: defaults read com.apple.Safari AutoOpenSafeDownloads :param self: essential if you override this definition :param pCompliance: :param pRuleSuccess: :returns: boolean - If successful True; If failure False @author: ekkehard j. koch ''' success = True self.logdispatch.log(LogPriority.DEBUG, "pCompliance = " + \ str(pCompliance) + ".") self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + ".") cmd = [self.dc, "read", self.path, self.key] self.logdispatch.log(LogPriority.DEBUG, str(cmd)) if self.ch.executeCommand(cmd): output = self.ch.getOutputString() return success def checkFixForRule(self, pRuleSuccess): self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + ".") success = self.checkReportForRule(True, pRuleSuccess) return success def checkUndoForRule(self, pRuleSuccess): self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + ".") success = self.checkReportForRule(False, pRuleSuccess) return success if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testName'] unittest.main() </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">6,575,902,741,037,396,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">42.2</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">82</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.580177</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">4.277228</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">true</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45143"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">HomeRad/TorCleaner</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">wc/filter/rules/FolderRule.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">3945</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "># -*- coding: iso-8859-1 -*- # Copyright (C) 2000-2009 Bastian Kleineidam """ Group filter rules into folders. """ from ... import fileutil, configuration from . import Rule def recalc_up_down(rules): """ Add .up and .down attributes to rules, used for display up/down arrows in GUIs """ upper = len(rules)-1 for i, rule in enumerate(rules): rule.up = (i>0) rule.down = (i<upper) class FolderRule(Rule.Rule): """ Container for a list of rules. """ def __init__(self, sid=None, titles=None, descriptions=None, disable=0, filename=""): """ Initialize rule data. """ super(FolderRule, self).__init__(sid=sid, titles=titles, descriptions=descriptions, disable=disable) # make filename read-only self._filename = filename self.rules = [] self.attrnames.extend(('oid', 'configversion')) self.intattrs.append('oid') self.oid = None self.configversion = "-" def __str__(self): """ Return rule data as string. """ return super(FolderRule, self).__str__() + \ ("\nrules: %d" % len(self.rules)) def filename_get(self): """ Get filename where this folder is stored. """ return self._filename filename = property(filename_get) def append_rule(self, r): """ Append rule to folder. """ r.oid = len(self.rules) # note: the rules are added in order self.rules.append(r) r.parent = self def delete_rule(self, i): """ Delete rule from folder with index i. """ del self.rules[i] recalc_up_down(self.rules) def update(self, rule, dryrun=False, log=None): """ Update this folder with given folder rule data. """ chg = super(FolderRule, self).update(rule, dryrun=dryrun, log=log) for child in rule.rules: if child.sid is None or not child.sid.startswith("wc"): # ignore local rules continue oldrule = self.get_rule(child.sid) if oldrule is not None: if oldrule.update(child, dryrun=dryrun, log=log): chg = True else: print >> log, _("inserting new rule %s") % \ child.tiptext() if not dryrun: self.rules.append(child) chg = True if chg: recalc_up_down(self.rules) return chg def get_rule(self, sid): """ Return rule with given sid or None if not found. """ for rule in self.rules: if rule.sid == sid: return rule return None def toxml(self): """ Rule data as XML for storing. """ s = u"""<?xml version="1.0" encoding="%s"?> <!DOCTYPE folder SYSTEM "filter.dtd"> %s oid="%d" configversion="%s">""" % \ (configuration.ConfigCharset, super(FolderRule, self).toxml(), self.oid, self.configversion) s += u"\n"+self.title_desc_toxml()+u"\n" for r in self.rules: s += u"\n%s\n" % r.toxml() return s+u"</folder>\n" def write(self, fd=None): """ Write xml data into filename. @raise: OSError if file could not be written. """ s = self.toxml().encode("iso-8859-1", "replace") if fd is None: fileutil.write_file(self.filename, s) else: fd.write(s) def tiptext(self): """ Return short info for gui display. """ l = len(self.rules) if l == 1: text = _("with 1 rule") else: text = _("with %d rules") % l return "%s %s" % (super(FolderRule, self).tiptext(), text) </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">716,819,241,840,942,200</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">27.79562</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">78</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.509759</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.937126</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">true</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45144"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">RAJSD2610/SDNopenflowSwitchAnalysis</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">TotalFlowPlot.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">2742</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">import os import pandas as pd import matplotlib.pyplot as plt import seaborn seaborn.set() path= os.path.expanduser("~/Desktop/ece671/udpt8") num_files = len([f for f in os.listdir(path)if os.path.isfile(os.path.join(path, f))]) print(num_files) u8=[] i=0 def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 while i<(num_files/2) : # df+=[] j=i+1 path ="/home/vetri/Desktop/ece671/udpt8/ftotal."+str(j)+".csv" y = file_len(path) # except: pass #df.append(pd.read_csv(path,header=None)) # a+=[] #y=len(df[i].index)-1 #1 row added by default so that table has a entry if y<0: y=0 u8.append(y) i+=1 print(u8) path= os.path.expanduser("~/Desktop/ece671/udpnone") num_files = len([f for f in os.listdir(path)if os.path.isfile(os.path.join(path, f))]) print(num_files) i=0 j=0 u=[] while i<(num_files/2): j=i+1 path ="/home/vetri/Desktop/ece671/udpnone/ftotal."+str(j)+".csv" y = file_len(path) # except: pass #df.append(pd.read_csv(path,header=None)) # a+=[] #y=len(df[i].index)-1 #1 row added by default so that table has a entry if y<0: y=0 u.append(y) i+=1 print(u) path= os.path.expanduser("~/Desktop/ece671/tcpnone") num_files = len([f for f in os.listdir(path)if os.path.isfile(os.path.join(path, f))]) print(num_files) i=0 j=0 t=[] while i<(num_files/2): j=i+1 path ="/home/vetri/Desktop/ece671/tcpnone/ftotal."+str(j)+".csv" y = file_len(path) # except: pass #df.append(pd.read_csv(path,header=None)) # a+=[] #y=len(df[i].index)-1 #1 row added by default so that table has a entry if y<0: y=0 t.append(y) i+=1 print(t) path= os.path.expanduser("~/Desktop/ece671/tcpt8") num_files = len([f for f in os.listdir(path)if os.path.isfile(os.path.join(path, f))]) print(num_files) i=0 j=0 t8=[] while i<(num_files/2): j=i+1 path ="/home/vetri/Desktop/ece671/tcpt8/ftotal."+str(j)+".csv" y = file_len(path) # except: pass #df.append(pd.read_csv(path,header=None)) # a+=[] #y=len(df[i].index)-1 #1 row added by default so that table has a entry if y<0: y=0 t8.append(y) i+=1 print(t8) #plt.figure(figsize=(4, 5)) plt.plot(list(range(1,len(u8)+1)),u8, '.-',label="udpt8") plt.plot(list(range(1,len(u)+1)),u, '.-',label="udpnone") plt.plot(list(range(1,len(t)+1)),t, '.-',label="tcpnone") plt.plot(list(range(1,len(t8)+1)),t8, '.-',label="tcpt8") plt.title("Total Flows Present after 1st flow") plt.xlabel("time(s)") plt.ylabel("flows") #plt.frameon=True plt.legend() plt.show() </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-3.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3,297,434,910,053,564,400</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">24.388889</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">86</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.591174</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">2.515596</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45145"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">cschenck/blender_sim</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">fluid_sim_deps/blender-2.69/2.69/scripts/addons/io_scene_3ds/__init__.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">6950</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "># ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # <pep8-80 compliant> bl_info = { "name": "Autodesk 3DS format", "author": "Bob Holcomb, Campbell Barton", "blender": (2, 57, 0), "location": "File > Import-Export", "description": "Import-Export 3DS, meshes, uvs, materials, textures, " "cameras & lamps", "warning": "", "wiki_url": "http://wiki.blender.org/index.php/Extensions:2.6/Py/" "Scripts/Import-Export/Autodesk_3DS", "tracker_url": "", "support": 'OFFICIAL', "category": "Import-Export"} if "bpy" in locals(): import imp if "import_3ds" in locals(): imp.reload(import_3ds) if "export_3ds" in locals(): imp.reload(export_3ds) import bpy from bpy.props import StringProperty, FloatProperty, BoolProperty, EnumProperty from bpy_extras.io_utils import (ImportHelper, ExportHelper, axis_conversion, ) class Import3DS(bpy.types.Operator, ImportHelper): """Import from 3DS file format (.3ds)""" bl_idname = "import_scene.autodesk_3ds" bl_label = 'Import 3DS' bl_options = {'UNDO'} filename_ext = ".3ds" filter_glob = StringProperty(default="*.3ds", options={'HIDDEN'}) constrain_size = FloatProperty( name="Size Constraint", description="Scale the model by 10 until it reaches the " "size constraint (0 to disable)", min=0.0, max=1000.0, soft_min=0.0, soft_max=1000.0, default=10.0, ) use_image_search = BoolProperty( name="Image Search", description="Search subdirectories for any associated images " "(Warning, may be slow)", default=True, ) use_apply_transform = BoolProperty( name="Apply Transform", description="Workaround for object transformations " "importing incorrectly", default=True, ) axis_forward = EnumProperty( name="Forward", items=(('X', "X Forward", ""), ('Y', "Y Forward", ""), ('Z', "Z Forward", ""), ('-X', "-X Forward", ""), ('-Y', "-Y Forward", ""), ('-Z', "-Z Forward", ""), ), default='Y', ) axis_up = EnumProperty( name="Up", items=(('X', "X Up", ""), ('Y', "Y Up", ""), ('Z', "Z Up", ""), ('-X', "-X Up", ""), ('-Y', "-Y Up", ""), ('-Z', "-Z Up", ""), ), default='Z', ) def execute(self, context): from . import import_3ds keywords = self.as_keywords(ignore=("axis_forward", "axis_up", "filter_glob", )) global_matrix = axis_conversion(from_forward=self.axis_forward, from_up=self.axis_up, ).to_4x4() keywords["global_matrix"] = global_matrix return import_3ds.load(self, context, **keywords) class Export3DS(bpy.types.Operator, ExportHelper): """Export to 3DS file format (.3ds)""" bl_idname = "export_scene.autodesk_3ds" bl_label = 'Export 3DS' filename_ext = ".3ds" filter_glob = StringProperty( default="*.3ds", options={'HIDDEN'}, ) use_selection = BoolProperty( name="Selection Only", description="Export selected objects only", default=False, ) axis_forward = EnumProperty( name="Forward", items=(('X', "X Forward", ""), ('Y', "Y Forward", ""), ('Z', "Z Forward", ""), ('-X', "-X Forward", ""), ('-Y', "-Y Forward", ""), ('-Z', "-Z Forward", ""), ), default='Y', ) axis_up = EnumProperty( name="Up", items=(('X', "X Up", ""), ('Y', "Y Up", ""), ('Z', "Z Up", ""), ('-X', "-X Up", ""), ('-Y', "-Y Up", ""), ('-Z', "-Z Up", ""), ), default='Z', ) def execute(self, context): from . import export_3ds keywords = self.as_keywords(ignore=("axis_forward", "axis_up", "filter_glob", "check_existing", )) global_matrix = axis_conversion(to_forward=self.axis_forward, to_up=self.axis_up, ).to_4x4() keywords["global_matrix"] = global_matrix return export_3ds.save(self, context, **keywords) # Add to a menu def menu_func_export(self, context): self.layout.operator(Export3DS.bl_idname, text="3D Studio (.3ds)") def menu_func_import(self, context): self.layout.operator(Import3DS.bl_idname, text="3D Studio (.3ds)") def register(): bpy.utils.register_module(__name__) bpy.types.INFO_MT_file_import.append(menu_func_import) bpy.types.INFO_MT_file_export.append(menu_func_export) def unregister(): bpy.utils.unregister_module(__name__) bpy.types.INFO_MT_file_import.remove(menu_func_import) bpy.types.INFO_MT_file_export.remove(menu_func_export) # NOTES: # why add 1 extra vertex? and remove it when done? - # "Answer - eekadoodle - would need to re-order UV's without this since face # order isnt always what we give blender, BMesh will solve :D" # # disabled scaling to size, this requires exposing bb (easy) and understanding # how it works (needs some time) if __name__ == "__main__": register() </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-3.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-6,396,439,276,597,938,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">32.095238</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">79</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.496259</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">4.131986</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45146"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">HyperloopTeam/FullOpenMDAO</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">cantera-2.0.2/interfaces/python/MixMaster/Units/unit.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">2833</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">import operator class unit: _zero = (0,) * 7 _negativeOne = (-1, ) * 7 _labels = ('m', 'kg', 's', 'A', 'K', 'mol', 'cd') def __init__(self, value, derivation): self.value = value self.derivation = derivation return def __add__(self, other): if not self.derivation == other.derivation: raise ImcompatibleUnits(self, other) return unit(self.value + other.value, self.derivation) def __sub__(self, other): if not self.derivation == other.derivation: raise ImcompatibleUnits(self, other) return unit(self.value - other.value, self.derivation) def __mul__(self, other): if type(other) == type(0) or type(other) == type(0.0): return unit(other*self.value, self.derivation) value = self.value * other.value derivation = tuple(map(operator.add, self.derivation, other.derivation)) return unit(value, derivation) def __div__(self, other): if type(other) == type(0) or type(other) == type(0.0): return unit(self.value/other, self.derivation) value = self.value / other.value derivation = tuple(map(operator.sub, self.derivation, other.derivation)) return unit(value, derivation) def __pow__(self, other): if type(other) != type(0) and type(other) != type(0.0): raise BadOperation value = self.value ** other derivation = tuple(map(operator.mul, [other]*7, self.derivation)) return unit(value, derivation) def __pos__(self): return self def __neg__(self): return unit(-self.value, self.derivation) def __abs__(self): return unit(abs(self.value), self.derivation) def __invert__(self): value = 1./self.value derivation = tuple(map(operator.mul, self._negativeOne, self.derivation)) return unit(value, derivation) def __rmul__(self, other): return unit.__mul__(self, other) def __rdiv__(self, other): if type(other) != type(0) and type(other) != type(0.0): raise BadOperation(self, other) value = other/self.value derivation = tuple(map(operator.mul, self._negativeOne, self.derivation)) return unit(value, derivation) def __float__(self): return self.value #if self.derivation == self._zero: return self.value #raise BadConversion(self) def __str__(self): str = "%g" % self.value for i in range(0, 7): exponent = self.derivation[i] if exponent == 0: continue if exponent == 1: str = str + " %s" % (self._labels[i]) else: str = str + " %s^%d" % (self._labels[i], exponent) return str dimensionless = unit(1, unit._zero) </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3,539,097,702,608,451,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">25.476636</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">81</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.570773</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.674449</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45147"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">lmazuel/azure-sdk-for-python</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">azure-mgmt-compute/azure/mgmt/compute/v2016_03_30/models/windows_configuration_py3.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">2719</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "># coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class WindowsConfiguration(Model): """Specifies Windows operating system settings on the virtual machine. :param provision_vm_agent: Indicates whether virtual machine agent should be provisioned on the virtual machine. <br><br> When this property is not specified in the request body, default behavior is to set it to true. This will ensure that VM Agent is installed on the VM so that extensions can be added to the VM later. :type provision_vm_agent: bool :param enable_automatic_updates: Indicates whether virtual machine is enabled for automatic updates. :type enable_automatic_updates: bool :param time_zone: Specifies the time zone of the virtual machine. e.g. "Pacific Standard Time" :type time_zone: str :param additional_unattend_content: Specifies additional base-64 encoded XML formatted information that can be included in the Unattend.xml file, which is used by Windows Setup. :type additional_unattend_content: list[~azure.mgmt.compute.v2016_03_30.models.AdditionalUnattendContent] :param win_rm: Specifies the Windows Remote Management listeners. This enables remote Windows PowerShell. :type win_rm: ~azure.mgmt.compute.v2016_03_30.models.WinRMConfiguration """ _attribute_map = { 'provision_vm_agent': {'key': 'provisionVMAgent', 'type': 'bool'}, 'enable_automatic_updates': {'key': 'enableAutomaticUpdates', 'type': 'bool'}, 'time_zone': {'key': 'timeZone', 'type': 'str'}, 'additional_unattend_content': {'key': 'additionalUnattendContent', 'type': '[AdditionalUnattendContent]'}, 'win_rm': {'key': 'winRM', 'type': 'WinRMConfiguration'}, } def __init__(self, *, provision_vm_agent: bool=None, enable_automatic_updates: bool=None, time_zone: str=None, additional_unattend_content=None, win_rm=None, **kwargs) -> None: super(WindowsConfiguration, self).__init__(**kwargs) self.provision_vm_agent = provision_vm_agent self.enable_automatic_updates = enable_automatic_updates self.time_zone = time_zone self.additional_unattend_content = additional_unattend_content self.win_rm = win_rm </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">7,741,615,214,177,697,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">49.351852</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">180</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.670835</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">4.189522</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45148"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">matiboy/django_safari_notifications</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">django_safari_notifications/apps.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1111</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "># -*- coding: utf-8 from django.apps import AppConfig import logging class DjangoSafariNotificationsConfig(AppConfig): name = 'django_safari_notifications' verbose_name = 'Safari Push Notifications' version = 'v1' service_base = 'push' userinfo_key = 'userinfo' logger = logging.getLogger('django_safari_notifications') # Provide path to a pem file containing the certificate, the key as well as Apple's WWDRCA cert = 'path/to/your/cert' passphrase = 'pass:xxxx' # this will be used with -passin in the openssl command so could be with pass, env etc # If single site, just set these values. Otherwise create Domain entries website_conf = None # sample single site: do not include the authenticationToken """ website_conf = { "websiteName": "Bay Airlines", "websitePushID": "web.com.example.domain", "allowedDomains": ["http://domain.example.com"], "urlFormatString": "http://domain.example.com/%@/?flight=%@", "webServiceURL": "https://example.com/push" } """ iconset_folder = '/path/to/your/iconset' </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-6,515,032,378,796,969,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">38.678571</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">115</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.673267</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.715719</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45149"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">TomSkelly/MatchAnnot</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">showAnnot.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">2299</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">#!/usr/bin/env python # Read annotation file, print selected stuff in human-readable format. # AUTHOR: Tom Skelly (<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="37435f585a564419445c525b5b4e7751595b544519595e5f19505841">[email protected]</a>) import os import sys import optparse import re # regular expressions import cPickle as pickle from tt_log import logger import Annotations as anno VERSION = '20150417.01' def main (): logger.debug('version %s starting' % VERSION) opt, args = getParms() if opt.gtfpickle is not None: handle = open (opt.gtfpickle, 'r') pk = pickle.Unpickler (handle) annotList = pk.load() handle.close() else: annotList = anno.AnnotationList (opt.gtf) geneList = annotList.getGene (opt.gene) if geneList is None: print 'gene %s not found in annotations' % opt.gene elif len(geneList) != 1: print 'there are %d occurrences of gene %s in annotations' % (len(geneList), opt.gene) else: geneEnt = geneList[0] print 'gene: ', printEnt (geneEnt) for transEnt in geneEnt.getChildren(): print '\ntr: ', printTran (transEnt) for exonEnt in transEnt.getChildren(): print 'exon: ', printEnt (exonEnt) logger.debug('finished') return def printEnt (ent): print '%-15s %9d %9d %6d' % (ent.name, ent.start, ent.end, ent.end-ent.start+1) return def printTran (ent): print '%-15s %9d %9d %6d' % (ent.name, ent.start, ent.end, ent.end-ent.start+1), if hasattr (ent, 'startcodon'): print ' start: %9d' % ent.startcodon, if hasattr (ent, 'stopcodon'): print ' stop: %9d' % ent.stopcodon, print return def getParms (): # use default input sys.argv[1:] parser = optparse.OptionParser(usage='%prog [options] <fasta_file> ... ') parser.add_option ('--gtf', help='annotations in gtf format') parser.add_option ('--gtfpickle', help='annotations in pickled gtf format') parser.add_option ('--gene', help='gene to print') parser.set_defaults (gtf=None, gtfpickle=None, gene=None, ) opt, args = parser.parse_args() return opt, args if __name__ == "__main__": main() </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-3.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-1,754,153,406,302,757,400</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">24.263736</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">94</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.579382</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.467572</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45150"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Midrya/chromium</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">rietveld.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">26054</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "># coding: utf-8 # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Defines class Rietveld to easily access a rietveld instance. Security implications: The following hypothesis are made: - Rietveld enforces: - Nobody else than issue owner can upload a patch set - Verifies the issue owner credentials when creating new issues - A issue owner can't change once the issue is created - A patch set cannot be modified """ import copy import errno import json import logging import re import socket import ssl import sys import time import urllib import urllib2 import urlparse import patch from third_party import upload import third_party.oauth2client.client as oa2client from third_party import httplib2 # Appengine replies with 302 when authentication fails (sigh.) oa2client.REFRESH_STATUS_CODES.append(302) upload.LOGGER.setLevel(logging.WARNING) # pylint: disable=E1103 class Rietveld(object): """Accesses rietveld.""" def __init__( self, url, auth_config, email=None, extra_headers=None, maxtries=None): self.url = url.rstrip('/') self.rpc_server = upload.GetRpcServer(self.url, auth_config, email) self._xsrf_token = None self._xsrf_token_time = None self._maxtries = maxtries or 40 def xsrf_token(self): if (not self._xsrf_token_time or (time.time() - self._xsrf_token_time) > 30*60): self._xsrf_token_time = time.time() self._xsrf_token = self.get( '/xsrf_token', extra_headers={'X-Requesting-XSRF-Token': '1'}) return self._xsrf_token def get_pending_issues(self): """Returns an array of dict of all the pending issues on the server.""" # TODO: Convert this to use Rietveld::search(), defined below. return json.loads( self.get('/search?format=json&commit=2&closed=3&' 'keys_only=True&limit=1000&order=__key__'))['results'] def close_issue(self, issue): """Closes the Rietveld issue for this changelist.""" logging.info('closing issue %d' % issue) self.post("/%d/close" % issue, [('xsrf_token', self.xsrf_token())]) def get_description(self, issue): """Returns the issue's description. Converts any CRLF into LF and strip extraneous whitespace. """ return '\n'.join(self.get('/%d/description' % issue).strip().splitlines()) def get_issue_properties(self, issue, messages): """Returns all the issue's metadata as a dictionary.""" url = '/api/%d' % issue if messages: url += '?messages=true' data = json.loads(self.get(url, retry_on_404=True)) data['description'] = '\n'.join(data['description'].strip().splitlines()) return data def get_depends_on_patchset(self, issue, patchset): """Returns the patchset this patchset depends on if it exists.""" url = '/%d/patchset/%d/get_depends_on_patchset' % (issue, patchset) resp = None try: resp = json.loads(self.post(url, [])) except (urllib2.HTTPError, ValueError): # The get_depends_on_patchset endpoint does not exist on this Rietveld # instance yet. Ignore the error and proceed. # TODO(rmistry): Make this an error when all Rietveld instances have # this endpoint. pass return resp def get_patchset_properties(self, issue, patchset): """Returns the patchset properties.""" url = '/api/%d/%d' % (issue, patchset) return json.loads(self.get(url)) def get_file_content(self, issue, patchset, item): """Returns the content of a new file. Throws HTTP 302 exception if the file doesn't exist or is not a binary file. """ # content = 0 is the old file, 1 is the new file. content = 1 url = '/%d/binary/%d/%d/%d' % (issue, patchset, item, content) return self.get(url) def get_file_diff(self, issue, patchset, item): """Returns the diff of the file. Returns a useless diff for binary files. """ url = '/download/issue%d_%d_%d.diff' % (issue, patchset, item) return self.get(url) def get_patch(self, issue, patchset): """Returns a PatchSet object containing the details to apply this patch.""" props = self.get_patchset_properties(issue, patchset) or {} out = [] for filename, state in props.get('files', {}).iteritems(): logging.debug('%s' % filename) # If not status, just assume it's a 'M'. Rietveld often gets it wrong and # just has status: null. Oh well. status = state.get('status') or 'M' if status[0] not in ('A', 'D', 'M', 'R'): raise patch.UnsupportedPatchFormat( filename, 'Change with status \'%s\' is not supported.' % status) svn_props = self.parse_svn_properties( state.get('property_changes', ''), filename) if state.get('is_binary'): if status[0] == 'D': if status[0] != status.strip(): raise patch.UnsupportedPatchFormat( filename, 'Deleted file shouldn\'t have property change.') out.append(patch.FilePatchDelete(filename, state['is_binary'])) else: content = self.get_file_content(issue, patchset, state['id']) if not content: # As a precaution due to a bug in upload.py for git checkout, refuse # empty files. If it's empty, it's not a binary file. raise patch.UnsupportedPatchFormat( filename, 'Binary file is empty. Maybe the file wasn\'t uploaded in the ' 'first place?') out.append(patch.FilePatchBinary( filename, content, svn_props, is_new=(status[0] == 'A'))) continue try: diff = self.get_file_diff(issue, patchset, state['id']) except urllib2.HTTPError, e: if e.code == 404: raise patch.UnsupportedPatchFormat( filename, 'File doesn\'t have a diff.') raise # FilePatchDiff() will detect file deletion automatically. p = patch.FilePatchDiff(filename, diff, svn_props) out.append(p) if status[0] == 'A': # It won't be set for empty file. p.is_new = True if (len(status) > 1 and status[1] == '+' and not (p.source_filename or p.svn_properties)): raise patch.UnsupportedPatchFormat( filename, 'Failed to process the svn properties') return patch.PatchSet(out) @staticmethod def parse_svn_properties(rietveld_svn_props, filename): """Returns a list of tuple [('property', 'newvalue')]. rietveld_svn_props is the exact format from 'svn diff'. """ rietveld_svn_props = rietveld_svn_props.splitlines() svn_props = [] if not rietveld_svn_props: return svn_props # 1. Ignore svn:mergeinfo. # 2. Accept svn:eol-style and svn:executable. # 3. Refuse any other. # \n # Added: svn:ignore\n # + LF\n spacer = rietveld_svn_props.pop(0) if spacer or not rietveld_svn_props: # svn diff always put a spacer between the unified diff and property # diff raise patch.UnsupportedPatchFormat( filename, 'Failed to parse svn properties.') while rietveld_svn_props: # Something like 'Added: svn:eol-style'. Note the action is localized. # *sigh*. action = rietveld_svn_props.pop(0) match = re.match(r'^(\w+): (.+)$', action) if not match or not rietveld_svn_props: raise patch.UnsupportedPatchFormat( filename, 'Failed to parse svn properties: %s, %s' % (action, svn_props)) if match.group(2) == 'svn:mergeinfo': # Silently ignore the content. rietveld_svn_props.pop(0) continue if match.group(1) not in ('Added', 'Modified'): # Will fail for our French friends. raise patch.UnsupportedPatchFormat( filename, 'Unsupported svn property operation.') if match.group(2) in ('svn:eol-style', 'svn:executable', 'svn:mime-type'): # ' + foo' where foo is the new value. That's fragile. content = rietveld_svn_props.pop(0) match2 = re.match(r'^ \+ (.*)$', content) if not match2: raise patch.UnsupportedPatchFormat( filename, 'Unsupported svn property format.') svn_props.append((match.group(2), match2.group(1))) return svn_props def update_description(self, issue, description): """Sets the description for an issue on Rietveld.""" logging.info('new description for issue %d' % issue) self.post('/%d/description' % issue, [ ('description', description), ('xsrf_token', self.xsrf_token())]) def add_comment(self, issue, message, add_as_reviewer=False): max_message = 10000 tail = '…\n(message too large)' if len(message) > max_message: message = message[:max_message-len(tail)] + tail logging.info('issue %d; comment: %s' % (issue, message.strip()[:300])) return self.post('/%d/publish' % issue, [ ('xsrf_token', self.xsrf_token()), ('message', message), ('message_only', 'True'), ('add_as_reviewer', str(bool(add_as_reviewer))), ('send_mail', 'True'), ('no_redirect', 'True')]) def add_inline_comment( self, issue, text, side, snapshot, patchset, patchid, lineno): logging.info('add inline comment for issue %d' % issue) return self.post('/inline_draft', [ ('issue', str(issue)), ('text', text), ('side', side), ('snapshot', snapshot), ('patchset', str(patchset)), ('patch', str(patchid)), ('lineno', str(lineno))]) def set_flag(self, issue, patchset, flag, value): return self.post('/%d/edit_flags' % issue, [ ('last_patchset', str(patchset)), ('xsrf_token', self.xsrf_token()), (flag, str(value))]) def search( self, owner=None, reviewer=None, base=None, closed=None, private=None, commit=None, created_before=None, created_after=None, modified_before=None, modified_after=None, per_request=None, keys_only=False, with_messages=False): """Yields search results.""" # These are expected to be strings. string_keys = { 'owner': owner, 'reviewer': reviewer, 'base': base, 'created_before': created_before, 'created_after': created_after, 'modified_before': modified_before, 'modified_after': modified_after, } # These are either None, False or True. three_state_keys = { 'closed': closed, 'private': private, 'commit': commit, } url = '/search?format=json' # Sort the keys mainly to ease testing. for key in sorted(string_keys): value = string_keys[key] if value: url += '&%s=%s' % (key, urllib2.quote(value)) for key in sorted(three_state_keys): value = three_state_keys[key] if value is not None: url += '&%s=%d' % (key, int(value) + 1) if keys_only: url += '&keys_only=True' if with_messages: url += '&with_messages=True' if per_request: url += '&limit=%d' % per_request cursor = '' while True: output = self.get(url + cursor) if output.startswith('<'): # It's an error message. Return as no result. break data = json.loads(output) or {} if not data.get('results'): break for i in data['results']: yield i cursor = '&cursor=%s' % data['cursor'] def trigger_try_jobs( self, issue, patchset, reason, clobber, revision, builders_and_tests, master=None, category='cq'): """Requests new try jobs. |builders_and_tests| is a map of builders: [tests] to run. |master| is the name of the try master the builders belong to. |category| is used to distinguish regular jobs and experimental jobs. Returns the keys of the new TryJobResult entites. """ params = [ ('reason', reason), ('clobber', 'True' if clobber else 'False'), ('builders', json.dumps(builders_and_tests)), ('xsrf_token', self.xsrf_token()), ('category', category), ] if revision: params.append(('revision', revision)) if master: # Temporarily allow empty master names for old configurations. The try # job will not be associated with a master name on rietveld. This is # going to be deprecated. params.append(('master', master)) return self.post('/%d/try/%d' % (issue, patchset), params) def trigger_distributed_try_jobs( self, issue, patchset, reason, clobber, revision, masters, category='cq'): """Requests new try jobs. |masters| is a map of masters: map of builders: [tests] to run. |category| is used to distinguish regular jobs and experimental jobs. """ for (master, builders_and_tests) in masters.iteritems(): self.trigger_try_jobs( issue, patchset, reason, clobber, revision, builders_and_tests, master, category) def get_pending_try_jobs(self, cursor=None, limit=100): """Retrieves the try job requests in pending state. Returns a tuple of the list of try jobs and the cursor for the next request. """ url = '/get_pending_try_patchsets?limit=%d' % limit extra = ('&cursor=' + cursor) if cursor else '' data = json.loads(self.get(url + extra)) return data['jobs'], data['cursor'] def get(self, request_path, **kwargs): kwargs.setdefault('payload', None) return self._send(request_path, **kwargs) def post(self, request_path, data, **kwargs): ctype, body = upload.EncodeMultipartFormData(data, []) return self._send(request_path, payload=body, content_type=ctype, **kwargs) def _send(self, request_path, retry_on_404=False, **kwargs): """Sends a POST/GET to Rietveld. Returns the response body.""" # rpc_server.Send() assumes timeout=None by default; make sure it's set # to something reasonable. kwargs.setdefault('timeout', 15) logging.debug('POSTing to %s, args %s.', request_path, kwargs) try: # Sadly, upload.py calls ErrorExit() which does a sys.exit(1) on HTTP # 500 in AbstractRpcServer.Send(). old_error_exit = upload.ErrorExit def trap_http_500(msg): """Converts an incorrect ErrorExit() call into a HTTPError exception.""" m = re.search(r'(50\d) Server Error', msg) if m: # Fake an HTTPError exception. Cheezy. :( raise urllib2.HTTPError( request_path, int(m.group(1)), msg, None, None) old_error_exit(msg) upload.ErrorExit = trap_http_500 for retry in xrange(self._maxtries): try: logging.debug('%s' % request_path) result = self.rpc_server.Send(request_path, **kwargs) # Sometimes GAE returns a HTTP 200 but with HTTP 500 as the content. # How nice. return result except urllib2.HTTPError, e: if retry >= (self._maxtries - 1): raise flake_codes = [500, 502, 503] if retry_on_404: flake_codes.append(404) if e.code not in flake_codes: raise except urllib2.URLError, e: if retry >= (self._maxtries - 1): raise if (not 'Name or service not known' in e.reason and not 'EOF occurred in violation of protocol' in e.reason and # On windows we hit weird bug http://crbug.com/537417 # with message '[Errno 10060] A connection attempt failed...' not (sys.platform.startswith('win') and isinstance(e.reason, socket.error) and e.reason.errno == errno.ETIMEDOUT ) ): # Usually internal GAE flakiness. raise except ssl.SSLError, e: if retry >= (self._maxtries - 1): raise if not 'timed out' in str(e): raise # If reaching this line, loop again. Uses a small backoff. time.sleep(min(10, 1+retry*2)) except urllib2.HTTPError as e: print 'Request to %s failed: %s' % (e.geturl(), e.read()) raise finally: upload.ErrorExit = old_error_exit # DEPRECATED. Send = get class OAuthRpcServer(object): def __init__(self, host, client_email, client_private_key, private_key_password='notasecret', user_agent=None, timeout=None, extra_headers=None): """Wrapper around httplib2.Http() that handles authentication. client_email: email associated with the service account client_private_key: encrypted private key, as a string private_key_password: password used to decrypt the private key """ # Enforce https host_parts = urlparse.urlparse(host) if host_parts.scheme == 'https': # fine self.host = host elif host_parts.scheme == 'http': upload.logging.warning('Changing protocol to https') self.host = 'https' + host[4:] else: msg = 'Invalid url provided: %s' % host upload.logging.error(msg) raise ValueError(msg) self.host = self.host.rstrip('/') self.extra_headers = extra_headers or {} if not oa2client.HAS_OPENSSL: logging.error("No support for OpenSSL has been found, " "OAuth2 support requires it.") logging.error("Installing pyopenssl will probably solve this issue.") raise RuntimeError('No OpenSSL support') self.creds = oa2client.SignedJwtAssertionCredentials( client_email, client_private_key, 'https://www.googleapis.com/auth/userinfo.email', private_key_password=private_key_password, user_agent=user_agent) self._http = self.creds.authorize(httplib2.Http(timeout=timeout)) def Send(self, request_path, payload=None, content_type='application/octet-stream', timeout=None, extra_headers=None, **kwargs): """Send a POST or GET request to the server. Args: request_path: path on the server to hit. This is concatenated with the value of 'host' provided to the constructor. payload: request is a POST if not None, GET otherwise timeout: in seconds extra_headers: (dict) """ # This method signature should match upload.py:AbstractRpcServer.Send() method = 'GET' headers = self.extra_headers.copy() headers.update(extra_headers or {}) if payload is not None: method = 'POST' headers['Content-Type'] = content_type prev_timeout = self._http.timeout try: if timeout: self._http.timeout = timeout # TODO(pgervais) implement some kind of retry mechanism (see upload.py). url = self.host + request_path if kwargs: url += "?" + urllib.urlencode(kwargs) # This weird loop is there to detect when the OAuth2 token has expired. # This is specific to appengine *and* rietveld. It relies on the # assumption that a 302 is triggered only by an expired OAuth2 token. This # prevents any usage of redirections in pages accessed this way. # This variable is used to make sure the following loop runs only twice. redirect_caught = False while True: try: ret = self._http.request(url, method=method, body=payload, headers=headers, redirections=0) except httplib2.RedirectLimit: if redirect_caught or method != 'GET': logging.error('Redirection detected after logging in. Giving up.') raise redirect_caught = True logging.debug('Redirection detected. Trying to log in again...') self.creds.access_token = None continue break return ret[1] finally: self._http.timeout = prev_timeout class JwtOAuth2Rietveld(Rietveld): """Access to Rietveld using OAuth authentication. This class is supposed to be used only by bots, since this kind of access is restricted to service accounts. """ # The parent__init__ is not called on purpose. # pylint: disable=W0231 def __init__(self, url, client_email, client_private_key_file, private_key_password=None, extra_headers=None, maxtries=None): if private_key_password is None: # '' means 'empty password' private_key_password = 'notasecret' self.url = url.rstrip('/') bot_url = self.url if self.url.endswith('googleplex.com'): bot_url = self.url + '/bots' with open(client_private_key_file, 'rb') as f: client_private_key = f.read() logging.info('Using OAuth login: %s' % client_email) self.rpc_server = OAuthRpcServer(bot_url, client_email, client_private_key, private_key_password=private_key_password, extra_headers=extra_headers or {}) self._xsrf_token = None self._xsrf_token_time = None self._maxtries = maxtries or 40 class CachingRietveld(Rietveld): """Caches the common queries. Not to be used in long-standing processes, like the commit queue. """ def __init__(self, *args, **kwargs): super(CachingRietveld, self).__init__(*args, **kwargs) self._cache = {} def _lookup(self, function_name, args, update): """Caches the return values corresponding to the arguments. It is important that the arguments are standardized, like None vs False. """ function_cache = self._cache.setdefault(function_name, {}) if args not in function_cache: function_cache[args] = update(*args) return copy.deepcopy(function_cache[args]) def get_description(self, issue): return self._lookup( 'get_description', (issue,), super(CachingRietveld, self).get_description) def get_issue_properties(self, issue, messages): """Returns the issue properties. Because in practice the presubmit checks often ask without messages first and then with messages, always ask with messages and strip off if not asked for the messages. """ # It's a tad slower to request with the message but it's better than # requesting the properties twice. data = self._lookup( 'get_issue_properties', (issue, True), super(CachingRietveld, self).get_issue_properties) if not messages: # Assumes self._lookup uses deepcopy. del data['messages'] return data def get_patchset_properties(self, issue, patchset): return self._lookup( 'get_patchset_properties', (issue, patchset), super(CachingRietveld, self).get_patchset_properties) class ReadOnlyRietveld(object): """ Only provides read operations, and simulates writes locally. Intentionally do not inherit from Rietveld to avoid any write-issuing logic to be invoked accidentally. """ # Dictionary of local changes, indexed by issue number as int. _local_changes = {} def __init__(self, *args, **kwargs): # We still need an actual Rietveld instance to issue reads, just keep # it hidden. self._rietveld = Rietveld(*args, **kwargs) @classmethod def _get_local_changes(cls, issue): """Returns dictionary of local changes for |issue|, if any.""" return cls._local_changes.get(issue, {}) @property def url(self): return self._rietveld.url def get_pending_issues(self): pending_issues = self._rietveld.get_pending_issues() # Filter out issues we've closed or unchecked the commit checkbox. return [issue for issue in pending_issues if not self._get_local_changes(issue).get('closed', False) and self._get_local_changes(issue).get('commit', True)] def close_issue(self, issue): # pylint:disable=R0201 logging.info('ReadOnlyRietveld: closing issue %d' % issue) ReadOnlyRietveld._local_changes.setdefault(issue, {})['closed'] = True def get_issue_properties(self, issue, messages): data = self._rietveld.get_issue_properties(issue, messages) data.update(self._get_local_changes(issue)) return data def get_patchset_properties(self, issue, patchset): return self._rietveld.get_patchset_properties(issue, patchset) def get_depends_on_patchset(self, issue, patchset): return self._rietveld.get_depends_on_patchset(issue, patchset) def get_patch(self, issue, patchset): return self._rietveld.get_patch(issue, patchset) def update_description(self, issue, description): # pylint:disable=R0201 logging.info('ReadOnlyRietveld: new description for issue %d: %s' % (issue, description)) def add_comment(self, # pylint:disable=R0201 issue, message, add_as_reviewer=False): logging.info('ReadOnlyRietveld: posting comment "%s" to issue %d' % (message, issue)) def set_flag(self, issue, patchset, flag, value): # pylint:disable=R0201 logging.info('ReadOnlyRietveld: setting flag "%s" to "%s" for issue %d' % (flag, value, issue)) ReadOnlyRietveld._local_changes.setdefault(issue, {})[flag] = value def trigger_try_jobs( # pylint:disable=R0201 self, issue, patchset, reason, clobber, revision, builders_and_tests, master=None, category='cq'): logging.info('ReadOnlyRietveld: triggering try jobs %r for issue %d' % (builders_and_tests, issue)) def trigger_distributed_try_jobs( # pylint:disable=R0201 self, issue, patchset, reason, clobber, revision, masters, category='cq'): logging.info('ReadOnlyRietveld: triggering try jobs %r for issue %d' % (masters, issue)) </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">bsd-3-clause</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">759,426,349,750,002,600</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">34.253045</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">80</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.620183</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.801547</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45151"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gonicus/gosa</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">backend/src/gosa/backend/plugins/samba/logonhours.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">2755</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "># This file is part of the GOsa framework. # # http://gosa-project.org # # Copyright: # (C) 2016 GONICUS GmbH, Germany, http://www.gonicus.de # # See the LICENSE file in the project's top-level directory for details. import time from gosa.backend.objects.types import AttributeType class SambaLogonHoursAttribute(AttributeType): """ This is a special object-attribute-type for sambaLogonHours. This call can convert sambaLogonHours to a UnicodeString and vice versa. It is used in the samba-object definition file. """ __alias__ = "SambaLogonHours" def values_match(self, value1, value2): return str(value1) == str(value2) def is_valid_value(self, value): if len(value): try: # Check if each week day contains 24 values. if type(value[0]) is not str or len(value[0]) != 168 or len(set(value[0]) - set('01')): return False return True except: return False def _convert_to_unicodestring(self, value): """ This method is a converter used when values gets read from or written to the backend. Converts the 'SambaLogonHours' object-type into a 'UnicodeString'-object. """ if len(value): # Combine the binary strings lstr = value[0] # New reverse every 8 bit part, and toggle high- and low-tuple (4Bits) new = "" for i in range(0, 21): n = lstr[i * 8:((i + 1) * 8)] n = n[0:4] + n[4:] n = n[::-1] n = str(hex(int(n, 2)))[2::].rjust(2, '0') new += n value = [new.upper()] return value def _convert_from_string(self, value): return self._convert_from_unicodestring(value) def _convert_from_unicodestring(self, value): """ This method is a converter used when values gets read from or written to the backend. Converts a 'UnicodeString' attribute into the 'SambaLogonHours' object-type. """ if len(value): # Convert each hex-pair into binary values. # Then reverse the binary result and switch high and low pairs. value = value[0] lstr = "" for i in range(0, 42, 2): n = (bin(int(value[i:i + 2], 16))[2::]).rjust(8, '0') n = n[::-1] lstr += n[0:4] + n[4:] # Shift lster by timezone offset shift_by = int((168 + (time.timezone/3600)) % 168) lstr = lstr[shift_by:] + lstr[:shift_by] # Parse result into more readable value value = [lstr] return value </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">lgpl-2.1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">5,620,265,410,477,604,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">29.611111</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">103</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.549546</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.837047</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45152"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mice-software/maus</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">tests/integration/test_simulation/test_beam_maker/binomial_beam_config.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">4151</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "># This file is part of MAUS: http://micewww.pp.rl.ac.uk:8080/projects/maus # # MAUS is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # MAUS is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with MAUS. If not, see <http://www.gnu.org/licenses/>. """ Configuration to generate a beam distribution with binomial distribution in the spill and various distributions for difference particle types """ #pylint: disable = C0103, R0801 import os mrd = os.environ["MAUS_ROOT_DIR"] simulation_geometry_filename = os.path.join( mrd, "tests", "integration", "test_simulation", "test_beam_maker", "BeamTest.dat" ) output_root_file_name = os.path.join(mrd, "tmp", "test_beammaker_output.root") input_root_file_name = output_root_file_name # for conversion spill_generator_number_of_spills = 1000 verbose_level = 1 beam = { "particle_generator":"binomial", # routine for generating empty primaries "binomial_n":20, # number of coin tosses "binomial_p":0.1, # probability of making a particle on each toss "random_seed":5, # random seed for beam generation; controls also how the MC # seeds are generated "definitions":[ ##### MUONS ####### { "reference":{ "position":{"x":0.0, "y":0.0, "z":3.0}, "momentum":{"x":0.0, "y":0.0, "z":1.0}, "spin":{"x":0.0, "y":0.0, "z":1.0}, "particle_id":-13, "energy":226.0, "time":2.e6, "random_seed":0 }, # reference particle "random_seed_algorithm":"incrementing_random", # algorithm for seeding MC "weight":90., # probability of generating a particle "transverse":{ "transverse_mode":"penn", "emittance_4d":6., "beta_4d":333., "alpha_4d":1., "normalised_angular_momentum":2., "bz":4.e-3 }, "longitudinal":{ "longitudinal_mode":"sawtooth_time", "momentum_variable":"p", "sigma_p":25., "t_start":-1.e6, "t_end":+1.e6}, "coupling":{"coupling_mode":"none"} }, ##### PIONS ##### { # as above... "reference":{ "position":{"x":0.0, "y":-0.0, "z":0.0}, "momentum":{"x":0.0, "y":0.0, "z":1.0}, "spin":{"x":0.0, "y":0.0, "z":1.0}, "particle_id":211, "energy":285.0, "time":0.0, "random_seed":10 }, "random_seed_algorithm":"incrementing_random", "weight":2., "transverse":{"transverse_mode":"constant_solenoid", "emittance_4d":6., "normalised_angular_momentum":0.1, "bz":4.e-3}, "longitudinal":{"longitudinal_mode":"uniform_time", "momentum_variable":"p", "sigma_p":25., "t_start":-1.e6, "t_end":+1.e6}, "coupling":{"coupling_mode":"none"} }, ##### ELECTRONS ##### { # as above... "reference":{ "position":{"x":0.0, "y":-0.0, "z":0.0}, "momentum":{"x":0.0, "y":0.0, "z":1.0}, "spin":{"x":0.0, "y":0.0, "z":1.0}, "particle_id":-11, "energy":200.0, "time":0.0, "random_seed":10 }, "random_seed_algorithm":"incrementing_random", "weight":8., "transverse":{"transverse_mode":"constant_solenoid", "emittance_4d":6., "normalised_angular_momentum":0.1, "bz":4.e-3}, "longitudinal":{"longitudinal_mode":"uniform_time", "momentum_variable":"p", "sigma_p":25., "t_start":-2.e6, "t_end":+1.e6}, "coupling":{"coupling_mode":"none"} }] } </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-3.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">8,497,676,633,273,780,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">37.082569</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">80</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.544688</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.245504</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45153"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">amagnus/pulsegig</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">app/models.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1894</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">from django.db import models from django.contrib.auth.models import User class Guy(models.Model): user = models.OneToOneField(User, primary_key=True) cell = models.CharField(max_length=15) metroarea_name = models.CharField(max_length=30, default=None, null=True) metroareaID = models.IntegerField(default=None, null=True) created = models.DateTimeField(auto_now_add=True) def __unicode__(self): return self.user class Band(models.Model): name = models.CharField(max_length=100) genre = models.CharField(max_length=100) skID = models.IntegerField() created = models.DateTimeField(auto_now_add=True) def __unicode__(self): return self.name class SimilarBand(models.Model): band_input = models.ForeignKey(Band, related_name='band_input') band_suggest = models.ForeignKey(Band, related_name='band_suggest') disabled = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) def __unicode__(self): return self.band_input.name class Alert(models.Model): user = models.ForeignKey(User) band = models.ForeignKey(Band) disabled = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) def __unicode__(self): return self.band.name class AlertLog(models.Model): user = models.ForeignKey(User) band = models.ForeignKey(Band) eventskID = models.IntegerField(default=None) showDate = models.DateField() showURL = models.CharField(max_length=255) is_similar = models.BooleanField(default=False) send_on = models.DateTimeField() has_sent = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) def __unicode__(self): return self.band.name </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-6,112,383,756,835,243,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">30.566667</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">77</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.705913</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.743083</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45154"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">PyBossa/pybossa</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">pybossa/auth/token.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1271</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "># -*- coding: utf8 -*- # This file is part of PYBOSSA. # # Copyright (C) 2015 Scifabric LTD. # # PYBOSSA is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # PYBOSSA is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with PYBOSSA. If not, see <http://www.gnu.org/licenses/>. class TokenAuth(object): _specific_actions = [] @property def specific_actions(self): return self._specific_actions def can(self, user, action, _, token=None): action = ''.join(['_', action]) return getattr(self, action)(user, token) def _create(self, user, token=None): return False def _read(self, user, token=None): return not user.is_anonymous() def _update(self, user, token): return False def _delete(self, user, token): return False </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">agpl-3.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">7,030,215,194,736,983,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">30</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">77</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.683714</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.875</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45155"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">ekumenlabs/terminus</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">terminus/generators/rndf_id_mapper.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">2695</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">""" Copyright (C) 2017 Open Source Robotics Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from city_visitor import CityVisitor from models.polyline_geometry import PolylineGeometry class RNDFIdMapper(CityVisitor): """Simple city visitor that generates the RNDF ids for segments, lanes and waypoints. Ids and objects are stored in two dictionaries, so we can later perform lookups in either way""" # Note: For the time being we treat streets and trunks in the same way, # hence generating a single lane for any of them. This will change in the # future, when we properly support multi-lanes trunks. def run(self): self.segment_id = 0 self.waypoint_id = 0 self.lane_id = 0 self.object_to_id_level_1 = {} self.object_to_id_level_2 = {} self.id_to_object = {} super(RNDFIdMapper, self).run() def id_for(self, object): try: return self.object_to_id_level_1[id(object)] except KeyError: return self.object_to_id_level_2[object] def object_for(self, id): return self.id_to_object[id] def map_road(self, road): self.segment_id = self.segment_id + 1 self.lane_id = 0 self._register(str(self.segment_id), road) def start_street(self, street): self.map_road(street) def start_trunk(self, trunk): self.map_road(trunk) def start_lane(self, lane): self.lane_id = self.lane_id + 1 rndf_lane_id = str(self.segment_id) + '.' + str(self.lane_id) self._register(rndf_lane_id, lane) self.waypoint_id = 0 for waypoint in lane.waypoints_for(PolylineGeometry): self.waypoint_id = self.waypoint_id + 1 rndf_waypoint_id = rndf_lane_id + '.' + str(self.waypoint_id) self._register(rndf_waypoint_id, waypoint) def _register(self, rndf_id, object): """We do some caching by id, to avoid computing hashes if they are expensive, but keep the hash-based dict as a fallback""" self.object_to_id_level_1[id(object)] = rndf_id self.object_to_id_level_2[object] = rndf_id self.id_to_object[rndf_id] = object </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">apache-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-5,815,910,434,938,483,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">35.418919</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">77</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.661224</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.550725</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45156"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">wkia/kodi-addon-repo</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">plugin.audio.openlast/default.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">6672</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "># -*- coding: utf-8 -*- import os import sys import urllib import urlparse import xbmcaddon import xbmcgui import xbmcplugin if sys.version_info < (2, 7): import simplejson as json else: import json from logging import log from util import build_url __addon__ = xbmcaddon.Addon() #__addonid__ = __addon__.getAddonInfo('id') #__settings__ = xbmcaddon.Addon(id='xbmc-vk.svoka.com') #__language__ = __settings__.getLocalizedString #LANGUAGE = __addon__.getLocalizedString ADDONVERSION = __addon__.getAddonInfo('version') CWD = __addon__.getAddonInfo('path').decode("utf-8") log('start -----------------------------------------------------') log('script version %s started' % ADDONVERSION) #xbmc.log(str(sys.argv)) addonUrl = sys.argv[0] addon_handle = int(sys.argv[1]) args = urlparse.parse_qs(sys.argv[2][1:]) #my_addon = xbmcaddon.Addon() # lastfmUser = my_addon.getSetting('lastfm_username') xbmcplugin.setContent(addon_handle, 'audio') lastfmApi = 'http://ws.audioscrobbler.com/2.0/' lastfmApiKey = '47608ece2138b2edae9538f83f703457' # TODO use Openlast key lastfmAddon = None lastfmUser = '' try: lastfmAddon = xbmcaddon.Addon('service.scrobbler.lastfm') lastfmUser = lastfmAddon.getSetting('lastfmuser') except RuntimeError: pass #xbmc.log(str(args)) action = args.get('action', None) folder = args.get('folder', None) #xbmc.log('openlast: folder=' + str(folder)) #, xbmc.LOGDEBUG) #xbmc.log('openlast: action=' + str(action)) #, xbmc.LOGDEBUG) if folder is None: url = build_url(addonUrl, {'folder': 'similarArtist'}) li = xbmcgui.ListItem('Similar artist radio', iconImage='DefaultFolder.png') xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li, isFolder=True) if '' != lastfmUser: url = build_url(addonUrl, {'folder': 'lastfm', 'username': lastfmUser}) # xbmc.log(url) li = xbmcgui.ListItem('Personal radio for Last.fm user: ' + lastfmUser, iconImage='DefaultFolder.png') xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li, isFolder=True) url = build_url(addonUrl, {'folder': 'lastfm'}) li = xbmcgui.ListItem('Personal radio for Last.fm user...', iconImage='DefaultFolder.png') xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li, isFolder=True) xbmcplugin.endOfDirectory(addon_handle) elif folder[0] == 'lastfm': username = '' if None != args.get('username'): username = args.get('username')[0] playcount = 0 if None != args.get('playcount'): playcount = int(args.get('playcount')[0]) if username == '': user_keyboard = xbmc.Keyboard() user_keyboard.setHeading('Last.FM user name') # __language__(30001)) user_keyboard.setHiddenInput(False) user_keyboard.setDefault(lastfmUser) user_keyboard.doModal() if user_keyboard.isConfirmed(): username = user_keyboard.getText() else: raise Exception("Login input was cancelled.") if action is None: url = build_url(lastfmApi, {'method': 'user.getInfo', 'user': username, 'format': 'json', 'api_key': lastfmApiKey}) reply = urllib.urlopen(url) resp = json.load(reply) if "error" in resp: raise Exception("Error! DATA: " + str(resp)) else: # xbmc.log(str(resp)) pass playcount = int(resp['user']['playcount']) img = resp['user']['image'][2]['#text'] if '' == img: img = 'DefaultAudio.png' url = build_url(addonUrl, {'folder': folder[0], 'action': 'lovedTracks', 'username': username}) li = xbmcgui.ListItem('Listen to loved tracks', iconImage=img) xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li, isFolder=False) url = build_url(addonUrl, {'folder': folder[0], 'action': 'topTracks', 'username': username, 'playcount': playcount}) li = xbmcgui.ListItem('Listen to track library', iconImage=img) xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li, isFolder=False) url = build_url(addonUrl, {'folder': folder[0], 'action': 'topArtists', 'username': username, 'playcount': playcount}) li = xbmcgui.ListItem('Listen to artist library', iconImage=img) xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li, isFolder=False) url = build_url(addonUrl, {'folder': folder[0], 'action': 'syncLibrary', 'username': username, 'playcount': playcount}) li = xbmcgui.ListItem('[EXPERIMENTAL] Syncronize library to folder', iconImage=img) xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li, isFolder=False) xbmcplugin.endOfDirectory(addon_handle) elif action[0] == 'lovedTracks': script = os.path.join(CWD, "run_app.py") log('running script %s...' % script) xbmc.executebuiltin('XBMC.RunScript(%s, %s, %s)' % (script, action[0], username)) elif action[0] == 'topTracks': script = os.path.join(CWD, "run_app.py") log('running script %s...' % script) xbmc.executebuiltin('XBMC.RunScript(%s, %s, %s, %s)' % (script, action[0], username, playcount)) elif action[0] == 'topArtists': script = os.path.join(CWD, "run_app.py") log('running script %s...' % script) xbmc.executebuiltin('XBMC.RunScript(%s, %s, %s, %s)' % (script, action[0], username, playcount)) elif action[0] == 'syncLibrary': script = os.path.join(CWD, "run_app.py") log('running script %s...' % script) xbmc.executebuiltin('XBMC.RunScript(%s, %s, %s)' % (script, action[0], username)) elif folder[0] == 'similarArtist': if action is None: url = build_url(lastfmApi, {'method': 'chart.getTopArtists', 'format': 'json', 'api_key': lastfmApiKey}) reply = urllib.urlopen(url) resp = json.load(reply) if "error" in resp: raise Exception("Error! DATA: " + str(resp)) else: #log(str(resp)) pass for a in resp['artists']['artist']: url = build_url(addonUrl, {'folder': folder[0], 'action': a['name'].encode('utf-8')}) li = xbmcgui.ListItem(a['name']) li.setArt({'icon': a['image'][2]['#text'], 'thumb': a['image'][2]['#text'], 'fanart': a['image'][4]['#text']}) xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li, isFolder=False) pass xbmcplugin.endOfDirectory(addon_handle) log('end -----------------------------------------------------') </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">4,180,069,975,239,429,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">37.566474</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">127</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.618855</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.439175</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45157"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mozman/ezdxf</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">tests/test_06_math/test_630b_bezier4p_functions.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">4662</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "># Copyright (c) 2010-2020 Manfred Moitzi # License: MIT License import pytest import random from ezdxf.math import ( cubic_bezier_interpolation, Vec3, Bezier3P, quadratic_to_cubic_bezier, Bezier4P, have_bezier_curves_g1_continuity, bezier_to_bspline, ) def test_vertex_interpolation(): points = [(0, 0), (3, 1), (5, 3), (0, 8)] result = list(cubic_bezier_interpolation(points)) assert len(result) == 3 c1, c2, c3 = result p = c1.control_points assert p[0].isclose((0, 0)) assert p[1].isclose((0.9333333333333331, 0.3111111111111111)) assert p[2].isclose((1.8666666666666663, 0.6222222222222222)) assert p[3].isclose((3, 1)) p = c2.control_points assert p[0].isclose((3, 1)) assert p[1].isclose((4.133333333333334, 1.3777777777777778)) assert p[2].isclose((5.466666666666667, 1.822222222222222)) assert p[3].isclose((5, 3)) p = c3.control_points assert p[0].isclose((5, 3)) assert p[1].isclose((4.533333333333333, 4.177777777777778)) assert p[2].isclose((2.2666666666666666, 6.088888888888889)) assert p[3].isclose((0, 8)) def test_quadratic_to_cubic_bezier(): r = random.Random(0) def random_vec() -> Vec3: return Vec3(r.uniform(-10, 10), r.uniform(-10, 10), r.uniform(-10, 10)) for i in range(1000): quadratic = Bezier3P((random_vec(), random_vec(), random_vec())) quadratic_approx = list(quadratic.approximate(10)) cubic = quadratic_to_cubic_bezier(quadratic) cubic_approx = list(cubic.approximate(10)) assert len(quadratic_approx) == len(cubic_approx) for p1, p2 in zip(quadratic_approx, cubic_approx): assert p1.isclose(p2) # G1 continuity: normalized end-tangent == normalized start-tangent of next curve B1 = Bezier4P([(0, 0), (1, 1), (2, 1), (3, 0)]) # B1/B2 has G1 continuity: B2 = Bezier4P([(3, 0), (4, -1), (5, -1), (6, 0)]) # B1/B3 has no G1 continuity: B3 = Bezier4P([(3, 0), (4, 1), (5, 1), (6, 0)]) # B1/B4 G1 continuity off tolerance: B4 = Bezier4P([(3, 0), (4, -1.03), (5, -1.0), (6, 0)]) # B1/B5 has a gap between B1 end and B5 start: B5 = Bezier4P([(4, 0), (5, -1), (6, -1), (7, 0)]) def test_g1_continuity_for_bezier_curves(): assert have_bezier_curves_g1_continuity(B1, B2) is True assert have_bezier_curves_g1_continuity(B1, B3) is False assert have_bezier_curves_g1_continuity(B1, B4, g1_tol=1e-4) is False, \ "should be outside of tolerance " assert have_bezier_curves_g1_continuity(B1, B5) is False, \ "end- and start point should match" D1 = Bezier4P([(0, 0), (1, 1), (3, 0), (3, 0)]) D2 = Bezier4P([(3, 0), (3, 0), (5, -1), (6, 0)]) def test_g1_continuity_for_degenerated_bezier_curves(): assert have_bezier_curves_g1_continuity(D1, B2) is False assert have_bezier_curves_g1_continuity(B1, D2) is False assert have_bezier_curves_g1_continuity(D1, D2) is False @pytest.mark.parametrize('curve', [D1, D2]) def test_flatten_degenerated_bezier_curves(curve): # Degenerated Bezier curves behave like regular curves! assert len(list(curve.flattening(0.1))) > 4 @pytest.mark.parametrize("b1,b2", [ (B1, B2), # G1 continuity, the common case (B1, B3), # without G1 continuity is also a regular B-spline (B1, B5), # regular B-spline, but first control point of B5 is lost ], ids=["G1", "without G1", "gap"]) def test_bezier_curves_to_bspline(b1, b2): bspline = bezier_to_bspline([b1, b2]) # Remove duplicate control point between two adjacent curves: expected = list(b1.control_points) + list(b2.control_points)[1:] assert bspline.degree == 3, "should be a cubic B-spline" assert bspline.control_points == tuple(expected) def test_quality_of_bezier_to_bspline_conversion_1(): # This test shows the close relationship between cubic Bézier- and # cubic B-spline curves. points0 = B1.approximate(10) points1 = bezier_to_bspline([B1]).approximate(10) for p0, p1 in zip(points0, points1): assert p0.isclose(p1) is True, "conversion should be perfect" def test_quality_of_bezier_to_bspline_conversion_2(): # This test shows the close relationship between cubic Bézier- and # cubic B-spline curves. # Remove duplicate point between the two curves: points0 = list(B1.approximate(10)) + list(B2.approximate(10))[1:] points1 = bezier_to_bspline([B1, B2]).approximate(20) for p0, p1 in zip(points0, points1): assert p0.isclose(p1) is True, "conversion should be perfect" def test_bezier_curves_to_bspline_error(): with pytest.raises(ValueError): bezier_to_bspline([]) # one or more curves expected </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">2,218,089,063,526,213,400</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">35.40625</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">81</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.65794</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">2.729936</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">true</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45158"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">fdouetteau/PyBabe</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">pybabe/format_csv.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">3107</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "> from base import BabeBase, StreamHeader, StreamFooter import csv from charset import UTF8Recoder, UTF8RecoderWithCleanup, PrefixReader, UnicodeCSVWriter import codecs import logging log = logging.getLogger("csv") def linepull(stream, dialect, kwargs): it = iter(stream) fields = kwargs.get('fields', None) if not fields: fields = [it.next().rstrip('\r\n')] metainfo = StreamHeader(**dict(kwargs, fields=fields)) yield metainfo for row in it: yield metainfo.t._make([row.rstrip('\r\n')]) yield StreamFooter() def build_value(x, null_value): if x == null_value: return None else: return unicode(x, "utf-8") def csvpull(stream, dialect, kwargs): reader = csv.reader(stream, dialect) fields = kwargs.get('fields', None) null_value = kwargs.get('null_value', "") ignore_malformed = kwargs.get('ignore_bad_lines', False) if not fields: fields = reader.next() metainfo = StreamHeader(**dict(kwargs, fields=fields)) yield metainfo for row in reader: try: yield metainfo.t._make([build_value(x, null_value) for x in row]) except Exception, e: if ignore_malformed: log.warn("Malformed line: %s, %s" % (row, e)) else: raise e yield StreamFooter() def pull(format, stream, kwargs): if kwargs.get('utf8_cleanup', False): stream = UTF8RecoderWithCleanup(stream, kwargs.get('encoding', 'utf-8')) elif codecs.getreader(kwargs.get('encoding', 'utf-8')) != codecs.getreader('utf-8'): stream = UTF8Recoder(stream, kwargs.get('encoding', None)) else: pass delimiter = kwargs.get('delimiter', None) sniff_read = stream.next() stream = PrefixReader(sniff_read, stream, linefilter=kwargs.get("linefilter", None)) dialect = csv.Sniffer().sniff(sniff_read) if sniff_read.endswith('\r\n'): dialect.lineterminator = '\r\n' else: dialect.lineterminator = '\n' if dialect.delimiter.isalpha() and not delimiter: # http://bugs.python.org/issue2078 for row in linepull(stream, dialect, kwargs): yield row return if delimiter: dialect.delimiter = delimiter for row in csvpull(stream, dialect, kwargs): yield row class default_dialect(csv.Dialect): lineterminator = '\n' delimiter = ',' doublequote = False escapechar = '\\' quoting = csv.QUOTE_MINIMAL quotechar = '"' def push(format, metainfo, instream, outfile, encoding, delimiter=None, **kwargs): if not encoding: encoding = "utf8" dialect = kwargs.get('dialect', default_dialect) if delimiter: dialect.delimiter = delimiter writer = UnicodeCSVWriter(outfile, dialect=dialect, encoding=encoding) writer.writerow(metainfo.fields) for k in instream: if isinstance(k, StreamFooter): break else: writer.writerow(k) BabeBase.addPullPlugin('csv', ['csv', 'tsv', 'txt'], pull) BabeBase.addPushPlugin('csv', ['csv', 'tsv', 'txt'], push) </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">bsd-3-clause</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-8,952,105,549,496,500,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">30.07</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">88</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.631799</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.703218</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45159"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">filippog/pysnmp</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">examples/hlapi/asyncore/sync/agent/ntforg/v3-trap.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1601</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">""" SNMPv3 TRAP: auth SHA, privacy: AES128 ++++++++++++++++++++++++++++++++++++++ Send SNMP notification using the following options: * SNMPv3 * with authoritative snmpEngineId = 0x8000000001020304 (USM must be configured at the Receiver accordingly) * with user 'usr-sha-aes128', auth: SHA, priv: AES128 * over IPv4/UDP * send TRAP notification * with TRAP ID 'authenticationFailure' specified as a MIB symbol * do not include any additional managed object information SNMPv3 TRAPs requires pre-sharing the Notification Originator's value of SnmpEngineId with Notification Receiver. To facilitate that we will use static (e.g. not autogenerated) version of snmpEngineId. Functionally similar to: | $ snmptrap -v3 -e 8000000001020304 -l authPriv -u usr-sha-aes -A authkey1 -X privkey1 -a SHA -x AES demo.snmplabs.com 12345 1.3.6.1.4.1.20408.4.1.1.2 1.3.6.1.2.1.1.1.0 s "my system" """# from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( sendNotification(SnmpEngine(OctetString(hexValue='8000000001020304')), UsmUserData('usr-sha-aes128', 'authkey1', 'privkey1', authProtocol=usmHMACSHAAuthProtocol, privProtocol=usmAesCfb128Protocol), UdpTransportTarget(('demo.snmplabs.com', 162)), ContextData(), 'trap', NotificationType( ObjectIdentity('SNMPv2-MIB', 'authenticationFailure') ) ) ) if errorIndication: print(errorIndication) </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">bsd-3-clause</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">7,296,825,608,207,418,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">38.04878</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">183</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.647096</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.573661</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">true</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45160"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">SU-ECE-17-7/hotspotter</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">hsviz/draw_func2.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">54605</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">''' Lots of functions for drawing and plotting visiony things ''' # TODO: New naming scheme # viz_<func_name> will clear everything. The current axes and fig: clf, cla. # Will add annotations # interact_<func_name> will clear everything and start user interactions. # show_<func_name> will always clear the current axes, but not fig: cla # Might # add annotates? # plot_<func_name> will not clear the axes or figure. More useful for graphs # draw_<func_name> same as plot for now. More useful for images from __future__ import division, print_function from hscom import __common__ (print, print_, print_on, print_off, rrr, profile, printDBG) = __common__.init(__name__, '[df2]', DEBUG=False, initmpl=True) # Python from itertools import izip from os.path import splitext, split, join, normpath, exists import colorsys import itertools import pylab import sys import textwrap import time import warnings # Matplotlib / Qt import matplotlib import matplotlib as mpl # NOQA from matplotlib.collections import PatchCollection, LineCollection from matplotlib.font_manager import FontProperties from matplotlib.patches import Rectangle, Circle, FancyArrow from matplotlib.transforms import Affine2D from matplotlib.backends import backend_qt4 import matplotlib.pyplot as plt # Qt from PyQt4 import QtCore, QtGui from PyQt4.QtCore import Qt # Scientific import numpy as np import scipy.stats import cv2 # HotSpotter from hscom import helpers from hscom import tools from hscom.Printable import DynStruct #================ # GLOBALS #================ TMP_mevent = None QT4_WINS = [] plotWidget = None # GENERAL FONTS SMALLER = 8 SMALL = 10 MED = 12 LARGE = 14 #fpargs = dict(family=None, style=None, variant=None, stretch=None, fname=None) FONTS = DynStruct() FONTS.small = FontProperties(weight='light', size=SMALL) FONTS.smaller = FontProperties(weight='light', size=SMALLER) FONTS.med = FontProperties(weight='light', size=MED) FONTS.large = FontProperties(weight='light', size=LARGE) FONTS.medbold = FontProperties(weight='bold', size=MED) FONTS.largebold = FontProperties(weight='bold', size=LARGE) # SPECIFIC FONTS FONTS.legend = FONTS.small FONTS.figtitle = FONTS.med FONTS.axtitle = FONTS.med FONTS.subtitle = FONTS.med FONTS.xlabel = FONTS.smaller FONTS.ylabel = FONTS.small FONTS.relative = FONTS.smaller # COLORS ORANGE = np.array((255, 127, 0, 255)) / 255.0 RED = np.array((255, 0, 0, 255)) / 255.0 GREEN = np.array(( 0, 255, 0, 255)) / 255.0 BLUE = np.array(( 0, 0, 255, 255)) / 255.0 YELLOW = np.array((255, 255, 0, 255)) / 255.0 BLACK = np.array(( 0, 0, 0, 255)) / 255.0 WHITE = np.array((255, 255, 255, 255)) / 255.0 GRAY = np.array((127, 127, 127, 255)) / 255.0 DEEP_PINK = np.array((255, 20, 147, 255)) / 255.0 PINK = np.array((255, 100, 100, 255)) / 255.0 FALSE_RED = np.array((255, 51, 0, 255)) / 255.0 TRUE_GREEN = np.array(( 0, 255, 0, 255)) / 255.0 DARK_ORANGE = np.array((127, 63, 0, 255)) / 255.0 DARK_YELLOW = np.array((127, 127, 0, 255)) / 255.0 PURPLE = np.array((102, 0, 153, 255)) / 255.0 UNKNOWN_PURP = PURPLE # FIGURE GEOMETRY DPI = 80 #DPI = 160 #FIGSIZE = (24) # default windows fullscreen FIGSIZE_MED = (12, 6) FIGSIZE_SQUARE = (12, 12) FIGSIZE_BIGGER = (24, 12) FIGSIZE_HUGE = (32, 16) FIGSIZE = FIGSIZE_MED # Quality drawings #FIGSIZE = FIGSIZE_SQUARE #DPI = 120 tile_within = (-1, 30, 969, 1041) if helpers.get_computer_name() == 'Ooo': TILE_WITHIN = (-1912, 30, -969, 1071) # DEFAULTS. (TODO: Can these be cleaned up?) DISTINCT_COLORS = True # and False DARKEN = None ELL_LINEWIDTH = 1.5 if DISTINCT_COLORS: ELL_ALPHA = .6 LINE_ALPHA = .35 else: ELL_ALPHA = .4 LINE_ALPHA = .4 LINE_ALPHA_OVERRIDE = helpers.get_arg('--line-alpha-override', type_=float, default=None) ELL_ALPHA_OVERRIDE = helpers.get_arg('--ell-alpha-override', type_=float, default=None) #LINE_ALPHA_OVERRIDE = None #ELL_ALPHA_OVERRIDE = None ELL_COLOR = BLUE LINE_COLOR = RED LINE_WIDTH = 1.4 SHOW_LINES = True # True SHOW_ELLS = True POINT_SIZE = 2 base_fnum = 9001 def next_fnum(): global base_fnum base_fnum += 1 return base_fnum def my_prefs(): global LINE_COLOR global ELL_COLOR global ELL_LINEWIDTH global ELL_ALPHA LINE_COLOR = (1, 0, 0) ELL_COLOR = (0, 0, 1) ELL_LINEWIDTH = 2 ELL_ALPHA = .5 def execstr_global(): execstr = ['global' + key for key in globals().keys()] return execstr def register_matplotlib_widget(plotWidget_): 'talks to PyQt4 guis' global plotWidget plotWidget = plotWidget_ #fig = plotWidget.figure #axes_list = fig.get_axes() #ax = axes_list[0] #plt.sca(ax) def unregister_qt4_win(win): global QT4_WINS if win == 'all': QT4_WINS = [] def register_qt4_win(win): global QT4_WINS QT4_WINS.append(win) def OooScreen2(): nRows = 1 nCols = 1 x_off = 30 * 4 y_off = 30 * 4 x_0 = -1920 y_0 = 30 w = (1912 - x_off) / nRows h = (1080 - y_off) / nCols return dict(num_rc=(1, 1), wh=(w, h), xy_off=(x_0, y_0), wh_off=(0, 10), row_first=True, no_tile=False) def deterministic_shuffle(list_): randS = int(np.random.rand() * np.uint(0 - 2) / 2) np.random.seed(len(list_)) np.random.shuffle(list_) np.random.seed(randS) def distinct_colors(N, brightness=.878): # http://blog.jianhuashao.com/2011/09/generate-n-distinct-colors.html sat = brightness val = brightness HSV_tuples = [(x * 1.0 / N, sat, val) for x in xrange(N)] RGB_tuples = map(lambda x: colorsys.hsv_to_rgb(*x), HSV_tuples) deterministic_shuffle(RGB_tuples) return RGB_tuples def add_alpha(colors): return [list(color) + [1] for color in colors] def _axis_xy_width_height(ax, xaug=0, yaug=0, waug=0, haug=0): 'gets geometry of a subplot' autoAxis = ax.axis() xy = (autoAxis[0] + xaug, autoAxis[2] + yaug) width = (autoAxis[1] - autoAxis[0]) + waug height = (autoAxis[3] - autoAxis[2]) + haug return xy, width, height def draw_border(ax, color=GREEN, lw=2, offset=None): 'draws rectangle border around a subplot' xy, width, height = _axis_xy_width_height(ax, -.7, -.2, 1, .4) if offset is not None: xoff, yoff = offset xy = [xoff, yoff] height = - height - yoff width = width - xoff rect = matplotlib.patches.Rectangle(xy, width, height, lw=lw) rect = ax.add_patch(rect) rect.set_clip_on(False) rect.set_fill(False) rect.set_edgecolor(color) def draw_roi(roi, label=None, bbox_color=(1, 0, 0), lbl_bgcolor=(0, 0, 0), lbl_txtcolor=(1, 1, 1), theta=0, ax=None): if ax is None: ax = gca() (rx, ry, rw, rh) = roi #cos_ = np.cos(theta) #sin_ = np.sin(theta) #rot_t = Affine2D([( cos_, -sin_, 0), #( sin_, cos_, 0), #( 0, 0, 1)]) #scale_t = Affine2D([( rw, 0, 0), #( 0, rh, 0), #( 0, 0, 1)]) #trans_t = Affine2D([( 1, 0, rx + rw / 2), #( 0, 1, ry + rh / 2), #( 0, 0, 1)]) #t_end = scale_t + rot_t + trans_t + t_start # Transformations are specified in backwards order. trans_roi = Affine2D() trans_roi.scale(rw, rh) trans_roi.rotate(theta) trans_roi.translate(rx + rw / 2, ry + rh / 2) t_end = trans_roi + ax.transData bbox = matplotlib.patches.Rectangle((-.5, -.5), 1, 1, lw=2, transform=t_end) arw_x, arw_y, arw_dx, arw_dy = (-0.5, -0.5, 1.0, 0.0) arrowargs = dict(head_width=.1, transform=t_end, length_includes_head=True) arrow = FancyArrow(arw_x, arw_y, arw_dx, arw_dy, **arrowargs) bbox.set_fill(False) #bbox.set_transform(trans) bbox.set_edgecolor(bbox_color) arrow.set_edgecolor(bbox_color) arrow.set_facecolor(bbox_color) ax.add_patch(bbox) ax.add_patch(arrow) #ax.add_patch(arrow2) if label is not None: ax_absolute_text(rx, ry, label, ax=ax, horizontalalignment='center', verticalalignment='center', color=lbl_txtcolor, backgroundcolor=lbl_bgcolor) # ---- GENERAL FIGURE COMMANDS ---- def sanatize_img_fname(fname): fname_clean = fname search_replace_list = [(' ', '_'), ('\n', '--'), ('\\', ''), ('/', '')] for old, new in search_replace_list: fname_clean = fname_clean.replace(old, new) fname_noext, ext = splitext(fname_clean) fname_clean = fname_noext + ext.lower() # Check for correct extensions if not ext.lower() in helpers.IMG_EXTENSIONS: fname_clean += '.png' return fname_clean def sanatize_img_fpath(fpath): [dpath, fname] = split(fpath) fname_clean = sanatize_img_fname(fname) fpath_clean = join(dpath, fname_clean) fpath_clean = normpath(fpath_clean) return fpath_clean def set_geometry(fnum, x, y, w, h): fig = get_fig(fnum) qtwin = fig.canvas.manager.window qtwin.setGeometry(x, y, w, h) def get_geometry(fnum): fig = get_fig(fnum) qtwin = fig.canvas.manager.window (x1, y1, x2, y2) = qtwin.geometry().getCoords() (x, y, w, h) = (x1, y1, x2 - x1, y2 - y1) return (x, y, w, h) def get_screen_info(): from PyQt4 import Qt, QtGui # NOQA desktop = QtGui.QDesktopWidget() mask = desktop.mask() # NOQA layout_direction = desktop.layoutDirection() # NOQA screen_number = desktop.screenNumber() # NOQA normal_geometry = desktop.normalGeometry() # NOQA num_screens = desktop.screenCount() # NOQA avail_rect = desktop.availableGeometry() # NOQA screen_rect = desktop.screenGeometry() # NOQA QtGui.QDesktopWidget().availableGeometry().center() # NOQA normal_geometry = desktop.normalGeometry() # NOQA def get_all_figures(): all_figures_ = [manager.canvas.figure for manager in matplotlib._pylab_helpers.Gcf.get_all_fig_managers()] all_figures = [] # Make sure you dont show figures that this module closed for fig in iter(all_figures_): if not 'df2_closed' in fig.__dict__.keys() or not fig.df2_closed: all_figures.append(fig) # Return all the figures sorted by their number all_figures = sorted(all_figures, key=lambda fig: fig.number) return all_figures def get_all_qt4_wins(): return QT4_WINS def all_figures_show(): if plotWidget is not None: plotWidget.figure.show() plotWidget.figure.canvas.draw() for fig in iter(get_all_figures()): time.sleep(.1) fig.show() fig.canvas.draw() def all_figures_tight_layout(): for fig in iter(get_all_figures()): fig.tight_layout() #adjust_subplots() time.sleep(.1) def get_monitor_geom(monitor_num=0): from PyQt4 import QtGui # NOQA desktop = QtGui.QDesktopWidget() rect = desktop.availableGeometry() geom = (rect.x(), rect.y(), rect.width(), rect.height()) return geom def golden_wh(x): 'returns a width / height with a golden aspect ratio' return map(int, map(round, (x * .618, x * .312))) def all_figures_tile(num_rc=(3, 4), wh=1000, xy_off=(0, 0), wh_off=(0, 10), row_first=True, no_tile=False, override1=False): 'Lays out all figures in a grid. if wh is a scalar, a golden ratio is used' # RCOS TODO: # I want this function to layout all the figures and qt windows within the # bounds of a rectangle. (taken from the get_monitor_geom, or specified by # the user i.e. left half of monitor 0). It should lay them out # rectangularly and choose figure sizes such that all of them will fit. if no_tile: return if not np.iterable(wh): wh = golden_wh(wh) all_figures = get_all_figures() all_qt4wins = get_all_qt4_wins() if override1: if len(all_figures) == 1: fig = all_figures[0] win = fig.canvas.manager.window win.setGeometry(0, 0, 900, 900) update() return #nFigs = len(all_figures) + len(all_qt4_wins) num_rows, num_cols = num_rc w, h = wh x_off, y_off = xy_off w_off, h_off = wh_off x_pad, y_pad = (0, 0) printDBG('[df2] Tile all figures: ') printDBG('[df2] wh = %r' % ((w, h),)) printDBG('[df2] xy_offsets = %r' % ((x_off, y_off),)) printDBG('[df2] wh_offsets = %r' % ((w_off, h_off),)) printDBG('[df2] xy_pads = %r' % ((x_pad, y_pad),)) if sys.platform == 'win32': h_off += 0 w_off += 40 x_off += 40 y_off += 40 x_pad += 0 y_pad += 100 def position_window(i, win): isqt4_mpl = isinstance(win, backend_qt4.MainWindow) isqt4_back = isinstance(win, QtGui.QMainWindow) if not isqt4_mpl and not isqt4_back: raise NotImplementedError('%r-th Backend %r is not a Qt Window' % (i, win)) if row_first: y = (i % num_rows) * (h + h_off) + 40 x = (int(i / num_rows)) * (w + w_off) + x_pad else: x = (i % num_cols) * (w + w_off) + 40 y = (int(i / num_cols)) * (h + h_off) + y_pad x += x_off y += y_off win.setGeometry(x, y, w, h) ioff = 0 for i, win in enumerate(all_qt4wins): position_window(i, win) ioff += 1 for i, fig in enumerate(all_figures): win = fig.canvas.manager.window position_window(i + ioff, win) def all_figures_bring_to_front(): all_figures = get_all_figures() for fig in iter(all_figures): bring_to_front(fig) def close_all_figures(): all_figures = get_all_figures() for fig in iter(all_figures): close_figure(fig) def close_figure(fig): fig.clf() fig.df2_closed = True qtwin = fig.canvas.manager.window qtwin.close() def bring_to_front(fig): #what is difference between show and show normal? qtwin = fig.canvas.manager.window qtwin.raise_() qtwin.activateWindow() qtwin.setWindowFlags(Qt.WindowStaysOnTopHint) qtwin.setWindowFlags(Qt.WindowFlags(0)) qtwin.show() def show(): all_figures_show() all_figures_bring_to_front() plt.show() def reset(): close_all_figures() def draw(): all_figures_show() def update(): draw() all_figures_bring_to_front() def present(*args, **kwargs): 'execing present should cause IPython magic' print('[df2] Presenting figures...') with warnings.catch_warnings(): warnings.simplefilter("ignore") all_figures_tile(*args, **kwargs) all_figures_show() all_figures_bring_to_front() # Return an exec string execstr = helpers.ipython_execstr() execstr += textwrap.dedent(''' if not embedded: print('[df2] Presenting in normal shell.') print('[df2] ... plt.show()') plt.show() ''') return execstr def save_figure(fnum=None, fpath=None, usetitle=False, overwrite=True): #import warnings #warnings.simplefilter("error") # Find the figure if fnum is None: fig = gcf() else: fig = plt.figure(fnum, figsize=FIGSIZE, dpi=DPI) # Enforce inches and DPI fig.set_size_inches(FIGSIZE[0], FIGSIZE[1]) fnum = fig.number if fpath is None: # Find the title fpath = sanatize_img_fname(fig.canvas.get_window_title()) if usetitle: title = sanatize_img_fname(fig.canvas.get_window_title()) fpath = join(fpath, title) # Add in DPI information fpath_noext, ext = splitext(fpath) size_suffix = '_DPI=%r_FIGSIZE=%d,%d' % (DPI, FIGSIZE[0], FIGSIZE[1]) fpath = fpath_noext + size_suffix + ext # Sanatize the filename fpath_clean = sanatize_img_fpath(fpath) #fname_clean = split(fpath_clean)[1] print('[df2] save_figure() %r' % (fpath_clean,)) #adjust_subplots() with warnings.catch_warnings(): warnings.filterwarnings('ignore', category=DeprecationWarning) if not exists(fpath_clean) or overwrite: fig.savefig(fpath_clean, dpi=DPI) def set_ticks(xticks, yticks): ax = gca() ax.set_xticks(xticks) ax.set_yticks(yticks) def set_xticks(tick_set): ax = gca() ax.set_xticks(tick_set) def set_yticks(tick_set): ax = gca() ax.set_yticks(tick_set) def set_xlabel(lbl, ax=None): if ax is None: ax = gca() ax.set_xlabel(lbl, fontproperties=FONTS.xlabel) def set_title(title, ax=None): if ax is None: ax = gca() ax.set_title(title, fontproperties=FONTS.axtitle) def set_ylabel(lbl): ax = gca() ax.set_ylabel(lbl, fontproperties=FONTS.xlabel) def plot(*args, **kwargs): return plt.plot(*args, **kwargs) def plot2(x_data, y_data, marker='o', title_pref='', x_label='x', y_label='y', *args, **kwargs): do_plot = True ax = gca() if len(x_data) != len(y_data): warnstr = '[df2] ! Warning: len(x_data) != len(y_data). Cannot plot2' warnings.warn(warnstr) draw_text(warnstr) do_plot = False if len(x_data) == 0: warnstr = '[df2] ! Warning: len(x_data) == 0. Cannot plot2' warnings.warn(warnstr) draw_text(warnstr) do_plot = False if do_plot: ax.plot(x_data, y_data, marker, *args, **kwargs) min_ = min(x_data.min(), y_data.min()) max_ = max(x_data.max(), y_data.max()) # Equal aspect ratio ax.set_xlim(min_, max_) ax.set_ylim(min_, max_) ax.set_aspect('equal') ax.set_xlabel(x_label, fontproperties=FONTS.xlabel) ax.set_ylabel(y_label, fontproperties=FONTS.xlabel) ax.set_title(title_pref + ' ' + x_label + ' vs ' + y_label, fontproperties=FONTS.axtitle) def adjust_subplots_xlabels(): adjust_subplots(left=.03, right=.97, bottom=.2, top=.9, hspace=.15) def adjust_subplots_xylabels(): adjust_subplots(left=.03, right=1, bottom=.1, top=.9, hspace=.15) def adjust_subplots_safe(left=.1, right=.9, bottom=.1, top=.9, wspace=.3, hspace=.5): adjust_subplots(left, bottom, right, top, wspace, hspace) def adjust_subplots(left=0.02, bottom=0.02, right=0.98, top=0.90, wspace=0.1, hspace=0.15): ''' left = 0.125 # the left side of the subplots of the figure right = 0.9 # the right side of the subplots of the figure bottom = 0.1 # the bottom of the subplots of the figure top = 0.9 # the top of the subplots of the figure wspace = 0.2 # the amount of width reserved for blank space between subplots hspace = 0.2 ''' #print('[df2] adjust_subplots(%r)' % locals()) plt.subplots_adjust(left, bottom, right, top, wspace, hspace) #======================= # TEXT FUNCTIONS # TODO: I have too many of these. Need to consolidate #======================= def upperleft_text(txt): txtargs = dict(horizontalalignment='left', verticalalignment='top', #fontsize='smaller', #fontweight='ultralight', backgroundcolor=(0, 0, 0, .5), color=ORANGE) ax_relative_text(.02, .02, txt, **txtargs) def upperright_text(txt, offset=None): txtargs = dict(horizontalalignment='right', verticalalignment='top', #fontsize='smaller', #fontweight='ultralight', backgroundcolor=(0, 0, 0, .5), color=ORANGE, offset=offset) ax_relative_text(.98, .02, txt, **txtargs) def lowerright_text(txt): txtargs = dict(horizontalalignment='right', verticalalignment='top', #fontsize='smaller', #fontweight='ultralight', backgroundcolor=(0, 0, 0, .5), color=ORANGE) ax_relative_text(.98, .92, txt, **txtargs) def absolute_lbl(x_, y_, txt, roffset=(-.02, -.02), **kwargs): txtargs = dict(horizontalalignment='right', verticalalignment='top', backgroundcolor=(0, 0, 0, .5), color=ORANGE, **kwargs) ax_absolute_text(x_, y_, txt, roffset=roffset, **txtargs) def ax_relative_text(x, y, txt, ax=None, offset=None, **kwargs): if ax is None: ax = gca() xy, width, height = _axis_xy_width_height(ax) x_, y_ = ((xy[0]) + x * width, (xy[1] + height) - y * height) if offset is not None: xoff, yoff = offset x_ += xoff y_ += yoff ax_absolute_text(x_, y_, txt, ax=ax, **kwargs) def ax_absolute_text(x_, y_, txt, ax=None, roffset=None, **kwargs): if ax is None: ax = gca() if 'fontproperties' in kwargs: kwargs['fontproperties'] = FONTS.relative if roffset is not None: xroff, yroff = roffset xy, width, height = _axis_xy_width_height(ax) x_ += xroff * width y_ += yroff * height ax.text(x_, y_, txt, **kwargs) def fig_relative_text(x, y, txt, **kwargs): kwargs['horizontalalignment'] = 'center' kwargs['verticalalignment'] = 'center' fig = gcf() #xy, width, height = _axis_xy_width_height(ax) #x_, y_ = ((xy[0]+width)+x*width, (xy[1]+height)-y*height) fig.text(x, y, txt, **kwargs) def draw_text(text_str, rgb_textFG=(0, 0, 0), rgb_textBG=(1, 1, 1)): ax = gca() xy, width, height = _axis_xy_width_height(ax) text_x = xy[0] + (width / 2) text_y = xy[1] + (height / 2) ax.text(text_x, text_y, text_str, horizontalalignment='center', verticalalignment='center', color=rgb_textFG, backgroundcolor=rgb_textBG) def set_figtitle(figtitle, subtitle='', forcefignum=True, incanvas=True): if figtitle is None: figtitle = '' fig = gcf() if incanvas: if subtitle != '': subtitle = '\n' + subtitle fig.suptitle(figtitle + subtitle, fontsize=14, fontweight='bold') #fig.suptitle(figtitle, x=.5, y=.98, fontproperties=FONTS.figtitle) #fig_relative_text(.5, .96, subtitle, fontproperties=FONTS.subtitle) else: fig.suptitle('') window_figtitle = ('fig(%d) ' % fig.number) + figtitle fig.canvas.set_window_title(window_figtitle) def convert_keypress_event_mpl_to_qt4(mevent): global TMP_mevent TMP_mevent = mevent # Grab the key from the mpl.KeyPressEvent key = mevent.key print('[df2] convert event mpl -> qt4') print('[df2] key=%r' % key) # dicts modified from backend_qt4.py mpl2qtkey = {'control': Qt.Key_Control, 'shift': Qt.Key_Shift, 'alt': Qt.Key_Alt, 'super': Qt.Key_Meta, 'enter': Qt.Key_Return, 'left': Qt.Key_Left, 'up': Qt.Key_Up, 'right': Qt.Key_Right, 'down': Qt.Key_Down, 'escape': Qt.Key_Escape, 'f1': Qt.Key_F1, 'f2': Qt.Key_F2, 'f3': Qt.Key_F3, 'f4': Qt.Key_F4, 'f5': Qt.Key_F5, 'f6': Qt.Key_F6, 'f7': Qt.Key_F7, 'f8': Qt.Key_F8, 'f9': Qt.Key_F9, 'f10': Qt.Key_F10, 'f11': Qt.Key_F11, 'f12': Qt.Key_F12, 'home': Qt.Key_Home, 'end': Qt.Key_End, 'pageup': Qt.Key_PageUp, 'pagedown': Qt.Key_PageDown} # Reverse the control and super (aka cmd/apple) keys on OSX if sys.platform == 'darwin': mpl2qtkey.update({'super': Qt.Key_Control, 'control': Qt.Key_Meta, }) # Try to reconstruct QtGui.KeyEvent type_ = QtCore.QEvent.Type(QtCore.QEvent.KeyPress) # The type should always be KeyPress text = '' # Try to extract the original modifiers modifiers = QtCore.Qt.NoModifier # initialize to no modifiers if key.find(u'ctrl+') >= 0: modifiers = modifiers | QtCore.Qt.ControlModifier key = key.replace(u'ctrl+', u'') print('[df2] has ctrl modifier') text += 'Ctrl+' if key.find(u'alt+') >= 0: modifiers = modifiers | QtCore.Qt.AltModifier key = key.replace(u'alt+', u'') print('[df2] has alt modifier') text += 'Alt+' if key.find(u'super+') >= 0: modifiers = modifiers | QtCore.Qt.MetaModifier key = key.replace(u'super+', u'') print('[df2] has super modifier') text += 'Super+' if key.isupper(): modifiers = modifiers | QtCore.Qt.ShiftModifier print('[df2] has shift modifier') text += 'Shift+' # Try to extract the original key try: if key in mpl2qtkey: key_ = mpl2qtkey[key] else: key_ = ord(key.upper()) # Qt works with uppercase keys text += key.upper() except Exception as ex: print('[df2] ERROR key=%r' % key) print('[df2] ERROR %r' % ex) raise autorep = False # default false count = 1 # default 1 text = QtCore.QString(text) # The text is somewhat arbitrary # Create the QEvent print('----------------') print('[df2] Create event') print('[df2] type_ = %r' % type_) print('[df2] text = %r' % text) print('[df2] modifiers = %r' % modifiers) print('[df2] autorep = %r' % autorep) print('[df2] count = %r ' % count) print('----------------') qevent = QtGui.QKeyEvent(type_, key_, modifiers, text, autorep, count) return qevent def test_build_qkeyevent(): import draw_func2 as df2 qtwin = df2.QT4_WINS[0] # This reconstructs an test mplevent canvas = df2.figure(1).canvas mevent = matplotlib.backend_bases.KeyEvent('key_press_event', canvas, u'ctrl+p', x=672, y=230.0) qevent = df2.convert_keypress_event_mpl_to_qt4(mevent) app = qtwin.backend.app app.sendEvent(qtwin.ui, mevent) #type_ = QtCore.QEvent.Type(QtCore.QEvent.KeyPress) # The type should always be KeyPress #text = QtCore.QString('A') # The text is somewhat arbitrary #modifiers = QtCore.Qt.NoModifier # initialize to no modifiers #modifiers = modifiers | QtCore.Qt.ControlModifier #modifiers = modifiers | QtCore.Qt.AltModifier #key_ = ord('A') # Qt works with uppercase keys #autorep = False # default false #count = 1 # default 1 #qevent = QtGui.QKeyEvent(type_, key_, modifiers, text, autorep, count) return qevent # This actually doesn't matter def on_key_press_event(event): 'redirects keypress events to main window' global QT4_WINS print('[df2] %r' % event) print('[df2] %r' % str(event.__dict__)) for qtwin in QT4_WINS: qevent = convert_keypress_event_mpl_to_qt4(event) app = qtwin.backend.app print('[df2] attempting to send qevent to qtwin') app.sendEvent(qtwin, qevent) # TODO: FINISH ME #PyQt4.QtGui.QKeyEvent #qtwin.keyPressEvent(event) #fig.canvas.manager.window.keyPressEvent() def customize_figure(fig, docla): if not 'user_stat_list' in fig.__dict__.keys() or docla: fig.user_stat_list = [] fig.user_notes = [] # We dont need to catch keypress events because you just need to set it as # an application level shortcut # Catch key press events #key_event_cbid = fig.__dict__.get('key_event_cbid', None) #if key_event_cbid is not None: #fig.canvas.mpl_disconnect(key_event_cbid) #fig.key_event_cbid = fig.canvas.mpl_connect('key_press_event', on_key_press_event) fig.df2_closed = False def gcf(): if plotWidget is not None: #print('is plotwidget visible = %r' % plotWidget.isVisible()) fig = plotWidget.figure return fig return plt.gcf() def gca(): if plotWidget is not None: #print('is plotwidget visible = %r' % plotWidget.isVisible()) axes_list = plotWidget.figure.get_axes() current = 0 ax = axes_list[current] return ax return plt.gca() def cla(): return plt.cla() def clf(): return plt.clf() def get_fig(fnum=None): printDBG('[df2] get_fig(fnum=%r)' % fnum) fig_kwargs = dict(figsize=FIGSIZE, dpi=DPI) if plotWidget is not None: return gcf() if fnum is None: try: fig = gcf() except Exception as ex: printDBG('[df2] get_fig(): ex=%r' % ex) fig = plt.figure(**fig_kwargs) fnum = fig.number else: try: fig = plt.figure(fnum, **fig_kwargs) except Exception as ex: print(repr(ex)) warnings.warn(repr(ex)) fig = gcf() return fig def get_ax(fnum=None, pnum=None): figure(fnum=fnum, pnum=pnum) ax = gca() return ax def figure(fnum=None, docla=False, title=None, pnum=(1, 1, 1), figtitle=None, doclf=False, **kwargs): ''' fnum = fignum = figure number pnum = plotnum = plot tuple ''' #matplotlib.pyplot.xkcd() fig = get_fig(fnum) axes_list = fig.get_axes() # Ensure my customized settings customize_figure(fig, docla) # Convert pnum to tuple format if tools.is_int(pnum): nr = pnum // 100 nc = pnum // 10 - (nr * 10) px = pnum - (nr * 100) - (nc * 10) pnum = (nr, nc, px) if doclf: # a bit hacky. Need to rectify docla and doclf fig.clf() # Get the subplot if docla or len(axes_list) == 0: printDBG('[df2] *** NEW FIGURE %r.%r ***' % (fnum, pnum)) if not pnum is None: #ax = plt.subplot(*pnum) ax = fig.add_subplot(*pnum) ax.cla() else: ax = gca() else: printDBG('[df2] *** OLD FIGURE %r.%r ***' % (fnum, pnum)) if not pnum is None: ax = plt.subplot(*pnum) # fig.add_subplot fails here #ax = fig.add_subplot(*pnum) else: ax = gca() #ax = axes_list[0] # Set the title if not title is None: ax = gca() ax.set_title(title, fontproperties=FONTS.axtitle) # Add title to figure if figtitle is None and pnum == (1, 1, 1): figtitle = title if not figtitle is None: set_figtitle(figtitle, incanvas=False) return fig def plot_pdf(data, draw_support=True, scale_to=None, label=None, color=0, nYTicks=3): fig = gcf() ax = gca() data = np.array(data) if len(data) == 0: warnstr = '[df2] ! Warning: len(data) = 0. Cannot visualize pdf' warnings.warn(warnstr) draw_text(warnstr) return bw_factor = .05 if isinstance(color, (int, float)): colorx = color line_color = plt.get_cmap('gist_rainbow')(colorx) else: line_color = color # Estimate a pdf data_pdf = estimate_pdf(data, bw_factor) # Get probability of seen data prob_x = data_pdf(data) # Get probability of unseen data data x_data = np.linspace(0, data.max(), 500) y_data = data_pdf(x_data) # Scale if requested if not scale_to is None: scale_factor = scale_to / y_data.max() y_data *= scale_factor prob_x *= scale_factor #Plot the actual datas on near the bottom perterbed in Y if draw_support: pdfrange = prob_x.max() - prob_x.min() perb = (np.random.randn(len(data))) * pdfrange / 30. preb_y_data = np.abs([pdfrange / 50. for _ in data] + perb) ax.plot(data, preb_y_data, 'o', color=line_color, figure=fig, alpha=.1) # Plot the pdf (unseen data) ax.plot(x_data, y_data, color=line_color, label=label) if nYTicks is not None: yticks = np.linspace(min(y_data), max(y_data), nYTicks) ax.set_yticks(yticks) def estimate_pdf(data, bw_factor): try: data_pdf = scipy.stats.gaussian_kde(data, bw_factor) data_pdf.covariance_factor = bw_factor except Exception as ex: print('[df2] ! Exception while estimating kernel density') print('[df2] data=%r' % (data,)) print('[df2] ex=%r' % (ex,)) raise return data_pdf def show_histogram(data, bins=None, **kwargs): print('[df2] show_histogram()') dmin = int(np.floor(data.min())) dmax = int(np.ceil(data.max())) if bins is None: bins = dmax - dmin fig = figure(**kwargs) ax = gca() ax.hist(data, bins=bins, range=(dmin, dmax)) #help(np.bincount) fig.show() def show_signature(sig, **kwargs): fig = figure(**kwargs) plt.plot(sig) fig.show() def plot_stems(x_data=None, y_data=None): if y_data is not None and x_data is None: x_data = np.arange(len(y_data)) pass if len(x_data) != len(y_data): print('[df2] WARNING plot_stems(): len(x_data)!=len(y_data)') if len(x_data) == 0: print('[df2] WARNING plot_stems(): len(x_data)=len(y_data)=0') x_data_ = np.array(x_data) y_data_ = np.array(y_data) x_data_sort = x_data_[y_data_.argsort()[::-1]] y_data_sort = y_data_[y_data_.argsort()[::-1]] markerline, stemlines, baseline = pylab.stem(x_data_sort, y_data_sort, linefmt='-') pylab.setp(markerline, 'markerfacecolor', 'b') pylab.setp(baseline, 'linewidth', 0) ax = gca() ax.set_xlim(min(x_data) - 1, max(x_data) + 1) ax.set_ylim(min(y_data) - 1, max(max(y_data), max(x_data)) + 1) def plot_sift_signature(sift, title='', fnum=None, pnum=None): figure(fnum=fnum, pnum=pnum) ax = gca() plot_bars(sift, 16) ax.set_xlim(0, 128) ax.set_ylim(0, 256) space_xticks(9, 16) space_yticks(5, 64) ax.set_title(title) dark_background(ax) return ax def dark_background(ax=None, doubleit=False): if ax is None: ax = gca() xy, width, height = _axis_xy_width_height(ax) if doubleit: halfw = (doubleit) * (width / 2) halfh = (doubleit) * (height / 2) xy = (xy[0] - halfw, xy[1] - halfh) width *= (doubleit + 1) height *= (doubleit + 1) rect = matplotlib.patches.Rectangle(xy, width, height, lw=0, zorder=0) rect.set_clip_on(True) rect.set_fill(True) rect.set_color(BLACK * .9) rect = ax.add_patch(rect) def space_xticks(nTicks=9, spacing=16, ax=None): if ax is None: ax = gca() ax.set_xticks(np.arange(nTicks) * spacing) small_xticks(ax) def space_yticks(nTicks=9, spacing=32, ax=None): if ax is None: ax = gca() ax.set_yticks(np.arange(nTicks) * spacing) small_yticks(ax) def small_xticks(ax=None): for tick in ax.xaxis.get_major_ticks(): tick.label.set_fontsize(8) def small_yticks(ax=None): for tick in ax.yaxis.get_major_ticks(): tick.label.set_fontsize(8) def plot_bars(y_data, nColorSplits=1): width = 1 nDims = len(y_data) nGroup = nDims // nColorSplits ori_colors = distinct_colors(nColorSplits) x_data = np.arange(nDims) ax = gca() for ix in xrange(nColorSplits): xs = np.arange(nGroup) + (nGroup * ix) color = ori_colors[ix] x_dat = x_data[xs] y_dat = y_data[xs] ax.bar(x_dat, y_dat, width, color=color, edgecolor=np.array(color) * .8) def phantom_legend_label(label, color, loc='upper right'): 'adds a legend label without displaying an actor' pass #phantom_actor = plt.Circle((0, 0), 1, fc=color, prop=FONTS.legend, loc=loc) #plt.legend(phant_actor, label, framealpha=.2) #plt.legend(*zip(*legend_tups), framealpha=.2) #legend_tups = [] #legend_tups.append((phantom_actor, label)) def legend(loc='upper right'): ax = gca() ax.legend(prop=FONTS.legend, loc=loc) def plot_histpdf(data, label=None, draw_support=False, nbins=10): freq, _ = plot_hist(data, nbins=nbins) plot_pdf(data, draw_support=draw_support, scale_to=freq.max(), label=label) def plot_hist(data, bins=None, nbins=10, weights=None): if isinstance(data, list): data = np.array(data) if bins is None: dmin = data.min() dmax = data.max() bins = dmax - dmin ax = gca() freq, bins_, patches = ax.hist(data, bins=nbins, weights=weights, range=(dmin, dmax)) return freq, bins_ def variation_trunctate(data): ax = gca() data = np.array(data) if len(data) == 0: warnstr = '[df2] ! Warning: len(data) = 0. Cannot variation_truncate' warnings.warn(warnstr) return trunc_max = data.mean() + data.std() * 2 trunc_min = np.floor(data.min()) ax.set_xlim(trunc_min, trunc_max) #trunc_xticks = np.linspace(0, int(trunc_max),11) #trunc_xticks = trunc_xticks[trunc_xticks >= trunc_min] #trunc_xticks = np.append([int(trunc_min)], trunc_xticks) #no_zero_yticks = ax.get_yticks()[ax.get_yticks() > 0] #ax.set_xticks(trunc_xticks) #ax.set_yticks(no_zero_yticks) #_----------------- HELPERS ^^^ --------- # ---- IMAGE CREATION FUNCTIONS ---- @tools.debug_exception def draw_sift(desc, kp=None): # TODO: There might be a divide by zero warning in here. ''' desc = np.random.rand(128) desc = desc / np.sqrt((desc**2).sum()) desc = np.round(desc * 255) ''' # This is draw, because it is an overlay ax = gca() tau = 2 * np.pi DSCALE = .25 XYSCALE = .5 XYSHIFT = -.75 ORI_SHIFT = 0 # -tau #1/8 * tau # SIFT CONSTANTS NORIENTS = 8 NX = 4 NY = 4 NBINS = NX * NY def cirlce_rad2xy(radians, mag): return np.cos(radians) * mag, np.sin(radians) * mag discrete_ori = (np.arange(0, NORIENTS) * (tau / NORIENTS) + ORI_SHIFT) # Build list of plot positions # Build an "arm" for each sift measurement arm_mag = desc / 255.0 arm_ori = np.tile(discrete_ori, (NBINS, 1)).flatten() # The offset x,y's for each sift measurment arm_dxy = np.array(zip(*cirlce_rad2xy(arm_ori, arm_mag))) yxt_gen = itertools.product(xrange(NY), xrange(NX), xrange(NORIENTS)) yx_gen = itertools.product(xrange(NY), xrange(NX)) # Transform the drawing of the SIFT descriptor to the its elliptical patch axTrans = ax.transData kpTrans = None if kp is None: kp = [0, 0, 1, 0, 1] kp = np.array(kp) kpT = kp.T x, y, a, c, d = kpT[:, 0] kpTrans = Affine2D([( a, 0, x), ( c, d, y), ( 0, 0, 1)]) axTrans = ax.transData # Draw 8 directional arms in each of the 4x4 grid cells arrow_patches = [] arrow_patches2 = [] for y, x, t in yxt_gen: index = y * NX * NORIENTS + x * NORIENTS + t (dx, dy) = arm_dxy[index] arw_x = x * XYSCALE + XYSHIFT arw_y = y * XYSCALE + XYSHIFT arw_dy = dy * DSCALE * 1.5 # scale for viz Hack arw_dx = dx * DSCALE * 1.5 #posA = (arw_x, arw_y) #posB = (arw_x+arw_dx, arw_y+arw_dy) _args = [arw_x, arw_y, arw_dx, arw_dy] _kwargs = dict(head_width=.0001, transform=kpTrans, length_includes_head=False) arrow_patches += [FancyArrow(*_args, **_kwargs)] arrow_patches2 += [FancyArrow(*_args, **_kwargs)] # Draw circles around each of the 4x4 grid cells circle_patches = [] for y, x in yx_gen: circ_xy = (x * XYSCALE + XYSHIFT, y * XYSCALE + XYSHIFT) circ_radius = DSCALE circle_patches += [Circle(circ_xy, circ_radius, transform=kpTrans)] # Efficiently draw many patches with PatchCollections circ_collection = PatchCollection(circle_patches) circ_collection.set_facecolor('none') circ_collection.set_transform(axTrans) circ_collection.set_edgecolor(BLACK) circ_collection.set_alpha(.5) # Body of arrows arw_collection = PatchCollection(arrow_patches) arw_collection.set_transform(axTrans) arw_collection.set_linewidth(.5) arw_collection.set_color(RED) arw_collection.set_alpha(1) # Border of arrows arw_collection2 = matplotlib.collections.PatchCollection(arrow_patches2) arw_collection2.set_transform(axTrans) arw_collection2.set_linewidth(1) arw_collection2.set_color(BLACK) arw_collection2.set_alpha(1) # Add artists to axes ax.add_collection(circ_collection) ax.add_collection(arw_collection2) ax.add_collection(arw_collection) def feat_scores_to_color(fs, cmap_='hot'): assert len(fs.shape) == 1, 'score must be 1d' cmap = plt.get_cmap(cmap_) mins = fs.min() rnge = fs.max() - mins if rnge == 0: return [cmap(.5) for fx in xrange(len(fs))] score2_01 = lambda score: .1 + .9 * (float(score) - mins) / (rnge) colors = [cmap(score2_01(score)) for score in fs] return colors def colorbar(scalars, colors): 'adds a color bar next to the axes' orientation = ['vertical', 'horizontal'][0] TICK_FONTSIZE = 8 # Put colors and scalars in correct order sorted_scalars = sorted(scalars) sorted_colors = [x for (y, x) in sorted(zip(scalars, colors))] # Make a listed colormap and mappable object listed_cmap = mpl.colors.ListedColormap(sorted_colors) sm = plt.cm.ScalarMappable(cmap=listed_cmap) sm.set_array(sorted_scalars) # Use mapable object to create the colorbar cb = plt.colorbar(sm, orientation=orientation) # Add the colorbar to the correct label axis = cb.ax.xaxis if orientation == 'horizontal' else cb.ax.yaxis position = 'bottom' if orientation == 'horizontal' else 'right' axis.set_ticks_position(position) axis.set_ticks([0, .5, 1]) cb.ax.tick_params(labelsize=TICK_FONTSIZE) def draw_lines2(kpts1, kpts2, fm=None, fs=None, kpts2_offset=(0, 0), color_list=None, **kwargs): if not DISTINCT_COLORS: color_list = None # input data if not SHOW_LINES: return if fm is None: # assume kpts are in director correspondence assert kpts1.shape == kpts2.shape if len(fm) == 0: return ax = gca() woff, hoff = kpts2_offset # Draw line collection kpts1_m = kpts1[fm[:, 0]].T kpts2_m = kpts2[fm[:, 1]].T xxyy_iter = iter(zip(kpts1_m[0], kpts2_m[0] + woff, kpts1_m[1], kpts2_m[1] + hoff)) if color_list is None: if fs is None: # Draw with solid color color_list = [ LINE_COLOR for fx in xrange(len(fm))] else: # Draw with colors proportional to score difference color_list = feat_scores_to_color(fs) segments = [((x1, y1), (x2, y2)) for (x1, x2, y1, y2) in xxyy_iter] linewidth = [LINE_WIDTH for fx in xrange(len(fm))] line_alpha = LINE_ALPHA if LINE_ALPHA_OVERRIDE is not None: line_alpha = LINE_ALPHA_OVERRIDE line_group = LineCollection(segments, linewidth, color_list, alpha=line_alpha) #plt.colorbar(line_group, ax=ax) ax.add_collection(line_group) #figure(100) #plt.hexbin(x,y, cmap=plt.cm.YlOrRd_r) def draw_kpts(kpts, *args, **kwargs): draw_kpts2(kpts, *args, **kwargs) def draw_kpts2(kpts, offset=(0, 0), ell=SHOW_ELLS, pts=False, pts_color=ORANGE, pts_size=POINT_SIZE, ell_alpha=ELL_ALPHA, ell_linewidth=ELL_LINEWIDTH, ell_color=ELL_COLOR, color_list=None, rect=None, arrow=False, **kwargs): if not DISTINCT_COLORS: color_list = None printDBG('drawkpts2: Drawing Keypoints! ell=%r pts=%r' % (ell, pts)) # get matplotlib info ax = gca() pltTrans = ax.transData ell_actors = [] # data kpts = np.array(kpts) kptsT = kpts.T x = kptsT[0, :] + offset[0] y = kptsT[1, :] + offset[1] printDBG('[df2] draw_kpts()----------') printDBG('[df2] draw_kpts() ell=%r pts=%r' % (ell, pts)) printDBG('[df2] draw_kpts() drawing kpts.shape=%r' % (kpts.shape,)) if rect is None: rect = ell rect = False if pts is True: rect = False if ell or rect: printDBG('[df2] draw_kpts() drawing ell kptsT.shape=%r' % (kptsT.shape,)) # We have the transformation from unit circle to ellipse here. (inv(A)) a = kptsT[2] b = np.zeros(len(a)) c = kptsT[3] d = kptsT[4] kpts_iter = izip(x, y, a, b, c, d) aff_list = [Affine2D([( a_, b_, x_), ( c_, d_, y_), ( 0, 0, 1)]) for (x_, y_, a_, b_, c_, d_) in kpts_iter] patch_list = [] ell_actors = [Circle( (0, 0), 1, transform=aff) for aff in aff_list] if ell: patch_list += ell_actors if rect: rect_actors = [Rectangle( (-1, -1), 2, 2, transform=aff) for aff in aff_list] patch_list += rect_actors if arrow: _kwargs = dict(head_width=.01, length_includes_head=False) arrow_actors1 = [FancyArrow(0, 0, 0, 1, transform=aff, **_kwargs) for aff in aff_list] arrow_actors2 = [FancyArrow(0, 0, 1, 0, transform=aff, **_kwargs) for aff in aff_list] patch_list += arrow_actors1 patch_list += arrow_actors2 ellipse_collection = matplotlib.collections.PatchCollection(patch_list) ellipse_collection.set_facecolor('none') ellipse_collection.set_transform(pltTrans) if ELL_ALPHA_OVERRIDE is not None: ell_alpha = ELL_ALPHA_OVERRIDE ellipse_collection.set_alpha(ell_alpha) ellipse_collection.set_linewidth(ell_linewidth) if not color_list is None: ell_color = color_list if ell_color == 'distinct': ell_color = distinct_colors(len(kpts)) ellipse_collection.set_edgecolor(ell_color) ax.add_collection(ellipse_collection) if pts: printDBG('[df2] draw_kpts() drawing pts x.shape=%r y.shape=%r' % (x.shape, y.shape)) if color_list is None: color_list = [pts_color for _ in xrange(len(x))] ax.autoscale(enable=False) ax.scatter(x, y, c=color_list, s=2 * pts_size, marker='o', edgecolor='none') #ax.autoscale(enable=False) #ax.plot(x, y, linestyle='None', marker='o', markerfacecolor=pts_color, markersize=pts_size, markeredgewidth=0) # ---- CHIP DISPLAY COMMANDS ---- def imshow(img, fnum=None, title=None, figtitle=None, pnum=None, interpolation='nearest', **kwargs): 'other interpolations = nearest, bicubic, bilinear' #printDBG('[df2] ----- IMSHOW ------ ') #printDBG('[***df2.imshow] fnum=%r pnum=%r title=%r *** ' % (fnum, pnum, title)) #printDBG('[***df2.imshow] img.shape = %r ' % (img.shape,)) #printDBG('[***df2.imshow] img.stats = %r ' % (helpers.printable_mystats(img),)) fig = figure(fnum=fnum, pnum=pnum, title=title, figtitle=figtitle, **kwargs) ax = gca() if not DARKEN is None: imgdtype = img.dtype img = np.array(img, dtype=float) * DARKEN img = np.array(img, dtype=imgdtype) plt_imshow_kwargs = { 'interpolation': interpolation, #'cmap': plt.get_cmap('gray'), 'vmin': 0, 'vmax': 255, } try: if len(img.shape) == 3 and img.shape[2] == 3: # img is in a color format imgBGR = img if imgBGR.dtype == np.float64: if imgBGR.max() <= 1: imgBGR = np.array(imgBGR, dtype=np.float32) else: imgBGR = np.array(imgBGR, dtype=np.uint8) imgRGB = cv2.cvtColor(imgBGR, cv2.COLOR_BGR2RGB) ax.imshow(imgRGB, **plt_imshow_kwargs) elif len(img.shape) == 2: # img is in grayscale imgGRAY = img ax.imshow(imgGRAY, cmap=plt.get_cmap('gray'), **plt_imshow_kwargs) else: raise Exception('unknown image format') except TypeError as te: print('[df2] imshow ERROR %r' % te) raise except Exception as ex: print('[df2] img.dtype = %r' % (img.dtype,)) print('[df2] type(img) = %r' % (type(img),)) print('[df2] img.shape = %r' % (img.shape,)) print('[df2] imshow ERROR %r' % ex) raise #plt.set_cmap('gray') ax.set_xticks([]) ax.set_yticks([]) #ax.set_autoscale(False) #try: #if pnum == 111: #fig.tight_layout() #except Exception as ex: #print('[df2] !! Exception durring fig.tight_layout: '+repr(ex)) #raise return fig, ax def get_num_channels(img): ndims = len(img.shape) if ndims == 2: nChannels = 1 elif ndims == 3 and img.shape[2] == 3: nChannels = 3 elif ndims == 3 and img.shape[2] == 1: nChannels = 1 else: raise Exception('Cannot determine number of channels') return nChannels def stack_images(img1, img2, vert=None): nChannels = get_num_channels(img1) nChannels2 = get_num_channels(img2) assert nChannels == nChannels2 (h1, w1) = img1.shape[0: 2] # get chip dimensions (h2, w2) = img2.shape[0: 2] woff, hoff = 0, 0 vert_wh = max(w1, w2), h1 + h2 horiz_wh = w1 + w2, max(h1, h2) if vert is None: # Display the orientation with the better (closer to 1) aspect ratio vert_ar = max(vert_wh) / min(vert_wh) horiz_ar = max(horiz_wh) / min(horiz_wh) vert = vert_ar < horiz_ar if vert: wB, hB = vert_wh hoff = h1 else: wB, hB = horiz_wh woff = w1 # concatentate images if nChannels == 3: imgB = np.zeros((hB, wB, 3), np.uint8) imgB[0:h1, 0:w1, :] = img1 imgB[hoff:(hoff + h2), woff:(woff + w2), :] = img2 elif nChannels == 1: imgB = np.zeros((hB, wB), np.uint8) imgB[0:h1, 0:w1] = img1 imgB[hoff:(hoff + h2), woff:(woff + w2)] = img2 return imgB, woff, hoff def show_chipmatch2(rchip1, rchip2, kpts1, kpts2, fm=None, fs=None, title=None, vert=None, fnum=None, pnum=None, **kwargs): '''Draws two chips and the feature matches between them. feature matches kpts1 and kpts2 use the (x,y,a,c,d) ''' printDBG('[df2] draw_matches2() fnum=%r, pnum=%r' % (fnum, pnum)) # get matching keypoints + offset (h1, w1) = rchip1.shape[0:2] # get chip (h, w) dimensions (h2, w2) = rchip2.shape[0:2] # Stack the compared chips match_img, woff, hoff = stack_images(rchip1, rchip2, vert) xywh1 = (0, 0, w1, h1) xywh2 = (woff, hoff, w2, h2) # Show the stacked chips fig, ax = imshow(match_img, title=title, fnum=fnum, pnum=pnum) # Overlay feature match nnotations draw_fmatch(xywh1, xywh2, kpts1, kpts2, fm, fs, **kwargs) return ax, xywh1, xywh2 # draw feature match def draw_fmatch(xywh1, xywh2, kpts1, kpts2, fm, fs=None, lbl1=None, lbl2=None, fnum=None, pnum=None, rect=False, colorbar_=True, **kwargs): '''Draws the matching features. This is draw because it is an overlay xywh1 - location of rchip1 in the axes xywh2 - location or rchip2 in the axes ''' if fm is None: assert kpts1.shape == kpts2.shape, 'shapes different or fm not none' fm = np.tile(np.arange(0, len(kpts1)), (2, 1)).T pts = kwargs.get('draw_pts', False) ell = kwargs.get('draw_ell', True) lines = kwargs.get('draw_lines', True) ell_alpha = kwargs.get('ell_alpha', .4) nMatch = len(fm) #printDBG('[df2.draw_fnmatch] nMatch=%r' % nMatch) x1, y1, w1, h1 = xywh1 x2, y2, w2, h2 = xywh2 offset2 = (x2, y2) # Custom user label for chips 1 and 2 if lbl1 is not None: absolute_lbl(x1 + w1, y1, lbl1) if lbl2 is not None: absolute_lbl(x2 + w2, y2, lbl2) # Plot the number of matches if kwargs.get('show_nMatches', False): upperleft_text('#match=%d' % nMatch) # Draw all keypoints in both chips as points if kwargs.get('all_kpts', False): all_args = dict(ell=False, pts=pts, pts_color=GREEN, pts_size=2, ell_alpha=ell_alpha, rect=rect) all_args.update(kwargs) draw_kpts2(kpts1, **all_args) draw_kpts2(kpts2, offset=offset2, **all_args) # Draw Lines and Ellipses and Points oh my if nMatch > 0: colors = [kwargs['colors']] * nMatch if 'colors' in kwargs else distinct_colors(nMatch) if fs is not None: colors = feat_scores_to_color(fs, 'hot') acols = add_alpha(colors) # Helper functions def _drawkpts(**_kwargs): _kwargs.update(kwargs) fxs1 = fm[:, 0] fxs2 = fm[:, 1] draw_kpts2(kpts1[fxs1], rect=rect, **_kwargs) draw_kpts2(kpts2[fxs2], offset=offset2, rect=rect, **_kwargs) def _drawlines(**_kwargs): _kwargs.update(kwargs) draw_lines2(kpts1, kpts2, fm, fs, kpts2_offset=offset2, **_kwargs) # User helpers if ell: _drawkpts(pts=False, ell=True, color_list=colors) if pts: _drawkpts(pts_size=8, pts=True, ell=False, pts_color=BLACK) _drawkpts(pts_size=6, pts=True, ell=False, color_list=acols) if lines: _drawlines(color_list=colors) else: draw_boxedX(xywh2) if fs is not None and colorbar_ and 'colors' in vars() and colors is not None: colorbar(fs, colors) #legend() return None def draw_boxedX(xywh, color=RED, lw=2, alpha=.5, theta=0): 'draws a big red x. redx' ax = gca() x1, y1, w, h = xywh x2, y2 = x1 + w, y1 + h segments = [((x1, y1), (x2, y2)), ((x1, y2), (x2, y1))] trans = Affine2D() trans.rotate(theta) trans = trans + ax.transData width_list = [lw] * len(segments) color_list = [color] * len(segments) line_group = LineCollection(segments, width_list, color_list, alpha=alpha, transOffset=trans) ax.add_collection(line_group) def disconnect_callback(fig, callback_type, **kwargs): #print('[df2] disconnect %r callback' % callback_type) axes = kwargs.get('axes', []) for ax in axes: ax._hs_viewtype = '' cbid_type = callback_type + '_cbid' cbfn_type = callback_type + '_func' cbid = fig.__dict__.get(cbid_type, None) cbfn = fig.__dict__.get(cbfn_type, None) if cbid is not None: fig.canvas.mpl_disconnect(cbid) else: cbfn = None fig.__dict__[cbid_type] = None return cbid, cbfn def connect_callback(fig, callback_type, callback_fn): #print('[df2] register %r callback' % callback_type) if callback_fn is None: return cbid_type = callback_type + '_cbid' cbfn_type = callback_type + '_func' fig.__dict__[cbid_type] = fig.canvas.mpl_connect(callback_type, callback_fn) fig.__dict__[cbfn_type] = callback_fn </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">apache-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-1,678,968,028,501,710,800</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">31.697605</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">119</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.588353</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.052776</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45161"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">silas/rock</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">rock/text.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1235</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">from __future__ import unicode_literals def _(text): return text.strip('\n') USAGE = _(""" Usage: rock [--help] [--env=ENV] [--path=PATH] [--runtime=RUNTIME] command """) HELP = _(""" --help show help message --verbose show script while running --dry-run show script without running --version show version project: --env=ENV set env --path=PATH set path --runtime=RUNTIME set runtime commands: build run build test run tests run run in environment clean clean project files other commands: config show project configuration env show evaluable environment variables init generates project skeleton runtime show installed runtimes """) CONFIG_USAGE = _(""" Usage: rock config [--format=FORMAT] """) CONFIG_HELP = _(""" --help show help message --format set output format (json, yaml) """) ENV_USAGE = _(""" Usage: rock env """) ENV_HELP = _(""" --help show help message """) RUNTIME_USAGE = _(""" Usage: rock runtime """) RUNTIME_HELP = _(""" --help show help message """) </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">5,519,456,527,590,050,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">20.293103</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">74</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.545749</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">4.116667</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45162"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">setsid/yacron</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">yacron/time.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">5052</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">""" This file is part of yacron. Copyright (C) 2016 Vadim Kuznetsov <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="57213e3a2224382117303a363e3b7934383a">[email protected]</a>> yacron is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. yacron is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with yacron. If not, see <http://www.gnu.org/licenses/>. """ class CronTime(object): """ Parse and store scheduled time. """ def __init__(self, minutes, hours, weekdays): """ Parse and store the minutes, hours and weekdays values. :param minutes: Minutes (str) :param hours: Hours (str) :param weekdays: Weekdays (str) :raise ValueError if any of the values is invalid """ self._minutes = self._parse_value(0, minutes, 59) self._hours = self._parse_value(0, hours, 23) # slashes are unacceptable in weekdays value self._weekdays = self._parse_value(1, weekdays, 7, slash_acceptable=False) @property def minutes(self): return self._minutes @property def hours(self): return self._hours @property def weekdays(self): return self._weekdays def _check_value_range(self, min_value, value, max_value): """ Check is value in range. :param min_value: Minimal valid value :param value: Value :param max_value: Maximum valid value :return True if the value is in range :raise ValueError if the value is out of range """ if not (min_value <= value <= max_value): raise ValueError("invalid value '{0:d}', must be in [{1:d}..{2:d}]".format(value, min_value, max_value)) return True def _check_special_chars(self, value): """ Check special characters in the value: 1) value can not contains more than one '*' or '/' or '-' characters; 2) special characters can not be mixed (there can be the only one except ','); :param value: Value. :raise ValueError if any invalid sequence of special characters found in the value. """ all_count = value.count('*') slash_count = value.count('/') comma_count = value.count(',') hyphen_count = value.count('-') is_invalid = any(( all_count > 1, slash_count > 1, hyphen_count > 1, all_count and (slash_count or comma_count or hyphen_count), slash_count and (all_count or comma_count or hyphen_count), comma_count and (all_count or slash_count or hyphen_count), hyphen_count and (all_count or slash_count or comma_count), )) if is_invalid: raise ValueError("invalid format in value '{0:s}'".format(value)) def _parse_value(self, min_value, value, max_value, slash_acceptable=True): """ Parse and check a value. :param min_value: Minimal valid value :param value: Value :param max_value: Maximum valid value :param slash_acceptable: Slash is valid in the value :return: List of values. :raise ValueError if parsing failed """ self._check_special_chars(value) if value == '*': return list(range(min_value, max_value + 1)) if value.startswith('/'): if not slash_acceptable: raise ValueError("value '{0:s}' can not contains slash".format(value)) divisor = int(value[1:]) self._check_value_range(min_value, divisor, max_value) return [n for n in range(min_value, max_value + 1) if n % divisor == 0] if '-' in value: start_value, stop_value = map(int, value.split('-')) self._check_value_range(min_value, start_value, max_value) self._check_value_range(min_value, stop_value, max_value) if start_value >= stop_value: raise ValueError("start value can not be greater or equal to stop value") return list(range(start_value, stop_value + 1)) if ',' in value: return [n for n in map(int, value.split(',')) if self._check_value_range(min_value, n, max_value)] return [int(value)] def check_time(self, cur_time): """ Compare parsed time and current time. :param cur_time: Current time (datetime). :return: True if current time matches with parser time and False otherwise """ return all(( cur_time.minute in self._minutes, cur_time.hour in self._hours, cur_time.isoweekday() in self._weekdays, )) </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-3.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">7,801,523,714,869,108,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">35.345324</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">116</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.598773</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">4.103981</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45163"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">UCSC-iGEM-2016/taris_controller</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">taris_controller/taris_sensor.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">9944</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">#!/usr/bin/python from __future__ import print_function import io # used to create file streams import fcntl # used to access I2C parameters like addresses import sys import time # used for sleep delay and timestamps class Taris_Sensor(): ''' This object holds all required interface data for the Atlas Scientific \ EZO pH and RTD sensors. Built off of the base library, with new functions \ added for calibration and additional testing. ''' def __init__(self, address, bus): # open two file streams, one for reading and one for writing # the specific I2C channel is selected with bus # it is usually 1, except for older revisions where it's 0 # wb and rb indicate binary read and write self.file_read = io.open("/dev/i2c-"+str(bus), "rb", buffering=0) self.file_write = io.open("/dev/i2c-"+str(bus), "wb", buffering=0) # initializes I2C to either a user specified or default address self.set_i2c_address(address) self.cal_timeout = 1.6 # timeout for calibrations self.read_timeout = 1.0 # timeout for reads self.short_timeout = 0.3 # timeout for regular commands # Set if testing board self.DEBUG = True def set_i2c_address(self, addr): '''Set the I2C communications to the slave specified by the address. \ The commands for I2C dev using the ioctl functions are specified in \ the i2c-dev.h file from i2c-tools''' I2C_SLAVE = 0x703 fcntl.ioctl(self.file_read, I2C_SLAVE, addr) fcntl.ioctl(self.file_write, I2C_SLAVE, addr) def write(self, cmd): '''Writes a command to the sensor.''' # appends the null character and sends the string over I2C cmd += "\00" self.file_write.write(cmd) def read(self, num_of_bytes=31,startbit=1): '''Reads data from the sensor and parses the incoming response.''' # reads a specified number of bytes from I2C, then parses and displays the result res = self.file_read.read(num_of_bytes) # read from the board response = filter(lambda x: x != '\x00', res) # remove the null characters to get the response if ord(response[0]) == 1: # if the response isn't an error # change MSB to 0 for all received characters except the first and get a list of characters char_list = map(lambda x: chr(ord(x) & ~0x80), list(response[startbit:])) # NOTE: having to change the MSB to 0 is a glitch in the raspberry pi, and you shouldn't have to do this! return ''.join(char_list) # convert the char list to a string and returns it else: return "Error " + str(ord(response[0])) def query(self, string, start=1): '''For commands that require a write, a wait, and a response. For instance, \ calibration requires writing an initial CAL command, waiting 300ms, \ then checking for a pass/fail indicator message.''' # write a command to the board, wait the correct timeout, and read the response self.write(string) # the read and calibration commands require a longer timeout if string.upper().startswith("R"): time.sleep(self.read_timeout) elif string.upper().startswith("CAL"): time.sleep(self.cal_timeout) else: time.sleep(self.short_timeout) return self.read(startbit=start) def verify(self): '''Verifies that the sensor is connected, also returns firmware version.''' device_ID = self.query("I") if device_ID.startswith("?I"): print("Connected sensor: " + str(device_ID)[3:]) else: raw_input("EZO not connected: " + device_ID) def close(self): '''Closes the sensor's filestream, not usually required.''' self.file_read.close() self.file_write.close() def getData(self): '''Gets data from sensor reading as a float.''' data = self.query("R") return float(data) def cal_wait(self, cal_time): '''UI for waiting for pH sensor to stabilize during calibration''' x=1 if self.DEBUG == True: cal_time = 4 while x<cal_time: if x==1: sys.stdout.write("Please wait for sensor to stabilize:") else: sys.stdout.write(".") sys.stdout.flush() time.sleep(1) x+=1 print('\n') def pH_calibrateSensor(self): '''Performs pH sensor calibration using included buffers.''' # Clear previous calibration data print("Starting pH sensor calibration...") q = self.query("Cal,clear", 0) if str(ord(q)) != '1': print("Calibration failed with response " + str(q)) time.sleep(2) return False # Midpoint calibration. This will also reset previous data. raw_input("Please rinse probe. Press [Enter] when pH 7 buffer is loaded.") self.cal_wait(60) mid_pH = "7.00" q = self.query("CAL,MID," + mid_pH, 0) if str(ord(q)) != '1': print("Calibration failed with response " + str(q)) time.sleep(2) return False # Lowpoint calibration raw_input("Please rinse probe. Press [Enter] when pH 4 buffer is loaded.") self.cal_wait(60) low_pH = "4.00" q = self.query("CAL,LOW," + low_pH, 0) if str(ord(q)) != '1': print("Calibration failed with response " + str(q)) time.sleep(2) return False # Highpoint calibration raw_input("Please rinse probe. Press [Enter] when pH 10 buffer is loaded.") self.cal_wait(60) high_pH = "10.00" q = self.query("CAL,HIGH," + high_pH, 0) if str(ord(q)) != '1': print("Calibration failed with response " + str(q)) time.sleep(2) return False q = str(self.query("Cal,?")) # Check that 3-point calibration is complete, otherwise return ERROR if q != "?CAL,3": print("Three point calibration incomplete!" + str(q)) cal_response = raw_input("Enter 'R' to retry or Enter to exit.") if cal_response == "R" or cal_response == "r": self.pH_calibrateSensor() else: return False print("Three point pH calibration complete!") time.sleep(1) return True def temp_calibrateSensor(self): '''Calibrates the temperature sensor. Requires an external thermometer.''' print("Clearing previous temperature calibration.") q = str(ord(self.query("Cal,clear\0x0d", 0))) if q == "1": cal_temp = raw_input("Enter room temperature\n>>") self.cal_wait(5) q = str(ord(self.query("Cal,"+str(cal_temp) + "\0x0d", 0))) if q == "1": q = str(self.query("Cal,?")) if q == "?CAL,1": print("One point temperature calibration complete!") return True elif q == "?CAL,0": print("One point temperature calibration incomplete!") cal_response = raw_input("Enter R to retry or Enter to exit.") if cal_response == "R" or cal_response == "r": self.temp_calibrateSensor() else: return False else: print("Error setting new calibration temperature: " + str(q)) time.sleep(1) return False else: print("Could not set new calibration temperature: " + str(q)) time.sleep(1) return False else: print("Could not clear RTD sensor: " + str(q)) time.sleep(1) return False return False def pH_compensateTemp(self,temp): '''Compensates the pH sensor for temperature, is used in conjunction with \ a reading from the RTD sensor.''' comp_status = self.query("T," + str(temp),0) if str(ord(comp_status)) != '1': print("Temperature compensation failed!: ") time.sleep(2) return False else: comp_status = str(self.query("T,?")) print("Temperature compensation set for: " + comp_status[3:] + u'\xb0' + "C") time.sleep(2) return False def lockProtocol(self,command): '''Not currently working. Normally used for locking some of the \ internal parameters (e.g. baud rate for UART mode).''' read_bytes = 9 print("1.\tDisconnect power to device and any signal wires.\n\ 2.\tShort PRB to TX.\n\ 3.\tTurn device on and wait for LED to change to blue.\n\ 4.\tRemove short from PRB to TX, then restart device.\n\ 5.\tConnect data lines to Raspberry Pi I2C pins.") raw_input("Press Enter when this is complete.") raw_input("Press Enter to prevent further changes to device configuration.") command_message = "PLOCK," + str(command) self.sensorQ(command_message) time.sleep(0.3) lock_status = self.sensorRead(read_bytes) if lock_status == "?PLOCK,1": print("Sensor settings locked.") return_code = 1 elif lock_status == "?PLOCK,0": print("Sensor settings unlocked.") return_code = 0 else: print("False locking sensor settings.") return False return return_code </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-3.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">2,327,405,068,719,227,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">38.776</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">117</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.559433</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">4.107394</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45164"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">lezizi/A-Framework</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">python/local-source/source.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">2324</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">#!/usr/bin/env python # # Copyright (C) 2012 LeZiZi Studio # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class SourceHandler(): ''' Provides basic source handling. Property: source: source object ''' from base import Source def __init__(self, source=None): if source is None: self.source = self.Source() else: self.source = source def append(self,action): ''' Append an Action to current source. Argument: action: An Action. Return: Boolean. True for success and False when action exsisits. ''' self.source.list.append(action) def delete(self,act): ''' Argument: act: An Action OR a string of action key. Return: Boolean. True for success. ''' if self.source.list.count(act) == 0: del(self.list[self.list.index(act)]) return(True) else: return(False) def join(self, source): ''' Copy source form another souce to current source. ''' for each in source: if self.list.count(each) == 0 : self.list.append(each) def match(self,ingroups=[],outgroups=[],implementation=None,key=None): ### NOT YET IMP ## pass def test(): from base import Action b = Action() b.key = "1" c = Action() c.key = "1" print(cmp(b,c)) a = SourceHandler() print(a.append(b)) print(a.append(c)) print(a.source.list) print(a.delete(b)) #for each in dir(a): # print(getattr(a,each)) # test() </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">apache-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-1,190,390,218,465,255,400</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">25.023256</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">76</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.547762</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">4.070053</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45165"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">lyndsysimon/hgrid-git-example</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">app.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1874</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">from flask import Flask, jsonify, render_template, request import json import os import tempfile app = Flask(__name__) from git_subprocess import Repository repo_path = '/tmp/test/' # Set up a git repository for a storage backend repo = Repository(repo_path or tempfile.mkdtemp()) repo.init() # Homepage - just render the template @app.route('/') def index(): return render_template('index.html') # DELETE verb @app.route('/api/files/', methods=['DELETE', ]) def delete_files(): # since multiple items could be deleted at once, iterate the list. for id in json.loads(request.form.get('ids', '[]')): repo._rm_file(id) repo.commit( author='Internet User <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dfbeb1b0b19fb6b1abbaadf1b1baab">[email protected]</a>>', message='Deleted file(s)', ) return jsonify({'deleted': request.form.get('ids')}) # GET verb @app.route('/api/files/', methods=['GET', ]) def get_files(): return jsonify({ 'files': [ _file_dict(f) for f in os.listdir(repo.path) if os.path.isfile(os.path.join(repo.path, f)) ] }) # POST verb @app.route('/api/files/', methods=['POST', ]) def add_file(): f = request.files.get('file') # write the file out to its new location new_path = os.path.join(repo.path, f.filename) with open(new_path, 'w') as outfile: outfile.write(f.read()) # add it to git and commit repo.add_file( file_path=f.filename, commit_author='Internet User <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c6a7a8a9a886afa8b2a3b4e8a8a3b2">[email protected]</a>>', commit_message='Commited file {}'.format(f.filename) ) return json.dumps([_file_dict(new_path), ]) def _file_dict(f): return { 'uid': f, 'name': f, 'size': os.path.getsize(os.path.join(repo.path, f)), 'type': 'file', 'parent_uid': 'null' } if __name__ == '__main__': app.run(debug=True, port=5000) </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">bsd-2-clause</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">4,562,782,882,468,337,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">23.337662</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">70</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.593917</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.432234</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45166"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">lliss/tr-55</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">tr55/model.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">14151</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "># -*- coding: utf-8 -*- from __future__ import print_function from __future__ import unicode_literals from __future__ import division """ TR-55 Model Implementation A mapping between variable/parameter names found in the TR-55 document and variables used in this program are as follows: * `precip` is referred to as P in the report * `runoff` is Q * `evaptrans` maps to ET, the evapotranspiration * `inf` is the amount of water that infiltrates into the soil (in inches) * `init_abs` is Ia, the initial abstraction, another form of infiltration """ import copy from tr55.tablelookup import lookup_cn, lookup_bmp_infiltration, \ lookup_ki, is_bmp, is_built_type, make_precolumbian, get_pollutants from tr55.water_quality import get_volume_of_runoff, get_pollutant_load from tr55.operations import dict_plus def runoff_pitt(precip, land_use): """ The Pitt Small Storm Hydrology method. The output is a runoff value in inches. """ c1 = +3.638858398e-2 c2 = -1.243464039e-1 c3 = +1.295682223e-1 c4 = +9.375868043e-1 c5 = -2.235170859e-2 c6 = +0.170228067e+0 c7 = -3.971810782e-1 c8 = +3.887275538e-1 c9 = -2.289321859e-2 p4 = pow(precip, 4) p3 = pow(precip, 3) p2 = pow(precip, 2) impervious = (c1 * p3) + (c2 * p2) + (c3 * precip) + c4 urb_grass = (c5 * p4) + (c6 * p3) + (c7 * p2) + (c8 * precip) + c9 runoff_vals = { 'open_water': impervious, 'developed_low': 0.20 * impervious + 0.80 * urb_grass, 'cluster_housing': 0.20 * impervious + 0.80 * urb_grass, 'developed_med': 0.65 * impervious + 0.35 * urb_grass, 'developed_high': impervious, 'developed_open': urb_grass } if land_use not in runoff_vals: raise Exception('Land use %s not a built-type.' % land_use) else: return min(runoff_vals[land_use], precip) def nrcs_cutoff(precip, curve_number): """ A function to find the cutoff between precipitation/curve number pairs that have zero runoff by definition, and those that do not. """ if precip <= -1 * (2 * (curve_number - 100.0) / curve_number): return True else: return False def runoff_nrcs(precip, evaptrans, soil_type, land_use): """ The runoff equation from the TR-55 document. The output is a runoff value in inches. """ if land_use == 'cluster_housing': land_use = 'developed_low' curve_number = lookup_cn(soil_type, land_use) if nrcs_cutoff(precip, curve_number): return 0.0 potential_retention = (1000.0 / curve_number) - 10 initial_abs = 0.2 * potential_retention precip_minus_initial_abs = precip - initial_abs numerator = pow(precip_minus_initial_abs, 2) denominator = (precip_minus_initial_abs + potential_retention) runoff = numerator / denominator return min(runoff, precip - evaptrans) def simulate_cell_day(precip, evaptrans, cell, cell_count): """ Simulate a bunch of cells of the same type during a one-day event. `precip` is the amount of precipitation in inches. `evaptrans` is evapotranspiration. `cell` is a string which contains a soil type and land use separated by a colon. `cell_count` is the number of cells to simulate. The return value is a dictionary of runoff, evapotranspiration, and infiltration as volumes of water. """ def clamp(runoff, et, inf, precip): """ This function clamps ensures that runoff + et + inf <= precip. NOTE: infiltration is normally independent of the precipitation level, but this function introduces a slight dependency (that is, at very low levels of precipitation, this function can cause infiltration to be smaller than it ordinarily would be. """ total = runoff + et + inf if (total > precip): scale = precip / total runoff *= scale et *= scale inf *= scale return (runoff, et, inf) precip = max(0.0, precip) soil_type, land_use, bmp = cell.lower().split(':') # If there is no precipitation, then there is no runoff or # infiltration. There is evapotranspiration, however (it is # understood that over a period of time, this can lead to the sum # of the three values exceeding the total precipitation). if precip == 0.0: return { 'runoff-vol': 0.0, # 'et-vol': cell_count * evaptrans, 'et-vol': 0.0, 'inf-vol': 0.0, } # Deal with the Best Management Practices (BMPs). For most BMPs, # the infiltration is read from the table and the runoff is what # is left over after infiltration and evapotranspiration. Rain # gardens are treated differently. if bmp and is_bmp(bmp) and bmp != 'rain_garden': inf = lookup_bmp_infiltration(soil_type, bmp) # infiltration runoff = max(0.0, precip - (evaptrans + inf)) # runoff (runoff, evaptrans, inf) = clamp(runoff, evaptrans, inf, precip) return { 'runoff-vol': cell_count * runoff, 'et-vol': cell_count * evaptrans, 'inf-vol': cell_count * inf } elif bmp and bmp == 'rain_garden': # Here, return a mixture of 20% ideal rain garden and 80% # high-intensity residential. inf = lookup_bmp_infiltration(soil_type, bmp) runoff = max(0.0, precip - (evaptrans + inf)) hi_res_cell = soil_type + ':developed_med:' hi_res = simulate_cell_day(precip, evaptrans, hi_res_cell, 1) hir_run = hi_res['runoff-vol'] hir_et = hi_res['et-vol'] hir_inf = hi_res['inf-vol'] final_runoff = (0.2 * runoff + 0.8 * hir_run) final_et = (0.2 * evaptrans + 0.8 * hir_et) final_inf = (0.2 * inf + 0.8 * hir_inf) final = clamp(final_runoff, final_et, final_inf, precip) (final_runoff, final_et, final_inf) = final return { 'runoff-vol': cell_count * final_runoff, 'et-vol': cell_count * final_et, 'inf-vol': cell_count * final_inf } # At this point, if the `bmp` string has non-zero length, it is # equal to either 'no_till' or 'cluster_housing'. if bmp and bmp != 'no_till' and bmp != 'cluster_housing': raise KeyError('Unexpected BMP: %s' % bmp) land_use = bmp or land_use # When the land use is a built-type and the level of precipitation # is two inches or less, use the Pitt Small Storm Hydrology Model. # When the land use is a built-type but the level of precipitation # is higher, the runoff is the larger of that predicted by the # Pitt model and NRCS model. Otherwise, return the NRCS amount. if is_built_type(land_use) and precip <= 2.0: runoff = runoff_pitt(precip, land_use) elif is_built_type(land_use): pitt_runoff = runoff_pitt(2.0, land_use) nrcs_runoff = runoff_nrcs(precip, evaptrans, soil_type, land_use) runoff = max(pitt_runoff, nrcs_runoff) else: runoff = runoff_nrcs(precip, evaptrans, soil_type, land_use) inf = max(0.0, precip - (evaptrans + runoff)) (runoff, evaptrans, inf) = clamp(runoff, evaptrans, inf, precip) return { 'runoff-vol': cell_count * runoff, 'et-vol': cell_count * evaptrans, 'inf-vol': cell_count * inf, } def create_unmodified_census(census): """ This creates a cell census, ignoring any modifications. The output is suitable for use with `simulate_water_quality`. """ unmod = copy.deepcopy(census) unmod.pop('modifications', None) return unmod def create_modified_census(census): """ This creates a cell census, with modifications, that is suitable for use with `simulate_water_quality`. For every type of cell that undergoes modification, the modifications are indicated with a sub-distribution under that cell type. """ mod = copy.deepcopy(census) mod.pop('modifications', None) for (cell, subcensus) in mod['distribution'].items(): n = subcensus['cell_count'] changes = { 'distribution': { cell: { 'distribution': { cell: {'cell_count': n} } } } } mod = dict_plus(mod, changes) for modification in (census.get('modifications') or []): for (orig_cell, subcensus) in modification['distribution'].items(): n = subcensus['cell_count'] soil1, land1 = orig_cell.split(':') soil2, land2, bmp = modification['change'].split(':') changed_cell = '%s:%s:%s' % (soil2 or soil1, land2 or land1, bmp) changes = { 'distribution': { orig_cell: { 'distribution': { orig_cell: {'cell_count': -n}, changed_cell: {'cell_count': n} } } } } mod = dict_plus(mod, changes) return mod def simulate_water_quality(tree, cell_res, fn, current_cell=None, precolumbian=False): """ Perform a water quality simulation by doing simulations on each of the cell types (leaves), then adding them together by summing the values of a node's subtrees and storing them at that node. `tree` is the (sub)tree of cell distributions that is currently under consideration. `cell_res` is the size of each cell (used for turning inches of water into volumes of water). `fn` is a function that takes a cell type and a number of cells and returns a dictionary containing runoff, et, and inf as volumes. `current_cell` is the cell type for the present node. """ # Internal node. if 'cell_count' in tree and 'distribution' in tree: n = tree['cell_count'] # simulate subtrees if n != 0: tally = {} for cell, subtree in tree['distribution'].items(): simulate_water_quality(subtree, cell_res, fn, cell, precolumbian) subtree_ex_dist = subtree.copy() subtree_ex_dist.pop('distribution', None) tally = dict_plus(tally, subtree_ex_dist) tree.update(tally) # update this node # effectively a leaf elif n == 0: for pol in get_pollutants(): tree[pol] = 0.0 # Leaf node. elif 'cell_count' in tree and 'distribution' not in tree: # the number of cells covered by this leaf n = tree['cell_count'] # canonicalize the current_cell string split = current_cell.split(':') if (len(split) == 2): split.append('') if precolumbian: split[1] = make_precolumbian(split[1]) current_cell = '%s:%s:%s' % tuple(split) # run the runoff model on this leaf result = fn(current_cell, n) # runoff, et, inf tree.update(result) # perform water quality calculation if n != 0: soil_type, land_use, bmp = split runoff_per_cell = result['runoff-vol'] / n liters = get_volume_of_runoff(runoff_per_cell, n, cell_res) for pol in get_pollutants(): tree[pol] = get_pollutant_load(land_use, pol, liters) def postpass(tree): """ Remove volume units and replace them with inches. """ if 'cell_count' in tree: if tree['cell_count'] > 0: n = tree['cell_count'] tree['runoff'] = tree['runoff-vol'] / n tree['et'] = tree['et-vol'] / n tree['inf'] = tree['inf-vol'] / n else: tree['runoff'] = 0 tree['et'] = 0 tree['inf'] = 0 tree.pop('runoff-vol', None) tree.pop('et-vol', None) tree.pop('inf-vol', None) if 'distribution' in tree: for subtree in tree['distribution'].values(): postpass(subtree) def simulate_modifications(census, fn, cell_res, precolumbian=False): """ Simulate effects of modifications. `census` contains a distribution of cell-types in the area of interest. `fn` is as described in `simulate_water_quality`. `cell_res` is as described in `simulate_water_quality`. """ mod = create_modified_census(census) simulate_water_quality(mod, cell_res, fn, precolumbian=precolumbian) postpass(mod) unmod = create_unmodified_census(census) simulate_water_quality(unmod, cell_res, fn, precolumbian=precolumbian) postpass(unmod) return { 'unmodified': unmod, 'modified': mod } def simulate_day(census, precip, cell_res=10, precolumbian=False): """ Simulate a day, including water quality effects of modifications. `census` contains a distribution of cell-types in the area of interest. `cell_res` is as described in `simulate_water_quality`. `precolumbian` indicates that artificial types should be turned into forest. """ et_max = 0.207 if 'modifications' in census: verify_census(census) def fn(cell, cell_count): # Compute et for cell type split = cell.split(':') if (len(split) == 2): (land_use, bmp) = split else: (_, land_use, bmp) = split et = et_max * lookup_ki(bmp or land_use) # Simulate the cell for one day return simulate_cell_day(precip, et, cell, cell_count) return simulate_modifications(census, fn, cell_res, precolumbian) def verify_census(census): """ Assures that there is no soil type/land cover pair in a modification census that isn't in the AoI census. """ for modification in census['modifications']: for land_cover in modification['distribution']: if land_cover not in census['distribution']: raise ValueError("Invalid modification census") </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">apache-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-1,927,152,914,711,812,900</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">33.098795</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">77</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.596636</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.429714</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45167"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">luwei0917/awsemmd_script</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">small_script/computeRg.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">2040</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">from Bio.PDB.PDBParser import PDBParser import argparse parser = argparse.ArgumentParser(description="Compute Rg of pdb") parser.add_argument("pdb", help="pdb file") args = parser.parse_args() def computeRg(pdb_file, chain="A"): # compute Radius of gyration # pdb_file = f"/Users/weilu/Research/server/feb_2019/iterative_optimization_new_temp_range/all_simulations/{p}/{p}/crystal_structure.pdb" chain_name = chain parser = PDBParser() structure = parser.get_structure('X', pdb_file) chain = list(structure[0][chain_name]) all_res = list(structure.get_residues()) # n = len(all_res) # n = len(chain) regular_res_list = [res for res in all_res if res.get_id()[0] == ' '] n = len(regular_res_list) print("all chains") cutoff = 15 for residue in regular_res_list: if residue.get_id()[0] == ' ' and abs(residue["CA"].get_vector()[-1]) < cutoff: print(residue.get_id()[1]) rg = 0.0 for i, residue_i in enumerate(regular_res_list): for j, residue_j in enumerate(regular_res_list[i+1:]): try: r = residue_i["CA"] - residue_j["CA"] except: print(residue_i, residue_j) rg += r**2 return (rg/(n**2))**0.5 rg = computeRg(args.pdb) print(rg) def cylindrical_rg_bias_term(oa, k_rg=4.184, rg0=0, atomGroup=-1, forceGroup=27): nres, ca = oa.nres, oa.ca if atomGroup == -1: group = list(range(nres)) else: group = atomGroup # atomGroup = [0, 1, 10, 12] means include residue 1, 2, 11, 13. n = len(group) rg_square = CustomBondForce("1/normalization*(x^2+y^2)") # rg = CustomBondForce("1") rg_square.addGlobalParameter("normalization", n*n) for i in group: for j in group: if j <= i: continue rg_square.addBond(ca[i], ca[j], []) rg = CustomCVForce(f"{k_rg}*(rg_square^0.5-{rg0})^2") rg.addCollectiveVariable("rg_square", rg_square) rg.setForceGroup(forceGroup) return rg </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">9,124,268,330,187,088,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">35.428571</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">141</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.59951</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.022222</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45168"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Airbitz/airbitz-ofx</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">qbo.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">7851</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">##################################################################### # # # File: qbo.py # # Developer: Justin Leto # # # # qbo class provides an interface from main csv iterator method # # to handle qbo formatting, validations, and writing to file. # # # # Usage: python csvtoqbo.py <options> <csvfiles> # # # ##################################################################### import sys, traceback import os from datetime import datetime import logging import qboconst class qbo: # Holds a list of valid transactions via the addTransaction() method __transactions = list() # The full QBO document build from constants and transactions __document = None # Flag indicating whether the QBO document is valid __isValid = None # constructor def __init__(self): # Reads in constant values from file, set to private (const) variables self.__HEADER = qboconst.HEADER self.__FOOTER = qboconst.FOOTER self.__DATE_START = qboconst.DATE_START self.__DATE_END = qboconst.DATE_END self.__BANKTRANLIST_START = qboconst.BANKTRANLIST_START self.__BANKTRANLIST_END = qboconst.BANKTRANLIST_END self.__TRANSACTION_START = qboconst.TRANSACTION_START self.__TRANSACTION_END = qboconst.TRANSACTION_END # Set document to valid self.__isValid = True # PUBLIC GET METHODS for constant values - used in unit testing. # # def getHEADER(self): return self.__HEADER def getFOOTER(self): return self.__FOOTER def getDATE_START(self): return self.__DATE_START def getDATE_END(self): return self.__DATE_END def getBANKTRANLIST_START(self): return self.__BANKTRANLIST_START def getBANKTRANLIST_END(self): return self.__BANKTRANLIST_END def getTRANSACTION_START(self): return self.__TRANSACTION_START def getTRANSACTION_END(self): return self.__TRANSACTION_END # method to validate paramters used to submit transactions def validateTransaction(self, status, date_posted, txn_type, to_from_flag, txn_amount, txn_exrate, name): # if str.lower(status) != 'completed': # #log status failure # logging.info("Transaction status [" + status + "] invalid.") # raise Exception("Transaction status [" + status + "] invalid.") # #if type(datetime.strptime(str(date_posted), '%m/%d/%Y')) is not datetime: # logging.info("Transaction posted date [" + date_posted + "] invalid.") # raise Exception("Transaction posted date [" + date_posted + "] invalid.") # if str.lower(txn_type) not in ('payment','refund','withdrawal', 'withdraw funds', 'send', 'receive'): # logging.info("Transaction type [" + str(txn_type) + "] not 'Payment', 'Refund', 'Withdraw Funds', or 'Withdrawal'.") # raise Exception("Transaction type [" + str(txn_type) + "] not 'Payment', 'Refund', 'Withdraw Funds', or 'Withdrawal'.") # # if str.lower(to_from_flag) not in ('to', 'from'): # logging.info("Transaction 'To/From' field [" + to_from_flag + "] invalid.") # raise Exception("Transaction 'To/From' field [" + to_from_flag + "] invalid.") # # #logical test of txn_type and to_from_flag # if ((str.lower(txn_type) == 'refund' and str.lower(to_from_flag) != 'to') or (str.lower(txn_type) == 'payment' and str.lower(to_from_flag) != 'from')): # logging.info("Transaction type inconsistent with 'To/From' field.") # raise Exception("Transaction type inconsistent with 'To/From' field.") # if len(name) == 0 or not name: logging.info("Transaction name empty or null.") raise Exception("Transaction name empty or null.") return True # Add transaction takes in param values uses the required formatting QBO transactions # and pushes to list def addTransaction(self, denom, date_posted, txn_memo, txn_id, txn_amount, txn_curamt, txn_category, name): # try: # # Validating param values prior to committing transaction # self.validateTransaction(status, date_posted, txn_type, txn_id, txn_amount, name) # except: # raise Exception # Construct QBO formatted transaction transaction = "" day = "" month = "" date_array = date_posted.split('-') day = date_array[2] month = date_array[1] year = date_array[0] if len(day) == 1: day = "0"+day if len(month) ==1: month = "0"+month rec_date = datetime.strptime(year+"/"+month+"/"+day, '%Y/%m/%d') rec_date = rec_date.strftime('%Y%m%d%H%M%S') + '.000' dtposted = ' <DTPOSTED>' + rec_date if float(txn_amount) > 0: trtype = ' <TRNTYPE>CREDIT' else: trtype = ' <TRNTYPE>DEBIT' # # if str.lower(txn_type) == 'receive': # trtype = '<TRNTYPE>CREDIT' # elif str.lower(txn_type) == 'send': # trtype = '<TRNTYPE>DEBIT' # if str.lower(txn_type) in ('refund', 'withdrawal', 'withdraw funds'): # tramt = '<TRNAMT>-' + str(txn_amount).replace('$','') # else: # tramt = '<TRNAMT>' + str(txn_amount).replace('$','') tramtbits = float(txn_amount) * denom tramt = ' <TRNAMT>' + str(tramtbits) if name: trname = ' <NAME>' + str(name) + "\n" else: trname = '' exrate = float(txn_curamt) / (tramtbits) curamt = "{0:0.2f}".format(abs(float(txn_curamt))) fmtexrate = "{0:0.6f}".format(float(exrate)) rawmemo = 'Rate=' + fmtexrate + " USD=" + curamt + " category=\"" + str(txn_category) + "\" memo=\"" + str(txn_memo) memo = ' <MEMO>' + rawmemo[:253] + "\"\n" fitid = ' <FITID>' + str(txn_id) exrate = ' <CURRATE>' + fmtexrate transaction = ("" + self.__TRANSACTION_START + "\n" "" + trtype + "\n" "" + dtposted + "\n" "" + tramt + "\n" "" + fitid + "\n" "" + trname + "" + memo + "" + " <CURRENCY>" + "\n" "" + exrate + "\n" "" + " <CURSYM>USD" + "\n" "" + " </CURRENCY>" + "\n" "" + self.__TRANSACTION_END + "\n") # Commit transaction to the document by adding to private member list object self.__transactions.append(transaction) logging.info("Transaction [" + str(self.getCount()) + "] Accepted.") return True # get the current number of valid committed transactions def getCount(self): return len(self.__transactions) # get the valid status of the document def isValid(self): # If number of valid transactions are 0 document is invalid if self.getCount() == 0: self.__isValid = False return self.__isValid # get the text of the document def getDocument(self): self.Build() return self.__document # Construct the document, add the transactions # save str into private member variable __document def Build(self): if not self.isValid(): logging.info("Error: QBO document is not valid.") raise Exception("Error: QBO document is not valid.") self.__document = ("" + self.__HEADER + "\n" "" + self.__BANKTRANLIST_START + "\n" "" + self.__DATE_START + "\n" "" + self.__DATE_END + "\n") for txn in self.__transactions: self.__document = self.__document + str(txn) self.__document = self.__document + ("" + self.__BANKTRANLIST_END + "\n" "" + self.__FOOTER + "") # Write QBO document to file def Write(self, filename): try: with open(filename, 'w') as f: # getDocument method will build document # test for validity and return string for write f.write(self.getDocument()) return True except: #log io error return False exc_type, exc_value, exc_traceback = sys.exc_info() lines = traceback.format_exception(exc_type, exc_value, exc_traceback) print(''.join('!! ' + line for line in lines)) logging.info('qbo.Write() method: '.join('!! ' + line for line in lines)) return False </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">1,675,282,766,867,628,800</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">31.126582</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">155</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.603235</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.155547</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45169"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">berkerpeksag/pythondotorg</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">pydotorg/settings/base.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">5943</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">import os import dj_database_url ### Basic config BASE = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')) DEBUG = TEMPLATE_DEBUG = True SITE_ID = 1 SECRET_KEY = 'its-a-secret-to-everybody' # Until Sentry works on Py3, do errors the old-fashioned way. ADMINS = [] # General project information # These are available in the template as SITE_INFO.<title> SITE_VARIABLES = { 'site_name': 'Python.org', 'site_descript': 'The official home of the Python Programming Language', } ### Databases DATABASES = { 'default': dj_database_url.config(default='postgres:///python.org') } ### Locale settings TIME_ZONE = 'UTC' LANGUAGE_CODE = 'en-us' USE_I18N = True USE_L10N = True USE_TZ = True DATE_FORMAT = 'Y-m-d' ### Files (media and static) MEDIA_ROOT = os.path.join(BASE, 'media') MEDIA_URL = '/m/' # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/var/www/example.com/static/" STATIC_ROOT = os.path.join(BASE, 'static-root') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE, 'static'), ] STATICFILES_STORAGE = 'pipeline.storage.PipelineStorage' ### Authentication AUTHENTICATION_BACKENDS = ( # Needed to login by username in Django admin, regardless of `allauth` "django.contrib.auth.backends.ModelBackend", # `allauth` specific authentication methods, such as login by e-mail "allauth.account.auth_backends.AuthenticationBackend", ) LOGIN_REDIRECT_URL = 'home' ACCOUNT_LOGOUT_REDIRECT_URL = 'home' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_EMAIL_VERIFICATION = 'mandatory' SOCIALACCOUNT_EMAIL_REQUIRED = True SOCIALACCOUNT_EMAIL_VERIFICATION = True SOCIALACCOUNT_QUERY_EMAIL = True ### Templates TEMPLATE_DIRS = [ os.path.join(BASE, 'templates') ] TEMPLATE_CONTEXT_PROCESSORS = [ "django.contrib.auth.context_processors.auth", "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.media", "django.core.context_processors.static", "django.core.context_processors.tz", "django.core.context_processors.request", "allauth.account.context_processors.account", "allauth.socialaccount.context_processors.socialaccount", "django.contrib.messages.context_processors.messages", "pydotorg.context_processors.site_info", "pydotorg.context_processors.url_name", ] ### URLs, WSGI, middleware, etc. ROOT_URLCONF = 'pydotorg.urls' MIDDLEWARE_CLASSES = ( 'pydotorg.middleware.AdminNoCaching', 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'pages.middleware.PageFallbackMiddleware', 'django.contrib.redirects.middleware.RedirectFallbackMiddleware', ) AUTH_USER_MODEL = 'users.User' WSGI_APPLICATION = 'pydotorg.wsgi.application' ### Apps INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.redirects', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.comments', 'django.contrib.admin', 'django.contrib.admindocs', 'django_comments_xtd', 'jsonfield', 'pipeline', 'sitetree', 'timedelta', 'imagekit', 'haystack', 'honeypot', 'users', 'boxes', 'cms', 'companies', 'feedbacks', 'community', 'jobs', 'pages', 'sponsors', 'successstories', 'events', 'minutes', 'peps', 'blogs', 'downloads', 'codesamples', 'allauth', 'allauth.account', 'allauth.socialaccount', #'allauth.socialaccount.providers.facebook', #'allauth.socialaccount.providers.github', #'allauth.socialaccount.providers.openid', #'allauth.socialaccount.providers.twitter', # Tastypie needs the `users` app to be already loaded. 'tastypie', ] # Fixtures FIXTURE_DIRS = ( os.path.join(BASE, 'fixtures'), ) ### Testing SKIP_NETWORK_TESTS = True ### Logging LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } } ### Development DEV_FIXTURE_URL = 'https://www.python.org/m/fixtures/dev-fixtures.json.gz' ### Comments COMMENTS_APP = 'django_comments_xtd' COMMENTS_XTD_MAX_THREAD_LEVEL = 0 COMMENTS_XTD_FORM_CLASS = "jobs.forms.JobCommentForm" ### Honeypot HONEYPOT_FIELD_NAME = 'email_body_text' HONEYPOT_VALUE = 'write your message' ### Blog Feed URL PYTHON_BLOG_FEED_URL = "http://feeds.feedburner.com/PythonInsider" PYTHON_BLOG_URL = "http://blog.python.org" ### Registration mailing lists MAILING_LIST_PSF_MEMBERS = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0b7b786d26666e66696e7978266a6565647e65686e26796e7a7e6e787f4b7b727f6364652564796c">[email protected]</a>" ### PEP Repo Location PEP_REPO_PATH = '' ### Fastly ### FASTLY_API_KEY = False # Set to Fastly API key in production to allow pages to # be purged on save # Jobs JOB_THRESHOLD_DAYS = 90 JOB_FROM_EMAIL = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="167c79746556666f627e797838796471">[email protected]</a>' ### Pipeline from .pipeline import ( PIPELINE_CSS, PIPELINE_JS, PIPELINE_COMPILERS, PIPELINE_SASS_BINARY, PIPELINE_SASS_ARGUMENTS, PIPELINE_CSS_COMPRESSOR, PIPELINE_JS_COMPRESSOR, ) </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">apache-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-7,469,629,725,360,730,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">23.557851</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">79</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.676931</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.346284</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45170"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">stevegt/UltimakerUtils</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">leveling-rings-UM1.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">2681</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">#!/usr/bin/python # Derived from the UM2 version by an anonymous contributor... # # http://umforum.ultimaker.com/index.php?/topic/5951-um2-calibration-utility-leveling-ringsgcode/?p=54694 # # ...who wisely says: "I accept NO liability for any damage done by # using either version or any derivatives. USE AT YOUR OWN RISK." filament_diameter = 2.89 build_area_width = 205.0 build_area_depth = 205.0 rings = 10 wide = 0.4 thick = 0.2925 / 2 temperature = 230 bed_temperature = 60 base_dia = 180 pi=3.1415927 center_x = build_area_width/2.0 center_y = build_area_depth/2.0 filament_area = (filament_diameter / 2) ** 2 * pi head = ''' M107 ;start with the fan off G21 ;metric values G90 ;absolute positioning M82 ;set extruder to absolute mode M107 ;start with the fan off G28 X0 Y0 ;move X/Y to min endstops G28 Z0 ;move Z to min endstops G1 Z15.0 F9000 ;move the platform down 15mm M140 S{bed_temperature:.2f} ;set bed temp (no wait) M109 T0 S{temperature:.2f} ;set extruder temp (wait) M190 S{bed_temperature:.2f} ;set bed temp (wait) G92 E0 ;zero the extruded length G1 F200 E3 ;extrude 3mm of feed stock G92 E0 ;zero the extruded length again G1 F9000 ;set speed to 9000 ;Put printing message on LCD screen M117 Printing... ;Layer count: 1 ;LAYER:0 ''' loop = ''' G0 F9000 X{x:.2f} Y{y:.2f} Z{z:.2f} G2 F1000 X{x:.2f} Y{y:.2f} I{r:.2f} E{total_mm3:.2f}''' tail = ''' ;End GCode M104 S0 ;extruder heater off M140 S0 ;heated bed heater off (if you have it) G91 ;relative positioning G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure G1 Z+0.5 E-5 X-20 Y-20 F9000 ;move Z up a bit and retract filament even more G28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way M84 ;steppers off G90 ;absolute positioning''' total_mm3 = 0 body = '' cross_section = thick * wide z = thick for i in range(rings): dia = base_dia - ((wide * 2) * i) circumference = pi * dia r = dia/2.0; x = center_x - r y = center_y mm3 = (circumference * cross_section) / filament_area total_mm3 += mm3 body += loop.format(**vars()) print head.format(**vars()) print body print tail.format(**vars()) </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">5,621,385,078,935,052,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">30.174419</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">118</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.564715</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.099422</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45171"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">udapi/udapi-python</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">udapi/block/ud/complywithtext.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">11648</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">r"""Block ComplyWithText for adapting the nodes to comply with the text. Implementation design details: Usually, most of the inconsistencies between tree tokens and the raw text are simple to solve. However, there may be also rare cases when it is not clear how to align the tokens (nodes in the tree) with the raw text (stored in ``root.text``). This block tries to solve the general case using several heuristics. It starts with running a LCS-like algorithm (LCS = longest common subsequence) ``difflib.SequenceMatcher`` on the raw text and concatenation of tokens' forms, i.e. on sequences of characters (as opposed to running LCS on sequences of tokens). To prevent mis-alignment problems, we keep the spaces present in the raw text and we insert spaces into the concatenated forms (``tree_chars``) according to ``SpaceAfter=No``. An example of a mis-alignment problem: text "énfase na necesidade" with 4 nodes "énfase en a necesidade" should be solved by adding multiword token "na" over the nodes "en" and "a". However, running LCS (or difflib) over the character sequences "énfaseenanecesidade" "énfasenanecesidade" may result in énfase -> énfas. Author: Martin Popel """ import difflib import logging import re from udapi.core.block import Block from udapi.core.mwt import MWT class ComplyWithText(Block): """Adapt the nodes to comply with the text.""" def __init__(self, fix_text=True, prefer_mwt=True, allow_goeswith=True, max_mwt_length=4, **kwargs): """Args: fix_text: After all heuristics are applied, the token forms may still not match the text. Should we edit the text to match the token forms (as a last resort)? Default=True. prefer_mwt - What to do if multiple subsequent nodes correspond to a text written without spaces and non-word characters (punctuation)? E.g. if "3pm doesn't" is annotated with four nodes "3 pm does n't". We can use either SpaceAfter=No, or create a multi-word token (MWT). Note that if there is space or punctuation, SpaceAfter=No will be used always (e.g. "3 p.m." annotated with three nodes "3 p. m."). If the character sequence does not match exactly, MWT will be used always (e.g. "3pm doesn't" annotated with four nodes "3 p.m. does not"). Thus this parameter influences only the "unclear" cases. Default=True (i.e. prefer multi-word tokens over SpaceAfter=No). allow_goeswith - If a node corresponds to multiple space-separated strings in text, which are not allowed as tokens with space, we can either leave this diff unresolved or create new nodes and join them with the `goeswith` deprel. Default=True (i.e. add the goeswith nodes if applicable). max_mwt_length - Maximum length of newly created multi-word tokens (in syntactic words). Default=4. """ super().__init__(**kwargs) self.fix_text = fix_text self.prefer_mwt = prefer_mwt self.allow_goeswith = allow_goeswith self.max_mwt_length = max_mwt_length @staticmethod def allow_space(form): """Is space allowed within this token form?""" return re.fullmatch('[0-9 ]+([,.][0-9]+)?', form) @staticmethod def store_orig_form(node, new_form): """Store the original form of this node into MISC, unless the change is common&expected.""" _ = new_form if node.form not in ("''", "``"): node.misc['OrigForm'] = node.form def process_tree(self, root): text = root.text if text is None: raise ValueError('Tree %s has no text, cannot use ud.ComplyWithText' % root) # Normalize the stored text (double space -> single space) # and skip sentences which are already ok. text = ' '.join(text.split()) if text == root.compute_text(): return tree_chars, char_nodes = _nodes_to_chars(root.token_descendants) # Align. difflib may not give LCS, but usually it is good enough. matcher = difflib.SequenceMatcher(None, tree_chars, text, autojunk=False) diffs = list(matcher.get_opcodes()) _log_diffs(diffs, tree_chars, text, 'matcher') diffs = self.unspace_diffs(diffs, tree_chars, text) _log_diffs(diffs, tree_chars, text, 'unspace') diffs = self.merge_diffs(diffs, char_nodes) _log_diffs(diffs, tree_chars, text, 'merge') # Solve diffs. self.solve_diffs(diffs, tree_chars, char_nodes, text) # Fill SpaceAfter=No. tmp_text = text for node in root.token_descendants: if tmp_text.startswith(node.form): tmp_text = tmp_text[len(node.form):] if not tmp_text or tmp_text[0].isspace(): del node.misc['SpaceAfter'] tmp_text = tmp_text.lstrip() else: node.misc['SpaceAfter'] = 'No' else: logging.warning('Node %s does not match text "%s"', node, tmp_text[:20]) return # Edit root.text if needed. if self.fix_text: computed_text = root.compute_text() if text != computed_text: root.add_comment('ToDoOrigText = ' + root.text) root.text = computed_text def unspace_diffs(self, orig_diffs, tree_chars, text): diffs = [] for diff in orig_diffs: edit, tree_lo, tree_hi, text_lo, text_hi = diff if edit != 'insert': if tree_chars[tree_lo] == ' ': tree_lo += 1 if tree_chars[tree_hi - 1] == ' ': tree_hi -= 1 old = tree_chars[tree_lo:tree_hi] new = text[text_lo:text_hi] if old == '' and new == '': continue elif old == new: edit = 'equal' elif old == '': edit = 'insert' diffs.append((edit, tree_lo, tree_hi, text_lo, text_hi)) return diffs def merge_diffs(self, orig_diffs, char_nodes): """Make sure each diff starts on original token boundary. If not, merge the diff with the previous diff. E.g. (equal, "5", "5"), (replace, "-6", "–7") is changed into (replace, "5-6", "5–7") """ diffs = [] for diff in orig_diffs: edit, tree_lo, tree_hi, text_lo, text_hi = diff if edit != 'insert' and char_nodes[tree_lo] is not None: diffs.append(diff) elif edit == 'equal': while tree_lo < tree_hi and char_nodes[tree_lo] is None: tree_lo += 1 text_lo += 1 diffs[-1] = ('replace', diffs[-1][1], tree_lo, diffs[-1][3], text_lo) if tree_lo < tree_hi: diffs.append(('equal', tree_lo, tree_hi, text_lo, text_hi)) else: if not diffs: diffs = [diff] elif diffs[-1][0] != 'equal': diffs[-1] = ('replace', diffs[-1][1], tree_hi, diffs[-1][3], text_hi) else: p_tree_hi = diffs[-1][2] - 1 p_text_hi = diffs[-1][4] - 1 while char_nodes[p_tree_hi] is None: p_tree_hi -= 1 p_text_hi -= 1 assert p_tree_hi >= diffs[-1][1] assert p_text_hi >= diffs[-1][3] diffs[-1] = ('equal', diffs[-1][1], p_tree_hi, diffs[-1][3], p_text_hi) diffs.append(('replace', p_tree_hi, tree_hi, p_text_hi, text_hi)) return diffs def solve_diffs(self, diffs, tree_chars, char_nodes, text): for diff in diffs: edit, tree_lo, tree_hi, text_lo, text_hi = diff # Focus only on edits of type 'replace', log insertions and deletions as failures. if edit == 'equal': continue if edit in ('insert', 'delete'): logging.warning('Unable to solve token-vs-text mismatch\n%s', _diff2str(diff, tree_chars, text)) continue # Revert the splittng and solve the diff. nodes = [n for n in char_nodes[tree_lo:tree_hi] if n is not None] form = text[text_lo:text_hi] self.solve_diff(nodes, form.strip()) def solve_diff(self, nodes, form): """Fix a given (minimal) tokens-vs-text inconsistency.""" nodes_str = ' '.join([n.form for n in nodes]) # just for debugging node = nodes[0] # First, solve the cases when the text contains a space. if ' ' in form: if len(nodes) == 1 and node.form == form.replace(' ', ''): if self.allow_space(form): self.store_orig_form(node, form) node.form = form elif self.allow_goeswith: forms = form.split() node.form = forms[0] for split_form in reversed(forms[1:]): new = node.create_child(form=split_form, deprel='goeswith', upos=node.upos) new.shift_after_node(node) else: logging.warning('Unable to solve 1:m diff:\n%s -> %s', nodes_str, form) else: logging.warning('Unable to solve n:m diff:\n%s -> %s', nodes_str, form) # Second, solve the cases when multiple nodes match one form (without any spaces). elif len(nodes) > 1: # If the match is exact, we can choose between MWT ans SpaceAfter solutions. if not self.prefer_mwt and ''.join([n.form for n in nodes]) == form: pass # SpaceAfter=No will be added later on. # If one of the nodes is already a MWT, we cannot have nested MWTs. # TODO: enlarge the MWT instead of failing. elif any(isinstance(n, MWT) for n in nodes): logging.warning('Unable to solve partial-MWT diff:\n%s -> %s', nodes_str, form) # MWT with too many words are suspicious. elif len(nodes) > self.max_mwt_length: logging.warning('Not creating too long (%d>%d) MWT:\n%s -> %s', len(nodes), self.max_mwt_length, nodes_str, form) # Otherwise, create a new MWT. else: node.root.create_multiword_token(nodes, form) # Third, solve the 1-1 cases. else: self.store_orig_form(node, form) node.form = form def _nodes_to_chars(nodes): chars, char_nodes = [], [] for node in nodes: form = node.form if node.misc['SpaceAfter'] != 'No' and node != nodes[-1]: form += ' ' chars.extend(form) char_nodes.append(node) char_nodes.extend([None] * (len(form) - 1)) return ''.join(chars), char_nodes def _log_diffs(diffs, tree_chars, text, msg): if logging.getLogger().isEnabledFor(logging.DEBUG): logging.warning('=== After %s:', msg) for diff in diffs: logging.warning(_diff2str(diff, tree_chars, text)) def _diff2str(diff, tree, text): old = '|' + ''.join(tree[diff[1]:diff[2]]) + '|' new = '|' + ''.join(text[diff[3]:diff[4]]) + '|' if diff[0] == 'equal': return '{:7} {!s:>50}'.format(diff[0], old) return '{:7} {!s:>50} --> {!s}'.format(diff[0], old, new) </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-3.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">6,423,815,890,427,901,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">42.75188</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">99</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.559117</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.789645</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45172"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">storiesofsolidarity/story-database</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">stories/admin.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1393</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">from django.contrib import admin from models import Location, Story from people.models import Author class LocationAdmin(admin.ModelAdmin): list_display = ('zipcode', 'city_fmt', 'county_fmt', 'state_fmt', 'story_count') list_filter = ('state',) search_fields = ('zipcode', 'city', 'county') admin.site.register(Location, LocationAdmin) class EmployerFilter(admin.SimpleListFilter): title = 'author employer' parameter_name = 'employer' def lookups(self, request, model_admin): employer_set = set() for a in Author.objects.all(): if a.employer: employer_set.add(a.employer.split(' ', 1)[0]) return [(str(c), str(c)) for c in employer_set if c] def queryset(self, request, queryset): if self.value() or self.value() == 'None': return queryset.filter(author__employer__startswith=self.value()) else: return queryset class StoryAdmin(admin.ModelAdmin): list_display = ('excerpt', 'author_display', 'employer', 'anonymous', 'created_at') list_filter = (EmployerFilter, 'location__state', 'truncated') date_hierarchy = 'created_at' readonly_fields = ('truncated',) raw_id_fields = ('author', 'location') search_fields = ('location__city', 'author__user__first_name', 'author__user__last_name', 'content') admin.site.register(Story, StoryAdmin) </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">agpl-3.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-544,278,433,607,546,560</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">33.825</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">104</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.648959</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.491228</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45173"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">peppelinux/inventario_verdebinario</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">museo/models.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">4183</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">from django.db import models from photologue.models import ImageModel from django.core.urlresolvers import reverse from django.utils.translation import ugettext_lazy as _ class Produttore(ImageModel): id_tabella = models.AutoField(primary_key=True) nome = models.CharField(max_length=135, blank=True) nome_abbreviato = models.CharField(max_length=135, blank=True) #slug = models.SlugField(unique=True, help_text=('"slug": un identificatore automatico e univoco')) descrizione = models.TextField(max_length=1024, blank=True) data_nascita = models.DateField(null=True, blank=True) data_chiusura = models.DateField(null=True, blank=True) #immagine_logo = models.ImageField(upload_to="LoghiProduttori", blank=True) url = models.CharField(max_length=256, blank=True) def save(self, *args, **kwargs): if self.nome_abbreviato == None or self.nome_abbreviato.split() == []: self.nome_abbreviato = self.nome.upper() super(self.__class__, self).save(*args, **kwargs) # Call the "real" save() method. class Meta: ordering = ['nome'] db_table = 'produttore' verbose_name_plural = "Produttore" # def get_absolute_url(self): # return '%s' % (self.url) def __str__(self): return '%s' % (self.nome_abbreviato) class SchedaTecnica(models.Model): id_tabella = models.AutoField(primary_key=True) modello = models.CharField(max_length=135, blank=True) produttore = models.ForeignKey(Produttore, null=True, blank=True, on_delete=models.SET_NULL) paese_di_origine = models.CharField(max_length=135, blank=True) anno = models.CharField(max_length=135, blank=True) tastiera = models.CharField(max_length=135, blank=True) cpu = models.CharField(max_length=135, blank=True) velocita = models.CharField(max_length=135, blank=True) memoria_volatile = models.CharField(max_length=135, blank=True) memoria_di_massa = models.CharField(max_length=135, blank=True) modalita_grafica = models.CharField(max_length=135, blank=True) audio = models.CharField(max_length=135, blank=True) dispositivi_media = models.CharField(max_length=135, blank=True) alimentazione = models.CharField(max_length=135, blank=True) prezzo = models.CharField(max_length=135, blank=True) descrizione = models.TextField(max_length=1024, blank=True) data_inserimento = models.DateField(null=True, blank=False, auto_now_add=True) class Meta: db_table = 'scheda_tecnica' verbose_name_plural = "Scheda Tecnica" class FotoHardwareMuseo(ImageModel): id_tabella = models.AutoField(primary_key=True) #immagine = models.ImageField(upload_to="FotoHardwareMuseo/%d.%m.%Y", blank=True) etichetta_verde = models.CharField(max_length=135, blank=True) data_inserimento = models.DateField(null=True, blank=False, auto_now_add=True) seriale = models.CharField(max_length=384, blank=True) didascalia = models.TextField(max_length=328, blank=True) scheda_tecnica = models.ForeignKey(SchedaTecnica, null=True, blank=True, on_delete=models.SET_NULL) class Meta: db_table = 'foto_hardware_museo' verbose_name_plural = "Foto Hardware Museo" def __str__(self): return '%s %s' % (self.seriale, self.scheda_tecnica) def get_absolute_url(self): #return '/media/foto/FotoHardwareMuseo/' + self.data_inserimento.strftime('%d.%m.%Y') + '/' + self.image.name return '/media/%s' % self.image.name def admin_thumbnail(self): func = getattr(self, 'get_admin_thumbnail_url', None) if func is None: return _('An "admin_thumbnail" photo size has not been defined.') else: if hasattr(self, 'get_absolute_url'): return '<a class="foto_admin_thumbs" target="_blank" href="%s"><img src="%s"></a>' % \ (self.get_absolute_url(), func()) else: return '<a class="foto_admin_thumbs" target="_blank" href="%s"><img src="%s"></a>' % \ (self.image.url, func()) admin_thumbnail.short_description = _('Thumbnail') admin_thumbnail.allow_tags = True </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-3.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3,234,902,780,985,170,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">44.967033</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">117</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.671528</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.220169</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45174"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">XtheOne/Inverter-Data-Logger</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">InverterLib.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">3301</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">import socket import struct import os import binascii import sys if sys.version[0] == '2': reload(sys) sys.setdefaultencoding('cp437') def getNetworkIp(): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) s.connect(('<broadcast>', 0)) return s.getsockname()[0] def createV4RequestFrame(logger_sn): """Create request frame for inverter logger. The request string is build from several parts. The first part is a fixed 4 char string; the second part is the reversed hex notation of the s/n twice; then again a fixed string of two chars; a checksum of the double s/n with an offset; and finally a fixed ending char. Args: logger_sn (int): Serial number of the inverter Returns: str: Information request string for inverter """ #frame = (headCode) + (dataFieldLength) + (contrlCode) + (sn) + (sn) + (command) + (checksum) + (endCode) frame_hdr = binascii.unhexlify('680241b1') #from SolarMan / new Omnik app command = binascii.unhexlify('0100') defchk = binascii.unhexlify('87') endCode = binascii.unhexlify('16') tar = bytearray.fromhex(hex(logger_sn)[8:10] + hex(logger_sn)[6:8] + hex(logger_sn)[4:6] + hex(logger_sn)[2:4]) frame = bytearray(frame_hdr + tar + tar + command + defchk + endCode) checksum = 0 frame_bytes = bytearray(frame) for i in range(1, len(frame_bytes) - 2, 1): checksum += frame_bytes[i] & 255 frame_bytes[len(frame_bytes) - 2] = int((checksum & 255)) return bytearray(frame_bytes) def expand_path(path): """ Expand relative path to absolute path. Args: path: file path Returns: absolute path to file """ if os.path.isabs(path): return path else: return os.path.dirname(os.path.abspath(__file__)) + "/" + path def getLoggers(): # Create the datagram socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind((getNetworkIp(), 48899)) # Set a timeout so the socket does not block indefinitely when trying to receive data. sock.settimeout(3) # Set the time-to-live for messages to 1 so they do not go past the local network segment. ttl = struct.pack('b', 1) sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) SendData = "WIFIKIT-214028-READ" # Lotto/TM = "AT+YZAPP=214028,READ" gateways = '' try: # Send data to the broadcast address sent = sock.sendto(SendData, ('<broadcast>', 48899)) # Look for responses from all recipients while True: try: data, server = sock.recvfrom(1024) except socket.timeout: break else: if (data == SendData): continue #skip sent data a = data.split(',') wifi_ip, wifi_mac, wifi_sn = a[0],a[1],a[2] if (len(gateways)>1): gateways = gateways+',' gateways = gateways+wifi_ip+','+wifi_sn finally: sock.close() return gateways </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-3.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">8,714,258,900,020,281,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">33.385417</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">115</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.62678</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.54565</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45175"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">jiaojianbupt/tools</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">project_manager/alias.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1746</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "># -*- coding: utf-8 -*- """ Created by jiaojian at 2018/6/29 16:30 """ import os import sys import termios from tools.utils.basic_printer import print_with_style, ConsoleColor HOME = os.environ['HOME'] def get_input(): fd = sys.stdin.fileno() old_tty_info = termios.tcgetattr(fd) new_tty_info = old_tty_info[:] new_tty_info[3] &= ~termios.ICANON new_tty_info[3] &= ~termios.ECHO termios.tcsetattr(fd, termios.TCSANOW, new_tty_info) answer = os.read(fd, 1) termios.tcsetattr(fd, termios.TCSANOW, old_tty_info) return answer def add_alias(): if sys.platform == 'darwin': bash_profile_name = '.bash_profile' else: bash_profile_name = '.bashrc' linux_bash_profile_path = os.path.join(HOME, bash_profile_name) exec_file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'main.py') alias = 'alias updateall="python %s"' % exec_file_path if os.path.exists(linux_bash_profile_path): with open(linux_bash_profile_path, 'rw') as bashrc_file: bash_profile = bashrc_file.read() if bash_profile.find(alias) >= 0: return answer = '' while not answer or answer not in {'y', 'n'}: print_with_style('Add \'%s\' to your %s?(y/n)' % (alias, bash_profile_name), color=ConsoleColor.YELLOW) answer = get_input() if answer == 'n': return elif answer == 'y': break bash_profile = bash_profile + '\n' + alias with open(linux_bash_profile_path, 'w') as bashrc_file: bashrc_file.write(bash_profile) print_with_style('Alias added.', color=ConsoleColor.YELLOW) </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-3.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-6,002,306,353,356,231</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">35.375</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">119</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.587056</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.332061</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45176"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">dapengchen123/code_v1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">reid/datasets/market1501.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">3563</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">from __future__ import print_function, absolute_import import os.path as osp from ..utils.data import Dataset from ..utils.osutils import mkdir_if_missing from ..utils.serialization import write_json class Market1501(Dataset): url = 'https://drive.google.com/file/d/0B8-rUzbwVRk0c054eEozWG9COHM/view' md5 = '65005ab7d12ec1c44de4eeafe813e68a' def __init__(self, root, split_id=0, num_val=0.3, download=False): super(Market1501, self).__init__(root, split_id=split_id) if download: self.download() if not self._check_integrity(): raise RuntimeError("Dataset not found or corrupted. " + "You can use download=True to download it.") self.load(num_val) def download(self): if self._check_integrity(): print("Files already downloaded and verified") return import re import hashlib import shutil from glob import glob from zipfile import ZipFile raw_dir = osp.join(self.root, 'raw') mkdir_if_missing(raw_dir) # Download the raw zip file fpath = osp.join(raw_dir, 'Market-1501-v15.09.15.zip') if osp.isfile(fpath) and \ hashlib.md5(open(fpath, 'rb').read()).hexdigest() == self.md5: print("Using downloaded file: " + fpath) else: raise RuntimeError("Please download the dataset manually from {} " "to {}".format(self.url, fpath)) # Extract the file exdir = osp.join(raw_dir, 'Market-1501-v15.09.15') if not osp.isdir(exdir): print("Extracting zip file") with ZipFile(fpath) as z: z.extractall(path=raw_dir) # Format images_dir = osp.join(self.root, 'images') mkdir_if_missing(images_dir) # 1501 identities (+1 for background) with 6 camera views each identities = [[[] for _ in range(6)] for _ in range(1502)] def register(subdir, pattern=re.compile(r'([-\d]+)_c(\d)')): fpaths = sorted(glob(osp.join(exdir, subdir, '*.jpg'))) pids = set() for fpath in fpaths: fname = osp.basename(fpath) pid, cam = map(int, pattern.search(fname).groups()) if pid == -1: continue # junk images are just ignored assert 0 <= pid <= 1501 # pid == 0 means background assert 1 <= cam <= 6 cam -= 1 pids.add(pid) fname = ('{:08d}_{:02d}_{:04d}.jpg' .format(pid, cam, len(identities[pid][cam]))) identities[pid][cam].append(fname) shutil.copy(fpath, osp.join(images_dir, fname)) return pids trainval_pids = register('bounding_box_train') gallery_pids = register('bounding_box_test') query_pids = register('query') assert query_pids <= gallery_pids assert trainval_pids.isdisjoint(gallery_pids) # Save meta information into a json file meta = {'name': 'Market1501', 'shot': 'multiple', 'num_cameras': 6, 'identities': identities} write_json(meta, osp.join(self.root, 'meta.json')) # Save the only training / test split splits = [{ 'trainval': sorted(list(trainval_pids)), 'query': sorted(list(query_pids)), 'gallery': sorted(list(gallery_pids))}] write_json(splits, osp.join(self.root, 'splits.json')) </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-2,535,048,846,858,501,600</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">36.505263</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">78</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.561605</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.782378</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45177"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">glenflet/ZtoRGBpy</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">ZtoRGBpy/_info.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">2082</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "># -*- coding: utf-8 -*- # ================================================================================= # Copyright 2019 Glen Fletcher <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4f222e26230f28232a2129232a3b2c272a3d612c2022">[email protected]</a>> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # All documentation this file as docstrings or comments are licensed under the # Creative Commons Attribution-ShareAlike 4.0 International License; you may # not use this documentation except in compliance with this License. # You may obtain a copy of this License at # # https://creativecommons.org/licenses/by-sa/4.0 # # ================================================================================= """ ZtoRGB information definition module Special private module used for automatic processing, and inclusion .. moduleauthor:: Glen Fletcher <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cda0aca4a18daaa1a8a3aba1a8b9aea5a8bfe3aea2a0">[email protected]</a>> """ __authors__ = [ ("Glen Fletcher", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9df0fcf4f1ddfaf1f8f3fbf1f8e9fef5f8efb3fef2f0">[email protected]</a>")] __copyright__ = "2019 Glen Fletcher" __license__ = """\ The source code for this package is licensed under the [Apache 2.0 License](http://www.apache.org/licenses/LICENSE-2.0), while the documentation including docstrings and comments embedded in the source code are licensed under the [Creative Commons Attribution-ShareAlike 4.0 International License](https://creativecommons.org/licenses/by-sa/4.0) """ __contact__ = "Glen Fletcher <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="305d51595c70575c555e565c5544535855421e535f5d">[email protected]</a>>" __version__ = "2.0" __title__ = "ZtoRGBpy" __desc__ = """\ Complex number to perceptually uniform RGB subset mapping library""" __all__ = [ '__authors__', '__copyright__', '__license__', '__contact__', '__version__', '__title__', '__desc__'] </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-2,552,345,746,239,531,500</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">40.64</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">120</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.662344</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.869888</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45178"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">ElecProg/decmath</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">decmath/trig.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">4598</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">from decimal import getcontext, Decimal from decmath import _pi, _to_Decimal, sign # Trigonometric functions def acos(x): """Return the arc cosine (measured in radians) of x.""" x = _to_Decimal(x) if x.is_nan(): return Decimal("NaN") elif abs(x) > 1: raise ValueError("Domain error: acos accepts -1 <= x <= 1.") elif x == -1: return _pi() elif x == 0: return _pi() / 2 elif x == 1: return Decimal(0) getcontext().prec += 2 one_half = Decimal('0.5') i, lasts, s, gamma, fact, num = Decimal(0), 0, _pi() / 2 - x, 1, 1, x while s != lasts: lasts = s i += 1 fact *= i num *= x * x gamma *= i - one_half coeff = gamma / ((2 * i + 1) * fact) s -= coeff * num getcontext().prec -= 2 return +s def asin(x): """Return the arc sine (measured in radians) of x.""" x = _to_Decimal(x) if x.is_nan(): return Decimal("NaN") elif abs(x) > 1: raise ValueError("Domain error: asin accepts -1 <= x <= 1.") elif x == -1: return -_pi() / 2 elif x == 0: return Decimal(0) elif x == 1: return _pi() / 2 getcontext().prec += 2 one_half = Decimal('0.5') i, lasts, s, gamma, fact, num = Decimal(0), 0, x, 1, 1, x while s != lasts: lasts = s i += 1 fact *= i num *= x * x gamma *= i - one_half coeff = gamma / ((2 * i + 1) * fact) s += coeff * num getcontext().prec -= 2 return +s def atan(x): """Return the arc tangent (measured in radians) of x.""" x = _to_Decimal(x) if x.is_nan(): return Decimal("NaN") elif x == Decimal('-Inf'): return -_pi() / 2 elif x == 0: return Decimal(0) elif x == Decimal('Inf'): return _pi() / 2 if x < -1: c = _pi() / -2 x = 1 / x elif x > 1: c = _pi() / 2 x = 1 / x else: c = 0 getcontext().prec += 2 x_squared = x**2 y = x_squared / (1 + x_squared) y_over_x = y / x i, lasts, s, coeff, num = Decimal(0), 0, y_over_x, 1, y_over_x while s != lasts: lasts = s i += 2 coeff *= i / (i + 1) num *= y s += coeff * num if c: s = c - s getcontext().prec -= 2 return +s def atan2(y, x): """Return the arc tangent (measured in radians) of y/x. Unlike atan(y/x), the signs of both x and y are considered.""" y = _to_Decimal(y) x = _to_Decimal(x) abs_y = abs(y) abs_x = abs(x) y_is_real = abs_y != Decimal('Inf') if y.is_nan() or x.is_nan(): return Decimal("NaN") if x: if y_is_real: a = y and atan(y / x) or Decimal(0) if x < 0: a += sign(y) * _pi() return a elif abs_y == abs_x: x = sign(x) y = sign(y) return _pi() * (Decimal(2) * abs(x) - x) / (Decimal(4) * y) if y: return atan(sign(y) * Decimal('Inf')) elif sign(x) < 0: return sign(y) * _pi() else: return sign(y) * Decimal(0) def cos(x): """Return the cosine of x as measured in radians.""" x = _to_Decimal(x) % (2 * _pi()) if x.is_nan(): return Decimal('NaN') elif x == _pi() / 2 or x == 3 * _pi() / 2: return Decimal(0) getcontext().prec += 2 i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1 while s != lasts: lasts = s i += 2 fact *= i * (i - 1) num *= x * x sign *= -1 s += num / fact * sign getcontext().prec -= 2 return +s def hypot(x, y): """Return the Euclidean distance, sqrt(x*x + y*y).""" return (_to_Decimal(x).__pow__(2) + _to_Decimal(y).__pow__(2)).sqrt() def sin(x): """Return the sine of x as measured in radians.""" x = _to_Decimal(x) % (2 * _pi()) if x.is_nan(): return Decimal('NaN') elif x == 0 or x == _pi(): return Decimal(0) getcontext().prec += 2 i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1 while s != lasts: lasts = s i += 2 fact *= i * (i - 1) num *= x * x sign *= -1 s += num / fact * sign getcontext().prec -= 2 return +s def tan(x): """Return the tangent of x (measured in radians).""" x = _to_Decimal(x) if x.is_nan(): return Decimal('NaN') elif x == _pi() / 2: return Decimal('Inf') elif x == 3 * _pi() / 2: return Decimal('-Inf') return sin(x) / cos(x) </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-8,599,662,519,578,526,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">22.579487</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">73</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.45933</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.102564</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45179"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">martindurant/astrobits</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">time_series.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">12543</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">"""Take a list of files and known star coordinates, and perform photometry on them all, either with apertures (phot) or by PSF fitting (daophot, which required additional parameters and is apropriate to poor S/N or crowded fields). Makes extensive use of iraf tasks; set all photometry parameters before running: datapars - for data characteristics centerpars - finding the reference star on each image. centerpars, photpars, fitskypars - for controling aperture photometry daopars - for controling daophot filelist: set of image files, in IRAF syntax (image.fits[1][*,*,2] etc); can be more than one per cube. coords: name a file containing all star coords for photometry, based on an image unshifted relative to (0,0) in the shifts list. Be pure numbers for phot method, .mag or .als for daophot method. shifts: name a file containing shifts, a tuple of shifts arrays, image header keywords (tuple of two= or None for no shifts refstar: coords of star for deriving (x,y) offset, as in coords timestamp: source of the timing information: a header keyword, delta-t for uniform sampling or a file with times (in whatever formate you'll be using later. psf: whether to use daophot or aperture phot for analysis. If this is a filename, that is the PSF profile to use for every image; if it is "True", make a new PSF for every image. Pars below only for full PSF fitting pststars: a .pst file from daophot, listing the IDs of stars for making the PSF for each image. NB: DAOphot refuses to measure any star with SNR<2. ids: which stars are interesting, by ID (in input coord list order) coords: starting well-measured coords (pdump-ed from a .als, perhaps). """ import os import numpy from glob import glob import pyfits from pylab import find from numpy import load,vstack,save,median thisdir = os.getcwd() os.chdir("/home/durant") from pyraf import iraf iraf.cd(thisdir) iraf.digiphot() iraf.daophot() import pyraf import pyfits import numpy as n def shift_file_coords(filename,xshift,yshift,output,sort=None): """Understands filetypes: 2-column ascii numbers, .mag, .als, .pst. NB: shift means where each image is, relative to the original (not where it should be moved to). """ if not(sort): sort = 'num' if filename.find('.mag')>0: sort = 'mag' if filename.find('.als')>0: sort = 'als' if filename.find('.pst')>0: sort = 'pst' if not(sort=='num' or sort=='mag' or sort=='als' or sort=='pst'): raise ValueError('Unknown input filetype: %s'%filename) if sort=='num': # shift 2-column numeric ASCII table x,y = load(filename,usecols=[0,1],unpack=True) x += xshift y += yshift X = vstack((x,y)) save(output,X.transpose()) return if sort=='mag': #shift a .mag photometry file fred = open(filename) freda= open(output,'w') for line in fred: if line.split()[-1]=='\\' and len(line.split())==9 and line[0]!='#': x = float(line.split()[0]) + xshift y = float(line.split()[1]) + yshift line = "%-14.3f %-11.3f"%(x,y)+line[21:] freda.write(line) if sort=='als': #shift a .als DAOphot photometry file fred = open(filename) freda= open(output,'w') for line in fred: if line.split()[-1]=='\\' and len(line.split())==8 and line[0]!='#': x = float(line.split()[1]) + xshift y = float(line.split()[2]) + yshift line = line[:9] + "%-10.3f %-10.3f"%(x,y) + line[29:] freda.write(line) if sort=='pst': #shift a PSF star list for DAOphot fred = open(filename) freda= open(output,'w') for line in fred: if line[0]!="#": x = float(line.split()[1]) + xshift y = float(line.split()[2]) + yshift line = line[:9] + "%-10.3f %-10.3f"%(x,y) + line[29:] freda.write(line) fred.close() freda.close() def recentre(image,refcoordfile): """Returns improved shift by centroiding on the reference star using phot. This can be VERY sensitive to the parameters in centerpars.""" xin,yin = load(refcoordfile,unpack=True) try: iraf.phot(image,refcoordfile,'temp.mag',inter="no",calgorithm='centroid', mode='h',verify='no',update='no',verbose='no') xout,yout=iraf.pdump('temp.mag','xcen,ycen','yes',Stdout=1)[0].split() except: print "Recentring failed on", image return 0.,0. xout,yout = float(xout),float(yout) return xout-xin,yout-yin vary_par = 1. vary_max = 10 vary_min = 6 vary_fwhm= 0 def setaperture(image,refstar): """Measure the FWHM of the reference star unsing simple DAOphot editor and then set the photometry aperture to this number""" x,y = load(refstar,unpack=True) fred = open('tempaperfile','w') fred.write("%f %f 100 a\nq"%(x,y)) fred.close() try: output=iraf.daoedit(image,icomm='tempaperfile',Stdout=1,Stderr=1) except: print "Aperture setting failed on",image return FWHM = float(output[3].split()[4]) iraf.photpars.apertures = min(max(FWHM*vary_par,vary_min),vary_max) iraf.daopars.fitrad = min(max(FWHM*vary_par,vary_min),vary_max) global vary_fwhm vary_fwhm = FWHM print "FWHM: ", FWHM, " aperture: ",iraf.photpars.apertures def apphot(image,coords,refstar=None,centre=False,vary=False): """Apperture photometry with centering based on a reference star. NB: centre refers to shifting the coordinates by centroiding on the reference star; recentering on the final phot depends on centerpars.calgorithm .""" iraf.dele('temp.mag*') if centre: xsh,ysh = recentre(image,refstar) print "Fine centring: ", xsh,ysh else: #no recentreing by reference star (but could still have calgorithm!=none) xsh,ysh = 0,0 if vary: setaperture(image,refstar) shift_file_coords(coords,xsh,ysh,'tempcoords') iraf.phot(image,'tempcoords','temp.mag2',inter="no", mode='h',verify='no',update='no',verbose='no') out = iraf.pdump('temp.mag2','id,flux,msky,stdev','yes',Stdout=1) return out def psfphot(image,coords,pststars,refstar,centre=True,vary=False): """PSF photometry. Centering is through phot on refstar. Assume coords is a .als file for now. Recentering is always done for the reference star, never for the targets.""" iraf.dele('temp.mag*') iraf.dele('temp.psf.fits') iraf.dele('temp.als') if centre: xsh,ysh = recentre(image,refstar) print "Fine Centring: ", xsh,ysh else: xsh,ysh = 0,0 if vary: setaperture(image,refstar) shift_file_coords(coords,xsh,ysh,'tempcoords2',sort='als') shift_file_coords(pststars,xsh,ysh,'temppst2',sort='pst') iraf.phot(image,'tempcoords2','temp.mag2',inter="no",calgorithm='none', mode='h',verify='no',update='no',verbose='no') iraf.psf(image,'temp.mag2','temppst2','temp.psf','temp.mag.pst','temp.mag.psg', inter='no',mode='h',verify='no',update='no',verbose='no') iraf.allstar(image,'temp.mag2','temp.psf','temp.als','temp.mag.arj',"default", mode='h',verify='no',update='no',verbose='no') out = iraf.pdump('temp.als','id,mag,merr,msky','yes',Stdout=1) return out def simplepsfphot(image,coords,psf,refstar,centre=True,vary=False): """PSF photometry, with a given PSF file in psf used for every image""" iraf.dele('temp.mag*') iraf.dele('temp.als') iraf.dele('temp.sub.fits') if centre: xsh,ysh = recentre(image,refstar) print "Fine Centring: ", xsh,ysh else: xsh,ysh = 0,0 if vary: setaperture(image,refstar) shift_file_coords(coords,xsh,ysh,'tempcoords2',sort='als') iraf.phot(image,'tempcoords2','temp.mag2',inter="no",calgorithm='none', mode='h',verify='no',update='no',verbose='no') iraf.allstar(image,'temp.mag2',psf,'temp.als','temp.mag.arj','temp.sub.fits', mode='h',verify='no',update='no',verbose='no') out = iraf.pdump('temp.als','id,mag,merr,msky','yes',Stdout=1) return out def custom1(filename): # for NACO timing mode cubes - removes horizontal banding #iraf.imarith(filename,'-','dark','temp') iraf.imarith(filename,'/','flatK','temp') im = pyfits.getdata('temp.fits') med = median(im.transpose()) out = ((im).transpose()-med).transpose() (pyfits.ImageHDU(out)).writeto("temp2.fits",clobber=True) iraf.imdel('temp') iraf.imcopy('temp2[1]','temp') def get_id(starid,output='output'): """from the output of the photometry, grab the magnitudes and magerrs of starid""" mag = load(output,usecols=[4+starid*4]) merr= load(output,usecols=[5+starid*4]) return mag,merr def run(filelist,coords,refstar,shifts=None,centre=False,psf=False,pststars=None, ids=None,dark=0,flat=1,timestamp="TIME",output='output',custom_process=None, vary=False): """If psf==True, must include all extra par files. If PSF is a filename (.psf.fits), this profileis used to fit every image. Timestamp can be either a file of times (same length as filelist), a header keyword, or an array of times. The input list can include [] notation for multiple extensions or sections of each file (incompatible with header-based time-stamps). custom_process(file) is a function taking a filename (possible including [x] syntax) and places a processed image in temp.fits.""" output = open(output,'w') x = load(coords,usecols=[1]) numstars = len(x) myfiles = open(filelist).readlines() myfiles = [myfiles[i][:-1] for i in range(len(myfiles))] if timestamp.__class__ == numpy.ndarray: #--sort out times-- times = 1 #times=1 means we know the times beforehand elif len(glob(timestamp))>0: timestamp = load(timestamp,usecols=[0]) times=1 else: times=0 #times=0 mean find the time from each image if type(shifts)==type(" "): #--sort out shifts-- xshifts,yshifts = load(shifts,unpack=True)#filename give, assuming 2 columns xshifts,yshifts = -xshifts,-yshifts #these are in the opposite sense to coords from stack elif n.iterable(shifts): xshifts=n.array(shifts[0]) #for shifts given as arrays/lists yshifts=n.array(shifts[1]) else: print "No shifts" #assume all shifts are zero xshifts = n.zeros(len(myfiles)) yshifts = n.zeros(len(myfiles)) for i,thisfile in enumerate(myfiles): #run! print i,thisfile if times: time = timestamp[i] #known time else: time = pyfits.getval(thisfile,timestamp) #FITS keyword try: iraf.dele('temp.fits') if custom_process: #arbitrary subroutine to process a file -> temp.fits custom_process(thisfile) else: #typical dark/bias subtract and flatfield iraf.imarith(thisfile,'-',dark,'temp') iraf.imarith('temp','/',flat,'temp') shift_file_coords(coords,xshifts[i],yshifts[i],'tempcoords') #apply coarse shifts shift_file_coords(refstar,xshifts[i],yshifts[i],'tempref',sort='num') if psf: if psf is True: #full PSF fit shift_file_coords(pststars,xshifts[i],yshifts[i],'temppst') out=psfphot('temp.fits','tempcoords','temppst','tempref',centre,vary) else: #DAOphot with known PSF out=simplepsfphot('temp.fits','tempcoords',psf,'tempref',centre,vary) else: #aperture photometry out=apphot('temp.fits','tempcoords','tempref',centre,vary=vary) output.write("%s %s %s "%(thisfile,time,vary_fwhm)) myids = n.array([int(out[i].split()[0]) for i in range(len(out))]) for i in ids or range(numstars): try: #search for each requested ID foundid = find(myids==i)[0] output.write(out[foundid]+" ") except: #ID not found output.write(" 0 0 0 0 ") output.write("\n") except KeyboardInterrupt: #exit on Ctrl-C break except pyraf.irafglobals.IrafError, err: print "IRAF error ",err,thisfile break except ValueError, err: print "Value error ",err,thisfile raise output.close() #iraf.dele('temp*') </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-5,665,480,579,238,870,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">42.251724</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">97</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.63358</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.20957</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45180"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">freelawproject/recap-server</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">settings.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1377</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">"""Settings are derived by compiling any files ending in .py in the settings directory, in alphabetical order. This results in the following concept: - default settings are in 10-public.py (this should contain most settings) - custom settings are in 05-private.py (an example of this file is here for you) - any overrides to public settings can go in 20-private.py (you'll need to create this) """ from __future__ import with_statement import os import glob import sys def _generate_secret_key(file_path): import random chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)' def random_char(): return chars[int(len(chars)*random.random())] rand_str = ''.join(random_char() for i in range(64)) with open(file_path, 'w') as f: f.write('SECRET_KEY=%s\n' % repr(rand_str)) ROOT_PATH = os.path.dirname(__file__) # Try importing the SECRET_KEY from the file secret_key.py. If it doesn't exist, # there is an import error, and the key is generated and written to the file. try: from secret_key import SECRET_KEY except ImportError: _generate_secret_key(os.path.join(ROOT_PATH, 'secret_key.py')) from secret_key import SECRET_KEY # Load the conf files. conf_files = glob.glob(os.path.join( os.path.dirname(__file__), 'settings', '*.py')) conf_files.sort() for f in conf_files: execfile(os.path.abspath(f)) </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-3.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">8,784,527,857,870,266,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">31.023256</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">80</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.697168</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.451128</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45181"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mxamin/youtube-dl</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">youtube_dl/extractor/criterion.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1284</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "># -*- coding: utf-8 -*- from __future__ import unicode_literals import re from .common import InfoExtractor class CriterionIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?criterion\.com/films/(?P<id>[0-9]+)-.+' _TEST = { 'url': 'http://www.criterion.com/films/184-le-samourai', 'md5': 'bc51beba55685509883a9a7830919ec3', 'info_dict': { 'id': '184', 'ext': 'mp4', 'title': 'Le Samouraï', 'description': 'md5:a2b4b116326558149bef81f76dcbb93f', } } def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) video_id = mobj.group('id') webpage = self._download_webpage(url, video_id) final_url = self._search_regex( r'so.addVariable\("videoURL", "(.+?)"\)\;', webpage, 'video url') title = self._og_search_title(webpage) description = self._html_search_meta('description', webpage) thumbnail = self._search_regex( r'so.addVariable\("thumbnailURL", "(.+?)"\)\;', webpage, 'thumbnail url') return { 'id': video_id, 'url': final_url, 'title': title, 'description': description, 'thumbnail': thumbnail, } </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">unlicense</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-7,290,849,255,959,012,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">30.292683</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">77</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.535464</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.439678</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45182"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">qedsoftware/commcare-hq</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">custom/opm/constants.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1732</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">from corehq.apps.fixtures.models import FixtureDataItem from corehq.util.quickcache import quickcache DOMAIN = 'opm' PREG_REG_XMLNS = "http://openrosa.org/formdesigner/D127C457-3E15-4F5E-88C3-98CD1722C625" VHND_XMLNS = "http://openrosa.org/formdesigner/ff5de10d75afda15cddb3b00a0b1e21d33a50d59" BIRTH_PREP_XMLNS = "http://openrosa.org/formdesigner/50378991-FEC3-408D-B4A5-A264F3B52184" DELIVERY_XMLNS = "http://openrosa.org/formdesigner/492F8F0E-EE7D-4B28-B890-7CDA5F137194" CHILD_FOLLOWUP_XMLNS = "http://openrosa.org/formdesigner/C90C2C1F-3B34-47F3-B3A3-061EAAC1A601" CFU1_XMLNS = "http://openrosa.org/formdesigner/d642dd328514f2af92c093d414d63e5b2670b9c" CFU2_XMLNS = "http://openrosa.org/formdesigner/9ef423bba8595a99976f0bc9532617841253a7fa" CFU3_XMLNS = "http://openrosa.org/formdesigner/f15b9f8fb92e2552b1885897ece257609ed16649" GROWTH_MONITORING_XMLNS= "http://openrosa.org/formdesigner/F1356F3F-C695-491F-9277-7F9B5522200C" CLOSE_FORM = "http://openrosa.org/formdesigner/41A1B3E0-C1A4-41EA-AE90-71A328F0D8FD" CHILDREN_FORMS = [CFU1_XMLNS, CFU2_XMLNS, CFU3_XMLNS, CHILD_FOLLOWUP_XMLNS] OPM_XMLNSs = [PREG_REG_XMLNS, VHND_XMLNS, BIRTH_PREP_XMLNS, DELIVERY_XMLNS, CHILD_FOLLOWUP_XMLNS, CFU1_XMLNS, CFU2_XMLNS, CFU3_XMLNS, GROWTH_MONITORING_XMLNS, CLOSE_FORM] # TODO Move these to a cached fixtures lookup MONTH_AMT = 250 TWO_YEAR_AMT = 2000 THREE_YEAR_AMT = 3000 @quickcache([], timeout=30 * 60) def get_fixture_data(): fixtures = FixtureDataItem.get_indexed_items(DOMAIN, 'condition_amounts', 'condition') return dict((k, int(fixture['rs_amount'])) for k, fixture in fixtures.items()) class InvalidRow(Exception): """ Raise this in the row constructor to skip row """ </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">bsd-3-clause</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">7,714,274,633,423,886,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">44.578947</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">96</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.769053</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">2.255208</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45183"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">tonioo/modoboa</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">modoboa/lib/u2u_decode.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">2282</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "># -*- coding: utf-8 -*- """ Unstructured rfc2047 header to unicode. A stupid (and not accurate) answer to https://bugs.python.org/issue1079. """ from __future__ import unicode_literals import re from email.header import decode_header, make_header from email.utils import parseaddr from django.utils.encoding import smart_text # check spaces between encoded_words (and strip them) sre = re.compile(r"\?=[ \t]+=\?") # re pat for MIME encoded_word (without trailing spaces) mre = re.compile(r"=\?[^?]*?\?[bq]\?[^?\t]*?\?=", re.I) # re do detect encoded ASCII characters ascii_re = re.compile(r"=[\dA-F]{2,3}", re.I) def clean_spaces(m): """Replace unencoded spaces in string. :param str m: a match object :return: the cleaned string """ return m.group(0).replace(" ", "=20") def clean_non_printable_char(m): """Strip non printable characters.""" code = int(m.group(0)[1:], 16) if code < 20: return "" return m.group(0) def decode_mime(m): """Substitute matching encoded_word with unicode equiv.""" h = decode_header(clean_spaces(m)) try: u = smart_text(make_header(h)) except (LookupError, UnicodeDecodeError): return m.group(0) return u def clean_header(header): """Clean header function.""" header = "".join(header.splitlines()) header = sre.sub("?==?", header) return ascii_re.sub(clean_non_printable_char, header) def u2u_decode(s): """utility function for (final) decoding of mime header note: resulting string is in one line (no \n within) note2: spaces between enc_words are stripped (see RFC2047) """ return mre.sub(decode_mime, clean_header(s)).strip(" \r\t\n") def decode_address(value): """Special function for address decoding. We need a dedicated processing because RFC1342 explicitely says address MUST NOT contain encoded-word: These are the ONLY locations where an encoded-word may appear. In particular, an encoded-word MUST NOT appear in any portion of an "address". In addition, an encoded-word MUST NOT be used in a Received header field. """ phrase, address = parseaddr(clean_header(value)) if phrase: phrase = mre.sub(decode_mime, phrase) return phrase, address </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">isc</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-962,520,203,660,710,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">26.493976</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">72</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.660824</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.510769</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45184"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">tudarmstadt-lt/topicrawler</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">lt.lm/src/main/py/mr_ngram_count.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1297</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">#!/usr/bin/env python # -*- coding: utf-8 -*- """ test: cat data | map | sort | reduce cat data | ./x.py -m | sort | ./x.py -r hadoop jar /opt/cloudera/parcels/CDH/lib/hadoop-mapreduce/hadoop-streaming.jar \ -files x.py \ -mapper 'x.py -m' \ -reducer 'x.py -r' \ -input in \ -output out @author: stevo """ from __future__ import print_function from __future__ import division import itertools as it import sys def readlines(): with sys.stdin as f: for line in f: if line.strip(): yield line def mapper(lines): for line in lines: print('{}'.format(line.rstrip())) def line2tuple(lines): for line in lines: splits = line.rstrip().split('\t') yield splits def reducer(lines, mincount=1): for key, values in it.groupby(lines, lambda line : line.rstrip()): num = reduce(lambda x, y: x + 1, values, 0) if num >= mincount: print('{}\t{}'.format(key, num)) if len(sys.argv) < 2: raise Exception('specify mapper (-m) or reducer (-r) function') t = sys.argv[1] mincount = int(sys.argv[2]) if len(sys.argv) > 2 else 1 if '-m' == t: mapper(readlines()); elif '-r' == t: reducer(readlines(), mincount); else: raise Exception('specify mapper (-m) or reducer (-r) function')</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">apache-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-1,830,261,497,265,860,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">22.6</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">80</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.597533</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.117788</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45185"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Ziqi-Li/bknqgis</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">bokeh/bokeh/sphinxext/example_handler.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">2905</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">import sys from ..application.handlers.code_runner import CodeRunner from ..application.handlers.handler import Handler from ..io import set_curdoc, curdoc class ExampleHandler(Handler): """ A stripped-down handler similar to CodeHandler but that does some appropriate monkeypatching to """ _output_funcs = ['output_notebook', 'output_file', 'reset_output'] _io_funcs = ['show', 'save'] def __init__(self, source, filename): super(ExampleHandler, self).__init__(self) self._runner = CodeRunner(source, filename, []) def modify_document(self, doc): if self.failed: return module = self._runner.new_module() sys.modules[module.__name__] = module doc._modules.append(module) old_doc = curdoc() set_curdoc(doc) old_io, old_doc = self._monkeypatch() try: self._runner.run(module, lambda: None) finally: self._unmonkeypatch(old_io, old_doc) set_curdoc(old_doc) def _monkeypatch(self): def _pass(*args, **kw): pass def _add_root(obj, *args, **kw): from bokeh.io import curdoc curdoc().add_root(obj) def _curdoc(*args, **kw): return curdoc() # these functions are transitively imported from io into plotting, # so we have to patch them all. Assumption is that no other patching # has occurred, i.e. we can just save the funcs being patched once, # from io, and use those as the originals to replace everywhere import bokeh.io as io import bokeh.plotting as p mods = [io, p] # TODO (bev) restore when bkcharts package is ready (but remove at 1.0 release) # import bkcharts as c # mods.append(c) old_io = {} for f in self._output_funcs + self._io_funcs: old_io[f] = getattr(io, f) for mod in mods: for f in self._output_funcs: setattr(mod, f, _pass) for f in self._io_funcs: setattr(mod, f, _add_root) import bokeh.document as d old_doc = d.Document d.Document = _curdoc return old_io, old_doc def _unmonkeypatch(self, old_io, old_doc): import bokeh.io as io import bokeh.plotting as p mods = [io, p] # TODO (bev) restore when bkcharts package is ready (but remove at 1.0 release) # import bkcharts as c # mods.append(c) for mod in mods: for f in old_io: setattr(mod, f, old_io[f]) import bokeh.document as d d.Document = old_doc @property def failed(self): return self._runner.failed @property def error(self): return self._runner.error @property def error_detail(self): return self._runner.error_detail </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-5,235,527,630,608,026,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">27.203883</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">87</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.578313</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.878505</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45186"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">BurningNetel/ctf-manager</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">CTFmanager/tests/views/event/test_event.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">6138</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">import json from django.core.urlresolvers import reverse from CTFmanager.tests.views.base import ViewTestCase class EventPageAJAXJoinEventTest(ViewTestCase): """ Tests that a user can join an event A user should be able to join upcoming events. And get a response without the page reloading """ def get_valid_event_join_post(self): event = self.create_event() response = self.client.post(reverse('event_join', args=[event.name])) _json = json.loads(response.content.decode()) return _json, event def test_POST_returns_expected_json_on_valid_post(self): _json, event = self.get_valid_event_join_post() self.assertEqual(200, _json['status_code']) def test_POST_gives_correct_user_count(self): _json, event = self.get_valid_event_join_post() self.assertEqual(1, _json['members']) def test_logout_POST_gives_401_and_negative(self): self.client.logout() _json, event = self.get_valid_event_join_post() self.assertEqual(-1, _json['members']) self.assertEqual(401, _json['status_code']) def test_duplicate_POST_gives_304_and_negative(self): _json, event = self.get_valid_event_join_post() response = self.client.post(reverse('event_join', args=[event.name])) _json = json.loads(response.content.decode()) self.assertEqual(-1, _json['members']) self.assertEqual(304, _json['status_code']) def test_valid_DELETE_gives_valid_json(self): event = self.create_event_join_user() response = self.client.delete(reverse('event_join', args=[event.name])) _json = json.loads(response.content.decode()) self.assertEqual(200, _json['status_code']) self.assertEqual(0, _json['members']) def test_duplicate_DELETE_gives_304_and_negative(self): event = self.create_event_join_user() self.client.delete(reverse('event_join', args=[event.name])) response = self.client.delete(reverse('event_join', args=[event.name])) _json = json.loads(response.content.decode()) self.assertEqual(304, _json['status_code']) self.assertEqual(-1, _json['members']) def test_logout_then_DELTE_gives_401_and_negative(self): event = self.create_event_join_user() self.client.logout() response = self.client.delete(reverse('event_join', args=[event.name])) _json = json.loads(response.content.decode()) self.assertEqual(401, _json['status_code']) self.assertEqual(-1, _json['members']) def create_event_join_user(self): event = self.create_event() event.join(self.user) return event class EventPageTest(ViewTestCase): def test_events_page_requires_authentication(self): self.client.logout() response = self.client.get(reverse('events')) self.assertRedirects(response, reverse('login') + '?next=' + reverse('events')) def test_events_page_renders_events_template(self): response = self.client.get(reverse('events')) self.assertTemplateUsed(response, 'event/events.html') def test_events_page_contains_new_event_button(self): response = self.client.get(reverse('events')) expected = 'id="btn_add_event" href="/events/new/">Add Event</a>' self.assertContains(response, expected) def test_events_page_displays_only_upcoming_events(self): event_future = self.create_event("hatCTF", True) event_past = self.create_event("RuCTF_2015", False) response = self.client.get(reverse('events')) _event = response.context['events'] self.assertEqual(_event[0], event_future) self.assertEqual(len(_event), 1) self.assertNotEqual(_event[0], event_past) def test_events_page_has_correct_headers(self): response = self.client.get(reverse('events')) expected = 'Upcoming Events' expected2 = 'Archive' self.assertContains(response, expected) self.assertContains(response, expected2) def test_empty_events_set_shows_correct_message(self): response = self.client.get(reverse('events')) expected = 'No upcoming events!' self.assertContains(response, expected) def test_events_page_display_archive(self): event_past = self.create_event('past_event', False) response = self.client.get(reverse('events')) archive = response.context['archive'] self.assertContains(response, '<table id="table_archive"') self.assertContains(response, event_past.name) self.assertEqual(archive[0], event_past) def test_events_page_displays_error_message_when_nothing_in_archive(self): response = self.client.get(reverse('events')) archive = response.context['archive'] self.assertEqual(len(archive), 0) self.assertContains(response, 'No past events!') def test_event_page_displays_event_members_count(self): event = self.create_event() response = self.client.get(reverse('events')) self.assertContains(response, '0 Participating') event.members.add(self.user) event.save() response = self.client.get(reverse('events')) self.assertContains(response, '1 Participating') def test_event_page_displays_correct_button_text(self): event = self.create_event() response = self.client.get(reverse('events')) self.assertContains(response, 'Join</button>') event.join(self.user) response = self.client.get(reverse('events')) self.assertContains(response, 'Leave</button>') def test_event_page_shows_username_in_popup(self): event = self.create_event() response = self.client.get(reverse('events')) self.assertContains(response, self.user.username, 1) self.assertContains(response, 'Nobody has joined yet!') event.join(self.user) response = self.client.get(reverse('events')) self.assertContains(response, self.user.username, 2) self.assertNotContains(response, 'Nobody has joined yet!')</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-3.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-6,477,876,122,721,076,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">38.352564</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">87</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.654774</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.807692</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">true</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45187"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">jeffmurphy/cif-router</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">poc/cif-router.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">21349</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">#!/usr/bin/python # # # cif-router proof of concept # # cif-router [-p pubport] [-r routerport] [-m myname] [-h] # -p default: 5556 # -r default: 5555 # -m default: cif-router # # cif-router is a zmq device with the following sockets: # XPUB # for republishing messages # XSUB # for subscribing to message feeds # ROUTER # for routing REQ/REP messages between clients # also for accepting REQs from clients # locally accepted types: # REGISTER, UNREGISTER, LIST-CLIENTS # locally generated replies: # UNAUTHORIZED, OK, FAILED # # communication between router and clients is via CIF.msg passing # the 'ControlStruct' portion of CIF.msg is used for communication # # a typical use case: # # cif-smrt's REQ connects to ROUTER and sends a REGISTER message with dst=cif-router # cif-router's ROUTER responds with SUCCESS (if valid) or UNAUTHORIZED (if not valid) # the apikey will be validated during this step # cif-router's XSUB connects to cif-smrt's XPUB # cif-smrt begins publishing CIF messages # cif-router re-publishes the CIF messages to clients connected to cif-router's XPUB # clients may be: cif-correlator, cif-db import sys import zmq import time import datetime import threading import getopt import json import pprint import struct sys.path.append('/usr/local/lib/cif-protocol/pb-python/gen-py') import msg_pb2 import feed_pb2 import RFC5070_IODEF_v1_pb2 import MAEC_v2_pb2 import control_pb2 import cifsupport sys.path.append('../../libcif/lib') from CIF.RouterStats import * from CIF.CtrlCommands.Clients import * from CIF.CtrlCommands.Ping import * from CIFRouter.MiniClient import * from CIF.CtrlCommands.ThreadTracker import ThreadTracker myname = "cif-router" def dosubscribe(client, m): client = m.src if client in publishers : print "dosubscribe: we've seen this client before. re-using old connection." return control_pb2.ControlType.SUCCESS elif clients.isregistered(client) == True: if clients.apikey(client) == m.apikey: print "dosubscribe: New publisher to connect to " + client publishers[client] = time.time() addr = m.iPublishRequest.ipaddress port = m.iPublishRequest.port print "dosubscribe: connect our xsub -> xpub on " + addr + ":" + str(port) xsub.connect("tcp://" + addr + ":" + str(port)) return control_pb2.ControlType.SUCCESS print "dosubscribe: iPublish from a registered client with a bad apikey: " + client + " " + m.apikey print "dosubscribe: iPublish from a client who isnt registered: \"" + client + "\"" return control_pb2.ControlType.FAILED def list_clients(client, apikey): if clients.isregistered(client) == True and clients.apikey(client) == apikey: return clients.asmessage() return None def make_register_reply(msgfrom, _apikey): msg = control_pb2.ControlType() msg.version = msg.version # required msg.type = control_pb2.ControlType.REPLY msg.command = control_pb2.ControlType.REGISTER msg.dst = msgfrom msg.src = "cif-router" print "mrr " + _apikey msg.apikey = _apikey return msg def make_unregister_reply(msgfrom, _apikey): msg = control_pb2.ControlType() msg.version = msg.version # required msg.type = control_pb2.ControlType.REPLY msg.command = control_pb2.ControlType.UNREGISTER msg.dst = msgfrom msg.src = "cif-router" msg.apikey = _apikey return msg def make_msg_seq(msg): _md5 = hashlib.md5() _md5.update(msg.SerializeToString()) return _md5.digest() def handle_miniclient_reply(socket, routerport, publisherport): pending_registers = miniclient.pending_apikey_lookups() print "pending_apikey_lookups: ", pending_registers for apikey in pending_registers: if apikey in register_wait_map: reply_to = register_wait_map[apikey] apikey_results = miniclient.get_pending_apikey(apikey) print " send reply to: ", reply_to msg = make_register_reply(reply_to['msgfrom'], apikey) msg.status = control_pb2.ControlType.FAILED if apikey_results != None: if apikey_results.revoked == False: if apikey_results.expires == 0 or apikey_results.expires >= time.time(): msg.registerResponse.REQport = routerport msg.registerResponse.PUBport = publisherport msg.status = control_pb2.ControlType.SUCCESS clients.register(reply_to['msgfrom'], reply_to['from_zmqid'], apikey) print " Register succeeded." else: print " Register failed: key expired" else: print " Register failed: key revoked" else: print " Register failed: unknown key" msg.seq = reply_to['msgseq'] socket.send_multipart([reply_to['from_zmqid'], '', msg.SerializeToString()]) del register_wait_map[apikey] elif apikey in unregister_wait_map: reply_to = unregister_wait_map[apikey] apikey_results = miniclient.get_pending_apikey(apikey) print " send reply to: ", reply_to msg = make_unregister_reply(reply_to['msgfrom'], apikey) msg.status = control_pb2.ControlType.FAILED if apikey_results != None: if apikey_results.revoked == False: if apikey_results.expires == 0 or apikey_results.expires >= time.time(): msg.status = control_pb2.ControlType.SUCCESS clients.unregister(reply_to['msgfrom']) print " Unregister succeeded." else: print " Unregister failed: key expired" else: print " Unregister failed: key revoked" else: print " Unregister failed: unknown key" msg.seq = reply_to['msgseq'] socket.send_multipart([reply_to['from_zmqid'], '', msg.SerializeToString()]) del unregister_wait_map[apikey] miniclient.remove_pending_apikey(apikey) def myrelay(pubport): relaycount = 0 print "[myrelay] Create XPUB socket on " + str(pubport) xpub = context.socket(zmq.PUB) xpub.bind("tcp://*:" + str(pubport)) while True: try: relaycount = relaycount + 1 m = xsub.recv() _m = msg_pb2.MessageType() _m.ParseFromString(m) if _m.type == msg_pb2.MessageType.QUERY: mystats.setrelayed(1, 'QUERY') elif _m.type == msg_pb2.MessageType.REPLY: mystats.setrelayed(1, 'REPLY') elif _m.type == msg_pb2.MessageType.SUBMISSION: mystats.setrelayed(1, 'SUBMISSION') for bmt in _m.submissionRequest: mystats.setrelayed(1, bmt.baseObjectType) print "[myrelay] total:%d got:%d bytes" % (relaycount, len(m)) #print "[myrelay] got msg on our xsub socket: " , m xpub.send(m) except Exception as e: print "[myrelay] invalid message received: ", e def usage(): print "cif-router [-r routerport] [-p pubport] [-m myid] [-a myapikey] [-dn dbname] [-dk dbkey] [-h]" print " routerport = 5555, pubport = 5556, myid = cif-router" print " dbkey = a8fd97c3-9f8b-477b-b45b-ba06719a0088" print " dbname = cif-db" try: opts, args = getopt.getopt(sys.argv[1:], 'p:r:m:h') except getopt.GetoptError, err: print str(err) usage() sys.exit(2) global mystats global clients global thread_tracker context = zmq.Context() clients = Clients() mystats = RouterStats() publishers = {} routerport = 5555 publisherport = 5556 myid = "cif-router" dbkey = 'a8fd97c3-9f8b-477b-b45b-ba06719a0088' dbname = 'cif-db' global apikey apikey = 'a1fd11c1-1f1b-477b-b45b-ba06719a0088' miniclient = None miniclient_id = myid + "-miniclient" register_wait_map = {} unregister_wait_map = {} for o, a in opts: if o == "-r": routerport = a elif o == "-p": publisherport = a elif o == "-m": myid = a elif o == "-dk": dbkey = a elif o == "-dn": dbname = a elif o == "-a": apikey = a elif o == "-h": usage() sys.exit(2) print "Create ROUTER socket on " + str(routerport) global socket socket = context.socket(zmq.ROUTER) socket.bind("tcp://*:" + str(routerport)) socket.setsockopt(zmq.IDENTITY, myname) poller = zmq.Poller() poller.register(socket, zmq.POLLIN) print "Create XSUB socket" xsub = context.socket(zmq.SUB) xsub.setsockopt(zmq.SUBSCRIBE, '') print "Connect XSUB<->XPUB" thread = threading.Thread(target=myrelay, args=(publisherport,)) thread.start() while not thread.isAlive(): print "waiting for pubsub relay thread to become alive" time.sleep(1) thread_tracker = ThreadTracker(False) thread_tracker.add(id=thread.ident, user='Router', host='localhost', state='Running', info="PUBSUB Relay") print "Entering event loop" try: open_for_business = False while True: sockets_with_data_ready = dict(poller.poll(1000)) #print "[up " + str(int(mystats.getuptime())) + "s]: Wakeup: " if miniclient != None: if miniclient.pending() == True: print "\tMiniclient has replies we need to handle." handle_miniclient_reply(socket, routerport, publisherport) if sockets_with_data_ready and sockets_with_data_ready.get(socket) == zmq.POLLIN: print "[up " + str(int(mystats.getuptime())) + "s]: Got an inbound message" rawmsg = socket.recv_multipart() #print " Got ", rawmsg msg = control_pb2.ControlType() try: msg.ParseFromString(rawmsg[2]) except Exception as e: print "Received message isn't a protobuf: ", e mystats.setbad() else: from_zmqid = rawmsg[0] # save the ZMQ identity of who sent us this message #print "Got msg: "#, msg.seq try: cifsupport.versionCheck(msg) except Exception as e: print "\tReceived message has incompatible version: ", e mystats.setbadversion(1, msg.version) else: if cifsupport.isControl(msg): msgfrom = msg.src msgto = msg.dst msgcommand = msg.command msgcommandtext = control_pb2._CONTROLTYPE_COMMANDTYPE.values_by_number[msg.command].name msgid = msg.seq if msgfrom != '' and msg.apikey != '': if msgto == myname and msg.type == control_pb2.ControlType.REPLY: print "\tREPLY for me: ", msgcommand if msgcommand == control_pb2.ControlType.APIKEY_GET: print "\tReceived a REPLY for an APIKEY_GET" elif msgto == myname and msg.type == control_pb2.ControlType.COMMAND: print "\tCOMMAND for me: ", msgcommandtext mystats.setcontrols(1, msgcommandtext) """ For REGISTER: We allow only the db to register with us while we are not open_for_business. Once the DB registers, we are open_for_business since we can then start validating apikeys. Until that time, we can only validate the dbkey that is specified on the command line when you launch this program. """ if msgcommand == control_pb2.ControlType.REGISTER: print "\tREGISTER from: " + msgfrom msg.status = control_pb2.ControlType.FAILED msg.type = control_pb2.ControlType.REPLY msg.seq = msgid if msgfrom == miniclient_id and msg.apikey == apikey: clients.register(msgfrom, from_zmqid, msg.apikey) msg.status = control_pb2.ControlType.SUCCESS msg.registerResponse.REQport = routerport msg.registerResponse.PUBport = publisherport print "\tMiniClient has registered." socket.send_multipart([from_zmqid, '', msg.SerializeToString()]) elif msgfrom == dbname and msg.apikey == dbkey: clients.register(msgfrom, from_zmqid, msg.apikey) msg.status = control_pb2.ControlType.SUCCESS msg.registerResponse.REQport = routerport msg.registerResponse.PUBport = publisherport open_for_business = True print "\tDB has connected successfully. Sending reply to DB." print "\tStarting embedded client" miniclient = MiniClient(apikey, "127.0.0.1", "127.0.0.1:" + str(routerport), 5557, miniclient_id, thread_tracker, True) socket.send_multipart([from_zmqid, '', msg.SerializeToString()]) elif open_for_business == True: """ Since we need to wait for the DB to response, we note this pending request, ask the miniclient to handle the lookup. We will poll the MC to see if the lookup has finished. Reply to client will be sent from handle_miniclient_reply() """ miniclient.lookup_apikey(msg.apikey) register_wait_map[msg.apikey] = {'msgfrom': msgfrom, 'from_zmqid': from_zmqid, 'msgseq': msg.seq} else: print "\tNot open_for_business yet. Go away." elif msgcommand == control_pb2.ControlType.UNREGISTER: """ If the database unregisters, then we are not open_for_business any more. """ print "\tUNREGISTER from: " + msgfrom if open_for_business == True: if msgfrom == dbname and msg.apikey == dbkey: print "\t\tDB unregistered. Closing for business." open_for_business = False clients.unregister(msgfrom) msg.status = control_pb2.ControlType.SUCCESS msg.seq = msgid socket.send_multipart([ from_zmqid, '', msg.SerializeToString()]) else: """ Since we need to wait for the DB to response, we note this pending request, ask the miniclient to handle the lookup. We will poll the MC to see if the lookup has finished. Reply to the client will be sent from handle_miniclient_reply() """ miniclient.lookup_apikey(msg.apikey) unregister_wait_map[msg.apikey] = {'msgfrom': msgfrom, 'from_zmqid': from_zmqid, 'msgseq': msg.seq} elif msgcommand == control_pb2.ControlType.LISTCLIENTS: print "\tLIST-CLIENTS for: " + msgfrom if open_for_business == True: rv = list_clients(msg.src, msg.apikey) msg.seq = msgid msg.status = msg.status | control_pb2.ControlType.FAILED if rv != None: msg.status = msg.status | control_pb2.ControlType.SUCCESS msg.listClientsResponse.client.extend(rv.client) msg.listClientsResponse.connectTimestamp.extend(rv.connectTimestamp) socket.send_multipart( [ from_zmqid, '', msg.SerializeToString() ] ) elif msg.command == control_pb2.ControlType.STATS: print "\tSTATS for: " + msgfrom if open_for_business == True: tmp = msg.dst msg.dst = msg.src msg.src = tmp msg.status = control_pb2.ControlType.SUCCESS msg.statsResponse.statsType = control_pb2.StatsResponse.ROUTER msg.statsResponse.stats = mystats.asjson() socket.send_multipart( [ from_zmqid, '', msg.SerializeToString() ] ) elif msg.command == control_pb2.ControlType.THREADS_LIST: tmp = msg.dst msg.dst = msg.src msg.src = tmp msg.status = control_pb2.ControlType.SUCCESS thread_tracker.asmessage(msg.listThreadsResponse) socket.send_multipart( [ from_zmqid, '', msg.SerializeToString() ] ) if msg.command == control_pb2.ControlType.PING: c = Ping.makereply(msg) socket.send_multipart( [ from_zmqid, '', c.SerializeToString() ] ) elif msgcommand == control_pb2.ControlType.IPUBLISH: print "\tIPUBLISH from: " + msgfrom if open_for_business == True: rv = dosubscribe(from_zmqid, msg) msg.status = rv socket.send_multipart( [from_zmqid, '', msg.SerializeToString()] ) else: print "\tCOMMAND for someone else: cmd=", msgcommandtext, "src=", msgfrom, " dst=", msgto msgto_zmqid = clients.getzmqidentity(msgto) if msgto_zmqid != None: socket.send_multipart([msgto_zmqid, '', msg.SerializeToString()]) else: print "\tUnknown message destination: ", msgto else: print "\tmsgfrom and/or msg.apikey is empty" except KeyboardInterrupt: print "Shut down." if thread.isAlive(): try: thread._Thread__stop() except: print(str(thread.getName()) + ' could not be terminated') sys.exit(0) </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">bsd-3-clause</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-4,783,758,994,462,898,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">44.230932</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">161</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.492154</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">4.620996</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45188"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">fdouetteau/PyBabe</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">pybabe/pivot.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">2935</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "> try: from collections import OrderedDict except: ## 2.6 Fallback from ordereddict import OrderedDict from base import StreamHeader, StreamFooter, BabeBase class OrderedDefaultdict(OrderedDict): def __init__(self, *args, **kwargs): newdefault = None newargs = () if args: newdefault = args[0] if not (newdefault is None or callable(newdefault)): raise TypeError('first argument must be callable or None') newargs = args[1:] self.default_factory = newdefault super(self.__class__, self).__init__(*newargs, **kwargs) def __missing__(self, key): if self.default_factory is None: raise KeyError(key) self[key] = value = self.default_factory() return value def __reduce__(self): # optional, for pickle support args = self.default_factory if self.default_factory else tuple() return type(self), args, None, None, self.items() class OrderedSet(set): def __init__(self): self.list = [] def add(self, elt): if elt in self: return else: super(OrderedSet, self).add(elt) self.list.append(elt) def __iter__(self): return self.list.__iter__() def pivot(stream, pivot, group): "Create a pivot around field, grouping on identical value for 'group'" groups = OrderedDefaultdict(dict) pivot_values = OrderedSet() header = None group_n = map(StreamHeader.keynormalize, group) for row in stream: if isinstance(row, StreamHeader): header = row elif isinstance(row, StreamFooter): # HEADER IS : GROUP + (OTHER FIELDS * EACH VALUE other_fields = [f for f in header.fields if not f in group and not f == pivot] other_fields_k = map(StreamHeader.keynormalize, other_fields) fields = group + [f + "-" + str(v) for v in pivot_values.list for f in other_fields] newheader = header.replace(fields=fields) yield newheader for _, row_dict in groups.iteritems(): ## Create a line per group mrow = row_dict.itervalues().next() group_cols = [getattr(mrow, col) for col in group_n] for v in pivot_values: if v in row_dict: mrow = row_dict[v] group_cols.extend([getattr(mrow, col) for col in other_fields_k]) else: group_cols.extend([None for col in other_fields]) yield group_cols yield row else: kgroup = "" for f in group_n: kgroup = kgroup + str(getattr(row, f)) groups[kgroup][getattr(row, pivot)] = row pivot_values.add(getattr(row, pivot)) BabeBase.register("pivot", pivot) </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">bsd-3-clause</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-1,801,747,529,367,375,600</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">33.529412</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">90</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.560136</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">4.186876</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45189"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">rbn42/stiler</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">config.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1027</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">WinBorder = 2 LeftPadding = 15 BottomPadding = 15 TopPadding = BottomPadding RightPadding = BottomPadding NavigateAcrossWorkspaces = True # availabe in Unity7 TempFile = "/dev/shm/.stiler_db" LockFile = "/dev/shm/.stiler.lock" # This is the congiguration that works for unity7. If you are using a # different Desktop Environment, close all windows and execute "wmctrl # -lG" to find out all the applications need to exclude. EXCLUDE_APPLICATIONS = ['<unknown>', 'x-nautilus-desktop', 'unity-launcher', 'unity-panel', 'Hud', 'unity-dash', 'Desktop', 'Docky', 'screenkey', 'XdndCollectionWindowImp'] # An alternative method to exclude applications. EXCLUDE_WM_CLASS = ['wesnoth-1.12'] UNRESIZABLE_APPLICATIONS = ['Screenkey'] RESIZE_STEP = 50 MOVE_STEP = 50 MIN_WINDOW_WIDTH = 50 MIN_WINDOW_HEIGHT = 50 #NOFRAME_WMCLASS = ['Wine'] # In i3-wm's window tree, only one child of a node is allowed to split. #MAX_KD_TREE_BRANCH = 1 MAX_KD_TREE_BRANCH = 2 </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">8,967,949,853,643,365,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">31.09375</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">76</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.685492</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.22956</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45190"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">ojii/sandlib</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">lib/lib_pypy/_ctypes/primitive.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">11496</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">import _ffi import _rawffi import weakref import sys SIMPLE_TYPE_CHARS = "cbBhHiIlLdfguzZqQPXOv?" from _ctypes.basics import _CData, _CDataMeta, cdata_from_address,\ CArgObject from _ctypes.builtin import ConvMode from _ctypes.array import Array from _ctypes.pointer import _Pointer, as_ffi_pointer #from _ctypes.function import CFuncPtr # this import is moved at the bottom # because else it's circular class NULL(object): pass NULL = NULL() TP_TO_DEFAULT = { 'c': 0, 'u': 0, 'b': 0, 'B': 0, 'h': 0, 'H': 0, 'i': 0, 'I': 0, 'l': 0, 'L': 0, 'q': 0, 'Q': 0, 'f': 0.0, 'd': 0.0, 'g': 0.0, 'P': None, # not part of struct 'O': NULL, 'z': None, 'Z': None, '?': False, } if sys.platform == 'win32': TP_TO_DEFAULT['X'] = NULL TP_TO_DEFAULT['v'] = 0 DEFAULT_VALUE = object() class GlobalPyobjContainer(object): def __init__(self): self.objs = [] def add(self, obj): num = len(self.objs) self.objs.append(weakref.ref(obj)) return num def get(self, num): return self.objs[num]() pyobj_container = GlobalPyobjContainer() def generic_xxx_p_from_param(cls, value): if value is None: return cls(None) if isinstance(value, basestring): return cls(value) if isinstance(value, _SimpleCData) and \ type(value)._type_ in 'zZP': return value return None # eventually raise def from_param_char_p(cls, value): "used by c_char_p and c_wchar_p subclasses" res = generic_xxx_p_from_param(cls, value) if res is not None: return res if isinstance(value, (Array, _Pointer)): from ctypes import c_char, c_byte, c_wchar if type(value)._type_ in [c_char, c_byte, c_wchar]: return value def from_param_void_p(cls, value): "used by c_void_p subclasses" res = generic_xxx_p_from_param(cls, value) if res is not None: return res if isinstance(value, Array): return value if isinstance(value, (_Pointer, CFuncPtr)): return cls.from_address(value._buffer.buffer) if isinstance(value, (int, long)): return cls(value) FROM_PARAM_BY_TYPE = { 'z': from_param_char_p, 'Z': from_param_char_p, 'P': from_param_void_p, } class SimpleType(_CDataMeta): def __new__(self, name, bases, dct): try: tp = dct['_type_'] except KeyError: for base in bases: if hasattr(base, '_type_'): tp = base._type_ break else: raise AttributeError("cannot find _type_ attribute") if (not isinstance(tp, str) or not len(tp) == 1 or tp not in SIMPLE_TYPE_CHARS): raise ValueError('%s is not a type character' % (tp)) default = TP_TO_DEFAULT[tp] ffiarray = _rawffi.Array(tp) result = type.__new__(self, name, bases, dct) result._ffiargshape = tp result._ffishape = tp result._fficompositesize = None result._ffiarray = ffiarray if tp == 'z': # c_char_p def _getvalue(self): addr = self._buffer[0] if addr == 0: return None else: return _rawffi.charp2string(addr) def _setvalue(self, value): if isinstance(value, basestring): if isinstance(value, unicode): value = value.encode(ConvMode.encoding, ConvMode.errors) #self._objects = value array = _rawffi.Array('c')(len(value)+1, value) self._objects = CArgObject(value, array) value = array.buffer elif value is None: value = 0 self._buffer[0] = value result.value = property(_getvalue, _setvalue) result._ffiargtype = _ffi.types.Pointer(_ffi.types.char) elif tp == 'Z': # c_wchar_p def _getvalue(self): addr = self._buffer[0] if addr == 0: return None else: return _rawffi.wcharp2unicode(addr) def _setvalue(self, value): if isinstance(value, basestring): if isinstance(value, str): value = value.decode(ConvMode.encoding, ConvMode.errors) #self._objects = value array = _rawffi.Array('u')(len(value)+1, value) self._objects = CArgObject(value, array) value = array.buffer elif value is None: value = 0 self._buffer[0] = value result.value = property(_getvalue, _setvalue) result._ffiargtype = _ffi.types.Pointer(_ffi.types.unichar) elif tp == 'P': # c_void_p def _getvalue(self): addr = self._buffer[0] if addr == 0: return None return addr def _setvalue(self, value): if isinstance(value, str): array = _rawffi.Array('c')(len(value)+1, value) self._objects = CArgObject(value, array) value = array.buffer elif value is None: value = 0 self._buffer[0] = value result.value = property(_getvalue, _setvalue) elif tp == 'u': def _setvalue(self, val): if isinstance(val, str): val = val.decode(ConvMode.encoding, ConvMode.errors) # possible if we use 'ignore' if val: self._buffer[0] = val def _getvalue(self): return self._buffer[0] result.value = property(_getvalue, _setvalue) elif tp == 'c': def _setvalue(self, val): if isinstance(val, unicode): val = val.encode(ConvMode.encoding, ConvMode.errors) if val: self._buffer[0] = val def _getvalue(self): return self._buffer[0] result.value = property(_getvalue, _setvalue) elif tp == 'O': def _setvalue(self, val): num = pyobj_container.add(val) self._buffer[0] = num def _getvalue(self): return pyobj_container.get(self._buffer[0]) result.value = property(_getvalue, _setvalue) elif tp == 'X': from ctypes import WinDLL # Use WinDLL("oleaut32") instead of windll.oleaut32 # because the latter is a shared (cached) object; and # other code may set their own restypes. We need out own # restype here. oleaut32 = WinDLL("oleaut32") SysAllocStringLen = oleaut32.SysAllocStringLen SysStringLen = oleaut32.SysStringLen SysFreeString = oleaut32.SysFreeString def _getvalue(self): addr = self._buffer[0] if addr == 0: return None else: size = SysStringLen(addr) return _rawffi.wcharp2rawunicode(addr, size) def _setvalue(self, value): if isinstance(value, basestring): if isinstance(value, str): value = value.decode(ConvMode.encoding, ConvMode.errors) array = _rawffi.Array('u')(len(value)+1, value) value = SysAllocStringLen(array.buffer, len(value)) elif value is None: value = 0 if self._buffer[0]: SysFreeString(self._buffer[0]) self._buffer[0] = value result.value = property(_getvalue, _setvalue) elif tp == '?': # regular bool def _getvalue(self): return bool(self._buffer[0]) def _setvalue(self, value): self._buffer[0] = bool(value) result.value = property(_getvalue, _setvalue) elif tp == 'v': # VARIANT_BOOL type def _getvalue(self): return bool(self._buffer[0]) def _setvalue(self, value): if value: self._buffer[0] = -1 # VARIANT_TRUE else: self._buffer[0] = 0 # VARIANT_FALSE result.value = property(_getvalue, _setvalue) # make pointer-types compatible with the _ffi fast path if result._is_pointer_like(): def _as_ffi_pointer_(self, ffitype): return as_ffi_pointer(self, ffitype) result._as_ffi_pointer_ = _as_ffi_pointer_ return result from_address = cdata_from_address def from_param(self, value): if isinstance(value, self): return value from_param_f = FROM_PARAM_BY_TYPE.get(self._type_) if from_param_f: res = from_param_f(self, value) if res is not None: return res else: try: return self(value) except (TypeError, ValueError): pass return super(SimpleType, self).from_param(value) def _CData_output(self, resbuffer, base=None, index=-1): output = super(SimpleType, self)._CData_output(resbuffer, base, index) if self.__bases__[0] is _SimpleCData: return output.value return output def _sizeofinstances(self): return _rawffi.sizeof(self._type_) def _alignmentofinstances(self): return _rawffi.alignment(self._type_) def _is_pointer_like(self): return self._type_ in "sPzUZXO" class _SimpleCData(_CData): __metaclass__ = SimpleType _type_ = 'i' def __init__(self, value=DEFAULT_VALUE): if not hasattr(self, '_buffer'): self._buffer = self._ffiarray(1, autofree=True) if value is not DEFAULT_VALUE: self.value = value def _ensure_objects(self): if self._type_ not in 'zZP': assert self._objects is None return self._objects def _getvalue(self): return self._buffer[0] def _setvalue(self, value): self._buffer[0] = value value = property(_getvalue, _setvalue) del _getvalue, _setvalue def __ctypes_from_outparam__(self): meta = type(type(self)) if issubclass(meta, SimpleType) and meta != SimpleType: return self return self.value def __repr__(self): if type(self).__bases__[0] is _SimpleCData: return "%s(%r)" % (type(self).__name__, self.value) else: return "<%s object at 0x%x>" % (type(self).__name__, id(self)) def __nonzero__(self): return self._buffer[0] not in (0, '\x00') from _ctypes.function import CFuncPtr </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">bsd-3-clause</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">4,007,503,311,104,080,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">31.752137</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">78</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.501044</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">4.08674</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45191"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mongolab/mongoctl</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mongoctl/tests/sharded_test.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">2582</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "># The MIT License # Copyright (c) 2012 ObjectLabs Corporation # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import unittest import time from mongoctl.tests.test_base import MongoctlTestBase, append_user_arg ######################################################################################################################## # Servers SHARD_TEST_SERVERS = [ "ConfigServer1", "ConfigServer2", "ConfigServer3", "Mongos1", "Mongos2", "ShardServer1", "ShardServer2", "ShardServer3", "ShardServer4", "ShardServer5", "ShardServer6", "ShardArbiter" ] ######################################################################################################################## ### Sharded Servers class ShardedTest(MongoctlTestBase): ######################################################################################################################## def test_sharded(self): # Start all sharded servers for s_id in SHARD_TEST_SERVERS: self.assert_start_server(s_id, start_options=["--rs-add"]) print "Sleeping for 10 seconds..." # sleep for 10 of seconds time.sleep(10) conf_cmd = ["configure-shard-cluster", "ShardedCluster"] append_user_arg(conf_cmd) # Configure the sharded cluster self.mongoctl_assert_cmd(conf_cmd) ########################################################################### def get_my_test_servers(self): return SHARD_TEST_SERVERS # booty if __name__ == '__main__': unittest.main() </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">1,538,437,245,596,689,700</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">33.891892</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">124</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.585593</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">4.635548</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">true</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45192"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">jamasi/Xtal-xplore-R</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gui/doublespinslider.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">3682</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "># -*- coding: utf-8 -*- """DoubleSpinSlider - a custom widget combining a slider with a spinbox Copyright (C) 2014 Jan M. Simons <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7914180b0d1c1739010d1815570b0e0d115418181a111c17571d1c">[email protected]</a>> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ from __future__ import division, print_function, absolute_import from decimal import Decimal from PyQt4 import QtGui, QtCore from PyQt4.QtCore import pyqtSlot class DoubleSpinSlider(QtGui.QWidget): """This is a QWidget containing a QSlider and a QDoubleSpinBox""" def __init__(self, parent=None, width=50, height=100, dpi=100): #super(DoubleSpinSlider, self).__init__(parent) QtGui.QWidget.__init__(self, parent) self._vLayout = QtGui.QVBoxLayout() self._label = QtGui.QLabel(parent) self._label.setAlignment(QtCore.Qt.AlignCenter) self._vLayout.addWidget(self._label) self._dSBox = QtGui.QDoubleSpinBox(parent) self._dSBox.setWrapping(True) self._dSBox.setDecimals(4) self._dSBox.setMaximum(1.00000000) self._dSBox.setSingleStep(0.1000000000) self._vLayout.addWidget(self._dSBox) self._hLayout = QtGui.QHBoxLayout() self._vSlider = QtGui.QSlider(parent) self._vSlider.setMinimum(0) self._vSlider.setMaximum(10000) self._vSlider.setPageStep(1000) self._vSlider.setOrientation(QtCore.Qt.Vertical) self._vSlider.setTickPosition(QtGui.QSlider.TicksBothSides) self._vSlider.setTickInterval(0) self._hLayout.addWidget(self._vSlider) self._vLayout.addLayout(self._hLayout) self.setLayout(self._vLayout) self.setParent(parent) # map functions self.setText = self._label.setText self.text = self._label.text self.setValue = self._dSBox.setValue self.value = self._dSBox.value self._vSlider.valueChanged.connect(self.ChangeSpinBox) self._dSBox.valueChanged.connect(self.ChangeSlider) def _multiplier(self): return 10.000000 ** self._dSBox.decimals() @pyqtSlot(int) def ChangeSpinBox(self, slidervalue): #print("sv: {}".format(slidervalue)) newvalue = round(slidervalue / (self._multiplier()),4) #print("nv: {}".format(newvalue)) if newvalue != self._dSBox.value(): self._dSBox.setValue(newvalue) @pyqtSlot('double') def ChangeSlider(self, spinboxvalue): newvalue = spinboxvalue * self._multiplier() #print("sb: {sb} mult: {mult} prod: {prod}".format( # sb=spinboxvalue, # mult=int(10.00000000 ** self._dSBox.decimals()), # prod=newvalue)) self._vSlider.setValue(newvalue) @pyqtSlot('double') def setMaximum(self, maximum): self._dSBox.setMaximum(maximum) self._vSlider.setMaximum(maximum * self._multiplier()) @pyqtSlot('double') def setMinimum(self, minimum): self._dSBox.setMinimum(minimum) self._vSlider.setMinimum(minimum * self._multiplier()) </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">agpl-3.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">7,329,879,116,559,789,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">38.591398</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">77</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.655894</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.835417</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45193"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">adw0rd/lettuce-py3</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">lettuce/__init__.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">6767</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "># -*- coding: utf-8 -*- # <Lettuce - Behaviour Driven Development for python> # Copyright (C) <2010-2012> Gabriel Falcão <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a5c2c4c7d7ccc0c9e5cbc4c6c4cac9ccd3d7c08bcad7c2">[email protected]</a>> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. __version__ = version = '0.2.22' release = 'kryptonite' import os import sys import traceback import warnings try: from imp import reload except ImportError: # python 2.5 fallback pass import random from lettuce.core import Feature, TotalResult from lettuce.terrain import after from lettuce.terrain import before from lettuce.terrain import world from lettuce.decorators import step, steps from lettuce.registry import call_hook from lettuce.registry import STEP_REGISTRY from lettuce.registry import CALLBACK_REGISTRY from lettuce.exceptions import StepLoadingError from lettuce.plugins import ( xunit_output, subunit_output, autopdb, smtp_mail_queue, ) from lettuce import fs from lettuce import exceptions try: from colorama import init as ms_windows_workaround ms_windows_workaround() except ImportError: pass __all__ = [ 'after', 'before', 'step', 'steps', 'world', 'STEP_REGISTRY', 'CALLBACK_REGISTRY', 'call_hook', ] try: terrain = fs.FileSystem._import("terrain") reload(terrain) except Exception as e: if not "No module named 'terrain'" in str(e): string = 'Lettuce has tried to load the conventional environment ' \ 'module "terrain"\nbut it has errors, check its contents and ' \ 'try to run lettuce again.\n\nOriginal traceback below:\n\n' sys.stderr.write(string) sys.stderr.write(exceptions.traceback.format_exc()) raise SystemExit(1) class Runner(object): """ Main lettuce's test runner Takes a base path as parameter (string), so that it can look for features and step definitions on there. """ def __init__(self, base_path, scenarios=None, verbosity=0, no_color=False, random=False, enable_xunit=False, xunit_filename=None, enable_subunit=False, subunit_filename=None, tags=None, failfast=False, auto_pdb=False, smtp_queue=None, root_dir=None, **kwargs): """ lettuce.Runner will try to find a terrain.py file and import it from within `base_path` """ self.tags = tags self.single_feature = None if os.path.isfile(base_path) and os.path.exists(base_path): self.single_feature = base_path base_path = os.path.dirname(base_path) sys.path.insert(0, base_path) self.loader = fs.FeatureLoader(base_path, root_dir) self.verbosity = verbosity self.scenarios = scenarios and list(map(int, scenarios.split(","))) or None self.failfast = failfast if auto_pdb: autopdb.enable(self) sys.path.remove(base_path) if verbosity == 0: from lettuce.plugins import non_verbose as output elif verbosity == 1: from lettuce.plugins import dots as output elif verbosity == 2: from lettuce.plugins import scenario_names as output else: if verbosity == 4: from lettuce.plugins import colored_shell_output as output msg = ('Deprecated in lettuce 2.2.21. Use verbosity 3 without ' '--no-color flag instead of verbosity 4') warnings.warn(msg, DeprecationWarning) elif verbosity == 3: if no_color: from lettuce.plugins import shell_output as output else: from lettuce.plugins import colored_shell_output as output self.random = random if enable_xunit: xunit_output.enable(filename=xunit_filename) if smtp_queue: smtp_mail_queue.enable() if enable_subunit: subunit_output.enable(filename=subunit_filename) reload(output) self.output = output def run(self): """ Find and load step definitions, and them find and load features under `base_path` specified on constructor """ results = [] if self.single_feature: features_files = [self.single_feature] else: features_files = self.loader.find_feature_files() if self.random: random.shuffle(features_files) if not features_files: self.output.print_no_features_found(self.loader.base_dir) return # only load steps if we've located some features. # this prevents stupid bugs when loading django modules # that we don't even want to test. try: self.loader.find_and_load_step_definitions() except StepLoadingError as e: print("Error loading step definitions:\n", e) return call_hook('before', 'all') failed = False try: for filename in features_files: feature = Feature.from_file(filename) results.append( feature.run(self.scenarios, tags=self.tags, random=self.random, failfast=self.failfast)) except exceptions.LettuceSyntaxError as e: sys.stderr.write(e.msg) failed = True except exceptions.NoDefinitionFound as e: sys.stderr.write(e.msg) failed = True except: if not self.failfast: e = sys.exc_info()[1] print("Died with %s" % str(e)) traceback.print_exc() else: print() print ("Lettuce aborted running any more tests " "because was called with the `--failfast` option") failed = True finally: total = TotalResult(results) total.output_format() call_hook('after', 'all', total) if failed: raise SystemExit(2) return total </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-3.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-6,675,595,172,369,562,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">30.469767</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">83</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.604936</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">4.143295</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45194"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">sam-roth/Keypad</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">keypad/plugins/shell/bourne_model.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">4068</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">import subprocess import shlex from keypad.api import (Plugin, register_plugin, Filetype, Cursor) from keypad.abstract.code import IndentRetainingCodeModel, AbstractCompletionResults from keypad.core.syntaxlib import SyntaxHighlighter, lazy from keypad.core.processmgr.client import AsyncServerProxy from keypad.core.fuzzy import FuzzyMatcher from keypad.core.executors import future_wrap from keypad.core.attributed_string import AttributedString @lazy def lexer(): from . import bourne_lexer return bourne_lexer.Shell class GetManPage: def __init__(self, cmd): self.cmd = cmd def __call__(self, ns): with subprocess.Popen(['man', self.cmd], stdout=subprocess.PIPE) as proc: out, _ = proc.communicate() import re return [re.subn('.\x08', '', out.decode())[0]] class ShellCompletionResults(AbstractCompletionResults): def __init__(self, token_start, results, prox): ''' token_start - the (line, col) position at which the token being completed starts ''' super().__init__(token_start) self.results = [(AttributedString(x.decode()),) for x in results] self._prox = prox def doc_async(self, index): ''' Return a Future for the documentation for a given completion result as a list of AttributedString. ''' return self._prox.submit(GetManPage(self.text(index))) @property def rows(self): ''' Return a list of tuples of AttributedString containing the contents of each column for each row in the completion results. ''' return self._filtered.rows def text(self, index): ''' Return the text that should be inserted for the given completion. ''' return self._filtered.rows[index][0].text def filter(self, text=''): ''' Filter the completion results using the given text. ''' self._filtered = FuzzyMatcher(text).filter(self.results, key=lambda x: x[0].text) self._filtered.sort(lambda item: len(item[0].text)) def dispose(self): pass class GetPathItems: def __init__(self, prefix): self.prefix = prefix def __call__(self, ns): with subprocess.Popen(['bash', '-c', 'compgen -c ' + shlex.quote(self.prefix)], stdout=subprocess.PIPE) as proc: out, _ = proc.communicate() return [l.strip() for l in out.splitlines()] class BourneCodeModel(IndentRetainingCodeModel): completion_triggers = [] def __init__(self, *args, **kw): super().__init__(*args, **kw) self._prox = AsyncServerProxy() self._prox.start() def dispose(self): self._prox.shutdown() super().dispose() def highlight(self): ''' Rehighlight the buffer. ''' highlighter = SyntaxHighlighter( 'keypad.plugins.shell.syntax', lexer(), dict(lexcat=None) ) highlighter.highlight_buffer(self.buffer) def completions_async(self, pos): ''' Return a future to the completions available at the given position in the document. Raise NotImplementedError if not implemented. ''' c = Cursor(self.buffer).move(pos) text_to_pos = c.line.text[:c.x] for x, ch in reversed(list(enumerate(text_to_pos))): if ch.isspace(): x += 1 break else: x = 0 print('text_to_pos', text_to_pos[x:], pos) return self._prox.submit(GetPathItems(text_to_pos[x:]), transform=lambda r: ShellCompletionResults((pos[0], x), r, self._prox)) </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-3.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-4,100,649,501,340,423,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">26.863014</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">91</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.555556</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">4.360129</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45195"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">dmvieira/P.O.D.</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">func.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">5799</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">from mergesort import * def comeca(sequencia,entrada,entrada2,entrada3): div=open(entrada3,'w') t=open(entrada,'r') saida=open(entrada2,'w') x=t.readlines() if (x[-1][-1])<>'\n': comp=x[-1][-1] comp=comp+'\n' x.insert(-1,comp) comp=x[-1] comp=comp+'\n' del(x[-1]) x.insert(-1,comp) del(x[-1]) l=[] b=0 t.close() if sequencia=='r': for j in range(0,len(x)): k=len(x[j]) if x[j][0]=='>': if b==1: l.append(c) l.append(x[j][:k-1]) c="" b=1 else: y="" for i in range(0,k-1): if x[j][i] == 'a' or x[j][i] == 'A' or x[j][i] == 'c' or x[j][i] == 'C' or x[j][i] == 'g' or x[j][i] == 'G' or x[j][i] == 'u' or x[j][i] == 'U' or x[j][i] == 'r' or x[j][i] == 'R' or x[j][i] == 'y' or x[j][i] == 'Y' or x[j][i] == 'k' or x[j][i] == 'K' or x[j][i] == 'm' or x[j][i] == 'M' or x[j][i] == 's' or x[j][i] == 'S' or x[j][i] == 'w' or x[j][i] == 'W' or x[j][i] == 'b' or x[j][i] == 'B' or x[j][i] == 'd' or x[j][i] == 'D' or x[j][i] == 'h' or x[j][i] == 'H' or x[j][i] == 'v' or x[j][i] == 'V' or x[j][i] == 'n' or x[j][i] == 'N': y=y+x[j][i] c=c+y l.append(c) elif sequencia=='p': for j in range(0,len(x)): k=len(x[j]) if x[j][0]=='>': if b==1: l.append(c) l.append(x[j][:k-1]) c="" b=1 else: y="" for i in range(0,k-1): if x[j][i] == 'a' or x[j][i] == 'A' or x[j][i] == 'c' or x[j][i] == 'C' or x[j][i] == 'g' or x[j][i] == 'G' or x[j][i] == 'v' or x[j][i] == 'V' or x[j][i] == 'L' or x[j][i] == 'l' or x[j][i] == 'I' or x[j][i] == 'i' or x[j][i] == 'S' or x[j][i] == 's' or x[j][i] == 'T' or x[j][i] == 't' or x[j][i] == 'Y' or x[j][i] == 'y' or x[j][i] == 'M' or x[j][i] == 'm' or x[j][i] == 'd' or x[j][i] == 'D' or x[j][i] == 'n' or x[j][i] == 'N' or x[j][i] == 'E' or x[j][i] == 'e' or x[j][i] == 'Q' or x[j][i] == 'q' or x[j][i] == 'R' or x[j][i] == 'r' or x[j][i] == 'K' or x[j][i] == 'k' or x[j][i] == 'H' or x[j][i] == 'h' or x[j][i] == 'F' or x[j][i] == 'f' or x[j][i] == 'W' or x[j][i] == 'w' or x[j][i] == 'P' or x[j][i] == 'p' or x[j][i] == 'b' or x[j][i] == 'B' or x[j][i] == 'z' or x[j][i] == 'Z' or x[j][i] == 'x' or x[j][i] == 'X' or x[j][i] == 'u' or x[j][i] == 'U': y=y+x[j][i] c=c+y l.append(c) else: for j in range(0,len(x)): k=len(x[j]) if x[j][0]=='>': if b==1: l.append(c) l.append(x[j][:k-1]) c="" b=1 else: y="" for i in range(0,k-1): if x[j][i] == 'a' or x[j][i] == 'A' or x[j][i] == 'c' or x[j][i] == 'C' or x[j][i] == 'g' or x[j][i] == 'G' or x[j][i] == 't' or x[j][i] == 'T' or x[j][i] == 'r' or x[j][i] == 'R' or x[j][i] == 'y' or x[j][i] == 'Y' or x[j][i] == 'k' or x[j][i] == 'K' or x[j][i] == 'm' or x[j][i] == 'M' or x[j][i] == 's' or x[j][i] == 'S' or x[j][i] == 'w' or x[j][i] == 'W' or x[j][i] == 'b' or x[j][i] == 'B' or x[j][i] == 'd' or x[j][i] == 'D' or x[j][i] == 'h' or x[j][i] == 'H' or x[j][i] == 'v' or x[j][i] == 'V' or x[j][i] == 'n' or x[j][i] == 'N': y=y+x[j][i] c=c+y l.append(c) dec,dic={},{} for j in range(0,len(l),2): alta=(l[j+1]).upper() del(l[j+1]) l.insert(j+1,alta) if (dic.has_key((l[j+1][::-1])))==True: del(l[j+1]) l.insert((j+1),alta[::-1]) d={l[j]:l[j+1]} dec.update(d) d={l[j+1]:l[j]} dic.update(d) vou=dic.keys() v=dec.values() diversidade=[] dic={} for j in range(0,len(l),2): alta=(l[j+1]) divo=(len(alta))/65 if divo > 0: alta2='' for h in range(1,divo+1): alta2=alta2+alta[(65*(h-1)):(65*h)]+'\n' alta=alta2+alta[65*divo:] del(l[j+1]) l.insert(j+1,alta) d= {alta:l[j]} dic.update(d) key=dic.keys() value=dic.values() for j in range(len(key)): saida.write(value[j]+'\n'+key[j]+'\n') diversidade.append((v.count(vou[j]))) saida.close() ordena(diversidade, value, key, div) div.close() </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-3.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-1,694,803,398,801,581,800</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">52.196262</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">904</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.272116</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">2.777299</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45196"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">cdriehuys/chmvh-website</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">chmvh_website/contact/forms.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">2333</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">import logging from smtplib import SMTPException from captcha.fields import ReCaptchaField from django import forms from django.conf import settings from django.core import mail from django.template import loader logger = logging.getLogger("chmvh_website.{0}".format(__name__)) class ContactForm(forms.Form): captcha = ReCaptchaField() name = forms.CharField() email = forms.EmailField() message = forms.CharField(widget=forms.Textarea(attrs={"rows": 5})) street_address = forms.CharField(required=False) city = forms.CharField(required=False) zipcode = forms.CharField(required=False) template = loader.get_template("contact/email/message.txt") def clean_city(self): """ If no city was provided, use a default string. """ if not self.cleaned_data["city"]: return "<No City Given>" return self.cleaned_data["city"] def send_email(self): assert self.is_valid(), self.errors subject = "[CHMVH Website] Message from {}".format( self.cleaned_data["name"] ) address_line_2_parts = [self.cleaned_data["city"], "North Carolina"] if self.cleaned_data["zipcode"]: address_line_2_parts.append(self.cleaned_data["zipcode"]) address_line_1 = self.cleaned_data["street_address"] address_line_2 = ", ".join(address_line_2_parts) address = "" if address_line_1: address = "\n".join([address_line_1, address_line_2]) context = { "name": self.cleaned_data["name"], "email": self.cleaned_data["email"], "message": self.cleaned_data["message"], "address": address, } logger.debug("Preparing to send email") try: emails_sent = mail.send_mail( subject, self.template.render(context), settings.DEFAULT_FROM_EMAIL, ["<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dfb6b1b9b09fbcb7beafbab3b7b6b3b3a9baabf1bcb0b2">[email protected]</a>"], ) logger.info( "Succesfully sent email from {0}".format( self.cleaned_data["email"] ) ) except SMTPException as e: emails_sent = 0 logger.exception("Failed to send email.", exc_info=e) return emails_sent == 1 </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3,360,558,135,283,314,700</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">28.1625</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">76</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.582512</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">4.078671</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45197"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gdsfactory/gdsfactory</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">pp/components/coupler.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">2755</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">import pp from pp.component import Component from pp.components.coupler_straight import coupler_straight from pp.components.coupler_symmetric import coupler_symmetric from pp.cross_section import get_waveguide_settings from pp.snap import assert_on_1nm_grid from pp.types import ComponentFactory @pp.cell_with_validator def coupler( gap: float = 0.236, length: float = 20.0, coupler_symmetric_factory: ComponentFactory = coupler_symmetric, coupler_straight_factory: ComponentFactory = coupler_straight, dy: float = 5.0, dx: float = 10.0, waveguide: str = "strip", **kwargs ) -> Component: r"""Symmetric coupler. Args: gap: between straights length: of coupling region coupler_symmetric_factory coupler_straight_factory dy: port to port vertical spacing dx: length of bend in x direction waveguide: from tech.waveguide kwargs: overwrites waveguide_settings .. code:: dx dx |------| |------| W1 ________ _______E1 \ / | \ length / | ======================= gap | dy / \ | ________/ \_______ | W0 E0 coupler_straight_factory coupler_symmetric_factory """ assert_on_1nm_grid(length) assert_on_1nm_grid(gap) c = Component() waveguide_settings = get_waveguide_settings(waveguide, **kwargs) sbend = coupler_symmetric_factory(gap=gap, dy=dy, dx=dx, **waveguide_settings) sr = c << sbend sl = c << sbend cs = c << coupler_straight_factory(length=length, gap=gap, **waveguide_settings) sl.connect("W1", destination=cs.ports["W0"]) sr.connect("W0", destination=cs.ports["E0"]) c.add_port("W1", port=sl.ports["E0"]) c.add_port("W0", port=sl.ports["E1"]) c.add_port("E0", port=sr.ports["E0"]) c.add_port("E1", port=sr.ports["E1"]) c.absorb(sl) c.absorb(sr) c.absorb(cs) c.length = sbend.length c.min_bend_radius = sbend.min_bend_radius return c if __name__ == "__main__": # c = pp.Component() # cp1 = c << coupler(gap=0.2) # cp2 = c << coupler(gap=0.5) # cp1.ymin = 0 # cp2.ymin = 0 # c = coupler(gap=0.2, waveguide="nitride") # c = coupler(width=0.9, length=1, dy=2, gap=0.2) # print(c.settings_changed) c = coupler(gap=0.2, waveguide="nitride") # c = coupler(gap=0.2, waveguide="strip_heater") c.show() </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">505,920,847,848,893,060</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">29.955056</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">84</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.52559</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.44806</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45198"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Murali-group/GraphSpace</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">applications/uniprot/models.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1246</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">from __future__ import unicode_literals from sqlalchemy import ForeignKeyConstraint, text from applications.users.models import * from django.conf import settings from graphspace.mixins import * Base = settings.BASE # ================== Table Definitions =================== # class UniprotAlias(IDMixin, TimeStampMixin, Base): __tablename__ = 'uniprot_alias' accession_number = Column(String, nullable=False) alias_source = Column(String, nullable=False) alias_name = Column(String, nullable=False) constraints = ( UniqueConstraint('accession_number', 'alias_source', 'alias_name', name='_uniprot_alias_uc_accession_number_alias_source_alias_name'), ) indices = ( Index('uniprot_alias_idx_accession_number', text("accession_number gin_trgm_ops"), postgresql_using="gin"), Index('uniprot_alias_idx_alias_name', text("alias_name gin_trgm_ops"), postgresql_using="gin"), ) @declared_attr def __table_args__(cls): args = cls.constraints + cls.indices return args def serialize(cls, **kwargs): return { # 'id': cls.id, 'id': cls.accession_number, 'alias_source': cls.alias_source, 'alias_name': cls.alias_name, 'created_at': cls.created_at.isoformat(), 'updated_at': cls.updated_at.isoformat() } </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">1,488,446,659,459,923,500</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">27.976744</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">136</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.695024</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.178571</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="45199"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">rohithredd94/Computer-Vision-using-OpenCV</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Particle-Filter-Tracking/PF_Tracker.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">1</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">4110</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">import cv2 import numpy as mp from similarity import * from hist import * class PF_Tracker: def __init__(self, model, search_space, num_particles=100, state_dims=2, control_std=10, sim_std=20, alpha=0.0): self.model = model self.search_space = search_space[::-1] self.num_particles = num_particles self.state_dims = state_dims self.control_std = control_std self.sim_std = sim_std self.alpha = alpha #Initialize particles using a uniform distribution self.particles = np.array([np.random.uniform(0, self.search_space[i],self.num_particles) for i in range(self.state_dims)]).T self.weights = np.ones(len(self.particles)) / len(self.particles) self.idxs = np.arange(num_particles) self.estimate_state() def update(self, frame): self.displace() self.observe(frame) self.resample() self.estimate_state() if self.alpha > 0: self.update_model(frame) def displace(self): #Displace particles using a normal distribution centered around 0 self.particles += np.random.normal(0, self.control_std, self.particles.shape) def observe(self, img): #Get patches corresponding to each particle mh, mw = self.model.shape[:2] minx = (self.particles[:,0] - mw/2).astype(np.int) miny = (self.particles[:,1] - mh/2).astype(np.int) candidates = [img[miny[i]:miny[i]+mh, minx[i]:minx[i]+mw] for i in range(self.num_particles)] #Compute importance weight - similarity of each patch to the model self.weights = np.array([similarity(cand, self.model, self.sim_std) for cand in candidates]) self.weights /= np.sum(self.weights) def resample(self): sw, sh = self.search_space[:2] mh, mw = self.model.shape[:2] j = np.random.choice(self.idxs, self.num_particles, True, p=self.weights.T) #Sample new particle indices using the distribution of the weights control = np.random.normal(0, self.control_std, self.particles.shape) #Get a random control input from a normal distribution self.particles = np.array(self.particles[j]) self.particles[:,0] = np.clip(self.particles[:,0], 0, sw - 1) self.particles[:,1] = np.clip(self.particles[:,1], 0, sh - 1) def estimate_state(self): state_idx = np.random.choice(self.idxs, 1, p=self.weights) self.state = self.particles[state_idx][0] def update_model(self, frame): #Get current model based on belief mh, mw = self.model.shape[:2] minx = int(self.state[0] - mw/2) miny = int(self.state[1] - mh/2) best_model = frame[miny:miny+mh, minx:minx+mw] #Apply appearance model update if new model shape is unchanged if best_model.shape == self.model.shape: self.model = self.alpha * best_model + (1-self.alpha) * self.model self.model = self.model.astype(np.uint8) def visualize_filter(self, img): self.draw_particles(img) self.draw_window(img) self.draw_std(img) def draw_particles(self, img): for p in self.particles: cv2.circle(img, tuple(p.astype(int)), 2, (180,255,0), -1) def draw_window(self, img): best_idx = cv2.minMaxLoc(self.weights)[3][1] best_state = self.particles[best_idx] pt1 = (best_state - np.array(self.model.shape[::-1])/2).astype(np.int) pt2 = pt1 + np.array(self.model.shape[::-1]) cv2.rectangle(img, tuple(pt1), tuple(pt2), (0,255,0), 2) def draw_std(self, img): weighted_sum = 0 dist = np.linalg.norm(self.particles - self.state) weighted_sum = np.sum(dist * self.weights.reshape((-1,1))) cv2.circle(img, tuple(self.state.astype(np.int)), int(weighted_sum), (255,255,255), 1)</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">-8,084,760,379,983,337,000</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">37.92233</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">132</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">0.584672</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3.506826</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">false</div></div> </td> </tr></tbody></table> </div> <div class="bg-linear-to-b from-gray-100 to-white dark:from-gray-950 dark:to-gray-900 rounded-b-lg"><hr class="flex-none -translate-y-px border-t border-dashed border-gray-300 bg-white dark:border-gray-700 dark:bg-gray-950"> <nav><ul class="flex select-none items-center justify-between space-x-2 text-gray-700 sm:justify-center py-1 text-center font-mono text-xs "><li><a class="flex items-center rounded-lg px-2.5 py-1 hover:bg-gray-50 dark:hover:bg-gray-800 " href="/datasets/codeparrot/codeparrot-valid-v2-near-dedup/viewer/default/train?p=450"><svg class="mr-1.5" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M10 16L20 6l1.4 1.4l-8.6 8.6l8.6 8.6L20 26z" fill="currentColor"></path></svg> Previous</a></li> <li class="hidden sm:block"><a class="rounded-lg px-2.5 py-1 hover:bg-gray-50 dark:hover:bg-gray-800" href="/datasets/codeparrot/codeparrot-valid-v2-near-dedup/viewer/default/train?p=0">1</a> </li><li class="hidden sm:block"><a class="rounded-lg px-2.5 py-1 pointer-events-none cursor-default" href="#">...</a> </li><li class="hidden sm:block"><a class="rounded-lg px-2.5 py-1 hover:bg-gray-50 dark:hover:bg-gray-800" href="/datasets/codeparrot/codeparrot-valid-v2-near-dedup/viewer/default/train?p=449">450</a> </li><li class="hidden sm:block"><a class="rounded-lg px-2.5 py-1 hover:bg-gray-50 dark:hover:bg-gray-800" href="/datasets/codeparrot/codeparrot-valid-v2-near-dedup/viewer/default/train?p=450">451</a> </li><li class="hidden sm:block"><a class="rounded-lg px-2.5 py-1 bg-gray-50 font-semibold ring-1 ring-inset ring-gray-200 dark:bg-gray-900 dark:text-yellow-500 dark:ring-gray-900 hover:bg-gray-50 dark:hover:bg-gray-800" href="/datasets/codeparrot/codeparrot-valid-v2-near-dedup/viewer/default/train?p=451">452</a> </li><li class="hidden sm:block"><a class="rounded-lg px-2.5 py-1 hover:bg-gray-50 dark:hover:bg-gray-800" href="/datasets/codeparrot/codeparrot-valid-v2-near-dedup/viewer/default/train?p=452">453</a> </li><li class="hidden sm:block"><a class="rounded-lg px-2.5 py-1 hover:bg-gray-50 dark:hover:bg-gray-800" href="/datasets/codeparrot/codeparrot-valid-v2-near-dedup/viewer/default/train?p=453">454</a> </li><li class="hidden sm:block"><a class="rounded-lg px-2.5 py-1 hover:bg-gray-50 dark:hover:bg-gray-800" href="/datasets/codeparrot/codeparrot-valid-v2-near-dedup/viewer/default/train?p=454">455</a> </li> <li><a class="flex items-center rounded-lg px-2.5 py-1 hover:bg-gray-50 dark:hover:bg-gray-800 " href="/datasets/codeparrot/codeparrot-valid-v2-near-dedup/viewer/default/train?p=452">Next <svg class="ml-1.5 transform rotate-180" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M10 16L20 6l1.4 1.4l-8.6 8.6l8.6 8.6L20 26z" fill="currentColor"></path></svg></a></li></ul></nav></div></div> </div></div></div></div></div></div></div> <div class="hidden items-center md:flex"> <div class="mx-1 flex items-center justify-center"><div class="h-8 w-1 cursor-ew-resize rounded-full bg-gray-200 hover:bg-gray-400 dark:bg-gray-700 dark:hover:bg-gray-600 max-sm:hidden" role="separator"></div></div> <div class="flex h-full flex-col" style="height: calc(100vh - 48px)"><div class="my-4 mr-4 h-full overflow-auto rounded-lg border shadow-lg dark:border-gray-800" style="width: 480px"><div class="flex h-full flex-col"><div class="flex flex-col "> <div class="px-4 md:mt-4"><div class="mb-4 flex justify-end"> <div class="flex w-full flex-col rounded-lg border-slate-200 bg-white p-2 shadow-md ring-1 ring-slate-200 dark:border-slate-700 dark:bg-slate-800 dark:ring-slate-700"> <div class="mt-0 flex items-start gap-1"><div class="flex items-center rounded-md bg-slate-100 p-2 dark:bg-slate-700"><svg class="size-4 text-gray-700 dark:text-gray-300" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 11 11"><path fill="currentColor" d="M4.881 4.182c0 .101-.031.2-.087.283a.5.5 0 0 1-.242.18l-.65.217a1.3 1.3 0 0 0-.484.299 1.3 1.3 0 0 0-.298.484l-.222.639a.46.46 0 0 1-.18.242.5.5 0 0 1-.288.092.5.5 0 0 1-.294-.097.5.5 0 0 1-.175-.242l-.211-.644a1.26 1.26 0 0 0-.299-.48 1.14 1.14 0 0 0-.479-.298L.328 4.64a.48.48 0 0 1-.247-.18.515.515 0 0 1 .247-.758l.644-.21a1.28 1.28 0 0 0 .788-.789l.211-.634a.5.5 0 0 1 .165-.242.5.5 0 0 1 .283-.103.5.5 0 0 1 .294.083c.086.058.152.14.19.237l.217.659a1.28 1.28 0 0 0 .788.788l.644.222a.476.476 0 0 1 .237.18.5.5 0 0 1 .092.288"></path><path fill="currentColor" d="M10.031 7.458a.5.5 0 0 1-.098.314.5.5 0 0 1-.267.196l-.881.293c-.272.09-.519.242-.721.443a1.8 1.8 0 0 0-.443.721l-.31.876a.5.5 0 0 1-.185.263.56.56 0 0 1-.319.098.515.515 0 0 1-.515-.366l-.294-.88a1.8 1.8 0 0 0-.443-.722c-.204-.2-.45-.353-.72-.448l-.881-.288a.57.57 0 0 1-.263-.191.56.56 0 0 1-.014-.64.5.5 0 0 1 .271-.194l.886-.294A1.82 1.82 0 0 0 6.01 5.465l.293-.87a.515.515 0 0 1 .49-.377c.11 0 .219.03.314.088a.56.56 0 0 1 .206.263l.298.896a1.82 1.82 0 0 0 1.175 1.174l.875.31a.5.5 0 0 1 .263.195c.07.09.108.2.108.314"></path><path fill="currentColor" d="M7.775 1.684a.5.5 0 0 0 .088-.262.45.45 0 0 0-.088-.263.5.5 0 0 0-.21-.155L7.24.896a.5.5 0 0 1-.165-.103.5.5 0 0 1-.103-.17l-.108-.33a.5.5 0 0 0-.165-.21A.5.5 0 0 0 6.426 0a.5.5 0 0 0-.252.098.5.5 0 0 0-.145.206l-.108.32a.5.5 0 0 1-.103.17.5.5 0 0 1-.17.102L5.334 1a.45.45 0 0 0-.216.155.5.5 0 0 0-.088.262c0 .094.029.186.083.263a.5.5 0 0 0 .216.16l.32.103q.095.03.164.103a.37.37 0 0 1 .103.165l.108.319c.031.09.088.17.165.227a.56.56 0 0 0 .252.077.42.42 0 0 0 .268-.093.5.5 0 0 0 .15-.2l.113-.325a.43.43 0 0 1 .268-.268l.32-.108a.42.42 0 0 0 .215-.155"></path></svg></div> <div class="flex min-w-0 flex-1"><textarea placeholder="Ask AI to help write your query..." class="max-h-64 min-h-8 w-full resize-none overflow-y-auto border-none bg-transparent py-1 text-sm leading-6 text-slate-700 placeholder-slate-400 [scrollbar-width:thin] focus:ring-0 dark:text-slate-200 dark:placeholder-slate-400" rows="1"></textarea> </div> </div> </div></div> <div class="relative flex flex-col rounded-md bg-gray-100 pt-2 dark:bg-gray-800/50"> <div class="flex h-64 items-center justify-center "><svg class="animate-spin text-xs" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" fill="none" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 12 12"><path class="opacity-75" fill-rule="evenodd" clip-rule="evenodd" d="M6 0C2.6862 0 0 2.6862 0 6H1.8C1.8 4.88609 2.2425 3.8178 3.03015 3.03015C3.8178 2.2425 4.88609 1.8 6 1.8V0ZM12 6C12 9.3138 9.3138 12 6 12V10.2C7.11391 10.2 8.1822 9.7575 8.96985 8.96985C9.7575 8.1822 10.2 7.11391 10.2 6H12Z" fill="currentColor"></path><path class="opacity-25" fill-rule="evenodd" clip-rule="evenodd" d="M3.03015 8.96985C3.8178 9.7575 4.88609 10.2 6 10.2V12C2.6862 12 0 9.3138 0 6H1.8C1.8 7.11391 2.2425 8.1822 3.03015 8.96985ZM7.60727 2.11971C7.0977 1.90864 6.55155 1.8 6 1.8V0C9.3138 0 12 2.6862 12 6H10.2C10.2 5.44845 10.0914 4.9023 9.88029 4.39273C9.66922 3.88316 9.35985 3.42016 8.96985 3.03015C8.57984 2.64015 8.11684 2.33078 7.60727 2.11971Z" fill="currentColor"></path></svg></div></div> <div class="mt-2 flex flex-col gap-2"><div class="flex items-center justify-between max-sm:text-sm"><div class="flex w-full items-center justify-between gap-4"> <span class="flex flex-shrink-0 items-center gap-1"><span class="font-semibold">Subsets and Splits</span> <span class="inline-block "><span class="contents"><svg class="text-xs text-gray-500 dark:text-gray-400" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M17 22v-8h-4v2h2v6h-3v2h8v-2h-3z" fill="currentColor"></path><path d="M16 8a1.5 1.5 0 1 0 1.5 1.5A1.5 1.5 0 0 0 16 8z" fill="currentColor"></path><path d="M16 30a14 14 0 1 1 14-14a14 14 0 0 1-14 14zm0-26a12 12 0 1 0 12 12A12 12 0 0 0 16 4z" fill="currentColor"></path></svg></span> </span> </span> <div class="ml-4 flex flex-1 items-center justify-end gap-1"> </div></div></div> <div class="flex flex-nowrap gap-1 overflow-x-auto"></div></div> <button type="button" class="btn mt-2 h-10 w-full text-sm font-semibold md:text-base" ><span class="flex items-center gap-1.5"> <span>Run Query</span> <span class="shadow-xs ml-2 hidden items-center rounded-sm border bg-white px-0.5 text-xs font-medium text-gray-700 sm:inline-flex">Ctrl+↵</span></span></button></div> <div class="flex flex-col px-2 pb-4"></div></div> <div class="mt-auto pb-4"><div class="flex justify-center"><div class="w-full sm:px-4"><div class="mb-3"><ul class="flex gap-1 text-sm "><li><button class="flex items-center whitespace-nowrap rounded-lg px-2 text-gray-500 hover:bg-gray-100 hover:text-gray-700 dark:hover:bg-gray-900 dark:hover:text-gray-300">Saved Queries </button> </li><li><button class="flex items-center whitespace-nowrap rounded-lg px-2 bg-black text-white dark:bg-gray-800">Top Community Queries </button> </li></ul></div> <div class="h-48 overflow-y-auto"><div class="flex flex-col gap-2"><div class="flex h-48 flex-col items-center justify-center rounded border border-gray-200 bg-gray-50 p-4 text-center dark:border-gray-700/60 dark:bg-gray-900"><p class="mb-1 font-semibold text-gray-600 dark:text-gray-400">No community queries yet</p> <p class="max-w-xs text-xs text-gray-500 dark:text-gray-400">The top public SQL queries from the community will appear here once available.</p></div></div></div></div></div></div></div></div></div></div> </div></div></div></main> </div> <script data-cfasync="false" src="/cdn-cgi/scripts/5c5dd728/cloudflare-static/email-decode.min.js"></script><script> import("\/front\/build\/kube-9c71b14\/index.js"); window.moonSha = "kube-9c71b14\/"; window.__hf_deferred = {}; </script> <!-- Stripe --> <script> if (["hf.co", "huggingface.co"].includes(window.location.hostname)) { const script = document.createElement("script"); script.src = "https://js.stripe.com/v3/"; script.async = true; document.head.appendChild(script); } </script> </body> </html>